pRRT.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/rrt/pRRT.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <limits>
41 
42 ompl::geometric::pRRT::pRRT(const base::SpaceInformationPtr &si) : base::Planner(si, "pRRT"),
43  samplerArray_(si)
44 {
46  specs_.multithreaded = true;
47  specs_.directed = true;
48 
49  setThreadCount(2);
50  goalBias_ = 0.05;
51  maxDistance_ = 0.0;
52  lastGoalMotion_ = nullptr;
53 
54  Planner::declareParam<double>("range", this, &pRRT::setRange, &pRRT::getRange, "0.:1.:10000.");
55  Planner::declareParam<double>("goal_bias", this, &pRRT::setGoalBias, &pRRT::getGoalBias, "0.:.05:1.");
56  Planner::declareParam<unsigned int>("thread_count", this, &pRRT::setThreadCount, &pRRT::getThreadCount, "1:64");
57 }
58 
59 ompl::geometric::pRRT::~pRRT()
60 {
61  freeMemory();
62 }
63 
65 {
66  Planner::setup();
69 
70  if (!nn_)
71  nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
72  nn_->setDistanceFunction(std::bind(&pRRT::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));
73 }
74 
76 {
77  Planner::clear();
78  samplerArray_.clear();
79  freeMemory();
80  if (nn_)
81  nn_->clear();
82  lastGoalMotion_ = nullptr;
83 }
84 
85 void ompl::geometric::pRRT::freeMemory()
86 {
87  if (nn_)
88  {
89  std::vector<Motion*> motions;
90  nn_->list(motions);
91  for (unsigned int i = 0 ; i < motions.size() ; ++i)
92  {
93  if (motions[i]->state)
94  si_->freeState(motions[i]->state);
95  delete motions[i];
96  }
97  }
98 }
99 
100 void ompl::geometric::pRRT::threadSolve(unsigned int tid, const base::PlannerTerminationCondition &ptc, SolutionInfo *sol)
101 {
102  base::Goal *goal = pdef_->getGoal().get();
103  base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion*>(goal);
104  RNG rng;
105 
106  Motion *rmotion = new Motion(si_);
107  base::State *rstate = rmotion->state;
108  base::State *xstate = si_->allocState();
109 
110  while (sol->solution == nullptr && ptc == false)
111  {
112  /* sample random state (with goal biasing) */
113  if (goal_s && rng.uniform01() < goalBias_ && goal_s->canSample())
114  goal_s->sampleGoal(rstate);
115  else
116  samplerArray_[tid]->sampleUniform(rstate);
117 
118  /* find closest state in the tree */
119  nnLock_.lock();
120  Motion *nmotion = nn_->nearest(rmotion);
121  nnLock_.unlock();
122  base::State *dstate = rstate;
123 
124  /* find state to add */
125  double d = si_->distance(nmotion->state, rstate);
126  if (d > maxDistance_)
127  {
128  si_->getStateSpace()->interpolate(nmotion->state, rstate, maxDistance_ / d, xstate);
129  dstate = xstate;
130  }
131 
132  if (si_->checkMotion(nmotion->state, dstate))
133  {
134  /* create a motion */
135  Motion *motion = new Motion(si_);
136  si_->copyState(motion->state, dstate);
137  motion->parent = nmotion;
138 
139  nnLock_.lock();
140  nn_->add(motion);
141  nnLock_.unlock();
142 
143  double dist = 0.0;
144  bool solved = goal->isSatisfied(motion->state, &dist);
145  if (solved)
146  {
147  sol->lock.lock();
148  sol->approxdif = dist;
149  sol->solution = motion;
150  sol->lock.unlock();
151  break;
152  }
153  if (dist < sol->approxdif)
154  {
155  sol->lock.lock();
156  if (dist < sol->approxdif)
157  {
158  sol->approxdif = dist;
159  sol->approxsol = motion;
160  }
161  sol->lock.unlock();
162  }
163  }
164  }
165 
166  si_->freeState(xstate);
167  if (rmotion->state)
168  si_->freeState(rmotion->state);
169  delete rmotion;
170 }
171 
173 {
174  checkValidity();
175 
176  base::GoalRegion *goal = dynamic_cast<base::GoalRegion*>(pdef_->getGoal().get());
177 
178  if (!goal)
179  {
180  OMPL_ERROR("%s: Unknow type of goal", getName().c_str());
182  }
183 
184  samplerArray_.resize(threadCount_);
185 
186  while (const base::State *st = pis_.nextStart())
187  {
188  Motion *motion = new Motion(si_);
189  si_->copyState(motion->state, st);
190  nn_->add(motion);
191  }
192 
193  if (nn_->size() == 0)
194  {
195  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
197  }
198 
199  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), nn_->size());
200 
201  SolutionInfo sol;
202  sol.solution = nullptr;
203  sol.approxsol = nullptr;
204  sol.approxdif = std::numeric_limits<double>::infinity();
205 
206  std::vector<std::thread*> th(threadCount_);
207  for (unsigned int i = 0 ; i < threadCount_ ; ++i)
208  th[i] = new std::thread(std::bind(&pRRT::threadSolve, this, i, ptc, &sol));
209  for (unsigned int i = 0 ; i < threadCount_ ; ++i)
210  {
211  th[i]->join();
212  delete th[i];
213  }
214 
215  bool solved = false;
216  bool approximate = false;
217  if (sol.solution == nullptr)
218  {
219  sol.solution = sol.approxsol;
220  approximate = true;
221  }
222 
223  if (sol.solution != nullptr)
224  {
225  lastGoalMotion_ = sol.solution;
226 
227  /* construct the solution path */
228  std::vector<Motion*> mpath;
229  while (sol.solution != nullptr)
230  {
231  mpath.push_back(sol.solution);
232  sol.solution = sol.solution->parent;
233  }
234 
235  /* set the solution path */
236  PathGeometric *path = new PathGeometric(si_);
237  for (int i = mpath.size() - 1 ; i >= 0 ; --i)
238  path->append(mpath[i]->state);
239 
240  pdef_->addSolutionPath(base::PathPtr(path), approximate, sol.approxdif, getName());
241  solved = true;
242  }
243 
244  OMPL_INFORM("%s: Created %u states", getName().c_str(), nn_->size());
245 
246  return base::PlannerStatus(solved, approximate);
247 }
248 
250 {
251  Planner::getPlannerData(data);
252 
253  std::vector<Motion*> motions;
254  if (nn_)
255  nn_->list(motions);
256 
257  if (lastGoalMotion_)
259 
260  for (unsigned int i = 0 ; i < motions.size() ; ++i)
261  {
262  if (motions[i]->parent == nullptr)
263  data.addStartVertex(base::PlannerDataVertex(motions[i]->state));
264  else
265  data.addEdge(base::PlannerDataVertex(motions[i]->parent->state),
266  base::PlannerDataVertex(motions[i]->state));
267  }
268 }
269 
270 void ompl::geometric::pRRT::setThreadCount(unsigned int nthreads)
271 {
272  assert(nthreads > 0);
273  threadCount_ = nthreads;
274 }
std::shared_ptr< NearestNeighbors< Motion * > > nn_
A nearest-neighbors datastructure containing the tree of motions.
Definition: LBTRRT.h:279
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:212
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:163
void freeMemory()
Free the memory allocated by this planner.
Definition: LBTRRT.cpp:94
double getGoalBias() const
Get the goal bias the planner is using.
Definition: pRRT.h:97
void setGoalBias(double goalBias)
Set the goal bias.
Definition: pRRT.h:91
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...
Abstract definition of goals.
Definition: Goal.h:62
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: LBTRRT.h:291
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
bool directed
Flag indicating whether the planner is able to account for the fact that the validity of a motion fro...
Definition: Planner.h:220
virtual void sampleGoal(State *st) const =0
Sample a state in the goal region.
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: pRRT.cpp:249
double goalBias_
The fraction of time the goal is picked as the state to expand towards (if such a state is available)...
Definition: LBTRRT.h:288
void setThreadCount(unsigned int nthreads)
Set the number of threads the planner should use. Default is 2.
Definition: pRRT.cpp:270
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
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: pRRT.cpp:75
Abstract definition of a goal region that can be sampled.
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
Motion * lastGoalMotion_
The most recent goal motion. Used for PlannerData computation.
Definition: LBTRRT.h:300
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: pRRT.h:107
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...
bool canSample() const
Return true if maxSampleCount() > 0, since in this case samples can certainly be produced.
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
double getRange() const
Get the range the planner is using.
Definition: pRRT.h:113
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
virtual bool isSatisfied(const State *st) const =0
Return true if the state satisfies the goal constraints.
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
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
Definition of a goal region.
Definition: GoalRegion.h:50
Definition of a geometric path.
Definition: PathGeometric.h:60
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:398
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: pRRT.cpp:172
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: pRRT.cpp:64
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:55
A shared pointer wrapper for ompl::base::Path.
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68