Nav2 Navigation Stack - rolling  main
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  if (max_reachable_idx < 0) {continue;}
326 
327  // Bounded Euclidean search: closest path point within [0..max_reachable_idx]
328  Eigen::Index eucl_idx;
329  ((data.path.x.head(max_reachable_idx + 1) - traj_x_end(i)).square() +
330  (data.path.y.head(max_reachable_idx + 1) - traj_y_end(i)).square()).minCoeff(&eucl_idx);
331 
332  max_idx = std::max(max_idx, static_cast<int>(eucl_idx));
333 
334  // Early exit if we've already reached the end of the path
335  if (max_idx == n_cols - 1) {
336  break;
337  }
338  }
339 
340  return static_cast<size_t>(max_idx);
341 }
342 
347 inline void setPathFurthestPointIfNotSet(CriticData & data)
348 {
349  if (!data.furthest_reached_path_point) {
350  data.furthest_reached_path_point = findPathFurthestReachedPoint(data);
351  }
352 }
353 
358 inline void findPathCosts(
359  CriticData & data,
360  std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
361 {
362  auto * costmap = costmap_ros->getCostmap();
363  unsigned int map_x, map_y;
364  const size_t path_segments_count = data.path.x.size() - 1;
365  data.path_pts_valid = std::vector<bool>(path_segments_count, false);
366  const bool tracking_unknown = costmap_ros->getLayeredCostmap()->isTrackingUnknown();
367  for (unsigned int idx = 0; idx < path_segments_count; idx++) {
368  if (!costmap->worldToMap(data.path.x(idx), data.path.y(idx), map_x, map_y)) {
369  (*data.path_pts_valid)[idx] = false;
370  continue;
371  }
372 
373  switch (costmap->getCost(map_x, map_y)) {
374  case (nav2_costmap_2d::LETHAL_OBSTACLE):
375  (*data.path_pts_valid)[idx] = false;
376  continue;
377  case (nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE):
378  (*data.path_pts_valid)[idx] = false;
379  continue;
380  case (nav2_costmap_2d::NO_INFORMATION):
381  (*data.path_pts_valid)[idx] = tracking_unknown ? true : false;
382  continue;
383  }
384 
385  (*data.path_pts_valid)[idx] = true;
386  }
387 }
388 
393 inline void setPathCostsIfNotSet(
394  CriticData & data,
395  std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
396 {
397  if (!data.path_pts_valid) {
398  findPathCosts(data, costmap_ros);
399  }
400 }
401 
410 inline float posePointAngle(
411  const geometry_msgs::msg::Pose & pose, double point_x, double point_y, bool forward_preference)
412 {
413  float pose_x = pose.position.x;
414  float pose_y = pose.position.y;
415  float pose_yaw = tf2::getYaw(pose.orientation);
416 
417  float yaw = atan2f(point_y - pose_y, point_x - pose_x);
418 
419  // If no preference for forward, return smallest angle either in heading or 180 of heading
420  if (!forward_preference) {
421  return std::min(
422  fabs(angles::shortest_angular_distance(yaw, pose_yaw)),
423  fabs(angles::shortest_angular_distance(yaw, angles::normalize_angle(pose_yaw + M_PIF))));
424  }
425 
426  return fabs(angles::shortest_angular_distance(yaw, pose_yaw));
427 }
428 
437 inline float posePointAngle(
438  const geometry_msgs::msg::Pose & pose,
439  double point_x, double point_y, double point_yaw)
440 {
441  float pose_x = static_cast<float>(pose.position.x);
442  float pose_y = static_cast<float>(pose.position.y);
443  float pose_yaw = static_cast<float>(tf2::getYaw(pose.orientation));
444 
445  float yaw = atan2f(static_cast<float>(point_y) - pose_y, static_cast<float>(point_x) - pose_x);
446 
447  if (fabs(angles::shortest_angular_distance(yaw, static_cast<float>(point_yaw))) > M_PIF_2) {
448  yaw = angles::normalize_angle(yaw + M_PIF);
449  }
450 
451  return fabs(angles::shortest_angular_distance(yaw, pose_yaw));
452 }
453 
460 inline void savitskyGolayFilter(
461  models::ControlSequence & control_sequence,
462  std::array<mppi::models::Control, 4> & control_history,
463  const models::OptimizerSettings & settings)
464 {
465  // Savitzky-Golay filter coefficients, 9-point window
466  Eigen::Array<float, 9, 1> filter;
467  if (settings.sgf_order == 1) {
468  // Degree-1 (linear): uniform moving average with more aggressive smoothing
469  filter = {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f};
470  filter /= 9.0f;
471  } else {
472  // Degree-2 (quadratic): standard 9-point SG coefficients
473  filter = {-21.0f, 14.0f, 39.0f, 54.0f, 59.0f, 54.0f, 39.0f, 14.0f, -21.0f};
474  filter /= 231.0f;
475  }
476 
477  // Too short to smooth meaningfully
478  const unsigned int num_sequences = control_sequence.vx.size() - 1;
479  if (num_sequences < 20) {
480  return;
481  }
482 
483  auto applyFilter = [&](const Eigen::Array<float, 9, 1> & data) -> float {
484  return (data * filter).eval().sum();
485  };
486 
487  auto applyFilterOverAxis =
488  [&](Eigen::ArrayXf & sequence, const Eigen::ArrayXf & initial_sequence,
489  const float hist_0, const float hist_1, const float hist_2, const float hist_3) -> void
490  {
491  float pt_m4 = hist_0;
492  float pt_m3 = hist_1;
493  float pt_m2 = hist_2;
494  float pt_m1 = hist_3;
495  float pt = initial_sequence(0);
496  float pt_p1 = initial_sequence(1);
497  float pt_p2 = initial_sequence(2);
498  float pt_p3 = initial_sequence(3);
499  float pt_p4 = initial_sequence(4);
500 
501  for (unsigned int idx = 0; idx != num_sequences; idx++) {
502  sequence(idx) = applyFilter({pt_m4, pt_m3, pt_m2, pt_m1, pt, pt_p1, pt_p2, pt_p3, pt_p4});
503  pt_m4 = pt_m3;
504  pt_m3 = pt_m2;
505  pt_m2 = pt_m1;
506  pt_m1 = pt;
507  pt = pt_p1;
508  pt_p1 = pt_p2;
509  pt_p2 = pt_p3;
510  pt_p3 = pt_p4;
511 
512  if (idx + 5 < num_sequences) {
513  pt_p4 = initial_sequence(idx + 5);
514  } else {
515  // Return the last point
516  pt_p4 = initial_sequence(num_sequences);
517  }
518  }
519  };
520 
521  // Filter trajectories
522  const models::ControlSequence initial_control_sequence = control_sequence;
523  applyFilterOverAxis(
524  control_sequence.vx, initial_control_sequence.vx, control_history[0].vx,
525  control_history[1].vx, control_history[2].vx, control_history[3].vx);
526  applyFilterOverAxis(
527  control_sequence.vy, initial_control_sequence.vy, control_history[0].vy,
528  control_history[1].vy, control_history[2].vy, control_history[3].vy);
529  applyFilterOverAxis(
530  control_sequence.wz, initial_control_sequence.wz, control_history[0].wz,
531  control_history[1].wz, control_history[2].wz, control_history[3].wz);
532 
533  // Update control history
534  unsigned int offset = settings.shift_control_sequence ? 1 : 0;
535  control_history[0] = control_history[1];
536  control_history[1] = control_history[2];
537  control_history[2] = control_history[3];
538  control_history[3] = {
539  control_sequence.vx(offset),
540  control_sequence.vy(offset),
541  control_sequence.wz(offset)};
542 }
543 
550 inline unsigned int findClosestPathPt(
551  const std::vector<float> & vec, const float dist, const unsigned int init = 0u)
552 {
553  float distim1 = init != 0u ? vec[init] : 0.0f; // First is 0, no accumulated distance yet
554  float disti = 0.0f;
555  const unsigned int size = vec.size();
556  for (unsigned int i = init + 1; i != size; i++) {
557  disti = vec[i];
558  if (disti > dist) {
559  if (i > 0 && dist - distim1 < disti - dist) {
560  return i - 1;
561  }
562  return i;
563  }
564  distim1 = disti;
565  }
566  return size - 1;
567 }
568 
569 // A struct to hold pose data in floating point resolution
570 struct Pose2D
571 {
572  float x, y, theta;
573 };
574 
582 inline void shiftColumnsByOnePlace(Eigen::Ref<Eigen::ArrayXXf> e, int direction)
583 {
584  int size = e.size();
585  if (size == 1) {return;}
586  if (abs(direction) != 1) {
587  throw std::logic_error("Invalid direction, only 1 and -1 are valid values.");
588  }
589 
590  if ((e.cols() == 1 || e.rows() == 1) && size > 1) {
591  auto start_ptr = direction == 1 ? e.data() + size - 2 : e.data() + 1;
592  auto end_ptr = direction == 1 ? e.data() : e.data() + size - 1;
593  while (start_ptr != end_ptr) {
594  *(start_ptr + direction) = *start_ptr;
595  start_ptr -= direction;
596  }
597  *(start_ptr + direction) = *start_ptr;
598  } else {
599  auto start_ptr = direction == 1 ? e.data() + size - 2 * e.rows() : e.data() + e.rows();
600  auto end_ptr = direction == 1 ? e.data() : e.data() + size - e.rows();
601  auto span = e.rows();
602  while (start_ptr != end_ptr) {
603  std::copy(start_ptr, start_ptr + span, start_ptr + direction * span);
604  start_ptr -= (direction * span);
605  }
606  std::copy(start_ptr, start_ptr + span, start_ptr + direction * span);
607  }
608 }
609 
617 inline auto normalize_yaws_between_points(
618  const Eigen::Ref<const Eigen::ArrayXf> & last_yaws,
619  const Eigen::Ref<const Eigen::ArrayXf> & yaw_between_points)
620 {
621  Eigen::ArrayXf yaws = utils::shortest_angular_distance(
622  last_yaws, yaw_between_points).abs();
623  int size = yaws.size();
624  Eigen::ArrayXf yaws_between_points_corrected(size);
625  for (int i = 0; i != size; i++) {
626  const float & yaw_between_point = yaw_between_points[i];
627  yaws_between_points_corrected[i] = yaws[i] < M_PIF_2 ?
628  yaw_between_point : angles::normalize_angle(yaw_between_point + M_PIF);
629  }
630  return yaws_between_points_corrected;
631 }
632 
639 inline auto normalize_yaws_between_points(
640  const float goal_yaw, const Eigen::Ref<const Eigen::ArrayXf> & yaw_between_points)
641 {
642  int size = yaw_between_points.size();
643  Eigen::ArrayXf yaws_between_points_corrected(size);
644  for (int i = 0; i != size; i++) {
645  const float & yaw_between_point = yaw_between_points[i];
646  yaws_between_points_corrected[i] = fabs(
647  angles::normalize_angle(yaw_between_point - goal_yaw)) < M_PIF_2 ?
648  yaw_between_point : angles::normalize_angle(yaw_between_point + M_PIF);
649  }
650  return yaws_between_points_corrected;
651 }
652 
659 inline float clamp(
660  const float lower_bound, const float upper_bound, const float input)
661 {
662  return std::min(upper_bound, std::max(input, lower_bound));
663 }
664 
674 inline float clampVelocityByAccel(
675  const float last_vel, const float curr_vel,
676  const float min_delta, const float max_delta)
677 {
678  if (last_vel >= 0) {
679  return clamp(last_vel + min_delta, last_vel + max_delta, curr_vel);
680  }
681  return clamp(last_vel - max_delta, last_vel - min_delta, curr_vel);
682 }
683 
684 } // namespace mppi::utils
685 
686 #endif // NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
void reset(unsigned int size)
Reset path data.
Definition: path.hpp:36