SST.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2015, Rutgers the State University of New Jersey, New Brunswick
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 Rutgers 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: Zakary Littlefield */
36 
37 #include "ompl/geometric/planners/sst/SST.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/base/objectives/MinimaxObjective.h"
40 #include "ompl/base/objectives/MaximizeMinClearanceObjective.h"
41 #include "ompl/base/objectives/PathLengthOptimizationObjective.h"
42 #include "ompl/tools/config/SelfConfig.h"
43 #include <limits>
44 
45 ompl::geometric::SST::SST(const base::SpaceInformationPtr &si) : base::Planner(si, "SST")
46 {
48  specs_.directed = true;
49  prevSolution_.clear();
50 
51  goalBias_ = 0.05;
52  selectionRadius_ = 5.0;
53  pruningRadius_ = 3.0;
54  maxDistance_ = 5.0;
55 
56  Planner::declareParam<double>("range", this, &SST::setRange, &SST::getRange, ".1:.1:100");
57  Planner::declareParam<double>("goal_bias", this, &SST::setGoalBias, &SST::getGoalBias, "0.:.05:1.");
58  Planner::declareParam<double>("selection_radius", this, &SST::setSelectionRadius, &SST::getSelectionRadius, "0.:.1:100");
59  Planner::declareParam<double>("pruning_radius", this, &SST::setPruningRadius, &SST::getPruningRadius, "0.:.1:100");
60 }
61 
62 ompl::geometric::SST::~SST()
63 {
64  freeMemory();
65 }
66 
68 {
70  if (!nn_)
71  nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
72  nn_->setDistanceFunction(std::bind(&SST::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));
73  if (!witnesses_)
74  witnesses_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
75  witnesses_->setDistanceFunction(std::bind(&SST::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));
76 
77  if (pdef_)
78  {
79  if (pdef_->hasOptimizationObjective())
80  {
81  opt_ = pdef_->getOptimizationObjective();
82  if (dynamic_cast<base::MaximizeMinClearanceObjective*>(opt_.get()) || dynamic_cast<base::MinimaxObjective*>(opt_.get()))
83  OMPL_WARN("%s: Asymptotic near-optimality has only been proven with Lipschitz continuous cost functions w.r.t. state and control. This optimization objective will result in undefined behavior", getName().c_str());
84  }
85  else
86  {
87  OMPL_WARN("%s: No optimization object set. Using path length", getName().c_str());
88  opt_.reset(new base::PathLengthOptimizationObjective(si_));
89  pdef_->setOptimizationObjective(opt_);
90  }
91  }
92 
93  prevSolutionCost_ = opt_->infiniteCost();
94 
95 }
96 
98 {
99  Planner::clear();
100  sampler_.reset();
101  freeMemory();
102  if (nn_)
103  nn_->clear();
104  if (witnesses_)
105  witnesses_->clear();
106  prevSolutionCost_ = opt_->infiniteCost();
107 }
108 
110 {
111  if (nn_)
112  {
113  std::vector<Motion*> motions;
114  nn_->list(motions);
115  for (unsigned int i = 0 ; i < motions.size() ; ++i)
116  {
117  if (motions[i]->state_)
118  si_->freeState(motions[i]->state_);
119  delete motions[i];
120  }
121  }
122  if (witnesses_)
123  {
124  std::vector<Motion*> witnesses;
125  witnesses_->list(witnesses);
126  for (unsigned int i = 0 ; i < witnesses.size() ; ++i)
127  {
128  if (witnesses[i]->state_)
129  si_->freeState(witnesses[i]->state_);
130  delete witnesses[i];
131  }
132  }
133 
134  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
135  {
136  if (prevSolution_[i])
137  si_->freeState(prevSolution_[i]);
138  }
139  prevSolution_.clear();
140 }
141 
143 {
144  std::vector<Motion*> ret;
145  Motion* selected = nullptr;
146  base::Cost bestCost = opt_->infiniteCost();
147  nn_->nearestR(sample, selectionRadius_, ret);
148  for (unsigned int i = 0; i < ret.size(); i++)
149  {
150  if (!ret[i]->inactive_ && opt_->isCostBetterThan(ret[i]->accCost_, bestCost))
151  {
152  bestCost = ret[i]->accCost_;
153  selected = ret[i];
154  }
155  }
156  if(selected==nullptr)
157  {
158  int k = 1;
159  while (selected == nullptr)
160  {
161  nn_->nearestK(sample,k,ret);
162  for (unsigned int i = 0; i < ret.size() && selected == nullptr; i++)
163  if(!ret[i]->inactive_)
164  selected = ret[i];
165  k += 5;
166  }
167  }
168  return selected;
169 }
170 
172 {
173  if(witnesses_->size() > 0)
174  {
175  Witness *closest = static_cast<Witness*>(witnesses_->nearest(node));
176  if(distanceFunction(closest, node) > pruningRadius_)
177  {
178  closest = new Witness(si_);
179  closest->linkRep(node);
180  si_->copyState(closest->state_, node->state_);
181  witnesses_->add(closest);
182  }
183  return closest;
184  }
185  else
186  {
187  Witness *closest = new Witness(si_);
188  closest->linkRep(node);
189  si_->copyState(closest->state_, node->state_);
190  witnesses_->add(closest);
191  return closest;
192  }
193 }
194 
195 
197 {
198  //sample random point to serve as a direction
199  base::State *xstate = si_->allocState();
200  sampler_->sampleUniform(xstate);
201 
202  //sample length of step from (0 - maxDistance_]
203  double step = rng_.uniformReal(0, maxDistance_);
204 
205  //take a step of length step towards the random state
206  double d = si_->distance(m->state_, xstate);
207  si_->getStateSpace()->interpolate(m->state_, xstate, step / d, xstate);
208 
209  return xstate;
210 }
211 
213 {
214  checkValidity();
215  base::Goal *goal = pdef_->getGoal().get();
216  base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion*>(goal);
217 
218  while (const base::State *st = pis_.nextStart())
219  {
220  Motion *motion = new Motion(si_);
221  si_->copyState(motion->state_, st);
222  nn_->add(motion);
223  motion->accCost_ = opt_->identityCost();
224  findClosestWitness(motion);
225  }
226 
227  if (nn_->size() == 0)
228  {
229  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
231  }
232 
233  if (!sampler_)
234  sampler_ = si_->allocStateSampler();
235 
236  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), nn_->size());
237 
238  Motion *solution = nullptr;
239  Motion *approxsol = nullptr;
240  double approxdif = std::numeric_limits<double>::infinity();
241  bool sufficientlyShort = false;
242  Motion *rmotion = new Motion(si_);
243  base::State *rstate = rmotion->state_;
244  base::State *xstate = si_->allocState();
245 
246  unsigned iterations = 0;
247 
248  while (ptc == false)
249  {
250  /* sample random state (with goal biasing) */
251  bool attemptToReachGoal = (goal_s && rng_.uniform01() < goalBias_ && goal_s->canSample());
252  if (attemptToReachGoal)
253  goal_s->sampleGoal(rstate);
254  else
255  sampler_->sampleUniform(rstate);
256 
257  /* find closest state in the tree */
258  Motion *nmotion = selectNode(rmotion);
259 
260  base::State *dstate = rstate;
261  double d = si_->distance(nmotion->state_, rstate);
262 
263  attemptToReachGoal = rng_.uniform01() < .5;
264  if (attemptToReachGoal)
265  {
266  if (d > maxDistance_)
267  {
268  si_->getStateSpace()->interpolate(nmotion->state_, rstate, maxDistance_ / d, xstate);
269  dstate = xstate;
270  }
271  }
272  else
273  {
274  dstate = monteCarloProp(nmotion);
275  }
276 
277 
278  si_->copyState(rstate, dstate);
279 
280  if (si_->checkMotion(nmotion->state_, rstate))
281  {
282  base::Cost incCost = opt_->motionCost(nmotion->state_, rstate);
283  base::Cost cost = opt_->combineCosts(nmotion->accCost_, incCost);
284  Witness* closestWitness = findClosestWitness(rmotion);
285 
286  if (closestWitness->rep_ == rmotion || opt_->isCostBetterThan(cost, closestWitness->rep_->accCost_))
287  {
288  Motion* oldRep = closestWitness->rep_;
289  /* create a motion */
290  Motion *motion = new Motion(si_);
291  motion->accCost_ = cost;
292  si_->copyState(motion->state_, rstate);
293 
294  if (!attemptToReachGoal)
295  si_->freeState(dstate);
296  motion->parent_ = nmotion;
297  nmotion->numChildren_++;
298  closestWitness->linkRep(motion);
299 
300  nn_->add(motion);
301  double dist = 0.0;
302  bool solv = goal->isSatisfied(motion->state_, &dist);
303  if (solv && opt_->isCostBetterThan(motion->accCost_,prevSolutionCost_))
304  {
305  approxdif = dist;
306  solution = motion;
307 
308  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
309  if (prevSolution_[i])
310  si_->freeState(prevSolution_[i]);
311  prevSolution_.clear();
312  Motion* solTrav = solution;
313  while (solTrav!=nullptr)
314  {
315  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
316  solTrav = solTrav->parent_;
317  }
318  prevSolutionCost_ = solution->accCost_;
319 
320  OMPL_INFORM("Found solution with cost %.2f",solution->accCost_.value());
321  sufficientlyShort = opt_->isSatisfied(solution->accCost_);
322  if (sufficientlyShort)
323  {
324  break;
325  }
326  }
327  if (solution==nullptr && dist < approxdif)
328  {
329  approxdif = dist;
330  approxsol = motion;
331 
332  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
333  {
334  if (prevSolution_[i])
335  si_->freeState(prevSolution_[i]);
336  }
337  prevSolution_.clear();
338  Motion *solTrav = approxsol;
339  while (solTrav!=nullptr)
340  {
341  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
342  solTrav = solTrav->parent_;
343  }
344  }
345 
346  if(oldRep != rmotion)
347  {
348  oldRep->inactive_ = true;
349  nn_->remove(oldRep);
350  while (oldRep->inactive_ && oldRep->numChildren_==0)
351  {
352  if (oldRep->state_)
353  si_->freeState(oldRep->state_);
354  oldRep->state_=nullptr;
355  oldRep->parent_->numChildren_--;
356  Motion* oldRepParent = oldRep->parent_;
357  delete oldRep;
358  oldRep = oldRepParent;
359  }
360  }
361 
362  }
363  }
364  iterations++;
365  }
366 
367  bool solved = false;
368  bool approximate = false;
369  if (solution == nullptr)
370  {
371  solution = approxsol;
372  approximate = true;
373  }
374 
375  if (solution != nullptr)
376  {
377  /* set the solution path */
378  PathGeometric *path = new PathGeometric(si_);
379  for (int i = prevSolution_.size() - 1 ; i >= 0 ; --i)
380  path->append(prevSolution_[i]);
381  solved = true;
382  pdef_->addSolutionPath(base::PathPtr(path), approximate, approxdif, getName());
383  }
384 
385  si_->freeState(xstate);
386  if (rmotion->state_)
387  si_->freeState(rmotion->state_);
388  rmotion->state_=nullptr;
389  delete rmotion;
390 
391  OMPL_INFORM("%s: Created %u states in %u iterations", getName().c_str(), nn_->size(),iterations);
392 
393  return base::PlannerStatus(solved, approximate);
394 }
395 
397 {
398  Planner::getPlannerData(data);
399 
400  std::vector<Motion*> motions;
401  std::vector<Motion*> allMotions;
402  if (nn_)
403  nn_->list(motions);
404 
405  for (unsigned i=0; i<motions.size(); i++)
406  if(motions[i]->numChildren_ == 0)
407  allMotions.push_back(motions[i]);
408  for(unsigned i=0;i <allMotions.size(); i++)
409  if(allMotions[i]->getParent() != nullptr)
410  allMotions.push_back(allMotions[i]->getParent());
411 
412  if (prevSolution_.size()!=0)
413  data.addGoalVertex(base::PlannerDataVertex(prevSolution_[0]));
414 
415  for (unsigned int i = 0 ; i < allMotions.size() ; ++i)
416  {
417  if (allMotions[i]->getParent() == nullptr)
418  data.addStartVertex(base::PlannerDataVertex(allMotions[i]->getState()));
419  else
420  data.addEdge(base::PlannerDataVertex(allMotions[i]->getParent()->getState()),
421  base::PlannerDataVertex(allMotions[i]->getState()));
422  }
423 }
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:212
Motion * rep_
The node in the tree that is within the pruning radius.
Definition: SST.h:240
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: SST.cpp:109
Motion * parent_
The parent motion in the exploration tree.
Definition: SST.h:203
SST(const base::SpaceInformationPtr &si)
Constructor.
Definition: SST.cpp:45
double getGoalBias() const
Get the goal bias the planner is using.
Definition: SST.h:93
void setSelectionRadius(double selectionRadius)
Set the radius for selecting nodes relative to random sample.
Definition: SST.h:123
bool inactive_
If inactive, this node is not considered for selection.
Definition: SST.h:209
Motion * selectNode(Motion *sample)
Finds the best node in the tree withing the selection radius around a random sample.
Definition: SST.cpp:142
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...
unsigned numChildren_
Number of children.
Definition: SST.h:206
double goalBias_
The fraction of time the goal is picked as the state to expand towards (if such a state is available)...
Definition: SST.h:272
void setGoalBias(double goalBias)
Definition: SST.h:87
double getPruningRadius() const
Get the pruning radius the planner is using.
Definition: SST.h:151
void setPruningRadius(double pruningRadius)
Set the radius for pruning nodes.
Definition: SST.h:145
void append(const base::State *state)
Append state to the end of this path. The memory for state is copied.
double getSelectionRadius() const
Get the selection radius the planner is using.
Definition: SST.h:129
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.
std::vector< base::State * > prevSolution_
The best solution we found so far.
Definition: SST.h:287
double getRange() const
Get the range the planner is using.
Definition: SST.h:110
Base class for a vertex in the PlannerData structure. All derived classes must implement the clone an...
Definition: PlannerData.h:59
Representation of a motion.
Definition: SST.h:172
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
Abstract definition of a goal region that can be sampled.
base::State * monteCarloProp(Motion *m)
Randomly propagate a new edge.
Definition: SST.cpp:196
virtual void clear()
Clear datastructures. Call this function if the input data to the planner has changed and you do not ...
Definition: SST.cpp:97
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
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: SST.cpp:396
double pruningRadius_
The radius for determining the size of the pruning region.
Definition: SST.h:281
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)
Continue solving for some amount of time. Return true if solution was found.
Definition: SST.cpp:212
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.
A shared pointer wrapper for ompl::base::SpaceInformation.
An optimization objective which corresponds to optimizing path length.
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
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: SST.cpp:67
virtual bool isSatisfied(const State *st) const =0
Return true if the state satisfies the goal constraints.
#define OMPL_WARN(fmt,...)
Log a formatted warning string.
Definition: Console.h:66
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: SST.h:104
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:410
double selectionRadius_
The radius for determining the node selected for extension.
Definition: SST.h:278
Definition of a geometric path.
Definition: PathGeometric.h:60
base::State * state_
The state contained by the motion.
Definition: SST.h:200
Witness * findClosestWitness(Motion *node)
Find the closest witness node to a newly generated potential node.
Definition: SST.cpp:171
Definition of a cost value. Can represent the cost of a motion or the cost of a state.
Definition: Cost.h:47
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: SST.h:275
A shared pointer wrapper for ompl::base::Path.
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68
double distanceFunction(const Motion *a, const Motion *b) const
Compute distance between motions (actually distance between contained states)
Definition: SST.h:257