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/prediction/network
apollo_public_repos/apollo/modules/prediction/network/rnn_model/rnn_model_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "gtest/gtest.h" #include "cyber/common/file.h" #include "modules/prediction/network/rnn_model/rnn_model.h" namespace apollo { namespace prediction { namespace network { class NetModelTest : public ::testing::Test { public: void SetUp() override {} }; TEST(NetModelTest, verification_test) { const std::string rnn_filename = "modules/prediction/data/rnn_vehicle_model.bin"; NetParameter net_parameter = NetParameter(); EXPECT_TRUE(cyber::common::GetProtoFromFile(rnn_filename, &net_parameter)); EXPECT_TRUE(RnnModel::Instance()->LoadModel(net_parameter)); Eigen::MatrixXf obstacle_feature; Eigen::MatrixXf lane_feature; Eigen::MatrixXf output; for (int i = 0; i < net_parameter.verification_samples_size(); ++i) { VerificationSample sample = net_parameter.verification_samples(i); EXPECT_EQ(sample.features_size(), 2); EXPECT_TRUE(LoadTensor(sample.features(0), &obstacle_feature)); EXPECT_TRUE(LoadTensor(sample.features(1), &lane_feature)); RnnModel::Instance()->Run({obstacle_feature, lane_feature}, &output); EXPECT_EQ(output.size(), 2); EXPECT_TRUE(sample.has_probability()); EXPECT_NEAR(output(0, 0), sample.probability(), 0.1); RnnModel::Instance()->ResetState(); } } } // namespace network } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/network
apollo_public_repos/apollo/modules/prediction/network/rnn_model/rnn_model.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <vector> #include "cyber/common/macros.h" #include "modules/prediction/network/net_model.h" /** * @namespace apollo::prediction::network * @brief apollo::prediction::network */ namespace apollo { namespace prediction { namespace network { /** * @class RnnModel * @brief RnnModel is a derived class from NetModel, it has a specific layers * structure. */ class RnnModel : public NetModel { public: /** * @brief Compute the model output from inputs according to a defined layers' * flow * @param Inputs to the network * @param Output of the network will be returned */ void Run(const std::vector<Eigen::MatrixXf>& inputs, Eigen::MatrixXf* output) const override; /** * @brief Set the internal state of a network model * @param A specified internal state in a vector of Eigen::MatrixXf */ void SetState(const std::vector<Eigen::MatrixXf>& states) override; /** * @brief Access to the internal state of a network model * @return Internal state in a vector of Eigen::MatrixXf of the model */ void State(std::vector<Eigen::MatrixXf>* states) const override; /** * @brief Set the internal state of a model * @param A specified internal state in a vector of Eigen::MatrixXf */ void ResetState() const override; DECLARE_SINGLETON(RnnModel) }; } // namespace network } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/network
apollo_public_repos/apollo/modules/prediction/network/rnn_model/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "rnn_model", srcs = ["rnn_model.cc"], hdrs = ["rnn_model.h"], deps = [ "//cyber", "//modules/prediction/network:net_model", ], ) cc_test( name = "rnn_model_test", size = "small", srcs = ["rnn_model_test.cc"], data = [ "//modules/prediction:prediction_data", ], deps = [ "//cyber", "//modules/prediction/network/rnn_model", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/container/container_manager_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/prediction/container/container_manager.h" #include "cyber/common/file.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; class ContainerManagerTest : public ::testing::Test { public: virtual void SetUp() { manager_.reset(new ContainerManager()); } protected: std::unique_ptr<ContainerManager> manager_ = nullptr; common::adapter::AdapterManagerConfig conf_; }; TEST_F(ContainerManagerTest, GetContainer) { std::string conf_file = "modules/prediction/testdata/adapter_conf.pb.txt"; bool ret_load_conf = cyber::common::GetProtoFromFile(conf_file, &conf_); EXPECT_TRUE(ret_load_conf); EXPECT_TRUE(conf_.IsInitialized()); manager_->Init(conf_); EXPECT_TRUE(manager_->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES) != nullptr); EXPECT_TRUE(manager_->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION) != nullptr); EXPECT_TRUE(manager_->GetContainer<PoseContainer>( AdapterConfig::CONTROL_COMMAND) == nullptr); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/container/container_manager.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/prediction/container/container_manager.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/container/storytelling/storytelling_container.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManagerConfig; void ContainerManager::Init(const AdapterManagerConfig& config) { config_.CopyFrom(config); RegisterContainers(); } void ContainerManager::RegisterContainers() { for (const auto& adapter_config : config_.config()) { if (adapter_config.has_type() && (adapter_config.mode() == AdapterConfig::RECEIVE_ONLY || adapter_config.mode() == AdapterConfig::DUPLEX)) { RegisterContainer(adapter_config.type()); } } } std::unique_ptr<Container> ContainerManager::CreateContainer( const AdapterConfig::MessageType& type) { std::unique_ptr<Container> container_ptr(nullptr); if (type == AdapterConfig::PERCEPTION_OBSTACLES) { container_ptr.reset(new ObstaclesContainer()); } else if (type == AdapterConfig::LOCALIZATION) { container_ptr.reset(new PoseContainer()); } else if (type == AdapterConfig::PLANNING_TRAJECTORY) { container_ptr.reset(new ADCTrajectoryContainer()); } else if (type == AdapterConfig::STORYTELLING) { container_ptr.reset(new StoryTellingContainer()); } return container_ptr; } void ContainerManager::RegisterContainer( const AdapterConfig::MessageType& type) { containers_[static_cast<int>(type)] = CreateContainer(type); AINFO << "Container [" << type << "] is registered."; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/container/container.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 * @brief Define the data container base class */ #pragma once #include "google/protobuf/message.h" /** * @namespace apollo::prediction * @brief apollo::prediction */ namespace apollo { namespace prediction { class Container { public: /** * @brief Constructor */ Container() = default; /** * @brief Destructor */ virtual ~Container() = default; /** * @brief Insert data into the container * @param Message data in protobuf format */ virtual void Insert(const ::google::protobuf::Message& message) = 0; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/container/container_manager.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 * @brief Use container manager to manage all containers */ #pragma once #include <memory> #include <unordered_map> #include "cyber/common/macros.h" #include "gtest/gtest.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/prediction/container/container.h" /** * @namespace apollo::prediction * @brief apollo::prediction */ namespace apollo { namespace prediction { class ContainerManager { public: /** * @brief Constructor */ ContainerManager() = default; /** * @brief Container manager initialization * @param Adapter config */ void Init(const common::adapter::AdapterManagerConfig &config); /** * @brief Get mutable container * @param Type of the container * @return Pointer to the container given the name */ template <typename T> T *GetContainer(const common::adapter::AdapterConfig::MessageType &type) { auto key_type = static_cast<int>(type); if (containers_.find(key_type) != containers_.end()) { return static_cast<T *>(containers_[key_type].get()); } return nullptr; } /** * @brief Create a container * @param Container type * @return Container pointer */ std::unique_ptr<Container> CreateContainer( const common::adapter::AdapterConfig::MessageType &type); FRIEND_TEST(FeatureExtractorTest, junction); FRIEND_TEST(ScenarioManagerTest, run); private: /** * @brief Register a container * @param Container type */ void RegisterContainer( const common::adapter::AdapterConfig::MessageType &type); /** * @brief Register all containers */ void RegisterContainers(); private: std::unordered_map<int, std::unique_ptr<Container>> containers_; common::adapter::AdapterManagerConfig config_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/container/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "container_manager", srcs = ["container_manager.cc"], hdrs = ["container_manager.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/common/adapters/proto:adapter_config_cc_proto", "//modules/prediction/container/adc_trajectory:adc_trajectory_container", "//modules/prediction/container/obstacles:obstacles_container", "//modules/prediction/container/pose:pose_container", "//modules/prediction/container/storytelling:storytelling_container", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "container_manager_test", size = "small", srcs = ["container_manager_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ "//modules/prediction/container:container_manager", ], ) cc_library( name = "container", hdrs = ["container.h"], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacles_container_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/prediction/container/obstacles/obstacles_container.h" #include "cyber/common/file.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { class ObstaclesContainerTest : public KMLMapBasedTest { public: virtual void SetUp() { const std::string file = "modules/prediction/testdata/perception_vehicles_pedestrians.pb.txt"; perception::PerceptionObstacles perception_obstacles; cyber::common::GetProtoFromFile(file, &perception_obstacles); container_.Insert(perception_obstacles); } protected: ObstaclesContainer container_; }; TEST_F(ObstaclesContainerTest, Vehicles) { Obstacle* obstacle_ptr0 = container_.GetObstacle(0); EXPECT_NE(nullptr, obstacle_ptr0); EXPECT_EQ(obstacle_ptr0->id(), 0); EXPECT_EQ(obstacle_ptr0->type(), perception::PerceptionObstacle::VEHICLE); Obstacle* obstacle_ptr1 = container_.GetObstacle(1); EXPECT_NE(nullptr, obstacle_ptr1); EXPECT_EQ(obstacle_ptr1->id(), 1); EXPECT_EQ(obstacle_ptr1->type(), perception::PerceptionObstacle::VEHICLE); Obstacle* obstacle_ptr2 = container_.GetObstacle(2); EXPECT_NE(nullptr, obstacle_ptr2); EXPECT_EQ(obstacle_ptr2->id(), 2); EXPECT_EQ(obstacle_ptr2->type(), perception::PerceptionObstacle::VEHICLE); Obstacle* obstacle_ptr3 = container_.GetObstacle(3); EXPECT_NE(nullptr, obstacle_ptr3); EXPECT_EQ(obstacle_ptr3->id(), 3); EXPECT_EQ(obstacle_ptr3->type(), perception::PerceptionObstacle::VEHICLE); Obstacle* obstacle_ptr4 = container_.GetObstacle(4); EXPECT_EQ(nullptr, obstacle_ptr4); EXPECT_EQ(container_.curr_frame_movable_obstacle_ids().size(), 6); } TEST_F(ObstaclesContainerTest, Pedestrian) { Obstacle* obstacle_ptr101 = container_.GetObstacle(101); EXPECT_NE(nullptr, obstacle_ptr101); EXPECT_EQ(obstacle_ptr101->id(), 101); EXPECT_EQ(obstacle_ptr101->type(), perception::PerceptionObstacle::PEDESTRIAN); Obstacle* obstacle_ptr102 = container_.GetObstacle(102); EXPECT_NE(nullptr, obstacle_ptr102); EXPECT_EQ(obstacle_ptr102->id(), 102); EXPECT_EQ(obstacle_ptr102->type(), perception::PerceptionObstacle::PEDESTRIAN); Obstacle* obstacle_ptr103 = container_.GetObstacle(103); EXPECT_EQ(nullptr, obstacle_ptr103); } TEST_F(ObstaclesContainerTest, ClearAll) { container_.Clear(); EXPECT_EQ(nullptr, container_.GetObstacle(0)); EXPECT_EQ(nullptr, container_.GetObstacle(1)); EXPECT_EQ(nullptr, container_.GetObstacle(2)); EXPECT_EQ(nullptr, container_.GetObstacle(3)); EXPECT_EQ(nullptr, container_.GetObstacle(101)); EXPECT_EQ(nullptr, container_.GetObstacle(102)); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/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. *****************************************************************************/ #include "absl/strings/str_cat.h" #include "cyber/common/file.h" #include "modules/prediction/common/kml_map_based_test.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/container/obstacles/obstacles_container.h" namespace apollo { namespace prediction { class ObstacleTest : public KMLMapBasedTest { public: virtual void SetUp() { FLAGS_p_var = 0.1; FLAGS_q_var = 0.1; FLAGS_r_var = 0.001; FLAGS_enable_kf_tracking = false; FLAGS_min_prediction_trajectory_spatial_length = 50.0; FLAGS_adjust_velocity_by_position_shift = false; FLAGS_adjust_vehicle_heading_by_lane = false; int num_frame = 3; for (int i = 1; i <= num_frame; ++i) { const auto filename = absl::StrCat( "modules/prediction/testdata/frame_sequence/frame_", i, ".pb.txt"); perception::PerceptionObstacles perception_obstacles; cyber::common::GetProtoFromFile(filename, &perception_obstacles); container_.Insert(perception_obstacles); container_.BuildLaneGraph(); } } protected: ObstaclesContainer container_; }; TEST_F(ObstacleTest, VehicleBasic) { Obstacle* obstacle_ptr = container_.GetObstacle(1); EXPECT_NE(obstacle_ptr, nullptr); EXPECT_EQ(obstacle_ptr->id(), 1); EXPECT_EQ(obstacle_ptr->type(), perception::PerceptionObstacle::VEHICLE); EXPECT_TRUE(obstacle_ptr->IsOnLane()); EXPECT_EQ(obstacle_ptr->history_size(), 3); EXPECT_DOUBLE_EQ(obstacle_ptr->timestamp(), 0.2); } TEST_F(ObstacleTest, VehiclePosition) { Obstacle* obstacle_ptr = container_.GetObstacle(1); const Feature& start_feature = obstacle_ptr->feature(2); EXPECT_DOUBLE_EQ(start_feature.timestamp(), 0.0); EXPECT_DOUBLE_EQ(start_feature.position().x(), -458.941); EXPECT_DOUBLE_EQ(start_feature.position().y(), -159.240); Feature* mid_feature_ptr = obstacle_ptr->mutable_feature(1); EXPECT_DOUBLE_EQ(mid_feature_ptr->timestamp(), 0.1); EXPECT_DOUBLE_EQ(mid_feature_ptr->position().x(), -457.010); EXPECT_DOUBLE_EQ(mid_feature_ptr->position().y(), -160.023); const Feature& latest_feature = obstacle_ptr->latest_feature(); EXPECT_DOUBLE_EQ(latest_feature.timestamp(), 0.2); EXPECT_DOUBLE_EQ(latest_feature.position().x(), -455.182); EXPECT_DOUBLE_EQ(latest_feature.position().y(), -160.608); } TEST_F(ObstacleTest, VehicleVelocity) { Obstacle* obstacle_ptr = container_.GetObstacle(1); const Feature& start_feature = obstacle_ptr->feature(2); EXPECT_DOUBLE_EQ(start_feature.timestamp(), 0.0); EXPECT_DOUBLE_EQ(start_feature.velocity().x(), 18.794); EXPECT_DOUBLE_EQ(start_feature.velocity().y(), -6.839); const Feature& mid_feature = obstacle_ptr->feature(1); EXPECT_DOUBLE_EQ(mid_feature.timestamp(), 0.1); EXPECT_DOUBLE_EQ(mid_feature.velocity().x(), 17.994); EXPECT_DOUBLE_EQ(mid_feature.velocity().y(), -6.8390000000000004); Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); EXPECT_DOUBLE_EQ(latest_feature_ptr->timestamp(), 0.2); EXPECT_DOUBLE_EQ(latest_feature_ptr->velocity().x(), 17.994); EXPECT_DOUBLE_EQ(latest_feature_ptr->velocity().y(), -6.8390000000000004); EXPECT_NEAR(latest_feature_ptr->speed(), 19.249830051197854, 0.001); } TEST_F(ObstacleTest, VehicleHeading) { Obstacle* obstacle_ptr = container_.GetObstacle(1); const Feature& latest_feature = obstacle_ptr->latest_feature(); EXPECT_DOUBLE_EQ(latest_feature.theta(), -0.352); } TEST_F(ObstacleTest, VehicleLaneGraph) { Obstacle* obstacle_ptr = container_.GetObstacle(1); const Feature& latest_feature = obstacle_ptr->latest_feature(); const LaneGraph& lane_graph = latest_feature.lane().lane_graph(); EXPECT_EQ(lane_graph.lane_sequence_size(), 2); EXPECT_EQ(lane_graph.lane_sequence(0).lane_segment_size(), 3); EXPECT_EQ(lane_graph.lane_sequence(0).lane_segment(0).lane_id(), "l164"); EXPECT_EQ(lane_graph.lane_sequence(0).lane_segment(1).lane_id(), "l120"); EXPECT_EQ(lane_graph.lane_sequence(0).lane_segment(2).lane_id(), "l151"); EXPECT_EQ(lane_graph.lane_sequence(1).lane_segment_size(), 3); EXPECT_EQ(lane_graph.lane_sequence(1).lane_segment(0).lane_id(), "l164"); EXPECT_EQ(lane_graph.lane_sequence(1).lane_segment(1).lane_id(), "l35"); EXPECT_EQ(lane_graph.lane_sequence(1).lane_segment(2).lane_id(), "l153"); } TEST_F(ObstacleTest, PedestrianBasic) { Obstacle* obstacle_ptr = container_.GetObstacle(101); EXPECT_NE(obstacle_ptr, nullptr); EXPECT_EQ(obstacle_ptr->id(), 101); EXPECT_EQ(obstacle_ptr->type(), perception::PerceptionObstacle::PEDESTRIAN); EXPECT_EQ(obstacle_ptr->history_size(), 3); EXPECT_DOUBLE_EQ(obstacle_ptr->timestamp(), 0.2); } TEST_F(ObstacleTest, PedestrianPosition) { Obstacle* obstacle_ptr = container_.GetObstacle(101); const Feature& start_feature = obstacle_ptr->feature(2); EXPECT_DOUBLE_EQ(start_feature.timestamp(), 0.0); EXPECT_DOUBLE_EQ(start_feature.position().x(), -438.879); EXPECT_DOUBLE_EQ(start_feature.position().y(), -161.931); Feature* mid_feature_ptr = obstacle_ptr->mutable_feature(1); EXPECT_DOUBLE_EQ(mid_feature_ptr->timestamp(), 0.1); EXPECT_DOUBLE_EQ(mid_feature_ptr->position().x(), -438.610); EXPECT_DOUBLE_EQ(mid_feature_ptr->position().y(), -161.521); const Feature& latest_feature = obstacle_ptr->latest_feature(); EXPECT_DOUBLE_EQ(latest_feature.timestamp(), 0.2); EXPECT_DOUBLE_EQ(latest_feature.position().x(), -438.537); EXPECT_DOUBLE_EQ(latest_feature.position().y(), -160.991); } TEST_F(ObstacleTest, PedestrianVelocity) { Obstacle* obstacle_ptr = container_.GetObstacle(101); const Feature& start_feature = obstacle_ptr->feature(2); EXPECT_DOUBLE_EQ(start_feature.timestamp(), 0.0); EXPECT_DOUBLE_EQ(start_feature.velocity().x(), 1.710); EXPECT_DOUBLE_EQ(start_feature.velocity().y(), 4.699); const Feature& mid_feature = obstacle_ptr->feature(1); EXPECT_DOUBLE_EQ(mid_feature.timestamp(), 0.1); EXPECT_DOUBLE_EQ(mid_feature.velocity().x(), 1.710); EXPECT_DOUBLE_EQ(mid_feature.velocity().y(), 4.699); Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); EXPECT_DOUBLE_EQ(latest_feature_ptr->timestamp(), 0.2); EXPECT_DOUBLE_EQ(latest_feature_ptr->velocity().x(), 1.710); EXPECT_DOUBLE_EQ(latest_feature_ptr->velocity().y(), 4.699); EXPECT_NEAR(latest_feature_ptr->speed(), 5.0004700779026763, 0.001); } TEST_F(ObstacleTest, PedestrianHeading) { Obstacle* obstacle_ptr = container_.GetObstacle(101); const Feature& latest_feature = obstacle_ptr->latest_feature(); EXPECT_DOUBLE_EQ(latest_feature.theta(), 1.220); } TEST_F(ObstacleTest, Priority) { Obstacle* obstacle_ptr = container_.GetObstacle(101); EXPECT_FALSE(obstacle_ptr->ToIgnore()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacle_clusters.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "modules/common/util/util.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/common_msgs/prediction_msgs/feature.pb.h" namespace apollo { namespace prediction { class ObstacleClusters { public: /** * @brief Constructor */ ObstacleClusters() = default; /** * @brief Remove all lane graphs */ void Init(); /** * @brief Obtain a lane graph given a lane info and s * @param lane start s * @param lane total length * @param if consider lane split ahead * @param lane info * @return a corresponding lane graph */ LaneGraph GetLaneGraph( const double start_s, const double length, const bool consider_lane_split, std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info_ptr); /** * @brief Obtain a lane graph given a lane info and s, but don't * memorize it. * @param lane start s * @param lane total length * @param if the obstacle is on lane * @param lane info * @return a corresponding lane graph */ LaneGraph GetLaneGraphWithoutMemorizing( const double start_s, const double length, const bool is_on_lane, std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info_ptr); /** * @brief Get the nearest obstacle on lane sequence at s * @param Lane sequence * @param s offset in the first lane of the lane sequence * @param the forward obstacle on lane * @return If the forward obstacle is found */ bool ForwardNearbyObstacle(const LaneSequence& lane_sequence, const double s, LaneObstacle* const lane_obstacle); /** * @brief Add an obstacle into clusters * @param obstacle id * @param lane id * @param lane s * @param lane l */ void AddObstacle(const int obstacle_id, const std::string& lane_id, const double lane_s, const double lane_l); /** * @brief Sort lane obstacles by lane s */ void SortObstacles(); /** * @brief Get the forward nearest obstacle on lane sequence at s * @param Lane sequence * @param s offset in the first lane of the lane sequence * @param the forward obstacle on lane * @return If the forward obstacle is found */ bool ForwardNearbyObstacle(const LaneSequence& lane_sequence, const int obstacle_id, const double obstacle_s, const double obstacle_l, NearbyObstacle* const nearby_obstacle_ptr); /** * @brief Get the backward nearest obstacle on lane sequence at s * @param Lane sequence * @param s offset in the first lane of the lane sequence * @param the forward obstacle on lane * @return If the backward obstacle is found */ bool BackwardNearbyObstacle(const LaneSequence& lane_sequence, const int obstacle_id, const double obstacle_s, const double obstacle_l, NearbyObstacle* const nearby_obstacle_ptr); /** * @brief Query stop sign by lane ID * @param lane ID * @return the stop sign */ StopSign QueryStopSignByLaneId(const std::string& lane_id); std::unordered_map<std::string, std::vector<LaneObstacle>>& GetLaneObstacles() { return lane_obstacles_; } private: std::unordered_map<std::string, std::vector<LaneObstacle>> lane_obstacles_; std::unordered_map<std::string, StopSign> lane_id_stop_sign_map_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/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. *****************************************************************************/ #include "modules/prediction/container/obstacles/obstacle.h" #include <algorithm> #include <iomanip> #include <limits> #include "modules/common/util/util.h" #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/prediction_constants.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/prediction/network/rnn_model/rnn_model.h" namespace apollo { namespace prediction { namespace { using apollo::common::PathPoint; using apollo::common::Point3D; using apollo::hdmap::JunctionInfo; using apollo::hdmap::LaneInfo; using apollo::perception::PerceptionObstacle; double Damp(const double x, const double sigma) { return 1.0 / (1.0 + std::exp(1.0 / (std::fabs(x) + sigma))); } bool IsClosed(const double x0, const double y0, const double theta0, const double x1, const double y1, const double theta1) { double angle_diff = std::fabs(common::math::AngleDiff(theta0, theta1)); double distance = std::hypot(x0 - x1, y0 - y1); return distance < FLAGS_distance_threshold_to_junction_exit && angle_diff < FLAGS_angle_threshold_to_junction_exit; } } // namespace PerceptionObstacle::Type Obstacle::type() const { return type_; } bool Obstacle::IsPedestrian() const { return type_ == PerceptionObstacle::PEDESTRIAN; } int Obstacle::id() const { return id_; } double Obstacle::timestamp() const { ACHECK(!feature_history_.empty()); return feature_history_.front().timestamp(); } const Feature& Obstacle::feature(const size_t i) const { ACHECK(i < feature_history_.size()); return feature_history_[i]; } Feature* Obstacle::mutable_feature(const size_t i) { ACHECK(!feature_history_.empty()); ACHECK(i < feature_history_.size()); return &feature_history_[i]; } const Feature& Obstacle::latest_feature() const { ACHECK(!feature_history_.empty()); return feature_history_.front(); } const Feature& Obstacle::earliest_feature() const { ACHECK(!feature_history_.empty()); return feature_history_.back(); } Feature* Obstacle::mutable_latest_feature() { ACHECK(!feature_history_.empty()); return &(feature_history_.front()); } size_t Obstacle::history_size() const { return feature_history_.size(); } bool Obstacle::IsStill() { if (feature_history_.size() > 0) { return feature_history_.front().is_still(); } return true; } bool Obstacle::IsSlow() { const Feature& feature = latest_feature(); return feature.speed() < FLAGS_slow_obstacle_speed_threshold; } bool Obstacle::IsOnLane() const { if (feature_history_.empty() || !latest_feature().has_lane() || latest_feature().lane().current_lane_feature().empty()) { return false; } for (const auto& curr_lane : latest_feature().lane().current_lane_feature()) { if (curr_lane.lane_type() != hdmap::Lane::CITY_DRIVING && curr_lane.lane_type() != hdmap::Lane::BIKING) { return false; } } ADEBUG << "Obstacle [" << id_ << "] is on lane."; return true; } bool Obstacle::ToIgnore() { if (feature_history_.empty()) { return true; } return latest_feature().priority().priority() == ObstaclePriority::IGNORE; } bool Obstacle::IsNearJunction() { if (feature_history_.empty()) { return false; } double pos_x = latest_feature().position().x(); double pos_y = latest_feature().position().y(); return PredictionMap::NearJunction({pos_x, pos_y}, FLAGS_junction_search_radius); } bool Obstacle::Insert(const PerceptionObstacle& perception_obstacle, const double timestamp, const int prediction_obstacle_id) { if (!perception_obstacle.has_id() || !perception_obstacle.has_type()) { AERROR << "Perception obstacle has incomplete information; " "skip insertion"; return false; } if (ReceivedOlderMessage(timestamp)) { AERROR << "Obstacle [" << id_ << "] received an older frame [" << std::setprecision(20) << timestamp << "] than the most recent timestamp [ " << this->timestamp() << "]."; return false; } // Set ID, Type, and Status of the feature. Feature feature; if (!SetId(perception_obstacle, &feature, prediction_obstacle_id)) { return false; } SetType(perception_obstacle, &feature); SetStatus(perception_obstacle, timestamp, &feature); // Set obstacle lane features if (type_ != PerceptionObstacle::PEDESTRIAN) { SetCurrentLanes(&feature); SetNearbyLanes(&feature); } if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpDataForLearning) { SetSurroundingLaneIds(&feature, FLAGS_surrounding_lane_search_radius); } if (FLAGS_adjust_vehicle_heading_by_lane && type_ == PerceptionObstacle::VEHICLE) { AdjustHeadingByLane(&feature); } // Insert obstacle feature to history InsertFeatureToHistory(feature); // Set obstacle motion status if (FLAGS_use_navigation_mode) { SetMotionStatusBySpeed(); } else { SetMotionStatus(); } // Trim historical features DiscardOutdatedHistory(); return true; } bool Obstacle::InsertFeature(const Feature& feature) { InsertFeatureToHistory(feature); type_ = feature.type(); id_ = feature.id(); return true; } void Obstacle::ClearOldInformation() { if (feature_history_.size() <= 1) { return; } feature_history_[1].clear_predicted_trajectory(); Lane* lane = feature_history_[1].mutable_lane(); lane->clear_current_lane_feature(); lane->clear_nearby_lane_feature(); lane->clear_lane_graph(); lane->clear_lane_graph_ordered(); } void Obstacle::TrimHistory(const size_t remain_size) { if (feature_history_.size() > remain_size) { feature_history_.resize(remain_size); } } bool Obstacle::IsInJunction(const std::string& junction_id) const { // TODO(all) Consider if need to use vehicle front rather than position if (feature_history_.empty()) { AERROR << "Obstacle [" << id_ << "] has no history"; return false; } if (junction_id.empty()) { return false; } std::shared_ptr<const JunctionInfo> junction_info_ptr = PredictionMap::JunctionById(junction_id); if (junction_info_ptr == nullptr) { return false; } const auto& position = latest_feature().position(); return PredictionMap::IsPointInJunction(position.x(), position.y(), junction_info_ptr); } void Obstacle::BuildJunctionFeature() { // If obstacle has no history at all, then exit. if (feature_history_.empty()) { AERROR << "Obstacle [" << id_ << "] has no history"; return; } // If obstacle is not in the given junction, then exit. const std::string& junction_id = junction_analyzer_->GetJunctionId(); if (!IsInJunction(junction_id)) { ADEBUG << "Obstacle [" << id_ << "] is not in junction [" << junction_id << "]"; return; } // Set the junction features by calling SetJunctionFeatureWithoutEnterLane. Feature* latest_feature_ptr = mutable_latest_feature(); if (feature_history_.size() == 1) { SetJunctionFeatureWithoutEnterLane(latest_feature_ptr); return; } const Feature& prev_feature = feature(1); if (prev_feature.junction_feature().has_enter_lane()) { ACHECK(prev_feature.junction_feature().enter_lane().has_lane_id()); std::string enter_lane_id = prev_feature.junction_feature().enter_lane().lane_id(); // TODO(all) use enter lane when tracking is better SetJunctionFeatureWithoutEnterLane(latest_feature_ptr); } else { SetJunctionFeatureWithoutEnterLane(latest_feature_ptr); } } bool Obstacle::IsCloseToJunctionExit() const { if (!HasJunctionFeatureWithExits()) { AERROR << "No junction feature found"; return false; } CHECK_GT(history_size(), 0U); const Feature& latest_feature = feature_history_.front(); double position_x = latest_feature.position().x(); double position_y = latest_feature.position().y(); double raw_velocity_heading = std::atan2(latest_feature.raw_velocity().y(), latest_feature.raw_velocity().x()); for (const JunctionExit& junction_exit : latest_feature.junction_feature().junction_exit()) { double exit_x = junction_exit.exit_position().x(); double exit_y = junction_exit.exit_position().y(); double exit_heading = junction_exit.exit_heading(); if (IsClosed(position_x, position_y, raw_velocity_heading, exit_x, exit_y, exit_heading)) { return true; } } return false; } void Obstacle::SetJunctionFeatureWithEnterLane(const std::string& enter_lane_id, Feature* const feature_ptr) { feature_ptr->mutable_junction_feature()->CopyFrom( junction_analyzer_->GetJunctionFeature(enter_lane_id)); } void Obstacle::SetJunctionFeatureWithoutEnterLane(Feature* const feature_ptr) { // Sanity checks. if (!feature_ptr->has_lane()) { ADEBUG << "Obstacle [" << id_ << "] has no lane."; return; } // Get the possible lanes that the obstalce is on and their neighbor // lanes and treat them as the starting-lane-segments. std::vector<std::string> start_lane_ids; if (feature_ptr->lane().current_lane_feature_size() > 0) { for (const auto& lane_feature : feature_ptr->lane().current_lane_feature()) { start_lane_ids.push_back(lane_feature.lane_id()); } } if (feature_ptr->lane().nearby_lane_feature_size() > 0) { for (const auto& lane_feature : feature_ptr->lane().nearby_lane_feature()) { start_lane_ids.push_back(lane_feature.lane_id()); } } if (start_lane_ids.empty()) { ADEBUG << "Obstacle [" << id_ << "] has no lane in junction"; return; } // TODO(kechxu) Maybe output all exits if no start lane found feature_ptr->mutable_junction_feature()->CopyFrom( junction_analyzer_->GetJunctionFeature(start_lane_ids)); } void Obstacle::SetStatus(const PerceptionObstacle& perception_obstacle, const double timestamp, Feature* feature) { SetTimestamp(perception_obstacle, timestamp, feature); SetPolygonPoints(perception_obstacle, feature); SetPosition(perception_obstacle, feature); SetVelocity(perception_obstacle, feature); SetAcceleration(feature); SetTheta(perception_obstacle, feature); SetLengthWidthHeight(perception_obstacle, feature); SetIsNearJunction(perception_obstacle, feature); } bool Obstacle::SetId(const PerceptionObstacle& perception_obstacle, Feature* feature, const int prediction_obstacle_id) { int id = prediction_obstacle_id > 0 ? prediction_obstacle_id : perception_obstacle.id(); if (id_ < 0) { id_ = id; ADEBUG << "Obstacle has id [" << id_ << "]."; } else { if (id_ != id) { AERROR << "Obstacle [" << id_ << "] has a mismatched ID [" << id << "] from perception obstacle."; return false; } } feature->set_id(id); return true; } void Obstacle::SetType(const PerceptionObstacle& perception_obstacle, Feature* feature) { type_ = perception_obstacle.type(); ADEBUG << "Obstacle [" << id_ << "] has type [" << type_ << "]."; feature->set_type(type_); } void Obstacle::SetTimestamp(const PerceptionObstacle& perception_obstacle, const double timestamp, Feature* feature) { double ts = timestamp; feature->set_timestamp(ts); ADEBUG << "Obstacle [" << id_ << "] has timestamp [" << std::fixed << std::setprecision(6) << ts << "]."; } void Obstacle::SetPolygonPoints(const PerceptionObstacle& perception_obstacle, Feature* feature) { for (const auto& polygon_point : perception_obstacle.polygon_point()) { *feature->add_polygon_point() = polygon_point; ADEBUG << "Obstacle [" << id_ << "] has new corner point:" << polygon_point.DebugString(); } } void Obstacle::SetPosition(const PerceptionObstacle& perception_obstacle, Feature* feature) { *feature->mutable_position() = perception_obstacle.position(); ADEBUG << "Obstacle [" << id_ << "] has position:" << perception_obstacle.position().DebugString(); } void Obstacle::SetVelocity(const PerceptionObstacle& perception_obstacle, Feature* feature) { double velocity_x = 0.0; double velocity_y = 0.0; double velocity_z = 0.0; if (perception_obstacle.has_velocity()) { if (perception_obstacle.velocity().has_x()) { velocity_x = perception_obstacle.velocity().x(); if (std::isnan(velocity_x)) { AERROR << "Found nan velocity_x from perception obstacle"; velocity_x = 0.0; } else if (velocity_x > 50.0 || velocity_x < -50.0) { AERROR << "Found unreasonable velocity_x from perception obstacle"; } } if (perception_obstacle.velocity().has_y()) { velocity_y = perception_obstacle.velocity().y(); if (std::isnan(velocity_y)) { AERROR << "Found nan velocity_y from perception obstacle"; velocity_y = 0.0; } else if (velocity_y > 50.0 || velocity_y < -50.0) { AERROR << "Found unreasonable velocity_y from perception obstacle"; } } if (perception_obstacle.velocity().has_z()) { velocity_z = perception_obstacle.velocity().z(); if (std::isnan(velocity_z)) { AERROR << "Found nan velocity z from perception obstacle"; velocity_z = 0.0; } else if (velocity_z > 50.0 || velocity_z < -50.0) { AERROR << "Found unreasonable velocity_z from perception obstacle"; } } } feature->mutable_raw_velocity()->set_x(velocity_x); feature->mutable_raw_velocity()->set_y(velocity_y); feature->mutable_raw_velocity()->set_z(velocity_z); double speed = std::hypot(velocity_x, velocity_y); double velocity_heading = std::atan2(velocity_y, velocity_x); if (FLAGS_adjust_velocity_by_obstacle_heading || speed < 0.1) { velocity_heading = perception_obstacle.theta(); } if (!FLAGS_use_navigation_mode && FLAGS_adjust_velocity_by_position_shift && history_size() > 0) { double diff_x = feature->position().x() - feature_history_.front().position().x(); double diff_y = feature->position().y() - feature_history_.front().position().y(); double prev_obstacle_size = std::fmax(feature_history_.front().length(), feature_history_.front().width()); double obstacle_size = std::fmax(perception_obstacle.length(), perception_obstacle.width()); double size_diff = std::abs(obstacle_size - prev_obstacle_size); double shift_thred = std::fmax(obstacle_size * FLAGS_valid_position_diff_rate_threshold, FLAGS_valid_position_diff_threshold); double size_diff_thred = FLAGS_split_rate * std::min(obstacle_size, prev_obstacle_size); if (std::fabs(diff_x) > shift_thred && std::fabs(diff_y) > shift_thred && size_diff < size_diff_thred) { double shift_heading = std::atan2(diff_y, diff_x); double angle_diff = common::math::NormalizeAngle(shift_heading - velocity_heading); if (std::fabs(angle_diff) > FLAGS_max_lane_angle_diff) { ADEBUG << "Shift velocity heading to be " << shift_heading; velocity_heading = shift_heading; } } velocity_x = speed * std::cos(velocity_heading); velocity_y = speed * std::sin(velocity_heading); } feature->mutable_velocity()->set_x(velocity_x); feature->mutable_velocity()->set_y(velocity_y); feature->mutable_velocity()->set_z(velocity_z); feature->set_velocity_heading(velocity_heading); feature->set_speed(speed); ADEBUG << "Obstacle [" << id_ << "] has velocity [" << std::fixed << std::setprecision(6) << velocity_x << ", " << std::fixed << std::setprecision(6) << velocity_y << ", " << std::fixed << std::setprecision(6) << velocity_z << "]"; ADEBUG << "Obstacle [" << id_ << "] has velocity heading [" << std::fixed << std::setprecision(6) << velocity_heading << "] "; ADEBUG << "Obstacle [" << id_ << "] has speed [" << std::fixed << std::setprecision(6) << speed << "]."; } void Obstacle::AdjustHeadingByLane(Feature* feature) { if (!feature->has_lane() || !feature->lane().has_lane_feature()) { return; } double velocity_heading = feature->velocity_heading(); double lane_heading = feature->lane().lane_feature().lane_heading(); double angle_diff = feature->lane().lane_feature().angle_diff(); if (std::abs(angle_diff) < FLAGS_max_angle_diff_to_adjust_velocity) { velocity_heading = lane_heading; double speed = feature->speed(); feature->mutable_velocity()->set_x(speed * std::cos(velocity_heading)); feature->mutable_velocity()->set_y(speed * std::sin(velocity_heading)); feature->set_velocity_heading(velocity_heading); } } void Obstacle::UpdateVelocity(const double theta, double* velocity_x, double* velocity_y, double* velocity_heading, double* speed) { *speed = std::hypot(*velocity_x, *velocity_y); double angle_diff = common::math::NormalizeAngle(*velocity_heading - theta); if (std::fabs(angle_diff) <= FLAGS_max_lane_angle_diff) { *velocity_heading = theta; *velocity_x = *speed * std::cos(*velocity_heading); *velocity_y = *speed * std::sin(*velocity_heading); } } void Obstacle::SetAcceleration(Feature* feature) { double acc_x = 0.0; double acc_y = 0.0; double acc_z = 0.0; double acc = 0.0; if (feature_history_.size() > 0) { double curr_ts = feature->timestamp(); double prev_ts = feature_history_.front().timestamp(); const Point3D& curr_velocity = feature->velocity(); const Point3D& prev_velocity = feature_history_.front().velocity(); if (curr_ts > prev_ts) { // A damp function is to punish acc calculation for low speed double damping_x = Damp(curr_velocity.x(), 0.001); double damping_y = Damp(curr_velocity.y(), 0.001); double damping_z = Damp(curr_velocity.z(), 0.001); acc_x = (curr_velocity.x() - prev_velocity.x()) / (curr_ts - prev_ts); acc_y = (curr_velocity.y() - prev_velocity.y()) / (curr_ts - prev_ts); acc_z = (curr_velocity.z() - prev_velocity.z()) / (curr_ts - prev_ts); acc_x *= damping_x; acc_y *= damping_y; acc_z *= damping_z; acc_x = common::math::Clamp(acc_x, FLAGS_vehicle_min_linear_acc, FLAGS_vehicle_max_linear_acc); acc_y = common::math::Clamp(acc_y, FLAGS_vehicle_min_linear_acc, FLAGS_vehicle_max_linear_acc); acc_z = common::math::Clamp(acc_z, FLAGS_vehicle_min_linear_acc, FLAGS_vehicle_max_linear_acc); double heading = feature->velocity_heading(); acc = acc_x * std::cos(heading) + acc_y * std::sin(heading); } } feature->mutable_acceleration()->set_x(acc_x); feature->mutable_acceleration()->set_y(acc_y); feature->mutable_acceleration()->set_z(acc_z); feature->set_acc(acc); ADEBUG << "Obstacle [" << id_ << "] has acceleration [" << std::fixed << std::setprecision(6) << acc_x << ", " << std::fixed << std::setprecision(6) << acc_y << ", " << std::fixed << std::setprecision(6) << acc_z << "]"; ADEBUG << "Obstacle [" << id_ << "] has acceleration value [" << std::fixed << std::setprecision(6) << acc << "]."; } void Obstacle::SetTheta(const PerceptionObstacle& perception_obstacle, Feature* feature) { double theta = 0.0; if (perception_obstacle.has_theta()) { theta = perception_obstacle.theta(); } feature->set_theta(theta); ADEBUG << "Obstacle [" << id_ << "] has theta [" << std::fixed << std::setprecision(6) << theta << "]."; } void Obstacle::SetLengthWidthHeight( const PerceptionObstacle& perception_obstacle, Feature* feature) { double length = 0.0; double width = 0.0; double height = 0.0; if (perception_obstacle.has_length()) { length = perception_obstacle.length(); } if (perception_obstacle.has_width()) { width = perception_obstacle.width(); } if (perception_obstacle.has_height()) { height = perception_obstacle.height(); } feature->set_length(length); feature->set_width(width); feature->set_height(height); ADEBUG << "Obstacle [" << id_ << "] has dimension [" << std::fixed << std::setprecision(6) << length << ", " << std::fixed << std::setprecision(6) << width << ", " << std::fixed << std::setprecision(6) << height << "]."; } void Obstacle::SetIsNearJunction(const PerceptionObstacle& perception_obstacle, Feature* feature) { if (!perception_obstacle.has_position()) { return; } if (!perception_obstacle.position().has_x() || !perception_obstacle.position().has_y()) { return; } double x = perception_obstacle.position().x(); double y = perception_obstacle.position().y(); bool is_near_junction = PredictionMap::NearJunction({x, y}, FLAGS_junction_search_radius); feature->set_is_near_junction(is_near_junction); } bool Obstacle::HasJunctionFeatureWithExits() const { if (history_size() == 0) { return false; } return latest_feature().has_junction_feature() && latest_feature().junction_feature().junction_exit_size() > 0; } void Obstacle::SetCurrentLanes(Feature* feature) { Eigen::Vector2d point(feature->position().x(), feature->position().y()); double heading = feature->velocity_heading(); int max_num_lane = FLAGS_max_num_current_lane; double max_angle_diff = FLAGS_max_lane_angle_diff; double lane_search_radius = FLAGS_lane_search_radius; if (PredictionMap::InJunction(point, FLAGS_junction_search_radius)) { max_num_lane = FLAGS_max_num_current_lane_in_junction; max_angle_diff = FLAGS_max_lane_angle_diff_in_junction; lane_search_radius = FLAGS_lane_search_radius_in_junction; } std::vector<std::shared_ptr<const LaneInfo>> current_lanes; PredictionMap::OnLane(current_lanes_, point, heading, lane_search_radius, true, max_num_lane, max_angle_diff, &current_lanes); current_lanes_ = current_lanes; if (current_lanes_.empty()) { ADEBUG << "Obstacle [" << id_ << "] has no current lanes."; return; } Lane lane; if (feature->has_lane()) { lane = feature->lane(); } double min_heading_diff = std::numeric_limits<double>::infinity(); for (std::shared_ptr<const LaneInfo> current_lane : current_lanes) { if (current_lane == nullptr) { continue; } int turn_type = PredictionMap::LaneTurnType(current_lane->id().id()); std::string lane_id = current_lane->id().id(); double s = 0.0; double l = 0.0; PredictionMap::GetProjection(point, current_lane, &s, &l); if (s < 0.0) { continue; } common::math::Vec2d vec_point(point[0], point[1]); double distance = 0.0; common::PointENU nearest_point = current_lane->GetNearestPoint(vec_point, &distance); double nearest_point_heading = PredictionMap::PathHeading(current_lane, nearest_point); double angle_diff = common::math::AngleDiff(heading, nearest_point_heading); double left = 0.0; double right = 0.0; current_lane->GetWidth(s, &left, &right); LaneFeature* lane_feature = lane.add_current_lane_feature(); lane_feature->set_lane_turn_type(turn_type); lane_feature->set_lane_id(lane_id); lane_feature->set_lane_s(s); lane_feature->set_lane_l(l); lane_feature->set_angle_diff(angle_diff); lane_feature->set_lane_heading(nearest_point_heading); lane_feature->set_dist_to_left_boundary(left - l); lane_feature->set_dist_to_right_boundary(right + l); lane_feature->set_lane_type(current_lane->lane().type()); if (std::fabs(angle_diff) < min_heading_diff) { lane.mutable_lane_feature()->CopyFrom(*lane_feature); min_heading_diff = std::fabs(angle_diff); } clusters_ptr_->AddObstacle(id_, lane_id, s, l); ADEBUG << "Obstacle [" << id_ << "] has current lanes [" << lane_feature->ShortDebugString() << "]."; } if (lane.has_lane_feature()) { ADEBUG << "Obstacle [" << id_ << "] has one current lane [" << lane.lane_feature().ShortDebugString() << "]."; } feature->mutable_lane()->CopyFrom(lane); } void Obstacle::SetNearbyLanes(Feature* feature) { Eigen::Vector2d point(feature->position().x(), feature->position().y()); int max_num_lane = FLAGS_max_num_nearby_lane; double lane_search_radius = FLAGS_lane_search_radius; if (PredictionMap::InJunction(point, FLAGS_junction_search_radius)) { max_num_lane = FLAGS_max_num_nearby_lane_in_junction; lane_search_radius = FLAGS_lane_search_radius_in_junction; } double theta = feature->velocity_heading(); std::vector<std::shared_ptr<const LaneInfo>> nearby_lanes; PredictionMap::NearbyLanesByCurrentLanes(point, theta, lane_search_radius, current_lanes_, max_num_lane, &nearby_lanes); if (nearby_lanes.empty()) { ADEBUG << "Obstacle [" << id_ << "] has no nearby lanes."; return; } for (std::shared_ptr<const LaneInfo> nearby_lane : nearby_lanes) { if (nearby_lane == nullptr) { continue; } // Ignore bike and sidewalk lanes for vehicles if (type_ == PerceptionObstacle::VEHICLE && nearby_lane->lane().has_type() && (nearby_lane->lane().type() == ::apollo::hdmap::Lane::BIKING || nearby_lane->lane().type() == ::apollo::hdmap::Lane::SIDEWALK)) { ADEBUG << "Obstacle [" << id_ << "] ignores disqualified lanes."; continue; } double s = -1.0; double l = 0.0; PredictionMap::GetProjection(point, nearby_lane, &s, &l); if (s < 0.0 || s >= nearby_lane->total_length()) { continue; } int turn_type = PredictionMap::LaneTurnType(nearby_lane->id().id()); double heading = feature->velocity_heading(); double angle_diff = 0.0; hdmap::MapPathPoint nearest_point; if (PredictionMap::ProjectionFromLane(nearby_lane, s, &nearest_point)) { angle_diff = common::math::AngleDiff(nearest_point.heading(), heading); } double left = 0.0; double right = 0.0; nearby_lane->GetWidth(s, &left, &right); LaneFeature* lane_feature = feature->mutable_lane()->add_nearby_lane_feature(); lane_feature->set_lane_turn_type(turn_type); lane_feature->set_lane_id(nearby_lane->id().id()); lane_feature->set_lane_s(s); lane_feature->set_lane_l(l); lane_feature->set_angle_diff(angle_diff); lane_feature->set_dist_to_left_boundary(left - l); lane_feature->set_dist_to_right_boundary(right + l); lane_feature->set_lane_type(nearby_lane->lane().type()); ADEBUG << "Obstacle [" << id_ << "] has nearby lanes [" << lane_feature->ShortDebugString() << "]"; } } void Obstacle::SetSurroundingLaneIds(Feature* feature, const double radius) { Eigen::Vector2d point(feature->position().x(), feature->position().y()); std::vector<std::string> lane_ids = PredictionMap::NearbyLaneIds(point, radius); for (const auto& lane_id : lane_ids) { feature->add_surrounding_lane_id(lane_id); std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById(lane_id); if (lane_info->IsOnLane( {feature->position().x(), feature->position().y()})) { feature->add_within_lane_id(lane_id); } } } bool Obstacle::HasJunctionExitLane( const LaneSequence& lane_sequence, const std::unordered_set<std::string>& exit_lane_id_set) { const Feature& feature = latest_feature(); if (!feature.has_junction_feature()) { AERROR << "Obstacle [" << id_ << "] has no junction feature."; return false; } for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) { if (exit_lane_id_set.find(lane_segment.lane_id()) != exit_lane_id_set.end()) { return true; } } return false; } void Obstacle::BuildLaneGraph() { // Sanity checks. if (history_size() == 0) { AERROR << "No feature found."; return; } Feature* feature = mutable_latest_feature(); // No need to BuildLaneGraph for those non-moving obstacles. if (feature->is_still() && id_ != FLAGS_ego_vehicle_id) { ADEBUG << "Not build lane graph for still obstacle"; return; } if (feature->lane().lane_graph().lane_sequence_size() > 0) { ADEBUG << "Not build lane graph for an old obstacle"; return; } double speed = feature->speed(); double t_max = FLAGS_prediction_trajectory_time_length; auto estimated_move_distance = speed * t_max; double road_graph_search_distance = std::fmax( estimated_move_distance, FLAGS_min_prediction_trajectory_spatial_length); bool is_in_junction = HasJunctionFeatureWithExits(); std::unordered_set<std::string> exit_lane_id_set; if (is_in_junction) { for (const auto& exit : feature->junction_feature().junction_exit()) { exit_lane_id_set.insert(exit.exit_lane_id()); } } // BuildLaneGraph for current lanes: // Go through all the LaneSegments in current_lane, // construct up to max_num_current_lane of them. int seq_id = 0; int curr_lane_count = 0; for (auto& lane : feature->lane().current_lane_feature()) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById(lane.lane_id()); LaneGraph lane_graph = clusters_ptr_->GetLaneGraph( lane.lane_s(), road_graph_search_distance, true, lane_info); if (lane_graph.lane_sequence_size() > 0) { ++curr_lane_count; } for (const auto& lane_seq : lane_graph.lane_sequence()) { if (is_in_junction && !HasJunctionExitLane(lane_seq, exit_lane_id_set)) { continue; } LaneSequence* lane_seq_ptr = feature->mutable_lane()->mutable_lane_graph()->add_lane_sequence(); lane_seq_ptr->CopyFrom(lane_seq); lane_seq_ptr->set_lane_sequence_id(seq_id++); lane_seq_ptr->set_lane_s(lane.lane_s()); lane_seq_ptr->set_lane_l(lane.lane_l()); lane_seq_ptr->set_vehicle_on_lane(true); lane_seq_ptr->set_lane_type(lane.lane_type()); SetLaneSequenceStopSign(lane_seq_ptr); ADEBUG << "Obstacle [" << id_ << "] set a lane sequence [" << lane_seq.ShortDebugString() << "]."; } if (curr_lane_count >= FLAGS_max_num_current_lane) { break; } } // BuildLaneGraph for neighbor lanes. int nearby_lane_count = 0; for (auto& lane : feature->lane().nearby_lane_feature()) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById(lane.lane_id()); LaneGraph lane_graph = clusters_ptr_->GetLaneGraph( lane.lane_s(), road_graph_search_distance, false, lane_info); if (lane_graph.lane_sequence_size() > 0) { ++nearby_lane_count; } for (const auto& lane_seq : lane_graph.lane_sequence()) { if (is_in_junction && !HasJunctionExitLane(lane_seq, exit_lane_id_set)) { continue; } LaneSequence* lane_seq_ptr = feature->mutable_lane()->mutable_lane_graph()->add_lane_sequence(); lane_seq_ptr->CopyFrom(lane_seq); lane_seq_ptr->set_lane_sequence_id(seq_id++); lane_seq_ptr->set_lane_s(lane.lane_s()); lane_seq_ptr->set_lane_l(lane.lane_l()); lane_seq_ptr->set_vehicle_on_lane(false); lane_seq_ptr->set_lane_type(lane.lane_type()); SetLaneSequenceStopSign(lane_seq_ptr); ADEBUG << "Obstacle [" << id_ << "] set a lane sequence [" << lane_seq.ShortDebugString() << "]."; } if (nearby_lane_count >= FLAGS_max_num_nearby_lane) { break; } } if (feature->has_lane() && feature->lane().has_lane_graph()) { SetLanePoints(feature); SetLaneSequencePath(feature->mutable_lane()->mutable_lane_graph()); } ADEBUG << "Obstacle [" << id_ << "] set lane graph features."; } void Obstacle::SetLaneSequenceStopSign(LaneSequence* lane_sequence_ptr) { // Set the nearest stop sign along the lane sequence if (lane_sequence_ptr->lane_segment().empty()) { return; } double accumulate_s = 0.0; for (const LaneSegment& lane_segment : lane_sequence_ptr->lane_segment()) { const StopSign& stop_sign = clusters_ptr_->QueryStopSignByLaneId(lane_segment.lane_id()); if (stop_sign.has_stop_sign_id() && stop_sign.lane_s() + accumulate_s > lane_sequence_ptr->lane_s()) { lane_sequence_ptr->mutable_stop_sign()->CopyFrom(stop_sign); lane_sequence_ptr->mutable_stop_sign()->set_lane_sequence_s( stop_sign.lane_s() + accumulate_s); ADEBUG << "Set StopSign for LaneSequence [" << lane_sequence_ptr->lane_sequence_id() << "]."; break; } accumulate_s += lane_segment.total_length(); } } void Obstacle::GetNeighborLaneSegments( std::shared_ptr<const LaneInfo> center_lane_info, bool is_left, int recursion_depth, std::list<std::string>* const lane_ids_ordered, std::unordered_set<std::string>* const existing_lane_ids) { // Exit recursion if reached max num of allowed search depth. if (recursion_depth <= 0) { return; } if (is_left) { std::vector<std::string> curr_left_lane_ids; for (const auto& left_lane_id : center_lane_info->lane().left_neighbor_forward_lane_id()) { if (left_lane_id.has_id()) { const std::string& lane_id = left_lane_id.id(); // If haven't seen this lane id before. if (existing_lane_ids->count(lane_id) == 0) { existing_lane_ids->insert(lane_id); lane_ids_ordered->push_front(lane_id); curr_left_lane_ids.push_back(lane_id); } } } for (const std::string& lane_id : curr_left_lane_ids) { GetNeighborLaneSegments(PredictionMap::LaneById(lane_id), true, recursion_depth - 1, lane_ids_ordered, existing_lane_ids); } } else { std::vector<std::string> curr_right_lane_ids; for (const auto& right_lane_id : center_lane_info->lane().right_neighbor_forward_lane_id()) { if (right_lane_id.has_id()) { const std::string& lane_id = right_lane_id.id(); // If haven't seen this lane id before. if (existing_lane_ids->count(lane_id) == 0) { existing_lane_ids->insert(lane_id); lane_ids_ordered->push_back(lane_id); curr_right_lane_ids.push_back(lane_id); } } } for (const std::string& lane_id : curr_right_lane_ids) { GetNeighborLaneSegments(PredictionMap::LaneById(lane_id), false, recursion_depth - 1, lane_ids_ordered, existing_lane_ids); } } } void Obstacle::BuildLaneGraphFromLeftToRight() { // Sanity checks. if (history_size() == 0) { AERROR << "No feature found."; return; } // No need to BuildLaneGraph for those non-moving obstacles. Feature* feature = mutable_latest_feature(); if (feature->is_still()) { ADEBUG << "Don't build lane graph for non-moving obstacle."; return; } if (feature->lane().lane_graph_ordered().lane_sequence_size() > 0) { ADEBUG << "Don't build lane graph for an old obstacle."; return; } // double speed = feature->speed(); double road_graph_search_distance = 50.0 * 0.95; // (45mph for 3sec) // std::fmax(speed * FLAGS_prediction_trajectory_time_length + // 0.5 * FLAGS_vehicle_max_linear_acc * // FLAGS_prediction_trajectory_time_length * // FLAGS_prediction_trajectory_time_length, // FLAGS_min_prediction_trajectory_spatial_length); // Treat the most probable lane_segment as the center, put its left // and right neighbors into a vector following the left-to-right order. if (!feature->has_lane() || !feature->lane().has_lane_feature()) { return; } bool is_in_junction = HasJunctionFeatureWithExits(); std::unordered_set<std::string> exit_lane_id_set; if (is_in_junction) { for (const auto& exit : feature->junction_feature().junction_exit()) { exit_lane_id_set.insert(exit.exit_lane_id()); } } std::shared_ptr<const LaneInfo> center_lane_info = PredictionMap::LaneById(feature->lane().lane_feature().lane_id()); std::list<std::string> lane_ids_ordered_list; std::unordered_set<std::string> existing_lane_ids; GetNeighborLaneSegments(center_lane_info, true, 2, &lane_ids_ordered_list, &existing_lane_ids); lane_ids_ordered_list.push_back(feature->lane().lane_feature().lane_id()); existing_lane_ids.insert(feature->lane().lane_feature().lane_id()); GetNeighborLaneSegments(center_lane_info, false, 2, &lane_ids_ordered_list, &existing_lane_ids); const std::vector<std::string> lane_ids_ordered(lane_ids_ordered_list.begin(), lane_ids_ordered_list.end()); // TODO(all): sort the lane_segments from left to right (again) // to double-check and make sure it's well sorted. // Build lane_graph for every lane_segment and update it into proto. int seq_id = 0; for (const std::string& lane_id : lane_ids_ordered) { // Construct the local lane_graph based on the current lane_segment. bool vehicle_is_on_lane = (lane_id == center_lane_info->lane().id().id()); std::shared_ptr<const LaneInfo> curr_lane_info = PredictionMap::LaneById(lane_id); LaneGraph local_lane_graph = clusters_ptr_->GetLaneGraphWithoutMemorizing( feature->lane().lane_feature().lane_s(), road_graph_search_distance, true, curr_lane_info); // Update it into the Feature proto for (const auto& lane_seq : local_lane_graph.lane_sequence()) { if (is_in_junction && !HasJunctionExitLane(lane_seq, exit_lane_id_set)) { continue; } LaneSequence* lane_seq_ptr = feature->mutable_lane() ->mutable_lane_graph_ordered() ->add_lane_sequence(); lane_seq_ptr->CopyFrom(lane_seq); lane_seq_ptr->set_lane_sequence_id(seq_id++); lane_seq_ptr->set_lane_s(feature->lane().lane_feature().lane_s()); lane_seq_ptr->set_lane_l(feature->lane().lane_feature().lane_l()); lane_seq_ptr->set_vehicle_on_lane(vehicle_is_on_lane); ADEBUG << "Obstacle [" << id_ << "] set a lane sequence [" << lane_seq.ShortDebugString() << "]."; } } // Build lane_points. if (feature->lane().has_lane_graph_ordered()) { SetLanePoints(feature, 0.5, 100, true, feature->mutable_lane()->mutable_lane_graph_ordered()); SetLaneSequencePath(feature->mutable_lane()->mutable_lane_graph_ordered()); } ADEBUG << "Obstacle [" << id_ << "] set lane graph features."; } // The default SetLanePoints applies to lane_graph with // FLAGS_target_lane_gap. void Obstacle::SetLanePoints(Feature* feature) { LaneGraph* lane_graph = feature->mutable_lane()->mutable_lane_graph(); SetLanePoints(feature, FLAGS_target_lane_gap, FLAGS_max_num_lane_point, false, lane_graph); } // The generic SetLanePoints void Obstacle::SetLanePoints(const Feature* feature, const double lane_point_spacing, const uint64_t max_num_lane_point, const bool is_bidirection, LaneGraph* const lane_graph) { ADEBUG << "Spacing = " << lane_point_spacing; // Sanity checks. if (feature == nullptr || !feature->has_velocity_heading()) { AERROR << "Null feature or no velocity heading."; return; } double heading = feature->velocity_heading(); double x = feature->position().x(); double y = feature->position().y(); Eigen::Vector2d position(x, y); // Go through every lane_sequence. for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) { LaneSequence* lane_sequence = lane_graph->mutable_lane_sequence(i); if (lane_sequence->lane_segment().empty()) { continue; } // TODO(jiacheng): can refactor the following two parts into one to // make it more elegant. // If building bidirectionally, then build backward lane-points as well. if (is_bidirection) { int lane_index = 0; double lane_seg_s = lane_sequence->lane_segment(lane_index).start_s(); while (lane_index < lane_sequence->lane_segment_size()) { // Go through lane_segment one by one sequentially. LaneSegment* lane_segment = lane_sequence->mutable_lane_segment(lane_index); // End-condition: reached the current ADC's location. if (lane_index == lane_sequence->adc_lane_segment_idx() && lane_seg_s > lane_segment->adc_s()) { lane_segment->set_adc_lane_point_idx(lane_segment->lane_point_size()); break; } if (lane_seg_s > lane_segment->end_s()) { // If already exceeds the current lane_segment, then go to the // next following one. ADEBUG << "Move on to the next lane-segment."; lane_seg_s = lane_seg_s - lane_segment->end_s(); ++lane_index; } else { // Otherwise, update lane_graph: // 1. Sanity checks. std::string lane_id = lane_segment->lane_id(); lane_segment->set_lane_turn_type( PredictionMap::LaneTurnType(lane_id)); ADEBUG << "Currently on " << lane_id; auto lane_info = PredictionMap::LaneById(lane_id); if (lane_info == nullptr) { break; } // 2. Get the closeset lane_point ADEBUG << "Lane-segment s = " << lane_seg_s; Eigen::Vector2d lane_point_pos = PredictionMap::PositionOnLane(lane_info, lane_seg_s); double lane_point_heading = PredictionMap::HeadingOnLane(lane_info, lane_seg_s); double lane_point_width = PredictionMap::LaneTotalWidth(lane_info, lane_seg_s); double lane_point_angle_diff = common::math::AngleDiff(lane_point_heading, heading); // 3. Update it into the lane_graph ADEBUG << lane_point_pos[0] << " " << lane_point_pos[1]; LanePoint lane_point; lane_point.mutable_position()->set_x(lane_point_pos[0]); lane_point.mutable_position()->set_y(lane_point_pos[1]); lane_point.set_heading(lane_point_heading); lane_point.set_width(lane_point_width); lane_point.set_angle_diff(lane_point_angle_diff); // Update into lane_segment. lane_segment->add_lane_point()->CopyFrom(lane_point); lane_seg_s += lane_point_spacing; } } } // Build lane-point in the forward direction. int lane_index = lane_sequence->adc_lane_segment_idx(); double total_s = 0.0; double lane_seg_s = lane_sequence->lane_segment(lane_index).adc_s(); if (!is_bidirection) { lane_index = 0; lane_seg_s = lane_sequence->lane_segment(0).start_s(); } std::size_t count_point = 0; while (lane_index < lane_sequence->lane_segment_size() && count_point < max_num_lane_point) { // Go through lane_segment one by one sequentially. LaneSegment* lane_segment = lane_sequence->mutable_lane_segment(lane_index); if (lane_seg_s > lane_segment->end_s()) { // If already exceeds the current lane_segment, then go to the // next following one. ADEBUG << "Move on to the next lane-segment."; lane_seg_s = lane_seg_s - lane_segment->end_s(); ++lane_index; } else { // Otherwise, update lane_graph: // 1. Sanity checks. std::string lane_id = lane_segment->lane_id(); lane_segment->set_lane_turn_type(PredictionMap::LaneTurnType(lane_id)); ADEBUG << "Currently on " << lane_id; auto lane_info = PredictionMap::LaneById(lane_id); if (lane_info == nullptr) { break; } // 2. Get the closeset lane_point ADEBUG << "Lane-segment s = " << lane_seg_s; Eigen::Vector2d lane_point_pos = PredictionMap::PositionOnLane(lane_info, lane_seg_s); double lane_point_heading = PredictionMap::HeadingOnLane(lane_info, lane_seg_s); double lane_point_width = PredictionMap::LaneTotalWidth(lane_info, lane_seg_s); double lane_point_angle_diff = common::math::AngleDiff(lane_point_heading, heading); // 3. Update it into the lane_graph ADEBUG << lane_point_pos[0] << " " << lane_point_pos[1]; LanePoint lane_point; // Update direct information. lane_point.mutable_position()->set_x(lane_point_pos[0]); lane_point.mutable_position()->set_y(lane_point_pos[1]); lane_point.set_heading(lane_point_heading); lane_point.set_width(lane_point_width); lane_point.set_angle_diff(lane_point_angle_diff); // Update deducted information. double lane_l = feature->lane().lane_feature().lane_l(); lane_point.set_relative_s(total_s); lane_point.set_relative_l(0.0 - lane_l); // Update into lane_segment. lane_segment->add_lane_point()->CopyFrom(lane_point); ++count_point; total_s += lane_point_spacing; lane_seg_s += lane_point_spacing; } } } ADEBUG << "Obstacle [" << id_ << "] has lane segments and points."; } void Obstacle::SetLaneSequencePath(LaneGraph* const lane_graph) { // Go through every lane_sequence. for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) { LaneSequence* lane_sequence = lane_graph->mutable_lane_sequence(i); double lane_segment_s = 0.0; // Go through every lane_segment. for (const LaneSegment& lane_segment : lane_sequence->lane_segment()) { // Go through every lane_point and set the corresponding path_point. for (const LanePoint& lane_point : lane_segment.lane_point()) { PathPoint* path_point = lane_sequence->add_path_point(); path_point->set_s(lane_point.relative_s()); path_point->set_theta(lane_point.heading()); } lane_segment_s += lane_segment.total_length(); } // Sanity checks. int num_path_point = lane_sequence->path_point_size(); if (num_path_point <= 0) { continue; } // Go through every path_point, calculate kappa, and update it. int segment_index = 0; int point_index = 0; for (int j = 0; j + 1 < num_path_point; ++j) { while (segment_index < lane_sequence->lane_segment_size() && point_index >= lane_sequence->lane_segment(segment_index).lane_point_size()) { ++segment_index; point_index = 0; } PathPoint* first_point = lane_sequence->mutable_path_point(j); PathPoint* second_point = lane_sequence->mutable_path_point(j + 1); double delta_theta = apollo::common::math::AngleDiff( second_point->theta(), first_point->theta()); double delta_s = second_point->s() - first_point->s(); double kappa = std::abs(delta_theta / (delta_s + FLAGS_double_precision)); lane_sequence->mutable_path_point(j)->set_kappa(kappa); if (segment_index < lane_sequence->lane_segment_size() && point_index < lane_sequence->lane_segment(segment_index).lane_point_size()) { lane_sequence->mutable_lane_segment(segment_index) ->mutable_lane_point(point_index) ->set_kappa(kappa); ++point_index; } } lane_sequence->mutable_path_point(num_path_point - 1)->set_kappa(0.0); } } void Obstacle::SetNearbyObstacles() { // This function runs after all basic features have been set up Feature* feature_ptr = mutable_latest_feature(); LaneGraph* lane_graph = feature_ptr->mutable_lane()->mutable_lane_graph(); for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) { LaneSequence* lane_sequence = lane_graph->mutable_lane_sequence(i); if (lane_sequence->lane_segment_size() == 0) { AERROR << "Empty lane sequence found."; continue; } double obstacle_s = lane_sequence->lane_s(); double obstacle_l = lane_sequence->lane_l(); NearbyObstacle forward_obstacle; if (clusters_ptr_->ForwardNearbyObstacle(*lane_sequence, id_, obstacle_s, obstacle_l, &forward_obstacle)) { lane_sequence->add_nearby_obstacle()->CopyFrom(forward_obstacle); } NearbyObstacle backward_obstacle; if (clusters_ptr_->BackwardNearbyObstacle(*lane_sequence, id_, obstacle_s, obstacle_l, &backward_obstacle)) { lane_sequence->add_nearby_obstacle()->CopyFrom(backward_obstacle); } } } void Obstacle::SetMotionStatus() { int history_size = static_cast<int>(feature_history_.size()); if (history_size == 0) { AERROR << "Zero history found"; return; } double pos_std = FLAGS_still_obstacle_position_std; double speed_threshold = FLAGS_still_obstacle_speed_threshold; if (type_ == PerceptionObstacle::PEDESTRIAN || type_ == PerceptionObstacle::BICYCLE) { speed_threshold = FLAGS_still_pedestrian_speed_threshold; pos_std = FLAGS_still_pedestrian_position_std; } else if (type_ == PerceptionObstacle::UNKNOWN || type_ == PerceptionObstacle::UNKNOWN_MOVABLE) { speed_threshold = FLAGS_still_unknown_speed_threshold; pos_std = FLAGS_still_unknown_position_std; } double speed = feature_history_.front().speed(); if (history_size == 1) { if (speed < speed_threshold) { ADEBUG << "Obstacle [" << id_ << "] has a small speed [" << speed << "] and is considered stationary in the first frame."; feature_history_.front().set_is_still(true); } else { feature_history_.front().set_is_still(false); } return; } double start_x = 0.0; double start_y = 0.0; double avg_drift_x = 0.0; double avg_drift_y = 0.0; int len = std::min(history_size, FLAGS_max_still_obstacle_history_length); len = std::max(len, FLAGS_min_still_obstacle_history_length); CHECK_GT(len, 1); auto feature_riter = feature_history_.rbegin(); start_x = feature_riter->position().x(); start_y = feature_riter->position().y(); ++feature_riter; while (feature_riter != feature_history_.rend()) { avg_drift_x += (feature_riter->position().x() - start_x) / (len - 1); avg_drift_y += (feature_riter->position().y() - start_y) / (len - 1); ++feature_riter; } double delta_ts = feature_history_.front().timestamp() - feature_history_.back().timestamp(); double speed_sensibility = std::sqrt(2 * history_size) * 4 * pos_std / ((history_size + 1) * delta_ts); if (speed < speed_threshold) { ADEBUG << "Obstacle [" << id_ << "] has a small speed [" << speed << "] and is considered stationary."; feature_history_.front().set_is_still(true); } else if (speed_sensibility < speed_threshold) { ADEBUG << "Obstacle [" << id_ << "]" << "] considered moving [sensibility = " << speed_sensibility << "]"; feature_history_.front().set_is_still(false); } else { double distance = std::hypot(avg_drift_x, avg_drift_y); double distance_std = std::sqrt(2.0 / len) * pos_std; if (distance > 2.0 * distance_std) { ADEBUG << "Obstacle [" << id_ << "] is moving."; feature_history_.front().set_is_still(false); } else { ADEBUG << "Obstacle [" << id_ << "] is stationary."; feature_history_.front().set_is_still(true); } } } void Obstacle::SetMotionStatusBySpeed() { auto history_size = feature_history_.size(); if (history_size < 2) { ADEBUG << "Obstacle [" << id_ << "] has no history and " << "is considered moving."; if (history_size > 0) { feature_history_.front().set_is_still(false); } return; } double speed_threshold = FLAGS_still_obstacle_speed_threshold; double speed = feature_history_.front().speed(); if (FLAGS_use_navigation_mode) { if (speed < speed_threshold) { feature_history_.front().set_is_still(true); } else { feature_history_.front().set_is_still(false); } } } void Obstacle::InsertFeatureToHistory(const Feature& feature) { feature_history_.emplace_front(feature); ADEBUG << "Obstacle [" << id_ << "] inserted a frame into the history."; } std::unique_ptr<Obstacle> Obstacle::Create( const PerceptionObstacle& perception_obstacle, const double timestamp, const int prediction_id, ObstacleClusters* clusters_ptr) { std::unique_ptr<Obstacle> ptr_obstacle(new Obstacle()); ptr_obstacle->SetClusters(clusters_ptr); if (!ptr_obstacle->Insert(perception_obstacle, timestamp, prediction_id)) { return nullptr; } return ptr_obstacle; } std::unique_ptr<Obstacle> Obstacle::Create(const Feature& feature, ObstacleClusters* clusters_ptr) { std::unique_ptr<Obstacle> ptr_obstacle(new Obstacle()); ptr_obstacle->SetClusters(clusters_ptr); ptr_obstacle->InsertFeatureToHistory(feature); return ptr_obstacle; } bool Obstacle::ReceivedOlderMessage(const double timestamp) const { if (feature_history_.empty()) { return false; } auto last_timestamp_received = feature_history_.front().timestamp(); return timestamp <= last_timestamp_received; } void Obstacle::DiscardOutdatedHistory() { auto num_of_frames = feature_history_.size(); const double latest_ts = feature_history_.front().timestamp(); while (latest_ts - feature_history_.back().timestamp() >= FLAGS_max_history_time) { feature_history_.pop_back(); } auto num_of_discarded_frames = num_of_frames - feature_history_.size(); if (num_of_discarded_frames > 0) { ADEBUG << "Obstacle [" << id_ << "] discards " << num_of_discarded_frames << " historical features"; } } void Obstacle::SetCaution() { CHECK_GT(feature_history_.size(), 0U); Feature* feature = mutable_latest_feature(); feature->mutable_priority()->set_priority(ObstaclePriority::CAUTION); } bool Obstacle::IsCaution() const { if (feature_history_.empty()) { return false; } const Feature& feature = latest_feature(); return feature.priority().priority() == ObstaclePriority::CAUTION; } void Obstacle::SetInteractiveTag() { CHECK_GT(feature_history_.size(), 0U); Feature* feature = mutable_latest_feature(); feature->mutable_interactive_tag() ->set_interactive_tag(ObstacleInteractiveTag::INTERACTION); } void Obstacle::SetNonInteractiveTag() { CHECK_GT(feature_history_.size(), 0U); Feature* feature = mutable_latest_feature(); feature->mutable_interactive_tag() ->set_interactive_tag(ObstacleInteractiveTag::NONINTERACTION); } bool Obstacle::IsInteractiveObstacle() const { if (feature_history_.empty()) { return false; } const Feature& feature = latest_feature(); return feature.interactive_tag().interactive_tag() == ObstacleInteractiveTag::INTERACTION; } void Obstacle::SetEvaluatorType( const ObstacleConf::EvaluatorType& evaluator_type) { obstacle_conf_.set_evaluator_type(evaluator_type); } void Obstacle::SetPredictorType( const ObstacleConf::PredictorType& predictor_type) { obstacle_conf_.set_predictor_type(predictor_type); } PredictionObstacle Obstacle::GeneratePredictionObstacle() { PredictionObstacle prediction_obstacle; // TODO(kechxu) implement return prediction_obstacle; } void Obstacle::SetClusters(ObstacleClusters* clusters_ptr) { clusters_ptr_ = clusters_ptr; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacle_clusters_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/prediction/common/kml_map_based_test.h" #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { class ObstacleClustersTest : public KMLMapBasedTest {}; TEST_F(ObstacleClustersTest, ObstacleClusters) { auto lane = PredictionMap::LaneById("l9"); double start_s = 99.0; double length = 100.0; ObstacleClusters cluster; const LaneGraph &lane_graph = cluster.GetLaneGraph(start_s, length, true, lane); EXPECT_EQ(1, lane_graph.lane_sequence_size()); EXPECT_EQ(3, lane_graph.lane_sequence(0).lane_segment_size()); EXPECT_EQ("l9", lane_graph.lane_sequence(0).lane_segment(0).lane_id()); EXPECT_EQ("l18", lane_graph.lane_sequence(0).lane_segment(1).lane_id()); EXPECT_EQ("l21", lane_graph.lane_sequence(0).lane_segment(2).lane_id()); double length_2 = 50.0; const LaneGraph &lane_graph_2 = cluster.GetLaneGraph(start_s, length_2, true, lane); EXPECT_EQ(1, lane_graph_2.lane_sequence_size()); EXPECT_EQ(2, lane_graph_2.lane_sequence(0).lane_segment_size()); EXPECT_EQ("l9", lane_graph_2.lane_sequence(0).lane_segment(0).lane_id()); EXPECT_EQ("l18", lane_graph_2.lane_sequence(0).lane_segment(1).lane_id()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacles_container.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/prediction/container/obstacles/obstacles_container.h" #include <iomanip> #include <utility> #include "modules/prediction/common/feature_output.h" #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/prediction_constants.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" namespace apollo { namespace prediction { using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; ObstaclesContainer::ObstaclesContainer() : ptr_obstacles_(FLAGS_max_num_obstacles), clusters_(new ObstacleClusters()) {} ObstaclesContainer::ObstaclesContainer(const SubmoduleOutput& submodule_output) : ptr_obstacles_(FLAGS_max_num_obstacles), clusters_(new ObstacleClusters()) { for (const Obstacle& obstacle : submodule_output.curr_frame_obstacles()) { // Deep copy of obstacle is needed for modification std::unique_ptr<Obstacle> ptr_obstacle(new Obstacle(obstacle)); ptr_obstacle->SetJunctionAnalyzer(&junction_analyzer_); ptr_obstacles_.Put(obstacle.id(), std::move(ptr_obstacle)); } Obstacle ego_vehicle = submodule_output.GetEgoVehicle(); std::unique_ptr<Obstacle> ptr_ego_vehicle( new Obstacle(std::move(ego_vehicle))); ptr_ego_vehicle->SetJunctionAnalyzer(&junction_analyzer_); ptr_obstacles_.Put(ego_vehicle.id(), std::move(ptr_ego_vehicle)); curr_frame_movable_obstacle_ids_ = submodule_output.curr_frame_movable_obstacle_ids(); curr_frame_unmovable_obstacle_ids_ = submodule_output.curr_frame_unmovable_obstacle_ids(); curr_frame_considered_obstacle_ids_ = submodule_output.curr_frame_considered_obstacle_ids(); curr_scenario_ = submodule_output.curr_scenario(); } void ObstaclesContainer::CleanUp() { // Clean up the history and get the PerceptionObstacles curr_frame_movable_obstacle_ids_.clear(); curr_frame_unmovable_obstacle_ids_.clear(); curr_frame_considered_obstacle_ids_.clear(); } // This is called by Perception module at every frame to insert all // detected obstacles. void ObstaclesContainer::Insert(const ::google::protobuf::Message& message) { PerceptionObstacles perception_obstacles; perception_obstacles.CopyFrom( dynamic_cast<const PerceptionObstacles&>(message)); // Get the new timestamp and update it in the class // - If it's more than 10sec later than the most recent one, clear the // obstacle history. // - If it's not a valid time (earlier than history), continue. // - Also consider the offline_mode case. double timestamp = 0.0; if (perception_obstacles.has_header() && perception_obstacles.header().has_timestamp_sec()) { timestamp = perception_obstacles.header().timestamp_sec(); } if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap) { ptr_obstacles_.Clear(); ADEBUG << "Replay mode is enabled."; } else if (timestamp <= timestamp_) { AERROR << "Invalid timestamp curr [" << timestamp << "] v.s. prev [" << timestamp_ << "]."; return; } switch (FLAGS_prediction_offline_mode) { case 1: { if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap || FeatureOutput::Size() > FLAGS_max_num_dump_feature) { FeatureOutput::WriteFeatureProto(); } break; } case 2: { if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap || FeatureOutput::SizeOfDataForLearning() > FLAGS_max_num_dump_dataforlearn) { FeatureOutput::WriteDataForLearning(); } break; } case 3: { if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap || FeatureOutput::SizeOfPredictionResult() > FLAGS_max_num_dump_feature) { FeatureOutput::WritePredictionResult(); } break; } case 4: { if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap || FeatureOutput::SizeOfFrameEnv() > FLAGS_max_num_dump_feature) { FeatureOutput::WriteFrameEnv(); } break; } case 5: { if (std::fabs(timestamp - timestamp_) > FLAGS_replay_timestamp_gap || FeatureOutput::SizeOfFrameEnv() > FLAGS_max_num_dump_feature) { FeatureOutput::WriteDataForTuning(); } break; } default: { // No data dump FeatureOutput::Clear(); break; } } timestamp_ = timestamp; ADEBUG << "Current timestamp is [" << std::fixed << std::setprecision(6) << timestamp_ << "]"; // Set up the ObstacleClusters: // Insert the Obstacles one by one for (const PerceptionObstacle& perception_obstacle : perception_obstacles.perception_obstacle()) { ADEBUG << "Perception obstacle [" << perception_obstacle.id() << "] " << "was detected"; InsertPerceptionObstacle(perception_obstacle, timestamp_); ADEBUG << "Perception obstacle [" << perception_obstacle.id() << "] " << "was inserted"; } SetConsideredObstacleIds(); clusters_->SortObstacles(); } Obstacle* ObstaclesContainer::GetObstacle(const int id) { auto ptr_obstacle = ptr_obstacles_.GetSilently(id); if (ptr_obstacle != nullptr) { return ptr_obstacle->get(); } return nullptr; } Obstacle* ObstaclesContainer::GetObstacleWithLRUUpdate(const int obstacle_id) { auto ptr_obstacle = ptr_obstacles_.Get(obstacle_id); if (ptr_obstacle != nullptr) { return ptr_obstacle->get(); } return nullptr; } void ObstaclesContainer::Clear() { ptr_obstacles_.Clear(); timestamp_ = -1.0; } const std::vector<int>& ObstaclesContainer::curr_frame_movable_obstacle_ids() { return curr_frame_movable_obstacle_ids_; } const std::vector<int>& ObstaclesContainer::curr_frame_unmovable_obstacle_ids() { return curr_frame_unmovable_obstacle_ids_; } const std::vector<int>& ObstaclesContainer::curr_frame_considered_obstacle_ids() { return curr_frame_considered_obstacle_ids_; } void ObstaclesContainer::SetConsideredObstacleIds() { curr_frame_considered_obstacle_ids_.clear(); for (const int id : curr_frame_movable_obstacle_ids_) { Obstacle* obstacle_ptr = GetObstacle(id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle found."; continue; } if (obstacle_ptr->ToIgnore()) { ADEBUG << "Ignore obstacle [" << obstacle_ptr->id() << "]"; continue; } curr_frame_considered_obstacle_ids_.push_back(id); } } std::vector<int> ObstaclesContainer::curr_frame_obstacle_ids() { std::vector<int> curr_frame_obs_ids = curr_frame_movable_obstacle_ids_; curr_frame_obs_ids.insert(curr_frame_obs_ids.end(), curr_frame_unmovable_obstacle_ids_.begin(), curr_frame_unmovable_obstacle_ids_.end()); return curr_frame_obs_ids; } void ObstaclesContainer::InsertPerceptionObstacle( const PerceptionObstacle& perception_obstacle, const double timestamp) { // Sanity checks. int id = perception_obstacle.id(); if (id < FLAGS_ego_vehicle_id) { AERROR << "Invalid ID [" << id << "]"; return; } if (!IsMovable(perception_obstacle)) { ADEBUG << "Perception obstacle [" << perception_obstacle.id() << "] is unmovable."; curr_frame_unmovable_obstacle_ids_.push_back(id); return; } // Insert the obstacle and also update the LRUCache. auto obstacle_ptr = GetObstacleWithLRUUpdate(id); if (obstacle_ptr != nullptr) { ADEBUG << "Current time = " << std::fixed << std::setprecision(6) << timestamp; obstacle_ptr->Insert(perception_obstacle, timestamp, id); ADEBUG << "Refresh obstacle [" << id << "]"; } else { auto ptr_obstacle = Obstacle::Create(perception_obstacle, timestamp, id, clusters_.get()); if (ptr_obstacle == nullptr) { AERROR << "Failed to insert obstacle into container"; return; } ptr_obstacle->SetJunctionAnalyzer(&junction_analyzer_); ptr_obstacles_.Put(id, std::move(ptr_obstacle)); ADEBUG << "Insert obstacle [" << id << "]"; } if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpDataForLearning || id != FLAGS_ego_vehicle_id) { curr_frame_movable_obstacle_ids_.push_back(id); } } void ObstaclesContainer::InsertFeatureProto(const Feature& feature) { if (!feature.has_id()) { AERROR << "Invalid feature, no ID found."; return; } int id = feature.id(); auto obstacle_ptr = GetObstacleWithLRUUpdate(id); if (obstacle_ptr != nullptr) { obstacle_ptr->InsertFeature(feature); } else { auto ptr_obstacle = Obstacle::Create(feature, clusters_.get()); if (ptr_obstacle == nullptr) { AERROR << "Failed to insert obstacle into container"; return; } ptr_obstacle->SetJunctionAnalyzer(&junction_analyzer_); ptr_obstacles_.Put(id, std::move(ptr_obstacle)); } } void ObstaclesContainer::BuildLaneGraph() { // Go through every obstacle in the current frame, after some // sanity checks, build lane graph for non-junction cases. for (const int id : curr_frame_considered_obstacle_ids_) { Obstacle* obstacle_ptr = GetObstacle(id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle found."; continue; } if (FLAGS_prediction_offline_mode != PredictionConstants::kDumpDataForLearning) { ADEBUG << "Building Lane Graph."; obstacle_ptr->BuildLaneGraph(); obstacle_ptr->BuildLaneGraphFromLeftToRight(); } else { ADEBUG << "Building ordered Lane Graph."; ADEBUG << "Building lane graph for id = " << id; obstacle_ptr->BuildLaneGraphFromLeftToRight(); } obstacle_ptr->SetNearbyObstacles(); } Obstacle* ego_vehicle_ptr = GetObstacle(FLAGS_ego_vehicle_id); if (ego_vehicle_ptr == nullptr) { AERROR << "Ego vehicle not inserted"; return; } ego_vehicle_ptr->BuildLaneGraph(); ego_vehicle_ptr->SetNearbyObstacles(); } void ObstaclesContainer::BuildJunctionFeature() { // Go through every obstacle in the current frame, after some // sanity checks, build junction features for those that are in junction. for (const int id : curr_frame_considered_obstacle_ids_) { Obstacle* obstacle_ptr = GetObstacle(id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle found."; continue; } const std::string& junction_id = junction_analyzer_.GetJunctionId(); if (obstacle_ptr->IsInJunction(junction_id)) { ADEBUG << "Build junction feature for obstacle [" << obstacle_ptr->id() << "] in junction [" << junction_id << "]"; obstacle_ptr->BuildJunctionFeature(); } } } bool ObstaclesContainer::IsMovable( const PerceptionObstacle& perception_obstacle) { if (!perception_obstacle.has_type() || perception_obstacle.type() == PerceptionObstacle::UNKNOWN_UNMOVABLE) { return false; } return true; } double ObstaclesContainer::timestamp() const { return timestamp_; } SubmoduleOutput ObstaclesContainer::GetSubmoduleOutput( const size_t history_size, const apollo::cyber::Time& frame_start_time) { SubmoduleOutput container_output; for (int id : curr_frame_considered_obstacle_ids_) { Obstacle* obstacle = GetObstacle(id); if (obstacle == nullptr) { AERROR << "Nullptr found for obstacle [" << id << "]"; continue; } obstacle->TrimHistory(history_size); obstacle->ClearOldInformation(); container_output.InsertObstacle(std::move(*obstacle)); } Obstacle* ego_obstacle = GetObstacle(FLAGS_ego_vehicle_id); if (ego_obstacle != nullptr) { container_output.InsertEgoVehicle(std::move(*ego_obstacle)); } container_output.set_curr_frame_movable_obstacle_ids( curr_frame_movable_obstacle_ids_); container_output.set_curr_frame_unmovable_obstacle_ids( curr_frame_unmovable_obstacle_ids_); container_output.set_curr_frame_considered_obstacle_ids( curr_frame_considered_obstacle_ids_); container_output.set_frame_start_time(frame_start_time); return container_output; } const Scenario& ObstaclesContainer::curr_scenario() const { return curr_scenario_; } ObstacleClusters* ObstaclesContainer::GetClustersPtr() const { return clusters_.get(); } JunctionAnalyzer* ObstaclesContainer::GetJunctionAnalyzer() { return &junction_analyzer_; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacles_container.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 * @brief Obstacles container */ #pragma once #include <memory> #include <string> #include <vector> #include "modules/common/util/lru_cache.h" #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/container/container.h" #include "modules/prediction/container/obstacles/obstacle.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" #include "modules/prediction/submodules/submodule_output.h" namespace apollo { namespace prediction { class ObstaclesContainer : public Container { public: /** * @brief Constructor */ ObstaclesContainer(); /** * @brief Constructor from container output */ explicit ObstaclesContainer(const SubmoduleOutput& submodule_output); /** * @brief Destructor */ virtual ~ObstaclesContainer() = default; /** * @brief Insert a data message into the container * @param Data message to be inserted in protobuf */ void Insert(const ::google::protobuf::Message& message) override; /** * @brief Insert an perception obstacle * @param Perception obstacle * Timestamp */ void InsertPerceptionObstacle( const perception::PerceptionObstacle& perception_obstacle, const double timestamp); /** * @brief Insert a feature proto message into the container * @param feature proto message */ void InsertFeatureProto(const Feature& feature); /** * @brief Build lane graph for obstacles */ void BuildLaneGraph(); /** * @brief Build junction feature for obstacles */ void BuildJunctionFeature(); /** * @brief Get obstacle pointer * @param Obstacle ID * @return Obstacle pointer */ Obstacle* GetObstacle(const int id); /** * @brief Clear obstacle container */ void Clear(); void CleanUp(); size_t NumOfObstacles() { return ptr_obstacles_.size(); } const apollo::perception::PerceptionObstacle& GetPerceptionObstacle( const int id); /** * @brief Get movable obstacle IDs in the current frame * @return Movable obstacle IDs in the current frame */ const std::vector<int>& curr_frame_movable_obstacle_ids(); /** * @brief Get unmovable obstacle IDs in the current frame * @return unmovable obstacle IDs in the current frame */ const std::vector<int>& curr_frame_unmovable_obstacle_ids(); /** * @brief Get non-ignore obstacle IDs in the current frame * @return Non-ignore obstacle IDs in the current frame */ const std::vector<int>& curr_frame_considered_obstacle_ids(); /* * @brief Set non-ignore obstacle IDs in the current frame */ void SetConsideredObstacleIds(); /** * @brief Get current frame obstacle IDs in the current frame * @return Current frame obstacle IDs in the current frame */ std::vector<int> curr_frame_obstacle_ids(); double timestamp() const; SubmoduleOutput GetSubmoduleOutput( const size_t history_size, const apollo::cyber::Time& frame_start_time); /** * @brief Get current scenario */ const Scenario& curr_scenario() const; /** * @brief Get the raw pointer of clusters_ */ ObstacleClusters* GetClustersPtr() const; JunctionAnalyzer* GetJunctionAnalyzer(); private: Obstacle* GetObstacleWithLRUUpdate(const int obstacle_id); /** * @brief Check if an obstacle is movable * @param An obstacle * @return True if the obstacle is movable; otherwise false; */ bool IsMovable(const perception::PerceptionObstacle& perception_obstacle); private: double timestamp_ = -1.0; common::util::LRUCache<int, std::unique_ptr<Obstacle>> ptr_obstacles_; std::vector<int> curr_frame_movable_obstacle_ids_; std::vector<int> curr_frame_unmovable_obstacle_ids_; std::vector<int> curr_frame_considered_obstacle_ids_; Scenario curr_scenario_; std::unique_ptr<ObstacleClusters> clusters_; JunctionAnalyzer junction_analyzer_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""] cc_library( name = "obstacles_container", srcs = ["obstacles_container.cc"], hdrs = ["obstacles_container.h"], copts = PREDICTION_COPTS, deps = [ ":obstacle_clusters", "//modules/prediction/common:environment_features", "//modules/prediction/common:feature_output", "//modules/prediction/common:junction_analyzer", "//modules/prediction/common:prediction_constants", "//modules/prediction/container", "//modules/prediction/container/obstacles:obstacle", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "//modules/prediction/submodules:submodule_output", ], ) cc_library( name = "obstacle", srcs = ["obstacle.cc"], hdrs = ["obstacle.h"], copts = PREDICTION_COPTS, deps = [ ":obstacle_clusters", "//modules/common/filters", "//modules/prediction/common:junction_analyzer", "//modules/prediction/common:prediction_constants", "//modules/prediction/network/rnn_model", "//modules/prediction/proto:prediction_conf_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", ], ) cc_test( name = "obstacles_container_test", size = "small", srcs = ["obstacles_container_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ "//modules/prediction/common:kml_map_based_test", "//modules/prediction/container/obstacles:obstacles_container", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "obstacle_test", size = "small", srcs = ["obstacle_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ "//modules/prediction/common:kml_map_based_test", "//modules/prediction/container/obstacles:obstacles_container", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "obstacle_clusters", srcs = ["obstacle_clusters.cc"], hdrs = ["obstacle_clusters.h"], copts = PREDICTION_COPTS, deps = [ "//modules/common/util", "//modules/prediction/common:road_graph", "//modules/common_msgs/prediction_msgs:feature_cc_proto", ], ) cc_test( name = "obstacle_clusters_test", size = "small", srcs = ["obstacle_clusters_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ "//modules/prediction/common:kml_map_based_test", "//modules/prediction/container/obstacles:obstacle_clusters", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacle.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Obstacle */ #pragma once #include <deque> #include <list> #include <memory> #include <string> #include <unordered_set> #include <vector> #include "modules/common/filters/digital_filter.h" #include "modules/common/math/kalman_filter.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/common_msgs/prediction_msgs/feature.pb.h" #include "modules/prediction/proto/prediction_conf.pb.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" /** * @namespace apollo::prediction * @brief apollo::prediction */ namespace apollo { namespace prediction { /** * @class Obstacle * @brief Prediction obstacle. */ class Obstacle { public: /** * @brief Constructor */ static std::unique_ptr<Obstacle> Create( const perception::PerceptionObstacle& perception_obstacle, const double timestamp, const int prediction_id, ObstacleClusters* clusters_ptr); static std::unique_ptr<Obstacle> Create(const Feature& feature, ObstacleClusters* clusters_ptr); Obstacle() = default; /** * @brief Destructor */ virtual ~Obstacle() = default; void SetJunctionAnalyzer(JunctionAnalyzer* junction_analyzer) { junction_analyzer_ = junction_analyzer; } /** * @brief Insert a perception obstacle with its timestamp. * @param perception_obstacle The obstacle from perception. * @param timestamp The timestamp when the perception obstacle was detected. */ bool Insert(const perception::PerceptionObstacle& perception_obstacle, const double timestamp, const int prediction_id); /** * @brief Insert a feature proto message. * @param feature proto message. */ bool InsertFeature(const Feature& feature); void ClearOldInformation(); void TrimHistory(const size_t remain_size); /** * @brief Get the type of perception obstacle's type. * @return The type pf perception obstacle. */ perception::PerceptionObstacle::Type type() const; bool IsPedestrian() const; /** * @brief Get the obstacle's ID. * @return The obstacle's ID. */ int id() const; /** * @brief Get the obstacle's timestamp. * @return The obstacle's timestamp. */ double timestamp() const; bool ReceivedOlderMessage(const double timestamp) const; /** * @brief Get the ith feature from latest to earliest. * @param i The index of the feature. * @return The ith feature. */ const Feature& feature(const size_t i) const; /** * @brief Get a pointer to the ith feature from latest to earliest. * @param i The index of the feature. * @return A pointer to the ith feature. */ Feature* mutable_feature(const size_t i); /** * @brief Get the latest feature. * @return The latest feature. */ const Feature& latest_feature() const; /** * @brief Get the earliest feature. * @return The earliest feature. */ const Feature& earliest_feature() const; /** * @brief Get a pointer to the latest feature. * @return A pointer to the latest feature. */ Feature* mutable_latest_feature(); /** * @brief Set nearby obstacles. */ void SetNearbyObstacles(); /** * @brief Get the number of historical features. * @return The number of historical features. */ size_t history_size() const; /** * @brief Check if the obstacle is still. * @return If the obstacle is still. */ bool IsStill(); /** * @brief Check if the obstacle is slow. * @return If the obstacle is slow. */ bool IsSlow(); /** * @brief Check if the obstacle is on any lane. * @return If the obstacle is on any lane. */ bool IsOnLane() const; /** * @brief Check if the obstacle can be ignored. * @return If the obstacle can be ignored. */ bool ToIgnore(); /** * @brief Check if the obstacle is near a junction. * @return If the obstacle is near a junction. */ bool IsNearJunction(); /** * @brief Check if the obstacle is a junction. * @param junction ID * @return If the obstacle is in a junction. */ bool IsInJunction(const std::string& junction_id) const; /** * @brief Check if the obstacle is close to a junction exit. * @return If the obstacle is closed to a junction exit. */ bool IsCloseToJunctionExit() const; /** * @brief Check if the obstacle has junction feature. * @return If the obstacle has junction feature. */ bool HasJunctionFeatureWithExits() const; /** * @brief Build junction feature. */ void BuildJunctionFeature(); /** * @brief Build obstacle's lane graph */ void BuildLaneGraph(); /** * @brief Build obstacle's lane graph with lanes being ordered. * This would be useful for lane-scanning algorithms. */ void BuildLaneGraphFromLeftToRight(); /** * @brief Set the obstacle as caution level */ void SetCaution(); bool IsCaution() const; /** * @brief Set the obstacle as interactive obstacle. */ void SetInteractiveTag(); /** * @brief Set the obstacle as noninteractive obstacle. */ void SetNonInteractiveTag(); bool IsInteractiveObstacle() const; void SetEvaluatorType(const ObstacleConf::EvaluatorType& evaluator_type); void SetPredictorType(const ObstacleConf::PredictorType& predictor_type); const ObstacleConf& obstacle_conf() { return obstacle_conf_; } PredictionObstacle GeneratePredictionObstacle(); private: void SetStatus(const perception::PerceptionObstacle& perception_obstacle, double timestamp, Feature* feature); bool SetId(const perception::PerceptionObstacle& perception_obstacle, Feature* feature, const int prediction_id = -1); void SetType(const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void SetIsNearJunction( const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void SetTimestamp(const perception::PerceptionObstacle& perception_obstacle, const double timestamp, Feature* feature); void SetPolygonPoints( const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void SetPosition(const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void SetVelocity(const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void AdjustHeadingByLane(Feature* feature); void UpdateVelocity(const double theta, double* velocity_x, double* velocity_y, double* velocity_heading, double* speed); void SetAcceleration(Feature* feature); void SetTheta(const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void SetLengthWidthHeight( const perception::PerceptionObstacle& perception_obstacle, Feature* feature); void UpdateLaneBelief(Feature* feature); void SetCurrentLanes(Feature* feature); void SetNearbyLanes(Feature* feature); void SetSurroundingLaneIds(Feature* feature, const double radius); void SetLaneSequenceStopSign(LaneSequence* lane_sequence_ptr); /** @brief This functions updates the lane-points into the lane-segments * based on the given lane_point_spacing. */ void SetLanePoints(Feature* feature); void SetLanePoints(const Feature* feature, const double lane_point_spacing, const uint64_t max_num_lane_point, const bool is_bidirection, LaneGraph* const lane_graph); /** @brief This functions is mainly for lane-sequence kappa calculation. */ void SetLaneSequencePath(LaneGraph* const lane_graph); void SetMotionStatus(); void SetMotionStatusBySpeed(); void InsertFeatureToHistory(const Feature& feature); void SetJunctionFeatureWithEnterLane(const std::string& enter_lane_id, Feature* const feature_ptr); void SetJunctionFeatureWithoutEnterLane(Feature* const feature_ptr); void DiscardOutdatedHistory(); void GetNeighborLaneSegments( std::shared_ptr<const apollo::hdmap::LaneInfo> center_lane_info, bool is_left, int recursion_depth, std::list<std::string>* const lane_ids_ordered, std::unordered_set<std::string>* const existing_lane_ids); bool HasJunctionExitLane( const LaneSequence& lane_sequence, const std::unordered_set<std::string>& exit_lane_id_set); void SetClusters(ObstacleClusters* clusters_ptr); private: int id_ = FLAGS_ego_vehicle_id; perception::PerceptionObstacle::Type type_ = perception::PerceptionObstacle::UNKNOWN_UNMOVABLE; std::deque<Feature> feature_history_; std::vector<std::shared_ptr<const hdmap::LaneInfo>> current_lanes_; ObstacleConf obstacle_conf_; ObstacleClusters* clusters_ptr_ = nullptr; JunctionAnalyzer* junction_analyzer_ = nullptr; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/obstacles/obstacle_clusters.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/prediction/container/obstacles/obstacle_clusters.h" #include <algorithm> #include <limits> #include "modules/prediction/common/road_graph.h" namespace apollo { namespace prediction { using ::apollo::hdmap::LaneInfo; LaneGraph ObstacleClusters::GetLaneGraph( const double start_s, const double length, const bool consider_lane_split, std::shared_ptr<const LaneInfo> lane_info_ptr) { std::string lane_id = lane_info_ptr->id().id(); RoadGraph road_graph(start_s, length, consider_lane_split, lane_info_ptr); LaneGraph lane_graph; road_graph.BuildLaneGraph(&lane_graph); return lane_graph; } LaneGraph ObstacleClusters::GetLaneGraphWithoutMemorizing( const double start_s, const double length, bool is_on_lane, std::shared_ptr<const LaneInfo> lane_info_ptr) { RoadGraph road_graph(start_s, length, true, lane_info_ptr); LaneGraph lane_graph; road_graph.BuildLaneGraphBidirection(&lane_graph); return lane_graph; } void ObstacleClusters::AddObstacle(const int obstacle_id, const std::string& lane_id, const double lane_s, const double lane_l) { LaneObstacle lane_obstacle; lane_obstacle.set_obstacle_id(obstacle_id); lane_obstacle.set_lane_id(lane_id); lane_obstacle.set_lane_s(lane_s); lane_obstacle.set_lane_l(lane_l); lane_obstacles_[lane_id].push_back(std::move(lane_obstacle)); } void ObstacleClusters::SortObstacles() { for (auto iter = lane_obstacles_.begin(); iter != lane_obstacles_.end(); ++iter) { std::sort(iter->second.begin(), iter->second.end(), [](const LaneObstacle& obs0, const LaneObstacle& obs1) -> bool { return obs0.lane_s() < obs1.lane_s(); }); } } bool ObstacleClusters::ForwardNearbyObstacle( const LaneSequence& lane_sequence, const int obstacle_id, const double obstacle_s, const double obstacle_l, NearbyObstacle* const nearby_obstacle_ptr) { double accumulated_s = 0.0; for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) { std::string lane_id = lane_segment.lane_id(); double lane_length = lane_segment.total_length(); if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() || lane_obstacles_[lane_id].empty()) { accumulated_s += lane_length; continue; } for (const LaneObstacle& lane_obstacle : lane_obstacles_[lane_id]) { if (lane_obstacle.obstacle_id() == obstacle_id) { continue; } double relative_s = accumulated_s + lane_obstacle.lane_s() - obstacle_s; double relative_l = lane_obstacle.lane_l() - obstacle_l; if (relative_s > 0.0) { nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id()); nearby_obstacle_ptr->set_s(relative_s); nearby_obstacle_ptr->set_l(relative_l); return true; } } } return false; } bool ObstacleClusters::BackwardNearbyObstacle( const LaneSequence& lane_sequence, const int obstacle_id, const double obstacle_s, const double obstacle_l, NearbyObstacle* const nearby_obstacle_ptr) { if (lane_sequence.lane_segment().empty()) { AERROR << "Empty lane sequence found."; return false; } const LaneSegment& lane_segment = lane_sequence.lane_segment(0); std::string lane_id = lane_segment.lane_id(); // Search current lane if (lane_obstacles_.find(lane_id) != lane_obstacles_.end() && !lane_obstacles_[lane_id].empty()) { for (int i = static_cast<int>(lane_obstacles_[lane_id].size()) - 1; i >= 0; --i) { const LaneObstacle& lane_obstacle = lane_obstacles_[lane_id][i]; if (lane_obstacle.obstacle_id() == obstacle_id) { continue; } double relative_s = lane_obstacle.lane_s() - obstacle_s; double relative_l = lane_obstacle.lane_l() - obstacle_l; if (relative_s < 0.0) { nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id()); nearby_obstacle_ptr->set_s(relative_s); nearby_obstacle_ptr->set_l(relative_l); return true; } } } // Search backward lanes std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); bool found_one_behind = false; double relative_s = -std::numeric_limits<double>::infinity(); double relative_l = 0.0; for (const auto& predecessor_lane_id : lane_info_ptr->lane().predecessor_id()) { std::string lane_id = predecessor_lane_id.id(); if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() || lane_obstacles_[lane_id].empty()) { continue; } std::shared_ptr<const LaneInfo> pred_lane_info_ptr = PredictionMap::LaneById(predecessor_lane_id.id()); const LaneObstacle& backward_obs = lane_obstacles_[lane_id].back(); double delta_s = backward_obs.lane_s() - (obstacle_s + pred_lane_info_ptr->total_length()); found_one_behind = true; if (delta_s > relative_s) { relative_s = delta_s; relative_l = backward_obs.lane_l() - obstacle_l; nearby_obstacle_ptr->set_id(backward_obs.obstacle_id()); nearby_obstacle_ptr->set_s(relative_s); nearby_obstacle_ptr->set_l(relative_l); } } return found_one_behind; } StopSign ObstacleClusters::QueryStopSignByLaneId(const std::string& lane_id) { StopSign stop_sign; // Find the stop_sign by lane_id in the hashtable if (lane_id_stop_sign_map_.find(lane_id) != lane_id_stop_sign_map_.end()) { return lane_id_stop_sign_map_[lane_id]; } std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); CHECK_NOTNULL(lane_info_ptr); for (const auto& overlap_id : lane_info_ptr->lane().overlap_id()) { auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id()); if (overlap_info_ptr == nullptr) { continue; } for (const auto& object : overlap_info_ptr->overlap().object()) { // find the overlap with stop_sign if (object.has_stop_sign_overlap_info()) { for (const auto& obj : overlap_info_ptr->overlap().object()) { // find the obj of in the overlap if (obj.has_lane_overlap_info()) { if (!stop_sign.has_lane_s() || stop_sign.lane_s() > obj.lane_overlap_info().start_s()) { stop_sign.set_stop_sign_id(object.id().id()); stop_sign.set_lane_id(lane_id); stop_sign.set_lane_s(obj.lane_overlap_info().start_s()); lane_id_stop_sign_map_[lane_id] = stop_sign; } } } } } } return lane_id_stop_sign_map_[lane_id]; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/adc_trajectory/adc_trajectory_container.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/prediction/container/adc_trajectory/adc_trajectory_container.h" #include <utility> #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::common::PathPoint; using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; using apollo::hdmap::JunctionInfo; using apollo::planning::ADCTrajectory; ADCTrajectoryContainer::ADCTrajectoryContainer() : adc_junction_info_ptr_(nullptr), s_dist_to_junction_(0.0) {} void ADCTrajectoryContainer::Insert( const ::google::protobuf::Message& message) { adc_lane_ids_.clear(); adc_lane_seq_.clear(); adc_target_lane_ids_.clear(); adc_target_lane_seq_.clear(); adc_junction_polygon_ = std::move(Polygon2d()); adc_trajectory_.CopyFrom(dynamic_cast<const ADCTrajectory&>(message)); ADEBUG << "Received a planning message [" << adc_trajectory_.ShortDebugString() << "]."; // Find ADC lane sequence SetLaneSequence(); ADEBUG << "Generate an ADC lane id sequence [" << ToString(adc_lane_seq_) << "]."; // Find ADC target lane sequence SetTargetLaneSequence(); ADEBUG << "Generate an ADC target lane id sequence [" << ToString(adc_target_lane_seq_) << "]."; } bool ADCTrajectoryContainer::IsPointInJunction(const PathPoint& point) const { if (adc_junction_polygon_.points().size() < 3) { return false; } bool in_polygon = adc_junction_polygon_.IsPointIn({point.x(), point.y()}); bool on_virtual_lane = false; if (point.has_lane_id()) { on_virtual_lane = PredictionMap::IsVirtualLane(point.lane_id()); } if (!on_virtual_lane) { on_virtual_lane = PredictionMap::OnVirtualLane({point.x(), point.y()}, FLAGS_virtual_lane_radius); } return in_polygon && on_virtual_lane; } bool ADCTrajectoryContainer::IsProtected() const { return adc_trajectory_.has_right_of_way_status() && adc_trajectory_.right_of_way_status() == ADCTrajectory::PROTECTED; } void ADCTrajectoryContainer::SetJunction(const std::string& junction_id, const double distance) { std::shared_ptr<const JunctionInfo> junction_info = PredictionMap::JunctionById(junction_id); if (junction_info != nullptr && junction_info->junction().has_polygon()) { std::vector<Vec2d> vertices; for (const auto& point : junction_info->junction().polygon().point()) { vertices.emplace_back(point.x(), point.y()); } if (vertices.size() >= 3) { adc_junction_info_ptr_ = junction_info; s_dist_to_junction_ = distance; adc_junction_polygon_ = std::move(Polygon2d{vertices}); } } } void ADCTrajectoryContainer::SetJunctionPolygon() { std::shared_ptr<const JunctionInfo> junction_info(nullptr); double s_start = 0.0; double s_at_junction = 0.0; if (adc_trajectory_.trajectory_point_size() > 0) { s_start = adc_trajectory_.trajectory_point(0).path_point().s(); } for (int i = 0; i < adc_trajectory_.trajectory_point_size(); ++i) { double s = adc_trajectory_.trajectory_point(i).path_point().s(); if (s > FLAGS_adc_trajectory_search_length) { break; } if (junction_info != nullptr) { s_at_junction = s; break; } double x = adc_trajectory_.trajectory_point(i).path_point().x(); double y = adc_trajectory_.trajectory_point(i).path_point().y(); std::vector<std::shared_ptr<const JunctionInfo>> junctions = PredictionMap::GetJunctions({x, y}, FLAGS_junction_search_radius); if (!junctions.empty() && junctions.front() != nullptr) { junction_info = junctions.front(); } } if (junction_info != nullptr && junction_info->junction().has_polygon()) { std::vector<Vec2d> vertices; for (const auto& point : junction_info->junction().polygon().point()) { vertices.emplace_back(point.x(), point.y()); } if (vertices.size() >= 3) { adc_junction_info_ptr_ = junction_info; s_dist_to_junction_ = s_at_junction - s_start; adc_junction_polygon_ = std::move(Polygon2d{vertices}); } } } std::shared_ptr<const apollo::hdmap::JunctionInfo> ADCTrajectoryContainer::ADCJunction() const { return adc_junction_info_ptr_; } double ADCTrajectoryContainer::ADCDistanceToJunction() const { return s_dist_to_junction_; } const ADCTrajectory& ADCTrajectoryContainer::adc_trajectory() const { return adc_trajectory_; } bool ADCTrajectoryContainer::IsLaneIdInReferenceLine( const std::string& lane_id) const { return adc_lane_ids_.find(lane_id) != adc_lane_ids_.end(); } bool ADCTrajectoryContainer::IsLaneIdInTargetReferenceLine( const std::string& lane_id) const { return adc_target_lane_ids_.find(lane_id) != adc_target_lane_ids_.end(); } void ADCTrajectoryContainer::SetLaneSequence() { for (const auto& lane : adc_trajectory_.lane_id()) { if (!lane.id().empty()) { if (adc_lane_seq_.empty() || lane.id() != adc_lane_seq_.back()) { adc_lane_seq_.emplace_back(lane.id()); } } } adc_lane_ids_.clear(); adc_lane_ids_.insert(adc_lane_seq_.begin(), adc_lane_seq_.end()); } void ADCTrajectoryContainer::SetTargetLaneSequence() { for (const auto& lane : adc_trajectory_.target_lane_id()) { if (!lane.id().empty()) { if (adc_target_lane_seq_.empty() || lane.id() != adc_target_lane_seq_.back()) { adc_target_lane_seq_.emplace_back(lane.id()); } } } adc_target_lane_ids_.clear(); adc_target_lane_ids_.insert(adc_target_lane_seq_.begin(), adc_target_lane_seq_.end()); } std::string ADCTrajectoryContainer::ToString( const std::unordered_set<std::string>& lane_ids) { std::string str_lane_sequence = ""; auto it = lane_ids.begin(); if (it != lane_ids.end()) { str_lane_sequence += (*it); ++it; } for (; it != lane_ids.end(); ++it) { str_lane_sequence += ("->" + *it); } return str_lane_sequence; } std::string ADCTrajectoryContainer::ToString( const std::vector<std::string>& lane_ids) { std::string str_lane_sequence = ""; auto it = lane_ids.begin(); if (it != lane_ids.end()) { str_lane_sequence += (*it); ++it; } for (; it != lane_ids.end(); ++it) { str_lane_sequence += ("->" + *it); } return str_lane_sequence; } bool ADCTrajectoryContainer::HasOverlap( const LaneSequence& lane_sequence) const { for (const auto& lane_segment : lane_sequence.lane_segment()) { std::string lane_id = lane_segment.lane_id(); if (adc_lane_ids_.find(lane_id) != adc_lane_ids_.end()) { return true; } } return false; } void ADCTrajectoryContainer::SetPosition(const Vec2d& position) { for (auto it = adc_lane_seq_.begin(); it != adc_lane_seq_.end(); ++it) { auto lane_info = PredictionMap::LaneById(*it); if (lane_info != nullptr && lane_info->IsOnLane(position)) { adc_lane_ids_.clear(); adc_lane_ids_.insert(it, adc_lane_seq_.end()); break; } } ADEBUG << "Generate an ADC lane ids [" << ToString(adc_lane_ids_) << "]."; } const std::vector<std::string>& ADCTrajectoryContainer::GetADCLaneIDSequence() const { return adc_lane_seq_; } const std::vector<std::string>& ADCTrajectoryContainer::GetADCTargetLaneIDSequence() const { return adc_target_lane_seq_; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/adc_trajectory/adc_trajectory_container.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 * @brief ADC trajectory container */ #pragma once #include <memory> #include <string> #include <unordered_set> #include <vector> #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/container.h" #include "modules/common_msgs/prediction_msgs/lane_graph.pb.h" namespace apollo { namespace prediction { class ADCTrajectoryContainer : public Container { public: /** * @brief Constructor */ ADCTrajectoryContainer(); /** * @brief Destructor */ virtual ~ADCTrajectoryContainer() = default; /** * @brief Insert a data message into the container * @param Data message to be inserted in protobuf */ void Insert(const ::google::protobuf::Message& message) override; /** * @brief Get the right-of-way status of ADC * @return The right-of-way status of ADC */ bool IsProtected() const; /** * @brief Check if a point is in the first junction of the adc trajectory * @param Point * @return True if the point is in the first junction of the adc trajectory */ bool IsPointInJunction(const common::PathPoint& point) const; /** * @brief Has overlap with ADC trajectory * @return True if a target lane sequence has overlap with ADC trajectory */ bool HasOverlap(const LaneSequence& lane_sequence) const; /** * @brief Set ADC position */ void SetPosition(const common::math::Vec2d& position); /** * @brief Get ADC junction * @return A pointer to ADC junction information */ std::shared_ptr<const hdmap::JunctionInfo> ADCJunction() const; /** * @brief Compute ADC's distance to junction * @return ADC's distance to junction */ double ADCDistanceToJunction() const; /** * @brief Get ADC planning trajectory * @return ADC planning trajectory */ const planning::ADCTrajectory& adc_trajectory() const; /** * @brief Determine if a lane ID is in the reference line * @return The lane ID to be investigated */ bool IsLaneIdInReferenceLine(const std::string& lane_id) const; bool IsLaneIdInTargetReferenceLine(const std::string& lane_id) const; const std::vector<std::string>& GetADCLaneIDSequence() const; const std::vector<std::string>& GetADCTargetLaneIDSequence() const; void SetJunction(const std::string& junction_id, const double distance); private: void SetJunctionPolygon(); void SetLaneSequence(); void SetTargetLaneSequence(); std::string ToString(const std::unordered_set<std::string>& lane_ids); std::string ToString(const std::vector<std::string>& lane_ids); private: planning::ADCTrajectory adc_trajectory_; common::math::Polygon2d adc_junction_polygon_; std::shared_ptr<const hdmap::JunctionInfo> adc_junction_info_ptr_; double s_dist_to_junction_; std::unordered_set<std::string> adc_lane_ids_; std::vector<std::string> adc_lane_seq_; std::unordered_set<std::string> adc_target_lane_ids_; std::vector<std::string> adc_target_lane_seq_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/adc_trajectory/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "adc_trajectory_container", srcs = ["adc_trajectory_container.cc"], hdrs = ["adc_trajectory_container.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/prediction/common:prediction_map", "//modules/prediction/container", "//modules/common_msgs/prediction_msgs:lane_graph_cc_proto", ], ) cc_test( name = "adc_trajectory_container_test", size = "small", srcs = ["adc_trajectory_container_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":adc_trajectory_container", "//modules/prediction/common:kml_map_based_test", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/adc_trajectory/adc_trajectory_container_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::math::Vec2d; using ::apollo::hdmap::Id; using ::apollo::planning::ADCTrajectory; class ADCTrajectoryTest : public KMLMapBasedTest { public: ADCTrajectoryTest() : container_() {} virtual void SetUp() { PathPoint path_point; path_point.set_x(-455.182); path_point.set_y(-160.608); path_point.set_s(50.1); TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_.add_trajectory_point()->CopyFrom(trajectory_point); Id lane_id; lane_id.set_id("l164"); trajectory_.add_lane_id()->CopyFrom(lane_id); } protected: ADCTrajectoryContainer container_; ADCTrajectory trajectory_; }; TEST_F(ADCTrajectoryTest, InsertionWithProtection) { trajectory_.set_right_of_way_status(ADCTrajectory::PROTECTED); container_.Insert(trajectory_); Vec2d vec; vec.set_x(-455.182); vec.set_y(-160.608); container_.SetPosition(vec); EXPECT_TRUE(container_.IsProtected()); PathPoint path_point; path_point.set_x(-438.537); path_point.set_y(-160.991); EXPECT_FALSE(container_.IsPointInJunction(path_point)); EXPECT_EQ(container_.ADCJunction(), nullptr); LaneSequence non_overlap_lane_sequence; LaneSegment lane_segment; lane_segment.set_lane_id("l22"); non_overlap_lane_sequence.add_lane_segment()->CopyFrom(lane_segment); EXPECT_FALSE(container_.HasOverlap(non_overlap_lane_sequence)); LaneSequence overlap_lane_sequence; lane_segment.set_lane_id("l164"); non_overlap_lane_sequence.add_lane_segment()->CopyFrom(lane_segment); EXPECT_TRUE(container_.HasOverlap(non_overlap_lane_sequence)); } TEST_F(ADCTrajectoryTest, InsertionWithoutProtection) { trajectory_.set_right_of_way_status(ADCTrajectory::UNPROTECTED); container_.Insert(trajectory_); EXPECT_FALSE(container_.IsProtected()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/pose/pose_container_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/prediction/container/pose/pose_container.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; class PoseContainerTest : public ::testing::Test { protected: void InitPose(LocalizationEstimate *localization) { localization->mutable_pose()->mutable_position()->set_x(position_[0]); localization->mutable_pose()->mutable_position()->set_y(position_[1]); localization->mutable_pose()->mutable_linear_velocity()->set_x( velocity_[0]); localization->mutable_pose()->mutable_linear_velocity()->set_y( velocity_[1]); localization->mutable_header()->set_timestamp_sec(timestamp_); } protected: PoseContainer pose_; private: std::array<double, 2> position_{{1.0, 1.5}}; std::array<double, 2> velocity_{{2.0, 2.5}}; double timestamp_ = 3.0; }; TEST_F(PoseContainerTest, Insertion) { LocalizationEstimate localization; InitPose(&localization); pose_.Insert(localization); EXPECT_DOUBLE_EQ(pose_.GetTimestamp(), 3.0); const PerceptionObstacle *obstacle = pose_.ToPerceptionObstacle(); EXPECT_NE(obstacle, nullptr); EXPECT_TRUE(obstacle->has_position()); EXPECT_TRUE(obstacle->has_velocity()); EXPECT_DOUBLE_EQ(obstacle->position().x(), 1.0); EXPECT_DOUBLE_EQ(obstacle->position().y(), 1.5); EXPECT_DOUBLE_EQ(obstacle->velocity().x(), 2.0); EXPECT_DOUBLE_EQ(obstacle->velocity().y(), 2.5); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/pose/pose_container.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/prediction/container/pose/pose_container.h" #include "cyber/common/log.h" #include "modules/common/math/quaternion.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using Point = apollo::common::Point3D; void PoseContainer::Insert(const ::google::protobuf::Message& message) { localization::LocalizationEstimate localization; localization.CopyFrom(dynamic_cast<const LocalizationEstimate&>(message)); Update(localization); } void PoseContainer::Update( const localization::LocalizationEstimate& localization) { if (!localization.has_header() || !localization.header().has_timestamp_sec()) { AERROR << "Localization message has no timestamp [" << localization.ShortDebugString() << "]."; return; } else if (!localization.has_pose()) { AERROR << "Localization message has no pose [" << localization.ShortDebugString() << "]."; return; } else if (!localization.pose().has_position() || !localization.pose().has_linear_velocity()) { AERROR << "Localization message has no position or linear velocity [" << localization.ShortDebugString() << "]."; return; } if (obstacle_ptr_.get() == nullptr) { obstacle_ptr_.reset(new PerceptionObstacle()); } obstacle_ptr_->Clear(); obstacle_ptr_->set_id(FLAGS_ego_vehicle_id); Point position; position.set_x(localization.pose().position().x()); position.set_y(localization.pose().position().y()); position.set_z(localization.pose().position().z()); obstacle_ptr_->mutable_position()->CopyFrom(position); double theta = 0.0; if (localization.pose().has_orientation() && localization.pose().orientation().has_qx() && localization.pose().orientation().has_qy() && localization.pose().orientation().has_qz() && localization.pose().orientation().has_qw()) { double qw = localization.pose().orientation().qw(); double qx = localization.pose().orientation().qx(); double qy = localization.pose().orientation().qy(); double qz = localization.pose().orientation().qz(); theta = common::math::QuaternionToHeading(qw, qx, qy, qz); } obstacle_ptr_->set_theta(theta); Point velocity; velocity.set_x(localization.pose().linear_velocity().x()); velocity.set_y(localization.pose().linear_velocity().y()); velocity.set_z(localization.pose().linear_velocity().z()); obstacle_ptr_->mutable_velocity()->CopyFrom(velocity); obstacle_ptr_->set_type(type_); obstacle_ptr_->set_timestamp(localization.header().timestamp_sec()); ADEBUG << "ADC obstacle [" << obstacle_ptr_->ShortDebugString() << "]."; } double PoseContainer::GetTimestamp() { if (obstacle_ptr_ != nullptr) { return obstacle_ptr_->timestamp(); } else { return 0.0; } } const PerceptionObstacle* PoseContainer::ToPerceptionObstacle() { return obstacle_ptr_.get(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/pose/pose_container.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 * @brief Obstacles container */ #pragma once #include <memory> #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/prediction/container/container.h" namespace apollo { namespace prediction { class PoseContainer : public Container { public: /** * @brief Constructor */ PoseContainer() = default; /** * @brief Destructor */ virtual ~PoseContainer() = default; /** * @brief Insert a data message into the container * @param Data message to be inserted in protobuf */ void Insert(const ::google::protobuf::Message& message) override; /** * @brief Transform pose to a perception obstacle. * @return A pointer to a perception obstacle. */ const perception::PerceptionObstacle* ToPerceptionObstacle(); /** * @brief Get timestamp */ double GetTimestamp(); private: /** * @brief Update pose * @param Received localization message */ void Update(const localization::LocalizationEstimate& localization); public: static const perception::PerceptionObstacle::Type type_ = perception::PerceptionObstacle::VEHICLE; private: std::unique_ptr<perception::PerceptionObstacle> obstacle_ptr_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/pose/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "pose_container", srcs = ["pose_container.cc"], hdrs = ["pose_container.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/common/math", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/prediction/common:prediction_gflags", "//modules/prediction/container", ], ) cc_test( name = "pose_container_test", size = "small", srcs = ["pose_container_test.cc"], deps = [ "//modules/prediction/container/pose:pose_container", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/storytelling/storytelling_container.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief story telling container */ #pragma once #include <memory> #include <string> #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/container.h" #include "modules/common_msgs/storytelling_msgs/story.pb.h" namespace apollo { namespace prediction { class StoryTellingContainer : public Container { public: /** * @brief Constructor */ StoryTellingContainer() = default; /** * @brief Destructor */ virtual ~StoryTellingContainer() = default; /** * @brief Insert a data message into the container * @param Data message to be inserted in protobuf */ void Insert(const ::google::protobuf::Message& message) override; /** * @brief Get ADC junction * @return A pointer to ADC junction information */ std::shared_ptr<const hdmap::JunctionInfo> ADCJunction() const; /** * @brief Get ADC junction id * @return A reference of ADC_junction_id */ const std::string& ADCJunctionId() const; /** * @brief Compute ADC's distance to junction * @return ADC's distance to junction */ double ADCDistanceToJunction() const; private: apollo::storytelling::CloseToJunction close_to_junction_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/storytelling/storytelling_container.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/prediction/container/storytelling/storytelling_container.h" namespace apollo { namespace prediction { using apollo::storytelling::Stories; void StoryTellingContainer::Insert(const ::google::protobuf::Message& message) { Stories story_message = dynamic_cast<const Stories&>(message); close_to_junction_.CopyFrom(story_message.close_to_junction()); } std::shared_ptr<const hdmap::JunctionInfo> StoryTellingContainer::ADCJunction() const { std::string adc_junction_id = close_to_junction_.id(); return PredictionMap::JunctionById(adc_junction_id); } const std::string& StoryTellingContainer::ADCJunctionId() const { return close_to_junction_.id(); } double StoryTellingContainer::ADCDistanceToJunction() const { return close_to_junction_.distance(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/container
apollo_public_repos/apollo/modules/prediction/container/storytelling/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "storytelling_container", srcs = ["storytelling_container.cc"], hdrs = ["storytelling_container.h"], copts = [ "-DMODULE_NAME=\\\"prediction_container\\\"", ], deps = [ "//modules/prediction/common:prediction_map", "//modules/prediction/container", "//modules/common_msgs/storytelling_msgs:story_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_util.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *implied. See the License for the specific language governing *permissions and limitations under the License. *****************************************************************************/ #pragma once #include <limits> #include <utility> #include <vector> #include "Eigen/Dense" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { namespace math_util { /** * @brief Normalize the value by specified mean and standard deviation. * @param value The value to be normalized. * @param mean The mean used for normalization. * @param std The standard deviation used for normalization. * @return The normalized value. */ double Normalize(const double value, const double mean, const double std); /** * @brief RELU function used in neural networks as an activation function. * @param value The input. * @return The output of RELU function. */ double Relu(const double value); /** * @brief Softmax function used in neural networks as an activation function. * @param vector The input. * @return The output of Softmax function. */ std::vector<double> Softmax(const std::vector<double>& value, bool use_exp = true); /** * @brief Solve quadratic equation. * @param coefficients The coefficients of quadratic equation. * @param roots Two roots of the equation if any. * @return An integer indicating the success of solving equation. */ int SolveQuadraticEquation(const std::vector<double>& coefficients, std::pair<double, double>* roots); /** * @brief Evaluate quintic polynomial. * @param coefficients of the quintic polynomial, lower to higher. * @param parameter of the quintic polynomial. * @return order of derivative to evaluate. */ double EvaluateQuinticPolynomial(const std::array<double, 6>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v); /** * @brief Evaluate quartic polynomial. * @param coefficients of the quartic polynomial, lower to higher. * @param parameter of the quartic polynomial. * @return order of derivative to evaluate. */ double EvaluateQuarticPolynomial(const std::array<double, 5>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v); /** * @brief Evaluate cubic polynomial. * @param coefficients of the cubic polynomial, lower to higher. * @param parameter of the cubic polynomial. * @param end_t ending time for extrapolation. * @param end_v ending velocity for extrapolation. * @return order of derivative to evaluate. */ double EvaluateCubicPolynomial( const std::array<double, 4>& coefs, const double t, const uint32_t order, const double end_t = std::numeric_limits<double>::infinity(), const double end_v = 0.0); template <std::size_t N> std::array<double, 2 * N - 2> ComputePolynomial( const std::array<double, N - 1>& start_state, const std::array<double, N - 1>& end_state, const double param); template <> inline std::array<double, 4> ComputePolynomial<3>( const std::array<double, 2>& start_state, const std::array<double, 2>& end_state, const double param) { std::array<double, 4> coefs; coefs[0] = start_state[0]; coefs[1] = start_state[1]; auto m0 = end_state[0] - start_state[0] - start_state[1] * param; auto m1 = end_state[1] - start_state[1]; auto param_p3 = param * param * param; coefs[3] = (m1 * param - 2.0 * m0) / param_p3; coefs[2] = (m1 - 3.0 * coefs[3] * param * param) / param * 0.5; return coefs; } double GetSByConstantAcceleration(const double v0, const double acceleration, const double t); } // namespace math_util namespace predictor_util { /** * @brief Translate a point. * @param translate_x The translation along x-axis. * @param translate_y The translation along y-axis. * @param point The point to be translated. */ void TranslatePoint(const double translate_x, const double translate_y, common::TrajectoryPoint* point); /** * @brief Generate a set of free move trajectory points * @param state matrix * @param transition matrix * @param heading * @param start time * @param total number of generated trajectory points required * @param trajectory point interval period * @param generated trajectory points */ void GenerateFreeMoveTrajectoryPoints( Eigen::Matrix<double, 6, 1>* state, const Eigen::Matrix<double, 6, 6>& transition, double theta, const double start_time, const std::size_t num, const double period, std::vector<common::TrajectoryPoint>* points); /** * @brief Adjust a speed value according to a curvature. If the input speed * is okay on the input curvature, return the original speed, otherwise, * adjust the speed. * @param speed The original speed value. * @param curvature The curvature value. * @return The adjusted speed according to the curvature. */ double AdjustSpeedByCurvature(const double speed, const double curvature); } // namespace predictor_util } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/junction_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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <unordered_map> #include <vector> #include "modules/prediction/common/prediction_map.h" #include "modules/common_msgs/prediction_msgs/feature.pb.h" namespace apollo { namespace prediction { class JunctionAnalyzer { public: /** * @brief Initialize by junction ID, if junction id differs from prev cycle * @param junction ID */ void Init(const std::string& junction_id); /** * @brief Clear all stored data */ void Clear(); /** * @brief Get junction ID * @return Junction ID */ const std::string& GetJunctionId(); /** * @brief Compute junction range * @return Junction range */ double ComputeJunctionRange(); /** * @brief Get junction feature starting from start_lane_id * @param start lane ID * @return junction */ const JunctionFeature& GetJunctionFeature(const std::string& start_lane_id); /** * @brief Get junction feature starting from start_lane_ids * @param start lane IDs * @return junction */ JunctionFeature GetJunctionFeature( const std::vector<std::string>& start_lane_ids); private: /** * @brief Set all junction exits in the hashtable junction_exits_ */ void SetAllJunctionExits(); /** * @brief Get all filtered junction exits associated to start lane ID * @param start lane ID * @return Filtered junction exits */ std::vector<JunctionExit> GetJunctionExits(const std::string& start_lane_id); /** * @brief Determine if a lane with lane_id is an exit lane of this junction * @param lane ID * @return If a lane with lane_id is an exit lane of this junction */ bool IsExitLane(const std::string& lane_id); private: // junction_info pointer associated to the input junction_id std::shared_ptr<const apollo::hdmap::JunctionInfo> junction_info_ptr_; // Hashtable: exit_lane_id -> junction_exit std::unordered_map<std::string, JunctionExit> junction_exits_; // Hashtable: start_lane_id -> junction_feature std::unordered_map<std::string, JunctionFeature> junction_features_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_util.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/prediction/common/prediction_util.h" #include <algorithm> #include "modules/common/math/linear_interpolation.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { namespace math_util { double Normalize(const double value, const double mean, const double std) { const double eps = 1e-10; return (value - mean) / (std + eps); } double Relu(const double value) { return (value > 0.0) ? value : 0.0; } std::vector<double> Softmax(const std::vector<double>& value, bool use_exp) { std::vector<double> result; double sum = 0.0; for (std::size_t i = 0; i < value.size(); ++i) { double exp_value = std::max(0.001, value[i]); if (use_exp) { exp_value = std::exp(value[i]); } sum += exp_value; result.push_back(exp_value); } for (std::size_t i = 0; i < value.size(); ++i) { result[i] = result[i] / sum; } return result; } int SolveQuadraticEquation(const std::vector<double>& coefficients, std::pair<double, double>* roots) { if (coefficients.size() != 3) { return -1; } const double a = coefficients[0]; const double b = coefficients[1]; const double c = coefficients[2]; if (std::fabs(a) <= std::numeric_limits<double>::epsilon()) { return -1; } double delta = b * b - 4.0 * a * c; if (delta < 0.0) { return -1; } double sqrt_delta = std::sqrt(delta); roots->first = (-b + sqrt_delta) * 0.5 / a; roots->second = (-b - sqrt_delta) * 0.5 / a; return 0; } double EvaluateQuinticPolynomial(const std::array<double, 6>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = ((((coeffs[5] * end_t + coeffs[4]) * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + end_v * (t - end_t); } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((((coeffs[5] * t + coeffs[4]) * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return (((5.0 * coeffs[5] * t + 4.0 * coeffs[4]) * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (((20.0 * coeffs[5] * t + 12.0 * coeffs[4]) * t) + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return (60.0 * coeffs[5] * t + 24.0 * coeffs[4]) * t + 6.0 * coeffs[3]; } case 4: { return 120.0 * coeffs[5] * t + 24.0 * coeffs[4]; } case 5: { return 120.0 * coeffs[5]; } default: return 0.0; } } double EvaluateQuarticPolynomial(const std::array<double, 5>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = (((coeffs[4] * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return (((coeffs[4] * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return ((4.0 * coeffs[4] * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (12.0 * coeffs[4] * t + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return 24.0 * coeffs[4] * t + 6.0 * coeffs[3]; } case 4: { return 24.0 * coeffs[4]; } default: return 0.0; } } double EvaluateCubicPolynomial(const std::array<double, 4>& coefs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t > end_t) { switch (order) { case 0: { double end_value = ((coefs[3] * end_t + coefs[2]) * end_t + coefs[1]) * end_t + coefs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((coefs[3] * t + coefs[2]) * t + coefs[1]) * t + coefs[0]; } case 1: { return (3.0 * coefs[3] * t + 2.0 * coefs[2]) * t + coefs[1]; } case 2: { return 6.0 * coefs[3] * t + 2.0 * coefs[2]; } case 3: { return 6.0 * coefs[3]; } default: return 0.0; } } double GetSByConstantAcceleration(const double v0, const double acceleration, const double t) { if (acceleration > -FLAGS_double_precision) { return v0 * t + 0.5 * acceleration * t * t; } double t_stop = v0 / (-acceleration); double t_actual = std::min(t, t_stop); return v0 * t_actual + 0.5 * acceleration * t_actual * t_actual; } } // namespace math_util namespace predictor_util { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; void TranslatePoint(const double translate_x, const double translate_y, TrajectoryPoint* point) { if (point == nullptr || !point->has_path_point()) { AERROR << "Point is nullptr or has NO path_point."; return; } const double original_x = point->path_point().x(); const double original_y = point->path_point().y(); point->mutable_path_point()->set_x(original_x + translate_x); point->mutable_path_point()->set_y(original_y + translate_y); } void GenerateFreeMoveTrajectoryPoints( Eigen::Matrix<double, 6, 1>* state, const Eigen::Matrix<double, 6, 6>& transition, double theta, const double start_time, const std::size_t num, const double period, std::vector<TrajectoryPoint>* points) { double x = (*state)(0, 0); double y = (*state)(1, 0); double v_x = (*state)(2, 0); double v_y = (*state)(3, 0); double acc_x = (*state)(4, 0); double acc_y = (*state)(5, 0); for (std::size_t i = 0; i < num; ++i) { double speed = std::hypot(v_x, v_y); double acc = 0.0; if (speed <= std::numeric_limits<double>::epsilon()) { speed = 0.0; v_x = 0.0; v_y = 0.0; acc_x = 0.0; acc_y = 0.0; acc = 0.0; } else { speed = std::fmin(speed, FLAGS_vehicle_max_speed); } // update theta and acc if (speed > std::numeric_limits<double>::epsilon()) { if (points->size() > 0) { TrajectoryPoint& prev_trajectory_point = points->back(); PathPoint* prev_path_point = prev_trajectory_point.mutable_path_point(); theta = std::atan2(y - prev_path_point->y(), x - prev_path_point->x()); prev_path_point->set_theta(theta); acc = (speed - prev_trajectory_point.v()) / period; prev_trajectory_point.set_a(acc); } } else { if (points->size() > 0) { theta = points->back().path_point().theta(); } } // update state (*state)(2, 0) = v_x; (*state)(3, 0) = v_y; (*state)(4, 0) = acc_x; (*state)(5, 0) = acc_y; // obtain position x = (*state)(0, 0); y = (*state)(1, 0); // Generate trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(x); path_point.set_y(y); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(speed); trajectory_point.set_a(acc); trajectory_point.set_relative_time(start_time + static_cast<double>(i) * period); points->emplace_back(std::move(trajectory_point)); // Update position, velocity and acceleration (*state) = transition * (*state); x = (*state)(0, 0); y = (*state)(1, 0); v_x = (*state)(2, 0); v_y = (*state)(3, 0); acc_x = (*state)(4, 0); acc_y = (*state)(5, 0); } } double AdjustSpeedByCurvature(const double speed, const double curvature) { if (std::abs(curvature) < FLAGS_turning_curvature_lower_bound) { return speed; } if (std::abs(curvature) > FLAGS_turning_curvature_upper_bound) { return FLAGS_speed_at_upper_curvature; } return apollo::common::math::lerp( FLAGS_speed_at_lower_curvature, FLAGS_turning_curvature_lower_bound, FLAGS_speed_at_upper_curvature, FLAGS_turning_curvature_upper_bound, curvature); } } // namespace predictor_util } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/semantic_map.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/prediction/common/semantic_map.h" #include <utility> #include <vector> #include "cyber/common/file.h" #include "cyber/common/log.h" #include "cyber/task/task.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/util/point_factory.h" #include "modules/common/util/string_util.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { namespace { bool ValidFeatureHistory(const ObstacleHistory& obstacle_history, const double curr_base_x, const double curr_base_y) { if (obstacle_history.feature_size() == 0) { return false; } double center_x = curr_base_x + FLAGS_base_image_half_range; double center_y = curr_base_y + FLAGS_base_image_half_range; const Feature& feature = obstacle_history.feature(0); double diff_x = feature.position().x() - center_x; double diff_y = feature.position().y() - center_y; double distance = std::hypot(diff_x, diff_y); return distance < FLAGS_caution_distance_threshold; } } // namespace SemanticMap::SemanticMap() {} void SemanticMap::Init() { curr_img_ = cv::Mat(2000, 2000, CV_8UC3, cv::Scalar(0, 0, 0)); obstacle_id_history_map_.clear(); } void SemanticMap::RunCurrFrame( const std::unordered_map<int, ObstacleHistory>& obstacle_id_history_map) { if (obstacle_id_history_map.find(FLAGS_ego_vehicle_id) == obstacle_id_history_map.end()) { return; } ego_feature_ = obstacle_id_history_map.at(FLAGS_ego_vehicle_id).feature(0); if (!FLAGS_enable_async_draw_base_image) { double x = ego_feature_.position().x(); double y = ego_feature_.position().y(); curr_base_x_ = x - FLAGS_base_image_half_range; curr_base_y_ = y - FLAGS_base_image_half_range; DrawBaseMap(x, y, curr_base_x_, curr_base_y_); base_img_.copyTo(curr_img_); } else { base_img_.copyTo(curr_img_); curr_base_x_ = base_x_; curr_base_y_ = base_y_; task_future_ = cyber::Async(&SemanticMap::DrawBaseMapThread, this); // This is only for the first frame without base image yet if (!started_drawing_) { started_drawing_ = true; return; } } // Draw ADC trajectory if (FLAGS_enable_draw_adc_trajectory) { DrawADCTrajectory(cv::Scalar(0, 255, 255), curr_base_x_, curr_base_y_, &curr_img_); } // Draw all obstacles_history for (const auto obstacle_id_history_pair : obstacle_id_history_map) { DrawHistory(obstacle_id_history_pair.second, cv::Scalar(0, 255, 255), curr_base_x_, curr_base_y_, &curr_img_); } obstacle_id_history_map_ = obstacle_id_history_map; // Crop ego_vehicle for demo if (FLAGS_img_show_semantic_map) { cv::Mat output_img; if (GetMapById(FLAGS_ego_vehicle_id, &output_img)) { cv::namedWindow("Demo window", cv::WINDOW_NORMAL); cv::imshow("Demo window", output_img); cv::waitKey(); } } } void SemanticMap::DrawBaseMap(const double x, const double y, const double base_x, const double base_y) { base_img_ = cv::Mat(2000, 2000, CV_8UC3, cv::Scalar(0, 0, 0)); common::PointENU center_point = common::util::PointFactory::ToPointENU(x, y); DrawRoads(center_point, base_x, base_y); DrawJunctions(center_point, base_x, base_y); DrawCrosswalks(center_point, base_x, base_y); DrawLanes(center_point, base_x, base_y); } void SemanticMap::DrawBaseMapThread() { std::lock_guard<std::mutex> lock(draw_base_map_thread_mutex_); double x = ego_feature_.position().x(); double y = ego_feature_.position().y(); base_x_ = x - FLAGS_base_image_half_range; base_y_ = y - FLAGS_base_image_half_range; DrawBaseMap(x, y, base_x_, base_y_); } void SemanticMap::DrawRoads(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color) { std::vector<apollo::hdmap::RoadInfoConstPtr> roads; apollo::hdmap::HDMapUtil::BaseMap().GetRoads(center_point, 141.4, &roads); for (const auto& road : roads) { for (const auto& section : road->road().section()) { std::vector<cv::Point> polygon; for (const auto& edge : section.boundary().outer_polygon().edge()) { if (edge.type() == 2) { // left edge for (const auto& segment : edge.curve().segment()) { for (const auto& point : segment.line_segment().point()) { polygon.push_back(std::move( GetTransPoint(point.x(), point.y(), base_x, base_y))); } } } else if (edge.type() == 3) { // right edge for (const auto& segment : edge.curve().segment()) { for (const auto& point : segment.line_segment().point()) { polygon.insert(polygon.begin(), std::move(GetTransPoint(point.x(), point.y(), base_x, base_y))); } } } } cv::fillPoly(base_img_, std::vector<std::vector<cv::Point>>({std::move(polygon)}), color); } } } void SemanticMap::DrawJunctions(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color) { std::vector<apollo::hdmap::JunctionInfoConstPtr> junctions; apollo::hdmap::HDMapUtil::BaseMap().GetJunctions(center_point, 141.4, &junctions); for (const auto& junction : junctions) { std::vector<cv::Point> polygon; for (const auto& point : junction->junction().polygon().point()) { polygon.push_back( std::move(GetTransPoint(point.x(), point.y(), base_x, base_y))); } cv::fillPoly(base_img_, std::vector<std::vector<cv::Point>>({std::move(polygon)}), color); } } void SemanticMap::DrawCrosswalks(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color) { std::vector<apollo::hdmap::CrosswalkInfoConstPtr> crosswalks; apollo::hdmap::HDMapUtil::BaseMap().GetCrosswalks(center_point, 141.4, &crosswalks); for (const auto& crosswalk : crosswalks) { std::vector<cv::Point> polygon; for (const auto& point : crosswalk->crosswalk().polygon().point()) { polygon.push_back( std::move(GetTransPoint(point.x(), point.y(), base_x, base_y))); } cv::fillPoly(base_img_, std::vector<std::vector<cv::Point>>({std::move(polygon)}), color); } } void SemanticMap::DrawLanes(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color) { std::vector<apollo::hdmap::LaneInfoConstPtr> lanes; apollo::hdmap::HDMapUtil::BaseMap().GetLanes(center_point, 141.4, &lanes); for (const auto& lane : lanes) { // Draw lane_central first for (const auto& segment : lane->lane().central_curve().segment()) { for (int i = 0; i < segment.line_segment().point_size() - 1; ++i) { const auto& p0 = GetTransPoint(segment.line_segment().point(i).x(), segment.line_segment().point(i).y(), base_x, base_y); const auto& p1 = GetTransPoint(segment.line_segment().point(i + 1).x(), segment.line_segment().point(i + 1).y(), base_x, base_y); double theta = atan2(segment.line_segment().point(i + 1).y() - segment.line_segment().point(i).y(), segment.line_segment().point(i + 1).x() - segment.line_segment().point(i).x()); double H = theta >= 0 ? theta / (2 * M_PI) : theta / (2 * M_PI) + 1; // // Original cv::cvtColor() is 4 times slower than HSVtoRGB() // cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(H * 360.0, 1.0, 1.0)); // cv::Mat rgb; // cv::cvtColor(hsv, rgb, cv::COLOR_HSV2RGB); // cv::Scalar c = // cv::Scalar(rgb.at<float>(0, 0) * 255, rgb.at<float>(0, 1) * 255, // rgb.at<float>(0, 2) * 255); cv::line(base_img_, p0, p1, HSVtoRGB(H), 4); } } // Not drawing boundary for virtual city_driving lane if (lane->lane().type() == 2 && lane->lane().left_boundary().virtual_() && lane->lane().right_boundary().virtual_()) { continue; } // Draw lane's left_boundary for (const auto& segment : lane->lane().left_boundary().curve().segment()) { for (int i = 0; i < segment.line_segment().point_size() - 1; ++i) { const auto& p0 = GetTransPoint(segment.line_segment().point(i).x(), segment.line_segment().point(i).y(), base_x, base_y); const auto& p1 = GetTransPoint(segment.line_segment().point(i + 1).x(), segment.line_segment().point(i + 1).y(), base_x, base_y); cv::line(base_img_, p0, p1, color, 2); } } // Draw lane's right_boundary for (const auto& segment : lane->lane().right_boundary().curve().segment()) { for (int i = 0; i < segment.line_segment().point_size() - 1; ++i) { const auto& p0 = GetTransPoint(segment.line_segment().point(i).x(), segment.line_segment().point(i).y(), base_x, base_y); const auto& p1 = GetTransPoint(segment.line_segment().point(i + 1).x(), segment.line_segment().point(i + 1).y(), base_x, base_y); cv::line(base_img_, p0, p1, color, 2); } } } } cv::Scalar SemanticMap::HSVtoRGB(double H, double S, double V) { int I = static_cast<int>(floor(H * 6.0)); double F = H * 6.0 - floor(H * 6.0); double M = V * (1.0 - S); double N = V * (1.0 - S * F); double K = V * (1.0 - S * (1.0 - F)); switch (I) { case 0: return cv::Scalar(V, K, M) * 255.0; case 1: return cv::Scalar(N, V, M) * 255.0; case 2: return cv::Scalar(M, V, K) * 255.0; case 3: return cv::Scalar(M, N, V) * 255.0; case 4: return cv::Scalar(K, M, V) * 255.0; default: return cv::Scalar(V, M, N) * 255.0; } } void SemanticMap::DrawRect(const Feature& feature, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img) { double obs_l = feature.length(); double obs_w = feature.width(); double obs_x = feature.position().x(); double obs_y = feature.position().y(); double theta = feature.theta(); std::vector<cv::Point> polygon; // point 1 (head-right point) polygon.push_back(std::move(GetTransPoint( obs_x + (cos(theta) * obs_l - sin(theta) * obs_w) / 2, obs_y + (sin(theta) * obs_l + cos(theta) * obs_w) / 2, base_x, base_y))); // point 2 (head-left point) polygon.push_back(std::move(GetTransPoint( obs_x + (cos(theta) * -obs_l - sin(theta) * obs_w) / 2, obs_y + (sin(theta) * -obs_l + cos(theta) * obs_w) / 2, base_x, base_y))); // point 3 (back-left point) polygon.push_back(std::move( GetTransPoint(obs_x + (cos(theta) * -obs_l - sin(theta) * -obs_w) / 2, obs_y + (sin(theta) * -obs_l + cos(theta) * -obs_w) / 2, base_x, base_y))); // point 4 (back-right point) polygon.push_back(std::move(GetTransPoint( obs_x + (cos(theta) * obs_l - sin(theta) * -obs_w) / 2, obs_y + (sin(theta) * obs_l + cos(theta) * -obs_w) / 2, base_x, base_y))); cv::fillPoly(*img, std::vector<std::vector<cv::Point>>({std::move(polygon)}), color); } void SemanticMap::DrawPoly(const Feature& feature, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img) { std::vector<cv::Point> polygon; for (auto& polygon_point : feature.polygon_point()) { polygon.push_back(std::move( GetTransPoint(polygon_point.x(), polygon_point.y(), base_x, base_y))); } cv::fillPoly(*img, std::vector<std::vector<cv::Point>>({std::move(polygon)}), color); } void SemanticMap::DrawHistory(const ObstacleHistory& history, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img) { for (int i = history.feature_size() - 1; i >= 0; --i) { const Feature& feature = history.feature(i); double time_decay = 1.0 - ego_feature_.timestamp() + feature.timestamp(); cv::Scalar decay_color = color * time_decay; if (feature.id() == FLAGS_ego_vehicle_id) { DrawRect(feature, decay_color, base_x, base_y, img); } else { if (feature.polygon_point_size() == 0) { AERROR << "No polygon points in feature, please check!"; continue; } DrawPoly(feature, decay_color, base_x, base_y, img); } } } void SemanticMap::DrawADCTrajectory(const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img) { size_t traj_num = ego_feature_.adc_trajectory_point().size(); for (size_t i = 0; i < traj_num; ++i) { double time_decay = ego_feature_.adc_trajectory_point(i).relative_time() - ego_feature_.adc_trajectory_point(0).relative_time(); cv::Scalar decay_color = color * time_decay; DrawPoly(ego_feature_, decay_color, base_x, base_y, img); } } cv::Mat SemanticMap::CropArea(const cv::Mat& input_img, const cv::Point2i& center_point, const double heading) { cv::Mat rotation_mat = cv::getRotationMatrix2D(center_point, 90.0 - heading * 180.0 / M_PI, 1.0); cv::Mat rotated_mat; cv::warpAffine(input_img, rotated_mat, rotation_mat, input_img.size()); cv::Rect rect(center_point.x - 200, center_point.y - 300, 400, 400); cv::Mat output_img; cv::resize(rotated_mat(rect), output_img, cv::Size(224, 224)); return output_img; } cv::Mat SemanticMap::CropByHistory(const ObstacleHistory& history, const cv::Scalar& color, const double base_x, const double base_y) { cv::Mat feature_map = curr_img_.clone(); DrawHistory(history, color, base_x, base_y, &feature_map); const Feature& curr_feature = history.feature(0); const cv::Point2i& center_point = GetTransPoint( curr_feature.position().x(), curr_feature.position().y(), base_x, base_y); return CropArea(feature_map, center_point, curr_feature.theta()); } bool SemanticMap::GetMapById(const int obstacle_id, cv::Mat* feature_map) { if (obstacle_id_history_map_.find(obstacle_id) == obstacle_id_history_map_.end()) { return false; } const auto& obstacle_history = obstacle_id_history_map_[obstacle_id]; if (!ValidFeatureHistory(obstacle_history, curr_base_x_, curr_base_y_)) { return false; } cv::Mat output_img = CropByHistory(obstacle_id_history_map_[obstacle_id], cv::Scalar(0, 0, 255), curr_base_x_, curr_base_y_); output_img.copyTo(*feature_map); return true; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_gflags.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/prediction_gflags.h" #include <cmath> DEFINE_double(double_precision, 1e-6, "precision of double"); // prediction trajectory and dynamic model DEFINE_double(prediction_trajectory_time_length, 8.0, "Time length of predicted trajectory (in seconds)"); DEFINE_double(prediction_trajectory_time_resolution, 0.1, "Time resolution of predicted trajectory (in seconds"); DEFINE_double(min_prediction_trajectory_spatial_length, 100.0, "Minimal spatial length of predicted trajectory"); DEFINE_bool(enable_trajectory_validation_check, false, "If check the validity of prediction trajectory."); DEFINE_bool(enable_tracking_adaptation, false, "If enable prediction tracking adaptation"); DEFINE_double(vehicle_max_linear_acc, 4.0, "Upper bound of vehicle linear acceleration"); DEFINE_double(vehicle_min_linear_acc, -4.0, "Lower bound of vehicle linear deceleration"); DEFINE_double(vehicle_max_speed, 35.0, "Max speed of vehicle"); // Tracking Adaptation DEFINE_double(max_tracking_time, 0.5, "Max tracking time for disappear obstacles"); DEFINE_double(max_tracking_dist, 3.0, "Max tracking distance for disappear obstacles"); // Map DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane"); DEFINE_double(lane_search_radius_in_junction, 15.0, "Search radius for a candidate lane"); DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction"); DEFINE_double(pedestrian_nearby_lane_search_radius, 5.0, "Radius to determine if pedestrian-like obstacle is near lane."); DEFINE_int32(road_graph_max_search_horizon, 20, "Maximal search depth for building road graph"); DEFINE_double(surrounding_lane_search_radius, 3.0, "Search radius for surrounding lanes."); // Semantic Map DEFINE_double(base_image_half_range, 100.0, "The half range of base image."); DEFINE_bool(enable_draw_adc_trajectory, true, "If draw adc trajectory in semantic map"); DEFINE_bool(img_show_semantic_map, false, "If show the image of semantic map."); // Scenario DEFINE_double(junction_distance_threshold, 10.0, "Distance threshold " "to junction to consider as junction scenario"); DEFINE_bool(enable_all_junction, false, "If consider all junction with junction_mlp_model."); DEFINE_bool(enable_all_pedestrian_caution_in_front, false, "If true, then all pedestrian in front of ADC are marked caution."); DEFINE_bool(enable_rank_caution_obstacles, true, "Rank the caution-level obstacles."); DEFINE_bool(enable_rank_interactive_obstacles, true, "Rank the interactive obstacles."); DEFINE_int32(caution_obs_max_nums, 6, "The max number of caution-level obstacles"); DEFINE_double(caution_distance_threshold, 60.0, "Distance threshold for caution obstacles"); DEFINE_double(caution_search_distance_ahead, 50.0, "The distance ahead to search caution-level obstacles"); DEFINE_double(caution_search_distance_backward, 50.0, "The distance backward to search caution-level obstacles"); DEFINE_double(caution_search_distance_backward_for_merge, 60.0, "The distance backward to search caution-lebel obstacles " "in the case of merging"); DEFINE_double(caution_search_distance_backward_for_overlap, 30.0, "The distance backward to search caution-lebel obstacles " "in the case of overlap"); DEFINE_double(caution_pedestrian_approach_time, 3.0, "The time for a pedestrian to approach adc trajectory"); DEFINE_int32(interactive_obs_max_nums, 6, "The max number of interactive obstacles"); DEFINE_double(interaction_distance_threshold, 60.0, "Distance threshold for interactive obstacles"); DEFINE_double(interaction_search_distance_ahead, 50.0, "The distance ahead to search interactive obstacles"); DEFINE_double(interaction_search_distance_backward, 50.0, "The distance backward to search interactive obstacles"); DEFINE_double(interaction_search_distance_backward_for_merge, 60.0, "The distance backward to search interactive obstacles " "in the case of merging"); DEFINE_double(interaction_search_distance_backward_for_overlap, 30.0, "The distance backward to search interactive obstacles " "in the case of overlap"); // Obstacle features DEFINE_int32(ego_vehicle_id, -1, "The obstacle ID of the ego vehicle."); DEFINE_double(scan_length, 80.0, "The length of the obstacles scan area"); DEFINE_double(scan_width, 12.0, "The width of the obstacles scan area"); DEFINE_double(back_dist_ignore_ped, -2.0, "Backward distance to ignore pedestrians."); DEFINE_uint64(cruise_historical_frame_length, 5, "The number of historical frames of the obstacle" "that the cruise model will look at."); DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking"); DEFINE_double(max_angle_diff_to_adjust_velocity, M_PI / 6.0, "The maximal angle diff to adjust velocity heading."); DEFINE_double(q_var, 0.01, "Processing noise covariance"); DEFINE_double(r_var, 0.25, "Measurement noise covariance"); DEFINE_double(p_var, 0.1, "Error covariance"); DEFINE_double(go_approach_rate, 0.995, "The rate to approach to the reference line of going straight"); DEFINE_double(cutin_approach_rate, 0.95, "The rate to approach to the reference line of cutin"); DEFINE_int32(min_still_obstacle_history_length, 4, "Min # historical frames for still obstacles"); DEFINE_int32(max_still_obstacle_history_length, 10, "Min # historical frames for still obstacles"); DEFINE_double(still_obstacle_speed_threshold, 0.99, "Speed threshold for still obstacles"); DEFINE_double(still_pedestrian_speed_threshold, 0.2, "Speed threshold for still pedestrians"); DEFINE_double(still_unknown_speed_threshold, 0.5, "Speed threshold for still unknown obstacles"); DEFINE_double(still_obstacle_position_std, 0.5, "Position standard deviation for still obstacles"); DEFINE_double(still_pedestrian_position_std, 0.5, "Position standard deviation for still pedestrians"); DEFINE_double(still_unknown_position_std, 0.5, "Position standard deviation for still unknown obstacles"); DEFINE_double(slow_obstacle_speed_threshold, 2.0, "Speed threshold for slow obstacles"); DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time."); DEFINE_double(target_lane_gap, 2.0, "Gap between two lane points."); DEFINE_double(dense_lane_gap, 0.2, "Gap between two adjacent lane points" " for constructing dense lane graph."); DEFINE_int32(max_num_current_lane, 2, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff, M_PI / 3.0, "Max angle difference for a candidate lane"); DEFINE_int32(max_num_current_lane_in_junction, 3, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane_in_junction, 2, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff_in_junction, M_PI / 4.0, "Max angle difference for a candidate lane"); DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation"); DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian"); DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration"); DEFINE_double(still_speed, 0.01, "speed considered to be still"); DEFINE_string(evaluator_vehicle_mlp_file, "/apollo/modules/prediction/data/mlp_vehicle_model.bin", "mlp model file for vehicle evaluator"); DEFINE_string(evaluator_vehicle_rnn_file, "/apollo/modules/prediction/data/rnn_vehicle_model.bin", "rnn model file for vehicle evaluator"); DEFINE_string( torch_vehicle_jointly_model_file, "/apollo/modules/prediction/data/" "jointly_prediction_planning_vehicle_model.pt", "Vehicle jointly prediction and planning model file"); DEFINE_string( torch_vehicle_jointly_model_cpu_file, "/apollo/modules/prediction/data/" "jointly_prediction_planning_vehicle_cpu_model.pt", "Vehicle jointly prediction and planning cpu model file"); DEFINE_string(torch_vehicle_junction_mlp_file, "/apollo/modules/prediction/data/junction_mlp_vehicle_model.pt", "Vehicle junction MLP model file"); DEFINE_string(torch_vehicle_junction_map_file, "/apollo/modules/prediction/data/junction_map_vehicle_model.pt", "Vehicle junction map model file"); DEFINE_string(torch_vehicle_semantic_lstm_file, "/apollo/modules/prediction/data/semantic_lstm_vehicle_model.pt", "Vehicle semantic lstm model file, default for gpu"); DEFINE_string( torch_vehicle_semantic_lstm_cpu_file, "/apollo/modules/prediction/data/semantic_lstm_vehicle_cpu_model.pt", "Vehicle semantic lstm cpu model file"); DEFINE_string(torch_vehicle_cruise_go_file, "/apollo/modules/prediction/data/cruise_go_vehicle_model.pt", "Vehicle cruise go model file"); DEFINE_string(torch_vehicle_cruise_cutin_file, "/apollo/modules/prediction/data/cruise_cutin_vehicle_model.pt", "Vehicle cruise cutin model file"); DEFINE_string(torch_vehicle_lane_scanning_file, "/apollo/modules/prediction/data/lane_scanning_vehicle_model.pt", "Vehicle lane scanning model file"); DEFINE_string(torch_vehicle_vectornet_file, "/apollo/modules/prediction/data/vectornet_vehicle_model.pt", "Vehicle vectornet model file"); DEFINE_string(torch_vehicle_vectornet_cpu_file, "/apollo/modules/prediction/data/vectornet_vehicle_cpu_model.pt", "Vehicle vectornet cpu model file"); DEFINE_string(torch_pedestrian_interaction_position_embedding_file, "/apollo/modules/prediction/data/" "pedestrian_interaction_position_embedding.pt", "pedestrian interaction position embedding"); DEFINE_string(torch_pedestrian_interaction_social_embedding_file, "/apollo/modules/prediction/data/" "pedestrian_interaction_social_embedding.pt", "pedestrian interaction social embedding"); DEFINE_string(torch_pedestrian_interaction_single_lstm_file, "/apollo/modules/prediction/data/" "pedestrian_interaction_single_lstm.pt", "pedestrian interaction single lstm"); DEFINE_string(torch_pedestrian_interaction_prediction_layer_file, "/apollo/modules/prediction/data/" "pedestrian_interaction_prediction_layer.pt", "pedestrian interaction prediction layer"); DEFINE_string( torch_pedestrian_semantic_lstm_file, "/apollo/modules/prediction/data/semantic_lstm_pedestrian_model.pt", "Pedestrian semantic lstm model file, default for gpu"); DEFINE_string( torch_pedestrian_semantic_lstm_cpu_file, "/apollo/modules/prediction/data/semantic_lstm_pedestrian_cpu_model.pt", "Pedestrian semantic lstm cpu model file"); DEFINE_string(torch_lane_aggregating_obstacle_encoding_file, "/apollo/modules/prediction/data/" "traced_online_obs_enc.pt", "lane aggregating obstacle encoding layer"); DEFINE_string(torch_lane_aggregating_lane_encoding_file, "/apollo/modules/prediction/data/" "traced_online_lane_enc.pt", "lane aggregating lane encoding layer"); DEFINE_string(torch_lane_aggregating_prediction_layer_file, "/apollo/modules/prediction/data/" "traced_online_pred_layer.pt", "lane aggregating prediction layer"); DEFINE_int32(max_num_obstacles, 300, "maximal number of obstacles stored in obstacles container."); DEFINE_double(valid_position_diff_threshold, 0.5, "threshold of valid position difference"); DEFINE_double(valid_position_diff_rate_threshold, 0.075, "threshold of valid position difference rate"); DEFINE_double(split_rate, 0.5, "obstacle split rate for adjusting velocity"); DEFINE_double(rnn_min_lane_relatice_s, 5.0, "Minimal relative s for RNN model."); DEFINE_bool(adjust_velocity_by_obstacle_heading, false, "Use obstacle heading for velocity."); DEFINE_bool(adjust_velocity_by_position_shift, false, "adjust velocity heading to lane heading"); DEFINE_bool(adjust_vehicle_heading_by_lane, true, "adjust vehicle heading by lane"); DEFINE_double(heading_filter_param, 0.98, "heading filter parameter"); DEFINE_uint64(max_num_lane_point, 20, "The maximal number of lane points to store"); DEFINE_double(distance_threshold_to_junction_exit, 1.0, "Threshold of distance to junction exit"); DEFINE_double(angle_threshold_to_junction_exit, M_PI * 0.25, "Threshold of angle to junction exit"); DEFINE_uint32(sample_size_for_average_lane_curvature, 10, "The sample size to compute average lane curvature"); // Validation checker DEFINE_double(centripetal_acc_coeff, 0.5, "Coefficient of centripetal acceleration probability"); // Junction Scenario DEFINE_uint32(junction_historical_frame_length, 5, "The number of historical frames of the obstacle" "that the junction model will look at."); DEFINE_double(junction_exit_lane_threshold, 0.1, "If a lane extends out of the junction by this value," "consider it as an exit_lane."); DEFINE_double(distance_beyond_junction, 0.5, "If the obstacle is in junction more than this threshold," "consider it in junction."); DEFINE_double(defualt_junction_range, 10.0, "Default value for the range of a junction."); DEFINE_double(distance_to_slow_down_at_stop_sign, 80.0, "The distance to slow down at stop sign"); // Evaluator DEFINE_double(time_to_center_if_not_reach, 10.0, "Default value of time to lane center of not reach."); DEFINE_double(default_s_if_no_obstacle_in_lane_sequence, 1000.0, "The default s value if no obstacle in the lane sequence."); DEFINE_double(default_l_if_no_obstacle_in_lane_sequence, 10.0, "The default l value if no obstacle in the lane sequence."); DEFINE_bool(enable_semantic_map, true, "If enable semantic map on prediction"); // Obstacle trajectory DEFINE_bool(enable_cruise_regression, false, "If enable using regression in cruise model"); DEFINE_double(lane_sequence_threshold_cruise, 0.5, "Threshold for trimming lane sequence trajectories in cruise"); DEFINE_double(lane_sequence_threshold_junction, 0.5, "Threshold for trimming lane sequence trajectories in junction"); DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC"); DEFINE_bool(enable_lane_sequence_acc, false, "If use acceleration in lane sequence."); DEFINE_bool(enable_trim_prediction_trajectory, true, "If trim the prediction trajectory to avoid crossing" "protected adc planning trajectory."); DEFINE_double(adc_trajectory_search_length, 10.0, "How far to search junction along adc planning trajectory"); DEFINE_double(virtual_lane_radius, 2.0, "Radius to search virtual lanes"); DEFINE_double(default_lateral_approach_speed, 0.5, "Default lateral speed approaching to center of lane"); DEFINE_double(centripedal_acc_threshold, 2.0, "Threshold of centripedal acceleration."); // move sequence prediction DEFINE_double(time_upper_bound_to_lane_center, 6.0, "Upper bound of time to get to the lane center"); DEFINE_double(time_lower_bound_to_lane_center, 1.0, "Lower bound of time to get to the lane center"); DEFINE_double(sample_time_gap, 0.5, "Gap of time to sample time to get to the lane center"); DEFINE_double(cost_alpha, 100.0, "The coefficient of lateral acceleration in cost function"); DEFINE_double(default_time_to_lat_end_state, 5.0, "The default time to lane center"); DEFINE_double(turning_curvature_lower_bound, 0.02, "The curvature lower bound of turning lane"); DEFINE_double(turning_curvature_upper_bound, 0.14, "The curvature upper bound of turning lane"); DEFINE_double(speed_at_lower_curvature, 8.5, "The speed at turning lane with lower bound curvature"); DEFINE_double(speed_at_upper_curvature, 3.0, "The speed at turning lane with upper bound curvature"); DEFINE_double(cost_function_alpha, 0.25, "alpha of the cost function for best trajectory selection," "alpha weighs the influence by max lateral acceleration" "and that by the total time. The larger alpha gets, the" "more cost function values trajectory with shorter times," "and vice versa."); DEFINE_double(cost_function_sigma, 5.0, "This is the sigma for the bell curve that is used by" "the cost function in move-sequence-trajectory-predictor." "The bell curve has its average equal to the time to cross" "lane predicted by the model."); DEFINE_bool(use_bell_curve_for_cost_function, false, "Whether to use bell curve for the cost function or not."); // interaction predictor DEFINE_bool(enable_interactive_tag, true, "Whether to set interactive tag for obstacles."); DEFINE_double(collision_cost_time_resolution, 1.0, "The time resolution used to compute the collision cost"); DEFINE_double(longitudinal_acceleration_cost_weight, 0.2, "The weight of longitudinal acceleration cost"); DEFINE_double(centripedal_acceleration_cost_weight, 0.1, "The weight of the cost related to centripedal acceleration"); DEFINE_double(collision_cost_weight, 1.0, "The weight of the cost related to collision"); DEFINE_double(collision_cost_exp_coefficient, 1.0, "The coefficient in the collision exponential cost function"); DEFINE_double(likelihood_exp_coefficient, 1.0, "The coefficient in the likelihood exponential function"); DEFINE_double(lane_distance_threshold, 3.0, "The threshold for distance to ego/neighbor lane " "in feature extraction"); DEFINE_double(lane_angle_difference_threshold, M_PI * 0.25, "The threshold for distance to ego/neighbor lane " "in feature extraction"); // Trajectory evaluation DEFINE_double(distance_threshold_on_lane, 1.5, "The threshold of distance in on-lane situation");
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/validation_checker.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_msgs/prediction_msgs/lane_graph.pb.h" namespace apollo { namespace prediction { class ValidationChecker { public: /** * @brief Compute the probability by centripetal acceleration * @param lane sequence * @param current speed of obstacle * @return probability */ static double ProbabilityByCentripetalAcceleration( const LaneSequence& lane_sequence, const double speed); /** * @brief Check the validity of trajectory's centripetal acceleration * @param The discretized trajectory * @return The validity of trajectory's centripetal acceleration */ static bool ValidCentripetalAcceleration( const std::vector<common::TrajectoryPoint>& discretized_trajectory); /** * @brief Check if a trajectory point is valid * @param A trajectory point * @return True if the trajectory point is valid */ static bool ValidTrajectoryPoint( const common::TrajectoryPoint& trajectory_point); private: ValidationChecker() = delete; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_map_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/prediction/common/prediction_map.h" #include "modules/prediction/common/kml_map_based_test.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using apollo::hdmap::MapPathPoint; class PredictionMapTest : public KMLMapBasedTest {}; TEST_F(PredictionMapTest, get_lane_info) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); EXPECT_NE(nullptr, lane_info); EXPECT_EQ("l20", lane_info->id().id()); lane_info = PredictionMap::LaneById("l500"); EXPECT_EQ(nullptr, lane_info); } TEST_F(PredictionMapTest, get_position_on_lane) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); // on lane Eigen::Vector2d position_on_lane = PredictionMap::PositionOnLane(lane_info, 10.0); EXPECT_DOUBLE_EQ(124.85930930657942, position_on_lane(0)); EXPECT_DOUBLE_EQ(348.52732962417451, position_on_lane(1)); // beyond end of lane Eigen::Vector2d position_off_lane = PredictionMap::PositionOnLane(lane_info, 1000.0); EXPECT_DOUBLE_EQ(392.71861332684404, position_off_lane(0)); EXPECT_DOUBLE_EQ(286.16205764480401, position_off_lane(1)); } TEST_F(PredictionMapTest, heading_on_lane) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); // on lane EXPECT_DOUBLE_EQ(-0.066794953844859783, PredictionMap::HeadingOnLane(lane_info, 10.0)); } TEST_F(PredictionMapTest, get_lane_width) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); // on lane EXPECT_DOUBLE_EQ(2.9895597224833121, PredictionMap::LaneTotalWidth(lane_info, 10.0)); // beyond end of lane EXPECT_DOUBLE_EQ(3.1943980708125523, PredictionMap::LaneTotalWidth(lane_info, 1000.0)); EXPECT_DOUBLE_EQ(3.1943980708125523, PredictionMap::LaneTotalWidth(lane_info, 1000.0)); } TEST_F(PredictionMapTest, get_projection) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); // on lane Eigen::Vector2d position_on_lane(124.85931, 347.52733); double s = 0.0; double l = 0.0; PredictionMap::GetProjection(position_on_lane, lane_info, &s, &l); EXPECT_DOUBLE_EQ(10.061275933723756, s); EXPECT_DOUBLE_EQ(-0.9981204878650296, l); // off lane Eigen::Vector2d position_off_lane(124.85931, 357.52733); PredictionMap::GetProjection(position_off_lane, lane_info, &s, &l); EXPECT_DOUBLE_EQ(9.4485232873738045, s); EXPECT_DOUBLE_EQ(8.9830885668733345, l); } TEST_F(PredictionMapTest, get_map_pathpoint) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); double s = 10.0; // on lane MapPathPoint point; EXPECT_TRUE(PredictionMap::ProjectionFromLane(lane_info, s, &point)); EXPECT_DOUBLE_EQ(124.85930930657942, point.x()); EXPECT_DOUBLE_EQ(348.52732962417451, point.y()); EXPECT_DOUBLE_EQ(-0.066794953844859783, point.heading()); // non-existent lane lane_info.reset(); s = 10.0; EXPECT_FALSE(PredictionMap::ProjectionFromLane(lane_info, s, &point)); } TEST_F(PredictionMapTest, on_lane) { std::vector<std::shared_ptr<const LaneInfo>> prev_lanes(0); Eigen::Vector2d point(124.85931, 347.52733); double heading = 0.0; double radius = 3.0; // on lane without previous lanes std::vector<std::shared_ptr<const LaneInfo>> curr_lanes(0); PredictionMap::OnLane(prev_lanes, point, heading, radius, true, FLAGS_max_num_current_lane, FLAGS_max_lane_angle_diff, &curr_lanes); EXPECT_EQ(1, curr_lanes.size()); EXPECT_EQ("l20", curr_lanes[0]->id().id()); // on lane with previous lanes prev_lanes.emplace_back(PredictionMap::LaneById("l10")); curr_lanes.clear(); PredictionMap::OnLane(prev_lanes, point, heading, radius, true, FLAGS_max_num_current_lane, FLAGS_max_lane_angle_diff, &curr_lanes); EXPECT_EQ(0, curr_lanes.size()); // off lane without previous lanes prev_lanes.clear(); point(0) = 124.85931; point(1) = 357.52733; curr_lanes.clear(); PredictionMap::OnLane(prev_lanes, point, heading, radius, true, FLAGS_max_num_current_lane, FLAGS_max_lane_angle_diff, &curr_lanes); EXPECT_TRUE(curr_lanes.empty()); } TEST_F(PredictionMapTest, get_path_heading) { std::shared_ptr<const LaneInfo> lane_info = PredictionMap::LaneById("l20"); common::PointENU point; point.set_x(124.85931); point.set_y(347.52733); auto actual_heading = PredictionMap::PathHeading(lane_info, point); EXPECT_NEAR(-0.066973788088279029, actual_heading, 1.0e-10); } TEST_F(PredictionMapTest, get_smooth_point_from_lane) { const std::string id = "l20"; double s = 10.0; double l = 0.0; double heading = M_PI; Eigen::Vector2d point; EXPECT_TRUE(PredictionMap::SmoothPointFromLane(id, s, l, &point, &heading)); EXPECT_DOUBLE_EQ(124.85930930657942, point.x()); EXPECT_DOUBLE_EQ(348.52732962417451, point.y()); EXPECT_DOUBLE_EQ(-0.066794953844859783, heading); } TEST_F(PredictionMapTest, get_nearby_lanes_by_current_lanes) { std::vector<std::shared_ptr<const LaneInfo>> curr_lanes(0); curr_lanes.emplace_back(PredictionMap::LaneById("l20")); std::vector<std::shared_ptr<const LaneInfo>> nearby_lanes(0); // large radius Eigen::Vector2d point(124.85931, 348.52733); double radius = 6.0; double theta = -0.061427808505166936; PredictionMap::NearbyLanesByCurrentLanes(point, theta, radius, curr_lanes, FLAGS_max_num_nearby_lane, &nearby_lanes); EXPECT_EQ(1, nearby_lanes.size()); EXPECT_EQ("l21", nearby_lanes[0]->id().id()); // small radius nearby_lanes.clear(); radius = 0.5; PredictionMap::NearbyLanesByCurrentLanes(point, theta, radius, curr_lanes, FLAGS_max_num_nearby_lane, &nearby_lanes); EXPECT_EQ(0, nearby_lanes.size()); // without current lanes curr_lanes.clear(); nearby_lanes.clear(); radius = 5.0; PredictionMap::NearbyLanesByCurrentLanes(point, theta, radius, curr_lanes, FLAGS_max_num_nearby_lane, &nearby_lanes); EXPECT_EQ(2, nearby_lanes.size()); EXPECT_EQ("l20", nearby_lanes[0]->id().id()); EXPECT_EQ("l21", nearby_lanes[1]->id().id()); } TEST_F(PredictionMapTest, neighbor_lane_detection) { std::vector<std::shared_ptr<const LaneInfo>> curr_lanes(0); // empty current lanes EXPECT_TRUE(PredictionMap::IsLeftNeighborLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsRightNeighborLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsSuccessorLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsPredecessorLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsIdenticalLane(PredictionMap::LaneById("l20"), curr_lanes)); // given current lanes std::shared_ptr<const LaneInfo> curr_lane = PredictionMap::LaneById("l21"); curr_lanes.emplace_back(curr_lane); EXPECT_TRUE(PredictionMap::IsLeftNeighborLane(PredictionMap::LaneById("l22"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsRightNeighborLane( PredictionMap::LaneById("l22"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsSuccessorLane(PredictionMap::LaneById("l22"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsPredecessorLane(PredictionMap::LaneById("l22"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsIdenticalLane(PredictionMap::LaneById("l22"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsLeftNeighborLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsRightNeighborLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsSuccessorLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsPredecessorLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsIdenticalLane(PredictionMap::LaneById("l20"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsLeftNeighborLane(PredictionMap::LaneById("l18"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsRightNeighborLane( PredictionMap::LaneById("l18"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsSuccessorLane(PredictionMap::LaneById("l18"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsPredecessorLane(PredictionMap::LaneById("l18"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsIdenticalLane(PredictionMap::LaneById("l18"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsLeftNeighborLane(PredictionMap::LaneById("l99"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsRightNeighborLane( PredictionMap::LaneById("l99"), curr_lanes)); EXPECT_TRUE(PredictionMap::IsSuccessorLane(PredictionMap::LaneById("l99"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsPredecessorLane(PredictionMap::LaneById("l99"), curr_lanes)); EXPECT_FALSE(PredictionMap::IsIdenticalLane(PredictionMap::LaneById("l99"), curr_lanes)); } TEST_F(PredictionMapTest, lane_turn_type) { // Valid lane EXPECT_EQ(1, PredictionMap::LaneTurnType("l20")); // Invalid lane EXPECT_FALSE(PredictionMap::LaneById("l500")); EXPECT_EQ(1, PredictionMap::LaneTurnType("l500")); EXPECT_EQ(3, PredictionMap::LaneTurnType("l5")); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_thread_pool.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/prediction/common/prediction_thread_pool.h" namespace apollo { namespace prediction { thread_local int PredictionThreadPool::s_thread_pool_level = 0; std::vector<int> BaseThreadPool::THREAD_POOL_CAPACITY = {20, 20, 20}; BaseThreadPool::BaseThreadPool(int thread_num, int next_thread_pool_level) : stopped_(false) { if (!task_queue_.Init(thread_num, new apollo::cyber::base::BlockWaitStrategy())) { throw std::runtime_error("Task queue init failed."); } for (int i = 0; i < thread_num; ++i) { workers_.emplace_back([this, next_thread_pool_level, i] { PredictionThreadPool::s_thread_pool_level = next_thread_pool_level; while (!stopped_) { std::function<void()> task; if (task_queue_.WaitDequeue(&task)) { task(); } } }); } } void BaseThreadPool::Stop() { task_queue_.BreakAllWait(); for (std::thread& worker : workers_) { worker.join(); } stopped_ = true; } BaseThreadPool::~BaseThreadPool() { if (stopped_.exchange(true)) { return; } task_queue_.BreakAllWait(); for (std::thread& worker : workers_) { worker.join(); } } BaseThreadPool* PredictionThreadPool::Instance() { int pool_level = s_thread_pool_level; int max_thread_pool_level = static_cast<int>(BaseThreadPool::THREAD_POOL_CAPACITY.size()); CHECK_LT(pool_level, max_thread_pool_level); int index = s_thread_pool_level; switch (index) { case 0: { return LevelThreadPool<0>::Instance(); } case 1: { return LevelThreadPool<1>::Instance(); } case 2: { return LevelThreadPool<2>::Instance(); } } AERROR << "Should not hit here"; return LevelThreadPool<0>::Instance(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/environment_features.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/prediction/common/environment_features.h" #include "cyber/common/log.h" namespace apollo { namespace prediction { void EnvironmentFeatures::set_ego_position(const double x, const double y) { ego_position_.set_x(x); ego_position_.set_y(y); ego_position_.set_z(0.0); } const apollo::common::Point3D& EnvironmentFeatures::get_ego_position() const { return ego_position_; } void EnvironmentFeatures::set_ego_speed(const double ego_speed) { ego_speed_ = ego_speed; } double EnvironmentFeatures::get_ego_speed() const { return ego_speed_; } void EnvironmentFeatures::set_ego_heading(const double ego_heading) { ego_heading_ = ego_heading; } double EnvironmentFeatures::get_ego_heading() const { return ego_heading_; } void EnvironmentFeatures::set_ego_acceleration(const double ego_acceleration) { ego_acceleration_ = ego_acceleration; } double EnvironmentFeatures::get_ego_acceleration() const { return ego_acceleration_; } bool EnvironmentFeatures::has_ego_lane() const { return has_ego_lane_; } void EnvironmentFeatures::reset_ego_lane() { has_ego_lane_ = false; ego_lane_id_ = ""; ego_lane_s_ = -1.0; } void EnvironmentFeatures::SetEgoLane(const std::string& lane_id, const double lane_s) { has_ego_lane_ = true; ego_lane_id_ = lane_id; ego_lane_s_ = lane_s; } std::pair<std::string, double> EnvironmentFeatures::GetEgoLane() const { ACHECK(has_ego_lane_); return {ego_lane_id_, ego_lane_s_}; } bool EnvironmentFeatures::has_left_neighbor_lane() const { return has_left_neighbor_lane_; } void EnvironmentFeatures::reset_left_neighbor_lane() { has_left_neighbor_lane_ = false; } void EnvironmentFeatures::SetLeftNeighborLane(const std::string& lane_id, const double lane_s) { has_left_neighbor_lane_ = true; left_neighbor_lane_id_ = lane_id; left_neighbor_lane_s_ = lane_s; } std::pair<std::string, double> EnvironmentFeatures::GetLeftNeighborLane() const { ACHECK(has_left_neighbor_lane_); return {left_neighbor_lane_id_, left_neighbor_lane_s_}; } bool EnvironmentFeatures::has_right_neighbor_lane() const { return has_right_neighbor_lane_; } void EnvironmentFeatures::reset_right_neighbor_lane() { has_right_neighbor_lane_ = false; } void EnvironmentFeatures::SetRightNeighborLane(const std::string& lane_id, const double lane_s) { has_right_neighbor_lane_ = true; right_neighbor_lane_id_ = lane_id; right_neighbor_lane_s_ = lane_s; } std::pair<std::string, double> EnvironmentFeatures::GetRightNeighborLane() const { ACHECK(has_right_neighbor_lane_); return {right_neighbor_lane_id_, right_neighbor_lane_s_}; } bool EnvironmentFeatures::has_front_junction() const { return has_front_junction_; } void EnvironmentFeatures::reset_front_junction() { has_front_junction_ = false; } void EnvironmentFeatures::SetFrontJunction(const std::string& junction_id, const double dist) { has_front_junction_ = true; front_junction_id_ = junction_id; dist_to_front_junction_ = dist; } std::pair<std::string, double> EnvironmentFeatures::GetFrontJunction() const { ACHECK(has_front_junction_); return {front_junction_id_, dist_to_front_junction_}; } void EnvironmentFeatures::AddObstacleId(const int obstacle_id) { obstacle_ids_.push_back(obstacle_id); } const std::vector<int>& EnvironmentFeatures::get_obstacle_ids() const { return obstacle_ids_; } const std::unordered_set<std::string>& EnvironmentFeatures::nonneglectable_reverse_lanes() const { return nonneglectable_reverse_lanes_; } void EnvironmentFeatures::AddNonneglectableReverseLanes( const std::string& lane_id) { nonneglectable_reverse_lanes_.insert(lane_id); } bool EnvironmentFeatures::RemoveNonneglectableReverseLanes( const std::string& lane_id) { if (nonneglectable_reverse_lanes_.find(lane_id) == nonneglectable_reverse_lanes_.end()) { return false; } nonneglectable_reverse_lanes_.erase(lane_id); return true; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/junction_analyzer_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { class JunctionAnalyzerTest : public KMLMapBasedTest {}; TEST_F(JunctionAnalyzerTest, SingleLane) { JunctionAnalyzer junction_analyzer; junction_analyzer.Init("j2"); EXPECT_NEAR(junction_analyzer.ComputeJunctionRange(), 74.0306, 0.001); const JunctionFeature& junction_feature = junction_analyzer.GetJunctionFeature("l61"); EXPECT_EQ(junction_feature.junction_id(), "j2"); EXPECT_EQ(junction_feature.enter_lane().lane_id(), "l61"); EXPECT_GT(junction_feature.junction_exit_size(), 0); junction_analyzer.Clear(); } TEST_F(JunctionAnalyzerTest, MultiLane) { JunctionAnalyzer junction_analyzer; junction_analyzer.Init("j2"); const JunctionFeature& merged_junction_feature = junction_analyzer.GetJunctionFeature( std::vector<std::string>{"l35", "l61", "l114", "l162"}); EXPECT_EQ(merged_junction_feature.junction_id(), "j2"); EXPECT_EQ(merged_junction_feature.junction_exit_size(), 3); junction_analyzer.Clear(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/message_process.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/prediction/common/message_process.h" #include <memory> #include "cyber/common/file.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/prediction/common/feature_output.h" #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/prediction_constants.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/common/validation_checker.h" #include "modules/prediction/container/storytelling/storytelling_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/offline_features.pb.h" #include "modules/prediction/scenario/interaction_filter/interaction_filter.h" #include "modules/prediction/scenario/prioritization/obstacles_prioritizer.h" #include "modules/prediction/scenario/right_of_way/right_of_way.h" #include "modules/common/util/data_extraction.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; using apollo::cyber::proto::SingleMessage; using apollo::cyber::record::RecordMessage; using apollo::cyber::record::RecordReader; using apollo::cyber::record::RecordWriter; using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; using apollo::planning::ADCTrajectory; using apollo::storytelling::Stories; bool MessageProcess::Init(ContainerManager* container_manager, EvaluatorManager* evaluator_manager, PredictorManager* predictor_manager, const PredictionConf& prediction_conf) { InitContainers(container_manager); InitEvaluators(evaluator_manager, prediction_conf); InitPredictors(predictor_manager, prediction_conf); if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) { AERROR << "Map cannot be loaded."; return false; } return true; } bool MessageProcess::InitContainers(ContainerManager* container_manager) { common::adapter::AdapterManagerConfig adapter_conf; if (!cyber::common::GetProtoFromFile(FLAGS_prediction_adapter_config_filename, &adapter_conf)) { AERROR << "Unable to load adapter conf file: " << FLAGS_prediction_adapter_config_filename; return false; } ADEBUG << "Adapter config file is loaded into: " << adapter_conf.ShortDebugString(); container_manager->Init(adapter_conf); return true; } bool MessageProcess::InitEvaluators(EvaluatorManager* evaluator_manager, const PredictionConf& prediction_conf) { evaluator_manager->Init(prediction_conf); return true; } bool MessageProcess::InitPredictors(PredictorManager* predictor_manager, const PredictionConf& prediction_conf) { predictor_manager->Init(prediction_conf); return true; } void MessageProcess::ContainerProcess( const std::shared_ptr<ContainerManager>& container_manager, const perception::PerceptionObstacles& perception_obstacles, ScenarioManager* scenario_manager) { ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; // Get obstacles_container auto ptr_obstacles_container = container_manager->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); CHECK_NOTNULL(ptr_obstacles_container); ptr_obstacles_container->CleanUp(); // Get pose_container auto ptr_ego_pose_container = container_manager->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION); CHECK_NOTNULL(ptr_ego_pose_container); // Get adc_trajectory_container auto ptr_ego_trajectory_container = container_manager->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); CHECK_NOTNULL(ptr_ego_trajectory_container); // Get storytelling_container auto ptr_storytelling_container = container_manager->GetContainer<StoryTellingContainer>( AdapterConfig::STORYTELLING); CHECK_NOTNULL(ptr_storytelling_container); // Insert ADC into the obstacle_container. const PerceptionObstacle* ptr_ego_vehicle = ptr_ego_pose_container->ToPerceptionObstacle(); if (ptr_ego_vehicle != nullptr) { double perception_obs_timestamp = ptr_ego_vehicle->timestamp(); if (perception_obstacles.has_header() && perception_obstacles.header().has_timestamp_sec()) { ADEBUG << "Correcting " << std::fixed << std::setprecision(6) << ptr_ego_vehicle->timestamp() << " to " << std::fixed << std::setprecision(6) << perception_obstacles.header().timestamp_sec(); perception_obs_timestamp = perception_obstacles.header().timestamp_sec(); } ptr_obstacles_container->InsertPerceptionObstacle(*ptr_ego_vehicle, perception_obs_timestamp); double x = ptr_ego_vehicle->position().x(); double y = ptr_ego_vehicle->position().y(); ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x << ", " << std::fixed << std::setprecision(6) << y << "]."; ptr_ego_trajectory_container->SetPosition({x, y}); } // Insert perception_obstacles ptr_obstacles_container->Insert(perception_obstacles); ObstaclesPrioritizer obstacles_prioritizer(container_manager); InteractionFilter interaction_filter(container_manager); // Ignore some obstacles obstacles_prioritizer.AssignIgnoreLevel(); // Scenario analysis scenario_manager->Run(container_manager.get()); // Build junction feature for the obstacles in junction const Scenario scenario = scenario_manager->scenario(); if (scenario.type() == Scenario::JUNCTION && scenario.has_junction_id()) { ptr_obstacles_container->GetJunctionAnalyzer()->Init( scenario.junction_id()); ptr_obstacles_container->BuildJunctionFeature(); } // Build lane graph ptr_obstacles_container->BuildLaneGraph(); // Assign CautionLevel for obstacles obstacles_prioritizer.AssignCautionLevel(); // Add interactive tag if (FLAGS_enable_interactive_tag) { interaction_filter.AssignInteractiveTag(); } // Analyze RightOfWay for the caution obstacles RightOfWay::Analyze(container_manager.get()); } void MessageProcess::OnPerception( const perception::PerceptionObstacles& perception_obstacles, const std::shared_ptr<ContainerManager>& container_manager, EvaluatorManager* evaluator_manager, PredictorManager* predictor_manager, ScenarioManager* scenario_manager, PredictionObstacles* const prediction_obstacles) { ContainerProcess(container_manager, perception_obstacles, scenario_manager); auto ptr_obstacles_container = container_manager->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); CHECK_NOTNULL(ptr_obstacles_container); auto ptr_ego_trajectory_container = container_manager->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); CHECK_NOTNULL(ptr_ego_trajectory_container); // Insert features to FeatureOutput for offline_mode if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpFeatureProto) { for (const int id : ptr_obstacles_container->curr_frame_movable_obstacle_ids()) { Obstacle* obstacle_ptr = ptr_obstacles_container->GetObstacle(id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle found."; continue; } if (!obstacle_ptr->latest_feature().IsInitialized()) { AERROR << "Obstacle [" << id << "] has no latest feature."; continue; } // TODO(all): the adc trajectory should be part of features for learning // algorithms rather than part of the feature.proto *obstacle_ptr->mutable_latest_feature()->mutable_adc_trajectory_point() = ptr_ego_trajectory_container->adc_trajectory().trajectory_point(); // adc trajectory timestamp obstacle_ptr->mutable_latest_feature()->set_adc_timestamp( ptr_ego_trajectory_container->adc_trajectory() .header().timestamp_sec()); // ego pose_container auto ptr_ego_pose = container_manager->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION); CHECK_NOTNULL(ptr_ego_pose); // adc localization obstacle_ptr->mutable_latest_feature()->mutable_adc_localization()-> CopyFrom(*ptr_ego_pose->ToPerceptionObstacle()); FeatureOutput::InsertFeatureProto(obstacle_ptr->latest_feature()); ADEBUG << "Insert feature into feature output"; } // Not doing evaluation on offline mode return; } // Make evaluations evaluator_manager->Run(ptr_ego_trajectory_container, ptr_obstacles_container); if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpDataForLearning || FLAGS_prediction_offline_mode == PredictionConstants::kDumpFrameEnv) { return; } // Make predictions predictor_manager->Run(perception_obstacles, ptr_ego_trajectory_container, ptr_obstacles_container); // Get predicted obstacles *prediction_obstacles = predictor_manager->prediction_obstacles(); } void MessageProcess::OnLocalization( ContainerManager* container_manager, const localization::LocalizationEstimate& localization) { auto ptr_ego_pose_container = container_manager->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION); ACHECK(ptr_ego_pose_container != nullptr); ptr_ego_pose_container->Insert(localization); ADEBUG << "Received a localization message [" << localization.ShortDebugString() << "]."; } void MessageProcess::OnPlanning(ContainerManager* container_manager, const planning::ADCTrajectory& adc_trajectory) { auto ptr_ego_trajectory_container = container_manager->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); ACHECK(ptr_ego_trajectory_container != nullptr); ptr_ego_trajectory_container->Insert(adc_trajectory); ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString() << "]."; auto ptr_storytelling_container = container_manager->GetContainer<StoryTellingContainer>( AdapterConfig::STORYTELLING); CHECK_NOTNULL(ptr_storytelling_container); ptr_ego_trajectory_container->SetJunction( ptr_storytelling_container->ADCJunctionId(), ptr_storytelling_container->ADCDistanceToJunction()); } void MessageProcess::OnStoryTelling(ContainerManager* container_manager, const Stories& story) { auto ptr_storytelling_container = container_manager->GetContainer<StoryTellingContainer>( AdapterConfig::STORYTELLING); CHECK_NOTNULL(ptr_storytelling_container); ptr_storytelling_container->Insert(story); ADEBUG << "Received a storytelling message [" << story.ShortDebugString() << "]."; } void MessageProcess::ProcessOfflineData( const PredictionConf& prediction_conf, const std::shared_ptr<ContainerManager>& container_manager, EvaluatorManager* evaluator_manager, PredictorManager* predictor_manager, ScenarioManager* scenario_manager, const std::string& record_filepath) { RecordReader reader(record_filepath); RecordMessage message; RecordWriter writer; if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpRecord) { writer.Open(record_filepath + ".new_prediction"); } while (reader.ReadMessage(&message)) { if (message.channel_name == prediction_conf.topic_conf().perception_obstacle_topic()) { PerceptionObstacles perception_obstacles; if (perception_obstacles.ParseFromString(message.content)) { if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpRecord) { writer.WriteMessage<PerceptionObstacles>( message.channel_name, perception_obstacles, message.time); } PredictionObstacles prediction_obstacles; OnPerception(perception_obstacles, container_manager, evaluator_manager, predictor_manager, scenario_manager, &prediction_obstacles); if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpRecord) { writer.WriteMessage<PredictionObstacles>( prediction_conf.topic_conf().perception_obstacle_topic(), prediction_obstacles, message.time); AINFO << "Generated a new prediction message."; } } } else if (message.channel_name == prediction_conf.topic_conf().localization_topic()) { LocalizationEstimate localization; if (localization.ParseFromString(message.content)) { if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpRecord) { writer.WriteMessage<LocalizationEstimate>(message.channel_name, localization, message.time); } OnLocalization(container_manager.get(), localization); } } else if (message.channel_name == prediction_conf.topic_conf().planning_trajectory_topic()) { ADCTrajectory adc_trajectory; if (adc_trajectory.ParseFromString(message.content)) { OnPlanning(container_manager.get(), adc_trajectory); } } } if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpRecord) { writer.Close(); } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/kml_map_based_test.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "gtest/gtest.h" #include "modules/common/configs/config_gflags.h" namespace apollo { namespace prediction { class KMLMapBasedTest : public ::testing::Test { public: KMLMapBasedTest() { FLAGS_map_dir = "modules/prediction/testdata"; FLAGS_base_map_filename = "kml_map.bin"; } }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/feature_output.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *implied. See the License for the specific language governing *permissions and limitations under the License. *****************************************************************************/ #pragma once #include <mutex> #include <string> #include <vector> #include "modules/prediction/container/obstacles/obstacle.h" #include "modules/prediction/proto/offline_features.pb.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" namespace apollo { namespace prediction { 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 feature * @param A feature in proto */ static void InsertFeatureProto(const Feature& feature); /** * @brief Insert a data_for_learning * @param A feature in proto */ static void InsertDataForLearning(const Feature& feature, const std::vector<double>& feature_values, const std::string& category, const LaneSequence* lane_sequence_ptr); static void InsertDataForLearning( const Feature& feature, const std::vector<double>& feature_values, const std::vector<std::string>& string_feature_values, const std::string& category, const LaneSequence* lane_sequence_ptr); /** * @brief Insert a prediction result with predicted trajectories * @param Obstacle id * @param prediction_obstacle * @param obstacle_conf * @param scenario */ static void InsertPredictionResult( const Obstacle* obstacle, const PredictionObstacle& prediction_obstacle, const ObstacleConf& obstacle_conf, const Scenario& scenario); /** * @brief Insert a frame env * @param frame env */ static void InsertFrameEnv(const FrameEnv& frame_env); /** * @brief Insert a data_for_tuning * @param A feature in proto * @param values for tuning * @param category of the data * @param lane sequence * @param adc trajectory */ static void InsertDataForTuning( const Feature& feature, const std::vector<double>& feature_values, const std::string& category, const LaneSequence& lane_sequence, const std::vector<apollo::common::TrajectoryPoint>& adc_trajectory); /** * @brief Write features to a file */ static void WriteFeatureProto(); /** * @brief Write DataForLearning features to a file */ static void WriteDataForLearning(); /** * @brief Write PredictionResult to a file */ static void WritePredictionResult(); /** * @brief Write frame env to a file */ static void WriteFrameEnv(); /** * @brief Write DataForTuning features to a file */ static void WriteDataForTuning(); /** * @brief Get feature size * @return Feature size */ static int Size(); /** * @brief Get the size of data_for_learning features. * @return The size of data_for_learning features. */ static int SizeOfDataForLearning(); /** * @brief Get the size of prediction results. * @return The size of prediction results. */ static int SizeOfPredictionResult(); /** * @brief Get the size of frame env. * @return The size of frame env. */ static int SizeOfFrameEnv(); /** * @brief Get the size of data for tuning. * @return The size of data for tuning. */ static int SizeOfDataForTuning(); private: static Features features_; static std::size_t idx_feature_; static ListDataForLearning list_data_for_learning_; static std::size_t idx_learning_; static ListPredictionResult list_prediction_result_; static std::size_t idx_prediction_result_; static ListFrameEnv list_frame_env_; static std::size_t idx_frame_env_; static ListDataForTuning list_data_for_tuning_; static std::size_t idx_tuning_; static std::mutex mutex_feature_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/road_graph.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <list> #include <memory> #include <string> #include <vector> #include "modules/common/status/status.h" #include "modules/prediction/common/prediction_map.h" #include "modules/common_msgs/prediction_msgs/lane_graph.pb.h" namespace apollo { namespace prediction { class RoadGraph { public: /** * @brief Constructor * @param start_s The starting longitudinal s value. * @param length The length to build the road graph. * @param If consider all successor lanes after dividing. * @param lane_info_ptr The starting lane. */ RoadGraph(const double start_s, const double length, const bool consider_divide, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr); /** * @brief Build the lane graph. * @param The built lane graph. * @return The status of the road graph building. */ common::Status BuildLaneGraph(LaneGraph* const lane_graph); common::Status BuildLaneGraphBidirection(LaneGraph* const lane_graph_ptr); /** * @brief Check if a lane with an s is on the lane graph * @param Lane ID * @param Lane s * @param The pointer to the given lane graph * @return If the given lane ID and lane s is on the lane graph */ bool IsOnLaneGraph(std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, const LaneGraph& lane_graph); private: /** @brief Combine the lane-graph of forward direction and that of backward * direction together. */ LaneGraph CombineLaneGraphs(const LaneGraph& lane_graph_predecessor, const LaneGraph& lane_graph_successor); /** * @brief * @param Whether it is searching in the forward direction or backward. * @param The accumulated s-distance starting from the obstacle's position * up until the beginning of current lane-segment. * @param The s_diff of the current position w.r.t. the start_s of the * current lane-segment, regardless of the search direction. * @param The LaneInfo the current lane segment we are looking at. * @param The max. number of recursive calls (so that it won't recurse * for too many times when given unreasonable speed info. etc.) * @param If we consider all successor lanes after dividing * @param The vector of lane_segments visited (DFS). * @param The LaneGraph that we need to write in. */ void ConstructLaneSequence( const bool search_forward_direction, const double accumulated_s, const double curr_lane_seg_s, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, const int graph_search_horizon, const bool consider_lane_split, std::list<LaneSegment>* const lane_segments, LaneGraph* const lane_graph_ptr) const; /** @brief If direction unspecified, by default construct forward direction. */ void ConstructLaneSequence( const double accumulated_s, const double curr_lane_seg_s, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, const int graph_search_horizon, const bool consider_lane_split, std::list<LaneSegment>* const lane_segments, LaneGraph* const lane_graph_ptr) const; private: // The s of the obstacle on its own lane_segment. double start_s_ = 0; // The total length to search for lane_graph. double length_ = -1.0; // If we consider all successor lanes after dividing bool consider_divide_ = false; // The lane_info of the lane_segment where the obstacle is on. std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr_ = nullptr; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_system_gflags.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/prediction/common/prediction_system_gflags.h" #include <limits> // System gflags DEFINE_string(prediction_module_name, "prediction", "Default prediction module name"); DEFINE_string(prediction_conf_file, "/apollo/modules/prediction/conf/prediction_conf.pb.txt", "Default conf file for prediction"); DEFINE_string(prediction_adapter_config_filename, "/apollo/modules/prediction/conf/adapter.conf", "Default conf file for prediction"); DEFINE_string(prediction_data_dir, "/apollo/modules/prediction/data/prediction/", "Prefix of files to store feature data"); DEFINE_string(offline_feature_proto_file_name, "", "The bin file including a series of feature proto messages"); DEFINE_string(output_filename, "", "The filename for offline process."); DEFINE_string(extract_feature_type, "", "The extract feature type, either cruise or junction"); DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode"); DEFINE_double( prediction_test_duration, std::numeric_limits<double>::infinity(), "The runtime duration in test mode (in seconds). Negative value will not " "restrict the runtime duration."); DEFINE_string( prediction_offline_bags, "", "a list of bag files or directories for offline mode. The items need to be " "separated by colon ':'. If this value is not set, the prediction module " "will use the listen to published ros topic mode."); DEFINE_int32(prediction_offline_mode, 0, "0: online mode, no dump file" "1: dump feature proto to feature.*.bin" "2: dump data for learning to datalearn.*.bin" "3: dump predicted trajectory to predict_result.*.bin" "4: dump frame environment info to frame_env.*.bin" "5: dump data for tuning to datatuning.*.bin"); DEFINE_bool(enable_multi_thread, true, "If enable multi-thread."); DEFINE_int32(max_thread_num, 8, "Maximal number of threads."); DEFINE_int32(max_caution_thread_num, 2, "Maximal number of threads for caution obstacles."); DEFINE_bool(enable_async_draw_base_image, true, "If enable async to draw base image"); DEFINE_bool(use_cuda, true, "If use cuda for torch."); // Bag replay timestamp gap DEFINE_double(replay_timestamp_gap, 10.0, "Max timestamp gap for rosbag replay"); DEFINE_int32(max_num_dump_feature, 10000, "Max number of features to dump"); DEFINE_int32(max_num_dump_dataforlearn, 5000, "Max number of dataforlearn to dump"); // Submodules DEFINE_bool(use_lego, false, "If use lego architecture"); DEFINE_string(container_topic_name, "/apollo/prediction/container", "Container topic name"); DEFINE_string(adccontainer_topic_name, "/apollo/prediction/adccontainer", "ADC Container topic name"); DEFINE_string(evaluator_topic_name, "/apollo/prediction/evaluator", "Evaluator topic name"); DEFINE_string(container_submodule_name, "container_submodule", "Container submodule name"); DEFINE_string(evaluator_submodule_name, "evaluator_submodule", "Evaluator submodule name"); DEFINE_string(perception_obstacles_topic_name, "/apollo/prediction/perception_obstacles", "Internal topic of perception obstacles"); // VectorNet DEFINE_string(prediction_target_file, "/apollo/data/train/test.pb.txt", "VectorNet target pb file name"); DEFINE_string(world_coordinate_file, "/apollo/data/world_coord.bin", "VectorNet world coordinate file name"); DEFINE_string(prediction_target_dir, "/apollo/data/train/", "VectorNet target dir"); DEFINE_double(obstacle_x, 0.0, "obstacle position x"); DEFINE_double(obstacle_y, 0.0, "obstacle position y"); DEFINE_double(obstacle_phi, 0.0, "obstacle heading phi"); DEFINE_double(road_distance, 100.0, "road distance within which the points are got"); DEFINE_double(point_distance, 5.0, "sampling distance of two points");
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_util_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/prediction/common/prediction_util.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { namespace math_util { TEST(PredictionUtilTest, normalize) { double value = 3.0; double mean = 2.0; double std_dev = 0.01; EXPECT_DOUBLE_EQ(Normalize(value, mean, std_dev), 99.999999); } TEST(PredictionUtilTest, relu) { double value = 2.0; EXPECT_DOUBLE_EQ(Relu(value), 2.0); value = -3.0; EXPECT_DOUBLE_EQ(Relu(value), 0.0); } TEST(PredictionUtilTest, softmax) { std::vector<double> value = {0.0, 10.0, 100.0}; std::vector<double> result = Softmax(value); EXPECT_NEAR(result[0], 0.0, 0.001); EXPECT_NEAR(result[1], 0.0, 0.001); EXPECT_NEAR(result[2], 1.0, 0.001); } TEST(PredictionUtilTest, softmax_balanced) { std::vector<double> value = {10.0, 10.0, 10.0}; std::vector<double> result = Softmax(value); EXPECT_NEAR(result[0], 0.3333, 0.001); EXPECT_NEAR(result[1], 0.3333, 0.001); EXPECT_NEAR(result[2], 0.3333, 0.001); } TEST(PredictionUtilTest, solvable_quadratic_equation) { std::vector<double> coefficients = {5.0, 6.0, 1.0}; std::pair<double, double> roots; EXPECT_EQ(SolveQuadraticEquation(coefficients, &roots), 0); EXPECT_DOUBLE_EQ(roots.first, -0.2); EXPECT_DOUBLE_EQ(roots.second, -1.0); } TEST(PredictionUtilTest, non_solvable_quadratic_equation) { std::vector<double> coefficients = {5.0, 2.0, 1.0}; std::pair<double, double> roots; EXPECT_EQ(SolveQuadraticEquation(coefficients, &roots), -1); } TEST(PredictionUtilTest, solve_cubic_polynomial_and_evaluate) { std::array<double, 2> start = {2.0, 3.0}; std::array<double, 2> end = {8.0, 1.0}; double param = 5.0; auto coefs = ComputePolynomial<3>(start, end, param); EXPECT_DOUBLE_EQ(EvaluateCubicPolynomial(coefs, 0.0, 0, param, 1.0), start[0]); EXPECT_DOUBLE_EQ(EvaluateCubicPolynomial(coefs, 0.0, 1, param, 1.0), start[1]); EXPECT_DOUBLE_EQ(EvaluateCubicPolynomial(coefs, param, 0, param, 1.0), end[0]); EXPECT_DOUBLE_EQ(EvaluateCubicPolynomial(coefs, param, 1, param, 1.0), end[1]); } } // namespace math_util namespace predictor_util { using ::apollo::common::TrajectoryPoint; TEST(PredictionUtilTest, translate_point) { double x = 1.0; double y = 2.0; TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_x(1.0); trajectory_point.mutable_path_point()->set_y(1.0); TranslatePoint(x, y, &trajectory_point); EXPECT_DOUBLE_EQ(trajectory_point.path_point().x(), 2.0); EXPECT_DOUBLE_EQ(trajectory_point.path_point().y(), 3.0); } } // namespace predictor_util } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/semantic_map.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *implied. See the License for the specific language governing *permissions and limitations under the License. *****************************************************************************/ #pragma once #include <future> #include <unordered_map> #include "opencv2/opencv.hpp" #include "cyber/common/macros.h" #include "modules/common_msgs/prediction_msgs/feature.pb.h" namespace apollo { namespace prediction { class SemanticMap { public: SemanticMap(); virtual ~SemanticMap() = default; void Init(); void RunCurrFrame( const std::unordered_map<int, ObstacleHistory>& obstacle_id_history_map); bool GetMapById(const int obstacle_id, cv::Mat* feature_map); private: cv::Point2i GetTransPoint(const double x, const double y, const double base_x, const double base_y) { return cv::Point2i(static_cast<int>((x - base_x) / 0.1), static_cast<int>(2000 - (y - base_y) / 0.1)); } void DrawBaseMap(const double x, const double y, const double base_x, const double base_y); void DrawBaseMapThread(); void DrawRoads(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color = cv::Scalar(64, 64, 64)); void DrawJunctions(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color = cv::Scalar(128, 128, 128)); void DrawCrosswalks(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color = cv::Scalar(192, 192, 192)); void DrawLanes(const common::PointENU& center_point, const double base_x, const double base_y, const cv::Scalar& color = cv::Scalar(255, 255, 255)); cv::Scalar HSVtoRGB(double H = 1.0, double S = 1.0, double V = 1.0); void DrawRect(const Feature& feature, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img); void DrawPoly(const Feature& feature, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img); void DrawHistory(const ObstacleHistory& history, const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img); // Draw adc trajectory in semantic map void DrawADCTrajectory(const cv::Scalar& color, const double base_x, const double base_y, cv::Mat* img); cv::Mat CropArea(const cv::Mat& input_img, const cv::Point2i& center_point, const double heading); cv::Mat CropByHistory(const ObstacleHistory& history, const cv::Scalar& color, const double base_x, const double base_y); private: // base_image, base_x, and base_y to be updated by async thread cv::Mat base_img_; double base_x_ = 0.0; double base_y_ = 0.0; std::mutex draw_base_map_thread_mutex_; // base_image, base_x, and base_y to be used in the current cycle cv::Mat curr_img_; double curr_base_x_ = 0.0; double curr_base_y_ = 0.0; std::unordered_map<int, ObstacleHistory> obstacle_id_history_map_; Feature ego_feature_; std::future<void> task_future_; bool started_drawing_ = false; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/feature_output_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/prediction/common/feature_output.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { class FeatureOutputTest : public ::testing::Test { public: void SetUp() override { FeatureOutput::Ready(); } }; TEST_F(FeatureOutputTest, get_ready) { EXPECT_TRUE(FeatureOutput::Ready()); EXPECT_EQ(0, FeatureOutput::Size()); } TEST_F(FeatureOutputTest, insertion) { Feature feature; for (int i = 0; i < 3; ++i) { Feature feature; FeatureOutput::InsertFeatureProto(feature); } EXPECT_EQ(3, FeatureOutput::Size()); } TEST_F(FeatureOutputTest, clear) { Feature feature; for (int i = 0; i < 3; ++i) { Feature feature; FeatureOutput::InsertFeatureProto(feature); } FeatureOutput::Clear(); EXPECT_EQ(0, FeatureOutput::Size()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/environment_features.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 <string> #include <unordered_set> #include <utility> #include <vector> #include "modules/common_msgs/basic_msgs/geometry.pb.h" namespace apollo { namespace prediction { class EnvironmentFeatures { public: EnvironmentFeatures() = default; virtual ~EnvironmentFeatures() = default; void set_ego_position(const double x, const double y); const common::Point3D& get_ego_position() const; void set_ego_speed(const double ego_speed); double get_ego_speed() const; void set_ego_acceleration(const double ego_acceleration); double get_ego_acceleration() const; void set_ego_heading(const double ego_heading); double get_ego_heading() const; bool has_ego_lane() const; void reset_ego_lane(); void SetEgoLane(const std::string& lane_id, const double lane_s); std::pair<std::string, double> GetEgoLane() const; bool has_left_neighbor_lane() const; void reset_left_neighbor_lane(); void SetLeftNeighborLane(const std::string& lane_id, const double lane_s); std::pair<std::string, double> GetLeftNeighborLane() const; bool has_right_neighbor_lane() const; void reset_right_neighbor_lane(); void SetRightNeighborLane(const std::string& lane_id, const double lane_s); std::pair<std::string, double> GetRightNeighborLane() const; bool has_front_junction() const; void reset_front_junction(); void SetFrontJunction(const std::string& junction_id, const double dist); std::pair<std::string, double> GetFrontJunction() const; void AddObstacleId(const int obstacle_id); const std::vector<int>& get_obstacle_ids() const; const std::unordered_set<std::string>& nonneglectable_reverse_lanes() const; void AddNonneglectableReverseLanes(const std::string& lane_id); bool RemoveNonneglectableReverseLanes(const std::string& lane_id); private: common::Point3D ego_position_; double ego_speed_ = 0.0; double ego_acceleration_ = 0.0; double ego_heading_ = 0.0; bool has_ego_lane_ = false; std::string ego_lane_id_; double ego_lane_s_ = 0.0; bool has_left_neighbor_lane_ = false; std::string left_neighbor_lane_id_; double left_neighbor_lane_s_ = 0.0; bool has_right_neighbor_lane_ = false; std::string right_neighbor_lane_id_; double right_neighbor_lane_s_ = 0.0; bool has_front_junction_ = false; std::string front_junction_id_; double dist_to_front_junction_ = 0.0; std::vector<int> obstacle_ids_; std::unordered_set<std::string> nonneglectable_reverse_lanes_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/environment_features_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/environment_features.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { class EnvironmentFeaturesTest : public ::testing::Test { public: void SetUp() override {} }; TEST_F(EnvironmentFeaturesTest, EgoPosition) { EnvironmentFeatures environment_features; environment_features.set_ego_position(1.0, 2.0); const auto& ego_position = environment_features.get_ego_position(); EXPECT_DOUBLE_EQ(ego_position.x(), 1.0); EXPECT_DOUBLE_EQ(ego_position.y(), 2.0); } TEST_F(EnvironmentFeaturesTest, EgoSpeed) { EnvironmentFeatures environment_features; environment_features.set_ego_speed(1.0); EXPECT_DOUBLE_EQ(environment_features.get_ego_speed(), 1.0); } TEST_F(EnvironmentFeaturesTest, EgoAcceleration) { EnvironmentFeatures environment_features; environment_features.set_ego_acceleration(1.0); EXPECT_DOUBLE_EQ(environment_features.get_ego_acceleration(), 1.0); } TEST_F(EnvironmentFeaturesTest, EgoHeading) { EnvironmentFeatures environment_features; environment_features.set_ego_heading(1.0); EXPECT_DOUBLE_EQ(environment_features.get_ego_heading(), 1.0); } TEST_F(EnvironmentFeaturesTest, EgoLane) { EnvironmentFeatures environment_features; EXPECT_FALSE(environment_features.has_ego_lane()); environment_features.SetEgoLane("1-1", 1.0); EXPECT_TRUE(environment_features.has_ego_lane()); auto ego_lane = environment_features.GetEgoLane(); EXPECT_EQ(ego_lane.first, "1-1"); EXPECT_DOUBLE_EQ(ego_lane.second, 1.0); environment_features.reset_ego_lane(); EXPECT_FALSE(environment_features.has_ego_lane()); } TEST_F(EnvironmentFeaturesTest, LeftLane) { EnvironmentFeatures environment_features; EXPECT_FALSE(environment_features.has_left_neighbor_lane()); environment_features.SetLeftNeighborLane("1-1", 1.0); EXPECT_TRUE(environment_features.has_left_neighbor_lane()); auto left_lane = environment_features.GetLeftNeighborLane(); EXPECT_EQ(left_lane.first, "1-1"); EXPECT_DOUBLE_EQ(left_lane.second, 1.0); environment_features.reset_left_neighbor_lane(); EXPECT_FALSE(environment_features.has_left_neighbor_lane()); } TEST_F(EnvironmentFeaturesTest, RightLane) { EnvironmentFeatures environment_features; EXPECT_FALSE(environment_features.has_right_neighbor_lane()); environment_features.SetRightNeighborLane("1-1", 1.0); EXPECT_TRUE(environment_features.has_right_neighbor_lane()); auto right_lane = environment_features.GetRightNeighborLane(); EXPECT_EQ(right_lane.first, "1-1"); EXPECT_DOUBLE_EQ(right_lane.second, 1.0); environment_features.reset_right_neighbor_lane(); EXPECT_FALSE(environment_features.has_right_neighbor_lane()); } TEST_F(EnvironmentFeaturesTest, FrontJunction) { EnvironmentFeatures environment_features; EXPECT_FALSE(environment_features.has_front_junction()); environment_features.SetFrontJunction("2-1", 1.0); EXPECT_TRUE(environment_features.has_front_junction()); auto junction = environment_features.GetFrontJunction(); EXPECT_EQ(junction.first, "2-1"); EXPECT_DOUBLE_EQ(junction.second, 1.0); environment_features.reset_front_junction(); EXPECT_FALSE(environment_features.has_front_junction()); } TEST_F(EnvironmentFeaturesTest, Obstacles) { EnvironmentFeatures environment_features; environment_features.AddObstacleId(1); environment_features.AddObstacleId(2); EXPECT_EQ(environment_features.get_obstacle_ids().size(), 2); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/feature_output.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/prediction/common/feature_output.h" #include "absl/strings/str_cat.h" #include "cyber/common/file.h" #include "modules/common/util/util.h" #include "modules/prediction/common/prediction_system_gflags.h" namespace apollo { namespace prediction { using apollo::common::TrajectoryPoint; Features FeatureOutput::features_; ListDataForLearning FeatureOutput::list_data_for_learning_; ListPredictionResult FeatureOutput::list_prediction_result_; ListFrameEnv FeatureOutput::list_frame_env_; ListDataForTuning FeatureOutput::list_data_for_tuning_; std::size_t FeatureOutput::idx_feature_ = 0; std::size_t FeatureOutput::idx_learning_ = 0; std::size_t FeatureOutput::idx_prediction_result_ = 0; std::size_t FeatureOutput::idx_frame_env_ = 0; std::size_t FeatureOutput::idx_tuning_ = 0; std::mutex FeatureOutput::mutex_feature_; void FeatureOutput::Close() { ADEBUG << "Close feature output"; switch (FLAGS_prediction_offline_mode) { case 1: { WriteFeatureProto(); break; } case 2: { WriteDataForLearning(); break; } case 3: { WritePredictionResult(); break; } case 4: { WriteFrameEnv(); break; } case 5: { WriteDataForTuning(); break; } default: { // No data dump break; } } Clear(); } void FeatureOutput::Clear() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); idx_feature_ = 0; idx_learning_ = 0; idx_prediction_result_ = 0; idx_frame_env_ = 0; idx_tuning_ = 0; features_.Clear(); list_data_for_learning_.Clear(); list_prediction_result_.Clear(); list_frame_env_.Clear(); list_data_for_tuning_.Clear(); } bool FeatureOutput::Ready() { Clear(); return true; } void FeatureOutput::InsertFeatureProto(const Feature& feature) { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); features_.add_feature()->CopyFrom(feature); } void FeatureOutput::InsertDataForLearning( const Feature& feature, const std::vector<double>& feature_values, const std::string& category, const LaneSequence* lane_sequence_ptr) { const std::vector<std::string> dummy_string_feature_values; InsertDataForLearning(feature, feature_values, dummy_string_feature_values, category, lane_sequence_ptr); } void FeatureOutput::InsertDataForLearning( const Feature& feature, const std::vector<double>& feature_values, const std::vector<std::string>& string_feature_values, const std::string& category, const LaneSequence* lane_sequence_ptr) { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); DataForLearning* data_for_learning = list_data_for_learning_.add_data_for_learning(); data_for_learning->set_id(feature.id()); data_for_learning->set_timestamp(feature.timestamp()); *(data_for_learning->mutable_features_for_learning()) = { feature_values.begin(), feature_values.end()}; *(data_for_learning->mutable_string_features_for_learning()) = { string_feature_values.begin(), string_feature_values.end()}; data_for_learning->set_category(category); ADEBUG << "Insert [" << category << "] data for learning with size = " << feature_values.size(); if (lane_sequence_ptr != nullptr) { data_for_learning->set_lane_sequence_id( lane_sequence_ptr->lane_sequence_id()); } } void FeatureOutput::InsertPredictionResult( const Obstacle* obstacle, const PredictionObstacle& prediction_obstacle, const ObstacleConf& obstacle_conf, const Scenario& scenario) { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); PredictionResult* prediction_result = list_prediction_result_.add_prediction_result(); prediction_result->set_id(obstacle->id()); prediction_result->set_timestamp(prediction_obstacle.timestamp()); for (int i = 0; i < prediction_obstacle.trajectory_size(); ++i) { prediction_result->add_trajectory()->CopyFrom( prediction_obstacle.trajectory(i)); prediction_result->mutable_obstacle_conf()->CopyFrom(obstacle_conf); } // Insert the scenario that the single obstacle is in if (scenario.type() == Scenario::JUNCTION && obstacle->IsInJunction(scenario.junction_id())) { prediction_result->mutable_scenario()->set_type(Scenario::JUNCTION); } else if (obstacle->IsOnLane()) { prediction_result->mutable_scenario()->set_type(Scenario::CRUISE); } } void FeatureOutput::InsertFrameEnv(const FrameEnv& frame_env) { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); list_frame_env_.add_frame_env()->CopyFrom(frame_env); } void FeatureOutput::InsertDataForTuning( const Feature& feature, const std::vector<double>& feature_values, const std::string& category, const LaneSequence& lane_sequence, const std::vector<TrajectoryPoint>& adc_trajectory) { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); DataForTuning* data_for_tuning = list_data_for_tuning_.add_data_for_tuning(); data_for_tuning->set_id(feature.id()); data_for_tuning->set_timestamp(feature.timestamp()); *data_for_tuning->mutable_values_for_tuning() = {feature_values.begin(), feature_values.end()}; data_for_tuning->set_category(category); ADEBUG << "Insert [" << category << "] data for tuning with size = " << feature_values.size(); data_for_tuning->set_lane_sequence_id(lane_sequence.lane_sequence_id()); for (const auto& adc_traj_point : adc_trajectory) { data_for_tuning->add_adc_trajectory_point()->CopyFrom(adc_traj_point); } } void FeatureOutput::WriteFeatureProto() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); if (features_.feature().empty()) { ADEBUG << "Skip writing empty feature."; } else { const std::string file_name = absl::StrCat( FLAGS_prediction_data_dir, "/feature.", idx_feature_, ".bin"); cyber::common::SetProtoToBinaryFile(features_, file_name); features_.Clear(); ++idx_feature_; } } void FeatureOutput::WriteDataForLearning() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); if (list_data_for_learning_.data_for_learning().empty()) { ADEBUG << "Skip writing empty data_for_learning."; } else { const std::string file_name = absl::StrCat( FLAGS_prediction_data_dir, "/datalearn.", idx_learning_, ".bin"); cyber::common::SetProtoToBinaryFile(list_data_for_learning_, file_name); list_data_for_learning_.Clear(); ++idx_learning_; } } void FeatureOutput::WritePredictionResult() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); if (list_prediction_result_.prediction_result().empty()) { ADEBUG << "Skip writing empty prediction_result."; } else { const std::string file_name = absl::StrCat(FLAGS_prediction_data_dir, "/prediction_result.", idx_prediction_result_, ".bin"); cyber::common::SetProtoToBinaryFile(list_prediction_result_, file_name); list_prediction_result_.Clear(); ++idx_prediction_result_; } } void FeatureOutput::WriteFrameEnv() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); if (list_frame_env_.frame_env().empty()) { ADEBUG << "Skip writing empty prediction_result."; } else { const std::string file_name = absl::StrCat( FLAGS_prediction_data_dir, "/frame_env.", idx_frame_env_, ".bin"); cyber::common::SetProtoToBinaryFile(list_frame_env_, file_name); list_frame_env_.Clear(); ++idx_frame_env_; } } void FeatureOutput::WriteDataForTuning() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); if (list_data_for_tuning_.data_for_tuning().empty()) { ADEBUG << "Skip writing empty data_for_tuning."; return; } const std::string file_name = absl::StrCat( FLAGS_prediction_data_dir, "/datatuning.", idx_tuning_, ".bin"); cyber::common::SetProtoToBinaryFile(list_data_for_tuning_, file_name); list_data_for_tuning_.Clear(); ++idx_tuning_; } int FeatureOutput::Size() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); return features_.feature_size(); } int FeatureOutput::SizeOfDataForLearning() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); return list_data_for_learning_.data_for_learning_size(); } int FeatureOutput::SizeOfPredictionResult() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); return list_prediction_result_.prediction_result_size(); } int FeatureOutput::SizeOfFrameEnv() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); return list_frame_env_.frame_env_size(); } int FeatureOutput::SizeOfDataForTuning() { UNIQUE_LOCK_MULTITHREAD(mutex_feature_); return list_data_for_tuning_.data_for_tuning_size(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_thread_pool_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/prediction/common/prediction_thread_pool.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { TEST(PredictionThreadPoolTest, global_for_each) { std::vector<int> expect = {1, 2, 3, 4, 5, 6, 7, 8}; std::vector<int> real = {1, 2, 3, 4, 5, 6, 7, 8}; auto incr = [](int& input) { ++input; }; std::for_each(expect.begin(), expect.end(), incr); PredictionThreadPool::ForEach(real.begin(), real.end(), incr); EXPECT_EQ(expect, real); } /* TODO(kechxu) uncomment this when deadlock issue is fixed TEST(PredictionThreadPoolTest, avoid_deadlock) { std::vector<int> expect = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; std::vector<int> real = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; std::for_each(expect.begin(), expect.end(), [](int& input) { std::vector<int> vec = {1, 2, 3, 4}; std::for_each(vec.begin(), vec.end(), [](int& v) { ++v; }); input = std::accumulate(vec.begin(), vec.end(), input); }); EXPECT_EQ(0, PredictionThreadPool::s_thread_pool_level); PredictionThreadPool::ForEach(real.begin(), real.end(), [](int& input) { EXPECT_EQ(1, PredictionThreadPool::s_thread_pool_level); std::vector<int> vec = {1, 2, 3, 4}; PredictionThreadPool::ForEach(vec.begin(), vec.end(), [](int& v) { ++v; EXPECT_EQ(2, PredictionThreadPool::s_thread_pool_level); }); input = std::accumulate(vec.begin(), vec.end(), input); }); EXPECT_EQ(expect, real); } */ } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/validation_checker_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/validation_checker.h" #include "gtest/gtest.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using ::apollo::common::TrajectoryPoint; class ValidationCheckerTest : public ::testing::Test { public: void SetUp() {} }; TEST_F(ValidationCheckerTest, valid_centripedal_acc) { FLAGS_centripedal_acc_threshold = 2.0; std::vector<TrajectoryPoint> trajectory_points(0); double theta = 0.0; double relative_time = 0.1; for (int i = 0; i < 3; ++i) { TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_theta(theta); trajectory_point.set_v(1.0); trajectory_point.set_relative_time(i * relative_time); theta += 0.1; trajectory_points.emplace_back(std::move(trajectory_point)); } EXPECT_EQ(trajectory_points.size(), 3); EXPECT_TRUE( ValidationChecker::ValidCentripetalAcceleration(trajectory_points)); } TEST_F(ValidationCheckerTest, invalid_centripedal_acc) { FLAGS_centripedal_acc_threshold = 2.0; std::vector<TrajectoryPoint> trajectory_points(0); double theta = 0.0; double relative_time = 0.1; for (int i = 0; i < 3; ++i) { TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_theta(theta); trajectory_point.set_v(1.0); trajectory_point.set_relative_time(i * relative_time); theta += 3.14; trajectory_points.emplace_back(std::move(trajectory_point)); } EXPECT_EQ(trajectory_points.size(), 3); EXPECT_TRUE( !ValidationChecker::ValidCentripetalAcceleration(trajectory_points)); } TEST_F(ValidationCheckerTest, valid_trajectory_point) { TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->set_x(0.0); trajectory_point.mutable_path_point()->set_y(0.0); trajectory_point.mutable_path_point()->set_theta(0.0); trajectory_point.set_v(0.0); trajectory_point.set_a(0.0); trajectory_point.set_relative_time(0.0); EXPECT_TRUE(ValidationChecker::ValidTrajectoryPoint(trajectory_point)); } TEST_F(ValidationCheckerTest, invalid_trajectory_point) { TrajectoryPoint trajectory_point; EXPECT_FALSE(ValidationChecker::ValidTrajectoryPoint(trajectory_point)); trajectory_point.mutable_path_point()->set_x( std::numeric_limits<double>::quiet_NaN()); trajectory_point.mutable_path_point()->set_y(0.0); trajectory_point.mutable_path_point()->set_theta(0.0); trajectory_point.set_v(0.0); trajectory_point.set_a(0.0); trajectory_point.set_relative_time(0.0); EXPECT_FALSE(ValidationChecker::ValidTrajectoryPoint(trajectory_point)); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/junction_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 <algorithm> #include <limits> #include <queue> #include <unordered_set> #include <utility> #include "modules/prediction/common/junction_analyzer.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::common::PointENU; using apollo::hdmap::JunctionInfo; using apollo::hdmap::LaneInfo; using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>; void JunctionAnalyzer::Init(const std::string& junction_id) { if (junction_info_ptr_ != nullptr && junction_info_ptr_->id().id() == junction_id) { return; } Clear(); junction_info_ptr_ = PredictionMap::JunctionById(junction_id); SetAllJunctionExits(); } void JunctionAnalyzer::Clear() { // Clear all data junction_info_ptr_ = nullptr; junction_exits_.clear(); junction_features_.clear(); } void JunctionAnalyzer::SetAllJunctionExits() { CHECK_NOTNULL(junction_info_ptr_); // Go through everything that the junction overlaps with. for (const auto& overlap_id : junction_info_ptr_->junction().overlap_id()) { auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id()); if (overlap_info_ptr == nullptr) { continue; } // Find the lane-segments that are overlapping, yet also extends out of // the junction area. Those are the junction-exit-lanes. for (const auto& object : overlap_info_ptr->overlap().object()) { if (object.has_lane_overlap_info()) { const std::string& lane_id = object.id().id(); auto lane_info_ptr = PredictionMap::LaneById(lane_id); double s = object.lane_overlap_info().end_s(); if (s + FLAGS_junction_exit_lane_threshold < lane_info_ptr->total_length()) { JunctionExit junction_exit; PointENU position = lane_info_ptr->GetSmoothPoint(s); junction_exit.set_exit_lane_id(lane_id); junction_exit.mutable_exit_position()->set_x(position.x()); junction_exit.mutable_exit_position()->set_y(position.y()); junction_exit.set_exit_heading(lane_info_ptr->Heading(s)); junction_exit.set_exit_width(lane_info_ptr->GetWidth(s)); // add junction_exit to hashtable junction_exits_[lane_id] = junction_exit; } } } } } std::vector<JunctionExit> JunctionAnalyzer::GetJunctionExits( const std::string& start_lane_id) { // TODO(hongyi) make this a gflag int max_search_level = 6; std::vector<JunctionExit> junction_exits; std::queue<std::pair<ConstLaneInfoPtr, int>> lane_info_queue; lane_info_queue.emplace(PredictionMap::LaneById(start_lane_id), 0); std::unordered_set<std::string> visited_exit_lanes; // Perform a BFS to find all exit lanes that can be connected through // this start_lane_id. while (!lane_info_queue.empty()) { ConstLaneInfoPtr curr_lane = lane_info_queue.front().first; int level = lane_info_queue.front().second; lane_info_queue.pop(); const std::string& curr_lane_id = curr_lane->id().id(); // Stop if this is already an exit lane. if (IsExitLane(curr_lane_id) && visited_exit_lanes.find(curr_lane_id) == visited_exit_lanes.end()) { junction_exits.push_back(junction_exits_[curr_lane_id]); visited_exit_lanes.insert(curr_lane_id); continue; } // Stop if reached max-search-level. if (level >= max_search_level) { continue; } for (const auto& succ_lane_id : curr_lane->lane().successor_id()) { ConstLaneInfoPtr succ_lane_ptr = PredictionMap::LaneById(succ_lane_id.id()); lane_info_queue.emplace(succ_lane_ptr, level + 1); } } return junction_exits; } const JunctionFeature& JunctionAnalyzer::GetJunctionFeature( const std::string& start_lane_id) { if (junction_features_.find(start_lane_id) != junction_features_.end()) { return junction_features_[start_lane_id]; } JunctionFeature junction_feature; junction_feature.set_junction_id(GetJunctionId()); junction_feature.set_junction_range(ComputeJunctionRange()); // Find all junction-exit-lanes that are successors of the start_lane_id. std::vector<JunctionExit> junction_exits = GetJunctionExits(start_lane_id); for (const auto& junction_exit : junction_exits) { junction_feature.add_junction_exit()->CopyFrom(junction_exit); } junction_feature.mutable_enter_lane()->set_lane_id(start_lane_id); junction_feature.add_start_lane_id(start_lane_id); junction_features_[start_lane_id] = junction_feature; return junction_features_[start_lane_id]; } JunctionFeature JunctionAnalyzer::GetJunctionFeature( const std::vector<std::string>& start_lane_ids) { JunctionFeature merged_junction_feature; bool initialized = false; std::unordered_map<std::string, JunctionExit> junction_exits_map; for (const std::string& start_lane_id : start_lane_ids) { JunctionFeature junction_feature = GetJunctionFeature(start_lane_id); if (!initialized) { merged_junction_feature.set_junction_id(junction_feature.junction_id()); merged_junction_feature.set_junction_range( junction_feature.junction_range()); initialized = true; } for (const JunctionExit& junction_exit : junction_feature.junction_exit()) { if (junction_exits_map.find(junction_exit.exit_lane_id()) == junction_exits_map.end()) { junction_exits_map[junction_exit.exit_lane_id()] = junction_exit; } } } for (const auto& exit : junction_exits_map) { merged_junction_feature.add_start_lane_id(exit.first); merged_junction_feature.add_junction_exit()->CopyFrom(exit.second); } return merged_junction_feature; } bool JunctionAnalyzer::IsExitLane(const std::string& lane_id) { return junction_exits_.find(lane_id) != junction_exits_.end(); } const std::string& JunctionAnalyzer::GetJunctionId() { CHECK_NOTNULL(junction_info_ptr_); return junction_info_ptr_->id().id(); } double JunctionAnalyzer::ComputeJunctionRange() { CHECK_NOTNULL(junction_info_ptr_); if (!junction_info_ptr_->junction().has_polygon() || junction_info_ptr_->junction().polygon().point_size() < 3) { AERROR << "Junction [" << GetJunctionId() << "] has not enough polygon points to compute range"; return FLAGS_defualt_junction_range; } double x_min = std::numeric_limits<double>::infinity(); double x_max = -std::numeric_limits<double>::infinity(); double y_min = std::numeric_limits<double>::infinity(); double y_max = -std::numeric_limits<double>::infinity(); for (const auto& point : junction_info_ptr_->junction().polygon().point()) { x_min = std::min(x_min, point.x()); x_max = std::max(x_max, point.x()); y_min = std::min(y_min, point.y()); y_max = std::max(y_max, point.y()); } double dx = std::abs(x_max - x_min); double dy = std::abs(y_max - y_min); double range = std::sqrt(dx * dx + dy * dy); return range; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_thread_pool.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 <future> #include <memory> #include <utility> #include <vector> #include "cyber/base/bounded_queue.h" #include "cyber/common/log.h" namespace apollo { namespace prediction { class BaseThreadPool { public: BaseThreadPool(int thread_num, int next_thread_pool_level); void Stop(); ~BaseThreadPool(); template <typename InputIter, typename F> void ForEach(InputIter begin, InputIter end, F f) { std::vector<std::future<void>> futures; for (auto iter = begin; iter != end; ++iter) { auto& elem = *iter; futures.emplace_back(this->Post([&] { f(elem); })); } for (auto& future : futures) { if (future.valid()) { future.get(); } else { AERROR << "Future is invalid."; } } } template <typename FuncType> std::future<typename std::result_of<FuncType()>::type> Post(FuncType&& func) { typedef typename std::result_of<FuncType()>::type ReturnType; typedef typename std::packaged_task<ReturnType()> TaskType; // Post requires that the functions in it are copy-constructible. // We used a shared pointer for the packaged_task, // Since it's only movable and non-copyable std::shared_ptr<TaskType> task = std::make_shared<TaskType>(std::move(func)); std::future<ReturnType> returned_future = task->get_future(); // Note: variables eg. `task` must be copied here because of the lifetime if (stopped_) { return std::future<ReturnType>(); } task_queue_.Enqueue([task]() { (*task)(); }); return returned_future; } static std::vector<int> THREAD_POOL_CAPACITY; private: std::vector<std::thread> workers_; apollo::cyber::base::BoundedQueue<std::function<void()>> task_queue_; std::atomic_bool stopped_; }; template <int LEVEL> class LevelThreadPool : public BaseThreadPool { public: static LevelThreadPool* Instance() { static LevelThreadPool<LEVEL> pool; return &pool; } private: LevelThreadPool() : BaseThreadPool(THREAD_POOL_CAPACITY[LEVEL], LEVEL + 1) { ADEBUG << "Level = " << LEVEL << "; thread pool capacity = " << THREAD_POOL_CAPACITY[LEVEL]; } }; class PredictionThreadPool { public: static BaseThreadPool* Instance(); static thread_local int s_thread_pool_level; template <typename InputIter, typename F> static void ForEach(InputIter begin, InputIter end, F f) { Instance()->ForEach(begin, end, f); } }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/message_process.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #pragma once #include <memory> #include <string> #include "cyber/proto/record.pb.h" #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/prediction_conf.pb.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" #include "modules/prediction/scenario/scenario_manager.h" #include "modules/common_msgs/storytelling_msgs/story.pb.h" namespace apollo { namespace prediction { class MessageProcess { public: MessageProcess() = delete; static bool Init(ContainerManager *container_manager, EvaluatorManager *evaluator_manager, PredictorManager *predictor_manager, const PredictionConf &prediction_conf); static bool InitContainers(ContainerManager *container_manager); static bool InitEvaluators(EvaluatorManager *evaluator_manager, const PredictionConf &prediction_conf); static bool InitPredictors(PredictorManager *predictor_manager, const PredictionConf &prediction_conf); static void ContainerProcess( const std::shared_ptr<ContainerManager> &container_manager, const perception::PerceptionObstacles &perception_obstacles, ScenarioManager *scenario_manger); static void OnPerception( const perception::PerceptionObstacles &perception_obstacles, const std::shared_ptr<ContainerManager> &container_manager, EvaluatorManager *evaluator_manager, PredictorManager *predictor_manager, ScenarioManager *scenario_manager, PredictionObstacles *const prediction_obstacles); static void OnLocalization( ContainerManager *container_manager, const localization::LocalizationEstimate &localization); static void OnPlanning(ContainerManager *container_manager, const planning::ADCTrajectory &adc_trajectory); static void OnStoryTelling(ContainerManager *container_manager, const storytelling::Stories &story); static void ProcessOfflineData( const PredictionConf &prediction_conf, const std::shared_ptr<ContainerManager> &container_manager, EvaluatorManager *evaluator_manager, PredictorManager *predictor_manager, ScenarioManager *scenario_manager, const std::string &record_filepath); }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/road_graph.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/road_graph.h" #include <algorithm> #include <set> #include <utility> #include "modules/prediction/common/prediction_constants.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_system_gflags.h" namespace apollo { namespace prediction { namespace { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::hdmap::Lane; using apollo::hdmap::LaneInfo; // Custom helper functions for sorting purpose. bool HeadingIsAtLeft(const std::vector<double>& heading1, const std::vector<double>& heading2, const size_t idx) { if (idx >= heading1.size() || idx >= heading2.size()) { return true; } const double angle = apollo::common::math::NormalizeAngle(heading1[idx] - heading2[idx]); if (angle > 0.0) { return true; } else if (angle < 0.0) { return false; } return HeadingIsAtLeft(heading1, heading2, idx + 1); } int ConvertTurnTypeToDegree(const Lane& lane) { // Sanity checks. if (!lane.has_turn()) { return 0; } // Assign a number to measure how much it is bent to the left. switch (lane.turn()) { case Lane::NO_TURN: return 0; case Lane::LEFT_TURN: return 1; case Lane::U_TURN: return 2; default: break; } return -1; } bool IsAtLeft(std::shared_ptr<const LaneInfo> lane1, std::shared_ptr<const LaneInfo> lane2) { if (lane1->lane().has_turn() && lane2->lane().has_turn() && lane1->lane().turn() != lane2->lane().turn()) { int degree_to_left_1 = ConvertTurnTypeToDegree(lane1->lane()); int degree_to_left_2 = ConvertTurnTypeToDegree(lane2->lane()); return degree_to_left_1 > degree_to_left_2; } return HeadingIsAtLeft(lane1->headings(), lane2->headings(), 0); } } // namespace RoadGraph::RoadGraph(const double start_s, const double length, const bool consider_divide, std::shared_ptr<const LaneInfo> lane_info_ptr) : start_s_(start_s), length_(length), consider_divide_(consider_divide), lane_info_ptr_(lane_info_ptr) {} Status RoadGraph::BuildLaneGraph(LaneGraph* const lane_graph_ptr) { // Sanity checks. if (length_ < 0.0 || lane_info_ptr_ == nullptr) { const auto error_msg = absl::StrCat( "Invalid road graph settings. Road graph length = ", length_); AERROR << error_msg; return Status(ErrorCode::PREDICTION_ERROR, error_msg); } if (lane_graph_ptr == nullptr) { const auto error_msg = "Invalid input lane graph."; AERROR << error_msg; return Status(ErrorCode::PREDICTION_ERROR, error_msg); } // Run the recursive function to perform DFS. std::list<LaneSegment> lane_segments; double accumulated_s = 0.0; ConstructLaneSequence(accumulated_s, start_s_, lane_info_ptr_, FLAGS_road_graph_max_search_horizon, consider_divide_, &lane_segments, lane_graph_ptr); return Status::OK(); } Status RoadGraph::BuildLaneGraphBidirection(LaneGraph* const lane_graph_ptr) { // Sanity checks. if (length_ < 0.0 || lane_info_ptr_ == nullptr) { const auto error_msg = absl::StrCat( "Invalid road graph settings. Road graph length = ", length_); AERROR << error_msg; return Status(ErrorCode::PREDICTION_ERROR, error_msg); } if (lane_graph_ptr == nullptr) { const auto error_msg = "Invalid input lane graph."; AERROR << error_msg; return Status(ErrorCode::PREDICTION_ERROR, error_msg); } // Run the recursive function to perform DFS. std::list<LaneSegment> lane_segments; LaneGraph lane_graph_successor; ConstructLaneSequence(true, 0.0, start_s_, lane_info_ptr_, FLAGS_road_graph_max_search_horizon, consider_divide_, &lane_segments, &lane_graph_successor); lane_segments.clear(); LaneGraph lane_graph_predecessor; length_ = length_ / 2.0; ConstructLaneSequence(false, 0.0, start_s_, lane_info_ptr_, FLAGS_road_graph_max_search_horizon, consider_divide_, &lane_segments, &lane_graph_predecessor); *lane_graph_ptr = CombineLaneGraphs(lane_graph_predecessor, lane_graph_successor); return Status::OK(); } LaneGraph RoadGraph::CombineLaneGraphs(const LaneGraph& lane_graph_predecessor, const LaneGraph& lane_graph_successor) { LaneGraph final_lane_graph; for (const auto& lane_sequence_pre : lane_graph_predecessor.lane_sequence()) { const auto& ending_lane_segment = lane_sequence_pre.lane_segment( lane_sequence_pre.lane_segment_size() - 1); for (const auto& lane_sequence_suc : lane_graph_successor.lane_sequence()) { if (lane_sequence_suc.lane_segment(0).lane_id() == ending_lane_segment.lane_id()) { LaneSequence* lane_sequence = final_lane_graph.add_lane_sequence(); for (const auto& it : lane_sequence_pre.lane_segment()) { *(lane_sequence->add_lane_segment()) = it; } lane_sequence ->mutable_lane_segment(lane_sequence->lane_segment_size() - 1) ->set_end_s(lane_sequence_suc.lane_segment(0).end_s()); lane_sequence ->mutable_lane_segment(lane_sequence->lane_segment_size() - 1) ->set_adc_s(lane_sequence_suc.lane_segment(0).start_s()); lane_sequence->set_adc_lane_segment_idx( lane_sequence->lane_segment_size() - 1); for (int i = 1; i < lane_sequence_suc.lane_segment_size(); ++i) { *(lane_sequence->add_lane_segment()) = lane_sequence_suc.lane_segment(i); } } } } return final_lane_graph; } bool RoadGraph::IsOnLaneGraph(std::shared_ptr<const LaneInfo> lane_info_ptr, const LaneGraph& lane_graph) { if (!lane_graph.IsInitialized()) { return false; } for (const auto& lane_sequence : lane_graph.lane_sequence()) { for (const auto& lane_segment : lane_sequence.lane_segment()) { if (lane_segment.has_lane_id() && lane_segment.lane_id() == lane_info_ptr->id().id()) { return true; } } } return false; } void RoadGraph::ConstructLaneSequence( const double accumulated_s, const double curr_lane_seg_s, std::shared_ptr<const LaneInfo> lane_info_ptr, const int graph_search_horizon, const bool consider_lane_split, std::list<LaneSegment>* const lane_segments, LaneGraph* const lane_graph_ptr) const { ConstructLaneSequence(true, accumulated_s, curr_lane_seg_s, lane_info_ptr, graph_search_horizon, consider_lane_split, lane_segments, lane_graph_ptr); } void RoadGraph::ConstructLaneSequence( const bool search_forward_direction, const double accumulated_s, const double curr_lane_seg_s, std::shared_ptr<const LaneInfo> lane_info_ptr, const int graph_search_horizon, const bool consider_lane_split, std::list<LaneSegment>* const lane_segments, LaneGraph* const lane_graph_ptr) const { // Sanity checks. if (lane_info_ptr == nullptr) { AERROR << "Invalid lane."; return; } if (graph_search_horizon < 0) { AERROR << "The lane search has already reached the limits"; AERROR << "Possible map error found!"; return; } // Create a new lane_segment based on the current lane_info_ptr. double curr_s = curr_lane_seg_s >= 0.0 ? curr_lane_seg_s : lane_info_ptr->total_length(); LaneSegment lane_segment; lane_segment.set_adc_s(curr_s); lane_segment.set_lane_id(lane_info_ptr->id().id()); lane_segment.set_lane_turn_type( PredictionMap::LaneTurnType(lane_info_ptr->id().id())); lane_segment.set_total_length(lane_info_ptr->total_length()); if (search_forward_direction) { lane_segment.set_start_s(curr_s); lane_segment.set_end_s(std::fmin(curr_s + length_ - accumulated_s, lane_info_ptr->total_length())); } else { lane_segment.set_start_s( std::fmax(0.0, curr_s - (length_ - accumulated_s))); lane_segment.set_end_s(curr_s); } if (search_forward_direction) { lane_segments->push_back(std::move(lane_segment)); } else { lane_segments->push_front(std::move(lane_segment)); } // End condition: if search reached the maximum search distance, // or if there is no more successor lane_segment. if (search_forward_direction) { if (lane_segments->back().end_s() < lane_info_ptr->total_length() || lane_info_ptr->lane().successor_id().empty()) { LaneSequence* sequence = lane_graph_ptr->add_lane_sequence(); for (const auto& it : *lane_segments) { *(sequence->add_lane_segment()) = it; } lane_segments->pop_back(); return; } } else { if (lane_segments->front().start_s() > 0.0 || lane_info_ptr->lane().predecessor_id().empty()) { LaneSequence* sequence = lane_graph_ptr->add_lane_sequence(); for (const auto& it : *lane_segments) { *(sequence->add_lane_segment()) = it; } lane_segments->pop_front(); return; } } // Otherwise, continue searching for subsequent lane_segments. double new_accumulated_s = 0.0; double new_lane_seg_s = 0.0; std::vector<std::shared_ptr<const hdmap::LaneInfo>> candidate_lanes; std::set<std::string> set_lane_ids; if (search_forward_direction) { new_accumulated_s = accumulated_s + lane_info_ptr->total_length() - curr_s; // Reundancy removal. for (const auto& successor_lane_id : lane_info_ptr->lane().successor_id()) { set_lane_ids.insert(successor_lane_id.id()); } for (const auto& unique_id : set_lane_ids) { candidate_lanes.push_back(PredictionMap::LaneById(unique_id)); } // Sort the successor lane_segments from left to right. std::sort(candidate_lanes.begin(), candidate_lanes.end(), IsAtLeft); // Based on other conditions, select what successor lanes should be used. if (!consider_lane_split) { candidate_lanes = { PredictionMap::LaneWithSmallestAverageCurvature(candidate_lanes)}; } } else { new_accumulated_s = accumulated_s + curr_s; new_lane_seg_s = -0.1; // Redundancy removal. for (const auto& predecessor_lane_id : lane_info_ptr->lane().predecessor_id()) { set_lane_ids.insert(predecessor_lane_id.id()); } for (const auto& unique_id : set_lane_ids) { candidate_lanes.push_back(PredictionMap::LaneById(unique_id)); } } bool consider_further_lane_split = !search_forward_direction || (FLAGS_prediction_offline_mode == PredictionConstants::kDumpFeatureProto) || (FLAGS_prediction_offline_mode == PredictionConstants::kDumpDataForLearning) || (consider_lane_split && candidate_lanes.size() == 1); // Recursively expand lane-sequence. for (const auto& candidate_lane : candidate_lanes) { ConstructLaneSequence(search_forward_direction, new_accumulated_s, new_lane_seg_s, candidate_lane, graph_search_horizon - 1, consider_further_lane_split, lane_segments, lane_graph_ptr); } if (search_forward_direction) { lane_segments->pop_back(); } else { lane_segments->pop_front(); } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/validation_checker.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/prediction/common/validation_checker.h" #include "modules/common/math/math_utils.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using common::TrajectoryPoint; double ValidationChecker::ProbabilityByCentripetalAcceleration( const LaneSequence& lane_sequence, const double speed) { double centripetal_acc_cost_sum = 0.0; double centripetal_acc_cost_sqr_sum = 0.0; for (int i = 0; i < lane_sequence.path_point_size(); ++i) { const auto& path_point = lane_sequence.path_point(i); double centripetal_acc = speed * speed * std::fabs(path_point.kappa()); double centripetal_acc_cost = centripetal_acc / FLAGS_centripedal_acc_threshold; centripetal_acc_cost_sum += centripetal_acc_cost; centripetal_acc_cost_sqr_sum += centripetal_acc_cost * centripetal_acc_cost; } double mean_cost = centripetal_acc_cost_sqr_sum / (centripetal_acc_cost_sum + FLAGS_double_precision); return std::exp(-FLAGS_centripetal_acc_coeff * mean_cost); } bool ValidationChecker::ValidCentripetalAcceleration( const std::vector<TrajectoryPoint>& trajectory_points) { for (size_t i = 0; i + 1 < trajectory_points.size(); ++i) { const auto& p0 = trajectory_points[i]; const auto& p1 = trajectory_points[i + 1]; double time_diff = std::abs(p1.relative_time() - p0.relative_time()); if (time_diff < FLAGS_double_precision) { continue; } double theta_diff = std::abs(common::math::NormalizeAngle( p1.path_point().theta() - p0.path_point().theta())); double v = (p0.v() + p1.v()) * 0.5; double angular_a = v * theta_diff / time_diff; if (angular_a > FLAGS_centripedal_acc_threshold) { return false; } } return true; } bool ValidationChecker::ValidTrajectoryPoint( const TrajectoryPoint& trajectory_point) { return trajectory_point.has_path_point() && (!std::isnan(trajectory_point.path_point().x())) && (!std::isnan(trajectory_point.path_point().y())) && (!std::isnan(trajectory_point.path_point().theta())) && (!std::isnan(trajectory_point.v())) && (!std::isnan(trajectory_point.a())) && (!std::isnan(trajectory_point.relative_time())); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_gflags.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "gflags/gflags.h" DECLARE_double(double_precision); // prediction trajectory and dynamic model DECLARE_double(prediction_trajectory_time_length); DECLARE_double(prediction_trajectory_time_resolution); DECLARE_double(min_prediction_trajectory_spatial_length); DECLARE_bool(enable_trajectory_validation_check); DECLARE_bool(enable_tracking_adaptation); DECLARE_double(vehicle_max_linear_acc); DECLARE_double(vehicle_min_linear_acc); DECLARE_double(vehicle_max_speed); // Tracking Adaptation DECLARE_double(max_tracking_time); DECLARE_double(max_tracking_dist); // Map DECLARE_double(lane_search_radius); DECLARE_double(lane_search_radius_in_junction); DECLARE_double(junction_search_radius); DECLARE_double(pedestrian_nearby_lane_search_radius); DECLARE_int32(road_graph_max_search_horizon); DECLARE_double(surrounding_lane_search_radius); // Semantic Map DECLARE_double(base_image_half_range); DECLARE_bool(enable_draw_adc_trajectory); DECLARE_bool(img_show_semantic_map); // Scenario DECLARE_double(junction_distance_threshold); DECLARE_bool(enable_all_junction); DECLARE_bool(enable_all_pedestrian_caution_in_front); DECLARE_bool(enable_rank_caution_obstacles); DECLARE_bool(enable_rank_interactive_obstacles); DECLARE_int32(caution_obs_max_nums); DECLARE_double(caution_distance_threshold); DECLARE_double(caution_search_distance_ahead); DECLARE_double(caution_search_distance_backward); DECLARE_double(caution_search_distance_backward_for_merge); DECLARE_double(caution_search_distance_backward_for_overlap); DECLARE_double(caution_pedestrian_approach_time); DECLARE_int32(interactive_obs_max_nums); DECLARE_double(interaction_distance_threshold); DECLARE_double(interaction_search_distance_ahead); DECLARE_double(interaction_search_distance_backward); DECLARE_double(interaction_search_distance_backward_for_merge); DECLARE_double(interaction_search_distance_backward_for_overlap); // Obstacle features DECLARE_int32(ego_vehicle_id); DECLARE_double(scan_length); DECLARE_double(scan_width); DECLARE_double(back_dist_ignore_ped); DECLARE_uint64(cruise_historical_frame_length); DECLARE_bool(enable_kf_tracking); DECLARE_double(max_angle_diff_to_adjust_velocity); DECLARE_double(q_var); DECLARE_double(r_var); DECLARE_double(p_var); DECLARE_double(go_approach_rate); DECLARE_double(cutin_approach_rate); DECLARE_int32(min_still_obstacle_history_length); DECLARE_int32(max_still_obstacle_history_length); DECLARE_double(still_obstacle_speed_threshold); DECLARE_double(still_pedestrian_speed_threshold); DECLARE_double(still_unknown_speed_threshold); DECLARE_double(still_obstacle_position_std); DECLARE_double(still_pedestrian_position_std); DECLARE_double(still_unknown_position_std); DECLARE_double(slow_obstacle_speed_threshold); DECLARE_double(max_history_time); DECLARE_double(target_lane_gap); DECLARE_double(dense_lane_gap); DECLARE_int32(max_num_current_lane); DECLARE_int32(max_num_nearby_lane); DECLARE_double(max_lane_angle_diff); DECLARE_int32(max_num_current_lane_in_junction); DECLARE_int32(max_num_nearby_lane_in_junction); DECLARE_double(max_lane_angle_diff_in_junction); DECLARE_double(coeff_mul_sigma); DECLARE_double(pedestrian_max_speed); DECLARE_double(pedestrian_max_acc); DECLARE_double(still_speed); DECLARE_string(evaluator_vehicle_mlp_file); DECLARE_string(torch_vehicle_jointly_model_file); DECLARE_string(torch_vehicle_jointly_model_cpu_file); DECLARE_string(torch_vehicle_junction_mlp_file); DECLARE_string(torch_vehicle_junction_map_file); DECLARE_string(torch_vehicle_semantic_lstm_file); DECLARE_string(torch_vehicle_semantic_lstm_cpu_file); DECLARE_string(torch_vehicle_cruise_go_file); DECLARE_string(torch_vehicle_cruise_cutin_file); DECLARE_string(torch_vehicle_lane_scanning_file); DECLARE_string(torch_vehicle_vectornet_file); DECLARE_string(torch_vehicle_vectornet_cpu_file); DECLARE_string(torch_pedestrian_interaction_position_embedding_file); DECLARE_string(torch_pedestrian_interaction_social_embedding_file); DECLARE_string(torch_pedestrian_interaction_single_lstm_file); DECLARE_string(torch_pedestrian_interaction_prediction_layer_file); DECLARE_string(torch_pedestrian_semantic_lstm_file); DECLARE_string(torch_pedestrian_semantic_lstm_cpu_file); DECLARE_string(torch_lane_aggregating_obstacle_encoding_file); DECLARE_string(torch_lane_aggregating_lane_encoding_file); DECLARE_string(torch_lane_aggregating_prediction_layer_file); DECLARE_string(evaluator_vehicle_rnn_file); DECLARE_string(evaluator_vehicle_cruise_mlp_file); DECLARE_int32(max_num_obstacles); DECLARE_double(valid_position_diff_threshold); DECLARE_double(valid_position_diff_rate_threshold); DECLARE_double(split_rate); DECLARE_double(rnn_min_lane_relatice_s); DECLARE_bool(adjust_velocity_by_obstacle_heading); DECLARE_bool(adjust_velocity_by_position_shift); DECLARE_bool(adjust_vehicle_heading_by_lane); DECLARE_double(heading_filter_param); DECLARE_uint64(max_num_lane_point); DECLARE_double(distance_threshold_to_junction_exit); DECLARE_double(angle_threshold_to_junction_exit); DECLARE_uint32(sample_size_for_average_lane_curvature); // Validation checker DECLARE_double(centripetal_acc_coeff); // Junction Scenario DECLARE_uint32(junction_historical_frame_length); DECLARE_double(junction_exit_lane_threshold); DECLARE_double(distance_beyond_junction); DECLARE_double(defualt_junction_range); DECLARE_double(distance_to_slow_down_at_stop_sign); // Evaluator DECLARE_double(time_to_center_if_not_reach); DECLARE_double(default_s_if_no_obstacle_in_lane_sequence); DECLARE_double(default_l_if_no_obstacle_in_lane_sequence); DECLARE_bool(enable_semantic_map); // Obstacle trajectory DECLARE_bool(enable_cruise_regression); DECLARE_double(lane_sequence_threshold_cruise); DECLARE_double(lane_sequence_threshold_junction); DECLARE_double(lane_change_dist); DECLARE_bool(enable_lane_sequence_acc); DECLARE_bool(enable_trim_prediction_trajectory); DECLARE_double(adc_trajectory_search_length); DECLARE_double(virtual_lane_radius); DECLARE_double(default_lateral_approach_speed); DECLARE_double(centripedal_acc_threshold); // move sequence prediction DECLARE_double(time_upper_bound_to_lane_center); DECLARE_double(time_lower_bound_to_lane_center); DECLARE_double(sample_time_gap); DECLARE_double(cost_alpha); DECLARE_double(default_time_to_lat_end_state); DECLARE_double(turning_curvature_lower_bound); DECLARE_double(turning_curvature_upper_bound); DECLARE_double(speed_at_lower_curvature); DECLARE_double(speed_at_upper_curvature); DECLARE_double(cost_function_alpha); DECLARE_double(cost_function_sigma); DECLARE_bool(use_bell_curve_for_cost_function); // interaction predictor DECLARE_bool(enable_interactive_tag); DECLARE_double(collision_cost_time_resolution); DECLARE_double(longitudinal_acceleration_cost_weight); DECLARE_double(centripedal_acceleration_cost_weight); DECLARE_double(collision_cost_weight); DECLARE_double(collision_cost_exp_coefficient); DECLARE_double(likelihood_exp_coefficient); // scenario feature extraction DECLARE_double(lane_distance_threshold); DECLARE_double(lane_angle_difference_threshold); // Trajectory evaluation DECLARE_double(distance_threshold_on_lane);
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") package(default_visibility = ["//visibility:public"]) PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""] cc_library( name = "prediction_gflags", srcs = ["libprediction_gflags.so"], hdrs = ["prediction_gflags.h"], deps = [ "@com_github_gflags_gflags//:gflags", ], alwayslink = True, ) cc_binary( name = "libprediction_gflags.so", srcs = ["prediction_gflags.cc", "prediction_gflags.h"], linkshared = True, linkstatic = True, deps = [ "@com_github_gflags_gflags//:gflags", ], ) install( name = "install", library_dest = "prediction/lib", targets = [ ":libprediction_gflags.so", ":libprediction_system_gflags.so" ], visibility = ["//visibility:public"], ) cc_binary( name = "libprediction_system_gflags.so", srcs = ["prediction_system_gflags.cc", "prediction_system_gflags.h"], linkshared = True, linkstatic = True, deps = [ "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "prediction_system_gflags", srcs = [":libprediction_system_gflags.so"], hdrs = ["prediction_system_gflags.h"], deps = [ "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "prediction_util", srcs = ["prediction_util.cc"], hdrs = ["prediction_util.h"], copts = PREDICTION_COPTS, deps = [ ":prediction_gflags", ":prediction_map", ], ) cc_test( name = "prediction_util_test", size = "small", srcs = ["prediction_util_test.cc"], deps = [ ":prediction_util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "prediction_map", srcs = ["prediction_map.cc"], hdrs = ["prediction_map.h"], copts = PREDICTION_COPTS, deps = [ ":prediction_gflags", "//modules/map/pnc_map", ], ) cc_test( name = "prediction_map_test", size = "small", srcs = ["prediction_map_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":kml_map_based_test", ":prediction_map", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "feature_output", srcs = ["feature_output.cc"], hdrs = ["feature_output.h"], copts = PREDICTION_COPTS, deps = [ "//modules/common/util", "//modules/prediction/common:prediction_gflags", "//modules/prediction/container/obstacles:obstacle", "//modules/prediction/proto:offline_features_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", ], ) cc_test( name = "feature_output_test", size = "small", srcs = ["feature_output_test.cc"], deps = [ ":feature_output", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "road_graph", srcs = ["road_graph.cc"], hdrs = ["road_graph.h"], copts = PREDICTION_COPTS, deps = [ ":prediction_map", "//modules/prediction/common:prediction_constants", "//modules/prediction/common:prediction_gflags", "//modules/prediction/common:prediction_system_gflags", "//modules/common_msgs/prediction_msgs:lane_graph_cc_proto", ], ) cc_test( name = "road_graph_test", size = "small", srcs = ["road_graph_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":kml_map_based_test", ":road_graph", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "kml_map_based_test", hdrs = ["kml_map_based_test.h"], ) cc_library( name = "validation_checker", srcs = ["validation_checker.cc"], hdrs = ["validation_checker.h"], deps = [ "//modules/common/math", "//modules/prediction/common:prediction_gflags", "//modules/common_msgs/prediction_msgs:lane_graph_cc_proto", ], ) cc_test( name = "validation_checker_test", size = "small", srcs = ["validation_checker_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":validation_checker", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "environment_features", srcs = ["environment_features.cc"], hdrs = ["environment_features.h"], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:geometry_cc_proto", ], ) cc_test( name = "environment_features_test", size = "small", srcs = ["environment_features_test.cc"], deps = [ ":environment_features", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "junction_analyzer", srcs = ["junction_analyzer.cc"], hdrs = ["junction_analyzer.h"], copts = PREDICTION_COPTS, deps = [ ":prediction_map", "//modules/common_msgs/prediction_msgs:feature_cc_proto", ], ) cc_test( name = "junction_analyzer_test", size = "small", srcs = ["junction_analyzer_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":junction_analyzer", ":kml_map_based_test", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "message_process", srcs = ["message_process.cc"], hdrs = ["message_process.h"], copts = PREDICTION_COPTS, deps = [ ":semantic_map", "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/prediction/evaluator:evaluator_manager", "//modules/prediction/predictor:predictor_manager", "//modules/prediction/proto:offline_features_cc_proto", "//modules/prediction/scenario:scenario_manager", "//modules/common/util:util_tool", ], ) cc_library( name = "prediction_thread_pool", srcs = ["prediction_thread_pool.cc"], hdrs = ["prediction_thread_pool.h"], copts = PREDICTION_COPTS, deps = [ "//cyber", ], ) cc_test( name = "prediction_thread_pool_test", size = "small", srcs = ["prediction_thread_pool_test.cc"], deps = [ ":prediction_thread_pool", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "semantic_map", srcs = ["semantic_map.cc"], hdrs = ["semantic_map.h"], copts = PREDICTION_COPTS, deps = [ ":prediction_gflags", "//cyber", "//modules/common/configs:config_gflags", "//modules/common/util", "//modules/prediction/container:container_manager", "//modules/prediction/container/pose:pose_container", "//modules/common_msgs/prediction_msgs:feature_cc_proto", "@opencv//:highgui", "@opencv//:imgcodecs", ], ) cc_library( name = "prediction_constants", hdrs = ["prediction_constants.h"], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_map.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <vector> #include "modules/map/pnc_map/path.h" namespace apollo { namespace prediction { class PredictionMap { public: /** * @brief Check if map is ready * @return True if map is ready */ static bool Ready(); /** * @brief Get the position of a point on a specific distance along a lane. * @param lane_info The lane to get a position. * @param s The distance along the lane. * @return The position with coordinates. */ static Eigen::Vector2d PositionOnLane( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s); /** * @brief Get the heading of a point on a specific distance along a lane. * @param lane_info The lane to get a heading. * @param s The distance along the lane. * @return The heading of the point. */ static double HeadingOnLane( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s); /** * @brief Get the curvature of a point on a specific distance along a lane. * @param lane_iid The id of the lane to get a curvature. * @param s The distance along the lane. * @return The curvature of the point. */ static double CurvatureOnLane(const std::string& lane_id, const double s); /** * @brief Get the width on a specified distance on a lane. * @param lane_info The lane to get the width. * @param s The distance along the lane. * @return The width on the distance s. */ static double LaneTotalWidth( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s); /** * @brief Get a shared pointer to a lane by lane ID. * @param id The ID of the target lane ID in the form of string. * @return A shared pointer to the lane with the input lane ID. */ static std::shared_ptr<const hdmap::LaneInfo> LaneById(const std::string& id); /** * @brief Get a shared pointer to a junction by junction ID. * @param id The ID of the target junction ID in the form of string. * @return A shared pointer to the junction with the input junction ID. */ static std::shared_ptr<const hdmap::JunctionInfo> JunctionById( const std::string& id); /** * @brief Get a shared pointer to an overlap by overlap ID. * @param id The ID of the target overlap ID in the form of string. * @return A shared pointer to the overlap with the input overlap ID. */ static std::shared_ptr<const hdmap::OverlapInfo> OverlapById( const std::string& id); /** * @brief Get the frenet coordinates (s, l) on a lane by a position. * @param position The position to get its frenet coordinates. * @param lane_info The lane on which to get the frenet coordinates. * @param s The longitudinal coordinate of the position. * @param l The lateral coordinate of the position. */ static bool GetProjection( const Eigen::Vector2d& position, const std::shared_ptr<const hdmap::LaneInfo> lane_info, double* s, double* l); /** * @brief If there is a lane in the range with radius * @param x x-axis coordinate * @param y y-axis coordinate * @param radius range radius * @return If there is a lane in the range with radius */ static bool HasNearbyLane(const double x, const double y, const double radius); /** * @brief Get the nearest path point to a longitudinal coordinate on a lane. * @param lane_info The lane on which to get the projected point. * @param s The longitudinal coordinate. * @param path_point The nearest path point. * @param If the process is successful. */ static bool ProjectionFromLane( std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s, hdmap::MapPathPoint* path_point); /** * @brief Determine if a lane is a virtual lane. * @param The lane ID of the lane. * @return If the lane is a virtual lane. */ static bool IsVirtualLane(const std::string& lane_id); /** * @brief Determine if a point is on a virtual lane. * @param The point coordinate. * @return If the point is on a virtual lane. */ static bool OnVirtualLane(const Eigen::Vector2d& position, const double radius); /** * @brief Get the connected lanes from some specified lanes. * @param prev_lanes The lanes from which to search their connected lanes. * @param heading The specified heading. * @param radius The searching radius. * @param on_lane If the position is on lane. * @param lanes The searched lanes. */ static void OnLane( const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, const bool on_lane, const int max_num_lane, const double max_lane_angle_diff, std::vector<std::shared_ptr<const hdmap::LaneInfo>>* lanes); /** * @brief Get the lane that the position is on with minimal angle diff * @param position the position of an obstacle * @param radius The searching radius * @param heading The specified heading * @param angle_diff_threshold Threshold of angle diff * @return A pointer to a lane info */ static std::shared_ptr<const apollo::hdmap::LaneInfo> GetMostLikelyCurrentLane(const common::PointENU& position, const double radius, const double heading, const double angle_diff_threshold); /** * @brief Check whether the projection of ego vehicle is on the target lane. * Note: the direction of the lane is approximated * by the terminal points. * @param ego_position The position of the ego vehicle * @param lane_id The target lane to project * @return true if the projection of ego vehicle is within the lane range; * false otherwise. */ static bool IsProjectionApproximateWithinLane( const Eigen::Vector2d& ego_position, const std::string& lane_id); /** * @brief Check if there are any junctions within the range centered at * a certain point with a radius. * @param point The position. * @param radius The radius to search junctions. * @return If any junctions exist. */ static bool NearJunction(const Eigen::Vector2d& point, const double radius); /** * @brief Check if a point with coord x and y is in the junction. * @param X axis coordinate. * @param Y axis coordinate. * @param A pointer to junction info. * @return If the point is in the junction. */ static bool IsPointInJunction( const double x, const double y, const std::shared_ptr<const hdmap::JunctionInfo> junction_info_ptr); /** * @brief Check if the obstacle is in a junction. * @param point position * @param radius the radius to search candidate junctions * @return If the obstacle is in a junction. */ static bool InJunction(const Eigen::Vector2d& point, const double radius); /** * @brief Check if a lane is in a junction * @param lane * @param junction id * @return If the lane is in the junction */ static bool IsLaneInJunction( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const std::string& junction_id); /** * @brief Get a list of junctions given a point and a search radius * @param Point * @param Search radius * @return A list of junctions */ static std::vector<std::shared_ptr<const apollo::hdmap::JunctionInfo>> GetJunctions(const Eigen::Vector2d& point, const double radius); /** * @brief Get a list of junctions given a point and a search radius * @param Point * @param Search radius * @return A list of junctions */ static std::vector<std::shared_ptr<const apollo::hdmap::PNCJunctionInfo>> GetPNCJunctions(const Eigen::Vector2d& point, const double radius); /** * @brief Get the lane heading on a point. * @param lane_info The target lane. * @param point The point to get the heading. * @return The heading of the input point on the input lane. */ static double PathHeading(std::shared_ptr<const hdmap::LaneInfo> lane_info, const common::PointENU& point); /** * @brief Get the smooth point on a lane by a longitudinal coordinate. * @param id The lane ID. * @param s The longitudinal coordinate along the lane. * @param l The lateral coordinate of the position. * @param point The point corresponding to the s,l-value coordinate. * @param heading The lane heading on the point. * @return If the process is successful. */ static bool SmoothPointFromLane(const std::string& id, const double s, const double l, Eigen::Vector2d* point, double* heading); /** * @brief Get nearby lanes by a position and current lanes. * @param point The position to search its nearby lanes. * @param heading The heading of an obstacle. * @param radius The searching radius. * @param lanes The current lanes. * @param nearby_lanes The searched nearby lanes. */ static void NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, const double heading, const double radius, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes, const int max_num_lane, std::vector<std::shared_ptr<const hdmap::LaneInfo>>* nearby_lanes); static std::shared_ptr<const hdmap::LaneInfo> GetLeftNeighborLane( const std::shared_ptr<const hdmap::LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold); static std::shared_ptr<const hdmap::LaneInfo> GetRightNeighborLane( const std::shared_ptr<const hdmap::LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold); /** * @brief Get nearby lanes by a position. * @param point The position to search its nearby lanes. * @param radius The searching radius. * @return A vector of nearby lane IDs. */ static std::vector<std::string> NearbyLaneIds(const Eigen::Vector2d& point, const double radius); /** * @brief Check if a lane is a left neighbor of another lane. * @param target_lane The lane to check if it is a left neighbor. * @param curr_lane The current lane. * @return If left_lane is a left neighbor of curr_lane. */ static bool IsLeftNeighborLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, std::shared_ptr<const hdmap::LaneInfo> curr_lane); /** * @brief Check if the target lane is a left neighbor of one of some lanes. * @param target_lane The lane to check if it is a left neighbor. * @param lanes The current lanes. * @return If left_lane is a left neighbor of one of lanes. */ static bool IsLeftNeighborLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes); /** * @brief Check if a lane is a right neighbor of another lane. * @param target_lane The lane to check if it is a right neighbor. * @param curr_lane The current lane. * @return If right_lane is a right neighbor of curr_lane. */ static bool IsRightNeighborLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, std::shared_ptr<const hdmap::LaneInfo> curr_lane); /** * @brief Check if the target lane is a right neighbor of one of some lanes. * @param target_lane The lane to check if it is a right neighbor. * @param lanes The current lanes. * @return If right_lane is a right neighbor of one of lanes. */ static bool IsRightNeighborLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes); /** * @brief Check if the target lane is a successor of another lane. * @param target_lane The lane to check if it is a successor. * @param curr_lane The current lane. * @return If succ_lane is a successor of curr_lane. */ static bool IsSuccessorLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, std::shared_ptr<const hdmap::LaneInfo> curr_lane); /** * @brief Check if the target lane is a successor of one of some lanes. * @param target_lane The lane to check if it is a successor. * @param lanes The current lanes. * @return If succ_lane is a successor of one of lanes. */ static bool IsSuccessorLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes); /** * @brief Check if the target lane is a predecessor of another lane. * @param target_lane The lane to check if it is a predecessor. * @param curr_lane The current lane. * @return If pred_lane is a predecessor of curr_lane. */ static bool IsPredecessorLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, std::shared_ptr<const hdmap::LaneInfo> curr_lane); /** * @brief Check if the target lane is a predecessor of one of some lanes. * @param target_lane The lane to check if it is a predecessor. * @param lanes The current lanes. * @return If pred_lane is a predecessor of one of lanes. */ static bool IsPredecessorLane( std::shared_ptr<const hdmap::LaneInfo> target_lane, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes); /** * @brief Check if two lanes are identical. * @param other_lane The other lane. * @param curr_lane The current lane. * @return If other_lane is identical to curr_lane. */ static bool IsIdenticalLane(std::shared_ptr<const hdmap::LaneInfo> other_lane, std::shared_ptr<const hdmap::LaneInfo> curr_lane); /** * @brief Check if a lane is identical to one of some lanes. * @param other_lane The other lane. * @param lanes The lanes. * @return If other_lane is identical to one of lanes. */ static bool IsIdenticalLane( std::shared_ptr<const hdmap::LaneInfo> other_lane, const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lanes); /** * @brief Get lane turn type. * @param lane_id The lane ID. * @return Integer corresponding to the lane turn type. */ static int LaneTurnType(const std::string& lane_id); /** * @brief Get all nearby lanes within certain radius given a position * @param position Position in ENU frame * @param nearyby_radius Search radius around the given position * @return All nearby lanes within the radius */ static std::vector<std::shared_ptr<const hdmap::LaneInfo>> GetNearbyLanes( const common::PointENU& position, const double nearby_radius); /** * @brief Get the pointer to the lane with the smallest average curvature * @param The vector of lane infos * @return The pointer to the lane with the smallest average curvature */ static std::shared_ptr<const hdmap::LaneInfo> LaneWithSmallestAverageCurvature( const std::vector<std::shared_ptr<const hdmap::LaneInfo>>& lane_infos); /** * @brief Get the average curvature along a lane with the ID lane_id * @param The ID of the lane * @param The size of samples alone the lane to compute the average curvature * @return The average curvature */ static double AverageCurvature(const std::string& lane_id, const size_t sample_size); private: static std::shared_ptr<const hdmap::LaneInfo> GetNeighborLane( const std::shared_ptr<const hdmap::LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const std::vector<std::string>& neighbor_lane_ids, const double threshold); PredictionMap() = delete; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_constants.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Holds all global constants for the prediction module. */ #pragma once namespace apollo { namespace prediction { class PredictionConstants { public: static const int kOnlineMode = 0; static const int kDumpFeatureProto = 1; static const int kDumpDataForLearning = 2; static const int kDumpPredictionResult = 3; static const int kDumpFrameEnv = 4; static const int kDumpDataForTuning = 5; static const int kDumpRecord = 6; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_map.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/prediction/common/prediction_map.h" #include <algorithm> #include <limits> #include <unordered_set> #include <utility> #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; using apollo::hdmap::HDMapUtil; using apollo::hdmap::JunctionInfo; using apollo::hdmap::LaneInfo; using apollo::hdmap::MapPathPoint; using apollo::hdmap::OverlapInfo; using apollo::hdmap::PNCJunctionInfo; bool PredictionMap::Ready() { return HDMapUtil::BaseMapPtr() != nullptr; } Eigen::Vector2d PredictionMap::PositionOnLane( const std::shared_ptr<const LaneInfo> lane_info, const double s) { common::PointENU point = lane_info->GetSmoothPoint(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane( const std::shared_ptr<const LaneInfo> lane_info, const double s) { return lane_info->Heading(s); } double PredictionMap::CurvatureOnLane(const std::string& lane_id, const double s) { std::shared_ptr<const hdmap::LaneInfo> lane_info = LaneById(lane_id); if (lane_info == nullptr) { AERROR << "Null lane_info ptr found"; return 0.0; } return lane_info->Curvature(s); } double PredictionMap::LaneTotalWidth( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s) { double left = 0.0; double right = 0.0; lane_info->GetWidth(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { return HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(str_id)); } std::shared_ptr<const JunctionInfo> PredictionMap::JunctionById( const std::string& str_id) { return HDMapUtil::BaseMap().GetJunctionById(hdmap::MakeMapId(str_id)); } std::shared_ptr<const OverlapInfo> PredictionMap::OverlapById( const std::string& str_id) { return HDMapUtil::BaseMap().GetOverlapById(hdmap::MakeMapId(str_id)); } bool PredictionMap::GetProjection( const Eigen::Vector2d& pos, const std::shared_ptr<const LaneInfo> lane_info, double* s, double* l) { if (lane_info == nullptr) { return false; } return lane_info->GetProjection({pos.x(), pos.y()}, s, l); } bool PredictionMap::HasNearbyLane(const double x, const double y, const double radius) { common::PointENU point_enu; point_enu.set_x(x); point_enu.set_y(y); std::vector<std::shared_ptr<const LaneInfo>> lanes; HDMapUtil::BaseMap().GetLanes(point_enu, radius, &lanes); return (!lanes.empty()); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info, const double s, MapPathPoint* path_point) { if (lane_info == nullptr) { return false; } const common::PointENU point = lane_info->GetSmoothPoint(s); const double heading = HeadingOnLane(lane_info, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } bool PredictionMap::IsVirtualLane(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane_info = HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id)); if (lane_info == nullptr) { return false; } const hdmap::Lane& lane = lane_info->lane(); bool left_virtual = lane.has_left_boundary() && lane.left_boundary().has_virtual_() && lane.left_boundary().virtual_(); bool right_virtual = lane.has_right_boundary() && lane.right_boundary().has_virtual_() && lane.right_boundary().virtual_(); return left_virtual && right_virtual; } bool PredictionMap::OnVirtualLane(const Eigen::Vector2d& point, const double radius) { std::vector<std::shared_ptr<const LaneInfo>> lanes; common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); HDMapUtil::BaseMap().GetLanes(hdmap_point, radius, &lanes); for (const auto& lane : lanes) { if (IsVirtualLane(lane->id().id())) { return true; } } return false; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, const bool on_lane, const int max_num_lane, const double max_lane_angle_diff, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); if (HDMapUtil::BaseMap().GetLanesWithHeading(hdmap_point, radius, heading, max_lane_angle_diff, &candidate_lanes) != 0) { return; } std::vector<std::pair<std::shared_ptr<const LaneInfo>, double>> lane_pairs; for (const auto& candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } if (on_lane && !candidate_lane->IsOnLane({point.x(), point.y()})) { continue; } if (!FLAGS_use_navigation_mode && !IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } double distance = 0.0; common::PointENU nearest_point = candidate_lane->GetNearestPoint({point.x(), point.y()}, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double diff = std::fabs(common::math::AngleDiff(heading, nearest_point_heading)); if (diff <= max_lane_angle_diff) { lane_pairs.emplace_back(candidate_lane, diff); } } if (lane_pairs.empty()) { return; } std::sort(lane_pairs.begin(), lane_pairs.end(), [](const std::pair<std::shared_ptr<const LaneInfo>, double>& p1, const std::pair<std::shared_ptr<const LaneInfo>, double>& p2) { return p1.second < p2.second; }); int count = 0; for (const auto& lane_pair : lane_pairs) { lanes->push_back(lane_pair.first); ++count; if (count >= max_num_lane) { break; } } } std::shared_ptr<const LaneInfo> PredictionMap::GetMostLikelyCurrentLane( const common::PointENU& position, const double radius, const double heading, const double angle_diff_threshold) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; if (HDMapUtil::BaseMap().GetLanesWithHeading(position, radius, heading, angle_diff_threshold, &candidate_lanes) != 0) { return nullptr; } double min_angle_diff = 2.0 * M_PI; std::shared_ptr<const LaneInfo> curr_lane_ptr = nullptr; for (auto candidate_lane : candidate_lanes) { if (!candidate_lane->IsOnLane({position.x(), position.y()})) { continue; } double distance = 0.0; common::PointENU nearest_point = candidate_lane->GetNearestPoint( {position.x(), position.y()}, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double angle_diff = std::fabs(common::math::AngleDiff(heading, nearest_point_heading)); if (angle_diff < min_angle_diff) { min_angle_diff = angle_diff; curr_lane_ptr = candidate_lane; } } return curr_lane_ptr; } bool PredictionMap::IsProjectionApproximateWithinLane( const Eigen::Vector2d& ego_position, const std::string& lane_id) { auto ptr_lane = LaneById(lane_id); const auto& lane_points = ptr_lane->points(); if (lane_points.size() < 2) { return false; } const auto& start_point = lane_points.front(); const auto& end_point = lane_points.back(); auto lane_vec = end_point - start_point; auto approx_lane_length = lane_vec.Length(); if (approx_lane_length < 1.0e-3) { return false; } auto dist_vec = common::math::Vec2d(ego_position.x(), ego_position.y()) - start_point; auto projection_length = dist_vec.InnerProd(lane_vec) / approx_lane_length; if (projection_length < 0.0 || projection_length > approx_lane_length) { return false; } return true; } bool PredictionMap::NearJunction(const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const JunctionInfo>> junctions; HDMapUtil::BaseMap().GetJunctions(hdmap_point, radius, &junctions); return junctions.size() > 0; } bool PredictionMap::IsPointInJunction( const double x, const double y, const std::shared_ptr<const JunctionInfo> junction_info_ptr) { if (junction_info_ptr == nullptr) { return false; } const Polygon2d& polygon = junction_info_ptr->polygon(); return polygon.IsPointIn({x, y}); } std::vector<std::shared_ptr<const JunctionInfo>> PredictionMap::GetJunctions( const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const JunctionInfo>> junctions; HDMapUtil::BaseMap().GetJunctions(hdmap_point, radius, &junctions); return junctions; } std::vector<std::shared_ptr<const PNCJunctionInfo>> PredictionMap::GetPNCJunctions(const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const PNCJunctionInfo>> junctions; HDMapUtil::BaseMap().GetPNCJunctions(hdmap_point, radius, &junctions); return junctions; } bool PredictionMap::InJunction(const Eigen::Vector2d& point, const double radius) { auto junction_infos = GetJunctions(point, radius); if (junction_infos.empty()) { return false; } for (const auto junction_info : junction_infos) { if (junction_info == nullptr || !junction_info->junction().has_polygon()) { continue; } std::vector<Vec2d> vertices; for (const auto& point : junction_info->junction().polygon().point()) { vertices.emplace_back(point.x(), point.y()); } if (vertices.size() < 3) { continue; } Polygon2d junction_polygon{vertices}; if (junction_polygon.IsPointIn({point.x(), point.y()})) { return true; } } return false; } bool PredictionMap::IsLaneInJunction( const std::shared_ptr<const LaneInfo> lane_info, const std::string& junction_id) { if (lane_info == nullptr) { return false; } // first, check whether the lane is virtual if (!PredictionMap::IsVirtualLane(lane_info->lane().id().id())) { return false; } // second, use junction from lane if (lane_info->lane().has_junction_id() && lane_info->lane().junction_id().id() == junction_id) { return true; } // third, use junction from road auto ptr_road_info = HDMapUtil::BaseMap().GetRoadById(lane_info->road_id()); if (ptr_road_info->has_junction_id() && ptr_road_info->junction_id().id() == junction_id) { return true; } return false; } double PredictionMap::PathHeading(std::shared_ptr<const LaneInfo> lane_info, const common::PointENU& point) { double s = 0.0; double l = 0.0; if (lane_info->GetProjection({point.x(), point.y()}, &s, &l)) { return HeadingOnLane(lane_info, s); } else { return M_PI; } } bool PredictionMap::SmoothPointFromLane(const std::string& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { if (point == nullptr || heading == nullptr) { return false; } std::shared_ptr<const LaneInfo> lane = LaneById(id); common::PointENU hdmap_point = lane->GetSmoothPoint(s); *heading = PathHeading(lane, hdmap_point); point->x() = hdmap_point.x() - std::sin(*heading) * l; point->y() = hdmap_point.y() + std::cos(*heading) * l; return true; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, const double heading, const double radius, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, const int max_num_lane, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { if (lanes.empty()) { std::vector<std::shared_ptr<const LaneInfo>> prev_lanes; OnLane(prev_lanes, point, heading, radius, false, max_num_lane, FLAGS_max_lane_angle_diff, nearby_lanes); } else { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (s < 0.0 || s >= nearby_lane->total_length() || std::fabs(l) > radius) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (s < 0.0 || s >= nearby_lane->total_length() || std::fabs(l) > radius) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } } } } std::shared_ptr<const LaneInfo> PredictionMap::GetLeftNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold) { std::vector<std::string> neighbor_ids; for (const auto& lane_id : ptr_ego_lane->lane().left_neighbor_forward_lane_id()) { neighbor_ids.push_back(lane_id.id()); } return GetNeighborLane(ptr_ego_lane, ego_position, neighbor_ids, threshold); } std::shared_ptr<const LaneInfo> PredictionMap::GetRightNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold) { std::vector<std::string> neighbor_ids; for (const auto& lane_id : ptr_ego_lane->lane().right_neighbor_forward_lane_id()) { neighbor_ids.push_back(lane_id.id()); } return GetNeighborLane(ptr_ego_lane, ego_position, neighbor_ids, threshold); } std::shared_ptr<const LaneInfo> PredictionMap::GetNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const std::vector<std::string>& neighbor_lane_ids, const double threshold) { double ego_s = 0.0; double ego_l = 0.0; GetProjection(ego_position, ptr_ego_lane, &ego_s, &ego_l); double s_diff_min = std::numeric_limits<double>::max(); std::shared_ptr<const LaneInfo> ptr_lane_min = nullptr; for (auto& lane_id : neighbor_lane_ids) { std::shared_ptr<const LaneInfo> ptr_lane = LaneById(lane_id); double s = -1.0; double l = 0.0; GetProjection(ego_position, ptr_lane, &s, &l); double s_diff = std::fabs(s - ego_s); if (s_diff < s_diff_min) { s_diff_min = s_diff; ptr_lane_min = ptr_lane; } } if (s_diff_min > threshold) { return nullptr; } return ptr_lane_min; } std::vector<std::string> PredictionMap::NearbyLaneIds( const Eigen::Vector2d& point, const double radius) { std::vector<std::string> lane_ids; std::vector<std::shared_ptr<const LaneInfo>> lanes; common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); HDMapUtil::BaseMap().GetLanes(hdmap_point, radius, &lanes); for (const auto& lane : lanes) { lane_ids.push_back(lane->id().id()); } return lane_ids; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (target_lane->id().id() == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (target_lane->id().id() == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (const auto& lane : lanes) { if (IsRightNeighborLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane(std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& successor_lane_id : curr_lane->lane().successor_id()) { if (target_lane->id().id() == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (target_lane->id().id() == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane(std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return true; } return other_lane->id().id() == curr_lane->id().id(); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane = LaneById(lane_id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } std::vector<std::shared_ptr<const LaneInfo>> PredictionMap::GetNearbyLanes( const common::PointENU& position, const double nearby_radius) { ACHECK(position.has_x() && position.has_y() && position.has_z()); ACHECK(nearby_radius > 0.0); std::vector<std::shared_ptr<const LaneInfo>> nearby_lanes; HDMapUtil::BaseMap().GetLanes(position, nearby_radius, &nearby_lanes); return nearby_lanes; } std::shared_ptr<const LaneInfo> PredictionMap::LaneWithSmallestAverageCurvature( const std::vector<std::shared_ptr<const LaneInfo>>& lane_infos) { ACHECK(!lane_infos.empty()); size_t sample_size = FLAGS_sample_size_for_average_lane_curvature; std::shared_ptr<const hdmap::LaneInfo> selected_lane_info = lane_infos[0]; if (selected_lane_info == nullptr) { AERROR << "Lane Vector first element: selected_lane_info is nullptr."; return nullptr; } double smallest_curvature = AverageCurvature(selected_lane_info->id().id(), sample_size); for (size_t i = 1; i < lane_infos.size(); ++i) { std::shared_ptr<const hdmap::LaneInfo> lane_info = lane_infos[i]; if (lane_info == nullptr) { AWARN << "Lane vector element: one lane_info is nullptr."; continue; } double curvature = AverageCurvature(lane_info->id().id(), sample_size); if (curvature < smallest_curvature) { smallest_curvature = curvature; selected_lane_info = lane_info; } } return selected_lane_info; } double PredictionMap::AverageCurvature(const std::string& lane_id, const size_t sample_size) { CHECK_GT(sample_size, 0U); std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { return 0.0; } double lane_length = lane_info_ptr->total_length(); double s_gap = lane_length / static_cast<double>(sample_size); double curvature_sum = 0.0; for (size_t i = 0; i < sample_size; ++i) { double s = s_gap * static_cast<double>(i); curvature_sum += std::abs(PredictionMap::CurvatureOnLane(lane_id, s)); } return curvature_sum / static_cast<double>(sample_size); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/road_graph_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/road_graph.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { class RoadGraphTest : public KMLMapBasedTest {}; TEST_F(RoadGraphTest, General) { auto lane = PredictionMap::LaneById("l9"); EXPECT_NE(lane, nullptr); double start_s = 99.0; double length = 100.0; RoadGraph road_graph(start_s, length, true, lane); LaneGraph lane_graph; EXPECT_TRUE(road_graph.BuildLaneGraph(&lane_graph).ok()); EXPECT_EQ(1, lane_graph.lane_sequence_size()); EXPECT_EQ(3, lane_graph.lane_sequence(0).lane_segment_size()); EXPECT_EQ("l9", lane_graph.lane_sequence(0).lane_segment(0).lane_id()); EXPECT_EQ("l18", lane_graph.lane_sequence(0).lane_segment(1).lane_id()); EXPECT_EQ("l21", lane_graph.lane_sequence(0).lane_segment(2).lane_id()); EXPECT_TRUE( road_graph.IsOnLaneGraph(PredictionMap::LaneById("l9"), lane_graph)); EXPECT_TRUE( road_graph.IsOnLaneGraph(PredictionMap::LaneById("l18"), lane_graph)); EXPECT_TRUE( road_graph.IsOnLaneGraph(PredictionMap::LaneById("l21"), lane_graph)); EXPECT_FALSE( road_graph.IsOnLaneGraph(PredictionMap::LaneById("l30"), lane_graph)); for (const auto &lane_sequence : lane_graph.lane_sequence()) { double total_length = 0.0; for (const auto &lane_segment : lane_sequence.lane_segment()) { total_length += (lane_segment.end_s() - lane_segment.start_s()); } EXPECT_DOUBLE_EQ(length, total_length); } } /* TEST_F(RoadGraphTest, NegativeStartS) { auto lane = PredictionMap::LaneById("l9"); EXPECT_NE(lane, nullptr); double start_s = -10.0; double length = 50.0; RoadGraph road_graph(start_s, length, true, lane); LaneGraph lane_graph; EXPECT_TRUE(road_graph.BuildLaneGraph(&lane_graph).ok()); EXPECT_EQ(1, lane_graph.lane_sequence_size()); EXPECT_EQ(1, lane_graph.lane_sequence(0).lane_segment_size()); EXPECT_EQ("l9", lane_graph.lane_sequence(0).lane_segment(0).lane_id()); for (const auto &lane_sequence : lane_graph.lane_sequence()) { double total_length = 0.0; for (const auto &lane_segment : lane_sequence.lane_segment()) { total_length += (lane_segment.end_s() - lane_segment.start_s()); } EXPECT_DOUBLE_EQ(length, total_length); } } */ TEST_F(RoadGraphTest, LengthLongerThanEnd) { auto lane = PredictionMap::LaneById("l22"); EXPECT_NE(lane, nullptr); double start_s = 200.0; double length = 200.0; RoadGraph road_graph(start_s, length, true, lane); LaneGraph lane_graph; EXPECT_TRUE(road_graph.BuildLaneGraph(&lane_graph).ok()); EXPECT_EQ(1, lane_graph.lane_sequence_size()); EXPECT_EQ(3, lane_graph.lane_sequence(0).lane_segment_size()); EXPECT_EQ("l22", lane_graph.lane_sequence(0).lane_segment(0).lane_id()); EXPECT_EQ("l100", lane_graph.lane_sequence(0).lane_segment(1).lane_id()); EXPECT_EQ("l97", lane_graph.lane_sequence(0).lane_segment(2).lane_id()); for (const auto &lane_sequence : lane_graph.lane_sequence()) { double total_length = 0.0; for (const auto &lane_segment : lane_sequence.lane_segment()) { total_length += (lane_segment.end_s() - lane_segment.start_s()); } EXPECT_LT(total_length, length); } } TEST_F(RoadGraphTest, MultipleLaneSequence) { auto lane = PredictionMap::LaneById("l20"); EXPECT_NE(lane, nullptr); double start_s = 200.0; double length = 200.0; RoadGraph road_graph(start_s, length, true, lane); LaneGraph lane_graph; EXPECT_TRUE(road_graph.BuildLaneGraph(&lane_graph).ok()); EXPECT_EQ(2, lane_graph.lane_sequence_size()); EXPECT_EQ(3, lane_graph.lane_sequence(0).lane_segment_size()); EXPECT_EQ(3, lane_graph.lane_sequence(1).lane_segment_size()); EXPECT_EQ("l20", lane_graph.lane_sequence(0).lane_segment(0).lane_id()); EXPECT_EQ("l98", lane_graph.lane_sequence(0).lane_segment(1).lane_id()); EXPECT_EQ("l95", lane_graph.lane_sequence(0).lane_segment(2).lane_id()); EXPECT_EQ("l20", lane_graph.lane_sequence(1).lane_segment(0).lane_id()); EXPECT_EQ("l31", lane_graph.lane_sequence(1).lane_segment(1).lane_id()); EXPECT_EQ("l29", lane_graph.lane_sequence(1).lane_segment(2).lane_id()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/common/prediction_system_gflags.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 "gflags/gflags.h" // System gflags DECLARE_string(prediction_module_name); DECLARE_string(prediction_conf_file); DECLARE_string(prediction_adapter_config_filename); DECLARE_string(prediction_data_dir); DECLARE_string(offline_feature_proto_file_name); DECLARE_string(output_filename); DECLARE_string(extract_feature_type); DECLARE_bool(prediction_test_mode); DECLARE_double(prediction_test_duration); DECLARE_string(prediction_offline_bags); DECLARE_int32(prediction_offline_mode); DECLARE_bool(enable_multi_thread); DECLARE_int32(max_thread_num); DECLARE_int32(max_caution_thread_num); DECLARE_bool(enable_async_draw_base_image); DECLARE_bool(use_cuda); // Bag replay timestamp gap DECLARE_double(replay_timestamp_gap); DECLARE_int32(max_num_dump_feature); DECLARE_int32(max_num_dump_dataforlearn); // Submodules DECLARE_bool(use_lego); DECLARE_string(container_topic_name); DECLARE_string(adccontainer_topic_name); DECLARE_string(evaluator_topic_name); DECLARE_string(container_submodule_name); DECLARE_string(evaluator_submodule_name); DECLARE_string(perception_obstacles_topic_name); // VectorNet DECLARE_string(prediction_target_file); DECLARE_string(world_coordinate_file); DECLARE_string(prediction_target_dir); DECLARE_double(obstacle_x); DECLARE_double(obstacle_y); DECLARE_double(obstacle_phi); DECLARE_double(road_distance); DECLARE_double(point_distance);
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/scenario/scenario_manager_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/scenario_manager.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; class ScenarioManagerTest : public ::testing::Test { public: virtual void SetUp() { container_manager_.reset(new ContainerManager()); } protected: ScenarioManager manager_; std::unique_ptr<ContainerManager> container_manager_ = nullptr; }; TEST_F(ScenarioManagerTest, init) { const auto& scenario = manager_.scenario(); EXPECT_EQ(scenario.type(), Scenario::UNKNOWN); } TEST_F(ScenarioManagerTest, run) { // TODO(kechxu) add unit tests with concrete contents container_manager_->RegisterContainers(); std::unique_ptr<Container> adc_traj_container = container_manager_->CreateContainer(AdapterConfig::PLANNING_TRAJECTORY); std::unique_ptr<Container> pose_container = container_manager_->CreateContainer(AdapterConfig::LOCALIZATION); manager_.Run(container_manager_.get()); const auto& scenario = manager_.scenario(); EXPECT_EQ(scenario.type(), Scenario::UNKNOWN); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/scenario/scenario_manager.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/scenario/analyzer/scenario_analyzer.h" #include "modules/prediction/scenario/feature_extractor/feature_extractor.h" #include "modules/prediction/scenario/scenario_features/cruise_scenario_features.h" namespace apollo { namespace prediction { class ScenarioManager { public: /** * @brief Constructor */ ScenarioManager() = default; /** * @brief Destructor */ ~ScenarioManager() = default; /** * @brief Run scenario analysis */ void Run(ContainerManager* container_manager); /** * @brief Get scenario analysis result */ const Scenario scenario() const; private: Scenario current_scenario_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/scenario/scenario_manager.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/scenario_manager.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { void ScenarioManager::Run(ContainerManager* container_manager) { auto environment_features = FeatureExtractor::ExtractEnvironmentFeatures(container_manager); auto ptr_scenario_features = ScenarioAnalyzer::Analyze(environment_features); current_scenario_ = ptr_scenario_features->scenario(); // TODO(all) other functionalities including lane, junction filters } const Scenario ScenarioManager::scenario() const { return current_scenario_; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/scenario/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "scenario_manager", srcs = ["scenario_manager.cc"], hdrs = ["scenario_manager.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/prediction/scenario/analyzer:scenario_analyzer", "//modules/prediction/scenario/feature_extractor", "//modules/prediction/scenario/interaction_filter:interaction_filter", "//modules/prediction/scenario/prioritization:obstacles_prioritizer", "//modules/prediction/scenario/right_of_way", ], ) cc_test( name = "scenario_manager_test", size = "small", srcs = ["scenario_manager_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":scenario_manager", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/prioritization/obstacles_prioritizer.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/prediction/scenario/prioritization/obstacles_prioritizer.h" #include <limits> #include <queue> #include <unordered_map> #include <utility> #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/container/storytelling/storytelling_container.h" namespace apollo { namespace prediction { using apollo::common::Point3D; using apollo::common::adapter::AdapterConfig; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; using apollo::hdmap::LaneInfo; using apollo::hdmap::OverlapInfo; using apollo::perception::PerceptionObstacle; using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>; namespace { bool IsLaneSequenceInReferenceLine( const LaneSequence& lane_sequence, const ADCTrajectoryContainer* ego_trajectory_container) { for (const auto& lane_segment : lane_sequence.lane_segment()) { std::string lane_id = lane_segment.lane_id(); if (ego_trajectory_container->IsLaneIdInTargetReferenceLine(lane_id)) { return true; } } return false; } int NearestFrontObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) { int nearest_front_obstacle_id = std::numeric_limits<int>::min(); double smallest_relative_s = std::numeric_limits<double>::max(); for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) { if (nearby_obs.s() < 0.0 || nearby_obs.s() > FLAGS_caution_search_distance_ahead) { continue; } if (nearby_obs.s() < smallest_relative_s) { smallest_relative_s = nearby_obs.s(); nearest_front_obstacle_id = nearby_obs.id(); } } return nearest_front_obstacle_id; } int NearestBackwardObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) { int nearest_backward_obstacle_id = std::numeric_limits<int>::min(); double smallest_relative_s = std::numeric_limits<double>::max(); for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) { if (nearby_obs.s() > 0.0 || nearby_obs.s() < -FLAGS_caution_search_distance_backward) { continue; } if (-nearby_obs.s() < smallest_relative_s) { smallest_relative_s = -nearby_obs.s(); nearest_backward_obstacle_id = nearby_obs.id(); } } return nearest_backward_obstacle_id; } } // namespace ObstaclesPrioritizer::ObstaclesPrioritizer( const std::shared_ptr<ContainerManager>& container_manager) : container_manager_(container_manager) {} void ObstaclesPrioritizer::AssignIgnoreLevel() { auto obstacles_container = container_manager_->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); if (obstacles_container == nullptr) { AERROR << "Obstacles container pointer is a null pointer."; return; } Obstacle* ego_obstacle_ptr = obstacles_container->GetObstacle(FLAGS_ego_vehicle_id); if (ego_obstacle_ptr == nullptr) { AERROR << "Ego obstacle nullptr found"; return; } const Feature& ego_feature = ego_obstacle_ptr->latest_feature(); double ego_theta = ego_feature.theta(); double ego_x = ego_feature.position().x(); double ego_y = ego_feature.position().y(); ADEBUG << "Get pose (" << ego_x << ", " << ego_y << ", " << ego_theta << ")"; // Build rectangular scan_area Box2d scan_box({ego_x + FLAGS_scan_length / 2.0 * std::cos(ego_theta), ego_y + FLAGS_scan_length / 2.0 * std::sin(ego_theta)}, ego_theta, FLAGS_scan_length, FLAGS_scan_width); const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle pointer found."; continue; } if (obstacle_ptr->history_size() == 0) { AERROR << "Obstacle [" << obstacle_ptr->id() << "] has no feature."; continue; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); double obstacle_x = latest_feature_ptr->position().x(); double obstacle_y = latest_feature_ptr->position().y(); Vec2d ego_to_obstacle_vec(obstacle_x - ego_x, obstacle_y - ego_y); Vec2d ego_vec = Vec2d::CreateUnitVec2d(ego_theta); double s = ego_to_obstacle_vec.InnerProd(ego_vec); double pedestrian_like_nearby_lane_radius = FLAGS_pedestrian_nearby_lane_search_radius; bool is_near_lane = PredictionMap::HasNearbyLane( obstacle_x, obstacle_y, pedestrian_like_nearby_lane_radius); // Decide if we need consider this obstacle bool is_in_scan_area = scan_box.IsPointIn({obstacle_x, obstacle_y}); bool is_on_lane = obstacle_ptr->IsOnLane(); bool is_pedestrian_like_in_front_near_lanes = s > FLAGS_back_dist_ignore_ped && (latest_feature_ptr->type() == PerceptionObstacle::PEDESTRIAN || latest_feature_ptr->type() == PerceptionObstacle::BICYCLE || latest_feature_ptr->type() == PerceptionObstacle::UNKNOWN || latest_feature_ptr->type() == PerceptionObstacle::UNKNOWN_MOVABLE) && is_near_lane; bool is_near_junction = obstacle_ptr->IsNearJunction(); bool need_consider = is_in_scan_area || is_on_lane || is_near_junction || is_pedestrian_like_in_front_near_lanes; if (!need_consider) { latest_feature_ptr->mutable_priority()->set_priority( ObstaclePriority::IGNORE); } else { latest_feature_ptr->mutable_priority()->set_priority( ObstaclePriority::NORMAL); } } obstacles_container->SetConsideredObstacleIds(); } void ObstaclesPrioritizer::AssignCautionLevel() { auto obstacles_container = container_manager_->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); if (obstacles_container == nullptr) { AERROR << "Obstacles container pointer is a null pointer."; return; } Obstacle* ego_vehicle = obstacles_container->GetObstacle(FLAGS_ego_vehicle_id); if (ego_vehicle == nullptr) { AERROR << "Ego vehicle not found"; return; } if (ego_vehicle->history_size() == 0) { AERROR << "Ego vehicle has no history"; return; } auto storytelling_container = container_manager_->GetContainer<StoryTellingContainer>( AdapterConfig::STORYTELLING); if (storytelling_container->ADCDistanceToJunction() < FLAGS_junction_distance_threshold) { AssignCautionLevelInJunction(*ego_vehicle, obstacles_container, storytelling_container->ADCJunctionId()); } AssignCautionLevelCruiseKeepLane(*ego_vehicle, obstacles_container); AssignCautionLevelCruiseChangeLane(*ego_vehicle, obstacles_container); AssignCautionLevelByEgoReferenceLine(*ego_vehicle, obstacles_container); AssignCautionLevelPedestrianByEgoReferenceLine(*ego_vehicle, obstacles_container); if (FLAGS_enable_all_pedestrian_caution_in_front) { AssignCautionLevelPedestrianInFront(*ego_vehicle, obstacles_container); } if (FLAGS_enable_rank_caution_obstacles) { RankingCautionLevelObstacles(*ego_vehicle, obstacles_container); } } void ObstaclesPrioritizer::AssignCautionLevelInJunction( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container, const std::string& junction_id) { // TODO(Hongyi): get current junction_id from Storytelling const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle pointer found."; continue; } if (obstacle_ptr->IsInJunction(junction_id)) { SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); } } } void ObstaclesPrioritizer::AssignCautionLevelCruiseKeepLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { const Feature& ego_latest_feature = ego_vehicle.latest_feature(); for (const LaneSequence& lane_sequence : ego_latest_feature.lane().lane_graph().lane_sequence()) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id < 0) { continue; } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found"; continue; } SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); } } void ObstaclesPrioritizer::AssignCautionLevelCruiseChangeLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { ADCTrajectoryContainer* ego_trajectory_container = container_manager_->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); const Feature& ego_latest_feature = ego_vehicle.latest_feature(); for (const LaneSequence& lane_sequence : ego_latest_feature.lane().lane_graph().lane_sequence()) { if (lane_sequence.vehicle_on_lane()) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id < 0) { continue; } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found"; continue; } SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); } else if (IsLaneSequenceInReferenceLine(lane_sequence, ego_trajectory_container)) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); int nearest_backward_obstacle_id = NearestBackwardObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id >= 0) { Obstacle* front_obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (front_obstacle_ptr != nullptr) { SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, front_obstacle_ptr); } } if (nearest_backward_obstacle_id >= 0) { Obstacle* backward_obstacle_ptr = obstacles_container->GetObstacle(nearest_backward_obstacle_id); if (backward_obstacle_ptr != nullptr) { SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, backward_obstacle_ptr); } } } } } void ObstaclesPrioritizer::AssignCautionLevelByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { ADCTrajectoryContainer* adc_trajectory_container = container_manager_->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); if (adc_trajectory_container == nullptr) { AERROR << "adc_trajectory_container is nullptr"; return; } const std::vector<std::string>& lane_ids = adc_trajectory_container->GetADCTargetLaneIDSequence(); if (lane_ids.empty()) { return; } const Feature& ego_feature = ego_vehicle.latest_feature(); double ego_x = ego_feature.position().x(); double ego_y = ego_feature.position().y(); double ego_vehicle_s = std::numeric_limits<double>::max(); double ego_vehicle_l = std::numeric_limits<double>::max(); double accumulated_s = 0.0; // first loop for lane_ids to findout ego_vehicle_s for (const std::string& lane_id : lane_ids) { std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } double s = 0.0; double l = 0.0; if (PredictionMap::GetProjection({ego_x, ego_y}, lane_info_ptr, &s, &l)) { if (std::fabs(l) < std::fabs(ego_vehicle_l)) { ego_vehicle_s = accumulated_s + s; ego_vehicle_l = l; ego_lane_id_ = lane_id; ego_lane_s_ = s; } } accumulated_s += lane_info_ptr->total_length(); } // insert ego_back_lane_id accumulated_s = 0.0; for (const std::string& lane_id : lane_ids) { if (lane_id == ego_lane_id_) { break; } ego_back_lane_id_set_.insert(lane_id); } std::unordered_set<std::string> visited_lanes(lane_ids.begin(), lane_ids.end()); // then loop through lane_ids to AssignCaution for obstacle vehicles for (const std::string& lane_id : lane_ids) { if (ego_back_lane_id_set_.find(lane_id) != ego_back_lane_id_set_.end()) { continue; } std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } accumulated_s += lane_info_ptr->total_length(); if (lane_id != ego_lane_id_) { AssignCautionByMerge(ego_vehicle, lane_info_ptr, &visited_lanes, obstacles_container); } AssignCautionByOverlap(ego_vehicle, lane_info_ptr, &visited_lanes, obstacles_container); if (accumulated_s > FLAGS_caution_search_distance_ahead + ego_vehicle_s) { break; } } } void ObstaclesPrioritizer::AssignCautionLevelPedestrianByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { ADCTrajectoryContainer* adc_trajectory_container = container_manager_->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); if (adc_trajectory_container == nullptr) { AERROR << "adc_trajectory_container is nullptr"; return; } for (const int obstacle_id : obstacles_container->curr_frame_movable_obstacle_ids()) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle pointer found."; continue; } if (obstacle_ptr->history_size() == 0) { AERROR << "Obstacle [" << obstacle_ptr->id() << "] has no feature."; continue; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); if (latest_feature_ptr->type() != PerceptionObstacle::PEDESTRIAN) { continue; } double start_x = latest_feature_ptr->position().x(); double start_y = latest_feature_ptr->position().y(); double end_x = start_x + FLAGS_caution_pedestrian_approach_time * latest_feature_ptr->raw_velocity().x(); double end_y = start_y + FLAGS_caution_pedestrian_approach_time * latest_feature_ptr->raw_velocity().y(); std::vector<std::string> nearby_lane_ids = PredictionMap::NearbyLaneIds( {start_x, start_y}, FLAGS_pedestrian_nearby_lane_search_radius); if (nearby_lane_ids.empty()) { continue; } for (const std::string& lane_id : nearby_lane_ids) { if (!adc_trajectory_container->IsLaneIdInTargetReferenceLine(lane_id)) { continue; } std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } double start_s = 0.0; double start_l = 0.0; double end_s = 0.0; double end_l = 0.0; if (PredictionMap::GetProjection({start_x, start_y}, lane_info_ptr, &start_s, &start_l) && PredictionMap::GetProjection({end_x, end_y}, lane_info_ptr, &end_s, &end_l)) { if (std::fabs(start_l) < FLAGS_pedestrian_nearby_lane_search_radius || std::fabs(end_l) < FLAGS_pedestrian_nearby_lane_search_radius || start_l * end_l < 0.0) { SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); } } } } } void ObstaclesPrioritizer::AssignCautionLevelPedestrianInFront( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { const Point3D& ego_position = ego_vehicle.latest_feature().position(); double ego_heading = ego_vehicle.latest_feature().theta(); const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (!obstacle_ptr) { continue; } if (!obstacle_ptr->IsPedestrian() || obstacle_ptr->history_size() == 0) { continue; } const Feature& obs_feature = obstacle_ptr->latest_feature(); double obs_x = obs_feature.position().x(); double obs_y = obs_feature.position().y(); double diff_x = obs_x - ego_position.x(); double diff_y = obs_y - ego_position.y(); double inner_prod = std::cos(ego_heading) * diff_x + std::sin(ego_heading) * diff_y; if (inner_prod < 0.0) { continue; } SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); } } void ObstaclesPrioritizer::RankingCautionLevelObstacles( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { const Point3D& ego_position = ego_vehicle.latest_feature().position(); const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); std::priority_queue<std::pair<double, Obstacle*>> caution_obstacle_queue; for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << obstacle_id << "] Not found"; continue; } if (!obstacle_ptr->IsCaution()) { continue; } const Point3D& obstacle_position = obstacle_ptr->latest_feature().position(); double distance = std::hypot(obstacle_position.x() - ego_position.x(), obstacle_position.y() - ego_position.y()); caution_obstacle_queue.push({distance, obstacle_ptr}); } while (static_cast<int>(caution_obstacle_queue.size()) > FLAGS_caution_obs_max_nums) { Obstacle* obstacle_ptr = caution_obstacle_queue.top().second; obstacle_ptr->mutable_latest_feature()->mutable_priority()->set_priority( ObstaclePriority::NORMAL); caution_obstacle_queue.pop(); } } void ObstaclesPrioritizer::AssignCautionByMerge( const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { SetCautionBackward(FLAGS_caution_search_distance_backward_for_merge, ego_vehicle, lane_info_ptr, visited_lanes, obstacles_container); } void ObstaclesPrioritizer::AssignCautionByOverlap( const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { std::string lane_id = lane_info_ptr->id().id(); const std::vector<std::shared_ptr<const OverlapInfo>> cross_lanes = lane_info_ptr->cross_lanes(); for (const auto overlap_ptr : cross_lanes) { bool consider_overlap = true; for (const auto& object : overlap_ptr->overlap().object()) { if (object.id().id() == lane_info_ptr->id().id() && object.lane_overlap_info().end_s() < ego_lane_s_) { consider_overlap = false; } } if (!consider_overlap) { continue; } for (const auto& object : overlap_ptr->overlap().object()) { const auto& object_id = object.id().id(); if (object_id == lane_info_ptr->id().id()) { continue; } std::shared_ptr<const LaneInfo> overlap_lane_ptr = PredictionMap::LaneById(object_id); // ahead_s is the length in front of the overlap double ahead_s = overlap_lane_ptr->total_length() - object.lane_overlap_info().start_s(); SetCautionBackward( ahead_s + FLAGS_caution_search_distance_backward_for_overlap, ego_vehicle, overlap_lane_ptr, visited_lanes, obstacles_container); } } } void ObstaclesPrioritizer::SetCautionBackward( const double max_distance, const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> start_lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { std::string start_lane_id = start_lane_info_ptr->id().id(); if (ego_back_lane_id_set_.find(start_lane_id) != ego_back_lane_id_set_.end()) { return; } std::unordered_map<std::string, std::vector<LaneObstacle>> lane_obstacles = obstacles_container->GetClustersPtr()->GetLaneObstacles(); std::queue<std::pair<ConstLaneInfoPtr, double>> lane_info_queue; lane_info_queue.emplace(start_lane_info_ptr, start_lane_info_ptr->total_length()); while (!lane_info_queue.empty()) { ConstLaneInfoPtr curr_lane = lane_info_queue.front().first; double cumu_distance = lane_info_queue.front().second; lane_info_queue.pop(); const std::string& lane_id = curr_lane->id().id(); if (visited_lanes->find(lane_id) == visited_lanes->end() && lane_obstacles.find(lane_id) != lane_obstacles.end() && !lane_obstacles[lane_id].empty()) { visited_lanes->insert(lane_id); // find the obstacle with largest lane_s on the lane int obstacle_id = lane_obstacles[lane_id].front().obstacle_id(); double obstacle_s = lane_obstacles[lane_id].front().lane_s(); for (const LaneObstacle& lane_obstacle : lane_obstacles[lane_id]) { if (lane_obstacle.lane_s() > obstacle_s) { obstacle_id = lane_obstacle.obstacle_id(); obstacle_s = lane_obstacle.lane_s(); } } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << obstacle_id << "] Not found"; continue; } SetCautionIfCloseToEgo(ego_vehicle, FLAGS_caution_distance_threshold, obstacle_ptr); continue; } if (cumu_distance > max_distance) { continue; } for (const auto& pre_lane_id : curr_lane->lane().predecessor_id()) { if (ego_back_lane_id_set_.find(pre_lane_id.id()) != ego_back_lane_id_set_.end()) { continue; } ConstLaneInfoPtr pre_lane_ptr = PredictionMap::LaneById(pre_lane_id.id()); lane_info_queue.emplace(pre_lane_ptr, cumu_distance + pre_lane_ptr->total_length()); } } } void ObstaclesPrioritizer::SetCautionIfCloseToEgo( const Obstacle& ego_vehicle, const double distance_threshold, Obstacle* obstacle_ptr) { const Point3D& obstacle_position = obstacle_ptr->latest_feature().position(); const Point3D& ego_position = ego_vehicle.latest_feature().position(); double diff_x = obstacle_position.x() - ego_position.x(); double diff_y = obstacle_position.y() - ego_position.y(); double distance = std::hypot(diff_x, diff_y); if (distance < distance_threshold) { obstacle_ptr->SetCaution(); } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/prioritization/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "obstacles_prioritizer", srcs = ["obstacles_prioritizer.cc"], hdrs = ["obstacles_prioritizer.h"], copts = ['-DMODULE_NAME=\\"prediction\\"'], deps = [ "//modules/prediction/common:environment_features", "//modules/prediction/container:container_manager", "//modules/prediction/container/obstacles:obstacle_clusters", "//modules/prediction/container/obstacles:obstacles_container", "//modules/prediction/container/pose:pose_container", "//modules/prediction/scenario/scenario_features", "//modules/prediction/scenario/scenario_features:cruise_scenario_features", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/prioritization/obstacles_prioritizer.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <unordered_set> #include <vector> #include "cyber/common/macros.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/scenario/scenario_features/cruise_scenario_features.h" #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { class ObstaclesPrioritizer { public: ObstaclesPrioritizer() = delete; explicit ObstaclesPrioritizer( const std::shared_ptr<ContainerManager>& container_manager); void AssignIgnoreLevel(); void AssignCautionLevel(); private: void AssignCautionLevelInJunction(const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container, const std::string& junction_id); void AssignCautionLevelCruiseKeepLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignCautionLevelCruiseChangeLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignCautionLevelByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignCautionLevelPedestrianByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignCautionLevelPedestrianInFront( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void RankingCautionLevelObstacles(const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignCautionByMerge( const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void AssignCautionByOverlap( const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void SetCautionBackward( const double distance, const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> start_lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void SetCautionIfCloseToEgo(const Obstacle& ego_vehicle, const double distance_threshold, Obstacle* obstacle_ptr); private: std::unordered_set<std::string> ego_back_lane_id_set_; std::shared_ptr<ContainerManager> container_manager_; std::string ego_lane_id_ = ""; double ego_lane_s_ = 0.0; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/cruise_scenario_features_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/scenario_features/cruise_scenario_features.h" #include "gtest/gtest.h" namespace apollo { namespace prediction { class CruiseScenarioFeaturesTest : public ::testing::Test { public: void SetUp() override {} }; TEST_F(CruiseScenarioFeaturesTest, LaneId) { CruiseScenarioFeatures cruise_scenario_features; EXPECT_FALSE(cruise_scenario_features.IsLaneOfInterest("1-1")); cruise_scenario_features.InsertLaneOfInterest("1-1"); EXPECT_TRUE(cruise_scenario_features.IsLaneOfInterest("1-1")); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/junction_scenario_features.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #pragma once #include "modules/prediction/common/environment_features.h" #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { class JunctionScenarioFeatures : public ScenarioFeatures { public: JunctionScenarioFeatures(); virtual ~JunctionScenarioFeatures(); void BuildJunctionScenarioFeatures( const EnvironmentFeatures& environment_features); }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/junction_scenario_features.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/prediction/scenario/scenario_features/junction_scenario_features.h" namespace apollo { namespace prediction { JunctionScenarioFeatures::JunctionScenarioFeatures() { scenario_.set_type(Scenario::JUNCTION); } JunctionScenarioFeatures::~JunctionScenarioFeatures() {} void JunctionScenarioFeatures::BuildJunctionScenarioFeatures( const EnvironmentFeatures& environment_features) { // ACHECK(environment_features.has_front_junction()); scenario_.set_junction_id(environment_features.GetFrontJunction().first); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/cruise_scenario_features.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #pragma once #include <string> #include <unordered_set> #include "modules/prediction/common/environment_features.h" #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { class CruiseScenarioFeatures : public ScenarioFeatures { public: CruiseScenarioFeatures(); virtual ~CruiseScenarioFeatures(); bool IsLaneOfInterest(const std::string& lane_id) const; void InsertLaneOfInterest(const std::string& lane_id); void BuildCruiseScenarioFeatures( const EnvironmentFeatures& environment_features); private: void SearchForwardAndInsert(const std::string& lane_id, const double start_lane_s, const double range); std::unordered_set<std::string> lane_ids_of_interest_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/scenario_features.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #pragma once #include "modules/common_msgs/prediction_msgs/scenario.pb.h" namespace apollo { namespace prediction { class ScenarioFeatures { public: ScenarioFeatures(); virtual ~ScenarioFeatures() = default; const Scenario& scenario() const; protected: Scenario scenario_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/scenario_features.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/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { ScenarioFeatures::ScenarioFeatures() { scenario_.set_type(Scenario::UNKNOWN); } const Scenario& ScenarioFeatures::scenario() const { return scenario_; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/cruise_scenario_features.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/prediction/scenario/scenario_features/cruise_scenario_features.h" #include <memory> #include <queue> #include <utility> #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>; using apollo::hdmap::Lane; CruiseScenarioFeatures::CruiseScenarioFeatures() { scenario_.set_type(Scenario::CRUISE); } CruiseScenarioFeatures::~CruiseScenarioFeatures() {} bool CruiseScenarioFeatures::IsLaneOfInterest( const std::string& lane_id) const { return lane_ids_of_interest_.find(lane_id) != lane_ids_of_interest_.end(); } void CruiseScenarioFeatures::InsertLaneOfInterest(const std::string& lane_id) { lane_ids_of_interest_.insert(lane_id); } void CruiseScenarioFeatures::BuildCruiseScenarioFeatures( const EnvironmentFeatures& environment_features) { // Forward lanes if (environment_features.has_ego_lane()) { auto ego_lane = environment_features.GetEgoLane(); const std::string& ego_lane_id = ego_lane.first; double ego_lane_s = ego_lane.second; SearchForwardAndInsert(ego_lane_id, ego_lane_s, 50.0); } if (environment_features.has_left_neighbor_lane()) { auto left_lane = environment_features.GetLeftNeighborLane(); const std::string& left_lane_id = left_lane.first; double left_lane_s = left_lane.second; SearchForwardAndInsert(left_lane_id, left_lane_s, 50.0); } if (environment_features.has_right_neighbor_lane()) { auto right_lane = environment_features.GetRightNeighborLane(); const std::string& right_lane_id = right_lane.first; double right_lane_s = right_lane.second; SearchForwardAndInsert(right_lane_id, right_lane_s, 50.0); } // Reverse lanes const std::unordered_set<std::string>& reverse_lane_ids = environment_features.nonneglectable_reverse_lanes(); if (reverse_lane_ids.empty()) { ADEBUG << "No reverse lane considered"; } for (const std::string& reverse_lane_id : reverse_lane_ids) { lane_ids_of_interest_.insert(reverse_lane_id); } for (const std::string& reverse_lane_id : reverse_lane_ids) { std::shared_ptr<const LaneInfo> reverse_lane_info = PredictionMap::LaneById(reverse_lane_id); for (const auto& prede_id : reverse_lane_info->lane().predecessor_id()) { lane_ids_of_interest_.insert(prede_id.id()); } } } void CruiseScenarioFeatures::SearchForwardAndInsert( const std::string& start_lane_id, const double start_lane_s, const double range) { ConstLaneInfoPtr start_lane_info = PredictionMap::LaneById(start_lane_id); double start_lane_length = start_lane_info->total_length(); double start_accumulated_s = start_lane_length - start_lane_s; std::queue<std::pair<ConstLaneInfoPtr, double>> lane_queue; lane_queue.emplace(start_lane_info, start_accumulated_s); while (!lane_queue.empty()) { ConstLaneInfoPtr lane_info = lane_queue.front().first; double accumulated_s = lane_queue.front().second; lane_queue.pop(); InsertLaneOfInterest(lane_info->id().id()); const Lane& lane = lane_info->lane(); for (const auto prede_lane_id : lane.predecessor_id()) { InsertLaneOfInterest(prede_lane_id.id()); } if (accumulated_s > range) { continue; } for (const auto succ_lane_id : lane.successor_id()) { ConstLaneInfoPtr succ_lane_info = PredictionMap::LaneById(succ_lane_id.id()); double succ_lane_length = succ_lane_info->total_length(); lane_queue.emplace(succ_lane_info, accumulated_s + succ_lane_length); } } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/scenario_features/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "scenario_features", srcs = ["scenario_features.cc"], hdrs = ["scenario_features.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/common_msgs/prediction_msgs:scenario_cc_proto", ], ) cc_library( name = "cruise_scenario_features", srcs = ["cruise_scenario_features.cc"], hdrs = ["cruise_scenario_features.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ ":scenario_features", "//modules/prediction/common:environment_features", "//modules/prediction/common:prediction_map", ], ) cc_library( name = "junction_scenario_features", srcs = ["junction_scenario_features.cc"], hdrs = ["junction_scenario_features.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ ":scenario_features", "//modules/prediction/common:environment_features", ], ) cc_test( name = "cruise_scenario_features_test", size = "small", srcs = ["cruise_scenario_features_test.cc"], deps = [ ":cruise_scenario_features", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/right_of_way/right_of_way.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/prediction/scenario/right_of_way/right_of_way.h" #include <limits> #include <memory> #include <string> #include <unordered_set> #include <vector> #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; using apollo::hdmap::LaneInfo; using apollo::perception::PerceptionObstacle; void RightOfWay::Analyze(ContainerManager* container_manager) { ObstaclesContainer* obstacles_container = container_manager->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); if (obstacles_container == nullptr) { AERROR << "Null obstacles container found"; return; } ADCTrajectoryContainer* adc_trajectory_container = container_manager->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); if (adc_trajectory_container == nullptr) { AERROR << "adc_trajectory_container is nullptr"; return; } const std::vector<std::string>& lane_ids = adc_trajectory_container->GetADCLaneIDSequence(); if (lane_ids.empty()) { return; } auto pose_container = container_manager->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION); if (pose_container == nullptr) { AERROR << "Pose container pointer is a null pointer."; return; } const PerceptionObstacle* pose_obstacle_ptr = pose_container->ToPerceptionObstacle(); if (pose_obstacle_ptr == nullptr) { AERROR << "Pose obstacle pointer is a null pointer."; return; } double pose_x = pose_obstacle_ptr->position().x(); double pose_y = pose_obstacle_ptr->position().y(); double ego_vehicle_s = std::numeric_limits<double>::max(); double ego_vehicle_l = std::numeric_limits<double>::max(); double accumulated_s = 0.0; std::string ego_lane_id = ""; // loop for lane_ids to findout ego_vehicle_s and lane_id for (const std::string& lane_id : lane_ids) { std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } double s = 0.0; double l = 0.0; if (PredictionMap::GetProjection({pose_x, pose_y}, lane_info_ptr, &s, &l)) { if (std::fabs(l) < std::fabs(ego_vehicle_l)) { ego_vehicle_s = accumulated_s + s; ego_vehicle_l = l; ego_lane_id = lane_id; } } accumulated_s += lane_info_ptr->total_length(); } // loop again to assign ego_back_lane_id_set_ & ego_front_lane_id_set_ accumulated_s = 0.0; std::unordered_set<std::string> ego_back_lane_id_set_; std::unordered_set<std::string> ego_front_lane_id_set_; for (const std::string& lane_id : lane_ids) { std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } accumulated_s += lane_info_ptr->total_length(); if (accumulated_s < ego_vehicle_s) { ego_back_lane_id_set_.insert(lane_id); } else if (accumulated_s > ego_vehicle_s) { ego_front_lane_id_set_.insert(lane_id); } } // then loop through all obstacle vehicles for (const int id : obstacles_container->curr_frame_considered_obstacle_ids()) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(id); if (obstacle_ptr == nullptr) { continue; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); if (latest_feature_ptr->type() != PerceptionObstacle::VEHICLE) { continue; } ADEBUG << "RightOfWay for obstacle [" << latest_feature_ptr->id() << "], " << "with lane_sequence_size: " << latest_feature_ptr->lane().lane_graph().lane_sequence_size(); for (auto& lane_sequence : *latest_feature_ptr->mutable_lane() ->mutable_lane_graph() ->mutable_lane_sequence()) { accumulated_s = 0.0; for (auto lane_segment : lane_sequence.lane_segment()) { accumulated_s += lane_segment.end_s() - lane_segment.start_s(); // set lower righ_of_way for turn lanes if (lane_segment.lane_turn_type() == 2) { // left_turn lane_sequence.set_right_of_way(-20); } else if (lane_segment.lane_turn_type() == 3) { // right_turn lane_sequence.set_right_of_way(-10); } if (accumulated_s > 50.0) { break; } } } } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/right_of_way/right_of_way.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "modules/prediction/container/container_manager.h" namespace apollo { namespace prediction { class RightOfWay { public: /** * @brief Constructor */ RightOfWay() = delete; /** * @brief Set right_of_way for all lane_sequence * @return Scenario features */ static void Analyze(ContainerManager* container_manager); }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/right_of_way/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "right_of_way", srcs = ["right_of_way.cc"], hdrs = ["right_of_way.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/prediction/container:container_manager", "//modules/prediction/container/obstacles:obstacles_container", "//modules/prediction/container/pose:pose_container", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/interaction_filter/interaction_filter.h
/****************************************************************************** * Copyright 2021 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <unordered_set> #include <vector> #include "cyber/common/macros.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/scenario/scenario_features/cruise_scenario_features.h" #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { class InteractionFilter { public: InteractionFilter() = delete; explicit InteractionFilter( const std::shared_ptr<ContainerManager>& container_manager); /** * @brief Assign interactive tag for vehicle type obstacles which are close to ADC */ void AssignInteractiveTag(); private: /** * @brief Assign interactive tag for obstacles in junction */ void AssignInteractiveTagInJunction(const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container, const std::string& junction_id); /** * @brief Assign interactive tag for obstacles in the cruising lane * which are in front of ADC */ void AssignInteractiveTagCruiseKeepLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); /** * @brief Assign interactive tag for obstacles in the target lane * which are close to ADC(include backward obstacles) during lane change */ void AssignInteractiveTagCruiseChangeLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); /** * @brief Assign interactive tag for obstacles that may interact with ADC * according to the ADC's trajectory */ void AssignInteractiveTagByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void RankingInteractiveTagObstacles(const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container); void AssignInteractiveByMerge( const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void AssignInteractiveByOverlap( const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void SetInteractiveBackward( const double distance, const Obstacle& ego_vehicle, std::shared_ptr<const hdmap::LaneInfo> start_lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container); void SetInteractiveIfCloseToEgo(const Obstacle& ego_vehicle, const double distance_threshold, Obstacle* obstacle_ptr); private: std::unordered_set<std::string> ego_back_lane_id_set_; std::shared_ptr<ContainerManager> container_manager_; std::string ego_lane_id_ = ""; double ego_lane_s_ = 0.0; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/interaction_filter/interaction_filter.cc
/****************************************************************************** * Copyright 2021 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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/prediction/scenario/interaction_filter/interaction_filter.h" #include <limits> #include <queue> #include <unordered_map> #include <utility> #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/obstacles/obstacle_clusters.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/container/storytelling/storytelling_container.h" namespace apollo { namespace prediction { using apollo::common::Point3D; using apollo::common::adapter::AdapterConfig; using apollo::hdmap::LaneInfo; using apollo::hdmap::OverlapInfo; using apollo::perception::PerceptionObstacle; using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>; namespace { bool IsLaneSequenceInReferenceLine( const LaneSequence& lane_sequence, const ADCTrajectoryContainer* ego_trajectory_container) { for (const auto& lane_segment : lane_sequence.lane_segment()) { std::string lane_id = lane_segment.lane_id(); if (ego_trajectory_container->IsLaneIdInTargetReferenceLine(lane_id)) { return true; } } return false; } int NearestFrontObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) { int nearest_front_obstacle_id = std::numeric_limits<int>::min(); double smallest_relative_s = std::numeric_limits<double>::max(); for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) { if (nearby_obs.s() < 0.0 || nearby_obs.s() > FLAGS_interaction_search_distance_ahead) { continue; } if (nearby_obs.s() < smallest_relative_s) { smallest_relative_s = nearby_obs.s(); nearest_front_obstacle_id = nearby_obs.id(); } } return nearest_front_obstacle_id; } int NearestBackwardObstacleIdOnLaneSequence(const LaneSequence& lane_sequence) { int nearest_backward_obstacle_id = std::numeric_limits<int>::min(); double smallest_relative_s = std::numeric_limits<double>::max(); for (const auto& nearby_obs : lane_sequence.nearby_obstacle()) { if (nearby_obs.s() > 0.0 || nearby_obs.s() < -FLAGS_interaction_search_distance_backward) { continue; } if (-nearby_obs.s() < smallest_relative_s) { smallest_relative_s = -nearby_obs.s(); nearest_backward_obstacle_id = nearby_obs.id(); } } return nearest_backward_obstacle_id; } } // namespace InteractionFilter::InteractionFilter( const std::shared_ptr<ContainerManager>& container_manager) : container_manager_(container_manager) {} void InteractionFilter::AssignInteractiveTag() { auto obstacles_container = container_manager_->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); if (obstacles_container == nullptr) { AERROR << "Obstacles container pointer is a null pointer."; return; } Obstacle* ego_vehicle = obstacles_container->GetObstacle(FLAGS_ego_vehicle_id); if (ego_vehicle == nullptr) { AERROR << "Ego vehicle not found"; return; } if (ego_vehicle->history_size() == 0) { AERROR << "Ego vehicle has no history"; return; } const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle pointer found."; continue; } if (obstacle_ptr->history_size() == 0) { AERROR << "Obstacle [" << obstacle_ptr->id() << "] has no feature."; continue; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); latest_feature_ptr->mutable_interactive_tag()->set_interactive_tag( ObstacleInteractiveTag::NONINTERACTION); } auto storytelling_container = container_manager_->GetContainer<StoryTellingContainer>( AdapterConfig::STORYTELLING); if (storytelling_container->ADCDistanceToJunction() < FLAGS_junction_distance_threshold) { AssignInteractiveTagInJunction(*ego_vehicle, obstacles_container, storytelling_container->ADCJunctionId()); } AssignInteractiveTagCruiseKeepLane(*ego_vehicle, obstacles_container); AssignInteractiveTagCruiseChangeLane(*ego_vehicle, obstacles_container); AssignInteractiveTagByEgoReferenceLine(*ego_vehicle, obstacles_container); if (FLAGS_enable_rank_interactive_obstacles) { RankingInteractiveTagObstacles(*ego_vehicle, obstacles_container); } } void InteractionFilter::AssignInteractiveTagInJunction( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container, const std::string& junction_id) { const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Null obstacle pointer found."; continue; } if (obstacle_ptr->IsInJunction(junction_id)) { SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, obstacle_ptr); } } } void InteractionFilter::AssignInteractiveTagCruiseKeepLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { const Feature& ego_latest_feature = ego_vehicle.latest_feature(); for (const LaneSequence& lane_sequence : ego_latest_feature.lane().lane_graph().lane_sequence()) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id < 0) { continue; } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found"; continue; } SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, obstacle_ptr); } } void InteractionFilter::AssignInteractiveTagCruiseChangeLane( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { ADCTrajectoryContainer* ego_trajectory_container = container_manager_->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); const Feature& ego_latest_feature = ego_vehicle.latest_feature(); for (const LaneSequence& lane_sequence : ego_latest_feature.lane().lane_graph().lane_sequence()) { if (lane_sequence.vehicle_on_lane()) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id < 0) { continue; } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << nearest_front_obstacle_id << "] Not found"; continue; } SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, obstacle_ptr); } else if (IsLaneSequenceInReferenceLine(lane_sequence, ego_trajectory_container)) { int nearest_front_obstacle_id = NearestFrontObstacleIdOnLaneSequence(lane_sequence); int nearest_backward_obstacle_id = NearestBackwardObstacleIdOnLaneSequence(lane_sequence); if (nearest_front_obstacle_id >= 0) { Obstacle* front_obstacle_ptr = obstacles_container->GetObstacle(nearest_front_obstacle_id); if (front_obstacle_ptr != nullptr) { SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, front_obstacle_ptr); } } if (nearest_backward_obstacle_id >= 0) { Obstacle* backward_obstacle_ptr = obstacles_container->GetObstacle(nearest_backward_obstacle_id); if (backward_obstacle_ptr != nullptr) { SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, backward_obstacle_ptr); } } } } } void InteractionFilter::AssignInteractiveTagByEgoReferenceLine( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { ADCTrajectoryContainer* adc_trajectory_container = container_manager_->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); if (adc_trajectory_container == nullptr) { AERROR << "adc_trajectory_container is nullptr"; return; } const std::vector<std::string>& lane_ids = adc_trajectory_container->GetADCTargetLaneIDSequence(); if (lane_ids.empty()) { return; } const Feature& ego_feature = ego_vehicle.latest_feature(); double ego_x = ego_feature.position().x(); double ego_y = ego_feature.position().y(); double ego_vehicle_s = std::numeric_limits<double>::max(); double ego_vehicle_l = std::numeric_limits<double>::max(); double accumulated_s = 0.0; // first loop for lane_ids to findout ego_vehicle_s for (const std::string& lane_id : lane_ids) { std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } double s = 0.0; double l = 0.0; if (PredictionMap::GetProjection({ego_x, ego_y}, lane_info_ptr, &s, &l)) { if (std::fabs(l) < std::fabs(ego_vehicle_l)) { ego_vehicle_s = accumulated_s + s; ego_vehicle_l = l; ego_lane_id_ = lane_id; ego_lane_s_ = s; } } accumulated_s += lane_info_ptr->total_length(); } // insert ego_back_lane_id accumulated_s = 0.0; for (const std::string& lane_id : lane_ids) { if (lane_id == ego_lane_id_) { break; } ego_back_lane_id_set_.insert(lane_id); } std::unordered_set<std::string> visited_lanes(lane_ids.begin(), lane_ids.end()); // then loop through lane_ids to AssignInteractive for obstacle vehicles for (const std::string& lane_id : lane_ids) { if (ego_back_lane_id_set_.find(lane_id) != ego_back_lane_id_set_.end()) { continue; } std::shared_ptr<const LaneInfo> lane_info_ptr = PredictionMap::LaneById(lane_id); if (lane_info_ptr == nullptr) { AERROR << "Null lane info pointer found."; continue; } accumulated_s += lane_info_ptr->total_length(); if (lane_id != ego_lane_id_) { AssignInteractiveByMerge(ego_vehicle, lane_info_ptr, &visited_lanes, obstacles_container); } AssignInteractiveByOverlap(ego_vehicle, lane_info_ptr, &visited_lanes, obstacles_container); if (accumulated_s > FLAGS_interaction_search_distance_ahead + ego_vehicle_s) { break; } } } void InteractionFilter::RankingInteractiveTagObstacles( const Obstacle& ego_vehicle, ObstaclesContainer* obstacles_container) { const Point3D& ego_position = ego_vehicle.latest_feature().position(); const auto& obstacle_ids = obstacles_container->curr_frame_movable_obstacle_ids(); std::priority_queue<std::pair<double, Obstacle*>> interactive_obstacle_queue; for (const int obstacle_id : obstacle_ids) { Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << obstacle_id << "] Not found"; continue; } if (!obstacle_ptr->IsInteractiveObstacle()) { continue; } const Point3D& obstacle_position = obstacle_ptr->latest_feature().position(); double distance = std::hypot(obstacle_position.x() - ego_position.x(), obstacle_position.y() - ego_position.y()); interactive_obstacle_queue.push({distance, obstacle_ptr}); } while (static_cast<int>(interactive_obstacle_queue.size()) > FLAGS_interactive_obs_max_nums) { Obstacle* obstacle_ptr = interactive_obstacle_queue.top().second; obstacle_ptr->mutable_latest_feature()-> mutable_interactive_tag()->set_interactive_tag( ObstacleInteractiveTag::INTERACTION); interactive_obstacle_queue.pop(); } } void InteractionFilter::AssignInteractiveByMerge( const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { SetInteractiveBackward(FLAGS_interaction_search_distance_backward_for_merge, ego_vehicle, lane_info_ptr, visited_lanes, obstacles_container); } void InteractionFilter::AssignInteractiveByOverlap( const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { std::string lane_id = lane_info_ptr->id().id(); const std::vector<std::shared_ptr<const OverlapInfo>> cross_lanes = lane_info_ptr->cross_lanes(); for (const auto overlap_ptr : cross_lanes) { bool consider_overlap = true; for (const auto& object : overlap_ptr->overlap().object()) { if (object.id().id() == lane_info_ptr->id().id() && object.lane_overlap_info().end_s() < ego_lane_s_) { consider_overlap = false; } } if (!consider_overlap) { continue; } for (const auto& object : overlap_ptr->overlap().object()) { const auto& object_id = object.id().id(); if (object_id == lane_info_ptr->id().id()) { continue; } std::shared_ptr<const LaneInfo> overlap_lane_ptr = PredictionMap::LaneById(object_id); // ahead_s is the length in front of the overlap double ahead_s = overlap_lane_ptr->total_length() - object.lane_overlap_info().start_s(); SetInteractiveBackward( ahead_s + FLAGS_interaction_search_distance_backward_for_overlap, ego_vehicle, overlap_lane_ptr, visited_lanes, obstacles_container); } } } void InteractionFilter::SetInteractiveBackward( const double max_distance, const Obstacle& ego_vehicle, std::shared_ptr<const LaneInfo> start_lane_info_ptr, std::unordered_set<std::string>* const visited_lanes, ObstaclesContainer* obstacles_container) { std::string start_lane_id = start_lane_info_ptr->id().id(); if (ego_back_lane_id_set_.find(start_lane_id) != ego_back_lane_id_set_.end()) { return; } std::unordered_map<std::string, std::vector<LaneObstacle>> lane_obstacles = obstacles_container->GetClustersPtr()->GetLaneObstacles(); std::queue<std::pair<ConstLaneInfoPtr, double>> lane_info_queue; lane_info_queue.emplace(start_lane_info_ptr, start_lane_info_ptr->total_length()); while (!lane_info_queue.empty()) { ConstLaneInfoPtr curr_lane = lane_info_queue.front().first; double cumu_distance = lane_info_queue.front().second; lane_info_queue.pop(); const std::string& lane_id = curr_lane->id().id(); if (visited_lanes->find(lane_id) == visited_lanes->end() && lane_obstacles.find(lane_id) != lane_obstacles.end() && !lane_obstacles[lane_id].empty()) { visited_lanes->insert(lane_id); // find the obstacle with largest lane_s on the lane int obstacle_id = lane_obstacles[lane_id].front().obstacle_id(); double obstacle_s = lane_obstacles[lane_id].front().lane_s(); for (const LaneObstacle& lane_obstacle : lane_obstacles[lane_id]) { if (lane_obstacle.lane_s() > obstacle_s) { obstacle_id = lane_obstacle.obstacle_id(); obstacle_s = lane_obstacle.lane_s(); } } Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id); if (obstacle_ptr == nullptr) { AERROR << "Obstacle [" << obstacle_id << "] Not found"; continue; } SetInteractiveIfCloseToEgo(ego_vehicle, FLAGS_interaction_distance_threshold, obstacle_ptr); continue; } if (cumu_distance > max_distance) { continue; } for (const auto& pre_lane_id : curr_lane->lane().predecessor_id()) { if (ego_back_lane_id_set_.find(pre_lane_id.id()) != ego_back_lane_id_set_.end()) { continue; } ConstLaneInfoPtr pre_lane_ptr = PredictionMap::LaneById(pre_lane_id.id()); lane_info_queue.emplace(pre_lane_ptr, cumu_distance + pre_lane_ptr->total_length()); } } } void InteractionFilter::SetInteractiveIfCloseToEgo( const Obstacle& ego_vehicle, const double distance_threshold, Obstacle* obstacle_ptr) { const Point3D& obstacle_position = obstacle_ptr->latest_feature().position(); const Point3D& ego_position = ego_vehicle.latest_feature().position(); double diff_x = obstacle_position.x() - ego_position.x(); double diff_y = obstacle_position.y() - ego_position.y(); double distance = std::hypot(diff_x, diff_y); // Add interactive tag only for vehicles if (distance < distance_threshold && obstacle_ptr->latest_feature().type() == PerceptionObstacle::VEHICLE) { obstacle_ptr->SetInteractiveTag(); } else { obstacle_ptr->SetNonInteractiveTag(); } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/interaction_filter/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "interaction_filter", srcs = ["interaction_filter.cc"], hdrs = ["interaction_filter.h"], copts = ['-DMODULE_NAME=\\"prediction\\"'], deps = [ "//modules/prediction/common:environment_features", "//modules/prediction/container:container_manager", "//modules/prediction/container/obstacles:obstacle_clusters", "//modules/prediction/container/obstacles:obstacles_container", "//modules/prediction/container/pose:pose_container", "//modules/prediction/scenario/scenario_features", "//modules/prediction/scenario/scenario_features:cruise_scenario_features", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/feature_extractor/feature_extractor.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/prediction/scenario/feature_extractor/feature_extractor.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using common::adapter::AdapterConfig; using common::math::Vec2d; using hdmap::JunctionInfo; using hdmap::LaneInfo; using LaneInfoPtr = std::shared_ptr<const LaneInfo>; using JunctionInfoPtr = std::shared_ptr<const JunctionInfo>; EnvironmentFeatures FeatureExtractor::ExtractEnvironmentFeatures( ContainerManager* container_manager) { EnvironmentFeatures environment_features; auto ego_state_container = container_manager->GetContainer<PoseContainer>( AdapterConfig::LOCALIZATION); if (ego_state_container == nullptr || ego_state_container->ToPerceptionObstacle() == nullptr) { AERROR << "Null ego state container found or " "the container pointer is nullptr"; return environment_features; } auto ptr_ego_state = ego_state_container->ToPerceptionObstacle(); if (!ptr_ego_state->has_position() || !ptr_ego_state->position().has_x() || !ptr_ego_state->position().has_y() || !ptr_ego_state->has_theta() || !ptr_ego_state->has_velocity() || !ptr_ego_state->velocity().has_x() || !ptr_ego_state->velocity().has_y()) { AERROR << "Incomplete ego pose information."; return environment_features; } if (std::isnan(ptr_ego_state->position().x()) || std::isnan(ptr_ego_state->position().y()) || std::isnan(ptr_ego_state->theta()) || std::isnan(ptr_ego_state->velocity().x()) || std::isnan(ptr_ego_state->velocity().y())) { AERROR << "nan found in ego state"; return environment_features; } Vec2d ego_position(ptr_ego_state->position().x(), ptr_ego_state->position().y()); Vec2d ego_velocity(ptr_ego_state->velocity().x(), ptr_ego_state->velocity().y()); environment_features.set_ego_speed(ego_velocity.Length()); environment_features.set_ego_heading(ptr_ego_state->theta()); auto ptr_ego_lane = GetEgoLane(ptr_ego_state->position(), ptr_ego_state->theta()); ExtractEgoLaneFeatures(&environment_features, ptr_ego_lane, ego_position); ExtractNeighborLaneFeatures(&environment_features, ptr_ego_lane, ego_position); ExtractFrontJunctionFeatures(&environment_features, container_manager); return environment_features; } void FeatureExtractor::ExtractEgoLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const common::math::Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { ADEBUG << "Ego vehicle is not on any lane."; return; } ADEBUG << "Ego vehicle is on lane [" << ptr_ego_lane->id().id() << "]"; double curr_lane_s = 0.0; double curr_lane_l = 0.0; ptr_ego_lane->GetProjection(ego_position, &curr_lane_s, &curr_lane_l); ptr_environment_features->SetEgoLane(ptr_ego_lane->id().id(), curr_lane_s); double threshold = 1.0; auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_left_neighbor_lane == nullptr && ptr_ego_lane->lane().has_left_boundary() && ptr_ego_lane->lane().left_boundary().boundary_type_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types(0) != hdmap::LaneBoundaryType::CURB) { const auto& reverse_lanes = ptr_ego_lane->lane().left_neighbor_reverse_lane_id(); std::for_each( reverse_lanes.begin(), reverse_lanes.end(), [&ptr_environment_features](decltype(*reverse_lanes.begin())& t) { ptr_environment_features->AddNonneglectableReverseLanes(t.id()); }); } } void FeatureExtractor::ExtractNeighborLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { ADEBUG << "Ego vehicle is not on any lane."; return; } auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, FLAGS_lane_distance_threshold); if (ptr_left_neighbor_lane != nullptr) { double left_neighbor_lane_s = 0.0; double left_neighbor_lane_l = 0.0; ptr_left_neighbor_lane->GetProjection(ego_position, &left_neighbor_lane_s, &left_neighbor_lane_l); ptr_environment_features->SetLeftNeighborLane( ptr_left_neighbor_lane->id().id(), left_neighbor_lane_s); } auto ptr_right_neighbor_lane = PredictionMap::GetRightNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, FLAGS_lane_distance_threshold); if (ptr_right_neighbor_lane != nullptr) { double right_neighbor_lane_s = 0.0; double right_neighbor_lane_l = 0.0; ptr_right_neighbor_lane->GetProjection(ego_position, &right_neighbor_lane_s, &right_neighbor_lane_l); ptr_environment_features->SetRightNeighborLane( ptr_right_neighbor_lane->id().id(), right_neighbor_lane_s); } } void FeatureExtractor::ExtractFrontJunctionFeatures( EnvironmentFeatures* ptr_environment_features, ContainerManager* container_manager) { auto ego_trajectory_container = container_manager->GetContainer<ADCTrajectoryContainer>( AdapterConfig::PLANNING_TRAJECTORY); if (ego_trajectory_container == nullptr) { AERROR << "Null ego trajectory container"; return; } JunctionInfoPtr junction = ego_trajectory_container->ADCJunction(); if (junction == nullptr) { return; } // Only consider junction have overlap with signal or stop_sign bool need_consider = FLAGS_enable_all_junction; for (const auto& overlap_id : junction->junction().overlap_id()) { if (PredictionMap::OverlapById(overlap_id.id()) != nullptr) { for (const auto& object : PredictionMap::OverlapById(overlap_id.id())->overlap().object()) { if (object.has_signal_overlap_info() || object.has_stop_sign_overlap_info()) { need_consider = true; } } } } if (need_consider) { ptr_environment_features->SetFrontJunction( junction->id().id(), ego_trajectory_container->ADCDistanceToJunction()); } } LaneInfoPtr FeatureExtractor::GetEgoLane(const common::Point3D& position, const double heading) { common::PointENU position_enu; position_enu.set_x(position.x()); position_enu.set_y(position.y()); position_enu.set_z(position.z()); return PredictionMap::GetMostLikelyCurrentLane( position_enu, FLAGS_lane_distance_threshold, heading, FLAGS_lane_angle_difference_threshold); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/feature_extractor/feature_extractor.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/prediction/common/environment_features.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { class FeatureExtractor { public: /** * @brief Constructor */ FeatureExtractor() = delete; /** * @brief Extract features for scenario analysis * @return Scenario features */ static EnvironmentFeatures ExtractEnvironmentFeatures( ContainerManager* container_manager); FRIEND_TEST(FeatureExtractorTest, junction); private: static void ExtractEgoLaneFeatures( EnvironmentFeatures* ptr_environment_features, const std::shared_ptr<const hdmap::LaneInfo>& ptr_ego_lane, const common::math::Vec2d& ego_position); static void ExtractNeighborLaneFeatures( EnvironmentFeatures* ptr_environment_features, const std::shared_ptr<const hdmap::LaneInfo>& ptr_ego_lane, const common::math::Vec2d& ego_position); static void ExtractFrontJunctionFeatures( EnvironmentFeatures* ptr_environment_features, ContainerManager* container_manager); static std::shared_ptr<const hdmap::LaneInfo> GetEgoLane( const common::Point3D& position, const double heading); }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/feature_extractor/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "feature_extractor", srcs = ["feature_extractor.cc"], hdrs = ["feature_extractor.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/prediction/container:container_manager", ], ) cc_test( name = "feature_extractor_test", size = "small", srcs = ["feature_extractor_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":feature_extractor", "//modules/prediction/common:kml_map_based_test", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/feature_extractor/feature_extractor_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/feature_extractor/feature_extractor.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; class FeatureExtractorTest : public KMLMapBasedTest {}; TEST_F(FeatureExtractorTest, junction) { std::unique_ptr<ContainerManager> container_manager(new ContainerManager()); container_manager->RegisterContainers(); std::unique_ptr<Container> adc_traj_container = container_manager->CreateContainer(AdapterConfig::PLANNING_TRAJECTORY); EnvironmentFeatures environment_features; FeatureExtractor::ExtractFrontJunctionFeatures(&environment_features, container_manager.get()); environment_features = FeatureExtractor::ExtractEnvironmentFeatures(container_manager.get()); EXPECT_FALSE(environment_features.has_front_junction()); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/analyzer/scenario_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. *****************************************************************************/ #pragma once #include <memory> #include "modules/prediction/common/environment_features.h" #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { class ScenarioAnalyzer { public: ScenarioAnalyzer() = delete; static std::shared_ptr<ScenarioFeatures> Analyze( const EnvironmentFeatures& environment_features); }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/analyzer/scenario_analyzer_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/analyzer/scenario_analyzer.h" #include "modules/prediction/common/kml_map_based_test.h" namespace apollo { namespace prediction { class ScenarioAnalyzerTest : public KMLMapBasedTest {}; TEST_F(ScenarioAnalyzerTest, unknown) { EnvironmentFeatures environment_features; auto ptr_scenario_features = ScenarioAnalyzer::Analyze(environment_features); EXPECT_EQ(ptr_scenario_features->scenario().type(), Scenario::UNKNOWN); } TEST_F(ScenarioAnalyzerTest, junction) { EnvironmentFeatures environment_features; environment_features.SetFrontJunction("1", 3.0); auto ptr_scenario_features = ScenarioAnalyzer::Analyze(environment_features); EXPECT_EQ(ptr_scenario_features->scenario().type(), Scenario::JUNCTION); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/analyzer/scenario_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/prediction/scenario/analyzer/scenario_analyzer.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/scenario/scenario_features/cruise_scenario_features.h" #include "modules/prediction/scenario/scenario_features/junction_scenario_features.h" namespace apollo { namespace prediction { std::shared_ptr<ScenarioFeatures> ScenarioAnalyzer::Analyze( const EnvironmentFeatures& environment_features) { Scenario::Type scenario_type = Scenario::UNKNOWN; if (environment_features.has_front_junction() && environment_features.GetFrontJunction().second < FLAGS_junction_distance_threshold) { scenario_type = Scenario::JUNCTION; } else if (environment_features.has_ego_lane()) { scenario_type = Scenario::CRUISE; } if (scenario_type == Scenario::CRUISE) { auto cruise_scenario_features = std::make_shared<CruiseScenarioFeatures>(); cruise_scenario_features->BuildCruiseScenarioFeatures(environment_features); return cruise_scenario_features; } if (scenario_type == Scenario::JUNCTION) { auto junction_scenario_features = std::make_shared<JunctionScenarioFeatures>(); // TODO(all) refactor this part junction_scenario_features->BuildJunctionScenarioFeatures( environment_features); return junction_scenario_features; } return std::make_shared<ScenarioFeatures>(); } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction/scenario
apollo_public_repos/apollo/modules/prediction/scenario/analyzer/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "scenario_analyzer", srcs = ["scenario_analyzer.cc"], hdrs = ["scenario_analyzer.h"], copts = [ "-DMODULE_NAME=\\\"prediction\\\"", ], deps = [ "//modules/prediction/scenario/scenario_features:cruise_scenario_features", "//modules/prediction/scenario/scenario_features:junction_scenario_features", ], ) cc_test( name = "scenario_analyzer_test", size = "small", srcs = ["scenario_analyzer_test.cc"], data = [ "//modules/prediction:prediction_data", "//modules/prediction:prediction_testdata", ], deps = [ ":scenario_analyzer", "//modules/prediction/common:kml_map_based_test", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/submodule_output.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Output information of prediction container submodule */ #pragma once #include <vector> #include "cyber/time/time.h" #include "modules/common/util/lru_cache.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/prediction/container/obstacles/obstacle.h" namespace apollo { namespace prediction { class SubmoduleOutput { public: /** * @brief Constructor */ SubmoduleOutput() = default; /** * @brief Destructor */ virtual ~SubmoduleOutput() = default; void InsertObstacle(const Obstacle&& obstacle); void InsertEgoVehicle(const Obstacle&& ego_vehicle); void set_curr_frame_movable_obstacle_ids( const std::vector<int>& curr_frame_movable_obstacle_ids); void set_curr_frame_unmovable_obstacle_ids( const std::vector<int>& curr_frame_unmovable_obstacle_ids); void set_curr_frame_considered_obstacle_ids( const std::vector<int>& curr_frame_considered_obstacle_ids); void set_frame_start_time(const apollo::cyber::Time& frame_start_time); void set_curr_scenario(const Scenario& scenario); const std::vector<Obstacle>& curr_frame_obstacles() const; const Obstacle& GetEgoVehicle() const; const std::vector<apollo::perception::PerceptionObstacle>& curr_frame_perception_obstacles() const; std::vector<int> curr_frame_movable_obstacle_ids() const; std::vector<int> curr_frame_unmovable_obstacle_ids() const; std::vector<int> curr_frame_considered_obstacle_ids() const; const apollo::cyber::Time& frame_start_time() const; const Scenario& curr_scenario() const { return curr_scenario_; } protected: std::vector<Obstacle> curr_frame_obstacles_; Obstacle ego_vehicle_; std::vector<int> curr_frame_movable_obstacle_ids_; std::vector<int> curr_frame_unmovable_obstacle_ids_; std::vector<int> curr_frame_considered_obstacle_ids_; apollo::cyber::Time frame_start_time_; Scenario curr_scenario_; }; } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/predictor_submodule.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Use predictor submodule to manage all predictors */ #pragma once #include <memory> #include <string> #include "cyber/component/component.h" #include "modules/prediction/common/message_process.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/submodules/submodule_output.h" namespace apollo { namespace prediction { class PredictorSubmodule : public cyber::Component<apollo::perception::PerceptionObstacles, ADCTrajectoryContainer, SubmoduleOutput> { public: /** * @brief Destructor */ ~PredictorSubmodule() = default; /** * @brief Get name of the node * @return Name of the node */ std::string Name() const; /** * @brief Initialize the node * @return If initialized */ bool Init() override; /** * @brief Data callback upon receiving a prediction evaluator output. * @param Prediction adc trajectory container. * @param Prediction evaluator output. */ bool Proc(const std::shared_ptr<apollo::perception::PerceptionObstacles>&, const std::shared_ptr<ADCTrajectoryContainer>&, const std::shared_ptr<SubmoduleOutput>&) override; private: std::shared_ptr<cyber::Writer<PredictionObstacles>> predictor_writer_; std::unique_ptr<PredictorManager> predictor_manager_; }; CYBER_REGISTER_COMPONENT(PredictorSubmodule) } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/submodule_output.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/prediction/submodules/submodule_output.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { void SubmoduleOutput::InsertObstacle(const Obstacle&& obstacle) { curr_frame_obstacles_.push_back(obstacle); } void SubmoduleOutput::InsertEgoVehicle(const Obstacle&& ego_vehicle) { ego_vehicle_ = ego_vehicle; } void SubmoduleOutput::set_curr_frame_movable_obstacle_ids( const std::vector<int>& curr_frame_movable_obstacle_ids) { curr_frame_movable_obstacle_ids_ = curr_frame_movable_obstacle_ids; } void SubmoduleOutput::set_curr_frame_unmovable_obstacle_ids( const std::vector<int>& curr_frame_unmovable_obstacle_ids) { curr_frame_unmovable_obstacle_ids_ = curr_frame_unmovable_obstacle_ids; } void SubmoduleOutput::set_curr_frame_considered_obstacle_ids( const std::vector<int>& curr_frame_considered_obstacle_ids) { curr_frame_considered_obstacle_ids_ = curr_frame_considered_obstacle_ids; } void SubmoduleOutput::set_frame_start_time( const apollo::cyber::Time& frame_start_time) { frame_start_time_ = frame_start_time; } void SubmoduleOutput::set_curr_scenario(const Scenario& scenario) { curr_scenario_ = scenario; } const std::vector<Obstacle>& SubmoduleOutput::curr_frame_obstacles() const { return curr_frame_obstacles_; } const Obstacle& SubmoduleOutput::GetEgoVehicle() const { return ego_vehicle_; } std::vector<int> SubmoduleOutput::curr_frame_movable_obstacle_ids() const { return curr_frame_movable_obstacle_ids_; } std::vector<int> SubmoduleOutput::curr_frame_unmovable_obstacle_ids() const { return curr_frame_unmovable_obstacle_ids_; } std::vector<int> SubmoduleOutput::curr_frame_considered_obstacle_ids() const { return curr_frame_considered_obstacle_ids_; } const apollo::cyber::Time& SubmoduleOutput::frame_start_time() const { return frame_start_time_; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/evaluator_submodule.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/prediction/submodules/evaluator_submodule.h" #include "cyber/time/clock.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/prediction/common/message_process.h" #include "modules/prediction/common/prediction_system_gflags.h" namespace apollo { namespace prediction { EvaluatorSubmodule::~EvaluatorSubmodule() {} std::string EvaluatorSubmodule::Name() const { return FLAGS_evaluator_submodule_name; } bool EvaluatorSubmodule::Init() { evaluator_manager_.reset(new EvaluatorManager()); PredictionConf prediction_conf; if (!ComponentBase::GetProtoConfig(&prediction_conf)) { AERROR << "Unable to load prediction conf file: " << ComponentBase::ConfigFilePath(); return false; } ADEBUG << "Prediction config file is loaded into: " << prediction_conf.ShortDebugString(); if (!MessageProcess::InitEvaluators(evaluator_manager_.get(), prediction_conf)) { return false; } // TODO(kechxu) change topic name when finalized evaluator_writer_ = node_->CreateWriter<SubmoduleOutput>( prediction_conf.topic_conf().evaluator_topic_name()); return true; } bool EvaluatorSubmodule::Proc( const std::shared_ptr<ADCTrajectoryContainer>& adc_trajectory_container, const std::shared_ptr<SubmoduleOutput>& container_output) { constexpr static size_t kHistorySize = 1; const auto frame_start_time = container_output->frame_start_time(); ObstaclesContainer obstacles_container(*container_output); evaluator_manager_->Run(adc_trajectory_container.get(), &obstacles_container); SubmoduleOutput submodule_output = obstacles_container.GetSubmoduleOutput(kHistorySize, frame_start_time); evaluator_writer_->Write(submodule_output); return true; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/predictor_submodule.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/prediction/submodules/predictor_submodule.h" #include "cyber/time/time.h" #include "cyber/time/clock.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/util/message_util.h" #include "modules/prediction/common/prediction_system_gflags.h" namespace apollo { namespace prediction { using apollo::cyber::Clock; using apollo::perception::PerceptionObstacles; std::string PredictorSubmodule::Name() const { return FLAGS_evaluator_submodule_name; } bool PredictorSubmodule::Init() { predictor_manager_.reset(new PredictorManager()); PredictionConf prediction_conf; if (!ComponentBase::GetProtoConfig(&prediction_conf)) { AERROR << "Unable to load prediction conf file: " << ComponentBase::ConfigFilePath(); return false; } ADEBUG << "Prediction config file is loaded into: " << prediction_conf.ShortDebugString(); if (!MessageProcess::InitPredictors(predictor_manager_.get(), prediction_conf)) { return false; } predictor_writer_ = node_->CreateWriter<PredictionObstacles>( prediction_conf.topic_conf().prediction_topic()); return true; } bool PredictorSubmodule::Proc( const std::shared_ptr<PerceptionObstacles>& perception_obstacles, const std::shared_ptr<ADCTrajectoryContainer>& adc_trajectory_container, const std::shared_ptr<SubmoduleOutput>& submodule_output) { const apollo::common::Header& perception_header = perception_obstacles->header(); const apollo::common::ErrorCode& perception_error_code = perception_obstacles->error_code(); const apollo::cyber::Time& frame_start_time = submodule_output->frame_start_time(); ObstaclesContainer obstacles_container(*submodule_output); predictor_manager_->Run(*perception_obstacles, adc_trajectory_container.get(), &obstacles_container); PredictionObstacles prediction_obstacles = predictor_manager_->prediction_obstacles(); prediction_obstacles.set_end_timestamp(Clock::NowInSeconds()); prediction_obstacles.mutable_header()->set_lidar_timestamp( perception_header.lidar_timestamp()); prediction_obstacles.mutable_header()->set_camera_timestamp( perception_header.camera_timestamp()); prediction_obstacles.mutable_header()->set_radar_timestamp( perception_header.radar_timestamp()); prediction_obstacles.set_perception_error_code(perception_error_code); common::util::FillHeader(node_->Name(), &prediction_obstacles); predictor_writer_->Write(prediction_obstacles); const apollo::cyber::Time& end_time = Clock::Now(); ADEBUG << "End to end time = " << (end_time - frame_start_time).ToSecond() * 1000 << " ms"; return true; } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/evaluator_submodule.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Use evaluator submodule to manage all evaluators */ #pragma once #include <memory> #include <string> #include "cyber/component/component.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/submodules/submodule_output.h" namespace apollo { namespace prediction { class EvaluatorSubmodule : public cyber::Component<ADCTrajectoryContainer, SubmoduleOutput> { public: /** * @brief Destructor */ ~EvaluatorSubmodule(); /** * @brief Get name of the node * @return Name of the node */ std::string Name() const; /** * @brief Initialize the node * @return If initialized */ bool Init() override; /** * @brief Data callback upon receiving a prediction container output. * @param Prediction container output. */ bool Proc( const std::shared_ptr<ADCTrajectoryContainer>& adc_trajectory_container, const std::shared_ptr<SubmoduleOutput>&) override; private: std::shared_ptr<cyber::Writer<SubmoduleOutput>> evaluator_writer_; std::unique_ptr<EvaluatorManager> evaluator_manager_; }; CYBER_REGISTER_COMPONENT(EvaluatorSubmodule) } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/prediction
apollo_public_repos/apollo/modules/prediction/submodules/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") package(default_visibility = ["//visibility:public"]) PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""] install( name = "install", library_dest = "prediction/lib", targets = [ ":evaluator_submodule.so", ":predictor_submodule.so", ":prediction_lego.so", ], visibility = ["//visibility:public"], ) cc_library( name = "submodule_output", srcs = ["submodule_output.cc"], hdrs = ["submodule_output.h"], copts = PREDICTION_COPTS, deps = [ "//modules/common/util:util_tool", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/prediction/common:prediction_gflags", "//modules/prediction/container/obstacles:obstacle", ], ) cc_library( name = "evaluator_submodule_lib", srcs = ["evaluator_submodule.cc"], hdrs = ["evaluator_submodule.h"], copts = PREDICTION_COPTS, deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/adapters/proto:adapter_config_cc_proto", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/prediction/common:message_process", "//modules/prediction/common:prediction_gflags", "//modules/prediction/evaluator:evaluator_manager", ], alwayslink = True, ) cc_binary( name = "evaluator_submodule.so", linkshared = True, linkstatic = False, deps = [":evaluator_submodule_lib"], ) cc_library( name = "predictor_submodule_lib", srcs = ["predictor_submodule.cc"], hdrs = ["predictor_submodule.h"], copts = PREDICTION_COPTS, deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/adapters/proto:adapter_config_cc_proto", "//modules/common/util:util_tool", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/prediction/common:message_process", "//modules/prediction/common:prediction_gflags", "//modules/prediction/container/adc_trajectory:adc_trajectory_container", "//modules/prediction/predictor:predictor_manager", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", ], alwayslink = True, ) cc_binary( name = "predictor_submodule.so", linkshared = True, linkstatic = False, deps = [":evaluator_submodule_lib"], ) cc_library( name = "prediction_lego_lib", deps = [ ":evaluator_submodule_lib", ":predictor_submodule_lib", "//modules/prediction:prediction_component_lib", ], ) cc_binary( name = "prediction_lego.so", linkshared = True, linkstatic = False, deps = [":prediction_lego_lib"], ) cpplint()
0