25 #include "angles/angles.h"
27 #include "ompl/base/ScopedState.h"
28 #include "ompl/base/spaces/DubinsStateSpace.h"
29 #include "ompl/base/spaces/ReedsSheppStateSpace.h"
31 #include "nav2_smac_planner/node_lattice.hpp"
33 using namespace std::chrono;
35 namespace nav2_smac_planner
39 LatticeMotionTable NodeLattice::motion_table;
40 float NodeLattice::size_lookup = 25;
41 LookupTable NodeLattice::dist_heuristic_lookup_table;
49 void LatticeMotionTable::initMotionModel(
50 unsigned int & size_x_in,
55 if (current_lattice_filepath == search_info.lattice_filepath) {
60 change_penalty = search_info.change_penalty;
61 non_straight_penalty = search_info.non_straight_penalty;
62 cost_penalty = search_info.cost_penalty;
63 reverse_penalty = search_info.reverse_penalty;
64 travel_distance_reward = 1.0f - search_info.retrospective_penalty;
65 current_lattice_filepath = search_info.lattice_filepath;
66 allow_reverse_expansion = search_info.allow_reverse_expansion;
67 rotation_penalty = search_info.rotation_penalty;
68 min_turning_radius = search_info.minimum_turning_radius;
71 lattice_metadata = getLatticeMetadata(current_lattice_filepath);
72 std::ifstream latticeFile(current_lattice_filepath);
73 if (!latticeFile.is_open()) {
74 throw std::runtime_error(
"Could not open lattice file");
78 num_angle_quantization = lattice_metadata.number_of_headings;
81 if (!allow_reverse_expansion) {
82 state_space = std::make_shared<ompl::base::DubinsStateSpace>(
83 lattice_metadata.min_turning_radius);
84 motion_model = MotionModel::DUBIN;
86 state_space = std::make_shared<ompl::base::ReedsSheppStateSpace>(
87 lattice_metadata.min_turning_radius);
88 motion_model = MotionModel::REEDS_SHEPP;
93 float prev_start_angle = 0.0;
94 std::vector<MotionPrimitive> primitives;
95 nlohmann::json json_primitives = json[
"primitives"];
96 for (
unsigned int i = 0; i < json_primitives.size(); ++i) {
98 fromJsonToMotionPrimitive(json_primitives[i], new_primitive);
100 if (prev_start_angle != new_primitive.start_angle) {
101 motion_primitives.push_back(primitives);
103 prev_start_angle = new_primitive.start_angle;
105 primitives.push_back(new_primitive);
107 motion_primitives.push_back(primitives);
110 trig_values.reserve(lattice_metadata.number_of_headings);
111 for (
unsigned int i = 0; i < lattice_metadata.heading_angles.size(); ++i) {
112 trig_values.emplace_back(
113 cos(lattice_metadata.heading_angles[i]),
114 sin(lattice_metadata.heading_angles[i]));
118 MotionPrimitivePtrs LatticeMotionTable::getMotionPrimitives(
120 unsigned int & direction_change_index)
122 MotionPrimitives & prims_at_heading = motion_primitives[node->pose.theta];
123 MotionPrimitivePtrs primitive_projection_list;
124 for (
unsigned int i = 0; i != prims_at_heading.size(); i++) {
125 primitive_projection_list.push_back(&prims_at_heading[i]);
129 direction_change_index =
static_cast<unsigned int>(primitive_projection_list.size());
131 if (allow_reverse_expansion) {
133 double reserve_heading = node->pose.theta - (num_angle_quantization / 2);
134 if (reserve_heading < 0) {
135 reserve_heading += num_angle_quantization;
137 if (reserve_heading > num_angle_quantization) {
138 reserve_heading -= num_angle_quantization;
141 MotionPrimitives & prims_at_reverse_heading = motion_primitives[reserve_heading];
142 for (
unsigned int i = 0; i != prims_at_reverse_heading.size(); i++) {
143 primitive_projection_list.push_back(&prims_at_reverse_heading[i]);
147 return primitive_projection_list;
150 LatticeMetadata LatticeMotionTable::getLatticeMetadata(
const std::string & lattice_filepath)
152 std::ifstream lattice_file(lattice_filepath);
153 if (!lattice_file.is_open()) {
154 throw std::runtime_error(
"Could not open lattice file!");
160 fromJsonToMetaData(j[
"lattice_metadata"], metadata);
164 unsigned int LatticeMotionTable::getClosestAngularBin(
const double & theta)
166 float min_dist = std::numeric_limits<float>::max();
167 unsigned int closest_idx = 0;
169 for (
unsigned int i = 0; i != lattice_metadata.heading_angles.size(); i++) {
170 dist = fabs(angles::shortest_angular_distance(theta, lattice_metadata.heading_angles[i]));
171 if (dist < min_dist) {
179 float & LatticeMotionTable::getAngleFromBin(
const unsigned int & bin_idx)
181 return lattice_metadata.heading_angles[bin_idx];
184 double LatticeMotionTable::getAngle(
const double & theta)
186 return getClosestAngularBin(theta);
189 NodeLattice::NodeLattice(
const uint64_t index)
191 pose(0.0f, 0.0f, 0.0f),
192 _cell_cost(std::numeric_limits<float>::quiet_NaN()),
193 _accumulated_cost(std::numeric_limits<float>::max()),
196 _motion_primitive(nullptr),
198 _is_node_valid(false)
210 _cell_cost = std::numeric_limits<float>::quiet_NaN();
211 _accumulated_cost = std::numeric_limits<float>::max();
212 _was_visited =
false;
216 _motion_primitive =
nullptr;
218 _is_node_valid =
false;
222 const bool & traverse_unknown,
228 if (!std::isnan(_cell_cost)) {
229 return _is_node_valid;
235 const double & angle = motion_table.
getAngleFromBin(this->pose.theta) / bin_size;
237 this->pose.x, this->pose.y, angle , traverse_unknown))
239 _is_node_valid =
false;
240 _cell_cost = collision_checker->
getCost();
245 float max_cell_cost = collision_checker->
getCost();
248 if (motion_primitive) {
249 const float & grid_resolution = motion_table.lattice_metadata.grid_resolution;
250 const float & resolution_diag_sq = 2.0 * grid_resolution * grid_resolution;
251 MotionPose last_pose(1e9, 1e9, 1e9, TurnDirection::UNKNOWN);
252 MotionPose pose_dist(0.0, 0.0, 0.0, TurnDirection::UNKNOWN);
256 initial_pose._x = this->pose.x - (motion_primitive->poses.back()._x / grid_resolution);
257 initial_pose._y = this->pose.y - (motion_primitive->poses.back()._y / grid_resolution);
258 initial_pose._theta = motion_table.
getAngleFromBin(motion_primitive->start_angle);
260 for (
auto it = motion_primitive->poses.begin(); it != motion_primitive->poses.end(); ++it) {
262 pose_dist = *it - last_pose;
264 if (pose_dist._x * pose_dist._x + pose_dist._y * pose_dist._y > resolution_diag_sq) {
267 prim_pose._x = initial_pose._x + (it->_x / grid_resolution);
268 prim_pose._y = initial_pose._y + (it->_y / grid_resolution);
272 prim_pose._theta = std::fmod(it->_theta + M_PI, 2.0 * M_PI);
274 prim_pose._theta = it->_theta;
279 prim_pose._theta / bin_size ,
282 _is_node_valid =
false;
283 _cell_cost = std::max(max_cell_cost, collision_checker->
getCost());
286 max_cell_cost = std::max(max_cell_cost, collision_checker->
getCost());
291 _cell_cost = max_cell_cost;
292 _is_node_valid =
true;
293 return _is_node_valid;
298 const float normalized_cost = child->
getCost() / 252.0;
299 if (std::isnan(normalized_cost)) {
300 throw std::runtime_error(
301 "Node attempted to get traversal "
302 "cost without a known collision cost!");
308 const float prim_length =
309 transition_prim->trajectory_length / motion_table.lattice_metadata.grid_resolution;
310 if (prim ==
nullptr) {
315 if (transition_prim->trajectory_length < 1e-4) {
316 return motion_table.rotation_penalty * (1.0 + motion_table.cost_penalty * normalized_cost);
319 float travel_cost = 0.0;
320 float travel_cost_raw = prim_length *
321 (motion_table.travel_distance_reward + motion_table.cost_penalty * normalized_cost);
323 if (transition_prim->arc_length < 0.001) {
325 travel_cost = travel_cost_raw;
327 if (prim->left_turn == transition_prim->left_turn) {
329 travel_cost = travel_cost_raw * motion_table.non_straight_penalty;
332 travel_cost = travel_cost_raw *
333 (motion_table.non_straight_penalty + motion_table.change_penalty);
340 travel_cost *= motion_table.reverse_penalty;
348 const CoordinateVector & goals_coords)
353 node_coords, goals_coords[0], motion_table.cost_penalty);
354 float distance_heuristic = std::numeric_limits<float>::max();
355 for (
unsigned int i = 0; i < goals_coords.size(); i++) {
356 distance_heuristic = std::min(
360 return std::max(obstacle_heuristic, distance_heuristic);
364 const MotionModel & motion_model,
365 unsigned int & size_x,
370 if (motion_model != MotionModel::STATE_LATTICE) {
371 throw std::runtime_error(
372 "Invalid motion model for Lattice node. Please select"
373 " STATE_LATTICE and provide a valid lattice file.");
382 const float & obstacle_heuristic)
391 const TrigValues & trig_vals = motion_table.trig_values[goal_coords.theta];
392 const float cos_th = trig_vals.first;
393 const float sin_th = -trig_vals.second;
394 const float dx = node_coords.x - goal_coords.x;
395 const float dy = node_coords.y - goal_coords.y;
397 double dtheta_bin = node_coords.theta - goal_coords.theta;
398 if (dtheta_bin < 0) {
399 dtheta_bin += motion_table.num_angle_quantization;
401 if (dtheta_bin > motion_table.num_angle_quantization) {
402 dtheta_bin -= motion_table.num_angle_quantization;
406 round(dx * cos_th - dy * sin_th),
407 round(dx * sin_th + dy * cos_th),
413 float motion_heuristic = 0.0;
414 const int floored_size = floor(size_lookup / 2.0);
415 const int ceiling_size = ceil(size_lookup / 2.0);
416 const float mirrored_relative_y = abs(node_coords_relative.y);
417 if (abs(node_coords_relative.x) < floored_size && mirrored_relative_y < floored_size) {
420 if (node_coords_relative.y < 0.0) {
421 theta_pos = motion_table.num_angle_quantization - node_coords_relative.theta;
423 theta_pos = node_coords_relative.theta;
425 const int x_pos = node_coords_relative.x + floored_size;
426 const int y_pos =
static_cast<int>(mirrored_relative_y);
428 x_pos * ceiling_size * motion_table.num_angle_quantization +
429 y_pos * motion_table.num_angle_quantization +
431 motion_heuristic = dist_heuristic_lookup_table[index];
432 }
else if (obstacle_heuristic == 0.0) {
433 static ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
434 to[0] = goal_coords.x;
435 to[1] = goal_coords.y;
437 from[0] = node_coords.x;
438 from[1] = node_coords.y;
440 motion_heuristic = motion_table.state_space->distance(from(), to());
443 return motion_heuristic;
447 const float & lookup_table_dim,
448 const MotionModel & ,
449 const unsigned int & dim_3_size,
453 if (!search_info.allow_reverse_expansion) {
454 motion_table.state_space = std::make_shared<ompl::base::DubinsStateSpace>(
455 search_info.minimum_turning_radius);
456 motion_table.motion_model = MotionModel::DUBIN;
458 motion_table.state_space = std::make_shared<ompl::base::ReedsSheppStateSpace>(
459 search_info.minimum_turning_radius);
460 motion_table.motion_model = MotionModel::REEDS_SHEPP;
462 motion_table.lattice_metadata =
465 ompl::base::ScopedState<> from(motion_table.state_space), to(motion_table.state_space);
469 size_lookup = lookup_table_dim;
470 float motion_heuristic = 0.0;
471 unsigned int index = 0;
472 int dim_3_size_int =
static_cast<int>(dim_3_size);
479 dist_heuristic_lookup_table.resize(size_lookup * ceil(size_lookup / 2.0) * dim_3_size_int);
480 for (
float x = ceil(-size_lookup / 2.0); x <= floor(size_lookup / 2.0); x += 1.0) {
481 for (
float y = 0.0; y <= floor(size_lookup / 2.0); y += 1.0) {
482 for (
int heading = 0; heading != dim_3_size_int; heading++) {
486 motion_heuristic = motion_table.state_space->distance(from(), to());
487 dist_heuristic_lookup_table[index] = motion_heuristic;
495 std::function<
bool(
const uint64_t &,
498 const bool & traverse_unknown,
499 NodeVector & neighbors)
504 Coordinates initial_node_coords, motion_projection;
505 unsigned int direction_change_index = 0;
508 direction_change_index);
509 const float & grid_resolution = motion_table.lattice_metadata.grid_resolution;
511 for (
unsigned int i = 0; i != motion_primitives.size(); i++) {
512 const MotionPose & end_pose = motion_primitives[i]->poses.back();
513 motion_projection.x = this->pose.x + (end_pose._x / grid_resolution);
514 motion_projection.y = this->pose.y + (end_pose._y / grid_resolution);
515 motion_projection.theta = motion_primitives[i]->end_angle ;
522 if (i >= direction_change_index) {
524 float opposite_heading_theta =
525 motion_projection.theta - (motion_table.num_angle_quantization / 2);
526 if (opposite_heading_theta < 0) {
527 opposite_heading_theta += motion_table.num_angle_quantization;
529 if (opposite_heading_theta > motion_table.num_angle_quantization) {
530 opposite_heading_theta -= motion_table.num_angle_quantization;
532 motion_projection.theta = opposite_heading_theta;
536 static_cast<unsigned int>(motion_projection.x),
537 static_cast<unsigned int>(motion_projection.y),
538 static_cast<unsigned int>(motion_projection.theta));
540 if (NeighborGetter(index, neighbor) && !neighbor->
wasVisited()) {
543 initial_node_coords = neighbor->pose;
549 motion_projection.theta));
554 traverse_unknown, collision_checker, motion_primitives[i],
backwards))
559 neighbors.push_back(neighbor);
561 neighbor->
setPose(initial_node_coords);
575 while (current_node->parent) {
577 current_node = current_node->parent;
588 NodeLattice::CoordinateVector & path)
592 const float & grid_resolution = NodeLattice::motion_table.lattice_metadata.grid_resolution;
597 initial_pose.x = current_node->pose.x - (prim->poses.back()._x / grid_resolution);
598 initial_pose.y = current_node->pose.y - (prim->poses.back()._y / grid_resolution);
599 initial_pose.theta = NodeLattice::motion_table.getAngleFromBin(prim->start_angle);
601 for (
auto it = prim->poses.crbegin(); it != prim->poses.crend(); ++it) {
603 prim_pose.x = initial_pose.x + (it->_x / grid_resolution);
604 prim_pose.y = initial_pose.y + (it->_y / grid_resolution);
608 prim_pose.theta = std::fmod(it->_theta + M_PI, 2.0 * M_PI);
610 prim_pose.theta = it->_theta;
612 path.push_back(prim_pose);
616 path.push_back(current_node->pose);
617 path.back().theta = NodeLattice::motion_table.getAngleFromBin(path.back().theta);
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 getNeighbors(std::function< bool(const uint64_t &, nav2_smac_planner::NodeLattice *&)> &validity_checker, GridCollisionChecker *collision_checker, const bool &traverse_unknown, NodeVector &neighbors)
Retrieve all valid neighbors of a node.
void backwards(bool back=true)
Sets that this primitive is moving in reverse.
uint64_t getIndex()
Gets cell index.
~NodeLattice()
A destructor for nav2_smac_planner::NodeLattice.
float getCost()
Gets the costmap cost at this node.
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 CoordinateVector &goals_coords)
Get cost of heuristic of node.
void addNodeToPath(NodePtr current_node, CoordinateVector &path)
add node to the path
bool isBackward()
Gets if this primitive is moving in reverse.
bool wasVisited()
Gets if cell has been visited in search.
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.
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.
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.
void initMotionModel(unsigned int &size_x_in, SearchInfo &search_info)
Initializing state lattice planner's motion model.
MotionPrimitivePtrs getMotionPrimitives(const NodeLattice *node, unsigned int &direction_change_index)
Get projections of motion models.
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.