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