EST.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2015, Rice University
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 Rice 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 /* Author: Ryan Luna */
36 
37 #include "ompl/geometric/planners/est/EST.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <limits>
41 #include <cassert>
42 
43 ompl::geometric::EST::EST(const base::SpaceInformationPtr &si) : base::Planner(si, "EST")
44 {
46  specs_.directed = true;
47 
48  Planner::declareParam<double>("range", this, &EST::setRange, &EST::getRange, "0.:1.:10000.");
49  Planner::declareParam<double>("goal_bias", this, &EST::setGoalBias, &EST::getGoalBias, "0.:.05:1.");
50 }
51 
52 ompl::geometric::EST::~EST()
53 {
54  freeMemory();
55 }
56 
58 {
59  Planner::setup();
60  tools::SelfConfig sc(si_, getName());
61  sc.configurePlannerRange(maxDistance_);
62 
63  // Make the neighborhood radius smaller than sampling range to keep probabilities relatively high for rejection
64  // sampling
65  nbrhoodRadius_ = maxDistance_ / 3.0;
66 
67  if (!nn_)
68  nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion *>(this));
69  nn_->setDistanceFunction([this](const Motion *a, const Motion *b)
70  {
71  return distanceFunction(a, b);
72  });
73 }
74 
76 {
77  Planner::clear();
78  sampler_.reset();
79  freeMemory();
80  if (nn_)
81  nn_->clear();
82 
83  motions_.clear();
84  pdf_.clear();
85  lastGoalMotion_ = nullptr;
86 }
87 
89 {
90  for (auto &motion : motions_)
91  {
92  if (motion->state != nullptr)
93  si_->freeState(motion->state);
94  delete motion;
95  }
96 }
97 
99 {
100  checkValidity();
101  base::Goal *goal = pdef_->getGoal().get();
102  auto *goal_s = dynamic_cast<base::GoalSampleableRegion *>(goal);
103 
104  if (goal_s == nullptr)
105  {
106  OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
108  }
109 
110  if (!goal_s->couldSample())
111  {
112  OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str());
114  }
115 
116  std::vector<Motion *> neighbors;
117 
118  while (const base::State *st = pis_.nextStart())
119  {
120  auto *motion = new Motion(si_);
121  si_->copyState(motion->state, st);
122 
123  nn_->nearestR(motion, nbrhoodRadius_, neighbors);
124  addMotion(motion, neighbors);
125  }
126 
127  if (motions_.empty())
128  {
129  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
131  }
132 
133  if (!sampler_)
134  sampler_ = si_->allocValidStateSampler();
135 
136  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), motions_.size());
137 
138  Motion *solution = nullptr;
139  Motion *approxsol = nullptr;
140  double approxdif = std::numeric_limits<double>::infinity();
141  base::State *xstate = si_->allocState();
142  auto *xmotion = new Motion();
143 
144  while (!ptc)
145  {
146  // Select a state to expand from
147  Motion *existing = pdf_.sample(rng_.uniform01());
148  assert(existing);
149 
150  // Sample random state in the neighborhood (with goal biasing)
151  if (rng_.uniform01() < goalBias_ && goal_s->canSample())
152  {
153  goal_s->sampleGoal(xstate);
154 
155  // Compute neighborhood of candidate motion
156  xmotion->state = xstate;
157  nn_->nearestR(xmotion, nbrhoodRadius_, neighbors);
158  }
159  else
160  {
161  // Sample a state in the neighborhood
162  if (!sampler_->sampleNear(xstate, existing->state, maxDistance_))
163  continue;
164 
165  // Compute neighborhood of candidate state
166  xmotion->state = xstate;
167  nn_->nearestR(xmotion, nbrhoodRadius_, neighbors);
168 
169  // reject state with probability proportional to neighborhood density
170  if (!neighbors.empty() )
171  {
172  double p = 1.0 - (1.0 / neighbors.size());
173  if (rng_.uniform01() < p)
174  continue;
175  }
176  }
177 
178  // Is motion good?
179  if (si_->checkMotion(existing->state, xstate))
180  {
181  // create a motion
182  auto *motion = new Motion(si_);
183  si_->copyState(motion->state, xstate);
184  motion->parent = existing;
185 
186  // add it to everything
187  addMotion(motion, neighbors);
188 
189  // done?
190  double dist = 0.0;
191  bool solved = goal->isSatisfied(motion->state, &dist);
192  if (solved)
193  {
194  approxdif = dist;
195  solution = motion;
196  break;
197  }
198  if (dist < approxdif)
199  {
200  approxdif = dist;
201  approxsol = motion;
202  }
203  }
204  }
205 
206  bool solved = false;
207  bool approximate = false;
208  if (solution == nullptr)
209  {
210  solution = approxsol;
211  approximate = true;
212  }
213 
214  if (solution != nullptr)
215  {
216  lastGoalMotion_ = solution;
217 
218  // construct the solution path
219  std::vector<Motion *> mpath;
220  while (solution != nullptr)
221  {
222  mpath.push_back(solution);
223  solution = solution->parent;
224  }
225 
226  // set the solution path
227  auto path(std::make_shared<PathGeometric>(si_));
228  for (int i = mpath.size() - 1; i >= 0; --i)
229  path->append(mpath[i]->state);
230  pdef_->addSolutionPath(path, approximate, approxdif, getName());
231  solved = true;
232  }
233 
234  si_->freeState(xstate);
235  delete xmotion;
236 
237  OMPL_INFORM("%s: Created %u states", getName().c_str(), motions_.size());
238 
239  return {solved, approximate};
240 }
241 
242 void ompl::geometric::EST::addMotion(Motion *motion, const std::vector<Motion *> &neighbors)
243 {
244  // Updating neighborhood size counts
245  for (auto neighbor : neighbors)
246  {
247  PDF<Motion *>::Element *elem = neighbor->element;
248  double w = pdf_.getWeight(elem);
249  pdf_.update(elem, w / (w + 1.));
250  }
251 
252  // now add new motion to the data structures
253  motion->element = pdf_.add(motion, 1. / (neighbors.size() + 1.)); // +1 for self
254  motions_.push_back(motion);
255  nn_->add(motion);
256 }
257 
259 {
260  Planner::getPlannerData(data);
261 
262  if (lastGoalMotion_ != nullptr)
263  data.addGoalVertex(base::PlannerDataVertex(lastGoalMotion_->state));
264 
265  for (auto motion : motions_)
266  {
267  if (motion->parent == nullptr)
268  data.addStartVertex(base::PlannerDataVertex(motion->state));
269  else
270  data.addEdge(base::PlannerDataVertex(motion->parent->state), base::PlannerDataVertex(motion->state));
271  }
272 }
@ UNRECOGNIZED_GOAL_TYPE
The goal is of a type that a planner does not recognize.
void configurePlannerRange(double &range)
Compute what a good length for motion segments is.
Definition: SelfConfig.cpp:225
double getRange() const
Get the range the planner is using.
Definition: EST.h:205
Definition of an abstract state.
Definition: State.h:113
This class contains methods that automatically configure various parameters for motion planning....
Definition: SelfConfig.h:122
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: EST.cpp:258
void setGoalBias(double goalBias)
In the process of randomly selecting states in the state space to attempt to go towards,...
Definition: EST.h:180
PDF< Motion * >::Element * element
A pointer to the corresponding element in the probability distribution function.
Definition: EST.h:235
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68
double getGoalBias() const
Get the goal bias the planner is using.
Definition: EST.h:186
EST(const base::SpaceInformationPtr &si)
Constructor.
Definition: EST.cpp:43
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique,...
Definition: PlannerData.h:238
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:486
@ INVALID_GOAL
Invalid goal state.
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: EST.h:196
bool directed
Flag indicating whether the planner is able to account for the fact that the validity of a motion fro...
Definition: Planner.h:269
base::State * state
The state contained by the motion.
Definition: EST.h:229
A class to store the exit status of Planner::solve()
void addMotion(Motion *motion, const std::vector< Motion * > &neighbors)
Add a motion to the exploration tree.
Definition: EST.cpp:242
Abstract definition of goals.
Definition: Goal.h:126
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...
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: EST.cpp:98
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:259
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...
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 a goal region that can be sampled.
The definition of a motion.
Definition: EST.h:216
void clear() override
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: EST.cpp:75
A class that will hold data contained in the PDF.
Definition: PDF.h:116
@ INVALID_START
Invalid start state or no start state specified.
Base class for a vertex in the PlannerData structure. All derived classes must implement the clone an...
Definition: PlannerData.h:122
Motion * parent
The parent motion in the exploration tree.
Definition: EST.h:232
void setup() override
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: EST.cpp:57
void freeMemory()
Free the memory allocated by this planner.
Definition: EST.cpp:88