All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
KPIECE1.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2010, 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: Ioan Sucan */
36 
37 #include "ompl/control/planners/kpiece/KPIECE1.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include "ompl/util/Exception.h"
41 #include <limits>
42 #include <cassert>
43 
44 ompl::control::KPIECE1::KPIECE1(const SpaceInformationPtr &si) : base::Planner(si, "KPIECE1")
45 {
47 
48  siC_ = si.get();
49  nCloseSamples_ = 30;
50  goalBias_ = 0.05;
52  badScoreFactor_ = 0.45;
53  goodScoreFactor_ = 0.9;
55  lastGoalMotion_ = NULL;
56 
57  Planner::declareParam<double>("goal_bias", this, &KPIECE1::setGoalBias, &KPIECE1::getGoalBias);
58  Planner::declareParam<double>("border_fraction", this, &KPIECE1::setBorderFraction, &KPIECE1::getBorderFraction);
59  Planner::declareParam<unsigned int>("max_close_samples", this, &KPIECE1::setMaxCloseSamplesCount, &KPIECE1::getMaxCloseSamplesCount);
60  Planner::declareParam<double>("bad_score_factor", this, &KPIECE1::setBadCellScoreFactor, &KPIECE1::getBadCellScoreFactor);
61  Planner::declareParam<double>("good_score_factor", this, &KPIECE1::setGoodCellScoreFactor, &KPIECE1::getGoodCellScoreFactor);
62 }
63 
64 ompl::control::KPIECE1::~KPIECE1(void)
65 {
66  freeMemory();
67 }
68 
70 {
71  Planner::setup();
72  tools::SelfConfig sc(si_, getName());
73  sc.configureProjectionEvaluator(projectionEvaluator_);
74 
75  if (badScoreFactor_ < std::numeric_limits<double>::epsilon() || badScoreFactor_ > 1.0)
76  throw Exception("Bad cell score factor must be in the range (0,1]");
77  if (goodScoreFactor_ < std::numeric_limits<double>::epsilon() || goodScoreFactor_ > 1.0)
78  throw Exception("Good cell score factor must be in the range (0,1]");
79  if (selectBorderFraction_ < std::numeric_limits<double>::epsilon() || selectBorderFraction_ > 1.0)
80  throw Exception("The fraction of time spent selecting border cells must be in the range (0,1]");
81 
82  tree_.grid.setDimension(projectionEvaluator_->getDimension());
83 }
84 
86 {
87  Planner::clear();
88  controlSampler_.reset();
89  freeMemory();
90  tree_.grid.clear();
91  tree_.size = 0;
92  tree_.iteration = 1;
93  lastGoalMotion_ = NULL;
94 }
95 
97 {
98  freeGridMotions(tree_.grid);
99 }
100 
102 {
103  for (Grid::iterator it = grid.begin(); it != grid.end() ; ++it)
104  freeCellData(it->second->data);
105 }
106 
108 {
109  for (unsigned int i = 0 ; i < cdata->motions.size() ; ++i)
110  freeMotion(cdata->motions[i]);
111  delete cdata;
112 }
113 
115 {
116  if (motion->state)
117  si_->freeState(motion->state);
118  if (motion->control)
119  siC_->freeControl(motion->control);
120  delete motion;
121 }
122 
124 {
125  if (samples.empty())
126  {
127  CloseSample cs(cell, motion, distance);
128  samples.insert(cs);
129  return true;
130  }
131  // if the sample we're considering is closer to the goal than the worst sample in the
132  // set of close samples, we include it
133  if (samples.rbegin()->distance > distance)
134  {
135  // if the inclusion would go above the maximum allowed size,
136  // remove the last element
137  if (samples.size() >= maxSize)
138  samples.erase(--samples.end());
139  CloseSample cs(cell, motion, distance);
140  samples.insert(cs);
141  return true;
142  }
143 
144  return false;
145 }
146 
147 
149 // this is the factor by which distances are inflated when considered for addition to closest samples
150 static const double CLOSE_MOTION_DISTANCE_INFLATION_FACTOR = 1.1;
152 
154 {
155  if (samples.size() > 0)
156  {
157  scell = samples.begin()->cell;
158  smotion = samples.begin()->motion;
159  // average the highest & lowest distances and multiply by CLOSE_MOTION_DISTANCE_INFLATION_FACTOR
160  // (make the distance appear artificially longer)
161  double d = (samples.begin()->distance + samples.rbegin()->distance) * (CLOSE_MOTION_DISTANCE_INFLATION_FACTOR / 2.0);
162  samples.erase(samples.begin());
163  consider(scell, smotion, d);
164  return true;
165  }
166  return false;
167 }
168 
169 unsigned int ompl::control::KPIECE1::findNextMotion(const std::vector<Grid::Coord> &coords, unsigned int index, unsigned int count)
170 {
171  for (unsigned int i = index + 1 ; i < count ; ++i)
172  if (coords[i] != coords[index])
173  return i - 1;
174 
175  return count - 1;
176 }
177 
179 {
180  checkValidity();
181  base::Goal *goal = pdef_->getGoal().get();
182 
183  while (const base::State *st = pis_.nextStart())
184  {
185  Motion *motion = new Motion(siC_);
186  si_->copyState(motion->state, st);
187  siC_->nullControl(motion->control);
188  addMotion(motion, 1.0);
189  }
190 
191  if (tree_.grid.size() == 0)
192  {
193  logError("There are no valid initial states!");
195  }
196 
197  if (!controlSampler_)
198  controlSampler_ = siC_->allocControlSampler();
199 
200  logInform("Starting with %u states", tree_.size);
201 
202  Motion *solution = NULL;
203  Motion *approxsol = NULL;
204  double approxdif = std::numeric_limits<double>::infinity();
205 
206  Control *rctrl = siC_->allocControl();
207 
208  std::vector<base::State*> states(siC_->getMaxControlDuration() + 1);
209  std::vector<Grid::Coord> coords(states.size());
210  std::vector<Grid::Cell*> cells(coords.size());
211 
212  for (unsigned int i = 0 ; i < states.size() ; ++i)
213  states[i] = si_->allocState();
214 
215  // samples that were found to be the best, so far
216  CloseSamples closeSamples(nCloseSamples_);
217 
218  while (ptc() == false)
219  {
220  tree_.iteration++;
221 
222  /* Decide on a state to expand from */
223  Motion *existing = NULL;
224  Grid::Cell *ecell = NULL;
225 
226  if (closeSamples.canSample() && rng_.uniform01() < goalBias_)
227  {
228  if (!closeSamples.selectMotion(existing, ecell))
229  selectMotion(existing, ecell);
230  }
231  else
232  selectMotion(existing, ecell);
233  assert(existing);
234 
235  /* sample a random control */
236  controlSampler_->sampleNext(rctrl, existing->control, existing->state);
237 
238  /* propagate */
239  unsigned int cd = controlSampler_->sampleStepCount(siC_->getMinControlDuration(), siC_->getMaxControlDuration());
240  cd = siC_->propagateWhileValid(existing->state, rctrl, cd, states, false);
241 
242  /* if we have enough steps */
243  if (cd >= siC_->getMinControlDuration())
244  {
245  std::size_t avgCov_two_thirds = (2 * tree_.size) / (3 * tree_.grid.size());
246  bool interestingMotion = false;
247 
248  // split the motion into smaller ones, so we do not cross cell boundaries
249  for (unsigned int i = 0 ; i < cd ; ++i)
250  {
251  projectionEvaluator_->computeCoordinates(states[i], coords[i]);
252  cells[i] = tree_.grid.getCell(coords[i]);
253  if (!cells[i])
254  interestingMotion = true;
255  else
256  {
257  if (!interestingMotion && cells[i]->data->motions.size() <= avgCov_two_thirds)
258  interestingMotion = true;
259  }
260  }
261 
262  if (interestingMotion || rng_.uniform01() < 0.05)
263  {
264  unsigned int index = 0;
265  while (index < cd)
266  {
267  unsigned int nextIndex = findNextMotion(coords, index, cd);
268  Motion *motion = new Motion(siC_);
269  si_->copyState(motion->state, states[nextIndex]);
270  siC_->copyControl(motion->control, rctrl);
271  motion->steps = nextIndex - index + 1;
272  motion->parent = existing;
273 
274  double dist = 0.0;
275  bool solv = goal->isSatisfied(motion->state, &dist);
276  Grid::Cell *toCell = addMotion(motion, dist);
277 
278  if (solv)
279  {
280  approxdif = dist;
281  solution = motion;
282  break;
283  }
284  if (dist < approxdif)
285  {
286  approxdif = dist;
287  approxsol = motion;
288  }
289 
290  closeSamples.consider(toCell, motion, dist);
291 
292  // new parent will be the newly created motion
293  existing = motion;
294  index = nextIndex + 1;
295  }
296 
297  if (solution)
298  break;
299  }
300 
301  // update cell score
302  ecell->data->score *= goodScoreFactor_;
303  }
304  else
305  ecell->data->score *= badScoreFactor_;
306 
307  tree_.grid.update(ecell);
308  }
309 
310  bool solved = false;
311  bool approximate = false;
312  if (solution == NULL)
313  {
314  solution = approxsol;
315  approximate = true;
316  }
317 
318  if (solution != NULL)
319  {
320  lastGoalMotion_ = solution;
321 
322  /* construct the solution path */
323  std::vector<Motion*> mpath;
324  while (solution != NULL)
325  {
326  mpath.push_back(solution);
327  solution = solution->parent;
328  }
329 
330  /* set the solution path */
331  PathControl *path = new PathControl(si_);
332  for (int i = mpath.size() - 1 ; i >= 0 ; --i)
333  if (mpath[i]->parent)
334  path->append(mpath[i]->state, mpath[i]->control, mpath[i]->steps * siC_->getPropagationStepSize());
335  else
336  path->append(mpath[i]->state);
337 
338  pdef_->addSolutionPath(base::PathPtr(path), approximate, approxdif);
339  solved = true;
340  }
341 
342  siC_->freeControl(rctrl);
343  for (unsigned int i = 0 ; i < states.size() ; ++i)
344  si_->freeState(states[i]);
345 
346  logInform("Created %u states in %u cells (%u internal + %u external)", tree_.size, tree_.grid.size(),
347  tree_.grid.countInternal(), tree_.grid.countExternal());
348 
349  return base::PlannerStatus(solved, approximate);
350 }
351 
353 {
354  scell = rng_.uniform01() < std::max(selectBorderFraction_, tree_.grid.fracExternal()) ?
355  tree_.grid.topExternal() : tree_.grid.topInternal();
356 
357  // We are running on finite precision, so our update scheme will end up
358  // with 0 values for the score. This is where we fix the problem
359  if (scell->data->score < std::numeric_limits<double>::epsilon())
360  {
361  logDebug("Numerical precision limit reached. Resetting costs.");
362  std::vector<CellData*> content;
363  content.reserve(tree_.grid.size());
364  tree_.grid.getContent(content);
365  for (std::vector<CellData*>::iterator it = content.begin() ; it != content.end() ; ++it)
366  (*it)->score += 1.0 + log((double)((*it)->iteration));
367  tree_.grid.updateAll();
368  }
369 
370  if (scell && !scell->data->motions.empty())
371  {
372  scell->data->selections++;
373  smotion = scell->data->motions[rng_.halfNormalInt(0, scell->data->motions.size() - 1)];
374  return true;
375  }
376  else
377  return false;
378 }
379 
381 // this is the offset added to estimated distances to the goal, so we avoid division by 0
382 static const double DISTANCE_TO_GOAL_OFFSET = 1e-3;
384 
386 {
387  Grid::Coord coord;
388  projectionEvaluator_->computeCoordinates(motion->state, coord);
389  Grid::Cell* cell = tree_.grid.getCell(coord);
390  if (cell)
391  {
392  cell->data->motions.push_back(motion);
393  cell->data->coverage += motion->steps;
394  tree_.grid.update(cell);
395  }
396  else
397  {
398  cell = tree_.grid.createCell(coord);
399  cell->data = new CellData();
400  cell->data->motions.push_back(motion);
401  cell->data->coverage = motion->steps;
402  cell->data->iteration = tree_.iteration;
403  cell->data->selections = 1;
404  cell->data->score = (1.0 + log((double)(tree_.iteration))) / (DISTANCE_TO_GOAL_OFFSET + dist);
405  tree_.grid.add(cell);
406  }
407  tree_.size++;
408  return cell;
409 }
410 
412 {
413  Planner::getPlannerData(data);
414 
415  Grid::CellArray cells;
416  tree_.grid.getCells(cells);
417 
418  double delta = siC_->getPropagationStepSize();
419 
420  if (lastGoalMotion_)
421  data.addGoalVertex(base::PlannerDataVertex(lastGoalMotion_->state));
422 
423  for (unsigned int i = 0 ; i < cells.size() ; ++i)
424  {
425  for (unsigned int j = 0 ; j < cells[i]->data->motions.size() ; ++j)
426  {
427  const Motion* m = cells[i]->data->motions[j];
428  if (m->parent)
429  {
430  if (data.hasControls())
432  base::PlannerDataVertex (m->state, cells[i]->border ? 2 : 1),
434  else
436  base::PlannerDataVertex (m->state, cells[i]->border ? 2 : 1));
437  }
438  else
439  data.addStartVertex(base::PlannerDataVertex (m->state, cells[i]->border ? 2 : 1));
440 
441  // A state created as a parent first may have an improper tag variable
442  data.tagState(m->state, cells[i]->border ? 2 : 1);
443  }
444  }
445 }