moveit2
The MoveIt Motion Planning Framework for ROS 2.
model_based_planning_context.cpp
Go to the documentation of this file.
1 /*********************************************************************
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2012, Willow Garage, Inc.
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 Willow Garage 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: Ioan Sucan */
36 
37 #include <boost/algorithm/string/trim.hpp>
38 #include <boost/algorithm/string/split.hpp>
39 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/lexical_cast.hpp>
41 
49 
51 
53 
54 #include <ompl/config.h>
55 #include <ompl/base/samplers/UniformValidStateSampler.h>
56 #include <ompl/base/goals/GoalLazySamples.h>
57 #include <ompl/tools/config/SelfConfig.h>
58 #include <ompl/base/spaces/SE3StateSpace.h>
59 #include <ompl/datastructures/PDF.h>
60 #include <ompl/base/terminationconditions/IterationTerminationCondition.h>
61 #include <ompl/base/terminationconditions/CostConvergenceTerminationCondition.h>
62 
63 #include <ompl/base/objectives/PathLengthOptimizationObjective.h>
64 #include <ompl/base/objectives/MechanicalWorkOptimizationObjective.h>
65 #include <ompl/base/objectives/MinimaxObjective.h>
66 #include <ompl/base/objectives/StateCostIntegralObjective.h>
67 #include <ompl/base/objectives/MaximizeMinClearanceObjective.h>
68 #include <ompl/geometric/planners/prm/LazyPRM.h>
69 
70 namespace ompl_interface
71 {
72 static const rclcpp::Logger LOGGER = rclcpp::get_logger("moveit.ompl_planning.model_based_planning_context");
73 } // namespace ompl_interface
74 
77  : planning_interface::PlanningContext(name, spec.state_space_->getJointModelGroup()->getName())
78  , spec_(spec)
79  , complete_initial_robot_state_(spec.state_space_->getRobotModel())
80  , ompl_simple_setup_(spec.ompl_simple_setup_)
81  , ompl_benchmark_(*ompl_simple_setup_)
82  , ompl_parallel_plan_(ompl_simple_setup_->getProblemDefinition())
83  , ptc_(nullptr)
84  , last_plan_time_(0.0)
85  , last_simplify_time_(0.0)
86  , max_goal_samples_(0)
87  , max_state_sampling_attempts_(0)
88  , max_goal_sampling_attempts_(0)
89  , max_planning_threads_(0)
90  , max_solution_segment_length_(0.0)
91  , minimum_waypoint_count_(0)
92  , multi_query_planning_enabled_(false) // maintain "old" behavior by default
93  , simplify_solutions_(true)
94  , interpolate_(true)
95  , hybridize_(true)
96 {
97  complete_initial_robot_state_.setToDefaultValues(); // avoid uninitialized memory
99 
100  constraints_library_ = std::make_shared<ConstraintsLibrary>(this);
101 }
102 
103 void ompl_interface::ModelBasedPlanningContext::configure(const rclcpp::Node::SharedPtr& node,
104  bool use_constraints_approximations)
105 {
106  loadConstraintApproximations(node);
107  if (!use_constraints_approximations)
108  {
109  setConstraintsApproximations(ConstraintsLibraryPtr());
110  }
111  complete_initial_robot_state_.update();
112  ompl_simple_setup_->getStateSpace()->computeSignature(space_signature_);
113  ompl_simple_setup_->getStateSpace()->setStateSamplerAllocator(
114  [this](const ompl::base::StateSpace* ss) { return allocPathConstrainedSampler(ss); });
115 
116  if (spec_.constrained_state_space_)
117  {
118  // convert the input state to the corresponding OMPL state
119  ompl::base::ScopedState<> ompl_start_state(spec_.constrained_state_space_);
120  spec_.state_space_->copyToOMPLState(ompl_start_state.get(), getCompleteInitialRobotState());
121  ompl_simple_setup_->setStartState(ompl_start_state);
122  ompl_simple_setup_->setStateValidityChecker(std::make_shared<ConstrainedPlanningStateValidityChecker>(this));
123  }
124  else
125  {
126  // convert the input state to the corresponding OMPL state
127  ompl::base::ScopedState<> ompl_start_state(spec_.state_space_);
128  spec_.state_space_->copyToOMPLState(ompl_start_state.get(), getCompleteInitialRobotState());
129  ompl_simple_setup_->setStartState(ompl_start_state);
130  ompl_simple_setup_->setStateValidityChecker(std::make_shared<StateValidityChecker>(this));
131  }
132 
133  if (path_constraints_ && constraints_library_)
134  {
135  const ConstraintApproximationPtr& constraint_approx =
136  constraints_library_->getConstraintApproximation(path_constraints_msg_);
137  if (constraint_approx)
138  {
139  getOMPLStateSpace()->setInterpolationFunction(constraint_approx->getInterpolationFunction());
140  RCLCPP_INFO(LOGGER, "Using precomputed interpolation states");
141  }
142  }
143 
144  useConfig();
145  if (ompl_simple_setup_->getGoal())
146  ompl_simple_setup_->setup();
147 }
148 
150 {
151  if (!spec_.state_space_)
152  {
153  RCLCPP_ERROR(LOGGER, "No state space is configured yet");
154  return;
155  }
156  ob::ProjectionEvaluatorPtr projection_eval = getProjectionEvaluator(peval);
157  if (projection_eval)
158  spec_.state_space_->registerDefaultProjection(projection_eval);
159 }
160 
161 ompl::base::ProjectionEvaluatorPtr
163 {
164  if (peval.find_first_of("link(") == 0 && peval[peval.length() - 1] == ')')
165  {
166  std::string link_name = peval.substr(5, peval.length() - 6);
167  if (getRobotModel()->hasLinkModel(link_name))
168  return std::make_shared<ProjectionEvaluatorLinkPose>(this, link_name);
169  else
170  RCLCPP_ERROR(LOGGER,
171  "Attempted to set projection evaluator with respect to position of link '%s', "
172  "but that link is not known to the kinematic model.",
173  link_name.c_str());
174  }
175  else if (peval.find_first_of("joints(") == 0 && peval[peval.length() - 1] == ')')
176  {
177  std::string joints = peval.substr(7, peval.length() - 8);
178  boost::replace_all(joints, ",", " ");
179  std::vector<unsigned int> j;
180  std::stringstream ss(joints);
181  while (ss.good() && !ss.eof())
182  {
183  std::string joint;
184  ss >> joint >> std::ws;
185  if (getJointModelGroup()->hasJointModel(joint))
186  {
187  unsigned int variable_count = getJointModelGroup()->getJointModel(joint)->getVariableCount();
188  if (variable_count > 0)
189  {
190  int idx = getJointModelGroup()->getVariableGroupIndex(joint);
191  for (unsigned int q = 0; q < variable_count; ++q)
192  {
193  j.push_back(idx + q);
194  }
195  }
196  else
197  {
198  RCLCPP_WARN(LOGGER, "%s: Ignoring joint '%s' in projection since it has 0 DOF", name_.c_str(), joint.c_str());
199  }
200  }
201  else
202  {
203  RCLCPP_ERROR(LOGGER,
204  "%s: Attempted to set projection evaluator with respect to value of joint "
205  "'%s', but that joint is not known to the group '%s'.",
206  name_.c_str(), joint.c_str(), getGroupName().c_str());
207  }
208  }
209  if (j.empty())
210  {
211  RCLCPP_ERROR(LOGGER, "%s: No valid joints specified for joint projection", name_.c_str());
212  }
213  else
214  {
215  return std::make_shared<ProjectionEvaluatorJointValue>(this, j);
216  }
217  }
218  else
219  {
220  RCLCPP_ERROR(LOGGER, "Unable to allocate projection evaluator based on description: '%s'", peval.c_str());
221  }
222  return ob::ProjectionEvaluatorPtr();
223 }
224 
225 ompl::base::StateSamplerPtr
226 ompl_interface::ModelBasedPlanningContext::allocPathConstrainedSampler(const ompl::base::StateSpace* state_space) const
227 {
228  if (spec_.state_space_.get() != state_space)
229  {
230  RCLCPP_ERROR(LOGGER, "%s: Attempted to allocate a state sampler for an unknown state space", name_.c_str());
231  return ompl::base::StateSamplerPtr();
232  }
233 
234  RCLCPP_DEBUG(LOGGER, "%s: Allocating a new state sampler (attempts to use path constraints)", name_.c_str());
235 
236  if (path_constraints_)
237  {
238  if (constraints_library_)
239  {
240  const ConstraintApproximationPtr& constraint_approx =
241  constraints_library_->getConstraintApproximation(path_constraints_msg_);
242  if (constraint_approx)
243  {
244  ompl::base::StateSamplerAllocator state_sampler_allocator =
245  constraint_approx->getStateSamplerAllocator(path_constraints_msg_);
246  if (state_sampler_allocator)
247  {
248  ompl::base::StateSamplerPtr state_sampler = state_sampler_allocator(state_space);
249  if (state_sampler)
250  {
251  RCLCPP_INFO(LOGGER,
252  "%s: Using precomputed state sampler (approximated constraint space) for constraint '%s'",
253  name_.c_str(), path_constraints_msg_.name.c_str());
254  return state_sampler;
255  }
256  }
257  }
258  }
259 
260  constraint_samplers::ConstraintSamplerPtr constraint_sampler;
261  if (spec_.constraint_sampler_manager_)
262  constraint_sampler = spec_.constraint_sampler_manager_->selectSampler(getPlanningScene(), getGroupName(),
263  path_constraints_->getAllConstraints());
264 
265  if (constraint_sampler)
266  {
267  RCLCPP_INFO(LOGGER, "%s: Allocating specialized state sampler for state space", name_.c_str());
268  return std::make_shared<ConstrainedSampler>(this, constraint_sampler);
269  }
270  }
271  RCLCPP_DEBUG(LOGGER, "%s: Allocating default state sampler for state space", name_.c_str());
272  return state_space->allocDefaultStateSampler();
273 }
274 
276 {
277  const std::map<std::string, std::string>& config = spec_.config_;
278  if (config.empty())
279  return;
280  std::map<std::string, std::string> cfg = config;
281 
282  // set the distance between waypoints when interpolating and collision checking.
283  auto it = cfg.find("longest_valid_segment_fraction");
284  // If one of the two variables is set.
285  if (it != cfg.end() || max_solution_segment_length_ != 0.0)
286  {
287  // clang-format off
288  double longest_valid_segment_fraction_config = (it != cfg.end())
289  ? moveit::core::toDouble(it->second) // value from config file if there
290  : 0.01; // default value in OMPL.
291  double longest_valid_segment_fraction_final = longest_valid_segment_fraction_config;
292  if (max_solution_segment_length_ > 0.0)
293  {
294  // If this parameter is specified too, take the most conservative of the two variables,
295  // i.e. the one that uses the shorter segment length.
296  longest_valid_segment_fraction_final = std::min(
297  longest_valid_segment_fraction_config,
298  max_solution_segment_length_ / spec_.state_space_->getMaximumExtent()
299  );
300  }
301  // clang-format on
302 
303  // convert to string using no locale
304  cfg["longest_valid_segment_fraction"] = moveit::core::toString(longest_valid_segment_fraction_final);
305  }
306 
307  // set the projection evaluator
308  it = cfg.find("projection_evaluator");
309  if (it != cfg.end())
310  {
311  setProjectionEvaluator(boost::trim_copy(it->second));
312  cfg.erase(it);
313  }
314 
315  if (cfg.empty())
316  {
317  return;
318  }
319 
320  std::string optimizer;
321  ompl::base::OptimizationObjectivePtr objective;
322  it = cfg.find("optimization_objective");
323  if (it != cfg.end())
324  {
325  optimizer = it->second;
326  cfg.erase(it);
327 
328  if (optimizer == "PathLengthOptimizationObjective")
329  {
330  objective =
331  std::make_shared<ompl::base::PathLengthOptimizationObjective>(ompl_simple_setup_->getSpaceInformation());
332  }
333  else if (optimizer == "MinimaxObjective")
334  {
335  objective = std::make_shared<ompl::base::MinimaxObjective>(ompl_simple_setup_->getSpaceInformation());
336  }
337  else if (optimizer == "StateCostIntegralObjective")
338  {
339  objective = std::make_shared<ompl::base::StateCostIntegralObjective>(ompl_simple_setup_->getSpaceInformation());
340  }
341  else if (optimizer == "MechanicalWorkOptimizationObjective")
342  {
343  objective =
344  std::make_shared<ompl::base::MechanicalWorkOptimizationObjective>(ompl_simple_setup_->getSpaceInformation());
345  }
346  else if (optimizer == "MaximizeMinClearanceObjective")
347  {
348  objective =
349  std::make_shared<ompl::base::MaximizeMinClearanceObjective>(ompl_simple_setup_->getSpaceInformation());
350  }
351  else
352  {
353  objective =
354  std::make_shared<ompl::base::PathLengthOptimizationObjective>(ompl_simple_setup_->getSpaceInformation());
355  }
356 
357  ompl_simple_setup_->setOptimizationObjective(objective);
358  }
359 
360  // Don't clear planner data if multi-query planning is enabled
361  it = cfg.find("multi_query_planning_enabled");
362  if (it != cfg.end())
363  {
364  multi_query_planning_enabled_ = boost::lexical_cast<bool>(it->second);
365  }
366 
367  // check whether the path returned by the planner should be interpolated
368  it = cfg.find("interpolate");
369  if (it != cfg.end())
370  {
371  interpolate_ = boost::lexical_cast<bool>(it->second);
372  cfg.erase(it);
373  }
374 
375  // check whether the path returned by the planner should be simplified
376  it = cfg.find("simplify_solutions");
377  if (it != cfg.end())
378  {
379  simplify_solutions_ = boost::lexical_cast<bool>(it->second);
380  cfg.erase(it);
381  }
382 
383  // check whether solution paths from parallel planning should be hybridized
384  it = cfg.find("hybridize");
385  if (it != cfg.end())
386  {
387  hybridize_ = boost::lexical_cast<bool>(it->second);
388  cfg.erase(it);
389  }
390 
391  // remove the 'type' parameter; the rest are parameters for the planner itself
392  it = cfg.find("type");
393  if (it == cfg.end())
394  {
395  if (name_ != getGroupName())
396  RCLCPP_WARN(LOGGER, "%s: Attribute 'type' not specified in planner configuration", name_.c_str());
397  }
398  else
399  {
400  std::string type = it->second;
401  cfg.erase(it);
402  const std::string planner_name = getGroupName() + "/" + name_;
403  ompl_simple_setup_->setPlannerAllocator(
404  [planner_name, &spec = this->spec_, allocator = spec_.planner_selector_(type)](
405  const ompl::base::SpaceInformationPtr& si) { return allocator(si, planner_name, spec); });
406  RCLCPP_INFO(LOGGER,
407  "Planner configuration '%s' will use planner '%s'. "
408  "Additional configuration parameters will be set when the planner is constructed.",
409  name_.c_str(), type.c_str());
410  }
411 
412  // call the setParams() after setup(), so we know what the params are
413  ompl_simple_setup_->getSpaceInformation()->setup();
414  ompl_simple_setup_->getSpaceInformation()->params().setParams(cfg, true);
415  // call setup() again for possibly new param values
416  ompl_simple_setup_->getSpaceInformation()->setup();
417 }
418 
419 void ompl_interface::ModelBasedPlanningContext::setPlanningVolume(const moveit_msgs::msg::WorkspaceParameters& wparams)
420 {
421  if (wparams.min_corner.x == wparams.max_corner.x && wparams.min_corner.x == 0.0 &&
422  wparams.min_corner.y == wparams.max_corner.y && wparams.min_corner.y == 0.0 &&
423  wparams.min_corner.z == wparams.max_corner.z && wparams.min_corner.z == 0.0)
424  {
425  RCLCPP_WARN(LOGGER, "It looks like the planning volume was not specified.");
426  }
427 
428  RCLCPP_DEBUG(LOGGER,
429  "%s: Setting planning volume (affects SE2 & SE3 joints only) to x = [%f, %f], y = "
430  "[%f, %f], z = [%f, %f]",
431  name_.c_str(), wparams.min_corner.x, wparams.max_corner.x, wparams.min_corner.y, wparams.max_corner.y,
432  wparams.min_corner.z, wparams.max_corner.z);
433 
434  spec_.state_space_->setPlanningVolume(wparams.min_corner.x, wparams.max_corner.x, wparams.min_corner.y,
435  wparams.max_corner.y, wparams.min_corner.z, wparams.max_corner.z);
436 }
437 
439 {
440  ompl::time::point start = ompl::time::now();
441  ob::PlannerTerminationCondition ptc = constructPlannerTerminationCondition(timeout, start);
442  registerTerminationCondition(ptc);
443  ompl_simple_setup_->simplifySolution(ptc);
444  last_simplify_time_ = ompl_simple_setup_->getLastSimplificationTime();
445  unregisterTerminationCondition();
446 }
447 
449 {
450  if (ompl_simple_setup_->haveSolutionPath())
451  {
452  og::PathGeometric& pg = ompl_simple_setup_->getSolutionPath();
453 
454  // Find the number of states that will be in the interpolated solution.
455  // This is what interpolate() does internally.
456  unsigned int eventual_states = 1;
457  std::vector<ompl::base::State*> states = pg.getStates();
458  for (size_t i = 0; i < states.size() - 1; ++i)
459  {
460  eventual_states += ompl_simple_setup_->getStateSpace()->validSegmentCount(states[i], states[i + 1]);
461  }
462 
463  if (eventual_states < minimum_waypoint_count_)
464  {
465  // If that's not enough states, use the minimum amount instead.
466  pg.interpolate(minimum_waypoint_count_);
467  }
468  else
469  {
470  // Interpolate the path to have as the exact states that are checked when validating motions.
471  pg.interpolate();
472  }
473  }
474 }
475 
476 void ompl_interface::ModelBasedPlanningContext::convertPath(const ompl::geometric::PathGeometric& pg,
478 {
479  moveit::core::RobotState ks = complete_initial_robot_state_;
480  for (std::size_t i = 0; i < pg.getStateCount(); ++i)
481  {
482  spec_.state_space_->copyToRobotState(ks, pg.getState(i));
483  traj.addSuffixWayPoint(ks, 0.0);
484  }
485 }
486 
488 {
489  traj.clear();
490  if (ompl_simple_setup_->haveSolutionPath())
491  {
492  convertPath(ompl_simple_setup_->getSolutionPath(), traj);
493  }
494  return ompl_simple_setup_->haveSolutionPath();
495 }
496 
498 {
499  if (ompl_simple_setup_->getStateValidityChecker())
500  {
501  static_cast<StateValidityChecker*>(ompl_simple_setup_->getStateValidityChecker().get())->setVerbose(flag);
502  }
503 }
504 
506 {
507  // ******************* set up the goal representation, based on goal constraints
508 
509  std::vector<ob::GoalPtr> goals;
510  for (kinematic_constraints::KinematicConstraintSetPtr& goal_constraint : goal_constraints_)
511  {
512  constraint_samplers::ConstraintSamplerPtr constraint_sampler;
513  if (spec_.constraint_sampler_manager_)
514  {
515  constraint_sampler = spec_.constraint_sampler_manager_->selectSampler(getPlanningScene(), getGroupName(),
516  goal_constraint->getAllConstraints());
517  }
518 
519  if (constraint_sampler)
520  {
521  ob::GoalPtr goal = std::make_shared<ConstrainedGoalSampler>(this, goal_constraint, constraint_sampler);
522  goals.push_back(goal);
523  }
524  }
525 
526  if (!goals.empty())
527  {
528  return goals.size() == 1 ? goals[0] : std::make_shared<GoalSampleableRegionMux>(goals);
529  }
530  else
531  {
532  RCLCPP_ERROR(LOGGER, "Unable to construct goal representation");
533  }
534 
535  return ob::GoalPtr();
536 }
537 
538 ompl::base::PlannerTerminationCondition
540  const ompl::time::point& start)
541 {
542  auto it = spec_.config_.find("termination_condition");
543  if (it == spec_.config_.end())
544  {
545  return ob::timedPlannerTerminationCondition(timeout - ompl::time::seconds(ompl::time::now() - start));
546  }
547 
548  std::string termination_string = it->second;
549  std::vector<std::string> termination_and_params;
550  boost::split(termination_and_params, termination_string, boost::is_any_of("[ ,]"));
551 
552  if (termination_and_params.empty())
553  {
554  RCLCPP_ERROR(LOGGER, "Termination condition not specified");
555  }
556 
557  // Terminate if a maximum number of iterations is exceeded or a timeout occurs.
558  // The semantics of "iterations" are planner-specific, but typically it corresponds to the number of times
559  // an attempt was made to grow a roadmap/tree.
560  else if (termination_and_params[0] == "Iteration")
561  {
562  if (termination_and_params.size() > 1)
563  {
564  return ob::plannerOrTerminationCondition(
565  ob::timedPlannerTerminationCondition(timeout - ompl::time::seconds(ompl::time::now() - start)),
566  ob::IterationTerminationCondition(std::stoul(termination_and_params[1])));
567  }
568  else
569  {
570  RCLCPP_ERROR(LOGGER, "Missing argument to Iteration termination condition");
571  }
572  }
573 // TODO: remove when ROS Melodic and older are no longer supported
574 #if OMPL_VERSION_VALUE >= 1005000
575  // Terminate if the cost has converged or a timeout occurs.
576  // Only useful for anytime/optimizing planners.
577  else if (termination_and_params[0] == "CostConvergence")
578  {
579  std::size_t solutions_window = 10u;
580  double epsilon = 0.1;
581  if (termination_and_params.size() > 1)
582  {
583  solutions_window = std::stoul(termination_and_params[1]);
584  if (termination_and_params.size() > 2)
585  {
586  epsilon = moveit::core::toDouble(termination_and_params[2]);
587  }
588  }
589  return ob::plannerOrTerminationCondition(
590  ob::timedPlannerTerminationCondition(timeout - ompl::time::seconds(ompl::time::now() - start)),
591  ob::CostConvergenceTerminationCondition(ompl_simple_setup_->getProblemDefinition(), solutions_window, epsilon));
592  }
593 #endif
594  // Terminate as soon as an exact solution is found or a timeout occurs.
595  // This modifies the behavior of anytime/optimizing planners to terminate upon discovering
596  // the first feasible solution.
597  else if (termination_and_params[0] == "ExactSolution")
598  {
599  return ob::plannerOrTerminationCondition(
600  ob::timedPlannerTerminationCondition(timeout - ompl::time::seconds(ompl::time::now() - start)),
601  ob::exactSolnPlannerTerminationCondition(ompl_simple_setup_->getProblemDefinition()));
602  }
603  else
604  {
605  RCLCPP_ERROR(LOGGER, "Unknown planner termination condition");
606  }
607  // return a planner termination condition to suppress compiler warning
608  return ob::plannerAlwaysTerminatingCondition();
609 }
610 
612  const moveit::core::RobotState& complete_initial_robot_state)
613 {
614  complete_initial_robot_state_ = complete_initial_robot_state;
615  complete_initial_robot_state_.update();
616 }
617 
619 {
620  if (!multi_query_planning_enabled_)
621  {
622  ompl_simple_setup_->clear();
623  }
624 // TODO: remove when ROS Melodic and older are no longer supported
625 #if OMPL_VERSION_VALUE >= 1005000
626  else
627  {
628  // For LazyPRM and LazyPRMstar we assume that the environment *could* have changed
629  // This means that we need to reset the validity flags for every node and edge in
630  // the roadmap. For PRM and PRMstar we assume that the environment is static. If
631  // this is not the case, then multi-query planning should not be enabled.
632  auto planner = dynamic_cast<ompl::geometric::LazyPRM*>(ompl_simple_setup_->getPlanner().get());
633  if (planner != nullptr)
634  {
635  planner->clearValidity();
636  }
637  }
638 #endif
639  ompl_simple_setup_->clearStartStates();
640  ompl_simple_setup_->setGoal(ob::GoalPtr());
641  ompl_simple_setup_->setStateValidityChecker(ob::StateValidityCheckerPtr());
642  path_constraints_.reset();
643  goal_constraints_.clear();
644  getOMPLStateSpace()->setInterpolationFunction(InterpolationFunction());
645 }
646 
648  moveit_msgs::msg::MoveItErrorCodes* /*error*/)
649 {
650  // ******************* set the path constraints to use
651  path_constraints_ = std::make_shared<kinematic_constraints::KinematicConstraintSet>(getRobotModel());
652  path_constraints_->add(path_constraints, getPlanningScene()->getTransforms());
653  path_constraints_msg_ = path_constraints;
654 
655  return true;
656 }
657 
659  const std::vector<moveit_msgs::msg::Constraints>& goal_constraints,
660  const moveit_msgs::msg::Constraints& path_constraints, moveit_msgs::msg::MoveItErrorCodes* error)
661 {
662  // ******************* check if the input is correct
663  goal_constraints_.clear();
664  for (const moveit_msgs::msg::Constraints& goal_constraint : goal_constraints)
665  {
666  moveit_msgs::msg::Constraints constr = kinematic_constraints::mergeConstraints(goal_constraint, path_constraints);
667  kinematic_constraints::KinematicConstraintSetPtr kset(
668  new kinematic_constraints::KinematicConstraintSet(getRobotModel()));
669  kset->add(constr, getPlanningScene()->getTransforms());
670  if (!kset->empty())
671  {
672  goal_constraints_.push_back(kset);
673  }
674  }
675 
676  if (goal_constraints_.empty())
677  {
678  RCLCPP_WARN(LOGGER, "%s: No goal constraints specified. There is no problem to solve.", name_.c_str());
679  if (error)
680  {
681  error->val = moveit_msgs::msg::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
682  }
683  return false;
684  }
685 
686  ob::GoalPtr goal = constructGoal();
687  ompl_simple_setup_->setGoal(goal);
688  return static_cast<bool>(goal);
689 }
690 
691 bool ompl_interface::ModelBasedPlanningContext::benchmark(double timeout, unsigned int count,
692  const std::string& filename)
693 {
694  ompl_benchmark_.clearPlanners();
695  ompl_simple_setup_->setup();
696  ompl_benchmark_.addPlanner(ompl_simple_setup_->getPlanner());
697  ompl_benchmark_.setExperimentName(getRobotModel()->getName() + "_" + getGroupName() + "_" +
698  getPlanningScene()->getName() + "_" + name_);
699 
700  ot::Benchmark::Request req;
701  req.maxTime = timeout;
702  req.runCount = count;
703  req.displayProgress = true;
704  req.saveConsoleOutput = false;
705  ompl_benchmark_.benchmark(req);
706  return filename.empty() ? ompl_benchmark_.saveResultsToFile() : ompl_benchmark_.saveResultsToFile(filename.c_str());
707 }
708 
710 {
711  bool gls = ompl_simple_setup_->getGoal()->hasType(ob::GOAL_LAZY_SAMPLES);
712  if (gls)
713  {
714  static_cast<ob::GoalLazySamples*>(ompl_simple_setup_->getGoal().get())->startSampling();
715  }
716  else
717  {
718  // we know this is a GoalSampleableMux by elimination
719  static_cast<GoalSampleableRegionMux*>(ompl_simple_setup_->getGoal().get())->startSampling();
720  }
721 }
722 
724 {
725  bool gls = ompl_simple_setup_->getGoal()->hasType(ob::GOAL_LAZY_SAMPLES);
726  if (gls)
727  {
728  static_cast<ob::GoalLazySamples*>(ompl_simple_setup_->getGoal().get())->stopSampling();
729  }
730  else
731  {
732  // we know this is a GoalSampleableMux by elimination
733  static_cast<GoalSampleableRegionMux*>(ompl_simple_setup_->getGoal().get())->stopSampling();
734  }
735 }
736 
738 {
739  // clear previously computed solutions
740  ompl_simple_setup_->getProblemDefinition()->clearSolutionPaths();
741  const ob::PlannerPtr planner = ompl_simple_setup_->getPlanner();
742  if (planner && !multi_query_planning_enabled_)
743  {
744  planner->clear();
745  }
746  startSampling();
747  ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->resetMotionCounter();
748 }
749 
751 {
752  stopSampling();
753  int v = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getValidMotionCount();
754  int iv = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getInvalidMotionCount();
755  RCLCPP_DEBUG(LOGGER, "There were %d valid motions and %d invalid motions.", v, iv);
756 
757  // Debug OMPL setup and solution
758  RCLCPP_DEBUG(LOGGER, "%s",
759  [&] {
760  std::stringstream debug_out;
761  ompl_simple_setup_->print(debug_out);
762  return debug_out.str();
763  }()
764  .c_str());
765 }
766 
768 {
769  res.error_code_ = solve(request_.allowed_planning_time, request_.num_planning_attempts);
770  if (res.error_code_.val == moveit_msgs::msg::MoveItErrorCodes::SUCCESS)
771  {
772  double ptime = getLastPlanTime();
773  if (simplify_solutions_)
774  {
775  simplifySolution(request_.allowed_planning_time - ptime);
776  ptime += getLastSimplifyTime();
777  }
778 
779  if (interpolate_)
780  {
781  interpolateSolution();
782  }
783 
784  // fill the response
785  RCLCPP_DEBUG(LOGGER, "%s: Returning successful solution with %lu states", getName().c_str(),
786  getOMPLSimpleSetup()->getSolutionPath().getStateCount());
787 
788  res.trajectory_ = std::make_shared<robot_trajectory::RobotTrajectory>(getRobotModel(), getGroupName());
789  getSolutionPath(*res.trajectory_);
790  res.planning_time_ = ptime;
791  return true;
792  }
793  else
794  {
795  RCLCPP_INFO(LOGGER, "Unable to solve the planning problem");
796  return false;
797  }
798 }
799 
801 {
802  moveit_msgs::msg::MoveItErrorCodes moveit_result =
803  solve(request_.allowed_planning_time, request_.num_planning_attempts);
804  if (moveit_result.val == moveit_msgs::msg::MoveItErrorCodes::SUCCESS)
805  {
806  res.trajectory_.reserve(3);
807 
808  // add info about planned solution
809  double ptime = getLastPlanTime();
810  res.processing_time_.push_back(ptime);
811  res.description_.emplace_back("plan");
812  res.trajectory_.resize(res.trajectory_.size() + 1);
813  res.trajectory_.back() = std::make_shared<robot_trajectory::RobotTrajectory>(getRobotModel(), getGroupName());
814  getSolutionPath(*res.trajectory_.back());
815 
816  // simplify solution if time remains
817  if (simplify_solutions_)
818  {
819  simplifySolution(request_.allowed_planning_time - ptime);
820  res.processing_time_.push_back(getLastSimplifyTime());
821  res.description_.emplace_back("simplify");
822  res.trajectory_.resize(res.trajectory_.size() + 1);
823  res.trajectory_.back() = std::make_shared<robot_trajectory::RobotTrajectory>(getRobotModel(), getGroupName());
824  getSolutionPath(*res.trajectory_.back());
825  }
826 
827  if (interpolate_)
828  {
829  ompl::time::point start_interpolate = ompl::time::now();
830  interpolateSolution();
831  res.processing_time_.push_back(ompl::time::seconds(ompl::time::now() - start_interpolate));
832  res.description_.emplace_back("interpolate");
833  res.trajectory_.resize(res.trajectory_.size() + 1);
834  res.trajectory_.back() = std::make_shared<robot_trajectory::RobotTrajectory>(getRobotModel(), getGroupName());
835  getSolutionPath(*res.trajectory_.back());
836  }
837 
838  RCLCPP_DEBUG(LOGGER, "%s: Returning successful solution with %lu states", getName().c_str(),
839  getOMPLSimpleSetup()->getSolutionPath().getStateCount());
840  res.error_code_.val = moveit_result.val;
841  return true;
842  }
843  else
844  {
845  RCLCPP_INFO(LOGGER, "Unable to solve the planning problem");
846  res.error_code_.val = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
847  return false;
848  }
849 }
850 
851 const moveit_msgs::msg::MoveItErrorCodes ompl_interface::ModelBasedPlanningContext::solve(double timeout,
852  unsigned int count)
853 {
854  ompl::time::point start = ompl::time::now();
855  preSolve();
856 
857  moveit_msgs::msg::MoveItErrorCodes result;
858  result.val = moveit_msgs::msg::MoveItErrorCodes::FAILURE;
859  if (count <= 1 || multi_query_planning_enabled_) // multi-query planners should always run in single instances
860  {
861  RCLCPP_DEBUG(LOGGER, "%s: Solving the planning problem once...", name_.c_str());
862  ob::PlannerTerminationCondition ptc = constructPlannerTerminationCondition(timeout, start);
863  registerTerminationCondition(ptc);
864  std::ignore = ompl_simple_setup_->solve(ptc);
865  last_plan_time_ = ompl_simple_setup_->getLastPlanComputationTime();
866  unregisterTerminationCondition();
867  // fill the result status code
868  result.val = logPlannerStatus(ompl_simple_setup_);
869  }
870  else
871  {
872  RCLCPP_DEBUG(LOGGER, "%s: Solving the planning problem %u times...", name_.c_str(), count);
873  ompl_parallel_plan_.clearHybridizationPaths();
874  if (count <= max_planning_threads_)
875  {
876  ompl_parallel_plan_.clearPlanners();
877  if (ompl_simple_setup_->getPlannerAllocator())
878  for (unsigned int i = 0; i < count; ++i)
879  {
880  ompl_parallel_plan_.addPlannerAllocator(ompl_simple_setup_->getPlannerAllocator());
881  }
882  else
883  {
884  for (unsigned int i = 0; i < count; ++i)
885  {
886  ompl_parallel_plan_.addPlanner(ompl::tools::SelfConfig::getDefaultPlanner(ompl_simple_setup_->getGoal()));
887  }
888  }
889 
890  ob::PlannerTerminationCondition ptc = constructPlannerTerminationCondition(timeout, start);
891  registerTerminationCondition(ptc);
892  if (ompl_parallel_plan_.solve(ptc, 1, count, hybridize_) == ompl::base::PlannerStatus::EXACT_SOLUTION)
893  {
894  result.val = moveit_msgs::msg::MoveItErrorCodes::SUCCESS;
895  }
896  last_plan_time_ = ompl::time::seconds(ompl::time::now() - start);
897  unregisterTerminationCondition();
898  }
899  else
900  {
901  ob::PlannerTerminationCondition ptc = constructPlannerTerminationCondition(timeout, start);
902  registerTerminationCondition(ptc);
903  int n = count / max_planning_threads_;
904  result.val = moveit_msgs::msg::MoveItErrorCodes::SUCCESS;
905  for (int i = 0; i < n && !ptc(); ++i)
906  {
907  ompl_parallel_plan_.clearPlanners();
908  if (ompl_simple_setup_->getPlannerAllocator())
909  {
910  for (unsigned int i = 0; i < max_planning_threads_; ++i)
911  {
912  ompl_parallel_plan_.addPlannerAllocator(ompl_simple_setup_->getPlannerAllocator());
913  }
914  }
915  else
916  {
917  for (unsigned int i = 0; i < max_planning_threads_; ++i)
918  {
919  ompl_parallel_plan_.addPlanner(ompl::tools::SelfConfig::getDefaultPlanner(ompl_simple_setup_->getGoal()));
920  }
921  }
922 
923  bool r = ompl_parallel_plan_.solve(ptc, 1, count, hybridize_) == ompl::base::PlannerStatus::EXACT_SOLUTION;
924  // Was this latest call successful too?
925  result.val = (result.val == moveit_msgs::msg::MoveItErrorCodes::SUCCESS && r) ?
926  moveit_msgs::msg::MoveItErrorCodes::SUCCESS :
927  moveit_msgs::msg::MoveItErrorCodes::FAILURE;
928  }
929  n = count % max_planning_threads_;
930  if (n && !ptc())
931  {
932  ompl_parallel_plan_.clearPlanners();
933  if (ompl_simple_setup_->getPlannerAllocator())
934  {
935  for (int i = 0; i < n; ++i)
936  {
937  ompl_parallel_plan_.addPlannerAllocator(ompl_simple_setup_->getPlannerAllocator());
938  }
939  }
940  else
941  {
942  for (int i = 0; i < n; ++i)
943  {
944  ompl_parallel_plan_.addPlanner(ompl::tools::SelfConfig::getDefaultPlanner(ompl_simple_setup_->getGoal()));
945  }
946  }
947 
948  bool r = ompl_parallel_plan_.solve(ptc, 1, count, hybridize_) == ompl::base::PlannerStatus::EXACT_SOLUTION;
949  // Was this latest call successful too?
950  result.val = (result.val == moveit_msgs::msg::MoveItErrorCodes::SUCCESS && r) ?
951  moveit_msgs::msg::MoveItErrorCodes::SUCCESS :
952  moveit_msgs::msg::MoveItErrorCodes::FAILURE;
953  }
954  last_plan_time_ = ompl::time::seconds(ompl::time::now() - start);
955  unregisterTerminationCondition();
956  }
957  }
958 
959  postSolve();
960  return result;
961 }
962 
963 void ompl_interface::ModelBasedPlanningContext::registerTerminationCondition(const ob::PlannerTerminationCondition& ptc)
964 {
965  std::unique_lock<std::mutex> slock(ptc_lock_);
966  ptc_ = &ptc;
967 }
968 
970 {
971  std::unique_lock<std::mutex> slock(ptc_lock_);
972  ptc_ = nullptr;
973 }
974 
975 int32_t ompl_interface::ModelBasedPlanningContext::logPlannerStatus(const og::SimpleSetupPtr& ompl_simple_setup)
976 {
977  auto result = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
978  const ompl::base::PlannerStatus ompl_status = ompl_simple_setup->getLastPlannerStatus();
979  switch (ompl::base::PlannerStatus::StatusType(ompl_status))
980  {
981  case ompl::base::PlannerStatus::UNKNOWN:
982  RCLCPP_WARN(LOGGER, "Motion planning failed for an unknown reason");
983  result = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
984  break;
985  case ompl::base::PlannerStatus::INVALID_START:
986  RCLCPP_WARN(LOGGER, "Invalid start state");
987  result = moveit_msgs::msg::MoveItErrorCodes::START_STATE_INVALID;
988  break;
989  case ompl::base::PlannerStatus::INVALID_GOAL:
990  RCLCPP_WARN(LOGGER, "Invalid goal state");
991  result = moveit_msgs::msg::MoveItErrorCodes::GOAL_STATE_INVALID;
992  break;
993  case ompl::base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE:
994  RCLCPP_WARN(LOGGER, "Unrecognized goal type");
995  result = moveit_msgs::msg::MoveItErrorCodes::UNRECOGNIZED_GOAL_TYPE;
996  break;
997  case ompl::base::PlannerStatus::TIMEOUT:
998  RCLCPP_WARN(LOGGER, "Timed out: %.1fs ≥ %.1fs", ompl_simple_setup->getLastPlanComputationTime(),
999  request_.allowed_planning_time);
1000  result = moveit_msgs::msg::MoveItErrorCodes::TIMED_OUT;
1001  break;
1002  case ompl::base::PlannerStatus::APPROXIMATE_SOLUTION:
1003  // timeout is a common reason for APPROXIMATE_SOLUTION
1004  if (ompl_simple_setup->getLastPlanComputationTime() > request_.allowed_planning_time)
1005  {
1006  RCLCPP_WARN(LOGGER, "Planning timed out: %.1fs ≥ %.1fs", ompl_simple_setup->getLastPlanComputationTime(),
1007  request_.allowed_planning_time);
1008  result = moveit_msgs::msg::MoveItErrorCodes::TIMED_OUT;
1009  }
1010  else
1011  {
1012  RCLCPP_WARN(LOGGER, "Solution is approximate");
1013  result = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
1014  }
1015  break;
1016  case ompl::base::PlannerStatus::EXACT_SOLUTION:
1017  result = moveit_msgs::msg::MoveItErrorCodes::SUCCESS;
1018  break;
1019  case ompl::base::PlannerStatus::CRASH:
1020  RCLCPP_WARN(LOGGER, "OMPL crashed!");
1021  result = moveit_msgs::msg::MoveItErrorCodes::CRASH;
1022  break;
1023  case ompl::base::PlannerStatus::ABORT:
1024  RCLCPP_WARN(LOGGER, "OMPL was aborted");
1025  result = moveit_msgs::msg::MoveItErrorCodes::ABORT;
1026  break;
1027  default:
1028  // This should never happen
1029  RCLCPP_WARN(LOGGER, "Unexpected PlannerStatus code from OMPL.");
1030  result = moveit_msgs::msg::MoveItErrorCodes::PLANNING_FAILED;
1031  }
1032  return result;
1033 }
1034 
1036 {
1037  std::unique_lock<std::mutex> slock(ptc_lock_);
1038  if (ptc_)
1039  {
1040  ptc_->terminate();
1041  }
1042  return true;
1043 }
1044 
1046 {
1047  std::string constraint_path;
1048  if (node->get_parameter("constraint_approximations_path", constraint_path))
1049  {
1050  constraints_library_->saveConstraintApproximations(constraint_path);
1051  return true;
1052  }
1053  RCLCPP_WARN(LOGGER, "ROS param 'constraint_approximations' not found. Unable to save constraint approximations");
1054  return false;
1055 }
1056 
1058 {
1059  std::string constraint_path;
1060  if (node->get_parameter("constraint_approximations_path", constraint_path))
1061  {
1062  constraints_library_->loadConstraintApproximations(constraint_path);
1063  std::stringstream ss;
1064  constraints_library_->printConstraintApproximations(ss);
1065  RCLCPP_INFO_STREAM(LOGGER, ss.str());
1066  return true;
1067  }
1068  return false;
1069 }
A class that contains many different constraints, and can check RobotState *versus the full set....
Representation of a robot's state. This includes position, velocity, acceleration and effort.
Definition: robot_state.h:90
void update(bool force=false)
Update all transforms.
void setToDefaultValues()
Set all joints to their default positions. The default position is 0, or if that is not within bounds...
int32_t logPlannerStatus(const og::SimpleSetupPtr &ompl_simple_setup)
Convert OMPL PlannerStatus to moveit_msgs::msg::MoveItErrorCode.
virtual ob::ProjectionEvaluatorPtr getProjectionEvaluator(const std::string &peval) const
void clear() override
Clear the data structures used by the planner.
bool getSolutionPath(robot_trajectory::RobotTrajectory &traj) const
void registerTerminationCondition(const ob::PlannerTerminationCondition &ptc)
bool loadConstraintApproximations(const rclcpp::Node::SharedPtr &node)
Look up param server 'constraint_approximations' and use its value as the path to load constraint app...
bool setPathConstraints(const moveit_msgs::msg::Constraints &path_constraints, moveit_msgs::msg::MoveItErrorCodes *error)
ModelBasedPlanningContext(const std::string &name, const ModelBasedPlanningContextSpecification &spec)
virtual ob::PlannerTerminationCondition constructPlannerTerminationCondition(double timeout, const ompl::time::point &start)
bool saveConstraintApproximations(const rclcpp::Node::SharedPtr &node)
Look up param server 'constraint_approximations' and use its value as the path to save constraint app...
virtual void configure(const rclcpp::Node::SharedPtr &node, bool use_constraints_approximations)
Configure ompl_simple_setup_ and optionally the constraints_library_.
bool setGoalConstraints(const std::vector< moveit_msgs::msg::Constraints > &goal_constraints, const moveit_msgs::msg::Constraints &path_constraints, moveit_msgs::msg::MoveItErrorCodes *error)
void convertPath(const og::PathGeometric &pg, robot_trajectory::RobotTrajectory &traj) const
void setCompleteInitialState(const moveit::core::RobotState &complete_initial_robot_state)
void setPlanningVolume(const moveit_msgs::msg::WorkspaceParameters &wparams)
bool benchmark(double timeout, unsigned int count, const std::string &filename="")
bool terminate() override
If solve() is running, terminate the computation. Return false if termination not possible....
virtual ob::StateSamplerPtr allocPathConstrainedSampler(const ompl::base::StateSpace *ss) const
bool solve(planning_interface::MotionPlanResponse &res) override
Solve the motion planning problem and store the result in res. This function should not clear data st...
An interface for a OMPL state validity checker.
Maintain a sequence of waypoints and the time durations between these waypoints.
RobotTrajectory & addSuffixWayPoint(const moveit::core::RobotState &state, double dt)
Add a point to the trajectory.
locale-agnostic conversion functions from floating point numbers to strings
moveit_msgs::msg::Constraints mergeConstraints(const moveit_msgs::msg::Constraints &first, const moveit_msgs::msg::Constraints &second)
Merge two sets of constraints into one.
Definition: utils.cpp:56
double toDouble(const std::string &s)
Converts a std::string to double using the classic C locale.
std::string toString(double d)
Convert a double to std::string using the classic C locale.
The MoveIt interface to OMPL.
std::function< bool(const ompl::base::State *from, const ompl::base::State *to, const double t, ompl::base::State *state)> InterpolationFunction
r
Definition: plan.py:56
This namespace includes the base class for MoveIt planners.
name
Definition: setup.py:7
moveit_msgs::msg::MoveItErrorCodes error_code_
std::vector< robot_trajectory::RobotTrajectoryPtr > trajectory_
robot_trajectory::RobotTrajectoryPtr trajectory_
moveit_msgs::msg::MoveItErrorCodes error_code_