pSBL.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2008, 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 the 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 "ompl/geometric/planners/sbl/pSBL.h"
38 #include "ompl/base/goals/GoalState.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <limits>
41 #include <cassert>
42 
43 ompl::geometric::pSBL::pSBL(const base::SpaceInformationPtr &si) : base::Planner(si, "pSBL"),
44  samplerArray_(si)
45 {
47  specs_.multithreaded = true;
48  maxDistance_ = 0.0;
49  setThreadCount(2);
50  connectionPoint_ = std::make_pair<base::State*, base::State*>(nullptr, nullptr);
51 
52  Planner::declareParam<double>("range", this, &pSBL::setRange, &pSBL::getRange, "0.:1.:10000.");
53  Planner::declareParam<unsigned int>("thread_count", this, &pSBL::setThreadCount, &pSBL::getThreadCount, "1:64");
54 }
55 
56 ompl::geometric::pSBL::~pSBL()
57 {
58  freeMemory();
59 }
60 
62 {
63  Planner::setup();
67 
68  tStart_.grid.setDimension(projectionEvaluator_->getDimension());
69  tGoal_.grid.setDimension(projectionEvaluator_->getDimension());
70 }
71 
73 {
74  Planner::clear();
75 
76  samplerArray_.clear();
77 
78  freeMemory();
79 
80  tStart_.grid.clear();
81  tStart_.size = 0;
82  tStart_.pdf.clear();
83 
84  tGoal_.grid.clear();
85  tGoal_.size = 0;
86  tGoal_.pdf.clear();
87 
88  removeList_.motions.clear();
89  connectionPoint_ = std::make_pair<base::State*, base::State*>(nullptr, nullptr);
90 }
91 
92 void ompl::geometric::pSBL::freeGridMotions(Grid<MotionInfo> &grid)
93 {
94  for (Grid<MotionInfo>::iterator it = grid.begin(); it != grid.end() ; ++it)
95  {
96  for (unsigned int i = 0 ; i < it->second->data.size() ; ++i)
97  {
98  if (it->second->data[i]->state)
99  si_->freeState(it->second->data[i]->state);
100  delete it->second->data[i];
101  }
102  }
103 }
104 
105 void ompl::geometric::pSBL::threadSolve(unsigned int tid, const base::PlannerTerminationCondition &ptc, SolutionInfo *sol)
106 {
107  RNG rng;
108 
109  std::vector<Motion*> solution;
110  base::State *xstate = si_->allocState();
111  bool startTree = rng.uniformBool();
112 
113  while (!sol->found && ptc == false)
114  {
115  bool retry = true;
116  while (retry && !sol->found && ptc == false)
117  {
118  removeList_.lock.lock();
119  if (!removeList_.motions.empty())
120  {
121  if (loopLock_.try_lock())
122  {
123  retry = false;
124  std::map<Motion*, bool> seen;
125  for (unsigned int i = 0 ; i < removeList_.motions.size() ; ++i)
126  if (seen.find(removeList_.motions[i].motion) == seen.end())
127  removeMotion(*removeList_.motions[i].tree, removeList_.motions[i].motion, seen);
128  removeList_.motions.clear();
129  loopLock_.unlock();
130  }
131  }
132  else
133  retry = false;
134  removeList_.lock.unlock();
135  }
136 
137  if (sol->found || ptc)
138  break;
139 
140  loopLockCounter_.lock();
141  if (loopCounter_ == 0)
142  loopLock_.lock();
143  loopCounter_++;
144  loopLockCounter_.unlock();
145 
146 
147  TreeData &tree = startTree ? tStart_ : tGoal_;
148  startTree = !startTree;
149  TreeData &otherTree = startTree ? tStart_ : tGoal_;
150 
151  Motion *existing = selectMotion(rng, tree);
152  if (!samplerArray_[tid]->sampleNear(xstate, existing->state, maxDistance_))
153  continue;
154 
155  /* create a motion */
156  Motion *motion = new Motion(si_);
157  si_->copyState(motion->state, xstate);
158  motion->parent = existing;
159  motion->root = existing->root;
160 
161  existing->lock.lock();
162  existing->children.push_back(motion);
163  existing->lock.unlock();
164 
165  addMotion(tree, motion);
166 
167  if (checkSolution(rng, !startTree, tree, otherTree, motion, solution))
168  {
169  sol->lock.lock();
170  if (!sol->found)
171  {
172  sol->found = true;
173  PathGeometric *path = new PathGeometric(si_);
174  for (unsigned int i = 0 ; i < solution.size() ; ++i)
175  path->append(solution[i]->state);
176  pdef_->addSolutionPath(base::PathPtr(path), false, 0.0, getName());
177  }
178  sol->lock.unlock();
179  }
180 
181 
182  loopLockCounter_.lock();
183  loopCounter_--;
184  if (loopCounter_ == 0)
185  loopLock_.unlock();
186  loopLockCounter_.unlock();
187  }
188 
189  si_->freeState(xstate);
190 }
191 
193 {
194  checkValidity();
195 
196  base::GoalState *goal = dynamic_cast<base::GoalState*>(pdef_->getGoal().get());
197 
198  if (!goal)
199  {
200  OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
202  }
203 
204  while (const base::State *st = pis_.nextStart())
205  {
206  Motion *motion = new Motion(si_);
207  si_->copyState(motion->state, st);
208  motion->valid = true;
209  motion->root = motion->state;
210  addMotion(tStart_, motion);
211  }
212 
213  if (tGoal_.size == 0)
214  {
215  if (si_->satisfiesBounds(goal->getState()) && si_->isValid(goal->getState()))
216  {
217  Motion *motion = new Motion(si_);
218  si_->copyState(motion->state, goal->getState());
219  motion->valid = true;
220  motion->root = motion->state;
221  addMotion(tGoal_, motion);
222  }
223  else
224  OMPL_ERROR("%s: Goal state is invalid!", getName().c_str());
225  }
226 
227  if (tStart_.size == 0)
228  {
229  OMPL_ERROR("%s: Motion planning start tree could not be initialized!", getName().c_str());
231  }
232  if (tGoal_.size == 0)
233  {
234  OMPL_ERROR("%s: Motion planning goal tree could not be initialized!", getName().c_str());
236  }
237 
238  samplerArray_.resize(threadCount_);
239 
240  OMPL_INFORM("%s: Starting planning with %d states already in datastructure", getName().c_str(), (int)(tStart_.size + tGoal_.size));
241 
242  SolutionInfo sol;
243  sol.found = false;
244  loopCounter_ = 0;
245 
246  std::vector<std::thread*> th(threadCount_);
247  for (unsigned int i = 0 ; i < threadCount_ ; ++i)
248  th[i] = new std::thread(std::bind(&pSBL::threadSolve, this, i, ptc, &sol));
249  for (unsigned int i = 0 ; i < threadCount_ ; ++i)
250  {
251  th[i]->join();
252  delete th[i];
253  }
254 
255  OMPL_INFORM("%s: Created %u (%u start + %u goal) states in %u cells (%u start + %u goal)",
257  tStart_.grid.size() + tGoal_.grid.size(), tStart_.grid.size(), tGoal_.grid.size());
258 
260 }
261 
262 bool ompl::geometric::pSBL::checkSolution(RNG &rng, bool start, TreeData &tree, TreeData &otherTree, Motion *motion, std::vector<Motion*> &solution)
263 {
265  projectionEvaluator_->computeCoordinates(motion->state, coord);
266 
267  otherTree.lock.lock();
268  Grid<MotionInfo>::Cell* cell = otherTree.grid.getCell(coord);
269 
270  if (cell && !cell->data.empty())
271  {
272  Motion *connectOther = cell->data[rng.uniformInt(0, cell->data.size() - 1)];
273  otherTree.lock.unlock();
274 
275  if (pdef_->getGoal()->isStartGoalPairValid(start ? motion->root : connectOther->root, start ? connectOther->root : motion->root))
276  {
277  Motion *connect = new Motion(si_);
278 
279  si_->copyState(connect->state, connectOther->state);
280  connect->parent = motion;
281  connect->root = motion->root;
282 
283  motion->lock.lock();
284  motion->children.push_back(connect);
285  motion->lock.unlock();
286 
287  addMotion(tree, connect);
288 
289  if (isPathValid(tree, connect) && isPathValid(otherTree, connectOther))
290  {
291  if (start)
292  connectionPoint_ = std::make_pair(motion->state, connectOther->state);
293  else
294  connectionPoint_ = std::make_pair(connectOther->state, motion->state);
295 
296  /* extract the motions and put them in solution vector */
297 
298  std::vector<Motion*> mpath1;
299  while (motion != nullptr)
300  {
301  mpath1.push_back(motion);
302  motion = motion->parent;
303  }
304 
305  std::vector<Motion*> mpath2;
306  while (connectOther != nullptr)
307  {
308  mpath2.push_back(connectOther);
309  connectOther = connectOther->parent;
310  }
311 
312  if (!start)
313  mpath1.swap(mpath2);
314 
315  for (int i = mpath1.size() - 1 ; i >= 0 ; --i)
316  solution.push_back(mpath1[i]);
317  solution.insert(solution.end(), mpath2.begin(), mpath2.end());
318 
319  return true;
320  }
321  }
322  }
323  else
324  otherTree.lock.unlock();
325 
326  return false;
327 }
328 
329 bool ompl::geometric::pSBL::isPathValid(TreeData &tree, Motion *motion)
330 {
331  std::vector<Motion*> mpath;
332 
333  /* construct the solution path */
334  while (motion != nullptr)
335  {
336  mpath.push_back(motion);
337  motion = motion->parent;
338  }
339 
340  bool result = true;
341 
342  /* check the path */
343  for (int i = mpath.size() - 1 ; result && i >= 0 ; --i)
344  {
345  mpath[i]->lock.lock();
346  if (!mpath[i]->valid)
347  {
348  if (si_->checkMotion(mpath[i]->parent->state, mpath[i]->state))
349  mpath[i]->valid = true;
350  else
351  {
352  // remember we need to remove this motion
354  prm.tree = &tree;
355  prm.motion = mpath[i];
356  removeList_.lock.lock();
357  removeList_.motions.push_back(prm);
358  removeList_.lock.unlock();
359  result = false;
360  }
361  }
362  mpath[i]->lock.unlock();
363  }
364 
365  return result;
366 }
367 
368 ompl::geometric::pSBL::Motion* ompl::geometric::pSBL::selectMotion(RNG &rng, TreeData &tree)
369 {
370  tree.lock.lock ();
371  GridCell* cell = tree.pdf.sample(rng.uniform01());
372  Motion *result = cell && !cell->data.empty() ? cell->data[rng.uniformInt(0, cell->data.size() - 1)] : nullptr;
373  tree.lock.unlock ();
374  return result;
375 }
376 
377 void ompl::geometric::pSBL::removeMotion(TreeData &tree, Motion *motion, std::map<Motion*, bool> &seen)
378 {
379  /* remove from grid */
380  seen[motion] = true;
381 
383  projectionEvaluator_->computeCoordinates(motion->state, coord);
384  Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
385  if (cell)
386  {
387  for (unsigned int i = 0 ; i < cell->data.size(); ++i)
388  if (cell->data[i] == motion)
389  {
390  cell->data.erase(cell->data.begin() + i);
391  tree.size--;
392  break;
393  }
394  if (cell->data.empty())
395  {
396  tree.pdf.remove(cell->data.elem_);
397  tree.grid.remove(cell);
398  tree.grid.destroyCell(cell);
399  }
400  else
401  {
402  tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
403  }
404  }
405 
406  /* remove self from parent list */
407 
408  if (motion->parent)
409  {
410  for (unsigned int i = 0 ; i < motion->parent->children.size() ; ++i)
411  if (motion->parent->children[i] == motion)
412  {
413  motion->parent->children.erase(motion->parent->children.begin() + i);
414  break;
415  }
416  }
417 
418  /* remove children */
419  for (unsigned int i = 0 ; i < motion->children.size() ; ++i)
420  {
421  motion->children[i]->parent = nullptr;
422  removeMotion(tree, motion->children[i], seen);
423  }
424 
425  if (motion->state)
426  si_->freeState(motion->state);
427  delete motion;
428 }
429 
430 void ompl::geometric::pSBL::addMotion(TreeData &tree, Motion *motion)
431 {
433  projectionEvaluator_->computeCoordinates(motion->state, coord);
434  tree.lock.lock();
435  Grid<MotionInfo>::Cell* cell = tree.grid.getCell(coord);
436  if (cell)
437  {
438  cell->data.push_back(motion);
439  tree.pdf.update(cell->data.elem_, 1.0/cell->data.size());
440  }
441  else
442  {
443  cell = tree.grid.createCell(coord);
444  cell->data.push_back(motion);
445  tree.grid.add(cell);
446  cell->data.elem_ = tree.pdf.add(cell, 1.0);
447  }
448  tree.size++;
449  tree.lock.unlock();
450 }
451 
453 {
454  Planner::getPlannerData(data);
455 
456  std::vector<MotionInfo> motions;
457  tStart_.grid.getContent(motions);
458 
459  for (unsigned int i = 0 ; i < motions.size() ; ++i)
460  for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
461  if (motions[i][j]->parent == nullptr)
462  data.addStartVertex(base::PlannerDataVertex(motions[i][j]->state, 1));
463  else
464  data.addEdge(base::PlannerDataVertex(motions[i][j]->parent->state, 1),
465  base::PlannerDataVertex(motions[i][j]->state, 1));
466 
467  motions.clear();
468  tGoal_.grid.getContent(motions);
469  for (unsigned int i = 0 ; i < motions.size() ; ++i)
470  for (unsigned int j = 0 ; j < motions[i].size() ; ++j)
471  if (motions[i][j]->parent == nullptr)
472  data.addGoalVertex(base::PlannerDataVertex(motions[i][j]->state, 2));
473  else
474  // The edges in the goal tree are reversed so that they are in the same direction as start tree
475  data.addEdge(base::PlannerDataVertex(motions[i][j]->state, 2),
476  base::PlannerDataVertex(motions[i][j]->parent->state, 2));
477 
478  data.addEdge(data.vertexIndex(connectionPoint_.first), data.vertexIndex(connectionPoint_.second));
479 }
480 
481 void ompl::geometric::pSBL::setThreadCount(unsigned int nthreads)
482 {
483  assert(nthreads > 0);
484  threadCount_ = nthreads;
485 }
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:163
TreeData tGoal_
The goal tree.
Definition: SBL.h:267
Representation of a simple grid.
Definition: Grid.h:51
void setThreadCount(unsigned int nthreads)
Set the number of threads the planner should use. Default is 2.
Definition: pSBL.cpp:481
The planner failed to find a solution.
Definition: PlannerStatus.h:62
GoalType recognizedGoal
The type of goal specification the planner can use.
Definition: Planner.h:206
std::vector< int > Coord
Definition of a coordinate within this grid.
Definition: Grid.h:56
const State * getState() const
Get the goal state.
Definition: GoalState.cpp:79
Definition of a goal state.
Definition: GoalState.h:50
void clear()
Clears the PDF.
Definition: PDF.h:241
unsigned int addGoalVertex(const PlannerDataVertex &v)
Adds the given vertex to the graph data, and marks it as a start vertex. The vertex index is returned...
void addMotion(TreeData &tree, Motion *motion)
Add a motion to a tree.
Definition: SBL.cpp:329
std::vector< Motion * > children
The set of motions descending from the current motion.
Definition: SBL.h:176
void freeMemory()
Free the memory allocated by the planner.
Definition: SBL.h:229
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
_T data
The data we store in the cell.
Definition: Grid.h:62
base::ProjectionEvaluatorPtr projectionEvaluator_
The employed projection evaluator.
Definition: SBL.h:261
bool uniformBool()
Generate a random boolean.
Definition: RandomNumbers.h:89
bool isPathValid(TreeData &tree, Motion *motion)
Since solutions are computed in a lazy fashion, once trees are connected, the solution found needs to...
Definition: SBL.cpp:241
void append(const base::State *state)
Append state to the end of this path. The memory for state is copied.
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:401
bool multithreaded
Flag indicating whether multiple threads are used in the computation of the planner.
Definition: Planner.h:209
Motion * selectMotion(TreeData &tree)
Select a motion from a tree.
Definition: SBL.cpp:267
double uniform01()
Generate a random real between 0 and 1.
Definition: RandomNumbers.h:69
Base class for a vertex in the PlannerData structure. All derived classes must implement the clone an...
Definition: PlannerData.h:59
void remove(Element *elem)
Removes the data in the given Element from the PDF. After calling this function, the Element object s...
Definition: PDF.h:177
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
CellPDF pdf
The PDF used for selecting a cell from which to sample a motion.
Definition: SBL.h:225
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: pSBL.cpp:192
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: pSBL.cpp:72
unsigned int size
The number of motions (in total) from the tree.
Definition: SBL.h:222
Random number generation. An instance of this class cannot be used by multiple threads at once (membe...
Definition: RandomNumbers.h:58
The goal is of a type that a planner does not recognize.
Definition: PlannerStatus.h:60
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
The planner found an exact solution.
Definition: PlannerStatus.h:66
unsigned int vertexIndex(const PlannerDataVertex &v) const
Return the index for the vertex associated with the given data. INVALID_INDEX is returned if this ver...
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...
iterator end() const
Return the end() iterator for the grid.
Definition: Grid.h:383
void removeMotion(TreeData &tree, Motion *motion)
Remove a motion from a tree.
Definition: SBL.cpp:273
unsigned int addStartVertex(const PlannerDataVertex &v)
Adds the given vertex to the graph data, and marks it as a start vertex. The vertex index is returned...
Definition of an abstract state.
Definition: State.h:50
Grid< MotionInfo > grid
The grid of motions corresponding to this tree.
Definition: SBL.h:219
virtual void checkValidity()
Check to see if the planner is in a working state (setup has been called, a goal was set...
Definition: Planner.cpp:100
bool checkSolution(bool start, TreeData &tree, TreeData &otherTree, Motion *motion, std::vector< Motion * > &solution)
Check if a solution can be obtained by connecting two trees using a specified motion.
Definition: SBL.cpp:184
PlannerInputStates pis_
Utility class to extract valid input states.
Definition: Planner.h:404
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:410
const State * nextStart()
Return the next valid start state or nullptr if no more valid start states are available.
Definition: Planner.cpp:230
Definition of a cell in this grid.
Definition: Grid.h:59
void update(Element *elem, const double w)
Updates the data in the given Element with a new weight value.
Definition: PDF.h:155
void configureProjectionEvaluator(base::ProjectionEvaluatorPtr &proj)
If proj is undefined, it is set to the default projection reported by base::StateSpace::getDefaultPro...
Definition: SelfConfig.cpp:236
std::pair< base::State *, base::State * > connectionPoint_
The pair of states in each tree connected during planning. Used for PlannerData computation.
Definition: SBL.h:276
Element * add(const _T &d, const double w)
Adds a piece of data with a given weight to the PDF. Returns a corresponding Element, which can be used to subsequently update or remove the data from the PDF.
Definition: PDF.h:97
iterator begin() const
Return the begin() iterator for the grid.
Definition: Grid.h:377
This bit is set if casting to goal state (ompl::base::GoalState) is possible.
Definition: GoalTypes.h:58
unsigned int getThreadCount() const
Get the thread count.
Definition: pSBL.h:136
void configurePlannerRange(double &range)
Compute what a good length for motion segments is.
Definition: SelfConfig.cpp:230
This class contains methods that automatically configure various parameters for motion planning...
Definition: SelfConfig.h:60
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: pSBL.cpp:452
Definition of a geometric path.
Definition: PathGeometric.h:60
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: pSBL.h:121
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: pSBL.cpp:61
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:398
int uniformInt(int lower_bound, int upper_bound)
Generate a random integer within given bounds: [lower_bound, upper_bound].
Definition: RandomNumbers.h:82
_T & sample(double r) const
Returns a piece of data from the PDF according to the input sampling value, which must be between 0 a...
Definition: PDF.h:132
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:55
double maxDistance_
The maximum length of a motion to be added in the tree.
Definition: SBL.h:270
double getRange() const
Get the range the planner is using.
Definition: pSBL.h:127
A shared pointer wrapper for ompl::base::Path.
CoordHash::const_iterator iterator
We only allow const iterators.
Definition: Grid.h:374
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68
TreeData tStart_
The start tree.
Definition: SBL.h:264