BKPIECE1.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2011, 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/geometric/planners/kpiece/BKPIECE1.h"
38 #include "ompl/base/goals/GoalSampleableRegion.h"
39 #include "ompl/tools/config/SelfConfig.h"
40 #include <cassert>
41 
43  : base::Planner(si, "BKPIECE1")
44  , dStart_([this](Motion *m)
45  {
46  freeMotion(m);
47  })
48  , dGoal_([this](Motion *m)
49  {
50  freeMotion(m);
51  })
52 {
54 
55  Planner::declareParam<double>("range", this, &BKPIECE1::setRange, &BKPIECE1::getRange, "0.:1.:10000.");
56  Planner::declareParam<double>("border_fraction", this, &BKPIECE1::setBorderFraction, &BKPIECE1::getBorderFraction,
57  "0.:.05:1.");
58  Planner::declareParam<double>("failed_expansion_score_factor", this, &BKPIECE1::setFailedExpansionCellScoreFactor,
60  Planner::declareParam<double>("min_valid_path_fraction", this, &BKPIECE1::setMinValidPathFraction,
62 }
63 
64 ompl::geometric::BKPIECE1::~BKPIECE1() = default;
65 
67 {
68  Planner::setup();
72 
73  if (failedExpansionScoreFactor_ < std::numeric_limits<double>::epsilon() || failedExpansionScoreFactor_ > 1.0)
74  throw Exception("Failed expansion cell score factor must be in the range (0,1]");
75  if (minValidPathFraction_ < std::numeric_limits<double>::epsilon() || minValidPathFraction_ > 1.0)
76  throw Exception("The minimum valid path fraction must be in the range (0,1]");
77 
78  dStart_.setDimension(projectionEvaluator_->getDimension());
79  dGoal_.setDimension(projectionEvaluator_->getDimension());
80 }
81 
83 {
84  checkValidity();
85  auto *goal = dynamic_cast<base::GoalSampleableRegion *>(pdef_->getGoal().get());
86 
87  if (goal == nullptr)
88  {
89  OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
91  }
92 
94 
95  while (const base::State *st = pis_.nextStart())
96  {
97  auto *motion = new Motion(si_);
98  si_->copyState(motion->state, st);
99  motion->root = motion->state;
100  projectionEvaluator_->computeCoordinates(motion->state, xcoord);
101  dStart_.addMotion(motion, xcoord);
102  }
103 
104  if (dStart_.getMotionCount() == 0)
105  {
106  OMPL_ERROR("%s: Motion planning start tree could not be initialized!", getName().c_str());
108  }
109 
110  if (!goal->couldSample())
111  {
112  OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str());
114  }
115 
116  if (!sampler_)
117  sampler_ = si_->allocValidStateSampler();
118 
119  OMPL_INFORM("%s: Starting planning with %d states already in datastructure", getName().c_str(),
120  (int)(dStart_.getMotionCount() + dGoal_.getMotionCount()));
121 
122  std::vector<Motion *> solution;
123  base::State *xstate = si_->allocState();
124  bool startTree = true;
125  bool solved = false;
126 
127  while (!ptc)
128  {
129  Discretization<Motion> &disc = startTree ? dStart_ : dGoal_;
130  startTree = !startTree;
131  Discretization<Motion> &otherDisc = startTree ? dStart_ : dGoal_;
132  disc.countIteration();
133 
134  // if we have not sampled too many goals already
135  if (dGoal_.getMotionCount() == 0 || pis_.getSampledGoalsCount() < dGoal_.getMotionCount() / 2)
136  {
137  const base::State *st = dGoal_.getMotionCount() == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal();
138  if (st != nullptr)
139  {
140  auto *motion = new Motion(si_);
141  si_->copyState(motion->state, st);
142  motion->root = motion->state;
143  projectionEvaluator_->computeCoordinates(motion->state, xcoord);
144  dGoal_.addMotion(motion, xcoord);
145  }
146  if (dGoal_.getMotionCount() == 0)
147  {
148  OMPL_ERROR("%s: Unable to sample any valid states for goal tree", getName().c_str());
149  break;
150  }
151  }
152 
153  Discretization<Motion>::Cell *ecell = nullptr;
154  Motion *existing = nullptr;
155  disc.selectMotion(existing, ecell);
156  assert(existing);
157  if (sampler_->sampleNear(xstate, existing->state, maxDistance_))
158  {
159  std::pair<base::State *, double> fail(xstate, 0.0);
160  bool keep = si_->checkMotion(existing->state, xstate, fail);
161  if (!keep && fail.second > minValidPathFraction_)
162  keep = true;
163 
164  if (keep)
165  {
166  /* create a motion */
167  auto *motion = new Motion(si_);
168  si_->copyState(motion->state, xstate);
169  motion->root = existing->root;
170  motion->parent = existing;
171 
172  projectionEvaluator_->computeCoordinates(motion->state, xcoord);
173  disc.addMotion(motion, xcoord);
174 
175  Discretization<Motion>::Cell *cellC = otherDisc.getGrid().getCell(xcoord);
176 
177  if ((cellC != nullptr) && !cellC->data->motions.empty())
178  {
179  Motion *connectOther = cellC->data->motions[rng_.uniformInt(0, cellC->data->motions.size() - 1)];
180 
181  if (goal->isStartGoalPairValid(startTree ? connectOther->root : motion->root,
182  startTree ? motion->root : connectOther->root) &&
183  si_->checkMotion(motion->state, connectOther->state))
184  {
185  if (startTree)
186  connectionPoint_ = std::make_pair(connectOther->state, motion->state);
187  else
188  connectionPoint_ = std::make_pair(motion->state, connectOther->state);
189 
190  /* extract the motions and put them in solution vector */
191 
192  std::vector<Motion *> mpath1;
193  while (motion != nullptr)
194  {
195  mpath1.push_back(motion);
196  motion = motion->parent;
197  }
198 
199  std::vector<Motion *> mpath2;
200  while (connectOther != nullptr)
201  {
202  mpath2.push_back(connectOther);
203  connectOther = connectOther->parent;
204  }
205 
206  if (startTree)
207  mpath1.swap(mpath2);
208 
209  auto path(std::make_shared<PathGeometric>(si_));
210  path->getStates().reserve(mpath1.size() + mpath2.size());
211  for (int i = mpath1.size() - 1; i >= 0; --i)
212  path->append(mpath1[i]->state);
213  for (auto &i : mpath2)
214  path->append(i->state);
215 
216  pdef_->addSolutionPath(path, false, 0.0, getName());
217  solved = true;
218  break;
219  }
220  }
221  }
222  else
223  ecell->data->score *= failedExpansionScoreFactor_;
224  }
225  else
226  ecell->data->score *= failedExpansionScoreFactor_;
227  disc.updateCell(ecell);
228  }
229 
230  si_->freeState(xstate);
231 
232  OMPL_INFORM("%s: Created %u (%u start + %u goal) states in %u cells (%u start (%u on boundary) + %u goal (%u on "
233  "boundary))",
234  getName().c_str(), dStart_.getMotionCount() + dGoal_.getMotionCount(), dStart_.getMotionCount(),
235  dGoal_.getMotionCount(), dStart_.getCellCount() + dGoal_.getCellCount(), dStart_.getCellCount(),
236  dStart_.getGrid().countExternal(), dGoal_.getCellCount(), dGoal_.getGrid().countExternal());
237 
239 }
240 
242 {
243  if (motion->state != nullptr)
244  si_->freeState(motion->state);
245  delete motion;
246 }
247 
249 {
250  Planner::clear();
251 
252  sampler_.reset();
253  dStart_.clear();
254  dGoal_.clear();
255  connectionPoint_ = std::make_pair<base::State *, base::State *>(nullptr, nullptr);
256 }
257 
259 {
260  Planner::getPlannerData(data);
261  dStart_.getPlannerData(data, 1, true, nullptr);
262  dGoal_.getPlannerData(data, 2, false, nullptr);
263 
264  // Insert the edge connecting the two trees
265  data.addEdge(data.vertexIndex(connectionPoint_.first), data.vertexIndex(connectionPoint_.second));
266 }
Grid::Coord Coord
The datatype for the maintained grid coordinates.
void setRange(double distance)
Set the range the planner is supposed to use.
Definition: BKPIECE1.h:106
Object containing planner generated vertex and edge data. It is assumed that all vertices are unique...
Definition: PlannerData.h:174
Discretization< Motion > dGoal_
The goal tree.
Definition: BKPIECE1.h:213
const base::State * root
The root state (start state) that leads to this motion.
Definition: BKPIECE1.h:191
std::pair< base::State *, base::State * > connectionPoint_
The pair of states in each tree connected during planning. Used for PlannerData computation.
Definition: BKPIECE1.h:234
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:197
void freeMotion(Motion *motion)
Free the memory for a motion.
Definition: BKPIECE1.cpp:241
base::ProjectionEvaluatorPtr projectionEvaluator_
The employed projection evaluator.
Definition: BKPIECE1.h:207
const State * nextGoal(const PlannerTerminationCondition &ptc)
Return the next valid goal state or nullptr if no more valid goal states are available. Because sampling of goal states may also produce invalid goals, this function takes an argument that specifies whether a termination condition has been reached. If the termination condition evaluates to true the function terminates even if no valid goal has been found.
Definition: Planner.cpp:264
void setup() override
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: BKPIECE1.cpp:66
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
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...
_T data
The data we store in the cell.
Definition: Grid.h:60
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: BKPIECE1.cpp:258
double failedExpansionScoreFactor_
When extending a motion from a cell, the extension can fail. If it is, the score of the cell is multi...
Definition: BKPIECE1.h:218
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:409
Discretization< Motion > dStart_
The start tree.
Definition: BKPIECE1.h:210
unsigned int getSampledGoalsCount() const
Get the number of sampled goal states, including invalid ones.
Definition: Planner.h:175
RNG rng_
The random number generator.
Definition: BKPIECE1.h:231
double getFailedExpansionCellScoreFactor() const
Get the factor that is multiplied to a cell&#39;s score if extending a motion from that cell failed...
Definition: BKPIECE1.h:147
double getRange() const
Get the range the planner is using.
Definition: BKPIECE1.h:112
Invalid start state or no start state specified.
Definition: PlannerStatus.h:56
Abstract definition of a goal region that can be sampled.
double maxDistance_
The maximum length of a motion to be added to a tree.
Definition: BKPIECE1.h:228
The goal is of a type that a planner does not recognize.
Definition: PlannerStatus.h:60
One-level discretization used for KPIECE.
#define OMPL_ERROR(fmt,...)
Log a formatted error string.
Definition: Console.h:64
The planner found an exact solution.
Definition: PlannerStatus.h:66
Representation of a motion for this algorithm.
Definition: BKPIECE1.h:178
unsigned int addMotion(Motion *motion, const Coord &coord, double dist=0.0)
Add a motion to the grid containing motions. As a hint, dist specifies the distance to the goal from ...
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...
A shared pointer wrapper for ompl::base::SpaceInformation.
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.
Definition: BKPIECE1.h:158
void clear() override
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: BKPIECE1.cpp:248
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
PlannerInputStates pis_
Utility class to extract valid input states.
Definition: Planner.h:412
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: BKPIECE1.cpp:82
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: BKPIECE1.h:140
base::State * state
The state contained by this motion.
Definition: BKPIECE1.h:194
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:418
const State * nextStart()
Return the next valid start state or nullptr if no more valid start states are available.
Definition: Planner.cpp:227
Definition of a cell in this grid.
Definition: Grid.h:57
Motion * parent
The parent motion in the exploration tree.
Definition: BKPIECE1.h:197
double getBorderFraction() const
Get the fraction of time to focus exploration on boundary.
Definition: BKPIECE1.h:131
double getMinValidPathFraction() const
Get the value of the fraction set by setMinValidPathFraction()
Definition: BKPIECE1.h:164
The exception type for ompl.
Definition: Exception.h:46
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
const std::string & getName() const
Get the name of the planner.
Definition: Planner.cpp:56
void selectMotion(Motion *&smotion, Cell *&scell)
Select a motion and the cell it is part of from the grid of motions. This is where preference is give...
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
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: BKPIECE1.h:225
BKPIECE1(const base::SpaceInformationPtr &si)
Constructor.
Definition: BKPIECE1.cpp:42
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:406
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: BKPIECE1.h:123
int uniformInt(int lower_bound, int upper_bound)
Generate a random integer within given bounds: [lower_bound, upper_bound].
Definition: RandomNumbers.h:81
base::ValidStateSamplerPtr sampler_
The employed state sampler.
Definition: BKPIECE1.h:204
This bit is set if casting to sampleable goal regions (ompl::base::GoalSampleableRegion) is possible...
Definition: GoalTypes.h:56
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68