Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
utils.hpp
1 // Copyright (c) 2022 Samsung Research America, @artofnothingness Alexey Budyakov
2 // Copyright (c) 2023 Open Navigation LLC
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #ifndef NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
17 #define NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
18 
19 #include <Eigen/Dense>
20 
21 #include <algorithm>
22 #include <chrono>
23 #include <string>
24 #include <limits>
25 #include <memory>
26 #include <vector>
27 
28 #include "angles/angles.h"
29 
30 #include "tf2/utils.hpp"
31 #include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
32 
33 #include "geometry_msgs/msg/twist_stamped.hpp"
34 #include "nav_msgs/msg/path.hpp"
35 #include "nav_msgs/msg/trajectory.hpp"
36 #include "visualization_msgs/msg/marker_array.hpp"
37 
38 #include "rclcpp/rclcpp.hpp"
39 #include "rclcpp_lifecycle/lifecycle_node.hpp"
40 
41 #include "nav2_ros_common/node_utils.hpp"
42 #include "nav2_core/goal_checker.hpp"
43 
44 #include "nav2_mppi_controller/models/optimizer_settings.hpp"
45 #include "nav2_mppi_controller/models/control_sequence.hpp"
46 #include "nav2_mppi_controller/models/path.hpp"
47 #include "builtin_interfaces/msg/time.hpp"
48 #include "nav2_mppi_controller/critic_data.hpp"
49 
50 #define M_PIF 3.141592653589793238462643383279502884e+00F
51 #define M_PIF_2 1.5707963267948966e+00F
52 
53 namespace mppi::utils
54 {
62 inline geometry_msgs::msg::Pose createPose(double x, double y, double z)
63 {
64  geometry_msgs::msg::Pose pose;
65  pose.position.x = x;
66  pose.position.y = y;
67  pose.position.z = z;
68  pose.orientation.w = 1;
69  pose.orientation.x = 0;
70  pose.orientation.y = 0;
71  pose.orientation.z = 0;
72  return pose;
73 }
74 
82 inline geometry_msgs::msg::Vector3 createScale(double x, double y, double z)
83 {
84  geometry_msgs::msg::Vector3 scale;
85  scale.x = x;
86  scale.y = y;
87  scale.z = z;
88  return scale;
89 }
90 
99 inline std_msgs::msg::ColorRGBA createColor(float r, float g, float b, float a)
100 {
101  std_msgs::msg::ColorRGBA color;
102  color.r = r;
103  color.g = g;
104  color.b = b;
105  color.a = a;
106  return color;
107 }
108 
118 inline visualization_msgs::msg::Marker createMarker(
119  int id, const geometry_msgs::msg::Pose & pose, const geometry_msgs::msg::Vector3 & scale,
120  const std_msgs::msg::ColorRGBA & color, const std::string & frame_id, const std::string & ns)
121 {
122  using visualization_msgs::msg::Marker;
123  Marker marker;
124  marker.header.frame_id = frame_id;
125  marker.header.stamp = rclcpp::Time(0, 0);
126  marker.ns = ns;
127  marker.id = id;
128  marker.type = Marker::SPHERE;
129  marker.action = Marker::ADD;
130 
131  marker.pose = pose;
132  marker.scale = scale;
133  marker.color = color;
134  return marker;
135 }
136 
144 inline geometry_msgs::msg::TwistStamped toTwistStamped(
145  float vx, float wz, const builtin_interfaces::msg::Time & stamp, const std::string & frame)
146 {
147  geometry_msgs::msg::TwistStamped twist;
148  twist.header.frame_id = frame;
149  twist.header.stamp = stamp;
150  twist.twist.linear.x = vx;
151  twist.twist.angular.z = wz;
152 
153  return twist;
154 }
155 
164 inline geometry_msgs::msg::TwistStamped toTwistStamped(
165  float vx, float vy, float wz, const builtin_interfaces::msg::Time & stamp,
166  const std::string & frame)
167 {
168  auto twist = toTwistStamped(vx, wz, stamp, frame);
169  twist.twist.linear.y = vy;
170 
171  return twist;
172 }
173 
174 inline std::unique_ptr<nav_msgs::msg::Trajectory> toTrajectoryMsg(
175  const Eigen::ArrayXXf & trajectory,
176  const models::ControlSequence & control_sequence,
177  const double & model_dt,
178  const std_msgs::msg::Header & header)
179 {
180  auto trajectory_msg = std::make_unique<nav_msgs::msg::Trajectory>();
181  trajectory_msg->header = header;
182  trajectory_msg->points.resize(trajectory.rows());
183 
184  for (int i = 0; i < trajectory.rows(); ++i) {
185  auto & curr_pt = trajectory_msg->points[i];
186  curr_pt.header.frame_id = header.frame_id;
187  curr_pt.header.stamp = header.stamp + rclcpp::Duration::from_seconds(i * model_dt);
188  curr_pt.pose.position.x = trajectory(i, 0);
189  curr_pt.pose.position.y = trajectory(i, 1);
190  tf2::Quaternion quat;
191  quat.setRPY(0.0, 0.0, trajectory(i, 2));
192  curr_pt.pose.orientation = tf2::toMsg(quat);
193  curr_pt.velocity.linear.x = control_sequence.vx(i);
194  curr_pt.velocity.angular.z = control_sequence.wz(i);
195  if (control_sequence.vy.size() > 0) {
196  curr_pt.velocity.linear.y = control_sequence.vy(i);
197  }
198  }
199 
200  return trajectory_msg;
201 }
202 
208 inline models::Path toTensor(const nav_msgs::msg::Path & path)
209 {
210  auto result = models::Path{};
211  result.reset(path.poses.size());
212 
213  for (size_t i = 0; i < path.poses.size(); ++i) {
214  result.x(i) = path.poses[i].pose.position.x;
215  result.y(i) = path.poses[i].pose.position.y;
216  result.yaws(i) = tf2::getYaw(path.poses[i].pose.orientation);
217  }
218 
219  return result;
220 }
221 
227 inline geometry_msgs::msg::Pose getLastPathPose(const models::Path & path)
228 {
229  const unsigned int path_last_idx = path.x.size() - 1;
230 
231  auto last_orientation = path.yaws(path_last_idx);
232 
233  tf2::Quaternion pose_orientation;
234  pose_orientation.setRPY(0.0, 0.0, last_orientation);
235 
236  geometry_msgs::msg::Pose pathPose;
237  pathPose.position.x = path.x(path_last_idx);
238  pathPose.position.y = path.y(path_last_idx);
239  pathPose.orientation.x = pose_orientation.x();
240  pathPose.orientation.y = pose_orientation.y();
241  pathPose.orientation.z = pose_orientation.z();
242  pathPose.orientation.w = pose_orientation.w();
243 
244  return pathPose;
245 }
246 
254 template<typename T>
255 auto normalize_angles(const T & angles)
256 {
257  return (angles + M_PIF).unaryExpr(
258  [&](const float x) {
259  float remainder = std::fmod(x, 2.0f * M_PIF);
260  return remainder < 0.0f ? remainder + M_PIF : remainder - M_PIF;
261  });
262 }
263 
277 template<typename F, typename T>
278 auto shortest_angular_distance(
279  const F & from,
280  const T & to)
281 {
282  return normalize_angles(to - from);
283 }
284 
292 inline size_t findPathFurthestReachedPoint(const CriticData & data)
293 {
294  const int traj_cols = data.trajectories.x.cols();
295  const int n_rows = static_cast<int>(data.trajectories.x.rows());
296  const int n_cols = static_cast<int>(data.path.x.size());
297 
298  // Cumulative arc-lengths along the reference path
299  std::vector<float> path_integrated_dists(n_cols, 0.0f);
300  for (int i = 1; i < n_cols; ++i) {
301  const float dx = data.path.x(i) - data.path.x(i - 1);
302  const float dy = data.path.y(i) - data.path.y(i - 1);
303  path_integrated_dists[i] = path_integrated_dists[i - 1] + sqrtf(dx * dx + dy * dy);
304  }
305 
306  // Arc-length of all candidate trajectories
307  const Eigen::ArrayXf traj_integrated_dists =
308  ((data.trajectories.x.rightCols(traj_cols - 1) -
309  data.trajectories.x.leftCols(traj_cols - 1)).square() +
310  (data.trajectories.y.rightCols(traj_cols - 1) -
311  data.trajectories.y.leftCols(traj_cols - 1)).square())
312  .sqrt().rowwise().sum();
313 
314  const auto & traj_x_end = data.trajectories.x.col(traj_cols - 1);
315  const auto & traj_y_end = data.trajectories.y.col(traj_cols - 1);
316 
317  int max_idx = 0;
318  for (int i = 0; i < n_rows; ++i) {
319  int max_reachable_idx = static_cast<int>(
320  std::lower_bound(
321  path_integrated_dists.begin(), path_integrated_dists.end(),
322  traj_integrated_dists(i)) - path_integrated_dists.begin());
323  max_reachable_idx = std::min(max_reachable_idx, n_cols - 1);
324 
325  // Bounded Euclidean search: closest path point within [0..max_reachable_idx]
326  Eigen::Index eucl_idx;
327  ((data.path.x.head(max_reachable_idx + 1) - traj_x_end(i)).square() +
328  (data.path.y.head(max_reachable_idx + 1) - traj_y_end(i)).square()).minCoeff(&eucl_idx);
329 
330  max_idx = std::max(max_idx, static_cast<int>(eucl_idx));
331 
332  // Early exit if we've already reached the end of the path
333  if (max_idx == n_cols - 1) {
334  break;
335  }
336  }
337 
338  return static_cast<size_t>(max_idx);
339 }
340 
345 inline void setPathFurthestPointIfNotSet(CriticData & data)
346 {
347  if (!data.furthest_reached_path_point) {
348  data.furthest_reached_path_point = findPathFurthestReachedPoint(data);
349  }
350 }
351 
356 inline void findPathCosts(
357  CriticData & data,
358  std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
359 {
360  auto * costmap = costmap_ros->getCostmap();
361  unsigned int map_x, map_y;
362  const size_t path_segments_count = data.path.x.size() - 1;
363  data.path_pts_valid = std::vector<bool>(path_segments_count, false);
364  const bool tracking_unknown = costmap_ros->getLayeredCostmap()->isTrackingUnknown();
365  for (unsigned int idx = 0; idx < path_segments_count; idx++) {
366  if (!costmap->worldToMap(data.path.x(idx), data.path.y(idx), map_x, map_y)) {
367  (*data.path_pts_valid)[idx] = false;
368  continue;
369  }
370 
371  switch (costmap->getCost(map_x, map_y)) {
372  case (nav2_costmap_2d::LETHAL_OBSTACLE):
373  (*data.path_pts_valid)[idx] = false;
374  continue;
375  case (nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE):
376  (*data.path_pts_valid)[idx] = false;
377  continue;
378  case (nav2_costmap_2d::NO_INFORMATION):
379  (*data.path_pts_valid)[idx] = tracking_unknown ? true : false;
380  continue;
381  }
382 
383  (*data.path_pts_valid)[idx] = true;
384  }
385 }
386 
391 inline void setPathCostsIfNotSet(
392  CriticData & data,
393  std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
394 {
395  if (!data.path_pts_valid) {
396  findPathCosts(data, costmap_ros);
397  }
398 }
399 
408 inline float posePointAngle(
409  const geometry_msgs::msg::Pose & pose, double point_x, double point_y, bool forward_preference)
410 {
411  float pose_x = pose.position.x;
412  float pose_y = pose.position.y;
413  float pose_yaw = tf2::getYaw(pose.orientation);
414 
415  float yaw = atan2f(point_y - pose_y, point_x - pose_x);
416 
417  // If no preference for forward, return smallest angle either in heading or 180 of heading
418  if (!forward_preference) {
419  return std::min(
420  fabs(angles::shortest_angular_distance(yaw, pose_yaw)),
421  fabs(angles::shortest_angular_distance(yaw, angles::normalize_angle(pose_yaw + M_PIF))));
422  }
423 
424  return fabs(angles::shortest_angular_distance(yaw, pose_yaw));
425 }
426 
435 inline float posePointAngle(
436  const geometry_msgs::msg::Pose & pose,
437  double point_x, double point_y, double point_yaw)
438 {
439  float pose_x = static_cast<float>(pose.position.x);
440  float pose_y = static_cast<float>(pose.position.y);
441  float pose_yaw = static_cast<float>(tf2::getYaw(pose.orientation));
442 
443  float yaw = atan2f(static_cast<float>(point_y) - pose_y, static_cast<float>(point_x) - pose_x);
444 
445  if (fabs(angles::shortest_angular_distance(yaw, static_cast<float>(point_yaw))) > M_PIF_2) {
446  yaw = angles::normalize_angle(yaw + M_PIF);
447  }
448 
449  return fabs(angles::shortest_angular_distance(yaw, pose_yaw));
450 }
451 
458 inline void savitskyGolayFilter(
459  models::ControlSequence & control_sequence,
460  std::array<mppi::models::Control, 4> & control_history,
461  const models::OptimizerSettings & settings)
462 {
463  // Savitzky-Golay filter coefficients, 9-point window
464  Eigen::Array<float, 9, 1> filter;
465  if (settings.sgf_order == 1) {
466  // Degree-1 (linear): uniform moving average with more aggressive smoothing
467  filter = {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f};
468  filter /= 9.0f;
469  } else {
470  // Degree-2 (quadratic): standard 9-point SG coefficients
471  filter = {-21.0f, 14.0f, 39.0f, 54.0f, 59.0f, 54.0f, 39.0f, 14.0f, -21.0f};
472  filter /= 231.0f;
473  }
474 
475  // Too short to smooth meaningfully
476  const unsigned int num_sequences = control_sequence.vx.size() - 1;
477  if (num_sequences < 20) {
478  return;
479  }
480 
481  auto applyFilter = [&](const Eigen::Array<float, 9, 1> & data) -> float {
482  return (data * filter).eval().sum();
483  };
484 
485  auto applyFilterOverAxis =
486  [&](Eigen::ArrayXf & sequence, const Eigen::ArrayXf & initial_sequence,
487  const float hist_0, const float hist_1, const float hist_2, const float hist_3) -> void
488  {
489  float pt_m4 = hist_0;
490  float pt_m3 = hist_1;
491  float pt_m2 = hist_2;
492  float pt_m1 = hist_3;
493  float pt = initial_sequence(0);
494  float pt_p1 = initial_sequence(1);
495  float pt_p2 = initial_sequence(2);
496  float pt_p3 = initial_sequence(3);
497  float pt_p4 = initial_sequence(4);
498 
499  for (unsigned int idx = 0; idx != num_sequences; idx++) {
500  sequence(idx) = applyFilter({pt_m4, pt_m3, pt_m2, pt_m1, pt, pt_p1, pt_p2, pt_p3, pt_p4});
501  pt_m4 = pt_m3;
502  pt_m3 = pt_m2;
503  pt_m2 = pt_m1;
504  pt_m1 = pt;
505  pt = pt_p1;
506  pt_p1 = pt_p2;
507  pt_p2 = pt_p3;
508  pt_p3 = pt_p4;
509 
510  if (idx + 5 < num_sequences) {
511  pt_p4 = initial_sequence(idx + 5);
512  } else {
513  // Return the last point
514  pt_p4 = initial_sequence(num_sequences);
515  }
516  }
517  };
518 
519  // Filter trajectories
520  const models::ControlSequence initial_control_sequence = control_sequence;
521  applyFilterOverAxis(
522  control_sequence.vx, initial_control_sequence.vx, control_history[0].vx,
523  control_history[1].vx, control_history[2].vx, control_history[3].vx);
524  applyFilterOverAxis(
525  control_sequence.vy, initial_control_sequence.vy, control_history[0].vy,
526  control_history[1].vy, control_history[2].vy, control_history[3].vy);
527  applyFilterOverAxis(
528  control_sequence.wz, initial_control_sequence.wz, control_history[0].wz,
529  control_history[1].wz, control_history[2].wz, control_history[3].wz);
530 
531  // Update control history
532  unsigned int offset = settings.shift_control_sequence ? 1 : 0;
533  control_history[0] = control_history[1];
534  control_history[1] = control_history[2];
535  control_history[2] = control_history[3];
536  control_history[3] = {
537  control_sequence.vx(offset),
538  control_sequence.vy(offset),
539  control_sequence.wz(offset)};
540 }
541 
548 inline unsigned int findClosestPathPt(
549  const std::vector<float> & vec, const float dist, const unsigned int init = 0u)
550 {
551  float distim1 = init != 0u ? vec[init] : 0.0f; // First is 0, no accumulated distance yet
552  float disti = 0.0f;
553  const unsigned int size = vec.size();
554  for (unsigned int i = init + 1; i != size; i++) {
555  disti = vec[i];
556  if (disti > dist) {
557  if (i > 0 && dist - distim1 < disti - dist) {
558  return i - 1;
559  }
560  return i;
561  }
562  distim1 = disti;
563  }
564  return size - 1;
565 }
566 
567 // A struct to hold pose data in floating point resolution
568 struct Pose2D
569 {
570  float x, y, theta;
571 };
572 
580 inline void shiftColumnsByOnePlace(Eigen::Ref<Eigen::ArrayXXf> e, int direction)
581 {
582  int size = e.size();
583  if (size == 1) {return;}
584  if (abs(direction) != 1) {
585  throw std::logic_error("Invalid direction, only 1 and -1 are valid values.");
586  }
587 
588  if ((e.cols() == 1 || e.rows() == 1) && size > 1) {
589  auto start_ptr = direction == 1 ? e.data() + size - 2 : e.data() + 1;
590  auto end_ptr = direction == 1 ? e.data() : e.data() + size - 1;
591  while (start_ptr != end_ptr) {
592  *(start_ptr + direction) = *start_ptr;
593  start_ptr -= direction;
594  }
595  *(start_ptr + direction) = *start_ptr;
596  } else {
597  auto start_ptr = direction == 1 ? e.data() + size - 2 * e.rows() : e.data() + e.rows();
598  auto end_ptr = direction == 1 ? e.data() : e.data() + size - e.rows();
599  auto span = e.rows();
600  while (start_ptr != end_ptr) {
601  std::copy(start_ptr, start_ptr + span, start_ptr + direction * span);
602  start_ptr -= (direction * span);
603  }
604  std::copy(start_ptr, start_ptr + span, start_ptr + direction * span);
605  }
606 }
607 
615 inline auto normalize_yaws_between_points(
616  const Eigen::Ref<const Eigen::ArrayXf> & last_yaws,
617  const Eigen::Ref<const Eigen::ArrayXf> & yaw_between_points)
618 {
619  Eigen::ArrayXf yaws = utils::shortest_angular_distance(
620  last_yaws, yaw_between_points).abs();
621  int size = yaws.size();
622  Eigen::ArrayXf yaws_between_points_corrected(size);
623  for (int i = 0; i != size; i++) {
624  const float & yaw_between_point = yaw_between_points[i];
625  yaws_between_points_corrected[i] = yaws[i] < M_PIF_2 ?
626  yaw_between_point : angles::normalize_angle(yaw_between_point + M_PIF);
627  }
628  return yaws_between_points_corrected;
629 }
630 
637 inline auto normalize_yaws_between_points(
638  const float goal_yaw, const Eigen::Ref<const Eigen::ArrayXf> & yaw_between_points)
639 {
640  int size = yaw_between_points.size();
641  Eigen::ArrayXf yaws_between_points_corrected(size);
642  for (int i = 0; i != size; i++) {
643  const float & yaw_between_point = yaw_between_points[i];
644  yaws_between_points_corrected[i] = fabs(
645  angles::normalize_angle(yaw_between_point - goal_yaw)) < M_PIF_2 ?
646  yaw_between_point : angles::normalize_angle(yaw_between_point + M_PIF);
647  }
648  return yaws_between_points_corrected;
649 }
650 
657 inline float clamp(
658  const float lower_bound, const float upper_bound, const float input)
659 {
660  return std::min(upper_bound, std::max(input, lower_bound));
661 }
662 
672 inline float clampVelocityByAccel(
673  const float last_vel, const float curr_vel,
674  const float min_delta, const float max_delta)
675 {
676  if (last_vel >= 0) {
677  return clamp(last_vel + min_delta, last_vel + max_delta, curr_vel);
678  }
679  return clamp(last_vel - max_delta, last_vel - min_delta, curr_vel);
680 }
681 
682 } // namespace mppi::utils
683 
684 #endif // NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
void reset(unsigned int size)
Reset path data.
Definition: path.hpp:36