BiEST.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/BiEST.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::BiEST::BiEST(const base::SpaceInformationPtr &si) : base::Planner(si, "BiEST")
44 {
46  specs_.directed = true;
47  maxDistance_ = 0.0;
48  connectionPoint_ = std::make_pair<ompl::base::State*, ompl::base::State*>(NULL, NULL);
49 
50  Planner::declareParam<double>("range", this, &BiEST::setRange, &BiEST::getRange, "0.:1.:10000.");
51 }
52 
53 ompl::geometric::BiEST::~BiEST()
54 {
55  freeMemory();
56 }
57 
59 {
60  Planner::setup();
61 
62  if (maxDistance_ < 1e-3)
63  {
64  tools::SelfConfig sc(si_, getName());
65  sc.configurePlannerRange(maxDistance_);
66 
67  // Make the neighborhood radius smaller than sampling range to
68  // keep probabilities relatively high for rejection sampling
69  nbrhoodRadius_ = maxDistance_ / 3.0;
70  }
71 
72  if (!nnStart_)
73  nnStart_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
74  if (!nnGoal_)
75  nnGoal_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(this));
76  nnStart_->setDistanceFunction(std::bind(&BiEST::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));
77  nnGoal_->setDistanceFunction(std::bind(&BiEST::distanceFunction, this, std::placeholders::_1, std::placeholders::_2));
78 }
79 
81 {
82  Planner::clear();
83  sampler_.reset();
84  freeMemory();
85  if (nnStart_)
86  nnStart_->clear();
87  if (nnGoal_)
88  nnGoal_->clear();
89 
90  startMotions_.clear();
91  startPdf_.clear();
92 
93  goalMotions_.clear();
94  goalPdf_.clear();
95 
96  connectionPoint_ = std::make_pair<base::State*, base::State*>(NULL, NULL);
97 }
98 
100 {
101  for(size_t i = 0; i < startMotions_.size(); ++i)
102  {
103  if (startMotions_[i]->state)
104  si_->freeState(startMotions_[i]->state);
105  delete startMotions_[i];
106  }
107 
108  for(size_t i = 0; i < goalMotions_.size(); ++i)
109  {
110  if (goalMotions_[i]->state)
111  si_->freeState(goalMotions_[i]->state);
112  delete goalMotions_[i];
113  }
114 }
115 
117 {
118  checkValidity();
119  base::GoalSampleableRegion *goal = dynamic_cast<base::GoalSampleableRegion*>(pdef_->getGoal().get());
120 
121  if (!goal)
122  {
123  OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
125  }
126 
127  std::vector<Motion*> neighbors;
128 
129  while (const base::State *st = pis_.nextStart())
130  {
131  Motion *motion = new Motion(si_);
132  si_->copyState(motion->state, st);
133  motion->root = motion->state;
134 
135  nnStart_->nearestR(motion, nbrhoodRadius_, neighbors);
136  addMotion(motion, startMotions_, startPdf_, nnStart_, neighbors);
137  }
138 
139  if (startMotions_.size() == 0)
140  {
141  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
143  }
144 
145  if (!goal->couldSample())
146  {
147  OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str());
149  }
150 
151  if (!sampler_)
152  sampler_ = si_->allocValidStateSampler();
153 
154  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(), startMotions_.size() + goalMotions_.size());
155 
156  base::State *xstate = si_->allocState();
157  Motion* xmotion = new Motion();
158 
159  bool startTree = true;
160  bool solved = false;
161 
162  while (ptc == false && !solved)
163  {
164  // Make sure goal tree has at least one state.
165  if (goalMotions_.size() == 0 || pis_.getSampledGoalsCount() < goalMotions_.size() / 2)
166  {
167  const base::State *st = goalMotions_.size() == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal();
168  if (st)
169  {
170  Motion *motion = new Motion(si_);
171  si_->copyState(motion->state, st);
172  motion->root = motion->state;
173 
174  nnGoal_->nearestR(motion, nbrhoodRadius_, neighbors);
175  addMotion(motion, goalMotions_, goalPdf_, nnGoal_, neighbors);
176  }
177 
178  if (goalMotions_.size() == 0)
179  {
180  OMPL_ERROR("%s: Unable to sample any valid states for goal tree", getName().c_str());
181  break;
182  }
183  }
184 
185  // Pointers to the tree structure we are expanding
186  std::vector<Motion*>& motions = startTree ? startMotions_ : goalMotions_;
187  PDF<Motion*>& pdf = startTree ? startPdf_ : goalPdf_;
188  std::shared_ptr< NearestNeighbors<Motion*> > nn = startTree ? nnStart_ : nnGoal_;
189 
190  // Select a state to expand from
191  Motion *existing = pdf.sample(rng_.uniform01());
192  assert(existing);
193 
194  // Sample a state in the neighborhood
195  if (!sampler_->sampleNear(xstate, existing->state, maxDistance_))
196  continue;
197 
198  // Compute neighborhood of candidate state
199  xmotion->state = xstate;
200  nn->nearestR(xmotion, nbrhoodRadius_, neighbors);
201 
202  // reject state with probability proportional to neighborhood density
203  if (neighbors.size())
204  {
205  double p = 1.0 - (1.0 / neighbors.size());
206  if (rng_.uniform01() < p)
207  continue;
208  }
209 
210  // Is motion good?
211  if (si_->checkMotion(existing->state, xstate))
212  {
213  // create a motion
214  Motion *motion = new Motion(si_);
215  si_->copyState(motion->state, xstate);
216  motion->parent = existing;
217  motion->root = existing->root;
218 
219  // add it to everything
220  addMotion(motion, motions, pdf, nn, neighbors);
221 
222  // try to connect this state to the other tree
223  // Get all states in the other tree within a maxDistance_ ball (bigger than "neighborhood" ball)
224  startTree ? nnGoal_->nearestR(motion, maxDistance_, neighbors) : nnStart_->nearestR(motion, maxDistance_, neighbors);
225  for(size_t i = 0; i < neighbors.size() && !solved; ++i)
226  {
227  if (goal->isStartGoalPairValid(motion->root, neighbors[i]->root) &&
228  si_->checkMotion(motion->state, neighbors[i]->state)) // win! solution found.
229  {
230  connectionPoint_ = std::make_pair(motion->state, neighbors[i]->state);
231 
232  Motion* startMotion = startTree ? motion : neighbors[i];
233  Motion* goalMotion = startTree ? neighbors[i] : motion;
234 
235  Motion *solution = startMotion;
236  std::vector<Motion*> mpath1;
237  while (solution != NULL)
238  {
239  mpath1.push_back(solution);
240  solution = solution->parent;
241  }
242 
243  solution = goalMotion;
244  std::vector<Motion*> mpath2;
245  while (solution != NULL)
246  {
247  mpath2.push_back(solution);
248  solution = solution->parent;
249  }
250 
251  PathGeometric *path = new PathGeometric(si_);
252  path->getStates().reserve(mpath1.size() + mpath2.size());
253  for (int i = mpath1.size() - 1 ; i >= 0 ; --i)
254  path->append(mpath1[i]->state);
255  for (unsigned int i = 0 ; i < mpath2.size() ; ++i)
256  path->append(mpath2[i]->state);
257 
258  pdef_->addSolutionPath(base::PathPtr(path), false, 0.0, getName());
259  solved = true;
260  }
261  }
262  }
263 
264  // swap trees for next iteration
265  startTree = !startTree;
266  }
267 
268  si_->freeState(xstate);
269  delete xmotion;
270 
271  OMPL_INFORM("%s: Created %u states (%u start + %u goal)", getName().c_str(), startMotions_.size() + goalMotions_.size(), startMotions_.size(), goalMotions_.size());
273 }
274 
275 void ompl::geometric::BiEST::addMotion(Motion* motion, std::vector<Motion*>& motions,
276  PDF<Motion*>& pdf, std::shared_ptr< NearestNeighbors<Motion*> > nn,
277  const std::vector<Motion*>& neighbors)
278 {
279  // Updating neighborhood size counts
280  for(size_t i = 0; i < neighbors.size(); ++i)
281  {
282  PDF<Motion*>::Element *elem = neighbors[i]->element;
283  double w = pdf.getWeight(elem);
284  pdf.update(elem, w / (w + 1.));
285  }
286 
287  motion->element = pdf.add(motion, 1. / (neighbors.size() + 1.)); // +1 for self
288  motions.push_back(motion);
289  nn->add(motion);
290 }
291 
293 {
294  Planner::getPlannerData(data);
295 
296  for (unsigned int i = 0 ; i < startMotions_.size() ; ++i)
297  {
298  if (startMotions_[i]->parent == NULL)
299  data.addStartVertex(base::PlannerDataVertex(startMotions_[i]->state, 1));
300  else
301  data.addEdge(base::PlannerDataVertex(startMotions_[i]->parent->state, 1),
302  base::PlannerDataVertex(startMotions_[i]->state, 1));
303  }
304 
305  for (unsigned int i = 0 ; i < goalMotions_.size() ; ++i)
306  {
307  if (goalMotions_[i]->parent == NULL)
308  data.addGoalVertex(base::PlannerDataVertex(goalMotions_[i]->state, 2));
309  else
310  // The edges in the goal tree are reversed to be consistent with start tree
311  data.addEdge(base::PlannerDataVertex(goalMotions_[i]->state, 2),
312  base::PlannerDataVertex(goalMotions_[i]->parent->state, 2));
313  }
314 
315  // Add the edge connecting the two trees
316  data.addEdge(data.vertexIndex(connectionPoint_.first), data.vertexIndex(connectionPoint_.second));
317 }
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:163
The planner failed to find a solution.
Definition: PlannerStatus.h:62
GoalType recognizedGoal
The type of goal specification the planner can use.
Definition: Planner.h:206
Motion * parent
The parent motion in the exploration tree.
Definition: BiEST.h:127
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...
double getWeight(const Element *elem) const
Returns the current weight of the given Element.
Definition: PDF.h:171
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: BiEST.h:166
const base::State * root
The root node of the tree this motion is in.
Definition: BiEST.h:133
void append(const base::State *state)
Append state to the end of this path. The memory for state is copied.
void freeMemory()
Free the memory allocated by this planner.
Definition: BiEST.cpp:99
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
A container that supports probabilistic sampling over weighted data.
Definition: PDF.h:48
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 distanceFunction(const Motion *a, const Motion *b) const
Compute distance between motions (actually distance between contained states)
Definition: BiEST.h:137
Abstract definition of a goal region that can be sampled.
The goal is of a type that a planner does not recognize.
Definition: PlannerStatus.h:60
std::vector< base::State * > & getStates()
Get the states that make up the path (as a reference, so it can be modified, hence the function is no...
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
The definition of a motion.
Definition: BiEST.h:106
The planner found an exact solution.
Definition: PlannerStatus.h:66
base::State * state
The state contained by the motion.
Definition: BiEST.h:124
unsigned int vertexIndex(const PlannerDataVertex &v) const
Return the index for the vertex associated with the given data. INVALID_INDEX is returned if this ver...
BiEST(const base::SpaceInformationPtr &si)
Constructor.
Definition: BiEST.cpp:43
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...
virtual bool isStartGoalPairValid(const State *, const State *) const
Since there can be multiple starting states (and multiple goal states) it is possible certain pairs a...
Definition: Goal.h:138
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:50
double getRange() const
Get the range the planner is using.
Definition: BiEST.h:94
A class that will hold data contained in the PDF.
Definition: PDF.h:53
Abstract representation of a container that can perform nearest neighbors queries.
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:410
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: BiEST.cpp:292
void addMotion(Motion *motion, std::vector< Motion * > &motions, PDF< Motion * > &pdf, std::shared_ptr< NearestNeighbors< Motion * > > nn, const std::vector< Motion * > &neighbors)
Add a motion to the exploration tree.
Definition: BiEST.cpp:275
void update(Element *elem, const double w)
Updates the data in the given Element with a new weight value.
Definition: PDF.h:155
Element * add(const _T &d, const double w)
Adds a piece of data with a given weight to the PDF. Returns a corresponding Element, which can be used to subsequently update or remove the data from the PDF.
Definition: PDF.h:97
virtual bool couldSample() const
Return true if samples could be generated by this sampler at some point in the future. By default this is equivalent to canSample(), but for GoalLazySamples, this call also reflects the fact that a sampling thread is active and although no samples are produced yet, some may become available at some point in the future.
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: BiEST.cpp:80
void configurePlannerRange(double &range)
Compute what a good length for motion segments is.
Definition: SelfConfig.cpp:230
This class contains methods that automatically configure various parameters for motion planning...
Definition: SelfConfig.h:60
virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc)
Function that can solve the motion planning problem. This function can be called multiple times on th...
Definition: BiEST.cpp:116
Definition of a geometric path.
Definition: PathGeometric.h:60
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: BiEST.h:84
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: BiEST.cpp:58
std::pair< base::State *, base::State * > connectionPoint_
The pair of states in each tree connected during planning. Used for PlannerData computation.
Definition: BiEST.h:175
_T & sample(double r) const
Returns a piece of data from the PDF according to the input sampling value, which must be between 0 a...
Definition: PDF.h:132
PDF< Motion * >::Element * element
A pointer to the corresponding element in the probability distribution function.
Definition: BiEST.h:130
A shared pointer wrapper for ompl::base::Path.
This bit is set if casting to sampleable goal regions (ompl::base::GoalSampleableRegion) is possible...
Definition: GoalTypes.h:55
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68