moveit2
The MoveIt Motion Planning Framework for ROS 2.
Loading...
Searching...
No Matches
BenchmarkExecutor.cpp
Go to the documentation of this file.
1/*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2015, Rice University
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
17 * * Neither the name of the Rice University nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 *********************************************************************/
34
35/* Author: Ryan Luna */
36
42#include <moveit/version.hpp>
43#include <tf2_eigen/tf2_eigen.hpp>
45
46#include <regex>
47#include <boost/regex.hpp>
48
49#if __has_include(<boost/timer/progress_display.hpp>)
50#include <boost/timer/progress_display.hpp>
51using boost_progress_display = boost::timer::progress_display;
52#else
53// boost < 1.72
54#define BOOST_TIMER_ENABLE_DEPRECATED 1
55#include <boost/progress.hpp>
56#undef BOOST_TIMER_ENABLE_DEPRECATED
57using boost_progress_display = boost::progress_display;
58#endif
59
60#include <boost/math/constants/constants.hpp>
61#include <boost/filesystem.hpp>
62#include <boost/date_time/posix_time/posix_time.hpp>
63#include <math.h>
64#include <limits>
65#include <filesystem>
66#ifndef _WIN32
67#include <unistd.h>
68#else
69#include <winsock2.h>
70#endif
71
72#undef max
73
74using namespace moveit_ros_benchmarks;
75
76namespace
77{
78rclcpp::Logger getLogger()
79{
80 return moveit::getLogger("moveit.benchmarks.executor");
81}
82} // namespace
83
84template <class Clock, class Duration>
85boost::posix_time::ptime toBoost(const std::chrono::time_point<Clock, Duration>& from)
86{
87 typedef std::chrono::nanoseconds duration_t;
88 typedef long rep_t;
89 rep_t d = std::chrono::duration_cast<duration_t>(from.time_since_epoch()).count();
90 rep_t sec = d / 1000000000;
91 rep_t nsec = d % 1000000000;
92 namespace pt = boost::posix_time;
93#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS
94 return pt::from_time_t(sec) + pt::nanoseconds(nsec)
95#else
96 return pt::from_time_t(sec) + pt::microseconds(nsec / 1000);
97#endif
98}
99
100BenchmarkExecutor::BenchmarkExecutor(const rclcpp::Node::SharedPtr& node, const std::string& robot_descriptionparam)
101 : planning_scene_monitor_{ std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(node,
102 robot_descriptionparam) }
103 , planning_scene_storage_{ nullptr }
104 , planning_scene_world_storage_{ nullptr }
105 , robot_state_storage_{ nullptr }
106 , constraints_storage_{ nullptr }
107 , trajectory_constraints_storage_{ nullptr }
108 , node_{ node }
109 , db_loader_{ node }
110{
111 planning_scene_ = planning_scene_monitor_->getPlanningScene();
112}
113
117
118[[nodiscard]] bool BenchmarkExecutor::initialize(const std::vector<std::string>& planning_pipeline_names)
119{
120 // Initialize moveit_cpp
121 moveit_cpp_ = std::make_shared<moveit_cpp::MoveItCpp>(node_);
122
123 for (const std::string& planning_pipeline_name : planning_pipeline_names)
124 {
125 if (moveit_cpp_->getPlanningPipelines().find(planning_pipeline_name) == moveit_cpp_->getPlanningPipelines().end())
126 {
127 RCLCPP_ERROR(getLogger(), "Cannot find pipeline '%s'", planning_pipeline_name.c_str());
128 return false;
129 }
130
131 const auto& pipeline = moveit_cpp_->getPlanningPipelines().at(planning_pipeline_name);
132 // Verify the pipeline has successfully initialized a planner
133 if (!pipeline)
134 {
135 RCLCPP_ERROR(getLogger(), "Failed to initialize planning pipeline '%s'", planning_pipeline_name.c_str());
136 continue;
137 }
138 }
139
140 // Error check
141 if (moveit_cpp_->getPlanningPipelines().empty())
142 {
143 RCLCPP_ERROR(getLogger(), "No planning pipelines have been loaded. Nothing to do for the benchmarking service.");
144 }
145 else
146 {
147 RCLCPP_INFO(getLogger(), "Available planning pipelines:");
148 for (const std::pair<const std::string, planning_pipeline::PlanningPipelinePtr>& entry :
149 moveit_cpp_->getPlanningPipelines())
150 {
151 RCLCPP_INFO_STREAM(getLogger(), entry.first);
152 }
153 }
154 return true;
155}
156
158{
160 {
162 }
164 {
166 }
168 {
169 robot_state_storage_.reset();
170 }
172 {
173 constraints_storage_.reset();
174 }
176 {
178 }
179
180 benchmark_data_.clear();
181 pre_event_functions_.clear();
182 post_event_functions_.clear();
186 query_end_functions_.clear();
187}
188
190{
191 pre_event_functions_.push_back(func);
192}
193
198
203
208
213
218
220{
221 if (moveit_cpp_->getPlanningPipelines().empty())
222 {
223 RCLCPP_ERROR(getLogger(), "No planning pipelines configured. Did you call BenchmarkExecutor::initialize?");
224 return false;
225 }
226
227 std::vector<BenchmarkRequest> queries;
228 moveit_msgs::msg::PlanningScene scene_msg;
229
230 if (initializeBenchmarks(options, scene_msg, queries))
231 {
232 for (std::size_t i = 0; i < queries.size(); ++i)
233 {
234 // Configure planning scene
235 if (scene_msg.robot_model_name != planning_scene_->getRobotModel()->getName())
236 {
237 // Clear all geometry from the scene
238 planning_scene_->getWorldNonConst()->clearObjects();
239 planning_scene_->getCurrentStateNonConst().clearAttachedBodies();
240 planning_scene_->getCurrentStateNonConst().setToDefaultValues();
241
242 planning_scene_->processPlanningSceneWorldMsg(scene_msg.world);
243 }
244 else
245 {
246 planning_scene_->usePlanningSceneMsg(scene_msg);
247 }
248
249 // Calling query start events
250 for (QueryStartEventFunction& query_start_fn : query_start_functions_)
251 {
252 query_start_fn(queries[i].request, planning_scene_);
253 }
254
255 RCLCPP_INFO(getLogger(), "Benchmarking query '%s' (%lu of %lu)", queries[i].name.c_str(), i + 1, queries.size());
256 std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
257 runBenchmark(queries[i].request, options);
258 std::chrono::duration<double> dt = std::chrono::system_clock::now() - start_time;
259 double duration = dt.count();
260
262 {
263 query_end_fn(queries[i].request, planning_scene_);
264 }
265
266 writeOutput(queries[i], boost::posix_time::to_iso_extended_string(toBoost(start_time)), duration, options);
267 }
268
269 return true;
270 }
271 return false;
272}
273
275 moveit_msgs::msg::PlanningScene& scene_msg,
276 std::vector<BenchmarkRequest>& requests)
277{
278 if (!pipelinesExist(options.planning_pipelines))
279 {
280 return false;
281 }
282
283 std::vector<StartState> start_states;
284 std::vector<PathConstraints> path_constraints;
285 std::vector<PathConstraints> goal_constraints;
286 std::vector<TrajectoryConstraints> traj_constraints;
287 std::vector<BenchmarkRequest> queries;
288
289 if (!loadBenchmarkQueryData(options, scene_msg, start_states, path_constraints, goal_constraints, traj_constraints,
290 queries))
291 {
292 RCLCPP_ERROR(getLogger(), "Failed to load benchmark query data");
293 return false;
294 }
295
296 RCLCPP_INFO(
297 getLogger(),
298 "Benchmark loaded %lu starts, %lu goals, %lu path constraints, %lu trajectory constraints, and %lu queries",
299 start_states.size(), goal_constraints.size(), path_constraints.size(), traj_constraints.size(), queries.size());
300
301 moveit_msgs::msg::WorkspaceParameters workspace_parameters = options.workspace;
302 // Make sure that workspace_parameters are set
303 if (workspace_parameters.min_corner.x == workspace_parameters.max_corner.x &&
304 workspace_parameters.min_corner.x == 0.0 &&
305 workspace_parameters.min_corner.y == workspace_parameters.max_corner.y &&
306 workspace_parameters.min_corner.y == 0.0 &&
307 workspace_parameters.min_corner.z == workspace_parameters.max_corner.z &&
308 workspace_parameters.min_corner.z == 0.0)
309 {
310 workspace_parameters.min_corner.x = workspace_parameters.min_corner.y = workspace_parameters.min_corner.z = -5.0;
311
312 workspace_parameters.max_corner.x = workspace_parameters.max_corner.y = workspace_parameters.max_corner.z = 5.0;
313 }
314
315 // Create the combinations of BenchmarkRequests
316
317 // 1) Create requests for combinations of start states,
318 // goal constraints, and path constraints
319 for (PathConstraints& goal_constraint : goal_constraints)
320 {
321 // Common benchmark request properties
322 BenchmarkRequest benchmark_request;
323 benchmark_request.name = goal_constraint.name;
324 benchmark_request.request.workspace_parameters = workspace_parameters;
325 benchmark_request.request.goal_constraints = goal_constraint.constraints;
326 benchmark_request.request.group_name = options.group_name;
327 benchmark_request.request.allowed_planning_time = options.timeout;
328 benchmark_request.request.num_planning_attempts = 1;
329
330 if (benchmark_request.request.goal_constraints.size() == 1 &&
331 benchmark_request.request.goal_constraints.at(0).position_constraints.size() == 1 &&
332 benchmark_request.request.goal_constraints.at(0).orientation_constraints.size() == 1 &&
333 benchmark_request.request.goal_constraints.at(0).visibility_constraints.empty() &&
334 benchmark_request.request.goal_constraints.at(0).joint_constraints.empty())
335 {
336 shiftConstraintsByOffset(benchmark_request.request.goal_constraints.at(0), options.goal_offsets);
337 }
338
339 std::vector<BenchmarkRequest> request_combos;
340 createRequestCombinations(benchmark_request, start_states, path_constraints, request_combos);
341 requests.insert(requests.end(), request_combos.begin(), request_combos.end());
342 }
343
344 // 2) Existing queries are treated like goal constraints.
345 // Create all combos of query, start states, and path constraints
346 for (BenchmarkRequest& query : queries)
347 {
348 // Common benchmark request properties
349 BenchmarkRequest benchmark_request;
350 benchmark_request.name = query.name;
351 benchmark_request.request = query.request;
352 benchmark_request.request.group_name = options.group_name;
353 benchmark_request.request.allowed_planning_time = options.timeout;
354 benchmark_request.request.num_planning_attempts = 1;
355
356 // Make sure that workspace_parameters are set
357 if (benchmark_request.request.workspace_parameters.min_corner.x ==
358 benchmark_request.request.workspace_parameters.max_corner.x &&
359 benchmark_request.request.workspace_parameters.min_corner.x == 0.0 &&
360 benchmark_request.request.workspace_parameters.min_corner.y ==
361 benchmark_request.request.workspace_parameters.max_corner.y &&
362 benchmark_request.request.workspace_parameters.min_corner.y == 0.0 &&
363 benchmark_request.request.workspace_parameters.min_corner.z ==
364 benchmark_request.request.workspace_parameters.max_corner.z &&
365 benchmark_request.request.workspace_parameters.min_corner.z == 0.0)
366 {
367 // ROS_WARN("Workspace parameters are not set for request %s. Setting defaults", queries[i].name.c_str());
368 benchmark_request.request.workspace_parameters = workspace_parameters;
369 }
370
371 // Create all combinations of start states and path constraints
372 std::vector<BenchmarkRequest> request_combos;
373 createRequestCombinations(benchmark_request, start_states, path_constraints, request_combos);
374 requests.insert(requests.end(), request_combos.begin(), request_combos.end());
375 }
376
377 // 3) Trajectory constraints are also treated like goal constraints
378 for (TrajectoryConstraints& traj_constraint : traj_constraints)
379 {
380 // Common benchmark request properties
381 BenchmarkRequest benchmark_request;
382 benchmark_request.name = traj_constraint.name;
383 benchmark_request.request.trajectory_constraints = traj_constraint.constraints;
384 benchmark_request.request.group_name = options.group_name;
385 benchmark_request.request.allowed_planning_time = options.timeout;
386 benchmark_request.request.num_planning_attempts = 1;
387
388 if (benchmark_request.request.trajectory_constraints.constraints.size() == 1 &&
389 benchmark_request.request.trajectory_constraints.constraints.at(0).position_constraints.size() == 1 &&
390 benchmark_request.request.trajectory_constraints.constraints.at(0).orientation_constraints.size() == 1 &&
391 benchmark_request.request.trajectory_constraints.constraints.at(0).visibility_constraints.empty() &&
392 benchmark_request.request.trajectory_constraints.constraints.at(0).joint_constraints.empty())
393 {
394 shiftConstraintsByOffset(benchmark_request.request.trajectory_constraints.constraints.at(0), options.goal_offsets);
395 }
396
397 std::vector<BenchmarkRequest> request_combos;
398 std::vector<PathConstraints> no_path_constraints;
399 createRequestCombinations(benchmark_request, start_states, no_path_constraints, request_combos);
400 requests.insert(requests.end(), request_combos.begin(), request_combos.end());
401 }
402 return true;
403}
404
406 const BenchmarkOptions& options, moveit_msgs::msg::PlanningScene& scene_msg, std::vector<StartState>& start_states,
407 std::vector<PathConstraints>& path_constraints, std::vector<PathConstraints>& goal_constraints,
408 std::vector<TrajectoryConstraints>& traj_constraints, std::vector<BenchmarkRequest>& queries)
409{
410 try
411 {
412 warehouse_ros::DatabaseConnection::Ptr warehouse_connection = db_loader_.loadDatabase();
413 warehouse_connection->setParams(options.hostname, options.port, 20);
414 if (warehouse_connection->connect())
415 {
416 planning_scene_storage_ = std::make_shared<moveit_warehouse::PlanningSceneStorage>(warehouse_connection);
418 std::make_shared<moveit_warehouse::PlanningSceneWorldStorage>(warehouse_connection);
419 robot_state_storage_ = std::make_shared<moveit_warehouse::RobotStateStorage>(warehouse_connection);
420 constraints_storage_ = std::make_shared<moveit_warehouse::ConstraintsStorage>(warehouse_connection);
422 std::make_shared<moveit_warehouse::TrajectoryConstraintsStorage>(warehouse_connection);
423 RCLCPP_INFO(getLogger(), "Connected to DB");
424 }
425 else
426 {
427 RCLCPP_ERROR(getLogger(), "Failed to connect to DB");
428 return false;
429 }
430 }
431 catch (std::exception& e)
432 {
433 RCLCPP_ERROR(getLogger(), "Failed to initialize benchmark server: '%s'", e.what());
434 return false;
435 }
436
437 if (!loadPlanningScene(options.scene_name, scene_msg))
438 {
439 RCLCPP_ERROR(getLogger(), "Failed to load the planning scene");
440 return false;
441 }
442 if (!loadStates(options.start_state_regex, start_states))
443 {
444 RCLCPP_ERROR(getLogger(), "Failed to load the states");
445 return false;
446 }
447 if (!loadPathConstraints(options.goal_constraint_regex, goal_constraints))
448 {
449 RCLCPP_ERROR(getLogger(), "Failed to load the goal constraints");
450 }
451 if (!loadPathConstraints(options.path_constraint_regex, path_constraints))
452 {
453 RCLCPP_ERROR(getLogger(), "Failed to load the path constraints");
454 }
455 if (!loadTrajectoryConstraints(options.trajectory_constraint_regex, traj_constraints))
456 {
457 RCLCPP_ERROR(getLogger(), "Failed to load the trajectory constraints");
458 }
459 if (!loadQueries(options.query_regex, options.scene_name, queries))
460 {
461 RCLCPP_ERROR(getLogger(), "Failed to get a query regex");
462 }
463 return true;
464}
465
466void BenchmarkExecutor::shiftConstraintsByOffset(moveit_msgs::msg::Constraints& constraints,
467 const std::vector<double>& offset)
468{
469 Eigen::Isometry3d offset_tf(Eigen::AngleAxis<double>(offset.at(3), Eigen::Vector3d::UnitX()) *
470 Eigen::AngleAxis<double>(offset.at(4), Eigen::Vector3d::UnitY()) *
471 Eigen::AngleAxis<double>(offset.at(5), Eigen::Vector3d::UnitZ()));
472 offset_tf.translation() = Eigen::Vector3d(offset.at(0), offset.at(1), offset.at(2));
473
474 geometry_msgs::msg::Pose constraint_pose_msg;
475 constraint_pose_msg.position =
476 constraints.position_constraints.at(0).constraint_region.primitive_poses.at(0).position;
477 constraint_pose_msg.orientation = constraints.orientation_constraints.at(0).orientation;
478 Eigen::Isometry3d constraint_pose;
479 tf2::fromMsg(constraint_pose_msg, constraint_pose);
480
481 Eigen::Isometry3d new_pose = constraint_pose * offset_tf;
482 geometry_msgs::msg::Pose new_pose_msg;
483 new_pose_msg = tf2::toMsg(new_pose);
484
485 constraints.position_constraints.at(0).constraint_region.primitive_poses.at(0).position = new_pose_msg.position;
486 constraints.orientation_constraints.at(0).orientation = new_pose_msg.orientation;
487}
488
490 const std::vector<StartState>& start_states,
491 const std::vector<PathConstraints>& path_constraints,
492 std::vector<BenchmarkRequest>& requests)
493{
494 // Use default start state
495 if (start_states.empty())
496 {
497 // Adding path constraints
498 for (const PathConstraints& path_constraint : path_constraints)
499 {
500 BenchmarkRequest new_benchmark_request = benchmark_request;
501 new_benchmark_request.request.path_constraints = path_constraint.constraints.at(0);
502 new_benchmark_request.name = benchmark_request.name + "_" + path_constraint.name;
503 requests.push_back(new_benchmark_request);
504 }
505
506 if (path_constraints.empty())
507 {
508 requests.push_back(benchmark_request);
509 }
510 }
511 else // Create a request for each start state specified
512 {
513 for (const StartState& start_state : start_states)
514 {
515 // Skip start states that have the same name as the goal
516 if (start_state.name == benchmark_request.name)
517 continue;
518
519 BenchmarkRequest new_benchmark_request = benchmark_request;
520 new_benchmark_request.request.start_state = start_state.state;
521
522 // Duplicate the request for each of the path constraints
523 for (const PathConstraints& path_constraint : path_constraints)
524 {
525 new_benchmark_request.request.path_constraints = path_constraint.constraints.at(0);
526 new_benchmark_request.name = start_state.name + "_" + new_benchmark_request.name + "_" + path_constraint.name;
527 requests.push_back(new_benchmark_request);
528 }
529
530 if (path_constraints.empty())
531 {
532 new_benchmark_request.name = start_state.name + "_" + benchmark_request.name;
533 requests.push_back(new_benchmark_request);
534 }
535 }
536 }
537}
538
539bool BenchmarkExecutor::pipelinesExist(const std::map<std::string, std::vector<std::string>>& pipeline_configurations)
540{
541 // Make sure planner plugins exist
542 for (const std::pair<const std::string, std::vector<std::string>>& pipeline_config_entry : pipeline_configurations)
543 {
544 bool pipeline_exists = false;
545 for (const std::pair<const std::string, planning_pipeline::PlanningPipelinePtr>& pipeline_entry :
546 moveit_cpp_->getPlanningPipelines())
547 {
548 pipeline_exists = pipeline_entry.first == pipeline_config_entry.first;
549 if (pipeline_exists)
550 break;
551 }
552
553 if (!pipeline_exists)
554 {
555 RCLCPP_ERROR(getLogger(), "Planning pipeline '%s' does NOT exist", pipeline_config_entry.first.c_str());
556 return false;
557 }
558 }
559 return true;
560}
561
562bool BenchmarkExecutor::loadPlanningScene(const std::string& scene_name, moveit_msgs::msg::PlanningScene& scene_msg)
563{
564 try
565 {
566 if (planning_scene_storage_->hasPlanningScene(scene_name)) // whole planning scene
567 {
568 moveit_warehouse::PlanningSceneWithMetadata planning_scene_w_metadata;
569
570 if (!planning_scene_storage_->getPlanningScene(planning_scene_w_metadata, scene_name))
571 {
572 RCLCPP_ERROR(getLogger(), "Failed to load planning scene '%s'", scene_name.c_str());
573 return false;
574 }
575 scene_msg = static_cast<moveit_msgs::msg::PlanningScene>(*planning_scene_w_metadata);
576 }
577 else if (planning_scene_world_storage_->hasPlanningSceneWorld(scene_name)) // Just the world (no robot)
578 {
580 if (!planning_scene_world_storage_->getPlanningSceneWorld(pswwm, scene_name))
581 {
582 RCLCPP_ERROR(getLogger(), "Failed to load planning scene world '%s'", scene_name.c_str());
583 return false;
584 }
585 scene_msg.world = static_cast<moveit_msgs::msg::PlanningSceneWorld>(*pswwm);
586 scene_msg.robot_model_name =
587 "NO ROBOT INFORMATION. ONLY WORLD GEOMETRY"; // this will be fixed when running benchmark
588 }
589 else
590 {
591 RCLCPP_ERROR(getLogger(), "Failed to find planning scene '%s'", scene_name.c_str());
592 return false;
593 }
594 }
595 catch (std::exception& ex)
596 {
597 RCLCPP_ERROR(getLogger(), "Error loading planning scene: %s", ex.what());
598 return false;
599 }
600 RCLCPP_INFO(getLogger(), "Loaded planning scene successfully");
601 return true;
602}
603
604bool BenchmarkExecutor::loadQueries(const std::string& regex, const std::string& scene_name,
605 std::vector<BenchmarkRequest>& queries)
606{
607 if (regex.empty())
608 {
609 RCLCPP_WARN(getLogger(), "No query regex provided, don't load any queries from the database");
610 return true;
611 }
612
613 std::vector<std::string> query_names;
614 try
615 {
616 planning_scene_storage_->getPlanningQueriesNames(regex, query_names, scene_name);
617 }
618 catch (std::exception& ex)
619 {
620 RCLCPP_ERROR(getLogger(), "Error loading motion planning queries: %s", ex.what());
621 return false;
622 }
623
624 if (query_names.empty())
625 {
626 RCLCPP_ERROR(getLogger(), "Scene '%s' has no associated queries", scene_name.c_str());
627 return false;
628 }
629
630 for (const std::string& query_name : query_names)
631 {
633 try
634 {
635 planning_scene_storage_->getPlanningQuery(planning_query, scene_name, query_name);
636 }
637 catch (std::exception& ex)
638 {
639 RCLCPP_ERROR(getLogger(), "Error loading motion planning query '%s': %s", query_name.c_str(), ex.what());
640 continue;
641 }
642
643 BenchmarkRequest query;
644 query.name = query_name;
645 query.request = static_cast<moveit_msgs::msg::MotionPlanRequest>(*planning_query);
646 queries.push_back(query);
647 }
648 RCLCPP_INFO(getLogger(), "Loaded queries successfully");
649 return true;
650}
651
652bool BenchmarkExecutor::loadStates(const std::string& regex, std::vector<StartState>& start_states)
653{
654 if (!regex.empty())
655 {
656 std::regex start_regex(regex);
657 std::vector<std::string> state_names;
658 robot_state_storage_->getKnownRobotStates(state_names);
659
660 if (state_names.empty())
661 {
662 RCLCPP_WARN(getLogger(), "Database does not contain any named states");
663 }
664
665 for (const std::string& state_name : state_names)
666 {
667 std::smatch match;
668 if (std::regex_match(state_name, match, start_regex))
669 {
671 try
672 {
673 if (robot_state_storage_->getRobotState(robot_state, state_name))
674 {
675 StartState start_state;
676 start_state.state = moveit_msgs::msg::RobotState(*robot_state);
677 start_state.name = state_name;
678 start_states.push_back(start_state);
679 }
680 }
681 catch (std::exception& ex)
682 {
683 RCLCPP_ERROR(getLogger(), "Runtime error when loading state '%s': %s", state_name.c_str(), ex.what());
684 continue;
685 }
686 }
687 }
688
689 if (start_states.empty())
690 {
691 RCLCPP_WARN(getLogger(), "No stored states matched the provided start state regex: '%s'", regex.c_str());
692 }
693 }
694 RCLCPP_INFO(getLogger(), "Loaded states successfully");
695 return true;
696}
697
698bool BenchmarkExecutor::loadPathConstraints(const std::string& regex, std::vector<PathConstraints>& constraints)
699{
700 if (!regex.empty())
701 {
702 std::vector<std::string> cnames;
703 constraints_storage_->getKnownConstraints(regex, cnames);
704
705 for (const std::string& cname : cnames)
706 {
708 try
709 {
710 if (constraints_storage_->getConstraints(constr, cname))
711 {
712 PathConstraints constraint;
713 constraint.constraints.push_back(*constr);
714 constraint.name = cname;
715 constraints.push_back(constraint);
716 }
717 }
718 catch (std::exception& ex)
719 {
720 RCLCPP_ERROR(getLogger(), "Runtime error when loading path constraint '%s': %s", cname.c_str(), ex.what());
721 continue;
722 }
723 }
724
725 if (constraints.empty())
726 {
727 RCLCPP_WARN(getLogger(), "No path constraints found that match regex: '%s'", regex.c_str());
728 }
729 else
730 {
731 RCLCPP_INFO(getLogger(), "Loaded path constraints successfully");
732 }
733 }
734 return true;
735}
736
738 std::vector<TrajectoryConstraints>& constraints)
739{
740 if (!regex.empty())
741 {
742 std::vector<std::string> cnames;
743 trajectory_constraints_storage_->getKnownTrajectoryConstraints(regex, cnames);
744
745 for (const std::string& cname : cnames)
746 {
748 try
749 {
750 if (trajectory_constraints_storage_->getTrajectoryConstraints(constr, cname))
751 {
752 TrajectoryConstraints constraint;
753 constraint.constraints = *constr;
754 constraint.name = cname;
755 constraints.push_back(constraint);
756 }
757 }
758 catch (std::exception& ex)
759 {
760 RCLCPP_ERROR(getLogger(), "Runtime error when loading trajectory constraint '%s': %s", cname.c_str(), ex.what());
761 continue;
762 }
763 }
764
765 if (constraints.empty())
766 {
767 RCLCPP_WARN(getLogger(), "No trajectory constraints found that match regex: '%s'", regex.c_str());
768 }
769 else
770 {
771 RCLCPP_INFO(getLogger(), "Loaded trajectory constraints successfully");
772 }
773 }
774 return true;
775}
776
777void BenchmarkExecutor::runBenchmark(moveit_msgs::msg::MotionPlanRequest request, const BenchmarkOptions& options)
778{
779 benchmark_data_.clear();
780
781 auto num_planners = 0;
782 for (const std::pair<const std::string, std::vector<std::string>>& pipeline_entry : options.planning_pipelines)
783 {
784 num_planners += pipeline_entry.second.size();
785 }
786 num_planners += options.parallel_planning_pipelines.size();
787
788 boost_progress_display progress(num_planners * options.runs, std::cout);
789
790 // Iterate through all planning pipelines
791 auto planning_pipelines = moveit_cpp_->getPlanningPipelines();
792 for (const std::pair<const std::string, std::vector<std::string>>& pipeline_entry : options.planning_pipelines)
793 {
794 // Iterate through all planners configured for the pipeline
795 for (const std::string& planner_id : pipeline_entry.second)
796 {
797 // This container stores all of the benchmark data for this planner
798 PlannerBenchmarkData planner_data(options.runs);
799 // This vector stores all motion plan results for further evaluation
800 std::vector<planning_interface::MotionPlanDetailedResponse> responses(options.runs);
801 std::vector<bool> solved(options.runs);
802
803 request.planner_id = planner_id;
804
805 // Planner start events
806 for (PlannerStartEventFunction& planner_start_function : planner_start_functions_)
807 {
808 planner_start_function(request, planner_data);
809 }
810
812 .planner_id = planner_id,
813 .planning_pipeline = pipeline_entry.first,
814 .planning_attempts = request.num_planning_attempts,
815 .planning_time = request.allowed_planning_time,
816 .max_velocity_scaling_factor = request.max_velocity_scaling_factor,
817 .max_acceleration_scaling_factor = request.max_acceleration_scaling_factor
818 };
819
820 // Iterate runs
821 for (int j = 0; j < options.runs; ++j)
822 {
823 // Pre-run events
824 for (PreRunEventFunction& pre_event_function : pre_event_functions_)
825 pre_event_function(request);
826
827 // Create planning component
828 auto planning_component = std::make_shared<moveit_cpp::PlanningComponent>(request.group_name, moveit_cpp_);
829 moveit::core::RobotState start_state(planning_scene_monitor_->getRobotModel());
830 moveit::core::robotStateMsgToRobotState(request.start_state, start_state);
831
832 planning_component->setStartState(start_state);
833 planning_component->setGoal(request.goal_constraints);
834 planning_component->setPathConstraints(request.path_constraints);
835 planning_component->setTrajectoryConstraints(request.trajectory_constraints);
836
837 // Solve problem
838 std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
839
840 // Planning pipeline benchmark
841 const auto response = planning_component->plan(plan_req_params, planning_scene_);
842
843 solved[j] = bool(response.error_code);
844
845 responses[j].error_code = response.error_code;
846 if (response.trajectory)
847 {
848 responses[j].description.push_back("plan");
849 responses[j].trajectory.push_back(response.trajectory);
850 responses[j].processing_time.push_back(response.planning_time);
851 }
852
853 std::chrono::duration<double> dt = std::chrono::system_clock::now() - start;
854 double total_time = dt.count();
855
856 // Collect data
857 start = std::chrono::system_clock::now();
858
859 // Post-run events
860 for (PostRunEventFunction& post_event_fn : post_event_functions_)
861 {
862 post_event_fn(request, responses[j], planner_data[j]);
863 }
864 collectMetrics(planner_data[j], responses[j], solved[j], total_time);
865 dt = std::chrono::system_clock::now() - start;
866 double metriconstraints_storage_time = dt.count();
867 RCLCPP_DEBUG(getLogger(), "Spent %lf seconds collecting metrics", metriconstraints_storage_time);
868
869 ++progress;
870 }
871
872 computeAveragePathSimilarities(planner_data, responses, solved);
873
874 // Planner completion events
876 {
877 planner_completion_fn(request, planner_data);
878 }
879
880 benchmark_data_.push_back(planner_data);
881 }
882 }
883
884 if (!options.parallel_planning_pipelines.empty())
885 {
886 // Iterate through all parallel pipelines
887 for (const std::pair<const std::string, std::vector<std::pair<std::string, std::string>>>& parallel_pipeline_entry :
888 options.parallel_planning_pipelines)
889 {
890 // This container stores all of the benchmark data for this planner
891 PlannerBenchmarkData planner_data(options.runs);
892 // This vector stores all motion plan results for further evaluation
893 std::vector<planning_interface::MotionPlanDetailedResponse> responses(options.runs);
894 std::vector<bool> solved(options.runs);
895
896 // Planner start events
897 for (PlannerStartEventFunction& planner_start_function : planner_start_functions_)
898 {
899 planner_start_function(request, planner_data);
900 }
901
902 // Create multi-pipeline request
904 for (const auto& pipeline_planner_id_pair : parallel_pipeline_entry.second)
905 {
907 .planner_id = pipeline_planner_id_pair.second,
908 .planning_pipeline = pipeline_planner_id_pair.first,
909 .planning_attempts = request.num_planning_attempts,
910 .planning_time = request.allowed_planning_time,
911 .max_velocity_scaling_factor = request.max_velocity_scaling_factor,
912 .max_acceleration_scaling_factor = request.max_acceleration_scaling_factor
913 };
914 multi_pipeline_plan_request.plan_request_parameter_vector.push_back(plan_req_params);
915 }
916
917 // Iterate runs
918 for (int j = 0; j < options.runs; ++j)
919 {
920 // Pre-run events
921 for (PreRunEventFunction& pre_event_function : pre_event_functions_)
922 {
923 pre_event_function(request);
924 }
925
926 // Create planning component
927 auto planning_component = std::make_shared<moveit_cpp::PlanningComponent>(request.group_name, moveit_cpp_);
928 moveit::core::RobotState start_state(planning_scene_monitor_->getRobotModel());
929 moveit::core::robotStateMsgToRobotState(request.start_state, start_state);
930
931 planning_component->setStartState(start_state);
932 planning_component->setGoal(request.goal_constraints);
933 planning_component->setPathConstraints(request.path_constraints);
934 planning_component->setTrajectoryConstraints(request.trajectory_constraints);
935
936 // Solve problem
937 std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
938
939 const auto t1 = std::chrono::system_clock::now();
940 const auto response = planning_component->plan(multi_pipeline_plan_request,
942 nullptr, planning_scene_);
943 const auto t2 = std::chrono::system_clock::now();
944
945 solved[j] = bool(response.error_code);
946
947 responses[j].error_code = response.error_code;
948 if (response.trajectory)
949 {
950 responses[j].description.push_back("plan");
951 responses[j].trajectory.push_back(response.trajectory);
952 responses[j].processing_time.push_back(std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count());
953 }
954
955 std::chrono::duration<double> dt = std::chrono::system_clock::now() - start;
956 double total_time = dt.count();
957
958 // Collect data
959 start = std::chrono::system_clock::now();
960 // Post-run events
961 for (PostRunEventFunction& post_event_fn : post_event_functions_)
962 {
963 post_event_fn(request, responses[j], planner_data[j]);
964 }
965
966 collectMetrics(planner_data[j], responses[j], solved[j], total_time);
967 dt = std::chrono::system_clock::now() - start;
968 double metriconstraints_storage_time = dt.count();
969 RCLCPP_DEBUG(getLogger(), "Spent %lf seconds collecting metrics", metriconstraints_storage_time);
970
971 ++progress;
972 }
973
974 computeAveragePathSimilarities(planner_data, responses, solved);
975
976 // Planner completion events
978 {
979 planner_completion_fn(request, planner_data);
980 }
981
982 benchmark_data_.push_back(planner_data);
983 }
984 }
985}
986
988 const planning_interface::MotionPlanDetailedResponse& motion_plan_response,
989 bool solved, double total_time)
990{
991 metrics["time REAL"] = moveit::core::toString(total_time);
992 metrics["solved BOOLEAN"] = solved ? "true" : "false";
993
994 if (solved)
995 {
996 // Analyzing the trajectory(ies) geometrically
997 double traj_len = 0.0; // trajectory length
998 double clearance = 0.0; // trajectory clearance (average)
999 bool correct = true; // entire trajectory collision free and in bounds
1000
1001 double process_time = total_time;
1002 for (std::size_t j = 0; j < motion_plan_response.trajectory.size(); ++j)
1003 {
1004 correct = true;
1005 traj_len = 0.0;
1006 clearance = 0.0;
1007 const robot_trajectory::RobotTrajectory& p = *motion_plan_response.trajectory[j];
1008
1009 // compute path length
1010 traj_len = robot_trajectory::pathLength(p);
1011
1012 // compute correctness and clearance
1014 req.pad_environment_collisions = false;
1015 for (std::size_t k = 0; k < p.getWayPointCount(); ++k)
1016 {
1018 planning_scene_->checkCollision(req, res, p.getWayPoint(k));
1019 if (res.collision)
1020 correct = false;
1021 if (!p.getWayPoint(k).satisfiesBounds())
1022 correct = false;
1023 double d = planning_scene_->distanceToCollisionUnpadded(p.getWayPoint(k));
1024 if (d > 0.0) // in case of collision, distance is negative
1025 clearance += d;
1026 }
1027 clearance /= static_cast<double>(p.getWayPointCount());
1028
1029 // compute smoothness
1030 const auto smoothness = [&]() {
1031 const auto s = robot_trajectory::smoothness(p);
1032 return s.has_value() ? s.value() : 0.0;
1033 }();
1034
1035 metrics["path_" + motion_plan_response.description[j] + "_correct BOOLEAN"] = correct ? "true" : "false";
1036 metrics["path_" + motion_plan_response.description[j] + "_length REAL"] = moveit::core::toString(traj_len);
1037 metrics["path_" + motion_plan_response.description[j] + "_clearance REAL"] = moveit::core::toString(clearance);
1038 metrics["path_" + motion_plan_response.description[j] + "_smoothness REAL"] = moveit::core::toString(smoothness);
1039 metrics["path_" + motion_plan_response.description[j] + "_time REAL"] =
1040 moveit::core::toString(motion_plan_response.processing_time[j]);
1041
1042 if (j == motion_plan_response.trajectory.size() - 1)
1043 {
1044 metrics["final_path_correct BOOLEAN"] = correct ? "true" : "false";
1045 metrics["final_path_length REAL"] = moveit::core::toString(traj_len);
1046 metrics["final_path_clearance REAL"] = moveit::core::toString(clearance);
1047 metrics["final_path_smoothness REAL"] = moveit::core::toString(smoothness);
1048 metrics["final_path_time REAL"] = moveit::core::toString(motion_plan_response.processing_time[j]);
1049 }
1050 process_time -= motion_plan_response.processing_time[j];
1051 }
1052 if (process_time <= 0.0)
1053 process_time = 0.0;
1054 metrics["process_time REAL"] = moveit::core::toString(process_time);
1055 }
1056}
1057
1059 PlannerBenchmarkData& planner_data, const std::vector<planning_interface::MotionPlanDetailedResponse>& responses,
1060 const std::vector<bool>& solved)
1061{
1062 RCLCPP_INFO(getLogger(), "Computing result path similarity");
1063 const size_t result_count = planner_data.size();
1064 size_t unsolved = std::count_if(solved.begin(), solved.end(), [](bool s) { return !s; });
1065 std::vector<double> average_distances(responses.size());
1066 for (size_t first_traj_i = 0; first_traj_i < result_count; ++first_traj_i)
1067 {
1068 // If trajectory was not solved there is no valid average distance so it's set to max double only
1069 if (!solved[first_traj_i])
1070 {
1071 average_distances[first_traj_i] = std::numeric_limits<double>::max();
1072 continue;
1073 }
1074 // Iterate all result trajectories that haven't been compared yet
1075 for (size_t second_traj_i = first_traj_i + 1; second_traj_i < result_count; ++second_traj_i)
1076 {
1077 // Ignore if other result has not been solved
1078 if (!solved[second_traj_i])
1079 continue;
1080
1081 // Get final trajectories
1082 const robot_trajectory::RobotTrajectory& traj_first = *responses[first_traj_i].trajectory.back();
1083 const robot_trajectory::RobotTrajectory& traj_second = *responses[second_traj_i].trajectory.back();
1084
1085 // Compute trajectory distance
1086 double trajectory_distance;
1087 if (!computeTrajectoryDistance(traj_first, traj_second, trajectory_distance))
1088 continue;
1089
1090 // Add average distance to counters of both trajectories
1091 average_distances[first_traj_i] += trajectory_distance;
1092 average_distances[second_traj_i] += trajectory_distance;
1093 }
1094 // Normalize average distance by number of actual comparisons
1095 average_distances[first_traj_i] /= result_count - unsolved - 1;
1096 }
1097
1098 // Store results in planner_data
1099 for (size_t i = 0; i < result_count; ++i)
1100 planner_data[i]["average_waypoint_distance REAL"] = moveit::core::toString(average_distances[i]);
1101}
1102
1104 const robot_trajectory::RobotTrajectory& traj_second,
1105 double& result_distance)
1106{
1107 // Abort if trajectories are empty
1108 if (traj_first.empty() || traj_second.empty())
1109 return false;
1110
1111 // Waypoint counter
1112 size_t pos_first = 0;
1113 size_t pos_second = 0;
1114 const size_t max_pos_first = traj_first.getWayPointCount() - 1;
1115 const size_t max_pos_second = traj_second.getWayPointCount() - 1;
1116
1117 // Compute total distance between pairwise waypoints of both trajectories.
1118 // The selection of waypoint pairs is based on what steps results in the minimal distance between the next pair of
1119 // waypoints. We first check what steps are still possible or if we reached the end of the trajectories. Then we
1120 // compute the pairwise waypoint distances of the pairs from increasing both, the first, or the second trajectory.
1121 // Finally we select the pair that results in the minimal distance, summarize the total distance and iterate
1122 // accordingly. After that we compute the average trajectory distance by normalizing over the number of steps.
1123 double total_distance = 0;
1124 size_t steps = 0;
1125 double current_distance = traj_first.getWayPoint(pos_first).distance(traj_second.getWayPoint(pos_second));
1126 while (true)
1127 {
1128 // Keep track of total distance and number of comparisons
1129 total_distance += current_distance;
1130 ++steps;
1131 if (pos_first == max_pos_first && pos_second == max_pos_second) // end reached
1132 break;
1133
1134 // Determine what steps are still possible
1135 bool can_up_first = pos_first < max_pos_first;
1136 bool can_up_second = pos_second < max_pos_second;
1137 bool can_up_both = can_up_first && can_up_second;
1138
1139 // Compute pair-wise waypoint distances (increasing both, first, or second trajectories).
1140 double up_both = std::numeric_limits<double>::max();
1141 double up_first = std::numeric_limits<double>::max();
1142 double up_second = std::numeric_limits<double>::max();
1143 if (can_up_both)
1144 up_both = traj_first.getWayPoint(pos_first + 1).distance(traj_second.getWayPoint(pos_second + 1));
1145 if (can_up_first)
1146 up_first = traj_first.getWayPoint(pos_first + 1).distance(traj_second.getWayPoint(pos_second));
1147 if (can_up_second)
1148 up_second = traj_first.getWayPoint(pos_first).distance(traj_second.getWayPoint(pos_second + 1));
1149
1150 // Select actual step, store new distance value and iterate trajectory positions
1151 if (can_up_both && up_both < up_first && up_both < up_second)
1152 {
1153 ++pos_first;
1154 ++pos_second;
1155 current_distance = up_both;
1156 }
1157 else if ((can_up_first && up_first < up_second) || !can_up_second)
1158 {
1159 ++pos_first;
1160 current_distance = up_first;
1161 }
1162 else if (can_up_second)
1163 {
1164 ++pos_second;
1165 current_distance = up_second;
1166 }
1167 }
1168 // Normalize trajectory distance by number of comparison steps
1169 result_distance = total_distance / static_cast<double>(steps);
1170 return true;
1171}
1172
1173void BenchmarkExecutor::writeOutput(const BenchmarkRequest& benchmark_request, const std::string& start_time,
1174 double benchmark_duration, const BenchmarkOptions& options)
1175{
1176 // Count number of benchmarked planners
1177 size_t num_planners = 0;
1178 for (const std::pair<const std::string, std::vector<std::string>>& pipeline : options.planning_pipelines)
1179 {
1180 num_planners += pipeline.second.size();
1181 }
1182 num_planners += options.parallel_planning_pipelines.size();
1183
1184 std::string hostname = [&]() {
1185 static const int BUF_SIZE = 1024;
1186 char buffer[BUF_SIZE];
1187 int err = gethostname(buffer, sizeof(buffer));
1188 if (err != 0)
1189 {
1190 return std::string();
1191 }
1192 else
1193 {
1194 buffer[BUF_SIZE - 1] = '\0';
1195 return std::string(buffer);
1196 }
1197 }();
1198 if (hostname.empty())
1199 {
1200 hostname = "UNKNOWN";
1201 }
1202
1203 // Set output directory name
1204 std::string filename = options.output_directory;
1205 if (!filename.empty() && filename[filename.size() - 1] != '/')
1206 {
1207 filename.append("/");
1208 }
1209
1210 // Ensure directories exist
1211 std::filesystem::create_directories(filename);
1212
1213 // Create output log file name
1214 filename += (options.benchmark_name.empty() ? "" : options.benchmark_name + "_") + benchmark_request.name + "_" +
1215 hostname + "_" + start_time + ".log";
1216
1217 // Write benchmark results to file
1218 std::ofstream out(filename.c_str());
1219 if (!out)
1220 {
1221 RCLCPP_ERROR(getLogger(), "Failed to open '%s' for benchmark output", filename.c_str());
1222 return;
1223 }
1224
1225 // General data
1226 out << "MoveIt version " << MOVEIT_VERSION_STR << '\n';
1227 out << "Experiment " << benchmark_request.name << '\n';
1228 out << "Running on " << hostname << '\n';
1229 out << "Starting at " << start_time << '\n';
1230
1231 // Experiment setup
1232 moveit_msgs::msg::PlanningScene scene_msg;
1233 planning_scene_->getPlanningSceneMsg(scene_msg);
1234 out << "<<<|" << '\n';
1235 out << "Motion plan request:" << '\n'
1236 << " planner_id: " << benchmark_request.request.planner_id << '\n'
1237 << " group_name: " << benchmark_request.request.group_name << '\n'
1238 << " num_planning_attempts: " << benchmark_request.request.num_planning_attempts << '\n'
1239 << " allowed_planning_time: " << benchmark_request.request.allowed_planning_time << '\n';
1240 out << "Planning scene:" << '\n'
1241 << " scene_name: " << scene_msg.name << '\n'
1242 << " robot_model_name: " << scene_msg.robot_model_name << '\n'
1243 << "|>>>" << '\n';
1244
1245 // The real random seed is unknown. Writing a fake value
1246 out << "0 is the random seed" << '\n';
1247 out << benchmark_request.request.allowed_planning_time << " seconds per run" << '\n';
1248 // There is no memory cap
1249 out << "-1 MB per run" << '\n';
1250 out << options.runs << " runs per planner" << '\n';
1251 out << benchmark_duration << " seconds spent to collect the data" << '\n';
1252
1253 // No enum types
1254 out << "0 enum types" << '\n';
1255
1256 out << num_planners << " planners" << '\n';
1257
1258 // Index for benchmark data of one planner
1259 size_t run_id = 0;
1260
1261 // Write data for individual planners to the output file
1262 for (const std::pair<const std::string, std::vector<std::string>>& pipeline : options.planning_pipelines)
1263 {
1264 for (std::size_t i = 0; i < pipeline.second.size(); ++i, ++run_id)
1265 {
1266 // Write the name of the planner and the used pipeline
1267 out << pipeline.second[i] << " (" << pipeline.first << ')' << '\n';
1268
1269 // in general, we could have properties specific for a planner;
1270 // right now, we do not include such properties
1271 out << "0 common properties" << '\n';
1272
1273 // Create a list of the benchmark properties for this planner
1274 std::set<std::string> properties_set;
1275 for (PlannerRunData& planner_run_data : benchmark_data_[run_id])
1276 { // each run of this planner
1277 for (PlannerRunData::const_iterator pit = planner_run_data.begin(); pit != planner_run_data.end();
1278 ++pit) // each benchmark property of the given run
1279 properties_set.insert(pit->first);
1280 }
1281
1282 // Writing property list
1283 out << properties_set.size() << " properties for each run" << '\n';
1284 for (const std::string& property : properties_set)
1285 out << property << '\n';
1286
1287 // Number of runs
1288 out << benchmark_data_[run_id].size() << " runs" << '\n';
1289
1290 // And the benchmark properties
1291 for (PlannerRunData& planner_run_data : benchmark_data_[run_id]) // each run of this planner
1292 {
1293 // Write out properties in the order we listed them above
1294 for (const std::string& property : properties_set)
1295 {
1296 // Make sure this run has this property
1297 PlannerRunData::const_iterator runit = planner_run_data.find(property);
1298 if (runit != planner_run_data.end())
1299 out << runit->second;
1300 out << "; ";
1301 }
1302 out << '\n'; // end of the run
1303 }
1304 out << '.' << '\n'; // end the planner
1305 }
1306 }
1307
1308 // Write results for parallel planning pipelines to output file
1309 for (const std::pair<const std::string, std::vector<std::pair<std::string, std::string>>>& parallel_pipeline :
1310 options.parallel_planning_pipelines)
1311 {
1312 // Write the name of the planner and the used pipeline
1313 out << parallel_pipeline.first << " (" << parallel_pipeline.first << ")" << '\n';
1314
1315 // in general, we could have properties specific for a planner;
1316 // right now, we do not include such properties
1317 out << "0 common properties" << '\n';
1318
1319 // Create a list of the benchmark properties for this planner
1320 std::set<std::string> properties_set;
1321 // each run of this planner
1322 for (PlannerRunData& planner_run_data : benchmark_data_[run_id])
1323 {
1324 for (PlannerRunData::const_iterator pit = planner_run_data.begin(); pit != planner_run_data.end(); ++pit)
1325 {
1326 properties_set.insert(pit->first);
1327 }
1328 }
1329
1330 // Writing property list
1331 out << properties_set.size() << " properties for each run" << '\n';
1332 for (const std::string& property : properties_set)
1333 out << property << '\n';
1334
1335 // Number of runs
1336 out << benchmark_data_[run_id].size() << " runs" << '\n';
1337
1338 // And the benchmark properties
1339 for (PlannerRunData& planner_run_data : benchmark_data_[run_id]) // each run of this planner
1340 {
1341 // Write out properties in the order we listed them above
1342 for (const std::string& property : properties_set)
1343 {
1344 // Make sure this run has this property
1345 PlannerRunData::const_iterator runit = planner_run_data.find(property);
1346 if (runit != planner_run_data.end())
1347 out << runit->second;
1348 out << "; ";
1349 }
1350 out << '\n'; // end of the run
1351 }
1352 out << "." << '\n'; // end the planner
1353
1354 // Increase index
1355 run_id += 1;
1356 }
1357
1358 out.close();
1359 RCLCPP_INFO(getLogger(), "Benchmark results saved to '%s'", filename.c_str());
1360}
boost::progress_display boost_progress_display
boost::posix_time::ptime toBoost(const std::chrono::time_point< Clock, Duration > &from)
Representation of a robot's state. This includes position, velocity, acceleration and effort.
double distance(const RobotState &other) const
Return the sum of joint distances to "other" state. An L1 norm. Only considers active joints.
bool satisfiesBounds(double margin=0.0) const
bool loadPlanningScene(const std::string &scene_name, moveit_msgs::msg::PlanningScene &scene_msg)
Load the planning scene with the given name from the warehouse.
void computeAveragePathSimilarities(PlannerBenchmarkData &planner_data, const std::vector< planning_interface::MotionPlanDetailedResponse > &responses, const std::vector< bool > &solved)
bool pipelinesExist(const std::map< std::string, std::vector< std::string > > &planners)
Check that the desired planning pipelines exist.
bool loadQueries(const std::string &regex, const std::string &scene_name, std::vector< BenchmarkRequest > &queries)
Load all motion plan requests matching the given regular expression from the warehouse.
void createRequestCombinations(const BenchmarkRequest &benchmark_request, const std::vector< StartState > &start_states, const std::vector< PathConstraints > &path_constraints, std::vector< BenchmarkRequest > &combos)
Duplicate the given benchmark request for all combinations of start states and path constraints.
std::vector< PlannerRunData > PlannerBenchmarkData
Structure to hold information for a single planner's benchmark data.
planning_scene::PlanningScenePtr planning_scene_
std::vector< PlannerStartEventFunction > planner_start_functions_
bool computeTrajectoryDistance(const robot_trajectory::RobotTrajectory &traj_first, const robot_trajectory::RobotTrajectory &traj_second, double &result_distance)
void addQueryStartEvent(const QueryStartEventFunction &func)
std::shared_ptr< moveit_warehouse::ConstraintsStorage > constraints_storage_
std::shared_ptr< moveit_warehouse::PlanningSceneStorage > planning_scene_storage_
std::function< void(const moveit_msgs::msg::MotionPlanRequest &request, PlannerBenchmarkData &benchmark_data)> PlannerCompletionEventFunction
std::vector< QueryCompletionEventFunction > query_end_functions_
std::shared_ptr< moveit_warehouse::TrajectoryConstraintsStorage > trajectory_constraints_storage_
std::function< void(const moveit_msgs::msg::MotionPlanRequest &request, planning_scene::PlanningScenePtr)> QueryCompletionEventFunction
Definition of a query-end benchmark event function. Invoked after a query has finished benchmarking.
std::shared_ptr< moveit_cpp::MoveItCpp > moveit_cpp_
virtual void collectMetrics(PlannerRunData &metrics, const planning_interface::MotionPlanDetailedResponse &motion_plan_response, bool solved, double total_time)
std::vector< QueryStartEventFunction > query_start_functions_
bool loadPathConstraints(const std::string &regex, std::vector< PathConstraints > &constraints)
Load all constraints matching the given regular expression from the warehouse.
std::vector< PreRunEventFunction > pre_event_functions_
void runBenchmark(moveit_msgs::msg::MotionPlanRequest request, const BenchmarkOptions &options)
Execute the given motion plan request on the set of planners for the set number of runs.
void addPreRunEvent(const PreRunEventFunction &func)
BenchmarkExecutor(const rclcpp::Node::SharedPtr &node, const std::string &robot_description_param="robot_description")
virtual bool runBenchmarks(const BenchmarkOptions &options)
std::vector< PlannerBenchmarkData > benchmark_data_
virtual bool loadBenchmarkQueryData(const BenchmarkOptions &options, moveit_msgs::msg::PlanningScene &scene_msg, std::vector< StartState > &start_states, std::vector< PathConstraints > &path_constraints, std::vector< PathConstraints > &goal_constraints, std::vector< TrajectoryConstraints > &traj_constraints, std::vector< BenchmarkRequest > &queries)
Initialize benchmark query data from start states and constraints.
std::vector< PostRunEventFunction > post_event_functions_
virtual bool initializeBenchmarks(const BenchmarkOptions &options, moveit_msgs::msg::PlanningScene &scene_msg, std::vector< BenchmarkRequest > &queries)
void addPlannerCompletionEvent(const PlannerCompletionEventFunction &func)
std::shared_ptr< planning_scene_monitor::PlanningSceneMonitor > planning_scene_monitor_
void addPlannerStartEvent(const PlannerStartEventFunction &func)
void addQueryCompletionEvent(const QueryCompletionEventFunction &func)
bool loadStates(const std::string &regex, std::vector< StartState > &start_states)
Load all states matching the given regular expression from the warehouse.
std::function< void(const moveit_msgs::msg::MotionPlanRequest &request, const planning_interface::MotionPlanDetailedResponse &response, PlannerRunData &run_data)> PostRunEventFunction
Definition of a post-run benchmark event function. Invoked immediately after each planner calls solve...
std::function< void(moveit_msgs::msg::MotionPlanRequest &request)> PreRunEventFunction
Definition of a pre-run benchmark event function. Invoked immediately before each planner calls solve...
std::vector< PlannerCompletionEventFunction > planner_completion_functions_
std::shared_ptr< moveit_warehouse::RobotStateStorage > robot_state_storage_
std::function< void(const moveit_msgs::msg::MotionPlanRequest &request, planning_scene::PlanningScenePtr)> QueryStartEventFunction
Definition of a query-start benchmark event function. Invoked before a new query is benchmarked.
virtual void writeOutput(const BenchmarkRequest &benchmark_request, const std::string &start_time, double benchmark_duration, const BenchmarkOptions &options)
bool initialize(const std::vector< std::string > &plugin_classes)
std::shared_ptr< moveit_warehouse::PlanningSceneWorldStorage > planning_scene_world_storage_
std::function< void(const moveit_msgs::msg::MotionPlanRequest &request, PlannerBenchmarkData &benchmark_data)> PlannerStartEventFunction
bool loadTrajectoryConstraints(const std::string &regex, std::vector< TrajectoryConstraints > &constraints)
Load all trajectory constraints from the warehouse that match the given regular expression.
void addPostRunEvent(const PostRunEventFunction &func)
void shiftConstraintsByOffset(moveit_msgs::msg::Constraints &constraints, const std::vector< double > &offset)
std::map< std::string, std::string > PlannerRunData
Structure to hold information for a single run of a planner.
Maintain a sequence of waypoints and the time durations between these waypoints.
const moveit::core::RobotState & getWayPoint(std::size_t index) const
std::string toString(double d)
Convert a double to std::string using the classic C locale.
bool robotStateMsgToRobotState(const Transforms &tf, const moveit_msgs::msg::RobotState &robot_state, RobotState &state, bool copy_attached_bodies=true)
Convert a robot state msg (with accompanying extra transforms) to a MoveIt robot state.
::planning_interface::MotionPlanResponse getShortestSolution(const std::vector<::planning_interface::MotionPlanResponse > &solutions)
Function that returns the shortest solution out of a vector of solutions based on robot_trajectory::p...
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::RobotState >::ConstPtr RobotStateWithMetadata
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::PlanningScene >::ConstPtr PlanningSceneWithMetadata
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::TrajectoryConstraints >::ConstPtr TrajectoryConstraintsWithMetadata
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::PlanningSceneWorld >::ConstPtr PlanningSceneWorldWithMetadata
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::MotionPlanRequest >::ConstPtr MotionPlanRequestWithMetadata
warehouse_ros::MessageWithMetadata< moveit_msgs::msg::Constraints >::ConstPtr ConstraintsWithMetadata
rclcpp::Logger getLogger(const std::string &name)
Creates a namespaced logger.
Definition logger.cpp:79
std::optional< double > smoothness(const RobotTrajectory &trajectory)
Calculate the smoothness of a given trajectory.
double pathLength(const RobotTrajectory &trajectory)
Calculate the path length of a given trajectory based on the accumulated robot state distances....
Representation of a collision checking request.
bool pad_environment_collisions
If true, use padded collision environment.
Representation of a collision checking result.
bool collision
True if collision was found, false otherwise.
Planner parameters provided with the MotionPlanRequest.
Planner parameters provided with the MotionPlanRequest.
std::vector< moveit_msgs::msg::Constraints > constraints
Options to configure a benchmark experiment. The configuration is provided via ROS2 parameters.
std::vector< robot_trajectory::RobotTrajectoryPtr > trajectory