AnytimePathShortening.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2014, 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 
37 #include "ompl/geometric/planners/AnytimePathShortening.h"
38 #include "ompl/geometric/PathHybridization.h"
39 #include "ompl/geometric/PathSimplifier.h"
40 #include "ompl/tools/config/SelfConfig.h"
41 #include "ompl/base/objectives/PathLengthOptimizationObjective.h"
42 
43 #include <thread>
44 
46  : ompl::base::Planner(si, "APS")
47  , defaultNumPlanners_(std::max(1u, std::thread::hardware_concurrency()))
48 {
50  specs_.multithreaded = true;
51  specs_.optimizingPaths = true;
52 
53  Planner::declareParam<bool>("shortcut", this, &AnytimePathShortening::setShortcut,
55  Planner::declareParam<bool>("hybridize", this, &AnytimePathShortening::setHybridize,
57  Planner::declareParam<unsigned int>("max_hybrid_paths", this, &AnytimePathShortening::setMaxHybridizationPath,
59  Planner::declareParam<unsigned int>("num_planners", this, &AnytimePathShortening::setDefaultNumPlanners,
61 
62  addPlannerProgressProperty("best cost REAL", [this]
63  {
64  return getBestCost();
65  });
66 }
67 
69 
71 {
72  if (planner && planner->getSpaceInformation().get() != si_.get())
73  {
74  OMPL_ERROR("NOT adding planner %s: SpaceInformation instances are different", planner->getName().c_str());
75  return;
76  }
77 
78  // Ensure all planners are unique instances
79  for (auto &i : planners_)
80  {
81  if (planner.get() == i.get())
82  {
83  OMPL_ERROR("NOT adding planner %s: Planner instances MUST be unique", planner->getName().c_str());
84  return;
85  }
86  }
87 
88  planners_.push_back(planner);
89 }
90 
92 {
94  for (auto &planner : planners_)
95  planner->setProblemDefinition(pdef);
96 }
97 
100 {
101  base::Goal *goal = pdef_->getGoal().get();
102  std::vector<std::thread *> threads(planners_.size());
104  base::Path *bestSln = nullptr;
105 
106  base::OptimizationObjectivePtr opt = pdef_->getOptimizationObjective();
107  if (!opt)
108  {
109  OMPL_INFORM("%s: No optimization objective specified. Defaulting to optimizing path length for the allowed "
110  "planning time.",
111  getName().c_str());
112  opt = std::make_shared<base::PathLengthOptimizationObjective>(si_);
113  pdef_->setOptimizationObjective(opt);
114  }
115  else
116  {
117  if (dynamic_cast<base::PathLengthOptimizationObjective *>(opt.get()) == nullptr)
118  OMPL_WARN("The optimization objective is not set for path length. The specified optimization criteria may "
119  "not be optimized over.");
120  }
121 
122  // Disable output from the motion planners, except for errors
123  msg::LogLevel currentLogLevel = msg::getLogLevel();
124  msg::setLogLevel(std::max(msg::LOG_ERROR, currentLogLevel));
125  while (!ptc())
126  {
127  // We have found a solution that is good enough
128  if ((bestSln != nullptr) && opt->isSatisfied(base::Cost(bestSln->length())))
129  break;
130 
131  // Clear any previous planning data for the set of planners
132  clear();
133 
134  // Spawn a thread for each planner. This will shortcut the best path after solving.
135  for (size_t i = 0; i < threads.size(); ++i)
136  threads[i] = new std::thread([this, i, &ptc]
137  {
138  return threadSolve(planners_[i].get(), ptc);
139  });
140 
141  // Join each thread, and then delete it
142  for (auto &thread : threads)
143  {
144  thread->join();
145  delete thread;
146  }
147 
148  // Hybridize the set of paths computed. Add the new hybrid path to the mix.
149  if (hybridize_ && !ptc())
150  {
151  const std::vector<base::PlannerSolution> &paths = pdef_->getSolutions();
152  for (size_t j = 0; j < paths.size() && j < maxHybridPaths_ && !ptc(); ++j)
153  phybrid.recordPath(paths[j].path_, false);
154 
155  phybrid.computeHybridPath();
156  const base::PathPtr &hsol = phybrid.getHybridPath();
157  if (hsol)
158  {
159  auto *pg = static_cast<geometric::PathGeometric *>(hsol.get());
160  double difference = 0.0;
161  bool approximate = !goal->isSatisfied(pg->getStates().back(), &difference);
162  pdef_->addSolutionPath(hsol, approximate, difference);
163  }
164  }
165 
166  // keep track of the best solution found so far
167  if (pdef_->getSolutionCount() > 0)
168  bestSln = pdef_->getSolutionPath().get();
169  }
170  msg::setLogLevel(currentLogLevel);
171 
172  if (bestSln != nullptr)
173  {
174  if (goal->isSatisfied(static_cast<geometric::PathGeometric *>(bestSln)->getStates().back()))
177  }
179 }
180 
183 {
184  // compute a motion plan
185  base::PlannerStatus status = planner->solve(ptc);
186 
187  // Shortcut the best solution found so far
189  {
190  geometric::PathGeometric *sln = static_cast<geometric::PathGeometric *>(pdef_->getSolutionPath().get());
191  auto pathCopy(std::make_shared<geometric::PathGeometric>(*sln));
192  geometric::PathSimplifier ps(pdef_->getSpaceInformation());
193  if (ps.shortcutPath(*pathCopy))
194  {
195  double difference = 0.0;
196  bool approximate = !pdef_->getGoal()->isSatisfied(pathCopy->getStates().back(), &difference);
197  pdef_->addSolutionPath(pathCopy, approximate, difference);
198  }
199  }
200 }
201 
203 {
204  Planner::clear();
205  for (auto &planner : planners_)
206  planner->clear();
207 }
208 
210 {
211  if (planners_.empty())
212  return;
213 
214  OMPL_WARN("Returning planner data for planner #0");
215  getPlannerData(data, 0);
216 }
217 
219 {
220  if (planners_.size() < idx)
221  return;
222  planners_[idx]->getPlannerData(data);
223 }
224 
226 {
227  Planner::setup();
228 
229  if (planners_.empty())
230  {
232  for (unsigned int i = 0; i < defaultNumPlanners_; ++i)
233  {
235  planners_.back()->setProblemDefinition(pdef_);
236  }
237  OMPL_INFORM("%s: No planners specified; using %u instances of %s", getName().c_str(), planners_.size(),
238  planners_[0]->getName().c_str());
239  }
240 
241  for (auto &planner : planners_)
242  planner->setup();
243 }
244 
246 {
247  for (auto &planner : planners_)
248  planner->checkValidity();
249 }
250 
252 {
253  return planners_.size();
254 }
255 
257 {
258  assert(idx < planners_.size());
259  return planners_[idx];
260 }
261 
263 {
264  return shortcut_;
265 }
266 
268 {
269  shortcut_ = shortcut;
270 }
271 
273 {
274  return hybridize_;
275 }
276 
278 {
279  hybridize_ = hybridize;
280 }
281 
283 {
284  return maxHybridPaths_;
285 }
286 
288 {
289  maxHybridPaths_ = maxPathCount;
290 }
291 
293 {
294  defaultNumPlanners_ = numPlanners;
295 }
296 
298 {
299  return defaultNumPlanners_;
300 }
301 
303 {
304  base::Cost bestCost(std::numeric_limits<double>::quiet_NaN());
305  if (pdef_ && pdef_->getSolutionCount() > 0)
306  bestCost = base::Cost(pdef_->getSolutionPath()->length());
307  return std::to_string(bestCost.value());
308 }
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:203
void addPlannerProgressProperty(const std::string &progressPropertyName, const PlannerProgressProperty &prop)
Add a planner progress property called progressPropertyName with a property querying function prop to...
Definition: Planner.h:399
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:174
bool isHybridizing() const
Return whether the anytime planner will extract a hybrid path from the set of solution paths...
A shared pointer wrapper for ompl::base::ProblemDefinition.
base::PlannerPtr getPlanner(unsigned int idx) const
Retrieve a pointer to the ith planner instance.
void setMaxHybridizationPath(unsigned int maxPathCount)
Set the maximum number of paths that will be hybridized.
~AnytimePathShortening() override
Destructor.
Abstract definition of goals.
Definition: Goal.h:62
void clear() override
Clear all internal planning datastructures. Planner settings are not affected. Subsequent calls to so...
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
STL namespace.
void getPlannerData(base::PlannerData &data) const override
Get information about the most recent run of the motion planner.
AnytimePathShortening(const base::SpaceInformationPtr &si)
Constructor requires the space information to plan in.
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:409
bool multithreaded
Flag indicating whether multiple threads are used in the computation of the planner.
Definition: Planner.h:200
unsigned int getDefaultNumPlanners() const
Get default number of planners used if none are specified.
void setHybridize(bool hybridize)
Enable/disable path hybridization on the set of solution paths.
void setDefaultNumPlanners(unsigned int numPlanners)
Set default number of planners to use if none are specified.
std::string getBestCost() const
Return best cost found so far by algorithm.
Main namespace. Contains everything in this library.
Definition: AppBase.h:21
unsigned int maxHybridPaths_
The maximum number of paths that will be hybridized. This prohibits hybridization of a very large pat...
A shared pointer wrapper for ompl::base::Planner.
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
Base class for a planner.
Definition: Planner.h:223
void checkValidity() override
Check to see if the planners are in a working state (setup has been called, a goal was set...
bool hybridize_
Flag indicating whether to hybridize the set of solution paths.
LogLevel getLogLevel()
Retrieve the current level of logging data. Messages with lower logging levels will not be recorded...
Definition: Console.cpp:142
The planner found an exact solution.
Definition: PlannerStatus.h:66
void setLogLevel(LogLevel level)
Set the minimum level of logging data to output. Messages with lower logging levels will not be recor...
Definition: Console.cpp:136
virtual void threadSolve(base::Planner *planner, const base::PlannerTerminationCondition &ptc)
The function that the planning threads execute when solving a motion planning problem.
void setShortcut(bool shortcut)
Enable/disable shortcutting on paths.
Abstract definition of a path.
Definition: Path.h:67
A class to store the exit status of Planner::solve()
Definition: PlannerStatus.h:48
virtual double length() const =0
Return the length of a path.
This class contains routines that attempt to simplify geometric paths.
A shared pointer wrapper for ompl::base::SpaceInformation.
virtual void setProblemDefinition(const ProblemDefinitionPtr &pdef)
Set the problem definition for the planner. The problem needs to be set before calling solve()...
Definition: Planner.cpp:76
void setup() override
Perform any necessary configuration steps. This method also invokes ompl::base::SpaceInformation::set...
unsigned int defaultNumPlanners_
The number of planners to use if none are specified. This defaults to the number of cores...
bool isShortcutting() const
Return whether the anytime planner will perform shortcutting on paths.
base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override
Method that solves the motion planning problem. This method terminates under just two conditions...
virtual bool isSatisfied(const State *st) const =0
Return true if the state satisfies the goal constraints.
#define OMPL_WARN(fmt,...)
Log a formatted warning string.
Definition: Console.h:66
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:418
static base::PlannerPtr getDefaultPlanner(const base::GoalPtr &goal)
Given a goal specification, decide on a planner for that goal.
Definition: SelfConfig.cpp:243
virtual PlannerStatus solve(const PlannerTerminationCondition &ptc)=0
Function that can solve the motion planning problem. This function can be called multiple times on th...
The planner found an approximate solution.
Definition: PlannerStatus.h:64
A shared pointer wrapper for ompl::base::OptimizationObjective.
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:56
void addPlanner(base::PlannerPtr &planner)
Adds the given planner to the set of planners used to compute candidate paths.
bool optimizingPaths
Flag indicating whether the planner attempts to optimize the path and reduce its length until the max...
Definition: Planner.h:207
std::vector< base::PlannerPtr > planners_
The list of planners used for solving the problem.
double value() const
The value of the cost.
Definition: Cost.h:56
unsigned int getNumPlanners() const
Retrieve the number of planners added.
void setProblemDefinition(const base::ProblemDefinitionPtr &pdef) override
Set the problem definition for the planners. The problem needs to be set before calling solve()...
Definition of a geometric path.
Definition: PathGeometric.h:60
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:406
Given multiple geometric paths, attempt to combine them in order to obtain a shorter solution...
LogLevel
The set of priorities for message logging.
Definition: Console.h:84
Definition of a cost value. Can represent the cost of a motion or the cost of a state.
Definition: Cost.h:47
A shared pointer wrapper for ompl::base::Path.
unsigned int maxHybridizationPaths() const
Return the maximum number of paths that will be hybridized.
bool shortcut_
Flag indicating whether to shortcut paths.
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68