26 #include "ompl/base/ScopedState.h"
27 #include "ompl/base/spaces/DubinsStateSpace.h"
28 #include "ompl/base/spaces/ReedsSheppStateSpace.h"
30 #include "nav2_smac_planner/node_lattice.hpp"
32 using namespace std::chrono;
34 namespace nav2_smac_planner
38 LatticeMotionTable NodeLattice::motion_table;
39 float NodeLattice::size_lookup = 25;
40 LookupTable NodeLattice::dist_heuristic_lookup_table;
48 void LatticeMotionTable::initMotionModel(
49 unsigned int & size_x_in,
54 if (current_lattice_filepath == search_info.lattice_filepath) {
59 change_penalty = search_info.change_penalty;
60 non_straight_penalty = search_info.non_straight_penalty;
61 cost_penalty = search_info.cost_penalty;
62 reverse_penalty = search_info.reverse_penalty;
63 travel_distance_reward = 1.0f - search_info.retrospective_penalty;
64 current_lattice_filepath = search_info.lattice_filepath;
65 allow_reverse_expansion = search_info.allow_reverse_expansion;
66 rotation_penalty = search_info.rotation_penalty;
69 lattice_metadata = getLatticeMetadata(current_lattice_filepath);
70 std::ifstream latticeFile(current_lattice_filepath);
71 if (!latticeFile.is_open()) {
72 throw std::runtime_error(
"Could not open lattice file");
76 num_angle_quantization = lattice_metadata.number_of_headings;
79 if (!allow_reverse_expansion) {
80 state_space = std::make_unique<ompl::base::DubinsStateSpace>(
81 lattice_metadata.min_turning_radius);
83 state_space = std::make_unique<ompl::base::ReedsSheppStateSpace>(
84 lattice_metadata.min_turning_radius);
89 float prev_start_angle = 0.0;
90 std::vector<MotionPrimitive> primitives;
91 nlohmann::json json_primitives = json[
"primitives"];
92 for (
unsigned int i = 0; i < json_primitives.size(); ++i) {
94 fromJsonToMotionPrimitive(json_primitives[i], new_primitive);
96 if (prev_start_angle != new_primitive.start_angle) {
97 motion_primitives.push_back(primitives);
99 prev_start_angle = new_primitive.start_angle;
101 primitives.push_back(new_primitive);
103 motion_primitives.push_back(primitives);
106 trig_values.reserve(lattice_metadata.number_of_headings);
107 for (
unsigned int i = 0; i < lattice_metadata.heading_angles.size(); ++i) {
108 trig_values.emplace_back(
109 cos(lattice_metadata.heading_angles[i]),
110 sin(lattice_metadata.heading_angles[i]));
114 MotionPrimitivePtrs LatticeMotionTable::getMotionPrimitives(
const NodeLattice * node)
116 MotionPrimitives & prims_at_heading = motion_primitives[node->pose.theta];
117 MotionPrimitivePtrs primitive_projection_list;
118 for (
unsigned int i = 0; i != prims_at_heading.size(); i++) {
119 primitive_projection_list.push_back(&prims_at_heading[i]);
122 if (allow_reverse_expansion) {
124 double reserve_heading = node->pose.theta - (num_angle_quantization / 2);
125 if (reserve_heading < 0) {
126 reserve_heading += num_angle_quantization;
128 if (reserve_heading > num_angle_quantization) {
129 reserve_heading -= num_angle_quantization;
132 MotionPrimitives & prims_at_reverse_heading = motion_primitives[reserve_heading];
133 for (
unsigned int i = 0; i != prims_at_reverse_heading.size(); i++) {
134 primitive_projection_list.push_back(&prims_at_reverse_heading[i]);
138 return primitive_projection_list;
141 LatticeMetadata LatticeMotionTable::getLatticeMetadata(
const std::string & lattice_filepath)
143 std::ifstream lattice_file(lattice_filepath);
144 if (!lattice_file.is_open()) {
145 throw std::runtime_error(
"Could not open lattice file!");
151 fromJsonToMetaData(j[
"lattice_metadata"], metadata);
155 unsigned int LatticeMotionTable::getClosestAngularBin(
const double & theta)
157 float min_dist = std::numeric_limits<float>::max();
158 unsigned int closest_idx = 0;
160 for (
unsigned int i = 0; i != lattice_metadata.heading_angles.size(); i++) {
161 dist = fabs(angles::shortest_angular_distance(theta, lattice_metadata.heading_angles[i]));
162 if (dist < min_dist) {
170 float & LatticeMotionTable::getAngleFromBin(
const unsigned int & bin_idx)
172 return lattice_metadata.heading_angles[bin_idx];
175 NodeLattice::NodeLattice(
const unsigned int index)
177 pose(0.0f, 0.0f, 0.0f),
178 _cell_cost(std::numeric_limits<float>::quiet_NaN()),
179 _accumulated_cost(std::numeric_limits<float>::max()),
182 _motion_primitive(nullptr),
195 _cell_cost = std::numeric_limits<float>::quiet_NaN();
196 _accumulated_cost = std::numeric_limits<float>::max();
197 _was_visited =
false;
201 _motion_primitive =
nullptr;
206 const bool & traverse_unknown,
214 const double & angle = motion_table.
getAngleFromBin(this->pose.theta) / bin_size;
216 this->pose.x, this->pose.y, angle , traverse_unknown))
222 float max_cell_cost = collision_checker->
getCost();
225 if (motion_primitive) {
226 const float & grid_resolution = motion_table.lattice_metadata.grid_resolution;
227 const float & resolution_diag_sq = 2.0 * grid_resolution * grid_resolution;
228 MotionPose last_pose(1e9, 1e9, 1e9), pose_dist(0.0, 0.0, 0.0);
232 initial_pose._x = this->pose.x - (motion_primitive->poses.back()._x / grid_resolution);
233 initial_pose._y = this->pose.y - (motion_primitive->poses.back()._y / grid_resolution);
234 initial_pose._theta = motion_table.
getAngleFromBin(motion_primitive->start_angle);
236 for (
auto it = motion_primitive->poses.begin(); it != motion_primitive->poses.end(); ++it) {
238 pose_dist = *it - last_pose;
240 if (pose_dist._x * pose_dist._x + pose_dist._y * pose_dist._y > resolution_diag_sq) {
243 prim_pose._x = initial_pose._x + (it->_x / grid_resolution);
244 prim_pose._y = initial_pose._y + (it->_y / grid_resolution);
248 prim_pose._theta = std::fmod(it->_theta + M_PI, 2.0 * M_PI);
250 prim_pose._theta = it->_theta;
255 prim_pose._theta / bin_size ,
260 max_cell_cost = std::max(max_cell_cost, collision_checker->
getCost());
265 _cell_cost = max_cell_cost;
271 const float normalized_cost = child->
getCost() / 252.0;
272 if (std::isnan(normalized_cost)) {
273 throw std::runtime_error(
274 "Node attempted to get traversal "
275 "cost without a known collision cost!");
281 const float prim_length =
282 transition_prim->trajectory_length / motion_table.lattice_metadata.grid_resolution;
283 if (prim ==
nullptr) {
288 if (transition_prim->trajectory_length < 1e-4) {
289 return motion_table.rotation_penalty * (1.0 + motion_table.cost_penalty * normalized_cost);
292 float travel_cost = 0.0;
293 float travel_cost_raw = prim_length *
294 (motion_table.travel_distance_reward + motion_table.cost_penalty * normalized_cost);
296 if (transition_prim->arc_length < 0.001) {
298 travel_cost = travel_cost_raw;
300 if (prim->left_turn == transition_prim->left_turn) {
302 travel_cost = travel_cost_raw * motion_table.non_straight_penalty;
305 travel_cost = travel_cost_raw *
306 (motion_table.non_straight_penalty + motion_table.change_penalty);
313 travel_cost *= motion_table.reverse_penalty;
326 node_coords, goal_coords, motion_table.cost_penalty);
327 const float distance_heuristic =
329 return std::max(obstacle_heuristic, distance_heuristic);
333 const MotionModel & motion_model,
334 unsigned int & size_x,
339 if (motion_model != MotionModel::STATE_LATTICE) {
340 throw std::runtime_error(
341 "Invalid motion model for Lattice node. Please select"
342 " STATE_LATTICE and provide a valid lattice file.");
351 const float & obstacle_heuristic)
360 const TrigValues & trig_vals = motion_table.trig_values[goal_coords.theta];
361 const float cos_th = trig_vals.first;
362 const float sin_th = -trig_vals.second;
363 const float dx = node_coords.x - goal_coords.x;
364 const float dy = node_coords.y - goal_coords.y;
366 double dtheta_bin = node_coords.theta - goal_coords.theta;
367 if (dtheta_bin < 0) {
368 dtheta_bin += motion_table.num_angle_quantization;
370 if (dtheta_bin > motion_table.num_angle_quantization) {
371 dtheta_bin -= motion_table.num_angle_quantization;
375 round(dx * cos_th - dy * sin_th),
376 round(dx * sin_th + dy * cos_th),
382 float motion_heuristic = 0.0;
383 const int floored_size = floor(size_lookup / 2.0);
384 const int ceiling_size = ceil(size_lookup / 2.0);
385 const float mirrored_relative_y = abs(node_coords_relative.y);
386 if (abs(node_coords_relative.x) < floored_size && mirrored_relative_y < floored_size) {
389 if (node_coords_relative.y < 0.0) {
390 theta_pos = motion_table.num_angle_quantization - node_coords_relative.theta;
392 theta_pos = node_coords_relative.theta;
394 const int x_pos = node_coords_relative.x + floored_size;
395 const int y_pos =
static_cast<int>(mirrored_relative_y);
397 x_pos * ceiling_size * motion_table.num_angle_quantization +
398 y_pos * motion_table.num_angle_quantization +
400 motion_heuristic = dist_heuristic_lookup_table[index];
401 }
else if (obstacle_heuristic == 0.0) {
402 static ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
403 to[0] = goal_coords.x;
404 to[1] = goal_coords.y;
406 from[0] = node_coords.x;
407 from[1] = node_coords.y;
409 motion_heuristic = motion_table.state_space->distance(from(), to());
412 return motion_heuristic;
416 const float & lookup_table_dim,
417 const MotionModel & motion_model,
418 const unsigned int & dim_3_size,
422 if (!search_info.allow_reverse_expansion) {
423 motion_table.state_space = std::make_unique<ompl::base::DubinsStateSpace>(
424 search_info.minimum_turning_radius);
426 motion_table.state_space = std::make_unique<ompl::base::ReedsSheppStateSpace>(
427 search_info.minimum_turning_radius);
429 motion_table.lattice_metadata =
432 ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
436 size_lookup = lookup_table_dim;
437 float motion_heuristic = 0.0;
438 unsigned int index = 0;
439 int dim_3_size_int =
static_cast<int>(dim_3_size);
446 dist_heuristic_lookup_table.resize(size_lookup * ceil(size_lookup / 2.0) * dim_3_size_int);
447 for (
float x = ceil(-size_lookup / 2.0); x <= floor(size_lookup / 2.0); x += 1.0) {
448 for (
float y = 0.0; y <= floor(size_lookup / 2.0); y += 1.0) {
449 for (
int heading = 0; heading != dim_3_size_int; heading++) {
453 motion_heuristic = motion_table.state_space->distance(from(), to());
454 dist_heuristic_lookup_table[index] = motion_heuristic;
464 const bool & traverse_unknown,
465 NodeVector & neighbors)
467 unsigned int index = 0;
470 Coordinates initial_node_coords, motion_projection;
472 const float & grid_resolution = motion_table.lattice_metadata.grid_resolution;
474 unsigned int direction_change_idx = 1e9;
475 for (
unsigned int i = 0; i != motion_primitives.size(); i++) {
476 if (motion_primitives[0]->start_angle != motion_primitives[i]->start_angle) {
477 direction_change_idx = i;
482 for (
unsigned int i = 0; i != motion_primitives.size(); i++) {
483 const MotionPose & end_pose = motion_primitives[i]->poses.back();
484 motion_projection.x = this->pose.x + (end_pose._x / grid_resolution);
485 motion_projection.y = this->pose.y + (end_pose._y / grid_resolution);
486 motion_projection.theta = motion_primitives[i]->end_angle ;
493 if (i >= direction_change_idx) {
495 float opposite_heading_theta =
496 motion_projection.theta - (motion_table.num_angle_quantization / 2);
497 if (opposite_heading_theta < 0) {
498 opposite_heading_theta += motion_table.num_angle_quantization;
500 if (opposite_heading_theta > motion_table.num_angle_quantization) {
501 opposite_heading_theta -= motion_table.num_angle_quantization;
503 motion_projection.theta = opposite_heading_theta;
507 static_cast<unsigned int>(motion_projection.x),
508 static_cast<unsigned int>(motion_projection.y),
509 static_cast<unsigned int>(motion_projection.theta));
511 if (NeighborGetter(index, neighbor) && !neighbor->
wasVisited()) {
514 initial_node_coords = neighbor->pose;
519 motion_projection.theta));
524 traverse_unknown, collision_checker, motion_primitives[i],
backwards))
529 neighbors.push_back(neighbor);
531 neighbor->
setPose(initial_node_coords);
545 while (current_node->parent) {
547 current_node = current_node->parent;
558 NodeLattice::CoordinateVector & path)
562 const float & grid_resolution = NodeLattice::motion_table.lattice_metadata.grid_resolution;
567 initial_pose.x = current_node->pose.x - (prim->poses.back()._x / grid_resolution);
568 initial_pose.y = current_node->pose.y - (prim->poses.back()._y / grid_resolution);
569 initial_pose.theta = NodeLattice::motion_table.getAngleFromBin(prim->start_angle);
571 for (
auto it = prim->poses.crbegin(); it != prim->poses.crend(); ++it) {
573 prim_pose.x = initial_pose.x + (it->_x / grid_resolution);
574 prim_pose.y = initial_pose.y + (it->_y / grid_resolution);
578 prim_pose.theta = std::fmod(it->_theta + M_PI, 2.0 * M_PI);
580 prim_pose.theta = it->_theta;
582 path.push_back(prim_pose);
586 path.push_back(current_node->pose);
587 path.back().theta = NodeLattice::motion_table.getAngleFromBin(path.back().theta);
A 2D costmap provides a mapping between points in the world and their associated "costs".
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.
std::vector< float > & getPrecomputedAngles()
Get the angles of the precomputed footprint orientations.
float getCost()
Get cost at footprint pose in costmap.
NodeLattice implementation for graph, Hybrid-A*.
void backwards(bool back=true)
Sets that this primitive is moving in reverse.
~NodeLattice()
A destructor for nav2_smac_planner::NodeLattice.
void reset()
Reset method for new search.
bool backtracePath(CoordinateVector &path)
Set the starting pose for planning, as a node index.
float getTraversalCost(const NodePtr &child)
Get traversal cost of parent node to child node.
bool isNodeValid(const bool &traverse_unknown, GridCollisionChecker *collision_checker, MotionPrimitive *primitive=nullptr, bool is_backwards=false)
Check if this node is valid.
static float getHeuristicCost(const Coordinates &node_coords, const Coordinates &goal_coordinates, const nav2_costmap_2d::Costmap2D *costmap)
Get cost of heuristic of node.
unsigned int & getIndex()
Gets cell index.
void addNodeToPath(NodePtr current_node, CoordinateVector &path)
add node to the path
bool isBackward()
Gets if this primitive is moving in reverse.
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.
MotionPrimitive *& getMotionPrimitive()
Gets the motion primitive used to achieve node in search.
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.
void getNeighbors(std::function< bool(const unsigned int &, nav2_smac_planner::NodeLattice *&)> &validity_checker, GridCollisionChecker *collision_checker, const bool &traverse_unknown, NodeVector &neighbors)
Retrieve all valid neighbors of a node.
static float getObstacleHeuristic(const Coordinates &node_coords, const Coordinates &goal_coords, const double &cost_penalty)
Compute the Obstacle heuristic.
void setMotionPrimitive(MotionPrimitive *prim)
Sets the motion primitive used to achieve node in search.
bool & wasVisited()
Gets if cell has been visited in search.
static float getDistanceHeuristic(const Coordinates &node_coords, const Coordinates &goal_coords, const float &obstacle_heuristic)
Compute the Distance heuristic.
void setPose(const Coordinates &pose_in)
setting continuous coordinate search poses (in partial-cells)
static LatticeMetadata getLatticeMetadata(const std::string &lattice_filepath)
Get file metadata needed.
MotionPrimitivePtrs getMotionPrimitives(const NodeLattice *node)
Get projections of motion models.
void initMotionModel(unsigned int &size_x_in, SearchInfo &search_info)
Initializing state lattice planner's motion model.
float & getAngleFromBin(const unsigned int &bin_idx)
Get the raw orientation from an angular bin.
A struct for poses in motion primitives.
A struct of all motion primitive data.
NodeHybrid implementation of coordinate structure.
Search properties and penalties.