16 #ifndef NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
17 #define NAV2_MPPI_CONTROLLER__TOOLS__UTILS_HPP_
26 #include <xtensor/xarray.hpp>
27 #include <xtensor/xnorm.hpp>
28 #include <xtensor/xmath.hpp>
29 #include <xtensor/xview.hpp>
31 #include "angles/angles.h"
33 #include "tf2/utils.h"
34 #include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
36 #include "geometry_msgs/msg/twist_stamped.hpp"
37 #include "nav_msgs/msg/path.hpp"
38 #include "visualization_msgs/msg/marker_array.hpp"
40 #include "rclcpp/rclcpp.hpp"
41 #include "rclcpp_lifecycle/lifecycle_node.hpp"
43 #include "nav2_util/node_utils.hpp"
44 #include "nav2_core/goal_checker.hpp"
46 #include "nav2_mppi_controller/models/optimizer_settings.hpp"
47 #include "nav2_mppi_controller/models/control_sequence.hpp"
48 #include "nav2_mppi_controller/models/path.hpp"
49 #include "builtin_interfaces/msg/time.hpp"
50 #include "nav2_mppi_controller/critic_data.hpp"
54 using xt::evaluation_strategy::immediate;
63 inline geometry_msgs::msg::Pose createPose(
double x,
double y,
double z)
65 geometry_msgs::msg::Pose pose;
69 pose.orientation.w = 1;
70 pose.orientation.x = 0;
71 pose.orientation.y = 0;
72 pose.orientation.z = 0;
83 inline geometry_msgs::msg::Vector3 createScale(
double x,
double y,
double z)
85 geometry_msgs::msg::Vector3 scale;
100 inline std_msgs::msg::ColorRGBA createColor(
float r,
float g,
float b,
float a)
102 std_msgs::msg::ColorRGBA color;
119 inline visualization_msgs::msg::Marker createMarker(
120 int id,
const geometry_msgs::msg::Pose & pose,
const geometry_msgs::msg::Vector3 & scale,
121 const std_msgs::msg::ColorRGBA & color,
const std::string & frame_id,
const std::string & ns)
123 using visualization_msgs::msg::Marker;
125 marker.header.frame_id = frame_id;
126 marker.header.stamp = rclcpp::Time(0, 0);
129 marker.type = Marker::SPHERE;
130 marker.action = Marker::ADD;
133 marker.scale = scale;
134 marker.color = color;
145 inline geometry_msgs::msg::TwistStamped toTwistStamped(
146 float vx,
float wz,
const builtin_interfaces::msg::Time & stamp,
const std::string & frame)
148 geometry_msgs::msg::TwistStamped twist;
149 twist.header.frame_id = frame;
150 twist.header.stamp = stamp;
151 twist.twist.linear.x = vx;
152 twist.twist.angular.z = wz;
165 inline geometry_msgs::msg::TwistStamped toTwistStamped(
166 float vx,
float vy,
float wz,
const builtin_interfaces::msg::Time & stamp,
167 const std::string & frame)
169 auto twist = toTwistStamped(vx, wz, stamp, frame);
170 twist.twist.linear.y = vy;
180 inline models::Path toTensor(
const nav_msgs::msg::Path & path)
182 auto result = models::Path{};
183 result.
reset(path.poses.size());
185 for (
size_t i = 0; i < path.poses.size(); ++i) {
186 result.x(i) = path.poses[i].pose.position.x;
187 result.y(i) = path.poses[i].pose.position.y;
188 result.yaws(i) = tf2::getYaw(path.poses[i].pose.orientation);
201 inline bool withinPositionGoalTolerance(
203 const geometry_msgs::msg::Pose & robot,
204 const geometry_msgs::msg::Pose & goal)
207 geometry_msgs::msg::Pose pose_tolerance;
208 geometry_msgs::msg::Twist velocity_tolerance;
209 goal_checker->
getTolerances(pose_tolerance, velocity_tolerance);
211 const auto pose_tolerance_sq = pose_tolerance.position.x * pose_tolerance.position.x;
213 auto dx = robot.position.x - goal.position.x;
214 auto dy = robot.position.y - goal.position.y;
216 auto dist_sq = dx * dx + dy * dy;
218 if (dist_sq < pose_tolerance_sq) {
233 inline bool withinPositionGoalTolerance(
234 float pose_tolerance,
235 const geometry_msgs::msg::Pose & robot,
236 const geometry_msgs::msg::Pose & goal)
238 const double & dist_sq =
239 std::pow(goal.position.x - robot.position.x, 2) +
240 std::pow(goal.position.y - robot.position.y, 2);
242 const float pose_tolerance_sq = pose_tolerance * pose_tolerance;
244 if (dist_sq < pose_tolerance_sq) {
259 auto normalize_angles(
const T & angles)
261 auto && theta = xt::eval(xt::fmod(angles + M_PI, 2.0 * M_PI));
262 return xt::eval(xt::where(theta <= 0.0, theta + M_PI, theta - M_PI));
278 template<
typename F,
typename T>
279 auto shortest_angular_distance(
283 return normalize_angles(to - from);
292 inline size_t findPathFurthestReachedPoint(
const CriticData & data)
294 const auto traj_x = xt::view(data.trajectories.x, xt::all(), -1, xt::newaxis());
295 const auto traj_y = xt::view(data.trajectories.y, xt::all(), -1, xt::newaxis());
297 const auto dx = data.path.x - traj_x;
298 const auto dy = data.path.y - traj_y;
300 const auto dists = dx * dx + dy * dy;
302 size_t max_id_by_trajectories = 0, min_id_by_path = 0;
303 float min_distance_by_path = std::numeric_limits<float>::max();
304 float cur_dist = 0.0f;
306 for (
size_t i = 0; i < dists.shape(0); i++) {
308 min_distance_by_path = std::numeric_limits<float>::max();
309 for (
size_t j = 0; j < dists.shape(1); j++) {
310 cur_dist = dists(i, j);
311 if (cur_dist < min_distance_by_path) {
312 min_distance_by_path = cur_dist;
316 max_id_by_trajectories = std::max(max_id_by_trajectories, min_id_by_path);
318 return max_id_by_trajectories;
327 inline size_t findPathTrajectoryInitialPoint(
const CriticData & data)
330 const auto dx = data.path.x - data.trajectories.x(0, 0);
331 const auto dy = data.path.y - data.trajectories.y(0, 0);
332 const auto dists = dx * dx + dy * dy;
334 float min_distance_by_path = std::numeric_limits<float>::max();
336 for (
size_t j = 0; j < dists.shape(0); j++) {
337 if (dists(j) < min_distance_by_path) {
338 min_distance_by_path = dists(j);
350 inline void setPathFurthestPointIfNotSet(CriticData & data)
352 if (!data.furthest_reached_path_point) {
353 data.furthest_reached_path_point = findPathFurthestReachedPoint(data);
361 inline void findPathCosts(
363 std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
365 auto * costmap = costmap_ros->getCostmap();
366 unsigned int map_x, map_y;
367 const size_t path_segments_count = data.path.x.shape(0) - 1;
368 data.path_pts_valid = std::vector<bool>(path_segments_count,
false);
369 for (
unsigned int idx = 0; idx < path_segments_count; idx++) {
370 const auto path_x = data.path.x(idx);
371 const auto path_y = data.path.y(idx);
372 if (!costmap->worldToMap(path_x, path_y, map_x, map_y)) {
373 (*data.path_pts_valid)[idx] =
false;
377 switch (costmap->getCost(map_x, map_y)) {
379 case (LETHAL_OBSTACLE):
380 (*data.path_pts_valid)[idx] =
false;
382 case (INSCRIBED_INFLATED_OBSTACLE):
383 (*data.path_pts_valid)[idx] =
false;
385 case (NO_INFORMATION):
386 const bool is_tracking_unknown =
387 costmap_ros->getLayeredCostmap()->isTrackingUnknown();
388 (*data.path_pts_valid)[idx] = is_tracking_unknown ?
true :
false;
392 (*data.path_pts_valid)[idx] =
true;
400 inline void setPathCostsIfNotSet(
402 std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
404 if (!data.path_pts_valid) {
405 findPathCosts(data, costmap_ros);
417 inline float posePointAngle(
418 const geometry_msgs::msg::Pose & pose,
double point_x,
double point_y,
bool forward_preference)
420 float pose_x = pose.position.x;
421 float pose_y = pose.position.y;
422 float pose_yaw = tf2::getYaw(pose.orientation);
424 float yaw = atan2f(point_y - pose_y, point_x - pose_x);
427 if (!forward_preference) {
429 fabs(angles::shortest_angular_distance(yaw, pose_yaw)),
430 fabs(angles::shortest_angular_distance(yaw, angles::normalize_angle(pose_yaw + M_PI))));
433 return fabs(angles::shortest_angular_distance(yaw, pose_yaw));
442 inline void savitskyGolayFilter(
443 models::ControlSequence & control_sequence,
444 std::array<mppi::models::Control, 4> & control_history,
445 const models::OptimizerSettings & settings)
448 xt::xarray<float> filter = {-21.0, 14.0, 39.0, 54.0, 59.0, 54.0, 39.0, 14.0, -21.0};
451 const unsigned int num_sequences = control_sequence.vx.shape(0) - 1;
454 if (num_sequences < 20) {
458 auto applyFilter = [&](
const xt::xarray<float> & data) ->
float {
459 return xt::sum(data * filter, {0}, immediate)();
462 auto applyFilterOverAxis =
463 [&](xt::xtensor<float, 1> & sequence,
464 const float hist_0,
const float hist_1,
const float hist_2,
const float hist_3) ->
void
466 unsigned int idx = 0;
467 sequence(idx) = applyFilter(
480 sequence(idx) = applyFilter(
493 sequence(idx) = applyFilter(
506 sequence(idx) = applyFilter(
518 for (idx = 4; idx != num_sequences - 4; idx++) {
519 sequence(idx) = applyFilter(
533 sequence(idx) = applyFilter(
546 sequence(idx) = applyFilter(
559 sequence(idx) = applyFilter(
572 sequence(idx) = applyFilter(
587 control_sequence.vx, control_history[0].vx,
588 control_history[1].vx, control_history[2].vx, control_history[3].vx);
590 control_sequence.vy, control_history[0].vy,
591 control_history[1].vy, control_history[2].vy, control_history[3].vy);
593 control_sequence.wz, control_history[0].wz,
594 control_history[1].wz, control_history[2].wz, control_history[3].wz);
597 unsigned int offset = settings.shift_control_sequence ? 1 : 0;
598 control_history[0] = control_history[1];
599 control_history[1] = control_history[2];
600 control_history[2] = control_history[3];
601 control_history[3] = {
602 control_sequence.vx(offset),
603 control_sequence.vy(offset),
604 control_sequence.wz(offset)};
612 inline unsigned int findFirstPathInversion(nav_msgs::msg::Path & path)
615 if (path.poses.size() < 3) {
616 return path.poses.size();
620 for (
unsigned int idx = 1; idx < path.poses.size() - 1; ++idx) {
622 float oa_x = path.poses[idx].pose.position.x -
623 path.poses[idx - 1].pose.position.x;
624 float oa_y = path.poses[idx].pose.position.y -
625 path.poses[idx - 1].pose.position.y;
626 float ab_x = path.poses[idx + 1].pose.position.x -
627 path.poses[idx].pose.position.x;
628 float ab_y = path.poses[idx + 1].pose.position.y -
629 path.poses[idx].pose.position.y;
632 float dot_product = (oa_x * ab_x) + (oa_y * ab_y);
633 if (dot_product < 0.0) {
638 return path.poses.size();
646 inline unsigned int removePosesAfterFirstInversion(nav_msgs::msg::Path & path)
648 nav_msgs::msg::Path cropped_path = path;
649 const unsigned int first_after_inversion = findFirstPathInversion(cropped_path);
650 if (first_after_inversion == path.poses.size()) {
654 cropped_path.poses.erase(
655 cropped_path.poses.begin() + first_after_inversion, cropped_path.poses.end());
657 return first_after_inversion;
665 inline size_t findClosestPathPt(
const std::vector<float> & vec,
float dist,
size_t init = 0)
667 auto iter = std::lower_bound(vec.begin() + init, vec.end(), dist);
668 if (iter == vec.begin() + init) {
671 if (dist - *(iter - 1) < *iter - dist) {
672 return iter - 1 - vec.begin();
674 return iter - vec.begin();
Function-object for checking whether a goal has been reached.
virtual bool getTolerances(geometry_msgs::msg::Pose &pose_tolerance, geometry_msgs::msg::Twist &vel_tolerance)=0
Get the maximum possible tolerances used for goal checking in the major types. Any field without a va...
void reset(unsigned int size)
Reset path data.