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/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_seg.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_2d_seg.cc
* @brief: polynomial smoothing spline
**/
#include "modules/planning/math/smoothing_spline/spline_2d_seg.h"
namespace apollo {
namespace planning {
Spline2dSeg::Spline2dSeg(const uint32_t order)
: spline_func_x_(order), spline_func_y_(order) {
derivative_x_ = PolynomialXd::DerivedFrom(spline_func_x_);
derivative_y_ = PolynomialXd::DerivedFrom(spline_func_y_);
second_derivative_x_ = PolynomialXd::DerivedFrom(derivative_x_);
second_derivative_y_ = PolynomialXd::DerivedFrom(derivative_y_);
third_derivative_x_ = PolynomialXd::DerivedFrom(second_derivative_x_);
third_derivative_y_ = PolynomialXd::DerivedFrom(second_derivative_y_);
}
Spline2dSeg::Spline2dSeg(const std::vector<double>& x_param,
const std::vector<double>& y_param)
: spline_func_x_(x_param), spline_func_y_(y_param) {
derivative_x_ = PolynomialXd::DerivedFrom(spline_func_x_);
derivative_y_ = PolynomialXd::DerivedFrom(spline_func_y_);
second_derivative_x_ = PolynomialXd::DerivedFrom(derivative_x_);
second_derivative_y_ = PolynomialXd::DerivedFrom(derivative_y_);
third_derivative_x_ = PolynomialXd::DerivedFrom(second_derivative_x_);
third_derivative_y_ = PolynomialXd::DerivedFrom(second_derivative_y_);
}
bool Spline2dSeg::SetParams(const std::vector<double>& x_param,
const std::vector<double>& y_param) {
if (x_param.size() != y_param.size()) {
return false;
}
spline_func_x_ = PolynomialXd(x_param);
spline_func_y_ = PolynomialXd(y_param);
derivative_x_ = PolynomialXd::DerivedFrom(spline_func_x_);
derivative_y_ = PolynomialXd::DerivedFrom(spline_func_y_);
second_derivative_x_ = PolynomialXd::DerivedFrom(derivative_x_);
second_derivative_y_ = PolynomialXd::DerivedFrom(derivative_y_);
third_derivative_x_ = PolynomialXd::DerivedFrom(second_derivative_x_);
third_derivative_y_ = PolynomialXd::DerivedFrom(second_derivative_y_);
return true;
}
std::pair<double, double> Spline2dSeg::operator()(const double t) const {
return std::make_pair(spline_func_x_(t), spline_func_y_(t));
}
double Spline2dSeg::x(const double t) const { return spline_func_x_(t); }
double Spline2dSeg::y(const double t) const { return spline_func_y_(t); }
double Spline2dSeg::DerivativeX(const double t) const {
return derivative_x_(t);
}
double Spline2dSeg::DerivativeY(const double t) const {
return derivative_y_(t);
}
double Spline2dSeg::SecondDerivativeX(const double t) const {
return second_derivative_x_(t);
}
double Spline2dSeg::SecondDerivativeY(const double t) const {
return second_derivative_y_(t);
}
double Spline2dSeg::ThirdDerivativeX(const double t) const {
return third_derivative_x_(t);
}
double Spline2dSeg::ThirdDerivativeY(const double t) const {
return third_derivative_y_(t);
}
const PolynomialXd& Spline2dSeg::spline_func_x() const {
return spline_func_x_;
}
const PolynomialXd& Spline2dSeg::spline_func_y() const {
return spline_func_y_;
}
const PolynomialXd& Spline2dSeg::DerivativeX() const { return derivative_x_; }
const PolynomialXd& Spline2dSeg::DerivativeY() const { return derivative_y_; }
const PolynomialXd& Spline2dSeg::SecondDerivativeX() const {
return second_derivative_x_;
}
const PolynomialXd& Spline2dSeg::SecondDerivativeY() const {
return second_derivative_y_;
}
const PolynomialXd& Spline2dSeg::ThirdDerivativeX() const {
return third_derivative_x_;
}
const PolynomialXd& Spline2dSeg::ThirdDerivativeY() const {
return third_derivative_y_;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_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_1d_constraint.h"
#include "gtest/gtest.h"
namespace apollo {
namespace planning {
TEST(Spline1dConstraint, add_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddBoundary(x_coord, lower_bound, upper_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(6, 6);
ref_mat <<
1, 0, 0, 0, 0, 0,
1, 0.5, 0.25, 0.125, 0.0625, 0.03125,
1, 1, 1, 1, 1, 1,
-1, -0, -0, -0, -0, -0,
-1, -0.5, -0.25, -0.125, -0.0625, -0.03125,
-1, -1, -1, -1, -1, -1;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_derivative_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddDerivativeBoundary(x_coord, lower_bound, upper_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(6, 6);
ref_mat <<
0, 1, 0, 0, 0, 0,
0, 1, 1, 0.75, 0.5, 0.3125,
0, 1, 2, 3, 4, 5,
0, -1, -0, -0, -0, -0,
0, -1, -1, -0.75, -0.5, -0.3125,
0, -1, -2, -3, -4, -5;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_second_derivative_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddSecondDerivativeBoundary(x_coord, lower_bound, upper_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(6, 6);
ref_mat <<
0, 0, 2, 0, 0, 0,
0, 0, 2, 3, 3, 2.5,
0, 0, 2, 6, 12, 20,
0, 0, -2, -0, -0, -0,
0, 0, -2, -3, -3, -2.5,
0, 0, -2, -6, -12, -20;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_smooth_constraint_01) {
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSmoothConstraint();
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, 12);
ref_mat << 1, 1, 1, 1, 1, 1, -1, -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_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_smooth_constraint_02) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(2, 18);
// clang-format off
ref_mat <<
1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, -1, -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_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 3;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddDerivativeSmoothConstraint();
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(4, 12);
ref_mat <<
1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0,
0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0,
0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_second_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 3;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSecondDerivativeSmoothConstraint();
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(6, 12);
ref_mat <<
1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0,
0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0,
0, 0, 2, 6, 0, 0, -2, -0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0,
0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0,
0, 0, 0, 0, 0, 0, 2, 6, 0, 0, -2, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_third_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddThirdDerivativeSmoothConstraint();
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(8, 15);
ref_mat <<
1, 1, 1, 1, 1, -1, -0, -0, -0, -0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 0, -1, -0, -0, -0, 0, 0, 0, 0, 0,
0, 0, 2, 6, 12, 0, 0, -2, -0, -0, 0, 0, 0, 0, 0,
0, 0, 0, 6, 24, 0, 0, 0, -6, -0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0,
0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, -1, -0, -0, -0,
0, 0, 0, 0, 0, 0, 0, 2, 6, 12, 0, 0, -2, -0, -0,
0, 0, 0, 0, 0, 0, 0, 0, 6, 24, 0, 0, 0, -6, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_monotone_inequality_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
constraint.AddMonotoneInequalityConstraint(x_coord);
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(6, 15);
ref_mat <<
0, 0.5, 0.25, 0.125, 0.0625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
-1, -0.5, -0.25, -0.125, -0.0625, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0.5, 0.25, 0.125, 0.0625, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, -1, -0.5, -0.25, -0.125, -0.0625, 1, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.25, 0.125, 0.0625, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.75, 0.875, 0.9375; // NOLINT
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_monotone_inequality_constraint_at_knots) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddMonotoneInequalityConstraintAtKnots();
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(3, 15);
// clang-format off
ref_mat <<
-1, -0, -0, -0, -0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, -0, -0, -0, -0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_point_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointConstraint(2.5, 12.3);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0.25, 0.125, 0.0625;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 12.3);
}
TEST(Spline1dConstraint, add_point_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 1.0, 0.75, 0.5;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
TEST(Spline1dConstraint, add_point_second_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointSecondDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.0, 3.0, 3.0;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
TEST(Spline1dConstraint, add_point_third_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointThirdDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.0, 12.0;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_solver.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 "Eigen/Core"
#include "modules/common/math/qp_solver/qp_solver.h"
#include "modules/planning/math/smoothing_spline/spline_1d.h"
#include "modules/planning/math/smoothing_spline/spline_1d_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_1d_kernel.h"
#include "modules/planning/proto/math/qp_problem.pb.h"
namespace apollo {
namespace planning {
class Spline1dSolver {
public:
Spline1dSolver(const std::vector<double>& x_knots, const uint32_t order)
: spline_(x_knots, order),
constraint_(x_knots, order),
kernel_(x_knots, order) {}
virtual ~Spline1dSolver() = default;
virtual void Reset(const std::vector<double>& x_knots, const uint32_t order) {
spline_ = Spline1d(x_knots, order);
constraint_ = Spline1dConstraint(x_knots, order);
kernel_ = Spline1dKernel(x_knots, order);
}
virtual Spline1dConstraint* mutable_spline_constraint() {
return &constraint_;
}
virtual Spline1dKernel* mutable_spline_kernel() { return &kernel_; }
virtual bool Solve() = 0;
// output
virtual const Spline1d& spline() const { return spline_; }
// convert qp problem to proto
void GenerateProblemProto(QuadraticProgrammingProblem* const qp_proto) const;
protected:
void ConvertMatrixXdToProto(const Eigen::MatrixXd& matrix,
QPMatrix* const proto) const;
protected:
Spline1d spline_;
Spline1dConstraint constraint_;
Spline1dKernel kernel_;
int last_num_constraint_ = 0;
int last_num_param_ = 0;
bool last_problem_success_ = false;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/affine_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 : affine_constraint.cc
**/
#include "modules/planning/math/smoothing_spline/affine_constraint.h"
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
AffineConstraint::AffineConstraint(const bool is_equality)
: is_equality_(is_equality) {}
AffineConstraint::AffineConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary,
const bool is_equality)
: constraint_matrix_(constraint_matrix),
constraint_boundary_(constraint_boundary),
is_equality_(is_equality) {
CHECK_EQ(constraint_boundary.rows(), constraint_matrix.rows());
}
void AffineConstraint::SetIsEquality(const double is_equality) {
is_equality_ = is_equality;
}
const Eigen::MatrixXd& AffineConstraint::constraint_matrix() const {
return constraint_matrix_;
}
const Eigen::MatrixXd& AffineConstraint::constraint_boundary() const {
return constraint_boundary_;
}
bool AffineConstraint::AddConstraint(
const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary) {
if (constraint_matrix.rows() != constraint_boundary.rows()) {
AERROR << "Fail to add constraint because constraint matrix rows != "
"constraint boundary rows.";
AERROR << "constraint matrix rows = " << constraint_matrix.rows();
AERROR << "constraint boundary rows = " << constraint_boundary.rows();
return false;
}
if (constraint_matrix_.rows() == 0) {
constraint_matrix_ = constraint_matrix;
constraint_boundary_ = constraint_boundary;
return true;
}
if (constraint_matrix_.cols() != constraint_matrix.cols()) {
AERROR
<< "constraint_matrix_ cols and constraint_matrix cols do not match.";
AERROR << "constraint_matrix_.cols() = " << constraint_matrix_.cols();
AERROR << "constraint_matrix.cols() = " << constraint_matrix.cols();
return false;
}
if (constraint_boundary.cols() != 1) {
AERROR << "constraint_boundary.cols() should be 1.";
return false;
}
Eigen::MatrixXd n_matrix(constraint_matrix_.rows() + constraint_matrix.rows(),
constraint_matrix_.cols());
Eigen::MatrixXd n_boundary(
constraint_boundary_.rows() + constraint_boundary.rows(), 1);
n_matrix << constraint_matrix_, constraint_matrix;
n_boundary << constraint_boundary_, constraint_boundary;
constraint_matrix_ = n_matrix;
constraint_boundary_ = n_boundary;
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_kernel_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_1d_kernel.h"
#include "gtest/gtest.h"
namespace apollo {
namespace planning {
TEST(Spline1dKernel, add_regularization) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 3;
Spline1dKernel kernel(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 1.0, 2.0, 3.0};
kernel.AddRegularization(0.2);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(12, 12);
// clang-format off
ref_kernel_matrix <<
0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j));
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(12, 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_01) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrix(1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(6, 6);
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1,
0, 1, 1.33333, 1.5, 1.6, 1.66667,
0, 1, 1.5, 1.8, 2, 2.14286,
0, 1, 1.6, 2, 2.28571, 2.5,
0, 1, 1.66667, 2.14286, 2.5, 2.77778;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(6, 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_02) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrix(1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // NOLINT
0, 1, 1.33333, 1.5, 1.6, 1.66667, 0, 0, 0, 0, 0, 0, // NOLINT
0, 1, 1.5, 1.8, 2, 2.14286, 0, 0, 0, 0, 0, 0, // NOLINT
0, 1, 1.6, 2, 2.28571, 2.5, 0, 0, 0, 0, 0, 0, // NOLINT
0, 1, 1.66667, 2.14286, 2.5, 2.77778, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, // NOLINT
0, 0, 0, 0, 0, 0, 0, 1, 1.33333, 1.5, 1.6, 1.66667, // NOLINT
0, 0, 0, 0, 0, 0, 0, 1, 1.5, 1.8, 2, 2.14286, // NOLINT
0, 0, 0, 0, 0, 0, 0, 1, 1.6, 2, 2.28571, 2.5, // NOLINT
0, 0, 0, 0, 0, 0, 0, 1, 1.66667, 2.14286, 2.5, 2.77778; // NOLINT
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_03) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 0.5};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrix(1.0);
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), 6 * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(6, 6);
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1,
0, 1, 1.33333, 1.5, 1.6, 1.66667,
0, 1, 1.5, 1.8, 2, 2.14286,
0, 1, 1.6, 2, 2.28571, 2.5,
0, 1, 1.66667, 2.14286, 2.5, 2.77778;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
double param = std::pow(0.5, i + j - 1);
EXPECT_NEAR(kernel.kernel_matrix()(i, j), param * ref_kernel_matrix(i, j),
1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(6, 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_04) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 3;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrix(1.0);
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), 4 * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(4, 4);
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0,
0, 1, 1, 1,
0, 1, 1.33333, 1.5,
0, 1, 1.5, 1.8;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(6, 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_second_derivative_kernel_matrix_01) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 0.5};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddSecondOrderDerivativeMatrix(1.0);
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), 6 * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix =
Eigen::MatrixXd::Zero(6 * (x_knots.size() - 1), 6 * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 4, 6, 8, 10,
0, 0, 6, 12, 18, 24,
0, 0, 8, 18, 28.8, 40,
0, 0, 10, 24, 40, 57.1429;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
const double param = std::pow(0.5, std::max(0, i + j - 3));
EXPECT_NEAR(kernel.kernel_matrix()(i, j), param * ref_kernel_matrix(i, j),
1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_second_derivative_kernel_matrix_02) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 0.5, 1.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddSecondOrderDerivativeMatrix(1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
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, 4, 6, 8, 10, 0, 0, 0, 0, 0, 0,
0, 0, 6, 12, 18, 24, 0, 0, 0, 0, 0, 0,
0, 0, 8, 18, 28.8, 40, 0, 0, 0, 0, 0, 0,
0, 0, 10, 24, 40, 57.1429, 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, 0, 0, 0, 0, 4, 6, 8, 10,
0, 0, 0, 0, 0, 0, 0, 0, 6, 12, 18, 24,
0, 0, 0, 0, 0, 0, 0, 0, 8, 18, 28.8, 40,
0, 0, 0, 0, 0, 0, 0, 0, 10, 24, 40, 57.1429;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
const double param = std::pow(0.5, std::max(0, i % 6 + j % 6 - 3));
EXPECT_NEAR(kernel.kernel_matrix()(i, j), param * ref_kernel_matrix(i, j),
1e-6);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_third_derivative_kernel_matrix_01) {
std::vector<double> x_knots = {0.0, 1.5};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddThirdOrderDerivativeMatrix(1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 36, 72, 120,
0, 0, 0, 72, 192, 360,
0, 0, 0, 120, 360, 720;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
const double param = std::pow(1.5, std::max(0, i % 6 + j % 6 - 5));
EXPECT_NEAR(kernel.kernel_matrix()(i, j), param * ref_kernel_matrix(i, j),
1e-6);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_third_derivative_kernel_matrix_02) {
std::vector<double> x_knots = {0.0, 1.5, 3.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddThirdOrderDerivativeMatrix(1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix =
Eigen::MatrixXd::Zero(num_params, num_params);
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 36, 72, 120,
0, 0, 0, 72, 192, 360,
0, 0, 0, 120, 360, 720;
// clang-format on
ref_kernel_matrix *= 2.0;
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
if ((i >= 6 && j < 6) || (i < 6 && j >= 6)) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.0);
} else {
const double param = std::pow(1.5, std::max(0, i % 6 + j % 6 - 5));
EXPECT_NEAR(kernel.kernel_matrix()(i, j),
param * ref_kernel_matrix(i % 6, j % 6), 1e-6);
}
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_reference_line_kernel_01) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[",
"]");
std::vector<double> x_coord = {0.0};
std::vector<double> ref_x = {0.0};
kernel.AddReferenceLineKernelMatrix(x_coord, ref_x, 1.0);
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
if (i == 0 && j == 0) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 2.0);
} else {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.0);
}
}
}
for (int i = 0; i < kernel.offset().rows(); ++i) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), 0);
}
}
TEST(Spline1dKernel, add_reference_line_kernel_02) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
std::vector<double> x_coord = {0.0};
std::vector<double> ref_x = {3.0};
kernel.AddReferenceLineKernelMatrix(x_coord, ref_x, 1.0);
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
if (i == 0 && j == 0) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 2.0);
} else {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.0);
}
}
}
for (int i = 0; i < kernel.offset().rows(); ++i) {
if (i == 0) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), -6.0);
} else {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), 0);
}
}
}
TEST(Spline1dKernel, add_reference_line_kernel_03) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5};
std::vector<double> ref_x = {0.0, 2.0};
kernel.AddReferenceLineKernelMatrix(x_coord, ref_x, 1.0);
Eigen::MatrixXd res = Eigen::MatrixXd::Zero(1, 6);
double d = 0.5;
for (int i = 0; i < 6; ++i) {
res(0, i) = std::pow(d, i);
}
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(6, 6);
ref_kernel_matrix = 2.0 * res.transpose() * res;
ref_kernel_matrix(0, 0) += 2.0;
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(6, 1);
ref_offset = -2.0 * 2.0 * res.transpose();
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j));
}
}
for (int i = 0; i < kernel.offset().rows(); ++i) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), ref_offset(i, 0));
}
}
TEST(Spline1dKernel, add_reference_line_kernel_04) {
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
std::vector<double> x_coord = {1.5};
std::vector<double> ref_x = {2.0};
kernel.AddReferenceLineKernelMatrix(x_coord, ref_x, 1.0);
Eigen::MatrixXd res = Eigen::MatrixXd::Zero(1, 6);
double d = 0.5;
for (int i = 0; i < 6; ++i) {
res(0, i) = std::pow(d, i);
}
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(6, 6);
ref_kernel_matrix = 2.0 * res.transpose() * res;
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(6, 1);
ref_offset = -2.0 * 2.0 * res.transpose();
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
if (i < 6 || j < 6) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.0);
} else {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j),
ref_kernel_matrix(i % 6, j % 6));
}
}
}
for (int i = 0; i < kernel.offset().rows(); ++i) {
if (i < 6) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), 0.0);
} else {
EXPECT_DOUBLE_EQ(kernel.offset()(i, 0), ref_offset(i % 6, 0));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_for_spline_k_01) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrixForSplineK(0, 1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, // NOLINT
0, 2, 2.66667, 3, 3.2, 3.33333, 0, 0, 0, 0, 0, 0, // NOLINT
0, 2, 3, 3.6, 4, 4.28571, 0, 0, 0, 0, 0, 0, // NOLINT
0, 2, 3.2, 4, 4.57143, 5, 0, 0, 0, 0, 0, 0, // NOLINT
0, 2, 3.33333, 4.28571, 5, 5.55556, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; // NOLINT
// clang-format on
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel, add_derivative_kernel_matrix_for_spline_k_02) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddDerivativeKernelMatrixForSplineK(1, 1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, // NOLINT
0, 0, 0, 0, 0, 0, 0, 2, 2.66667, 3, 3.2, 3.33333, // NOLINT
0, 0, 0, 0, 0, 0, 0, 2, 3, 3.6, 4, 4.28571, // NOLINT
0, 0, 0, 0, 0, 0, 0, 2, 3.2, 4, 4.57143, 5, // NOLINT
0, 0, 0, 0, 0, 0, 0, 2, 3.33333, 4.28571, 5, 5.55556; // NOLINT
// clang-format on
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel,
add_second_order_derivative_kernel_matrix_for_spline_k_01) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddSecondOrderDerivativeMatrixForSplineK(0, 1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 8, 12, 16, 20, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 12, 24, 36, 48, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 16, 36, 57.6, 80, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 20, 48, 80, 114.285714, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; // NOLINT
// clang-format on
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
TEST(Spline1dKernel,
add_second_order_derivative_kernel_matrix_for_spline_k_02) {
// please see the document at docs/specs/qp_spline_path_optimizer.md for
// details.
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 5;
Spline1dKernel kernel(x_knots, spline_order);
kernel.AddSecondOrderDerivativeMatrixForSplineK(1, 1.0);
const uint32_t num_params = spline_order + 1;
EXPECT_EQ(kernel.kernel_matrix().rows(), kernel.kernel_matrix().cols());
EXPECT_EQ(kernel.kernel_matrix().rows(), num_params * (x_knots.size() - 1));
Eigen::MatrixXd ref_kernel_matrix = Eigen::MatrixXd::Zero(
num_params * (x_knots.size() - 1), num_params * (x_knots.size() - 1));
// clang-format off
ref_kernel_matrix <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 8, 12, 16, 20, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 48, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 16, 36, 57.6, 80, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 20, 48, 80, 114.285714; // NOLINT
// clang-format on
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
EXPECT_NEAR(kernel.kernel_matrix()(i, j), ref_kernel_matrix(i, j), 1e-5);
}
}
Eigen::MatrixXd ref_offset = Eigen::MatrixXd::Zero(kernel.offset().rows(), 1);
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), ref_offset(i, j));
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d.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 : piecewise_smoothing_spline.h
* @brief: polynomial smoothing spline
**/
#include "modules/planning/math/smoothing_spline/spline_1d.h"
namespace apollo {
namespace planning {
Spline1d::Spline1d(const std::vector<double>& x_knots, const uint32_t order)
: x_knots_(x_knots), spline_order_(order) {
for (uint32_t i = 1; i < x_knots_.size(); ++i) {
splines_.emplace_back(spline_order_);
}
}
double Spline1d::operator()(const double x) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = FindIndex(x);
return splines_[index](x - x_knots_[index]);
}
double Spline1d::Derivative(const double x) const {
// zero order spline
if (splines_.empty()) {
return 0.0;
}
uint32_t index = FindIndex(x);
return splines_[index].Derivative(x - x_knots_[index]);
}
double Spline1d::SecondOrderDerivative(const double x) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = FindIndex(x);
return splines_[index].SecondOrderDerivative(x - x_knots_[index]);
}
double Spline1d::ThirdOrderDerivative(const double x) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = FindIndex(x);
return splines_[index].ThirdOrderDerivative(x - x_knots_[index]);
}
bool Spline1d::SetSplineSegs(const Eigen::MatrixXd& param_matrix,
const uint32_t order) {
const uint32_t num_params = order + 1;
// check if the parameter size fit
if (x_knots_.size() * num_params !=
num_params + static_cast<uint32_t>(param_matrix.rows())) {
return false;
}
for (uint32_t i = 0; i < splines_.size(); ++i) {
std::vector<double> spline_piece(num_params, 0.0);
for (uint32_t j = 0; j < num_params; ++j) {
spline_piece[j] = param_matrix(i * num_params + j, 0);
}
splines_[i].SetParams(spline_piece);
}
spline_order_ = order;
return true;
}
const std::vector<double>& Spline1d::x_knots() const { return x_knots_; }
uint32_t Spline1d::spline_order() const { return spline_order_; }
const std::vector<Spline1dSeg>& Spline1d::splines() const { return splines_; }
uint32_t Spline1d::FindIndex(const double x) const {
auto upper_bound = std::upper_bound(x_knots_.begin() + 1, x_knots_.end(), x);
const uint32_t dis =
static_cast<uint32_t>(std::distance(x_knots_.begin(), upper_bound));
if (dis < x_knots_.size()) {
return dis - 1;
} else {
return static_cast<uint32_t>(x_knots_.size()) - 2;
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_kernel.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_2d_kernel.h
**/
#pragma once
#include <vector>
#include "Eigen/Core"
#include "modules/common/math/vec2d.h"
#include "modules/planning/math/smoothing_spline/spline_2d.h"
namespace apollo {
namespace planning {
class Spline2dKernel {
public:
Spline2dKernel(const std::vector<double>& t_knots,
const uint32_t spline_order);
// customized input output
void AddRegularization(const double regularization_param);
bool AddKernel(const Eigen::MatrixXd& kernel, const Eigen::MatrixXd& offset,
const double weight);
bool AddKernel(const Eigen::MatrixXd& kernel, const double weight);
Eigen::MatrixXd* mutable_kernel_matrix();
Eigen::MatrixXd* mutable_offset();
Eigen::MatrixXd kernel_matrix() const;
const Eigen::MatrixXd offset() const;
// build-in kernel methods
void AddDerivativeKernelMatrix(const double weight);
void AddSecondOrderDerivativeMatrix(const double weight);
void AddThirdOrderDerivativeMatrix(const double weight);
// reference line kernel, x_coord in strictly increasing order
bool AddReferenceLineKernelMatrix(
const std::vector<double>& t_coord,
const std::vector<common::math::Vec2d>& ref_points, const double weight);
private:
void AddNthDerivativeKernelMatrix(const uint32_t n, const double weight);
uint32_t find_index(const double x) const;
private:
Eigen::MatrixXd kernel_matrix_;
Eigen::MatrixXd offset_;
std::vector<double> t_knots_;
uint32_t spline_order_;
size_t total_params_;
};
} // 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.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/smoothing_spline/osqp_spline_1d_solver.h"
#include "cyber/common/log.h"
#include "modules/common/math/matrix_operations.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::math::DenseToCSCMatrix;
using Eigen::MatrixXd;
OsqpSpline1dSolver::OsqpSpline1dSolver(const std::vector<double>& x_knots,
const uint32_t order)
: Spline1dSolver(x_knots, order) {
// Problem settings
settings_ = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings)));
// Define Solver settings as default
osqp_set_default_settings(settings_);
settings_->alpha = 1.0; // Change alpha parameter
settings_->eps_abs = 1.0e-03;
settings_->eps_rel = 1.0e-03;
settings_->max_iter = 5000;
// settings_->polish = true;
settings_->verbose = FLAGS_enable_osqp_debug;
settings_->warm_start = true;
// Populate data
data_ = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
}
OsqpSpline1dSolver::~OsqpSpline1dSolver() { CleanUp(); }
void OsqpSpline1dSolver::CleanUp() {
osqp_cleanup(work_);
if (data_ != nullptr) {
c_free(data_->A);
c_free(data_->P);
c_free(data_);
}
if (settings_ != nullptr) {
c_free(settings_);
}
}
void OsqpSpline1dSolver::ResetOsqp() {
// Problem settings
settings_ = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings)));
// Populate data
data_ = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
}
bool OsqpSpline1dSolver::Solve() {
// Namings here are following osqp convention.
// For details, visit: https://osqp.org/docs/examples/demo.html
// change P to csc format
const MatrixXd& P = kernel_.kernel_matrix();
ADEBUG << "P: " << P.rows() << ", " << P.cols();
if (P.rows() == 0) {
return false;
}
std::vector<c_float> P_data;
std::vector<c_int> P_indices;
std::vector<c_int> P_indptr;
DenseToCSCMatrix(P, &P_data, &P_indices, &P_indptr);
// change A to csc format
const MatrixXd& inequality_constraint_matrix =
constraint_.inequality_constraint().constraint_matrix();
const MatrixXd& equality_constraint_matrix =
constraint_.equality_constraint().constraint_matrix();
MatrixXd A(
inequality_constraint_matrix.rows() + equality_constraint_matrix.rows(),
inequality_constraint_matrix.cols());
A << inequality_constraint_matrix, equality_constraint_matrix;
ADEBUG << "A: " << A.rows() << ", " << A.cols();
if (A.rows() == 0) {
return false;
}
std::vector<c_float> A_data;
std::vector<c_int> A_indices;
std::vector<c_int> A_indptr;
DenseToCSCMatrix(A, &A_data, &A_indices, &A_indptr);
// set q, l, u: l < A < u
const MatrixXd& q_eigen = kernel_.offset();
c_float q[q_eigen.rows()]; // NOLINT
for (int i = 0; i < q_eigen.size(); ++i) {
q[i] = q_eigen(i);
}
const MatrixXd& inequality_constraint_boundary =
constraint_.inequality_constraint().constraint_boundary();
const MatrixXd& equality_constraint_boundary =
constraint_.equality_constraint().constraint_boundary();
int constraint_num = static_cast<int>(inequality_constraint_boundary.rows() +
equality_constraint_boundary.rows());
static constexpr double kEpsilon = 1e-9;
static constexpr float kUpperLimit = 1e9;
c_float l[constraint_num]; // NOLINT
c_float u[constraint_num]; // NOLINT
for (int i = 0; i < constraint_num; ++i) {
if (i < inequality_constraint_boundary.rows()) {
l[i] = inequality_constraint_boundary(i, 0);
u[i] = kUpperLimit;
} else {
const int idx =
i - static_cast<int>(inequality_constraint_boundary.rows());
l[i] = equality_constraint_boundary(idx, 0) - kEpsilon;
u[i] = equality_constraint_boundary(idx, 0) + kEpsilon;
}
}
data_->n = P.rows();
data_->m = constraint_num;
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 = l;
data_->u = u;
// osqp_setup(&work_, data_, settings_);
work_ = osqp_setup(data_, settings_);
// Solve Problem
osqp_solve(work_);
MatrixXd solved_params = MatrixXd::Zero(P.rows(), 1);
for (int i = 0; i < P.rows(); ++i) {
solved_params(i, 0) = work_->solution->x[i];
}
last_num_param_ = static_cast<int>(P.rows());
last_num_constraint_ = constraint_num;
return spline_.SetSplineSegs(solved_params, spline_.spline_order());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_seg.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_2d_seg.h
**/
#pragma once
#include <utility>
#include <vector>
#include "modules/planning/math/polynomial_xd.h"
namespace apollo {
namespace planning {
class Spline2dSeg {
public:
// order represent the number of parameters (not the highest order);
explicit Spline2dSeg(const uint32_t order);
Spline2dSeg(const std::vector<double>& x_param,
const std::vector<double>& y_param);
~Spline2dSeg() = default;
bool SetParams(const std::vector<double>& x_param,
const std::vector<double>& y_param);
std::pair<double, double> operator()(const double t) const;
double x(const double t) const;
double y(const double t) const;
double DerivativeX(const double t) const;
double DerivativeY(const double t) const;
double SecondDerivativeX(const double t) const;
double SecondDerivativeY(const double t) const;
double ThirdDerivativeX(const double t) const;
double ThirdDerivativeY(const double t) const;
const PolynomialXd& spline_func_x() const;
const PolynomialXd& spline_func_y() const;
const PolynomialXd& DerivativeX() const;
const PolynomialXd& DerivativeY() const;
const PolynomialXd& SecondDerivativeX() const;
const PolynomialXd& SecondDerivativeY() const;
const PolynomialXd& ThirdDerivativeX() const;
const PolynomialXd& ThirdDerivativeY() const;
private:
PolynomialXd spline_func_x_;
PolynomialXd spline_func_y_;
PolynomialXd derivative_x_;
PolynomialXd derivative_y_;
PolynomialXd second_derivative_x_;
PolynomialXd second_derivative_y_;
PolynomialXd third_derivative_x_;
PolynomialXd third_derivative_y_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d.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_2d.cc
**/
#include "modules/planning/math/smoothing_spline/spline_2d.h"
#include <algorithm>
namespace apollo {
namespace planning {
Spline2d::Spline2d(const std::vector<double>& t_knots, const uint32_t order)
: t_knots_(t_knots), spline_order_(order) {
if (t_knots.size() > 1) {
for (uint32_t i = 1; i < t_knots_.size(); ++i) {
splines_.emplace_back(spline_order_);
}
}
}
std::pair<double, double> Spline2d::operator()(const double t) const {
if (splines_.empty()) {
return std::make_pair(0.0, 0.0);
}
uint32_t index = find_index(t);
return splines_[index](t - t_knots_[index]);
}
double Spline2d::x(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].x(t - t_knots_[index]);
}
double Spline2d::y(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].y(t - t_knots_[index]);
}
double Spline2d::DerivativeX(const double t) const {
// zero order spline
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].DerivativeX(t - t_knots_[index]);
}
double Spline2d::DerivativeY(const double t) const {
// zero order spline
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].DerivativeY(t - t_knots_[index]);
}
double Spline2d::SecondDerivativeX(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].SecondDerivativeX(t - t_knots_[index]);
}
double Spline2d::SecondDerivativeY(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].SecondDerivativeY(t - t_knots_[index]);
}
double Spline2d::ThirdDerivativeX(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].ThirdDerivativeX(t - t_knots_[index]);
}
double Spline2d::ThirdDerivativeY(const double t) const {
if (splines_.empty()) {
return 0.0;
}
uint32_t index = find_index(t);
return splines_[index].ThirdDerivativeY(t - t_knots_[index]);
}
/**
* @brief: set splines
**/
bool Spline2d::set_splines(const Eigen::MatrixXd& params,
const uint32_t order) {
const uint32_t num_params = order + 1;
// check if the parameter size fit
if (2 * t_knots_.size() * num_params !=
2 * num_params + static_cast<uint32_t>(params.rows())) {
return false;
}
for (uint32_t i = 0; i < splines_.size(); ++i) {
std::vector<double> spline_piece_x(num_params, 0.0);
std::vector<double> spline_piece_y(num_params, 0.0);
for (uint32_t j = 0; j < num_params; ++j) {
spline_piece_x[j] = params(2 * i * num_params + j, 0);
spline_piece_y[j] = params((2 * i + 1) * num_params + j, 0);
}
splines_[i].SetParams(spline_piece_x, spline_piece_y);
}
spline_order_ = order;
return true;
}
const Spline2dSeg& Spline2d::smoothing_spline(const uint32_t index) const {
return splines_[index];
}
const std::vector<double>& Spline2d::t_knots() const { return t_knots_; }
uint32_t Spline2d::spline_order() const { return spline_order_; }
uint32_t Spline2d::find_index(const double t) const {
auto upper_bound = std::upper_bound(t_knots_.begin() + 1, t_knots_.end(), t);
return std::min(static_cast<uint32_t>(t_knots_.size() - 1),
static_cast<uint32_t>(upper_bound - t_knots_.begin())) -
1;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_seg_kernel.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_seg_kernel.h
* @brief: generating integrated kernels for smoothing spline
*
* x' P x = int_0 ^x (f(x)^(k))^2 dx, k = 0, 1, 2, 3
* P is the kernel of k-th smooth kernel
**/
#pragma once
#include <string>
#include "Eigen/Core"
#include "cyber/common/macros.h"
namespace apollo {
namespace planning {
class SplineSegKernel {
public:
// generating kernel matrix
Eigen::MatrixXd Kernel(const uint32_t num_params, const double accumulated_x);
// only support N <= 3 cases
Eigen::MatrixXd NthDerivativeKernel(const uint32_t n,
const uint32_t num_params,
const double accumulated_x);
private:
Eigen::MatrixXd DerivativeKernel(const uint32_t num_of_params,
const double accumulated_x);
Eigen::MatrixXd SecondOrderDerivativeKernel(const uint32_t num_of_params,
const double accumulated_x);
Eigen::MatrixXd ThirdOrderDerivativeKernel(const uint32_t num_of_params,
const double accumulated_x);
void IntegratedTermMatrix(const uint32_t num_of_params, const double x,
const std::string& type,
Eigen::MatrixXd* term_matrix) const;
void CalculateFx(const uint32_t num_of_params);
void CalculateDerivative(const uint32_t num_of_params);
void CalculateSecondOrderDerivative(const uint32_t num_of_params);
void CalculateThirdOrderDerivative(const uint32_t num_of_params);
const uint32_t reserved_order_ = 5;
Eigen::MatrixXd kernel_fx_;
Eigen::MatrixXd kernel_derivative_;
Eigen::MatrixXd kernel_second_order_derivative_;
Eigen::MatrixXd kernel_third_order_derivative_;
DECLARE_SINGLETON(SplineSegKernel)
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_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_smoother_constraint.cc
**/
#include "modules/planning/math/smoothing_spline/spline_2d_constraint.h"
#include <algorithm>
#include "cyber/common/log.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/math_utils.h"
namespace apollo {
namespace planning {
using apollo::common::math::Vec2d;
Spline2dConstraint::Spline2dConstraint(const std::vector<double>& t_knots,
const uint32_t order)
: t_knots_(t_knots), spline_order_(order) {
inequality_constraint_.SetIsEquality(false);
equality_constraint_.SetIsEquality(true);
total_param_ =
2 * (spline_order_ + 1) * (static_cast<uint32_t>(t_knots.size()) - 1);
}
// direct method
bool Spline2dConstraint::AddInequalityConstraint(
const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary) {
return inequality_constraint_.AddConstraint(constraint_matrix,
constraint_boundary);
}
bool Spline2dConstraint::AddEqualityConstraint(
const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary) {
return equality_constraint_.AddConstraint(constraint_matrix,
constraint_boundary);
}
// preset method
/**
* @brief: inequality boundary constraints
* if no boundary, do specify either by std::infinity or let vector.size() = 0
**/
bool Spline2dConstraint::Add2dBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound) {
if (t_coord.size() != angle.size() || angle.size() != ref_point.size() ||
ref_point.size() != lateral_bound.size() ||
lateral_bound.size() != longitudinal_bound.size()) {
return false;
}
Eigen::MatrixXd affine_inequality =
Eigen::MatrixXd::Zero(4 * t_coord.size(), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(4 * t_coord.size(), 1);
for (uint32_t i = 0; i < t_coord.size(); ++i) {
const double d_lateral = SignDistance(ref_point[i], angle[i]);
const double d_longitudinal =
SignDistance(ref_point[i], angle[i] - M_PI / 2.0);
const uint32_t index = FindIndex(t_coord[i]);
const double rel_t = t_coord[i] - t_knots_[index];
const uint32_t index_offset = 2 * index * (spline_order_ + 1);
std::vector<double> longi_coef = AffineCoef(angle[i], rel_t);
std::vector<double> longitudinal_coef =
AffineCoef(angle[i] - M_PI / 2, rel_t);
for (uint32_t j = 0; j < 2 * (spline_order_ + 1); ++j) {
// upper longi
affine_inequality(4 * i, index_offset + j) = longi_coef[j];
// lower longi
affine_inequality(4 * i + 1, index_offset + j) = -longi_coef[j];
// upper longitudinal
affine_inequality(4 * i + 2, index_offset + j) = longitudinal_coef[j];
// lower longitudinal
affine_inequality(4 * i + 3, index_offset + j) = -longitudinal_coef[j];
}
affine_boundary(4 * i, 0) = d_lateral - lateral_bound[i];
affine_boundary(4 * i + 1, 0) = -d_lateral - lateral_bound[i];
affine_boundary(4 * i + 2, 0) = d_longitudinal - longitudinal_bound[i];
affine_boundary(4 * i + 3, 0) = -d_longitudinal - longitudinal_bound[i];
}
return AddInequalityConstraint(affine_inequality, affine_boundary);
}
bool Spline2dConstraint::Add2dDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound) {
if (t_coord.size() != angle.size() || angle.size() != ref_point.size() ||
ref_point.size() != lateral_bound.size() ||
lateral_bound.size() != longitudinal_bound.size()) {
return false;
}
Eigen::MatrixXd affine_inequality =
Eigen::MatrixXd::Zero(4 * t_coord.size(), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(4 * t_coord.size(), 1);
for (uint32_t i = 0; i < t_coord.size(); ++i) {
const double d_lateral = SignDistance(ref_point[i], angle[i]);
const double d_longitudinal =
SignDistance(ref_point[i], angle[i] - M_PI / 2.0);
const uint32_t index = FindIndex(t_coord[i]);
const double rel_t = t_coord[i] - t_knots_[index];
const uint32_t index_offset = 2 * index * (spline_order_ + 1);
std::vector<double> longi_coef = AffineDerivativeCoef(angle[i], rel_t);
std::vector<double> longitudinal_coef =
AffineDerivativeCoef(angle[i] - M_PI / 2, rel_t);
for (uint32_t j = 0; j < 2 * (spline_order_ + 1); ++j) {
// upper longi
affine_inequality(4 * i, index_offset + j) = longi_coef[j];
// lower longi
affine_inequality(4 * i + 1, index_offset + j) = -longi_coef[j];
// upper longitudinal
affine_inequality(4 * i + 2, index_offset + j) = longitudinal_coef[j];
// lower longitudinal
affine_inequality(4 * i + 3, index_offset + j) = -longitudinal_coef[j];
}
affine_boundary(4 * i, 0) = d_lateral - lateral_bound[i];
affine_boundary(4 * i + 1, 0) = -d_lateral - lateral_bound[i];
affine_boundary(4 * i + 2, 0) = d_longitudinal - longitudinal_bound[i];
affine_boundary(4 * i + 3, 0) = -d_longitudinal - longitudinal_bound[i];
}
return AddInequalityConstraint(affine_inequality, affine_boundary);
}
bool Spline2dConstraint::Add2dSecondDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound) {
if (t_coord.size() != angle.size() || angle.size() != ref_point.size() ||
ref_point.size() != lateral_bound.size() ||
lateral_bound.size() != longitudinal_bound.size()) {
return false;
}
Eigen::MatrixXd affine_inequality =
Eigen::MatrixXd::Zero(4 * t_coord.size(), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(4 * t_coord.size(), 1);
for (uint32_t i = 0; i < t_coord.size(); ++i) {
const double d_lateral = SignDistance(ref_point[i], angle[i]);
const double d_longitudinal =
SignDistance(ref_point[i], angle[i] - M_PI / 2.0);
const uint32_t index = FindIndex(t_coord[i]);
const double rel_t = t_coord[i] - t_knots_[index];
const uint32_t index_offset = 2 * index * (spline_order_ + 1);
std::vector<double> longi_coef =
AffineSecondDerivativeCoef(angle[i], rel_t);
std::vector<double> longitudinal_coef =
AffineSecondDerivativeCoef(angle[i] - M_PI / 2, rel_t);
for (uint32_t j = 0; j < 2 * (spline_order_ + 1); ++j) {
// upper longi
affine_inequality(4 * i, index_offset + j) = longi_coef[j];
// lower longi
affine_inequality(4 * i + 1, index_offset + j) = -longi_coef[j];
// upper longitudinal
affine_inequality(4 * i + 2, index_offset + j) = longitudinal_coef[j];
// lower longitudinal
affine_inequality(4 * i + 3, index_offset + j) = -longitudinal_coef[j];
}
affine_boundary(4 * i, 0) = d_lateral - lateral_bound[i];
affine_boundary(4 * i + 1, 0) = -d_lateral - lateral_bound[i];
affine_boundary(4 * i + 2, 0) = d_longitudinal - longitudinal_bound[i];
affine_boundary(4 * i + 3, 0) = -d_longitudinal - longitudinal_bound[i];
}
return AddInequalityConstraint(affine_inequality, affine_boundary);
}
bool Spline2dConstraint::Add2dThirdDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound) {
if (t_coord.size() != angle.size() || angle.size() != ref_point.size() ||
ref_point.size() != lateral_bound.size() ||
lateral_bound.size() != longitudinal_bound.size()) {
return false;
}
Eigen::MatrixXd affine_inequality =
Eigen::MatrixXd::Zero(4 * t_coord.size(), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(4 * t_coord.size(), 1);
for (uint32_t i = 0; i < t_coord.size(); ++i) {
const double d_lateral = SignDistance(ref_point[i], angle[i]);
const double d_longitudinal =
SignDistance(ref_point[i], angle[i] - M_PI / 2.0);
const uint32_t index = FindIndex(t_coord[i]);
const double rel_t = t_coord[i] - t_knots_[index];
const uint32_t index_offset = 2 * index * (spline_order_ + 1);
std::vector<double> longi_coef = AffineThirdDerivativeCoef(angle[i], rel_t);
std::vector<double> longitudinal_coef =
AffineThirdDerivativeCoef(angle[i] - M_PI / 2, rel_t);
for (uint32_t j = 0; j < 2 * (spline_order_ + 1); ++j) {
// upper longi
affine_inequality(4 * i, index_offset + j) = longi_coef[j];
// lower longi
affine_inequality(4 * i + 1, index_offset + j) = -longi_coef[j];
// upper longitudinal
affine_inequality(4 * i + 2, index_offset + j) = longitudinal_coef[j];
// lower longitudinal
affine_inequality(4 * i + 3, index_offset + j) = -longitudinal_coef[j];
}
affine_boundary(4 * i, 0) = d_lateral - lateral_bound[i];
affine_boundary(4 * i + 1, 0) = -d_lateral - lateral_bound[i];
affine_boundary(4 * i + 2, 0) = d_longitudinal - longitudinal_bound[i];
affine_boundary(4 * i + 3, 0) = -d_longitudinal - longitudinal_bound[i];
}
return AddInequalityConstraint(affine_inequality, affine_boundary);
}
bool Spline2dConstraint::AddPointConstraint(const double t, const double x,
const double y) {
const uint32_t index = FindIndex(t);
const double rel_t = t - t_knots_[index];
std::vector<double> coef = PolyCoef(rel_t);
return AddPointKthOrderDerivativeConstraint(t, x, y, coef);
}
bool Spline2dConstraint::AddPointSecondDerivativeConstraint(const double t,
const double ddx,
const double ddy) {
const size_t index = FindIndex(t);
const double rel_t = t - t_knots_[index];
std::vector<double> coef = SecondDerivativeCoef(rel_t);
return AddPointKthOrderDerivativeConstraint(t, ddx, ddy, coef);
}
bool Spline2dConstraint::AddPointThirdDerivativeConstraint(const double t,
const double dddx,
const double dddy) {
const size_t index = FindIndex(t);
const double rel_t = t - t_knots_[index];
std::vector<double> coef = ThirdDerivativeCoef(rel_t);
return AddPointKthOrderDerivativeConstraint(t, dddx, dddy, coef);
}
bool Spline2dConstraint::AddPointKthOrderDerivativeConstraint(
const double t, const double x_kth_derivative,
const double y_kth_derivative, const std::vector<double>& coef) {
const uint32_t num_params = spline_order_ + 1;
Eigen::MatrixXd affine_equality = Eigen::MatrixXd::Zero(2, total_param_);
Eigen::MatrixXd affine_boundary = Eigen::MatrixXd::Zero(2, 1);
affine_boundary << x_kth_derivative, y_kth_derivative;
const size_t index = FindIndex(t);
const size_t index_offset = index * 2 * num_params;
for (size_t i = 0; i < num_params; ++i) {
affine_equality(0, i + index_offset) = coef[i];
affine_equality(1, i + num_params + index_offset) = coef[i];
}
return AddEqualityConstraint(affine_equality, affine_boundary);
}
bool Spline2dConstraint::AddPointAngleConstraint(const double t,
const double angle) {
const uint32_t index = FindIndex(t);
const uint32_t num_params = spline_order_ + 1;
const uint32_t index_offset = index * 2 * num_params;
const double rel_t = t - t_knots_[index];
// add equality constraint
Eigen::MatrixXd affine_equality = Eigen::MatrixXd::Zero(1, total_param_);
Eigen::MatrixXd affine_boundary = Eigen::MatrixXd::Zero(1, 1);
std::vector<double> line_derivative_coef = AffineDerivativeCoef(angle, rel_t);
for (uint32_t i = 0; i < line_derivative_coef.size(); ++i) {
affine_equality(0, i + index_offset) = line_derivative_coef[i];
}
// add inequality constraint
Eigen::MatrixXd affine_inequality = Eigen::MatrixXd::Zero(2, total_param_);
const Eigen::MatrixXd affine_inequality_boundary =
Eigen::MatrixXd::Zero(2, 1);
std::vector<double> t_coef = DerivativeCoef(rel_t);
int x_sign = 1;
int y_sign = 1;
double normalized_angle = fmod(angle, M_PI * 2);
if (normalized_angle < 0) {
normalized_angle += M_PI * 2;
}
if (normalized_angle > (M_PI / 2) && normalized_angle < (M_PI * 1.5)) {
x_sign = -1;
}
if (normalized_angle >= M_PI) {
y_sign = -1;
}
for (uint32_t i = 0; i < t_coef.size(); ++i) {
affine_inequality(0, i + index_offset) = t_coef[i] * x_sign;
affine_inequality(1, i + index_offset + num_params) = t_coef[i] * y_sign;
}
if (!AddEqualityConstraint(affine_equality, affine_boundary)) {
return false;
}
return AddInequalityConstraint(affine_inequality, affine_inequality_boundary);
}
// guarantee up to values are joint
bool Spline2dConstraint::AddSmoothConstraint() {
if (t_knots_.size() < 3) {
return false;
}
Eigen::MatrixXd affine_equality =
Eigen::MatrixXd::Zero(2 * (t_knots_.size() - 2), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(2 * (t_knots_.size() - 2), 1);
for (uint32_t i = 0; i + 2 < t_knots_.size(); ++i) {
const double rel_t = t_knots_[i + 1] - t_knots_[i];
const uint32_t num_params = spline_order_ + 1;
const uint32_t index_offset = 2 * i * num_params;
std::vector<double> power_t = PolyCoef(rel_t);
for (uint32_t j = 0; j < num_params; ++j) {
affine_equality(2 * i, j + index_offset) = power_t[j];
affine_equality(2 * i + 1, j + index_offset + num_params) = power_t[j];
}
affine_equality(2 * i, index_offset + 2 * num_params) = -1.0;
affine_equality(2 * i + 1, index_offset + 3 * num_params) = -1.0;
}
return AddEqualityConstraint(affine_equality, affine_boundary);
}
// guarantee up to derivative are joint
bool Spline2dConstraint::AddDerivativeSmoothConstraint() {
if (t_knots_.size() < 3) {
return true;
}
Eigen::MatrixXd affine_equality =
Eigen::MatrixXd::Zero(4 * (t_knots_.size() - 2), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(4 * (t_knots_.size() - 2), 1);
for (uint32_t i = 0; i + 2 < t_knots_.size(); ++i) {
const double rel_t = t_knots_[i + 1] - t_knots_[i];
const uint32_t num_params = spline_order_ + 1;
const uint32_t index_offset = 2 * i * num_params;
std::vector<double> power_t = PolyCoef(rel_t);
std::vector<double> derivative_t = DerivativeCoef(rel_t);
for (uint32_t j = 0; j < num_params; ++j) {
affine_equality(4 * i, j + index_offset) = power_t[j];
affine_equality(4 * i + 1, j + index_offset) = derivative_t[j];
affine_equality(4 * i + 2, j + index_offset + num_params) = power_t[j];
affine_equality(4 * i + 3, j + index_offset + num_params) =
derivative_t[j];
}
affine_equality(4 * i, index_offset + 2 * num_params) = -1.0;
affine_equality(4 * i + 1, index_offset + 2 * num_params + 1) = -1.0;
affine_equality(4 * i + 2, index_offset + 3 * num_params) = -1.0;
affine_equality(4 * i + 3, index_offset + 3 * num_params + 1) = -1.0;
}
return AddEqualityConstraint(affine_equality, affine_boundary);
}
// guarantee up to second order derivative are joint
bool Spline2dConstraint::AddSecondDerivativeSmoothConstraint() {
if (t_knots_.size() < 3) {
return true;
}
Eigen::MatrixXd affine_equality =
Eigen::MatrixXd::Zero(6 * (t_knots_.size() - 2), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(6 * (t_knots_.size() - 2), 1);
for (uint32_t i = 0; i + 2 < t_knots_.size(); ++i) {
const double rel_t = t_knots_[i + 1] - t_knots_[i];
const uint32_t num_params = spline_order_ + 1;
const uint32_t index_offset = 2 * i * num_params;
std::vector<double> power_t = PolyCoef(rel_t);
std::vector<double> derivative_t = DerivativeCoef(rel_t);
std::vector<double> second_derivative_t = SecondDerivativeCoef(rel_t);
for (uint32_t j = 0; j < num_params; ++j) {
affine_equality(6 * i, j + index_offset) = power_t[j];
affine_equality(6 * i + 1, j + index_offset) = derivative_t[j];
affine_equality(6 * i + 2, j + index_offset) = second_derivative_t[j];
affine_equality(6 * i + 3, j + index_offset + num_params) = power_t[j];
affine_equality(6 * i + 4, j + index_offset + num_params) =
derivative_t[j];
affine_equality(6 * i + 5, j + index_offset + num_params) =
second_derivative_t[j];
}
affine_equality(6 * i, index_offset + 2 * num_params) = -1.0;
affine_equality(6 * i + 1, index_offset + 2 * num_params + 1) = -1.0;
affine_equality(6 * i + 2, index_offset + 2 * num_params + 2) = -2.0;
affine_equality(6 * i + 3, index_offset + 3 * num_params) = -1.0;
affine_equality(6 * i + 4, index_offset + 3 * num_params + 1) = -1.0;
affine_equality(6 * i + 5, index_offset + 3 * num_params + 2) = -2.0;
}
return AddEqualityConstraint(affine_equality, affine_boundary);
}
// guarantee up to third order derivative are joint
bool Spline2dConstraint::AddThirdDerivativeSmoothConstraint() {
if (t_knots_.size() < 3) {
return false;
}
Eigen::MatrixXd affine_equality =
Eigen::MatrixXd::Zero(8 * (t_knots_.size() - 2), total_param_);
Eigen::MatrixXd affine_boundary =
Eigen::MatrixXd::Zero(8 * (t_knots_.size() - 2), 1);
for (uint32_t i = 0; i + 2 < t_knots_.size(); ++i) {
const double rel_t = t_knots_[i + 1] - t_knots_[i];
const uint32_t num_params = spline_order_ + 1;
const uint32_t index_offset = 2 * i * num_params;
std::vector<double> power_t = PolyCoef(rel_t);
std::vector<double> derivative_t = DerivativeCoef(rel_t);
std::vector<double> second_derivative_t = SecondDerivativeCoef(rel_t);
std::vector<double> third_derivative_t = ThirdDerivativeCoef(rel_t);
for (uint32_t j = 0; j < num_params; ++j) {
affine_equality(8 * i, j + index_offset) = power_t[j];
affine_equality(8 * i + 1, j + index_offset) = derivative_t[j];
affine_equality(8 * i + 2, j + index_offset) = second_derivative_t[j];
affine_equality(8 * i + 3, j + index_offset) = third_derivative_t[j];
affine_equality(8 * i + 4, j + index_offset + num_params) = power_t[j];
affine_equality(8 * i + 5, j + index_offset + num_params) =
derivative_t[j];
affine_equality(8 * i + 6, j + index_offset + num_params) =
second_derivative_t[j];
affine_equality(8 * i + 7, j + index_offset + num_params) =
third_derivative_t[j];
}
affine_equality(8 * i, index_offset + 2 * num_params) = -1.0;
affine_equality(8 * i + 1, index_offset + 2 * num_params + 1) = -1.0;
affine_equality(8 * i + 2, index_offset + 2 * num_params + 2) = -2.0;
affine_equality(8 * i + 3, index_offset + 2 * num_params + 3) = -6.0;
affine_equality(8 * i + 4, index_offset + 3 * num_params) = -1.0;
affine_equality(8 * i + 5, index_offset + 3 * num_params + 1) = -1.0;
affine_equality(8 * i + 6, index_offset + 3 * num_params + 2) = -2.0;
affine_equality(8 * i + 7, index_offset + 3 * num_params + 3) = -6.0;
}
return AddEqualityConstraint(affine_equality, affine_boundary);
}
/**
* @brief: output interface inequality constraint
**/
const AffineConstraint& Spline2dConstraint::inequality_constraint() const {
return inequality_constraint_;
}
const AffineConstraint& Spline2dConstraint::equality_constraint() const {
return equality_constraint_;
}
uint32_t Spline2dConstraint::FindIndex(const double t) const {
auto upper_bound = std::upper_bound(t_knots_.begin() + 1, t_knots_.end(), t);
return std::min(static_cast<uint32_t>(t_knots_.size() - 1),
static_cast<uint32_t>(upper_bound - t_knots_.begin())) -
1;
}
std::vector<double> Spline2dConstraint::AffineCoef(const double angle,
const double t) const {
const uint32_t num_params = spline_order_ + 1;
std::vector<double> result(num_params * 2, 0.0);
double x_coef = -common::math::sin(common::math::Angle16::from_rad(angle));
double y_coef = common::math::cos(common::math::Angle16::from_rad(angle));
for (uint32_t i = 0; i < num_params; ++i) {
result[i] = x_coef;
result[i + num_params] = y_coef;
x_coef *= t;
y_coef *= t;
}
return result;
}
std::vector<double> Spline2dConstraint::AffineDerivativeCoef(
const double angle, const double t) const {
const uint32_t num_params = spline_order_ + 1;
std::vector<double> result(num_params * 2, 0.0);
double x_coef = -common::math::sin(common::math::Angle16::from_rad(angle));
double y_coef = common::math::cos(common::math::Angle16::from_rad(angle));
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 1; i < num_params; ++i) {
result[i] = x_coef * power_t[i - 1] * i;
result[i + num_params] = y_coef * power_t[i - 1] * i;
}
return result;
}
std::vector<double> Spline2dConstraint::AffineSecondDerivativeCoef(
const double angle, const double t) const {
const uint32_t num_params = spline_order_ + 1;
std::vector<double> result(num_params * 2, 0.0);
double x_coef = -common::math::sin(common::math::Angle16::from_rad(angle));
double y_coef = common::math::cos(common::math::Angle16::from_rad(angle));
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 2; i < num_params; ++i) {
result[i] = x_coef * power_t[i - 2] * i * (i - 1);
result[i + num_params] = y_coef * power_t[i - 2] * i * (i - 1);
}
return result;
}
std::vector<double> Spline2dConstraint::AffineThirdDerivativeCoef(
const double angle, const double t) const {
const uint32_t num_params = spline_order_ + 1;
std::vector<double> result(num_params * 2, 0.0);
double x_coef = -common::math::sin(common::math::Angle16::from_rad(angle));
double y_coef = common::math::cos(common::math::Angle16::from_rad(angle));
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 3; i < num_params; ++i) {
result[i] = x_coef * power_t[i - 3] * i * (i - 1) * (i - 2);
result[i + num_params] = y_coef * power_t[i - 3] * i * (i - 1) * (i - 2);
}
return result;
}
double Spline2dConstraint::SignDistance(const Vec2d& xy_point,
const double angle) const {
return common::math::InnerProd(
xy_point.x(), xy_point.y(),
-common::math::sin(common::math::Angle16::from_rad(angle)),
common::math::cos(common::math::Angle16::from_rad(angle)));
}
std::vector<double> Spline2dConstraint::PolyCoef(const double t) const {
std::vector<double> result(spline_order_ + 1, 1.0);
for (uint32_t i = 1; i < result.size(); ++i) {
result[i] = result[i - 1] * t;
}
return result;
}
std::vector<double> Spline2dConstraint::DerivativeCoef(const double t) const {
std::vector<double> result(spline_order_ + 1, 0.0);
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 1; i < result.size(); ++i) {
result[i] = power_t[i - 1] * i;
}
return result;
}
std::vector<double> Spline2dConstraint::SecondDerivativeCoef(
const double t) const {
std::vector<double> result(spline_order_ + 1, 0.0);
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 2; i < result.size(); ++i) {
result[i] = power_t[i - 2] * i * (i - 1);
}
return result;
}
std::vector<double> Spline2dConstraint::ThirdDerivativeCoef(
const double t) const {
std::vector<double> result(spline_order_ + 1, 0.0);
std::vector<double> power_t = PolyCoef(t);
for (uint32_t i = 3; i < result.size(); ++i) {
result[i] = power_t[i - 3] * i * (i - 1) * (i - 2);
}
return result;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_seg.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_seg.cc
* @brief: polynomial smoothing spline segment
**/
#include "modules/planning/math/smoothing_spline/spline_1d_seg.h"
namespace apollo {
namespace planning {
Spline1dSeg::Spline1dSeg(const uint32_t order) {
SetSplineFunc(PolynomialXd(order));
}
Spline1dSeg::Spline1dSeg(const std::vector<double>& params) {
SetSplineFunc(PolynomialXd(params));
}
void Spline1dSeg::SetParams(const std::vector<double>& params) {
SetSplineFunc(PolynomialXd(params));
}
void Spline1dSeg::SetSplineFunc(const PolynomialXd& spline_func) {
spline_func_ = spline_func;
derivative_ = PolynomialXd::DerivedFrom(spline_func_);
second_order_derivative_ = PolynomialXd::DerivedFrom(derivative_);
third_order_derivative_ = PolynomialXd::DerivedFrom(second_order_derivative_);
}
double Spline1dSeg::operator()(const double x) const { return spline_func_(x); }
double Spline1dSeg::Derivative(const double x) const { return derivative_(x); }
double Spline1dSeg::SecondOrderDerivative(const double x) const {
return second_order_derivative_(x);
}
double Spline1dSeg::ThirdOrderDerivative(const double x) const {
return third_order_derivative_(x);
}
const PolynomialXd& Spline1dSeg::spline_func() const { return spline_func_; }
const PolynomialXd& Spline1dSeg::Derivative() const { return derivative_; }
const PolynomialXd& Spline1dSeg::SecondOrderDerivative() const {
return second_order_derivative_;
}
const PolynomialXd& Spline1dSeg::ThirdOrderDerivative() const {
return third_order_derivative_;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/osqp_spline_2d_solver.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 <vector>
#include "gtest/gtest_prod.h"
#include "modules/planning/math/smoothing_spline/spline_2d.h"
#include "modules/planning/math/smoothing_spline/spline_2d_solver.h"
#include "osqp/osqp.h"
namespace apollo {
namespace planning {
class OsqpSpline2dSolver final : public Spline2dSolver {
public:
OsqpSpline2dSolver(const std::vector<double>& t_knots, const uint32_t order);
void Reset(const std::vector<double>& t_knots, const uint32_t order) override;
// customize setup
Spline2dConstraint* mutable_constraint() override;
Spline2dKernel* mutable_kernel() override;
Spline2d* mutable_spline() override;
// solve
bool Solve() override;
// extract
const Spline2d& spline() const override;
private:
FRIEND_TEST(OSQPSolverTest, basic_test);
private:
OSQPSettings* osqp_settings_ = nullptr;
OSQPWorkspace* work_ = nullptr; // Workspace
OSQPData* data_ = nullptr; // OSQPData
int last_num_constraint_ = 0;
int last_num_param_ = 0;
bool last_problem_success_ = false;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_kernel.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 : piecewise_smoothing_spline_constraint.h
* @brief: wrap up solver constraint interface with direct methods and preset
*methods
**/
#include "modules/planning/math/smoothing_spline/spline_1d_kernel.h"
#include <algorithm>
#include "cyber/common/log.h"
#include "modules/planning/math/smoothing_spline/spline_seg_kernel.h"
namespace apollo {
namespace planning {
Spline1dKernel::Spline1dKernel(const Spline1d& spline1d)
: Spline1dKernel(spline1d.x_knots(), spline1d.spline_order()) {}
Spline1dKernel::Spline1dKernel(const std::vector<double>& x_knots,
const uint32_t spline_order)
: x_knots_(x_knots), spline_order_(spline_order) {
total_params_ =
(static_cast<uint32_t>(x_knots.size()) > 1
? (static_cast<uint32_t>(x_knots.size()) - 1) * (1 + spline_order_)
: 0);
kernel_matrix_ = Eigen::MatrixXd::Zero(total_params_, total_params_);
offset_ = Eigen::MatrixXd::Zero(total_params_, 1);
}
void Spline1dKernel::AddRegularization(const double regularized_param) {
Eigen::MatrixXd id_matrix =
Eigen::MatrixXd::Identity(kernel_matrix_.rows(), kernel_matrix_.cols());
kernel_matrix_ += 2.0 * id_matrix * regularized_param;
}
bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
const Eigen::MatrixXd& offset,
const double weight) {
if (kernel.rows() != kernel.cols() ||
kernel.rows() != kernel_matrix_.rows() || offset.cols() != 1 ||
offset.rows() != offset_.rows()) {
return false;
}
kernel_matrix_ += kernel * weight;
offset_ += offset * weight;
return true;
}
bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
const double weight) {
Eigen::MatrixXd offset = Eigen::MatrixXd::Zero(kernel.rows(), 1);
return AddKernel(kernel, offset, weight);
}
Eigen::MatrixXd* Spline1dKernel::mutable_kernel_matrix() {
return &kernel_matrix_;
}
Eigen::MatrixXd* Spline1dKernel::mutable_offset() { return &offset_; }
const Eigen::MatrixXd& Spline1dKernel::kernel_matrix() const {
return kernel_matrix_;
}
const Eigen::MatrixXd& Spline1dKernel::offset() const { return offset_; }
// build-in kernel methods
void Spline1dKernel::AddNthDerivativekernelMatrix(const uint32_t n,
const double weight) {
const uint32_t num_params = spline_order_ + 1;
for (uint32_t i = 0; i + 1 < x_knots_.size(); ++i) {
Eigen::MatrixXd cur_kernel =
2 *
SplineSegKernel::Instance()->NthDerivativeKernel(
n, num_params, x_knots_[i + 1] - x_knots_[i]) *
weight;
kernel_matrix_.block(i * num_params, i * num_params, num_params,
num_params) += cur_kernel;
}
}
void Spline1dKernel::AddDerivativeKernelMatrix(const double weight) {
AddNthDerivativekernelMatrix(1, weight);
}
void Spline1dKernel::AddSecondOrderDerivativeMatrix(const double weight) {
AddNthDerivativekernelMatrix(2, weight);
}
void Spline1dKernel::AddThirdOrderDerivativeMatrix(const double weight) {
AddNthDerivativekernelMatrix(3, weight);
}
void Spline1dKernel::AddNthDerivativekernelMatrixForSplineK(
const uint32_t n, const uint32_t k, const double weight) {
if (k + 1 >= x_knots_.size()) {
AERROR << "Cannot add NthDerivativeKernel for spline K because k is out of "
"range. k = "
<< k;
return;
}
const uint32_t num_params = spline_order_ + 1;
Eigen::MatrixXd cur_kernel =
2 *
SplineSegKernel::Instance()->NthDerivativeKernel(
n, num_params, x_knots_[k + 1] - x_knots_[k]) *
weight;
kernel_matrix_.block(k * num_params, k * num_params, num_params,
num_params) += cur_kernel;
}
void Spline1dKernel::AddDerivativeKernelMatrixForSplineK(const uint32_t k,
const double weight) {
AddNthDerivativekernelMatrixForSplineK(1, k, weight);
}
void Spline1dKernel::AddSecondOrderDerivativeMatrixForSplineK(
const uint32_t k, const double weight) {
AddNthDerivativekernelMatrixForSplineK(2, k, weight);
}
void Spline1dKernel::AddThirdOrderDerivativeMatrixForSplineK(
const uint32_t k, const double weight) {
AddNthDerivativekernelMatrixForSplineK(3, k, weight);
}
bool Spline1dKernel::AddReferenceLineKernelMatrix(
const std::vector<double>& x_coord, const std::vector<double>& ref_x,
const double weight) {
if (ref_x.size() != x_coord.size()) {
return false;
}
const uint32_t num_params = spline_order_ + 1;
for (size_t i = 0; i < x_coord.size(); ++i) {
auto cur_index = FindIndex(x_coord[i]);
double cur_rel_x = x_coord[i] - x_knots_[cur_index];
// update offset
double offset_coef = -2.0 * ref_x[i] * weight;
for (size_t j = 0; j < num_params; ++j) {
offset_(j + cur_index * num_params, 0) += offset_coef;
offset_coef *= cur_rel_x;
}
// update kernel matrix
Eigen::MatrixXd ref_kernel(num_params, num_params);
double cur_x = 1.0;
std::vector<double> power_x;
for (uint32_t n = 0; n + 1 < 2 * num_params; ++n) {
power_x.emplace_back(cur_x);
cur_x *= cur_rel_x;
}
for (uint32_t r = 0; r < num_params; ++r) {
for (uint32_t c = 0; c < num_params; ++c) {
ref_kernel(r, c) = 2.0 * power_x[r + c];
}
}
kernel_matrix_.block(cur_index * num_params, cur_index * num_params,
num_params, num_params) += weight * ref_kernel;
}
return true;
}
uint32_t Spline1dKernel::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;
}
void Spline1dKernel::AddDistanceOffset(const double weight) {
for (uint32_t i = 1; i < x_knots_.size(); ++i) {
const double cur_x = x_knots_[i] - x_knots_[i - 1];
double pw_x = 2.0 * weight;
for (uint32_t j = 0; j < spline_order_ + 1; ++j) {
offset_((i - 1) * (spline_order_ + 1) + j, 0) -= pw_x;
pw_x *= cur_x;
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_solver.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_1d_solver.h"
namespace apollo {
namespace planning {
using Eigen::MatrixXd;
// converte qp problem to proto
void Spline1dSolver::GenerateProblemProto(
QuadraticProgrammingProblem* const qp_proto) const {
const MatrixXd& kernel_matrix = kernel_.kernel_matrix();
const MatrixXd& offset = kernel_.offset();
const MatrixXd& inequality_constraint_matrix =
constraint_.inequality_constraint().constraint_matrix();
const MatrixXd& inequality_constraint_boundary =
constraint_.inequality_constraint().constraint_boundary();
const MatrixXd& equality_constraint_matrix =
constraint_.equality_constraint().constraint_matrix();
const MatrixXd& equality_constraint_boundary =
constraint_.equality_constraint().constraint_boundary();
qp_proto->set_param_size(static_cast<int32_t>(kernel_matrix.rows()));
ConvertMatrixXdToProto(kernel_matrix, qp_proto->mutable_quadratic_matrix());
for (int i = 0; i < offset.rows(); ++i) {
qp_proto->add_bias(offset(i, 0));
}
ConvertMatrixXdToProto(inequality_constraint_matrix,
qp_proto->mutable_inequality_matrix());
for (int i = 0; i < inequality_constraint_boundary.rows(); ++i) {
qp_proto->add_inequality_value(inequality_constraint_boundary(i, 0));
}
ConvertMatrixXdToProto(equality_constraint_matrix,
qp_proto->mutable_equality_matrix());
for (int i = 0; i < equality_constraint_boundary.rows(); ++i) {
qp_proto->add_equality_value(equality_constraint_boundary(i, 0));
}
// add the optimal solution
const auto& splines = spline_.splines();
for (const auto& spline_seg : splines) {
const auto& param_seg = spline_seg.spline_func().params();
for (const auto value : param_seg) {
qp_proto->add_optimal_param(value);
}
}
}
void Spline1dSolver::ConvertMatrixXdToProto(const Eigen::MatrixXd& matrix,
QPMatrix* const proto) const {
int row_size = static_cast<int>(matrix.rows());
int col_size = static_cast<int>(matrix.cols());
proto->set_row_size(row_size);
proto->set_col_size(col_size);
for (int r = 0; r < row_size; ++r) {
for (int c = 0; c < col_size; ++c) {
proto->add_element(matrix(r, c));
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_kernel_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_kernel.h"
#include "cyber/common/log.h"
#include "gtest/gtest.h"
namespace apollo {
namespace planning {
TEST(Spline2dKernel, add_regularization) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline2dKernel kernel(x_knots, spline_order);
kernel.AddRegularization(0.2);
for (int i = 0; i < kernel.kernel_matrix().rows(); ++i) {
for (int j = 0; j < kernel.kernel_matrix().cols(); ++j) {
if (i == j) {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.4);
} else {
EXPECT_DOUBLE_EQ(kernel.kernel_matrix()(i, j), 0.0);
}
}
}
for (int i = 0; i < kernel.offset().rows(); ++i) {
for (int j = 0; j < kernel.offset().cols(); ++j) {
EXPECT_DOUBLE_EQ(kernel.offset()(i, j), 0.0);
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_kernel.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_2d_kernel.cc
**/
#include "modules/planning/math/smoothing_spline/spline_2d_kernel.h"
#include <algorithm>
#include "modules/planning/math/smoothing_spline/spline_seg_kernel.h"
namespace apollo {
namespace planning {
using apollo::common::math::Vec2d;
Spline2dKernel::Spline2dKernel(const std::vector<double>& t_knots,
const uint32_t spline_order)
: t_knots_(t_knots), spline_order_(spline_order) {
total_params_ =
(t_knots_.size() > 1 ? 2 * (t_knots_.size() - 1) * (1 + spline_order_)
: 0);
kernel_matrix_ = Eigen::MatrixXd::Zero(total_params_, total_params_);
offset_ = Eigen::MatrixXd::Zero(total_params_, 1);
}
// customized input output
void Spline2dKernel::AddRegularization(const double regularization_param) {
Eigen::MatrixXd id_matrix =
Eigen::MatrixXd::Identity(kernel_matrix_.rows(), kernel_matrix_.cols());
kernel_matrix_ += id_matrix * regularization_param;
}
bool Spline2dKernel::AddKernel(const Eigen::MatrixXd& kernel,
const Eigen::MatrixXd& offset,
const double weight) {
if (kernel.rows() != kernel.cols() ||
kernel.rows() != kernel_matrix_.rows() || offset.cols() != 1 ||
offset.rows() != offset_.rows()) {
return false;
}
kernel_matrix_ += kernel * weight;
offset_ += offset * weight;
return true;
}
bool Spline2dKernel::AddKernel(const Eigen::MatrixXd& kernel,
const double weight) {
Eigen::MatrixXd offset = Eigen::MatrixXd::Zero(kernel.rows(), 1);
return AddKernel(kernel, offset, weight);
}
Eigen::MatrixXd* Spline2dKernel::mutable_kernel_matrix() {
return &kernel_matrix_;
}
Eigen::MatrixXd* Spline2dKernel::mutable_offset() { return &offset_; }
Eigen::MatrixXd Spline2dKernel::kernel_matrix() const {
return kernel_matrix_ * 2.0;
}
const Eigen::MatrixXd Spline2dKernel::offset() const { return offset_; }
// build-in kernel methods
void Spline2dKernel::AddNthDerivativeKernelMatrix(const uint32_t n,
const double weight) {
for (uint32_t i = 0; i + 1 < t_knots_.size(); ++i) {
const uint32_t num_params = spline_order_ + 1;
Eigen::MatrixXd cur_kernel =
SplineSegKernel::Instance()->NthDerivativeKernel(
n, num_params, t_knots_[i + 1] - t_knots_[i]) *
weight;
kernel_matrix_.block(2 * i * num_params, 2 * i * num_params, num_params,
num_params) += cur_kernel;
kernel_matrix_.block((2 * i + 1) * num_params, (2 * i + 1) * num_params,
num_params, num_params) += cur_kernel;
}
}
void Spline2dKernel::AddDerivativeKernelMatrix(const double weight) {
AddNthDerivativeKernelMatrix(1, weight);
}
void Spline2dKernel::AddSecondOrderDerivativeMatrix(const double weight) {
AddNthDerivativeKernelMatrix(2, weight);
}
void Spline2dKernel::AddThirdOrderDerivativeMatrix(const double weight) {
AddNthDerivativeKernelMatrix(3, weight);
}
// reference line kernel, t_coord in strictly increasing order (for path
// optimizer)
bool Spline2dKernel::AddReferenceLineKernelMatrix(
const std::vector<double>& t_coord, const std::vector<Vec2d>& ref_points,
const double weight) {
if (ref_points.size() != t_coord.size()) {
return false;
}
for (uint32_t i = 0; i < t_coord.size(); ++i) {
auto cur_index = find_index(t_coord[i]);
double cur_rel_t = t_coord[i] - t_knots_[cur_index];
// update offset
double offset_coef_x = -ref_points[i].x() * weight;
double offset_coef_y = -ref_points[i].y() * weight;
const uint32_t num_params = spline_order_ + 1;
for (uint32_t j = 0; j < num_params; ++j) {
offset_(j + (2 * cur_index) * num_params, 0) = offset_coef_x;
offset_(j + (2 * cur_index + 1) * num_params, 0) = offset_coef_y;
offset_coef_x *= cur_rel_t;
offset_coef_y *= cur_rel_t;
}
// update kernel matrix
Eigen::MatrixXd ref_kernel(num_params, num_params);
double cur_t = 1.0;
std::vector<double> power_t;
for (uint32_t n = 0; n + 1 < 2 * num_params; ++n) {
power_t.emplace_back(cur_t);
cur_t *= cur_rel_t;
}
for (uint32_t r = 0; r < num_params; ++r) {
for (uint32_t c = 0; c < num_params; ++c) {
ref_kernel(r, c) = power_t[r + c];
}
}
kernel_matrix_.block((2 * cur_index) * num_params,
(2 * cur_index) * num_params, num_params,
num_params) += weight * ref_kernel;
kernel_matrix_.block((2 * cur_index + 1) * num_params,
(2 * cur_index + 1) * num_params, num_params,
num_params) += weight * ref_kernel;
}
return true;
}
uint32_t Spline2dKernel::find_index(const double t) const {
auto upper_bound = std::upper_bound(t_knots_.begin() + 1, t_knots_.end(), t);
return std::min(static_cast<uint32_t>(t_knots_.size() - 1),
static_cast<uint32_t>(upper_bound - t_knots_.begin())) -
1;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_seg.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_seg.h
* @brief: polynomial smoothing spline
**/
#pragma once
#include <vector>
#include "Eigen/Core"
#include "modules/planning/math/polynomial_xd.h"
namespace apollo {
namespace planning {
class Spline1dSeg {
public:
// order represents the highest order.
explicit Spline1dSeg(const uint32_t order);
explicit Spline1dSeg(const std::vector<double>& params);
~Spline1dSeg() = default;
void SetParams(const std::vector<double>& params);
double operator()(const double x) const;
double Derivative(const double x) const;
double SecondOrderDerivative(const double x) const;
double ThirdOrderDerivative(const double x) const;
const PolynomialXd& spline_func() const;
const PolynomialXd& Derivative() const;
const PolynomialXd& SecondOrderDerivative() const;
const PolynomialXd& ThirdOrderDerivative() const;
private:
inline void SetSplineFunc(const PolynomialXd& spline_func);
PolynomialXd spline_func_;
PolynomialXd derivative_;
PolynomialXd second_order_derivative_;
PolynomialXd third_order_derivative_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/osqp_spline_2d_solver_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/smoothing_spline/osqp_spline_2d_solver.h"
#include <chrono>
#include "gtest/gtest.h"
#include "modules/planning/math/curve_math.h"
namespace apollo {
namespace planning {
using apollo::common::math::Vec2d;
using Eigen::MatrixXd;
TEST(OSQPSolverTest, solver_test_01) {
std::vector<double> t_knots{0, 1, 2, 3, 4, 5};
uint32_t order = 5;
OsqpSpline2dSolver spline_solver(t_knots, order);
Spline2dConstraint* constraint = spline_solver.mutable_constraint();
Spline2dKernel* kernel = spline_solver.mutable_kernel();
std::vector<double> et{0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5};
std::vector<double> bound(11, 0.2);
std::vector<std::vector<double>> constraint_data{
{-1.211566924, 434592.7844, 4437011.568},
{-1.211572116, 434594.6884, 4437006.498},
{-1.21157766, 434596.5923, 4437001.428},
{-1.211571616, 434598.4962, 4436996.358},
{-1.21155227, 434600.4002, 4436991.288},
{-1.211532017, 434602.3043, 4436986.218},
{-1.21155775, 434604.2083, 4436981.148},
{-1.211634014, 434606.1122, 4436976.077},
{-1.211698593, 434608.0156, 4436971.007},
{-1.211576177, 434609.9191, 4436965.937},
{-1.211256197, 434611.8237, 4436960.867}};
std::vector<double> angle;
std::vector<Vec2d> ref_point;
for (size_t i = 0; i < 11; ++i) {
angle.push_back(constraint_data[i][0]);
Vec2d prev_point(constraint_data[i][1], constraint_data[i][2]);
Vec2d new_point = prev_point;
ref_point.emplace_back(new_point.x(), new_point.y());
}
EXPECT_TRUE(constraint->Add2dBoundary(et, angle, ref_point, bound, bound));
EXPECT_TRUE(constraint->AddThirdDerivativeSmoothConstraint());
kernel->AddThirdOrderDerivativeMatrix(100);
// kernel->add_second_order_derivative_matrix(100);
// kernel->add_derivative_kernel_matrix(100);
kernel->AddRegularization(0.1);
// constraint->add_point_angle_constraint(0, -1.21);
// TODO(all): fix the test.
auto start = std::chrono::system_clock::now();
EXPECT_TRUE(spline_solver.Solve());
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Time to solver is " << diff.count() << " s\n";
MatrixXd gold_res(51, 6);
// clang-format off
gold_res <<
-1.211536842077514109 , 434592.66747698455583, 4437011.3104558130726, 3.8080526249093837876, -10.139728378837974176, -4.9702012767283664302e-06, // NOLINT
-1.2115424151423492827, 434593.04828098160215, 4437010.2964778374881, 3.8080266324837173109, -10.139830860402472723, -5.250894216084755994e-06, // NOLINT
-1.211548079937599498 , 434593.42908218270168, 4437009.282489891164 , 3.8079967985589404655, -10.139925941668183285, -5.1522704816467339639e-06, // NOLINT
-1.2115534670910343973, 434593.80988023628015, 4437008.2684932174161, 3.807963824342671888 , -10.140004109433711221, -4.7509311852720327338e-06, // NOLINT
-1.2115582901792760762, 434594.19067487574648, 4437007.2544898428023, 3.8079287063501028321, -10.140059191754115631, -4.1234548052899087269e-06, // NOLINT
-1.2115623457107336236, 434594.57146594882943, 4437006.2404822465032, 3.8078927364039967252, -10.140088357940907571, -3.346398718521420416e-06, // NOLINT
-1.2115655131115372622, 434594.95225344720529, 4437005.226473021321 , 3.807857501634689612 , -10.140092118562053614, -2.4963055868708661977e-06, // NOLINT
-1.2115677547171821438, 434595.33303753606742, 4437004.2124645449221, 3.807824884480089267 , -10.140074325441972292, -1.6497122000467622075e-06, // NOLINT
-1.2115691157708639025, 434595.71381858363748, 4437003.1984586389735, 3.8077970626856774139, -10.140042171661530546, -8.8315837695925047957e-07, // NOLINT
-1.2115697244277590094, 434596.09459719056031, 4437002.1844562413171, 3.807776509304506618 , -10.140006191558054383, -2.7319352839184158338e-07, // NOLINT
-1.2115697917627634705, 434596.47537421970628, 4437001.1704570697621, 3.8077659926972025062, -10.139980260725319994, 1.0362151721092292462e-07, // NOLINT
-1.2115695060626494595, 434596.85615080740536, 4437000.1564594125375, 3.8077678515443436069, -10.139976408292163512, 4.6408745318981610703e-07, // NOLINT
-1.2115687107848465143, 434597.23692818894051, 4436999.1424612496048, 3.8077816733989728881, -10.139988712761946132, 1.0340515817845881855e-06, // NOLINT
-1.2115672131285435409, 434597.61770749953575, 4436998.1284614419565, 3.8078062133014105584, -10.140007918433125766, 1.7505174784501674035e-06, // NOLINT
-1.2115648885226146803, 434597.99848974274937, 4436997.1144596887752, 3.8078400821457005776, -10.140026487871562466, 2.550493252490749351e-06, // NOLINT
-1.2115616806216027435, 434598.3792757759802 , 4436996.1004563607275, 3.8078817466796182067, -10.140038601910511318, 3.3709929708283110962e-06, // NOLINT
-1.2115576013019537793, 434598.76006629614858, 4436995.0864523220807, 3.8079295295046677872, -10.140040159650634877, 4.1490353176471159136e-06, // NOLINT
-1.2115527306601105995, 434599.1408618252608 , 4436994.0724487621337, 3.8079816090760862934, -10.140028778459988956, 4.8216404409474350213e-06, // NOLINT
-1.2115472170133783081, 434599.52166269585723, 4436993.058447021991 , 3.8080360197028402247, -10.140003793974035062, 5.3258259372985455144e-06, // NOLINT
-1.2115412769037934293, 434599.90246903675143, 4436992.0444484241307, 3.8080906515476260488, -10.139966260095631512, 5.598602925861600625e-06, // NOLINT
-1.2115351951045365553, 434600.28328075853642, 4436991.030454098247 , 3.808143250626879972 , -10.139918948995036985, 5.576973162632266028e-06, // NOLINT
-1.2115294702539036731, 434600.66409751231549, 4436990.0164647698402, 3.8081903561870884545, -10.139868008034298441, 4.8077597313767370503e-06, // NOLINT
-1.2115251375632734021, 434601.04491840628907, 4436989.0024801855907, 3.808224824160084232 , -10.139826306862863348, 3.0486030083292842975e-06, // NOLINT
-1.2115231321195760739, 434601.42574184050318, 4436987.9884988041595, 3.8082402598548479311, -10.13980562520879225 , 5.5275025457330651254e-07, // NOLINT
-1.2115241146872521849, 434601.80656567483675, 4436986.9745180681348, 3.8082322584127257237, -10.139814590034983866, -2.4265100165787592887e-06, // NOLINT
-1.2115284716799898934, 434602.18738742824644, 4436985.9605347122997, 3.8081984048074284388, -10.139858675539189292, -5.6358560536309203708e-06, // NOLINT
-1.2115363151431126632, 434602.56820447766222, 4436984.9465450821444, 3.8081382738450333392, -10.139940203154003129, -8.8219528535762411261e-06, // NOLINT
-1.2115474827532255464, 434602.94901425705757, 4436983.9325454477221, 3.8080534301639805683, -10.140058341546867027, -1.1731478591964790206e-05, // NOLINT
-1.2115615378377246891, 434603.32981445622863, 4436982.9185323221609, 3.8079474282350775916, -10.140209106620064361, -1.4111151966075817204e-05, // NOLINT
-1.2115777694127920494, 434603.71060322003905, 4436981.9045027736574, 3.8078258123614956432, -10.140385361510730888, -1.5707754920828727438e-05, // NOLINT
-1.2115951922344931901, 434604.09137934719911, 4436980.8904547393322, 3.8076961166787692825, -10.140576816590844089, -1.6268145228448618606e-05, // NOLINT
-1.2116125889487479039, 434604.47214246902149, 4436979.8763873716816, 3.8075670315926619658, -10.140769106614820672, -1.5673636657669147182e-05, // NOLINT
-1.2116287906335816427, 434604.85289298970019, 4436978.8623015228659, 3.8074450081129960211, -10.140943390519536749, -1.4090310598988598536e-05, // NOLINT
-1.2116428203719258327, 434605.23363187833456, 4436977.8481998452917, 3.8073351923255067675, -10.141083264606631786, -1.1692162504206557436e-05, // NOLINT
-1.21165388963954479 , 434605.61436058417894, 4436976.834086435847 , 3.8072420352090459161, -10.141176277484222013, -8.6530843040166213536e-06, // NOLINT
-1.2116613982288511053, 434605.99508096667705, 4436975.8199664391577, 3.8071692926355793496, -10.141213930066893312, -5.1468717174906078468e-06, // NOLINT
-1.2116649341851788435, 434606.37579522602027, 4436974.8058456517756, 3.8071200253701888983, -10.141191675575703002, -1.3472491624807740227e-06, // NOLINT
-1.2116642737662484119, 434606.75650583388051, 4436973.7917301254347, 3.8070965990710723403, -10.141108919538183386, 2.5720935559557779256e-06, // NOLINT
-1.2116593814313549871, 434607.13721546367742, 4436972.7776257768273, 3.8071006842895429578, -10.140969019788338201, 6.4374585958675587059e-06, // NOLINT
-1.2116504098626179609, 434607.51792692107847, 4436971.7635379871354, 3.8071332564700290924, -10.140779286466644393, 1.0075097281741009924e-05, // NOLINT
-1.2116377000164157973, 434607.89864307461539, 4436970.7494712099433, 3.8071945959500750334, -10.140550982020052118, 1.3311172977170112426e-05, // NOLINT
-1.2116217746240613984, 434608.27936676860554, 4436969.7354286238551, 3.8072835982384574116, -10.140297281596426515, 1.5999703511677472223e-05, // NOLINT
-1.2116032340269256018, 434608.66010057670064, 4436968.7214123532176, 3.8073960888063611563, -10.140025573140695414, 1.8150697288770883026e-05, // NOLINT
-1.2115826280259958114, 434609.04084661870729, 4436967.7074239440262, 3.8075275641774672941, -10.139740809308877445, 1.9824220542444219705e-05, // NOLINT
-1.2115604413276630513, 434609.42160658695502, 4436966.6934644868597, 3.8076739776390393644, -10.139447151801833868, 2.1080345198949189623e-05, // NOLINT
-1.2115370935378786399, 434609.80238179198932, 4436965.6795346960425, 3.8078317392419229748, -10.139147971365266798, 2.1979154386414284563e-05, // NOLINT
-1.211512939152885826 , 434610.18317320814822, 4436964.6656349897385, 3.8079977158005493543, -10.138845847789720978, 2.2580746160597712412e-05, // NOLINT
-1.2114882675477143259, 434610.56398151925532, 4436963.6517655644566, 3.8081692308929300239, -10.138542569910585556, 2.2945235784308586307e-05, // NOLINT
-1.2114633029633761208, 434610.94480716442922, 4436962.6379264798015, 3.8083440648606621259, -10.138239135608092312, 2.3132756898251399347e-05, // NOLINT
-1.211438204493459958 , 434611.3256503836019 , 4436961.624117734842 , 3.8085204548089248711, -10.137935751807310325, 2.3203461921265504272e-05, // NOLINT
-1.211413066070579303 , 434611.70651126321172, 4436960.6103393463418, 3.8086970946064799826, -10.13763183447815841 , 2.3217522018132972405e-05; // NOLINT
// clang-format on
double t = 0;
for (int i = 0; i < 51; ++i) {
auto xy = spline_solver.spline()(t);
EXPECT_NEAR(xy.first, gold_res(i, 1),
std::fmax(3e-3, gold_res(i, 1) * 1e-4));
EXPECT_NEAR(xy.second, gold_res(i, 2),
std::fmax(3e-3, gold_res(i, 2) * 1e-4));
t += 0.1;
}
}
} // 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.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 <vector>
#include "modules/common/math/qp_solver/qp_solver.h"
#include "modules/planning/math/smoothing_spline/spline_1d_solver.h"
#include "osqp/osqp.h"
namespace apollo {
namespace planning {
class OsqpSpline1dSolver : public Spline1dSolver {
public:
OsqpSpline1dSolver(const std::vector<double>& x_knots, const uint32_t order);
virtual ~OsqpSpline1dSolver();
bool Solve() override;
void CleanUp();
void ResetOsqp();
private:
OSQPSettings* settings_ = nullptr;
OSQPWorkspace* work_ = nullptr; // Workspace
OSQPData* data_ = nullptr; // OSQPData
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "affine_constraint",
srcs = ["affine_constraint.cc"],
hdrs = ["affine_constraint.h"],
deps = [
"//modules/planning/math:polynomial_xd",
"@eigen",
],
)
cc_library(
name = "spline_1d_seg",
srcs = ["spline_1d_seg.cc"],
hdrs = ["spline_1d_seg.h"],
deps = [
"//modules/planning/math:polynomial_xd",
"@eigen",
],
)
cc_library(
name = "spline_1d",
srcs = ["spline_1d.cc"],
hdrs = ["spline_1d.h"],
deps = [
":affine_constraint",
":spline_1d_seg",
"//modules/planning/math:polynomial_xd",
"@eigen",
],
)
cc_library(
name = "spline_1d_constraint",
srcs = ["spline_1d_constraint.cc"],
hdrs = ["spline_1d_constraint.h"],
deps = [
":affine_constraint",
":spline_1d",
"//cyber",
"@eigen",
],
)
cc_library(
name = "spline_seg_kernel",
srcs = ["spline_seg_kernel.cc"],
hdrs = ["spline_seg_kernel.h"],
copts = [
"-DMODULE_NAME=\\\"planning\\\"",
],
deps = [
"//cyber",
"@eigen",
],
)
cc_library(
name = "spline_1d_kernel",
srcs = ["spline_1d_kernel.cc"],
hdrs = ["spline_1d_kernel.h"],
deps = [
":affine_constraint",
":spline_1d",
":spline_seg_kernel",
"@eigen",
],
)
cc_library(
name = "spline_1d_solver",
srcs = ["spline_1d_solver.cc"],
hdrs = ["spline_1d_solver.h"],
deps = [
":spline_1d",
":spline_1d_constraint",
":spline_1d_kernel",
# "//modules/common/math",
"//modules/common/math/qp_solver",
"//modules/planning/common:planning_gflags",
"//modules/planning/proto/math:qp_problem_cc_proto",
"@eigen",
],
)
cc_library(
name = "osqp_spline_1d_solver",
srcs = ["osqp_spline_1d_solver.cc"],
hdrs = ["osqp_spline_1d_solver.h"],
deps = [
":spline_1d_solver",
"//modules/common/math",
"//modules/common/math/qp_solver",
"//modules/planning/common:planning_gflags",
"@osqp",
],
)
cc_test(
name = "osqp_spline_1d_solver_test",
size = "small",
srcs = ["osqp_spline_1d_solver_test.cc"],
deps = [
":osqp_spline_1d_solver",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "spline_2d_seg",
srcs = ["spline_2d_seg.cc"],
hdrs = ["spline_2d_seg.h"],
deps = [
"//modules/planning/math:polynomial_xd",
"@eigen",
],
)
cc_library(
name = "spline_2d",
srcs = ["spline_2d.cc"],
hdrs = ["spline_2d.h"],
deps = [
":spline_2d_seg",
"//modules/planning/math:polynomial_xd",
"@eigen",
],
)
cc_library(
name = "spline_2d_constraint",
srcs = ["spline_2d_constraint.cc"],
hdrs = ["spline_2d_constraint.h"],
deps = [
":affine_constraint",
":spline_2d",
"//modules/common/math",
"@eigen",
],
)
cc_library(
name = "spline_2d_kernel",
srcs = ["spline_2d_kernel.cc"],
hdrs = ["spline_2d_kernel.h"],
deps = [
":spline_2d",
":spline_seg_kernel",
"//modules/common/math",
"@eigen",
],
)
cc_library(
name = "spline_2d_solver",
hdrs = [
"osqp_spline_2d_solver.h",
"spline_2d_solver.h",
],
deps = [
":spline_2d",
":spline_2d_constraint",
":spline_2d_kernel",
# "//modules/common/math",
"//modules/common/math/qp_solver",
"//modules/planning/common:planning_gflags",
"@eigen",
"@osqp",
],
)
cc_library(
name = "osqp_spline_2d_solver",
srcs = ["osqp_spline_2d_solver.cc"],
hdrs = ["osqp_spline_2d_solver.h"],
deps = [
":spline_2d_solver",
":spline_2d",
"//modules/common/math",
"//modules/planning/common:planning_gflags",
"@com_google_googletest//:gtest",
"@osqp",
],
)
cc_test(
name = "osqp_spline_2d_solver_test",
size = "small",
srcs = ["osqp_spline_2d_solver_test.cc"],
deps = [
":osqp_spline_2d_solver",
"//modules/planning/math:curve_math",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "spline_1d_kernel_test",
size = "small",
srcs = ["spline_1d_kernel_test.cc"],
linkopts = ["-lm"],
deps = [
":spline_1d_kernel",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "spline_1d_constraint_test",
size = "small",
srcs = ["spline_1d_constraint_test.cc"],
deps = [
":spline_1d_constraint",
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "spline_2d_kernel_test",
size = "small",
srcs = ["spline_2d_kernel_test.cc"],
deps = [
":spline_2d_kernel",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "spline_2d_constraint_test",
size = "small",
srcs = ["spline_2d_constraint_test.cc"],
deps = [
":spline_2d_constraint",
"@com_google_googletest//:gtest_main",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_constraint.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_2d_constraint.h
**/
#pragma once
#include <vector>
#include "Eigen/Core"
#include "modules/common/math/vec2d.h"
#include "modules/planning/math/smoothing_spline/affine_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_2d.h"
namespace apollo {
namespace planning {
class Spline2dConstraint {
public:
Spline2dConstraint(const std::vector<double>& t_knots, const uint32_t order);
// direct method
bool AddInequalityConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary);
bool AddEqualityConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary);
// preset method
/**
* @brief: inequality boundary constraints
* if no boundary, do specify either by std::infinity or let vector.size() =
*0
**/
bool Add2dBoundary(const std::vector<double>& t_coord,
const std::vector<double>& angle,
const std::vector<apollo::common::math::Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound);
// ref point refer to derivative reference point
bool Add2dDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<apollo::common::math::Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound);
// ref point refer to second derivative ref point
bool Add2dSecondDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<apollo::common::math::Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound);
// ref point refer to third derivative ref point
bool Add2dThirdDerivativeBoundary(
const std::vector<double>& t_coord, const std::vector<double>& angle,
const std::vector<apollo::common::math::Vec2d>& ref_point,
const std::vector<double>& longitudinal_bound,
const std::vector<double>& lateral_bound);
bool AddPointConstraint(const double t, const double x, const double y);
bool AddPointSecondDerivativeConstraint(const double t, const double ddx,
const double ddy);
bool AddPointThirdDerivativeConstraint(const double t, const double dddx,
const double dddy);
bool AddPointAngleConstraint(const double t, const double angle);
// guarantee up to values are joint
bool AddSmoothConstraint();
// guarantee up to derivative are joint
bool AddDerivativeSmoothConstraint();
// guarantee up to second order derivative are joint
bool AddSecondDerivativeSmoothConstraint();
// guarantee up to third order derivative are joint
bool AddThirdDerivativeSmoothConstraint();
/**
* @brief: output interface inequality constraint
**/
const AffineConstraint& inequality_constraint() const;
const AffineConstraint& equality_constraint() const;
private:
uint32_t FindIndex(const double t) const;
std::vector<double> AffineCoef(const double angle, const double t) const;
std::vector<double> AffineDerivativeCoef(const double angle,
const double t) const;
std::vector<double> AffineSecondDerivativeCoef(const double angle,
const double t) const;
std::vector<double> AffineThirdDerivativeCoef(const double angle,
const double t) const;
std::vector<double> PolyCoef(const double t) const;
std::vector<double> DerivativeCoef(const double t) const;
std::vector<double> SecondDerivativeCoef(const double t) const;
std::vector<double> ThirdDerivativeCoef(const double t) const;
double SignDistance(const apollo::common::math::Vec2d& xy_point,
const double angle) const;
bool AddPointKthOrderDerivativeConstraint(
const double t, const double x_kth_derivative,
const double y_kth_derivative, const std::vector<double>& kth_coeff);
private:
AffineConstraint inequality_constraint_;
AffineConstraint equality_constraint_;
std::vector<double> t_knots_;
uint32_t spline_order_;
uint32_t total_param_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_solver.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_2d_solver.h
**/
#pragma once
#include <vector>
#include "modules/common/math/qp_solver/qp_solver.h"
#include "modules/planning/math/smoothing_spline/spline_2d.h"
#include "modules/planning/math/smoothing_spline/spline_2d_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_2d_kernel.h"
namespace apollo {
namespace planning {
class Spline2dSolver {
public:
Spline2dSolver(const std::vector<double>& t_knots, const uint32_t order)
: spline_(t_knots, order),
kernel_(t_knots, order),
constraint_(t_knots, order) {}
virtual ~Spline2dSolver() = default;
virtual void Reset(const std::vector<double>& t_knots,
const uint32_t order) = 0;
// customize setup
virtual Spline2dConstraint* mutable_constraint() = 0;
virtual Spline2dKernel* mutable_kernel() = 0;
virtual Spline2d* mutable_spline() = 0;
// solve
virtual bool Solve() = 0;
// extract
virtual const Spline2d& spline() const = 0;
protected:
Spline2d spline_;
Spline2dKernel kernel_;
Spline2dConstraint constraint_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/osqp_spline_2d_solver.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/smoothing_spline/osqp_spline_2d_solver.h"
#include "cyber/common/log.h"
#include "modules/common/math/matrix_operations.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
namespace {
constexpr double kRoadBound = 1e10;
}
using apollo::common::math::DenseToCSCMatrix;
using Eigen::MatrixXd;
OsqpSpline2dSolver::OsqpSpline2dSolver(const std::vector<double>& t_knots,
const uint32_t order)
: Spline2dSolver(t_knots, order) {}
void OsqpSpline2dSolver::Reset(const std::vector<double>& t_knots,
const uint32_t order) {
spline_ = Spline2d(t_knots, order);
kernel_ = Spline2dKernel(t_knots, order);
constraint_ = Spline2dConstraint(t_knots, order);
}
// customize setup
Spline2dConstraint* OsqpSpline2dSolver::mutable_constraint() {
return &constraint_;
}
Spline2dKernel* OsqpSpline2dSolver::mutable_kernel() { return &kernel_; }
Spline2d* OsqpSpline2dSolver::mutable_spline() { return &spline_; }
bool OsqpSpline2dSolver::Solve() {
// Namings here are following osqp convention.
// For details, visit: https://osqp.org/docs/examples/demo.html
// change P to csc format
const MatrixXd& P = kernel_.kernel_matrix();
ADEBUG << "P: " << P.rows() << ", " << P.cols();
if (P.rows() == 0) {
return false;
}
std::vector<c_float> P_data;
std::vector<c_int> P_indices;
std::vector<c_int> P_indptr;
DenseToCSCMatrix(P, &P_data, &P_indices, &P_indptr);
// change A to csc format
const MatrixXd& inequality_constraint_matrix =
constraint_.inequality_constraint().constraint_matrix();
const MatrixXd& equality_constraint_matrix =
constraint_.equality_constraint().constraint_matrix();
MatrixXd A(
inequality_constraint_matrix.rows() + equality_constraint_matrix.rows(),
inequality_constraint_matrix.cols());
A << inequality_constraint_matrix, equality_constraint_matrix;
ADEBUG << "A: " << A.rows() << ", " << A.cols();
if (A.rows() == 0) {
return false;
}
std::vector<c_float> A_data;
std::vector<c_int> A_indices;
std::vector<c_int> A_indptr;
DenseToCSCMatrix(A, &A_data, &A_indices, &A_indptr);
// set q, l, u: l < A < u
const MatrixXd& q_eigen = kernel_.offset();
c_float q[q_eigen.rows()]; // NOLINT
for (int i = 0; i < q_eigen.size(); ++i) {
q[i] = q_eigen(i);
}
const MatrixXd& inequality_constraint_boundary =
constraint_.inequality_constraint().constraint_boundary();
const MatrixXd& equality_constraint_boundary =
constraint_.equality_constraint().constraint_boundary();
auto constraint_num = inequality_constraint_boundary.rows() +
equality_constraint_boundary.rows();
static constexpr float kEpsilon = 1e-9f;
static constexpr float kUpperLimit = 1e9f;
c_float l[constraint_num]; // NOLINT
c_float u[constraint_num]; // NOLINT
for (int i = 0; i < constraint_num; ++i) {
if (i < inequality_constraint_boundary.rows()) {
l[i] = inequality_constraint_boundary(i, 0);
u[i] = kUpperLimit;
} else {
const auto idx = i - inequality_constraint_boundary.rows();
l[i] = equality_constraint_boundary(idx, 0) - kEpsilon;
u[i] = equality_constraint_boundary(idx, 0) + kEpsilon;
}
}
// Problem settings
OSQPSettings* settings =
reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings)));
// Populate data
OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
data->n = P.rows();
data->m = constraint_num;
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 = l;
data->u = u;
// Define Solver settings as default
osqp_set_default_settings(settings);
settings->alpha = 1.0; // Change alpha parameter
settings->eps_abs = 1.0e-05;
settings->eps_rel = 1.0e-05;
settings->max_iter = 5000;
settings->polish = true;
settings->verbose = FLAGS_enable_osqp_debug;
// Setup workspace
OSQPWorkspace* work = nullptr;
work = osqp_setup(data, settings);
// osqp_setup(&work, data, settings);
// Solve Problem
osqp_solve(work);
MatrixXd solved_params = MatrixXd::Zero(P.rows(), 1);
for (int i = 0; i < P.rows(); ++i) {
solved_params(i, 0) = work->solution->x[i];
}
last_num_param_ = static_cast<int>(P.rows());
last_num_constraint_ = static_cast<int>(constraint_num);
// Cleanup
osqp_cleanup(work);
c_free(data->A);
c_free(data->P);
c_free(data);
c_free(settings);
return spline_.set_splines(solved_params, spline_.spline_order());
}
// extract
const Spline2d& OsqpSpline2dSolver::spline() const { return spline_; }
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_constraint.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_constraint.h
* @brief: wrapp up solver constraint interface with direct methods and preset
*methods
**/
#pragma once
#include <algorithm>
#include <vector>
#include "Eigen/Core"
#include "modules/planning/math/smoothing_spline/affine_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_1d.h"
namespace apollo {
namespace planning {
class Spline1dConstraint {
public:
explicit Spline1dConstraint(const Spline1d& pss);
Spline1dConstraint(const std::vector<double>& x_knots, const uint32_t order);
// direct methods
bool AddInequalityConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary);
bool AddEqualityConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary);
// preset method
/**
* @brief: inequality boundary constraints
* if no boundary, do specify either by std::infinity or
* let vector.size() = 0
**/
bool AddBoundary(const std::vector<double>& x_coord,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound);
bool AddDerivativeBoundary(const std::vector<double>& x_coord,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound);
bool AddSecondDerivativeBoundary(const std::vector<double>& x_coord,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound);
bool AddThirdDerivativeBoundary(const std::vector<double>& x_coord,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound);
/**
* @brief: equality constraint to guarantee joint smoothness
* boundary equality constriant constraint on fx, dfx, ddfx ... in vector
* form; up to third order
**/
bool AddPointConstraint(const double x, const double fx);
bool AddPointDerivativeConstraint(const double x, const double dfx);
bool AddPointSecondDerivativeConstraint(const double x, const double ddfx);
bool AddPointThirdDerivativeConstraint(const double x, const double dddfx);
bool AddPointConstraintInRange(const double x, const double fx,
const double range);
bool AddPointDerivativeConstraintInRange(const double x, const double dfx,
const double range);
bool AddPointSecondDerivativeConstraintInRange(const double x,
const double ddfx,
const double range);
bool AddPointThirdDerivativeConstraintInRange(const double x,
const double dddfx,
const double range);
// guarantee up to values are joint
bool AddSmoothConstraint();
// guarantee up to derivative are joint
bool AddDerivativeSmoothConstraint();
// guarantee up to second order derivative are joint
bool AddSecondDerivativeSmoothConstraint();
// guarantee up to third order derivative are joint
bool AddThirdDerivativeSmoothConstraint();
/**
* @brief: Add monotone constraint inequality, guarantee the monotone city at
* evaluated point. customized monotone inequality constraint at x_coord
**/
bool AddMonotoneInequalityConstraint(const std::vector<double>& x_coord);
// default inequality constraint at knots
bool AddMonotoneInequalityConstraintAtKnots();
/**
* @brief: output interface inequality constraint
**/
const AffineConstraint& inequality_constraint() const;
const AffineConstraint& equality_constraint() const;
private:
uint32_t FindIndex(const double x) const;
bool 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);
void GeneratePowerX(const double x, const uint32_t order,
std::vector<double>* const power_x) const;
using AddConstraintInRangeFunc =
std::function<bool(const std::vector<double>&, const std::vector<double>&,
const std::vector<double>&)>;
bool AddConstraintInRange(AddConstraintInRangeFunc func, const double x,
const double val, const double range);
private:
AffineConstraint inequality_constraint_;
AffineConstraint equality_constraint_;
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_kernel.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_kernel.h
* @brief: wrap up solver constraint interface with direct methods and preset
*methods
**/
#pragma once
#include <vector>
#include "Eigen/Core"
#include "modules/planning/math/smoothing_spline/spline_1d.h"
namespace apollo {
namespace planning {
class Spline1dKernel {
public:
explicit Spline1dKernel(const Spline1d& spline1d);
Spline1dKernel(const std::vector<double>& x_knots,
const uint32_t spline_order);
// customized input / output method
void AddRegularization(const double regularized_param);
bool AddKernel(const Eigen::MatrixXd& kernel, const Eigen::MatrixXd& offset,
const double weight);
bool AddKernel(const Eigen::MatrixXd& kernel, const double weight);
Eigen::MatrixXd* mutable_kernel_matrix();
Eigen::MatrixXd* mutable_offset();
const Eigen::MatrixXd& kernel_matrix() const;
const Eigen::MatrixXd& offset() const;
// build-in kernel methods
void AddDerivativeKernelMatrix(const double weight);
void AddSecondOrderDerivativeMatrix(const double weight);
void AddThirdOrderDerivativeMatrix(const double weight);
void AddDerivativeKernelMatrixForSplineK(const uint32_t k,
const double weight);
void AddSecondOrderDerivativeMatrixForSplineK(const uint32_t k,
const double weight);
void AddThirdOrderDerivativeMatrixForSplineK(const uint32_t k,
const double weight);
// reference line kernel, x_coord in strictly increasing order (for path
// optimizer)
bool AddReferenceLineKernelMatrix(const std::vector<double>& x_coord,
const std::vector<double>& ref_fx,
const double weight);
// distance offset (for speed optimizer, given time optimize the distance can
// go)
void AddDistanceOffset(const double weight);
private:
void AddNthDerivativekernelMatrix(const uint32_t n, const double weight);
void AddNthDerivativekernelMatrixForSplineK(const uint32_t n,
const uint32_t k,
const double weight);
uint32_t FindIndex(const double x) const;
private:
Eigen::MatrixXd kernel_matrix_;
Eigen::MatrixXd offset_;
std::vector<double> x_knots_;
uint32_t spline_order_;
uint32_t total_params_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d.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_2d.h
* @brief: piecewise smoothing spline 2d class
**/
#pragma once
#include <utility>
#include <vector>
#include "Eigen/Core"
#include "modules/planning/math/polynomial_xd.h"
#include "modules/planning/math/smoothing_spline/spline_2d_seg.h"
namespace apollo {
namespace planning {
class Spline2d {
public:
Spline2d(const std::vector<double>& t_knots, const uint32_t order);
std::pair<double, double> operator()(const double t) const;
double x(const double t) const;
double y(const double t) const;
double DerivativeX(const double t) const;
double DerivativeY(const double t) const;
double SecondDerivativeX(const double t) const;
double SecondDerivativeY(const double t) const;
double ThirdDerivativeX(const double t) const;
double ThirdDerivativeY(const double t) const;
bool set_splines(const Eigen::MatrixXd& params, const uint32_t order);
const Spline2dSeg& smoothing_spline(const uint32_t index) const;
const std::vector<double>& t_knots() const;
uint32_t spline_order() const;
private:
uint32_t find_index(const double x) const;
private:
std::vector<Spline2dSeg> splines_;
std::vector<double> t_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/affine_constraint.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 : affine_constraint.h
**/
#pragma once
#include "Eigen/Core"
#include "modules/planning/math/polynomial_xd.h"
namespace apollo {
namespace planning {
class AffineConstraint {
public:
AffineConstraint() = default;
explicit AffineConstraint(const bool is_equality);
AffineConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary,
const bool is_equality);
void SetIsEquality(const double is_equality);
const Eigen::MatrixXd& constraint_matrix() const;
const Eigen::MatrixXd& constraint_boundary() const;
bool AddConstraint(const Eigen::MatrixXd& constraint_matrix,
const Eigen::MatrixXd& constraint_boundary);
private:
Eigen::MatrixXd constraint_matrix_;
Eigen::MatrixXd constraint_boundary_;
bool is_equality_ = true;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/math
|
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_seg_kernel.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_seg_kernel.cc
* @brief: generating spline kernels
**/
#include "modules/planning/math/smoothing_spline/spline_seg_kernel.h"
#include <vector>
namespace apollo {
namespace planning {
SplineSegKernel::SplineSegKernel() {
const int reserved_num_params = reserved_order_ + 1;
CalculateFx(reserved_num_params);
CalculateDerivative(reserved_num_params);
CalculateSecondOrderDerivative(reserved_num_params);
CalculateThirdOrderDerivative(reserved_num_params);
}
Eigen::MatrixXd SplineSegKernel::Kernel(const uint32_t num_params,
const double accumulated_x) {
if (num_params > reserved_order_ + 1) {
CalculateFx(num_params);
}
Eigen::MatrixXd term_matrix;
IntegratedTermMatrix(num_params, accumulated_x, "fx", &term_matrix);
return kernel_fx_.block(0, 0, num_params, num_params)
.cwiseProduct(term_matrix);
}
Eigen::MatrixXd SplineSegKernel::NthDerivativeKernel(
const uint32_t n, const uint32_t num_params, const double accumulated_x) {
if (n == 1) {
return DerivativeKernel(num_params, accumulated_x);
} else if (n == 2) {
return SecondOrderDerivativeKernel(num_params, accumulated_x);
} else if (n == 3) {
return ThirdOrderDerivativeKernel(num_params, accumulated_x);
} else {
return Eigen::MatrixXd::Zero(num_params, num_params);
}
}
Eigen::MatrixXd SplineSegKernel::DerivativeKernel(const uint32_t num_params,
const double accumulated_x) {
if (num_params > reserved_order_ + 1) {
CalculateDerivative(num_params);
}
Eigen::MatrixXd term_matrix;
IntegratedTermMatrix(num_params, accumulated_x, "derivative", &term_matrix);
return kernel_derivative_.block(0, 0, num_params, num_params)
.cwiseProduct(term_matrix);
}
Eigen::MatrixXd SplineSegKernel::SecondOrderDerivativeKernel(
const uint32_t num_params, const double accumulated_x) {
if (num_params > reserved_order_ + 1) {
CalculateSecondOrderDerivative(num_params);
}
Eigen::MatrixXd term_matrix;
IntegratedTermMatrix(num_params, accumulated_x, "second_order", &term_matrix);
return kernel_second_order_derivative_.block(0, 0, num_params, num_params)
.cwiseProduct(term_matrix);
}
Eigen::MatrixXd SplineSegKernel::ThirdOrderDerivativeKernel(
const uint32_t num_params, const double accumulated_x) {
if (num_params > reserved_order_ + 1) {
CalculateThirdOrderDerivative(num_params);
}
Eigen::MatrixXd term_matrix;
IntegratedTermMatrix(num_params, accumulated_x, "third_order", &term_matrix);
return (kernel_third_order_derivative_.block(0, 0, num_params, num_params))
.cwiseProduct(term_matrix);
}
void SplineSegKernel::IntegratedTermMatrix(const uint32_t num_params,
const double x,
const std::string& type,
Eigen::MatrixXd* term_matrix) const {
if (term_matrix->rows() != term_matrix->cols() ||
term_matrix->rows() != static_cast<int>(num_params)) {
term_matrix->resize(num_params, num_params);
}
std::vector<double> x_pow(2 * num_params + 1, 1.0);
for (uint32_t i = 1; i < 2 * num_params + 1; ++i) {
x_pow[i] = x_pow[i - 1] * x;
}
if (type == "fx") {
for (uint32_t r = 0; r < num_params; ++r) {
for (uint32_t c = 0; c < num_params; ++c) {
(*term_matrix)(r, c) = x_pow[r + c + 1];
}
}
} else if (type == "derivative") {
for (uint32_t r = 1; r < num_params; ++r) {
for (uint32_t c = 1; c < num_params; ++c) {
(*term_matrix)(r, c) = x_pow[r + c - 1];
}
}
(*term_matrix).block(0, 0, num_params, 1) =
Eigen::MatrixXd::Zero(num_params, 1);
(*term_matrix).block(0, 0, 1, num_params) =
Eigen::MatrixXd::Zero(1, num_params);
} else if (type == "second_order") {
for (uint32_t r = 2; r < num_params; ++r) {
for (uint32_t c = 2; c < num_params; ++c) {
(*term_matrix)(r, c) = x_pow[r + c - 3];
}
}
(*term_matrix).block(0, 0, num_params, 2) =
Eigen::MatrixXd::Zero(num_params, 2);
(*term_matrix).block(0, 0, 2, num_params) =
Eigen::MatrixXd::Zero(2, num_params);
} else {
for (uint32_t r = 3; r < num_params; ++r) {
for (uint32_t c = 3; c < num_params; ++c) {
(*term_matrix)(r, c) = x_pow[r + c - 5];
}
}
(*term_matrix).block(0, 0, num_params, 3) =
Eigen::MatrixXd::Zero(num_params, 3);
(*term_matrix).block(0, 0, 3, num_params) =
Eigen::MatrixXd::Zero(3, num_params);
}
}
void SplineSegKernel::CalculateFx(const uint32_t num_params) {
kernel_fx_ = Eigen::MatrixXd::Zero(num_params, num_params);
for (int r = 0; r < kernel_fx_.rows(); ++r) {
for (int c = 0; c < kernel_fx_.cols(); ++c) {
kernel_fx_(r, c) = 1.0 / (r + c + 1.0);
}
}
}
void SplineSegKernel::CalculateDerivative(const uint32_t num_params) {
kernel_derivative_ = Eigen::MatrixXd::Zero(num_params, num_params);
for (int r = 1; r < kernel_derivative_.rows(); ++r) {
for (int c = 1; c < kernel_derivative_.cols(); ++c) {
kernel_derivative_(r, c) = r * c / (r + c - 1.0);
}
}
}
void SplineSegKernel::CalculateSecondOrderDerivative(
const uint32_t num_params) {
kernel_second_order_derivative_ =
Eigen::MatrixXd::Zero(num_params, num_params);
for (int r = 2; r < kernel_second_order_derivative_.rows(); ++r) {
for (int c = 2; c < kernel_second_order_derivative_.cols(); ++c) {
kernel_second_order_derivative_(r, c) =
(r * r - r) * (c * c - c) / (r + c - 3.0);
}
}
}
void SplineSegKernel::CalculateThirdOrderDerivative(const uint32_t num_params) {
kernel_third_order_derivative_ =
Eigen::MatrixXd::Zero(num_params, num_params);
for (int r = 3; r < kernel_third_order_derivative_.rows(); ++r) {
for (int c = 3; c < kernel_third_order_derivative_.cols(); ++c) {
kernel_third_order_derivative_(r, c) =
(r * r - r) * (r - 2) * (c * c - c) * (c - 2) / (r + c - 5.0);
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/path_time_graph.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/behavior/path_time_graph.h"
#include <algorithm>
#include <limits>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/path_matcher.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/common_msgs/planning_msgs/sl_boundary.pb.h"
namespace apollo {
namespace planning {
using apollo::common::PathPoint;
using apollo::common::TrajectoryPoint;
using apollo::common::math::Box2d;
using apollo::common::math::lerp;
using apollo::common::math::PathMatcher;
using apollo::common::math::Polygon2d;
PathTimeGraph::PathTimeGraph(
const std::vector<const Obstacle*>& obstacles,
const std::vector<PathPoint>& discretized_ref_points,
const ReferenceLineInfo* ptr_reference_line_info, const double s_start,
const double s_end, const double t_start, const double t_end,
const std::array<double, 3>& init_d) {
CHECK_LT(s_start, s_end);
CHECK_LT(t_start, t_end);
path_range_.first = s_start;
path_range_.second = s_end;
time_range_.first = t_start;
time_range_.second = t_end;
ptr_reference_line_info_ = ptr_reference_line_info;
init_d_ = init_d;
SetupObstacles(obstacles, discretized_ref_points);
}
SLBoundary PathTimeGraph::ComputeObstacleBoundary(
const std::vector<common::math::Vec2d>& vertices,
const std::vector<PathPoint>& discretized_ref_points) const {
double start_s(std::numeric_limits<double>::max());
double end_s(std::numeric_limits<double>::lowest());
double start_l(std::numeric_limits<double>::max());
double end_l(std::numeric_limits<double>::lowest());
for (const auto& point : vertices) {
auto sl_point = PathMatcher::GetPathFrenetCoordinate(discretized_ref_points,
point.x(), point.y());
start_s = std::fmin(start_s, sl_point.first);
end_s = std::fmax(end_s, sl_point.first);
start_l = std::fmin(start_l, sl_point.second);
end_l = std::fmax(end_l, sl_point.second);
}
SLBoundary sl_boundary;
sl_boundary.set_start_s(start_s);
sl_boundary.set_end_s(end_s);
sl_boundary.set_start_l(start_l);
sl_boundary.set_end_l(end_l);
return sl_boundary;
}
void PathTimeGraph::SetupObstacles(
const std::vector<const Obstacle*>& obstacles,
const std::vector<PathPoint>& discretized_ref_points) {
for (const Obstacle* obstacle : obstacles) {
if (obstacle->IsVirtual()) {
continue;
}
if (!obstacle->HasTrajectory()) {
SetStaticObstacle(obstacle, discretized_ref_points);
} else {
SetDynamicObstacle(obstacle, discretized_ref_points);
}
}
std::sort(static_obs_sl_boundaries_.begin(), static_obs_sl_boundaries_.end(),
[](const SLBoundary& sl0, const SLBoundary& sl1) {
return sl0.start_s() < sl1.start_s();
});
for (auto& path_time_obstacle : path_time_obstacle_map_) {
path_time_obstacles_.push_back(path_time_obstacle.second);
}
}
void PathTimeGraph::SetStaticObstacle(
const Obstacle* obstacle,
const std::vector<PathPoint>& discretized_ref_points) {
const Polygon2d& polygon = obstacle->PerceptionPolygon();
std::string obstacle_id = obstacle->Id();
SLBoundary sl_boundary =
ComputeObstacleBoundary(polygon.GetAllVertices(), discretized_ref_points);
double left_width = FLAGS_default_reference_line_width * 0.5;
double right_width = FLAGS_default_reference_line_width * 0.5;
ptr_reference_line_info_->reference_line().GetLaneWidth(
sl_boundary.start_s(), &left_width, &right_width);
if (sl_boundary.start_s() > path_range_.second ||
sl_boundary.end_s() < path_range_.first ||
sl_boundary.start_l() > left_width ||
sl_boundary.end_l() < -right_width) {
ADEBUG << "Obstacle [" << obstacle_id << "] is out of range.";
return;
}
path_time_obstacle_map_[obstacle_id].set_id(obstacle_id);
path_time_obstacle_map_[obstacle_id].set_bottom_left_point(
SetPathTimePoint(obstacle_id, sl_boundary.start_s(), 0.0));
path_time_obstacle_map_[obstacle_id].set_bottom_right_point(SetPathTimePoint(
obstacle_id, sl_boundary.start_s(), FLAGS_trajectory_time_length));
path_time_obstacle_map_[obstacle_id].set_upper_left_point(
SetPathTimePoint(obstacle_id, sl_boundary.end_s(), 0.0));
path_time_obstacle_map_[obstacle_id].set_upper_right_point(SetPathTimePoint(
obstacle_id, sl_boundary.end_s(), FLAGS_trajectory_time_length));
static_obs_sl_boundaries_.push_back(std::move(sl_boundary));
ADEBUG << "ST-Graph mapping static obstacle: " << obstacle_id
<< ", start_s : " << sl_boundary.start_s()
<< ", end_s : " << sl_boundary.end_s()
<< ", start_l : " << sl_boundary.start_l()
<< ", end_l : " << sl_boundary.end_l();
}
void PathTimeGraph::SetDynamicObstacle(
const Obstacle* obstacle,
const std::vector<PathPoint>& discretized_ref_points) {
double relative_time = time_range_.first;
while (relative_time < time_range_.second) {
TrajectoryPoint point = obstacle->GetPointAtTime(relative_time);
Box2d box = obstacle->GetBoundingBox(point);
SLBoundary sl_boundary =
ComputeObstacleBoundary(box.GetAllCorners(), discretized_ref_points);
double left_width = FLAGS_default_reference_line_width * 0.5;
double right_width = FLAGS_default_reference_line_width * 0.5;
ptr_reference_line_info_->reference_line().GetLaneWidth(
sl_boundary.start_s(), &left_width, &right_width);
// The obstacle is not shown on the region to be considered.
if (sl_boundary.start_s() > path_range_.second ||
sl_boundary.end_s() < path_range_.first ||
sl_boundary.start_l() > left_width ||
sl_boundary.end_l() < -right_width) {
if (path_time_obstacle_map_.find(obstacle->Id()) !=
path_time_obstacle_map_.end()) {
break;
}
relative_time += FLAGS_trajectory_time_resolution;
continue;
}
if (path_time_obstacle_map_.find(obstacle->Id()) ==
path_time_obstacle_map_.end()) {
path_time_obstacle_map_[obstacle->Id()].set_id(obstacle->Id());
path_time_obstacle_map_[obstacle->Id()].set_bottom_left_point(
SetPathTimePoint(obstacle->Id(), sl_boundary.start_s(),
relative_time));
path_time_obstacle_map_[obstacle->Id()].set_upper_left_point(
SetPathTimePoint(obstacle->Id(), sl_boundary.end_s(), relative_time));
}
path_time_obstacle_map_[obstacle->Id()].set_bottom_right_point(
SetPathTimePoint(obstacle->Id(), sl_boundary.start_s(), relative_time));
path_time_obstacle_map_[obstacle->Id()].set_upper_right_point(
SetPathTimePoint(obstacle->Id(), sl_boundary.end_s(), relative_time));
relative_time += FLAGS_trajectory_time_resolution;
}
}
STPoint PathTimeGraph::SetPathTimePoint(const std::string& obstacle_id,
const double s, const double t) const {
STPoint path_time_point(s, t);
return path_time_point;
}
const std::vector<STBoundary>& PathTimeGraph::GetPathTimeObstacles() const {
return path_time_obstacles_;
}
bool PathTimeGraph::GetPathTimeObstacle(const std::string& obstacle_id,
STBoundary* path_time_obstacle) {
if (path_time_obstacle_map_.find(obstacle_id) ==
path_time_obstacle_map_.end()) {
return false;
}
*path_time_obstacle = path_time_obstacle_map_[obstacle_id];
return true;
}
std::vector<std::pair<double, double>> PathTimeGraph::GetPathBlockingIntervals(
const double t) const {
ACHECK(time_range_.first <= t && t <= time_range_.second);
std::vector<std::pair<double, double>> intervals;
for (const auto& pt_obstacle : path_time_obstacles_) {
if (t > pt_obstacle.max_t() || t < pt_obstacle.min_t()) {
continue;
}
double s_upper = lerp(pt_obstacle.upper_left_point().s(),
pt_obstacle.upper_left_point().t(),
pt_obstacle.upper_right_point().s(),
pt_obstacle.upper_right_point().t(), t);
double s_lower = lerp(pt_obstacle.bottom_left_point().s(),
pt_obstacle.bottom_left_point().t(),
pt_obstacle.bottom_right_point().s(),
pt_obstacle.bottom_right_point().t(), t);
intervals.emplace_back(s_lower, s_upper);
}
return intervals;
}
std::vector<std::vector<std::pair<double, double>>>
PathTimeGraph::GetPathBlockingIntervals(const double t_start,
const double t_end,
const double t_resolution) {
std::vector<std::vector<std::pair<double, double>>> intervals;
for (double t = t_start; t <= t_end; t += t_resolution) {
intervals.push_back(GetPathBlockingIntervals(t));
}
return intervals;
}
std::pair<double, double> PathTimeGraph::get_path_range() const {
return path_range_;
}
std::pair<double, double> PathTimeGraph::get_time_range() const {
return time_range_;
}
std::vector<STPoint> PathTimeGraph::GetObstacleSurroundingPoints(
const std::string& obstacle_id, const double s_dist,
const double t_min_density) const {
ACHECK(t_min_density > 0.0);
std::vector<STPoint> pt_pairs;
if (path_time_obstacle_map_.find(obstacle_id) ==
path_time_obstacle_map_.end()) {
return pt_pairs;
}
const auto& pt_obstacle = path_time_obstacle_map_.at(obstacle_id);
double s0 = 0.0;
double s1 = 0.0;
double t0 = 0.0;
double t1 = 0.0;
if (s_dist > 0.0) {
s0 = pt_obstacle.upper_left_point().s();
s1 = pt_obstacle.upper_right_point().s();
t0 = pt_obstacle.upper_left_point().t();
t1 = pt_obstacle.upper_right_point().t();
} else {
s0 = pt_obstacle.bottom_left_point().s();
s1 = pt_obstacle.bottom_right_point().s();
t0 = pt_obstacle.bottom_left_point().t();
t1 = pt_obstacle.bottom_right_point().t();
}
double time_gap = t1 - t0;
ACHECK(time_gap > -FLAGS_numerical_epsilon);
time_gap = std::fabs(time_gap);
size_t num_sections = static_cast<size_t>(time_gap / t_min_density + 1);
double t_interval = time_gap / static_cast<double>(num_sections);
for (size_t i = 0; i <= num_sections; ++i) {
double t = t_interval * static_cast<double>(i) + t0;
double s = lerp(s0, t0, s1, t1, t) + s_dist;
STPoint ptt;
ptt.set_t(t);
ptt.set_s(s);
pt_pairs.push_back(std::move(ptt));
}
return pt_pairs;
}
bool PathTimeGraph::IsObstacleInGraph(const std::string& obstacle_id) {
return path_time_obstacle_map_.find(obstacle_id) !=
path_time_obstacle_map_.end();
}
std::vector<std::pair<double, double>> PathTimeGraph::GetLateralBounds(
const double s_start, const double s_end, const double s_resolution) {
CHECK_LT(s_start, s_end);
CHECK_GT(s_resolution, FLAGS_numerical_epsilon);
std::vector<std::pair<double, double>> bounds;
std::vector<double> discretized_path;
double s_range = s_end - s_start;
double s_curr = s_start;
size_t num_bound = static_cast<size_t>(s_range / s_resolution);
const auto& vehicle_config =
common::VehicleConfigHelper::Instance()->GetConfig();
double ego_width = vehicle_config.vehicle_param().width();
// Initialize bounds by reference line width
for (size_t i = 0; i < num_bound; ++i) {
double left_width = FLAGS_default_reference_line_width / 2.0;
double right_width = FLAGS_default_reference_line_width / 2.0;
ptr_reference_line_info_->reference_line().GetLaneWidth(s_curr, &left_width,
&right_width);
double ego_d_lower = init_d_[0] - ego_width / 2.0;
double ego_d_upper = init_d_[0] + ego_width / 2.0;
bounds.emplace_back(
std::min(-right_width, ego_d_lower - FLAGS_bound_buffer),
std::max(left_width, ego_d_upper + FLAGS_bound_buffer));
discretized_path.push_back(s_curr);
s_curr += s_resolution;
}
for (const SLBoundary& static_sl_boundary : static_obs_sl_boundaries_) {
UpdateLateralBoundsByObstacle(static_sl_boundary, discretized_path, s_start,
s_end, &bounds);
}
for (size_t i = 0; i < bounds.size(); ++i) {
bounds[i].first += ego_width / 2.0;
bounds[i].second -= ego_width / 2.0;
if (bounds[i].first >= bounds[i].second) {
bounds[i].first = 0.0;
bounds[i].second = 0.0;
}
}
return bounds;
}
void PathTimeGraph::UpdateLateralBoundsByObstacle(
const SLBoundary& sl_boundary, const std::vector<double>& discretized_path,
const double s_start, const double s_end,
std::vector<std::pair<double, double>>* const bounds) {
if (sl_boundary.start_s() > s_end || sl_boundary.end_s() < s_start) {
return;
}
auto start_iter = std::lower_bound(
discretized_path.begin(), discretized_path.end(), sl_boundary.start_s());
auto end_iter = std::upper_bound(
discretized_path.begin(), discretized_path.end(), sl_boundary.start_s());
size_t start_index = start_iter - discretized_path.begin();
size_t end_index = end_iter - discretized_path.begin();
if (sl_boundary.end_l() > -FLAGS_numerical_epsilon &&
sl_boundary.start_l() < FLAGS_numerical_epsilon) {
for (size_t i = start_index; i < end_index; ++i) {
bounds->operator[](i).first = -FLAGS_numerical_epsilon;
bounds->operator[](i).second = FLAGS_numerical_epsilon;
}
return;
}
if (sl_boundary.end_l() < FLAGS_numerical_epsilon) {
for (size_t i = start_index; i < std::min(end_index + 1, bounds->size());
++i) {
bounds->operator[](i).first =
std::max(bounds->operator[](i).first,
sl_boundary.end_l() + FLAGS_nudge_buffer);
}
return;
}
if (sl_boundary.start_l() > -FLAGS_numerical_epsilon) {
for (size_t i = start_index; i < std::min(end_index + 1, bounds->size());
++i) {
bounds->operator[](i).second =
std::min(bounds->operator[](i).second,
sl_boundary.start_l() - FLAGS_nudge_buffer);
}
return;
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/path_time_graph.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "modules/common/math/polygon2d.h"
#include "modules/common_msgs/basic_msgs/geometry.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/obstacle.h"
#include "modules/planning/common/reference_line_info.h"
#include "modules/planning/common/speed/st_boundary.h"
#include "modules/planning/common/speed/st_point.h"
#include "modules/planning/reference_line/reference_line.h"
namespace apollo {
namespace planning {
class PathTimeGraph {
public:
PathTimeGraph(const std::vector<const Obstacle*>& obstacles,
const std::vector<common::PathPoint>& discretized_ref_points,
const ReferenceLineInfo* ptr_reference_line_info,
const double s_start, const double s_end, const double t_start,
const double t_end, const std::array<double, 3>& init_d);
const std::vector<STBoundary>& GetPathTimeObstacles() const;
bool GetPathTimeObstacle(const std::string& obstacle_id,
STBoundary* path_time_obstacle);
std::vector<std::pair<double, double>> GetPathBlockingIntervals(
const double t) const;
std::vector<std::vector<std::pair<double, double>>> GetPathBlockingIntervals(
const double t_start, const double t_end, const double t_resolution);
std::pair<double, double> get_path_range() const;
std::pair<double, double> get_time_range() const;
std::vector<STPoint> GetObstacleSurroundingPoints(
const std::string& obstacle_id, const double s_dist,
const double t_density) const;
bool IsObstacleInGraph(const std::string& obstacle_id);
std::vector<std::pair<double, double>> GetLateralBounds(
const double s_start, const double s_end, const double s_resolution);
private:
void SetupObstacles(
const std::vector<const Obstacle*>& obstacles,
const std::vector<common::PathPoint>& discretized_ref_points);
SLBoundary ComputeObstacleBoundary(
const std::vector<common::math::Vec2d>& vertices,
const std::vector<common::PathPoint>& discretized_ref_points) const;
STPoint SetPathTimePoint(const std::string& obstacle_id, const double s,
const double t) const;
void SetStaticObstacle(
const Obstacle* obstacle,
const std::vector<common::PathPoint>& discretized_ref_points);
void SetDynamicObstacle(
const Obstacle* obstacle,
const std::vector<common::PathPoint>& discretized_ref_points);
void UpdateLateralBoundsByObstacle(
const SLBoundary& sl_boundary,
const std::vector<double>& discretized_path, const double s_start,
const double s_end, std::vector<std::pair<double, double>>* const bounds);
private:
std::pair<double, double> time_range_;
std::pair<double, double> path_range_;
const ReferenceLineInfo* ptr_reference_line_info_;
std::array<double, 3> init_d_;
std::unordered_map<std::string, STBoundary> path_time_obstacle_map_;
std::vector<STBoundary> path_time_obstacles_;
std::vector<SLBoundary> static_obs_sl_boundaries_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/feasible_region.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 "modules/common_msgs/basic_msgs/pnc_point.pb.h"
namespace apollo {
namespace planning {
class FeasibleRegion {
public:
explicit FeasibleRegion(const std::array<double, 3>& init_s);
double SUpper(const double t) const;
double SLower(const double t) const;
double VUpper(const double t) const;
double VLower(const double t) const;
double TLower(const double s) const;
private:
std::array<double, 3> init_s_;
double t_at_zero_speed_;
double s_at_zero_speed_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/prediction_querier.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "modules/planning/common/obstacle.h"
namespace apollo {
namespace planning {
class PredictionQuerier {
public:
PredictionQuerier(const std::vector<const Obstacle*>& obstacles,
const std::shared_ptr<std::vector<common::PathPoint>>&
ptr_reference_line);
virtual ~PredictionQuerier() = default;
std::vector<const Obstacle*> GetObstacles() const;
double ProjectVelocityAlongReferenceLine(const std::string& obstacle_id,
const double s,
const double t) const;
private:
std::unordered_map<std::string, const Obstacle*> id_obstacle_map_;
std::vector<const Obstacle*> obstacles_;
std::shared_ptr<std::vector<common::PathPoint>> ptr_reference_line_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/prediction_querier.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/lattice/behavior/prediction_querier.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/path_matcher.h"
namespace apollo {
namespace planning {
PredictionQuerier::PredictionQuerier(
const std::vector<const Obstacle*>& obstacles,
const std::shared_ptr<std::vector<common::PathPoint>>& ptr_reference_line)
: ptr_reference_line_(ptr_reference_line) {
for (const auto ptr_obstacle : obstacles) {
if (common::util::InsertIfNotPresent(&id_obstacle_map_, ptr_obstacle->Id(),
ptr_obstacle)) {
obstacles_.push_back(ptr_obstacle);
} else {
AWARN << "Duplicated obstacle found [" << ptr_obstacle->Id() << "]";
}
}
}
std::vector<const Obstacle*> PredictionQuerier::GetObstacles() const {
return obstacles_;
}
double PredictionQuerier::ProjectVelocityAlongReferenceLine(
const std::string& obstacle_id, const double s, const double t) const {
ACHECK(id_obstacle_map_.find(obstacle_id) != id_obstacle_map_.end());
const auto& trajectory = id_obstacle_map_.at(obstacle_id)->Trajectory();
int num_traj_point = trajectory.trajectory_point_size();
if (num_traj_point < 2) {
return 0.0;
}
if (t < trajectory.trajectory_point(0).relative_time() ||
t > trajectory.trajectory_point(num_traj_point - 1).relative_time()) {
return 0.0;
}
auto matched_it =
std::lower_bound(trajectory.trajectory_point().begin(),
trajectory.trajectory_point().end(), t,
[](const common::TrajectoryPoint& p, const double t) {
return p.relative_time() < t;
});
double v = matched_it->v();
double theta = matched_it->path_point().theta();
double v_x = v * std::cos(theta);
double v_y = v * std::sin(theta);
common::PathPoint obstacle_point_on_ref_line =
common::math::PathMatcher::MatchToPath(*ptr_reference_line_, s);
auto ref_theta = obstacle_point_on_ref_line.theta();
return std::cos(ref_theta) * v_x + std::sin(ref_theta) * v_y;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""]
cc_library(
name = "feasible_region",
srcs = ["feasible_region.cc"],
hdrs = ["feasible_region.h"],
copts = PLANNING_COPTS,
deps = [
"//cyber",
"//modules/common_msgs/basic_msgs:pnc_point_cc_proto",
"//modules/planning/common:planning_gflags",
],
)
cc_library(
name = "path_time_graph",
srcs = ["path_time_graph.cc"],
hdrs = ["path_time_graph.h"],
copts = PLANNING_COPTS,
deps = [
"//cyber",
"//modules/common/math",
"//modules/common_msgs/basic_msgs:pnc_point_cc_proto",
"//modules/planning/common:frame",
"//modules/planning/common:obstacle",
"//modules/planning/common:planning_gflags",
"//modules/planning/proto:lattice_structure_cc_proto",
"//modules/planning/reference_line",
],
)
cc_library(
name = "prediction_querier",
srcs = ["prediction_querier.cc"],
hdrs = ["prediction_querier.h"],
copts = PLANNING_COPTS,
deps = [
"//modules/common/math",
"//modules/planning/common:obstacle",
"//modules/planning/proto:lattice_structure_cc_proto",
"//modules/common_msgs/planning_msgs:planning_cc_proto",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/behavior/feasible_region.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/lattice/behavior/feasible_region.h"
#include <cmath>
#include "cyber/common/log.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
FeasibleRegion::FeasibleRegion(const std::array<double, 3>& init_s) {
init_s_ = init_s;
double v = init_s[1];
CHECK_GE(v, 0.0);
const double max_deceleration = -FLAGS_longitudinal_acceleration_lower_bound;
t_at_zero_speed_ = v / max_deceleration;
s_at_zero_speed_ = init_s[0] + v * v / (2.0 * max_deceleration);
}
double FeasibleRegion::SUpper(const double t) const {
ACHECK(t >= 0.0);
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_upper_bound * t * t;
}
double FeasibleRegion::SLower(const double t) const {
if (t < t_at_zero_speed_) {
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_lower_bound * t * t;
}
return s_at_zero_speed_;
}
double FeasibleRegion::VUpper(const double t) const {
return init_s_[1] + FLAGS_longitudinal_acceleration_upper_bound * t;
}
double FeasibleRegion::VLower(const double t) const {
return t < t_at_zero_speed_
? init_s_[1] + FLAGS_longitudinal_acceleration_lower_bound * t
: 0.0;
}
double FeasibleRegion::TLower(const double s) const {
ACHECK(s >= init_s_[0]);
double delta_s = s - init_s_[0];
double v = init_s_[1];
double a = FLAGS_longitudinal_acceleration_upper_bound;
double t = (std::sqrt(v * v + 2.0 * a * delta_s) - v) / a;
return t;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lateral_osqp_optimizer.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/lattice/trajectory_generation/lateral_osqp_optimizer.h"
#include "cyber/common/log.h"
#include "modules/common/math/matrix_operations.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
bool LateralOSQPOptimizer::optimize(
const std::array<double, 3>& d_state, const double delta_s,
const std::vector<std::pair<double, double>>& d_bounds) {
std::vector<c_float> P_data;
std::vector<c_int> P_indices;
std::vector<c_int> P_indptr;
CalculateKernel(d_bounds, &P_data, &P_indices, &P_indptr);
delta_s_ = delta_s;
const int num_var = static_cast<int>(d_bounds.size());
const int kNumParam = 3 * static_cast<int>(d_bounds.size());
const int kNumConstraint = kNumParam + 3 * (num_var - 1) + 3;
c_float lower_bounds[kNumConstraint];
c_float upper_bounds[kNumConstraint];
const int prime_offset = num_var;
const int pprime_offset = 2 * num_var;
std::vector<std::vector<std::pair<c_int, c_float>>> columns;
columns.resize(kNumParam);
int constraint_index = 0;
// d_i+1'' - d_i''
for (int i = 0; i + 1 < num_var; ++i) {
columns[pprime_offset + i].emplace_back(constraint_index, -1.0);
columns[pprime_offset + i + 1].emplace_back(constraint_index, 1.0);
lower_bounds[constraint_index] =
-FLAGS_lateral_third_order_derivative_max * delta_s_;
upper_bounds[constraint_index] =
FLAGS_lateral_third_order_derivative_max * delta_s_;
++constraint_index;
}
// d_i+1' - d_i' - 0.5 * ds * (d_i'' + d_i+1'')
for (int i = 0; i + 1 < num_var; ++i) {
columns[prime_offset + i].emplace_back(constraint_index, -1.0);
columns[prime_offset + i + 1].emplace_back(constraint_index, 1.0);
columns[pprime_offset + i].emplace_back(constraint_index, -0.5 * delta_s_);
columns[pprime_offset + i + 1].emplace_back(constraint_index,
-0.5 * delta_s_);
lower_bounds[constraint_index] = 0.0;
upper_bounds[constraint_index] = 0.0;
++constraint_index;
}
// d_i+1 - d_i - d_i' * ds - 1/3 * d_i'' * ds^2 - 1/6 * d_i+1'' * ds^2
for (int i = 0; i + 1 < num_var; ++i) {
columns[i].emplace_back(constraint_index, -1.0);
columns[i + 1].emplace_back(constraint_index, 1.0);
columns[prime_offset + i].emplace_back(constraint_index, -delta_s_);
columns[pprime_offset + i].emplace_back(constraint_index,
-delta_s_ * delta_s_ / 3.0);
columns[pprime_offset + i + 1].emplace_back(constraint_index,
-delta_s_ * delta_s_ / 6.0);
lower_bounds[constraint_index] = 0.0;
upper_bounds[constraint_index] = 0.0;
++constraint_index;
}
columns[0].emplace_back(constraint_index, 1.0);
lower_bounds[constraint_index] = d_state[0];
upper_bounds[constraint_index] = d_state[0];
++constraint_index;
columns[prime_offset].emplace_back(constraint_index, 1.0);
lower_bounds[constraint_index] = d_state[1];
upper_bounds[constraint_index] = d_state[1];
++constraint_index;
columns[pprime_offset].emplace_back(constraint_index, 1.0);
lower_bounds[constraint_index] = d_state[2];
upper_bounds[constraint_index] = d_state[2];
++constraint_index;
const double LARGE_VALUE = 2.0;
for (int i = 0; i < kNumParam; ++i) {
columns[i].emplace_back(constraint_index, 1.0);
if (i < num_var) {
lower_bounds[constraint_index] = d_bounds[i].first;
upper_bounds[constraint_index] = d_bounds[i].second;
} else {
lower_bounds[constraint_index] = -LARGE_VALUE;
upper_bounds[constraint_index] = LARGE_VALUE;
}
++constraint_index;
}
CHECK_EQ(constraint_index, kNumConstraint);
// change affine_constraint to CSC format
std::vector<c_float> A_data;
std::vector<c_int> A_indices;
std::vector<c_int> A_indptr;
int ind_p = 0;
for (int j = 0; j < kNumParam; ++j) {
A_indptr.push_back(ind_p);
for (const auto& row_data_pair : columns[j]) {
A_data.push_back(row_data_pair.second);
A_indices.push_back(row_data_pair.first);
++ind_p;
}
}
A_indptr.push_back(ind_p);
// offset
double q[kNumParam];
for (int i = 0; i < kNumParam; ++i) {
if (i < num_var) {
q[i] = -2.0 * FLAGS_weight_lateral_obstacle_distance *
(d_bounds[i].first + d_bounds[i].second);
} else {
q[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 = 1.0; // Change alpha parameter
settings->eps_abs = 1.0e-05;
settings->eps_rel = 1.0e-05;
settings->max_iter = 5000;
settings->polish = true;
settings->verbose = FLAGS_enable_osqp_debug;
// Populate data
OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
data->n = kNumParam;
data->m = kNumConstraint;
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 = lower_bounds;
data->u = upper_bounds;
// Workspace
OSQPWorkspace* work = nullptr;
// osqp_setup(&work, data, settings);
work = osqp_setup(data, settings);
// Solve Problem
osqp_solve(work);
// extract primal results
for (int i = 0; i < num_var; ++i) {
opt_d_.push_back(work->solution->x[i]);
opt_d_prime_.push_back(work->solution->x[i + num_var]);
opt_d_pprime_.push_back(work->solution->x[i + 2 * num_var]);
}
opt_d_prime_[num_var - 1] = 0.0;
opt_d_pprime_[num_var - 1] = 0.0;
// Cleanup
osqp_cleanup(work);
c_free(data->A);
c_free(data->P);
c_free(data);
c_free(settings);
return true;
}
void LateralOSQPOptimizer::CalculateKernel(
const std::vector<std::pair<double, double>>& d_bounds,
std::vector<c_float>* P_data, std::vector<c_int>* P_indices,
std::vector<c_int>* P_indptr) {
const int kNumParam = 3 * static_cast<int>(d_bounds.size());
P_data->resize(kNumParam);
P_indices->resize(kNumParam);
P_indptr->resize(kNumParam + 1);
for (int i = 0; i < kNumParam; ++i) {
if (i < static_cast<int>(d_bounds.size())) {
P_data->at(i) = 2.0 * FLAGS_weight_lateral_offset +
2.0 * FLAGS_weight_lateral_obstacle_distance;
} else if (i < 2 * static_cast<int>(d_bounds.size())) {
P_data->at(i) = 2.0 * FLAGS_weight_lateral_derivative;
} else {
P_data->at(i) = 2.0 * FLAGS_weight_lateral_second_order_derivative;
}
P_indices->at(i) = i;
P_indptr->at(i) = i;
}
P_indptr->at(kNumParam) = kNumParam;
CHECK_EQ(P_data->size(), P_indices->size());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory1d_generator.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/lattice/trajectory_generation/trajectory1d_generator.h"
#include "cyber/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/trajectory1d/constant_deceleration_trajectory1d.h"
#include "modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.h"
#include "modules/planning/common/trajectory1d/standing_still_trajectory1d.h"
#include "modules/planning/lattice/trajectory_generation/lateral_osqp_optimizer.h"
#include "modules/planning/lattice/trajectory_generation/lateral_qp_optimizer.h"
namespace apollo {
namespace planning {
// A common function for trajectory bundles generation with
// a given initial state and end conditions.
typedef std::array<double, 3> State;
typedef std::pair<State, double> Condition;
typedef std::vector<std::shared_ptr<Curve1d>> Trajectory1DBundle;
Trajectory1dGenerator::Trajectory1dGenerator(
const State& lon_init_state, const State& lat_init_state,
std::shared_ptr<PathTimeGraph> ptr_path_time_graph,
std::shared_ptr<PredictionQuerier> ptr_prediction_querier)
: init_lon_state_(lon_init_state),
init_lat_state_(lat_init_state),
end_condition_sampler_(lon_init_state, lat_init_state,
ptr_path_time_graph, ptr_prediction_querier),
ptr_path_time_graph_(ptr_path_time_graph) {}
void Trajectory1dGenerator::GenerateTrajectoryBundles(
const PlanningTarget& planning_target,
Trajectory1DBundle* ptr_lon_trajectory_bundle,
Trajectory1DBundle* ptr_lat_trajectory_bundle) {
GenerateLongitudinalTrajectoryBundle(planning_target,
ptr_lon_trajectory_bundle);
GenerateLateralTrajectoryBundle(ptr_lat_trajectory_bundle);
}
void Trajectory1dGenerator::GenerateSpeedProfilesForCruising(
const double target_speed,
Trajectory1DBundle* ptr_lon_trajectory_bundle) const {
ADEBUG << "cruise speed is " << target_speed;
auto end_conditions =
end_condition_sampler_.SampleLonEndConditionsForCruising(target_speed);
if (end_conditions.empty()) {
return;
}
// For the cruising case, We use the "QuarticPolynomialCurve1d" class (not the
// "QuinticPolynomialCurve1d" class) to generate curves. Therefore, we can't
// invoke the common function to generate trajectory bundles.
GenerateTrajectory1DBundle<4>(init_lon_state_, end_conditions,
ptr_lon_trajectory_bundle);
}
void Trajectory1dGenerator::GenerateSpeedProfilesForStopping(
const double stop_point,
Trajectory1DBundle* ptr_lon_trajectory_bundle) const {
ADEBUG << "stop point is " << stop_point;
auto end_conditions =
end_condition_sampler_.SampleLonEndConditionsForStopping(stop_point);
if (end_conditions.empty()) {
return;
}
// Use the common function to generate trajectory bundles.
GenerateTrajectory1DBundle<5>(init_lon_state_, end_conditions,
ptr_lon_trajectory_bundle);
}
void Trajectory1dGenerator::GenerateSpeedProfilesForPathTimeObstacles(
Trajectory1DBundle* ptr_lon_trajectory_bundle) const {
auto end_conditions =
end_condition_sampler_.SampleLonEndConditionsForPathTimePoints();
if (end_conditions.empty()) {
return;
}
// Use the common function to generate trajectory bundles.
GenerateTrajectory1DBundle<5>(init_lon_state_, end_conditions,
ptr_lon_trajectory_bundle);
}
void Trajectory1dGenerator::GenerateLongitudinalTrajectoryBundle(
const PlanningTarget& planning_target,
Trajectory1DBundle* ptr_lon_trajectory_bundle) const {
// cruising trajectories are planned regardlessly.
GenerateSpeedProfilesForCruising(planning_target.cruise_speed(),
ptr_lon_trajectory_bundle);
GenerateSpeedProfilesForPathTimeObstacles(ptr_lon_trajectory_bundle);
if (planning_target.has_stop_point()) {
GenerateSpeedProfilesForStopping(planning_target.stop_point().s(),
ptr_lon_trajectory_bundle);
}
}
void Trajectory1dGenerator::GenerateLateralTrajectoryBundle(
Trajectory1DBundle* ptr_lat_trajectory_bundle) const {
if (!FLAGS_lateral_optimization) {
auto end_conditions = end_condition_sampler_.SampleLatEndConditions();
// Use the common function to generate trajectory bundles.
GenerateTrajectory1DBundle<5>(init_lat_state_, end_conditions,
ptr_lat_trajectory_bundle);
} else {
double s_min = init_lon_state_[0];
double s_max = s_min + FLAGS_max_s_lateral_optimization;
double delta_s = FLAGS_default_delta_s_lateral_optimization;
auto lateral_bounds =
ptr_path_time_graph_->GetLateralBounds(s_min, s_max, delta_s);
// LateralTrajectoryOptimizer lateral_optimizer;
std::unique_ptr<LateralQPOptimizer> lateral_optimizer(
new LateralOSQPOptimizer);
lateral_optimizer->optimize(init_lat_state_, delta_s, lateral_bounds);
auto lateral_trajectory = lateral_optimizer->GetOptimalTrajectory();
ptr_lat_trajectory_bundle->push_back(
std::make_shared<PiecewiseJerkTrajectory1d>(lateral_trajectory));
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory_combiner.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/lattice/trajectory_generation/trajectory_combiner.h"
#include <algorithm>
#include "modules/common/math/cartesian_frenet_conversion.h"
#include "modules/common/math/path_matcher.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::PathPoint;
using apollo::common::TrajectoryPoint;
using apollo::common::math::CartesianFrenetConverter;
using apollo::common::math::PathMatcher;
DiscretizedTrajectory TrajectoryCombiner::Combine(
const std::vector<PathPoint>& reference_line, const Curve1d& lon_trajectory,
const Curve1d& lat_trajectory, const double init_relative_time) {
DiscretizedTrajectory combined_trajectory;
double s0 = lon_trajectory.Evaluate(0, 0.0);
double s_ref_max = reference_line.back().s();
double accumulated_trajectory_s = 0.0;
PathPoint prev_trajectory_point;
double last_s = -FLAGS_numerical_epsilon;
double t_param = 0.0;
while (t_param < FLAGS_trajectory_time_length) {
// linear extrapolation is handled internally in LatticeTrajectory1d;
// no worry about t_param > lon_trajectory.ParamLength() situation
double s = lon_trajectory.Evaluate(0, t_param);
if (last_s > 0.0) {
s = std::max(last_s, s);
}
last_s = s;
double s_dot =
std::max(FLAGS_numerical_epsilon, lon_trajectory.Evaluate(1, t_param));
double s_ddot = lon_trajectory.Evaluate(2, t_param);
if (s > s_ref_max) {
break;
}
double relative_s = s - s0;
// linear extrapolation is handled internally in LatticeTrajectory1d;
// no worry about s_param > lat_trajectory.ParamLength() situation
double d = lat_trajectory.Evaluate(0, relative_s);
double d_prime = lat_trajectory.Evaluate(1, relative_s);
double d_pprime = lat_trajectory.Evaluate(2, relative_s);
PathPoint matched_ref_point = PathMatcher::MatchToPath(reference_line, s);
double x = 0.0;
double y = 0.0;
double theta = 0.0;
double kappa = 0.0;
double v = 0.0;
double a = 0.0;
const double rs = matched_ref_point.s();
const double rx = matched_ref_point.x();
const double ry = matched_ref_point.y();
const double rtheta = matched_ref_point.theta();
const double rkappa = matched_ref_point.kappa();
const double rdkappa = matched_ref_point.dkappa();
std::array<double, 3> s_conditions = {rs, s_dot, s_ddot};
std::array<double, 3> d_conditions = {d, d_prime, d_pprime};
CartesianFrenetConverter::frenet_to_cartesian(
rs, rx, ry, rtheta, rkappa, rdkappa, s_conditions, d_conditions, &x, &y,
&theta, &kappa, &v, &a);
if (prev_trajectory_point.has_x() && prev_trajectory_point.has_y()) {
double delta_x = x - prev_trajectory_point.x();
double delta_y = y - prev_trajectory_point.y();
double delta_s = std::hypot(delta_x, delta_y);
accumulated_trajectory_s += delta_s;
}
TrajectoryPoint trajectory_point;
trajectory_point.mutable_path_point()->set_x(x);
trajectory_point.mutable_path_point()->set_y(y);
trajectory_point.mutable_path_point()->set_s(accumulated_trajectory_s);
trajectory_point.mutable_path_point()->set_theta(theta);
trajectory_point.mutable_path_point()->set_kappa(kappa);
trajectory_point.set_v(v);
trajectory_point.set_a(a);
trajectory_point.set_relative_time(t_param + init_relative_time);
combined_trajectory.AppendTrajectoryPoint(trajectory_point);
t_param = t_param + FLAGS_trajectory_time_resolution;
prev_trajectory_point = trajectory_point.path_point();
}
return combined_trajectory;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lateral_qp_optimizer.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/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.h"
namespace apollo {
namespace planning {
class LateralQPOptimizer {
public:
LateralQPOptimizer() = default;
virtual ~LateralQPOptimizer() = default;
virtual bool optimize(
const std::array<double, 3>& d_state, const double delta_s,
const std::vector<std::pair<double, double>>& d_bounds) = 0;
virtual PiecewiseJerkTrajectory1d GetOptimalTrajectory() const;
virtual std::vector<common::FrenetFramePoint> GetFrenetFramePath() const;
protected:
double delta_s_ = FLAGS_default_delta_s_lateral_optimization;
std::vector<double> opt_d_;
std::vector<double> opt_d_prime_;
std::vector<double> opt_d_pprime_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lateral_qp_optimizer.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/lattice/trajectory_generation/lateral_qp_optimizer.h"
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
PiecewiseJerkTrajectory1d LateralQPOptimizer::GetOptimalTrajectory() const {
ACHECK(!opt_d_.empty() && !opt_d_prime_.empty() && !opt_d_pprime_.empty());
PiecewiseJerkTrajectory1d optimal_trajectory(
opt_d_.front(), opt_d_prime_.front(), opt_d_pprime_.front());
for (size_t i = 1; i < opt_d_.size(); ++i) {
double j = (opt_d_pprime_[i] - opt_d_pprime_[i - 1]) / delta_s_;
optimal_trajectory.AppendSegment(j, delta_s_);
}
return optimal_trajectory;
}
std::vector<common::FrenetFramePoint> LateralQPOptimizer::GetFrenetFramePath()
const {
std::vector<common::FrenetFramePoint> frenet_frame_path;
double accumulated_s = 0.0;
for (size_t i = 0; i < opt_d_.size(); ++i) {
common::FrenetFramePoint frenet_frame_point;
frenet_frame_point.set_s(accumulated_s);
frenet_frame_point.set_l(opt_d_[i]);
frenet_frame_point.set_dl(opt_d_prime_[i]);
frenet_frame_point.set_ddl(opt_d_pprime_[i]);
frenet_frame_path.push_back(std::move(frenet_frame_point));
accumulated_s += delta_s_;
}
return frenet_frame_path;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lateral_osqp_optimizer.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/common/trajectory1d/piecewise_jerk_trajectory1d.h"
#include "modules/planning/lattice/trajectory_generation/lateral_qp_optimizer.h"
#include "osqp/osqp.h"
namespace apollo {
namespace planning {
class LateralOSQPOptimizer : public LateralQPOptimizer {
public:
LateralOSQPOptimizer() = default;
virtual ~LateralOSQPOptimizer() = default;
bool optimize(
const std::array<double, 3>& d_state, const double delta_s,
const std::vector<std::pair<double, double>>& d_bounds) override;
private:
void CalculateKernel(const std::vector<std::pair<double, double>>& d_bounds,
std::vector<c_float>* P_data,
std::vector<c_int>* P_indices,
std::vector<c_int>* P_indptr);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory1d_generator.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <memory>
#include <utility>
#include <vector>
#include "modules/planning/lattice/behavior/path_time_graph.h"
#include "modules/planning/lattice/behavior/prediction_querier.h"
#include "modules/planning/lattice/trajectory_generation/end_condition_sampler.h"
#include "modules/planning/lattice/trajectory_generation/lattice_trajectory1d.h"
#include "modules/planning/math/curve1d/curve1d.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h"
#include "modules/planning/proto/lattice_structure.pb.h"
namespace apollo {
namespace planning {
class Trajectory1dGenerator {
public:
Trajectory1dGenerator(
const std::array<double, 3>& lon_init_state,
const std::array<double, 3>& lat_init_state,
std::shared_ptr<PathTimeGraph> ptr_path_time_graph,
std::shared_ptr<PredictionQuerier> ptr_prediction_querier);
virtual ~Trajectory1dGenerator() = default;
void GenerateTrajectoryBundles(
const PlanningTarget& planning_target,
std::vector<std::shared_ptr<Curve1d>>* ptr_lon_trajectory_bundle,
std::vector<std::shared_ptr<Curve1d>>* ptr_lat_trajectory_bundle);
void GenerateLateralTrajectoryBundle(
std::vector<std::shared_ptr<Curve1d>>* ptr_lat_trajectory_bundle) const;
private:
void GenerateSpeedProfilesForCruising(
const double target_speed,
std::vector<std::shared_ptr<Curve1d>>* ptr_lon_trajectory_bundle) const;
void GenerateSpeedProfilesForStopping(
const double stop_point,
std::vector<std::shared_ptr<Curve1d>>* ptr_lon_trajectory_bundle) const;
void GenerateSpeedProfilesForPathTimeObstacles(
std::vector<std::shared_ptr<Curve1d>>* ptr_lon_trajectory_bundle) const;
void GenerateLongitudinalTrajectoryBundle(
const PlanningTarget& planning_target,
std::vector<std::shared_ptr<Curve1d>>* ptr_lon_trajectory_bundle) const;
template <size_t N>
void GenerateTrajectory1DBundle(
const std::array<double, 3>& init_state,
const std::vector<std::pair<std::array<double, 3>, double>>&
end_conditions,
std::vector<std::shared_ptr<Curve1d>>* ptr_trajectory_bundle) const;
private:
std::array<double, 3> init_lon_state_;
std::array<double, 3> init_lat_state_;
EndConditionSampler end_condition_sampler_;
std::shared_ptr<PathTimeGraph> ptr_path_time_graph_;
};
template <>
inline void Trajectory1dGenerator::GenerateTrajectory1DBundle<4>(
const std::array<double, 3>& init_state,
const std::vector<std::pair<std::array<double, 3>, double>>& end_conditions,
std::vector<std::shared_ptr<Curve1d>>* ptr_trajectory_bundle) const {
CHECK_NOTNULL(ptr_trajectory_bundle);
ACHECK(!end_conditions.empty());
ptr_trajectory_bundle->reserve(ptr_trajectory_bundle->size() +
end_conditions.size());
for (const auto& end_condition : end_conditions) {
auto ptr_trajectory1d = std::make_shared<LatticeTrajectory1d>(
std::shared_ptr<Curve1d>(new QuarticPolynomialCurve1d(
init_state, {end_condition.first[1], end_condition.first[2]},
end_condition.second)));
ptr_trajectory1d->set_target_velocity(end_condition.first[1]);
ptr_trajectory1d->set_target_time(end_condition.second);
ptr_trajectory_bundle->push_back(ptr_trajectory1d);
}
}
template <>
inline void Trajectory1dGenerator::GenerateTrajectory1DBundle<5>(
const std::array<double, 3>& init_state,
const std::vector<std::pair<std::array<double, 3>, double>>& end_conditions,
std::vector<std::shared_ptr<Curve1d>>* ptr_trajectory_bundle) const {
CHECK_NOTNULL(ptr_trajectory_bundle);
ACHECK(!end_conditions.empty());
ptr_trajectory_bundle->reserve(ptr_trajectory_bundle->size() +
end_conditions.size());
for (const auto& end_condition : end_conditions) {
auto ptr_trajectory1d = std::make_shared<LatticeTrajectory1d>(
std::shared_ptr<Curve1d>(new QuinticPolynomialCurve1d(
init_state, end_condition.first, end_condition.second)));
ptr_trajectory1d->set_target_position(end_condition.first[0]);
ptr_trajectory1d->set_target_velocity(end_condition.first[1]);
ptr_trajectory1d->set_target_time(end_condition.second);
ptr_trajectory_bundle->push_back(ptr_trajectory1d);
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory_evaluator.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/lattice/trajectory_generation/trajectory_evaluator.h"
#include <algorithm>
#include <limits>
#include "cyber/common/log.h"
#include "modules/common/math/path_matcher.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/trajectory1d/piecewise_acceleration_trajectory1d.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
#include "modules/planning/lattice/trajectory_generation/piecewise_braking_trajectory_generator.h"
namespace apollo {
namespace planning {
using apollo::common::PathPoint;
using apollo::common::SpeedPoint;
using apollo::common::math::PathMatcher;
using Trajectory1d = Curve1d;
using PtrTrajectory1d = std::shared_ptr<Trajectory1d>;
using Trajectory1dPair =
std::pair<std::shared_ptr<Curve1d>, std::shared_ptr<Curve1d>>;
TrajectoryEvaluator::TrajectoryEvaluator(
const std::array<double, 3>& init_s, const PlanningTarget& planning_target,
const std::vector<PtrTrajectory1d>& lon_trajectories,
const std::vector<PtrTrajectory1d>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph,
std::shared_ptr<std::vector<PathPoint>> reference_line)
: path_time_graph_(path_time_graph),
reference_line_(reference_line),
init_s_(init_s) {
const double start_time = 0.0;
const double end_time = FLAGS_trajectory_time_length;
path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
reference_s_dot_ = ComputeLongitudinalGuideVelocity(planning_target);
// if we have a stop point along the reference line,
// filter out the lon. trajectories that pass the stop point.
double stop_point = std::numeric_limits<double>::max();
if (planning_target.has_stop_point()) {
stop_point = planning_target.stop_point().s();
}
for (const auto& lon_trajectory : lon_trajectories) {
double lon_end_s = lon_trajectory->Evaluate(0, end_time);
if (init_s[0] < stop_point &&
lon_end_s + FLAGS_lattice_stop_buffer > stop_point) {
continue;
}
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto& lat_trajectory : lat_trajectories) {
/**
* The validity of the code needs to be verified.
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
*/
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
cost_queue_.emplace(Trajectory1dPair(lon_trajectory, lat_trajectory),
cost);
}
}
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
return !cost_queue_.empty();
}
size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
return cost_queue_.size();
}
std::pair<PtrTrajectory1d, PtrTrajectory1d>
TrajectoryEvaluator::next_top_trajectory_pair() {
ACHECK(has_more_trajectory_pairs());
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
return cost_queue_.top().second;
}
double TrajectoryEvaluator::Evaluate(
const PlanningTarget& planning_target,
const PtrTrajectory1d& lon_trajectory,
const PtrTrajectory1d& lat_trajectory,
std::vector<double>* cost_components) const {
// Costs:
// 1. Cost of missing the objective, e.g., cruise, stop, etc.
// 2. Cost of longitudinal jerk
// 3. Cost of longitudinal collision
// 4. Cost of lateral offsets
// 5. Cost of lateral comfort
// Longitudinal costs
double lon_objective_cost =
LonObjectiveCost(lon_trajectory, planning_target, reference_s_dot_);
double lon_jerk_cost = LonComfortCost(lon_trajectory);
double lon_collision_cost = LonCollisionCost(lon_trajectory);
double centripetal_acc_cost = CentripetalAccelerationCost(lon_trajectory);
// decides the longitudinal evaluation horizon for lateral trajectories.
double evaluation_horizon =
std::min(FLAGS_speed_lon_decision_horizon,
lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
std::vector<double> s_values;
for (double s = 0.0; s < evaluation_horizon;
s += FLAGS_trajectory_space_resolution) {
s_values.emplace_back(s);
}
// Lateral costs
double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);
double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);
if (cost_components != nullptr) {
cost_components->emplace_back(lon_objective_cost);
cost_components->emplace_back(lon_jerk_cost);
cost_components->emplace_back(lon_collision_cost);
cost_components->emplace_back(lat_offset_cost);
}
return lon_objective_cost * FLAGS_weight_lon_objective +
lon_jerk_cost * FLAGS_weight_lon_jerk +
lon_collision_cost * FLAGS_weight_lon_collision +
centripetal_acc_cost * FLAGS_weight_centripetal_acceleration +
lat_offset_cost * FLAGS_weight_lat_offset +
lat_comfort_cost * FLAGS_weight_lat_comfort;
}
double TrajectoryEvaluator::LatOffsetCost(
const PtrTrajectory1d& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / FLAGS_lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
cost_abs_sum += std::fabs(cost) * FLAGS_weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
cost_abs_sum += std::fabs(cost) * FLAGS_weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_numerical_epsilon);
}
double TrajectoryEvaluator::LatComfortCost(
const PtrTrajectory1d& lon_trajectory,
const PtrTrajectory1d& lat_trajectory) const {
double max_cost = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double s_dot = lon_trajectory->Evaluate(1, t);
double s_dotdot = lon_trajectory->Evaluate(2, t);
double relative_s = s - init_s_[0];
double l_prime = lat_trajectory->Evaluate(1, relative_s);
double l_primeprime = lat_trajectory->Evaluate(2, relative_s);
double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot;
max_cost = std::max(max_cost, std::fabs(cost));
}
return max_cost;
}
double TrajectoryEvaluator::LonComfortCost(
const PtrTrajectory1d& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::fabs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_numerical_epsilon);
}
double TrajectoryEvaluator::LonObjectiveCost(
const PtrTrajectory1d& lon_trajectory,
const PlanningTarget& planning_target,
const std::vector<double>& ref_s_dots) const {
double t_max = lon_trajectory->ParamLength();
double dist_s =
lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_weight_sum = 0.0;
for (size_t i = 0; i < ref_s_dots.size(); ++i) {
double t = static_cast<double>(i) * FLAGS_trajectory_time_resolution;
double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += t * t * std::fabs(cost);
speed_cost_weight_sum += t * t;
}
double speed_cost =
speed_cost_sqr_sum / (speed_cost_weight_sum + FLAGS_numerical_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (speed_cost * FLAGS_weight_target_speed +
dist_travelled_cost * FLAGS_weight_dist_travelled) /
(FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}
// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
const PtrTrajectory1d& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (size_t i = 0; i < path_time_intervals_.size(); ++i) {
const auto& pt_interval = path_time_intervals_[i];
if (pt_interval.empty()) {
continue;
}
double t = static_cast<double>(i) * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
double sigma = FLAGS_lon_collision_cost_std;
for (const auto& m : pt_interval) {
double dist = 0.0;
if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
} else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
}
double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
cost_sqr_sum += cost * cost;
cost_abs_sum += cost;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_numerical_epsilon);
}
double TrajectoryEvaluator::CentripetalAccelerationCost(
const PtrTrajectory1d& lon_trajectory) const {
// Assumes the vehicle is not obviously deviate from the reference line.
double centripetal_acc_sum = 0.0;
double centripetal_acc_sqr_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double v = lon_trajectory->Evaluate(1, t);
PathPoint ref_point = PathMatcher::MatchToPath(*reference_line_, s);
ACHECK(ref_point.has_kappa());
double centripetal_acc = v * v * ref_point.kappa();
centripetal_acc_sum += std::fabs(centripetal_acc);
centripetal_acc_sqr_sum += centripetal_acc * centripetal_acc;
}
return centripetal_acc_sqr_sum /
(centripetal_acc_sum + FLAGS_numerical_epsilon);
}
std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity(
const PlanningTarget& planning_target) const {
std::vector<double> reference_s_dot;
double cruise_v = planning_target.cruise_speed();
if (!planning_target.has_stop_point()) {
PiecewiseAccelerationTrajectory1d lon_traj(init_s_[0], cruise_v);
lon_traj.AppendSegment(
0.0, FLAGS_trajectory_time_length + FLAGS_numerical_epsilon);
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
reference_s_dot.emplace_back(lon_traj.Evaluate(1, t));
}
} else {
double dist_s = planning_target.stop_point().s() - init_s_[0];
if (dist_s < FLAGS_numerical_epsilon) {
PiecewiseAccelerationTrajectory1d lon_traj(init_s_[0], 0.0);
lon_traj.AppendSegment(
0.0, FLAGS_trajectory_time_length + FLAGS_numerical_epsilon);
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
reference_s_dot.emplace_back(lon_traj.Evaluate(1, t));
}
return reference_s_dot;
}
double a_comfort = FLAGS_longitudinal_acceleration_upper_bound *
FLAGS_comfort_acceleration_factor;
double d_comfort = -FLAGS_longitudinal_acceleration_lower_bound *
FLAGS_comfort_acceleration_factor;
std::shared_ptr<Trajectory1d> lon_ref_trajectory =
PiecewiseBrakingTrajectoryGenerator::Generate(
planning_target.stop_point().s(), init_s_[0],
planning_target.cruise_speed(), init_s_[1], a_comfort, d_comfort,
FLAGS_trajectory_time_length + FLAGS_numerical_epsilon);
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
reference_s_dot.emplace_back(lon_ref_trajectory->Evaluate(1, t));
}
}
return reference_s_dot;
}
bool TrajectoryEvaluator::InterpolateDenseStPoints(
const std::vector<SpeedPoint>& st_points, double t, double* traj_s) const {
CHECK_GT(st_points.size(), 1U);
if (t < st_points[0].t() || t > st_points[st_points.size() - 1].t()) {
AERROR << "AutoTuning InterpolateDenseStPoints Error";
return false;
}
for (uint i = 1; i < st_points.size(); ++i) {
if (t <= st_points[i].t()) {
*traj_s = st_points[i].t();
return true;
}
}
return false;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory_evaluator.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 <functional>
#include <memory>
#include <queue>
#include <utility>
#include <vector>
#include "modules/planning/lattice/behavior/path_time_graph.h"
#include "modules/planning/math/curve1d/curve1d.h"
#include "modules/planning/proto/lattice_structure.pb.h"
#include "modules/planning/proto/planning_config.pb.h"
namespace apollo {
namespace planning {
class TrajectoryEvaluator {
// normal use
typedef std::pair<
std::pair<std::shared_ptr<Curve1d>, std::shared_ptr<Curve1d>>, double>
PairCost;
// auto tuning
typedef std::pair<
std::pair<std::shared_ptr<Curve1d>, std::shared_ptr<Curve1d>>,
std::pair<std::vector<double>, double>>
PairCostWithComponents;
public:
TrajectoryEvaluator(
const std::array<double, 3>& init_s,
const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Curve1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Curve1d>>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph,
std::shared_ptr<std::vector<apollo::common::PathPoint>> reference_line);
virtual ~TrajectoryEvaluator() = default;
bool has_more_trajectory_pairs() const;
size_t num_of_trajectory_pairs() const;
std::pair<std::shared_ptr<Curve1d>, std::shared_ptr<Curve1d>>
next_top_trajectory_pair();
double top_trajectory_pair_cost() const;
std::vector<double> top_trajectory_pair_component_cost() const;
private:
double Evaluate(const PlanningTarget& planning_target,
const std::shared_ptr<Curve1d>& lon_trajectory,
const std::shared_ptr<Curve1d>& lat_trajectory,
std::vector<double>* cost_components = nullptr) const;
double LatOffsetCost(const std::shared_ptr<Curve1d>& lat_trajectory,
const std::vector<double>& s_values) const;
double LatComfortCost(const std::shared_ptr<Curve1d>& lon_trajectory,
const std::shared_ptr<Curve1d>& lat_trajectory) const;
double LonComfortCost(const std::shared_ptr<Curve1d>& lon_trajectory) const;
double LonCollisionCost(const std::shared_ptr<Curve1d>& lon_trajectory) const;
double LonObjectiveCost(const std::shared_ptr<Curve1d>& lon_trajectory,
const PlanningTarget& planning_target,
const std::vector<double>& ref_s_dot) const;
double CentripetalAccelerationCost(
const std::shared_ptr<Curve1d>& lon_trajectory) const;
std::vector<double> ComputeLongitudinalGuideVelocity(
const PlanningTarget& planning_target) const;
bool InterpolateDenseStPoints(
const std::vector<apollo::common::SpeedPoint>& st_points, double t,
double* traj_s) const;
struct CostComparator
: public std::binary_function<const PairCost&, const PairCost&, bool> {
bool operator()(const PairCost& left, const PairCost& right) const {
return left.second > right.second;
}
};
std::priority_queue<PairCost, std::vector<PairCost>, CostComparator>
cost_queue_;
std::shared_ptr<PathTimeGraph> path_time_graph_;
std::shared_ptr<std::vector<apollo::common::PathPoint>> reference_line_;
std::vector<std::vector<std::pair<double, double>>> path_time_intervals_;
std::array<double, 3> init_s_;
std::vector<double> reference_s_dot_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lattice_trajectory1d.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <memory>
#include <string>
#include "modules/planning/math/curve1d/curve1d.h"
namespace apollo {
namespace planning {
class LatticeTrajectory1d : public Curve1d {
public:
explicit LatticeTrajectory1d(std::shared_ptr<Curve1d> ptr_trajectory1d);
virtual ~LatticeTrajectory1d() = default;
virtual double Evaluate(const std::uint32_t order, const double param) const;
virtual double ParamLength() const;
virtual std::string ToString() const;
bool has_target_position() const;
bool has_target_velocity() const;
bool has_target_time() const;
double target_position() const;
double target_velocity() const;
double target_time() const;
void set_target_position(double target_position);
void set_target_velocity(double target_velocity);
void set_target_time(double target_time);
private:
std::shared_ptr<Curve1d> ptr_trajectory1d_;
double target_position_ = 0.0;
double target_velocity_ = 0.0;
double target_time_ = 0.0;
bool has_target_position_ = false;
bool has_target_velocity_ = false;
bool has_target_time_ = false;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/backup_trajectory_generator.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/lattice/trajectory_generation/backup_trajectory_generator.h"
#include "modules/planning/lattice/trajectory_generation/trajectory_combiner.h"
namespace apollo {
namespace planning {
using apollo::common::PathPoint;
using State = std::array<double, 3>;
BackupTrajectoryGenerator::BackupTrajectoryGenerator(
const State& init_s, const State& init_d, const double init_relative_time,
const std::shared_ptr<CollisionChecker>& ptr_collision_checker,
const Trajectory1dGenerator* trajectory1d_generator)
: init_relative_time_(init_relative_time),
ptr_collision_checker_(ptr_collision_checker),
ptr_trajectory1d_generator_(trajectory1d_generator) {
GenerateTrajectory1dPairs(init_s, init_d);
}
void BackupTrajectoryGenerator::GenerateTrajectory1dPairs(const State& init_s,
const State& init_d) {
std::vector<std::shared_ptr<Curve1d>> lon_trajectories;
std::array<double, 5> dds_condidates = {-0.1, -1.0, -2.0, -3.0, -4.0};
for (const auto dds : dds_condidates) {
lon_trajectories.emplace_back(
new ConstantDecelerationTrajectory1d(init_s[0], init_s[1], dds));
}
std::vector<std::shared_ptr<Curve1d>> lat_trajectories;
ptr_trajectory1d_generator_->GenerateLateralTrajectoryBundle(
&lat_trajectories);
for (auto& lon : lon_trajectories) {
for (auto& lat : lat_trajectories) {
trajectory_pair_pqueue_.emplace(lon, lat);
}
}
}
DiscretizedTrajectory BackupTrajectoryGenerator::GenerateTrajectory(
const std::vector<PathPoint>& discretized_ref_points) {
while (trajectory_pair_pqueue_.size() > 1) {
auto top_pair = trajectory_pair_pqueue_.top();
trajectory_pair_pqueue_.pop();
DiscretizedTrajectory trajectory =
TrajectoryCombiner::Combine(discretized_ref_points, *top_pair.first,
*top_pair.second, init_relative_time_);
if (!ptr_collision_checker_->InCollision(trajectory)) {
return trajectory;
}
}
auto top_pair = trajectory_pair_pqueue_.top();
return TrajectoryCombiner::Combine(discretized_ref_points, *top_pair.first,
*top_pair.second, init_relative_time_);
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/piecewise_braking_trajectory_generator.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <memory>
#include "modules/planning/common/trajectory1d/piecewise_acceleration_trajectory1d.h"
namespace apollo {
namespace planning {
class PiecewiseBrakingTrajectoryGenerator {
public:
PiecewiseBrakingTrajectoryGenerator() = delete;
static std::shared_ptr<Curve1d> Generate(
const double s_target, const double s_curr, const double v_target,
const double v_curr, const double a_comfort, const double d_comfort,
const double max_time);
static double ComputeStopDistance(const double v, const double dec);
static double ComputeStopDeceleration(const double dist, const double v);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/lattice_trajectory1d.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/lattice_trajectory1d.h"
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
LatticeTrajectory1d::LatticeTrajectory1d(
std::shared_ptr<Curve1d> ptr_trajectory1d) {
ptr_trajectory1d_ = ptr_trajectory1d;
}
double LatticeTrajectory1d::Evaluate(const std::uint32_t order,
const double param) const {
double param_length = ptr_trajectory1d_->ParamLength();
if (param < param_length) {
return ptr_trajectory1d_->Evaluate(order, param);
}
// do constant acceleration extrapolation;
// to align all the trajectories with time.
double p = ptr_trajectory1d_->Evaluate(0, param_length);
double v = ptr_trajectory1d_->Evaluate(1, param_length);
double a = ptr_trajectory1d_->Evaluate(2, param_length);
double t = param - param_length;
switch (order) {
case 0:
return p + v * t + 0.5 * a * t * t;
case 1:
return v + a * t;
case 2:
return a;
default:
return 0.0;
}
}
double LatticeTrajectory1d::ParamLength() const {
return ptr_trajectory1d_->ParamLength();
}
std::string LatticeTrajectory1d::ToString() const {
return ptr_trajectory1d_->ToString();
}
bool LatticeTrajectory1d::has_target_position() const {
return has_target_position_;
}
bool LatticeTrajectory1d::has_target_velocity() const {
return has_target_velocity_;
}
bool LatticeTrajectory1d::has_target_time() const { return has_target_time_; }
double LatticeTrajectory1d::target_position() const {
ACHECK(has_target_position_);
return target_position_;
}
double LatticeTrajectory1d::target_velocity() const {
ACHECK(has_target_velocity_);
return target_velocity_;
}
double LatticeTrajectory1d::target_time() const {
ACHECK(has_target_time_);
return target_time_;
}
void LatticeTrajectory1d::set_target_position(double target_position) {
target_position_ = target_position;
has_target_position_ = true;
}
void LatticeTrajectory1d::set_target_velocity(double target_velocity) {
target_velocity_ = target_velocity;
has_target_velocity_ = true;
}
void LatticeTrajectory1d::set_target_time(double target_time) {
target_time_ = target_time;
has_target_time_ = true;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/end_condition_sampler.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/lattice/trajectory_generation/end_condition_sampler.h"
#include <algorithm>
#include "cyber/common/log.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using State = std::array<double, 3>;
using Condition = std::pair<State, double>;
EndConditionSampler::EndConditionSampler(
const State& init_s, const State& init_d,
std::shared_ptr<PathTimeGraph> ptr_path_time_graph,
std::shared_ptr<PredictionQuerier> ptr_prediction_querier)
: init_s_(init_s),
init_d_(init_d),
feasible_region_(init_s),
ptr_path_time_graph_(std::move(ptr_path_time_graph)),
ptr_prediction_querier_(std::move(ptr_prediction_querier)) {}
std::vector<Condition> EndConditionSampler::SampleLatEndConditions() const {
std::vector<Condition> end_d_conditions;
std::array<double, 3> end_d_candidates = {0.0, -0.5, 0.5};
std::array<double, 4> end_s_candidates = {10.0, 20.0, 40.0, 80.0};
for (const auto& s : end_s_candidates) {
for (const auto& d : end_d_candidates) {
State end_d_state = {d, 0.0, 0.0};
end_d_conditions.emplace_back(end_d_state, s);
}
}
return end_d_conditions;
}
std::vector<Condition> EndConditionSampler::SampleLonEndConditionsForCruising(
const double ref_cruise_speed) const {
CHECK_GT(FLAGS_num_velocity_sample, 1U);
// time interval is one second plus the last one 0.01
static constexpr size_t num_of_time_samples = 9;
std::array<double, num_of_time_samples> time_samples;
for (size_t i = 1; i < num_of_time_samples; ++i) {
auto ratio =
static_cast<double>(i) / static_cast<double>(num_of_time_samples - 1);
time_samples[i] = FLAGS_trajectory_time_length * ratio;
}
time_samples[0] = FLAGS_polynomial_minimal_param;
std::vector<Condition> end_s_conditions;
for (const auto& time : time_samples) {
double v_upper = std::min(feasible_region_.VUpper(time), ref_cruise_speed);
double v_lower = feasible_region_.VLower(time);
State lower_end_s = {0.0, v_lower, 0.0};
end_s_conditions.emplace_back(lower_end_s, time);
State upper_end_s = {0.0, v_upper, 0.0};
end_s_conditions.emplace_back(upper_end_s, time);
double v_range = v_upper - v_lower;
// Number of sample velocities
size_t num_of_mid_points =
std::min(static_cast<size_t>(FLAGS_num_velocity_sample - 2),
static_cast<size_t>(v_range / FLAGS_min_velocity_sample_gap));
if (num_of_mid_points > 0) {
double velocity_seg =
v_range / static_cast<double>(num_of_mid_points + 1);
for (size_t i = 1; i <= num_of_mid_points; ++i) {
State end_s = {0.0, v_lower + velocity_seg * static_cast<double>(i),
0.0};
end_s_conditions.emplace_back(end_s, time);
}
}
}
return end_s_conditions;
}
std::vector<Condition> EndConditionSampler::SampleLonEndConditionsForStopping(
const double ref_stop_point) const {
// time interval is one second plus the last one 0.01
static constexpr size_t num_of_time_samples = 9;
std::array<double, num_of_time_samples> time_samples;
for (size_t i = 1; i < num_of_time_samples; ++i) {
auto ratio =
static_cast<double>(i) / static_cast<double>(num_of_time_samples - 1);
time_samples[i] = FLAGS_trajectory_time_length * ratio;
}
time_samples[0] = FLAGS_polynomial_minimal_param;
std::vector<Condition> end_s_conditions;
for (const auto& time : time_samples) {
State end_s = {std::max(init_s_[0], ref_stop_point), 0.0, 0.0};
end_s_conditions.emplace_back(end_s, time);
}
return end_s_conditions;
}
std::vector<Condition>
EndConditionSampler::SampleLonEndConditionsForPathTimePoints() const {
std::vector<Condition> end_s_conditions;
std::vector<SamplePoint> sample_points = QueryPathTimeObstacleSamplePoints();
for (const SamplePoint& sample_point : sample_points) {
if (sample_point.path_time_point.t() < FLAGS_polynomial_minimal_param) {
continue;
}
double s = sample_point.path_time_point.s();
double v = sample_point.ref_v;
double t = sample_point.path_time_point.t();
if (s > feasible_region_.SUpper(t) || s < feasible_region_.SLower(t)) {
continue;
}
State end_state = {s, v, 0.0};
end_s_conditions.emplace_back(end_state, t);
}
return end_s_conditions;
}
std::vector<SamplePoint>
EndConditionSampler::QueryPathTimeObstacleSamplePoints() const {
const auto& vehicle_config =
common::VehicleConfigHelper::Instance()->GetConfig();
std::vector<SamplePoint> sample_points;
for (const auto& path_time_obstacle :
ptr_path_time_graph_->GetPathTimeObstacles()) {
std::string obstacle_id = path_time_obstacle.id();
QueryFollowPathTimePoints(vehicle_config, obstacle_id, &sample_points);
QueryOvertakePathTimePoints(vehicle_config, obstacle_id, &sample_points);
}
return sample_points;
}
void EndConditionSampler::QueryFollowPathTimePoints(
const common::VehicleConfig& vehicle_config, const std::string& obstacle_id,
std::vector<SamplePoint>* const sample_points) const {
std::vector<STPoint> follow_path_time_points =
ptr_path_time_graph_->GetObstacleSurroundingPoints(
obstacle_id, -FLAGS_numerical_epsilon, FLAGS_time_min_density);
for (const auto& path_time_point : follow_path_time_points) {
double v = ptr_prediction_querier_->ProjectVelocityAlongReferenceLine(
obstacle_id, path_time_point.s(), path_time_point.t());
// Generate candidate s
double s_upper = path_time_point.s() -
vehicle_config.vehicle_param().front_edge_to_center();
double s_lower = s_upper - FLAGS_default_lon_buffer;
CHECK_GE(FLAGS_num_sample_follow_per_timestamp, 2U);
double s_gap =
FLAGS_default_lon_buffer /
static_cast<double>(FLAGS_num_sample_follow_per_timestamp - 1);
for (size_t i = 0; i < FLAGS_num_sample_follow_per_timestamp; ++i) {
double s = s_lower + s_gap * static_cast<double>(i);
SamplePoint sample_point;
sample_point.path_time_point = path_time_point;
sample_point.path_time_point.set_s(s);
sample_point.ref_v = v;
sample_points->push_back(std::move(sample_point));
}
}
}
void EndConditionSampler::QueryOvertakePathTimePoints(
const common::VehicleConfig& vehicle_config, const std::string& obstacle_id,
std::vector<SamplePoint>* sample_points) const {
std::vector<STPoint> overtake_path_time_points =
ptr_path_time_graph_->GetObstacleSurroundingPoints(
obstacle_id, FLAGS_numerical_epsilon, FLAGS_time_min_density);
for (const auto& path_time_point : overtake_path_time_points) {
double v = ptr_prediction_querier_->ProjectVelocityAlongReferenceLine(
obstacle_id, path_time_point.s(), path_time_point.t());
SamplePoint sample_point;
sample_point.path_time_point = path_time_point;
sample_point.path_time_point.set_s(path_time_point.s() +
FLAGS_default_lon_buffer);
sample_point.ref_v = v;
sample_points->push_back(std::move(sample_point));
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/trajectory_combiner.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 "modules/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/planning/common/trajectory/discretized_trajectory.h"
#include "modules/planning/math/curve1d/curve1d.h"
namespace apollo {
namespace planning {
class TrajectoryCombiner {
public:
static DiscretizedTrajectory Combine(
const std::vector<common::PathPoint>& reference_line,
const Curve1d& lon_trajectory, const Curve1d& lat_trajectory,
const double init_relative_time);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""]
cc_library(
name = "lattice_trajectory1d",
srcs = ["lattice_trajectory1d.cc"],
hdrs = ["lattice_trajectory1d.h"],
copts = PLANNING_COPTS,
deps = [
"//cyber",
"//modules/planning/math/curve1d",
],
)
cc_library(
name = "end_condition_sampler",
srcs = ["end_condition_sampler.cc"],
hdrs = ["end_condition_sampler.h"],
deps = [
"//modules/common/configs:vehicle_config_helper",
"//modules/planning/common:planning_gflags",
"//modules/planning/lattice/behavior:feasible_region",
"//modules/planning/lattice/behavior:path_time_graph",
"//modules/planning/lattice/behavior:prediction_querier",
"//modules/planning/proto:lattice_structure_cc_proto",
],
)
cc_library(
name = "trajectory1d_generator",
srcs = ["trajectory1d_generator.cc"],
hdrs = ["trajectory1d_generator.h"],
deps = [
":end_condition_sampler",
":lateral_osqp_optimizer",
":lateral_qp_optimizer",
"//modules/planning/common:planning_gflags",
"//modules/planning/common/trajectory1d:constant_deceleration_trajectory1d",
"//modules/planning/common/trajectory1d:piecewise_acceleration_trajectory1d",
"//modules/planning/common/trajectory1d:piecewise_trajectory1d",
"//modules/planning/common/trajectory1d:standing_still_trajectory1d",
"//modules/planning/lattice/behavior:path_time_graph",
"//modules/planning/lattice/behavior:prediction_querier",
"//modules/planning/lattice/trajectory_generation:lattice_trajectory1d",
"//modules/planning/math/curve1d:quartic_polynomial_curve1d",
"//modules/planning/math/curve1d:quintic_polynomial_curve1d",
"//modules/planning/proto:lattice_structure_cc_proto",
],
)
cc_library(
name = "trajectory_evaluator",
srcs = ["trajectory_evaluator.cc"],
hdrs = ["trajectory_evaluator.h"],
copts = PLANNING_COPTS,
deps = [
"//modules/common/math",
"//modules/planning/common:planning_gflags",
"//modules/planning/common/trajectory1d:piecewise_acceleration_trajectory1d",
"//modules/planning/constraint_checker:constraint_checker1d",
"//modules/planning/lattice/behavior:path_time_graph",
"//modules/planning/lattice/trajectory_generation:piecewise_braking_trajectory_generator",
"//modules/planning/math/curve1d",
],
)
cc_library(
name = "backup_trajectory_generator",
srcs = ["backup_trajectory_generator.cc"],
hdrs = ["backup_trajectory_generator.h"],
deps = [
"//modules/planning/common:planning_gflags",
"//modules/planning/common/trajectory:discretized_trajectory",
"//modules/planning/common/trajectory1d:constant_deceleration_trajectory1d",
"//modules/planning/constraint_checker:collision_checker",
"//modules/planning/lattice/trajectory_generation:trajectory1d_generator",
"//modules/planning/lattice/trajectory_generation:trajectory_combiner",
"//modules/planning/math/curve1d",
],
)
cc_library(
name = "trajectory_combiner",
srcs = ["trajectory_combiner.cc"],
hdrs = ["trajectory_combiner.h"],
deps = [
"//modules/common/math",
"//modules/planning/common:planning_gflags",
"//modules/planning/common/trajectory:discretized_trajectory",
"//modules/planning/math/curve1d",
],
)
cc_library(
name = "piecewise_braking_trajectory_generator",
srcs = ["piecewise_braking_trajectory_generator.cc"],
hdrs = ["piecewise_braking_trajectory_generator.h"],
deps = [
"//modules/planning/common/trajectory1d:piecewise_acceleration_trajectory1d",
"//modules/planning/math/curve1d",
],
)
cc_library(
name = "lateral_qp_optimizer",
srcs = ["lateral_qp_optimizer.cc"],
hdrs = ["lateral_qp_optimizer.h"],
copts = PLANNING_COPTS,
deps = [
"//modules/common/util",
"//modules/planning/common/trajectory1d:piecewise_jerk_trajectory1d",
],
)
cc_library(
name = "lateral_osqp_optimizer",
srcs = ["lateral_osqp_optimizer.cc"],
hdrs = ["lateral_osqp_optimizer.h"],
copts = PLANNING_COPTS,
deps = [
":lateral_qp_optimizer",
"//cyber",
"//modules/common/math",
"//modules/planning/common/trajectory1d:piecewise_jerk_trajectory1d",
"@eigen",
"@osqp",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/end_condition_sampler.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/planning/common/speed/st_point.h"
#include "modules/planning/lattice/behavior/feasible_region.h"
#include "modules/planning/lattice/behavior/path_time_graph.h"
#include "modules/planning/lattice/behavior/prediction_querier.h"
namespace apollo {
namespace planning {
struct SamplePoint {
STPoint path_time_point;
double ref_v;
};
// Input: planning objective, vehicle kinematic/dynamic constraints,
// Output: sampled ending 1 dimensional states with corresponding time duration.
class EndConditionSampler {
public:
EndConditionSampler(
const std::array<double, 3>& init_s, const std::array<double, 3>& init_d,
std::shared_ptr<PathTimeGraph> ptr_path_time_graph,
std::shared_ptr<PredictionQuerier> ptr_prediction_querier);
virtual ~EndConditionSampler() = default;
std::vector<std::pair<std::array<double, 3>, double>> SampleLatEndConditions()
const;
std::vector<std::pair<std::array<double, 3>, double>>
SampleLonEndConditionsForCruising(const double ref_cruise_speed) const;
std::vector<std::pair<std::array<double, 3>, double>>
SampleLonEndConditionsForStopping(const double ref_stop_point) const;
std::vector<std::pair<std::array<double, 3>, double>>
SampleLonEndConditionsForPathTimePoints() const;
private:
std::vector<SamplePoint> QueryPathTimeObstacleSamplePoints() const;
void QueryFollowPathTimePoints(
const apollo::common::VehicleConfig& vehicle_config,
const std::string& obstacle_id,
std::vector<SamplePoint>* sample_points) const;
void QueryOvertakePathTimePoints(
const apollo::common::VehicleConfig& vehicle_config,
const std::string& obstacle_id,
std::vector<SamplePoint>* sample_points) const;
private:
std::array<double, 3> init_s_;
std::array<double, 3> init_d_;
FeasibleRegion feasible_region_;
std::shared_ptr<PathTimeGraph> ptr_path_time_graph_;
std::shared_ptr<PredictionQuerier> ptr_prediction_querier_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/backup_trajectory_generator.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 <functional>
#include <memory>
#include <queue>
#include <utility>
#include <vector>
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/trajectory/discretized_trajectory.h"
#include "modules/planning/common/trajectory1d/constant_deceleration_trajectory1d.h"
#include "modules/planning/constraint_checker/collision_checker.h"
#include "modules/planning/lattice/trajectory_generation/trajectory1d_generator.h"
#include "modules/planning/math/curve1d/curve1d.h"
namespace apollo {
namespace planning {
class BackupTrajectoryGenerator {
public:
typedef std::pair<std::shared_ptr<Curve1d>, std::shared_ptr<Curve1d>>
Trajectory1dPair;
typedef std::pair<Trajectory1dPair, double> PairCost;
BackupTrajectoryGenerator(
const std::array<double, 3>& init_s, const std::array<double, 3>& init_d,
const double init_relative_time,
const std::shared_ptr<CollisionChecker>& ptr_collision_checker,
const Trajectory1dGenerator* trajectory1d_generator);
DiscretizedTrajectory GenerateTrajectory(
const std::vector<common::PathPoint>& discretized_ref_points);
private:
void GenerateTrajectory1dPairs(const std::array<double, 3>& init_s,
const std::array<double, 3>& init_d);
double init_relative_time_;
std::shared_ptr<CollisionChecker> ptr_collision_checker_;
const Trajectory1dGenerator* ptr_trajectory1d_generator_;
struct CostComparator
: public std::binary_function<const Trajectory1dPair&,
const Trajectory1dPair&, bool> {
bool operator()(const Trajectory1dPair& left,
const Trajectory1dPair& right) const {
auto lon_left = left.first;
auto lon_right = right.first;
auto s_dot_left = lon_left->Evaluate(1, FLAGS_trajectory_time_length);
auto s_dot_right = lon_right->Evaluate(1, FLAGS_trajectory_time_length);
if (s_dot_left < s_dot_right) {
return true;
}
return false;
}
};
std::priority_queue<Trajectory1dPair, std::vector<Trajectory1dPair>,
CostComparator>
trajectory_pair_pqueue_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning/lattice
|
apollo_public_repos/apollo/modules/planning/lattice/trajectory_generation/piecewise_braking_trajectory_generator.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/piecewise_braking_trajectory_generator.h"
#include <cmath>
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
std::shared_ptr<Curve1d> PiecewiseBrakingTrajectoryGenerator::Generate(
const double s_target, const double s_curr, const double v_target,
const double v_curr, const double a_comfort, const double d_comfort,
const double max_time) {
std::shared_ptr<PiecewiseAccelerationTrajectory1d> ptr_trajectory =
std::make_shared<PiecewiseAccelerationTrajectory1d>(s_curr, v_curr);
double s_dist = s_target - s_curr;
double comfort_stop_dist = ComputeStopDistance(v_curr, d_comfort);
// if cannot stop using comfort deceleration, then brake in the beginning.
if (comfort_stop_dist > s_dist) {
double stop_d = ComputeStopDeceleration(s_dist, v_curr);
double stop_t = v_curr / stop_d;
ptr_trajectory->AppendSegment(-stop_d, stop_t);
if (ptr_trajectory->ParamLength() < max_time) {
ptr_trajectory->AppendSegment(0.0,
max_time - ptr_trajectory->ParamLength());
}
return ptr_trajectory;
}
// otherwise, the vehicle can stop from current speed with comfort brake.
if (v_curr > v_target) {
double t_cruise = (s_dist - comfort_stop_dist) / v_target;
double t_rampdown = (v_curr - v_target) / d_comfort;
double t_dec = v_target / d_comfort;
ptr_trajectory->AppendSegment(-d_comfort, t_rampdown);
ptr_trajectory->AppendSegment(0.0, t_cruise);
ptr_trajectory->AppendSegment(-d_comfort, t_dec);
if (ptr_trajectory->ParamLength() < max_time) {
ptr_trajectory->AppendSegment(0.0,
max_time - ptr_trajectory->ParamLength());
}
return ptr_trajectory;
} else {
double t_rampup = (v_target - v_curr) / a_comfort;
double t_rampdown = (v_target - v_curr) / d_comfort;
double s_ramp = (v_curr + v_target) * (t_rampup + t_rampdown) * 0.5;
double s_rest = s_dist - s_ramp - comfort_stop_dist;
if (s_rest > 0) {
double t_cruise = s_rest / v_target;
double t_dec = v_target / d_comfort;
// construct the trajectory
ptr_trajectory->AppendSegment(a_comfort, t_rampup);
ptr_trajectory->AppendSegment(0.0, t_cruise);
ptr_trajectory->AppendSegment(-d_comfort, t_dec);
if (ptr_trajectory->ParamLength() < max_time) {
ptr_trajectory->AppendSegment(0.0,
max_time - ptr_trajectory->ParamLength());
}
return ptr_trajectory;
} else {
double s_rampup_rampdown = s_dist - comfort_stop_dist;
double v_max = std::sqrt(v_curr * v_curr + 2.0 * a_comfort * d_comfort *
s_rampup_rampdown /
(a_comfort + d_comfort));
double t_acc = (v_max - v_curr) / a_comfort;
double t_dec = v_max / d_comfort;
// construct the trajectory
ptr_trajectory->AppendSegment(a_comfort, t_acc);
ptr_trajectory->AppendSegment(-d_comfort, t_dec);
if (ptr_trajectory->ParamLength() < max_time) {
ptr_trajectory->AppendSegment(0.0,
max_time - ptr_trajectory->ParamLength());
}
return ptr_trajectory;
}
}
}
double PiecewiseBrakingTrajectoryGenerator::ComputeStopDistance(
const double v, const double dec) {
ACHECK(dec > 0.0);
return v * v / dec * 0.5;
}
double PiecewiseBrakingTrajectoryGenerator::ComputeStopDeceleration(
const double dist, const double v) {
return v * v / dist * 0.5;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/speed_profile_generator.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 speed_profile_generator.h
**/
#pragma once
#include <utility>
#include <vector>
#include "modules/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/planning/common/ego_info.h"
#include "modules/planning/common/reference_line_info.h"
#include "modules/planning/common/speed/speed_data.h"
#include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h"
namespace apollo {
namespace planning {
class SpeedProfileGenerator {
public:
SpeedProfileGenerator() = delete;
static SpeedData GenerateFallbackSpeed(const EgoInfo* ego_info,
const double stop_distance = 0.0);
static void FillEnoughSpeedPoints(SpeedData* const speed_data);
static SpeedData GenerateFixedDistanceCreepProfile(const double distance,
const double max_speed);
private:
static SpeedData GenerateStopProfile(const double init_speed,
const double init_acc);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/speed_limit.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 speed_limit.cc
**/
#include "modules/planning/common/speed_limit.h"
#include <algorithm>
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
void SpeedLimit::AppendSpeedLimit(const double s, const double v) {
if (!speed_limit_points_.empty()) {
DCHECK_GE(s, speed_limit_points_.back().first);
}
speed_limit_points_.emplace_back(s, v);
}
const std::vector<std::pair<double, double>>& SpeedLimit::speed_limit_points()
const {
return speed_limit_points_;
}
double SpeedLimit::GetSpeedLimitByS(const double s) const {
CHECK_GE(speed_limit_points_.size(), 2U);
DCHECK_GE(s, speed_limit_points_.front().first);
auto compare_s = [](const std::pair<double, double>& point, const double s) {
return point.first < s;
};
auto it_lower = std::lower_bound(speed_limit_points_.begin(),
speed_limit_points_.end(), s, compare_s);
if (it_lower == speed_limit_points_.end()) {
return (it_lower - 1)->second;
}
return it_lower->second;
}
void SpeedLimit::Clear() { speed_limit_points_.clear(); }
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/dependency_injector.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/planning/common/ego_info.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/history.h"
#include "modules/planning/common/learning_based_data.h"
#include "modules/planning/common/planning_context.h"
namespace apollo {
namespace planning {
class DependencyInjector {
public:
DependencyInjector() = default;
~DependencyInjector() = default;
PlanningContext* planning_context() {
return &planning_context_;
}
FrameHistory* frame_history() {
return &frame_history_;
}
History* history() {
return &history_;
}
EgoInfo* ego_info() {
return &ego_info_;
}
apollo::common::VehicleStateProvider* vehicle_state() {
return &vehicle_state_;
}
LearningBasedData* learning_based_data() {
return &learning_based_data_;
}
private:
PlanningContext planning_context_;
FrameHistory frame_history_;
History history_;
EgoInfo ego_info_;
apollo::common::VehicleStateProvider vehicle_state_;
LearningBasedData learning_based_data_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/open_space_info.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/common/open_space_info.h"
namespace apollo {
namespace planning {
void CopyTrajectory(const DiscretizedTrajectory trajectory_src,
apollo::common::Trajectory* trajectory_tgt_ptr) {
const size_t horizon = trajectory_src.NumOfPoints();
for (size_t i = 0; i < horizon; ++i) {
*trajectory_tgt_ptr->add_trajectory_point() =
trajectory_src.TrajectoryPointAt(i);
}
}
// record more trajectory information to info debug
void OpenSpaceInfo::RecordDebug(apollo::planning_internal::Debug* ptr_debug) {
// 1, Copy info into ptr_debug
*ptr_debug = debug_instance_;
// 2, record partitioned trajectories into ptr_debug
auto* ptr_partitioned_trajectories = ptr_debug->mutable_planning_data()
->mutable_open_space()
->mutable_partitioned_trajectories();
for (auto& iter : partitioned_trajectories_) {
const auto& picked_trajectory = iter.first;
auto* ptr_added_trajectory = ptr_partitioned_trajectories->add_trajectory();
CopyTrajectory(picked_trajectory, ptr_added_trajectory);
}
// 3, record chosen partitioned into ptr_debug
auto* ptr_chosen_trajectory = ptr_debug->mutable_planning_data()
->mutable_open_space()
->mutable_chosen_trajectory()
->add_trajectory();
const auto& chosen_trajectory = chosen_partitioned_trajectory_.first;
CopyTrajectory(chosen_trajectory, ptr_chosen_trajectory);
// 4, record if the trajectory is fallback trajectory
ptr_debug->mutable_planning_data()
->mutable_open_space()
->set_is_fallback_trajectory(fallback_flag_);
// 5, record fallback trajectory if needed
if (fallback_flag_) {
auto* ptr_fallback_trajectory = ptr_debug->mutable_planning_data()
->mutable_open_space()
->mutable_fallback_trajectory()
->add_trajectory();
const auto& fallback_trajectory = fallback_trajectory_.first;
CopyTrajectory(fallback_trajectory, ptr_fallback_trajectory);
ptr_debug->mutable_planning_data()
->mutable_open_space()
->mutable_future_collision_point()
->CopyFrom(future_collision_point_);
}
auto open_space = ptr_debug->mutable_planning_data()->mutable_open_space();
open_space->set_time_latency(time_latency_);
open_space->mutable_origin_point()->set_x(origin_point_.x());
open_space->mutable_origin_point()->set_y(origin_point_.y());
open_space->mutable_origin_point()->set_z(0.0);
open_space->set_origin_heading_rad(origin_heading_);
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/open_space_info_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/common/open_space_info.h"
#include "gtest/gtest.h"
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/common_msgs/planning_msgs/sl_boundary.pb.h"
#include "modules/common_msgs/routing_msgs/routing.pb.h"
namespace apollo {
namespace planning {
class OpenSpaceInfoTest : public ::testing::Test {
public:
virtual void SetUp() {}
protected:
OpenSpaceInfo open_space_info_;
};
TEST_F(OpenSpaceInfoTest, Init) { EXPECT_NE(&open_space_info_, nullptr); }
bool ComputeSLBoundaryIntersection(const SLBoundary& sl_boundary,
const double s, double* ptr_l_min,
double* ptr_l_max);
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/history.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/common/history.h"
#include <utility>
#include "cyber/common/log.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
////////////////////////////////////////////////
// HistoryObjectDecision
void HistoryObjectDecision::Init(const ObjectDecision& object_decisions) {
id_ = object_decisions.id();
object_decision_.clear();
for (int i = 0; i < object_decisions.object_decision_size(); i++) {
object_decision_.push_back(object_decisions.object_decision(i));
}
}
void HistoryObjectDecision::Init(
const std::string& id,
const std::vector<ObjectDecisionType>& object_decision) {
id_ = id;
object_decision_.clear();
for (const auto decision_type : object_decision) {
object_decision_.push_back(decision_type);
}
}
std::vector<const ObjectDecisionType*>
HistoryObjectDecision::GetObjectDecision() const {
std::vector<const ObjectDecisionType*> result;
for (size_t i = 0; i < object_decision_.size(); i++) {
result.push_back(&(object_decision_[i]));
}
return result;
}
////////////////////////////////////////////////
// HistoryFrame
void HistoryFrame::Init(const ADCTrajectory& adc_trajactory) {
adc_trajactory_.CopyFrom(adc_trajactory);
seq_num_ = adc_trajactory.header().sequence_num();
const auto& object_decisions = adc_trajactory.decision().object_decision();
for (int i = 0; i < object_decisions.decision_size(); i++) {
const std::string id = object_decisions.decision(i).id();
HistoryObjectDecision object_decision;
object_decision.Init(object_decisions.decision(i));
object_decisions_map_[id] = object_decision;
object_decisions_.push_back(object_decision);
}
}
std::vector<const HistoryObjectDecision*> HistoryFrame::GetObjectDecisions()
const {
std::vector<const HistoryObjectDecision*> result;
for (size_t i = 0; i < object_decisions_.size(); i++) {
result.push_back(&(object_decisions_[i]));
}
return result;
}
std::vector<const HistoryObjectDecision*> HistoryFrame::GetStopObjectDecisions()
const {
std::vector<const HistoryObjectDecision*> result;
for (size_t i = 0; i < object_decisions_.size(); i++) {
auto obj_decision = object_decisions_[i].GetObjectDecision();
for (const ObjectDecisionType* decision_type : obj_decision) {
if (decision_type->has_stop()) {
std::vector<ObjectDecisionType> object_decision;
object_decision.push_back(*decision_type);
HistoryObjectDecision* decision = new HistoryObjectDecision();
decision->Init(object_decisions_[i].id(), object_decision);
result.push_back(decision);
}
}
}
// sort
std::sort(
result.begin(), result.end(),
[](const HistoryObjectDecision* lhs, const HistoryObjectDecision* rhs) {
return lhs->id() < rhs->id();
});
return result;
}
const HistoryObjectDecision* HistoryFrame::GetObjectDecisionsById(
const std::string& id) const {
if (object_decisions_map_.find(id) == object_decisions_map_.end()) {
return nullptr;
}
return &(object_decisions_map_.at(id));
}
////////////////////////////////////////////////
// HistoryObjectStatus
void HistoryObjectStatus::Init(const std::string& id,
const ObjectStatus& object_status) {
id_ = id;
object_status_ = object_status;
}
////////////////////////////////////////////////
// HistoryStatus
void HistoryStatus::SetObjectStatus(const std::string& id,
const ObjectStatus& object_status) {
object_id_to_status_[id] = object_status;
}
bool HistoryStatus::GetObjectStatus(const std::string& id,
ObjectStatus* const object_status) {
if (object_id_to_status_.count(id) == 0) {
return false;
}
*object_status = object_id_to_status_[id];
return true;
}
////////////////////////////////////////////////
// History
const HistoryFrame* History::GetLastFrame() const {
if (history_frames_.empty()) {
return nullptr;
} else {
return &(history_frames_.back());
}
}
void History::Clear() { history_frames_.clear(); }
int History::Add(const ADCTrajectory& adc_trajectory_pb) {
if (history_frames_.size() >=
static_cast<size_t>(FLAGS_history_max_record_num)) {
history_frames_.pop_front();
}
HistoryFrame history_frame;
history_frame.Init(adc_trajectory_pb);
history_frames_.emplace_back(std::move(history_frame));
return 0;
}
size_t History::Size() const { return history_frames_.size(); }
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/obstacle_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/common/obstacle.h"
#include "cyber/common/file.h"
#include "gtest/gtest.h"
#include "modules/common/util/util.h"
#include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
namespace apollo {
namespace planning {
using apollo::perception::PerceptionObstacle;
TEST(Obstacle, IsValidPerceptionObstacle) {
PerceptionObstacle perception_obstacle;
EXPECT_FALSE(Obstacle::IsValidPerceptionObstacle(perception_obstacle));
perception_obstacle.mutable_position()->set_x(2.5);
perception_obstacle.mutable_position()->set_y(0.5);
perception_obstacle.mutable_position()->set_z(0.5);
perception_obstacle.mutable_velocity()->set_x(2.5);
perception_obstacle.mutable_velocity()->set_y(0.5);
perception_obstacle.mutable_velocity()->set_z(0.5);
EXPECT_FALSE(Obstacle::IsValidPerceptionObstacle(perception_obstacle));
perception_obstacle.set_length(0.1);
EXPECT_FALSE(Obstacle::IsValidPerceptionObstacle(perception_obstacle));
perception_obstacle.set_width(0.1);
EXPECT_FALSE(Obstacle::IsValidPerceptionObstacle(perception_obstacle));
perception_obstacle.set_height(0.1);
EXPECT_TRUE(Obstacle::IsValidPerceptionObstacle(perception_obstacle));
}
class ObstacleTest : public ::testing::Test {
public:
virtual void SetUp() {
prediction::PredictionObstacles prediction_obstacles;
ASSERT_TRUE(cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/sample_prediction.pb.txt",
&prediction_obstacles));
auto obstacles = Obstacle::CreateObstacles(prediction_obstacles);
ASSERT_EQ(5, obstacles.size());
for (auto& obstacle : obstacles) {
const auto id = obstacle->Id();
indexed_obstacles_.Add(id, *obstacle);
}
}
protected:
IndexedObstacles indexed_obstacles_;
};
TEST_F(ObstacleTest, CreateObstacles) {
ASSERT_EQ(5, indexed_obstacles_.Items().size());
EXPECT_TRUE(indexed_obstacles_.Find("2156_0"));
EXPECT_TRUE(indexed_obstacles_.Find("2156_1"));
EXPECT_TRUE(indexed_obstacles_.Find("2157_0"));
EXPECT_TRUE(indexed_obstacles_.Find("2157_1"));
EXPECT_TRUE(indexed_obstacles_.Find("2161"));
}
TEST_F(ObstacleTest, Id) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
EXPECT_EQ("2156_0", obstacle->Id());
EXPECT_EQ(2156, obstacle->PerceptionId());
}
TEST_F(ObstacleTest, GetPointAtTime) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
// first
const auto first_point = obstacle->GetPointAtTime(0.0);
EXPECT_DOUBLE_EQ(0.0, first_point.relative_time());
EXPECT_DOUBLE_EQ(76.684071405, first_point.path_point().x());
EXPECT_DOUBLE_EQ(350.481852505, first_point.path_point().y());
// last
const auto last_point = obstacle->GetPointAtTime(10.04415320);
EXPECT_DOUBLE_EQ(10.0441531943, last_point.relative_time());
EXPECT_DOUBLE_EQ(186.259371951, last_point.path_point().x());
EXPECT_DOUBLE_EQ(341.853799387, last_point.path_point().y());
// middle
const auto middle_point = obstacle->GetPointAtTime(3.7300);
EXPECT_LE(3.68968892853, middle_point.relative_time());
EXPECT_GE(3.89467164678, middle_point.relative_time());
EXPECT_GE(139.091700103, middle_point.path_point().x());
EXPECT_LE(135.817210975, middle_point.path_point().x());
EXPECT_GE(349.875902219, middle_point.path_point().y());
EXPECT_LE(349.549888973, middle_point.path_point().y());
}
TEST_F(ObstacleTest, PerceptionBoundingBox) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
const auto& box = obstacle->PerceptionBoundingBox();
std::vector<common::math::Vec2d> corners;
box.GetAllCorners(&corners);
EXPECT_EQ(4, corners.size());
EXPECT_DOUBLE_EQ(3.8324769804600001, box.length());
EXPECT_DOUBLE_EQ(1.73200099013, box.width());
EXPECT_DOUBLE_EQ(76.684071405, box.center_x());
EXPECT_DOUBLE_EQ(350.481852505, box.center_y());
EXPECT_DOUBLE_EQ(0.00531211859358, box.heading());
}
TEST_F(ObstacleTest, GetBoundingBox) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
const auto& point = obstacle->Trajectory().trajectory_point(2);
const auto& box = obstacle->GetBoundingBox(point);
std::vector<common::math::Vec2d> corners;
box.GetAllCorners(&corners);
EXPECT_EQ(4, corners.size());
EXPECT_DOUBLE_EQ(3.8324769804600001, box.length());
EXPECT_DOUBLE_EQ(1.73200099013, box.width());
EXPECT_DOUBLE_EQ(83.2581699369, box.center_x());
EXPECT_DOUBLE_EQ(350.779556678, box.center_y());
EXPECT_DOUBLE_EQ(0.040689919196199999, box.heading());
}
TEST_F(ObstacleTest, PerceptionPolygon) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
const auto& polygon = obstacle->PerceptionPolygon();
const auto& points = polygon.points();
EXPECT_EQ(16, points.size());
EXPECT_DOUBLE_EQ(74.766181894499994, points[0].x());
EXPECT_DOUBLE_EQ(350.72985818299998, points[0].y());
EXPECT_DOUBLE_EQ(74.783198034400002, points[1].x());
EXPECT_DOUBLE_EQ(350.32601568799998, points[1].y());
EXPECT_DOUBLE_EQ(74.770555729799995, points[15].x());
EXPECT_DOUBLE_EQ(350.878567223, points[15].y());
}
TEST_F(ObstacleTest, Trajectory) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
const auto& points = obstacle->Trajectory().trajectory_point();
EXPECT_EQ(50, points.size());
}
TEST_F(ObstacleTest, Perception) {
const auto* obstacle = indexed_obstacles_.Find("2156_0");
ASSERT_TRUE(obstacle);
const auto& perception_obstacle = obstacle->Perception();
EXPECT_EQ(2156, perception_obstacle.id());
}
TEST(Obstacle, CreateStaticVirtualObstacle) {
common::math::Box2d box({0, 0}, 0.0, 4.0, 2.0);
std::unique_ptr<Obstacle> obstacle =
Obstacle::CreateStaticVirtualObstacles("abc", box);
EXPECT_EQ("abc", obstacle->Id());
EXPECT_EQ(-314721735, obstacle->PerceptionId());
EXPECT_TRUE(obstacle->IsVirtual());
auto& perception_box = obstacle->PerceptionBoundingBox();
EXPECT_DOUBLE_EQ(0.0, perception_box.center().x());
EXPECT_DOUBLE_EQ(0.0, perception_box.center().y());
EXPECT_DOUBLE_EQ(4.0, perception_box.length());
EXPECT_DOUBLE_EQ(2.0, perception_box.width());
EXPECT_DOUBLE_EQ(0.0, perception_box.heading());
}
TEST(IsLateralDecision, AllDecisions) {
ObjectDecisionType decision_ignore;
decision_ignore.mutable_ignore();
EXPECT_TRUE(Obstacle::IsLateralDecision(decision_ignore));
ObjectDecisionType decision_overtake;
decision_overtake.mutable_overtake();
EXPECT_FALSE(Obstacle::IsLateralDecision(decision_overtake));
ObjectDecisionType decision_follow;
decision_follow.mutable_follow();
EXPECT_FALSE(Obstacle::IsLateralDecision(decision_follow));
ObjectDecisionType decision_yield;
decision_yield.mutable_yield();
EXPECT_FALSE(Obstacle::IsLateralDecision(decision_yield));
ObjectDecisionType decision_stop;
decision_stop.mutable_stop();
EXPECT_FALSE(Obstacle::IsLateralDecision(decision_stop));
ObjectDecisionType decision_nudge;
decision_nudge.mutable_nudge();
EXPECT_TRUE(Obstacle::IsLateralDecision(decision_nudge));
}
TEST(IsLongitudinalDecision, AllDecisions) {
ObjectDecisionType decision_ignore;
decision_ignore.mutable_ignore();
EXPECT_TRUE(Obstacle::IsLongitudinalDecision(decision_ignore));
ObjectDecisionType decision_overtake;
decision_overtake.mutable_overtake();
EXPECT_TRUE(Obstacle::IsLongitudinalDecision(decision_overtake));
ObjectDecisionType decision_follow;
decision_follow.mutable_follow();
EXPECT_TRUE(Obstacle::IsLongitudinalDecision(decision_follow));
ObjectDecisionType decision_yield;
decision_yield.mutable_yield();
EXPECT_TRUE(Obstacle::IsLongitudinalDecision(decision_yield));
ObjectDecisionType decision_stop;
decision_stop.mutable_stop();
EXPECT_TRUE(Obstacle::IsLongitudinalDecision(decision_stop));
ObjectDecisionType decision_nudge;
decision_nudge.mutable_nudge();
EXPECT_FALSE(Obstacle::IsLongitudinalDecision(decision_nudge));
}
TEST(MergeLongitudinalDecision, AllDecisions) {
ObjectDecisionType decision_ignore;
decision_ignore.mutable_ignore();
ObjectDecisionType decision_overtake;
decision_overtake.mutable_overtake();
ObjectDecisionType decision_follow;
decision_follow.mutable_follow();
ObjectDecisionType decision_yield;
decision_yield.mutable_yield();
ObjectDecisionType decision_stop;
decision_stop.mutable_stop();
ObjectDecisionType decision_nudge;
decision_nudge.mutable_nudge();
// vertical decision comparison
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_stop, decision_ignore)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_stop, decision_overtake)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_stop, decision_follow)
.has_stop());
EXPECT_TRUE(Obstacle::MergeLongitudinalDecision(decision_stop, decision_yield)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_yield, decision_ignore)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_yield, decision_overtake)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_yield, decision_follow)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_follow, decision_ignore)
.has_follow());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_follow, decision_overtake)
.has_follow());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_overtake, decision_ignore)
.has_overtake());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_ignore, decision_overtake)
.has_overtake());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_ignore, decision_follow)
.has_follow());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_ignore, decision_yield)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_ignore, decision_stop)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_overtake, decision_follow)
.has_follow());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_overtake, decision_yield)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_overtake, decision_stop)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_follow, decision_yield)
.has_yield());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_follow, decision_stop)
.has_stop());
EXPECT_TRUE(Obstacle::MergeLongitudinalDecision(decision_yield, decision_stop)
.has_stop());
EXPECT_TRUE(
Obstacle::MergeLongitudinalDecision(decision_ignore, decision_ignore)
.has_ignore());
ObjectDecisionType decision_overtake1;
decision_overtake1.mutable_overtake()->set_distance_s(1);
ObjectDecisionType decision_overtake2;
decision_overtake2.mutable_overtake()->set_distance_s(2);
EXPECT_EQ(2, Obstacle::MergeLongitudinalDecision(decision_overtake1,
decision_overtake2)
.overtake()
.distance_s());
ObjectDecisionType decision_follow1;
decision_follow1.mutable_follow()->set_distance_s(-1);
ObjectDecisionType decision_follow2;
decision_follow2.mutable_follow()->set_distance_s(-2);
EXPECT_EQ(-2, Obstacle::MergeLongitudinalDecision(decision_follow1,
decision_follow2)
.follow()
.distance_s());
ObjectDecisionType decision_yield1;
decision_yield1.mutable_yield()->set_distance_s(-1);
ObjectDecisionType decision_yield2;
decision_yield2.mutable_yield()->set_distance_s(-2);
EXPECT_EQ(
-2, Obstacle::MergeLongitudinalDecision(decision_yield1, decision_yield2)
.yield()
.distance_s());
ObjectDecisionType decision_stop1;
decision_stop1.mutable_stop()->set_distance_s(-1);
ObjectDecisionType decision_stop2;
decision_stop2.mutable_stop()->set_distance_s(-2);
EXPECT_EQ(-2,
Obstacle::MergeLongitudinalDecision(decision_stop1, decision_stop2)
.stop()
.distance_s());
}
TEST(MergeLateralDecision, AllDecisions) {
ObjectDecisionType decision_ignore;
decision_ignore.mutable_ignore();
ObjectDecisionType decision_overtake;
decision_overtake.mutable_overtake();
ObjectDecisionType decision_follow;
decision_follow.mutable_follow();
ObjectDecisionType decision_yield;
decision_yield.mutable_yield();
ObjectDecisionType decision_stop;
decision_stop.mutable_stop();
ObjectDecisionType decision_nudge;
decision_nudge.mutable_nudge()->set_type(ObjectNudge::LEFT_NUDGE);
EXPECT_TRUE(Obstacle::MergeLateralDecision(decision_nudge, decision_ignore)
.has_nudge());
EXPECT_TRUE(Obstacle::MergeLateralDecision(decision_ignore, decision_nudge)
.has_nudge());
ObjectDecisionType decision_nudge2;
decision_nudge2.mutable_nudge()->set_type(ObjectNudge::LEFT_NUDGE);
EXPECT_TRUE(Obstacle::MergeLateralDecision(decision_nudge, decision_nudge2)
.has_nudge());
decision_nudge2.mutable_nudge()->set_type(ObjectNudge::RIGHT_NUDGE);
}
TEST(ObstacleMergeTest, add_decision_test) {
// init state
{
Obstacle obstacle;
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
}
// Ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_ignore();
obstacle.AddLongitudinalDecision("test_ignore", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_FALSE(obstacle.LateralDecision().has_ignore());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_ignore());
}
// stop and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_stop();
obstacle.AddLongitudinalDecision("test_stop", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
decision.mutable_ignore();
obstacle.AddLongitudinalDecision("test_ignore", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_FALSE(obstacle.LateralDecision().has_ignore());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
}
// left nudge and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_nudge()->set_type(ObjectNudge::LEFT_NUDGE);
obstacle.AddLateralDecision("test_nudge", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
decision.mutable_ignore();
obstacle.AddLateralDecision("test_ignore", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
EXPECT_FALSE(obstacle.LongitudinalDecision().has_ignore());
}
// right nudge and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_nudge()->set_type(ObjectNudge::RIGHT_NUDGE);
obstacle.AddLateralDecision("test_nudge", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
decision.mutable_ignore();
obstacle.AddLateralDecision("test_ignore", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
EXPECT_FALSE(obstacle.LongitudinalDecision().has_ignore());
}
// left nudge and right nudge
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_nudge()->set_type(ObjectNudge::LEFT_NUDGE);
obstacle.AddLateralDecision("test_left_nudge", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_FALSE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
}
// overtake and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_overtake();
obstacle.AddLongitudinalDecision("test_overtake", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_overtake());
decision.mutable_ignore();
obstacle.AddLongitudinalDecision("test_ignore", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_FALSE(obstacle.LateralDecision().has_ignore());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_overtake());
}
// follow and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_follow();
obstacle.AddLongitudinalDecision("test_follow", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_follow());
decision.mutable_ignore();
obstacle.AddLongitudinalDecision("test_ignore", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_FALSE(obstacle.LateralDecision().has_ignore());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_follow());
}
// yield and ignore
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_yield();
obstacle.AddLongitudinalDecision("test_yield", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_yield());
decision.mutable_ignore();
obstacle.AddLongitudinalDecision("test_ignore", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_FALSE(obstacle.LateralDecision().has_ignore());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_yield());
}
// stop and nudge
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_stop();
obstacle.AddLongitudinalDecision("test_stop", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
decision.mutable_nudge();
obstacle.AddLateralDecision("test_nudge", decision);
EXPECT_TRUE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LateralDecision().has_nudge());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
}
// stop and yield
{
Obstacle obstacle;
ObjectDecisionType decision;
decision.mutable_stop();
obstacle.AddLongitudinalDecision("test_stop", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
decision.mutable_yield();
obstacle.AddLongitudinalDecision("test_yield", decision);
EXPECT_FALSE(obstacle.HasLateralDecision());
EXPECT_TRUE(obstacle.HasLongitudinalDecision());
EXPECT_TRUE(obstacle.LongitudinalDecision().has_stop());
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/speed_limit_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/common/speed_limit.h"
#include "gtest/gtest.h"
namespace apollo {
namespace planning {
class SpeedLimitTest : public ::testing::Test {
public:
virtual void SetUp() {
speed_limit_.Clear();
for (int i = 0; i < 100; ++i) {
std::pair<double, double> sp;
sp.first = i * 1.0;
sp.second = (i % 2 == 0) ? 5.0 : 10.0;
speed_limit_.AppendSpeedLimit(sp.first, sp.second);
}
}
protected:
SpeedLimit speed_limit_;
};
TEST_F(SpeedLimitTest, SimpleSpeedLimitCreation) {
SpeedLimit simple_speed_limit;
EXPECT_TRUE(simple_speed_limit.speed_limit_points().empty());
EXPECT_EQ(speed_limit_.speed_limit_points().size(), 100);
}
TEST_F(SpeedLimitTest, GetSpeedLimitByS) {
EXPECT_EQ(speed_limit_.speed_limit_points().size(), 100);
double s = 0.0;
const double ds = 0.01;
while (s < 99.0) {
double v_limit = speed_limit_.GetSpeedLimitByS(s);
auto it_lower = std::lower_bound(
speed_limit_.speed_limit_points().begin(),
speed_limit_.speed_limit_points().end(), s,
[](const std::pair<double, double>& point, const double curr_s) {
return point.first < curr_s;
});
EXPECT_DOUBLE_EQ(v_limit, it_lower->second);
s += ds;
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/ego_info.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file speed_limit.cc
**/
#include "modules/planning/common/ego_info.h"
#include "cyber/common/log.h"
#include "modules/common/configs/vehicle_config_helper.h"
namespace apollo {
namespace planning {
using apollo::common::math::Box2d;
using apollo::common::math::Vec2d;
EgoInfo::EgoInfo() {
ego_vehicle_config_ = common::VehicleConfigHelper::GetConfig();
}
bool EgoInfo::Update(const common::TrajectoryPoint& start_point,
const common::VehicleState& vehicle_state) {
set_start_point(start_point);
set_vehicle_state(vehicle_state);
CalculateEgoBox(vehicle_state);
return true;
}
void EgoInfo::CalculateEgoBox(const common::VehicleState& vehicle_state) {
const auto& param = ego_vehicle_config_.vehicle_param();
ADEBUG << "param: " << param.DebugString();
Vec2d vec_to_center(
(param.front_edge_to_center() - param.back_edge_to_center()) / 2.0,
(param.left_edge_to_center() - param.right_edge_to_center()) / 2.0);
Vec2d position(vehicle_state.x(), vehicle_state.y());
Vec2d center(position + vec_to_center.rotate(vehicle_state.heading()));
ego_box_ =
Box2d(center, vehicle_state.heading(), param.length(), param.width());
}
void EgoInfo::Clear() {
start_point_.Clear();
vehicle_state_.Clear();
front_clear_distance_ = FLAGS_default_front_clear_distance;
}
// TODO(all): remove this function and "front_clear_distance" related.
// It doesn't make sense when:
// 1. the heading is not necessaries align with the road
// 2. the road is not necessaries straight
void EgoInfo::CalculateFrontObstacleClearDistance(
const std::vector<const Obstacle*>& obstacles) {
Vec2d position(vehicle_state_.x(), vehicle_state_.y());
const auto& param = ego_vehicle_config_.vehicle_param();
Vec2d vec_to_center(
(param.front_edge_to_center() - param.back_edge_to_center()) / 2.0,
(param.left_edge_to_center() - param.right_edge_to_center()) / 2.0);
Vec2d center(position + vec_to_center.rotate(vehicle_state_.heading()));
Vec2d unit_vec_heading = Vec2d::CreateUnitVec2d(vehicle_state_.heading());
// Due to the error of ego heading, only short range distance is meaningful
static constexpr double kDistanceThreshold = 50.0;
static constexpr double buffer = 0.1; // in meters
const double impact_region_length =
param.length() + buffer + kDistanceThreshold;
Box2d ego_front_region(center + unit_vec_heading * kDistanceThreshold / 2.0,
vehicle_state_.heading(), impact_region_length,
param.width() + buffer);
for (const auto& obstacle : obstacles) {
if (obstacle->IsVirtual() ||
!ego_front_region.HasOverlap(obstacle->PerceptionBoundingBox())) {
continue;
}
double dist = ego_box_.center().DistanceTo(
obstacle->PerceptionBoundingBox().center()) -
ego_box_.diagonal() / 2.0;
if (front_clear_distance_ < 0.0 || dist < front_clear_distance_) {
front_clear_distance_ = dist;
}
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/obstacle_blocking_analyzer.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/obstacle_blocking_analyzer.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/util/point_factory.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::VehicleConfigHelper;
using apollo::hdmap::HDMapUtil;
constexpr double kAdcDistanceThreshold = 35.0; // unit: m
constexpr double kObstaclesDistanceThreshold = 15.0;
bool IsNonmovableObstacle(const ReferenceLineInfo& reference_line_info,
const Obstacle& obstacle) {
// Obstacle is far away.
const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();
if (obstacle.PerceptionSLBoundary().start_s() >
adc_sl_boundary.end_s() + kAdcDistanceThreshold) {
ADEBUG << " - It is too far ahead and we are not so sure of its status.";
return false;
}
// Obstacle is parked obstacle.
if (IsParkedVehicle(reference_line_info.reference_line(), &obstacle)) {
ADEBUG << "It is Parked and NON-MOVABLE.";
return true;
}
// Obstacle is blocked by others too.
for (const auto* other_obstacle :
reference_line_info.path_decision().obstacles().Items()) {
if (other_obstacle->Id() == obstacle.Id()) {
continue;
}
if (other_obstacle->IsVirtual()) {
continue;
}
if (other_obstacle->PerceptionSLBoundary().start_l() >
obstacle.PerceptionSLBoundary().end_l() ||
other_obstacle->PerceptionSLBoundary().end_l() <
obstacle.PerceptionSLBoundary().start_l()) {
// not blocking the backside vehicle
continue;
}
double delta_s = other_obstacle->PerceptionSLBoundary().start_s() -
obstacle.PerceptionSLBoundary().end_s();
if (delta_s < 0.0 || delta_s > kObstaclesDistanceThreshold) {
continue;
}
// TODO(All): Fix the segmentation bug for large vehicles, otherwise
// the follow line will be problematic.
ADEBUG << " - It is blocked by others, and will move later.";
return false;
}
ADEBUG << "IT IS NON-MOVABLE!";
return true;
}
// This is the side-pass condition for every obstacle.
// TODO(all): if possible, transform as many function parameters into GFLAGS.
bool IsBlockingObstacleToSidePass(const Frame& frame, const Obstacle* obstacle,
double block_obstacle_min_speed,
double min_front_sidepass_distance,
bool enable_obstacle_blocked_check) {
// Get the necessary info.
const auto& reference_line_info = frame.reference_line_info().front();
const auto& reference_line = reference_line_info.reference_line();
const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();
const PathDecision& path_decision = reference_line_info.path_decision();
ADEBUG << "Evaluating Obstacle: " << obstacle->Id();
// Obstacle is virtual.
if (obstacle->IsVirtual()) {
ADEBUG << " - It is virtual.";
return false;
}
// Obstacle is moving.
if (!obstacle->IsStatic() || obstacle->speed() > block_obstacle_min_speed) {
ADEBUG << " - It is non-static.";
return false;
}
// Obstacle is behind ADC.
if (obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) {
ADEBUG << " - It is behind ADC.";
return false;
}
// Obstacle is far away.
static constexpr double kAdcDistanceSidePassThreshold = 15.0;
if (obstacle->PerceptionSLBoundary().start_s() >
adc_sl_boundary.end_s() + kAdcDistanceSidePassThreshold) {
ADEBUG << " - It is too far ahead.";
return false;
}
// Obstacle is too close.
if (adc_sl_boundary.end_s() + min_front_sidepass_distance >
obstacle->PerceptionSLBoundary().start_s()) {
ADEBUG << " - It is too close to side-pass.";
return false;
}
// Obstacle is not blocking our path.
if (!IsBlockingDrivingPathObstacle(reference_line, obstacle)) {
ADEBUG << " - It is not blocking our way.";
return false;
}
// Obstacle is blocked by others too.
if (enable_obstacle_blocked_check &&
!IsParkedVehicle(reference_line, obstacle)) {
for (const auto* other_obstacle : path_decision.obstacles().Items()) {
if (other_obstacle->Id() == obstacle->Id()) {
continue;
}
if (other_obstacle->IsVirtual()) {
continue;
}
if (other_obstacle->PerceptionSLBoundary().start_l() >
obstacle->PerceptionSLBoundary().end_l() ||
other_obstacle->PerceptionSLBoundary().end_l() <
obstacle->PerceptionSLBoundary().start_l()) {
// not blocking the backside vehicle
continue;
}
double delta_s = other_obstacle->PerceptionSLBoundary().start_s() -
obstacle->PerceptionSLBoundary().end_s();
if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) {
continue;
}
// TODO(All): Fix the segmentation bug for large vehicles, otherwise
// the follow line will be problematic.
ADEBUG << " - It is blocked by others, too.";
return false;
}
}
ADEBUG << "IT IS BLOCKING!";
return true;
}
double GetDistanceBetweenADCAndObstacle(const Frame& frame,
const Obstacle* obstacle) {
const auto& reference_line_info = frame.reference_line_info().front();
const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();
double distance_between_adc_and_obstacle =
obstacle->PerceptionSLBoundary().start_s() - adc_sl_boundary.end_s();
return distance_between_adc_and_obstacle;
}
bool IsBlockingDrivingPathObstacle(const ReferenceLine& reference_line,
const Obstacle* obstacle) {
const double driving_width =
reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary());
const double adc_width =
VehicleConfigHelper::GetConfig().vehicle_param().width();
ADEBUG << " (driving width = " << driving_width
<< ", adc_width = " << adc_width << ")";
if (driving_width > adc_width + FLAGS_static_obstacle_nudge_l_buffer +
FLAGS_side_pass_driving_width_l_buffer) {
// TODO(jiacheng): make this a GFLAG:
// side_pass_context_.scenario_config_.min_l_nudge_buffer()
ADEBUG << "It is NOT blocking our path.";
return false;
}
ADEBUG << "It is blocking our path.";
return true;
}
bool IsParkedVehicle(const ReferenceLine& reference_line,
const Obstacle* obstacle) {
if (!FLAGS_enable_scenario_side_pass_multiple_parked_obstacles) {
return false;
}
double road_left_width = 0.0;
double road_right_width = 0.0;
double max_road_right_width = 0.0;
reference_line.GetRoadWidth(obstacle->PerceptionSLBoundary().start_s(),
&road_left_width, &road_right_width);
max_road_right_width = road_right_width;
reference_line.GetRoadWidth(obstacle->PerceptionSLBoundary().end_s(),
&road_left_width, &road_right_width);
max_road_right_width = std::max(max_road_right_width, road_right_width);
bool is_at_road_edge = std::abs(obstacle->PerceptionSLBoundary().start_l()) >
max_road_right_width - 0.1;
std::vector<std::shared_ptr<const hdmap::LaneInfo>> lanes;
auto obstacle_box = obstacle->PerceptionBoundingBox();
HDMapUtil::BaseMapPtr()->GetLanes(
common::util::PointFactory::ToPointENU(obstacle_box.center().x(),
obstacle_box.center().y()),
std::min(obstacle_box.width(), obstacle_box.length()), &lanes);
bool is_on_parking_lane = false;
if (lanes.size() == 1 &&
lanes.front()->lane().type() == apollo::hdmap::Lane::PARKING) {
is_on_parking_lane = true;
}
bool is_parked = is_on_parking_lane || is_at_road_edge;
return is_parked && obstacle->IsStatic();
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/message_process.cc
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/message_process.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include "cyber/common/file.h"
#include "cyber/record/record_reader.h"
#include "cyber/time/clock.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/point_factory.h"
#include "modules/common/util/util.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/common_msgs/map_msgs/map_lane.pb.h"
#include "modules/planning/common/feature_output.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/util/math_util.h"
namespace apollo {
namespace planning {
using apollo::canbus::Chassis;
using apollo::cyber::Clock;
using apollo::cyber::record::RecordMessage;
using apollo::cyber::record::RecordReader;
using apollo::dreamview::HMIStatus;
using apollo::hdmap::ClearAreaInfoConstPtr;
using apollo::hdmap::CrosswalkInfoConstPtr;
using apollo::hdmap::HDMapUtil;
using apollo::hdmap::JunctionInfoConstPtr;
using apollo::hdmap::LaneInfoConstPtr;
using apollo::hdmap::PNCJunctionInfoConstPtr;
using apollo::hdmap::SignalInfoConstPtr;
using apollo::hdmap::StopSignInfoConstPtr;
using apollo::hdmap::YieldSignInfoConstPtr;
using apollo::localization::LocalizationEstimate;
using apollo::perception::TrafficLightDetection;
using apollo::prediction::PredictionObstacle;
using apollo::prediction::PredictionObstacles;
using apollo::routing::RoutingResponse;
using apollo::storytelling::CloseToJunction;
using apollo::storytelling::Stories;
bool MessageProcess::Init(const PlanningConfig& planning_config) {
planning_config_.CopyFrom(planning_config);
map_m_["Sunnyvale"] = "sunnyvale";
map_m_["Sunnyvale Big Loop"] = "sunnyvale_big_loop";
map_m_["Sunnyvale With Two Offices"] = "sunnyvale_with_two_offices";
map_m_["Gomentum"] = "gomentum";
map_m_["Sunnyvale Loop"] = "sunnyvale_loop";
map_m_["San Mateo"] = "san_mateo";
map_name_ = FLAGS_map_dir.substr(FLAGS_map_dir.find_last_of("/") + 1);
obstacle_history_map_.clear();
if (FLAGS_planning_offline_learning) {
// offline process logging
log_file_.open(FLAGS_planning_data_dir + "/learning_data.log",
std::ios_base::out | std::ios_base::app);
start_time_ = std::chrono::system_clock::now();
std::time_t now = std::time(nullptr);
log_file_ << "UTC date and time: " << std::asctime(std::gmtime(&now))
<< "Local date and time: " << std::asctime(std::localtime(&now));
}
return true;
}
bool MessageProcess::Init(const PlanningConfig& planning_config,
const std::shared_ptr<DependencyInjector>& injector) {
injector_ = injector;
return Init(planning_config);
}
void MessageProcess::Close() {
FeatureOutput::Clear();
if (FLAGS_planning_offline_learning) {
// offline process logging
const std::string msg = absl::StrCat(
"Total learning_data_frame number: ", total_learning_data_frame_num_);
AINFO << msg;
log_file_ << msg << std::endl;
auto end_time = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end_time - start_time_;
log_file_ << "Time elapsed(sec): " << elapsed_seconds.count() << std::endl
<< std::endl;
log_file_.close();
}
}
void MessageProcess::OnChassis(const apollo::canbus::Chassis& chassis) {
chassis_feature_.set_message_timestamp_sec(chassis.header().timestamp_sec());
chassis_feature_.set_speed_mps(chassis.speed_mps());
chassis_feature_.set_throttle_percentage(chassis.throttle_percentage());
chassis_feature_.set_brake_percentage(chassis.brake_percentage());
chassis_feature_.set_steering_percentage(chassis.steering_percentage());
chassis_feature_.set_gear_location(chassis.gear_location());
}
void MessageProcess::OnHMIStatus(apollo::dreamview::HMIStatus hmi_status) {
const std::string& current_map = hmi_status.current_map();
if (map_m_.count(current_map) > 0) {
map_name_ = map_m_[current_map];
const std::string& map_base_folder = "/apollo/modules/map/data/";
FLAGS_map_dir = map_base_folder + map_name_;
}
}
void MessageProcess::OnLocalization(const LocalizationEstimate& le) {
if (last_localization_message_timestamp_sec_ == 0.0) {
last_localization_message_timestamp_sec_ = le.header().timestamp_sec();
}
const double time_diff =
le.header().timestamp_sec() - last_localization_message_timestamp_sec_;
if (time_diff < 1.0 / FLAGS_planning_loop_rate) {
// for RL_TEST, E2E_TEST or HYBRID_TEST skip this check so that first
// frame can proceed
if (!(planning_config_.learning_mode() == PlanningConfig::RL_TEST ||
planning_config_.learning_mode() == PlanningConfig::E2E_TEST ||
planning_config_.learning_mode() == PlanningConfig::HYBRID_TEST)) {
return;
}
}
if (time_diff >= (1.0 * 2 / FLAGS_planning_loop_rate)) {
const std::string msg = absl::StrCat(
"missing localization too long: time_stamp[",
le.header().timestamp_sec(), "] time_diff[", time_diff, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
}
last_localization_message_timestamp_sec_ = le.header().timestamp_sec();
localizations_.push_back(le);
while (!localizations_.empty()) {
if (localizations_.back().header().timestamp_sec() -
localizations_.front().header().timestamp_sec() <=
FLAGS_trajectory_time_length) {
break;
}
localizations_.pop_front();
}
ADEBUG << "OnLocalization: size[" << localizations_.size() << "] time_diff["
<< localizations_.back().header().timestamp_sec() -
localizations_.front().header().timestamp_sec()
<< "]";
// generate one frame data
LearningDataFrame learning_data_frame;
if (GenerateLearningDataFrame(&learning_data_frame)) {
// output
if (FLAGS_planning_offline_learning) {
// offline
FeatureOutput::InsertLearningDataFrame(record_file_, learning_data_frame);
} else {
// online
injector_->learning_based_data()->InsertLearningDataFrame(
learning_data_frame);
}
}
}
void MessageProcess::OnPrediction(
const PredictionObstacles& prediction_obstacles) {
prediction_obstacles_map_.clear();
for (int i = 0; i < prediction_obstacles.prediction_obstacle_size(); ++i) {
const auto& prediction_obstacle =
prediction_obstacles.prediction_obstacle(i);
const int obstacle_id = prediction_obstacle.perception_obstacle().id();
prediction_obstacles_map_[obstacle_id].CopyFrom(prediction_obstacle);
}
// erase obstacle history if obstacle not exist in current predictio msg
/* comment out to relax this check for now
std::unordered_map<int, std::list<PerceptionObstacleFeature>>::iterator
it = obstacle_history_map_.begin();
while (it != obstacle_history_map_.end()) {
const int obstacle_id = it->first;
if (prediction_obstacles_map_.count(obstacle_id) == 0) {
// not exist in current prediction msg
it = obstacle_history_map_.erase(it);
} else {
++it;
}
}
*/
// debug
// add to obstacle history
// for (const auto& m : obstacle_history_map_) {
// for (const auto& p : m.second) {
// AERROR << "obstacle_history_map_: " << m.first << "; "
// << p.DebugString();
// }
// }
// add to obstacle history
for (const auto& m : prediction_obstacles_map_) {
const auto& perception_obstale = m.second.perception_obstacle();
PerceptionObstacleFeature obstacle_trajectory_point;
obstacle_trajectory_point.set_timestamp_sec(perception_obstale.timestamp());
obstacle_trajectory_point.mutable_position()->CopyFrom(
perception_obstale.position());
obstacle_trajectory_point.set_theta(perception_obstale.theta());
obstacle_trajectory_point.mutable_velocity()->CopyFrom(
perception_obstale.velocity());
for (int j = 0; j < perception_obstale.polygon_point_size(); ++j) {
auto polygon_point = obstacle_trajectory_point.add_polygon_point();
polygon_point->CopyFrom(perception_obstale.polygon_point(j));
}
obstacle_trajectory_point.mutable_acceleration()->CopyFrom(
perception_obstale.acceleration());
obstacle_history_map_[m.first].back().timestamp_sec();
if (obstacle_history_map_[m.first].empty() ||
obstacle_trajectory_point.timestamp_sec() -
obstacle_history_map_[m.first].back().timestamp_sec() >
0) {
obstacle_history_map_[m.first].push_back(obstacle_trajectory_point);
} else {
// abnormal perception data: time_diff <= 0
const double time_diff =
obstacle_trajectory_point.timestamp_sec() -
obstacle_history_map_[m.first].back().timestamp_sec();
const std::string msg = absl::StrCat(
"DISCARD: obstacle_id[", m.first, "] last_timestamp_sec[",
obstacle_history_map_[m.first].back().timestamp_sec(),
"] timestamp_sec[", obstacle_trajectory_point.timestamp_sec(),
"] time_diff[", time_diff, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
}
auto& obstacle_history = obstacle_history_map_[m.first];
while (!obstacle_history.empty()) {
const double time_distance = obstacle_history.back().timestamp_sec() -
obstacle_history.front().timestamp_sec();
if (time_distance < FLAGS_learning_data_obstacle_history_time_sec) {
break;
}
obstacle_history.pop_front();
}
}
}
void MessageProcess::OnRoutingResponse(
const apollo::routing::RoutingResponse& routing_response) {
ADEBUG << "routing_response received at frame["
<< total_learning_data_frame_num_ << "]";
routing_response_.CopyFrom(routing_response);
}
void MessageProcess::OnStoryTelling(
const apollo::storytelling::Stories& stories) {
// clear area
if (stories.has_close_to_clear_area()) {
auto clear_area_tag = planning_tag_.mutable_clear_area();
clear_area_tag->set_id(stories.close_to_clear_area().id());
clear_area_tag->set_distance(stories.close_to_clear_area().distance());
}
// crosswalk
if (stories.has_close_to_crosswalk()) {
auto crosswalk_tag = planning_tag_.mutable_crosswalk();
crosswalk_tag->set_id(stories.close_to_crosswalk().id());
crosswalk_tag->set_distance(stories.close_to_crosswalk().distance());
}
// pnc_junction
if (stories.has_close_to_junction() &&
stories.close_to_junction().type() == CloseToJunction::PNC_JUNCTION) {
auto pnc_junction_tag = planning_tag_.mutable_pnc_junction();
pnc_junction_tag->set_id(stories.close_to_junction().id());
pnc_junction_tag->set_distance(stories.close_to_junction().distance());
}
// traffic_light
if (stories.has_close_to_signal()) {
auto signal_tag = planning_tag_.mutable_signal();
signal_tag->set_id(stories.close_to_signal().id());
signal_tag->set_distance(stories.close_to_signal().distance());
}
// stop_sign
if (stories.has_close_to_stop_sign()) {
auto stop_sign_tag = planning_tag_.mutable_stop_sign();
stop_sign_tag->set_id(stories.close_to_stop_sign().id());
stop_sign_tag->set_distance(stories.close_to_stop_sign().distance());
}
// yield_sign
if (stories.has_close_to_yield_sign()) {
auto yield_sign_tag = planning_tag_.mutable_yield_sign();
yield_sign_tag->set_id(stories.close_to_yield_sign().id());
yield_sign_tag->set_distance(stories.close_to_yield_sign().distance());
}
ADEBUG << planning_tag_.DebugString();
}
void MessageProcess::OnTrafficLightDetection(
const TrafficLightDetection& traffic_light_detection) {
// AINFO << "traffic_light_detection received at frame["
// << total_learning_data_frame_num_ << "]";
traffic_light_detection_message_timestamp_ =
traffic_light_detection.header().timestamp_sec();
traffic_lights_.clear();
for (int i = 0; i < traffic_light_detection.traffic_light_size(); ++i) {
TrafficLightFeature traffic_light;
traffic_light.set_color(traffic_light_detection.traffic_light(i).color());
traffic_light.set_id(traffic_light_detection.traffic_light(i).id());
traffic_light.set_confidence(
traffic_light_detection.traffic_light(i).confidence());
traffic_light.set_tracking_time(
traffic_light_detection.traffic_light(i).tracking_time());
traffic_light.set_remaining_time(
traffic_light_detection.traffic_light(i).remaining_time());
traffic_lights_.push_back(traffic_light);
}
}
void MessageProcess::ProcessOfflineData(const std::string& record_file) {
log_file_ << "Processing: " << record_file << std::endl;
record_file_ = record_file;
RecordReader reader(record_file);
if (!reader.IsValid()) {
AERROR << "Fail to open " << record_file;
return;
}
RecordMessage message;
while (reader.ReadMessage(&message)) {
if (message.channel_name ==
planning_config_.topic_config().chassis_topic()) {
Chassis chassis;
if (chassis.ParseFromString(message.content)) {
OnChassis(chassis);
}
} else if (message.channel_name ==
planning_config_.topic_config().localization_topic()) {
LocalizationEstimate localization;
if (localization.ParseFromString(message.content)) {
OnLocalization(localization);
}
} else if (message.channel_name ==
planning_config_.topic_config().hmi_status_topic()) {
HMIStatus hmi_status;
if (hmi_status.ParseFromString(message.content)) {
OnHMIStatus(hmi_status);
}
} else if (message.channel_name ==
planning_config_.topic_config().prediction_topic()) {
PredictionObstacles prediction_obstacles;
if (prediction_obstacles.ParseFromString(message.content)) {
OnPrediction(prediction_obstacles);
}
} else if (message.channel_name ==
planning_config_.topic_config().routing_response_topic()) {
RoutingResponse routing_response;
if (routing_response.ParseFromString(message.content)) {
OnRoutingResponse(routing_response);
}
} else if (message.channel_name ==
planning_config_.topic_config().story_telling_topic()) {
Stories stories;
if (stories.ParseFromString(message.content)) {
OnStoryTelling(stories);
}
} else if (message.channel_name == planning_config_.topic_config()
.traffic_light_detection_topic()) {
TrafficLightDetection traffic_light_detection;
if (traffic_light_detection.ParseFromString(message.content)) {
OnTrafficLightDetection(traffic_light_detection);
}
}
}
}
bool MessageProcess::GetADCCurrentRoutingIndex(
int* adc_road_index, int* adc_passage_index, double* adc_passage_s) {
if (localizations_.empty()) return false;
static constexpr double kRadius = 4.0;
const auto& pose = localizations_.back().pose();
std::vector<std::shared_ptr<const apollo::hdmap::LaneInfo>> lanes;
apollo::hdmap::HDMapUtil::BaseMapPtr()->GetLanes(pose.position(), kRadius,
&lanes);
for (auto& lane : lanes) {
for (int i = 0; i < routing_response_.road_size(); ++i) {
*adc_passage_s = 0;
for (int j = 0; j < routing_response_.road(i).passage_size(); ++j) {
double passage_s = 0;
for (int k = 0; k < routing_response_.road(i).passage(j).segment_size();
++k) {
const auto& segment = routing_response_.road(i).passage(j).segment(k);
passage_s += (segment.end_s() - segment.start_s());
if (lane->id().id() == segment.id()) {
*adc_road_index = i;
*adc_passage_index = j;
*adc_passage_s = passage_s;
return true;
}
}
}
}
}
return false;
}
apollo::hdmap::LaneInfoConstPtr MessageProcess::GetCurrentLane(
const apollo::common::PointENU& position) {
constexpr double kRadiusUnit = 0.1;
std::vector<std::shared_ptr<const apollo::hdmap::LaneInfo>> lanes;
for (int i = 1; i <= 10; ++i) {
apollo::hdmap::HDMapUtil::BaseMapPtr()->GetLanes(position, i * kRadiusUnit,
&lanes);
if (lanes.size() > 0) {
break;
}
}
for (auto& lane : lanes) {
for (int i = 0; i < routing_response_.road_size(); ++i) {
for (int j = 0; j < routing_response_.road(i).passage_size(); ++j) {
for (int k = 0; k < routing_response_.road(i).passage(j).segment_size();
++k) {
if (lane->id().id() ==
routing_response_.road(i).passage(j).segment(k).id()) {
return lane;
}
}
}
}
}
return nullptr;
}
int MessageProcess::GetADCCurrentInfo(ADCCurrentInfo* adc_curr_info) {
CHECK_NOTNULL(adc_curr_info);
if (localizations_.empty()) return -1;
// ADC current position / velocity / acc/ heading
const auto& adc_cur_pose = localizations_.back().pose();
adc_curr_info->adc_cur_position_ =
std::make_pair(adc_cur_pose.position().x(), adc_cur_pose.position().y());
adc_curr_info->adc_cur_velocity_ = std::make_pair(
adc_cur_pose.linear_velocity().x(), adc_cur_pose.linear_velocity().y());
adc_curr_info->adc_cur_acc_ =
std::make_pair(adc_cur_pose.linear_acceleration().x(),
adc_cur_pose.linear_acceleration().y());
adc_curr_info->adc_cur_heading_ = adc_cur_pose.heading();
return 1;
}
void MessageProcess::GenerateObstacleTrajectory(
const int frame_num, const int obstacle_id,
const ADCCurrentInfo& adc_curr_info, ObstacleFeature* obstacle_feature) {
auto obstacle_trajectory = obstacle_feature->mutable_obstacle_trajectory();
const auto& obstacle_history = obstacle_history_map_[obstacle_id];
for (const auto& obj_traj_point : obstacle_history) {
auto perception_obstacle_history =
obstacle_trajectory->add_perception_obstacle_history();
perception_obstacle_history->set_timestamp_sec(
obj_traj_point.timestamp_sec());
// convert position to relative coordinate
const auto& relative_posistion = util::WorldCoordToObjCoord(
std::make_pair(obj_traj_point.position().x(),
obj_traj_point.position().y()),
adc_curr_info.adc_cur_position_, adc_curr_info.adc_cur_heading_);
auto position = perception_obstacle_history->mutable_position();
position->set_x(relative_posistion.first);
position->set_y(relative_posistion.second);
// convert theta to relative coordinate
const double relative_theta = util::WorldAngleToObjAngle(
obj_traj_point.theta(), adc_curr_info.adc_cur_heading_);
perception_obstacle_history->set_theta(relative_theta);
// convert velocity to relative coordinate
const auto& relative_velocity = util::WorldCoordToObjCoord(
std::make_pair(obj_traj_point.velocity().x(),
obj_traj_point.velocity().y()),
adc_curr_info.adc_cur_velocity_, adc_curr_info.adc_cur_heading_);
auto velocity = perception_obstacle_history->mutable_velocity();
velocity->set_x(relative_velocity.first);
velocity->set_y(relative_velocity.second);
// convert acceleration to relative coordinate
const auto& relative_acc = util::WorldCoordToObjCoord(
std::make_pair(obj_traj_point.acceleration().x(),
obj_traj_point.acceleration().y()),
adc_curr_info.adc_cur_acc_, adc_curr_info.adc_cur_heading_);
auto acceleration = perception_obstacle_history->mutable_acceleration();
acceleration->set_x(relative_acc.first);
acceleration->set_y(relative_acc.second);
for (int i = 0; i < obj_traj_point.polygon_point_size(); ++i) {
// convert polygon_point(s) to relative coordinate
const auto& relative_point = util::WorldCoordToObjCoord(
std::make_pair(obj_traj_point.polygon_point(i).x(),
obj_traj_point.polygon_point(i).y()),
adc_curr_info.adc_cur_position_, adc_curr_info.adc_cur_heading_);
auto polygon_point = perception_obstacle_history->add_polygon_point();
polygon_point->set_x(relative_point.first);
polygon_point->set_y(relative_point.second);
}
}
}
void MessageProcess::GenerateObstaclePrediction(
const int frame_num,
const PredictionObstacle& prediction_obstacle,
const ADCCurrentInfo& adc_curr_info, ObstacleFeature* obstacle_feature) {
const auto obstacle_id = obstacle_feature->id();
auto obstacle_prediction = obstacle_feature->mutable_obstacle_prediction();
obstacle_prediction->set_timestamp_sec(prediction_obstacle.timestamp());
obstacle_prediction->set_predicted_period(
prediction_obstacle.predicted_period());
obstacle_prediction->mutable_intent()->CopyFrom(prediction_obstacle.intent());
obstacle_prediction->mutable_priority()->CopyFrom(
prediction_obstacle.priority());
obstacle_prediction->set_is_static(prediction_obstacle.is_static());
for (int i = 0; i < prediction_obstacle.trajectory_size(); ++i) {
const auto& obstacle_trajectory = prediction_obstacle.trajectory(i);
auto trajectory = obstacle_prediction->add_trajectory();
trajectory->set_probability(obstacle_trajectory.probability());
// TrajectoryPoint
for (int j = 0; j < obstacle_trajectory.trajectory_point_size(); ++j) {
const auto& obstacle_trajectory_point =
obstacle_trajectory.trajectory_point(j);
if (trajectory->trajectory_point_size() >0) {
const auto last_relative_time =
trajectory->trajectory_point(trajectory->trajectory_point_size()-1)
.trajectory_point().relative_time();
if (obstacle_trajectory_point.relative_time() < last_relative_time) {
const std::string msg = absl::StrCat(
"DISCARD prediction trajectory point: frame_num[", frame_num,
"] obstacle_id[", obstacle_id, "] last_relative_time[",
last_relative_time, "] relative_time[",
obstacle_trajectory_point.relative_time(), "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
continue;
}
}
auto trajectory_point = trajectory->add_trajectory_point();
auto path_point =
trajectory_point->mutable_trajectory_point()->mutable_path_point();
// convert path_point position to relative coordinate
const auto& relative_path_point = util::WorldCoordToObjCoord(
std::make_pair(obstacle_trajectory_point.path_point().x(),
obstacle_trajectory_point.path_point().y()),
adc_curr_info.adc_cur_position_, adc_curr_info.adc_cur_heading_);
path_point->set_x(relative_path_point.first);
path_point->set_y(relative_path_point.second);
// convert path_point theta to relative coordinate
const double relative_theta = util::WorldAngleToObjAngle(
obstacle_trajectory_point.path_point().theta(),
adc_curr_info.adc_cur_heading_);
path_point->set_theta(relative_theta);
path_point->set_s(obstacle_trajectory_point.path_point().s());
path_point->set_lane_id(obstacle_trajectory_point.path_point().lane_id());
const double timestamp_sec = prediction_obstacle.timestamp() +
obstacle_trajectory_point.relative_time();
trajectory_point->set_timestamp_sec(timestamp_sec);
auto tp = trajectory_point->mutable_trajectory_point();
tp->set_v(obstacle_trajectory_point.v());
tp->set_a(obstacle_trajectory_point.a());
tp->set_relative_time(obstacle_trajectory_point.relative_time());
tp->mutable_gaussian_info()->CopyFrom(
obstacle_trajectory_point.gaussian_info());
}
}
}
void MessageProcess::GenerateObstacleFeature(
LearningDataFrame* learning_data_frame) {
ADCCurrentInfo adc_curr_info;
if (GetADCCurrentInfo(&adc_curr_info) == -1) {
const std::string msg = absl::StrCat(
"fail to get ADC current info: frame_num[",
learning_data_frame->frame_num(), "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
return;
}
const int frame_num = learning_data_frame->frame_num();
for (const auto& m : prediction_obstacles_map_) {
auto obstacle_feature = learning_data_frame->add_obstacle();
const auto& perception_obstale = m.second.perception_obstacle();
obstacle_feature->set_id(m.first);
obstacle_feature->set_length(perception_obstale.length());
obstacle_feature->set_width(perception_obstale.width());
obstacle_feature->set_height(perception_obstale.height());
obstacle_feature->set_type(perception_obstale.type());
// obstacle history trajectory points
GenerateObstacleTrajectory(frame_num, m.first, adc_curr_info,
obstacle_feature);
// obstacle prediction
GenerateObstaclePrediction(frame_num, m.second, adc_curr_info,
obstacle_feature);
}
}
bool MessageProcess::GenerateLocalRouting(
const int frame_num,
RoutingResponseFeature* local_routing,
std::vector<std::string>* local_routing_lane_ids) {
local_routing->Clear();
local_routing_lane_ids->clear();
if (routing_response_.road_size() == 0 ||
routing_response_.road(0).passage_size() == 0 ||
routing_response_.road(0).passage(0).segment_size() == 0) {
const std::string msg = absl::StrCat(
"DISCARD: invalid routing_response. frame_num[", frame_num, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
return false;
}
// calculate road_length
std::vector<std::pair<std::string, double>> road_lengths;
for (int i = 0; i < routing_response_.road_size(); ++i) {
ADEBUG << "road_id[" << routing_response_.road(i).id() << "] passage_size["
<< routing_response_.road(i).passage_size() << "]";
double road_length = 0.0;
for (int j = 0; j < routing_response_.road(i).passage_size(); ++j) {
ADEBUG << " passage: segment_size["
<< routing_response_.road(i).passage(j).segment_size() << "]";
double passage_length = 0;
for (int k = 0; k < routing_response_.road(i).passage(j).segment_size();
++k) {
const auto& segment = routing_response_.road(i).passage(j).segment(k);
passage_length += (segment.end_s() - segment.start_s());
}
ADEBUG << " passage_length[" << passage_length << "]";
road_length = std::max(road_length, passage_length);
}
road_lengths.push_back(
std::make_pair(routing_response_.road(i).id(), road_length));
ADEBUG << " road_length[" << road_length << "]";
}
/* debug
for (size_t i = 0; i < road_lengths.size(); ++i) {
AERROR << i << ": " << road_lengths[i].first << "; "
<< road_lengths[i].second;
}
*/
int adc_road_index;
int adc_passage_index;
double adc_passage_s;
if (!GetADCCurrentRoutingIndex(&adc_road_index, &adc_passage_index,
&adc_passage_s) ||
adc_road_index < 0 || adc_passage_index < 0 || adc_passage_s < 0) {
// reset localization history
localizations_.clear();
const std::string msg = absl::StrCat(
"DISCARD: fail to locate ADC on routing. frame_num[",
frame_num, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
return false;
}
ADEBUG << "adc_road_index[" << adc_road_index << "] adc_passage_index["
<< adc_passage_index << "] adc_passage_s[" << adc_passage_s << "]";
constexpr double kLocalRoutingForwardLength = 200.0;
constexpr double kLocalRoutingBackwardLength = 100.0;
// local_routing start point
int local_routing_start_road_index = 0;
double local_routing_start_road_s = 0;
double backward_length = kLocalRoutingBackwardLength;
for (int i = adc_road_index; i >= 0; --i) {
const double road_length =
(i == adc_road_index ? adc_passage_s : road_lengths[i].second);
if (backward_length > road_length) {
backward_length -= road_length;
} else {
local_routing_start_road_index = i;
local_routing_start_road_s = road_length - backward_length;
ADEBUG << "local_routing_start_road_index["
<< local_routing_start_road_index
<< "] local_routing_start_road_s["
<< local_routing_start_road_s << "]";
break;
}
}
// local routing end point
int local_routing_end_road_index = routing_response_.road_size() - 1;
double local_routing_end_road_s =
road_lengths[local_routing_end_road_index].second;
double forwardward_length = kLocalRoutingForwardLength;
for (int i = adc_road_index; i < routing_response_.road_size(); ++i) {
const double road_length =
(i == adc_road_index ? road_lengths[i].second - adc_passage_s
: road_lengths[i].second);
if (forwardward_length > road_length) {
forwardward_length -= road_length;
} else {
local_routing_end_road_index = i;
local_routing_end_road_s =
(i == adc_road_index ? adc_passage_s + forwardward_length
: forwardward_length);
ADEBUG << "local_routing_end_road_index[" << local_routing_end_road_index
<< "] local_routing_end_road_s["
<< local_routing_end_road_s << "]";
break;
}
}
ADEBUG << "local_routing: start_road_index[" << local_routing_start_road_index
<< "] start_road_s[" << local_routing_start_road_s
<< "] end_road_index[" << local_routing_end_road_index
<< "] end_road_s[" << local_routing_end_road_s << "]";
bool local_routing_end = false;
int last_passage_index = adc_passage_index;
for (int i = local_routing_start_road_index;
i <= local_routing_end_road_index; ++i) {
if (local_routing_end) break;
const auto& road = routing_response_.road(i);
auto local_routing_road = local_routing->add_road();
local_routing_road->set_id(road.id());
for (int j = 0; j < road.passage_size(); ++j) {
const auto& passage = road.passage(j);
auto local_routing_passage = local_routing_road->add_passage();
local_routing_passage->set_can_exit(passage.can_exit());
local_routing_passage->set_change_lane_type(passage.change_lane_type());
double road_s = 0;
for (int k = 0; k < passage.segment_size(); ++k) {
const auto& lane_segment = passage.segment(k);
road_s += (lane_segment.end_s() - lane_segment.start_s());
// first road
if (i == local_routing_start_road_index &&
road_s < local_routing_start_road_s) {
continue;
}
local_routing_passage->add_segment()->CopyFrom(lane_segment);
ADEBUG << "ADD road[" << i << "] id[" << road.id() << "] passage[" << j
<< "] id[" << lane_segment.id() << "] length["
<< lane_segment.end_s() - lane_segment.start_s() << "]";
// set local_routing_lane_ids
if (i == adc_road_index) {
// adc_road_index, pick the passage where ADC is
if (j == adc_passage_index) {
local_routing_lane_ids->push_back(lane_segment.id());
ADEBUG << "ADD local_routing_lane_ids: road[" << i
<< "] passage[" << j << "]: " << lane_segment.id();
last_passage_index = j;
}
} else {
if (road.passage_size() == 1) {
// single passage
ADEBUG << "ADD local_routing_lane_ids: road[" << i
<< "] passage[" << j << "]: " << lane_segment.id();
local_routing_lane_ids->push_back(lane_segment.id());
last_passage_index = j;
} else {
// multi passages
if (i < adc_road_index) {
// road behind ADC position
if (j == adc_passage_index ||
(j == road.passage_size() - 1 &&
j < adc_passage_index)) {
ADEBUG << "ADD local_routing_lane_ids: road[" << i
<< "] passage[" << j << "] adc_passage_index["
<< adc_passage_index << "] passage_size["
<< road.passage_size() << "]: " << lane_segment.id();
local_routing_lane_ids->push_back(lane_segment.id());
}
} else {
// road in front of ADC position:
// pick the passage towards change-left
if (j == last_passage_index + 1 ||
(j == road.passage_size() - 1 &&
j < last_passage_index + 1)) {
ADEBUG << "ADD local_routing_lane_ids: road[" << i
<< "] passage[" << j << "] last_passage_index["
<< last_passage_index << "] passage_size["
<< road.passage_size() << "]: " << lane_segment.id();
local_routing_lane_ids->push_back(lane_segment.id());
last_passage_index = j;
}
}
}
}
// last road
if (i == local_routing_end_road_index &&
road_s >= local_routing_end_road_s) {
local_routing_end = true;
break;
}
}
}
}
// check local_routing: to filter out map mismatching frames
if (FLAGS_planning_offline_learning) {
for (size_t i = 0; i < local_routing_lane_ids->size(); ++i) {
const std::string lane_id = local_routing_lane_ids->at(i);
const auto& lane =
hdmap::HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id));
if (lane == nullptr) {
const std::string msg = absl::StrCat(
"DISCARD: fail to find local_routing_lane on map. frame_num[",
frame_num, "] lane[", lane_id, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
return false;
}
}
}
return true;
}
void MessageProcess::GenerateRoutingFeature(
const RoutingResponseFeature& local_routing,
const std::vector<std::string>& local_routing_lane_ids,
LearningDataFrame* learning_data_frame) {
auto routing = learning_data_frame->mutable_routing();
routing->Clear();
routing->mutable_routing_response()->mutable_measurement()->set_distance(
routing_response_.measurement().distance());
for (int i = 0; i < routing_response_.road_size(); ++i) {
routing->mutable_routing_response()->add_road()->CopyFrom(
routing_response_.road(i));
}
for (const auto& lane_id : local_routing_lane_ids) {
routing->add_local_routing_lane_id(lane_id);
}
routing->mutable_local_routing()->CopyFrom(local_routing);
const int frame_num = learning_data_frame->frame_num();
const int local_routing_lane_id_size = routing->local_routing_lane_id_size();
if (local_routing_lane_id_size == 0) {
const std::string msg = absl::StrCat(
"empty local_routing. frame_num[", frame_num, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
}
if (local_routing_lane_id_size > 100) {
const std::string msg = absl::StrCat(
"LARGE local_routing. frame_num[", frame_num,
"] local_routing_lane_id_size[", local_routing_lane_id_size, "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
}
ADEBUG << "local_routing: frame_num[" << frame_num
<< "] size[" << routing->local_routing_lane_id_size() << "]";
}
void MessageProcess::GenerateTrafficLightDetectionFeature(
LearningDataFrame* learning_data_frame) {
auto traffic_light_detection =
learning_data_frame->mutable_traffic_light_detection();
traffic_light_detection->set_message_timestamp_sec(
traffic_light_detection_message_timestamp_);
traffic_light_detection->clear_traffic_light();
for (const auto& tl : traffic_lights_) {
auto traffic_light = traffic_light_detection->add_traffic_light();
traffic_light->CopyFrom(tl);
}
}
void MessageProcess::GenerateADCTrajectoryPoints(
const std::list<LocalizationEstimate>& localizations,
LearningDataFrame* learning_data_frame) {
std::vector<LocalizationEstimate> localization_samples;
for (const auto& le : localizations) {
localization_samples.insert(localization_samples.begin(), le);
}
constexpr double kSearchRadius = 1.0;
std::string clear_area_id;
double clear_area_distance = 0.0;
std::string crosswalk_id;
double crosswalk_distance = 0.0;
std::string pnc_junction_id;
double pnc_junction_distance = 0.0;
std::string signal_id;
double signal_distance = 0.0;
std::string stop_sign_id;
double stop_sign_distance = 0.0;
std::string yield_sign_id;
double yield_sign_distance = 0.0;
int trajectory_point_index = 0;
std::vector<ADCTrajectoryPoint> adc_trajectory_points;
for (const auto& localization_sample : localization_samples) {
ADCTrajectoryPoint adc_trajectory_point;
adc_trajectory_point.set_timestamp_sec(
localization_sample.measurement_time());
auto trajectory_point = adc_trajectory_point.mutable_trajectory_point();
auto& pose = localization_sample.pose();
trajectory_point->mutable_path_point()->set_x(pose.position().x());
trajectory_point->mutable_path_point()->set_y(pose.position().y());
trajectory_point->mutable_path_point()->set_z(pose.position().z());
trajectory_point->mutable_path_point()->set_theta(pose.heading());
const double v =
std::sqrt(pose.linear_velocity().x() * pose.linear_velocity().x() +
pose.linear_velocity().y() * pose.linear_velocity().y());
trajectory_point->set_v(v);
const double a = std::sqrt(
pose.linear_acceleration().x() * pose.linear_acceleration().x() +
pose.linear_acceleration().y() * pose.linear_acceleration().y());
trajectory_point->set_a(a);
auto planning_tag = adc_trajectory_point.mutable_planning_tag();
// planning_tag: lane_turn
const auto& cur_point = common::util::PointFactory::ToPointENU(
pose.position().x(), pose.position().y(), pose.position().z());
LaneInfoConstPtr lane = GetCurrentLane(cur_point);
// lane_turn
apollo::hdmap::Lane::LaneTurn lane_turn = apollo::hdmap::Lane::NO_TURN;
if (lane != nullptr) {
lane_turn = lane->lane().turn();
}
planning_tag->set_lane_turn(lane_turn);
planning_tag_.set_lane_turn(lane_turn);
if (FLAGS_planning_offline_learning) {
// planning_tag: overlap tags
double point_distance = 0.0;
if (trajectory_point_index > 0) {
auto& next_point = adc_trajectory_points[trajectory_point_index - 1]
.trajectory_point()
.path_point();
point_distance = common::util::DistanceXY(next_point, cur_point);
}
common::PointENU hdmap_point;
hdmap_point.set_x(cur_point.x());
hdmap_point.set_y(cur_point.y());
// clear area
planning_tag->clear_clear_area();
std::vector<ClearAreaInfoConstPtr> clear_areas;
if (HDMapUtil::BaseMap().GetClearAreas(hdmap_point, kSearchRadius,
&clear_areas) == 0 &&
clear_areas.size() > 0) {
clear_area_id = clear_areas.front()->id().id();
clear_area_distance = 0.0;
} else {
if (!clear_area_id.empty()) {
clear_area_distance += point_distance;
}
}
if (!clear_area_id.empty()) {
planning_tag->mutable_clear_area()->set_id(clear_area_id);
planning_tag->mutable_clear_area()->set_distance(clear_area_distance);
}
// crosswalk
planning_tag->clear_crosswalk();
std::vector<CrosswalkInfoConstPtr> crosswalks;
if (HDMapUtil::BaseMap().GetCrosswalks(hdmap_point, kSearchRadius,
&crosswalks) == 0 &&
crosswalks.size() > 0) {
crosswalk_id = crosswalks.front()->id().id();
crosswalk_distance = 0.0;
} else {
if (!crosswalk_id.empty()) {
crosswalk_distance += point_distance;
}
}
if (!crosswalk_id.empty()) {
planning_tag->mutable_crosswalk()->set_id(crosswalk_id);
planning_tag->mutable_crosswalk()->set_distance(crosswalk_distance);
}
// pnc_junction
std::vector<PNCJunctionInfoConstPtr> pnc_junctions;
if (HDMapUtil::BaseMap().GetPNCJunctions(hdmap_point, kSearchRadius,
&pnc_junctions) == 0 &&
pnc_junctions.size() > 0) {
pnc_junction_id = pnc_junctions.front()->id().id();
pnc_junction_distance = 0.0;
} else {
if (!pnc_junction_id.empty()) {
pnc_junction_distance += point_distance;
}
}
if (!pnc_junction_id.empty()) {
planning_tag->mutable_pnc_junction()->set_id(pnc_junction_id);
planning_tag->mutable_pnc_junction()->set_distance(
pnc_junction_distance);
}
// signal
std::vector<SignalInfoConstPtr> signals;
if (HDMapUtil::BaseMap().GetSignals(hdmap_point, kSearchRadius,
&signals) == 0 &&
signals.size() > 0) {
signal_id = signals.front()->id().id();
signal_distance = 0.0;
} else {
if (!signal_id.empty()) {
signal_distance += point_distance;
}
}
if (!signal_id.empty()) {
planning_tag->mutable_signal()->set_id(signal_id);
planning_tag->mutable_signal()->set_distance(signal_distance);
}
// stop sign
std::vector<StopSignInfoConstPtr> stop_signs;
if (HDMapUtil::BaseMap().GetStopSigns(hdmap_point, kSearchRadius,
&stop_signs) == 0 &&
stop_signs.size() > 0) {
stop_sign_id = stop_signs.front()->id().id();
stop_sign_distance = 0.0;
} else {
if (!stop_sign_id.empty()) {
stop_sign_distance += point_distance;
}
}
if (!stop_sign_id.empty()) {
planning_tag->mutable_stop_sign()->set_id(stop_sign_id);
planning_tag->mutable_stop_sign()->set_distance(stop_sign_distance);
}
// yield sign
std::vector<YieldSignInfoConstPtr> yield_signs;
if (HDMapUtil::BaseMap().GetYieldSigns(hdmap_point, kSearchRadius,
&yield_signs) == 0 &&
yield_signs.size() > 0) {
yield_sign_id = yield_signs.front()->id().id();
yield_sign_distance = 0.0;
} else {
if (!yield_sign_id.empty()) {
yield_sign_distance += point_distance;
}
}
if (!yield_sign_id.empty()) {
planning_tag->mutable_yield_sign()->set_id(yield_sign_id);
planning_tag->mutable_yield_sign()->set_distance(yield_sign_distance);
}
}
adc_trajectory_points.push_back(adc_trajectory_point);
++trajectory_point_index;
}
// update learning data
std::reverse(adc_trajectory_points.begin(), adc_trajectory_points.end());
for (const auto& trajectory_point : adc_trajectory_points) {
auto adc_trajectory_point = learning_data_frame->add_adc_trajectory_point();
adc_trajectory_point->CopyFrom(trajectory_point);
}
if (adc_trajectory_points.size() <= 5) {
const std::string msg = absl::StrCat(
"too few adc_trajectory_points: frame_num[",
learning_data_frame->frame_num(), "] size[",
adc_trajectory_points.size(), "]");
AERROR << msg;
if (FLAGS_planning_offline_learning) {
log_file_ << msg << std::endl;
}
}
// AINFO << "number of ADC trajectory points in one frame: "
// << trajectory_point_index;
}
void MessageProcess::GeneratePlanningTag(
LearningDataFrame* learning_data_frame) {
auto planning_tag = learning_data_frame->mutable_planning_tag();
if (FLAGS_planning_offline_learning) {
planning_tag->set_lane_turn(planning_tag_.lane_turn());
} else {
if (planning_config_.learning_mode() != PlanningConfig::NO_LEARNING) {
// online learning
planning_tag->CopyFrom(planning_tag_);
}
}
}
bool MessageProcess::GenerateLearningDataFrame(
LearningDataFrame* learning_data_frame) {
const double start_timestamp = Clock::NowInSeconds();
RoutingResponseFeature local_routing;
std::vector<std::string> local_routing_lane_ids;
if (!GenerateLocalRouting(total_learning_data_frame_num_,
&local_routing, &local_routing_lane_ids)) {
return false;
}
// add timestamp_sec & frame_num
learning_data_frame->set_message_timestamp_sec(
localizations_.back().header().timestamp_sec());
learning_data_frame->set_frame_num(total_learning_data_frame_num_++);
// map_name
learning_data_frame->set_map_name(map_name_);
// planning_tag
GeneratePlanningTag(learning_data_frame);
// add chassis
auto chassis = learning_data_frame->mutable_chassis();
chassis->CopyFrom(chassis_feature_);
// add localization
auto localization = learning_data_frame->mutable_localization();
localization->set_message_timestamp_sec(
localizations_.back().header().timestamp_sec());
const auto& pose = localizations_.back().pose();
localization->mutable_position()->CopyFrom(pose.position());
localization->set_heading(pose.heading());
localization->mutable_linear_velocity()->CopyFrom(pose.linear_velocity());
localization->mutable_linear_acceleration()->CopyFrom(
pose.linear_acceleration());
localization->mutable_angular_velocity()->CopyFrom(pose.angular_velocity());
// add traffic_light
GenerateTrafficLightDetectionFeature(learning_data_frame);
// add routing
GenerateRoutingFeature(local_routing, local_routing_lane_ids,
learning_data_frame);
// add obstacle
GenerateObstacleFeature(learning_data_frame);
// add trajectory_points
GenerateADCTrajectoryPoints(localizations_, learning_data_frame);
const double end_timestamp = Clock::NowInSeconds();
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
ADEBUG << "MessageProcess: start_timestamp[" << start_timestamp
<< "] end_timestamp[" << end_timestamp << "] time_diff_ms["
<< time_diff_ms << "]";
return true;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/trajectory_stitcher.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "modules/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/planning/common/trajectory/publishable_trajectory.h"
#include "modules/planning/reference_line/reference_line.h"
namespace apollo {
namespace planning {
class TrajectoryStitcher {
public:
TrajectoryStitcher() = delete;
static void TransformLastPublishedTrajectory(
const double x_diff, const double y_diff, const double theta_diff,
PublishableTrajectory* prev_trajectory);
static std::vector<common::TrajectoryPoint> ComputeStitchingTrajectory(
const common::VehicleState& vehicle_state, const double current_timestamp,
const double planning_cycle_time, const size_t preserved_points_num,
const bool replan_by_offset, const PublishableTrajectory* prev_trajectory,
std::string* replan_reason);
static std::vector<common::TrajectoryPoint> ComputeReinitStitchingTrajectory(
const double planning_cycle_time,
const common::VehicleState& vehicle_state);
private:
static std::pair<double, double> ComputePositionProjection(
const double x, const double y,
const common::TrajectoryPoint& matched_trajectory_point);
static common::TrajectoryPoint ComputeTrajectoryPointFromVehicleState(
const double planning_cycle_time,
const common::VehicleState& vehicle_state);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/trajectory_evaluator.cc
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/trajectory_evaluator.h"
#include <algorithm>
#include <limits>
#include "absl/strings/str_cat.h"
#include "cyber/common/file.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/trajectory/discretized_trajectory.h"
#include "modules/planning/pipeline/evaluator_logger.h"
namespace apollo {
namespace planning {
void TrajectoryEvaluator::WriteLog(const std::string& msg) {
AERROR << msg;
if (FLAGS_planning_offline_learning) {
EvaluatorLogger::GetStream() << msg << std::endl;
}
}
void TrajectoryEvaluator::EvaluateTrajectoryByTime(
const int frame_num, const std::string& obstacle_id,
const std::vector<std::pair<double, CommonTrajectoryPointFeature>>&
trajectory,
const double start_point_timestamp_sec, const double delta_time,
std::vector<TrajectoryPointFeature>* evaluated_trajectory) {
if (trajectory.empty() || (fabs(trajectory.front().first -
start_point_timestamp_sec) < delta_time &&
fabs(trajectory.back().first -
start_point_timestamp_sec) < delta_time)) {
return;
}
std::vector<apollo::common::TrajectoryPoint> updated_trajectory;
for (const auto& tp : trajectory) {
// CommonTrajectoryPointFeature => common::TrajectoryPoint
double relative_time = tp.first - start_point_timestamp_sec;
apollo::common::TrajectoryPoint trajectory_point;
Convert(tp.second, relative_time, &trajectory_point);
updated_trajectory.push_back(trajectory_point);
}
if (trajectory.front().first > trajectory.back().first) {
std::reverse(updated_trajectory.begin(), updated_trajectory.end());
}
DiscretizedTrajectory discretized_trajectory;
double last_relative_time = std::numeric_limits<double>::lowest();
for (const auto& tp : updated_trajectory) {
// filter out abnormal perception data
if (tp.relative_time() > last_relative_time) {
discretized_trajectory.AppendTrajectoryPoint(tp);
last_relative_time = tp.relative_time();
} else {
const std::string msg = absl::StrCat(
"DISCARD trajectory point: frame_num[", frame_num, "] obstacle_id[",
obstacle_id, "] last_relative_time[", last_relative_time,
"] relatice_time[", tp.relative_time(), "] relative_time_diff[",
tp.relative_time() - last_relative_time, "]");
WriteLog(msg);
}
}
const int low_bound =
std::max(-150.0,
ceil(updated_trajectory.front().relative_time() / delta_time));
const int high_bound =
std::min(150.0,
floor(updated_trajectory.back().relative_time() / delta_time));
ADEBUG << "frame_num[" << frame_num << "] obstacle_id[" << obstacle_id
<< "] low[" << low_bound << "] high[" << high_bound << "]";
for (int i = low_bound; i <= high_bound; ++i) {
double timestamp_sec = start_point_timestamp_sec + i * delta_time;
double relative_time = i * delta_time;
auto tp = discretized_trajectory.Evaluate(relative_time);
// common::TrajectoryPoint => TrajectoryPointFeature
TrajectoryPointFeature trajectory_point;
Convert(tp, timestamp_sec, &trajectory_point);
evaluated_trajectory->push_back(trajectory_point);
}
}
void TrajectoryEvaluator::EvaluateADCTrajectory(
const double start_point_timestamp_sec, const double delta_time,
LearningDataFrame* learning_data_frame) {
std::vector<std::pair<double, CommonTrajectoryPointFeature>> trajectory;
for (const auto& adc_tp : learning_data_frame->adc_trajectory_point()) {
trajectory.push_back(
std::make_pair(adc_tp.timestamp_sec(), adc_tp.trajectory_point()));
}
if (trajectory.size() <= 1) {
const std::string msg = absl::StrCat(
"too short adc_trajectory_point. frame_num[",
learning_data_frame->frame_num(), "] size[", trajectory.size(), "]");
WriteLog(msg);
return;
}
learning_data_frame->clear_adc_trajectory_point();
if (fabs(trajectory.front().first - start_point_timestamp_sec) <=
delta_time) {
auto adc_trajectory_point = learning_data_frame->add_adc_trajectory_point();
adc_trajectory_point->set_timestamp_sec(trajectory.back().first);
adc_trajectory_point->mutable_trajectory_point()->CopyFrom(
trajectory.back().second);
const std::string msg =
absl::StrCat("too short adc_trajectory. frame_num[",
learning_data_frame->frame_num(), "] size[",
trajectory.size(), "] timestamp_diff[",
start_point_timestamp_sec - trajectory.front().first, "]");
WriteLog(msg);
return;
}
std::vector<TrajectoryPointFeature> evaluated_trajectory;
EvaluateTrajectoryByTime(learning_data_frame->frame_num(), "adc_trajectory",
trajectory, start_point_timestamp_sec, delta_time,
&evaluated_trajectory);
ADEBUG << "frame_num[" << learning_data_frame->frame_num()
<< "] orig adc_trajectory[" << trajectory.size()
<< "] evaluated_trajectory_size[" << evaluated_trajectory.size()
<< "]";
for (const auto& tp : evaluated_trajectory) {
if (tp.trajectory_point().relative_time() <= 0.0 &&
tp.trajectory_point().relative_time() >=
-FLAGS_trajectory_time_length) {
auto adc_trajectory_point =
learning_data_frame->add_adc_trajectory_point();
adc_trajectory_point->set_timestamp_sec(tp.timestamp_sec());
adc_trajectory_point->mutable_trajectory_point()->CopyFrom(
tp.trajectory_point());
} else {
const std::string msg =
absl::StrCat("DISCARD adc_trajectory_point. frame_num[",
learning_data_frame->frame_num(), "] size[",
evaluated_trajectory.size(), "] relative_time[",
tp.trajectory_point().relative_time(), "]");
WriteLog(msg);
}
}
}
void TrajectoryEvaluator::EvaluateADCFutureTrajectory(
const int frame_num,
const std::vector<TrajectoryPointFeature>& adc_future_trajectory,
const double start_point_timestamp_sec, const double delta_time,
std::vector<TrajectoryPointFeature>* evaluated_adc_future_trajectory) {
evaluated_adc_future_trajectory->clear();
std::vector<std::pair<double, CommonTrajectoryPointFeature>> trajectory;
for (const auto& adc_future_trajectory_point : adc_future_trajectory) {
trajectory.push_back(
std::make_pair(adc_future_trajectory_point.timestamp_sec(),
adc_future_trajectory_point.trajectory_point()));
}
if (trajectory.size() <= 1) {
const std::string msg =
absl::StrCat("too short adc_future_trajectory. frame_num[", frame_num,
"] size[", trajectory.size(), "]");
WriteLog(msg);
return;
}
if (fabs(trajectory.back().first - start_point_timestamp_sec) <= delta_time) {
const std::string msg =
absl::StrCat("too short adc_future_trajectory. frame_num[", frame_num,
"] size[", trajectory.size(), "] time_range[",
trajectory.back().first - start_point_timestamp_sec, "]");
WriteLog(msg);
return;
}
std::vector<TrajectoryPointFeature> evaluated_trajectory;
EvaluateTrajectoryByTime(frame_num, "adc_future_trajectory", trajectory,
start_point_timestamp_sec, delta_time,
&evaluated_trajectory);
ADEBUG << "frame_num[" << frame_num << "] orig adc_future_trajectory["
<< trajectory.size() << "] evaluated_trajectory_size["
<< evaluated_trajectory.size() << "]";
if (evaluated_trajectory.empty()) {
const std::string msg = absl::StrCat(
"WARNING: adc_future_trajectory not long enough. ", "frame_num[",
frame_num, "] size[", evaluated_trajectory.size(), "]");
WriteLog(msg);
} else {
const double time_range =
evaluated_trajectory.back().timestamp_sec() - start_point_timestamp_sec;
if (time_range < FLAGS_trajectory_time_length) {
const std::string msg = absl::StrCat(
"WARNING: adc_future_trajectory not long enough. ", "frame_num[",
frame_num, "] size[", evaluated_trajectory.size(), "] time_range[",
time_range, "]");
WriteLog(msg);
}
}
for (const auto& tp : evaluated_trajectory) {
if (tp.trajectory_point().relative_time() > 0.0 &&
tp.trajectory_point().relative_time() <= FLAGS_trajectory_time_length) {
evaluated_adc_future_trajectory->push_back(tp);
} else {
const std::string msg = absl::StrCat(
"DISCARD adc_future_trajectory_point. frame_num[", frame_num,
"] size[", evaluated_trajectory.size(), "] relative_time[",
tp.trajectory_point().relative_time(), "]");
WriteLog(msg);
}
}
}
void TrajectoryEvaluator::EvaluateObstacleTrajectory(
const double start_point_timestamp_sec, const double delta_time,
LearningDataFrame* learning_data_frame) {
for (int i = 0; i < learning_data_frame->obstacle_size(); ++i) {
const int obstacle_id = learning_data_frame->obstacle(i).id();
const auto obstacle_trajectory =
learning_data_frame->obstacle(i).obstacle_trajectory();
std::vector<std::pair<double, CommonTrajectoryPointFeature>> trajectory;
for (const auto& perception_obstacle :
obstacle_trajectory.perception_obstacle_history()) {
CommonTrajectoryPointFeature trajectory_point;
trajectory_point.mutable_path_point()->set_x(
perception_obstacle.position().x());
trajectory_point.mutable_path_point()->set_y(
perception_obstacle.position().y());
trajectory_point.mutable_path_point()->set_z(
perception_obstacle.position().z());
trajectory_point.mutable_path_point()->set_theta(
perception_obstacle.theta());
const double v = std::sqrt(perception_obstacle.velocity().x() *
perception_obstacle.velocity().x() +
perception_obstacle.velocity().y() *
perception_obstacle.velocity().y());
trajectory_point.set_v(v);
const double a = std::sqrt(perception_obstacle.acceleration().x() *
perception_obstacle.acceleration().x() +
perception_obstacle.acceleration().y() *
perception_obstacle.acceleration().y());
trajectory_point.set_a(a);
trajectory.push_back(std::make_pair(perception_obstacle.timestamp_sec(),
trajectory_point));
}
std::vector<TrajectoryPointFeature> evaluated_trajectory;
if (trajectory.size() == 1 ||
fabs(trajectory.front().first - start_point_timestamp_sec)
<= delta_time ||
fabs(trajectory.front().first - trajectory.back().first)
<= delta_time) {
ADEBUG << "too short obstacle_trajectory. frame_num["
<< learning_data_frame->frame_num() << "] obstacle_id["
<< obstacle_id << "] size[" << trajectory.size()
<< "] timestamp_diff["
<< start_point_timestamp_sec - trajectory.front().first
<< "] time_range["
<< fabs(trajectory.front().first - trajectory.back().first) << "]";
// pick at lease one point regardless of short timestamp,
// to avoid model failure
TrajectoryPointFeature trajectory_point;
trajectory_point.set_timestamp_sec(trajectory.front().first);
trajectory_point.mutable_trajectory_point()->CopyFrom(
trajectory.front().second);
evaluated_trajectory.push_back(trajectory_point);
} else {
EvaluateTrajectoryByTime(learning_data_frame->frame_num(),
std::to_string(obstacle_id), trajectory,
start_point_timestamp_sec, delta_time,
&evaluated_trajectory);
ADEBUG << "frame_num[" << learning_data_frame->frame_num()
<< "] obstacle_id[" << obstacle_id
<< "] orig obstacle_trajectory[" << trajectory.size()
<< "] evaluated_trajectory_size[" << evaluated_trajectory.size()
<< "]";
}
// update learning_data
learning_data_frame->mutable_obstacle(i)
->mutable_obstacle_trajectory()
->clear_evaluated_trajectory_point();
for (const auto& tp : evaluated_trajectory) {
auto evaluated_trajectory_point = learning_data_frame->mutable_obstacle(i)
->mutable_obstacle_trajectory()
->add_evaluated_trajectory_point();
evaluated_trajectory_point->set_timestamp_sec(tp.timestamp_sec());
evaluated_trajectory_point->mutable_trajectory_point()->CopyFrom(
tp.trajectory_point());
}
}
}
void TrajectoryEvaluator::EvaluateObstaclePredictionTrajectory(
const double start_point_timestamp_sec, const double delta_time,
LearningDataFrame* learning_data_frame) {
for (int i = 0; i < learning_data_frame->obstacle_size(); ++i) {
const int obstacle_id = learning_data_frame->obstacle(i).id();
const auto obstacle_prediction =
learning_data_frame->obstacle(i).obstacle_prediction();
for (int j = 0; j < obstacle_prediction.trajectory_size(); ++j) {
const auto obstacle_prediction_trajectory =
obstacle_prediction.trajectory(j);
std::vector<std::pair<double, CommonTrajectoryPointFeature>> trajectory;
for (const auto& trajectory_point :
obstacle_prediction_trajectory.trajectory_point()) {
const double timestamp_sec =
obstacle_prediction.timestamp_sec() +
trajectory_point.trajectory_point().relative_time();
trajectory.push_back(
std::make_pair(timestamp_sec, trajectory_point.trajectory_point()));
}
if (fabs(trajectory.back().first - start_point_timestamp_sec) <=
delta_time) {
ADEBUG << "too short obstacle_prediction_trajectory. frame_num["
<< learning_data_frame->frame_num() << "] obstacle_id["
<< obstacle_id << "] size[" << trajectory.size()
<< "] timestamp_diff["
<< trajectory.back().first - start_point_timestamp_sec << "]";
continue;
}
std::vector<TrajectoryPointFeature> evaluated_trajectory;
EvaluateTrajectoryByTime(learning_data_frame->frame_num(),
std::to_string(obstacle_id), trajectory,
start_point_timestamp_sec, delta_time,
&evaluated_trajectory);
ADEBUG << "frame_num[" << learning_data_frame->frame_num()
<< "] obstacle_id[" << obstacle_id
<< "orig obstacle_prediction_trajectory[" << trajectory.size()
<< "] evaluated_trajectory_size[" << evaluated_trajectory.size()
<< "]";
// update learning_data
learning_data_frame->mutable_obstacle(i)
->mutable_obstacle_prediction()
->mutable_trajectory(j)
->clear_trajectory_point();
for (const auto& tp : evaluated_trajectory) {
auto obstacle_prediction_trajectory_point =
learning_data_frame->mutable_obstacle(i)
->mutable_obstacle_prediction()
->mutable_trajectory(j)
->add_trajectory_point();
obstacle_prediction_trajectory_point->set_timestamp_sec(
tp.timestamp_sec());
obstacle_prediction_trajectory_point->mutable_trajectory_point()
->CopyFrom(tp.trajectory_point());
}
}
}
}
void TrajectoryEvaluator::Convert(const CommonTrajectoryPointFeature& tp,
const double relative_time,
common::TrajectoryPoint* trajectory_point) {
auto path_point = trajectory_point->mutable_path_point();
path_point->set_x(tp.path_point().x());
path_point->set_y(tp.path_point().y());
path_point->set_z(tp.path_point().z());
path_point->set_theta(tp.path_point().theta());
path_point->set_s(tp.path_point().s());
path_point->set_lane_id(tp.path_point().lane_id());
trajectory_point->set_v(tp.v());
trajectory_point->set_a(tp.a());
trajectory_point->set_relative_time(relative_time);
trajectory_point->mutable_gaussian_info()->CopyFrom(tp.gaussian_info());
}
void TrajectoryEvaluator::Convert(const common::TrajectoryPoint& tp,
const double timestamp_sec,
TrajectoryPointFeature* trajectory_point) {
trajectory_point->set_timestamp_sec(timestamp_sec);
auto path_point =
trajectory_point->mutable_trajectory_point()->mutable_path_point();
path_point->set_x(tp.path_point().x());
path_point->set_y(tp.path_point().y());
path_point->set_z(tp.path_point().z());
path_point->set_theta(tp.path_point().theta());
path_point->set_s(tp.path_point().s());
path_point->set_lane_id(tp.path_point().lane_id());
trajectory_point->mutable_trajectory_point()->set_v(tp.v());
trajectory_point->mutable_trajectory_point()->set_a(tp.a());
trajectory_point->mutable_trajectory_point()->set_relative_time(
tp.relative_time());
trajectory_point->mutable_trajectory_point()
->mutable_gaussian_info()
->CopyFrom(tp.gaussian_info());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/obstacle.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/obstacle.h"
#include <algorithm>
#include <utility>
#include "cyber/common/log.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/util/map_util.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/speed/st_boundary.h"
namespace apollo {
namespace planning {
using apollo::common::VehicleConfigHelper;
using apollo::common::util::FindOrDie;
using apollo::perception::PerceptionObstacle;
using apollo::prediction::ObstaclePriority;
namespace {
const double kStBoundaryDeltaS = 0.2; // meters
const double kStBoundarySparseDeltaS = 1.0; // meters
const double kStBoundaryDeltaT = 0.05; // seconds
} // namespace
const std::unordered_map<ObjectDecisionType::ObjectTagCase, int,
Obstacle::ObjectTagCaseHash>
Obstacle::s_longitudinal_decision_safety_sorter_ = {
{ObjectDecisionType::kIgnore, 0},
{ObjectDecisionType::kOvertake, 100},
{ObjectDecisionType::kFollow, 300},
{ObjectDecisionType::kYield, 400},
{ObjectDecisionType::kStop, 500}};
const std::unordered_map<ObjectDecisionType::ObjectTagCase, int,
Obstacle::ObjectTagCaseHash>
Obstacle::s_lateral_decision_safety_sorter_ = {
{ObjectDecisionType::kIgnore, 0}, {ObjectDecisionType::kNudge, 100}};
Obstacle::Obstacle(const std::string& id,
const PerceptionObstacle& perception_obstacle,
const ObstaclePriority::Priority& obstacle_priority,
const bool is_static)
: id_(id),
perception_id_(perception_obstacle.id()),
perception_obstacle_(perception_obstacle),
perception_bounding_box_({perception_obstacle_.position().x(),
perception_obstacle_.position().y()},
perception_obstacle_.theta(),
perception_obstacle_.length(),
perception_obstacle_.width()) {
is_caution_level_obstacle_ = (obstacle_priority == ObstaclePriority::CAUTION);
std::vector<common::math::Vec2d> polygon_points;
if (FLAGS_use_navigation_mode ||
perception_obstacle.polygon_point_size() <= 2) {
perception_bounding_box_.GetAllCorners(&polygon_points);
} else {
ACHECK(perception_obstacle.polygon_point_size() > 2)
<< "object " << id << "has less than 3 polygon points";
for (const auto& point : perception_obstacle.polygon_point()) {
polygon_points.emplace_back(point.x(), point.y());
}
}
ACHECK(common::math::Polygon2d::ComputeConvexHull(polygon_points,
&perception_polygon_))
<< "object[" << id << "] polygon is not a valid convex hull.\n"
<< perception_obstacle.DebugString();
is_static_ = (is_static || obstacle_priority == ObstaclePriority::IGNORE);
is_virtual_ = (perception_obstacle.id() < 0);
speed_ = std::hypot(perception_obstacle.velocity().x(),
perception_obstacle.velocity().y());
}
Obstacle::Obstacle(const std::string& id,
const PerceptionObstacle& perception_obstacle,
const prediction::Trajectory& trajectory,
const ObstaclePriority::Priority& obstacle_priority,
const bool is_static)
: Obstacle(id, perception_obstacle, obstacle_priority, is_static) {
trajectory_ = trajectory;
auto& trajectory_points = *trajectory_.mutable_trajectory_point();
double cumulative_s = 0.0;
if (trajectory_points.size() > 0) {
trajectory_points[0].mutable_path_point()->set_s(0.0);
}
for (int i = 1; i < trajectory_points.size(); ++i) {
const auto& prev = trajectory_points[i - 1];
const auto& cur = trajectory_points[i];
if (prev.relative_time() >= cur.relative_time()) {
AERROR << "prediction time is not increasing."
<< "current point: " << cur.ShortDebugString()
<< "previous point: " << prev.ShortDebugString();
}
cumulative_s +=
common::util::DistanceXY(prev.path_point(), cur.path_point());
trajectory_points[i].mutable_path_point()->set_s(cumulative_s);
}
}
common::TrajectoryPoint Obstacle::GetPointAtTime(
const double relative_time) const {
const auto& points = trajectory_.trajectory_point();
if (points.size() < 2) {
common::TrajectoryPoint point;
point.mutable_path_point()->set_x(perception_obstacle_.position().x());
point.mutable_path_point()->set_y(perception_obstacle_.position().y());
point.mutable_path_point()->set_z(perception_obstacle_.position().z());
point.mutable_path_point()->set_theta(perception_obstacle_.theta());
point.mutable_path_point()->set_s(0.0);
point.mutable_path_point()->set_kappa(0.0);
point.mutable_path_point()->set_dkappa(0.0);
point.mutable_path_point()->set_ddkappa(0.0);
point.set_v(0.0);
point.set_a(0.0);
point.set_relative_time(0.0);
return point;
} else {
auto comp = [](const common::TrajectoryPoint p, const double time) {
return p.relative_time() < time;
};
auto it_lower =
std::lower_bound(points.begin(), points.end(), relative_time, comp);
if (it_lower == points.begin()) {
return *points.begin();
} else if (it_lower == points.end()) {
return *points.rbegin();
}
return common::math::InterpolateUsingLinearApproximation(
*(it_lower - 1), *it_lower, relative_time);
}
}
common::math::Box2d Obstacle::GetBoundingBox(
const common::TrajectoryPoint& point) const {
return common::math::Box2d({point.path_point().x(), point.path_point().y()},
point.path_point().theta(),
perception_obstacle_.length(),
perception_obstacle_.width());
}
bool Obstacle::IsValidPerceptionObstacle(const PerceptionObstacle& obstacle) {
if (obstacle.length() <= 0.0) {
AERROR << "invalid obstacle length:" << obstacle.length();
return false;
}
if (obstacle.width() <= 0.0) {
AERROR << "invalid obstacle width:" << obstacle.width();
return false;
}
if (obstacle.height() <= 0.0) {
AERROR << "invalid obstacle height:" << obstacle.height();
return false;
}
if (obstacle.has_velocity()) {
if (std::isnan(obstacle.velocity().x()) ||
std::isnan(obstacle.velocity().y())) {
AERROR << "invalid obstacle velocity:"
<< obstacle.velocity().DebugString();
return false;
}
}
for (auto pt : obstacle.polygon_point()) {
if (std::isnan(pt.x()) || std::isnan(pt.y())) {
AERROR << "invalid obstacle polygon point:" << pt.DebugString();
return false;
}
}
return true;
}
std::list<std::unique_ptr<Obstacle>> Obstacle::CreateObstacles(
const prediction::PredictionObstacles& predictions) {
std::list<std::unique_ptr<Obstacle>> obstacles;
for (const auto& prediction_obstacle : predictions.prediction_obstacle()) {
if (!IsValidPerceptionObstacle(prediction_obstacle.perception_obstacle())) {
AERROR << "Invalid perception obstacle: "
<< prediction_obstacle.perception_obstacle().DebugString();
continue;
}
const auto perception_id =
std::to_string(prediction_obstacle.perception_obstacle().id());
if (prediction_obstacle.trajectory().empty()) {
obstacles.emplace_back(
new Obstacle(perception_id, prediction_obstacle.perception_obstacle(),
prediction_obstacle.priority().priority(),
prediction_obstacle.is_static()));
continue;
}
int trajectory_index = 0;
for (const auto& trajectory : prediction_obstacle.trajectory()) {
bool is_valid_trajectory = true;
for (const auto& point : trajectory.trajectory_point()) {
if (!IsValidTrajectoryPoint(point)) {
AERROR << "obj:" << perception_id
<< " TrajectoryPoint: " << trajectory.ShortDebugString()
<< " is NOT valid.";
is_valid_trajectory = false;
break;
}
}
if (!is_valid_trajectory) {
continue;
}
const std::string obstacle_id =
absl::StrCat(perception_id, "_", trajectory_index);
obstacles.emplace_back(
new Obstacle(obstacle_id, prediction_obstacle.perception_obstacle(),
trajectory, prediction_obstacle.priority().priority(),
prediction_obstacle.is_static()));
++trajectory_index;
}
}
return obstacles;
}
std::unique_ptr<Obstacle> Obstacle::CreateStaticVirtualObstacles(
const std::string& id, const common::math::Box2d& obstacle_box) {
// create a "virtual" perception_obstacle
perception::PerceptionObstacle perception_obstacle;
// simulator needs a valid integer
size_t negative_id = std::hash<std::string>{}(id);
// set the first bit to 1 so negative_id became negative number
negative_id |= (0x1 << 31);
perception_obstacle.set_id(static_cast<int32_t>(negative_id));
perception_obstacle.mutable_position()->set_x(obstacle_box.center().x());
perception_obstacle.mutable_position()->set_y(obstacle_box.center().y());
perception_obstacle.set_theta(obstacle_box.heading());
perception_obstacle.mutable_velocity()->set_x(0);
perception_obstacle.mutable_velocity()->set_y(0);
perception_obstacle.set_length(obstacle_box.length());
perception_obstacle.set_width(obstacle_box.width());
perception_obstacle.set_height(FLAGS_virtual_stop_wall_height);
perception_obstacle.set_type(
perception::PerceptionObstacle::UNKNOWN_UNMOVABLE);
perception_obstacle.set_tracking_time(1.0);
std::vector<common::math::Vec2d> corner_points;
obstacle_box.GetAllCorners(&corner_points);
for (const auto& corner_point : corner_points) {
auto* point = perception_obstacle.add_polygon_point();
point->set_x(corner_point.x());
point->set_y(corner_point.y());
}
auto* obstacle =
new Obstacle(id, perception_obstacle, ObstaclePriority::NORMAL, true);
obstacle->is_virtual_ = true;
return std::unique_ptr<Obstacle>(obstacle);
}
bool Obstacle::IsValidTrajectoryPoint(const common::TrajectoryPoint& point) {
return !((!point.has_path_point()) || std::isnan(point.path_point().x()) ||
std::isnan(point.path_point().y()) ||
std::isnan(point.path_point().z()) ||
std::isnan(point.path_point().kappa()) ||
std::isnan(point.path_point().s()) ||
std::isnan(point.path_point().dkappa()) ||
std::isnan(point.path_point().ddkappa()) || std::isnan(point.v()) ||
std::isnan(point.a()) || std::isnan(point.relative_time()));
}
void Obstacle::SetPerceptionSlBoundary(const SLBoundary& sl_boundary) {
sl_boundary_ = sl_boundary;
}
double Obstacle::MinRadiusStopDistance(
const common::VehicleParam& vehicle_param) const {
if (min_radius_stop_distance_ > 0) {
return min_radius_stop_distance_;
}
static constexpr double stop_distance_buffer = 0.5;
const double min_turn_radius = VehicleConfigHelper::MinSafeTurnRadius();
double lateral_diff =
vehicle_param.width() / 2.0 + std::max(std::fabs(sl_boundary_.start_l()),
std::fabs(sl_boundary_.end_l()));
const double kEpison = 1e-5;
lateral_diff = std::min(lateral_diff, min_turn_radius - kEpison);
double stop_distance =
std::sqrt(std::fabs(min_turn_radius * min_turn_radius -
(min_turn_radius - lateral_diff) *
(min_turn_radius - lateral_diff))) +
stop_distance_buffer;
stop_distance -= vehicle_param.front_edge_to_center();
stop_distance = std::min(stop_distance, FLAGS_max_stop_distance_obstacle);
stop_distance = std::max(stop_distance, FLAGS_min_stop_distance_obstacle);
return stop_distance;
}
void Obstacle::BuildReferenceLineStBoundary(const ReferenceLine& reference_line,
const double adc_start_s) {
const auto& adc_param =
VehicleConfigHelper::Instance()->GetConfig().vehicle_param();
const double half_adc_width = adc_param.width() / 2;
if (is_static_ || trajectory_.trajectory_point().empty()) {
std::vector<std::pair<STPoint, STPoint>> point_pairs;
double start_s = sl_boundary_.start_s();
double end_s = sl_boundary_.end_s();
if (end_s - start_s < kStBoundaryDeltaS) {
end_s = start_s + kStBoundaryDeltaS;
}
if (!reference_line.IsBlockRoad(perception_bounding_box_, half_adc_width)) {
return;
}
point_pairs.emplace_back(STPoint(start_s - adc_start_s, 0.0),
STPoint(end_s - adc_start_s, 0.0));
point_pairs.emplace_back(STPoint(start_s - adc_start_s, FLAGS_st_max_t),
STPoint(end_s - adc_start_s, FLAGS_st_max_t));
reference_line_st_boundary_ = STBoundary(point_pairs);
} else {
if (BuildTrajectoryStBoundary(reference_line, adc_start_s,
&reference_line_st_boundary_)) {
ADEBUG << "Found st_boundary for obstacle " << id_;
ADEBUG << "st_boundary: min_t = " << reference_line_st_boundary_.min_t()
<< ", max_t = " << reference_line_st_boundary_.max_t()
<< ", min_s = " << reference_line_st_boundary_.min_s()
<< ", max_s = " << reference_line_st_boundary_.max_s();
} else {
ADEBUG << "No st_boundary for obstacle " << id_;
}
}
}
bool Obstacle::BuildTrajectoryStBoundary(const ReferenceLine& reference_line,
const double adc_start_s,
STBoundary* const st_boundary) {
if (!IsValidObstacle(perception_obstacle_)) {
AERROR << "Fail to build trajectory st boundary because object is not "
"valid. PerceptionObstacle: "
<< perception_obstacle_.DebugString();
return false;
}
const double object_width = perception_obstacle_.width();
const double object_length = perception_obstacle_.length();
const auto& trajectory_points = trajectory_.trajectory_point();
if (trajectory_points.empty()) {
AWARN << "object " << id_ << " has no trajectory points";
return false;
}
const auto& adc_param =
VehicleConfigHelper::Instance()->GetConfig().vehicle_param();
const double adc_length = adc_param.length();
const double adc_half_length = adc_length / 2.0;
const double adc_width = adc_param.width();
common::math::Box2d min_box({0, 0}, 1.0, 1.0, 1.0);
common::math::Box2d max_box({0, 0}, 1.0, 1.0, 1.0);
std::vector<std::pair<STPoint, STPoint>> polygon_points;
SLBoundary last_sl_boundary;
int last_index = 0;
for (int i = 1; i < trajectory_points.size(); ++i) {
ADEBUG << "last_sl_boundary: " << last_sl_boundary.ShortDebugString();
const auto& first_traj_point = trajectory_points[i - 1];
const auto& second_traj_point = trajectory_points[i];
const auto& first_point = first_traj_point.path_point();
const auto& second_point = second_traj_point.path_point();
double object_moving_box_length =
object_length + common::util::DistanceXY(first_point, second_point);
common::math::Vec2d center((first_point.x() + second_point.x()) / 2.0,
(first_point.y() + second_point.y()) / 2.0);
common::math::Box2d object_moving_box(
center, first_point.theta(), object_moving_box_length, object_width);
SLBoundary object_boundary;
// NOTICE: this method will have errors when the reference line is not
// straight. Need double loop to cover all corner cases.
// roughly skip points that are too close to last_sl_boundary box
const double distance_xy =
common::util::DistanceXY(trajectory_points[last_index].path_point(),
trajectory_points[i].path_point());
if (last_sl_boundary.start_l() > distance_xy ||
last_sl_boundary.end_l() < -distance_xy) {
continue;
}
const double mid_s =
(last_sl_boundary.start_s() + last_sl_boundary.end_s()) / 2.0;
const double start_s = std::fmax(0.0, mid_s - 2.0 * distance_xy);
const double end_s = (i == 1) ? reference_line.Length()
: std::fmin(reference_line.Length(),
mid_s + 2.0 * distance_xy);
if (!reference_line.GetApproximateSLBoundary(object_moving_box, start_s,
end_s, &object_boundary)) {
AERROR << "failed to calculate boundary";
return false;
}
// update history record
last_sl_boundary = object_boundary;
last_index = i;
// skip if object is entirely on one side of reference line.
static constexpr double kSkipLDistanceFactor = 0.4;
const double skip_l_distance =
(object_boundary.end_s() - object_boundary.start_s()) *
kSkipLDistanceFactor +
adc_width / 2.0;
if (!IsCautionLevelObstacle() &&
(std::fmin(object_boundary.start_l(), object_boundary.end_l()) >
skip_l_distance ||
std::fmax(object_boundary.start_l(), object_boundary.end_l()) <
-skip_l_distance)) {
continue;
}
if (!IsCautionLevelObstacle() && object_boundary.end_s() < 0) {
// skip if behind reference line
continue;
}
static constexpr double kSparseMappingS = 20.0;
const double st_boundary_delta_s =
(std::fabs(object_boundary.start_s() - adc_start_s) > kSparseMappingS)
? kStBoundarySparseDeltaS
: kStBoundaryDeltaS;
const double object_s_diff =
object_boundary.end_s() - object_boundary.start_s();
if (object_s_diff < st_boundary_delta_s) {
continue;
}
const double delta_t =
second_traj_point.relative_time() - first_traj_point.relative_time();
double low_s = std::max(object_boundary.start_s() - adc_half_length, 0.0);
bool has_low = false;
double high_s =
std::min(object_boundary.end_s() + adc_half_length, FLAGS_st_max_s);
bool has_high = false;
while (low_s + st_boundary_delta_s < high_s && !(has_low && has_high)) {
if (!has_low) {
auto low_ref = reference_line.GetReferencePoint(low_s);
has_low = object_moving_box.HasOverlap(
{low_ref, low_ref.heading(), adc_length,
adc_width + FLAGS_nonstatic_obstacle_nudge_l_buffer});
low_s += st_boundary_delta_s;
}
if (!has_high) {
auto high_ref = reference_line.GetReferencePoint(high_s);
has_high = object_moving_box.HasOverlap(
{high_ref, high_ref.heading(), adc_length,
adc_width + FLAGS_nonstatic_obstacle_nudge_l_buffer});
high_s -= st_boundary_delta_s;
}
}
if (has_low && has_high) {
low_s -= st_boundary_delta_s;
high_s += st_boundary_delta_s;
double low_t =
(first_traj_point.relative_time() +
std::fabs((low_s - object_boundary.start_s()) / object_s_diff) *
delta_t);
polygon_points.emplace_back(
std::make_pair(STPoint{low_s - adc_start_s, low_t},
STPoint{high_s - adc_start_s, low_t}));
double high_t =
(first_traj_point.relative_time() +
std::fabs((high_s - object_boundary.start_s()) / object_s_diff) *
delta_t);
if (high_t - low_t > 0.05) {
polygon_points.emplace_back(
std::make_pair(STPoint{low_s - adc_start_s, high_t},
STPoint{high_s - adc_start_s, high_t}));
}
}
}
if (!polygon_points.empty()) {
std::sort(polygon_points.begin(), polygon_points.end(),
[](const std::pair<STPoint, STPoint>& a,
const std::pair<STPoint, STPoint>& b) {
return a.first.t() < b.first.t();
});
auto last = std::unique(polygon_points.begin(), polygon_points.end(),
[](const std::pair<STPoint, STPoint>& a,
const std::pair<STPoint, STPoint>& b) {
return std::fabs(a.first.t() - b.first.t()) <
kStBoundaryDeltaT;
});
polygon_points.erase(last, polygon_points.end());
if (polygon_points.size() > 2) {
*st_boundary = STBoundary(polygon_points);
}
} else {
return false;
}
return true;
}
const STBoundary& Obstacle::reference_line_st_boundary() const {
return reference_line_st_boundary_;
}
const STBoundary& Obstacle::path_st_boundary() const {
return path_st_boundary_;
}
const std::vector<std::string>& Obstacle::decider_tags() const {
return decider_tags_;
}
const std::vector<ObjectDecisionType>& Obstacle::decisions() const {
return decisions_;
}
bool Obstacle::IsLateralDecision(const ObjectDecisionType& decision) {
return decision.has_ignore() || decision.has_nudge();
}
bool Obstacle::IsLongitudinalDecision(const ObjectDecisionType& decision) {
return decision.has_ignore() || decision.has_stop() || decision.has_yield() ||
decision.has_follow() || decision.has_overtake();
}
ObjectDecisionType Obstacle::MergeLongitudinalDecision(
const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {
if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {
return rhs;
}
if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {
return lhs;
}
const auto lhs_val =
FindOrDie(s_longitudinal_decision_safety_sorter_, lhs.object_tag_case());
const auto rhs_val =
FindOrDie(s_longitudinal_decision_safety_sorter_, rhs.object_tag_case());
if (lhs_val < rhs_val) {
return rhs;
} else if (lhs_val > rhs_val) {
return lhs;
} else {
if (lhs.has_ignore()) {
return rhs;
} else if (lhs.has_stop()) {
return lhs.stop().distance_s() < rhs.stop().distance_s() ? lhs : rhs;
} else if (lhs.has_yield()) {
return lhs.yield().distance_s() < rhs.yield().distance_s() ? lhs : rhs;
} else if (lhs.has_follow()) {
return lhs.follow().distance_s() < rhs.follow().distance_s() ? lhs : rhs;
} else if (lhs.has_overtake()) {
return lhs.overtake().distance_s() > rhs.overtake().distance_s() ? lhs
: rhs;
} else {
DCHECK(false) << "Unknown decision";
}
}
return lhs; // stop compiler complaining
}
const ObjectDecisionType& Obstacle::LongitudinalDecision() const {
return longitudinal_decision_;
}
const ObjectDecisionType& Obstacle::LateralDecision() const {
return lateral_decision_;
}
bool Obstacle::IsIgnore() const {
return IsLongitudinalIgnore() && IsLateralIgnore();
}
bool Obstacle::IsLongitudinalIgnore() const {
return longitudinal_decision_.has_ignore();
}
bool Obstacle::IsLateralIgnore() const {
return lateral_decision_.has_ignore();
}
ObjectDecisionType Obstacle::MergeLateralDecision(
const ObjectDecisionType& lhs, const ObjectDecisionType& rhs) {
if (lhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {
return rhs;
}
if (rhs.object_tag_case() == ObjectDecisionType::OBJECT_TAG_NOT_SET) {
return lhs;
}
const auto lhs_val =
FindOrDie(s_lateral_decision_safety_sorter_, lhs.object_tag_case());
const auto rhs_val =
FindOrDie(s_lateral_decision_safety_sorter_, rhs.object_tag_case());
if (lhs_val < rhs_val) {
return rhs;
} else if (lhs_val > rhs_val) {
return lhs;
} else {
if (lhs.has_ignore()) {
return rhs;
} else if (lhs.has_nudge()) {
DCHECK(lhs.nudge().type() == rhs.nudge().type())
<< "could not merge left nudge and right nudge";
return std::fabs(lhs.nudge().distance_l()) >
std::fabs(rhs.nudge().distance_l())
? lhs
: rhs;
}
}
DCHECK(false) << "Does not have rule to merge decision: "
<< lhs.ShortDebugString()
<< " and decision: " << rhs.ShortDebugString();
return lhs;
}
bool Obstacle::HasLateralDecision() const {
return lateral_decision_.object_tag_case() !=
ObjectDecisionType::OBJECT_TAG_NOT_SET;
}
bool Obstacle::HasLongitudinalDecision() const {
return longitudinal_decision_.object_tag_case() !=
ObjectDecisionType::OBJECT_TAG_NOT_SET;
}
bool Obstacle::HasNonIgnoreDecision() const {
return (HasLateralDecision() && !IsLateralIgnore()) ||
(HasLongitudinalDecision() && !IsLongitudinalIgnore());
}
void Obstacle::AddLongitudinalDecision(const std::string& decider_tag,
const ObjectDecisionType& decision) {
DCHECK(IsLongitudinalDecision(decision))
<< "Decision: " << decision.ShortDebugString()
<< " is not a longitudinal decision";
longitudinal_decision_ =
MergeLongitudinalDecision(longitudinal_decision_, decision);
ADEBUG << decider_tag << " added obstacle " << Id()
<< " longitudinal decision: " << decision.ShortDebugString()
<< ". The merged decision is: "
<< longitudinal_decision_.ShortDebugString();
decisions_.push_back(decision);
decider_tags_.push_back(decider_tag);
}
void Obstacle::AddLateralDecision(const std::string& decider_tag,
const ObjectDecisionType& decision) {
DCHECK(IsLateralDecision(decision))
<< "Decision: " << decision.ShortDebugString()
<< " is not a lateral decision";
lateral_decision_ = MergeLateralDecision(lateral_decision_, decision);
ADEBUG << decider_tag << " added obstacle " << Id()
<< " a lateral decision: " << decision.ShortDebugString()
<< ". The merged decision is: "
<< lateral_decision_.ShortDebugString();
decisions_.push_back(decision);
decider_tags_.push_back(decider_tag);
}
std::string Obstacle::DebugString() const {
std::stringstream ss;
ss << "Obstacle id: " << id_;
for (size_t i = 0; i < decisions_.size(); ++i) {
ss << " decision: " << decisions_[i].DebugString() << ", made by "
<< decider_tags_[i];
}
if (lateral_decision_.object_tag_case() !=
ObjectDecisionType::OBJECT_TAG_NOT_SET) {
ss << "lateral decision: " << lateral_decision_.ShortDebugString();
}
if (longitudinal_decision_.object_tag_case() !=
ObjectDecisionType::OBJECT_TAG_NOT_SET) {
ss << "longitudinal decision: "
<< longitudinal_decision_.ShortDebugString();
}
return ss.str();
}
const SLBoundary& Obstacle::PerceptionSLBoundary() const {
return sl_boundary_;
}
void Obstacle::set_path_st_boundary(const STBoundary& boundary) {
path_st_boundary_ = boundary;
path_st_boundary_initialized_ = true;
}
void Obstacle::SetStBoundaryType(const STBoundary::BoundaryType type) {
path_st_boundary_.SetBoundaryType(type);
}
void Obstacle::EraseStBoundary() { path_st_boundary_ = STBoundary(); }
void Obstacle::SetReferenceLineStBoundary(const STBoundary& boundary) {
reference_line_st_boundary_ = boundary;
}
void Obstacle::SetReferenceLineStBoundaryType(
const STBoundary::BoundaryType type) {
reference_line_st_boundary_.SetBoundaryType(type);
}
void Obstacle::EraseReferenceLineStBoundary() {
reference_line_st_boundary_ = STBoundary();
}
bool Obstacle::IsValidObstacle(
const perception::PerceptionObstacle& perception_obstacle) {
const double object_width = perception_obstacle.width();
const double object_length = perception_obstacle.length();
const double kMinObjectDimension = 1.0e-6;
return !std::isnan(object_width) && !std::isnan(object_length) &&
object_width > kMinObjectDimension &&
object_length > kMinObjectDimension;
}
void Obstacle::CheckLaneBlocking(const ReferenceLine& reference_line) {
if (!IsStatic()) {
is_lane_blocking_ = false;
return;
}
DCHECK(sl_boundary_.has_start_s());
DCHECK(sl_boundary_.has_end_s());
DCHECK(sl_boundary_.has_start_l());
DCHECK(sl_boundary_.has_end_l());
if (sl_boundary_.start_l() * sl_boundary_.end_l() < 0.0) {
is_lane_blocking_ = true;
return;
}
const double driving_width = reference_line.GetDrivingWidth(sl_boundary_);
auto vehicle_param = common::VehicleConfigHelper::GetConfig().vehicle_param();
if (reference_line.IsOnLane(sl_boundary_) &&
driving_width <
vehicle_param.width() + FLAGS_static_obstacle_nudge_l_buffer) {
is_lane_blocking_ = true;
return;
}
is_lane_blocking_ = false;
}
void Obstacle::SetLaneChangeBlocking(const bool is_distance_clear) {
is_lane_change_blocking_ = is_distance_clear;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/decision_data.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include "modules/common/math/box2d.h"
#include "modules/planning/common/obstacle.h"
#include "modules/planning/reference_line/reference_line.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
namespace apollo {
namespace planning {
enum class VirtualObjectType {
DESTINATION = 0,
CROSSWALK = 1,
TRAFFIC_LIGHT = 2,
CLEAR_ZONE = 3,
REROUTE = 4,
DECISION_JUMP = 5,
PRIORITY = 6
};
struct EnumClassHash {
template <typename T>
size_t operator()(T t) const {
return static_cast<size_t>(t);
}
};
class DecisionData {
public:
DecisionData(const prediction::PredictionObstacles& prediction_obstacles,
const ReferenceLine& reference_line);
~DecisionData() = default;
public:
Obstacle* GetObstacleById(const std::string& id);
std::vector<Obstacle*> GetObstacleByType(const VirtualObjectType& type);
std::unordered_set<std::string> GetObstacleIdByType(
const VirtualObjectType& type);
const std::vector<Obstacle*>& GetStaticObstacle() const;
const std::vector<Obstacle*>& GetDynamicObstacle() const;
const std::vector<Obstacle*>& GetVirtualObstacle() const;
const std::vector<Obstacle*>& GetPracticalObstacle() const;
const std::vector<Obstacle*>& GetAllObstacle() const;
public:
bool CreateVirtualObstacle(const ReferencePoint& point,
const VirtualObjectType& type,
std::string* const id);
bool CreateVirtualObstacle(const double point_s,
const VirtualObjectType& type,
std::string* const id);
private:
bool IsValidTrajectory(const prediction::Trajectory& trajectory);
bool IsValidTrajectoryPoint(const common::TrajectoryPoint& point);
bool CreateVirtualObstacle(const common::math::Box2d& obstacle_box,
const VirtualObjectType& type,
std::string* const id);
private:
std::vector<Obstacle*> static_obstacle_;
std::vector<Obstacle*> dynamic_obstacle_;
std::vector<Obstacle*> virtual_obstacle_;
std::vector<Obstacle*> practical_obstacle_;
std::vector<Obstacle*> all_obstacle_;
private:
const ReferenceLine& reference_line_;
std::list<std::unique_ptr<Obstacle>> obstacles_;
std::unordered_map<std::string, Obstacle*> obstacle_map_;
std::unordered_map<VirtualObjectType, std::unordered_set<std::string>,
EnumClassHash>
virtual_obstacle_id_map_;
std::mutex mutex_;
std::mutex transaction_mutex_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/trajectory_evaluator.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "modules/planning/proto/learning_data.pb.h"
namespace apollo {
namespace planning {
class TrajectoryEvaluator {
public:
~TrajectoryEvaluator() = default;
void EvaluateADCTrajectory(const double start_point_timestamp_sec,
const double delta_time,
LearningDataFrame* learning_data_frame);
void EvaluateADCFutureTrajectory(
const int frame_num,
const std::vector<TrajectoryPointFeature>& adc_future_trajectory,
const double start_point_timestamp_sec, const double delta_time,
std::vector<TrajectoryPointFeature>* evaluated_adc_future_trajectory);
void EvaluateObstacleTrajectory(const double start_point_timestamp_sec,
const double delta_time,
LearningDataFrame* learning_data_frame);
void EvaluateObstaclePredictionTrajectory(
const double start_point_timestamp_sec, const double delta_time,
LearningDataFrame* learning_data_frame);
private:
void EvaluateTrajectoryByTime(
const int frame_num, const std::string& obstacle_id,
const std::vector<std::pair<double, CommonTrajectoryPointFeature>>&
trajectory,
const double start_point_timestamp_sec, const double delta_time,
std::vector<TrajectoryPointFeature>* evaluated_trajectory);
void Convert(const CommonTrajectoryPointFeature& tp,
const double relative_time,
common::TrajectoryPoint* trajectory_point);
void Convert(const common::TrajectoryPoint& tp,
const double timestamp_sec,
TrajectoryPointFeature* trajectory_point);
void WriteLog(const std::string& msg);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/frame.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <list>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#include "modules/common/math/vec2d.h"
#include "modules/common/monitor_log/monitor_log_buffer.h"
#include "modules/common_msgs/basic_msgs/geometry.pb.h"
#include "modules/common/status/status.h"
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/common_msgs/localization_msgs/pose.pb.h"
#include "modules/planning/common/ego_info.h"
#include "modules/planning/common/indexed_queue.h"
#include "modules/planning/common/local_view.h"
#include "modules/planning/common/obstacle.h"
#include "modules/planning/common/open_space_info.h"
#include "modules/planning/common/reference_line_info.h"
#include "modules/planning/common/trajectory/publishable_trajectory.h"
#include "modules/common_msgs/planning_msgs/pad_msg.pb.h"
#include "modules/common_msgs/planning_msgs/planning.pb.h"
#include "modules/planning/proto/planning_config.pb.h"
#include "modules/common_msgs/planning_msgs/planning_internal.pb.h"
#include "modules/planning/reference_line/reference_line_provider.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
#include "modules/common_msgs/routing_msgs/routing.pb.h"
namespace apollo {
namespace planning {
/**
* @class Frame
*
* @brief Frame holds all data for one planning cycle.
*/
class Frame {
public:
explicit Frame(uint32_t sequence_num);
Frame(uint32_t sequence_num, const LocalView &local_view,
const common::TrajectoryPoint &planning_start_point,
const common::VehicleState &vehicle_state,
ReferenceLineProvider *reference_line_provider);
Frame(uint32_t sequence_num, const LocalView &local_view,
const common::TrajectoryPoint &planning_start_point,
const common::VehicleState &vehicle_state);
virtual ~Frame() = default;
const common::TrajectoryPoint &PlanningStartPoint() const;
common::Status Init(
const common::VehicleStateProvider *vehicle_state_provider,
const std::list<ReferenceLine> &reference_lines,
const std::list<hdmap::RouteSegments> &segments,
const std::vector<routing::LaneWaypoint> &future_route_waypoints,
const EgoInfo *ego_info);
common::Status InitForOpenSpace(
const common::VehicleStateProvider *vehicle_state_provider,
const EgoInfo *ego_info);
uint32_t SequenceNum() const;
std::string DebugString() const;
const PublishableTrajectory &ComputedTrajectory() const;
void RecordInputDebug(planning_internal::Debug *debug);
const std::list<ReferenceLineInfo> &reference_line_info() const;
std::list<ReferenceLineInfo> *mutable_reference_line_info();
Obstacle *Find(const std::string &id);
const ReferenceLineInfo *FindDriveReferenceLineInfo();
const ReferenceLineInfo *FindTargetReferenceLineInfo();
const ReferenceLineInfo *FindFailedReferenceLineInfo();
const ReferenceLineInfo *DriveReferenceLineInfo() const;
const std::vector<const Obstacle *> obstacles() const;
const Obstacle *CreateStopObstacle(
ReferenceLineInfo *const reference_line_info,
const std::string &obstacle_id, const double obstacle_s);
const Obstacle *CreateStopObstacle(const std::string &obstacle_id,
const std::string &lane_id,
const double lane_s);
const Obstacle *CreateStaticObstacle(
ReferenceLineInfo *const reference_line_info,
const std::string &obstacle_id, const double obstacle_start_s,
const double obstacle_end_s);
bool Rerouting(PlanningContext *planning_context);
const common::VehicleState &vehicle_state() const;
static void AlignPredictionTime(
const double planning_start_time,
prediction::PredictionObstacles *prediction_obstacles);
void set_current_frame_planned_trajectory(
ADCTrajectory current_frame_planned_trajectory) {
current_frame_planned_trajectory_ =
std::move(current_frame_planned_trajectory);
}
const ADCTrajectory ¤t_frame_planned_trajectory() const {
return current_frame_planned_trajectory_;
}
void set_current_frame_planned_path(
DiscretizedPath current_frame_planned_path) {
current_frame_planned_path_ = std::move(current_frame_planned_path);
}
const DiscretizedPath ¤t_frame_planned_path() const {
return current_frame_planned_path_;
}
const bool is_near_destination() const {
return is_near_destination_;
}
/**
* @brief Adjust reference line priority according to actual road conditions
* @id_to_priority lane id and reference line priority mapping relationship
*/
void UpdateReferenceLinePriority(
const std::map<std::string, uint32_t> &id_to_priority);
const LocalView &local_view() const {
return local_view_;
}
ThreadSafeIndexedObstacles *GetObstacleList() {
return &obstacles_;
}
const OpenSpaceInfo &open_space_info() const {
return open_space_info_;
}
OpenSpaceInfo *mutable_open_space_info() {
return &open_space_info_;
}
perception::TrafficLight GetSignal(const std::string &traffic_light_id) const;
const PadMessage::DrivingAction &GetPadMsgDrivingAction() const {
return pad_msg_driving_action_;
}
private:
common::Status InitFrameData(
const common::VehicleStateProvider *vehicle_state_provider,
const EgoInfo *ego_info);
bool CreateReferenceLineInfo(const std::list<ReferenceLine> &reference_lines,
const std::list<hdmap::RouteSegments> &segments);
/**
* Find an obstacle that collides with ADC (Autonomous Driving Car) if
* such obstacle exists.
* @return pointer to the obstacle if such obstacle exists, otherwise
* @return false if no colliding obstacle.
*/
const Obstacle *FindCollisionObstacle(const EgoInfo *ego_info) const;
/**
* @brief create a static virtual obstacle
*/
const Obstacle *CreateStaticVirtualObstacle(const std::string &id,
const common::math::Box2d &box);
void AddObstacle(const Obstacle &obstacle);
void ReadTrafficLights();
void ReadPadMsgDrivingAction();
void ResetPadMsgDrivingAction();
private:
static PadMessage::DrivingAction pad_msg_driving_action_;
uint32_t sequence_num_ = 0;
LocalView local_view_;
const hdmap::HDMap *hdmap_ = nullptr;
common::TrajectoryPoint planning_start_point_;
common::VehicleState vehicle_state_;
std::list<ReferenceLineInfo> reference_line_info_;
bool is_near_destination_ = false;
/**
* the reference line info that the vehicle finally choose to drive on
**/
const ReferenceLineInfo *drive_reference_line_info_ = nullptr;
ThreadSafeIndexedObstacles obstacles_;
std::unordered_map<std::string, const perception::TrafficLight *>
traffic_lights_;
// current frame published trajectory
ADCTrajectory current_frame_planned_trajectory_;
// current frame path for future possible speed fallback
DiscretizedPath current_frame_planned_path_;
const ReferenceLineProvider *reference_line_provider_ = nullptr;
OpenSpaceInfo open_space_info_;
std::vector<routing::LaneWaypoint> future_route_waypoints_;
common::monitor::MonitorLogBuffer monitor_logger_buffer_;
};
class FrameHistory : public IndexedQueue<uint32_t, Frame> {
public:
FrameHistory();
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/feature_output.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
*implied. See the License for the specific language governing
*permissions and limitations under the License.
*****************************************************************************/
#pragma once
#include <string>
#include "modules/planning/proto/learning_data.pb.h"
namespace apollo {
namespace planning {
class FeatureOutput {
public:
/**
* @brief Constructor; disabled
*/
FeatureOutput() = delete;
/**
* @brief Close the output stream
*/
static void Close();
/**
* @brief Reset
*/
static void Clear();
/**
* @brief Check if output is ready
* @return True if output is ready
*/
static bool Ready();
/**
* @brief Insert a a frame of learning data
* @param A feature in proto
*/
static void InsertLearningDataFrame(
const std::string& record_filename,
const LearningDataFrame& learning_data_frame);
static void InsertPlanningResult();
static LearningDataFrame* GetLatestLearningDataFrame();
/**
* @brief Write LearningData to a file
*/
static void WriteLearningData(const std::string& record_file);
static void WriteRemainderiLearningData(const std::string& record_file);
/**
* @brief Get the size of learning_data_
* @return The size of learning_data_
*/
static int SizeOfLearningData();
private:
static LearningData learning_data_;
static int learning_data_file_index_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/planning_context.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 "cyber/common/macros.h"
#include "modules/planning/proto/planning_status.pb.h"
/**
* @brief PlanningContext is the runtime context in planning. It is
* persistent across multiple frames.
*/
namespace apollo {
namespace planning {
class PlanningContext {
public:
PlanningContext() = default;
void Clear();
void Init();
/*
* please put all status info inside PlanningStatus for easy maintenance.
* do NOT create new struct at this level.
* */
const PlanningStatus& planning_status() const { return planning_status_; }
PlanningStatus* mutable_planning_status() { return &planning_status_; }
private:
PlanningStatus planning_status_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/reference_line_info.h
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <limits>
#include <list>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/common_msgs/basic_msgs/drive_state.pb.h"
#include "modules/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/common_msgs/planning_msgs/planning.pb.h"
#include "modules/planning/proto/lattice_structure.pb.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/map/pnc_map/pnc_map.h"
#include "modules/planning/common/path/path_data.h"
#include "modules/planning/common/path_boundary.h"
#include "modules/planning/common/path_decision.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/speed/speed_data.h"
#include "modules/planning/common/st_graph_data.h"
#include "modules/planning/common/trajectory/discretized_trajectory.h"
namespace apollo {
namespace planning {
/**
* @class ReferenceLineInfo
* @brief ReferenceLineInfo holds all data for one reference line.
*/
class ReferenceLineInfo {
public:
enum class LaneType { LeftForward, LeftReverse, RightForward, RightReverse };
ReferenceLineInfo() = default;
ReferenceLineInfo(const common::VehicleState& vehicle_state,
const common::TrajectoryPoint& adc_planning_point,
const ReferenceLine& reference_line,
const hdmap::RouteSegments& segments);
bool Init(const std::vector<const Obstacle*>& obstacles);
bool AddObstacles(const std::vector<const Obstacle*>& obstacles);
Obstacle* AddObstacle(const Obstacle* obstacle);
const common::VehicleState& vehicle_state() const { return vehicle_state_; }
PathDecision* path_decision();
const PathDecision& path_decision() const;
const ReferenceLine& reference_line() const;
ReferenceLine* mutable_reference_line();
double SDistanceToDestination() const;
bool ReachedDestination() const;
void SetTrajectory(const DiscretizedTrajectory& trajectory);
const DiscretizedTrajectory& trajectory() const;
double Cost() const { return cost_; }
void AddCost(double cost) { cost_ += cost; }
void SetCost(double cost) { cost_ = cost; }
double PriorityCost() const { return priority_cost_; }
void SetPriorityCost(double cost) { priority_cost_ = cost; }
// For lattice planner'speed planning target
void SetLatticeStopPoint(const StopPoint& stop_point);
void SetLatticeCruiseSpeed(double speed);
const PlanningTarget& planning_target() const { return planning_target_; }
void SetCruiseSpeed(double speed) { cruise_speed_ = speed; }
double GetCruiseSpeed() const;
hdmap::LaneInfoConstPtr LocateLaneInfo(const double s) const;
bool GetNeighborLaneInfo(const ReferenceLineInfo::LaneType lane_type,
const double s, hdmap::Id* ptr_lane_id,
double* ptr_lane_width) const;
/**
* @brief check if current reference line is started from another reference
*line info line. The method is to check if the start point of current
*reference line is on previous reference line info.
* @return returns true if current reference line starts on previous reference
*line, otherwise false.
**/
bool IsStartFrom(const ReferenceLineInfo& previous_reference_line_info) const;
planning_internal::Debug* mutable_debug() { return &debug_; }
const planning_internal::Debug& debug() const { return debug_; }
LatencyStats* mutable_latency_stats() { return &latency_stats_; }
const LatencyStats& latency_stats() const { return latency_stats_; }
const PathData& path_data() const;
const PathData& fallback_path_data() const;
const SpeedData& speed_data() const;
PathData* mutable_path_data();
PathData* mutable_fallback_path_data();
SpeedData* mutable_speed_data();
const RSSInfo& rss_info() const;
RSSInfo* mutable_rss_info();
// aggregate final result together by some configuration
bool CombinePathAndSpeedProfile(
const double relative_time, const double start_s,
DiscretizedTrajectory* discretized_trajectory);
// adjust trajectory if it starts from cur_vehicle postion rather planning
// init point from upstream
bool AdjustTrajectoryWhichStartsFromCurrentPos(
const common::TrajectoryPoint& planning_start_point,
const std::vector<common::TrajectoryPoint>& trajectory,
DiscretizedTrajectory* adjusted_trajectory);
const SLBoundary& AdcSlBoundary() const;
std::string PathSpeedDebugString() const;
/**
* Check if the current reference line is a change lane reference line, i.e.,
* ADC's current position is not on this reference line.
*/
bool IsChangeLanePath() const;
/**
* Check if the current reference line is the neighbor of the vehicle
* current position
*/
bool IsNeighborLanePath() const;
/**
* Set if the vehicle can drive following this reference line
* A planner need to set this value to true if the reference line is OK
*/
void SetDrivable(bool drivable);
bool IsDrivable() const;
void ExportEngageAdvice(common::EngageAdvice* engage_advice,
PlanningContext* planning_context) const;
const hdmap::RouteSegments& Lanes() const;
std::list<hdmap::Id> TargetLaneId() const;
void ExportDecision(DecisionResult* decision_result,
PlanningContext* planning_context) const;
void SetJunctionRightOfWay(const double junction_s,
const bool is_protected) const;
ADCTrajectory::RightOfWayStatus GetRightOfWayStatus() const;
hdmap::Lane::LaneTurn GetPathTurnType(const double s) const;
bool GetIntersectionRightofWayStatus(
const hdmap::PathOverlap& pnc_junction_overlap) const;
double OffsetToOtherReferenceLine() const {
return offset_to_other_reference_line_;
}
void SetOffsetToOtherReferenceLine(const double offset) {
offset_to_other_reference_line_ = offset;
}
const std::vector<PathBoundary>& GetCandidatePathBoundaries() const;
void SetCandidatePathBoundaries(
std::vector<PathBoundary>&& candidate_path_boundaries);
const std::vector<PathData>& GetCandidatePathData() const;
void SetCandidatePathData(std::vector<PathData>&& candidate_path_data);
Obstacle* GetBlockingObstacle() const { return blocking_obstacle_; }
void SetBlockingObstacle(const std::string& blocking_obstacle_id);
bool is_path_lane_borrow() const { return is_path_lane_borrow_; }
void set_is_path_lane_borrow(const bool is_path_lane_borrow) {
is_path_lane_borrow_ = is_path_lane_borrow;
}
void set_is_on_reference_line() { is_on_reference_line_ = true; }
uint32_t GetPriority() const { return reference_line_.GetPriority(); }
void SetPriority(uint32_t priority) { reference_line_.SetPriority(priority); }
void set_trajectory_type(
const ADCTrajectory::TrajectoryType trajectory_type) {
trajectory_type_ = trajectory_type;
}
ADCTrajectory::TrajectoryType trajectory_type() const {
return trajectory_type_;
}
StGraphData* mutable_st_graph_data() { return &st_graph_data_; }
const StGraphData& st_graph_data() { return st_graph_data_; }
// different types of overlaps that can be handled by different scenarios.
enum OverlapType {
CLEAR_AREA = 1,
CROSSWALK = 2,
OBSTACLE = 3,
PNC_JUNCTION = 4,
SIGNAL = 5,
STOP_SIGN = 6,
YIELD_SIGN = 7,
};
const std::vector<std::pair<OverlapType, hdmap::PathOverlap>>&
FirstEncounteredOverlaps() const {
return first_encounter_overlaps_;
}
int GetPnCJunction(const double s,
hdmap::PathOverlap* pnc_junction_overlap) const;
int GetJunction(const double s, hdmap::PathOverlap* junction_overlap) const;
std::vector<common::SLPoint> GetAllStopDecisionSLPoint() const;
void SetTurnSignal(const common::VehicleSignal::TurnSignal& turn_signal);
void SetEmergencyLight();
void set_path_reusable(const bool path_reusable) {
path_reusable_ = path_reusable;
}
bool path_reusable() const { return path_reusable_; }
private:
void InitFirstOverlaps();
bool CheckChangeLane() const;
void SetTurnSignalBasedOnLaneTurnType(
common::VehicleSignal* vehicle_signal) const;
void ExportVehicleSignal(common::VehicleSignal* vehicle_signal) const;
bool IsIrrelevantObstacle(const Obstacle& obstacle);
void MakeDecision(DecisionResult* decision_result,
PlanningContext* planning_context) const;
int MakeMainStopDecision(DecisionResult* decision_result) const;
void MakeMainMissionCompleteDecision(DecisionResult* decision_result,
PlanningContext* planning_context) const;
void MakeEStopDecision(DecisionResult* decision_result) const;
void SetObjectDecisions(ObjectDecisions* object_decisions) const;
bool AddObstacleHelper(const std::shared_ptr<Obstacle>& obstacle);
bool GetFirstOverlap(const std::vector<hdmap::PathOverlap>& path_overlaps,
hdmap::PathOverlap* path_overlap);
private:
static std::unordered_map<std::string, bool> junction_right_of_way_map_;
const common::VehicleState vehicle_state_;
const common::TrajectoryPoint adc_planning_point_;
ReferenceLine reference_line_;
/**
* @brief this is the number that measures the goodness of this reference
* line. The lower the better.
*/
double cost_ = 0.0;
bool is_drivable_ = true;
PathDecision path_decision_;
Obstacle* blocking_obstacle_;
std::vector<PathBoundary> candidate_path_boundaries_;
std::vector<PathData> candidate_path_data_;
PathData path_data_;
PathData fallback_path_data_;
SpeedData speed_data_;
DiscretizedTrajectory discretized_trajectory_;
RSSInfo rss_info_;
/**
* @brief SL boundary of stitching point (starting point of plan trajectory)
* relative to the reference line
*/
SLBoundary adc_sl_boundary_;
planning_internal::Debug debug_;
LatencyStats latency_stats_;
hdmap::RouteSegments lanes_;
bool is_on_reference_line_ = false;
bool is_path_lane_borrow_ = false;
ADCTrajectory::RightOfWayStatus status_ = ADCTrajectory::UNPROTECTED;
double offset_to_other_reference_line_ = 0.0;
double priority_cost_ = 0.0;
PlanningTarget planning_target_;
ADCTrajectory::TrajectoryType trajectory_type_ = ADCTrajectory::UNKNOWN;
/**
* Overlaps encountered in the first time along the reference line in front of
* the vehicle
*/
std::vector<std::pair<OverlapType, hdmap::PathOverlap>>
first_encounter_overlaps_;
/**
* @brief Data generated by speed_bounds_decider for constructing st_graph for
* different st optimizer
*/
StGraphData st_graph_data_;
common::VehicleSignal vehicle_signal_;
double cruise_speed_ = 0.0;
bool path_reusable_ = false;
DISALLOW_COPY_AND_ASSIGN(ReferenceLineInfo);
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/trajectory_stitcher.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/trajectory_stitcher.h"
#include <algorithm>
#include "absl/strings/str_cat.h"
#include "cyber/common/log.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/util/util.h"
#include "modules/common/vehicle_model/vehicle_model.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleModel;
using apollo::common::VehicleState;
using apollo::common::math::Vec2d;
TrajectoryPoint TrajectoryStitcher::ComputeTrajectoryPointFromVehicleState(
const double planning_cycle_time, const VehicleState& vehicle_state) {
TrajectoryPoint point;
point.mutable_path_point()->set_s(0.0);
point.mutable_path_point()->set_x(vehicle_state.x());
point.mutable_path_point()->set_y(vehicle_state.y());
point.mutable_path_point()->set_z(vehicle_state.z());
point.mutable_path_point()->set_theta(vehicle_state.heading());
point.mutable_path_point()->set_kappa(vehicle_state.kappa());
point.set_v(vehicle_state.linear_velocity());
point.set_a(vehicle_state.linear_acceleration());
point.set_relative_time(planning_cycle_time);
return point;
}
std::vector<TrajectoryPoint>
TrajectoryStitcher::ComputeReinitStitchingTrajectory(
const double planning_cycle_time, const VehicleState& vehicle_state) {
TrajectoryPoint reinit_point;
static constexpr double kEpsilon_v = 0.1;
static constexpr double kEpsilon_a = 0.4;
// TODO(Jinyun/Yu): adjust kEpsilon if corrected IMU acceleration provided
if (std::abs(vehicle_state.linear_velocity()) < kEpsilon_v &&
std::abs(vehicle_state.linear_acceleration()) < kEpsilon_a) {
reinit_point = ComputeTrajectoryPointFromVehicleState(planning_cycle_time,
vehicle_state);
} else {
VehicleState predicted_vehicle_state;
predicted_vehicle_state =
VehicleModel::Predict(planning_cycle_time, vehicle_state);
reinit_point = ComputeTrajectoryPointFromVehicleState(
planning_cycle_time, predicted_vehicle_state);
}
return std::vector<TrajectoryPoint>(1, reinit_point);
}
// only used in navigation mode
void TrajectoryStitcher::TransformLastPublishedTrajectory(
const double x_diff, const double y_diff, const double theta_diff,
PublishableTrajectory* prev_trajectory) {
if (!prev_trajectory) {
return;
}
// R^-1
double cos_theta = std::cos(theta_diff);
double sin_theta = -std::sin(theta_diff);
// -R^-1 * t
auto tx = -(cos_theta * x_diff - sin_theta * y_diff);
auto ty = -(sin_theta * x_diff + cos_theta * y_diff);
std::for_each(prev_trajectory->begin(), prev_trajectory->end(),
[&cos_theta, &sin_theta, &tx, &ty,
&theta_diff](common::TrajectoryPoint& p) {
auto x = p.path_point().x();
auto y = p.path_point().y();
auto theta = p.path_point().theta();
auto x_new = cos_theta * x - sin_theta * y + tx;
auto y_new = sin_theta * x + cos_theta * y + ty;
auto theta_new =
common::math::NormalizeAngle(theta - theta_diff);
p.mutable_path_point()->set_x(x_new);
p.mutable_path_point()->set_y(y_new);
p.mutable_path_point()->set_theta(theta_new);
});
}
/* Planning from current vehicle state if:
1. the auto-driving mode is off
(or) 2. we don't have the trajectory from last planning cycle
(or) 3. the position deviation from actual and target is too high
*/
std::vector<TrajectoryPoint> TrajectoryStitcher::ComputeStitchingTrajectory(
const VehicleState& vehicle_state, const double current_timestamp,
const double planning_cycle_time, const size_t preserved_points_num,
const bool replan_by_offset, const PublishableTrajectory* prev_trajectory,
std::string* replan_reason) {
if (!FLAGS_enable_trajectory_stitcher) {
*replan_reason = "stitch is disabled by gflag.";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
if (!prev_trajectory) {
*replan_reason = "replan for no previous trajectory.";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
if (vehicle_state.driving_mode() != canbus::Chassis::COMPLETE_AUTO_DRIVE) {
*replan_reason = "replan for manual mode.";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
size_t prev_trajectory_size = prev_trajectory->NumOfPoints();
if (prev_trajectory_size == 0) {
ADEBUG << "Projected trajectory at time [" << prev_trajectory->header_time()
<< "] size is zero! Previous planning not exist or failed. Use "
"origin car status instead.";
*replan_reason = "replan for empty previous trajectory.";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
const double veh_rel_time =
current_timestamp - prev_trajectory->header_time();
size_t time_matched_index =
prev_trajectory->QueryLowerBoundPoint(veh_rel_time);
if (time_matched_index == 0 &&
veh_rel_time < prev_trajectory->StartPoint().relative_time()) {
AWARN << "current time smaller than the previous trajectory's first time";
*replan_reason =
"replan for current time smaller than the previous trajectory's first "
"time.";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
if (time_matched_index + 1 >= prev_trajectory_size) {
AWARN << "current time beyond the previous trajectory's last time";
*replan_reason =
"replan for current time beyond the previous trajectory's last time";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
auto time_matched_point = prev_trajectory->TrajectoryPointAt(
static_cast<uint32_t>(time_matched_index));
if (!time_matched_point.has_path_point()) {
*replan_reason = "replan for previous trajectory missed path point";
return ComputeReinitStitchingTrajectory(planning_cycle_time, vehicle_state);
}
size_t position_matched_index = prev_trajectory->QueryNearestPointWithBuffer(
{vehicle_state.x(), vehicle_state.y()}, 1.0e-6);
auto frenet_sd = ComputePositionProjection(
vehicle_state.x(), vehicle_state.y(),
prev_trajectory->TrajectoryPointAt(
static_cast<uint32_t>(position_matched_index)));
if (replan_by_offset) {
auto lon_diff = time_matched_point.path_point().s() - frenet_sd.first;
auto lat_diff = frenet_sd.second;
ADEBUG << "Control lateral diff: " << lat_diff
<< ", longitudinal diff: " << lon_diff;
if (std::fabs(lat_diff) > FLAGS_replan_lateral_distance_threshold) {
const std::string msg = absl::StrCat(
"the distance between matched point and actual position is too "
"large. Replan is triggered. lat_diff = ",
lat_diff);
AERROR << msg;
*replan_reason = msg;
return ComputeReinitStitchingTrajectory(planning_cycle_time,
vehicle_state);
}
if (std::fabs(lon_diff) > FLAGS_replan_longitudinal_distance_threshold) {
const std::string msg = absl::StrCat(
"the distance between matched point and actual position is too "
"large. Replan is triggered. lon_diff = ",
lon_diff);
AERROR << msg;
*replan_reason = msg;
return ComputeReinitStitchingTrajectory(planning_cycle_time,
vehicle_state);
}
} else {
ADEBUG << "replan according to certain amount of lat and lon offset is "
"disabled";
}
double forward_rel_time = veh_rel_time + planning_cycle_time;
size_t forward_time_index =
prev_trajectory->QueryLowerBoundPoint(forward_rel_time);
ADEBUG << "Position matched index:\t" << position_matched_index;
ADEBUG << "Time matched index:\t" << time_matched_index;
auto matched_index = std::min(time_matched_index, position_matched_index);
std::vector<TrajectoryPoint> stitching_trajectory(
prev_trajectory->begin() +
std::max(0, static_cast<int>(matched_index - preserved_points_num)),
prev_trajectory->begin() + forward_time_index + 1);
ADEBUG << "stitching_trajectory size: " << stitching_trajectory.size();
const double zero_s = stitching_trajectory.back().path_point().s();
for (auto& tp : stitching_trajectory) {
if (!tp.has_path_point()) {
*replan_reason = "replan for previous trajectory missed path point";
return ComputeReinitStitchingTrajectory(planning_cycle_time,
vehicle_state);
}
tp.set_relative_time(tp.relative_time() + prev_trajectory->header_time() -
current_timestamp);
tp.mutable_path_point()->set_s(tp.path_point().s() - zero_s);
}
return stitching_trajectory;
}
std::pair<double, double> TrajectoryStitcher::ComputePositionProjection(
const double x, const double y, const TrajectoryPoint& p) {
Vec2d v(x - p.path_point().x(), y - p.path_point().y());
Vec2d n(std::cos(p.path_point().theta()), std::sin(p.path_point().theta()));
std::pair<double, double> frenet_sd;
frenet_sd.first = v.InnerProd(n) + p.path_point().s();
frenet_sd.second = v.CrossProd(n);
return frenet_sd;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/learning_based_data.cc
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/learning_based_data.h"
#include "cyber/common/log.h"
namespace apollo {
namespace planning {
void LearningBasedData::Clear() {
learning_data_.Clear();
}
void LearningBasedData::InsertLearningDataFrame(
const LearningDataFrame& learning_data_frame) {
learning_data_.add_learning_data_frame()->CopyFrom(learning_data_frame);
while (learning_data_.learning_data_frame_size() > 10) {
learning_data_.mutable_learning_data_frame()->DeleteSubrange(0, 1);
}
}
LearningDataFrame* LearningBasedData::GetLatestLearningDataFrame() {
const int size = learning_data_.learning_data_frame_size();
return size > 0 ? learning_data_.mutable_learning_data_frame(size - 1)
: nullptr;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/path_boundary.h
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <string>
#include <utility>
#include <vector>
namespace apollo {
namespace planning {
class PathBoundary {
public:
PathBoundary(const double start_s, const double delta_s,
std::vector<std::pair<double, double>> path_boundary);
virtual ~PathBoundary() = default;
double start_s() const;
double delta_s() const;
void set_boundary(const std::vector<std::pair<double, double>>& boundary);
const std::vector<std::pair<double, double>>& boundary() const;
void set_label(const std::string& label);
const std::string& label() const;
void set_blocking_obstacle_id(const std::string& obs_id);
const std::string& blocking_obstacle_id() const;
private:
double start_s_ = 0.0;
double delta_s_ = 0.0;
std::vector<std::pair<double, double>> boundary_;
std::string label_ = "regular";
std::string blocking_obstacle_id_ = "";
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/planning_context.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_context.h"
namespace apollo {
namespace planning {
void PlanningContext::Init() {}
void PlanningContext::Clear() { planning_status_.Clear(); }
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/st_graph_data.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file: st_graph_data.cc
**/
#include "modules/planning/common/st_graph_data.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::TrajectoryPoint;
void StGraphData::LoadData(const std::vector<const STBoundary*>& st_boundaries,
const double min_s_on_st_boundaries,
const apollo::common::TrajectoryPoint& init_point,
const SpeedLimit& speed_limit,
const double cruise_speed,
const double path_data_length,
const double total_time_by_conf,
planning_internal::STGraphDebug* st_graph_debug) {
init_ = true;
st_boundaries_ = st_boundaries;
min_s_on_st_boundaries_ = min_s_on_st_boundaries;
init_point_ = init_point;
speed_limit_ = speed_limit;
cruise_speed_ = cruise_speed;
path_data_length_ = path_data_length;
total_time_by_conf_ = total_time_by_conf;
st_graph_debug_ = st_graph_debug;
}
const std::vector<const STBoundary*>& StGraphData::st_boundaries() const {
return st_boundaries_;
}
double StGraphData::min_s_on_st_boundaries() const {
return min_s_on_st_boundaries_;
}
const TrajectoryPoint& StGraphData::init_point() const { return init_point_; }
const SpeedLimit& StGraphData::speed_limit() const { return speed_limit_; }
double StGraphData::cruise_speed() const {
return cruise_speed_ > 0.0 ? cruise_speed_ : FLAGS_default_cruise_speed;
}
double StGraphData::path_length() const { return path_data_length_; }
double StGraphData::total_time_by_conf() const { return total_time_by_conf_; }
planning_internal::STGraphDebug* StGraphData::mutable_st_graph_debug() {
return st_graph_debug_;
}
bool StGraphData::SetSTDrivableBoundary(
const std::vector<std::tuple<double, double, double>>& s_boundary,
const std::vector<std::tuple<double, double, double>>& v_obs_info) {
if (s_boundary.size() != v_obs_info.size()) {
return false;
}
for (size_t i = 0; i < s_boundary.size(); ++i) {
auto st_bound_instance = st_drivable_boundary_.add_st_boundary();
st_bound_instance->set_t(std::get<0>(s_boundary[i]));
st_bound_instance->set_s_lower(std::get<1>(s_boundary[i]));
st_bound_instance->set_s_upper(std::get<2>(s_boundary[i]));
if (std::get<1>(v_obs_info[i]) > -kObsSpeedIgnoreThreshold) {
st_bound_instance->set_v_obs_lower(std::get<1>(v_obs_info[i]));
}
if (std::get<2>(v_obs_info[i]) < kObsSpeedIgnoreThreshold) {
st_bound_instance->set_v_obs_upper(std::get<2>(v_obs_info[i]));
}
}
return true;
}
const STDrivableBoundary& StGraphData::st_drivable_boundary() const {
return st_drivable_boundary_;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/local_view.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <memory>
#include "modules/common_msgs/chassis_msgs/chassis.pb.h"
#include "modules/common_msgs/localization_msgs/localization.pb.h"
#include "modules/common_msgs/planning_msgs/navigation.pb.h"
#include "modules/common_msgs/perception_msgs/traffic_light_detection.pb.h"
#include "modules/common_msgs/planning_msgs/pad_msg.pb.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
#include "modules/common_msgs/routing_msgs/routing.pb.h"
#include "modules/common_msgs/storytelling_msgs/story.pb.h"
namespace apollo {
namespace planning {
/**
* @struct local_view
* @brief LocalView contains all necessary data as planning input
*/
struct LocalView {
std::shared_ptr<prediction::PredictionObstacles> prediction_obstacles;
std::shared_ptr<canbus::Chassis> chassis;
std::shared_ptr<localization::LocalizationEstimate> localization_estimate;
std::shared_ptr<perception::TrafficLightDetection> traffic_light;
std::shared_ptr<routing::RoutingResponse> routing;
std::shared_ptr<relative_map::MapMsg> relative_map;
std::shared_ptr<PadMessage> pad_msg;
std::shared_ptr<storytelling::Stories> stories;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/ego_info_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/ego_info.h"
#include "gtest/gtest.h"
#include "modules/common/util/point_factory.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/reference_line/reference_line_provider.h"
namespace apollo {
namespace planning {
TEST(EgoInfoTest, EgoInfoSimpleTest) {
const auto p = common::util::PointFactory::ToPathPoint(1.23, 3.23, 52.18, 0.0,
0.1, 0.3, 0.32, 0.4);
common::TrajectoryPoint tp;
tp.mutable_path_point()->CopyFrom(p);
auto ego_info = std::make_unique<EgoInfo>();
ego_info->set_start_point(tp);
EXPECT_DOUBLE_EQ(ego_info->start_point().path_point().x(), p.x());
EXPECT_DOUBLE_EQ(ego_info->start_point().path_point().y(), p.y());
EXPECT_DOUBLE_EQ(ego_info->start_point().path_point().z(), p.z());
uint32_t sequence_num = 0;
common::TrajectoryPoint planning_start_point;
common::VehicleState vehicle_state;
ReferenceLineProvider reference_line_provider;
LocalView dummy_local_view;
Frame frame(sequence_num, dummy_local_view, planning_start_point,
vehicle_state, &reference_line_provider);
ego_info->CalculateFrontObstacleClearDistance(frame.obstacles());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/frame.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 frame.cc
**/
#include "modules/planning/common/frame.h"
#include <algorithm>
#include <limits>
#include "absl/strings/str_cat.h"
#include "cyber/common/log.h"
#include "cyber/time/clock.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/point_factory.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/map/pnc_map/path.h"
#include "modules/map/pnc_map/pnc_map.h"
#include "modules/planning/common/feature_output.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/util/util.h"
#include "modules/planning/reference_line/reference_line_provider.h"
#include "modules/common_msgs/routing_msgs/routing.pb.h"
namespace apollo {
namespace planning {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::math::Box2d;
using apollo::common::math::Polygon2d;
using apollo::cyber::Clock;
using apollo::prediction::PredictionObstacles;
PadMessage::DrivingAction Frame::pad_msg_driving_action_ = PadMessage::NONE;
FrameHistory::FrameHistory()
: IndexedQueue<uint32_t, Frame>(FLAGS_max_frame_history_num) {}
Frame::Frame(uint32_t sequence_num)
: sequence_num_(sequence_num),
monitor_logger_buffer_(common::monitor::MonitorMessageItem::PLANNING) {}
Frame::Frame(uint32_t sequence_num, const LocalView &local_view,
const common::TrajectoryPoint &planning_start_point,
const common::VehicleState &vehicle_state,
ReferenceLineProvider *reference_line_provider)
: sequence_num_(sequence_num),
local_view_(local_view),
planning_start_point_(planning_start_point),
vehicle_state_(vehicle_state),
reference_line_provider_(reference_line_provider),
monitor_logger_buffer_(common::monitor::MonitorMessageItem::PLANNING) {}
Frame::Frame(uint32_t sequence_num, const LocalView &local_view,
const common::TrajectoryPoint &planning_start_point,
const common::VehicleState &vehicle_state)
: Frame(sequence_num, local_view, planning_start_point, vehicle_state,
nullptr) {}
const common::TrajectoryPoint &Frame::PlanningStartPoint() const {
return planning_start_point_;
}
const common::VehicleState &Frame::vehicle_state() const {
return vehicle_state_;
}
bool Frame::Rerouting(PlanningContext *planning_context) {
if (FLAGS_use_navigation_mode) {
AERROR << "Rerouting not supported in navigation mode";
return false;
}
if (local_view_.routing == nullptr) {
AERROR << "No previous routing available";
return false;
}
if (!hdmap_) {
AERROR << "Invalid HD Map.";
return false;
}
auto request = local_view_.routing->routing_request();
request.clear_header();
auto point = common::util::PointFactory::ToPointENU(vehicle_state_);
double s = 0.0;
double l = 0.0;
hdmap::LaneInfoConstPtr lane;
if (hdmap_->GetNearestLaneWithHeading(point, 5.0, vehicle_state_.heading(),
M_PI / 3.0, &lane, &s, &l) != 0) {
AERROR << "Failed to find nearest lane from map at position: "
<< point.DebugString() << ", heading:" << vehicle_state_.heading();
return false;
}
request.clear_waypoint();
auto *start_point = request.add_waypoint();
start_point->set_id(lane->id().id());
start_point->set_s(s);
start_point->mutable_pose()->CopyFrom(point);
for (const auto &waypoint : future_route_waypoints_) {
// reference_line_provider_->FutureRouteWaypoints()) {
request.add_waypoint()->CopyFrom(waypoint);
}
if (request.waypoint_size() <= 1) {
AERROR << "Failed to find future waypoints";
return false;
}
auto *rerouting =
planning_context->mutable_planning_status()->mutable_rerouting();
rerouting->set_need_rerouting(true);
*rerouting->mutable_routing_request() = request;
monitor_logger_buffer_.INFO("Planning send Rerouting request");
return true;
}
const std::list<ReferenceLineInfo> &Frame::reference_line_info() const {
return reference_line_info_;
}
std::list<ReferenceLineInfo> *Frame::mutable_reference_line_info() {
return &reference_line_info_;
}
void Frame::UpdateReferenceLinePriority(
const std::map<std::string, uint32_t> &id_to_priority) {
for (const auto &pair : id_to_priority) {
const auto id = pair.first;
const auto priority = pair.second;
auto ref_line_info_itr =
std::find_if(reference_line_info_.begin(), reference_line_info_.end(),
[&id](const ReferenceLineInfo &ref_line_info) {
return ref_line_info.Lanes().Id() == id;
});
if (ref_line_info_itr != reference_line_info_.end()) {
ref_line_info_itr->SetPriority(priority);
}
}
}
bool Frame::CreateReferenceLineInfo(
const std::list<ReferenceLine> &reference_lines,
const std::list<hdmap::RouteSegments> &segments) {
reference_line_info_.clear();
auto ref_line_iter = reference_lines.begin();
auto segments_iter = segments.begin();
while (ref_line_iter != reference_lines.end()) {
if (segments_iter->StopForDestination()) {
is_near_destination_ = true;
}
reference_line_info_.emplace_back(vehicle_state_, planning_start_point_,
*ref_line_iter, *segments_iter);
++ref_line_iter;
++segments_iter;
}
if (reference_line_info_.size() == 2) {
common::math::Vec2d xy_point(vehicle_state_.x(), vehicle_state_.y());
common::SLPoint first_sl;
if (!reference_line_info_.front().reference_line().XYToSL(xy_point,
&first_sl)) {
return false;
}
common::SLPoint second_sl;
if (!reference_line_info_.back().reference_line().XYToSL(xy_point,
&second_sl)) {
return false;
}
const double offset = first_sl.l() - second_sl.l();
reference_line_info_.front().SetOffsetToOtherReferenceLine(offset);
reference_line_info_.back().SetOffsetToOtherReferenceLine(-offset);
}
bool has_valid_reference_line = false;
for (auto &ref_info : reference_line_info_) {
if (!ref_info.Init(obstacles())) {
AERROR << "Failed to init reference line";
} else {
has_valid_reference_line = true;
}
}
return has_valid_reference_line;
}
/**
* @brief: create static virtual object with lane width,
* mainly used for virtual stop wall
*/
const Obstacle *Frame::CreateStopObstacle(
ReferenceLineInfo *const reference_line_info,
const std::string &obstacle_id, const double obstacle_s) {
if (reference_line_info == nullptr) {
AERROR << "reference_line_info nullptr";
return nullptr;
}
const auto &reference_line = reference_line_info->reference_line();
const double box_center_s = obstacle_s + FLAGS_virtual_stop_wall_length / 2.0;
auto box_center = reference_line.GetReferencePoint(box_center_s);
double heading = reference_line.GetReferencePoint(obstacle_s).heading();
static constexpr double kStopWallWidth = 4.0;
Box2d stop_wall_box{box_center, heading, FLAGS_virtual_stop_wall_length,
kStopWallWidth};
return CreateStaticVirtualObstacle(obstacle_id, stop_wall_box);
}
/**
* @brief: create static virtual object with lane width,
* mainly used for virtual stop wall
*/
const Obstacle *Frame::CreateStopObstacle(const std::string &obstacle_id,
const std::string &lane_id,
const double lane_s) {
if (!hdmap_) {
AERROR << "Invalid HD Map.";
return nullptr;
}
const auto lane = hdmap_->GetLaneById(hdmap::MakeMapId(lane_id));
if (!lane) {
AERROR << "Failed to find lane[" << lane_id << "]";
return nullptr;
}
double dest_lane_s = std::max(0.0, lane_s);
auto dest_point = lane->GetSmoothPoint(dest_lane_s);
double lane_left_width = 0.0;
double lane_right_width = 0.0;
lane->GetWidth(dest_lane_s, &lane_left_width, &lane_right_width);
Box2d stop_wall_box{{dest_point.x(), dest_point.y()},
lane->Heading(dest_lane_s),
FLAGS_virtual_stop_wall_length,
lane_left_width + lane_right_width};
return CreateStaticVirtualObstacle(obstacle_id, stop_wall_box);
}
/**
* @brief: create static virtual object with lane width,
*/
const Obstacle *Frame::CreateStaticObstacle(
ReferenceLineInfo *const reference_line_info,
const std::string &obstacle_id, const double obstacle_start_s,
const double obstacle_end_s) {
if (reference_line_info == nullptr) {
AERROR << "reference_line_info nullptr";
return nullptr;
}
const auto &reference_line = reference_line_info->reference_line();
// start_xy
common::SLPoint sl_point;
sl_point.set_s(obstacle_start_s);
sl_point.set_l(0.0);
common::math::Vec2d obstacle_start_xy;
if (!reference_line.SLToXY(sl_point, &obstacle_start_xy)) {
AERROR << "Failed to get start_xy from sl: " << sl_point.DebugString();
return nullptr;
}
// end_xy
sl_point.set_s(obstacle_end_s);
sl_point.set_l(0.0);
common::math::Vec2d obstacle_end_xy;
if (!reference_line.SLToXY(sl_point, &obstacle_end_xy)) {
AERROR << "Failed to get end_xy from sl: " << sl_point.DebugString();
return nullptr;
}
double left_lane_width = 0.0;
double right_lane_width = 0.0;
if (!reference_line.GetLaneWidth(obstacle_start_s, &left_lane_width,
&right_lane_width)) {
AERROR << "Failed to get lane width at s[" << obstacle_start_s << "]";
return nullptr;
}
common::math::Box2d obstacle_box{
common::math::LineSegment2d(obstacle_start_xy, obstacle_end_xy),
left_lane_width + right_lane_width};
return CreateStaticVirtualObstacle(obstacle_id, obstacle_box);
}
const Obstacle *Frame::CreateStaticVirtualObstacle(const std::string &id,
const Box2d &box) {
const auto *object = obstacles_.Find(id);
if (object) {
AWARN << "obstacle " << id << " already exist.";
return object;
}
auto *ptr =
obstacles_.Add(id, *Obstacle::CreateStaticVirtualObstacles(id, box));
if (!ptr) {
AERROR << "Failed to create virtual obstacle " << id;
}
return ptr;
}
Status Frame::Init(
const common::VehicleStateProvider *vehicle_state_provider,
const std::list<ReferenceLine> &reference_lines,
const std::list<hdmap::RouteSegments> &segments,
const std::vector<routing::LaneWaypoint> &future_route_waypoints,
const EgoInfo *ego_info) {
// TODO(QiL): refactor this to avoid redundant nullptr checks in scenarios.
auto status = InitFrameData(vehicle_state_provider, ego_info);
if (!status.ok()) {
AERROR << "failed to init frame:" << status.ToString();
return status;
}
if (!CreateReferenceLineInfo(reference_lines, segments)) {
const std::string msg = "Failed to init reference line info.";
AERROR << msg;
return Status(ErrorCode::PLANNING_ERROR, msg);
}
future_route_waypoints_ = future_route_waypoints;
return Status::OK();
}
Status Frame::InitForOpenSpace(
const common::VehicleStateProvider *vehicle_state_provider,
const EgoInfo *ego_info) {
return InitFrameData(vehicle_state_provider, ego_info);
}
Status Frame::InitFrameData(
const common::VehicleStateProvider *vehicle_state_provider,
const EgoInfo *ego_info) {
hdmap_ = hdmap::HDMapUtil::BaseMapPtr();
CHECK_NOTNULL(hdmap_);
vehicle_state_ = vehicle_state_provider->vehicle_state();
if (!util::IsVehicleStateValid(vehicle_state_)) {
AERROR << "Adc init point is not set";
return Status(ErrorCode::PLANNING_ERROR, "Adc init point is not set");
}
ADEBUG << "Enabled align prediction time ? : " << std::boolalpha
<< FLAGS_align_prediction_time;
if (FLAGS_align_prediction_time) {
auto prediction = *(local_view_.prediction_obstacles);
AlignPredictionTime(vehicle_state_.timestamp(), &prediction);
local_view_.prediction_obstacles->CopyFrom(prediction);
}
for (auto &ptr :
Obstacle::CreateObstacles(*local_view_.prediction_obstacles)) {
AddObstacle(*ptr);
}
if (planning_start_point_.v() < 1e-3) {
const auto *collision_obstacle = FindCollisionObstacle(ego_info);
if (collision_obstacle != nullptr) {
const std::string msg = absl::StrCat(
"Found collision with obstacle: ", collision_obstacle->Id());
AERROR << msg;
monitor_logger_buffer_.ERROR(msg);
return Status(ErrorCode::PLANNING_ERROR, msg);
}
}
ReadTrafficLights();
ReadPadMsgDrivingAction();
return Status::OK();
}
const Obstacle *Frame::FindCollisionObstacle(const EgoInfo *ego_info) const {
if (obstacles_.Items().empty()) {
return nullptr;
}
const auto &adc_polygon = Polygon2d(ego_info->ego_box());
for (const auto &obstacle : obstacles_.Items()) {
if (obstacle->IsVirtual()) {
continue;
}
const auto &obstacle_polygon = obstacle->PerceptionPolygon();
if (obstacle_polygon.HasOverlap(adc_polygon)) {
return obstacle;
}
}
return nullptr;
}
uint32_t Frame::SequenceNum() const { return sequence_num_; }
std::string Frame::DebugString() const {
return absl::StrCat("Frame: ", sequence_num_);
}
void Frame::RecordInputDebug(planning_internal::Debug *debug) {
if (!debug) {
ADEBUG << "Skip record input into debug";
return;
}
auto *planning_debug_data = debug->mutable_planning_data();
auto *adc_position = planning_debug_data->mutable_adc_position();
adc_position->CopyFrom(*local_view_.localization_estimate);
auto debug_chassis = planning_debug_data->mutable_chassis();
debug_chassis->CopyFrom(*local_view_.chassis);
if (!FLAGS_use_navigation_mode) {
auto debug_routing = planning_debug_data->mutable_routing();
debug_routing->CopyFrom(*local_view_.routing);
}
planning_debug_data->mutable_prediction_header()->CopyFrom(
local_view_.prediction_obstacles->header());
/*
auto relative_map = AdapterManager::GetRelativeMap();
if (!relative_map->Empty()) {
planning_debug_data->mutable_relative_map()->mutable_header()->CopyFrom(
relative_map->GetLatestObserved().header());
}
*/
}
void Frame::AlignPredictionTime(const double planning_start_time,
PredictionObstacles *prediction_obstacles) {
if (!prediction_obstacles || !prediction_obstacles->has_header() ||
!prediction_obstacles->header().has_timestamp_sec()) {
return;
}
double prediction_header_time =
prediction_obstacles->header().timestamp_sec();
for (auto &obstacle : *prediction_obstacles->mutable_prediction_obstacle()) {
for (auto &trajectory : *obstacle.mutable_trajectory()) {
for (auto &point : *trajectory.mutable_trajectory_point()) {
point.set_relative_time(prediction_header_time + point.relative_time() -
planning_start_time);
}
if (!trajectory.trajectory_point().empty() &&
trajectory.trajectory_point().begin()->relative_time() < 0) {
auto it = trajectory.trajectory_point().begin();
while (it != trajectory.trajectory_point().end() &&
it->relative_time() < 0) {
++it;
}
trajectory.mutable_trajectory_point()->erase(
trajectory.trajectory_point().begin(), it);
}
}
}
}
Obstacle *Frame::Find(const std::string &id) { return obstacles_.Find(id); }
void Frame::AddObstacle(const Obstacle &obstacle) {
obstacles_.Add(obstacle.Id(), obstacle);
}
void Frame::ReadTrafficLights() {
traffic_lights_.clear();
const auto traffic_light_detection = local_view_.traffic_light;
if (traffic_light_detection == nullptr) {
return;
}
const double delay = traffic_light_detection->header().timestamp_sec() -
Clock::NowInSeconds();
if (delay > FLAGS_signal_expire_time_sec) {
ADEBUG << "traffic signals msg is expired, delay = " << delay
<< " seconds.";
return;
}
for (const auto &traffic_light : traffic_light_detection->traffic_light()) {
traffic_lights_[traffic_light.id()] = &traffic_light;
}
}
perception::TrafficLight Frame::GetSignal(
const std::string &traffic_light_id) const {
const auto *result =
apollo::common::util::FindPtrOrNull(traffic_lights_, traffic_light_id);
if (result == nullptr) {
perception::TrafficLight traffic_light;
traffic_light.set_id(traffic_light_id);
traffic_light.set_color(perception::TrafficLight::UNKNOWN);
traffic_light.set_confidence(0.0);
traffic_light.set_tracking_time(0.0);
return traffic_light;
}
return *result;
}
void Frame::ReadPadMsgDrivingAction() {
if (local_view_.pad_msg) {
if (local_view_.pad_msg->has_action()) {
pad_msg_driving_action_ = local_view_.pad_msg->action();
}
}
}
void Frame::ResetPadMsgDrivingAction() {
pad_msg_driving_action_ = PadMessage::NONE;
}
const ReferenceLineInfo *Frame::FindDriveReferenceLineInfo() {
double min_cost = std::numeric_limits<double>::infinity();
drive_reference_line_info_ = nullptr;
for (const auto &reference_line_info : reference_line_info_) {
if (reference_line_info.IsDrivable() &&
reference_line_info.Cost() < min_cost) {
drive_reference_line_info_ = &reference_line_info;
min_cost = reference_line_info.Cost();
}
}
return drive_reference_line_info_;
}
const ReferenceLineInfo *Frame::FindTargetReferenceLineInfo() {
const ReferenceLineInfo *target_reference_line_info = nullptr;
for (const auto &reference_line_info : reference_line_info_) {
if (reference_line_info.IsChangeLanePath()) {
return &reference_line_info;
}
target_reference_line_info = &reference_line_info;
}
return target_reference_line_info;
}
const ReferenceLineInfo *Frame::FindFailedReferenceLineInfo() {
for (const auto &reference_line_info : reference_line_info_) {
// Find the unsuccessful lane-change path
if (!reference_line_info.IsDrivable() &&
reference_line_info.IsChangeLanePath()) {
return &reference_line_info;
}
}
return nullptr;
}
const ReferenceLineInfo *Frame::DriveReferenceLineInfo() const {
return drive_reference_line_info_;
}
const std::vector<const Obstacle *> Frame::obstacles() const {
return obstacles_.Items();
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/speed_profile_generator_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/speed_profile_generator.h"
#include "gtest/gtest.h"
#include "modules/planning/common/ego_info.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
TEST(SpeedProfileGeneratorTest, GenerateFallbackSpeedProfile) {}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/decision_data.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/decision_data.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
// this sanity check will move to the very beginning of planning
bool DecisionData::IsValidTrajectoryPoint(
const common::TrajectoryPoint& point) {
return !((!point.has_path_point()) || std::isnan(point.path_point().x()) ||
std::isnan(point.path_point().y()) ||
std::isnan(point.path_point().z()) ||
std::isnan(point.path_point().kappa()) ||
std::isnan(point.path_point().s()) ||
std::isnan(point.path_point().dkappa()) ||
std::isnan(point.path_point().ddkappa()) || std::isnan(point.v()) ||
std::isnan(point.a()) || std::isnan(point.relative_time()));
}
bool DecisionData::IsValidTrajectory(const prediction::Trajectory& trajectory) {
for (const auto& point : trajectory.trajectory_point()) {
if (!IsValidTrajectoryPoint(point)) {
AERROR << " TrajectoryPoint: " << trajectory.ShortDebugString()
<< " is NOT valid.";
return false;
}
}
return true;
}
DecisionData::DecisionData(
const prediction::PredictionObstacles& prediction_obstacles,
const ReferenceLine& reference_line)
: reference_line_(reference_line) {
for (const auto& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
const std::string perception_id =
std::to_string(prediction_obstacle.perception_obstacle().id());
if (prediction_obstacle.trajectory().empty()) {
obstacles_.emplace_back(new Obstacle(
perception_id, prediction_obstacle.perception_obstacle()));
all_obstacle_.emplace_back(obstacles_.back().get());
practical_obstacle_.emplace_back(obstacles_.back().get());
static_obstacle_.emplace_back(obstacles_.back().get());
obstacle_map_[perception_id] = obstacles_.back().get();
continue;
}
int trajectory_index = 0;
for (const auto& trajectory : prediction_obstacle.trajectory()) {
if (!IsValidTrajectory(trajectory)) {
AERROR << "obj:" << perception_id;
continue;
}
const std::string obstacle_id =
absl::StrCat(perception_id, "_", trajectory_index);
obstacles_.emplace_back(new Obstacle(
obstacle_id, prediction_obstacle.perception_obstacle(), trajectory));
all_obstacle_.emplace_back(obstacles_.back().get());
practical_obstacle_.emplace_back(obstacles_.back().get());
dynamic_obstacle_.emplace_back(obstacles_.back().get());
obstacle_map_[obstacle_id] = obstacles_.back().get();
++trajectory_index;
}
}
}
Obstacle* DecisionData::GetObstacleById(const std::string& id) {
std::lock_guard<std::mutex> lock(mutex_);
return common::util::FindPtrOrNull(obstacle_map_, id);
}
std::vector<Obstacle*> DecisionData::GetObstacleByType(
const VirtualObjectType& type) {
std::lock_guard<std::mutex> lock(transaction_mutex_);
std::unordered_set<std::string> ids = GetObstacleIdByType(type);
if (ids.empty()) {
return std::vector<Obstacle*>();
}
std::vector<Obstacle*> ret;
for (const std::string& id : ids) {
ret.emplace_back(GetObstacleById(id));
if (ret.back() == nullptr) {
AERROR << "Ignore. can't find obstacle by id: " << id;
ret.pop_back();
}
}
return ret;
}
std::unordered_set<std::string> DecisionData::GetObstacleIdByType(
const VirtualObjectType& type) {
std::lock_guard<std::mutex> lock(mutex_);
return common::util::FindWithDefault(virtual_obstacle_id_map_, type, {});
}
const std::vector<Obstacle*>& DecisionData::GetStaticObstacle() const {
return static_obstacle_;
}
const std::vector<Obstacle*>& DecisionData::GetDynamicObstacle() const {
return dynamic_obstacle_;
}
const std::vector<Obstacle*>& DecisionData::GetVirtualObstacle() const {
return virtual_obstacle_;
}
const std::vector<Obstacle*>& DecisionData::GetPracticalObstacle() const {
return practical_obstacle_;
}
const std::vector<Obstacle*>& DecisionData::GetAllObstacle() const {
return all_obstacle_;
}
bool DecisionData::CreateVirtualObstacle(const ReferencePoint& point,
const VirtualObjectType& type,
std::string* const id) {
// should build different box by type;
common::SLPoint sl_point;
if (!reference_line_.XYToSL(point, &sl_point)) {
return false;
}
double obstacle_s = sl_point.s();
const double box_center_s = obstacle_s + FLAGS_virtual_stop_wall_length / 2.0;
auto box_center = reference_line_.GetReferencePoint(box_center_s);
double heading = reference_line_.GetReferencePoint(obstacle_s).heading();
double lane_left_width = 0.0;
double lane_right_width = 0.0;
reference_line_.GetLaneWidth(obstacle_s, &lane_left_width, &lane_right_width);
common::math::Box2d box(box_center, heading, FLAGS_virtual_stop_wall_length,
lane_left_width + lane_right_width);
return CreateVirtualObstacle(box, type, id);
}
bool DecisionData::CreateVirtualObstacle(const double point_s,
const VirtualObjectType& type,
std::string* const id) {
// should build different box by type;
const double box_center_s = point_s + FLAGS_virtual_stop_wall_length / 2.0;
auto box_center = reference_line_.GetReferencePoint(box_center_s);
double heading = reference_line_.GetReferencePoint(point_s).heading();
double lane_left_width = 0.0;
double lane_right_width = 0.0;
reference_line_.GetLaneWidth(point_s, &lane_left_width, &lane_right_width);
common::math::Box2d box(box_center, heading, FLAGS_virtual_stop_wall_length,
lane_left_width + lane_right_width);
return CreateVirtualObstacle(box, type, id);
}
bool DecisionData::CreateVirtualObstacle(
const common::math::Box2d& obstacle_box, const VirtualObjectType& type,
std::string* const id) {
std::lock_guard<std::mutex> transaction_lock(transaction_mutex_);
std::lock_guard<std::mutex> lock(mutex_);
perception::PerceptionObstacle perception_obstacle;
// TODO(All) please chagne is_virtual in obstacle
perception_obstacle.set_id(virtual_obstacle_.size() + 1);
perception_obstacle.mutable_position()->set_x(obstacle_box.center().x());
perception_obstacle.mutable_position()->set_y(obstacle_box.center().y());
perception_obstacle.set_theta(obstacle_box.heading());
perception_obstacle.mutable_velocity()->set_x(0);
perception_obstacle.mutable_velocity()->set_y(0);
perception_obstacle.set_length(obstacle_box.length());
perception_obstacle.set_width(obstacle_box.width());
perception_obstacle.set_height(FLAGS_virtual_stop_wall_height);
perception_obstacle.set_type(
perception::PerceptionObstacle::UNKNOWN_UNMOVABLE);
perception_obstacle.set_tracking_time(1.0);
std::vector<common::math::Vec2d> corner_points;
obstacle_box.GetAllCorners(&corner_points);
for (const auto& corner_point : corner_points) {
auto* point = perception_obstacle.add_polygon_point();
point->set_x(corner_point.x());
point->set_y(corner_point.y());
}
*id = std::to_string(perception_obstacle.id());
obstacles_.emplace_back(new Obstacle(*id, perception_obstacle));
all_obstacle_.emplace_back(obstacles_.back().get());
virtual_obstacle_.emplace_back(obstacles_.back().get());
// would be changed if some virtual type is not static one
static_obstacle_.emplace_back(obstacles_.back().get());
virtual_obstacle_id_map_[type].insert(*id);
obstacle_map_[*id] = obstacles_.back().get();
return true;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/history.h
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include <list>
#include <string>
#include <unordered_map>
#include <vector>
#include "cyber/common/macros.h"
#include "modules/common_msgs/planning_msgs/planning.pb.h"
namespace apollo {
namespace planning {
class HistoryObjectDecision {
public:
HistoryObjectDecision() = default;
void Init(const ObjectDecision& object_decisions);
void Init(const std::string& id,
const std::vector<ObjectDecisionType>& object_decisions);
const std::string& id() const { return id_; }
std::vector<const ObjectDecisionType*> GetObjectDecision() const;
private:
std::string id_;
std::vector<ObjectDecisionType> object_decision_;
};
class HistoryFrame {
public:
HistoryFrame() = default;
void Init(const ADCTrajectory& adc_trajactory);
int seq_num() const { return seq_num_; }
std::vector<const HistoryObjectDecision*> GetObjectDecisions() const;
std::vector<const HistoryObjectDecision*> GetStopObjectDecisions() const;
const HistoryObjectDecision* GetObjectDecisionsById(
const std::string& id) const;
private:
int seq_num_;
ADCTrajectory adc_trajactory_;
std::unordered_map<std::string, HistoryObjectDecision> object_decisions_map_;
std::vector<HistoryObjectDecision> object_decisions_;
};
class HistoryObjectStatus {
public:
HistoryObjectStatus() = default;
void Init(const std::string& id, const ObjectStatus& object_status);
const std::string& id() const { return id_; }
const ObjectStatus GetObjectStatus() const { return object_status_; }
private:
std::string id_;
ObjectStatus object_status_;
};
class HistoryStatus {
public:
HistoryStatus() = default;
void SetObjectStatus(const std::string& id,
const ObjectStatus& object_status);
bool GetObjectStatus(const std::string& id,
ObjectStatus* const object_status);
private:
std::unordered_map<std::string, ObjectStatus> object_id_to_status_;
};
class History {
public:
History() = default;
const HistoryFrame* GetLastFrame() const;
int Add(const ADCTrajectory& adc_trajectory_pb);
void Clear();
size_t Size() const;
HistoryStatus* mutable_history_status() { return &history_status_; }
private:
std::list<HistoryFrame> history_frames_;
HistoryStatus history_status_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/indexed_queue_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/common/indexed_queue.h"
#include "gtest/gtest.h"
#include "modules/common/util/future.h"
namespace apollo {
namespace planning {
using StringIndexedQueue = IndexedQueue<int, std::string>;
TEST(IndexedQueue, QueueSize1) {
StringIndexedQueue object(1);
ASSERT_TRUE(object.Add(1, std::make_unique<std::string>("one")));
ASSERT_TRUE(object.Find(1) != nullptr);
ASSERT_TRUE(object.Find(2) == nullptr);
ASSERT_FALSE(object.Add(1, std::make_unique<std::string>("one")));
ASSERT_EQ("one", *object.Latest());
ASSERT_TRUE(object.Add(2, std::make_unique<std::string>("two")));
ASSERT_TRUE(object.Find(1) == nullptr);
ASSERT_TRUE(object.Find(2) != nullptr);
ASSERT_EQ("two", *object.Latest());
}
TEST(IndexedQueue, QueueSize2) {
StringIndexedQueue object(2);
ASSERT_TRUE(object.Add(1, std::make_unique<std::string>("one")));
ASSERT_TRUE(object.Find(1) != nullptr);
ASSERT_TRUE(object.Find(2) == nullptr);
ASSERT_FALSE(object.Add(1, std::make_unique<std::string>("one")));
ASSERT_EQ("one", *object.Latest());
ASSERT_TRUE(object.Add(2, std::make_unique<std::string>("two")));
ASSERT_TRUE(object.Find(1) != nullptr);
ASSERT_TRUE(object.Find(2) != nullptr);
ASSERT_EQ("two", *object.Latest());
ASSERT_TRUE(object.Add(3, std::make_unique<std::string>("three")));
ASSERT_TRUE(object.Find(1) == nullptr);
ASSERT_TRUE(object.Find(2) != nullptr);
ASSERT_TRUE(object.Find(3) != nullptr);
ASSERT_TRUE(object.Find(4) == nullptr);
ASSERT_EQ("three", *object.Latest());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/feature_output.cc
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/feature_output.h"
#include "absl/strings/str_cat.h"
#include "cyber/common/file.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
LearningData FeatureOutput::learning_data_;
int FeatureOutput::learning_data_file_index_ = 0;
void FeatureOutput::Close() { Clear(); }
void FeatureOutput::Clear() {
learning_data_.Clear();
learning_data_file_index_ = 0;
}
bool FeatureOutput::Ready() {
Clear();
return true;
}
void FeatureOutput::InsertLearningDataFrame(
const std::string& record_file,
const LearningDataFrame& learning_data_frame) {
learning_data_.add_learning_data_frame()->CopyFrom(learning_data_frame);
// write frames into a file
if (learning_data_.learning_data_frame_size() >=
FLAGS_learning_data_frame_num_per_file) {
WriteLearningData(record_file);
}
}
LearningDataFrame* FeatureOutput::GetLatestLearningDataFrame() {
const int size = learning_data_.learning_data_frame_size();
return size > 0 ? learning_data_.mutable_learning_data_frame(size - 1)
: nullptr;
}
void FeatureOutput::InsertPlanningResult() {}
void FeatureOutput::WriteLearningData(const std::string& record_file) {
std::string src_file_name =
record_file.substr(record_file.find_last_of("/") + 1);
src_file_name = src_file_name.empty() ? "00000" : src_file_name;
const std::string dest_file =
absl::StrCat(FLAGS_planning_data_dir, "/", src_file_name, ".",
learning_data_file_index_, ".bin");
cyber::common::SetProtoToBinaryFile(learning_data_, dest_file);
// cyber::common::SetProtoToASCIIFile(learning_data_, dest_file + ".txt");
learning_data_.Clear();
learning_data_file_index_++;
}
void FeatureOutput::WriteRemainderiLearningData(
const std::string& record_file) {
if (learning_data_.learning_data_frame_size() > 0) {
WriteLearningData(record_file);
}
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/st_graph_data_test.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/st_graph_data.h"
#include "cyber/common/log.h"
#include "gmock/gmock.h"
#include "modules/planning/common/speed/st_boundary.h"
namespace apollo {
namespace planning {
TEST(StGraphDataTest, basic_test) {
std::vector<const STBoundary*> boundary_vec;
auto boundary = STBoundary();
boundary_vec.push_back(&boundary);
apollo::common::TrajectoryPoint traj_point;
traj_point.mutable_path_point()->set_x(1.1);
traj_point.mutable_path_point()->set_y(2.1);
traj_point.mutable_path_point()->set_theta(0.2);
traj_point.mutable_path_point()->set_kappa(0.02);
traj_point.mutable_path_point()->set_dkappa(0.123);
traj_point.mutable_path_point()->set_ddkappa(0.003);
traj_point.set_v(10.001);
traj_point.set_a(1.022);
traj_point.set_relative_time(1010.022);
SpeedLimit speed_limit;
double cruise_speed = 5.0;
double path_data_length = 100.0;
double total_time_by_conf = 7.0;
planning_internal::STGraphDebug* st_graph_debug = nullptr;
StGraphData st_graph_data;
st_graph_data.LoadData(boundary_vec, 0.0, traj_point, speed_limit,
cruise_speed, path_data_length, total_time_by_conf,
st_graph_debug);
EXPECT_EQ(st_graph_data.st_boundaries().size(), 1);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().x(), 1.1);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().y(), 2.1);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().z(), 0.0);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().theta(), 0.2);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().kappa(), 0.02);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().dkappa(), 0.123);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().path_point().ddkappa(), 0.003);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().v(), 10.001);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().a(), 1.022);
EXPECT_DOUBLE_EQ(st_graph_data.init_point().relative_time(), 1010.022);
EXPECT_DOUBLE_EQ(st_graph_data.path_length(), 100.0);
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/frame_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/common/frame.h"
#include "cyber/common/file.h"
#include "gtest/gtest.h"
#include "modules/common/util/util.h"
#include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
namespace apollo {
namespace planning {
class FrameTest : public ::testing::Test {
public:
virtual void SetUp() {
ASSERT_TRUE(cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/sample_prediction.pb.txt",
&prediction_obstacles_));
}
protected:
prediction::PredictionObstacles prediction_obstacles_;
};
TEST_F(FrameTest, AlignPredictionTime) {
int first_traj_size = prediction_obstacles_.prediction_obstacle(0)
.trajectory(0)
.trajectory_point_size();
double origin_pred_time = prediction_obstacles_.header().timestamp_sec();
Frame::AlignPredictionTime(origin_pred_time + 0.1, &prediction_obstacles_);
ASSERT_EQ(first_traj_size - 1, prediction_obstacles_.prediction_obstacle(0)
.trajectory(0)
.trajectory_point_size());
Frame::AlignPredictionTime(origin_pred_time + 0.5, &prediction_obstacles_);
ASSERT_EQ(first_traj_size - 3, prediction_obstacles_.prediction_obstacle(0)
.trajectory(0)
.trajectory_point_size());
Frame::AlignPredictionTime(origin_pred_time + 12.0, &prediction_obstacles_);
ASSERT_EQ(0, prediction_obstacles_.prediction_obstacle(0)
.trajectory(0)
.trajectory_point_size());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/path_boundary.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/common/path_boundary.h"
namespace apollo {
namespace planning {
PathBoundary::PathBoundary(const double start_s, const double delta_s,
std::vector<std::pair<double, double>> path_boundary)
: start_s_(start_s),
delta_s_(delta_s),
boundary_(std::move(path_boundary)) {}
double PathBoundary::start_s() const { return start_s_; }
double PathBoundary::delta_s() const { return delta_s_; }
void PathBoundary::set_boundary(
const std::vector<std::pair<double, double>>& boundary) {
boundary_ = boundary;
}
const std::vector<std::pair<double, double>>& PathBoundary::boundary() const {
return boundary_;
}
void PathBoundary::set_label(const std::string& label) { label_ = label; }
const std::string& PathBoundary::label() const { return label_; }
void PathBoundary::set_blocking_obstacle_id(const std::string& obs_id) {
blocking_obstacle_id_ = obs_id;
}
const std::string& PathBoundary::blocking_obstacle_id() const {
return blocking_obstacle_id_;
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/history_test.cc
|
/* Copyright 2019 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/planning/common/history.h"
#include "cyber/common/file.h"
#include "gtest/gtest.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
class HistoryTest : public ::testing::Test {
public:
HistoryTest() {
history_.reset(new History());
history_->Clear();
}
protected:
std::unique_ptr<History> history_;
};
TEST_F(HistoryTest, Add) {
history_->Clear();
ADCTrajectory adc_trajectory;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_01.pb.txt",
&adc_trajectory));
int ret = history_->Add(adc_trajectory);
EXPECT_EQ(0, ret);
}
TEST_F(HistoryTest, GetLastFrame) {
FLAGS_history_max_record_num = 3; // capacity
history_->Clear();
ADCTrajectory adc_trajectory_1;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_01.pb.txt",
&adc_trajectory_1));
ADCTrajectory adc_trajectory_2;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_02.pb.txt",
&adc_trajectory_2));
// seq_num: 1
history_->Add(adc_trajectory_1);
EXPECT_NE(nullptr, history_->GetLastFrame());
EXPECT_EQ(1, history_->Size());
EXPECT_EQ(1, history_->GetLastFrame()->seq_num());
// seq_num: 2
history_->Add(adc_trajectory_2);
EXPECT_NE(nullptr, history_->GetLastFrame());
EXPECT_EQ(2, history_->Size());
EXPECT_EQ(2, history_->GetLastFrame()->seq_num());
// seq_num: 1
history_->Add(adc_trajectory_1);
EXPECT_NE(nullptr, history_->GetLastFrame());
EXPECT_EQ(3, history_->Size());
EXPECT_EQ(1, history_->GetLastFrame()->seq_num());
// seq_num: 2
history_->Add(adc_trajectory_2);
EXPECT_NE(nullptr, history_->GetLastFrame());
EXPECT_EQ(3, history_->Size());
EXPECT_EQ(2, history_->GetLastFrame()->seq_num());
}
TEST_F(HistoryTest, GetObjectDecisions) {
history_->Clear();
ADCTrajectory adc_trajectory;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_01.pb.txt",
&adc_trajectory));
history_->Add(adc_trajectory);
EXPECT_NE(nullptr, history_->GetLastFrame());
std::vector<const HistoryObjectDecision*> object_decisions =
history_->GetLastFrame()->GetObjectDecisions();
EXPECT_EQ(3, object_decisions.size());
// sort
std::sort(
object_decisions.begin(), object_decisions.end(),
[](const HistoryObjectDecision* lhs, const HistoryObjectDecision* rhs) {
return lhs->id() < rhs->id();
});
for (const HistoryObjectDecision* object_decision : object_decisions) {
ADEBUG << "object_decision[" << object_decision->id() << "]";
auto obj_decision = object_decision->GetObjectDecision();
for (const ObjectDecisionType* decision_type : obj_decision) {
ADEBUG << " decistion_type[" << decision_type->object_tag_case() << "]";
}
}
// 11720: nudge, stop
EXPECT_STREQ("11720", object_decisions[0]->id().c_str());
auto obj_decision = object_decisions[0]->GetObjectDecision();
EXPECT_EQ(2, obj_decision.size());
// sort
std::sort(obj_decision.begin(), obj_decision.end(),
[](const ObjectDecisionType* lhs, const ObjectDecisionType* rhs) {
return lhs->object_tag_case() < rhs->object_tag_case();
});
EXPECT_TRUE(obj_decision[0]->has_stop());
EXPECT_TRUE(obj_decision[1]->has_nudge());
// CW_2832: stop
EXPECT_STREQ("CW_2832", object_decisions[1]->id().c_str());
obj_decision = object_decisions[1]->GetObjectDecision();
EXPECT_EQ(1, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
// TL_2516: stop
EXPECT_STREQ("TL_2516", object_decisions[2]->id().c_str());
obj_decision = object_decisions[2]->GetObjectDecision();
EXPECT_EQ(1, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
}
TEST_F(HistoryTest, GetStopObjectDecisions) {
history_->Clear();
ADCTrajectory adc_trajectory;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_01.pb.txt",
&adc_trajectory));
history_->Add(adc_trajectory);
EXPECT_NE(nullptr, history_->GetLastFrame());
std::vector<const HistoryObjectDecision*> object_decisions =
history_->GetLastFrame()->GetStopObjectDecisions();
EXPECT_EQ(3, object_decisions.size());
// 11720: stop
EXPECT_STREQ("11720", object_decisions[0]->id().c_str());
auto obj_decision = object_decisions[0]->GetObjectDecision();
EXPECT_EQ(1, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
// CW_2832: stop
EXPECT_STREQ("CW_2832", object_decisions[1]->id().c_str());
obj_decision = object_decisions[1]->GetObjectDecision();
EXPECT_EQ(1, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
// TL_2516: stop
EXPECT_STREQ("TL_2516", object_decisions[2]->id().c_str());
obj_decision = object_decisions[2]->GetObjectDecision();
EXPECT_EQ(1, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
}
TEST_F(HistoryTest, GetObjectDecisionsById) {
history_->Clear();
ADCTrajectory adc_trajectory;
EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
"/apollo/modules/planning/testdata/common/history_01.pb.txt",
&adc_trajectory));
history_->Add(adc_trajectory);
EXPECT_NE(nullptr, history_->GetLastFrame());
// 11720: nudge, stop
const HistoryObjectDecision* object_decision =
history_->GetLastFrame()->GetObjectDecisionsById("11720");
EXPECT_STREQ("11720", object_decision->id().c_str());
auto obj_decision = object_decision->GetObjectDecision();
// sort
std::sort(obj_decision.begin(), obj_decision.end(),
[](const ObjectDecisionType* lhs, const ObjectDecisionType* rhs) {
return lhs->object_tag_case() < rhs->object_tag_case();
});
EXPECT_EQ(2, obj_decision.size());
EXPECT_TRUE(obj_decision[0]->has_stop());
EXPECT_TRUE(obj_decision[1]->has_nudge());
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/message_process.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
*/
#pragma once
#include <chrono>
#include <fstream>
#include <list>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "modules/common_msgs/chassis_msgs/chassis.pb.h"
#include "modules/common_msgs/dreamview_msgs/hmi_status.pb.h"
#include "modules/common_msgs/localization_msgs/localization.pb.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/common_msgs/perception_msgs/traffic_light_detection.pb.h"
#include "modules/planning/common/dependency_injector.h"
#include "modules/planning/proto/learning_data.pb.h"
#include "modules/planning/proto/planning_config.pb.h"
#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
#include "modules/common_msgs/routing_msgs/routing.pb.h"
#include "modules/common_msgs/storytelling_msgs/story.pb.h"
namespace apollo {
namespace planning {
class MessageProcess {
public:
bool Init(const PlanningConfig& planning_config);
bool Init(const PlanningConfig& planning_config,
const std::shared_ptr<DependencyInjector>& injector);
void Close();
void OnChassis(const apollo::canbus::Chassis& chassis);
void OnHMIStatus(apollo::dreamview::HMIStatus hmi_status);
void OnLocalization(const apollo::localization::LocalizationEstimate& le);
void OnPrediction(
const apollo::prediction::PredictionObstacles& prediction_obstacles);
void OnRoutingResponse(
const apollo::routing::RoutingResponse& routing_response);
void OnStoryTelling(const apollo::storytelling::Stories& stories);
void OnTrafficLightDetection(
const apollo::perception::TrafficLightDetection& traffic_light_detection);
void ProcessOfflineData(const std::string& record_file);
private:
struct ADCCurrentInfo {
std::pair<double, double> adc_cur_position_;
std::pair<double, double> adc_cur_velocity_;
std::pair<double, double> adc_cur_acc_;
double adc_cur_heading_;
};
apollo::hdmap::LaneInfoConstPtr GetCurrentLane(
const apollo::common::PointENU& position);
bool GetADCCurrentRoutingIndex(int* adc_road_index, int* adc_passage_index,
double* adc_passage_s);
int GetADCCurrentInfo(ADCCurrentInfo* adc_curr_info);
void GenerateObstacleTrajectory(const int frame_num, const int obstacle_id,
const ADCCurrentInfo& adc_curr_info,
ObstacleFeature* obstacle_feature);
void GenerateObstaclePrediction(
const int frame_num,
const apollo::prediction::PredictionObstacle& prediction_obstacle,
const ADCCurrentInfo& adc_curr_info, ObstacleFeature* obstacle_feature);
void GenerateObstacleFeature(LearningDataFrame* learning_data_frame);
bool GenerateLocalRouting(
const int frame_num,
RoutingResponseFeature* local_routing,
std::vector<std::string>* local_routing_lane_ids);
void GenerateRoutingFeature(
const RoutingResponseFeature& local_routing,
const std::vector<std::string>& local_routing_lane_ids,
LearningDataFrame* learning_data_frame);
void GenerateTrafficLightDetectionFeature(
LearningDataFrame* learning_data_frame);
void GenerateADCTrajectoryPoints(
const std::list<apollo::localization::LocalizationEstimate>&
localizations,
LearningDataFrame* learning_data_frame);
void GeneratePlanningTag(LearningDataFrame* learning_data_frame);
bool GenerateLearningDataFrame(LearningDataFrame* learning_data_frame);
private:
std::shared_ptr<DependencyInjector> injector_;
PlanningConfig planning_config_;
std::chrono::time_point<std::chrono::system_clock> start_time_;
std::ofstream log_file_;
std::string record_file_;
std::unordered_map<std::string, std::string> map_m_;
LearningData learning_data_;
int learning_data_file_index_ = 0;
std::list<apollo::localization::LocalizationEstimate> localizations_;
std::unordered_map<int, apollo::prediction::PredictionObstacle>
prediction_obstacles_map_;
std::unordered_map<int, std::list<PerceptionObstacleFeature>>
obstacle_history_map_;
ChassisFeature chassis_feature_;
std::string map_name_;
PlanningTag planning_tag_;
apollo::routing::RoutingResponse routing_response_;
double traffic_light_detection_message_timestamp_;
std::vector<TrafficLightFeature> traffic_lights_;
int total_learning_data_frame_num_ = 0;
double last_localization_message_timestamp_sec_ = 0.0;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/obstacle_blocking_analyzer.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.
*****************************************************************************/
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/planning/common/frame.h"
namespace apollo {
namespace planning {
bool IsNonmovableObstacle(const ReferenceLineInfo& reference_line_info,
const Obstacle& obstacle);
/**
* @brief Decide whether an obstacle is a blocking one that needs to be
* side-passed.
* @param The frame that contains reference_line and other info.
* @param The obstacle of interest.
* @param The speed threshold to tell whether an obstacle is stopped.
* @param The minimum distance to front blocking obstacle for side-pass.
* (if too close, don't side-pass for safety consideration)
* @param Whether to take into consideration that the blocking obstacle
* itself is blocked by others as well. In other words, if the
* front blocking obstacle is blocked by others, then don't try
* to side-pass it. (Parked obstacles are never blocked by others)
*/
bool IsBlockingObstacleToSidePass(const Frame& frame, const Obstacle* obstacle,
double block_obstacle_min_speed,
double min_front_sidepass_distance,
bool enable_obstacle_blocked_check);
double GetDistanceBetweenADCAndObstacle(const Frame& frame,
const Obstacle* obstacle);
// Check if the obstacle is blocking ADC's driving path (reference_line).
bool IsBlockingDrivingPathObstacle(const ReferenceLine& reference_line,
const Obstacle* obstacle);
bool IsParkedVehicle(const ReferenceLine& reference_line,
const Obstacle* obstacle);
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/reference_line_info_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/reference_line_info.h"
#include "gtest/gtest.h"
#include "modules/common_msgs/planning_msgs/planning.pb.h"
namespace apollo {
namespace planning {
class ReferenceLineInfoTest : public ::testing::Test {
public:
virtual void SetUp() {}
protected:
ReferenceLineInfo reference_line_info_;
};
TEST_F(ReferenceLineInfoTest, BasicTest) {
EXPECT_EQ(reference_line_info_.trajectory_type(), ADCTrajectory::UNKNOWN);
reference_line_info_.set_trajectory_type(ADCTrajectory::NORMAL);
EXPECT_EQ(reference_line_info_.trajectory_type(), ADCTrajectory::NORMAL);
reference_line_info_.set_trajectory_type(ADCTrajectory::PATH_FALLBACK);
EXPECT_EQ(reference_line_info_.trajectory_type(),
ADCTrajectory::PATH_FALLBACK);
reference_line_info_.set_trajectory_type(ADCTrajectory::SPEED_FALLBACK);
EXPECT_EQ(reference_line_info_.trajectory_type(),
ADCTrajectory::SPEED_FALLBACK);
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/indexed_list_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/common/indexed_list.h"
#include "gtest/gtest.h"
#include "modules/common/util/util.h"
namespace apollo {
namespace planning {
using StringIndexedList = IndexedList<int, std::string>;
TEST(IndexedList, Add_ConstRef) {
StringIndexedList object;
{
ASSERT_NE(nullptr, object.Add(1, "one"));
ASSERT_NE(nullptr, object.Find(1));
ASSERT_NE(nullptr, object.Add(1, "one"));
const auto& items = object.Items();
ASSERT_EQ(nullptr, object.Find(2));
ASSERT_EQ(1, items.size());
ASSERT_EQ("one", *items[0]);
}
{
ASSERT_NE(nullptr, object.Add(2, "two"));
ASSERT_NE(nullptr, object.Add(2, "two"));
ASSERT_NE(nullptr, object.Find(1));
ASSERT_NE(nullptr, object.Find(2));
const auto& items = object.Items();
ASSERT_EQ(2, items.size());
ASSERT_EQ("one", *items[0]);
ASSERT_EQ("two", *items[1]);
}
}
TEST(IndexedList, Find) {
StringIndexedList object;
object.Add(1, "one");
auto* one = object.Find(1);
ASSERT_EQ(*one, "one");
ASSERT_NE(nullptr, one);
*one = "one_again";
const auto* one_again = object.Find(1);
ASSERT_NE(nullptr, one_again);
ASSERT_EQ("one_again", *one_again);
ASSERT_EQ(nullptr, object.Find(2));
}
TEST(IndexedList, Copy) {
StringIndexedList b_object;
b_object.Add(1, "one");
b_object.Add(2, "two");
StringIndexedList a_object;
a_object.Add(3, "three");
a_object.Add(4, "four");
a_object = b_object;
ASSERT_NE(nullptr, a_object.Find(1));
ASSERT_NE(nullptr, a_object.Find(2));
ASSERT_EQ(nullptr, a_object.Find(3));
ASSERT_EQ(nullptr, a_object.Find(4));
}
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/learning_based_data.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file learning_data.h
**/
#pragma once
#include <vector>
#include "modules/planning/proto/learning_data.pb.h"
namespace apollo {
namespace planning {
class LearningBasedData {
public:
LearningBasedData() = default;
void Clear();
void InsertLearningDataFrame(const LearningDataFrame& learning_data_frame);
LearningDataFrame* GetLatestLearningDataFrame();
void set_learning_data_adc_future_trajectory_points(
const std::vector<common::TrajectoryPoint> &trajectory_points) {
learning_data_adc_future_trajectory_points_ = trajectory_points;
}
const std::vector<common::TrajectoryPoint>
&learning_data_adc_future_trajectory_points() const {
return learning_data_adc_future_trajectory_points_;
}
private:
LearningData learning_data_;
std::vector<common::TrajectoryPoint>
learning_data_adc_future_trajectory_points_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/speed_limit.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 speed_limit.h
**/
#pragma once
#include <utility>
#include <vector>
namespace apollo {
namespace planning {
class SpeedLimit {
public:
SpeedLimit() = default;
void AppendSpeedLimit(const double s, const double v);
const std::vector<std::pair<double, double>>& speed_limit_points() const;
double GetSpeedLimitByS(const double s) const;
void Clear();
private:
// use a vector to represent speed limit
// the first number is s, the second number is v
// It means at distance s from the start point, the speed limit is v.
std::vector<std::pair<double, double>> speed_limit_points_;
};
} // namespace planning
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/planning
|
apollo_public_repos/apollo/modules/planning/common/reference_line_info.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/reference_line_info.h"
#include <algorithm>
#include "absl/strings/str_cat.h"
#include "modules/common_msgs/planning_msgs/sl_boundary.pb.h"
#include "modules/planning/proto/planning_status.pb.h"
#include "cyber/task/task.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/util/point_factory.h"
#include "modules/common/util/util.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/map/hdmap/hdmap_util.h"
namespace apollo {
namespace planning {
using apollo::canbus::Chassis;
using apollo::common::EngageAdvice;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleConfigHelper;
using apollo::common::VehicleSignal;
using apollo::common::math::Box2d;
using apollo::common::math::Vec2d;
using apollo::common::util::PointFactory;
std::unordered_map<std::string, bool>
ReferenceLineInfo::junction_right_of_way_map_;
ReferenceLineInfo::ReferenceLineInfo(const common::VehicleState& vehicle_state,
const TrajectoryPoint& adc_planning_point,
const ReferenceLine& reference_line,
const hdmap::RouteSegments& segments)
: vehicle_state_(vehicle_state),
adc_planning_point_(adc_planning_point),
reference_line_(reference_line),
lanes_(segments) {}
bool ReferenceLineInfo::Init(const std::vector<const Obstacle*>& obstacles) {
const auto& param = VehicleConfigHelper::GetConfig().vehicle_param();
// stitching point
const auto& path_point = adc_planning_point_.path_point();
Vec2d position(path_point.x(), path_point.y());
Vec2d vec_to_center(
(param.front_edge_to_center() - param.back_edge_to_center()) / 2.0,
(param.left_edge_to_center() - param.right_edge_to_center()) / 2.0);
Vec2d center(position + vec_to_center.rotate(path_point.theta()));
Box2d box(center, path_point.theta(), param.length(), param.width());
// realtime vehicle position
Vec2d vehicle_position(vehicle_state_.x(), vehicle_state_.y());
Vec2d vehicle_center(vehicle_position +
vec_to_center.rotate(vehicle_state_.heading()));
Box2d vehicle_box(vehicle_center, vehicle_state_.heading(), param.length(),
param.width());
if (!reference_line_.GetSLBoundary(box, &adc_sl_boundary_)) {
AERROR << "Failed to get ADC boundary from box: " << box.DebugString();
return false;
}
InitFirstOverlaps();
if (adc_sl_boundary_.end_s() < 0 ||
adc_sl_boundary_.start_s() > reference_line_.Length()) {
AWARN << "Vehicle SL " << adc_sl_boundary_.ShortDebugString()
<< " is not on reference line:[0, " << reference_line_.Length()
<< "]";
}
static constexpr double kOutOfReferenceLineL = 10.0; // in meters
if (adc_sl_boundary_.start_l() > kOutOfReferenceLineL ||
adc_sl_boundary_.end_l() < -kOutOfReferenceLineL) {
AERROR << "Ego vehicle is too far away from reference line.";
return false;
}
is_on_reference_line_ = reference_line_.IsOnLane(adc_sl_boundary_);
if (!AddObstacles(obstacles)) {
AERROR << "Failed to add obstacles to reference line";
return false;
}
const auto& map_path = reference_line_.map_path();
for (const auto& speed_bump : map_path.speed_bump_overlaps()) {
// -1 and + 1.0 are added to make sure it can be sampled.
reference_line_.AddSpeedLimit(speed_bump.start_s - 1.0,
speed_bump.end_s + 1.0,
FLAGS_speed_bump_speed_limit);
}
SetCruiseSpeed(FLAGS_default_cruise_speed);
// set lattice planning target speed limit;
SetLatticeCruiseSpeed(FLAGS_default_cruise_speed);
vehicle_signal_.Clear();
return true;
}
const std::vector<PathData>& ReferenceLineInfo::GetCandidatePathData() const {
return candidate_path_data_;
}
void ReferenceLineInfo::SetCandidatePathData(
std::vector<PathData>&& candidate_path_data) {
candidate_path_data_ = std::move(candidate_path_data);
}
const std::vector<PathBoundary>& ReferenceLineInfo::GetCandidatePathBoundaries()
const {
return candidate_path_boundaries_;
}
void ReferenceLineInfo::SetCandidatePathBoundaries(
std::vector<PathBoundary>&& path_boundaries) {
candidate_path_boundaries_ = std::move(path_boundaries);
}
double ReferenceLineInfo::GetCruiseSpeed() const {
return cruise_speed_ > 0.0 ? cruise_speed_ : FLAGS_default_cruise_speed;
}
hdmap::LaneInfoConstPtr ReferenceLineInfo::LocateLaneInfo(
const double s) const {
std::vector<hdmap::LaneInfoConstPtr> lanes;
reference_line_.GetLaneFromS(s, &lanes);
if (lanes.empty()) {
AWARN << "cannot get any lane using s";
return nullptr;
}
return lanes.front();
}
bool ReferenceLineInfo::GetNeighborLaneInfo(
const ReferenceLineInfo::LaneType lane_type, const double s,
hdmap::Id* ptr_lane_id, double* ptr_lane_width) const {
auto ptr_lane_info = LocateLaneInfo(s);
if (ptr_lane_info == nullptr) {
return false;
}
switch (lane_type) {
case LaneType::LeftForward: {
if (ptr_lane_info->lane().left_neighbor_forward_lane_id().empty()) {
return false;
}
*ptr_lane_id = ptr_lane_info->lane().left_neighbor_forward_lane_id(0);
break;
}
case LaneType::LeftReverse: {
if (ptr_lane_info->lane().left_neighbor_reverse_lane_id().empty()) {
return false;
}
*ptr_lane_id = ptr_lane_info->lane().left_neighbor_reverse_lane_id(0);
break;
}
case LaneType::RightForward: {
if (ptr_lane_info->lane().right_neighbor_forward_lane_id().empty()) {
return false;
}
*ptr_lane_id = ptr_lane_info->lane().right_neighbor_forward_lane_id(0);
break;
}
case LaneType::RightReverse: {
if (ptr_lane_info->lane().right_neighbor_reverse_lane_id().empty()) {
return false;
}
*ptr_lane_id = ptr_lane_info->lane().right_neighbor_reverse_lane_id(0);
break;
}
default:
ACHECK(false);
}
auto ptr_neighbor_lane =
hdmap::HDMapUtil::BaseMapPtr()->GetLaneById(*ptr_lane_id);
if (ptr_neighbor_lane == nullptr) {
return false;
}
auto ref_point = reference_line_.GetReferencePoint(s);
double neighbor_s = 0.0;
double neighbor_l = 0.0;
if (!ptr_neighbor_lane->GetProjection({ref_point.x(), ref_point.y()},
&neighbor_s, &neighbor_l)) {
return false;
}
*ptr_lane_width = ptr_neighbor_lane->GetWidth(neighbor_s);
return true;
}
bool ReferenceLineInfo::GetFirstOverlap(
const std::vector<hdmap::PathOverlap>& path_overlaps,
hdmap::PathOverlap* path_overlap) {
CHECK_NOTNULL(path_overlap);
const double start_s = adc_sl_boundary_.end_s();
static constexpr double kMaxOverlapRange = 500.0;
double overlap_min_s = kMaxOverlapRange;
auto overlap_min_s_iter = path_overlaps.end();
for (auto iter = path_overlaps.begin(); iter != path_overlaps.end(); ++iter) {
if (iter->end_s < start_s) {
continue;
}
if (overlap_min_s > iter->start_s) {
overlap_min_s_iter = iter;
overlap_min_s = iter->start_s;
}
}
// Ensure that the path_overlaps is not empty.
if (overlap_min_s_iter != path_overlaps.end()) {
*path_overlap = *overlap_min_s_iter;
}
return overlap_min_s < kMaxOverlapRange;
}
void ReferenceLineInfo::InitFirstOverlaps() {
const auto& map_path = reference_line_.map_path();
// clear_zone
hdmap::PathOverlap clear_area_overlap;
if (GetFirstOverlap(map_path.clear_area_overlaps(), &clear_area_overlap)) {
first_encounter_overlaps_.emplace_back(CLEAR_AREA, clear_area_overlap);
}
// crosswalk
hdmap::PathOverlap crosswalk_overlap;
if (GetFirstOverlap(map_path.crosswalk_overlaps(), &crosswalk_overlap)) {
first_encounter_overlaps_.emplace_back(CROSSWALK, crosswalk_overlap);
}
// pnc_junction
hdmap::PathOverlap pnc_junction_overlap;
if (GetFirstOverlap(map_path.pnc_junction_overlaps(),
&pnc_junction_overlap)) {
first_encounter_overlaps_.emplace_back(PNC_JUNCTION, pnc_junction_overlap);
}
// signal
hdmap::PathOverlap signal_overlap;
if (GetFirstOverlap(map_path.signal_overlaps(), &signal_overlap)) {
first_encounter_overlaps_.emplace_back(SIGNAL, signal_overlap);
}
// stop_sign
hdmap::PathOverlap stop_sign_overlap;
if (GetFirstOverlap(map_path.stop_sign_overlaps(), &stop_sign_overlap)) {
first_encounter_overlaps_.emplace_back(STOP_SIGN, stop_sign_overlap);
}
// yield_sign
hdmap::PathOverlap yield_sign_overlap;
if (GetFirstOverlap(map_path.yield_sign_overlaps(), &yield_sign_overlap)) {
first_encounter_overlaps_.emplace_back(YIELD_SIGN, yield_sign_overlap);
}
// sort by start_s
if (!first_encounter_overlaps_.empty()) {
std::sort(first_encounter_overlaps_.begin(),
first_encounter_overlaps_.end(),
[](const std::pair<OverlapType, hdmap::PathOverlap>& a,
const std::pair<OverlapType, hdmap::PathOverlap>& b) {
return a.second.start_s < b.second.start_s;
});
}
}
bool WithinOverlap(const hdmap::PathOverlap& overlap, double s) {
static constexpr double kEpsilon = 1e-2;
return overlap.start_s - kEpsilon <= s && s <= overlap.end_s + kEpsilon;
}
void ReferenceLineInfo::SetJunctionRightOfWay(const double junction_s,
const bool is_protected) const {
for (const auto& overlap : reference_line_.map_path().junction_overlaps()) {
if (WithinOverlap(overlap, junction_s)) {
junction_right_of_way_map_[overlap.object_id] = is_protected;
}
}
}
ADCTrajectory::RightOfWayStatus ReferenceLineInfo::GetRightOfWayStatus() const {
for (const auto& overlap : reference_line_.map_path().junction_overlaps()) {
if (overlap.end_s < adc_sl_boundary_.start_s()) {
junction_right_of_way_map_.erase(overlap.object_id);
} else if (WithinOverlap(overlap, adc_sl_boundary_.end_s())) {
auto is_protected = junction_right_of_way_map_[overlap.object_id];
if (is_protected) {
return ADCTrajectory::PROTECTED;
}
}
}
return ADCTrajectory::UNPROTECTED;
}
const hdmap::RouteSegments& ReferenceLineInfo::Lanes() const { return lanes_; }
std::list<hdmap::Id> ReferenceLineInfo::TargetLaneId() const {
std::list<hdmap::Id> lane_ids;
for (const auto& lane_seg : lanes_) {
lane_ids.push_back(lane_seg.lane->id());
}
return lane_ids;
}
const SLBoundary& ReferenceLineInfo::AdcSlBoundary() const {
return adc_sl_boundary_;
}
PathDecision* ReferenceLineInfo::path_decision() { return &path_decision_; }
const PathDecision& ReferenceLineInfo::path_decision() const {
return path_decision_;
}
const ReferenceLine& ReferenceLineInfo::reference_line() const {
return reference_line_;
}
ReferenceLine* ReferenceLineInfo::mutable_reference_line() {
return &reference_line_;
}
void ReferenceLineInfo::SetTrajectory(const DiscretizedTrajectory& trajectory) {
discretized_trajectory_ = trajectory;
}
bool ReferenceLineInfo::AddObstacleHelper(
const std::shared_ptr<Obstacle>& obstacle) {
return AddObstacle(obstacle.get()) != nullptr;
}
// AddObstacle is thread safe
Obstacle* ReferenceLineInfo::AddObstacle(const Obstacle* obstacle) {
if (!obstacle) {
AERROR << "The provided obstacle is empty";
return nullptr;
}
auto* mutable_obstacle = path_decision_.AddObstacle(*obstacle);
if (!mutable_obstacle) {
AERROR << "failed to add obstacle " << obstacle->Id();
return nullptr;
}
SLBoundary perception_sl;
if (!reference_line_.GetSLBoundary(obstacle->PerceptionBoundingBox(),
&perception_sl)) {
AERROR << "Failed to get sl boundary for obstacle: " << obstacle->Id();
return mutable_obstacle;
}
mutable_obstacle->SetPerceptionSlBoundary(perception_sl);
mutable_obstacle->CheckLaneBlocking(reference_line_);
if (mutable_obstacle->IsLaneBlocking()) {
ADEBUG << "obstacle [" << obstacle->Id() << "] is lane blocking.";
} else {
ADEBUG << "obstacle [" << obstacle->Id() << "] is NOT lane blocking.";
}
if (IsIrrelevantObstacle(*mutable_obstacle)) {
ObjectDecisionType ignore;
ignore.mutable_ignore();
path_decision_.AddLateralDecision("reference_line_filter", obstacle->Id(),
ignore);
path_decision_.AddLongitudinalDecision("reference_line_filter",
obstacle->Id(), ignore);
ADEBUG << "NO build reference line st boundary. id:" << obstacle->Id();
} else {
ADEBUG << "build reference line st boundary. id:" << obstacle->Id();
mutable_obstacle->BuildReferenceLineStBoundary(reference_line_,
adc_sl_boundary_.start_s());
ADEBUG << "reference line st boundary: t["
<< mutable_obstacle->reference_line_st_boundary().min_t() << ", "
<< mutable_obstacle->reference_line_st_boundary().max_t() << "] s["
<< mutable_obstacle->reference_line_st_boundary().min_s() << ", "
<< mutable_obstacle->reference_line_st_boundary().max_s() << "]";
}
return mutable_obstacle;
}
bool ReferenceLineInfo::AddObstacles(
const std::vector<const Obstacle*>& obstacles) {
if (FLAGS_use_multi_thread_to_add_obstacles) {
std::vector<std::future<Obstacle*>> results;
for (const auto* obstacle : obstacles) {
results.push_back(
cyber::Async(&ReferenceLineInfo::AddObstacle, this, obstacle));
}
for (auto& result : results) {
if (!result.get()) {
AERROR << "Fail to add obstacles.";
return false;
}
}
} else {
for (const auto* obstacle : obstacles) {
if (!AddObstacle(obstacle)) {
AERROR << "Failed to add obstacle " << obstacle->Id();
return false;
}
}
}
return true;
}
bool ReferenceLineInfo::IsIrrelevantObstacle(const Obstacle& obstacle) {
if (obstacle.IsCautionLevelObstacle()) {
return false;
}
// if adc is on the road, and obstacle behind adc, ignore
const auto& obstacle_boundary = obstacle.PerceptionSLBoundary();
if (obstacle_boundary.end_s() > reference_line_.Length()) {
return true;
}
if (is_on_reference_line_ && !IsChangeLanePath() &&
obstacle_boundary.end_s() < adc_sl_boundary_.end_s() &&
(reference_line_.IsOnLane(obstacle_boundary) ||
obstacle_boundary.end_s() < 0.0)) { // if obstacle is far backward
return true;
}
return false;
}
const DiscretizedTrajectory& ReferenceLineInfo::trajectory() const {
return discretized_trajectory_;
}
void ReferenceLineInfo::SetLatticeStopPoint(const StopPoint& stop_point) {
planning_target_.mutable_stop_point()->CopyFrom(stop_point);
}
void ReferenceLineInfo::SetLatticeCruiseSpeed(double speed) {
planning_target_.set_cruise_speed(speed);
}
bool ReferenceLineInfo::IsStartFrom(
const ReferenceLineInfo& previous_reference_line_info) const {
if (reference_line_.reference_points().empty()) {
return false;
}
auto start_point = reference_line_.reference_points().front();
const auto& prev_reference_line =
previous_reference_line_info.reference_line();
common::SLPoint sl_point;
prev_reference_line.XYToSL(start_point, &sl_point);
return previous_reference_line_info.reference_line_.IsOnLane(sl_point);
}
const PathData& ReferenceLineInfo::path_data() const { return path_data_; }
const PathData& ReferenceLineInfo::fallback_path_data() const {
return fallback_path_data_;
}
const SpeedData& ReferenceLineInfo::speed_data() const { return speed_data_; }
PathData* ReferenceLineInfo::mutable_path_data() { return &path_data_; }
PathData* ReferenceLineInfo::mutable_fallback_path_data() {
return &fallback_path_data_;
}
SpeedData* ReferenceLineInfo::mutable_speed_data() { return &speed_data_; }
const RSSInfo& ReferenceLineInfo::rss_info() const { return rss_info_; }
RSSInfo* ReferenceLineInfo::mutable_rss_info() { return &rss_info_; }
bool ReferenceLineInfo::CombinePathAndSpeedProfile(
const double relative_time, const double start_s,
DiscretizedTrajectory* ptr_discretized_trajectory) {
ACHECK(ptr_discretized_trajectory != nullptr);
// use varied resolution to reduce data load but also provide enough data
// point for control module
const double kDenseTimeResoltuion = FLAGS_trajectory_time_min_interval;
const double kSparseTimeResolution = FLAGS_trajectory_time_max_interval;
const double kDenseTimeSec = FLAGS_trajectory_time_high_density_period;
if (path_data_.discretized_path().empty()) {
AERROR << "path data is empty";
return false;
}
if (speed_data_.empty()) {
AERROR << "speed profile is empty";
return false;
}
for (double cur_rel_time = 0.0; cur_rel_time < speed_data_.TotalTime();
cur_rel_time += (cur_rel_time < kDenseTimeSec ? kDenseTimeResoltuion
: kSparseTimeResolution)) {
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_.discretized_path().Length()) {
break;
}
common::PathPoint path_point =
path_data_.GetPathPointWithPathS(speed_point.s());
path_point.set_s(path_point.s() + start_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() + relative_time);
ptr_discretized_trajectory->AppendTrajectoryPoint(trajectory_point);
}
return true;
}
// TODO(all): It is a brutal way to insert the planning init point, one elegant
// way would be bypassing trajectory stitching logics somehow, or use planing
// init point from trajectory stitching to compute the trajectory at the very
// start
bool ReferenceLineInfo::AdjustTrajectoryWhichStartsFromCurrentPos(
const common::TrajectoryPoint& planning_start_point,
const std::vector<common::TrajectoryPoint>& trajectory,
DiscretizedTrajectory* adjusted_trajectory) {
ACHECK(adjusted_trajectory != nullptr);
// find insert index by check heading
static constexpr double kMaxAngleDiff = M_PI_2;
const double start_point_heading = planning_start_point.path_point().theta();
const double start_point_x = planning_start_point.path_point().x();
const double start_point_y = planning_start_point.path_point().y();
const double start_point_relative_time = planning_start_point.relative_time();
int insert_idx = -1;
for (size_t i = 0; i < trajectory.size(); ++i) {
// skip trajectory_points early than planning_start_point
if (trajectory[i].relative_time() <= start_point_relative_time) {
continue;
}
const double cur_point_x = trajectory[i].path_point().x();
const double cur_point_y = trajectory[i].path_point().y();
const double tracking_heading =
std::atan2(cur_point_y - start_point_y, cur_point_x - start_point_x);
if (std::fabs(common::math::AngleDiff(start_point_heading,
tracking_heading)) < kMaxAngleDiff) {
insert_idx = i;
break;
}
}
if (insert_idx == -1) {
AERROR << "All points are behind of planning init point";
return false;
}
DiscretizedTrajectory cut_trajectory(trajectory);
cut_trajectory.erase(cut_trajectory.begin(),
cut_trajectory.begin() + insert_idx);
cut_trajectory.insert(cut_trajectory.begin(), planning_start_point);
// In class TrajectoryStitcher, the stitched point which is also the planning
// init point is supposed have one planning_cycle_time ahead respect to
// current timestamp as its relative time. So the relative timelines
// of planning init point and the trajectory which start from current
// position(relative time = 0) are the same. Therefore any conflicts on the
// relative time including the one below should return false and inspected its
// cause.
if (cut_trajectory.size() > 1 && cut_trajectory.front().relative_time() >=
cut_trajectory[1].relative_time()) {
AERROR << "planning init point relative_time["
<< cut_trajectory.front().relative_time()
<< "] larger than its next point's relative_time["
<< cut_trajectory[1].relative_time() << "]";
return false;
}
// In class TrajectoryStitcher, the planing_init_point is set to have s as 0,
// so adjustment is needed to be done on the other points
double accumulated_s = 0.0;
for (size_t i = 1; i < cut_trajectory.size(); ++i) {
const auto& pre_path_point = cut_trajectory[i - 1].path_point();
auto* cur_path_point = cut_trajectory[i].mutable_path_point();
accumulated_s += std::sqrt((cur_path_point->x() - pre_path_point.x()) *
(cur_path_point->x() - pre_path_point.x()) +
(cur_path_point->y() - pre_path_point.y()) *
(cur_path_point->y() - pre_path_point.y()));
cur_path_point->set_s(accumulated_s);
}
// reevaluate relative_time to make delta t the same
adjusted_trajectory->clear();
// use varied resolution to reduce data load but also provide enough data
// point for control module
const double kDenseTimeResoltuion = FLAGS_trajectory_time_min_interval;
const double kSparseTimeResolution = FLAGS_trajectory_time_max_interval;
const double kDenseTimeSec = FLAGS_trajectory_time_high_density_period;
for (double cur_rel_time = cut_trajectory.front().relative_time();
cur_rel_time <= cut_trajectory.back().relative_time();
cur_rel_time += (cur_rel_time < kDenseTimeSec ? kDenseTimeResoltuion
: kSparseTimeResolution)) {
adjusted_trajectory->AppendTrajectoryPoint(
cut_trajectory.Evaluate(cur_rel_time));
}
return true;
}
void ReferenceLineInfo::SetDrivable(bool drivable) { is_drivable_ = drivable; }
bool ReferenceLineInfo::IsDrivable() const { return is_drivable_; }
bool ReferenceLineInfo::IsChangeLanePath() const {
return !Lanes().IsOnSegment();
}
bool ReferenceLineInfo::IsNeighborLanePath() const {
return Lanes().IsNeighborSegment();
}
std::string ReferenceLineInfo::PathSpeedDebugString() const {
return absl::StrCat("path_data:", path_data_.DebugString(),
"speed_data:", speed_data_.DebugString());
}
void ReferenceLineInfo::SetTurnSignalBasedOnLaneTurnType(
common::VehicleSignal* vehicle_signal) const {
CHECK_NOTNULL(vehicle_signal);
if (vehicle_signal->has_turn_signal() &&
vehicle_signal->turn_signal() != VehicleSignal::TURN_NONE) {
return;
}
vehicle_signal->set_turn_signal(VehicleSignal::TURN_NONE);
// Set turn signal based on lane-change.
if (IsChangeLanePath()) {
if (Lanes().PreviousAction() == routing::ChangeLaneType::LEFT) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_LEFT);
} else if (Lanes().PreviousAction() == routing::ChangeLaneType::RIGHT) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_RIGHT);
}
return;
}
// Set turn signal based on lane-borrow.
if (path_data_.path_label().find("left") != std::string::npos) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_LEFT);
return;
}
if (path_data_.path_label().find("right") != std::string::npos) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_RIGHT);
return;
}
// Set turn signal based on lane's turn type.
double route_s = 0.0;
const double adc_s = adc_sl_boundary_.end_s();
for (const auto& seg : Lanes()) {
if (route_s > adc_s + FLAGS_turn_signal_distance) {
break;
}
route_s += seg.end_s - seg.start_s;
if (route_s < adc_s) {
continue;
}
const auto& turn = seg.lane->lane().turn();
if (turn == hdmap::Lane::LEFT_TURN) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_LEFT);
break;
} else if (turn == hdmap::Lane::RIGHT_TURN) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_RIGHT);
break;
} else if (turn == hdmap::Lane::U_TURN) {
// check left or right by geometry.
auto start_xy =
PointFactory::ToVec2d(seg.lane->GetSmoothPoint(seg.start_s));
auto middle_xy = PointFactory::ToVec2d(
seg.lane->GetSmoothPoint((seg.start_s + seg.end_s) / 2.0));
auto end_xy = PointFactory::ToVec2d(seg.lane->GetSmoothPoint(seg.end_s));
auto start_to_middle = middle_xy - start_xy;
auto start_to_end = end_xy - start_xy;
if (start_to_middle.CrossProd(start_to_end) < 0) {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_RIGHT);
} else {
vehicle_signal->set_turn_signal(VehicleSignal::TURN_LEFT);
}
break;
}
}
}
void ReferenceLineInfo::SetTurnSignal(
const VehicleSignal::TurnSignal& turn_signal) {
vehicle_signal_.set_turn_signal(turn_signal);
}
void ReferenceLineInfo::SetEmergencyLight() {
vehicle_signal_.set_emergency_light(true);
}
void ReferenceLineInfo::ExportVehicleSignal(
common::VehicleSignal* vehicle_signal) const {
CHECK_NOTNULL(vehicle_signal);
*vehicle_signal = vehicle_signal_;
SetTurnSignalBasedOnLaneTurnType(vehicle_signal);
}
bool ReferenceLineInfo::ReachedDestination() const {
static constexpr double kDestinationDeltaS = 0.05;
const double distance_destination = SDistanceToDestination();
return distance_destination <= kDestinationDeltaS;
}
double ReferenceLineInfo::SDistanceToDestination() const {
double res = std::numeric_limits<double>::max();
const auto* dest_ptr = path_decision_.Find(FLAGS_destination_obstacle_id);
if (!dest_ptr) {
return res;
}
if (!dest_ptr->LongitudinalDecision().has_stop()) {
return res;
}
if (!reference_line_.IsOnLane(dest_ptr->PerceptionBoundingBox().center())) {
return res;
}
const double stop_s = dest_ptr->PerceptionSLBoundary().start_s() +
dest_ptr->LongitudinalDecision().stop().distance_s();
return stop_s - adc_sl_boundary_.end_s();
}
void ReferenceLineInfo::ExportDecision(
DecisionResult* decision_result, PlanningContext* planning_context) const {
MakeDecision(decision_result, planning_context);
ExportVehicleSignal(decision_result->mutable_vehicle_signal());
auto* main_decision = decision_result->mutable_main_decision();
if (main_decision->has_stop()) {
main_decision->mutable_stop()->set_change_lane_type(
Lanes().PreviousAction());
} else if (main_decision->has_cruise()) {
main_decision->mutable_cruise()->set_change_lane_type(
Lanes().PreviousAction());
}
}
void ReferenceLineInfo::MakeDecision(DecisionResult* decision_result,
PlanningContext* planning_context) const {
CHECK_NOTNULL(decision_result);
decision_result->Clear();
// cruise by default
decision_result->mutable_main_decision()->mutable_cruise();
// check stop decision
int error_code = MakeMainStopDecision(decision_result);
if (error_code < 0) {
MakeEStopDecision(decision_result);
}
MakeMainMissionCompleteDecision(decision_result, planning_context);
SetObjectDecisions(decision_result->mutable_object_decision());
}
void ReferenceLineInfo::MakeMainMissionCompleteDecision(
DecisionResult* decision_result, PlanningContext* planning_context) const {
if (!decision_result->main_decision().has_stop()) {
return;
}
auto main_stop = decision_result->main_decision().stop();
if (main_stop.reason_code() != STOP_REASON_DESTINATION &&
main_stop.reason_code() != STOP_REASON_PULL_OVER) {
return;
}
const auto& adc_pos = adc_planning_point_.path_point();
if (common::util::DistanceXY(adc_pos, main_stop.stop_point()) >
FLAGS_destination_check_distance) {
return;
}
auto mission_complete =
decision_result->mutable_main_decision()->mutable_mission_complete();
if (ReachedDestination()) {
planning_context->mutable_planning_status()
->mutable_destination()
->set_has_passed_destination(true);
} else {
mission_complete->mutable_stop_point()->CopyFrom(main_stop.stop_point());
mission_complete->set_stop_heading(main_stop.stop_heading());
}
}
int ReferenceLineInfo::MakeMainStopDecision(
DecisionResult* decision_result) const {
double min_stop_line_s = std::numeric_limits<double>::infinity();
const Obstacle* stop_obstacle = nullptr;
const ObjectStop* stop_decision = nullptr;
for (const auto* obstacle : path_decision_.obstacles().Items()) {
const auto& object_decision = obstacle->LongitudinalDecision();
if (!object_decision.has_stop()) {
continue;
}
apollo::common::PointENU stop_point = object_decision.stop().stop_point();
common::SLPoint stop_line_sl;
reference_line_.XYToSL(stop_point, &stop_line_sl);
double stop_line_s = stop_line_sl.s();
if (stop_line_s < 0 || stop_line_s > reference_line_.Length()) {
AERROR << "Ignore object:" << obstacle->Id() << " fence route_s["
<< stop_line_s << "] not in range[0, " << reference_line_.Length()
<< "]";
continue;
}
// check stop_line_s vs adc_s
if (stop_line_s < min_stop_line_s) {
min_stop_line_s = stop_line_s;
stop_obstacle = obstacle;
stop_decision = &(object_decision.stop());
}
}
if (stop_obstacle != nullptr) {
MainStop* main_stop =
decision_result->mutable_main_decision()->mutable_stop();
main_stop->set_reason_code(stop_decision->reason_code());
main_stop->set_reason("stop by " + stop_obstacle->Id());
main_stop->mutable_stop_point()->set_x(stop_decision->stop_point().x());
main_stop->mutable_stop_point()->set_y(stop_decision->stop_point().y());
main_stop->set_stop_heading(stop_decision->stop_heading());
ADEBUG << " main stop obstacle id:" << stop_obstacle->Id()
<< " stop_line_s:" << min_stop_line_s << " stop_point: ("
<< stop_decision->stop_point().x() << stop_decision->stop_point().y()
<< " ) stop_heading: " << stop_decision->stop_heading();
return 1;
}
return 0;
}
void ReferenceLineInfo::SetObjectDecisions(
ObjectDecisions* object_decisions) const {
for (const auto obstacle : path_decision_.obstacles().Items()) {
if (!obstacle->HasNonIgnoreDecision()) {
continue;
}
auto* object_decision = object_decisions->add_decision();
object_decision->set_id(obstacle->Id());
object_decision->set_perception_id(obstacle->PerceptionId());
if (obstacle->HasLateralDecision() && !obstacle->IsLateralIgnore()) {
object_decision->add_object_decision()->CopyFrom(
obstacle->LateralDecision());
}
if (obstacle->HasLongitudinalDecision() &&
!obstacle->IsLongitudinalIgnore()) {
object_decision->add_object_decision()->CopyFrom(
obstacle->LongitudinalDecision());
}
}
}
void ReferenceLineInfo::ExportEngageAdvice(
EngageAdvice* engage_advice, PlanningContext* planning_context) const {
static EngageAdvice prev_advice;
static constexpr double kMaxAngleDiff = M_PI / 6.0;
bool engage = false;
if (!IsDrivable()) {
prev_advice.set_reason("Reference line not drivable");
} else if (!is_on_reference_line_) {
const auto& scenario_type =
planning_context->planning_status().scenario().scenario_type();
if (scenario_type == ScenarioType::PARK_AND_GO || IsChangeLanePath()) {
// note: when is_on_reference_line_ is FALSE
// (1) always engage while in PARK_AND_GO scenario
// (2) engage when "ChangeLanePath" is picked as Drivable ref line
// where most likely ADC not OnLane yet
engage = true;
} else {
prev_advice.set_reason("Not on reference line");
}
} else {
// check heading
auto ref_point =
reference_line_.GetReferencePoint(adc_sl_boundary_.end_s());
if (common::math::AngleDiff(vehicle_state_.heading(), ref_point.heading()) <
kMaxAngleDiff) {
engage = true;
} else {
prev_advice.set_reason("Vehicle heading is not aligned");
}
}
if (engage) {
if (vehicle_state_.driving_mode() !=
Chassis::DrivingMode::Chassis_DrivingMode_COMPLETE_AUTO_DRIVE) {
// READY_TO_ENGAGE when in non-AUTO mode
prev_advice.set_advice(EngageAdvice::READY_TO_ENGAGE);
} else {
// KEEP_ENGAGED when in AUTO mode
prev_advice.set_advice(EngageAdvice::KEEP_ENGAGED);
}
prev_advice.clear_reason();
} else {
if (prev_advice.advice() != EngageAdvice::DISALLOW_ENGAGE) {
prev_advice.set_advice(EngageAdvice::PREPARE_DISENGAGE);
}
}
engage_advice->CopyFrom(prev_advice);
}
void ReferenceLineInfo::MakeEStopDecision(
DecisionResult* decision_result) const {
decision_result->Clear();
MainEmergencyStop* main_estop =
decision_result->mutable_main_decision()->mutable_estop();
main_estop->set_reason_code(MainEmergencyStop::ESTOP_REASON_INTERNAL_ERR);
main_estop->set_reason("estop reason to be added");
main_estop->mutable_cruise_to_stop();
// set object decisions
ObjectDecisions* object_decisions =
decision_result->mutable_object_decision();
for (const auto obstacle : path_decision_.obstacles().Items()) {
auto* object_decision = object_decisions->add_decision();
object_decision->set_id(obstacle->Id());
object_decision->set_perception_id(obstacle->PerceptionId());
object_decision->add_object_decision()->mutable_avoid();
}
}
hdmap::Lane::LaneTurn ReferenceLineInfo::GetPathTurnType(const double s) const {
const double forward_buffer = 20.0;
double route_s = 0.0;
for (const auto& seg : Lanes()) {
if (route_s > s + forward_buffer) {
break;
}
route_s += seg.end_s - seg.start_s;
if (route_s < s) {
continue;
}
const auto& turn_type = seg.lane->lane().turn();
if (turn_type == hdmap::Lane::LEFT_TURN ||
turn_type == hdmap::Lane::RIGHT_TURN ||
turn_type == hdmap::Lane::U_TURN) {
return turn_type;
}
}
return hdmap::Lane::NO_TURN;
}
bool ReferenceLineInfo::GetIntersectionRightofWayStatus(
const hdmap::PathOverlap& pnc_junction_overlap) const {
if (GetPathTurnType(pnc_junction_overlap.start_s) != hdmap::Lane::NO_TURN) {
return false;
}
// TODO(all): iterate exits of intersection to check/compare speed-limit
return true;
}
int ReferenceLineInfo::GetPnCJunction(
const double s, hdmap::PathOverlap* pnc_junction_overlap) const {
CHECK_NOTNULL(pnc_junction_overlap);
const std::vector<hdmap::PathOverlap>& pnc_junction_overlaps =
reference_line_.map_path().pnc_junction_overlaps();
static constexpr double kError = 1.0; // meter
for (const auto& overlap : pnc_junction_overlaps) {
if (s >= overlap.start_s - kError && s <= overlap.end_s + kError) {
*pnc_junction_overlap = overlap;
return 1;
}
}
return 0;
}
int ReferenceLineInfo::GetJunction(const double s,
hdmap::PathOverlap* junction_overlap) const {
CHECK_NOTNULL(junction_overlap);
const std::vector<hdmap::PathOverlap>& junction_overlaps =
reference_line_.map_path().junction_overlaps();
static constexpr double kError = 1.0; // meter
for (const auto& overlap : junction_overlaps) {
if (s >= overlap.start_s - kError && s <= overlap.end_s + kError) {
*junction_overlap = overlap;
return 1;
}
}
return 0;
}
void ReferenceLineInfo::SetBlockingObstacle(
const std::string& blocking_obstacle_id) {
blocking_obstacle_ = path_decision_.Find(blocking_obstacle_id);
}
std::vector<common::SLPoint> ReferenceLineInfo::GetAllStopDecisionSLPoint()
const {
std::vector<common::SLPoint> result;
for (const auto* obstacle : path_decision_.obstacles().Items()) {
const auto& object_decision = obstacle->LongitudinalDecision();
if (!object_decision.has_stop()) {
continue;
}
apollo::common::PointENU stop_point = object_decision.stop().stop_point();
common::SLPoint stop_line_sl;
reference_line_.XYToSL(stop_point, &stop_line_sl);
if (stop_line_sl.s() <= 0 || stop_line_sl.s() >= reference_line_.Length()) {
continue;
}
result.push_back(stop_line_sl);
}
// sort by s
if (!result.empty()) {
std::sort(result.begin(), result.end(),
[](const common::SLPoint& a, const common::SLPoint& b) {
return a.s() < b.s();
});
}
return result;
}
} // namespace planning
} // namespace apollo
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.