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