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/control/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/base/objectives/MechanicalWorkOptimizationObjective.h"
43 #include "ompl/tools/config/SelfConfig.h"
44 #include <limits>
45 
46 ompl::control::SST::SST(const SpaceInformationPtr &si) : base::Planner(si, "SST")
47 {
49  siC_ = si.get();
50  prevSolution_.clear();
51  prevSolutionControls_.clear();
52  prevSolutionSteps_.clear();
53 
54  goalBias_ = 0.05;
55  selectionRadius_ = 0.2;
56  pruningRadius_ = 0.1;
57 
58  Planner::declareParam<double>("goal_bias", this, &SST::setGoalBias, &SST::getGoalBias, "0.:.05:1.");
59  Planner::declareParam<double>("selection_radius", this, &SST::setSelectionRadius, &SST::getSelectionRadius, "0.:.1:100");
60  Planner::declareParam<double>("pruning_radius", this, &SST::setPruningRadius, &SST::getPruningRadius, "0.:.1:100");
61 }
62 
63 ompl::control::SST::~SST()
64 {
65  freeMemory();
66 }
67 
69 {
71  if (!nn_)
72  nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
73  nn_->setDistanceFunction(std::bind(&SST::distanceFunction, this,
74  std::placeholders::_1, std::placeholders::_2));
75  if (!witnesses_)
76  witnesses_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
77  witnesses_->setDistanceFunction(std::bind(&SST::distanceFunction, this,
78  std::placeholders::_1, std::placeholders::_2));
79 
80  if (pdef_)
81  {
82  if (pdef_->hasOptimizationObjective())
83  {
84  opt_ = pdef_->getOptimizationObjective();
85  if (dynamic_cast<base::MaximizeMinClearanceObjective*>(opt_.get()) || dynamic_cast<base::MinimaxObjective*>(opt_.get()))
86  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());
87  }
88  else
89  {
90  OMPL_WARN("%s: No optimization object set. Using path length", getName().c_str());
92  pdef_->setOptimizationObjective(opt_);
93  }
94  }
95 
96  prevSolutionCost_ = opt_->infiniteCost();
97 
98 }
99 
101 {
102  Planner::clear();
103  sampler_.reset();
104  controlSampler_.reset();
105  freeMemory();
106  if (nn_)
107  nn_->clear();
108  if (witnesses_)
109  witnesses_->clear();
110  prevSolutionCost_ = opt_->infiniteCost();
111 }
112 
114 {
115  if (nn_)
116  {
117  std::vector<Motion*> motions;
118  nn_->list(motions);
119  for (unsigned int i = 0 ; i < motions.size() ; ++i)
120  {
121  if (motions[i]->state_)
122  si_->freeState(motions[i]->state_);
123  if (motions[i]->control_)
124  siC_->freeControl(motions[i]->control_);
125  delete motions[i];
126  }
127  }
128  if (witnesses_)
129  {
130  std::vector<Motion*> witnesses;
131  witnesses_->list(witnesses);
132  for (unsigned int i = 0 ; i < witnesses.size() ; ++i)
133  {
134  delete witnesses[i];
135  }
136  }
137  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
138  {
139  if (prevSolution_[i])
140  si_->freeState(prevSolution_[i]);
141  }
142  prevSolution_.clear();
143  for (unsigned int i = 0 ; i < prevSolutionControls_.size() ; ++i)
144  {
145  if (prevSolutionControls_[i])
146  siC_->freeControl(prevSolutionControls_[i]);
147  }
148  prevSolutionControls_.clear();
149  prevSolutionSteps_.clear();
150 }
151 
153 {
154  std::vector<Motion*> ret;
155  Motion *selected = nullptr;
156  base::Cost bestCost = opt_->infiniteCost();
157  nn_->nearestR(sample, selectionRadius_, ret);
158  for (unsigned int i = 0; i < ret.size(); i++)
159  {
160  if (!ret[i]->inactive_ && opt_->isCostBetterThan(ret[i]->accCost_, bestCost))
161  {
162  bestCost = ret[i]->accCost_;
163  selected = ret[i];
164  }
165  }
166  if (selected == nullptr)
167  {
168  int k = 1;
169  while (selected == nullptr)
170  {
171  nn_->nearestK(sample, k, ret);
172  for (unsigned int i=0; i < ret.size() && selected == nullptr; i++)
173  if (!ret[i]->inactive_)
174  selected = ret[i];
175  k += 5;
176  }
177  }
178  return selected;
179 }
180 
182 {
183  if(witnesses_->size() > 0)
184  {
185  Witness* closest = static_cast<Witness*>(witnesses_->nearest(node));
186  if (distanceFunction(closest,node) > pruningRadius_)
187  {
188  closest = new Witness(siC_);
189  closest->linkRep(node);
190  si_->copyState(closest->state_, node->state_);
191  witnesses_->add(closest);
192  }
193  return closest;
194  }
195  else
196  {
197  Witness* closest = new Witness(siC_);
198  closest->linkRep(node);
199  si_->copyState(closest->state_, node->state_);
200  witnesses_->add(closest);
201  return closest;
202  }
203 }
204 
206 {
207  checkValidity();
208  base::Goal *goal = pdef_->getGoal().get();
209  base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion*>(goal);
210 
211  while (const base::State *st = pis_.nextStart())
212  {
213  Motion *motion = new Motion(siC_);
214  si_->copyState(motion->state_, st);
215  siC_->nullControl(motion->control_);
216  nn_->add(motion);
217  motion->accCost_ = opt_->identityCost();
218  findClosestWitness(motion);
219  }
220 
221  if (nn_->size() == 0)
222  {
223  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
225  }
226 
227  if (!sampler_)
228  sampler_ = si_->allocStateSampler();
229  if (!controlSampler_)
231 
232  OMPL_INFORM("%s: Starting planning with %u states already in datastructure\n", getName().c_str(), nn_->size());
233 
234  Motion *solution = nullptr;
235  Motion *approxsol = nullptr;
236  double approxdif = std::numeric_limits<double>::infinity();
237  bool sufficientlyShort = false;
238 
239  Motion *rmotion = new Motion(siC_);
240  base::State *rstate = rmotion->state_;
241  Control *rctrl = rmotion->control_;
242  base::State *xstate = si_->allocState();
243 
244  unsigned iterations = 0;
245 
246  while (ptc == false)
247  {
248 
249  /* sample random state (with goal biasing) */
250  if (goal_s && rng_.uniform01() < goalBias_ && goal_s->canSample())
251  goal_s->sampleGoal(rstate);
252  else
253  sampler_->sampleUniform(rstate);
254 
255  /* find closest state in the tree */
256  Motion *nmotion = selectNode(rmotion);
257 
258 
259 
260  /* sample a random control that attempts to go towards the random state, and also sample a control duration */
261  controlSampler_->sample(rctrl);
263  unsigned int propCd = siC_->propagateWhileValid(nmotion->state_,rctrl,cd,rstate);
264 
265 
266  if (propCd == cd)
267  {
268  base::Cost incCost = opt_->motionCost(nmotion->state_, rstate);
269  base::Cost cost = opt_->combineCosts(nmotion->accCost_, incCost);
270  Witness* closestWitness = findClosestWitness(rmotion);
271 
272 
273  if (closestWitness->rep_ == rmotion || opt_->isCostBetterThan(cost,closestWitness->rep_->accCost_))
274  {
275  Motion* oldRep = closestWitness->rep_;
276  /* create a motion */
277  Motion *motion = new Motion(siC_);
278  motion->accCost_ = cost;
279  si_->copyState(motion->state_, rmotion->state_);
280  siC_->copyControl(motion->control_, rctrl);
281  motion->steps_ = cd;
282  motion->parent_ = nmotion;
283  nmotion->numChildren_++;
284  closestWitness->linkRep(motion);
285 
286  nn_->add(motion);
287  double dist = 0.0;
288  bool solv = goal->isSatisfied(motion->state_, &dist);
289  if (solv && opt_->isCostBetterThan(motion->accCost_,prevSolutionCost_))
290  {
291  approxdif = dist;
292  solution = motion;
293 
294  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
295  if (prevSolution_[i])
296  si_->freeState(prevSolution_[i]);
297  prevSolution_.clear();
298  for (unsigned int i = 0 ; i < prevSolutionControls_.size() ; ++i)
299  if (prevSolutionControls_[i])
300  siC_->freeControl(prevSolutionControls_[i]);
301  prevSolutionControls_.clear();
302  prevSolutionSteps_.clear();
303 
304 
305  Motion* solTrav = solution;
306  while(solTrav->parent_!=nullptr)
307  {
308  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
309  prevSolutionControls_.push_back(siC_->cloneControl(solTrav->control_) );
310  prevSolutionSteps_.push_back(solTrav->steps_ );
311  solTrav = solTrav->parent_;
312  }
313  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
314  prevSolutionCost_ = solution->accCost_;
315 
316 
317 
318 
319  OMPL_INFORM("Found solution with cost %.2f",solution->accCost_.value());
320  sufficientlyShort = opt_->isSatisfied(solution->accCost_);
321  if (sufficientlyShort)
322  break;
323  }
324  if (solution==nullptr && dist < approxdif)
325  {
326  approxdif = dist;
327  approxsol = motion;
328 
329 
330 
331  for (unsigned int i = 0 ; i < prevSolution_.size() ; ++i)
332  if (prevSolution_[i])
333  si_->freeState(prevSolution_[i]);
334  prevSolution_.clear();
335  for (unsigned int i = 0 ; i < prevSolutionControls_.size() ; ++i)
336  if (prevSolutionControls_[i])
337  siC_->freeControl(prevSolutionControls_[i]);
338  prevSolutionControls_.clear();
339  prevSolutionSteps_.clear();
340 
341  Motion *solTrav = approxsol;
342  while (solTrav->parent_!=nullptr)
343  {
344  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
345  prevSolutionControls_.push_back(siC_->cloneControl(solTrav->control_) );
346  prevSolutionSteps_.push_back(solTrav->steps_ );
347  solTrav = solTrav->parent_;
348  }
349  prevSolution_.push_back(si_->cloneState(solTrav->state_) );
350  }
351 
352  if (oldRep != rmotion)
353  {
354  oldRep->inactive_ = true;
355  nn_->remove(oldRep);
356  while (oldRep->inactive_ && oldRep->numChildren_==0)
357  {
358  if (oldRep->state_)
359  si_->freeState(oldRep->state_);
360  if (oldRep->control_)
361  siC_->freeControl(oldRep->control_);
362 
363  oldRep->state_=nullptr;
364  oldRep->control_=nullptr;
365  oldRep->parent_->numChildren_--;
366  Motion* oldRepParent = oldRep->parent_;
367  delete oldRep;
368  oldRep = oldRepParent;
369  }
370  }
371 
372  }
373  }
374  iterations++;
375  }
376 
377  bool solved = false;
378  bool approximate = false;
379  if (solution == nullptr)
380  {
381  solution = approxsol;
382  approximate = true;
383  }
384 
385  if (solution != nullptr)
386  {
387  /* set the solution path */
388  PathControl *path = new PathControl(si_);
389  for (int i = prevSolution_.size() - 1 ; i >= 1 ; --i)
390  path->append(prevSolution_[i], prevSolutionControls_[i-1], prevSolutionSteps_[i-1] * siC_->getPropagationStepSize());
391  path->append(prevSolution_[0]);
392  solved = true;
393  pdef_->addSolutionPath(base::PathPtr(path), approximate, approxdif, getName());
394  }
395 
396  si_->freeState(xstate);
397  if (rmotion->state_)
398  si_->freeState(rmotion->state_);
399  if (rmotion->control_)
400  siC_->freeControl(rmotion->control_);
401  delete rmotion;
402 
403  OMPL_INFORM("%s: Created %u states in %u iterations", getName().c_str(), nn_->size(),iterations);
404 
405  return base::PlannerStatus(solved, approximate);
406 }
407 
409 {
410  Planner::getPlannerData(data);
411 
412  std::vector<Motion*> motions;
413  std::vector<Motion*> allMotions;
414  if (nn_)
415  nn_->list(motions);
416 
417  for(unsigned i=0;i<motions.size();i++)
418  {
419  if(motions[i]->numChildren_==0)
420  {
421  allMotions.push_back(motions[i]);
422  }
423  }
424  for(unsigned i=0;i<allMotions.size();i++)
425  {
426  if(allMotions[i]->parent_!=nullptr)
427  {
428  allMotions.push_back(allMotions[i]->parent_);
429  }
430  }
431 
432  double delta = siC_->getPropagationStepSize();
433 
434  if (prevSolution_.size()!=0)
436 
437  for (unsigned int i = 0 ; i < allMotions.size() ; ++i)
438  {
439  const Motion *m = allMotions[i];
440  if (m->parent_)
441  {
442  if (data.hasControls())
446  else
449  }
450  else
452  }
453 }
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:212
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: SST.cpp:68
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:163
unsigned int getMinControlDuration() const
Get the minimum number of steps a control is propagated for.
unsigned numChildren_
Number of children.
Definition: SST.h:195
unsigned int propagateWhileValid(const base::State *state, const Control *control, int steps, base::State *result) const
Propagate the model of the system forward, starting at a given state, with a given control...
void append(const base::State *state)
Append state to the end of the path; it is assumed state is the first state, so no control is applied...
base::StateSamplerPtr sampler_
State sampler.
Definition: SST.h:248
Definition of an abstract control.
Definition: Control.h:48
Motion * parent_
The parent motion in the exploration tree.
Definition: SST.h:192
virtual bool hasControls() const
Indicate whether any information about controls (ompl::control::Control) is stored in this instance...
base::Cost prevSolutionCost_
The best solution cost we found so far.
Definition: SST.h:281
Witness * findClosestWitness(Motion *node)
Find the closest witness node to a newly generated potential node.
Definition: SST.cpp:181
bool inactive_
If inactive, this node is not considered for selection.
Definition: SST.h:198
std::shared_ptr< NearestNeighbors< Motion * > > nn_
A nearest-neighbors datastructure containing the tree of motions.
Definition: SST.h:257
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...
std::vector< base::State * > prevSolution_
The best solution we found so far.
Definition: SST.h:276
Abstract definition of goals.
Definition: Goal.h:62
Control * control_
The control contained by the motion.
Definition: SST.h:186
const SpaceInformation * siC_
The base::SpaceInformation cast as control::SpaceInformation, for convenience.
Definition: SST.h:254
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
Representation of an edge in PlannerData for planning with controls. This structure encodes a specifi...
Definition: PlannerData.h:60
double getSelectionRadius() const
Get the selection radius the planner is using.
Definition: SST.h:112
ControlSamplerPtr controlSampler_
Control sampler.
Definition: SST.h:251
double getGoalBias() const
Get the goal bias the planner is using.
Definition: SST.h:93
SST(const SpaceInformationPtr &si)
Constructor.
Definition: SST.cpp:46
void freeControl(Control *control) const
Free the memory of a control.
Definition of a control path.
Definition: PathControl.h:60
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:408
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:401
virtual void sampleGoal(State *st) const =0
Sample a state in the goal region.
double pruningRadius_
The radius for determining the size of the pruning region.
Definition: SST.h:270
virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc)
Continue solving for some amount of time. Return true if solution was found.
Definition: SST.cpp:205
double uniform01()
Generate a random real between 0 and 1.
Definition: RandomNumbers.h:69
base::OptimizationObjectivePtr opt_
The optimization objective.
Definition: SST.h:284
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
double getPropagationStepSize() const
Propagation is performed at integer multiples of a specified step size. This function returns the val...
Motion * rep_
The node in the tree that is within the pruning radius.
Definition: SST.h:229
Abstract definition of a goal region that can be sampled.
double distanceFunction(const Motion *a, const Motion *b) const
Compute distance between motions (actually distance between contained states)
Definition: SST.h:242
void setPruningRadius(double pruningRadius)
Set the radius for pruning nodes.
Definition: SST.h:128
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
Motion * selectNode(Motion *sample)
Finds the best node in the tree withing the selection radius around a random sample.
Definition: SST.cpp:152
double selectionRadius_
The radius for determining the node selected for extension.
Definition: SST.h:267
unsigned int steps_
The number of steps_ the control is applied for.
Definition: SST.h:189
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: Planner.cpp:86
ControlSamplerPtr allocControlSampler() const
Allocate a control sampler.
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.
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 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.
#define OMPL_WARN(fmt,...)
Log a formatted warning string.
Definition: Console.h:66
PlannerInputStates pis_
Utility class to extract valid input states.
Definition: Planner.h:404
A shared pointer wrapper for ompl::control::SpaceInformation.
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
base::State * state_
The state contained by the motion.
Definition: SST.h:183
RNG rng_
The random number generator.
Definition: SST.h:273
unsigned int getMaxControlDuration() const
Get the maximum number of steps a control is propagated for.
std::shared_ptr< NearestNeighbors< Motion * > > witnesses_
A nearest-neighbors datastructure containing the tree of witness motions.
Definition: SST.h:261
void nullControl(Control *control) const
Make the control have no effect if it were to be applied to a state for any amount of time...
Control * cloneControl(const Control *source) const
Clone a control.
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:398
Representation of a motion.
Definition: SST.h:154
virtual void clear()
Clear datastructures. Call this function if the input data to the planner has changed and you do not ...
Definition: SST.cpp:100
void setGoalBias(double goalBias)
Definition: SST.h:87
double getPruningRadius() const
Get the pruning radius the planner is using.
Definition: SST.h:134
int uniformInt(int lower_bound, int upper_bound)
Generate a random integer within given bounds: [lower_bound, upper_bound].
Definition: RandomNumbers.h:82
void freeMemory()
Free the memory allocated by this planner.
Definition: SST.cpp:113
void setSelectionRadius(double selectionRadius)
Set the radius for selecting nodes relative to random sample.
Definition: SST.h:106
Definition of a cost value. Can represent the cost of a motion or the cost of a state.
Definition: Cost.h:47
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:55
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:264
A shared pointer wrapper for ompl::base::Path.
void copyControl(Control *destination, const Control *source) const
Copy a control to another.
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68