Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
planner_tester.hpp
1 // Copyright (c) 2018 Intel Corporation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License. Reserved.
14 
15 #ifndef PLANNING__PLANNER_TESTER_HPP_
16 #define PLANNING__PLANNER_TESTER_HPP_
17 
18 #include <gtest/gtest.h>
19 #include <memory>
20 #include <string>
21 #include <thread>
22 #include <vector>
23 #include <algorithm>
24 
25 #include "nav2_ros_common/lifecycle_node.hpp"
26 #include "nav2_msgs/action/compute_path_to_pose.hpp"
27 #include "nav_msgs/msg/occupancy_grid.hpp"
28 #include "nav2_msgs/msg/costmap.hpp"
29 #include "nav2_msgs/srv/get_costmap.hpp"
30 #include "nav2_msgs/srv/is_path_valid.hpp"
31 #include "nav2_util/costmap.hpp"
32 #include "nav2_ros_common/node_thread.hpp"
33 #include "geometry_msgs/msg/pose_stamped.hpp"
34 #include "geometry_msgs/msg/transform_stamped.hpp"
35 #include "nav2_planner/planner_server.hpp"
36 #include "nav2_ros_common/tf2_factories.hpp"
37 
38 namespace nav2_system_tests
39 {
40 
42 {
43 public:
45  : PlannerServer()
46  {
47  }
48 
49  void printCostmap()
50  {
51  // print costmap for debug
52  for (size_t i = 0; i != costmap_->getSizeInCellsX() * costmap_->getSizeInCellsY(); i++) {
53  if (i % costmap_->getSizeInCellsX() == 0) {
54  std::cout << "" << std::endl;
55  }
56  std::cout << costmap_ros_->getCostmap()->getCharMap()[i] << " ";
57  }
58  std::cout << "" << std::endl;
59  }
60 
61  void setCostmap(nav2_util::Costmap * costmap)
62  {
63  std::unique_lock<nav2_costmap_2d::Costmap2D::mutex_t> lock(
64  *(costmap_ros_->getCostmap()->getMutex()));
65 
66  nav2_msgs::msg::CostmapMetaData prop;
67  nav2_msgs::msg::Costmap cm = costmap->get_costmap(prop);
68  prop = cm.metadata;
69  costmap_ros_->getCostmap()->resizeMap(
70  prop.size_x, prop.size_y,
71  prop.resolution, prop.origin.position.x, prop.origin.position.x);
72  // Volatile prevents compiler from treating costmap_ptr as unused or changing its address
73  volatile unsigned char * costmap_ptr = costmap_ros_->getCostmap()->getCharMap();
74  delete[] costmap_ptr;
75  costmap_ptr = new unsigned char[prop.size_x * prop.size_y];
76  std::copy(cm.data.begin(), cm.data.end(), costmap_ptr);
77  }
78 
79  bool createPath(
80  const geometry_msgs::msg::PoseStamped & goal,
81  nav_msgs::msg::Path & path)
82  {
83  geometry_msgs::msg::PoseStamped start;
84  if (!nav2_util::getCurrentPose(start, *tf_, "map", "base_link", 0.1)) {
85  return false;
86  }
87  try {
88  auto dummy_cancel_checker = []() {return false;};
89  std::vector<geometry_msgs::msg::PoseStamped> viapoints{start};
90  path = planners_["GridBased"]->createPlan(start, goal, viapoints, dummy_cancel_checker);
91  // The situation when createPlan() did not throw any exception
92  // does not guarantee that plan was created correctly.
93  // So it should be checked additionally that path is correct.
94  if (!path.poses.size()) {
95  return false;
96  }
97  } catch (...) {
98  return false;
99  }
100  return true;
101  }
102 
103  void onCleanup(const rclcpp_lifecycle::State & state)
104  {
105  on_cleanup(state);
106  }
107 
108  void onActivate(const rclcpp_lifecycle::State & state)
109  {
110  on_activate(state);
111  }
112 
113  void onDeactivate(const rclcpp_lifecycle::State & state)
114  {
115  on_deactivate(state);
116  }
117 
118  void onConfigure(const rclcpp_lifecycle::State & state)
119  {
120  on_configure(state);
121  }
122 };
123 
124 enum class TaskStatus : int8_t
125 {
126  SUCCEEDED = 1,
127  FAILED = 2,
128  RUNNING = 3,
129 };
130 
132 {
133 public:
134  using ComputePathToPoseCommand = geometry_msgs::msg::PoseStamped;
135  using ComputePathToPoseResult = nav_msgs::msg::Path;
136 
137  PlannerTester();
138  ~PlannerTester();
139 
140  // Activate the tester before running tests
141  void activate();
142  void deactivate();
143 
144  // Loads the provided map and and generates a costmap from it.
145  void loadDefaultMap();
146 
147  // Alternatively, use a preloaded 10x10 costmap
148  void loadSimpleCostmap(const nav2_util::TestCostmap & testCostmapType);
149 
150  // Runs a single test with default poses depending on the loaded map
151  // Success criteria is a collision free path and a deviation to a
152  // reference path smaller than a tolerance.
153  bool defaultPlannerTest(
154  ComputePathToPoseResult & path,
155  const double deviation_tolerance = 1.0);
156 
157 
158  // Runs multiple tests with random initial and goal poses
159  bool defaultPlannerRandomTests(
160  const unsigned int number_tests,
161  const float acceptable_fail_ratio);
162 
163  std::shared_ptr<nav2_msgs::srv::IsPathValid::Response> isPathValid(
164  nav_msgs::msg::Path & path, unsigned int max_cost,
165  bool consider_unknown_as_obstacle, const std::string & layer_name = "",
166  const std::string & footprint = "", bool stop_at_first_collision = true,
167  double max_lookahead_distance = -1.0);
168 
169 private:
170  void setCostmap();
171 
172  TaskStatus createPlan(
173  const ComputePathToPoseCommand & goal,
174  ComputePathToPoseResult & path
175  );
176 
177  bool is_active_;
178  bool map_set_;
179  bool costmap_set_;
180  bool using_fake_costmap_;
181 
182  // Parameters of the costmap
183  bool trinary_costmap_;
184  bool track_unknown_space_;
185  int lethal_threshold_;
186  int unknown_cost_value_;
187  nav2_util::TestCostmap testCostmapType_;
188 
189  // The static map
190  std::shared_ptr<nav_msgs::msg::OccupancyGrid> map_;
191 
192  // The costmap representation of the static map
193  std::unique_ptr<nav2_util::Costmap> costmap_;
194 
195  // The global planner
196  std::shared_ptr<NavFnPlannerTester> planner_tester_;
197 
198  // The is path valid client
199  nav2::ServiceClient<nav2_msgs::srv::IsPathValid>::SharedPtr path_valid_client_;
200 
201  // A thread for spinning the ROS node
202  std::unique_ptr<nav2::NodeThread> spin_thread_;
203 
204  // The tester must provide the robot pose through a transform
205  std::unique_ptr<geometry_msgs::msg::TransformStamped> base_transform_;
206  nav2::TransformBroadcaster::SharedPtr tf_broadcaster_;
207  rclcpp::TimerBase::SharedPtr transform_timer_;
208  void publishRobotTransform();
209  void startRobotTransform();
210  void updateRobotPosition(const geometry_msgs::msg::Point & position);
211 
212  // Occupancy grid publisher for visualization
213  nav2::Publisher<nav_msgs::msg::OccupancyGrid>::SharedPtr map_pub_;
214  rclcpp::TimerBase::SharedPtr map_timer_;
215  void mapCallback();
216 
217  // Executes a test run with the provided end points.
218  // Success criteria is a collision free path.
219  // TODO(orduno): #443 Assuming a robot the size of a costmap cell
220  bool plannerTest(
221  const geometry_msgs::msg::Point & robot_position,
222  const ComputePathToPoseCommand & goal,
223  ComputePathToPoseResult & path);
224 
225  bool isCollisionFree(const ComputePathToPoseResult & path);
226 
227  bool isWithinTolerance(
228  const geometry_msgs::msg::Point & robot_position,
229  const ComputePathToPoseCommand & goal,
230  const ComputePathToPoseResult & path) const;
231 
232  bool isWithinTolerance(
233  const geometry_msgs::msg::Point & robot_position,
234  const ComputePathToPoseCommand & goal,
235  const ComputePathToPoseResult & path,
236  const double deviationTolerance,
237  const ComputePathToPoseResult & reference_path) const;
238 
239  void printPath(const ComputePathToPoseResult & path) const;
240 };
241 
242 } // namespace nav2_system_tests
243 
244 #endif // PLANNING__PLANNER_TESTER_HPP_
A lifecycle node wrapper to enable common Nav2 needs such as manipulating parameters.
unsigned int getSizeInCellsX() const
Accessor for the x size of the costmap in cells.
Definition: costmap_2d.cpp:548
unsigned int getSizeInCellsY() const
Accessor for the y size of the costmap in cells.
Definition: costmap_2d.cpp:553
An action server implements the behavior tree's ComputePathToPose interface and hosts various plugins...
nav2::CallbackReturn on_configure(const rclcpp_lifecycle::State &state) override
Configure member variables and initializes planner.
nav2::CallbackReturn on_deactivate(const rclcpp_lifecycle::State &state) override
Deactivate member variables.
PlannerServer(const rclcpp::NodeOptions &options=rclcpp::NodeOptions())
A constructor for nav2_planner::PlannerServer.
nav2::CallbackReturn on_cleanup(const rclcpp_lifecycle::State &state) override
Reset member variables.
nav2::CallbackReturn on_activate(const rclcpp_lifecycle::State &state) override
Activate member variables.
Class for a single layered costmap initialized from an occupancy grid representing the map.
Definition: costmap.hpp:45
nav2_msgs::msg::Costmap get_costmap(const nav2_msgs::msg::CostmapMetaData &specifications)
Get a costmap message from this object.
Definition: costmap.cpp:108