Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
node_hybrid.cpp
1 // Copyright (c) 2020, Samsung Research America
2 // Copyright (c) 2020, Applied Electric Vehicles Pty Ltd
3 // Copyright (c) 2023, Open Navigation LLC
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License. Reserved.
16 
17 #include <math.h>
18 #include <chrono>
19 #include <vector>
20 #include <memory>
21 #include <algorithm>
22 #include <queue>
23 #include <limits>
24 #include <utility>
25 
26 #include "ompl/base/ScopedState.h"
27 #include "ompl/base/spaces/DubinsStateSpace.h"
28 #include "ompl/base/spaces/ReedsSheppStateSpace.h"
29 
30 #include "nav2_smac_planner/node_hybrid.hpp"
31 
32 using namespace std::chrono; // NOLINT
33 
34 namespace nav2_smac_planner
35 {
36 
37 // defining static member for all instance to share
38 LookupTable NodeHybrid::obstacle_heuristic_lookup_table;
39 float NodeHybrid::travel_distance_cost = sqrtf(2.0f);
40 HybridMotionTable NodeHybrid::motion_table;
41 float NodeHybrid::size_lookup = 25;
42 LookupTable NodeHybrid::dist_heuristic_lookup_table;
43 std::shared_ptr<nav2_costmap_2d::Costmap2DROS> NodeHybrid::costmap_ros = nullptr;
44 
45 ObstacleHeuristicQueue NodeHybrid::obstacle_heuristic_queue;
46 
47 // Each of these tables are the projected motion models through
48 // time and space applied to the search on the current node in
49 // continuous map-coordinates (e.g. not meters but partial map cells)
50 // Currently, these are set to project *at minimum* into a neighboring
51 // cell. Though this could be later modified to project a certain
52 // amount of time or particular distance forward.
53 
54 // http://planning.cs.uiuc.edu/planning/node821.html
55 // Model for ackermann style vehicle with minimum radius restriction
56 void HybridMotionTable::initDubin(
57  unsigned int & size_x_in,
58  unsigned int & /*size_y_in*/,
59  unsigned int & num_angle_quantization_in,
60  SearchInfo & search_info)
61 {
62  size_x = size_x_in;
63  change_penalty = search_info.change_penalty;
64  non_straight_penalty = search_info.non_straight_penalty;
65  cost_penalty = search_info.cost_penalty;
66  reverse_penalty = search_info.reverse_penalty;
67  travel_distance_reward = 1.0f - search_info.retrospective_penalty;
68  downsample_obstacle_heuristic = search_info.downsample_obstacle_heuristic;
69  use_quadratic_cost_penalty = search_info.use_quadratic_cost_penalty;
70 
71  // if nothing changed, no need to re-compute primitives
72  if (num_angle_quantization_in == num_angle_quantization &&
73  min_turning_radius == search_info.minimum_turning_radius &&
74  motion_model == MotionModel::DUBIN)
75  {
76  return;
77  }
78 
79  num_angle_quantization = num_angle_quantization_in;
80  num_angle_quantization_float = static_cast<float>(num_angle_quantization);
81  min_turning_radius = search_info.minimum_turning_radius;
82  motion_model = MotionModel::DUBIN;
83 
84  // angle must meet 3 requirements:
85  // 1) be increment of quantized bin size
86  // 2) chord length must be greater than sqrt(2) to leave current cell
87  // 3) maximum curvature must be respected, represented by minimum turning angle
88  // Thusly:
89  // On circle of radius minimum turning angle, we need select motion primatives
90  // with chord length > sqrt(2) and be an increment of our bin size
91  //
92  // chord >= sqrt(2) >= 2 * R * sin (angle / 2); where angle / N = quantized bin size
93  // Thusly: angle <= 2.0 * asin(sqrt(2) / (2 * R))
94  float angle = 2.0 * asin(sqrt(2.0) / (2 * min_turning_radius));
95  // Now make sure angle is an increment of the quantized bin size
96  // And since its based on the minimum chord, we need to make sure its always larger
97  bin_size =
98  2.0f * static_cast<float>(M_PI) / static_cast<float>(num_angle_quantization);
99  float increments;
100  if (angle < bin_size) {
101  increments = 1.0f;
102  } else {
103  // Search dimensions are clean multiples of quantization - this prevents
104  // paths with loops in them
105  increments = ceil(angle / bin_size);
106  }
107  angle = increments * bin_size;
108 
109  // find deflections
110  // If we make a right triangle out of the chord in circle of radius
111  // min turning angle, we can see that delta X = R * sin (angle)
112  const float delta_x = min_turning_radius * sin(angle);
113  // Using that same right triangle, we can see that the complement
114  // to delta Y is R * cos (angle). If we subtract R, we get the actual value
115  const float delta_y = min_turning_radius - (min_turning_radius * cos(angle));
116  const float delta_dist = hypotf(delta_x, delta_y);
117 
118  projections.clear();
119  projections.reserve(3);
120  projections.emplace_back(delta_dist, 0.0, 0.0, TurnDirection::FORWARD); // Forward
121  projections.emplace_back(delta_x, delta_y, increments, TurnDirection::LEFT); // Left
122  projections.emplace_back(delta_x, -delta_y, -increments, TurnDirection::RIGHT); // Right
123 
124  if (search_info.allow_primitive_interpolation && increments > 1.0f) {
125  // Create primitives that are +/- N to fill in search space to use all set angular quantizations
126  // Allows us to create N many primitives so that each search iteration can expand into any angle
127  // bin possible with the minimum turning radius constraint, not just the most extreme turns.
128  projections.reserve(3 + (2 * (increments - 1)));
129  for (unsigned int i = 1; i < static_cast<unsigned int>(increments); i++) {
130  const float angle_n = static_cast<float>(i) * bin_size;
131  const float turning_rad_n = delta_dist / (2.0f * sin(angle_n / 2.0f));
132  const float delta_x_n = turning_rad_n * sin(angle_n);
133  const float delta_y_n = turning_rad_n - (turning_rad_n * cos(angle_n));
134  projections.emplace_back(
135  delta_x_n, delta_y_n, static_cast<float>(i), TurnDirection::LEFT); // Left
136  projections.emplace_back(
137  delta_x_n, -delta_y_n, -static_cast<float>(i), TurnDirection::RIGHT); // Right
138  }
139  }
140 
141  // Create the correct OMPL state space
142  state_space = std::make_shared<ompl::base::DubinsStateSpace>(min_turning_radius);
143 
144  // Precompute projection deltas
145  delta_xs.resize(projections.size());
146  delta_ys.resize(projections.size());
147  trig_values.resize(num_angle_quantization);
148 
149  for (unsigned int i = 0; i != projections.size(); i++) {
150  delta_xs[i].resize(num_angle_quantization);
151  delta_ys[i].resize(num_angle_quantization);
152 
153  for (unsigned int j = 0; j != num_angle_quantization; j++) {
154  double cos_theta = cos(bin_size * j);
155  double sin_theta = sin(bin_size * j);
156  if (i == 0) {
157  // if first iteration, cache the trig values for later
158  trig_values[j] = {cos_theta, sin_theta};
159  }
160  delta_xs[i][j] = projections[i]._x * cos_theta - projections[i]._y * sin_theta;
161  delta_ys[i][j] = projections[i]._x * sin_theta + projections[i]._y * cos_theta;
162  }
163  }
164 
165  // Precompute travel costs for each motion primitive
166  travel_costs.resize(projections.size());
167  for (unsigned int i = 0; i != projections.size(); i++) {
168  const TurnDirection turn_dir = projections[i]._turn_dir;
169  if (turn_dir != TurnDirection::FORWARD && turn_dir != TurnDirection::REVERSE) {
170  // Turning, so length is the arc length
171  const float angle = projections[i]._theta * bin_size;
172  const float turning_rad = delta_dist / (2.0f * sin(angle / 2.0f));
173  travel_costs[i] = turning_rad * angle;
174  } else {
175  travel_costs[i] = delta_dist;
176  }
177  }
178 }
179 
180 // http://planning.cs.uiuc.edu/planning/node822.html
181 // Same as Dubin model but now reverse is valid
182 // See notes in Dubin for explanation
183 void HybridMotionTable::initReedsShepp(
184  unsigned int & size_x_in,
185  unsigned int & /*size_y_in*/,
186  unsigned int & num_angle_quantization_in,
187  SearchInfo & search_info)
188 {
189  size_x = size_x_in;
190  change_penalty = search_info.change_penalty;
191  non_straight_penalty = search_info.non_straight_penalty;
192  cost_penalty = search_info.cost_penalty;
193  reverse_penalty = search_info.reverse_penalty;
194  travel_distance_reward = 1.0f - search_info.retrospective_penalty;
195  downsample_obstacle_heuristic = search_info.downsample_obstacle_heuristic;
196  use_quadratic_cost_penalty = search_info.use_quadratic_cost_penalty;
197 
198  // if nothing changed, no need to re-compute primitives
199  if (num_angle_quantization_in == num_angle_quantization &&
200  min_turning_radius == search_info.minimum_turning_radius &&
201  motion_model == MotionModel::REEDS_SHEPP)
202  {
203  return;
204  }
205 
206  num_angle_quantization = num_angle_quantization_in;
207  num_angle_quantization_float = static_cast<float>(num_angle_quantization);
208  min_turning_radius = search_info.minimum_turning_radius;
209  motion_model = MotionModel::REEDS_SHEPP;
210 
211  float angle = 2.0 * asin(sqrt(2.0) / (2 * min_turning_radius));
212  bin_size =
213  2.0f * static_cast<float>(M_PI) / static_cast<float>(num_angle_quantization);
214  float increments;
215  if (angle < bin_size) {
216  increments = 1.0f;
217  } else {
218  increments = ceil(angle / bin_size);
219  }
220  angle = increments * bin_size;
221 
222  const float delta_x = min_turning_radius * sin(angle);
223  const float delta_y = min_turning_radius - (min_turning_radius * cos(angle));
224  const float delta_dist = hypotf(delta_x, delta_y);
225 
226  projections.clear();
227  projections.reserve(6);
228  projections.emplace_back(delta_dist, 0.0, 0.0, TurnDirection::FORWARD); // Forward
229  projections.emplace_back(
230  delta_x, delta_y, increments, TurnDirection::LEFT); // Forward + Left
231  projections.emplace_back(
232  delta_x, -delta_y, -increments, TurnDirection::RIGHT); // Forward + Right
233  projections.emplace_back(-delta_dist, 0.0, 0.0, TurnDirection::REVERSE); // Backward
234  projections.emplace_back(
235  -delta_x, delta_y, -increments, TurnDirection::REV_LEFT); // Backward + Left
236  projections.emplace_back(
237  -delta_x, -delta_y, increments, TurnDirection::REV_RIGHT); // Backward + Right
238 
239  if (search_info.allow_primitive_interpolation && increments > 1.0f) {
240  // Create primitives that are +/- N to fill in search space to use all set angular quantizations
241  // Allows us to create N many primitives so that each search iteration can expand into any angle
242  // bin possible with the minimum turning radius constraint, not just the most extreme turns.
243  projections.reserve(6 + (4 * (increments - 1)));
244  for (unsigned int i = 1; i < static_cast<unsigned int>(increments); i++) {
245  const float angle_n = static_cast<float>(i) * bin_size;
246  const float turning_rad_n = delta_dist / (2.0f * sin(angle_n / 2.0f));
247  const float delta_x_n = turning_rad_n * sin(angle_n);
248  const float delta_y_n = turning_rad_n - (turning_rad_n * cos(angle_n));
249  projections.emplace_back(
250  delta_x_n, delta_y_n, static_cast<float>(i), TurnDirection::LEFT); // Forward + Left
251  projections.emplace_back(
252  delta_x_n, -delta_y_n, -static_cast<float>(i), TurnDirection::RIGHT); // Forward + Right
253  projections.emplace_back(
254  -delta_x_n, delta_y_n, -static_cast<float>(i),
255  TurnDirection::REV_LEFT); // Backward + Left
256  projections.emplace_back(
257  -delta_x_n, -delta_y_n, static_cast<float>(i),
258  TurnDirection::REV_RIGHT); // Backward + Right
259  }
260  }
261 
262  // Create the correct OMPL state space
263  state_space = std::make_shared<ompl::base::ReedsSheppStateSpace>(min_turning_radius);
264 
265  // Precompute projection deltas
266  delta_xs.resize(projections.size());
267  delta_ys.resize(projections.size());
268  trig_values.resize(num_angle_quantization);
269 
270  for (unsigned int i = 0; i != projections.size(); i++) {
271  delta_xs[i].resize(num_angle_quantization);
272  delta_ys[i].resize(num_angle_quantization);
273 
274  for (unsigned int j = 0; j != num_angle_quantization; j++) {
275  double cos_theta = cos(bin_size * j);
276  double sin_theta = sin(bin_size * j);
277  if (i == 0) {
278  // if first iteration, cache the trig values for later
279  trig_values[j] = {cos_theta, sin_theta};
280  }
281  delta_xs[i][j] = projections[i]._x * cos_theta - projections[i]._y * sin_theta;
282  delta_ys[i][j] = projections[i]._x * sin_theta + projections[i]._y * cos_theta;
283  }
284  }
285 
286  // Precompute travel costs for each motion primitive
287  travel_costs.resize(projections.size());
288  for (unsigned int i = 0; i != projections.size(); i++) {
289  const TurnDirection turn_dir = projections[i]._turn_dir;
290  if (turn_dir != TurnDirection::FORWARD && turn_dir != TurnDirection::REVERSE) {
291  // Turning, so length is the arc length
292  const float angle = projections[i]._theta * bin_size;
293  const float turning_rad = delta_dist / (2.0f * sin(angle / 2.0f));
294  travel_costs[i] = turning_rad * angle;
295  } else {
296  travel_costs[i] = delta_dist;
297  }
298  }
299 }
300 
301 MotionPoses HybridMotionTable::getProjections(const NodeHybrid * node)
302 {
303  MotionPoses projection_list;
304  projection_list.reserve(projections.size());
305 
306  for (unsigned int i = 0; i != projections.size(); i++) {
307  const MotionPose & motion_model = projections[i];
308 
309  // normalize theta, I know its overkill, but I've been burned before...
310  const float & node_heading = node->pose.theta;
311  float new_heading = node_heading + motion_model._theta;
312 
313  if (new_heading < 0.0) {
314  new_heading += num_angle_quantization_float;
315  }
316 
317  if (new_heading >= num_angle_quantization_float) {
318  new_heading -= num_angle_quantization_float;
319  }
320 
321  projection_list.emplace_back(
322  delta_xs[i][node_heading] + node->pose.x,
323  delta_ys[i][node_heading] + node->pose.y,
324  new_heading, motion_model._turn_dir);
325  }
326 
327  return projection_list;
328 }
329 
330 unsigned int HybridMotionTable::getClosestAngularBin(const double & theta)
331 {
332  auto bin = static_cast<unsigned int>(round(static_cast<float>(theta) / bin_size));
333  return bin < num_angle_quantization ? bin : 0u;
334 }
335 
336 float HybridMotionTable::getAngleFromBin(const unsigned int & bin_idx)
337 {
338  return bin_idx * bin_size;
339 }
340 
341 double HybridMotionTable::getAngle(const double & theta)
342 {
343  return theta / bin_size;
344 }
345 
346 NodeHybrid::NodeHybrid(const uint64_t index)
347 : parent(nullptr),
348  pose(0.0f, 0.0f, 0.0f),
349  _cell_cost(std::numeric_limits<float>::quiet_NaN()),
350  _accumulated_cost(std::numeric_limits<float>::max()),
351  _index(index),
352  _was_visited(false),
353  _motion_primitive_index(std::numeric_limits<unsigned int>::max()),
354  _is_node_valid(false)
355 {
356 }
357 
359 {
360  parent = nullptr;
361 }
362 
364 {
365  parent = nullptr;
366  _cell_cost = std::numeric_limits<float>::quiet_NaN();
367  _accumulated_cost = std::numeric_limits<float>::max();
368  _was_visited = false;
369  _motion_primitive_index = std::numeric_limits<unsigned int>::max();
370  pose.x = 0.0f;
371  pose.y = 0.0f;
372  pose.theta = 0.0f;
373  _is_node_valid = false;
374 }
375 
377  const bool & traverse_unknown,
378  GridCollisionChecker * collision_checker)
379 {
380  // Already found, we can return the result
381  if (!std::isnan(_cell_cost)) {
382  return _is_node_valid;
383  }
384 
385  _is_node_valid = !collision_checker->inCollision(
386  this->pose.x, this->pose.y, this->pose.theta /*bin number*/, traverse_unknown);
387  _cell_cost = collision_checker->getCost();
388  return _is_node_valid;
389 }
390 
392 {
393  const float normalized_cost = child->getCost() / 252.0f;
394  if (std::isnan(normalized_cost)) {
395  throw std::runtime_error(
396  "Node attempted to get traversal "
397  "cost without a known SE2 collision cost!");
398  }
399 
400  // this is the first node
401  if (getMotionPrimitiveIndex() == std::numeric_limits<unsigned int>::max()) {
402  return NodeHybrid::travel_distance_cost;
403  }
404 
405  const TurnDirection & child_turn_dir = child->getTurnDirection();
406  float travel_cost_raw = motion_table.travel_costs[child->getMotionPrimitiveIndex()];
407  float travel_cost = 0.0;
408 
409  if (motion_table.use_quadratic_cost_penalty) {
410  travel_cost_raw *=
411  (motion_table.travel_distance_reward +
412  (motion_table.cost_penalty * normalized_cost * normalized_cost));
413  } else {
414  travel_cost_raw *=
415  (motion_table.travel_distance_reward + motion_table.cost_penalty * normalized_cost);
416  }
417 
418  if (child_turn_dir == TurnDirection::FORWARD || child_turn_dir == TurnDirection::REVERSE) {
419  // New motion is a straight motion, no additional costs to be applied
420  travel_cost = travel_cost_raw;
421  } else {
422  if (getTurnDirection() == child_turn_dir) {
423  // Turning motion but keeps in same direction: encourages to commit to turning if starting it
424  travel_cost = travel_cost_raw * motion_table.non_straight_penalty;
425  } else {
426  // Turning motion and changing direction: penalizes wiggling
427  travel_cost = travel_cost_raw *
428  (motion_table.non_straight_penalty + motion_table.change_penalty);
429  }
430  }
431 
432  if (child_turn_dir == TurnDirection::REV_RIGHT ||
433  child_turn_dir == TurnDirection::REV_LEFT ||
434  child_turn_dir == TurnDirection::REVERSE)
435  {
436  // reverse direction
437  travel_cost *= motion_table.reverse_penalty;
438  }
439 
440  return travel_cost;
441 }
442 
444  const Coordinates & node_coords,
445  const Coordinates & goal_coords)
446 {
447  const float obstacle_heuristic =
448  getObstacleHeuristic(node_coords, goal_coords, motion_table.cost_penalty);
449  const float dist_heuristic = getDistanceHeuristic(node_coords, goal_coords, obstacle_heuristic);
450  return std::max(obstacle_heuristic, dist_heuristic);
451 }
452 
454  const MotionModel & motion_model,
455  unsigned int & size_x,
456  unsigned int & size_y,
457  unsigned int & num_angle_quantization,
458  SearchInfo & search_info)
459 {
460  // find the motion model selected
461  switch (motion_model) {
462  case MotionModel::DUBIN:
463  motion_table.initDubin(size_x, size_y, num_angle_quantization, search_info);
464  break;
465  case MotionModel::REEDS_SHEPP:
466  motion_table.initReedsShepp(size_x, size_y, num_angle_quantization, search_info);
467  break;
468  default:
469  throw std::runtime_error(
470  "Invalid motion model for Hybrid A*. Please select between"
471  " Dubin (Ackermann forward only),"
472  " Reeds-Shepp (Ackermann forward and back).");
473  }
474 
475  travel_distance_cost = motion_table.projections[0]._x;
476 }
477 
478 inline float distanceHeuristic2D(
479  const uint64_t idx, const unsigned int size_x,
480  const unsigned int target_x, const unsigned int target_y)
481 {
482  int dx = static_cast<int>(idx % size_x) - static_cast<int>(target_x);
483  int dy = static_cast<int>(idx / size_x) - static_cast<int>(target_y);
484  return std::sqrt(dx * dx + dy * dy);
485 }
486 
488  std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros_i,
489  const unsigned int & start_x, const unsigned int & start_y,
490  const unsigned int & goal_x, const unsigned int & goal_y)
491 {
492  // Downsample costmap 2x to compute a sparse obstacle heuristic. This speeds up
493  // the planner considerably to search through 75% less cells with no detectable
494  // erosion of path quality after even modest smoothing. The error would be no more
495  // than 0.05 * normalized cost. Since this is just a search prior, there's no loss in generality
496  costmap_ros = costmap_ros_i;
497  auto costmap = costmap_ros->getCostmap();
498 
499  // Clear lookup table
500  unsigned int size = 0u;
501  unsigned int size_x = 0u;
502  if (motion_table.downsample_obstacle_heuristic) {
503  size_x = ceil(static_cast<float>(costmap->getSizeInCellsX()) / 2.0f);
504  size = size_x *
505  ceil(static_cast<float>(costmap->getSizeInCellsY()) / 2.0f);
506  } else {
507  size_x = costmap->getSizeInCellsX();
508  size = size_x * costmap->getSizeInCellsY();
509  }
510 
511  if (obstacle_heuristic_lookup_table.size() == size) {
512  // must reset all values
513  std::fill(
514  obstacle_heuristic_lookup_table.begin(),
515  obstacle_heuristic_lookup_table.end(), 0.0f);
516  } else {
517  unsigned int obstacle_size = obstacle_heuristic_lookup_table.size();
518  obstacle_heuristic_lookup_table.resize(size, 0.0f);
519  // must reset values for non-constructed indices
520  std::fill_n(
521  obstacle_heuristic_lookup_table.begin(), obstacle_size, 0.0f);
522  }
523 
524  obstacle_heuristic_queue.clear();
525  obstacle_heuristic_queue.reserve(size);
526 
527  // Set initial goal point to queue from. Divided by 2 due to downsampled costmap.
528  unsigned int goal_index;
529  if (motion_table.downsample_obstacle_heuristic) {
530  goal_index = floor(goal_y / 2.0f) * size_x + floor(goal_x / 2.0f);
531  } else {
532  goal_index = floor(goal_y) * size_x + floor(goal_x);
533  }
534 
535  obstacle_heuristic_queue.emplace_back(
536  distanceHeuristic2D(goal_index, size_x, start_x, start_y), goal_index);
537 
538  // initialize goal cell with a very small value to differentiate it from 0.0 (~uninitialized)
539  // the negative value means the cell is in the open set
540  obstacle_heuristic_lookup_table[goal_index] = -0.00001f;
541 }
542 
544  const Coordinates & node_coords,
545  const Coordinates & goal_coords,
546  const float & cost_penalty)
547 {
548  // If already expanded, return the cost
549  auto costmap = costmap_ros->getCostmap();
550  unsigned int size_x = 0u;
551  unsigned int size_y = 0u;
552  if (motion_table.downsample_obstacle_heuristic) {
553  size_x = ceil(static_cast<float>(costmap->getSizeInCellsX()) / 2.0f);
554  size_y = ceil(static_cast<float>(costmap->getSizeInCellsY()) / 2.0f);
555  } else {
556  size_x = costmap->getSizeInCellsX();
557  size_y = costmap->getSizeInCellsY();
558  }
559 
560  // Divided by 2 due to downsampled costmap.
561  unsigned int start_y, start_x;
562  const bool & downsample_H = motion_table.downsample_obstacle_heuristic;
563  if (downsample_H) {
564  start_y = floor(node_coords.y / 2.0f);
565  start_x = floor(node_coords.x / 2.0f);
566  } else {
567  start_y = floor(node_coords.y);
568  start_x = floor(node_coords.x);
569  }
570 
571  const unsigned int start_index = start_y * size_x + start_x;
572  const float & requested_node_cost = obstacle_heuristic_lookup_table[start_index];
573  if (requested_node_cost > 0.0f) {
574  // costs are doubled due to downsampling
575  return downsample_H ? 2.0f * requested_node_cost : requested_node_cost;
576  }
577 
578  // If not, expand until it is included. This dynamic programming ensures that
579  // we only expand the MINIMUM spanning set of the costmap per planning request.
580  // Rather than naively expanding the entire (potentially massive) map for a limited
581  // path, we only expand to the extent required for the furthest expansion in the
582  // search-planning request that dynamically updates during search as needed.
583 
584  // start_x and start_y have changed since last call
585  // we need to recompute 2D distance heuristic and reprioritize queue
586  for (auto & n : obstacle_heuristic_queue) {
587  n.first = -obstacle_heuristic_lookup_table[n.second] +
588  distanceHeuristic2D(n.second, size_x, start_x, start_y);
589  }
590  std::make_heap(
591  obstacle_heuristic_queue.begin(), obstacle_heuristic_queue.end(),
593 
594  const int size_x_int = static_cast<int>(size_x);
595  const float sqrt2 = sqrtf(2.0f);
596  float c_cost, cost, travel_cost, new_cost, existing_cost;
597  unsigned int mx, my;
598  unsigned int idx, new_idx = 0;
599 
600  const std::vector<int> neighborhood = {1, -1, // left right
601  size_x_int, -size_x_int, // up down
602  size_x_int + 1, size_x_int - 1, // upper diagonals
603  -size_x_int + 1, -size_x_int - 1}; // lower diagonals
604 
605  while (!obstacle_heuristic_queue.empty()) {
606  idx = obstacle_heuristic_queue.front().second;
607  std::pop_heap(
608  obstacle_heuristic_queue.begin(), obstacle_heuristic_queue.end(),
610  obstacle_heuristic_queue.pop_back();
611  c_cost = obstacle_heuristic_lookup_table[idx];
612  if (c_cost > 0.0f) {
613  // cell has been processed and closed, no further cost improvements
614  // are mathematically possible thanks to euclidean distance heuristic consistency
615  continue;
616  }
617  c_cost = -c_cost;
618  obstacle_heuristic_lookup_table[idx] = c_cost; // set a positive value to close the cell
619 
620  // find neighbors
621  for (unsigned int i = 0; i != neighborhood.size(); i++) {
622  new_idx = static_cast<unsigned int>(static_cast<int>(idx) + neighborhood[i]);
623 
624  // if neighbor path is better and non-lethal, set new cost and add to queue
625  if (new_idx < size_x * size_y) {
626  if (downsample_H) {
627  // Get costmap values as if downsampled
628  unsigned int y_offset = (new_idx / size_x) * 2;
629  unsigned int x_offset = (new_idx - ((new_idx / size_x) * size_x)) * 2;
630  cost = costmap->getCost(x_offset, y_offset);
631  for (unsigned int i = 0; i < 2u; ++i) {
632  unsigned int mxd = x_offset + i;
633  if (mxd >= costmap->getSizeInCellsX()) {
634  continue;
635  }
636  for (unsigned int j = 0; j < 2u; ++j) {
637  unsigned int myd = y_offset + j;
638  if (myd >= costmap->getSizeInCellsY()) {
639  continue;
640  }
641  if (i == 0 && j == 0) {
642  continue;
643  }
644  cost = std::min(cost, static_cast<float>(costmap->getCost(mxd, myd)));
645  }
646  }
647  } else {
648  cost = static_cast<float>(costmap->getCost(new_idx));
649  }
650 
651  if (cost >= INSCRIBED) {
652  continue;
653  }
654 
655  my = new_idx / size_x;
656  mx = new_idx - (my * size_x);
657 
658  if (mx >= size_x - 3 || mx <= 3) {
659  continue;
660  }
661  if (my >= size_y - 3 || my <= 3) {
662  continue;
663  }
664 
665  existing_cost = obstacle_heuristic_lookup_table[new_idx];
666  if (existing_cost <= 0.0f) {
667  if (motion_table.use_quadratic_cost_penalty) {
668  travel_cost =
669  (i <= 3 ? 1.0f : sqrt2) * (1.0f + (cost_penalty * cost * cost / 63504.0f)); // 252^2
670  } else {
671  travel_cost =
672  ((i <= 3) ? 1.0f : sqrt2) * (1.0f + (cost_penalty * cost / 252.0f));
673  }
674 
675  new_cost = c_cost + travel_cost;
676  if (existing_cost == 0.0f || -existing_cost > new_cost) {
677  // the negative value means the cell is in the open set
678  obstacle_heuristic_lookup_table[new_idx] = -new_cost;
679  obstacle_heuristic_queue.emplace_back(
680  new_cost + distanceHeuristic2D(new_idx, size_x, start_x, start_y), new_idx);
681  std::push_heap(
682  obstacle_heuristic_queue.begin(), obstacle_heuristic_queue.end(),
684  }
685  }
686  }
687  }
688 
689  if (idx == start_index) {
690  break;
691  }
692  }
693 
694  // #include "nav_msgs/msg/occupancy_grid.hpp"
695  // static auto node = std::make_shared<rclcpp::Node>("test");
696  // static auto pub = node->create_publisher<nav_msgs::msg::OccupancyGrid>("test", 1);
697  // nav_msgs::msg::OccupancyGrid msg;
698  // msg.info.height = size_y;
699  // msg.info.width = size_x;
700  // msg.info.origin.position.x = -33.6;
701  // msg.info.origin.position.y = -26;
702  // msg.info.resolution = 0.05;
703  // msg.header.frame_id = "map";
704  // msg.header.stamp = node->now();
705  // msg.data.resize(size_x * size_y, 0);
706  // for (unsigned int i = 0; i != size_y * size_x; i++) {
707  // msg.data.at(i) = obstacle_heuristic_lookup_table[i] / 10.0;
708  // }
709  // pub->publish(std::move(msg));
710 
711  // return requested_node_cost which has been updated by the search
712  // costs are doubled due to downsampling
713  return downsample_H ? 2.0f * requested_node_cost : requested_node_cost;
714 }
715 
717  const Coordinates & node_coords,
718  const Coordinates & goal_coords,
719  const float & obstacle_heuristic)
720 {
721  // rotate and translate node_coords such that goal_coords relative is (0,0,0)
722  // Due to the rounding involved in exact cell increments for caching,
723  // this is not an exact replica of a live heuristic, but has bounded error.
724  // (Usually less than 1 cell)
725 
726  // This angle is negative since we are de-rotating the current node
727  // by the goal angle; cos(-th) = cos(th) & sin(-th) = -sin(th)
728  const TrigValues & trig_vals = motion_table.trig_values[goal_coords.theta];
729  const float cos_th = trig_vals.first;
730  const float sin_th = -trig_vals.second;
731  const float dx = node_coords.x - goal_coords.x;
732  const float dy = node_coords.y - goal_coords.y;
733 
734  double dtheta_bin = node_coords.theta - goal_coords.theta;
735  if (dtheta_bin < 0) {
736  dtheta_bin += motion_table.num_angle_quantization;
737  }
738  if (dtheta_bin > motion_table.num_angle_quantization) {
739  dtheta_bin -= motion_table.num_angle_quantization;
740  }
741 
742  Coordinates node_coords_relative(
743  round(dx * cos_th - dy * sin_th),
744  round(dx * sin_th + dy * cos_th),
745  round(dtheta_bin));
746 
747  // Check if the relative node coordinate is within the localized window around the goal
748  // to apply the distance heuristic. Since the lookup table is contains only the positive
749  // X axis, we mirror the Y and theta values across the X axis to find the heuristic values.
750  float motion_heuristic = 0.0;
751  const int floored_size = floor(size_lookup / 2.0);
752  const int ceiling_size = ceil(size_lookup / 2.0);
753  const float mirrored_relative_y = abs(node_coords_relative.y);
754  if (abs(node_coords_relative.x) < floored_size && mirrored_relative_y < floored_size) {
755  // Need to mirror angle if Y coordinate was mirrored
756  int theta_pos;
757  if (node_coords_relative.y < 0.0) {
758  theta_pos = motion_table.num_angle_quantization - node_coords_relative.theta;
759  } else {
760  theta_pos = node_coords_relative.theta;
761  }
762  const int x_pos = node_coords_relative.x + floored_size;
763  const int y_pos = static_cast<int>(mirrored_relative_y);
764  const int index =
765  x_pos * ceiling_size * motion_table.num_angle_quantization +
766  y_pos * motion_table.num_angle_quantization +
767  theta_pos;
768  motion_heuristic = dist_heuristic_lookup_table[index];
769  } else if (obstacle_heuristic <= 0.0) {
770  // If no obstacle heuristic value, must have some H to use
771  // In nominal situations, this should never be called.
772  static ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
773  to[0] = goal_coords.x;
774  to[1] = goal_coords.y;
775  to[2] = goal_coords.theta * motion_table.num_angle_quantization;
776  from[0] = node_coords.x;
777  from[1] = node_coords.y;
778  from[2] = node_coords.theta * motion_table.num_angle_quantization;
779  motion_heuristic = motion_table.state_space->distance(from(), to());
780  }
781 
782  return motion_heuristic;
783 }
784 
786  const float & lookup_table_dim,
787  const MotionModel & motion_model,
788  const unsigned int & dim_3_size,
789  const SearchInfo & search_info)
790 {
791  // Dubin or Reeds-Shepp shortest distances
792  if (motion_model == MotionModel::DUBIN) {
793  motion_table.state_space = std::make_shared<ompl::base::DubinsStateSpace>(
794  search_info.minimum_turning_radius);
795  } else if (motion_model == MotionModel::REEDS_SHEPP) {
796  motion_table.state_space = std::make_shared<ompl::base::ReedsSheppStateSpace>(
797  search_info.minimum_turning_radius);
798  } else {
799  throw std::runtime_error(
800  "Node attempted to precompute distance heuristics "
801  "with invalid motion model!");
802  }
803 
804  ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
805  to[0] = 0.0;
806  to[1] = 0.0;
807  to[2] = 0.0;
808  size_lookup = lookup_table_dim;
809  float motion_heuristic = 0.0;
810  unsigned int index = 0;
811  int dim_3_size_int = static_cast<int>(dim_3_size);
812  float angular_bin_size = 2 * M_PI / static_cast<float>(dim_3_size);
813 
814  // Create a lookup table of Dubin/Reeds-Shepp distances in a window around the goal
815  // to help drive the search towards admissible approaches. Deu to symmetries in the
816  // Heuristic space, we need to only store 2 of the 4 quadrants and simply mirror
817  // around the X axis any relative node lookup. This reduces memory overhead and increases
818  // the size of a window a platform can store in memory.
819  dist_heuristic_lookup_table.resize(size_lookup * ceil(size_lookup / 2.0) * dim_3_size_int);
820  for (float x = ceil(-size_lookup / 2.0); x <= floor(size_lookup / 2.0); x += 1.0) {
821  for (float y = 0.0; y <= floor(size_lookup / 2.0); y += 1.0) {
822  for (int heading = 0; heading != dim_3_size_int; heading++) {
823  from[0] = x;
824  from[1] = y;
825  from[2] = heading * angular_bin_size;
826  motion_heuristic = motion_table.state_space->distance(from(), to());
827  dist_heuristic_lookup_table[index] = motion_heuristic;
828  index++;
829  }
830  }
831  }
832 }
833 
835  std::function<bool(const uint64_t &,
836  nav2_smac_planner::NodeHybrid * &)> & NeighborGetter,
837  GridCollisionChecker * collision_checker,
838  const bool & traverse_unknown,
839  NodeVector & neighbors)
840 {
841  uint64_t index = 0;
842  NodePtr neighbor = nullptr;
843  Coordinates initial_node_coords;
844  const MotionPoses motion_projections = motion_table.getProjections(this);
845 
846  for (unsigned int i = 0; i != motion_projections.size(); i++) {
847  index = NodeHybrid::getIndex(
848  static_cast<unsigned int>(motion_projections[i]._x),
849  static_cast<unsigned int>(motion_projections[i]._y),
850  static_cast<unsigned int>(motion_projections[i]._theta),
851  motion_table.size_x, motion_table.num_angle_quantization);
852 
853  if (NeighborGetter(index, neighbor) && !neighbor->wasVisited()) {
854  // Cache the initial pose in case it was visited but valid
855  // don't want to disrupt continuous coordinate expansion
856  initial_node_coords = neighbor->pose;
857  neighbor->setPose(
858  Coordinates(
859  motion_projections[i]._x,
860  motion_projections[i]._y,
861  motion_projections[i]._theta));
862  if (neighbor->isNodeValid(traverse_unknown, collision_checker)) {
863  neighbor->setMotionPrimitiveIndex(i, motion_projections[i]._turn_dir);
864  neighbors.push_back(neighbor);
865  } else {
866  neighbor->setPose(initial_node_coords);
867  }
868  }
869  }
870 }
871 
872 bool NodeHybrid::backtracePath(CoordinateVector & path)
873 {
874  if (!this->parent) {
875  return false;
876  }
877 
878  NodePtr current_node = this;
879 
880  while (current_node->parent) {
881  path.push_back(current_node->pose);
882  // Convert angle to radians
883  path.back().theta = NodeHybrid::motion_table.getAngleFromBin(path.back().theta);
884  current_node = current_node->parent;
885  }
886 
887  // add the start pose
888  path.push_back(current_node->pose);
889  // Convert angle to radians
890  path.back().theta = NodeHybrid::motion_table.getAngleFromBin(path.back().theta);
891 
892  return true;
893 }
894 
895 } // namespace nav2_smac_planner
A costmap grid collision checker.
bool inCollision(const float &x, const float &y, const float &theta, const bool &traverse_unknown)
Check if in collision with costmap and footprint at pose.
float getCost()
Get cost at footprint pose in costmap.
NodeHybrid implementation for graph, Hybrid-A*.
static void precomputeDistanceHeuristic(const float &lookup_table_dim, const MotionModel &motion_model, const unsigned int &dim_3_size, const SearchInfo &search_info)
Compute the SE2 distance heuristic.
uint64_t getIndex()
Gets cell index.
bool isNodeValid(const bool &traverse_unknown, GridCollisionChecker *collision_checker)
Check if this node is valid.
float getTraversalCost(const NodePtr &child)
Get traversal cost of parent node to child node.
void setPose(const Coordinates &pose_in)
setting continuous coordinate search poses (in partial-cells)
~NodeHybrid()
A destructor for nav2_smac_planner::NodeHybrid.
void getNeighbors(std::function< bool(const uint64_t &, nav2_smac_planner::NodeHybrid *&)> &validity_checker, GridCollisionChecker *collision_checker, const bool &traverse_unknown, NodeVector &neighbors)
Retrieve all valid neighbors of a node.
float getCost()
Gets the costmap cost at this node.
static void initMotionModel(const MotionModel &motion_model, unsigned int &size_x, unsigned int &size_y, unsigned int &angle_quantization, SearchInfo &search_info)
Initialize motion models.
void reset()
Reset method for new search.
void setMotionPrimitiveIndex(const unsigned int &idx, const TurnDirection &turn_dir)
Sets the motion primitive index used to achieve node in search.
unsigned int & getMotionPrimitiveIndex()
Gets the motion primitive index used to achieve node in search.
static float getObstacleHeuristic(const Coordinates &node_coords, const Coordinates &goal_coords, const float &cost_penalty)
Compute the Obstacle heuristic.
static float getDistanceHeuristic(const Coordinates &node_coords, const Coordinates &goal_coords, const float &obstacle_heuristic)
Compute the Distance heuristic.
bool wasVisited()
Gets if cell has been visited in search.
static float getHeuristicCost(const Coordinates &node_coords, const Coordinates &goal_coordinates)
Get cost of heuristic of node.
TurnDirection & getTurnDirection()
Gets the motion primitive turning direction used to achieve node in search.
bool backtracePath(CoordinateVector &path)
Set the starting pose for planning, as a node index.
static void resetObstacleHeuristic(std::shared_ptr< nav2_costmap_2d::Costmap2DROS > costmap_ros, const unsigned int &start_x, const unsigned int &start_y, const unsigned int &goal_x, const unsigned int &goal_y)
reset the obstacle heuristic state
void initReedsShepp(unsigned int &size_x_in, unsigned int &size_y_in, unsigned int &angle_quantization_in, SearchInfo &search_info)
Initializing using Reeds-Shepp model.
MotionPoses getProjections(const NodeHybrid *node)
Get projections of motion models.
void initDubin(unsigned int &size_x_in, unsigned int &size_y_in, unsigned int &angle_quantization_in, SearchInfo &search_info)
Initializing using Dubin model.
Definition: node_hybrid.cpp:56
A struct for poses in motion primitives.
Definition: types.hpp:129
NodeHybrid implementation of coordinate structure.
Search properties and penalties.
Definition: types.hpp:36