LazyRRT.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/LazyRRT.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <cassert>
41 
42 ompl::geometric::LazyRRT::LazyRRT(const base::SpaceInformationPtr &si) : base::Planner(si, "LazyRRT")
43 {
44  specs_.directed = true;
45  goalBias_ = 0.05;
46  maxDistance_ = 0.0;
47  lastGoalMotion_ = nullptr;
48 
49  Planner::declareParam<double>("range", this, &LazyRRT::setRange, &LazyRRT::getRange, "0.:1.:10000.");
50  Planner::declareParam<double>("goal_bias", this, &LazyRRT::setGoalBias, &LazyRRT::getGoalBias, "0.:.05:1.");
51 }
52 
53 ompl::geometric::LazyRRT::~LazyRRT()
54 {
55  freeMemory();
56 }
57 
59 {
60  Planner::setup();
63 
64  if (!nn_)
65  nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion *>(this));
66  nn_->setDistanceFunction([this](const Motion *a, const Motion *b)
67  {
68  return distanceFunction(a, b);
69  });
70 }
71 
73 {
74  Planner::clear();
75  sampler_.reset();
76  freeMemory();
77  if (nn_)
78  nn_->clear();
79  lastGoalMotion_ = nullptr;
80 }
81 
83 {
84  if (nn_)
85  {
86  std::vector<Motion *> motions;
87  nn_->list(motions);
88  for (auto &motion : motions)
89  {
90  if (motion->state)
91  si_->freeState(motion->state);
92  delete motion;
93  }
94  }
95 }
96 
98 {
99  checkValidity();
100  base::Goal *goal = pdef_->getGoal().get();
101  base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion *>(goal);
102 
103  while (const base::State *st = pis_.nextStart())
104  {
105  auto *motion = new Motion(si_);
106  si_->copyState(motion->state, st);
107  motion->valid = true;
108  nn_->add(motion);
109  }
110 
111  if (nn_->size() == 0)
112  {
113  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
115  }
116 
117  if (!sampler_)
118  sampler_ = si_->allocStateSampler();
119 
120  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), nn_->size());
121 
122  Motion *solution = nullptr;
123  double distsol = -1.0;
124  auto *rmotion = new Motion(si_);
125  base::State *rstate = rmotion->state;
126  base::State *xstate = si_->allocState();
127 
128  bool solutionFound = false;
129 
130  while (ptc == false && !solutionFound)
131  {
132  /* sample random state (with goal biasing) */
133  if (goal_s && rng_.uniform01() < goalBias_ && goal_s->canSample())
134  goal_s->sampleGoal(rstate);
135  else
136  sampler_->sampleUniform(rstate);
137 
138  /* find closest state in the tree */
139  Motion *nmotion = nn_->nearest(rmotion);
140  assert(nmotion != rmotion);
141  base::State *dstate = rstate;
142 
143  /* find state to add */
144  double d = si_->distance(nmotion->state, rstate);
145  if (d > maxDistance_)
146  {
147  si_->getStateSpace()->interpolate(nmotion->state, rstate, maxDistance_ / d, xstate);
148  dstate = xstate;
149  }
150 
151  /* create a motion */
152  auto *motion = new Motion(si_);
153  si_->copyState(motion->state, dstate);
154  motion->parent = nmotion;
155  nmotion->children.push_back(motion);
156  nn_->add(motion);
157 
158  double dist = 0.0;
159  if (goal->isSatisfied(motion->state, &dist))
160  {
161  distsol = dist;
162  solution = motion;
163  solutionFound = true;
164  lastGoalMotion_ = solution;
165 
166  // Check that the solution is valid:
167  // construct the solution path
168  std::vector<Motion *> mpath;
169  while (solution != nullptr)
170  {
171  mpath.push_back(solution);
172  solution = solution->parent;
173  }
174 
175  // check each segment along the path for validity
176  for (int i = mpath.size() - 1; i >= 0 && solutionFound; --i)
177  if (!mpath[i]->valid)
178  {
179  if (si_->checkMotion(mpath[i]->parent->state, mpath[i]->state))
180  mpath[i]->valid = true;
181  else
182  {
183  removeMotion(mpath[i]);
184  solutionFound = false;
185  lastGoalMotion_ = nullptr;
186  }
187  }
188 
189  if (solutionFound)
190  {
191  // set the solution path
192  auto path(std::make_shared<PathGeometric>(si_));
193  for (int i = mpath.size() - 1; i >= 0; --i)
194  path->append(mpath[i]->state);
195 
196  pdef_->addSolutionPath(path, false, distsol, getName());
197  }
198  }
199  }
200 
201  si_->freeState(xstate);
202  si_->freeState(rstate);
203  delete rmotion;
204 
205  OMPL_INFORM("%s: Created %u states", getName().c_str(), nn_->size());
206 
208 }
209 
211 {
212  nn_->remove(motion);
213 
214  /* remove self from parent list */
215 
216  if (motion->parent)
217  {
218  for (unsigned int i = 0; i < motion->parent->children.size(); ++i)
219  if (motion->parent->children[i] == motion)
220  {
221  motion->parent->children.erase(motion->parent->children.begin() + i);
222  break;
223  }
224  }
225 
226  /* remove children */
227  for (auto &i : motion->children)
228  {
229  i->parent = nullptr;
230  removeMotion(i);
231  }
232 
233  if (motion->state)
234  si_->freeState(motion->state);
235  delete motion;
236 }
237 
239 {
240  Planner::getPlannerData(data);
241 
242  std::vector<Motion *> motions;
243  if (nn_)
244  nn_->list(motions);
245 
246  if (lastGoalMotion_)
248 
249  for (auto &motion : motions)
250  {
251  if (motion->parent == nullptr)
252  data.addStartVertex(base::PlannerDataVertex(motion->state));
253  else
254  data.addEdge(base::PlannerDataVertex(motion->parent ? motion->parent->state : nullptr),
255  base::PlannerDataVertex(motion->state));
256 
257  data.tagState(motion->state, motion->valid ? 1 : 0);
258  }
259 }
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:174
void setup() override
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: LazyRRT.cpp:58
void getPlannerData(base::PlannerData &data) const override
Get information about the current run of the motion planner. Repeated calls to this function will upd...
Definition: LazyRRT.cpp:238
double getRange() const
Get the range the planner is using.
Definition: LazyRRT.h:126
The planner failed to find a solution.
Definition: PlannerStatus.h:62
void setGoalBias(double goalBias)
Set the goal biasing.
Definition: LazyRRT.h:104
std::vector< Motion * > children
The set of motions that descend from this one.
Definition: LazyRRT.h:170
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...
base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override
Function that can solve the motion planning problem. This function can be called multiple times on th...
Definition: LazyRRT.cpp:97
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:418
bool directed
Flag indicating whether the planner is able to account for the fact that the validity of a motion fro...
Definition: Planner.h:222
virtual void sampleGoal(State *st) const =0
Sample a state in the goal region.
void removeMotion(Motion *motion)
Remove a motion from the tree datastructure.
Definition: LazyRRT.cpp:210
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: LazyRRT.h:196
Representation of a motion.
Definition: LazyRRT.h:146
double uniform01()
Generate a random real between 0 and 1.
Definition: RandomNumbers.h:68
Base class for a vertex in the PlannerData structure. All derived classes must implement the clone an...
Definition: PlannerData.h:58
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
Abstract definition of a goal region that can be sampled.
Motion * lastGoalMotion_
The most recent goal motion. Used for PlannerData computation.
Definition: LazyRRT.h:202
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: LazyRRT.h:120
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
bool tagState(const State *st, int tag)
Set the integer tag associated with the given state. If the given state does not exist in a vertex...
double goalBias_
The fraction of time the goal is picked as the state to expand towards (if such a state is available)...
Definition: LazyRRT.h:193
bool canSample() const
Return true if maxSampleCount() > 0, since in this case samples can certainly be produced.
The planner found an exact solution.
Definition: PlannerStatus.h:66
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...
RNG rng_
The random number generator.
Definition: LazyRRT.h:199
A shared pointer wrapper for ompl::base::SpaceInformation.
double getGoalBias() const
Get the goal bias the planner is using.
Definition: LazyRRT.h:110
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:49
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:101
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:421
base::State * state
The state contained by the motion.
Definition: LazyRRT.h:161
void freeMemory()
Free the memory allocated by this planner.
Definition: LazyRRT.cpp:82
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:427
const State * nextStart()
Return the next valid start state or nullptr if no more valid start states are available.
Definition: Planner.cpp:230
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:56
void configurePlannerRange(double &range)
Compute what a good length for motion segments is.
Definition: SelfConfig.cpp:225
std::shared_ptr< NearestNeighbors< Motion * > > nn_
A nearest-neighbors datastructure containing the tree of motions.
Definition: LazyRRT.h:189
void clear() override
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: LazyRRT.cpp:72
This class contains methods that automatically configure various parameters for motion planning...
Definition: SelfConfig.h:59
LazyRRT(const base::SpaceInformationPtr &si)
Constructor.
Definition: LazyRRT.cpp:42
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:415
Motion * parent
The parent motion in the exploration tree.
Definition: LazyRRT.h:164
base::StateSamplerPtr sampler_
State sampler.
Definition: LazyRRT.h:186
double distanceFunction(const Motion *a, const Motion *b) const
Compute distance between motions (actually distance between contained states)
Definition: LazyRRT.h:180
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68