CForest.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 /* Authors: Javier V. Gómez, Ioan Sucan, Mark Moll */
36 
37 #include "ompl/geometric/planners/cforest/CForest.h"
38 #include "ompl/geometric/planners/rrt/RRTstar.h"
39 #include "ompl/base/objectives/PathLengthOptimizationObjective.h"
40 #include <thread>
41 
42 ompl::geometric::CForest::CForest(const base::SpaceInformationPtr &si) : base::Planner(si, "CForest")
43 {
44  specs_.optimizingPaths = true;
45  specs_.multithreaded = true;
46 
47  numPathsShared_ = 0;
48  numStatesShared_ = 0;
49  focusSearch_ = true;
50 
51  numThreads_ = std::max(std::thread::hardware_concurrency(), 2u);
52  Planner::declareParam<bool>("focus_search", this, &CForest::setFocusSearch, &CForest::getFocusSearch, "0,1");
53  Planner::declareParam<unsigned int>("num_threads", this, &CForest::setNumThreads, &CForest::getNumThreads, "0:64");
54 
55  addPlannerProgressProperty("best cost REAL",
56  std::bind(&CForest::getBestCost, this));
57  addPlannerProgressProperty("shared paths INTEGER",
58  std::bind(&CForest::getNumPathsShared, this));
59  addPlannerProgressProperty("shared states INTEGER",
60  std::bind(&CForest::getNumStatesShared, this));
61 }
62 
63 ompl::geometric::CForest::~CForest()
64 {
65 }
66 
67 void ompl::geometric::CForest::setNumThreads(unsigned int numThreads)
68 {
69  numThreads_ = numThreads ? numThreads : std::max(std::thread::hardware_concurrency(), 2u);
70 }
71 
72 void ompl::geometric::CForest::addPlannerInstanceInternal(const base::PlannerPtr &planner)
73 {
74  if (!planner->getSpecs().canReportIntermediateSolutions)
75  OMPL_WARN("%s cannot report intermediate solutions, not added as CForest planner.", planner->getName().c_str());
76  else
77  {
78  planner->setProblemDefinition(pdef_);
79  if (planner->params().hasParam("focus_search"))
80  planner->params()["focus_search"] = focusSearch_;
81  else
82  OMPL_WARN("%s does not appear to support search focusing.", planner->getName().c_str());
83 
84  planners_.push_back(planner);
85  }
86 }
87 
89 {
91 
92  for (std::size_t i = 0 ; i < planners_.size() ; ++i)
93  {
94  base::PlannerData pd(si_);
95  planners_[i]->getPlannerData(pd);
96 
97  for (unsigned int j = 0; j < pd.numVertices(); ++j)
98  {
100 
101  v.setTag(i);
102  std::vector<unsigned int> edgeList;
103  unsigned int numEdges = pd.getIncomingEdges(j, edgeList);
104  for (unsigned int k = 0; k <numEdges; ++k)
105  {
106  base::Cost edgeWeight;
107  base::PlannerDataVertex &w = pd.getVertex(edgeList[k]);
108 
109  w.setTag(i);
110  pd.getEdgeWeight(j, k, &edgeWeight);
111  data.addEdge(v, w, pd.getEdge(j, k), edgeWeight);
112  }
113  }
114 
115  for (unsigned int j = 0; j < pd.numGoalVertices(); ++j)
116  data.markGoalState(pd.getGoalVertex(j).getState());
117 
118  for (unsigned int j = 0; j < pd.numStartVertices(); ++j)
119  data.markStartState(pd.getStartVertex(j).getState());
120  }
121 }
122 
124 {
125  Planner::clear();
126  for (std::size_t i = 0; i < planners_.size(); ++i)
127  planners_[i]->clear();
128 
129  bestCost_ = base::Cost(std::numeric_limits<double>::quiet_NaN());
130  numPathsShared_ = 0;
131  numStatesShared_ = 0;
132 
133  std::vector<base::StateSamplerPtr> samplers;
134  samplers.reserve(samplers_.size());
135  for (std::size_t i = 0; i < samplers_.size(); ++i)
136  if (samplers_[i].use_count() > 1)
137  samplers.push_back(samplers_[i]);
138  samplers_.swap(samplers);
139 }
140 
142 {
143  Planner::setup();
144  if (pdef_->hasOptimizationObjective())
145  opt_ = pdef_->getOptimizationObjective();
146  else
147  {
148  OMPL_INFORM("%s: No optimization objective specified. Defaulting to optimizing path length for the allowed planning time.", getName().c_str());
149  opt_.reset(new base::PathLengthOptimizationObjective(si_));
150  }
151 
152  bestCost_ = opt_->infiniteCost();
153 
154  if (planners_.empty())
155  {
156  OMPL_INFORM("%s: Number and type of instances not specified. Defaulting to %d instances of RRTstar.", getName().c_str(), numThreads_);
157  addPlannerInstances<RRTstar>(numThreads_);
158  }
159 
160  for (std::size_t i = 0; i < planners_.size() ; ++i)
161  if (!planners_[i]->isSetup())
162  planners_[i]->setup();
163 
164  // This call is needed to make sure the ParamSet is up to date after changes induced by the planner setup calls above, via the state space wrappers for CForest.
165  si_->setup();
166 }
167 
169 {
170  typedef void(CForest::*solveFunctionType)(base::Planner*, const base::PlannerTerminationCondition&);
171 
172  checkValidity();
173 
174  time::point start = time::now();
175  std::vector<std::thread*> threads(planners_.size());
176  const base::ReportIntermediateSolutionFn prevSolutionCallback = getProblemDefinition()->getIntermediateSolutionCallback();
177 
178  if (prevSolutionCallback)
179  OMPL_WARN("Cannot use previously set intermediate solution callback with %s", getName().c_str());
180 
181  pdef_->setIntermediateSolutionCallback(std::bind(&CForest::newSolutionFound, this,
182  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
183  bestCost_ = opt_->infiniteCost();
184 
185  // run each planner in its own thread, with the same ptc.
186  for (std::size_t i = 0 ; i < threads.size() ; ++i)
187  threads[i] = new std::thread(std::bind((solveFunctionType)&CForest::solve, this, planners_[i].get(), ptc));
188 
189  for (std::size_t i = 0 ; i < threads.size() ; ++i)
190  {
191  threads[i]->join();
192  delete threads[i];
193  }
194 
195  // restore callback
196  getProblemDefinition()->setIntermediateSolutionCallback(prevSolutionCallback);
197  OMPL_INFORM("Solution found in %f seconds", time::seconds(time::now() - start));
198  return base::PlannerStatus(pdef_->hasSolution(), pdef_->hasApproximateSolution());
199 }
200 
202 {
203  return std::to_string(bestCost_.value());
204 }
205 
207 {
208  return std::to_string(numPathsShared_);
209 }
210 
212 {
213  return std::to_string(numStatesShared_);
214 }
215 
216 void ompl::geometric::CForest::newSolutionFound(const base::Planner *planner, const std::vector<const base::State *> &states, const base::Cost cost)
217 {
218  bool change = false;
219  std::vector<const base::State *> statesToShare;
220  newSolutionFoundMutex_.lock();
221  if (opt_->isCostBetterThan(cost, bestCost_))
222  {
223  ++numPathsShared_;
224  bestCost_ = cost;
225  change = true;
226 
227  // Filtering the states to add only those not already added.
228  statesToShare.reserve(states.size());
229  for (std::vector<const base::State *>::const_iterator st = states.begin(); st != states.end(); ++st)
230  {
231  if (statesShared_.find(*st) == statesShared_.end())
232  {
233  statesShared_.insert(*st);
234  statesToShare.push_back(*st);
235  ++numStatesShared_;
236  }
237  }
238  }
239  newSolutionFoundMutex_.unlock();
240 
241  if (!change || statesToShare.empty()) return;
242 
243  for (std::size_t i = 0; i < samplers_.size(); ++i)
244  {
245  base::CForestStateSampler *sampler = static_cast<base::CForestStateSampler*>(samplers_[i].get());
246  const base::CForestStateSpaceWrapper *space = static_cast<const base::CForestStateSpaceWrapper*>(sampler->getStateSpace());
247  const base::Planner *cfplanner = space->getPlanner();
248  if (cfplanner != planner)
249  sampler->setStatesToSample(statesToShare);
250  }
251 }
252 
254 {
255  OMPL_DEBUG("Starting %s", planner->getName().c_str());
256  time::point start = time::now();
257  if (planner->solve(ptc))
258  {
259  double duration = time::seconds(time::now() - start);
260  OMPL_DEBUG("Solution found by %s in %lf seconds", planner->getName().c_str(), duration);
261  }
262 }
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:163
std::string getBestCost() const
Get best cost among all the planners.
Definition: CForest.cpp:201
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: CForest.cpp:141
State space wrapper to use together with CForest. It adds some functionalities to the regular state s...
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
bool markStartState(const State *st)
Mark the given state as a start vertex. If the given state does not exist in a vertex, false is returned.
std::function< void(const Planner *, const std::vector< const base::State * > &, const Cost)> ReportIntermediateSolutionFn
When a planner has an intermediate solution (e.g., optimizing planners), a function with this signatu...
unsigned int numGoalVertices() const
Returns the number of goal vertices.
const PlannerDataVertex & getStartVertex(unsigned int i) const
Retrieve a reference to the ith start vertex object. If i is greater than the number of start vertice...
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: Planner.cpp:112
std::string getNumStatesShared() const
Get number of states actually shared by the algorithm.
Definition: CForest.cpp:211
bool getEdgeWeight(unsigned int v1, unsigned int v2, Cost *weight) const
Returns the weight of the edge between the given vertex indices. If there exists an edge between v1 a...
unsigned int getIncomingEdges(unsigned int v, std::vector< unsigned int > &edgeList) const
Returns a list of vertices with outgoing edges to the vertex with index v. The number of edges connec...
void setNumThreads(unsigned int numThreads=0)
Set default number of threads to use when no planner instances are specified by the user...
Definition: CForest.cpp:67
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: CForest.cpp:123
Extended state sampler to use with the CForest planning algorithm. It wraps the user-specified state ...
Base class for a vertex in the PlannerData structure. All derived classes must implement the clone an...
Definition: PlannerData.h:59
duration seconds(double sec)
Return the time duration representing a given number of seconds.
Definition: Time.h:78
void setStatesToSample(const std::vector< const State * > &states)
Fills the vector StatesToSample_ of states to be sampled in the next calls to sampleUniform(), sampleUniformNear() or sampleGaussian().
A shared pointer wrapper for ompl::base::Planner.
virtual void getPlannerData(base::PlannerData &data) const
Get information about the current run of the motion planner. Repeated calls to this function will upd...
Definition: CForest.cpp:88
const PlannerDataVertex & getGoalVertex(unsigned int i) const
Retrieve a reference to the ith goal vertex object. If i is greater than the number of goal vertices...
Base class for a planner.
Definition: Planner.h:230
std::string getNumPathsShared() const
Get number of paths shared by the algorithm.
Definition: CForest.cpp:206
unsigned int numVertices() const
Retrieve the number of vertices in this structure.
virtual void setup()
Perform final setup steps. This function is automatically called by the SpaceInformation. If any default projections are to be registered, this call will set them and call their setup() functions. It is safe to call this function multiple times. At a subsequent call, projections that have been previously user configured are not re-instantiated, but their setup() method is still called.
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: Planner.cpp:86
virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc)
Function that can solve the motion planning problem. This function can be called multiple times on th...
Definition: CForest.cpp:168
A class to store the exit status of Planner::solve()
Definition: PlannerStatus.h:48
virtual bool addEdge(unsigned int v1, unsigned int v2, const PlannerDataEdge &edge=PlannerDataEdge(), Cost weight=Cost(1.0))
Adds a directed edge between the given vertex indexes. An optional edge structure and weight can be s...
const PlannerDataVertex & getVertex(unsigned int index) const
Retrieve a reference to the vertex object with the given index. If this vertex does not exist...
An optimization objective which corresponds to optimizing path length.
#define OMPL_WARN(fmt,...)
Log a formatted warning string.
Definition: Console.h:66
virtual PlannerStatus solve(const PlannerTerminationCondition &ptc)=0
Function that can solve the motion planning problem. This function can be called multiple times on th...
#define OMPL_DEBUG(fmt,...)
Log a formatted debugging string.
Definition: Console.h:70
const PlannerDataEdge & getEdge(unsigned int v1, unsigned int v2) const
Retrieve a reference to the edge object connecting vertices with indexes v1 and v2. If this edge does not exist, NO_EDGE is returned.
point now()
Get the current time point.
Definition: Time.h:72
bool markGoalState(const State *st)
Mark the given state as a goal vertex. If the given state does not exist in a vertex, false is returned.
virtual void getPlannerData(PlannerData &data) const
Get information about the current run of the motion planner. Repeated calls to this function will upd...
Definition: Planner.cpp:118
Coupled Forest of Random Engrafting Search Trees.
Definition: CForest.h:78
const std::string & getName() const
Get the name of the state space.
Definition: StateSpace.cpp:196
virtual void setTag(int tag)
Set the integer tag associated with this vertex.
Definition: PlannerData.h:71
unsigned int numStartVertices() const
Returns the number of start vertices.
std::chrono::system_clock::time_point point
Representation of a point in time.
Definition: Time.h:66
virtual const State * getState() const
Retrieve the state associated with this vertex.
Definition: PlannerData.h:73
Definition of a cost value. Can represent the cost of a motion or the cost of a state.
Definition: Cost.h:47
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:55
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68