repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/qp_spline_reference_line_smoother.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 qp_spline_reference_line_smoother.h **/ #pragma once #include <memory> #include <vector> #include "modules/planning/math/smoothing_spline/spline_2d_solver.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/proto/reference_line_smoother_config.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_line_smoother.h" #include "modules/planning/reference_line/reference_point.h" namespace apollo { namespace planning { class QpSplineReferenceLineSmoother : public ReferenceLineSmoother { public: explicit QpSplineReferenceLineSmoother( const ReferenceLineSmootherConfig& config); virtual ~QpSplineReferenceLineSmoother() = default; bool Smooth(const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) override; void SetAnchorPoints(const std::vector<AnchorPoint>& anchor_points) override; private: void Clear(); bool Sampling(); bool AddConstraint(); bool AddKernel(); bool Solve(); bool ExtractEvaluatedPoints( const ReferenceLine& raw_reference_line, const std::vector<double>& vec_t, std::vector<common::PathPoint>* const path_points) const; bool GetSFromParamT(const double t, double* const s) const; std::uint32_t FindIndex(const double t) const; private: std::vector<double> t_knots_; std::vector<AnchorPoint> anchor_points_; std::unique_ptr<Spline2dSolver> spline_solver_; double ref_x_ = 0.0; double ref_y_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/reference_line.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 reference_line.h **/ #pragma once #include <string> #include <utility> #include <vector> #include "modules/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/map/pnc_map/path.h" #include "modules/common_msgs/map_msgs/map.pb.h" #include "modules/common_msgs/map_msgs/map_geometry.pb.h" #include "modules/common_msgs/planning_msgs/sl_boundary.pb.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/common_msgs/routing_msgs/routing.pb.h" namespace apollo { namespace planning { class ReferenceLine { public: ReferenceLine() = default; explicit ReferenceLine(const ReferenceLine& reference_line) = default; template <typename Iterator> ReferenceLine(const Iterator begin, const Iterator end) : reference_points_(begin, end), map_path_(std::move(std::vector<hdmap::MapPathPoint>(begin, end))) {} explicit ReferenceLine(const std::vector<ReferencePoint>& reference_points); explicit ReferenceLine(const hdmap::Path& hdmap_path); /** Stitch current reference line with the other reference line * The stitching strategy is to use current reference points as much as * possible. The following two examples show two successful stitch cases. * * Example 1 * this: |--------A-----x-----B------| * other: |-----C------x--------D-------| * Result: |------A-----x-----B------x--------D-------| * In the above example, A-B is current reference line, and C-D is the other * reference line. If part B and part C matches, we update current reference * line to A-B-D. * * Example 2 * this: |-----A------x--------B-------| * other: |--------C-----x-----D------| * Result: |--------C-----x-----A------x--------B-------| * In the above example, A-B is current reference line, and C-D is the other * reference line. If part A and part D matches, we update current reference * line to C-A-B. * * @return false if these two reference line cannot be stitched */ bool Stitch(const ReferenceLine& other); bool Segment(const common::math::Vec2d& point, const double distance_backward, const double distance_forward); bool Segment(const double s, const double distance_backward, const double distance_forward); const hdmap::Path& map_path() const; const std::vector<ReferencePoint>& reference_points() const; ReferencePoint GetReferencePoint(const double s) const; common::FrenetFramePoint GetFrenetPoint( const common::PathPoint& path_point) const; std::pair<std::array<double, 3>, std::array<double, 3>> ToFrenetFrame( const common::TrajectoryPoint& traj_point) const; std::vector<ReferencePoint> GetReferencePoints(double start_s, double end_s) const; size_t GetNearestReferenceIndex(const double s) const; ReferencePoint GetNearestReferencePoint(const common::math::Vec2d& xy) const; std::vector<hdmap::LaneSegment> GetLaneSegments(const double start_s, const double end_s) const; ReferencePoint GetNearestReferencePoint(const double s) const; ReferencePoint GetReferencePoint(const double x, const double y) const; bool GetApproximateSLBoundary(const common::math::Box2d& box, const double start_s, const double end_s, SLBoundary* const sl_boundary) const; bool GetSLBoundary(const common::math::Box2d& box, SLBoundary* const sl_boundary) const; bool GetSLBoundary(const hdmap::Polygon& polygon, SLBoundary* const sl_boundary) const; bool SLToXY(const common::SLPoint& sl_point, common::math::Vec2d* const xy_point) const; bool XYToSL(const common::math::Vec2d& xy_point, common::SLPoint* const sl_point) const; template <class XYPoint> bool XYToSL(const XYPoint& xy, common::SLPoint* const sl_point) const { return XYToSL(common::math::Vec2d(xy.x(), xy.y()), sl_point); } bool GetLaneWidth(const double s, double* const lane_left_width, double* const lane_right_width) const; bool GetOffsetToMap(const double s, double* l_offset) const; bool GetRoadWidth(const double s, double* const road_left_width, double* const road_right_width) const; hdmap::Road::Type GetRoadType(const double s) const; void GetLaneFromS(const double s, std::vector<hdmap::LaneInfoConstPtr>* lanes) const; double GetDrivingWidth(const SLBoundary& sl_boundary) const; /** * @brief: check if a box/point is on lane along reference line */ bool IsOnLane(const common::SLPoint& sl_point) const; bool IsOnLane(const common::math::Vec2d& vec2d_point) const; template <class XYPoint> bool IsOnLane(const XYPoint& xy) const { return IsOnLane(common::math::Vec2d(xy.x(), xy.y())); } bool IsOnLane(const SLBoundary& sl_boundary) const; /** * @brief: check if a box/point is on road * (not on sideways/medians) along reference line */ bool IsOnRoad(const common::SLPoint& sl_point) const; bool IsOnRoad(const common::math::Vec2d& vec2d_point) const; bool IsOnRoad(const SLBoundary& sl_boundary) const; /** * @brief Check if a box is blocking the road surface. The criteria is to * check whether the remaining space on the road surface is larger than the * provided gap space. * @param boxed the provided box * @param gap check the gap of the space * @return true if the box blocks the road. */ bool IsBlockRoad(const common::math::Box2d& box2d, double gap) const; /** * @brief check if any part of the box has overlap with the road. */ bool HasOverlap(const common::math::Box2d& box) const; double Length() const { return map_path_.length(); } std::string DebugString() const; double GetSpeedLimitFromS(const double s) const; void AddSpeedLimit(double start_s, double end_s, double speed_limit); uint32_t GetPriority() const { return priority_; } void SetPriority(uint32_t priority) { priority_ = priority; } const hdmap::Path& GetMapPath() const { return map_path_; } private: /** * @brief Linearly interpolate p0 and p1 by s0 and s1. * The input has to satisfy condition: s0 <= s <= s1 * p0 and p1 must have lane_waypoint. * Note: it requires p0 and p1 are on the same lane, adjacent lanes, or * parallel neighboring lanes. Otherwise the interpolated result may not * valid. * @param p0 the first anchor point for interpolation. * @param s0 the longitutial distance (s) of p0 on current reference line. * s0 <= s && s0 <= s1 * @param p1 the second anchor point for interpolation * @param s1 the longitutial distance (s) of p1 on current reference line. * s1 * @param s identifies the middle point that is going to be * interpolated. * s >= s0 && s <= s1 * @return The interpolated ReferencePoint. */ static ReferencePoint Interpolate(const ReferencePoint& p0, const double s0, const ReferencePoint& p1, const double s1, const double s); ReferencePoint InterpolateWithMatchedIndex( const ReferencePoint& p0, const double s0, const ReferencePoint& p1, const double s1, const hdmap::InterpolatedIndex& index) const; static double FindMinDistancePoint(const ReferencePoint& p0, const double s0, const ReferencePoint& p1, const double s1, const double x, const double y); private: struct SpeedLimit { double start_s = 0.0; double end_s = 0.0; double speed_limit = 0.0; // unit m/s SpeedLimit() = default; SpeedLimit(double _start_s, double _end_s, double _speed_limit) : start_s(_start_s), end_s(_end_s), speed_limit(_speed_limit) {} }; /** * This speed limit overrides the lane speed limit **/ std::vector<SpeedLimit> speed_limit_; std::vector<ReferencePoint> reference_points_; hdmap::Path map_path_; uint32_t priority_ = 0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/discrete_points_reference_line_smoother_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/reference_line/discrete_points_reference_line_smoother.h" #include "gtest/gtest.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/proto/reference_line_smoother_config.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_point.h" namespace apollo { namespace planning { class DiscretePointsReferenceLineSmootherTest : public ::testing::Test { public: virtual void SetUp() { smoother_.reset(new DiscretePointsReferenceLineSmoother(config_)); hdmap_.LoadMapFromFile(map_file); const std::string lane_id = "1_-1"; lane_info_ptr = hdmap_.GetLaneById(hdmap::MakeMapId(lane_id)); if (!lane_info_ptr) { AERROR << "failed to find lane " << lane_id << " from map " << map_file; return; } std::vector<ReferencePoint> ref_points; const auto& points = lane_info_ptr->points(); const auto& headings = lane_info_ptr->headings(); const auto& accumulate_s = lane_info_ptr->accumulate_s(); for (size_t i = 0; i < points.size(); ++i) { std::vector<hdmap::LaneWaypoint> waypoint; waypoint.emplace_back(lane_info_ptr, accumulate_s[i]); hdmap::MapPathPoint map_path_point(points[i], headings[i], waypoint); ref_points.emplace_back(map_path_point, 0.0, 0.0); } reference_line_.reset(new ReferenceLine(ref_points)); vehicle_position_ = points[0]; } const std::string map_file = "/apollo/modules/planning/testdata/garage_map/base_map.txt"; hdmap::HDMap hdmap_; common::math::Vec2d vehicle_position_; ReferenceLineSmootherConfig config_; std::unique_ptr<ReferenceLineSmoother> smoother_; std::unique_ptr<ReferenceLine> reference_line_; hdmap::LaneInfoConstPtr lane_info_ptr = nullptr; }; TEST_F(DiscretePointsReferenceLineSmootherTest, smooth) { ReferenceLine smoothed_reference_line; EXPECT_DOUBLE_EQ(153.87421245682503, reference_line_->Length()); std::vector<AnchorPoint> anchor_points; const double interval = 10.0; int num_of_anchors = std::max(2, static_cast<int>(reference_line_->Length() / interval + 0.5)); std::vector<double> anchor_s; common::util::uniform_slice(0.0, reference_line_->Length(), num_of_anchors - 1, &anchor_s); for (const double s : anchor_s) { anchor_points.emplace_back(); auto& last_anchor = anchor_points.back(); auto ref_point = reference_line_->GetReferencePoint(s); last_anchor.path_point = ref_point.ToPathPoint(s); last_anchor.lateral_bound = 0.25; last_anchor.longitudinal_bound = 2.0; } anchor_points.front().longitudinal_bound = 1e-6; anchor_points.front().lateral_bound = 1e-6; anchor_points.back().longitudinal_bound = 1e-6; anchor_points.back().lateral_bound = 1e-6; smoother_->SetAnchorPoints(anchor_points); EXPECT_TRUE(smoother_->Smooth(*reference_line_, &smoothed_reference_line)); EXPECT_NEAR(153.0, smoothed_reference_line.Length(), 1.0); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/reference_line_provider.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief Implementation of the class ReferenceLineProvider. */ #include "modules/planning/reference_line/reference_line_provider.h" #include <algorithm> #include <limits> #include <utility> #include "cyber/common/file.h" #include "cyber/task/task.h" #include "cyber/time/clock.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/point_factory.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { using apollo::common::VehicleConfigHelper; using apollo::common::VehicleState; using apollo::common::math::AngleDiff; using apollo::common::math::Vec2d; using apollo::cyber::Clock; using apollo::hdmap::HDMapUtil; using apollo::hdmap::LaneWaypoint; using apollo::hdmap::MapPathPoint; using apollo::hdmap::PncMap; using apollo::hdmap::RouteSegments; ReferenceLineProvider::~ReferenceLineProvider() {} ReferenceLineProvider::ReferenceLineProvider( const common::VehicleStateProvider *vehicle_state_provider, const hdmap::HDMap *base_map, const std::shared_ptr<relative_map::MapMsg> &relative_map) : vehicle_state_provider_(vehicle_state_provider) { if (!FLAGS_use_navigation_mode) { pnc_map_ = std::make_unique<hdmap::PncMap>(base_map); relative_map_ = nullptr; } else { pnc_map_ = nullptr; relative_map_ = relative_map; } ACHECK(cyber::common::GetProtoFromFile(FLAGS_smoother_config_filename, &smoother_config_)) << "Failed to load smoother config file " << FLAGS_smoother_config_filename; if (smoother_config_.has_qp_spline()) { smoother_.reset(new QpSplineReferenceLineSmoother(smoother_config_)); } else if (smoother_config_.has_spiral()) { smoother_.reset(new SpiralReferenceLineSmoother(smoother_config_)); } else if (smoother_config_.has_discrete_points()) { smoother_.reset(new DiscretePointsReferenceLineSmoother(smoother_config_)); } else { ACHECK(false) << "unknown smoother config " << smoother_config_.DebugString(); } is_initialized_ = true; } bool ReferenceLineProvider::UpdateRoutingResponse( const routing::RoutingResponse &routing) { std::lock_guard<std::mutex> routing_lock(routing_mutex_); routing_ = routing; has_routing_ = true; return true; } std::vector<routing::LaneWaypoint> ReferenceLineProvider::FutureRouteWaypoints() { if (!FLAGS_use_navigation_mode) { std::lock_guard<std::mutex> lock(pnc_map_mutex_); return pnc_map_->FutureRouteWaypoints(); } // return an empty routing::LaneWaypoint vector in Navigation mode. return std::vector<routing::LaneWaypoint>(); } void ReferenceLineProvider::UpdateVehicleState( const VehicleState &vehicle_state) { std::lock_guard<std::mutex> lock(vehicle_state_mutex_); vehicle_state_ = vehicle_state; } bool ReferenceLineProvider::Start() { if (FLAGS_use_navigation_mode) { return true; } if (!is_initialized_) { AERROR << "ReferenceLineProvider has NOT been initiated."; return false; } if (FLAGS_enable_reference_line_provider_thread) { task_future_ = cyber::Async(&ReferenceLineProvider::GenerateThread, this); } return true; } void ReferenceLineProvider::Stop() { is_stop_ = true; if (FLAGS_enable_reference_line_provider_thread) { task_future_.get(); } } void ReferenceLineProvider::UpdateReferenceLine( const std::list<ReferenceLine> &reference_lines, const std::list<hdmap::RouteSegments> &route_segments) { if (reference_lines.size() != route_segments.size()) { AERROR << "The calculated reference line size(" << reference_lines.size() << ") and route_segments size(" << route_segments.size() << ") are different"; return; } std::lock_guard<std::mutex> lock(reference_lines_mutex_); if (reference_lines_.size() != reference_lines.size()) { reference_lines_ = reference_lines; route_segments_ = route_segments; } else { auto segment_iter = route_segments.begin(); auto internal_iter = reference_lines_.begin(); auto internal_segment_iter = route_segments_.begin(); for (auto iter = reference_lines.begin(); iter != reference_lines.end() && segment_iter != route_segments.end() && internal_iter != reference_lines_.end() && internal_segment_iter != route_segments_.end(); ++iter, ++segment_iter, ++internal_iter, ++internal_segment_iter) { if (iter->reference_points().empty()) { *internal_iter = *iter; *internal_segment_iter = *segment_iter; continue; } if (common::util::SamePointXY( iter->reference_points().front(), internal_iter->reference_points().front()) && common::util::SamePointXY(iter->reference_points().back(), internal_iter->reference_points().back()) && std::fabs(iter->Length() - internal_iter->Length()) < common::math::kMathEpsilon) { continue; } *internal_iter = *iter; *internal_segment_iter = *segment_iter; } } // update history reference_line_history_.push(reference_lines_); route_segments_history_.push(route_segments_); static constexpr int kMaxHistoryNum = 3; if (reference_line_history_.size() > kMaxHistoryNum) { reference_line_history_.pop(); route_segments_history_.pop(); } } void ReferenceLineProvider::GenerateThread() { while (!is_stop_) { static constexpr int32_t kSleepTime = 50; // milliseconds cyber::SleepFor(std::chrono::milliseconds(kSleepTime)); const double start_time = Clock::NowInSeconds(); if (!has_routing_) { AERROR << "Routing is not ready."; continue; } std::list<ReferenceLine> reference_lines; std::list<hdmap::RouteSegments> segments; if (!CreateReferenceLine(&reference_lines, &segments)) { is_reference_line_updated_ = false; AERROR << "Fail to get reference line"; continue; } UpdateReferenceLine(reference_lines, segments); const double end_time = Clock::NowInSeconds(); std::lock_guard<std::mutex> lock(reference_lines_mutex_); last_calculation_time_ = end_time - start_time; is_reference_line_updated_ = true; } } double ReferenceLineProvider::LastTimeDelay() { if (FLAGS_enable_reference_line_provider_thread && !FLAGS_use_navigation_mode) { std::lock_guard<std::mutex> lock(reference_lines_mutex_); return last_calculation_time_; } else { return last_calculation_time_; } } bool ReferenceLineProvider::GetReferenceLines( std::list<ReferenceLine> *reference_lines, std::list<hdmap::RouteSegments> *segments) { CHECK_NOTNULL(reference_lines); CHECK_NOTNULL(segments); if (FLAGS_use_navigation_mode) { double start_time = Clock::NowInSeconds(); bool result = GetReferenceLinesFromRelativeMap(reference_lines, segments); if (!result) { AERROR << "Failed to get reference line from relative map"; } double end_time = Clock::NowInSeconds(); last_calculation_time_ = end_time - start_time; return result; } if (FLAGS_enable_reference_line_provider_thread) { std::lock_guard<std::mutex> lock(reference_lines_mutex_); if (!reference_lines_.empty()) { reference_lines->assign(reference_lines_.begin(), reference_lines_.end()); segments->assign(route_segments_.begin(), route_segments_.end()); return true; } } else { double start_time = Clock::NowInSeconds(); if (CreateReferenceLine(reference_lines, segments)) { UpdateReferenceLine(*reference_lines, *segments); double end_time = Clock::NowInSeconds(); last_calculation_time_ = end_time - start_time; return true; } } AWARN << "Reference line is NOT ready."; if (reference_line_history_.empty()) { AERROR << "Failed to use reference line latest history"; return false; } reference_lines->assign(reference_line_history_.back().begin(), reference_line_history_.back().end()); segments->assign(route_segments_history_.back().begin(), route_segments_history_.back().end()); AWARN << "Use reference line from history!"; return true; } void ReferenceLineProvider::PrioritzeChangeLane( std::list<hdmap::RouteSegments> *route_segments) { CHECK_NOTNULL(route_segments); auto iter = route_segments->begin(); while (iter != route_segments->end()) { if (!iter->IsOnSegment()) { route_segments->splice(route_segments->begin(), *route_segments, iter); break; } ++iter; } } bool ReferenceLineProvider::GetReferenceLinesFromRelativeMap( std::list<ReferenceLine> *reference_lines, std::list<hdmap::RouteSegments> *segments) { CHECK_GE(relative_map_->navigation_path_size(), 0); CHECK_NOTNULL(reference_lines); CHECK_NOTNULL(segments); if (relative_map_->navigation_path().empty()) { AERROR << "There isn't any navigation path in current relative map."; return false; } auto *hdmap = HDMapUtil::BaseMapPtr(*relative_map_); if (!hdmap) { AERROR << "hdmap is null"; return false; } // 1.get adc current lane info ,such as lane_id,lane_priority,neighbor lanes std::unordered_set<std::string> navigation_lane_ids; for (const auto &path_pair : relative_map_->navigation_path()) { const auto lane_id = path_pair.first; navigation_lane_ids.insert(lane_id); } if (navigation_lane_ids.empty()) { AERROR << "navigation path ids is empty"; return false; } // get current adc lane info by vehicle state common::VehicleState vehicle_state = vehicle_state_provider_->vehicle_state(); hdmap::LaneWaypoint adc_lane_way_point; if (!GetNearestWayPointFromNavigationPath(vehicle_state, navigation_lane_ids, &adc_lane_way_point)) { return false; } const std::string adc_lane_id = adc_lane_way_point.lane->id().id(); auto *adc_navigation_path = apollo::common::util::FindOrNull( relative_map_->navigation_path(), adc_lane_id); if (adc_navigation_path == nullptr) { AERROR << "adc lane cannot be found in relative_map_->navigation_path"; return false; } const uint32_t adc_lane_priority = adc_navigation_path->path_priority(); // get adc left neighbor lanes std::vector<std::string> left_neighbor_lane_ids; auto left_lane_ptr = adc_lane_way_point.lane; while (left_lane_ptr != nullptr && left_lane_ptr->lane().left_neighbor_forward_lane_id_size() > 0) { auto neighbor_lane_id = left_lane_ptr->lane().left_neighbor_forward_lane_id(0); left_neighbor_lane_ids.emplace_back(neighbor_lane_id.id()); left_lane_ptr = hdmap->GetLaneById(neighbor_lane_id); } ADEBUG << adc_lane_id << " left neighbor size : " << left_neighbor_lane_ids.size(); for (const auto &neighbor : left_neighbor_lane_ids) { ADEBUG << adc_lane_id << " left neighbor : " << neighbor; } // get adc right neighbor lanes std::vector<std::string> right_neighbor_lane_ids; auto right_lane_ptr = adc_lane_way_point.lane; while (right_lane_ptr != nullptr && right_lane_ptr->lane().right_neighbor_forward_lane_id_size() > 0) { auto neighbor_lane_id = right_lane_ptr->lane().right_neighbor_forward_lane_id(0); right_neighbor_lane_ids.emplace_back(neighbor_lane_id.id()); right_lane_ptr = hdmap->GetLaneById(neighbor_lane_id); } ADEBUG << adc_lane_id << " right neighbor size : " << right_neighbor_lane_ids.size(); for (const auto &neighbor : right_neighbor_lane_ids) { ADEBUG << adc_lane_id << " right neighbor : " << neighbor; } // 2.get the higher priority lane info list which priority higher // than current lane and get the highest one as the target lane using LaneIdPair = std::pair<std::string, uint32_t>; std::vector<LaneIdPair> high_priority_lane_pairs; ADEBUG << "relative_map_->navigation_path_size = " << relative_map_->navigation_path_size(); for (const auto &path_pair : relative_map_->navigation_path()) { const auto lane_id = path_pair.first; const uint32_t priority = path_pair.second.path_priority(); ADEBUG << "lane_id = " << lane_id << " priority = " << priority << " adc_lane_id = " << adc_lane_id << " adc_lane_priority = " << adc_lane_priority; // the smaller the number, the higher the priority if (adc_lane_id != lane_id && priority < adc_lane_priority) { high_priority_lane_pairs.emplace_back(lane_id, priority); } } // get the target lane bool is_lane_change_needed = false; LaneIdPair target_lane_pair; if (!high_priority_lane_pairs.empty()) { std::sort(high_priority_lane_pairs.begin(), high_priority_lane_pairs.end(), [](const LaneIdPair &left, const LaneIdPair &right) { return left.second < right.second; }); ADEBUG << "need to change lane"; // the highest priority lane as the target navigation lane target_lane_pair = high_priority_lane_pairs.front(); is_lane_change_needed = true; } // 3.get current lane's the nearest neighbor lane to the target lane // and make sure it position is left or right on the current lane routing::ChangeLaneType lane_change_type = routing::FORWARD; std::string nearest_neighbor_lane_id; if (is_lane_change_needed) { // target on the left of adc if (left_neighbor_lane_ids.end() != std::find(left_neighbor_lane_ids.begin(), left_neighbor_lane_ids.end(), target_lane_pair.first)) { // take the id of the first adjacent lane on the left of adc as // the nearest_neighbor_lane_id lane_change_type = routing::LEFT; nearest_neighbor_lane_id = adc_lane_way_point.lane->lane().left_neighbor_forward_lane_id(0).id(); } else if (right_neighbor_lane_ids.end() != std::find(right_neighbor_lane_ids.begin(), right_neighbor_lane_ids.end(), target_lane_pair.first)) { // target lane on the right of adc // take the id of the first adjacent lane on the right of adc as // the nearest_neighbor_lane_id lane_change_type = routing::RIGHT; nearest_neighbor_lane_id = adc_lane_way_point.lane->lane() .right_neighbor_forward_lane_id(0) .id(); } } for (const auto &path_pair : relative_map_->navigation_path()) { const auto &lane_id = path_pair.first; const auto &path_points = path_pair.second.path().path_point(); auto lane_ptr = hdmap->GetLaneById(hdmap::MakeMapId(lane_id)); RouteSegments segment; segment.emplace_back(lane_ptr, 0.0, lane_ptr->total_length()); segment.SetCanExit(true); segment.SetId(lane_id); segment.SetNextAction(routing::FORWARD); segment.SetStopForDestination(false); segment.SetPreviousAction(routing::FORWARD); if (is_lane_change_needed) { if (lane_id == nearest_neighbor_lane_id) { ADEBUG << "adc lane_id = " << adc_lane_id << " nearest_neighbor_lane_id = " << lane_id; segment.SetIsNeighborSegment(true); segment.SetPreviousAction(lane_change_type); } else if (lane_id == adc_lane_id) { segment.SetIsOnSegment(true); segment.SetNextAction(lane_change_type); } } segments->emplace_back(segment); std::vector<ReferencePoint> ref_points; for (const auto &path_point : path_points) { ref_points.emplace_back( MapPathPoint{Vec2d{path_point.x(), path_point.y()}, path_point.theta(), LaneWaypoint(lane_ptr, path_point.s())}, path_point.kappa(), path_point.dkappa()); } reference_lines->emplace_back(ref_points.begin(), ref_points.end()); reference_lines->back().SetPriority(path_pair.second.path_priority()); } return !segments->empty(); } bool ReferenceLineProvider::GetNearestWayPointFromNavigationPath( const common::VehicleState &state, const std::unordered_set<std::string> &navigation_lane_ids, hdmap::LaneWaypoint *waypoint) { const double kMaxDistance = 10.0; waypoint->lane = nullptr; std::vector<hdmap::LaneInfoConstPtr> lanes; auto point = common::util::PointFactory::ToPointENU(state); if (std::isnan(point.x()) || std::isnan(point.y())) { AERROR << "vehicle state is invalid"; return false; } auto *hdmap = HDMapUtil::BaseMapPtr(); if (!hdmap) { AERROR << "hdmap is null"; return false; } // get all adc direction lanes from map in kMaxDistance range // by vehicle point in map const int status = hdmap->GetLanesWithHeading( point, kMaxDistance, state.heading(), M_PI / 2.0, &lanes); if (status < 0) { AERROR << "failed to get lane from point " << point.ShortDebugString(); return false; } // get lanes that exist in both map and navigation paths as valid lanes std::vector<hdmap::LaneInfoConstPtr> valid_lanes; std::copy_if(lanes.begin(), lanes.end(), std::back_inserter(valid_lanes), [&](hdmap::LaneInfoConstPtr ptr) { return navigation_lane_ids.count(ptr->lane().id().id()) > 0; }); if (valid_lanes.empty()) { AERROR << "no valid lane found within " << kMaxDistance << " meters with heading " << state.heading(); return false; } // get nearest lane waypoints for current adc position double min_distance = std::numeric_limits<double>::infinity(); for (const auto &lane : valid_lanes) { // project adc point to lane to check if it is out of lane range double s = 0.0; double l = 0.0; if (!lane->GetProjection({point.x(), point.y()}, &s, &l)) { continue; } static constexpr double kEpsilon = 1e-6; if (s > (lane->total_length() + kEpsilon) || (s + kEpsilon) < 0.0) { continue; } // get the nearest distance between adc point and lane double distance = 0.0; common::PointENU map_point = lane->GetNearestPoint({point.x(), point.y()}, &distance); // record the near distance lane if (distance < min_distance) { double s = 0.0; double l = 0.0; if (!lane->GetProjection({map_point.x(), map_point.y()}, &s, &l)) { AERROR << "failed to get projection for map_point " << map_point.DebugString(); continue; } min_distance = distance; waypoint->lane = lane; waypoint->s = s; } } if (waypoint->lane == nullptr) { AERROR << "failed to find nearest point " << point.ShortDebugString(); } return waypoint->lane != nullptr; } bool ReferenceLineProvider::CreateRouteSegments( const common::VehicleState &vehicle_state, std::list<hdmap::RouteSegments> *segments) { { std::lock_guard<std::mutex> lock(pnc_map_mutex_); if (!pnc_map_->GetRouteSegments(vehicle_state, segments)) { AERROR << "Failed to extract segments from routing"; return false; } } if (FLAGS_prioritize_change_lane) { PrioritzeChangeLane(segments); } return !segments->empty(); } bool ReferenceLineProvider::CreateReferenceLine( std::list<ReferenceLine> *reference_lines, std::list<hdmap::RouteSegments> *segments) { CHECK_NOTNULL(reference_lines); CHECK_NOTNULL(segments); common::VehicleState vehicle_state; { std::lock_guard<std::mutex> lock(vehicle_state_mutex_); vehicle_state = vehicle_state_; } routing::RoutingResponse routing; { std::lock_guard<std::mutex> lock(routing_mutex_); routing = routing_; } bool is_new_routing = false; { // Update routing in pnc_map std::lock_guard<std::mutex> lock(pnc_map_mutex_); if (pnc_map_->IsNewRouting(routing)) { is_new_routing = true; if (!pnc_map_->UpdateRoutingResponse(routing)) { AERROR << "Failed to update routing in pnc map"; return false; } } } if (!CreateRouteSegments(vehicle_state, segments)) { AERROR << "Failed to create reference line from routing"; return false; } if (is_new_routing || !FLAGS_enable_reference_line_stitching) { for (auto iter = segments->begin(); iter != segments->end();) { reference_lines->emplace_back(); if (!SmoothRouteSegment(*iter, &reference_lines->back())) { AERROR << "Failed to create reference line from route segments"; reference_lines->pop_back(); iter = segments->erase(iter); } else { common::SLPoint sl; if (!reference_lines->back().XYToSL(vehicle_state, &sl)) { AWARN << "Failed to project point: {" << vehicle_state.x() << "," << vehicle_state.y() << "} to stitched reference line"; } Shrink(sl, &reference_lines->back(), &(*iter)); ++iter; } } return true; } else { // stitching reference line for (auto iter = segments->begin(); iter != segments->end();) { reference_lines->emplace_back(); if (!ExtendReferenceLine(vehicle_state, &(*iter), &reference_lines->back())) { AERROR << "Failed to extend reference line"; reference_lines->pop_back(); iter = segments->erase(iter); } else { ++iter; } } } return true; } bool ReferenceLineProvider::ExtendReferenceLine(const VehicleState &state, RouteSegments *segments, ReferenceLine *reference_line) { RouteSegments segment_properties; segment_properties.SetProperties(*segments); auto prev_segment = route_segments_.begin(); auto prev_ref = reference_lines_.begin(); while (prev_segment != route_segments_.end()) { if (prev_segment->IsConnectedSegment(*segments)) { break; } ++prev_segment; ++prev_ref; } if (prev_segment == route_segments_.end()) { if (!route_segments_.empty() && segments->IsOnSegment()) { AWARN << "Current route segment is not connected with previous route " "segment"; } return SmoothRouteSegment(*segments, reference_line); } common::SLPoint sl_point; Vec2d vec2d(state.x(), state.y()); LaneWaypoint waypoint; if (!prev_segment->GetProjection(vec2d, &sl_point, &waypoint)) { AWARN << "Vehicle current point: " << vec2d.DebugString() << " not on previous reference line"; return SmoothRouteSegment(*segments, reference_line); } const double prev_segment_length = RouteSegments::Length(*prev_segment); const double remain_s = prev_segment_length - sl_point.s(); const double look_forward_required_distance = PncMap::LookForwardDistance(state.linear_velocity()); if (remain_s > look_forward_required_distance) { *segments = *prev_segment; segments->SetProperties(segment_properties); *reference_line = *prev_ref; ADEBUG << "Reference line remain " << remain_s << ", which is more than required " << look_forward_required_distance << " and no need to extend"; return true; } double future_start_s = std::max(sl_point.s(), prev_segment_length - FLAGS_reference_line_stitch_overlap_distance); double future_end_s = prev_segment_length + FLAGS_look_forward_extend_distance; RouteSegments shifted_segments; std::unique_lock<std::mutex> lock(pnc_map_mutex_); if (!pnc_map_->ExtendSegments(*prev_segment, future_start_s, future_end_s, &shifted_segments)) { lock.unlock(); AERROR << "Failed to shift route segments forward"; return SmoothRouteSegment(*segments, reference_line); } lock.unlock(); if (prev_segment->IsWaypointOnSegment(shifted_segments.LastWaypoint())) { *segments = *prev_segment; segments->SetProperties(segment_properties); *reference_line = *prev_ref; ADEBUG << "Could not further extend reference line"; return true; } hdmap::Path path(shifted_segments); ReferenceLine new_ref(path); if (!SmoothPrefixedReferenceLine(*prev_ref, new_ref, reference_line)) { AWARN << "Failed to smooth forward shifted reference line"; return SmoothRouteSegment(*segments, reference_line); } if (!reference_line->Stitch(*prev_ref)) { AWARN << "Failed to stitch reference line"; return SmoothRouteSegment(*segments, reference_line); } if (!shifted_segments.Stitch(*prev_segment)) { AWARN << "Failed to stitch route segments"; return SmoothRouteSegment(*segments, reference_line); } *segments = shifted_segments; segments->SetProperties(segment_properties); common::SLPoint sl; if (!reference_line->XYToSL(vec2d, &sl)) { AWARN << "Failed to project point: " << vec2d.DebugString() << " to stitched reference line"; } return Shrink(sl, reference_line, segments); } bool ReferenceLineProvider::Shrink(const common::SLPoint &sl, ReferenceLine *reference_line, RouteSegments *segments) { static constexpr double kMaxHeadingDiff = M_PI * 5.0 / 6.0; // shrink reference line double new_backward_distance = sl.s(); double new_forward_distance = reference_line->Length() - sl.s(); bool need_shrink = false; if (sl.s() > FLAGS_look_backward_distance * 1.5) { ADEBUG << "reference line back side is " << sl.s() << ", shrink reference line: origin length: " << reference_line->Length(); new_backward_distance = FLAGS_look_backward_distance; need_shrink = true; } // check heading const auto index = reference_line->GetNearestReferenceIndex(sl.s()); const auto &ref_points = reference_line->reference_points(); const double cur_heading = ref_points[index].heading(); auto last_index = index; while (last_index < ref_points.size() && AngleDiff(cur_heading, ref_points[last_index].heading()) < kMaxHeadingDiff) { ++last_index; } --last_index; if (last_index != ref_points.size() - 1) { need_shrink = true; common::SLPoint forward_sl; reference_line->XYToSL(ref_points[last_index], &forward_sl); new_forward_distance = forward_sl.s() - sl.s(); } if (need_shrink) { if (!reference_line->Segment(sl.s(), new_backward_distance, new_forward_distance)) { AWARN << "Failed to shrink reference line"; } if (!segments->Shrink(sl.s(), new_backward_distance, new_forward_distance)) { AWARN << "Failed to shrink route segment"; } } return true; } bool ReferenceLineProvider::IsReferenceLineSmoothValid( const ReferenceLine &raw, const ReferenceLine &smoothed) const { static constexpr double kReferenceLineDiffCheckStep = 10.0; for (double s = 0.0; s < smoothed.Length(); s += kReferenceLineDiffCheckStep) { auto xy_new = smoothed.GetReferencePoint(s); common::SLPoint sl_new; if (!raw.XYToSL(xy_new, &sl_new)) { AERROR << "Fail to change xy point on smoothed reference line to sl " "point respect to raw reference line."; return false; } const double diff = std::fabs(sl_new.l()); if (diff > FLAGS_smoothed_reference_line_max_diff) { AERROR << "Fail to provide reference line because too large diff " "between smoothed and raw reference lines. diff: " << diff; return false; } } return true; } AnchorPoint ReferenceLineProvider::GetAnchorPoint( const ReferenceLine &reference_line, double s) const { AnchorPoint anchor; anchor.longitudinal_bound = smoother_config_.longitudinal_boundary_bound(); auto ref_point = reference_line.GetReferencePoint(s); if (ref_point.lane_waypoints().empty()) { anchor.path_point = ref_point.ToPathPoint(s); anchor.lateral_bound = smoother_config_.max_lateral_boundary_bound(); return anchor; } const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); const Vec2d left_vec = Vec2d::CreateUnitVec2d(ref_point.heading() + M_PI / 2.0); auto waypoint = ref_point.lane_waypoints().front(); double left_width = 0.0; double right_width = 0.0; waypoint.lane->GetWidth(waypoint.s, &left_width, &right_width); const double kEpislon = 1e-8; double effective_width = 0.0; // shrink width by vehicle width, curb double safe_lane_width = left_width + right_width; safe_lane_width -= adc_width; bool is_lane_width_safe = true; if (safe_lane_width < kEpislon) { ADEBUG << "lane width [" << left_width + right_width << "] " << "is smaller than adc width [" << adc_width << "]"; effective_width = kEpislon; is_lane_width_safe = false; } double center_shift = 0.0; if (hdmap::RightBoundaryType(waypoint) == hdmap::LaneBoundaryType::CURB) { safe_lane_width -= smoother_config_.curb_shift(); if (safe_lane_width < kEpislon) { ADEBUG << "lane width smaller than adc width and right curb shift"; effective_width = kEpislon; is_lane_width_safe = false; } else { center_shift += 0.5 * smoother_config_.curb_shift(); } } if (hdmap::LeftBoundaryType(waypoint) == hdmap::LaneBoundaryType::CURB) { safe_lane_width -= smoother_config_.curb_shift(); if (safe_lane_width < kEpislon) { ADEBUG << "lane width smaller than adc width and left curb shift"; effective_width = kEpislon; is_lane_width_safe = false; } else { center_shift -= 0.5 * smoother_config_.curb_shift(); } } // apply buffer if possible const double buffered_width = safe_lane_width - 2.0 * smoother_config_.lateral_buffer(); safe_lane_width = buffered_width < kEpislon ? safe_lane_width : buffered_width; // shift center depending on the road width if (is_lane_width_safe) { effective_width = 0.5 * safe_lane_width; } ref_point += left_vec * center_shift; anchor.path_point = ref_point.ToPathPoint(s); anchor.lateral_bound = common::math::Clamp( effective_width, smoother_config_.min_lateral_boundary_bound(), smoother_config_.max_lateral_boundary_bound()); return anchor; } void ReferenceLineProvider::GetAnchorPoints( const ReferenceLine &reference_line, std::vector<AnchorPoint> *anchor_points) const { CHECK_NOTNULL(anchor_points); const double interval = smoother_config_.max_constraint_interval(); int num_of_anchors = std::max(2, static_cast<int>(reference_line.Length() / interval + 0.5)); std::vector<double> anchor_s; common::util::uniform_slice(0.0, reference_line.Length(), num_of_anchors - 1, &anchor_s); for (const double s : anchor_s) { AnchorPoint anchor = GetAnchorPoint(reference_line, s); anchor_points->emplace_back(anchor); } anchor_points->front().longitudinal_bound = 1e-6; anchor_points->front().lateral_bound = 1e-6; anchor_points->front().enforced = true; anchor_points->back().longitudinal_bound = 1e-6; anchor_points->back().lateral_bound = 1e-6; anchor_points->back().enforced = true; } bool ReferenceLineProvider::SmoothRouteSegment(const RouteSegments &segments, ReferenceLine *reference_line) { hdmap::Path path(segments); return SmoothReferenceLine(ReferenceLine(path), reference_line); } bool ReferenceLineProvider::SmoothPrefixedReferenceLine( const ReferenceLine &prefix_ref, const ReferenceLine &raw_ref, ReferenceLine *reference_line) { if (!FLAGS_enable_smooth_reference_line) { *reference_line = raw_ref; return true; } // generate anchor points: std::vector<AnchorPoint> anchor_points; GetAnchorPoints(raw_ref, &anchor_points); // modify anchor points based on prefix_ref for (auto &point : anchor_points) { common::SLPoint sl_point; if (!prefix_ref.XYToSL(point.path_point, &sl_point)) { continue; } if (sl_point.s() < 0 || sl_point.s() > prefix_ref.Length()) { continue; } auto prefix_ref_point = prefix_ref.GetNearestReferencePoint(sl_point.s()); point.path_point.set_x(prefix_ref_point.x()); point.path_point.set_y(prefix_ref_point.y()); point.path_point.set_z(0.0); point.path_point.set_theta(prefix_ref_point.heading()); point.longitudinal_bound = 1e-6; point.lateral_bound = 1e-6; point.enforced = true; break; } smoother_->SetAnchorPoints(anchor_points); if (!smoother_->Smooth(raw_ref, reference_line)) { AERROR << "Failed to smooth prefixed reference line with anchor points"; return false; } if (!IsReferenceLineSmoothValid(raw_ref, *reference_line)) { AERROR << "The smoothed reference line error is too large"; return false; } return true; } bool ReferenceLineProvider::SmoothReferenceLine( const ReferenceLine &raw_reference_line, ReferenceLine *reference_line) { if (!FLAGS_enable_smooth_reference_line) { *reference_line = raw_reference_line; return true; } // generate anchor points: std::vector<AnchorPoint> anchor_points; GetAnchorPoints(raw_reference_line, &anchor_points); smoother_->SetAnchorPoints(anchor_points); if (!smoother_->Smooth(raw_reference_line, reference_line)) { AERROR << "Failed to smooth reference line with anchor points"; return false; } if (!IsReferenceLineSmoothValid(raw_reference_line, *reference_line)) { AERROR << "The smoothed reference line error is too large"; return false; } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/spiral_reference_line_smoother.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. *****************************************************************************/ /* * spiral_reference_line_smoother.h */ #pragma once #include <vector> #include "Eigen/Dense" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_line_smoother.h" #include "modules/planning/reference_line/reference_point.h" namespace apollo { namespace planning { class SpiralReferenceLineSmoother : public ReferenceLineSmoother { public: explicit SpiralReferenceLineSmoother( const ReferenceLineSmootherConfig& config); virtual ~SpiralReferenceLineSmoother() = default; bool Smooth(const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) override; // For offline navigation line smoothing int SmoothStandAlone(std::vector<Eigen::Vector2d> point2d, std::vector<double>* ptr_theta, std::vector<double>* ptr_kappa, std::vector<double>* ptr_dkappa, std::vector<double>* ptr_s, std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; void SetAnchorPoints(const std::vector<AnchorPoint>&) override; std::vector<common::PathPoint> Interpolate(const std::vector<double>& theta, const std::vector<double>& kappa, const std::vector<double>& dkappa, const std::vector<double>& s, const std::vector<double>& x, const std::vector<double>& y, const double resolution) const; private: bool Smooth(std::vector<Eigen::Vector2d> point2d, std::vector<double>* ptr_theta, std::vector<double>* ptr_kappa, std::vector<double>* ptr_dkappa, std::vector<double>* ptr_s, std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; private: std::vector<common::PathPoint> Interpolate( const double start_x, const double start_y, const double start_s, const double theta0, const double kappa0, const double dkappa0, const double theta1, const double kappa1, const double dkappa1, const double delta_s, const double resolution) const; common::PathPoint to_path_point(const double x, const double y, const double s, const double theta, const double kappa, const double dkappa) const; std::vector<AnchorPoint> anchor_points_; bool fixed_start_point_ = false; double fixed_start_x_ = 0.0; double fixed_start_y_ = 0.0; double fixed_start_theta_ = 0.0; double fixed_start_kappa_ = 0.0; double fixed_start_dkappa_ = 0.0; double fixed_end_x_ = 0.0; double fixed_end_y_ = 0.0; double zero_x_ = 0.0; double zero_y_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "reference_line", srcs = [ "reference_line.cc", "reference_point.cc", ], hdrs = [ "reference_line.h", "reference_point.h", ], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util:util_tool", "//modules/map/pnc_map", "//modules/planning/common:planning_gflags", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@com_google_absl//:absl", ], ) cc_library( name = "reference_line_smoother", srcs = [], hdrs = ["reference_line_smoother.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/proto:reference_line_smoother_config_cc_proto", ], ) cc_library( name = "qp_spline_reference_line_smoother", srcs = ["qp_spline_reference_line_smoother.cc"], hdrs = ["qp_spline_reference_line_smoother.h"], copts = PLANNING_COPTS, deps = [ ":reference_line", ":reference_line_smoother", "//modules/planning/math:curve_math", "//modules/planning/math:polynomial_xd", "//modules/planning/math/smoothing_spline:osqp_spline_2d_solver", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:reference_line_smoother_config_cc_proto", "@eigen", ], ) cc_library( name = "spiral_reference_line_smoother", srcs = [ "spiral_problem_interface.cc", "spiral_reference_line_smoother.cc", ], hdrs = [ "spiral_problem_interface.h", "spiral_reference_line_smoother.h", ], copts = PLANNING_COPTS, deps = [ ":reference_line", ":reference_line_smoother", "//modules/common/math", "//modules/planning/common:planning_gflags", "//modules/planning/math/curve1d:quintic_spiral_path", "//modules/planning/math/smoothing_spline:spline_2d_solver", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@eigen", "@ipopt", ], ) cc_test( name = "spiral_reference_line_smoother_test", size = "small", srcs = ["spiral_reference_line_smoother_test.cc"], data = [ "//modules/planning:planning_conf", ], deps = [ ":spiral_reference_line_smoother", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "discrete_points_reference_line_smoother", srcs = ["discrete_points_reference_line_smoother.cc"], hdrs = ["discrete_points_reference_line_smoother.h"], copts = PLANNING_COPTS, deps = [ ":reference_line", ":reference_line_smoother", "//modules/common/math", "//modules/planning/common:planning_gflags", "//modules/planning/math:discrete_points_math", "//modules/planning/math/discretized_points_smoothing:cos_theta_smoother", "//modules/planning/math/discretized_points_smoothing:fem_pos_deviation_smoother", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:reference_line_smoother_config_cc_proto", ], ) cc_test( name = "qp_spline_reference_line_smoother_test", size = "small", srcs = ["qp_spline_reference_line_smoother_test.cc"], data = [ "//modules/planning:planning_conf", "//modules/planning:planning_testdata", ], deps = [ ":qp_spline_reference_line_smoother", "//modules/map/hdmap", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "discrete_points_reference_line_smoother_test", size = "small", srcs = ["discrete_points_reference_line_smoother_test.cc"], data = [ "//modules/planning:planning_conf", "//modules/planning:planning_testdata", ], deps = [ ":discrete_points_reference_line_smoother", "//modules/map/hdmap", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "reference_line_provider", srcs = ["reference_line_provider.cc"], hdrs = ["reference_line_provider.h"], copts = PLANNING_COPTS, deps = [ ":discrete_points_reference_line_smoother", ":qp_spline_reference_line_smoother", ":reference_line", ":spiral_reference_line_smoother", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/util:util_tool", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/map/pnc_map", "//modules/planning/common:indexed_queue", "//modules/planning/common:planning_context", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/proto:planning_status_cc_proto", "//modules/common/configs:config_gflags", "@eigen", ], ) cc_binary( name = "smoother_util", srcs = ["smoother_util.cc"], deps = [ ":discrete_points_reference_line_smoother", ":qp_spline_reference_line_smoother", ":reference_line", ":spiral_reference_line_smoother", "//modules/planning/proto:planning_config_cc_proto", ], ) cc_binary( name = "spiral_smoother_util", srcs = ["spiral_smoother_util.cc"], deps = [ ":spiral_reference_line_smoother", "//modules/planning/proto:planning_config_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/qp_spline_reference_line_smoother.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/reference_line/qp_spline_reference_line_smoother.h" #include <algorithm> #include <utility> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "cyber/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve_math.h" #include "modules/planning/math/smoothing_spline/osqp_spline_2d_solver.h" namespace apollo { namespace planning { QpSplineReferenceLineSmoother::QpSplineReferenceLineSmoother( const ReferenceLineSmootherConfig& config) : ReferenceLineSmoother(config) { spline_solver_.reset( new OsqpSpline2dSolver(t_knots_, config.qp_spline().spline_order())); } void QpSplineReferenceLineSmoother::Clear() { t_knots_.clear(); } bool QpSplineReferenceLineSmoother::Smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { Clear(); const double kEpsilon = 1e-6; if (!Sampling()) { AERROR << "Fail to sample reference line smoother points!"; return false; } spline_solver_->Reset(t_knots_, config_.qp_spline().spline_order()); if (!AddConstraint()) { AERROR << "Add constraint for spline smoother failed"; return false; } if (!AddKernel()) { AERROR << "Add kernel for spline smoother failed."; return false; } if (!Solve()) { AERROR << "Solve spline smoother problem failed"; } // mapping spline to reference line point const double start_t = t_knots_.front(); const double end_t = t_knots_.back(); const double resolution = (end_t - start_t) / (config_.num_of_total_points() - 1); double t = start_t; std::vector<ReferencePoint> ref_points; const auto& spline = spline_solver_->spline(); for (std::uint32_t i = 0; i < config_.num_of_total_points() && t < end_t; ++i, t += resolution) { const double heading = std::atan2(spline.DerivativeY(t), spline.DerivativeX(t)); const double kappa = CurveMath::ComputeCurvature( spline.DerivativeX(t), spline.SecondDerivativeX(t), spline.DerivativeY(t), spline.SecondDerivativeY(t)); const double dkappa = CurveMath::ComputeCurvatureDerivative( spline.DerivativeX(t), spline.SecondDerivativeX(t), spline.ThirdDerivativeX(t), spline.DerivativeY(t), spline.SecondDerivativeY(t), spline.ThirdDerivativeY(t)); std::pair<double, double> xy = spline(t); xy.first += ref_x_; xy.second += ref_y_; common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({xy.first, xy.second}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < -kEpsilon || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ref_sl_point.set_s(std::max(ref_sl_point.s(), 0.0)); ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); auto new_lane_waypoints = rlp.lane_waypoints(); for (auto& lane_waypoint : new_lane_waypoints) { lane_waypoint.l = ref_sl_point.l(); } ref_points.emplace_back(ReferencePoint( hdmap::MapPathPoint(common::math::Vec2d(xy.first, xy.second), heading, new_lane_waypoints), kappa, dkappa)); } ReferencePoint::RemoveDuplicates(&ref_points); if (ref_points.size() < 2) { AERROR << "Fail to generate smoothed reference line."; return false; } *smoothed_reference_line = ReferenceLine(ref_points); return true; } bool QpSplineReferenceLineSmoother::Sampling() { const double length = anchor_points_.back().path_point.s() - anchor_points_.front().path_point.s(); uint32_t num_spline = std::max(1u, static_cast<uint32_t>( length / config_.qp_spline().max_spline_length() + 0.5)); for (std::uint32_t i = 0; i <= num_spline; ++i) { t_knots_.push_back(i * 1.0); } // normalize point xy ref_x_ = anchor_points_.front().path_point.x(); ref_y_ = anchor_points_.front().path_point.y(); return true; } bool QpSplineReferenceLineSmoother::AddConstraint() { // Add x, y boundary constraint std::vector<double> headings; std::vector<double> longitudinal_bound; std::vector<double> lateral_bound; std::vector<common::math::Vec2d> xy_points; for (const auto& point : anchor_points_) { const auto& path_point = point.path_point; headings.push_back(path_point.theta()); longitudinal_bound.push_back(point.longitudinal_bound); lateral_bound.push_back(point.lateral_bound); xy_points.emplace_back(path_point.x() - ref_x_, path_point.y() - ref_y_); } const double scale = (anchor_points_.back().path_point.s() - anchor_points_.front().path_point.s()) / (t_knots_.back() - t_knots_.front()); std::vector<double> evaluated_t; for (const auto& point : anchor_points_) { evaluated_t.emplace_back(point.path_point.s() / scale); } auto* spline_constraint = spline_solver_->mutable_constraint(); // all points (x, y) should not deviate anchor points by a bounding box if (!spline_constraint->Add2dBoundary(evaluated_t, headings, xy_points, longitudinal_bound, lateral_bound)) { AERROR << "Add 2d boundary constraint failed."; return false; } // the heading of the first point should be identical to the anchor point. if (FLAGS_enable_reference_line_stitching && !spline_constraint->AddPointAngleConstraint(evaluated_t.front(), headings.front())) { AERROR << "Add 2d point angle constraint failed."; return false; } // all spline should be connected smoothly to the second order derivative. if (!spline_constraint->AddSecondDerivativeSmoothConstraint()) { AERROR << "Add jointness constraint failed."; return false; } return true; } bool QpSplineReferenceLineSmoother::AddKernel() { Spline2dKernel* kernel = spline_solver_->mutable_kernel(); // add spline kernel if (config_.qp_spline().second_derivative_weight() > 0.0) { kernel->AddSecondOrderDerivativeMatrix( config_.qp_spline().second_derivative_weight()); } if (config_.qp_spline().third_derivative_weight() > 0.0) { kernel->AddThirdOrderDerivativeMatrix( config_.qp_spline().third_derivative_weight()); } kernel->AddRegularization(config_.qp_spline().regularization_weight()); return true; } bool QpSplineReferenceLineSmoother::Solve() { return spline_solver_->Solve(); } void QpSplineReferenceLineSmoother::SetAnchorPoints( const std::vector<AnchorPoint>& anchor_points) { CHECK_GE(anchor_points.size(), 2U); anchor_points_ = anchor_points; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/reference_line_smoother.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <vector> #include "modules/planning/proto/reference_line_smoother_config.pb.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { struct AnchorPoint { common::PathPoint path_point; double lateral_bound = 0.0; double longitudinal_bound = 0.0; // enforce smoother to strictly follow this reference point bool enforced = false; }; class ReferenceLineSmoother { public: explicit ReferenceLineSmoother(const ReferenceLineSmootherConfig& config) : config_(config) {} /** * Smoothing constraints */ virtual void SetAnchorPoints( const std::vector<AnchorPoint>& achor_points) = 0; /** * Smooth a given reference line */ virtual bool Smooth(const ReferenceLine&, ReferenceLine* const) = 0; virtual ~ReferenceLineSmoother() = default; protected: ReferenceLineSmootherConfig config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/discrete_points_reference_line_smoother.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/reference_line/discrete_points_reference_line_smoother.h" #include <algorithm> #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/discrete_points_math.h" #include "modules/planning/math/discretized_points_smoothing/cos_theta_smoother.h" #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_smoother.h" namespace apollo { namespace planning { DiscretePointsReferenceLineSmoother::DiscretePointsReferenceLineSmoother( const ReferenceLineSmootherConfig& config) : ReferenceLineSmoother(config) {} bool DiscretePointsReferenceLineSmoother::Smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { std::vector<std::pair<double, double>> raw_point2d; std::vector<double> anchorpoints_lateralbound; for (const auto& anchor_point : anchor_points_) { raw_point2d.emplace_back(anchor_point.path_point.x(), anchor_point.path_point.y()); anchorpoints_lateralbound.emplace_back(anchor_point.lateral_bound); } // fix front and back points to avoid end states deviate from the center of // road anchorpoints_lateralbound.front() = 0.0; anchorpoints_lateralbound.back() = 0.0; NormalizePoints(&raw_point2d); bool status = false; const auto& smoothing_method = config_.discrete_points().smoothing_method(); std::vector<std::pair<double, double>> smoothed_point2d; switch (smoothing_method) { case DiscretePointsSmootherConfig::COS_THETA_SMOOTHING: status = CosThetaSmooth(raw_point2d, anchorpoints_lateralbound, &smoothed_point2d); break; case DiscretePointsSmootherConfig::FEM_POS_DEVIATION_SMOOTHING: status = FemPosSmooth(raw_point2d, anchorpoints_lateralbound, &smoothed_point2d); break; default: AERROR << "Smoother type not defined"; return false; } if (!status) { AERROR << "discrete_points reference line smoother fails"; return false; } DeNormalizePoints(&smoothed_point2d); std::vector<ReferencePoint> ref_points; GenerateRefPointProfile(raw_reference_line, smoothed_point2d, &ref_points); ReferencePoint::RemoveDuplicates(&ref_points); if (ref_points.size() < 2) { AERROR << "Fail to generate smoothed reference line."; return false; } *smoothed_reference_line = ReferenceLine(ref_points); return true; } bool DiscretePointsReferenceLineSmoother::CosThetaSmooth( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<std::pair<double, double>>* ptr_smoothed_point2d) { const auto& cos_theta_config = config_.discrete_points().cos_theta_smoothing(); CosThetaSmoother smoother(cos_theta_config); // box contraints on pos are used in cos theta smoother, thus shrink the // bounds by 1.0 / sqrt(2.0) std::vector<double> box_bounds = bounds; const double box_ratio = 1.0 / std::sqrt(2.0); for (auto& bound : box_bounds) { bound *= box_ratio; } std::vector<double> opt_x; std::vector<double> opt_y; bool status = smoother.Solve(raw_point2d, box_bounds, &opt_x, &opt_y); if (!status) { AERROR << "Costheta reference line smoothing failed"; return false; } if (opt_x.size() < 2 || opt_y.size() < 2) { AERROR << "Return by Costheta smoother is wrong. Size smaller than 2 "; return false; } CHECK_EQ(opt_x.size(), opt_y.size()) << "x and y result size not equal"; size_t point_size = opt_x.size(); for (size_t i = 0; i < point_size; ++i) { ptr_smoothed_point2d->emplace_back(opt_x[i], opt_y[i]); } return true; } bool DiscretePointsReferenceLineSmoother::FemPosSmooth( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<std::pair<double, double>>* ptr_smoothed_point2d) { const auto& fem_pos_config = config_.discrete_points().fem_pos_deviation_smoothing(); FemPosDeviationSmoother smoother(fem_pos_config); // box contraints on pos are used in fem pos smoother, thus shrink the // bounds by 1.0 / sqrt(2.0) std::vector<double> box_bounds = bounds; const double box_ratio = 1.0 / std::sqrt(2.0); for (auto& bound : box_bounds) { bound *= box_ratio; } std::vector<double> opt_x; std::vector<double> opt_y; bool status = smoother.Solve(raw_point2d, box_bounds, &opt_x, &opt_y); if (!status) { AERROR << "Fem Pos reference line smoothing failed"; return false; } if (opt_x.size() < 2 || opt_y.size() < 2) { AERROR << "Return by fem pos smoother is wrong. Size smaller than 2 "; return false; } CHECK_EQ(opt_x.size(), opt_y.size()) << "x and y result size not equal"; size_t point_size = opt_x.size(); for (size_t i = 0; i < point_size; ++i) { ptr_smoothed_point2d->emplace_back(opt_x[i], opt_y[i]); } return true; } void DiscretePointsReferenceLineSmoother::SetAnchorPoints( const std::vector<AnchorPoint>& anchor_points) { CHECK_GT(anchor_points.size(), 1U); anchor_points_ = anchor_points; } void DiscretePointsReferenceLineSmoother::NormalizePoints( std::vector<std::pair<double, double>>* xy_points) { zero_x_ = xy_points->front().first; zero_y_ = xy_points->front().second; std::for_each(xy_points->begin(), xy_points->end(), [this](std::pair<double, double>& point) { auto curr_x = point.first; auto curr_y = point.second; std::pair<double, double> xy(curr_x - zero_x_, curr_y - zero_y_); point = std::move(xy); }); } void DiscretePointsReferenceLineSmoother::DeNormalizePoints( std::vector<std::pair<double, double>>* xy_points) { std::for_each(xy_points->begin(), xy_points->end(), [this](std::pair<double, double>& point) { auto curr_x = point.first; auto curr_y = point.second; std::pair<double, double> xy(curr_x + zero_x_, curr_y + zero_y_); point = std::move(xy); }); } bool DiscretePointsReferenceLineSmoother::GenerateRefPointProfile( const ReferenceLine& raw_reference_line, const std::vector<std::pair<double, double>>& xy_points, std::vector<ReferencePoint>* reference_points) { // Compute path profile std::vector<double> headings; std::vector<double> kappas; std::vector<double> dkappas; std::vector<double> accumulated_s; if (!DiscretePointsMath::ComputePathProfile( xy_points, &headings, &accumulated_s, &kappas, &dkappas)) { return false; } // Load into ReferencePoints size_t points_size = xy_points.size(); for (size_t i = 0; i < points_size; ++i) { common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({xy_points[i].first, xy_points[i].second}, &ref_sl_point)) { return false; } const double kEpsilon = 1e-6; if (ref_sl_point.s() < -kEpsilon || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ref_sl_point.set_s(std::max(ref_sl_point.s(), 0.0)); ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); auto new_lane_waypoints = rlp.lane_waypoints(); for (auto& lane_waypoint : new_lane_waypoints) { lane_waypoint.l = ref_sl_point.l(); } reference_points->emplace_back(ReferencePoint( hdmap::MapPathPoint( common::math::Vec2d(xy_points[i].first, xy_points[i].second), headings[i], new_lane_waypoints), kappas[i], dkappas[i])); } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/reference_line/spiral_reference_line_smoother_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/reference_line/spiral_reference_line_smoother.h" #include "gtest/gtest.h" #include "modules/planning/proto/reference_line_smoother_config.pb.h" namespace apollo { namespace planning { class SpiralReferenceLineSmootherTest : public ::testing::Test { public: virtual void SetUp() { config_.mutable_spiral()->set_max_deviation(0.1); config_.mutable_spiral()->set_max_iteration(300); config_.mutable_spiral()->set_opt_tol(1.0e-6); config_.mutable_spiral()->set_opt_acceptable_tol(1.0e-4); config_.mutable_spiral()->set_weight_curve_length(1.0); config_.mutable_spiral()->set_weight_kappa(1.0); config_.mutable_spiral()->set_weight_dkappa(100.0); raw_points_.resize(21); raw_points_[0] = {4.946317773, 0.08436953512}; raw_points_[1] = {5.017218975, 0.7205757236}; raw_points_[2] = {4.734635316, 1.642930209}; raw_points_[3] = {4.425064575, 2.365356462}; raw_points_[4] = {3.960102096, 2.991632152}; raw_points_[5] = {3.503172702, 3.44091492}; raw_points_[6] = {2.989950824, 3.9590821}; raw_points_[7] = {2.258523535, 4.554377368}; raw_points_[8] = {1.562447892, 4.656801472}; raw_points_[9] = {0.8764776599, 4.971705856}; raw_points_[10] = {0.09899323097, 4.985845841}; raw_points_[11] = {-0.7132021974, 5.010851105}; raw_points_[12] = {-1.479055426, 4.680181989}; raw_points_[13] = {-2.170306775, 4.463442715}; raw_points_[14] = {-3.034455492, 4.074651273}; raw_points_[15] = {-3.621987909, 3.585790302}; raw_points_[16] = {-3.979289889, 3.014232351}; raw_points_[17] = {-4.434628966, 2.367848826}; raw_points_[18] = {-4.818245921, 1.467395733}; raw_points_[19] = {-4.860190444, 0.8444358019}; raw_points_[20] = {-5.09947597, -0.01022405467}; } ReferenceLineSmootherConfig config_; std::vector<Eigen::Vector2d> raw_points_; }; TEST_F(SpiralReferenceLineSmootherTest, smooth_stand_alone) { std::vector<double> theta; std::vector<double> kappa; std::vector<double> dkappa; std::vector<double> s; std::vector<double> x; std::vector<double> y; SpiralReferenceLineSmoother spiral_smoother(config_); int res = spiral_smoother.SmoothStandAlone(raw_points_, &theta, &kappa, &dkappa, &s, &x, &y); // TODO(Yajia): fix this test. EXPECT_LT(res, 100000); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/README.md
# Protobuf Package lgsvl_msgs for LG SVL Automotive Simulator This repository contains protobuf message definitions for lgsvl_msgs to subscribe protobuf messages being published by LG SVL Automotive Simulator via cyber bridge. ```text <proto> - detection2d.proto # 2D detection including id, label, score, and 2D bounding box - detection2darray.proto # A list of 2D detections - detection3d.proto # 3D detection including id, label, score, and 3D bounding box - detection3darray.proto # A list of 3D detections ``` # Copyright and License Copyright (c) 2018 LG Electronics, Inc. This software contains code licensed as described in LICENSE.
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package lgsvl_msgs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0.0.1 (2018-12-18) ------------------ * add changelog * update initial version number * add license * add Ros package for ground truth messages * initial commit * Contributors: David Uhm
0
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/proto/detection3d.proto
syntax = "proto3"; import "modules/common_msgs/basic_msgs/header.proto"; import "modules/common_msgs/basic_msgs/geometry.proto"; import "modules/contrib/lgsvl_msgs/proto/detection2d.proto"; package apollo.contrib.lgsvl_msgs; message Pose { apollo.common.Point3D position = 1; apollo.common.Quaternion orientation = 2; } message BoundingBox3D { Pose position = 1; Vector3 size = 2; } message Detection3D { apollo.common.Header header = 1; uint32 id = 2; string label = 3; double score = 4; BoundingBox3D bbox = 5; Twist velocity = 6; }
0
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/proto/detection3darray.proto
syntax = "proto3"; import "modules/common_msgs/basic_msgs/header.proto"; import "modules/contrib/lgsvl_msgs/proto/detection3d.proto"; package apollo.contrib.lgsvl_msgs; message Detection3DArray { apollo.common.Header header = 1; repeated Detection3D detections = 2; }
0
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "detection3d_cc_proto", deps = [ ":detection3d_proto", ], ) proto_library( name = "detection3d_proto", srcs = ["detection3d.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", "//modules/common_msgs/basic_msgs:geometry_proto", ":detection2d_proto", ], ) py_proto_library( name = "detection3d_py_pb2", deps = [ ":detection3d_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", "//modules/common_msgs/basic_msgs:geometry_py_pb2", ":detection2d_py_pb2", ], ) cc_proto_library( name = "detection3darray_cc_proto", deps = [ ":detection3darray_proto", ], ) proto_library( name = "detection3darray_proto", srcs = ["detection3darray.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ":detection3d_proto", ], ) py_proto_library( name = "detection3darray_py_pb2", deps = [ ":detection3darray_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ":detection3d_py_pb2", ], ) cc_proto_library( name = "detection2d_cc_proto", deps = [ ":detection2d_proto", ], ) proto_library( name = "detection2d_proto", srcs = ["detection2d.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ], ) py_proto_library( name = "detection2d_py_pb2", deps = [ ":detection2d_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ], ) cc_proto_library( name = "detection2darray_cc_proto", deps = [ ":detection2darray_proto", ], ) proto_library( name = "detection2darray_proto", srcs = ["detection2darray.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ":detection2d_proto", ], ) py_proto_library( name = "detection2darray_py_pb2", deps = [ ":detection2darray_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ":detection2d_py_pb2", ], )
0
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/proto/detection2d.proto
syntax = "proto3"; import "modules/common_msgs/basic_msgs/header.proto"; package apollo.contrib.lgsvl_msgs; message BoundingBox2D { float x = 1; float y = 2; float width = 3; float height = 4; } message Vector3 { double x = 1; double y = 2; double z = 3; } message Twist { Vector3 linear = 1; Vector3 angular = 2; } message Detection2D { apollo.common.Header header = 1; uint32 id = 2; string label = 3; double score = 4; BoundingBox2D bbox = 5; Twist velocity = 6; }
0
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs
apollo_public_repos/apollo/modules/contrib/lgsvl_msgs/proto/detection2darray.proto
syntax = "proto3"; import "modules/common_msgs/basic_msgs/header.proto"; import "modules/contrib/lgsvl_msgs/proto/detection2d.proto"; package apollo.contrib.lgsvl_msgs; message Detection2DArray { apollo.common.Header header = 1; repeated Detection2D detections = 2; }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/node.cc
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #include "modules/contrib/cyber_bridge/node.h" #include <utility> #include "cyber/common/log.h" #include "cyber/cyber.h" #include "cyber/message/py_message.h" #include "cyber/node/node.h" #include "cyber/node/reader.h" #include "cyber/node/writer.h" #include "modules/contrib/cyber_bridge/client.h" using apollo::cyber::message::PyMessageWrap; Node::Node() : node(apollo::cyber::CreateNode("bridge")) {} Node::~Node() {} void Node::remove(std::shared_ptr<Client> client) { for (auto it = writers.begin(); it != writers.end(); /* empty */) { if (it->second.clients.find(client) != it->second.clients.end()) { ADEBUG << "Removing client writer"; it->second.clients.erase(client); if (it->second.clients.empty()) { ADEBUG << "Removing Cyber writer"; it = writers.erase(it); } else { it++; } } else { it++; } } std::lock_guard<std::mutex> lock(mutex); for (auto it = readers.begin(); it != readers.end(); /* empty */) { if (it->second.clients.find(client) != it->second.clients.end()) { ADEBUG << "Removing client reader"; it->second.clients.erase(client); if (it->second.clients.empty()) { ADEBUG << "Removing Cyber reader"; it = readers.erase(it); } else { it++; } } else { it++; } } } void Node::add_reader(const std::string& channel, const std::string& type, std::shared_ptr<Client> client) { auto rit = readers.find(channel); if (rit != readers.end()) { ADEBUG << "Adding client to existing " << channel; rit->second.clients.insert(client); return; } auto cb = [this, channel](const std::shared_ptr<const PyMessageWrap>& msg) { ADEBUG << "New message on " << channel; const std::string& data = msg->data(); std::lock_guard<std::mutex> lock(mutex); auto it = readers.find(channel); if (it != readers.end()) { for (auto client : it->second.clients) { client->publish(channel, data); } } }; ADEBUG << "Adding new reader to " << channel; Reader reader; reader.reader = node->CreateReader<PyMessageWrap>(channel, cb); reader.clients.insert(client); std::lock_guard<std::mutex> lock(mutex); readers.insert(std::make_pair(channel, reader)); } void Node::add_writer(const std::string& channel, const std::string& type, std::shared_ptr<Client> client) { auto wit = writers.find(channel); if (wit != writers.end()) { wit->second.clients.insert(client); return; } Writer writer; writer.type = type; apollo::cyber::message::ProtobufFactory::Instance()->GetDescriptorString( type, &writer.desc); if (writer.desc.empty()) { AWARN << "Cannot find proto descriptor for message type " << type; return; } apollo::cyber::proto::RoleAttributes role; role.set_channel_name(channel); role.set_message_type(type); role.set_proto_desc(writer.desc); auto qos_profile = role.mutable_qos_profile(); qos_profile->set_depth(1); writer.writer = node->CreateWriter<PyMessageWrap>(role); writer.clients.insert(client); writers.insert(std::make_pair(channel, writer)); } void Node::publish(const std::string& channel, const std::string& data) { auto writer = writers.find(channel); if (writer == writers.end()) { AWARN << "No writer registered on channel " << channel; return; } auto message = std::make_shared<PyMessageWrap>(data, writer->second.type); writer->second.writer->Write(message); }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/clients.h
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #pragma once #include <memory> #include <unordered_set> #include "boost/asio.hpp" class Client; class Clients { public: Clients(); ~Clients(); void start(std::shared_ptr<Client> client); void stop(std::shared_ptr<Client> client); void stop_all(); private: std::unordered_set<std::shared_ptr<Client>> clients; };
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/client.h
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #pragma once #include <cstdint> #include <string> #include <vector> #include "boost/asio.hpp" class Clients; class Node; class Client : public std::enable_shared_from_this<Client> { public: Client(Node* node, Clients* clients, boost::asio::ip::tcp::socket socket); ~Client(); void start(); void stop(); void publish(const std::string& channel, const std::string& msg); private: Node& node; Clients& clients; boost::asio::ip::tcp::socket socket; uint8_t temp[1024 * 1024]; std::vector<uint8_t> buffer; std::vector<uint8_t> writing; std::vector<uint8_t> pending; std::mutex publish_mutex; const uint MAX_PENDING_SIZE = 1073741824; // 1GB void handle_read(const boost::system::error_code& ec, std::size_t length); void handle_write(const boost::system::error_code& ec); void handle_register_desc(); void handle_add_writer(); void handle_add_reader(); void handle_publish(); uint32_t get32le(size_t offset) const; };
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/cyberfile.xml
<package format="2"> <name>cyber-bridge</name> <version>local</version> <description> This is bridge that exposes custom TCP socket for accepting and transmitting Cyber messages. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//modules/contrib/cyber_bridge</src_path> </package>
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/node.h
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #pragma once #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <unordered_set> namespace apollo { namespace cyber { class Node; template <class T> class Writer; template <class T> class Reader; namespace message { class PyMessageWrap; } } // namespace cyber } // namespace apollo class Client; class Node { public: Node(); ~Node(); void remove(std::shared_ptr<Client> client); void add_reader(const std::string& channel, const std::string& type, std::shared_ptr<Client> client); void add_writer(const std::string& channel, const std::string& type, std::shared_ptr<Client> client); void publish(const std::string& channel, const std::string& data); private: std::unique_ptr<apollo::cyber::Node> node; std::mutex mutex; struct Writer { std::string desc; std::string type; std::shared_ptr< apollo::cyber::Writer<apollo::cyber::message::PyMessageWrap>> writer; std::unordered_set<std::shared_ptr<Client>> clients; }; struct Reader { std::shared_ptr< apollo::cyber::Reader<apollo::cyber::message::PyMessageWrap>> reader; std::unordered_set<std::shared_ptr<Client>> clients; }; typedef std::unordered_map<std::string, Writer> Writers; typedef std::unordered_map<std::string, Reader> Readers; Writers writers; Readers readers; };
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/clients.cc
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #include "modules/contrib/cyber_bridge/clients.h" #include <memory> #include "modules/contrib/cyber_bridge/client.h" Clients::Clients() {} Clients::~Clients() {} void Clients::start(std::shared_ptr<Client> client) { clients.insert(client); client->start(); } void Clients::stop(std::shared_ptr<Client> client) { clients.erase(client); client->stop(); } void Clients::stop_all() { for (auto& client : clients) { client->stop(); } clients.clear(); }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/README.md
# Apollo Cyber bridge for the `master` branch This is bridge that exposes custom TCP socket for accepting and transmitting Cyber messages. # Building Run the build from the `/apollo` directory inside docker. ``` bazel build //modules/contrib/cyber_bridge ``` # Running From the `/apollo` directory, execute: ``` ./bazel-bin/module/contrib/cyber_bridge/cyber_bridge ``` For extra logging: ``` GLOG_v=4 GLOG_logtostderr=1 ./bazel-bin/modules/contrib/cyber_bridge/cyber_bridge ``` Add extra `-port 9090` argument for custom port (9090 is default). # Example In one terminal launch `cyber_bridge`: ``` ./bazel-bin/modules/contrib/cyber_bridge/cyber_bridge ``` In another terminal launch example talker: ``` ./bazel-bin/cyber/python/cyber_py3/examples/talker ``` In one more terminal launch example listener: ``` ./bazel-bin/cyber/python/cyber_py3/examples/listener ``` Now you should observe talker and listener sending & receiving message with incrementing integer.
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/client.cc
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #include "modules/contrib/cyber_bridge/client.h" #include <functional> #include <memory> #include <string> #include <utility> #include "boost/bind.hpp" #include "cyber/common/log.h" #include "cyber/message/protobuf_factory.h" #include "modules/contrib/cyber_bridge/clients.h" #include "modules/contrib/cyber_bridge/node.h" enum { OP_REGISTER_DESC = 1, OP_ADD_READER = 2, OP_ADD_WRITER = 3, OP_PUBLISH = 4, }; Client::Client(Node* node, Clients* clients, boost::asio::ip::tcp::socket s) : node(*node), clients(*clients), socket(std::move(s)) { auto endpoint = socket.remote_endpoint(); AINFO << "Client [" << endpoint.address() << ":" << endpoint.port() << "] connected"; } Client::~Client() {} void Client::start() { socket.async_read_some( boost::asio::buffer(temp, sizeof(temp)), boost::bind(&Client::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void Client::stop() { socket.close(); } void Client::handle_read(const boost::system::error_code& ec, std::size_t size) { if (!ec) { ADEBUG << "Received " << size << " bytes"; buffer.insert(buffer.end(), temp, temp + size); size_t size = buffer.size(); while (size >= sizeof(uint8_t)) { if (buffer[0] == OP_REGISTER_DESC) { handle_register_desc(); } else if (buffer[0] == OP_ADD_READER) { handle_add_reader(); } else if (buffer[0] == OP_ADD_WRITER) { handle_add_writer(); } else if (buffer[0] == OP_PUBLISH) { handle_publish(); } else { AERROR << "Unknown operation received from client (" << uint32_t(buffer[0]) << "), disconnecting client"; clients.stop(shared_from_this()); return; } if (size == buffer.size()) { break; } size = buffer.size(); } start(); return; } if (ec == boost::asio::error::eof) { // remote side closed connection clients.stop(shared_from_this()); node.remove(shared_from_this()); return; } if (ec != boost::asio::error::operation_aborted) { AERROR << "Client read failed, disconnecting" << ec; clients.stop(shared_from_this()); node.remove(shared_from_this()); return; } } void Client::handle_write(const boost::system::error_code& ec) { if (ec) { if (ec != boost::asio::error::operation_aborted) { AERROR << "Client write failed, disconnecting" << ec; clients.stop(shared_from_this()); node.remove(shared_from_this()); } return; } std::lock_guard<std::mutex> lock(publish_mutex); writing.clear(); if (!pending.empty()) { writing.swap(pending); boost::asio::async_write( socket, boost::asio::buffer(writing.data(), writing.size()), boost::bind(&Client::handle_write, shared_from_this(), boost::asio::placeholders::error)); } } // [1] [count] [string] ... [string] void Client::handle_register_desc() { if (sizeof(uint8_t) + sizeof(uint32_t) > buffer.size()) { ADEBUG << "handle_register_desc too short"; return; } uint32_t count = get32le(1); std::vector<std::string> desc; bool complete = true; size_t offset = sizeof(uint8_t) + sizeof(uint32_t); for (uint32_t i = 0; i < count; i++) { if (offset + sizeof(uint32_t) > buffer.size()) { ADEBUG << "handle_register_desc too short"; complete = false; break; } uint32_t size = get32le(offset); offset += sizeof(uint32_t); if (offset + size > buffer.size()) { ADEBUG << "handle_register_desc too short"; complete = false; break; } desc.push_back(std::string(reinterpret_cast<char*>(&buffer[offset]), size)); offset += size; } if (complete) { ADEBUG << "OP_REGISTER_DESC, count = " << count; auto factory = apollo::cyber::message::ProtobufFactory::Instance(); for (const auto& s : desc) { factory->RegisterPythonMessage(s); } buffer.erase(buffer.begin(), buffer.begin() + offset); } } // [2] [channel] [type] void Client::handle_add_reader() { if (sizeof(uint8_t) + 2 * sizeof(uint32_t) > buffer.size()) { ADEBUG << "handle_add_reader too short header"; return; } size_t offset = sizeof(uint8_t); uint32_t channel_length = get32le(offset); offset += sizeof(uint32_t); if (offset + channel_length > buffer.size()) { ADEBUG << "handle_add_reader short1 " << offset + channel_length << " " << buffer.size(); return; } std::string channel(reinterpret_cast<char*>(&buffer[offset]), channel_length); offset += channel_length; uint32_t type_length = get32le(offset); offset += sizeof(uint32_t); if (offset + type_length > buffer.size()) { ADEBUG << "handle_add_reader short2 " << offset + type_length << " " << buffer.size(); return; } std::string type(reinterpret_cast<char*>(&buffer[offset]), type_length); offset += type_length; ADEBUG << "OP_NEW_READER, channel = " << channel << ", type = " << type; node.add_reader(channel, type, shared_from_this()); buffer.erase(buffer.begin(), buffer.begin() + offset); } // [3] [channel] [type] void Client::handle_add_writer() { if (sizeof(uint8_t) + 2 * sizeof(uint32_t) > buffer.size()) { ADEBUG << "handle_new_writer too short header"; return; } size_t offset = sizeof(uint8_t); uint32_t channel_length = get32le(offset); offset += sizeof(uint32_t); if (offset + channel_length > buffer.size()) { ADEBUG << "handle_new_writer short1 " << offset + channel_length << " " << buffer.size(); return; } std::string channel(reinterpret_cast<char*>(&buffer[offset]), channel_length); offset += channel_length; uint32_t type_length = get32le(offset); offset += sizeof(uint32_t); if (offset + type_length > buffer.size()) { ADEBUG << "handle_new_writer short2 " << offset + type_length << " " << buffer.size(); return; } std::string type(reinterpret_cast<char*>(&buffer[offset]), type_length); offset += type_length; ADEBUG << "OP_NEW_WRITER, channel = " << channel << ", type = " << type; node.add_writer(channel, type, shared_from_this()); buffer.erase(buffer.begin(), buffer.begin() + offset); } // [4] [channel] [message] void Client::handle_publish() { if (sizeof(uint8_t) + 2 * sizeof(uint32_t) > buffer.size()) { return; } size_t offset = sizeof(uint8_t); uint32_t channel_length = get32le(offset); offset += sizeof(uint32_t); if (offset + channel_length > buffer.size()) { return; } std::string channel(reinterpret_cast<char*>(&buffer[offset]), channel_length); offset += channel_length; uint32_t message_length = get32le(offset); offset += sizeof(uint32_t); if (offset + message_length > buffer.size()) { return; } std::string message(reinterpret_cast<char*>(&buffer[offset]), message_length); offset += message_length; ADEBUG << "OP_PUBLISH, channel = " << channel; node.publish(channel, message); buffer.erase(buffer.begin(), buffer.begin() + offset); } void fill_data(std::vector<uint8_t>* data, const std::string& channel, const std::string& msg) { data->reserve(data->size() + sizeof(uint8_t) + sizeof(uint32_t) + channel.size() + sizeof(uint32_t) + msg.size()); data->push_back(OP_PUBLISH); data->push_back(uint8_t(channel.size() >> 0)); data->push_back(uint8_t(channel.size() >> 8)); data->push_back(uint8_t(channel.size() >> 16)); data->push_back(uint8_t(channel.size() >> 24)); const uint8_t* channel_data = reinterpret_cast<const uint8_t*>(channel.data()); data->insert(data->end(), channel_data, channel_data + channel.size()); data->push_back(uint8_t(msg.size() >> 0)); data->push_back(uint8_t(msg.size() >> 8)); data->push_back(uint8_t(msg.size() >> 16)); data->push_back(uint8_t(msg.size() >> 24)); const uint8_t* msg_data = reinterpret_cast<const uint8_t*>(msg.data()); data->insert(data->end(), msg_data, msg_data + msg.size()); } void Client::publish(const std::string& channel, const std::string& msg) { std::lock_guard<std::mutex> lock(publish_mutex); if (writing.empty()) { fill_data(&writing, channel, msg); boost::asio::async_write( socket, boost::asio::buffer(writing.data(), writing.size()), boost::bind(&Client::handle_write, shared_from_this(), boost::asio::placeholders::error)); } else if (pending.size() < MAX_PENDING_SIZE) { fill_data(&pending, channel, msg); } else { // If pending size is larger than MAX_PENDING_SIZE, discard the message. AERROR << "Pending size too large. Discard message."; } } uint32_t Client::get32le(size_t offset) const { return buffer[offset + 0] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/bridge.cc
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #include <memory> #include <gflags/gflags.h> #include "cyber/common/log.h" #include "cyber/init.h" #include "modules/contrib/cyber_bridge/node.h" #include "modules/contrib/cyber_bridge/server.h" // bazel build //cyber/bridge:cyber_bridge // GLOG_v=4 GLOG_logtostderr=1 // ./bazel-bin/modules/contrib/cyber_bridge/cyber_bridge int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); apollo::cyber::Init(argv[0]); { Node node; auto server = std::make_shared<Server>(&node); server->run(); } apollo::cyber::Clear(); }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/server.cc
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #include "modules/contrib/cyber_bridge/server.h" #include <signal.h> #include <cstdint> #include <functional> #include <memory> #include <utility> #include "boost/bind.hpp" #include "cyber/common/log.h" #include "gflags/gflags.h" #include "modules/contrib/cyber_bridge/client.h" DEFINE_int32(port, 9090, "tcp listen port"); Server::Server(Node* node) : node(*node), signals(io), endpoint(boost::asio::ip::tcp::v4(), (uint16_t)FLAGS_port), acceptor(io, endpoint), socket(io) { signals.add(SIGTERM); signals.add(SIGINT); } Server::~Server() {} void Server::run() { signals.async_wait(boost::bind(&Server::stop, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::signal_number)); begin_accept(); io.run(); } void Server::stop(const boost::system::error_code& ec, int signal_number) { if (ec) { AERROR << "Error waiting on signals: " << ec.message(); } else { AINFO << "Signal " << signal_number << " received, stopping server"; } acceptor.close(); clients.stop_all(); } void Server::begin_accept() { acceptor.async_accept(socket, boost::bind(&Server::end_accept, shared_from_this(), boost::asio::placeholders::error)); } void Server::end_accept(const boost::system::error_code& ec) { if (!acceptor.is_open()) { return; } if (ec) { AERROR << "Error accepting connection: " << ec.message(); } else { auto client = std::make_shared<Client>(&node, &clients, std::move(socket)); clients.start(client); } begin_accept(); }
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install", "install_files", "install_src_files") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", data_dest = "cyber-bridge", data = [ ":cyberfile.xml", ":cyber-bridge.BUILD", ], targets = [ ":cyber_bridge", ], runtime_dest = "cyber-bridge/bin", deps = [ "//cyber:install", ], ) install_src_files( name = "install_src", deps = [ ":install_cyber-bridge_src", ":install_cyber-bridge_hdrs" ], ) install_src_files( name = "install_cyber-bridge_src", src_dir = ["."], dest = "cyber-bridge/src", filter = "*", ) install_src_files( name = "install_cyber-bridge_hdrs", src_dir = ["."], dest = "cyber-bridge/include", filter = "*.h", ) cc_binary( name = "cyber_bridge", srcs = ["bridge.cc"], deps = [ ":bridge_server", "@boost", "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "bridge_server", srcs = ["server.cc"], hdrs = ["server.h"], deps = [ ":bridge_client", ], ) cc_library( name = "bridge_client", srcs = ["client.cc"], deps = [ ":bridge_clients", ":bridge_node", "@boost", ], ) cc_library( name = "bridge_clients", srcs = ["clients.cc"], hdrs = ["clients.h"], deps = [ ":bridge_client_header", "@boost", ], ) cc_library( name = "bridge_node", srcs = ["node.cc"], hdrs = ["node.h"], deps = [ ":bridge_client_header", ], ) cc_library( name = "bridge_client_header", hdrs = ["client.h"], deps = [ "//cyber", "@boost", ], ) cpplint()
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/server.h
/** * Copyright (c) 2019 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ #pragma once #include <unordered_set> #include "boost/asio.hpp" #include "modules/contrib/cyber_bridge/clients.h" class Node; class Server : public std::enable_shared_from_this<Server> { public: explicit Server(Node* node); ~Server(); void run(); private: Node& node; Clients clients; boost::asio::io_service io; boost::asio::signal_set signals; boost::asio::ip::tcp::endpoint endpoint; boost::asio::ip::tcp::acceptor acceptor; boost::asio::ip::tcp::socket socket; void stop(const boost::system::error_code& error, int signal_number); void begin_accept(); void end_accept(const boost::system::error_code& ec); };
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/cyber_bridge/cyber-bridge.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "cyber_bridge", includes = ["include"], hdrs = glob(["include/**/*"]), srcs = glob(["lib/**/*.so*"]), include_prefix = "modules/cyber_bridge", strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/e2e/README.md
You can download the e2e (aka. End-To-End) module here [e2e-1.5.zip](https://github.com/ApolloAuto/apollo/releases/download/v1.5.0/e2e-1.5.zip)
0
apollo_public_repos/apollo/modules/contrib
apollo_public_repos/apollo/modules/contrib/elo/README.md
### Download You can download the elo (aka Ego Localization) module here [elo-1.5.zip](https://github.com/ApolloAuto/apollo/releases/download/v1.5.0/elo-1.5.zip) ### 1. Introduction Baidu ego localization system is an accurate ego localization solution for self-driving. By combining sensor information, Global navigation satellite systems (GNSS), and Baidu HD Map into one system, Baidu ego localization system is able to offer a localization solution with high accuracy. GNSS positioning observes range measurements from orbiting GNSS satellites, while GNSS in general has some restrictions that it may not be available for high accuracy requirements of self-driving. Baidu ego localization system combines sensor information with HD Map and GNSS solution to provide high-accuracy localization solution. System extracts features from sensors and Baidu HD Map for feature matching. After feature matching, system is able to locate current vehicle in HD Map. Motion compensation is proposed to compensate current localization solution. ![components of Baidu ego localization system](flowchart.jpg) The main components of Baidu ego localization system is introduced as follow: * Sensors: include vision sensors (in-vehicle cameras, industrial camera CCDs and other image collecting sensors) and position sensors (include GPS, GLONASS, Beidou and other GNSS). * HD Map: HD Map provides road information within specific area. * Real-time location feature: Baidu ego localization system applies deep neural network architecture `ENet` (see: [ENet: A Deep Neural Network Architecture for Real-Time Semantic Segmentation](https://arxiv.org/abs/1606.02147)) to extract lane lines and mark features by sensor for feature matching. * Pre-stored location feature: obtains lane lines and mark features provided by HD Map. * Feature matching: Baidu ego localization system locates current ego vehicle in HD Map by feature matching. * Motion compensation: compensates current frame and adjusts the matching result via historical information. ### 2. Requirements: software #### a. External dependencies * Requirements for `cmake 2.8.7` or higher (see: [cmake installation instructions](https://cmake.org/Wiki/CMake)) * Requirements for `OpenCV 3.X` (see: [OpenCV installation instructions](http://docs.opencv.org/master/df/d65/tutorial_table_of_content_introduction.html)) * Recommended requirements for `Protobuf` (see: [github](https://github.com/google/protobuf)) * Recommended requirements for `CUDA` (see: [CUDA installation instructions](http://docs.nvidia.com/cuda/index.html#installation-guides)) * Recommended requirements for `Eigen 3` (see: [Eigen installation instructions](http://eigen.tuxfamily.org/dox/)) * Recommended requirements for `jsoncpp` (see: [github](https://github.com/open-source-parsers/jsoncpp)) #### b. Internal dependencies * Requirements for `modified Caffe` (`lib/libcaffe.so`) * Requirements for `HD Map database` (`config/hadmap/hadmap.db`) ### 3. Requirements: hardware Deployed on NVIDIA Drive PX2 (PDK 4.1.4.0). ### 4. Data format * Input file: Note that optimum solution from SPAN-CPT (`ground_truth_longitude` and `ground_truth_latitude`) are provided to make comparison with solution from Baidu ego localization system. ``` image_name longitude latitude ground_truth_longitude ground_truth_latitude ``` * Config file: ``` # effective image rectangle: top-left corner point, width and height of resulting cropped image in BGR format, pixel top-left_corner_point_x top-left_corner_point_y width height # width and height of ENet input image, pixel segmented_image_width segmented_image_height # camera parameters: principal point, focal length and rotation angle of camera related to vehicle coordinate system, pixel and radian principal_point_x principal_point_y focal_length_x focal_length_y pitch yaw roll # center point of image, pixel center_point_x center_point_y # ENet parameters file enet_para_path # ENet structure file enet_structure_path # camera parameters: translation of camera related to vehicle coordinate system, pixel translation_x translation_y # database of HD Map database_path ``` Sample config parameters ``` 510 808 1410 1068 448 224 948.617 628.628 1918.64 1924.48 -3.9 0.6 0 960 604 ../data/model/model_binary.caffemodel ../data/model/net.prototxt 0 150 ../data/hadmap/hadmap.xml ``` * Output format: ``` image_name [+] Begin Localization [-] End Localization, misc time: runtime #### [INFO] GROUNDTRUTH (ground_truth_longitude, ground_truth_latitude) LOCALIZATION (localization_longitude, localization_latitude) ``` Sample output: ``` 20170628_000039131.jpg [+] Begin Localization [-] End Localization, misc time: 91.95475700ms #### [INFO] GROUNDTRUTH (133.02665542, 25.40116628) LOCALIZATION (133.02666082, 25.40117062) ``` ### 5. Installation * Install and build dependencies in `2. Recommended requirements: software`, then do the following steps. * a. System software dependencies can be installed with: ```Shell sudo apt-get install cmake libhdf5-dev liblmdb-dev libleveldb-dev libatlas-dev libatlas-base-dev libgflags-dev libgoogle-glog-dev libopencv-dev libmatio-dev libcurl4-openssl-dev ``` * b. Find the `elo` in `modules`: We'll call the directory `elo` into `P_ROOT` * c. Compile and run localization: ```Shell cd $P_ROOT mkdir build cd build cmake .. make ./localization_test config_file input_file image_path ``` ### 6. Demo * Hardware description: image: SEKONIX SF3323, 30 Hz; GNSS: U-Blox M8, 8 Hz; SPAN-CPT: 10 Hz; * Test data path: [testdata.zip](http://data.apollo.auto) unzip testdata in /data folder. * To run the localization demo in testdata1: ```Shell ./localization_test ../config/apollo_release.config ../data/testdata1/test_list.txt ../data/testdata1/image/ ```
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/common/common.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "common", includes = ["include"], hdrs = glob(["include/**/*.h"]), srcs = glob(["lib/**/*.so*"]), include_prefix = "modules/common", strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/common/cyberfile.xml
<package format="2"> <name>common</name> <version>local</version> <description> This module contains code that is not specific to any module but is useful for the functioning of Apollo. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//modules/common</src_path> <depend expose="False">3rd-rules-python-dev</depend> <depend expose="False">3rd-grpc-dev</depend> <depend repo_name="com_github_gflags_gflags" lib_names="gflags">3rd-gflags-dev</depend> <depend expose="False">3rd-bazel-skylib-dev</depend> <depend repo_name="com_google_absl" lib_names="absl">3rd-absl-dev</depend> <depend repo_name="sqlite3" so_names="sqlite3">libsqlite3-dev</depend> <depend expose="False">3rd-rules-proto-dev</depend> <depend repo_name="eigen">3rd-eigen3-dev</depend> <depend expose="False">3rd-gpus-dev</depend> <depend repo_name="osqp">3rd-osqp-dev</depend> <depend repo_name="boost">3rd-boost-dev</depend> <depend repo_name="com_google_googletest" lib_names="gtest,gtest_main">3rd-gtest-dev</depend> <depend type="binary" src_path="//cyber" version_eq="1.0.0.1" repo_name="cyber">cyber-dev</depend> <depend expose="False">3rd-py-dev</depend> <depend repo_name="com_github_nlohmann_json" lib_names="single_json,json">3rd-nlohmann-json-dev</depend> <depend repo_name="common-msgs" lib_names="common-msgs">common-msgs-dev</depend> </package>
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/common/README.md
# Common - Module This module contains code that is not specific to any module but is useful for the functioning of Apollo. ## adapters Topics are used by different modules to communicate with one another. A large number of topic names are defined in `adapter_gflags`. ## configs/data The vehicle configuration is specified in `configs/data` ## filters **filters** implements some filter classes including DigitalFilter and MeanFilter. ## kv_db **KVDB** is a lightweight key-value database to store system-wide parameters. ## latency_recorder **LatencyRecorder** can record the latency between two time points. ## math **math** implements a number of useful mathematical libraries. ## monitor_log **Monitor** defines a logging system. ## proto **Proto** defines a number of project-wide protocol buffers. ## status **Status** is used for determining whether certain functions were performed successfully or not. If not, status provides helpful error messages. ## util **Util** contains an implementation of a factory design pattern with registration, a few string parsing functions, and some utilities for parsing protocol buffers from files. ## vehicle_state The **vehicle_state** class specifies the current state of the vehicle (e.g. position, velocity, heading, etc.).
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/common/README_cn.md
# 通用模块 ``` 本模块中的代码不是针对某一模块的。 ``` ## adapters ``` 不同的模块间能通过topic彼此通信。在`adapter_flags`中定义了大量的topic名称。 ``` ## configs/data ``` 可以在这里对车辆进行配置。 ``` ## filters ``` 实现了一些滤波器类,包括低通数字滤波器、均值滤波器等。 ``` ## kv_db ``` 用于存储系统范围参数的轻量级“键-值”数据库。 ``` ## latency_recorder ``` 可以记录时延。 ``` ## math ``` 包含许多有用的数学库。 ``` ## monitor_log ``` 定义日志记录系统。 ``` ## proto ``` 定义多个项目范围的序列化数据。 ``` ## status ``` 用于确定某些函数是否成功执行, 否则提供有用的错误消息。 ``` ## util ``` 包含带有注册的工厂设计模式的实现, 一些字符串解析函数,以及一些解析工具用来解析序列化数据。 ``` ## vehicle_state ``` 该类指定车辆的当前状态(例如位置、速度、航向等)。 ```
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/common/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", library_dest = "common/lib", data_dest = "common", data = [ ":cyberfile.xml", "common.BUILD" ], deps = [ ":pb_common", ":pb_hdrs", "//modules/common/data:install", "//modules/common/vehicle_model:install", "//modules/common/adapters:install", "//modules/common/configs:install", "//modules/common/filters:install", "//modules/common/kv_db:install", "//modules/common/latency_recorder:install", "//modules/common/math:install", "//modules/common/status:install", "//modules/common/monitor_log:install", "//modules/common/util:install", "//modules/common/vehicle_state:install", "//modules/common/vehicle_state/proto:py_pb_common_vehicle_state", "//modules/common/vehicle_model/proto:py_pb_common_vehicle_model", "//modules/common/util/testdata:py_pb_common_util", "//modules/common/latency_recorder/proto:py_pb_common_latency_record", "//modules/common/adapters/proto:py_pb_common_adapter" ], ) # todo:// keep *.pb.h only install( name = "pb_hdrs", data_dest = "common/include", data = [ "//modules/common/adapters/proto:adapter_config_cc_proto", "//modules/common/latency_recorder/proto:latency_record_cc_proto", "//modules/common_msgs/monitor_msgs:monitor_log_cc_proto", "//modules/common/vehicle_model/proto:vehicle_model_config_cc_proto", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", ], ) install_files( name = "pb_common", dest = "common", files = [ "//modules/common_msgs/basic_msgs:direction_py_pb2", "//modules/common_msgs/basic_msgs:drive_state_py_pb2", "//modules/common_msgs/basic_msgs:error_code_py_pb2", "//modules/common_msgs/basic_msgs:geometry_py_pb2", "//modules/common_msgs/basic_msgs:header_py_pb2", "//modules/common_msgs/basic_msgs:pnc_point_py_pb2", "//modules/common_msgs/basic_msgs:vehicle_signal_py_pb2", "//modules/common_msgs/basic_msgs:drive_event_py_pb2", ], ) install_src_files( name = "install_src", deps = [ ":install_common_src", ":install_common_hdrs" ], ) install_src_files( name = "install_common_src", src_dir = ["."], dest = "common/src", filter = "*", ) install_src_files( name = "install_common_hdrs", src_dir = ["."], dest = "common/include", filter = "*.h", )
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter_coefficients_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/common/filters/digital_filter_coefficients.h" #include "gtest/gtest.h" namespace apollo { namespace common { class DigitalFilterCoefficientsTest : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(DigitalFilterCoefficientsTest, LpfCoefficients) { double ts = 0.01; double cutoff_freq = 20; std::vector<double> den; std::vector<double> num; LpfCoefficients(ts, cutoff_freq, &den, &num); EXPECT_EQ(den.size(), 3); EXPECT_EQ(num.size(), 3); EXPECT_NEAR(num[0], 0.1729, 0.01); EXPECT_NEAR(num[1], 0.3458, 0.01); EXPECT_NEAR(num[2], 0.1729, 0.01); EXPECT_NEAR(den[0], 1.0, 0.01); EXPECT_NEAR(den[2], 0.2217, 0.01); } TEST_F(DigitalFilterCoefficientsTest, LpFirstOrderCoefficients) { double ts = 0.01; double settling_time = 0.005; double dead_time = 0.04; std::vector<double> den; std::vector<double> num; LpFirstOrderCoefficients(ts, settling_time, dead_time, &den, &num); EXPECT_EQ(den.size(), 2); EXPECT_EQ(num.size(), 5); EXPECT_NEAR(den[1], -0.13533, 0.01); EXPECT_DOUBLE_EQ(num[0], 0.0); EXPECT_DOUBLE_EQ(num[1], 0.0); EXPECT_NEAR(num[4], 1 - 0.13533, 0.01); dead_time = 0.0; LpFirstOrderCoefficients(ts, settling_time, dead_time, &den, &num); EXPECT_EQ(den.size(), 2); EXPECT_EQ(num.size(), 1); EXPECT_NEAR(den[1], -0.13533, 0.01); EXPECT_NEAR(num[0], 1 - 0.13533, 0.01); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/mean_filter_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/common/filters/mean_filter.h" #include "gtest/gtest.h" namespace apollo { namespace common { class MeanFilterTest : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(MeanFilterTest, WindowSizeOne) { MeanFilter mean_filter(1); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 4.0); } TEST_F(MeanFilterTest, WindowSizeTwo) { MeanFilter mean_filter(2); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 4.0); EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 2.5); } TEST_F(MeanFilterTest, OnePositiveNonZero) { MeanFilter mean_filter(5); EXPECT_DOUBLE_EQ(mean_filter.Update(2.0), 2.0); } TEST_F(MeanFilterTest, OneNegativeNonZero) { MeanFilter mean_filter(5); EXPECT_DOUBLE_EQ(mean_filter.Update(-2.0), -2.0); } TEST_F(MeanFilterTest, TwoPositiveNonZeros) { MeanFilter mean_filter(5); mean_filter.Update(3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 3.5); } TEST_F(MeanFilterTest, TwoNegativeNonZeros) { MeanFilter mean_filter(5); mean_filter.Update(-3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(-4.0), -3.5); } TEST_F(MeanFilterTest, OnePositiveOneNegative) { MeanFilter mean_filter(5); mean_filter.Update(-3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 0.5); } TEST_F(MeanFilterTest, NormalThree) { MeanFilter mean_filter(5); mean_filter.Update(-3.0); mean_filter.Update(4.0); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 3.0); } TEST_F(MeanFilterTest, NormalFullFiveExact) { MeanFilter mean_filter(5); mean_filter.Update(-1.0); mean_filter.Update(0.0); mean_filter.Update(1.0); mean_filter.Update(2.0); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 1.0); } TEST_F(MeanFilterTest, NormalFullFiveOver) { MeanFilter mean_filter(5); mean_filter.Update(-1.0); mean_filter.Update(0.0); mean_filter.Update(1.0); mean_filter.Update(2.0); mean_filter.Update(3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 2.0); } TEST_F(MeanFilterTest, SameNumber) { MeanFilter mean_filter(5); for (int i = 0; i < 10; ++i) { EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 1.0); } } TEST_F(MeanFilterTest, LargeNumber) { MeanFilter mean_filter(10); double ret = 0.0; for (int i = 0; i < 100; ++i) { double input = static_cast<double>(i); ret = mean_filter.Update(input); } EXPECT_DOUBLE_EQ(ret, 94.5); } TEST_F(MeanFilterTest, AlmostScale) { MeanFilter mean_filter(3); EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 1.0); EXPECT_DOUBLE_EQ(mean_filter.Update(2.0), 1.5); EXPECT_DOUBLE_EQ(mean_filter.Update(9.0), 2.0); EXPECT_DOUBLE_EQ(mean_filter.Update(8.0), 8.0); EXPECT_DOUBLE_EQ(mean_filter.Update(7.0), 8.0); EXPECT_DOUBLE_EQ(mean_filter.Update(6.0), 7.0); EXPECT_DOUBLE_EQ(mean_filter.Update(5.0), 6.0); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 5.0); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 4.0); EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(2.0), 2.0); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 2.0); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 3.0); EXPECT_DOUBLE_EQ(mean_filter.Update(5.0), 4.0); } TEST_F(MeanFilterTest, ToyExample) { MeanFilter mean_filter(4); EXPECT_DOUBLE_EQ(mean_filter.Update(5.0), 5.0); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 4.0); EXPECT_DOUBLE_EQ(mean_filter.Update(8.0), 5.0); EXPECT_DOUBLE_EQ(mean_filter.Update(9.0), 6.5); EXPECT_DOUBLE_EQ(mean_filter.Update(7.0), 7.5); EXPECT_DOUBLE_EQ(mean_filter.Update(2.0), 7.5); EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 4.5); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 3.0); } TEST_F(MeanFilterTest, GoodMinRemoval) { MeanFilter mean_filter(2); EXPECT_DOUBLE_EQ(mean_filter.Update(1.0), 1.0); EXPECT_DOUBLE_EQ(mean_filter.Update(9.0), 5.0); EXPECT_DOUBLE_EQ(mean_filter.Update(8.0), 8.5); EXPECT_DOUBLE_EQ(mean_filter.Update(7.0), 7.5); EXPECT_DOUBLE_EQ(mean_filter.Update(6.0), 6.5); EXPECT_DOUBLE_EQ(mean_filter.Update(5.0), 5.5); EXPECT_DOUBLE_EQ(mean_filter.Update(4.0), 4.5); EXPECT_DOUBLE_EQ(mean_filter.Update(3.0), 3.5); EXPECT_DOUBLE_EQ(mean_filter.Update(2.0), 2.5); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter_coefficients.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 digital_filter_coefficients.h * @brief Functions to generate coefficients for digital filter. */ #pragma once #include <vector> /** * @namespace apollo::common * @brief apollo::common */ namespace apollo { namespace common { /** * @brief Get low-pass coefficients for digital filter. * @param ts Time interval between signals. * @param cutoff_freq Cutoff of frequency to filter high-frequency signals out. * @param denominators Denominator coefficients for digital filter. * @param numerators Numerator coefficients for digital filter. */ void LpfCoefficients(const double ts, const double cutoff_freq, std::vector<double> *denominators, std::vector<double> *numerators); /** * @brief Get first order low-pass coefficients for ZOH digital filter. * @param ts sampling time. * @param settling time: time required for an output to reach and remain within * a given error band * @param dead time: time delay * @param denominators Denominator coefficients for digital filter. * @param numerators Numerator coefficients for digital filter. */ void LpFirstOrderCoefficients(const double ts, const double settling_time, const double dead_time, std::vector<double> *denominators, std::vector<double> *numerators); } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter.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/common/filters/digital_filter.h" #include <cmath> #include "cyber/common/log.h" namespace { const double kDoubleEpsilon = 1.0e-6; } // namespace namespace apollo { namespace common { DigitalFilter::DigitalFilter(const std::vector<double> &denominators, const std::vector<double> &numerators) { set_coefficients(denominators, numerators); } void DigitalFilter::set_denominators(const std::vector<double> &denominators) { denominators_ = denominators; y_values_.resize(denominators_.size(), 0.0); } void DigitalFilter::set_numerators(const std::vector<double> &numerators) { numerators_ = numerators; x_values_.resize(numerators_.size(), 0.0); } void DigitalFilter::set_coefficients(const std::vector<double> &denominators, const std::vector<double> &numerators) { set_denominators(denominators); set_numerators(numerators); } void DigitalFilter::set_dead_zone(const double deadzone) { dead_zone_ = std::fabs(deadzone); AINFO << "Setting digital filter dead zone = " << dead_zone_; } double DigitalFilter::Filter(const double x_insert) { if (denominators_.empty() || numerators_.empty()) { AERROR << "Empty denominators or numerators"; return 0.0; } x_values_.pop_back(); x_values_.push_front(x_insert); const double xside = Compute(x_values_, numerators_, 0, numerators_.size() - 1); y_values_.pop_back(); const double yside = Compute(y_values_, denominators_, 1, denominators_.size() - 1); double y_insert = 0.0; if (std::fabs(denominators_.front()) > kDoubleEpsilon) { y_insert = (xside - yside) / denominators_.front(); } y_values_.push_front(y_insert); return UpdateLast(y_insert); } void DigitalFilter::reset_values() { std::fill(x_values_.begin(), x_values_.end(), 0.0); std::fill(y_values_.begin(), y_values_.end(), 0.0); } double DigitalFilter::UpdateLast(const double input) { const double diff = std::fabs(input - last_); if (diff < dead_zone_) { return last_; } last_ = input; return input; } double DigitalFilter::Compute(const std::deque<double> &values, const std::vector<double> &coefficients, const std::size_t coeff_start, const std::size_t coeff_end) { ACHECK(coeff_start <= coeff_end && coeff_end < coefficients.size()); ACHECK((coeff_end - coeff_start + 1) == values.size()); double sum = 0.0; auto i = coeff_start; for (const auto value : values) { sum += value * coefficients[i]; ++i; } return sum; } const std::vector<double> &DigitalFilter::denominators() const { return denominators_; } const std::vector<double> &DigitalFilter::numerators() const { return numerators_; } double DigitalFilter::dead_zone() const { return dead_zone_; } const std::deque<double> &DigitalFilter::inputs_queue() const { return x_values_; } const std::deque<double> &DigitalFilter::outputs_queue() const { return y_values_; } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter_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/common/filters/digital_filter.h" #include <vector> #include "gtest/gtest.h" namespace apollo { namespace common { class DigitalFilterTest : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(DigitalFilterTest, SetGet) { DigitalFilter digital_filter; std::vector<double> numerators = {1.0, 2.0, 3.0}; std::vector<double> denominators = {4.0, 5.0, 6.0}; digital_filter.set_denominators(denominators); digital_filter.set_numerators(numerators); std::vector<double> denominators_got = digital_filter.denominators(); std::vector<double> numerators_got = digital_filter.numerators(); EXPECT_EQ(numerators_got.size(), numerators.size()); EXPECT_EQ(denominators_got.size(), denominators.size()); for (size_t i = 0; i < numerators.size(); ++i) { EXPECT_DOUBLE_EQ(numerators_got[i], numerators[i]); } for (size_t i = 0; i < denominators.size(); ++i) { EXPECT_DOUBLE_EQ(denominators_got[i], denominators[i]); } digital_filter.set_coefficients(denominators, numerators); denominators_got.clear(); denominators_got = digital_filter.denominators(); numerators_got.clear(); numerators_got = digital_filter.numerators(); EXPECT_EQ(numerators_got.size(), numerators.size()); EXPECT_EQ(denominators_got.size(), denominators.size()); for (size_t i = 0; i < numerators.size(); ++i) { EXPECT_DOUBLE_EQ(numerators_got[i], numerators[i]); } for (size_t i = 0; i < denominators.size(); ++i) { EXPECT_DOUBLE_EQ(denominators_got[i], denominators[i]); } double dead_zone = 1.0; digital_filter.set_dead_zone(dead_zone); EXPECT_DOUBLE_EQ(digital_filter.dead_zone(), dead_zone); } TEST_F(DigitalFilterTest, FilterOff) { std::vector<double> numerators = {0.0, 0.0, 0.0}; std::vector<double> denominators = {1.0, 0.0, 0.0}; DigitalFilter digital_filter(denominators, numerators); const std::vector<double> step_input(100, 1.0); std::vector<double> rand_input(100, 1.0); unsigned int seed; for (size_t i = 0; i < rand_input.size(); ++i) { rand_input[i] = rand_r(&seed); } // Check setp input for (size_t i = 0; i < step_input.size(); ++i) { EXPECT_DOUBLE_EQ(digital_filter.Filter(step_input[i]), 0.0); } // Check random input for (size_t i = 0; i < rand_input.size(); ++i) { EXPECT_DOUBLE_EQ(digital_filter.Filter(rand_input[i]), 0.0); } } TEST_F(DigitalFilterTest, MovingAverage) { std::vector<double> numerators = {0.25, 0.25, 0.25, 0.25}; std::vector<double> denominators = {1.0, 0.0, 0.0}; DigitalFilter digital_filter; digital_filter.set_numerators(numerators); digital_filter.set_denominators(denominators); const std::vector<double> step_input(100, 1.0); // Check step input, transients. for (size_t i = 0; i < numerators.size(); ++i) { double expected_filter_out = static_cast<double>(i + 1) * 0.25; EXPECT_DOUBLE_EQ(digital_filter.Filter(step_input[i]), expected_filter_out); EXPECT_EQ(digital_filter.inputs_queue().size(), numerators.size()); EXPECT_EQ(digital_filter.outputs_queue().size(), denominators.size()); for (size_t j = 0; j < numerators.size(); ++j) { double input_state = (i >= j) ? step_input[i - j] : 0.0; EXPECT_DOUBLE_EQ(digital_filter.inputs_queue()[j], input_state); } for (size_t j = 0; j < denominators.size(); ++j) { double output_state = (i >= j) ? static_cast<double>(i - j + 1) * 0.25 : 0.0; EXPECT_DOUBLE_EQ(digital_filter.outputs_queue()[j], output_state); } } // Check step input, steady state for (size_t i = 4; i < step_input.size(); ++i) { EXPECT_DOUBLE_EQ(digital_filter.Filter(step_input[i]), 1.0); } } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter_coefficients.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/common/filters/digital_filter_coefficients.h" #include <cmath> #include <vector> #include "cyber/common/log.h" namespace apollo { namespace common { void LpfCoefficients(const double ts, const double cutoff_freq, std::vector<double> *denominators, std::vector<double> *numerators) { denominators->clear(); numerators->clear(); denominators->reserve(3); numerators->reserve(3); double wa = 2.0 * M_PI * cutoff_freq; // Analog frequency in rad/s double alpha = wa * ts / 2.0; // tan(Wd/2), Wd is discrete frequency double alpha_sqr = alpha * alpha; double tmp_term = std::sqrt(2.0) * alpha + alpha_sqr; double gain = alpha_sqr / (1.0 + tmp_term); denominators->push_back(1.0); denominators->push_back(2.0 * (alpha_sqr - 1.0) / (1.0 + tmp_term)); denominators->push_back((1.0 - std::sqrt(2.0) * alpha + alpha_sqr) / (1.0 + tmp_term)); numerators->push_back(gain); numerators->push_back(2.0 * gain); numerators->push_back(gain); } void LpFirstOrderCoefficients(const double ts, const double settling_time, const double dead_time, std::vector<double> *denominators, std::vector<double> *numerators) { // sanity check if (ts <= 0.0 || settling_time < 0.0 || dead_time < 0.0) { AERROR << "time cannot be negative"; return; } const size_t k_d = static_cast<size_t>(dead_time / ts); double a_term; denominators->clear(); numerators->clear(); denominators->reserve(2); numerators->reserve(k_d + 1); // size depends on dead-time if (settling_time == 0.0) { a_term = 0.0; } else { a_term = exp(-1 * ts / settling_time); } denominators->push_back(1.0); denominators->push_back(-a_term); numerators->insert(numerators->end(), k_d, 0.0); numerators->push_back(1 - a_term); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/mean_filter.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 Defines the MeanFilter class. */ #pragma once #include <cstdint> #include <deque> #include <utility> #include <vector> /** * @namespace apollo::common * @brief The apollo::common namespace contains the code of the common module. */ namespace apollo { namespace common { /** * @class MeanFilter * @brief The MeanFilter class is used to smoothen a series of noisy numbers, * such as sensor data or the output of a function that we wish to be smoother. * * This is achieved by keeping track of the last k measurements * (where k is the window size), and returning the average of all but the * minimum and maximum measurements, which are likely to be outliers. */ class MeanFilter { public: /** * @brief Initializes a MeanFilter with a given window size. * @param window_size The window size of the MeanFilter. * Older measurements are discarded. */ explicit MeanFilter(const std::uint_fast8_t window_size); /** * @brief Default constructor; defers initialization. */ MeanFilter() = default; /** * @brief Default destructor. */ ~MeanFilter() = default; /** * @brief Processes a new measurement in amortized constant time. * @param measurement The measurement to be processed by the filter. */ double Update(const double measurement); private: void RemoveEarliest(); void Insert(const double value); double GetMin() const; double GetMax() const; bool ShouldPopOldestCandidate(const std::uint_fast8_t old_time) const; std::uint_fast8_t window_size_ = 0; double sum_ = 0.0; std::uint_fast8_t time_ = 0; // front = earliest std::deque<double> values_; // front = min std::deque<std::pair<std::uint_fast8_t, double>> min_candidates_; // front = max std::deque<std::pair<std::uint_fast8_t, double>> max_candidates_; bool initialized_ = false; }; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") install( name = "install", library_dest = "common/lib", data_dest = "common", targets = [ ":libfilters.so", ], visibility = ["//visibility:public"], ) cc_binary( name = "libfilters.so", linkshared = True, linkstatic = True, deps = [ ":digital_filter_coefficients", ":digital_filter", ":mean_filter", ], ) cc_library( name = "filters", srcs = ["libfilters.so"], hdrs = [ "digital_filter_coefficients.h", "digital_filter.h", "mean_filter.h", ], visibility = ["//visibility:public"], ) cc_library( name = "digital_filter", srcs = ["digital_filter.cc"], hdrs = ["digital_filter.h"], alwayslink = True, deps = [ "//cyber:cyber", ], ) cc_library( name = "mean_filter", srcs = ["mean_filter.cc"], hdrs = ["mean_filter.h"], alwayslink = True, deps = [ "//cyber:cyber", ], ) cc_library( name = "digital_filter_coefficients", srcs = ["digital_filter_coefficients.cc"], hdrs = ["digital_filter_coefficients.h"], alwayslink = True, deps = [ "//cyber:cyber", ], ) cc_test( name = "digital_filter_test", size = "small", srcs = ["digital_filter_test.cc"], deps = [ ":digital_filter", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "mean_filter_test", size = "small", srcs = ["mean_filter_test.cc"], deps = [ ":mean_filter", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "digital_filter_coefficients_test", size = "small", srcs = ["digital_filter_coefficients_test.cc"], deps = [ ":digital_filter_coefficients", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/digital_filter.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 Defines the DigitalFilter class. */ #pragma once #include <deque> #include <vector> /** * @namespace apollo::common * @brief apollo::common */ namespace apollo { namespace common { /** * @class DigitalFilter * @brief The DigitalFilter class is used to pass signals with a frequency * lower than a certain cutoff frequency and attenuates signals with * frequencies higher than the cutoff frequency. */ class DigitalFilter { public: DigitalFilter() = default; /** * @brief Initializes a DigitalFilter with given denominators and numerators. * @param denominators The denominators of the DigitalFilter. * @param numerators The numerators of the DigitalFilter. */ DigitalFilter(const std::vector<double> &denominators, const std::vector<double> &numerators); /** * @brief Default destructor. */ ~DigitalFilter() = default; /** * @brief Processes a new measurement with the filter. * @param x_insert The new input to be processed by the filter. */ double Filter(const double x_insert); /** * @desc: Filter by the input x_insert * Input: new value of x_insert * Remove x[n - 1], insert x_insert into x[0] * Remove y[n - 1], * Solve den[0] * y + den[1] * y[0] + ... + den[n - 1]*y[n - 2] = * num[0] * x[0] + num[1] * x[1] + ... + num[n - 1] * x[n - 1] for y * Insert y into y[0] * Output: y[0] */ /** * @brief set denominators by an input vector * @param denominators The denominators of filter */ void set_denominators(const std::vector<double> &denominators); /** * @brief set numerators by an input vector * @param numerators The numerators of filter */ void set_numerators(const std::vector<double> &numerators); /** * @brief set denominators and numerators * @param denominators The denominators of filter * @param numerators The numerators of filter */ void set_coefficients(const std::vector<double> &denominators, const std::vector<double> &numerators); /** * @brief set filter deadzone * @param deadzone The value of deadzone */ void set_dead_zone(const double deadzone); /** * @brief re-set the x_values_ and y_values_ * @param deadzone The value of deadzone */ void reset_values(); /** * @brief get denominators * @return vector<double> The denominators of filter */ const std::vector<double> &denominators() const; /** * @brief get numerators * @return vector<double> The numerators of filter */ const std::vector<double> &numerators() const; /** * @brief get dead_zone * @return double The dead_zone */ double dead_zone() const; /** * @brief get inputs of the filter * @return deque<double> The queue of inputs of filter */ const std::deque<double> &inputs_queue() const; /** * @brief get outputs of the filter * @return deque<double> The queue of outputs of filter */ const std::deque<double> &outputs_queue() const; private: /** * @desc: Update the last-filtered value, * if the difference is less than dead_zone_ */ double UpdateLast(const double input); /** * @desc: Compute the inner product of values[coeff_start : coeff_end] and * coefficients[coeff_start : coeff_end] */ double Compute(const std::deque<double> &values, const std::vector<double> &coefficients, const std::size_t coeff_start, const std::size_t coeff_end); // Front is latest, back is oldest. std::deque<double> x_values_; // Front is latest, back is oldest. std::deque<double> y_values_; // Coefficients with y values std::vector<double> denominators_; // Coefficients with x values std::vector<double> numerators_; // threshold of updating last-filtered value double dead_zone_ = 0.0; // last-filtered value double last_ = 0.0; }; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/filters/mean_filter.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/common/filters/mean_filter.h" #include <limits> #include "cyber/common/log.h" namespace apollo { namespace common { using MF = MeanFilter; using uint8 = std::uint_fast8_t; using TimedValue = std::pair<uint8, double>; const uint8 kMaxWindowSize = std::numeric_limits<uint8>::max() / 2; MF::MeanFilter(const uint8 window_size) : window_size_(window_size) { CHECK_GT(window_size_, 0); CHECK_LE(window_size_, kMaxWindowSize); initialized_ = true; } double MF::GetMin() const { if (min_candidates_.empty()) { return std::numeric_limits<double>::infinity(); } else { return min_candidates_.front().second; } } double MF::GetMax() const { if (max_candidates_.empty()) { return -std::numeric_limits<double>::infinity(); } else { return max_candidates_.front().second; } } double MF::Update(const double measurement) { ACHECK(initialized_); CHECK_LE(values_.size(), window_size_); CHECK_LE(min_candidates_.size(), window_size_); CHECK_LE(max_candidates_.size(), window_size_); ++time_; time_ %= static_cast<std::uint_fast8_t>(2 * window_size_); if (values_.size() == window_size_) { RemoveEarliest(); } Insert(measurement); if (values_.size() > 2) { return (sum_ - GetMin() - GetMax()) / static_cast<double>(values_.size() - 2); } else { return sum_ / static_cast<double>(values_.size()); } } bool MF::ShouldPopOldestCandidate(const uint8 old_time) const { if (old_time < window_size_) { CHECK_LE(time_, old_time + window_size_); return old_time + window_size_ == time_; } else if (time_ < window_size_) { CHECK_GE(old_time, time_ + window_size_); return old_time == time_ + window_size_; } else { return false; } } void MF::RemoveEarliest() { CHECK_EQ(values_.size(), window_size_); double removed = values_.front(); values_.pop_front(); sum_ -= removed; if (ShouldPopOldestCandidate(min_candidates_.front().first)) { min_candidates_.pop_front(); } if (ShouldPopOldestCandidate(max_candidates_.front().first)) { max_candidates_.pop_front(); } } void MF::Insert(const double value) { values_.push_back(value); sum_ += value; while (min_candidates_.size() > 0 && min_candidates_.back().second > value) { min_candidates_.pop_back(); } min_candidates_.push_back(std::make_pair(time_, value)); while (max_candidates_.size() > 0 && max_candidates_.back().second < value) { max_candidates_.pop_back(); } max_candidates_.push_back(std::make_pair(time_, value)); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/string_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/common/util/string_util.h" #include <vector> #include "gtest/gtest.h" namespace apollo { namespace common { namespace util { TEST(StringUtilTest, EncodeBase64) { EXPECT_EQ("", EncodeBase64("")); EXPECT_EQ("Zg==", EncodeBase64("f")); EXPECT_EQ("Zm8=", EncodeBase64("fo")); EXPECT_EQ("Zm9v", EncodeBase64("foo")); EXPECT_EQ("Zm9vYg==", EncodeBase64("foob")); EXPECT_EQ("Zm9vYmE=", EncodeBase64("fooba")); EXPECT_EQ("Zm9vYmFy", EncodeBase64("foobar")); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/time_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 "cyber/common/macros.h" namespace apollo { namespace common { namespace util { class TimeUtil { public: // @brief: UNIX timestamp to GPS timestamp, in seconds. static double Unix2Gps(double unix_time) { double gps_time = unix_time - UNIX_GPS_DIFF; if (unix_time < LEAP_SECOND_TIMESTAMP) { gps_time -= 1.0; } return gps_time; } // @brief: GPS timestamp to UNIX timestamp, in seconds. static double Gps2Unix(double gps_time) { double unix_time = gps_time + UNIX_GPS_DIFF; if (unix_time + 1 < LEAP_SECOND_TIMESTAMP) { unix_time += 1.0; } return unix_time; } private: // unix timestamp(1970.01.01) is different from gps timestamp(1980.01.06) static const int UNIX_GPS_DIFF = 315964782; // unix timestamp(2016.12.31 23:59:59(60) UTC/GMT) static const int LEAP_SECOND_TIMESTAMP = 1483228799; DISALLOW_COPY_AND_ASSIGN(TimeUtil); }; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/perf_util_test.cc
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/util/perf_util.h" #include <thread> #include "gtest/gtest.h" namespace apollo { namespace common { namespace util { TEST(TimeTest, test_timer) { Timer timer; timer.Start(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); const uint64_t elapsed_time = timer.End("TimerTest"); EXPECT_GE(elapsed_time, 90); EXPECT_LE(elapsed_time, 110); } TEST(TimerWrapperTest, test) { TimerWrapper wrapper("TimerWrapperTest"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } TEST(PerfFunctionTest, test) { PERF_FUNCTION_WITH_NAME("FunctionTest"); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } TEST(PerfBlockTest, test) { PERF_BLOCK_START(); // do somethings. std::this_thread::sleep_for(std::chrono::milliseconds(100)); PERF_BLOCK_END("BLOCK1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); PERF_BLOCK_END("BLOCK2"); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/points_downsampler.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. *****************************************************************************/ /** * @points_downsampler */ #pragma once #include <cmath> #include <vector> #include "cyber/common/log.h" #include "modules/common/math/vec2d.h" /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { /** * @brief Calculate the angle between the directions of two points on the path. * @param points Points on the path. * @param start The index of the first point on the path. * @param end The index of the second point on the path. * @return The angle between the directions of the start point and the end * point. */ template <typename Points> double GetPathAngle(const Points &points, const size_t start, const size_t end) { if (start >= static_cast<size_t>(points.size() - 1) || end >= static_cast<size_t>(points.size() - 1)) { AERROR << "Input indices are out of the range of the points vector: " << "should be less than vector size - 1."; return 0.0; } if (start >= end) { AERROR << "Second index must be greater than the first index."; return 0.0; } double vec_start_x = points[start + 1].x() - points[start].x(); double vec_start_y = points[start + 1].y() - points[start].y(); double vec_start_norm = std::hypot(vec_start_x, vec_start_y); double vec_end_x = points[end + 1].x() - points[end].x(); double vec_end_y = points[end + 1].y() - points[end].y(); double vec_end_norm = std::hypot(vec_end_x, vec_end_y); double dot_product = vec_start_x * vec_end_x + vec_start_y * vec_end_y; double angle = std::acos(dot_product / (vec_start_norm * vec_end_norm)); return std::isnan(angle) ? 0.0 : angle; } /** * @brief Downsample the points on the path according to the angle. * @param points Points on the path. * @param angle_threshold Points are sampled when the accumulated direction * change exceeds the threshold. * @return sampled_indices Indices of all sampled points, or empty when fail. */ template <typename Points> std::vector<size_t> DownsampleByAngle(const Points &points, const double angle_threshold) { std::vector<size_t> sampled_indices; if (points.empty()) { return sampled_indices; } if (angle_threshold < 0.0) { AERROR << "Input angle threshold is negative."; return sampled_indices; } sampled_indices.push_back(0); if (points.size() > 1) { size_t start = 0; size_t end = 1; double accum_degree = 0.0; while (end + 1 < static_cast<size_t>(points.size())) { const double angle = GetPathAngle(points, start, end); accum_degree += std::fabs(angle); if (accum_degree > angle_threshold) { sampled_indices.push_back(end); start = end; accum_degree = 0.0; } ++end; } sampled_indices.push_back(end); } ADEBUG << "Point Vector is downsampled from " << points.size() << " to " << sampled_indices.size(); return sampled_indices; } /** * @brief Downsample the points on the path based on distance. * @param points Points on the path. * @param downsampleDistance downsample rate for a normal path * @param steepTurnDownsampleDistance downsample rate for a steep turn path * @return sampled_indices Indices of all sampled points, or empty when fail. */ template <typename Points> std::vector<size_t> DownsampleByDistance(const Points &points, int downsampleDistance, int steepTurnDownsampleDistance) { std::vector<size_t> sampled_indices; if (points.size() <= 4) { // No need to downsample if there are not too many points. for (size_t i = 0; i < points.size(); ++i) { sampled_indices.push_back(i); } return sampled_indices; } using apollo::common::math::Vec2d; Vec2d v_start = Vec2d(points[1].x() - points[0].x(), points[1].y() - points[0].y()); Vec2d v_end = Vec2d(points[points.size() - 1].x() - points[points.size() - 2].x(), points[points.size() - 1].y() - points[points.size() - 2].y()); v_start.Normalize(); v_end.Normalize(); // If the angle exceeds 80 degree, it's a steep turn bool is_steep_turn = v_start.InnerProd(v_end) <= cos(80.0 * M_PI / 180.0); int downsampleRate = is_steep_turn ? steepTurnDownsampleDistance : downsampleDistance; // Make sure the first point is included sampled_indices.push_back(0); double accum_distance = 0.0; for (size_t pos = 1; pos < points.size() - 1; ++pos) { Vec2d point_start = Vec2d(points[pos - 1].x(), points[pos - 1].y()); Vec2d point_end = Vec2d(points[pos].x(), points[pos].y()); accum_distance += point_start.DistanceTo(point_end); if (accum_distance > downsampleRate) { sampled_indices.push_back(pos); accum_distance = 0.0; } } // Make sure the last point is included sampled_indices.push_back(points.size() - 1); return sampled_indices; } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/factory_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 <string> #include "gtest/gtest.h" #include "modules/common/util/factory.h" namespace apollo { namespace common { namespace util { class Base { public: virtual std::string Name() const { return "base"; } }; class Derived : public Base { public: virtual std::string Name() const { return "derived"; } }; TEST(FactoryTest, Register) { Factory<std::string, Base> factory; EXPECT_TRUE(factory.Register("derived_class", []() -> Base* { return new Derived(); })); auto derived_ptr = factory.CreateObject("derived_class"); EXPECT_NE(nullptr, derived_ptr); EXPECT_EQ("derived", derived_ptr->Name()); auto non_exist_ptr = factory.CreateObject("non_exist_class"); EXPECT_EQ(nullptr, non_exist_ptr); } TEST(FactoryTest, Unregister) { Factory<std::string, Base> factory; EXPECT_TRUE(factory.Register("derived_class", []() -> Base* { return new Derived(); })); EXPECT_FALSE(factory.Unregister("fake_class")); auto derived_ptr = factory.CreateObject("derived_class"); EXPECT_NE(nullptr, derived_ptr); EXPECT_TRUE(factory.Unregister("derived_class")); auto non_exist_ptr = factory.CreateObject("derived_class"); EXPECT_EQ(nullptr, non_exist_ptr); } class ArgConstructor { public: explicit ArgConstructor(const std::string& name) : name_(name) {} ArgConstructor(const std::string& name, int value) : name_(name), value_(value) {} std::string Name() const { return name_; } int Value() const { return value_; } private: std::string name_; int value_ = 0; }; TEST(FactoryTest, OneArgConstructor) { Factory<std::string, ArgConstructor, ArgConstructor* (*)(const std::string&)> factory; EXPECT_TRUE(factory.Register( "arg_1", [](const std::string& arg) { return new ArgConstructor(arg); })); auto ptr = factory.CreateObject("arg_1", "name_1"); EXPECT_NE(nullptr, ptr); EXPECT_EQ("name_1", ptr->Name()); EXPECT_EQ(0, ptr->Value()); } TEST(FactoryTest, TwoArgConstructor) { Factory<std::string, ArgConstructor, ArgConstructor* (*)(const std::string&, int)> factory; EXPECT_TRUE(factory.Register("arg_2", [](const std::string& arg, int value) { return new ArgConstructor(arg, value); })); auto ptr = factory.CreateObject("arg_2", "name_2", 10); EXPECT_NE(nullptr, ptr); EXPECT_EQ("name_2", ptr->Name()); EXPECT_EQ(10, ptr->Value()); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/point_factory.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/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/geometry.pb.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" namespace apollo { namespace common { namespace util { class PointFactory { public: template <typename XY> static inline math::Vec2d ToVec2d(const XY& xy) { return math::Vec2d(xy.x(), xy.y()); } static inline SLPoint ToSLPoint(const double s, const double l) { SLPoint sl; sl.set_s(s); sl.set_l(l); return sl; } static inline PointENU ToPointENU(const double x, const double y, const double z = 0) { PointENU point_enu; point_enu.set_x(x); point_enu.set_y(y); point_enu.set_z(z); return point_enu; } template <typename XYZ> static inline PointENU ToPointENU(const XYZ& xyz) { return ToPointENU(xyz.x(), xyz.y(), xyz.z()); } static inline SpeedPoint ToSpeedPoint(const double s, const double t, const double v = 0, const double a = 0, const double da = 0) { SpeedPoint speed_point; speed_point.set_s(s); speed_point.set_t(t); speed_point.set_v(v); speed_point.set_a(a); speed_point.set_da(da); return speed_point; } static inline PathPoint ToPathPoint(const double x, const double y, const double z = 0, const double s = 0, const double theta = 0, const double kappa = 0, const double dkappa = 0, const double ddkappa = 0) { PathPoint path_point; path_point.set_x(x); path_point.set_y(y); path_point.set_z(z); path_point.set_s(s); path_point.set_theta(theta); path_point.set_kappa(kappa); path_point.set_dkappa(dkappa); path_point.set_ddkappa(ddkappa); return path_point; } }; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/future.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #if __cplusplus == 201103L || __cplusplus == 201402L # include "absl/types/optional.h" # include "absl/strings/string_view.h" #endif #if __cplusplus == 201103L # include "absl/memory/memory.h" # include "absl/utility/utility.h" #endif namespace std { // Drop-in replacement for code compliant with future C++ versions. #if __cplusplus == 201103L || __cplusplus == 201402L // Borrow from C++ 17 (201703L) using absl::optional; using absl::string_view; #endif #if __cplusplus == 201103L // Borrow from C++ 14. using absl::make_integer_sequence; using absl::make_unique; #endif } // namespace std
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/message_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. *****************************************************************************/ /** * @file * @brief Some string util functions. */ #pragma once #include <memory> #include <string> #include "absl/strings/str_cat.h" #include "google/protobuf/message.h" #include "cyber/common/file.h" #include "cyber/time/clock.h" /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { template <typename T, typename std::enable_if< std::is_base_of<google::protobuf::Message, T>::value, int>::type = 0> static void FillHeader(const std::string& module_name, T* msg) { static std::atomic<uint64_t> sequence_num = {0}; auto* header = msg->mutable_header(); double timestamp = ::apollo::cyber::Clock::NowInSeconds(); header->set_module_name(module_name); header->set_timestamp_sec(timestamp); header->set_sequence_num( static_cast<unsigned int>(sequence_num.fetch_add(1))); } template <typename T, typename std::enable_if< std::is_base_of<google::protobuf::Message, T>::value, int>::type = 0> bool DumpMessage(const std::shared_ptr<T>& msg, const std::string& dump_dir = "/tmp") { if (!msg) { AWARN << "Message to be dumped is nullptr!"; } auto type_name = T::descriptor()->full_name(); std::string dump_path = dump_dir + "/" + type_name; if (!cyber::common::DirectoryExists(dump_path)) { if (!cyber::common::EnsureDirectory(dump_path)) { AERROR << "Cannot enable dumping for '" << type_name << "' because the path " << dump_path << " cannot be created or is not a directory."; return false; } } auto sequence_num = msg->header().sequence_num(); return cyber::common::SetProtoToASCIIFile( *msg, absl::StrCat(dump_path, "/", sequence_num, ".pb.txt")); } inline size_t MessageFingerprint(const google::protobuf::Message& message) { static std::hash<std::string> hash_fn; std::string proto_bytes; message.SerializeToString(&proto_bytes); return hash_fn(proto_bytes); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/data_extraction.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/common/util/data_extraction.h" #include "cyber/common/log.h" namespace apollo { namespace prediction { void GetRecordFileNames(const boost::filesystem::path& p, std::vector<std::string>* record_files) { ACHECK(record_files); if (!boost::filesystem::exists(p)) { return; } if (boost::filesystem::is_regular_file(p)) { AINFO << "Found record file: " << p.c_str(); record_files->push_back(p.c_str()); return; } if (boost::filesystem::is_directory(p)) { for (auto& entry : boost::make_iterator_range( boost::filesystem::directory_iterator(p), {})) { GetRecordFileNames(entry.path(), record_files); } } } } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/perf_util.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 "absl/strings/str_cat.h" #include "cyber/common/macros.h" #include "cyber/time/time.h" #if defined(__GNUC__) || defined(__GNUG__) #define AFUNC __PRETTY_FUNCTION__ #elif defined(__clang__) #define AFUNC __PRETTY_FUNCTION__ #else #define AFUNC __func__ #endif // How to Use: // 1) Use PERF_FUNCTION to compute time cost of function execution as follows: // void MyFunc() { // PERF_FUNCION(); // // do somethings. // } // Console log: // >>>>>>>>>>>>>>>>>> // I0615 15:49:30.756429 12748 timer.cpp:31] TIMER MyFunc elapsed time: 100 ms // >>>>>>>>>>>>>>>>>> // // 2) Use PERF_BLOCK_START/END to compute time cost of block execution. // void MyFunc() { // // xxx1 // PERF_BLOCK_START(); // // // do xx2 // // PERF_BLOCK_END("xx2"); // // // do xx3 // // PERF_BLOCK_END("xx3"); // } // // Console log: // >>>>>>>>>>>>>>> // I0615 15:49:30.756429 12748 timer.cpp:31] TIMER xx2 elapsed time: 100 ms // I0615 15:49:30.756429 12748 timer.cpp:31] TIMER xx3 elapsed time: 200 ms // >>>>>>>>>>>>>>> namespace apollo { namespace common { namespace util { std::string function_signature(const std::string& func_name, const std::string& indicator = ""); class Timer { public: Timer() = default; // no-thread safe. void Start(); // return the elapsed time, // also output msg and time in glog. // automatically start a new timer. // no-thread safe. int64_t End(const std::string& msg); private: apollo::cyber::Time start_time_; apollo::cyber::Time end_time_; DISALLOW_COPY_AND_ASSIGN(Timer); }; class TimerWrapper { public: explicit TimerWrapper(const std::string& msg) : msg_(msg) { timer_.Start(); } ~TimerWrapper() { timer_.End(msg_); } private: Timer timer_; std::string msg_; DISALLOW_COPY_AND_ASSIGN(TimerWrapper); }; } // namespace util } // namespace common } // namespace apollo #if defined(ENABLE_PERF) #define PERF_FUNCTION() \ apollo::common::util::TimerWrapper _timer_wrapper_( \ apollo::common::util::function_signature(AFUNC)) #define PERF_FUNCTION_WITH_NAME(func_name) \ apollo::common::util::TimerWrapper _timer_wrapper_(func_name) #define PERF_FUNCTION_WITH_INDICATOR(indicator) \ apollo::common::util::TimerWrapper _timer_wrapper_( \ apollo::common::util::function_signature(AFUNC, indicator)) #define PERF_BLOCK_START() \ apollo::common::util::Timer _timer_; \ _timer_.Start() #define PERF_BLOCK_END(msg) _timer_.End(msg) #define PERF_BLOCK_END_WITH_INDICATOR(indicator, msg) \ _timer_.End(absl::StrCat(indicator, "_", msg)) #else #define PERF_FUNCTION() #define PERF_FUNCTION_WITH_NAME(func_name) UNUSED(func_name); #define PERF_FUNCTION_WITH_INDICATOR(indicator) UNUSED(indicator); #define PERF_BLOCK_START() #define PERF_BLOCK_END(msg) UNUSED(msg); #define PERF_BLOCK_END_WITH_INDICATOR(indicator, msg) \ { \ UNUSED(indicator); \ UNUSED(msg); \ } #endif // ENABLE_PERF
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/string_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. *****************************************************************************/ /** * @file * @brief Some string util functions. */ #pragma once #include <string> #include "absl/strings/str_format.h" #include "modules/common/util/future.h" #define FORMAT_TIMESTAMP(timestamp) \ std::fixed << std::setprecision(9) << timestamp /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { using absl::StrFormat; struct DebugStringFormatter { template <class T> void operator()(std::string* out, const T& t) const { out->append(t.DebugString()); } }; std::string EncodeBase64(std::string_view in); } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/lru_cache.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 <iostream> #include <map> #include <mutex> #include <utility> #include <vector> namespace apollo { namespace common { namespace util { template <class K, class V> struct Node { K key; V val; Node* prev; Node* next; Node() : prev(nullptr), next(nullptr) {} template <typename VV> Node(const K& key, VV&& val) : key(key), val(std::forward<VV>(val)), prev(nullptr), next(nullptr) {} }; template <class K, class V> class LRUCache { public: explicit LRUCache(const size_t capacity = kDefaultCapacity) : capacity_(capacity), head_(), tail_() { Init(); } ~LRUCache() { Clear(); } void GetCache(std::map<K, V>* cache) { for (auto it = map_.begin(); it != map_.end(); ++it) { cache->emplace(it->first, it->second.val); } } V& operator[](const K& key) { if (!Contains(key)) { K obsolete; GetObsolete(&obsolete); } return map_[key].val; } /* * Silently get all as vector */ void GetAllSilently(std::vector<V*>* ret) { for (auto it = map_.begin(); it != map_.end(); ++it) { ret->push_back(&it->second.val); } } /* * for both add & update purposes */ template <typename VV> bool Put(const K& key, VV&& val) { K tmp; return Update(key, std::forward<VV>(val), &tmp, false, false); } /* * update existing elements only */ template <typename VV> bool Update(const K& key, VV&& val) { if (!Contains(key)) { return false; } K tmp; return Update(key, std::forward<VV>(val), &tmp, true, false); } /* * silently update existing elements only */ template <typename VV> bool UpdateSilently(const K& key, VV* val) { if (!Contains(key)) { return false; } K tmp; return Update(key, std::forward<VV>(*val), &tmp, true, true); } /* * add new elements only */ template <typename VV> bool Add(const K& key, VV* val) { K tmp; return Update(key, std::forward<VV>(*val), &tmp, true, false); } template <typename VV> bool PutAndGetObsolete(const K& key, VV* val, K* obs) { return Update(key, std::forward<VV>(*val), obs, false, false); } template <typename VV> bool AddAndGetObsolete(const K& key, VV* val, K* obs) { return Update(key, std::forward<VV>(*val), obs, true, false); } V* GetSilently(const K& key) { return Get(key, true); } V* Get(const K& key) { return Get(key, false); } bool GetCopySilently(const K& key, V* const val) { return GetCopy(key, val, true); } bool GetCopy(const K& key, V* const val) { return GetCopy(key, val, false); } size_t size() { return size_; } bool Full() { return size() > 0 && size() >= capacity_; } bool Empty() { return size() == 0; } size_t capacity() { return capacity_; } Node<K, V>* First() { if (size()) { return head_.next; } return nullptr; } Node<K, V>* Last() { if (size()) { return tail_.prev; } return nullptr; } bool Contains(const K& key) { return map_.find(key) != map_.end(); } bool Prioritize(const K& key) { if (Contains(key)) { auto* node = &map_[key]; Detach(node); Attach(node); return true; } return false; } void Clear() { map_.clear(); Init(); } bool Remove(const K& key) { if (!Contains(key)) { return false; } auto* node = &map_[key]; Detach(node); return true; } bool ChangeCapacity(const size_t capacity) { if (size() > capacity) { return false; } capacity_ = capacity; return true; } private: static constexpr size_t kDefaultCapacity = 10; const size_t capacity_; size_t size_; std::map<K, Node<K, V>> map_; Node<K, V> head_; Node<K, V> tail_; void Init() { head_.prev = nullptr; head_.next = &tail_; tail_.prev = &head_; tail_.next = nullptr; size_ = 0; map_.clear(); } void Detach(Node<K, V>* node) { if (node->prev != nullptr) { node->prev->next = node->next; } if (node->next != nullptr) { node->next->prev = node->prev; } node->prev = nullptr; node->next = nullptr; --size_; } void Attach(Node<K, V>* node) { node->prev = &head_; node->next = head_.next; head_.next = node; if (node->next != nullptr) { node->next->prev = node; } ++size_; } template <typename VV> bool Update(const K& key, VV&& val, K* obs, bool add_only, bool silent_update) { if (obs == nullptr) { return false; } if (Contains(key)) { if (!add_only) { map_[key].val = std::forward<VV>(val); if (!silent_update) { auto* node = &map_[key]; Detach(node); Attach(node); } else { return false; } } } else { if (Full() && !GetObsolete(obs)) { return false; } map_.emplace(key, Node<K, V>(key, std::forward<VV>(val))); Attach(&map_[key]); } return true; } V* Get(const K& key, bool silent) { if (Contains(key)) { auto* node = &map_[key]; if (!silent) { Detach(node); Attach(node); } return &node->val; } return nullptr; } bool GetCopy(const K& key, V* const val, bool silent) { if (Contains(key)) { auto* node = &map_[key]; if (!silent) { Detach(node); Attach(node); } *val = node->val; return true; } return false; } bool GetObsolete(K* key) { if (Full()) { auto* node = tail_.prev; Detach(node); *key = node->key; map_.erase(node->key); return true; } return false; } }; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/map_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. *****************************************************************************/ /** * @file * @brief Some map util functions. */ #pragma once #include "google/protobuf/stubs/map_util.h" /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { // Expose some useful utils from protobuf. // Find*() using google::protobuf::FindCopy; using google::protobuf::FindLinkedPtrOrDie; using google::protobuf::FindLinkedPtrOrNull; using google::protobuf::FindOrDie; using google::protobuf::FindOrDieNoPrint; using google::protobuf::FindOrNull; using google::protobuf::FindPtrOrNull; using google::protobuf::FindWithDefault; // Contains*() using google::protobuf::ContainsKey; using google::protobuf::ContainsKeyValuePair; // Insert*() using google::protobuf::InsertAndDeleteExisting; using google::protobuf::InsertIfNotPresent; using google::protobuf::InsertKeyOrDie; using google::protobuf::InsertOrDie; using google::protobuf::InsertOrDieNoPrint; using google::protobuf::InsertOrUpdate; using google::protobuf::InsertOrUpdateMany; // Lookup*() using google::protobuf::AddTokenCounts; using google::protobuf::LookupOrInsert; using google::protobuf::LookupOrInsertNew; using google::protobuf::LookupOrInsertNewLinkedPtr; using google::protobuf::LookupOrInsertNewSharedPtr; // Misc Utility Functions using google::protobuf::AppendKeysFromMap; using google::protobuf::AppendValuesFromMap; using google::protobuf::EraseKeyReturnValuePtr; using google::protobuf::InsertKeysFromMap; using google::protobuf::InsertOrReturnExisting; using google::protobuf::UpdateReturnCopy; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/json_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/common/util/json_util.h" #include "google/protobuf/util/json_util.h" namespace apollo { namespace common { namespace util { namespace { using Json = nlohmann::json; using google::protobuf::util::MessageToJsonString; google::protobuf::util::JsonOptions JsonOption() { google::protobuf::util::JsonOptions json_option; json_option.always_print_primitive_fields = true; return json_option; } } // namespace nlohmann::json JsonUtil::ProtoToTypedJson( const std::string &json_type, const google::protobuf::Message &proto) { static const auto kJsonOption = JsonOption(); std::string json_string; const auto status = MessageToJsonString(proto, &json_string, kJsonOption); ACHECK(status.ok()) << "Cannot convert proto to json:" << proto.DebugString(); Json json_obj; json_obj["type"] = json_type; json_obj["data"] = Json::parse(json_string); return json_obj; } bool JsonUtil::GetString(const Json &json, const std::string &key, std::string *value) { const auto iter = json.find(key); if (iter == json.end()) { AERROR << "The json has no such key: " << key; return false; } if (!iter->is_string()) { AERROR << "The value of json[" << key << "] is not a string"; return false; } *value = *iter; return true; } bool JsonUtil::GetStringVector(const Json &json, const std::string &key, std::vector<std::string> *value) { const auto iter = json.find(key); if (iter == json.end()) { AERROR << "The json has no such key: " << key; return false; } if (!iter->is_array()) { AERROR << "The value of json[" << key << "] is not an array"; return false; } bool ret = true; value->clear(); value->reserve(iter->size()); for (const auto &elem : *iter) { // Note that we still try to get all string values though there are invalid // elements. if (!elem.is_string()) { AWARN << "The value of json[" << key << "] contains non-string element"; ret = false; } else { value->push_back(elem); } } return ret; } bool JsonUtil::GetBoolean(const nlohmann::json &json, const std::string &key, bool *value) { const auto iter = json.find(key); if (iter == json.end()) { AERROR << "The json has no such key: " << key; return false; } if (!iter->is_boolean()) { AERROR << "The value of json[" << key << "] is not a boolean"; return false; } *value = *iter; return true; } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/time_util_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/common/util/time_util.h" #include "gtest/gtest.h" namespace apollo { namespace common { namespace util { TEST(TimeUtilTest, TestUnix2Gps) { double unix_time = 1476761767; double gps_time = TimeUtil::Unix2Gps(unix_time); EXPECT_NEAR(gps_time, 1160796984, 0.000001); double unix_time1 = 1483228799; double gps_time1 = TimeUtil::Unix2Gps(unix_time1); EXPECT_NEAR(gps_time1, 1167264017, 0.000001); } TEST(TimeUtilTest, TestGps2Unix) { double gps_time = 1160796984; double unix_time = TimeUtil::Gps2Unix(gps_time); EXPECT_NEAR(unix_time, 1476761767, 0.000001); double gps_time1 = 1260796984; double unix_time1 = TimeUtil::Gps2Unix(gps_time1); EXPECT_NEAR(unix_time1, 1576761766, 0.000001); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/color.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 Console color definitions */ #pragma once #include <cstdio> namespace apollo { namespace common { namespace color { constexpr char ANSI_RED[] = "\x1b[31m"; constexpr char ANSI_GREEN[] = "\x1b[32m"; constexpr char ANSI_YELLOW[] = "\x1b[33m"; constexpr char ANSI_BLUE[] = "\x1b[34m"; constexpr char ANSI_MAGENTA[] = "\x1b[35m"; constexpr char ANSI_CYAN[] = "\x1b[36m"; constexpr char ANSI_RESET[] = "\x1b[0m"; } // namespace color } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/json_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 <string> #include <vector> #include "google/protobuf/message.h" #include "nlohmann/json.hpp" #include "cyber/common/log.h" namespace apollo { namespace common { namespace util { class JsonUtil { public: /** * @brief Convert proto to a json string. * @return A json with two fields: {type:<json_type>, data:<proto_to_json>}. */ static nlohmann::json ProtoToTypedJson( const std::string &json_type, const google::protobuf::Message &proto); /** * @brief Get a string value from the given json[key]. * @return Whether the field exists and is a valid string. */ static bool GetString(const nlohmann::json &json, const std::string &key, std::string *value); /** * @brief Get a number value from the given json[key]. * @return Whether the field exists and is a valid number. */ template <class T> static bool GetNumber(const nlohmann::json &json, const std::string &key, T *value) { const auto iter = json.find(key); if (iter == json.end()) { AERROR << "The json has no such key: " << key; return false; } if (!iter->is_number()) { AERROR << "The value of json[" << key << "] is not a number"; return false; } *value = *iter; return true; } /** * @brief Get a boolean value from the given json[key]. * @return Whether the field exists and is a valid boolean. */ static bool GetBoolean(const nlohmann::json &json, const std::string &key, bool *value); /** * @brief Get a string vector from the given json[key]. * @return Whether the field exists and is a valid string vector. */ static bool GetStringVector(const nlohmann::json &json, const std::string &key, std::vector<std::string> *value); }; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/message_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/common/util/message_util.h" #include <vector> #include "gtest/gtest.h" #include "modules/common/util/testdata/simple.pb.h" namespace apollo { namespace common { namespace util { TEST(MessageUtilTest, DumpMessage) { auto simple_msg = std::make_shared<test::SimpleMessage>(); FillHeader("test", simple_msg.get()); EXPECT_TRUE(DumpMessage(simple_msg)); EXPECT_TRUE(cyber::common::PathExists( "/tmp/apollo.common.util.test.SimpleMessage/0.pb.txt")); } TEST(MessageUtilTest, MessageFingerprint) { test::SimpleMessage msg; const size_t fp0 = MessageFingerprint(msg); msg.set_integer(1); const size_t fp1 = MessageFingerprint(msg); EXPECT_NE(fp0, fp1); msg.set_integer(2); EXPECT_NE(fp1, MessageFingerprint(msg)); msg.set_integer(1); EXPECT_EQ(fp1, MessageFingerprint(msg)); msg.clear_integer(); EXPECT_EQ(fp0, MessageFingerprint(msg)); } // TEST(MessageUtilTest, get_desy_sec) { // auto simple_msg = std::make_shared<test::SimpleMessage>(); // FillHeader("test", simple_msg.get()); // EXPECT_GT(GetDelaySec(simple_msg), 0); // } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/lru_cache_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/common/util/lru_cache.h" #include <vector> #include "gtest/gtest.h" namespace apollo { namespace common { namespace util { static const int TEST_NUM = 10; static const int CAPACITY = 4; TEST(LRUCache, General) { int ids[] = {0, 1, 2, 3, 2, 1, 4, 3, 5, 6}; int timestamps[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<std::vector<int>> keys = { {0}, {1, 0}, {2, 1, 0}, {3, 2, 1, 0}, {2, 3, 1, 0}, {1, 2, 3, 0}, {4, 1, 2, 3}, {3, 4, 1, 2}, {5, 3, 4, 1}, {6, 5, 3, 4}}; std::vector<std::vector<int>> values = { {0}, {1, 0}, {2, 1, 0}, {3, 2, 1, 0}, {4, 3, 1, 0}, {5, 4, 3, 0}, {6, 5, 4, 3}, {7, 6, 5, 4}, {8, 7, 6, 5}, {9, 8, 7, 6}}; int obsoletes[TEST_NUM] = {-1, -1, -1, -1, -1, -1, 0, -1, 2, 1}; LRUCache<int, int> lru(CAPACITY); for (int i = 0; i < TEST_NUM; ++i) { int obsolete = -1; lru.PutAndGetObsolete(ids[i], &timestamps[i], &obsolete); EXPECT_EQ(obsolete, obsoletes[i]); EXPECT_EQ(static_cast<int>(lru.size()), i < CAPACITY ? i + 1 : CAPACITY); Node<int, int>* cur = lru.First(); for (int j = 0; j < static_cast<int>(lru.size()); ++j) { EXPECT_EQ(cur->key, keys[i][j]); EXPECT_EQ(cur->val, values[i][j]); cur = cur->next; } } } TEST(LRUCache, UAF) { LRUCache<int, int> cache; std::vector<int> keys = {1, 3, 5}; std::vector<int> vals = {2, 4, 6}; for (size_t i = 0; i < 2; ++i) { cache.Put(keys[i], vals[i]); } EXPECT_EQ(2, cache.size()); Node<int, int>* curr = cache.First(); EXPECT_NE(curr, nullptr); for (size_t i = 0; i < 2; ++i) { EXPECT_EQ(curr->key, keys[1 - i]); EXPECT_EQ(curr->val, vals[1 - i]); curr = curr->next; } cache.Clear(); cache.Put(keys[2], vals[2]); EXPECT_EQ(1, cache.size()); curr = cache.First(); EXPECT_NE(curr, nullptr); for (int i = 2; i < 3; ++i) { EXPECT_EQ(curr->key, keys[i]); EXPECT_EQ(curr->val, vals[i]); curr = curr->next; } cache.Clear(); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/eigen_defs.h
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <functional> #include <map> #include <utility> #include <vector> #include "Eigen/Geometry" namespace apollo { namespace common { // Using STL Containers with Eigen: // https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html template <class EigenType> using EigenVector = std::vector<EigenType, Eigen::aligned_allocator<EigenType>>; template <typename T, class EigenType> using EigenMap = std::map<T, EigenType, std::less<T>, Eigen::aligned_allocator<std::pair<const T, EigenType>>>; using EigenVector3dVec = EigenVector<Eigen::Vector3d>; using EigenAffine3dVec = EigenVector<Eigen::Affine3d>; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/data_extraction.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 <vector> #include <boost/filesystem.hpp> #include <boost/range/iterator_range.hpp> namespace apollo { namespace prediction { void GetRecordFileNames(const boost::filesystem::path& p, std::vector<std::string>* data_files); } // namespace prediction } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/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/common/util/util.h" #include <cmath> #include <vector> namespace apollo { namespace common { namespace util { PointENU operator+(const PointENU enu, const math::Vec2d& xy) { PointENU point; point.set_x(enu.x() + xy.x()); point.set_y(enu.y() + xy.y()); point.set_z(enu.z()); return point; } PathPoint GetWeightedAverageOfTwoPathPoints(const PathPoint& p1, const PathPoint& p2, const double w1, const double w2) { PathPoint p; p.set_x(p1.x() * w1 + p2.x() * w2); p.set_y(p1.y() * w1 + p2.y() * w2); p.set_z(p1.z() * w1 + p2.z() * w2); p.set_theta(p1.theta() * w1 + p2.theta() * w2); p.set_kappa(p1.kappa() * w1 + p2.kappa() * w2); p.set_dkappa(p1.dkappa() * w1 + p2.dkappa() * w2); p.set_ddkappa(p1.ddkappa() * w1 + p2.ddkappa() * w2); p.set_s(p1.s() * w1 + p2.s() * w2); return p; } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/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/common/util/util.h" #include <vector> #include "gtest/gtest.h" #include "modules/common/util/testdata/simple.pb.h" namespace apollo { namespace common { namespace util { TEST(Util, IsProtoEqual) { test::SimpleRepeatedMessage sim1; for (int i = 0; i < 10; ++i) { auto* t = sim1.add_message(); t->set_integer(i); t->set_text(std::to_string(i)); } auto sim2 = sim1; EXPECT_TRUE(IsProtoEqual(sim1, sim2)); sim2.mutable_message(0)->set_integer(-1); EXPECT_FALSE(IsProtoEqual(sim1, sim2)); } TEST(Util, DistanceXY) { class TestPoint { public: TestPoint(double x, double y) : x_(x), y_(y) {} double x() const { return x_; } double y() const { return y_; } private: double x_ = 0.0; double y_ = 0.0; }; EXPECT_DOUBLE_EQ(0.0, DistanceXY(TestPoint(0, 0), TestPoint(0, 0))); EXPECT_DOUBLE_EQ(1.0, DistanceXY(TestPoint(1, 0), TestPoint(0, 0))); EXPECT_DOUBLE_EQ(1.0, DistanceXY(TestPoint(0, 0), TestPoint(1, 0))); EXPECT_DOUBLE_EQ(0.0, DistanceXY(TestPoint(1, 0), TestPoint(1, 0))); } TEST(Util, uniform_slice) { std::vector<double> result; uniform_slice(0.0, 10.0, 3, &result); ASSERT_EQ(4, result.size()); EXPECT_DOUBLE_EQ(0.0, result[0]); EXPECT_DOUBLE_EQ(3.3333333333333335, result[1]); EXPECT_DOUBLE_EQ(6.666666666666667, result[2]); EXPECT_DOUBLE_EQ(10.0, result[3]); uniform_slice(0.0, -10.0, 3, &result); ASSERT_EQ(4, result.size()); EXPECT_DOUBLE_EQ(0.0, result[0]); EXPECT_DOUBLE_EQ(-3.3333333333333335, result[1]); EXPECT_DOUBLE_EQ(-6.666666666666667, result[2]); EXPECT_DOUBLE_EQ(-10.0, result[3]); } TEST(Util, IsFloatEqual) { double d1 = 0.2; double d2 = 1 / std::sqrt(5) / std::sqrt(5); EXPECT_TRUE(IsFloatEqual(d1, d2)); double d3 = 0.999999999999999999; double d4 = 0.999999999999999998; EXPECT_TRUE(IsFloatEqual(d3, d4)); double d5 = 0.11; double d6 = 0.12; EXPECT_FALSE(IsFloatEqual(d5, d6)); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/perf_util.cc
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/util/perf_util.h" #include "cyber/common/log.h" namespace { std::string func_name_simplified(const std::string& str) { constexpr char kLeftBracket = '('; constexpr char kSpace = ' '; auto end = str.find(kLeftBracket); auto begin = str.rfind(kSpace, end); if (begin == std::string::npos) { return str.substr(0, end); } else if (end == std::string::npos) { return str.substr(begin + 1); } else { return str.substr(begin + 1, end - begin - 1); } } } // namespace using apollo::cyber::Time; namespace apollo { namespace common { namespace util { std::string function_signature(const std::string& func_name, const std::string& indicator) { auto simplified_name = func_name_simplified(func_name); if (indicator.empty()) { return simplified_name; } return absl::StrCat(indicator, "_", simplified_name); } void Timer::Start() { start_time_ = Time::Now(); } int64_t Timer::End(const std::string& msg) { end_time_ = Time::Now(); int64_t elapsed_time = (end_time_ - start_time_).ToNanosecond() / 1e6; ADEBUG << "TIMER " << msg << " elapsed_time: " << elapsed_time << " ms"; // start new timer. start_time_ = end_time_; return elapsed_time; } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/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. *****************************************************************************/ /** * @file * @brief Some util functions. */ #pragma once #include <algorithm> #include <iostream> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "cyber/common/log.h" #include "cyber/common/types.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/geometry.pb.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { template <typename ProtoA, typename ProtoB> bool IsProtoEqual(const ProtoA& a, const ProtoB& b) { return a.GetTypeName() == b.GetTypeName() && a.SerializeAsString() == b.SerializeAsString(); // Test shows that the above method is 5 times faster than the // API: google::protobuf::util::MessageDifferencer::Equals(a, b); } struct PairHash { template <typename T, typename U> size_t operator()(const std::pair<T, U>& pair) const { return std::hash<T>()(pair.first) ^ std::hash<U>()(pair.second); } }; template <typename T> bool WithinBound(T start, T end, T value) { return value >= start && value <= end; } PointENU operator+(const PointENU enu, const math::Vec2d& xy); /** * uniformly slice a segment [start, end] to num + 1 pieces * the result sliced will contain the n + 1 points that slices the provided * segment. `start` and `end` will be the first and last element in `sliced`. */ template <typename T> void uniform_slice(const T start, const T end, uint32_t num, std::vector<T>* sliced) { if (!sliced || num == 0) { return; } const T delta = (end - start) / num; sliced->resize(num + 1); T s = start; for (uint32_t i = 0; i < num; ++i, s += delta) { sliced->at(i) = s; } sliced->at(num) = end; } /** * calculate the distance beteween Point u and Point v, which are all have * member function x() and y() in XY dimension. * @param u one point that has member function x() and y(). * @param b one point that has member function x() and y(). * @return sqrt((u.x-v.x)^2 + (u.y-v.y)^2), i.e., the Euclid distance on XY * dimension. */ template <typename U, typename V> double DistanceXY(const U& u, const V& v) { return std::hypot(u.x() - v.x(), u.y() - v.y()); } /** * Check if two points u and v are the same point on XY dimension. * @param u one point that has member function x() and y(). * @param v one point that has member function x() and y(). * @return sqrt((u.x-v.x)^2 + (u.y-v.y)^2) < epsilon, i.e., the Euclid distance * on XY dimension. */ template <typename U, typename V> bool SamePointXY(const U& u, const V& v) { static constexpr double kMathEpsilonSqr = 1e-8 * 1e-8; return (u.x() - v.x()) * (u.x() - v.x()) < kMathEpsilonSqr && (u.y() - v.y()) * (u.y() - v.y()) < kMathEpsilonSqr; } PathPoint GetWeightedAverageOfTwoPathPoints(const PathPoint& p1, const PathPoint& p2, const double w1, const double w2); // Test whether two float or double numbers are equal. // ulp: units in the last place. template <typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type IsFloatEqual(T x, T y, int ulp = 2) { // the machine epsilon has to be scaled to the magnitude of the values used // and multiplied by the desired precision in ULPs (units in the last place) return std::fabs(x - y) < std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp // unless the result is subnormal || std::fabs(x - y) < std::numeric_limits<T>::min(); } } // namespace util } // namespace common } // namespace apollo template <typename T> class FunctionInfo { public: typedef int (T::*Function)(); Function function_; std::string fun_name_; }; template <typename T, size_t count> bool ExcuteAllFunctions(T* obj, FunctionInfo<T> fun_list[]) { for (size_t i = 0; i < count; i++) { if ((obj->*(fun_list[i].function_))() != apollo::cyber::SUCC) { AERROR << fun_list[i].fun_name_ << " failed."; return false; } } return true; } #define EXEC_ALL_FUNS(type, obj, list) \ ExcuteAllFunctions<type, sizeof(list) / sizeof(FunctionInfo<type>)>(obj, list) template <typename A, typename B> std::ostream& operator<<(std::ostream& os, std::pair<A, B>& p) { return os << "first: " << p.first << ", second: " << p.second; } #define UNIQUE_LOCK_MULTITHREAD(mutex_type) \ std::unique_ptr<std::unique_lock<std::mutex>> lock_ptr = nullptr; \ if (FLAGS_multithread_run) { \ lock_ptr.reset(new std::unique_lock<std::mutex>(mutex_type)); \ }
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/string_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/common/util/string_util.h" #include <cmath> #include <vector> #include "absl/strings/str_cat.h" namespace apollo { namespace common { namespace util { namespace { static const char kBase64Array[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string Base64Piece(const char in0, const char in1, const char in2) { const int triplet = in0 << 16 | in1 << 8 | in2; std::string out(4, '='); out[0] = kBase64Array[(triplet >> 18) & 0x3f]; out[1] = kBase64Array[(triplet >> 12) & 0x3f]; if (in1) { out[2] = kBase64Array[(triplet >> 6) & 0x3f]; } if (in2) { out[3] = kBase64Array[triplet & 0x3f]; } return out; } } // namespace std::string EncodeBase64(std::string_view in) { std::string out; if (in.empty()) { return out; } const size_t in_size = in.length(); out.reserve(((in_size - 1) / 3 + 1) * 4); for (size_t i = 0; i + 2 < in_size; i += 3) { absl::StrAppend(&out, Base64Piece(in[i], in[i + 1], in[i + 2])); } if (in_size % 3 == 1) { absl::StrAppend(&out, Base64Piece(in[in_size - 1], 0, 0)); } if (in_size % 3 == 2) { absl::StrAppend(&out, Base64Piece(in[in_size - 2], in[in_size - 1], 0)); } return out; } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/json_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/common/util/json_util.h" #include "gmock/gmock.h" #include "google/protobuf/util/json_util.h" #include "gtest/gtest.h" #include "modules/common_msgs/basic_msgs/error_code.pb.h" namespace apollo { namespace common { namespace util { using Json = nlohmann::json; TEST(JsonUtilTest, ProtoToTypedJson) { StatusPb status; status.set_msg("MsgA"); Json json_obj = JsonUtil::ProtoToTypedJson("TypeA", status); EXPECT_EQ("TypeA", json_obj["type"]); EXPECT_EQ("MsgA", json_obj["data"]["msg"]); } TEST(JsonUtilTest, GetString) { Json json_obj = {{"int", 0}, {"empty_str", ""}, {"str", "value2"}}; std::string value; // No such key. EXPECT_FALSE(JsonUtil::GetString(json_obj, "no_such_key", &value)); // Value is not string. EXPECT_FALSE(JsonUtil::GetString(json_obj, "int", &value)); // Empty string. EXPECT_TRUE(JsonUtil::GetString(json_obj, "empty_str", &value)); EXPECT_TRUE(value.empty()); // Non empty string. EXPECT_TRUE(JsonUtil::GetString(json_obj, "str", &value)); EXPECT_EQ("value2", value); } TEST(JsonUtilTest, GetStringVector) { Json json_obj = {{"int", 0}, {"empty_array", Json::array()}, {"int_array", {0}}, {"any_array", {0, "str1"}}, {"str_array", {"str1", "str2"}}}; std::vector<std::string> value; // No such key. EXPECT_FALSE(JsonUtil::GetStringVector(json_obj, "no_such_key", &value)); // Value is not array. EXPECT_FALSE(JsonUtil::GetStringVector(json_obj, "int", &value)); // Empty array. EXPECT_TRUE(JsonUtil::GetStringVector(json_obj, "empty_array", &value)); EXPECT_TRUE(value.empty()); // Non-string array. EXPECT_FALSE(JsonUtil::GetStringVector(json_obj, "int_array", &value)); EXPECT_TRUE(value.empty()); // Array contains non-string element. EXPECT_FALSE(JsonUtil::GetStringVector(json_obj, "any_array", &value)); EXPECT_THAT(value, testing::ElementsAre("str1")); // String array. EXPECT_TRUE(JsonUtil::GetStringVector(json_obj, "str_array", &value)); EXPECT_THAT(value, testing::ElementsAre("str1", "str2")); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/points_downsampler_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/common/util/points_downsampler.h" #include <vector> #include "gtest/gtest.h" #include "modules/common/math/vec2d.h" namespace apollo { namespace common { namespace util { using apollo::common::math::Vec2d; TEST(DownSamplerTest, DownsampleByAngle) { std::vector<Vec2d> points; points.emplace_back(-405.778, -134.969); points.emplace_back(-403.919, -127.696); points.emplace_back(-400.635, -115.407); points.emplace_back(-397.997, -105.291); points.emplace_back(-395.801, -96.8637); points.emplace_back(-392.889, -86.1015); points.emplace_back(-388.054, -67.9935); points.emplace_back(-385.994, -60.1831); points.emplace_back(-378.213, -30.2776); points.emplace_back(-376.702, -24.5804); points.emplace_back(-373.825, -13.3855); points.emplace_back(-367.583, 10.4028); points.emplace_back(-363.025, 27.4212); std::vector<size_t> sampled_indices = DownsampleByAngle(points, 0.1); EXPECT_EQ(2, sampled_indices.size()); EXPECT_EQ(0, sampled_indices[0]); EXPECT_EQ(12, sampled_indices[1]); } TEST(DownSamplerTest, DownsampleByDistanceNormal) { std::vector<Vec2d> points; points.emplace_back(0, 0); points.emplace_back(0, 4); points.emplace_back(0, 8); points.emplace_back(0, 12); points.emplace_back(0, 16); points.emplace_back(0, 20); std::vector<size_t> sampled_indices = DownsampleByDistance(points, 5, 1); EXPECT_EQ(4, sampled_indices.size()); EXPECT_EQ(0, sampled_indices[0]); EXPECT_EQ(2, sampled_indices[1]); EXPECT_EQ(4, sampled_indices[2]); EXPECT_EQ(5, sampled_indices[3]); } TEST(DownSamplerTest, DownsampleByDistanceSteepTurn) { std::vector<Vec2d> points; points.emplace_back(-2, 0); points.emplace_back(-1, 1); points.emplace_back(0, 2); points.emplace_back(1, 1); points.emplace_back(2, 0); std::vector<size_t> sampled_indices = DownsampleByDistance(points, 5, 1); EXPECT_EQ(5, sampled_indices.size()); EXPECT_EQ(0, sampled_indices[0]); EXPECT_EQ(1, sampled_indices[1]); EXPECT_EQ(2, sampled_indices[2]); EXPECT_EQ(3, sampled_indices[3]); EXPECT_EQ(4, sampled_indices[4]); } } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") package(default_visibility = ["//visibility:public"]) install( name = "install", library_dest = "common/lib", data_dest = "common", runtime_dest = "common/bin", targets = [ ":libutil_tool.so", ":libapolloutil.so", ], deps = [":util_testdata"], visibility = ["//visibility:public"], ) install( name = "util_testdata", data_dest = "common/addition_data/util", data = [ ":util_test_data", ], ) filegroup( name = "util_test_data", srcs = glob([ "testdata/*", ]), ) cc_binary( name = "libutil_tool.so", linkshared = True, linkstatic = True, deps = [ ":color", ":data_extraction", ":eigen_defs", ":factory", ":future", ":json_util", ":lru_cache", ":map_util", ":message_util", ":perf_util", ":string_util", ":time_util", ], ) cc_library( name = "util_tool", srcs = ["libutil_tool.so"], hdrs = glob( ["*.h"], exclude = [ "point_factory.h", "points_downsampler.h", "util.h", ], ), deps = [ "//cyber", "@boost", "@com_github_nlohmann_json//:json", "@com_google_absl//:absl", "@com_google_protobuf//:protobuf", "@eigen", ], visibility = ["//visibility:public"], ) cc_library( name = "util_lib", srcs = ["util.cc"], hdrs = ["util.h"], alwayslink = True, deps = [ "//cyber", "//modules/common/configs:config_gflags", "//modules/common/math", "//modules/common_msgs/basic_msgs:geometry_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "future", hdrs = ["future.h"], alwayslink = True, deps = [ "@com_google_absl//:absl", ], ) cc_library( name = "point_factory", hdrs = ["point_factory.h"], alwayslink = True, deps = [ "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", ], ) cc_test( name = "util_test", size = "small", srcs = ["util_test.cc"], deps = [ ":util_lib", "//modules/common/util/testdata:simple_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "lru_cache", hdrs = ["lru_cache.h"], alwayslink = True, ) cc_library( name = "color", hdrs = ["color.h"], alwayslink = True, ) cc_library( name = "data_extraction", srcs = ["data_extraction.cc"], hdrs = ["data_extraction.h"], alwayslink = True, deps = [ "//cyber", "@boost", ], ) cc_library( name = "string_util", srcs = ["string_util.cc"], hdrs = ["string_util.h"], alwayslink = True, deps = [ ":future", "@com_google_absl//:absl", ], ) cc_library( name = "message_util", hdrs = ["message_util.h"], alwayslink = True, deps = [ "//cyber", "@com_google_absl//:absl", "@com_google_protobuf//:protobuf", ], ) cc_test( name = "message_util_test", size = "small", srcs = ["message_util_test.cc"], tags = [ "external", ], deps = [ ":message_util", "//modules/common/util/testdata:simple_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "string_util_test", size = "small", srcs = ["string_util_test.cc"], deps = [ ":string_util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "time_util", hdrs = ["time_util.h"], alwayslink = True, deps = [ "//cyber", ], ) cc_test( name = "time_util_test", size = "small", srcs = ["time_util_test.cc"], deps = [ ":time_util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "map_util", hdrs = ["map_util.h"], alwayslink = True, deps = [ "@com_google_protobuf//:protobuf", ], ) cc_library( name = "factory", hdrs = ["factory.h"], alwayslink = True, deps = [ "//cyber", ], ) cc_test( name = "factory_test", size = "small", srcs = ["factory_test.cc"], deps = [ ":factory", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "lru_cache_test", size = "small", srcs = ["lru_cache_test.cc"], deps = [ ":lru_cache", "@com_google_googletest//:gtest_main", ], ) cc_binary( name = "libapolloutil.so", linkshared = True, linkstatic = True, deps = [ ":point_factory", ":points_downsampler", ":util_lib", ], ) cc_library( name = "util", srcs = ["libapolloutil.so"], hdrs = [ "point_factory.h", "points_downsampler.h", "util.h", ], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:geometry_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/configs:config_gflags", "//modules/common/math", "@com_github_gflags_gflags//:gflags", ], visibility = ["//visibility:public"], ) cc_library( name = "points_downsampler", hdrs = ["points_downsampler.h"], alwayslink = True, deps = [ "//cyber", "//modules/common/math", ], ) cc_test( name = "points_downsampler_test", size = "small", srcs = ["points_downsampler_test.cc"], deps = [ ":points_downsampler", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "json_util", srcs = ["json_util.cc"], hdrs = ["json_util.h"], alwayslink = True, deps = [ "//cyber", "@com_github_nlohmann_json//:json", "@com_google_protobuf//:protobuf", ], ) cc_test( name = "json_util_test", size = "small", srcs = ["json_util_test.cc"], deps = [ ":json_util", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "eigen_defs", hdrs = ["eigen_defs.h"], alwayslink = True, deps = ["@eigen"], ) cc_library( name = "perf_util", srcs = ["perf_util.cc"], hdrs = ["perf_util.h"], alwayslink = True, deps = [ "//cyber", "@com_google_absl//:absl", ], ) cc_test( name = "perf_util_test", size = "small", srcs = ["perf_util_test.cc"], deps = [ ":perf_util", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/util/factory.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 Defines the Factory class. */ #pragma once #include <map> #include <memory> #include <utility> #include "cyber/common/macros.h" #include "cyber/common/log.h" /** * @namespace apollo::common::util * @brief apollo::common::util */ namespace apollo { namespace common { namespace util { /** * @class Factory * @brief Implements a Factory design pattern with Register and Create methods * * The objects created by this factory all implement the same interface * (namely, AbstractProduct). This design pattern is useful in settings where * multiple implementations of an interface are available, and one wishes to * defer the choice of the implementation in use. * * @param IdentifierType Type used for identifying the registered classes, * typically std::string. * @param AbstractProduct The interface implemented by the registered classes * @param ProductCreator Function returning a pointer to an instance of * the registered class * @param MapContainer Internal implementation of the function mapping * IdentifierType to ProductCreator, by default std::unordered_map */ template <typename IdentifierType, class AbstractProduct, class ProductCreator = AbstractProduct *(*)(), class MapContainer = std::map<IdentifierType, ProductCreator>> class Factory { public: /** * @brief Registers the class given by the creator function, linking it to id. * Registration must happen prior to calling CreateObject. * @param id Identifier of the class being registered * @param creator Function returning a pointer to an instance of * the registered class * @return True if the key id is still available */ bool Register(const IdentifierType &id, ProductCreator creator) { return producers_.insert(std::make_pair(id, creator)).second; } bool Contains(const IdentifierType &id) { return producers_.find(id) != producers_.end(); } /** * @brief Unregisters the class with the given identifier * @param id The identifier of the class to be unregistered */ bool Unregister(const IdentifierType &id) { return producers_.erase(id) == 1; } void Clear() { producers_.clear(); } bool Empty() const { return producers_.empty(); } /** * @brief Creates and transfers membership of an object of type matching id. * Need to register id before CreateObject is called. May return nullptr * silently. * @param id The identifier of the class we which to instantiate * @param args the object construction arguments */ template <typename... Args> std::unique_ptr<AbstractProduct> CreateObjectOrNull(const IdentifierType &id, Args &&... args) { auto id_iter = producers_.find(id); if (id_iter != producers_.end()) { return std::unique_ptr<AbstractProduct>( (id_iter->second)(std::forward<Args>(args)...)); } return nullptr; } /** * @brief Creates and transfers membership of an object of type matching id. * Need to register id before CreateObject is called. * @param id The identifier of the class we which to instantiate * @param args the object construction arguments */ template <typename... Args> std::unique_ptr<AbstractProduct> CreateObject(const IdentifierType &id, Args &&... args) { auto result = CreateObjectOrNull(id, std::forward<Args>(args)...); AERROR_IF(!result) << "Factory could not create Object of type : " << id; return result; } private: MapContainer producers_; }; } // namespace util } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common/util
apollo_public_repos/apollo/modules/common/util/testdata/simple.proto
syntax = "proto2"; import "modules/common_msgs/basic_msgs/header.proto"; package apollo.common.util.test; message SimpleMessage { optional int32 integer = 1; optional string text = 2; optional Header header = 3; } message SimpleRepeatedMessage { repeated SimpleMessage message = 1; }
0
apollo_public_repos/apollo/modules/common/util
apollo_public_repos/apollo/modules/common/util/testdata/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "simple_cc_proto", deps = [ ":simple_proto", ], ) proto_library( name = "simple_proto", srcs = ["simple.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ], ) py_proto_library( name = "simple_py_pb2", deps = [ ":simple_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ], ) install_files( name = "py_pb_common_util", dest = "common/python/modules/common/util/testdata", files = [ "simple_py_pb2", ] )
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/vehicle_state/vehicle_state_provider_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/common/vehicle_state/vehicle_state_provider.h" #include <string> #include "Eigen/Core" #include "gtest/gtest.h" #include "cyber/common/file.h" #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/common/configs/config_gflags.h" namespace apollo { namespace common { namespace vehicle_state_provider { using apollo::canbus::Chassis; using apollo::localization::LocalizationEstimate; class VehicleStateProviderTest : public ::testing::Test { public: virtual void SetUp() { std::string localization_file = "modules/common/vehicle_state/testdata/3_localization_result_1.pb.txt"; ACHECK(cyber::common::GetProtoFromFile(localization_file, &localization_)); chassis_.set_speed_mps(3.0); chassis_.set_gear_location(canbus::Chassis::GEAR_DRIVE); FLAGS_enable_map_reference_unify = false; } protected: LocalizationEstimate localization_; Chassis chassis_; }; TEST_F(VehicleStateProviderTest, Accessors) { auto vehicle_state_provider = std::make_shared<VehicleStateProvider>(); vehicle_state_provider->Update(localization_, chassis_); EXPECT_DOUBLE_EQ(vehicle_state_provider->x(), 357.51331791372041); EXPECT_DOUBLE_EQ(vehicle_state_provider->y(), 96.165912376788725); EXPECT_DOUBLE_EQ(vehicle_state_provider->heading(), -1.8388082455104939); EXPECT_DOUBLE_EQ(vehicle_state_provider->roll(), 0.047026695713820919); EXPECT_DOUBLE_EQ(vehicle_state_provider->pitch(), -0.010712737572581465); EXPECT_DOUBLE_EQ(vehicle_state_provider->yaw(), 2.8735807348741953); EXPECT_DOUBLE_EQ(vehicle_state_provider->linear_velocity(), 3.0); EXPECT_DOUBLE_EQ(vehicle_state_provider->angular_velocity(), -0.0079623083093763921); EXPECT_DOUBLE_EQ(vehicle_state_provider->linear_acceleration(), -0.079383290718229638); EXPECT_DOUBLE_EQ(vehicle_state_provider->gear(), canbus::Chassis::GEAR_DRIVE); } TEST_F(VehicleStateProviderTest, EstimateFuturePosition) { auto vehicle_state_provider = std::make_shared<VehicleStateProvider>(); vehicle_state_provider->Update(localization_, chassis_); common::math::Vec2d future_position = vehicle_state_provider->EstimateFuturePosition(1.0); EXPECT_NEAR(future_position.x(), 356.707, 1e-3); EXPECT_NEAR(future_position.y(), 93.276, 1e-3); future_position = vehicle_state_provider->EstimateFuturePosition(2.0); EXPECT_NEAR(future_position.x(), 355.879, 1e-3); EXPECT_NEAR(future_position.y(), 90.393, 1e-3); } } // namespace vehicle_state_provider } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/vehicle_state/vehicle_state_provider.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 vehicle_state.h * * @brief Declaration of the class VehicleStateProvider. */ #pragma once #include <memory> #include <string> #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/common/math/box2d.h" #include "modules/common/math/vec2d.h" #include "modules/common/status/status.h" #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" /** * @namespace apollo::common * @brief apollo::common */ namespace apollo { namespace common { /** * @class VehicleStateProvider * @brief The class of vehicle state. * It includes basic information and computation * about the state of the vehicle. */ class VehicleStateProvider { public: /** * @brief Constructor by information of localization and chassis. * @param localization Localization information of the vehicle. * @param chassis Chassis information of the vehicle. */ Status Update(const localization::LocalizationEstimate& localization, const canbus::Chassis& chassis); /** * @brief Update VehicleStateProvider instance by protobuf files. * @param localization_file the localization protobuf file. * @param chassis_file The chassis protobuf file */ void Update(const std::string& localization_file, const std::string& chassis_file); double timestamp() const; const localization::Pose& pose() const; const localization::Pose& original_pose() const; /** * @brief Default destructor. */ virtual ~VehicleStateProvider() = default; /** * @brief Get the x-coordinate of vehicle position. * @return The x-coordinate of vehicle position. */ double x() const; /** * @brief Get the y-coordinate of vehicle position. * @return The y-coordinate of vehicle position. */ double y() const; /** * @brief Get the z coordinate of vehicle position. * @return The z coordinate of vehicle position. */ double z() const; /** * @brief Get the kappa of vehicle position. * the positive or negative sign is decided by the vehicle heading vector * along the path * @return The kappa of vehicle position. */ double kappa() const; /** * @brief Get the vehicle roll angle. * @return The euler roll angle. */ double roll() const; /** * @brief Get the vehicle pitch angle. * @return The euler pitch angle. */ double pitch() const; /** * @brief Get the vehicle yaw angle. * As of now, use the heading instead of yaw angle. * Heading angle with East as zero, yaw angle has North as zero * @return The euler yaw angle. */ double yaw() const; /** * @brief Get the heading of vehicle position, which is the angle * between the vehicle's heading direction and the x-axis. * @return The angle between the vehicle's heading direction * and the x-axis. */ double heading() const; /** * @brief Get the vehicle's linear velocity. * @return The vehicle's linear velocity. */ double linear_velocity() const; /** * @brief Get the vehicle's angular velocity. * @return The vehicle's angular velocity. */ double angular_velocity() const; /** * @brief Get the vehicle's linear acceleration. * @return The vehicle's linear acceleration. */ double linear_acceleration() const; /** * @brief Get the vehicle's gear position. * @return The vehicle's gear position. */ double gear() const; /** * @brief Get the vehicle's steering angle. * @return double */ double steering_percentage() const; /** * @brief Set the vehicle's linear velocity. * @param linear_velocity The value to set the vehicle's linear velocity. */ void set_linear_velocity(const double linear_velocity); /** * @brief Estimate future position from current position and heading, * along a period of time, by constant linear velocity, * linear acceleration, angular velocity. * @param t The length of time period. * @return The estimated future position in time t. */ math::Vec2d EstimateFuturePosition(const double t) const; /** * @brief Compute the position of center of mass(COM) of the vehicle, * given the distance from rear wheels to the center of mass. * @param rear_to_com_distance Distance from rear wheels to * the vehicle's center of mass. * @return The position of the vehicle's center of mass. */ math::Vec2d ComputeCOMPosition(const double rear_to_com_distance) const; const VehicleState& vehicle_state() const; private: bool ConstructExceptLinearVelocity( const localization::LocalizationEstimate& localization); common::VehicleState vehicle_state_; localization::LocalizationEstimate original_localization_; }; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/vehicle_state/vehicle_state_provider.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/common/vehicle_state/vehicle_state_provider.h" #include <cmath> #include "Eigen/Core" #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/math/euler_angles_zxy.h" #include "modules/common/math/quaternion.h" namespace apollo { namespace common { Status VehicleStateProvider::Update( const localization::LocalizationEstimate &localization, const canbus::Chassis &chassis) { original_localization_ = localization; if (!ConstructExceptLinearVelocity(localization)) { std::string msg = absl::StrCat( "Fail to update because ConstructExceptLinearVelocity error.", "localization:\n", localization.DebugString()); return Status(ErrorCode::LOCALIZATION_ERROR, msg); } if (localization.has_measurement_time()) { vehicle_state_.set_timestamp(localization.measurement_time()); } else if (localization.header().has_timestamp_sec()) { vehicle_state_.set_timestamp(localization.header().timestamp_sec()); } else if (chassis.has_header() && chassis.header().has_timestamp_sec()) { AERROR << "Unable to use location timestamp for vehicle state. Use chassis " "time instead."; vehicle_state_.set_timestamp(chassis.header().timestamp_sec()); } if (chassis.has_gear_location()) { vehicle_state_.set_gear(chassis.gear_location()); } else { vehicle_state_.set_gear(canbus::Chassis::GEAR_NONE); } if (chassis.has_speed_mps()) { vehicle_state_.set_linear_velocity(chassis.speed_mps()); if (!FLAGS_reverse_heading_vehicle_state && vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) { vehicle_state_.set_linear_velocity(-vehicle_state_.linear_velocity()); } } if (chassis.has_steering_percentage()) { vehicle_state_.set_steering_percentage(chassis.steering_percentage()); } static constexpr double kEpsilon = 1e-6; if (std::abs(vehicle_state_.linear_velocity()) < kEpsilon) { vehicle_state_.set_kappa(0.0); } else { vehicle_state_.set_kappa(vehicle_state_.angular_velocity() / vehicle_state_.linear_velocity()); } vehicle_state_.set_driving_mode(chassis.driving_mode()); return Status::OK(); } bool VehicleStateProvider::ConstructExceptLinearVelocity( const localization::LocalizationEstimate &localization) { if (!localization.has_pose()) { AERROR << "Invalid localization input."; return false; } // skip localization update when it is in use_navigation_mode. if (FLAGS_use_navigation_mode) { ADEBUG << "Skip localization update when it is in use_navigation_mode."; return true; } vehicle_state_.mutable_pose()->CopyFrom(localization.pose()); if (localization.pose().has_position()) { vehicle_state_.set_x(localization.pose().position().x()); vehicle_state_.set_y(localization.pose().position().y()); vehicle_state_.set_z(localization.pose().position().z()); } const auto &orientation = localization.pose().orientation(); if (localization.pose().has_heading()) { vehicle_state_.set_heading(localization.pose().heading()); } else { vehicle_state_.set_heading( math::QuaternionToHeading(orientation.qw(), orientation.qx(), orientation.qy(), orientation.qz())); } if (FLAGS_enable_map_reference_unify) { if (!localization.pose().has_angular_velocity_vrf()) { AERROR << "localization.pose().has_angular_velocity_vrf() must be true " "when FLAGS_enable_map_reference_unify is true."; return false; } vehicle_state_.set_angular_velocity( localization.pose().angular_velocity_vrf().z()); if (!localization.pose().has_linear_acceleration_vrf()) { AERROR << "localization.pose().has_linear_acceleration_vrf() must be " "true when FLAGS_enable_map_reference_unify is true."; return false; } vehicle_state_.set_linear_acceleration( localization.pose().linear_acceleration_vrf().y()); } else { if (!localization.pose().has_angular_velocity()) { AERROR << "localization.pose() has no angular velocity."; return false; } vehicle_state_.set_angular_velocity( localization.pose().angular_velocity().z()); if (!localization.pose().has_linear_acceleration()) { AERROR << "localization.pose() has no linear acceleration."; return false; } vehicle_state_.set_linear_acceleration( localization.pose().linear_acceleration().y()); } if (localization.pose().has_euler_angles()) { vehicle_state_.set_roll(localization.pose().euler_angles().y()); vehicle_state_.set_pitch(localization.pose().euler_angles().x()); vehicle_state_.set_yaw(localization.pose().euler_angles().z()); } else { math::EulerAnglesZXYd euler_angle(orientation.qw(), orientation.qx(), orientation.qy(), orientation.qz()); vehicle_state_.set_roll(euler_angle.roll()); vehicle_state_.set_pitch(euler_angle.pitch()); vehicle_state_.set_yaw(euler_angle.yaw()); } return true; } double VehicleStateProvider::x() const { return vehicle_state_.x(); } double VehicleStateProvider::y() const { return vehicle_state_.y(); } double VehicleStateProvider::z() const { return vehicle_state_.z(); } double VehicleStateProvider::roll() const { return vehicle_state_.roll(); } double VehicleStateProvider::pitch() const { return vehicle_state_.pitch(); } double VehicleStateProvider::yaw() const { return vehicle_state_.yaw(); } double VehicleStateProvider::heading() const { return vehicle_state_.heading(); } double VehicleStateProvider::kappa() const { return vehicle_state_.kappa(); } double VehicleStateProvider::linear_velocity() const { return vehicle_state_.linear_velocity(); } double VehicleStateProvider::angular_velocity() const { return vehicle_state_.angular_velocity(); } double VehicleStateProvider::linear_acceleration() const { return vehicle_state_.linear_acceleration(); } double VehicleStateProvider::gear() const { return vehicle_state_.gear(); } double VehicleStateProvider::steering_percentage() const { return vehicle_state_.steering_percentage(); } double VehicleStateProvider::timestamp() const { return vehicle_state_.timestamp(); } const localization::Pose &VehicleStateProvider::pose() const { return vehicle_state_.pose(); } const localization::Pose &VehicleStateProvider::original_pose() const { return original_localization_.pose(); } void VehicleStateProvider::set_linear_velocity(const double linear_velocity) { vehicle_state_.set_linear_velocity(linear_velocity); } const VehicleState &VehicleStateProvider::vehicle_state() const { return vehicle_state_; } math::Vec2d VehicleStateProvider::EstimateFuturePosition(const double t) const { Eigen::Vector3d vec_distance(0.0, 0.0, 0.0); double v = vehicle_state_.linear_velocity(); // Predict distance travel vector if (std::fabs(vehicle_state_.angular_velocity()) < 0.0001) { vec_distance[0] = 0.0; vec_distance[1] = v * t; } else { vec_distance[0] = -v / vehicle_state_.angular_velocity() * (1.0 - std::cos(vehicle_state_.angular_velocity() * t)); vec_distance[1] = std::sin(vehicle_state_.angular_velocity() * t) * v / vehicle_state_.angular_velocity(); } // If we have rotation information, take it into consideration. if (vehicle_state_.pose().has_orientation()) { const auto &orientation = vehicle_state_.pose().orientation(); Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(), orientation.qy(), orientation.qz()); Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(), vehicle_state_.z()); const Eigen::Vector3d future_pos_3d = quaternion.toRotationMatrix() * vec_distance + pos_vec; return math::Vec2d(future_pos_3d[0], future_pos_3d[1]); } // If no valid rotation information provided from localization, // return the estimated future position without rotation. return math::Vec2d(vec_distance[0] + vehicle_state_.x(), vec_distance[1] + vehicle_state_.y()); } math::Vec2d VehicleStateProvider::ComputeCOMPosition( const double rear_to_com_distance) const { // set length as distance between rear wheel and center of mass. Eigen::Vector3d v; if ((FLAGS_state_transform_to_com_reverse && vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) || (FLAGS_state_transform_to_com_drive && vehicle_state_.gear() == canbus::Chassis::GEAR_DRIVE)) { v << 0.0, rear_to_com_distance, 0.0; } else { v << 0.0, 0.0, 0.0; } Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(), vehicle_state_.z()); // Initialize the COM position without rotation Eigen::Vector3d com_pos_3d = v + pos_vec; // If we have rotation information, take it into consideration. if (vehicle_state_.pose().has_orientation()) { const auto &orientation = vehicle_state_.pose().orientation(); Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(), orientation.qy(), orientation.qz()); // Update the COM position with rotation com_pos_3d = quaternion.toRotationMatrix() * v + pos_vec; } return math::Vec2d(com_pos_3d[0], com_pos_3d[1]); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/vehicle_state/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") install( name = "install", library_dest = "common/lib", data_dest = "common", runtime_dest = "common/bin", targets = [ ":libvehicle_state_provider.so", ], visibility = ["//visibility:public"], ) package(default_visibility = ["//visibility:public"]) cc_binary( name = "libvehicle_state_provider.so", srcs = [ "vehicle_state_provider.cc", "vehicle_state_provider.h", ], linkshared = True, linkstatic = True, deps = [ "//cyber", "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common/configs:config_gflags", "//modules/common/math", "//modules/common/status", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "@eigen", "@com_google_absl//:absl", ], ) cc_library( name = "vehicle_state_provider", srcs = ["libvehicle_state_provider.so"], hdrs = ["vehicle_state_provider.h"], deps = [ "//cyber", "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common/configs:config_gflags", "//modules/common/math", "//modules/common/status", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "@eigen", "@com_google_absl//:absl", ], ) cc_test( name = "vehicle_state_provider_test", size = "small", srcs = ["vehicle_state_provider_test.cc"], data = [ ":testdata", ], deps = [ ":vehicle_state_provider", "//cyber", "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common/configs:config_gflags", "@eigen", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/common/vehicle_state
apollo_public_repos/apollo/modules/common/vehicle_state/testdata/3_localization_result_1.pb.txt
header { timestamp_sec: 1173545122.22 module_name: "localization" sequence_num: 128 } pose { position { x: 357.51331791372041 y: 96.165912376788725 z: -31.983237908221781 } orientation { qx: 0.024015498296453403 qy: 0.0021656820647661572 qz: -0.99072964388722151 qw: -0.13369120534226134 } linear_velocity { x: -1.5626866011382312 y: -5.9852188341040344 z: 0.024798037277423912 } linear_acceleration { x: -0.68775567663756187 y: -0.079383290718229638 z: -0.43889982872693695 } angular_velocity { x: 0.0035469168217162248 y: -0.039127693784838637 z: -0.0079623083093763921 } heading: -1.8388082455104939 }
0
apollo_public_repos/apollo/modules/common/vehicle_state
apollo_public_repos/apollo/modules/common/vehicle_state/proto/vehicle_state.proto
syntax = "proto2"; package apollo.common; import "modules/common_msgs/chassis_msgs/chassis.proto"; import "modules/common_msgs/localization_msgs/pose.proto"; message VehicleState { optional double x = 1 [default = 0.0]; optional double y = 2 [default = 0.0]; optional double z = 3 [default = 0.0]; optional double timestamp = 4 [default = 0.0]; optional double roll = 5 [default = 0.0]; optional double pitch = 6 [default = 0.0]; optional double yaw = 7 [default = 0.0]; optional double heading = 8 [default = 0.0]; optional double kappa = 9 [default = 0.0]; optional double linear_velocity = 10 [default = 0.0]; optional double angular_velocity = 11 [default = 0.0]; optional double linear_acceleration = 12 [default = 0.0]; optional apollo.canbus.Chassis.GearPosition gear = 13; optional apollo.canbus.Chassis.DrivingMode driving_mode = 14; optional apollo.localization.Pose pose = 15; optional double steering_percentage = 16; }
0
apollo_public_repos/apollo/modules/common/vehicle_state
apollo_public_repos/apollo/modules/common/vehicle_state/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "vehicle_state_cc_proto", deps = [ ":vehicle_state_proto", ], ) proto_library( name = "vehicle_state_proto", srcs = ["vehicle_state.proto"], deps = [ "//modules/common_msgs/chassis_msgs:chassis_proto", "//modules/common_msgs/localization_msgs:pose_proto", ], ) py_proto_library( name = "vehicle_state_py_pb2", deps = [ ":vehicle_state_proto", "//modules/common_msgs/chassis_msgs:chassis_py_pb2", "//modules/common_msgs/localization_msgs:pose_py_pb2", ], ) install_files( name = "py_pb_common_vehicle_state", dest = "common/python/modules/common/vehicle_state/proto", files = [ "vehicle_state_py_pb2", ] )
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/kv_db/kv_db.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 <string> #include "modules/common/util/future.h" /** * @namespace apollo::common * @brief apollo::common */ namespace apollo { namespace common { /** * @class KVDB * * @brief Lightweight key-value database to store system-wide parameters. * We prefer keys like "apollo:data:commit_id". */ class KVDB { public: /** * @brief Store {key, value} to DB. * @return Success or not. */ static bool Put(std::string_view key, std::string_view value); /** * @brief Delete a key. * @return Success or not. */ static bool Delete(std::string_view key); /** * @brief Get value of a key. * @return An optional value. * Use `has_value()` to check if there is non-empty value. * Use `value()` to get real value. * Use `value_or("")` to get existing value or fallback to default. */ static std::optional<std::string> Get(std::string_view key); }; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/kv_db/kv_db.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/common/kv_db/kv_db.h" #include <sqlite3.h> #include "gflags/gflags.h" #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "modules/common/util/util.h" DEFINE_string(kv_db_path, "/apollo/data/kv_db.sqlite", "Path to Key-value DB file."); namespace apollo { namespace common { namespace { // Self-maintained sqlite instance. class SqliteWraper { public: static int Callback(void *data, int argc, char **argv, char **col_name) { if (data != nullptr) { std::string *data_str = static_cast<std::string *>(data); *data_str = argc > 0 ? argv[0] : ""; } return 0; } SqliteWraper() { // Open DB. if (sqlite3_open(FLAGS_kv_db_path.c_str(), &db_) != 0) { AERROR << "Can't open Key-Value database: " << sqlite3_errmsg(db_); Release(); return; } // Create table if it doesn't exist. static const char *kCreateTableSql = "CREATE TABLE IF NOT EXISTS key_value " "(key VARCHAR(128) PRIMARY KEY NOT NULL, value TEXT);"; if (!SQL(kCreateTableSql)) { Release(); } } ~SqliteWraper() { Release(); } bool SQL(std::string_view sql, std::string *value = nullptr) { AINFO << "Executing SQL: " << sql; if (db_ == nullptr) { AERROR << "DB is not open properly."; return false; } char *error = nullptr; if (sqlite3_exec(db_, sql.data(), Callback, value, &error) != SQLITE_OK) { AERROR << "Failed to execute SQL: " << error; sqlite3_free(error); return false; } return true; } private: void Release() { if (db_ != nullptr) { sqlite3_close(db_); db_ = nullptr; } } sqlite3 *db_ = nullptr; }; } // namespace bool KVDB::Put(std::string_view key, std::string_view value) { SqliteWraper sqlite; return sqlite.SQL( absl::StrCat("INSERT OR REPLACE INTO key_value (key, value) VALUES ('", key, "', '", value, "');")); } bool KVDB::Delete(std::string_view key) { SqliteWraper sqlite; return sqlite.SQL( absl::StrCat("DELETE FROM key_value WHERE key='", key, "';")); } std::optional<std::string> KVDB::Get(std::string_view key) { SqliteWraper sqlite; std::string value; const bool ret = sqlite.SQL( absl::StrCat("SELECT value FROM key_value WHERE key='", key, "';"), &value); if (ret && !value.empty()) { return value; } return {}; } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/kv_db/kv_db_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/common/kv_db/kv_db.h" #include <thread> #include "gtest/gtest.h" namespace apollo { namespace common { TEST(KVDBTest, CRUD) { EXPECT_TRUE(KVDB::Delete("test_key")); EXPECT_FALSE(KVDB::Get("test_key").has_value()); // Put EXPECT_TRUE(KVDB::Put("test_key", "val0")); EXPECT_EQ("val0", KVDB::Get("test_key").value()); // Update EXPECT_TRUE(KVDB::Put("test_key", "val1")); EXPECT_EQ("val1", KVDB::Get("test_key").value()); // Delete EXPECT_TRUE(KVDB::Delete("test_key")); EXPECT_FALSE(KVDB::Get("test_key").has_value()); } TEST(KVDBTest, MultiThreads) { static const int N_THREADS = 10; std::vector<std::unique_ptr<std::thread>> threads(N_THREADS); for (auto &th : threads) { th.reset(new std::thread([]() { KVDB::Delete("test_key"); KVDB::Put("test_key", "val0"); KVDB::Get("test_key"); })); } for (auto &th : threads) { th->join(); } } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/kv_db/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") install( name = "install", library_dest = "common/lib", data_dest = "common", runtime_dest = "common/bin", targets = [ ":libkv_db.so", ":kv_db_tool", ], visibility = ["//visibility:public"], ) cc_binary( name = "libkv_db.so", srcs = [ "kv_db.cc", "kv_db.h", ], linkshared = True, linkstatic = True, deps = [ "//cyber:cyber", "//modules/common/util", "//modules/common/util:util_tool", "@com_github_gflags_gflags//:gflags", "@com_google_absl//:absl", "@sqlite3", ], ) cc_library( name = "kv_db", srcs = ["libkv_db.so"], hdrs = ["kv_db.h"], deps = [ "//cyber", "//modules/common/util", "//modules/common/util:util_tool", "@com_github_gflags_gflags//:gflags", "@com_google_absl//:absl", "@sqlite3", ], visibility = ["//visibility:public"], ) cc_test( name = "kv_db_test", size = "small", srcs = ["kv_db_test.cc"], deps = [ ":kv_db", "@com_google_googletest//:gtest_main", ], ) cc_binary( name = "kv_db_tool", srcs = ["kv_db_tool.cc"], deps = [ ":kv_db", "//cyber", "@com_github_gflags_gflags//:gflags", ], ) cpplint()
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/kv_db/kv_db_tool.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/common/kv_db/kv_db.h" #include <iostream> #include "gflags/gflags.h" #include "cyber/common/log.h" DEFINE_string(op, "get", "Operation to execute, should be put, get or del."); DEFINE_string(key, "", "The key to query."); DEFINE_string(value, "", "The value to query."); using apollo::common::KVDB; int main(int32_t argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_key.empty()) { AFATAL << "Please specify --key."; } if (FLAGS_op == "get") { std::cout << KVDB::Get(FLAGS_key).value() << std::endl; } else if (FLAGS_op == "put") { if (FLAGS_value.empty()) { AFATAL << "Please specify --value."; } std::cout << KVDB::Put(FLAGS_key, FLAGS_value) << std::endl; } else if (FLAGS_op == "del") { std::cout << KVDB::Delete(FLAGS_key) << std::endl; } else { AFATAL << "Unknown op: " << FLAGS_op; } return 0; }
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/latency_recorder/latency_recorder.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 <mutex> #include <string> #include "cyber/cyber.h" #include "modules/common/latency_recorder/proto/latency_record.pb.h" namespace apollo { namespace common { class LatencyRecorder { public: explicit LatencyRecorder(const std::string& module_name); void AppendLatencyRecord(const uint64_t message_id, const apollo::cyber::Time& begin_time, const apollo::cyber::Time& end_time); private: LatencyRecorder() = default; std::shared_ptr<apollo::cyber::Writer<LatencyRecordMap>> CreateWriter(); void PublishLatencyRecords( const std::shared_ptr<apollo::cyber::Writer<LatencyRecordMap>>& writer); std::string module_name_; std::mutex mutex_; std::unique_ptr<LatencyRecordMap> records_; apollo::cyber::Time current_time_; std::shared_ptr<apollo::cyber::Node> node_; }; } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/latency_recorder/latency_recorder.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/common/latency_recorder/latency_recorder.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/message_util.h" using apollo::cyber::Clock; using apollo::cyber::Time; namespace apollo { namespace common { LatencyRecorder::LatencyRecorder(const std::string& module_name) : module_name_(module_name) { records_.reset(new LatencyRecordMap); } void LatencyRecorder::AppendLatencyRecord(const uint64_t message_id, const Time& begin_time, const Time& end_time) { // TODO(michael): ALERT for now for trouble shooting, // CHECK_LT(begin_time, end_time) in the future to enforce the validation if (begin_time >= end_time) { // In Simulation mode, there might be large number of cases where // begin_time == end_time, reduce the error frequency in this mode static const int kErrorReduceBase = 1000; // FIXME(storypku): IsRealityMode|MockTime if (!cyber::common::GlobalData::Instance()->IsRealityMode()) { AERROR_EVERY(kErrorReduceBase) << "latency begin_time: " << begin_time << " >= end_time: " << end_time << ", " << kErrorReduceBase << " times"; return; } AERROR << "latency begin_time: " << begin_time << " >= end_time: " << end_time; return; } static auto writer = CreateWriter(); if (writer == nullptr || message_id == 0) { return; } std::lock_guard<std::mutex> lock(mutex_); auto* latency_record = records_->add_latency_records(); latency_record->set_begin_time(begin_time.ToNanosecond()); latency_record->set_end_time(end_time.ToNanosecond()); latency_record->set_message_id(message_id); const auto now = Clock::Now(); const apollo::cyber::Duration kPublishInterval(3.0); if (now - current_time_ > kPublishInterval) { PublishLatencyRecords(writer); current_time_ = now; } } std::shared_ptr<apollo::cyber::Writer<LatencyRecordMap>> LatencyRecorder::CreateWriter() { const std::string node_name_prefix = "latency_recorder"; if (module_name_.empty()) { AERROR << "missing module name for sending latency records"; return nullptr; } if (node_ == nullptr) { current_time_ = Clock::Now(); node_ = apollo::cyber::CreateNode(absl::StrCat( node_name_prefix, module_name_, current_time_.ToNanosecond())); if (node_ == nullptr) { AERROR << "unable to create node for latency recording"; return nullptr; } } return node_->CreateWriter<LatencyRecordMap>(FLAGS_latency_recording_topic); } void LatencyRecorder::PublishLatencyRecords( const std::shared_ptr<apollo::cyber::Writer<LatencyRecordMap>>& writer) { records_->set_module_name(module_name_); apollo::common::util::FillHeader("LatencyRecorderMap", records_.get()); writer->Write(*records_); records_.reset(new LatencyRecordMap); } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/latency_recorder/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") install( name = "install", library_dest = "common/lib", data_dest = "common", runtime_dest = "common/bin", targets = [ ":liblatency_recorder.so", ], visibility = ["//visibility:public"], ) cc_binary( name = "liblatency_recorder.so", srcs = [ "latency_recorder.cc", "latency_recorder.h", ], linkshared = True, linkstatic = True, deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/latency_recorder/proto:latency_record_cc_proto", "//modules/common/util:util_tool", ], ) cc_library( name = "latency_recorder", srcs = ["liblatency_recorder.so"], hdrs = ["latency_recorder.h"], deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/latency_recorder/proto:latency_record_cc_proto", "//modules/common/util:util_tool", ], visibility = ["//visibility:public"], ) cpplint()
0
apollo_public_repos/apollo/modules/common/latency_recorder
apollo_public_repos/apollo/modules/common/latency_recorder/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "latency_record_cc_proto", deps = [ ":latency_record_proto", ], ) proto_library( name = "latency_record_proto", srcs = ["latency_record.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ], ) py_proto_library( name = "latency_record_py_pb2", deps = [ ":latency_record_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ], ) install_files( name = "py_pb_common_latency_record", dest = "common/python/modules/common/latency_recorder/proto", files = [ "latency_record_py_pb2", ] )
0
apollo_public_repos/apollo/modules/common/latency_recorder
apollo_public_repos/apollo/modules/common/latency_recorder/proto/latency_record.proto
syntax = "proto2"; package apollo.common; import "modules/common_msgs/basic_msgs/header.proto"; message LatencyRecord { optional uint64 begin_time = 1; optional uint64 end_time = 2; optional uint64 message_id = 3; }; message LatencyRecordMap { optional apollo.common.Header header = 1; optional string module_name = 2; repeated LatencyRecord latency_records = 3; }; message LatencyStat { optional uint64 min_duration = 1 [default = 9223372036854775808]; // (1 << 63) optional uint64 max_duration = 2; optional uint64 aver_duration = 3; optional uint32 sample_size = 4; }; message LatencyTrack { message LatencyTrackMessage { optional string latency_name = 1; optional LatencyStat latency_stat = 2; } repeated LatencyTrackMessage latency_track = 1; } message LatencyReport { optional apollo.common.Header header = 1; optional LatencyTrack e2es_latency = 2; optional LatencyTrack modules_latency = 3; };
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/status/status.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #pragma once #include <string> #include "google/protobuf/descriptor.h" #include "modules/common_msgs/basic_msgs/error_code.pb.h" #include "modules/common/util/future.h" /** * @namespace apollo::common * @brief apollo::common */ namespace apollo { namespace common { /** * @class Status * * @brief A general class to denote the return status of an API call. It * can either be an OK status for success, or a failure status with error * message and error code enum. */ class Status { public: /** * @brief Create a status with the specified error code and msg as a * human-readable string containing more detailed information. * @param code the error code. * @param msg the message associated with the error. */ explicit Status(ErrorCode code = ErrorCode::OK, std::string_view msg = "") : code_(code), msg_(msg.data()) {} ~Status() = default; /** * @brief generate a success status. * @returns a success status */ static Status OK() { return Status(); } /** * @brief check whether the return status is OK. * @returns true if the code is ErrorCode::OK * false otherwise */ bool ok() const { return code_ == ErrorCode::OK; } /** * @brief get the error code * @returns the error code */ ErrorCode code() const { return code_; } /** * @brief defines the logic of testing if two Status are equal */ bool operator==(const Status &rh) const { return (this->code_ == rh.code_) && (this->msg_ == rh.msg_); } /** * @brief defines the logic of testing if two Status are unequal */ bool operator!=(const Status &rh) const { return !(*this == rh); } /** * @brief returns the error message of the status, empty if the status is OK. * @returns the error message */ const std::string &error_message() const { return msg_; } /** * @brief returns a string representation in a readable format. * @returns the string "OK" if success. * the internal error message otherwise. */ std::string ToString() const { if (ok()) { return "OK"; } return ErrorCode_Name(code_) + ": " + msg_; } /** * @brief save the error_code and error message to protobuf * @param the Status protobuf that will store the message. */ void Save(StatusPb *status_pb) { if (!status_pb) { return; } status_pb->set_error_code(code_); if (!msg_.empty()) { status_pb->set_msg(msg_); } } private: ErrorCode code_; std::string msg_; }; inline std::ostream &operator<<(std::ostream &os, const Status &s) { os << s.ToString(); return os; } } // namespace common } // namespace apollo
0
apollo_public_repos/apollo/modules/common
apollo_public_repos/apollo/modules/common/status/status_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/common/status/status.h" #include "gtest/gtest.h" namespace apollo { namespace common { TEST(Status, OK) { EXPECT_EQ(Status::OK().code(), ErrorCode::OK); EXPECT_EQ(Status::OK().error_message(), ""); EXPECT_EQ(Status::OK(), Status::OK()); EXPECT_EQ(Status::OK(), Status()); Status s; EXPECT_TRUE(s.ok()); } TEST(Status, Set) { Status status; status = Status(ErrorCode::CONTROL_ERROR, "Error message"); EXPECT_EQ(status.code(), ErrorCode::CONTROL_ERROR); EXPECT_EQ(status.error_message(), "Error message"); } TEST(Status, Copy) { Status a(ErrorCode::CONTROL_ERROR, "Error message"); Status b(a); EXPECT_EQ(a.ToString(), b.ToString()); } TEST(Status, Assign) { Status a(ErrorCode::CONTROL_ERROR, "Error message"); Status b; b = a; EXPECT_EQ(a.ToString(), b.ToString()); } TEST(Status, EqualsSame) { Status a(ErrorCode::CONTROL_ERROR, "Error message"); Status b(ErrorCode::CONTROL_ERROR, "Error message"); EXPECT_EQ(a, b); } TEST(Status, EqualsDifferentCode) { const Status a(ErrorCode::CONTROL_ERROR, "Error message"); const Status b(ErrorCode::CANBUS_ERROR, "Error message"); EXPECT_NE(a, b); } TEST(Status, EqualsDifferentMessage) { const Status a(ErrorCode::CONTROL_ERROR, "Error message1"); const Status b(ErrorCode::CONTROL_COMPUTE_ERROR, "Error message2"); EXPECT_NE(a, b); } TEST(Status, ToString) { EXPECT_EQ("OK", Status().ToString()); const Status a(ErrorCode::CONTROL_ERROR, "Error message"); EXPECT_EQ("CONTROL_ERROR: Error message", a.ToString()); } } // namespace common } // namespace apollo
0