Syclop.h
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: Matt Maly */
36 
37 #ifndef OMPL_CONTROL_PLANNERS_SYCLOP_SYCLOP_
38 #define OMPL_CONTROL_PLANNERS_SYCLOP_SYCLOP_
39 
40 #include <boost/graph/astar_search.hpp>
41 #include <boost/graph/graph_traits.hpp>
42 #include <boost/graph/adjacency_list.hpp>
43 #include <unordered_map>
44 #include "ompl/control/planners/PlannerIncludes.h"
45 #include "ompl/control/planners/syclop/Decomposition.h"
46 #include "ompl/control/planners/syclop/GridDecomposition.h"
47 #include "ompl/datastructures/PDF.h"
48 #include "ompl/util/Hash.h"
49 #include <functional>
50 #include <map>
51 #include <utility>
52 #include <vector>
53 
54 namespace ompl
55 {
56  namespace control
57  {
73  class Syclop : public base::Planner
74  {
75  public:
96  typedef std::function<double(int, int)> EdgeCostFactorFn;
97 
100  typedef std::function<void(int, int, std::vector<int> &)> LeadComputeFn;
101 
103  Syclop(const SpaceInformationPtr &si, DecompositionPtr d, const std::string &plannerName)
104  : ompl::base::Planner(si, plannerName)
105  , siC_(si.get())
106  , decomp_(std::move(d))
107  , covGrid_(Defaults::COVGRID_LENGTH, decomp_)
108  {
110 
111  Planner::declareParam<int>("free_volume_samples", this, &Syclop::setNumFreeVolumeSamples,
112  &Syclop::getNumFreeVolumeSamples, "10000:10000:500000");
113  Planner::declareParam<int>("num_region_expansions", this, &Syclop::setNumRegionExpansions,
114  &Syclop::getNumRegionExpansions, "10:10:500");
115  Planner::declareParam<int>("num_tree_expansions", this, &Syclop::setNumTreeExpansions,
116  &Syclop::getNumTreeExpansions, "0:1:100");
117  Planner::declareParam<double>("prob_abandon_lead_early", this, &Syclop::setProbAbandonLeadEarly,
118  &Syclop::getProbAbandonLeadEarly, "0.:.05:1.");
119  Planner::declareParam<double>("prob_add_available_regions", this,
122  Planner::declareParam<double>("prob_shortest_path_lead", this, &Syclop::setProbShortestPathLead,
123  &Syclop::getProbShortestPathLead, "0.:.05:1.");
124  }
125 
126  ~Syclop() override = default;
127 
130 
131  void setup() override;
132 
133  void clear() override;
134 
139 
142 
144  void setLeadComputeFn(const LeadComputeFn &compute);
145 
147  void addEdgeCostFactor(const EdgeCostFactorFn &factor);
148 
150  void clearEdgeCostFactors();
151 
154  {
155  return numFreeVolSamples_;
156  }
157 
160  void setNumFreeVolumeSamples(int numSamples)
161  {
162  numFreeVolSamples_ = numSamples;
163  }
164 
167  double getProbShortestPathLead() const
168  {
169  return probShortestPath_;
170  }
171 
174  void setProbShortestPathLead(double probability)
175  {
176  probShortestPath_ = probability;
177  }
178 
182  {
183  return probKeepAddingToAvail_;
184  }
185 
188  void setProbAddingToAvailableRegions(double probability)
189  {
190  probKeepAddingToAvail_ = probability;
191  }
192 
196  {
197  return numRegionExpansions_;
198  }
199 
202  void setNumRegionExpansions(int regionExpansions)
203  {
204  numRegionExpansions_ = regionExpansions;
205  }
206 
210  {
211  return numTreeSelections_;
212  }
213 
216  void setNumTreeExpansions(int treeExpansions)
217  {
218  numTreeSelections_ = treeExpansions;
219  }
220 
223  double getProbAbandonLeadEarly() const
224  {
225  return probAbandonLeadEarly_;
226  }
227 
230  void setProbAbandonLeadEarly(double probability)
231  {
232  probAbandonLeadEarly_ = probability;
233  }
235 
237  struct Defaults
238  {
239  static const int NUM_FREEVOL_SAMPLES = 100000;
240  static const int COVGRID_LENGTH = 128;
241  static const int NUM_REGION_EXPANSIONS = 100;
242  static const int NUM_TREE_SELECTIONS = 1;
243  // C++ standard prohibits non-integral static const member initialization
244  // These constants are set in Syclop.cpp. C++11 standard changes this
245  // with the constexpr keyword, but for compatibility this is not done.
246  static const double PROB_ABANDON_LEAD_EARLY /*= 0.25*/;
247  static const double PROB_KEEP_ADDING_TO_AVAIL /*= 0.50*/;
248  static const double PROB_SHORTEST_PATH /*= 0.95*/;
249  };
250 
251  protected:
252 #pragma pack(push, 4) // push default byte alignment to stack and align the following structure to 4 byte boundary
253 
257  class Motion
258  {
259  public:
260  Motion() = default;
261 
264  : state(si->allocState()), control(si->allocControl())
265  {
266  }
267  virtual ~Motion() = default;
269  base::State *state{nullptr};
271  Control *control{nullptr};
273  const Motion *parent{nullptr};
275  unsigned int steps{0};
276  };
277 #pragma pack(pop) // Restoring default byte alignment
278 
279 #pragma pack(push, 4) // push default byte alignment to stack and align the following structure to 4 byte boundary
280 
281  class Region
282  {
283  public:
284  Region() = default;
285  virtual ~Region() = default;
286 
287 #if __cplusplus >= 201103L
288  Region(const Region &) = default;
289  Region &operator=(const Region &) = default;
290  Region(Region &&) = default;
291  Region &operator=(Region &&) = default;
292 #endif
293 
295  void clear()
296  {
297  motions.clear();
298  covGridCells.clear();
299  pdfElem = nullptr;
300  }
301 
303  std::set<int> covGridCells;
305  std::vector<Motion *> motions;
307  double volume;
309  double freeVolume;
313  double weight;
315  double alpha;
317  int index;
319  unsigned int numSelections;
322  };
323 #pragma pack(pop) // Restoring default byte alignment
324 
325 #pragma pack(push, 4) // push default byte alignment to stack and align the following structure to 4 byte boundary
326 
328  class Adjacency
329  {
330  public:
331  Adjacency() = default;
332  virtual ~Adjacency() = default;
334  void clear()
335  {
336  covGridCells.clear();
337  }
340  std::set<int> covGridCells;
342  const Region *source;
344  const Region *target;
346  double cost;
354  bool empty;
355  };
356 #pragma pack(pop) // Restoring default byte alignment
357 
359  virtual Motion *addRoot(const base::State *s) = 0;
360 
363  virtual void selectAndExtend(Region &region, std::vector<Motion *> &newMotions) = 0;
364 
366  inline const Region &getRegionFromIndex(const int rid) const
367  {
368  return graph_[boost::vertex(rid, graph_)];
369  }
370 
372  int numFreeVolSamples_{Defaults::NUM_FREEVOL_SAMPLES};
373 
375  double probShortestPath_{Defaults::PROB_SHORTEST_PATH};
376 
378  double probKeepAddingToAvail_{Defaults::PROB_KEEP_ADDING_TO_AVAIL};
379 
381  int numRegionExpansions_{Defaults::NUM_REGION_EXPANSIONS};
382 
385  int numTreeSelections_{Defaults::NUM_TREE_SELECTIONS};
386 
389  double probAbandonLeadEarly_{Defaults::PROB_ABANDON_LEAD_EARLY};
390 
393 
396 
399 
400  private:
402 
403  struct HashRegionPair
404  {
405  size_t operator()(const std::pair<int, int> &p) const
406  {
407  std::size_t hash = std::hash<int>()(p.first);
408  hash_combine(hash, p.second);
409  return hash;
410  }
411  };
413 
416  class CoverageGrid : public GridDecomposition
417  {
418  public:
419  CoverageGrid(const int len, const DecompositionPtr &d)
420  : GridDecomposition(len, d->getDimension(), d->getBounds()), decomp(d)
421  {
422  }
423 
424  ~CoverageGrid() override = default;
425 
428  void project(const base::State *s, std::vector<double> &coord) const override
429  {
430  decomp->project(s, coord);
431  }
432 
434  void sampleFullState(const base::StateSamplerPtr & /*sampler*/, const std::vector<double> & /*coord*/,
435  base::State * /*s*/) const override
436  {
437  }
438 
439  protected:
440  const DecompositionPtr &decomp;
441  };
442 
443  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, Region, Adjacency> RegionGraph;
444  typedef boost::graph_traits<RegionGraph>::vertex_descriptor Vertex;
445  typedef boost::graph_traits<RegionGraph>::vertex_iterator VertexIter;
446  typedef boost::property_map<RegionGraph, boost::vertex_index_t>::type VertexIndexMap;
447  typedef boost::graph_traits<RegionGraph>::edge_iterator EdgeIter;
448 
450  friend class DecompositionHeuristic;
451 
452  class DecompositionHeuristic : public boost::astar_heuristic<RegionGraph, double>
453  {
454  public:
455  DecompositionHeuristic(const Syclop *s, const Region &goal) : syclop(s), goalRegion(goal)
456  {
457  }
458 
459  double operator()(Vertex v)
460  {
461  const Region &region = syclop->getRegionFromIndex(v);
462  return region.alpha * goalRegion.alpha;
463  }
464 
465  private:
466  const Syclop *syclop;
467  const Region &goalRegion;
468  };
469 
470  struct found_goal
471  {
472  };
473 
474  class GoalVisitor : public boost::default_astar_visitor
475  {
476  public:
477  GoalVisitor(const int goal) : goalRegion(goal)
478  {
479  }
480  void examine_vertex(Vertex v, const RegionGraph & /*g*/)
481  {
482  if (static_cast<int>(v) == goalRegion)
483  throw found_goal();
484  }
485 
486  private:
487  const int goalRegion;
488  };
490 
492  class RegionSet
493  {
494  public:
495  int sampleUniform()
496  {
497  if (empty())
498  return -1;
499  return regions.sample(rng.uniform01());
500  }
501  void insert(const int r)
502  {
503  if (regToElem.count(r) == 0)
504  regToElem[r] = regions.add(r, 1);
505  else
506  {
507  PDF<int>::Element *elem = regToElem[r];
508  regions.update(elem, regions.getWeight(elem) + 1);
509  }
510  }
511  void clear()
512  {
513  regions.clear();
514  regToElem.clear();
515  }
516  std::size_t size() const
517  {
518  return regions.size();
519  }
520  bool empty() const
521  {
522  return regions.empty();
523  }
524 
525  private:
526  RNG rng;
527  PDF<int> regions;
528  std::unordered_map<int, PDF<int>::Element *> regToElem;
529  };
531 
533  void initRegion(Region &r);
534 
536  void setupRegionEstimates();
537 
539  void updateRegion(Region &r);
540 
542  void initEdge(Adjacency &adj, const Region *source, const Region *target);
543 
545  void setupEdgeEstimates();
546 
548  void updateEdge(Adjacency &a);
549 
552  bool updateCoverageEstimate(Region &r, const base::State *s);
553 
556  bool updateConnectionEstimate(const Region &c, const Region &d, const base::State *s);
557 
560  void buildGraph();
561 
563  void clearGraphDetails();
564 
566  int selectRegion();
567 
569  void computeAvailableRegions();
570 
573  void defaultComputeLead(int startRegion, int goalRegion, std::vector<int> &lead);
574 
576  double defaultEdgeCost(int r, int s);
577 
579  LeadComputeFn leadComputeFn;
581  std::vector<int> lead_;
583  PDF<int> availDist_;
585  std::vector<EdgeCostFactorFn> edgeCostFactors_;
587  CoverageGrid covGrid_;
590  RegionGraph graph_;
592  bool graphReady_{false};
594  std::unordered_map<std::pair<int, int>, Adjacency *, HashRegionPair> regionsToEdge_;
596  unsigned int numMotions_{0};
598  RegionSet startRegions_;
600  RegionSet goalRegions_;
601  };
602  }
603 }
604 
605 #endif
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:203
Synergistic Combination of Layers of Planning.
Definition: Syclop.h:73
double getProbShortestPathLead() const
Get the probability [0,1] that a lead will be computed as a shortest-path instead of a random-DFS...
Definition: Syclop.h:167
double alpha
The coefficient contributed by this region to edge weights in lead computations.
Definition: Syclop.h:315
Representation of an adjacency (a directed edge) between two regions in the Decomposition assigned to...
Definition: Syclop.h:328
std::set< int > covGridCells
The cells of the underlying coverage grid that contain tree motions from this region.
Definition: Syclop.h:303
int numLeadInclusions
The number of times this adjacency has been included in a lead.
Definition: Syclop.h:348
int numSelections
The number of times the low-level tree planner has selected motions from the source region when attem...
Definition: Syclop.h:351
Definition of an abstract control.
Definition: Control.h:47
int index
The index of the graph node corresponding to this region.
Definition: Syclop.h:317
RNG rng_
Random number generator.
Definition: Syclop.h:398
PDF< int >::Element * pdfElem
The Element corresponding to this region in the PDF of available regions.
Definition: Syclop.h:321
A shared pointer wrapper for ompl::base::StateSampler.
double volume
The volume of this region.
Definition: Syclop.h:307
Representation of a region in the Decomposition assigned to Syclop.
Definition: Syclop.h:281
Motion(const SpaceInformation *si)
Constructor that allocates memory for the state and the control.
Definition: Syclop.h:263
Encapsulate a termination condition for a motion planner. Planners will call operator() to decide whe...
const SpaceInformation * siC_
Handle to the control::SpaceInformation object.
Definition: Syclop.h:392
STL namespace.
double getProbAddingToAvailableRegions() const
Get the probability [0,1] that the set of available regions will be augmented.
Definition: Syclop.h:181
DecompositionPtr decomp_
The high level decomposition used to focus tree expansion.
Definition: Syclop.h:395
A GridDecomposition is a Decomposition implemented using a grid.
Representation of a motion.
Definition: Syclop.h:257
int numTreeSelections_
The number of calls to selectAndExtend() in the low-level tree planner for a given lead and region...
Definition: Syclop.h:385
int getNumTreeExpansions() const
Get the number of calls to selectAndExtend() in the low-level tree planner for a given lead and regio...
Definition: Syclop.h:209
void clear()
Clears motions and coverage information from this region.
Definition: Syclop.h:295
std::function< void(int, int, std::vector< int > &)> LeadComputeFn
Leads should consist of a path of adjacent regions in the decomposition that start with the start reg...
Definition: Syclop.h:100
int numRegionExpansions_
The number of times a new region will be chosen and promoted for expansion from a given lead...
Definition: Syclop.h:381
A container that supports probabilistic sampling over weighted data.
Definition: PDF.h:48
void clearEdgeCostFactors()
Clears all edge cost factors, making all edge weights equivalent to 1.
Definition: Syclop.cpp:227
void setup() override
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: Syclop.cpp:48
int getNumFreeVolumeSamples() const
Get the number of states to sample when estimating free volume in the Decomposition.
Definition: Syclop.h:153
Main namespace. Contains everything in this library.
Definition: AppBase.h:21
Random number generation. An instance of this class cannot be used by multiple threads at once (membe...
Definition: RandomNumbers.h:58
double getWeight(const Element *elem) const
Returns the current weight of the given Element.
Definition: PDF.h:171
Base class for a planner.
Definition: Planner.h:223
Syclop(const SpaceInformationPtr &si, DecompositionPtr d, const std::string &plannerName)
Constructor. Requires a Decomposition, which Syclop uses to create high-level leads.
Definition: Syclop.h:103
void addEdgeCostFactor(const EdgeCostFactorFn &factor)
Adds an edge cost factor to be used for edge weights between adjacent regions.
Definition: Syclop.cpp:222
bool empty
This value is true if and only if this adjacency&#39;s source and target regions both contain zero tree m...
Definition: Syclop.h:354
std::set< int > covGridCells
The cells of the underlying coverage grid that contain tree motions originating from direct connectio...
Definition: Syclop.h:340
const Region * source
The source region of this adjacency edge.
Definition: Syclop.h:342
std::vector< Motion * > motions
The tree motions contained in this region.
Definition: Syclop.h:305
int getNumRegionExpansions() const
Get the number of times a new region will be chosen and promoted for expansion from a given lead...
Definition: Syclop.h:195
base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc) override
Continues solving until a solution is found or a given planner termination condition is met...
Definition: Syclop.cpp:74
std::function< double(int, int)> EdgeCostFactorFn
Each edge weight between two adjacent regions in the Decomposition is defined as a product of edge co...
Definition: Syclop.h:96
void setProbAbandonLeadEarly(double probability)
The probability that a lead will be abandoned early, before a new region is chosen for expansion...
Definition: Syclop.h:230
double cost
The cost of this adjacency edge, used in lead computations.
Definition: Syclop.h:346
A class to store the exit status of Planner::solve()
Definition: PlannerStatus.h:48
const Region * target
The target region of this adjacency edge.
Definition: Syclop.h:344
Definition of an abstract state.
Definition: State.h:49
double percentValidCells
The percent of free volume of this region.
Definition: Syclop.h:311
const Region & getRegionFromIndex(const int rid) const
Returns a reference to the Region object with the given index. Assumes the index is valid...
Definition: Syclop.h:366
A shared pointer wrapper for ompl::control::SpaceInformation.
virtual void project(const base::State *s, std::vector< double > &coord) const =0
Project a given State to a set of coordinates in R^k, where k is the dimension of this Decomposition...
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:418
double probShortestPath_
The probability that a lead will be computed as a shortest-path instead of a random-DFS.
Definition: Syclop.h:375
double getProbAbandonLeadEarly() const
Get the probability [0,1] that a lead will be abandoned early, before a new region is chosen for expa...
Definition: Syclop.h:223
void update(Element *elem, const double w)
Updates the data in the given Element with a new weight value.
Definition: PDF.h:155
Contains default values for Syclop parameters.
Definition: Syclop.h:237
void setLeadComputeFn(const LeadComputeFn &compute)
Allows the user to override the lead computation function.
Definition: Syclop.cpp:217
void clear() override
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: Syclop.cpp:63
unsigned int numSelections
The number of times this region has been selected for expansion.
Definition: Syclop.h:319
void setNumFreeVolumeSamples(int numSamples)
Set the number of states to sample when estimating free volume in the Decomposition.
Definition: Syclop.h:160
void setProbShortestPathLead(double probability)
Set the probability [0,1] that a lead will be computed as a shortest-path instead of a random-DFS...
Definition: Syclop.h:174
double probKeepAddingToAvail_
The probability that the set of available regions will be augmented.
Definition: Syclop.h:378
A shared pointer wrapper for ompl::control::Decomposition.
void clear()
Clears coverage information from this adjacency.
Definition: Syclop.h:334
double freeVolume
The free volume of this region.
Definition: Syclop.h:309
Space information containing necessary information for planning with controls. setup() needs to be ca...
int numFreeVolSamples_
The number of states to sample to estimate free volume in the Decomposition.
Definition: Syclop.h:372
void setNumTreeExpansions(int treeExpansions)
Set the number of calls to selectAndExtend() in the low-level tree planner for a given lead and regio...
Definition: Syclop.h:216
double probAbandonLeadEarly_
The probability that a lead will be abandoned early, before a new region is chosen for expansion...
Definition: Syclop.h:389
virtual void selectAndExtend(Region &region, std::vector< Motion *> &newMotions)=0
Select a Motion from the given Region, and extend the tree from the Motion. Add any new motions creat...
void setNumRegionExpansions(int regionExpansions)
Set the number of times a new region will be chosen and promoted for expansion from a given lead...
Definition: Syclop.h:202
double weight
The probabilistic weight of this region, used when sampling from PDF.
Definition: Syclop.h:313
virtual Motion * addRoot(const base::State *s)=0
Add State s as a new root in the low-level tree, and return the Motion corresponding to s...
void setProbAddingToAvailableRegions(double probability)
Set the probability [0,1] that the set of available regions will be augmented.
Definition: Syclop.h:188