KPIECE1.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2008, Willow Garage, Inc.
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 Willow Garage 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/geometric/planners/kpiece/KPIECE1.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <limits>
41 #include <cassert>
42 
44  : base::Planner(si, "KPIECE1")
45  , disc_([this](Motion *m)
46  {
47  freeMotion(m);
48  })
49 {
51  specs_.directed = true;
52 
53  goalBias_ = 0.05;
56  maxDistance_ = 0.0;
57  lastGoalMotion_ = nullptr;
58 
59  Planner::declareParam<double>("range", this, &KPIECE1::setRange, &KPIECE1::getRange, "0.:1.:10000.");
60  Planner::declareParam<double>("goal_bias", this, &KPIECE1::setGoalBias, &KPIECE1::getGoalBias, "0.:.05:1.");
61  Planner::declareParam<double>("border_fraction", this, &KPIECE1::setBorderFraction, &KPIECE1::getBorderFraction,
62  "0.:0.05:1.");
63  Planner::declareParam<double>("failed_expansion_score_factor", this, &KPIECE1::setFailedExpansionCellScoreFactor,
65  Planner::declareParam<double>("min_valid_path_fraction", this, &KPIECE1::setMinValidPathFraction,
67 }
68 
69 ompl::geometric::KPIECE1::~KPIECE1() = default;
70 
72 {
73  Planner::setup();
77 
78  if (failedExpansionScoreFactor_ < std::numeric_limits<double>::epsilon() || failedExpansionScoreFactor_ > 1.0)
79  throw Exception("Failed expansion cell score factor must be in the range (0,1]");
80  if (minValidPathFraction_ < std::numeric_limits<double>::epsilon() || minValidPathFraction_ > 1.0)
81  throw Exception("The minimum valid path fraction must be in the range (0,1]");
82 
83  disc_.setDimension(projectionEvaluator_->getDimension());
84 }
85 
87 {
88  Planner::clear();
89  sampler_.reset();
90  disc_.clear();
91  lastGoalMotion_ = nullptr;
92 }
93 
95 {
96  if (motion->state)
97  si_->freeState(motion->state);
98  delete motion;
99 }
100 
102 {
103  checkValidity();
104  base::Goal *goal = pdef_->getGoal().get();
105  base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion *>(goal);
106 
108 
109  while (const base::State *st = pis_.nextStart())
110  {
111  auto *motion = new Motion(si_);
112  si_->copyState(motion->state, st);
113  projectionEvaluator_->computeCoordinates(motion->state, xcoord);
114  disc_.addMotion(motion, xcoord, 1.0);
115  }
116 
117  if (disc_.getMotionCount() == 0)
118  {
119  OMPL_ERROR("%s: There are no valid initial states!", getName().c_str());
121  }
122 
123  if (!sampler_)
124  sampler_ = si_->allocStateSampler();
125 
126  OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(),
127  disc_.getMotionCount());
128 
129  Motion *solution = nullptr;
130  Motion *approxsol = nullptr;
131  double approxdif = std::numeric_limits<double>::infinity();
132  base::State *xstate = si_->allocState();
133 
134  while (ptc == false)
135  {
136  disc_.countIteration();
137 
138  /* Decide on a state to expand from */
139  Motion *existing = nullptr;
140  Discretization<Motion>::Cell *ecell = nullptr;
141  disc_.selectMotion(existing, ecell);
142  assert(existing);
143 
144  /* sample random state (with goal biasing) */
145  if (goal_s && rng_.uniform01() < goalBias_ && goal_s->canSample())
146  goal_s->sampleGoal(xstate);
147  else
148  sampler_->sampleUniformNear(xstate, existing->state, maxDistance_);
149 
150  std::pair<base::State *, double> fail(xstate, 0.0);
151  bool keep = si_->checkMotion(existing->state, xstate, fail);
152  if (!keep && fail.second > minValidPathFraction_)
153  keep = true;
154 
155  if (keep)
156  {
157  /* create a motion */
158  auto *motion = new Motion(si_);
159  si_->copyState(motion->state, xstate);
160  motion->parent = existing;
161 
162  double dist = 0.0;
163  bool solv = goal->isSatisfied(motion->state, &dist);
164  projectionEvaluator_->computeCoordinates(motion->state, xcoord);
165  disc_.addMotion(motion, xcoord, dist); // this will also update the discretization heaps as needed, so no
166  // call to updateCell() is needed
167 
168  if (solv)
169  {
170  approxdif = dist;
171  solution = motion;
172  break;
173  }
174  if (dist < approxdif)
175  {
176  approxdif = dist;
177  approxsol = motion;
178  }
179  }
180  else
181  ecell->data->score *= failedExpansionScoreFactor_;
182  disc_.updateCell(ecell);
183  }
184 
185  bool solved = false;
186  bool approximate = false;
187  if (solution == nullptr)
188  {
189  solution = approxsol;
190  approximate = true;
191  }
192 
193  if (solution != nullptr)
194  {
195  lastGoalMotion_ = solution;
196 
197  /* construct the solution path */
198  std::vector<Motion *> mpath;
199  while (solution != nullptr)
200  {
201  mpath.push_back(solution);
202  solution = solution->parent;
203  }
204 
205  /* set the solution path */
206  auto path(std::make_shared<PathGeometric>(si_));
207  for (int i = mpath.size() - 1; i >= 0; --i)
208  path->append(mpath[i]->state);
209  pdef_->addSolutionPath(path, approximate, approxdif, getName());
210  solved = true;
211  }
212 
213  si_->freeState(xstate);
214 
215  OMPL_INFORM("%s: Created %u states in %u cells (%u internal + %u external)", getName().c_str(),
216  disc_.getMotionCount(), disc_.getCellCount(), disc_.getGrid().countInternal(),
217  disc_.getGrid().countExternal());
218 
219  return base::PlannerStatus(solved, approximate);
220 }
221 
223 {
224  Planner::getPlannerData(data);
225  disc_.getPlannerData(data, 0, true, lastGoalMotion_);
226 }
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:212
double failedExpansionScoreFactor_
When extending a motion from a cell, the extension can fail. If it is, the score of the cell is multi...
Definition: KPIECE1.h:234
Grid::Coord Coord
The datatype for the maintained grid coordinates.
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:174
double getBorderFraction() const
Get the fraction of time to focus exploration on boundary.
Definition: KPIECE1.h:132
Motion * lastGoalMotion_
The most recent goal motion. Used for PlannerData computation.
Definition: KPIECE1.h:254
RNG rng_
The random number generator.
Definition: KPIECE1.h:251
base::State * state
The state contained by this motion.
Definition: KPIECE1.h:211
Representation of a motion for this algorithm.
Definition: KPIECE1.h:196
void freeMotion(Motion *motion)
Free the memory for a motion.
Definition: KPIECE1.cpp:94
double minValidPathFraction_
When extending a motion, the planner can decide to keep the first valid part of it, even if invalid states are found, as long as the valid part represents a sufficiently large fraction from the original motion.
Definition: KPIECE1.h:245
Abstract definition of goals.
Definition: Goal.h:62
double getFailedExpansionCellScoreFactor() const
Get the factor that is multiplied to a cell&#39;s score if extending a motion from that cell failed...
Definition: KPIECE1.h:165
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
_T data
The data we store in the cell.
Definition: Grid.h:60
double getMinValidPathFraction() const
Get the value of the fraction set by setMinValidPathFraction()
Definition: KPIECE1.h:149
Discretization< Motion > disc_
The tree datastructure and the grid that covers it.
Definition: KPIECE1.h:224
void clear() override
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: KPIECE1.cpp:86
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:418
bool directed
Flag indicating whether the planner is able to account for the fact that the validity of a motion fro...
Definition: Planner.h:222
double goalBias_
The fraction of time the goal is picked as the state to expand towards (if such a state is available)...
Definition: KPIECE1.h:238
virtual void sampleGoal(State *st) const =0
Sample a state in the goal region.
void setGoalBias(double goalBias)
Set the goal bias.
Definition: KPIECE1.h:92
double uniform01()
Generate a random real between 0 and 1.
Definition: RandomNumbers.h:68
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: KPIECE1.h:248
Abstract definition of a goal region that can be sampled.
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: KPIECE1.cpp:101
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
bool canSample() const
Return true if maxSampleCount() > 0, since in this case samples can certainly be produced.
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: KPIECE1.h:108
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: KPIECE1.cpp:222
A class to store the exit status of Planner::solve()
Definition: PlannerStatus.h:48
A shared pointer wrapper for ompl::base::SpaceInformation.
void setBorderFraction(double bp)
Set the fraction of time for focusing on the border (between 0 and 1). This is the minimum fraction u...
Definition: KPIECE1.h:125
KPIECE1(const base::SpaceInformationPtr &si)
Constructor.
Definition: KPIECE1.cpp:43
Definition of an abstract state.
Definition: State.h:49
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:101
virtual bool isSatisfied(const State *st) const =0
Return true if the state satisfies the goal constraints.
PlannerInputStates pis_
Utility class to extract valid input states.
Definition: Planner.h:421
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:427
const State * nextStart()
Return the next valid start state or nullptr if no more valid start states are available.
Definition: Planner.cpp:230
Definition of a cell in this grid.
Definition: Grid.h:57
void setMinValidPathFraction(double fraction)
When extending a motion, the planner can decide to keep the first valid part of it, even if invalid states are found, as long as the valid part represents a sufficiently large fraction from the original motion. This function sets the minimum acceptable fraction (between 0 and 1).
Definition: KPIECE1.h:143
The exception type for ompl.
Definition: Exception.h:46
double getRange() const
Get the range the planner is using.
Definition: KPIECE1.h:114
void setup() override
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: KPIECE1.cpp:71
void configureProjectionEvaluator(base::ProjectionEvaluatorPtr &proj)
If proj is undefined, it is set to the default projection reported by base::StateSpace::getDefaultPro...
Definition: SelfConfig.cpp:231
double getGoalBias() const
Get the goal bias the planner is using.
Definition: KPIECE1.h:98
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:56
void configurePlannerRange(double &range)
Compute what a good length for motion segments is.
Definition: SelfConfig.cpp:225
This class contains methods that automatically configure various parameters for motion planning...
Definition: SelfConfig.h:59
base::ProjectionEvaluatorPtr projectionEvaluator_
This algorithm uses a discretization (a grid) to guide the exploration. The exploration is imposed on...
Definition: KPIECE1.h:229
base::StateSamplerPtr sampler_
A state space sampler.
Definition: KPIECE1.h:221
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:415
void setFailedExpansionCellScoreFactor(double factor)
When extending a motion from a cell, the extension can be successful or it can fail. If the extension fails, the score of the cell is multiplied by factor. These number should be in the range (0, 1].
Definition: KPIECE1.h:158
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68