LTLPlanner.cpp
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright (c) 2012, 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 #include "ompl/control/planners/ltl/LTLPlanner.h"
38 #include "ompl/control/planners/PlannerIncludes.h"
39 #include "ompl/control/planners/ltl/ProductGraph.h"
40 #include "ompl/control/planners/ltl/LTLProblemDefinition.h"
41 #include "ompl/datastructures/PDF.h"
42 #include "ompl/util/Console.h"
43 #include <algorithm>
44 #include <unordered_map>
45 #include <limits>
46 #include <map>
47 #include <vector>
48 
49 #include <stdio.h>
50 
52  ompl::base::Planner(ltlsi, "LTLPlanner"),
53  ltlsi_(ltlsi.get()),
54  abstraction_(a),
55  prodStart_(nullptr),
56  exploreTime_(exploreTime)
57 {
59 }
60 
62 {
63  clearMotions();
64 }
65 
67 {
69 }
70 
72 {
74  availDist_.clear();
75  abstractInfo_.clear();
76  clearMotions();
77 }
78 
80 {
81  // \todo make solve work when called more than once!
82  checkValidity();
83  const base::State* start = pis_.nextStart();
84  prodStart_ = ltlsi_->getProdGraphState(start);
85 
86  if (pis_.haveMoreStartStates())
87  OMPL_WARN("Multiple start states given. Using only the first start state.");
88 
89  Motion* startMotion = new Motion(ltlsi_);
90  si_->copyState(startMotion->state, start);
91  ltlsi_->nullControl(startMotion->control);
92  startMotion->abstractState = prodStart_;
93 
94  motions_.push_back(startMotion);
95  abstractInfo_[prodStart_].addMotion(startMotion);
96  updateWeight(prodStart_);
97  availDist_.add(prodStart_, abstractInfo_[prodStart_].weight);
98 
99  abstraction_->buildGraph(prodStart_,
100  std::bind(&LTLPlanner::initAbstractInfo, this, std::placeholders::_1));
101 
102  if (!sampler_)
103  sampler_ = si_->allocStateSampler();
104  if (!controlSampler_)
105  controlSampler_ = ltlsi_->allocControlSampler();
106 
107  bool solved = false;
108  Motion* soln;
109 
110  while (ptc()==false && !solved)
111  {
112  const std::vector<ProductGraph::State*> lead = abstraction_->computeLead(prodStart_,
113  std::bind(&LTLPlanner::abstractEdgeWeight, this, std::placeholders::_1, std::placeholders::_2));
114  buildAvail(lead);
115  solved = explore(lead, soln, exploreTime_);
116  }
117 
118  if (solved)
119  {
120  //build solution path
121  std::vector<Motion*> path;
122  while (soln != nullptr)
123  {
124  path.push_back(soln);
125  soln = soln->parent;
126  }
127  PathControl* pc = new PathControl(si_);
128  for (int i = path.size()-1; i >= 0; --i)
129  {
130  if (path[i]->parent != nullptr) {
131  pc->append(path[i]->state, path[i]->control, path[i]->steps * ltlsi_->getPropagationStepSize());
132  }
133  else {
134  pc->append(path[i]->state);
135  }
136  }
137  pdef_->addSolutionPath(base::PathPtr(pc));
138  }
139 
140  OMPL_INFORM("Created %u states", motions_.size());
141  return base::PlannerStatus(solved, false);
142 }
143 
144 void ompl::control::LTLPlanner::getTree(std::vector<base::State*>& tree) const
145 {
146  tree.resize(motions_.size());
147  for (unsigned int i = 0; i < motions_.size(); ++i)
148  tree[i] = motions_[i]->state;
149 }
150 
151 std::vector<ompl::control::ProductGraph::State*> ompl::control::LTLPlanner::getHighLevelPath(const std::vector<base::State*>& path, ProductGraph::State* start) const
152 {
153  std::vector<ProductGraph::State*> hlPath(path.size());
154  hlPath[0] = (start != nullptr ? start : ltlsi_->getProdGraphState(path[0]));
155  for (unsigned int i = 1; i < path.size(); ++i)
156  {
157  hlPath[i] = ltlsi_->getProdGraphState(path[i]);
158  if (!hlPath[i]->isValid())
159  OMPL_WARN("High-level path fails automata");
160  }
161  return hlPath;
162 }
163 
164 ompl::control::LTLPlanner::Motion::Motion(void) : state(nullptr), control(nullptr), parent(nullptr), steps(0)
165 {
166 }
167 
169  state(si->allocState()),
170  control(si->allocControl()),
171  parent(nullptr),
172  steps(0)
173 {
174 }
175 
177 {
178 }
179 
181  numSel(0),
182  pdfElem(nullptr)
183 {
184 }
185 
187 {
188  motionElems[m] = motions.add(m, 1.);
189 }
190 
192 {
194  /* \todo weight should include freeVolume, for cases in which decomposition
195  does not respect obstacles. */
196  info.weight = ((info.motions.size()+1)*info.volume) / (info.autWeight*(info.numSel+1)*(info.numSel+1));
197  return info.weight;
198 }
199 
201 {
203  info.numSel = 0;
204  info.pdfElem = nullptr;
205  info.volume = abstraction_->getRegionVolume(as);
206  unsigned int autDist = std::max(abstraction_->getCosafeAutDistance(as),
207  abstraction_->getSafeAutDistance(as));
208  //\todo try something larger than epsilon
209  if (autDist == 0)
210  info.autWeight = std::numeric_limits<double>::epsilon();
211  else
212  info.autWeight = autDist;
213  info.weight = info.volume/info.autWeight;
214 }
215 
216 void ompl::control::LTLPlanner::buildAvail(const std::vector<ProductGraph::State*>& lead)
217 {
218  for (unsigned int i = 0; i < availDist_.size(); ++i)
219  abstractInfo_[availDist_[i]].pdfElem = nullptr;
220  availDist_.clear();
221  unsigned int numTreePts = 1;
222  for (int i = lead.size()-1; i >= 0; --i)
223  {
224  ProductGraph::State* as = lead[i];
226  if (!info.motions.empty())
227  {
228  info.pdfElem = availDist_.add(as, info.weight);
229  numTreePts += info.motions.size();
230  if (rng_.uniform01() < 0.5)
231  break;
232  }
233  }
234 }
235 
236 bool ompl::control::LTLPlanner::explore(const std::vector<ProductGraph::State*>& lead, Motion*& soln, double duration)
237 {
238  bool solved = false;
240  base::GoalPtr goal = pdef_->getGoal();
241  while (!ptc() && !solved)
242  {
244  ++abstractInfo_[as].numSel;
245  updateWeight(as);
246 
247  PDF<Motion*>& motions = abstractInfo_[as].motions;
248  Motion* v = motions.sample(rng_.uniform01());
249  PDF<Motion*>::Element* velem = abstractInfo_[as].motionElems[v];
250  double vweight = motions.getWeight(velem);
251  if (vweight > 1e-20)
252  motions.update(velem, vweight/(vweight+1.));
253 
254  Control* rctrl = ltlsi_->allocControl();
255  controlSampler_->sampleNext(rctrl, v->control, v->state);
256  unsigned int cd = controlSampler_->sampleStepCount(ltlsi_->getMinControlDuration(), ltlsi_->getMaxControlDuration());
257 
258  base::State* newState = si_->allocState();
259  cd = ltlsi_->propagateWhileValid(v->state, rctrl, cd, newState);
260  if (cd < ltlsi_->getMinControlDuration())
261  {
262  si_->freeState(newState);
263  ltlsi_->freeControl(rctrl);
264  continue;
265  }
266  Motion* m = new Motion();
267  m->state = newState;
268  m->control = rctrl;
269  m->steps = cd;
270  m->parent = v;
271  // Since the state was determined to be valid by SpaceInformation, we don't need to check automaton states
272  m->abstractState = ltlsi_->getProdGraphState(m->state);
273  motions_.push_back(m);
274 
275  abstractInfo_[m->abstractState].addMotion(m);
277  // update weight if hl state already exists in avail
278  if (abstractInfo_[m->abstractState].pdfElem != nullptr)
279  availDist_.update(abstractInfo_[m->abstractState].pdfElem, abstractInfo_[m->abstractState].weight);
280  else
281  {
282  // otherwise, only add hl state to avail if it already exists in lead
283  if (std::find(lead.begin(), lead.end(), m->abstractState) != lead.end())
284  {
286  abstractInfo_[m->abstractState].pdfElem = elem;
287  }
288  }
289 
290  solved = goal->isSatisfied(m->state);
291  if (solved)
292  {
293  soln = m;
294  break;
295  }
296  }
297  return solved;
298 }
299 
301 {
302  const ProductGraphStateInfo& infoA = abstractInfo_.find(a)->second;
303  const ProductGraphStateInfo& infoB = abstractInfo_.find(b)->second;
304  return 1./(infoA.weight * infoB.weight);
305 }
306 
307 void ompl::control::LTLPlanner::clearMotions(void)
308 {
309  availDist_.clear();
310  for (std::vector<Motion*>::iterator i = motions_.begin(); i != motions_.end(); ++i)
311  {
312  Motion* m = *i;
313  if (m->state != nullptr)
314  si_->freeState(m->state);
315  if (m->control != nullptr)
316  ltlsi_->freeControl(m->control);
317  delete m;
318  }
319  motions_.clear();
320  pis_.clear();
321  pis_.update();
322 }
bool approximateSolutions
Flag indicating whether the planner is able to compute approximate solutions.
Definition: Planner.h:212
void addMotion(Motion *m)
Adds a tree motion to an info object. This method is called whenever a new tree motion is created in ...
Definition: LTLPlanner.cpp:186
base::State * state
The state contained by the motion.
Definition: LTLPlanner.h:113
unsigned int getMinControlDuration() const
Get the minimum number of steps a control is propagated for.
const LTLSpaceInformation * ltlsi_
Handle to the control::SpaceInformation object.
Definition: LTLPlanner.h:179
Control * allocControl() const
Allocate memory for a control.
std::unordered_map< ProductGraph::State *, ProductGraphStateInfo > abstractInfo_
Map of abstraction states to their details.
Definition: LTLPlanner.h:200
unsigned int propagateWhileValid(const base::State *state, const Control *control, int steps, base::State *result) const
Propagate the model of the system forward, starting at a given state, with a given control...
unsigned int steps
The number of steps for which the control is applied.
Definition: LTLPlanner.h:122
void append(const base::State *state)
Append state to the end of the path; it is assumed state is the first state, so no control is applied...
Definition of an abstract control.
Definition: Control.h:48
virtual void initAbstractInfo(ProductGraph::State *as)
Initializes the info object for a new high-level state.
Definition: LTLPlanner.cpp:200
virtual double updateWeight(ProductGraph::State *as)
Updates and returns the weight of an abstraction state.
Definition: LTLPlanner.cpp:191
std::vector< Motion * > motions_
Set of all motions.
Definition: LTLPlanner.h:191
virtual void clear(void)
Clears all datastructures belonging to this LTLPlanner.
Definition: LTLPlanner.cpp:71
PDF< ProductGraph::State * > availDist_
Used to sample nonempty regions in which to promote expansion.
Definition: LTLPlanner.h:185
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...
Motion(void)
Default constructor for Motion.
Definition: LTLPlanner.cpp:164
virtual void clear()
Clear all internal datastructures. Planner settings are not affected. Subsequent calls to solve() wil...
Definition: Planner.cpp:112
void freeControl(Control *control) const
Free the memory of a control.
Definition of a control path.
Definition: PathControl.h:60
virtual double abstractEdgeWeight(ProductGraph::State *a, ProductGraph::State *b) const
Returns the weight of an edge between two given high-level states, which we compute as the product of...
Definition: LTLPlanner.cpp:300
ProblemDefinitionPtr pdef_
The user set problem definition.
Definition: Planner.h:401
Representation of a motion.
Definition: LTLPlanner.h:98
Control * control
The control contained by the motion.
Definition: LTLPlanner.h:116
A container that supports probabilistic sampling over weighted data.
Definition: PDF.h:48
double uniform01()
Generate a random real between 0 and 1.
Definition: RandomNumbers.h:69
A shared pointer wrapper for ompl::control::LTLSpaceInformation.
ControlSamplerPtr controlSampler_
Control sampler.
Definition: LTLPlanner.h:176
PlannerTerminationCondition timedPlannerTerminationCondition(double duration)
Return a termination condition that will become true duration seconds in the future (wall-time) ...
RNG rng_
A random number generator.
Definition: LTLPlanner.h:188
void clear()
Clear all stored information.
Definition: Planner.cpp:157
virtual void setup()
Perform extra configuration steps, if needed. This call will also issue a call to ompl::base::SpaceIn...
Definition: Planner.cpp:86
A State of a ProductGraph represents a vertex in the graph-based Cartesian product represented by the...
Definition: ProductGraph.h:84
A class to store the exit status of Planner::solve()
Definition: PlannerStatus.h:48
LTLPlanner(const LTLSpaceInformationPtr &si, const ProductGraphPtr &a, double exploreTime=0.5)
Create an LTLPlanner with a given space and product graph. Accepts an optional third parameter to con...
Definition: LTLPlanner.cpp:51
Definition of an abstract state.
Definition: State.h:50
virtual void buildAvail(const std::vector< ProductGraph::State * > &lead)
Compute a set of high-level states along a lead to be considered for expansion.
Definition: LTLPlanner.cpp:216
#define OMPL_WARN(fmt,...)
Log a formatted warning string.
Definition: Console.h:66
PlannerInputStates pis_
Utility class to extract valid input states.
Definition: Planner.h:404
ProductGraphStateInfo(void)
Creates an info object with no measurements and no tree motions.
Definition: LTLPlanner.cpp:180
A class that will hold data contained in the PDF.
Definition: PDF.h:53
void getTree(std::vector< base::State * > &tree) const
Helper debug method to access this planner's underlying tree of states.
Definition: LTLPlanner.cpp:144
ProductGraphPtr abstraction_
The high level abstaction used to grow the tree structure.
Definition: LTLPlanner.h:182
PlannerSpecs specs_
The specifications of the planner (its capabilities)
Definition: Planner.h:410
void update(Element *elem, const double w)
Updates the data in the given Element with a new weight value.
Definition: PDF.h:155
virtual bool explore(const std::vector< ProductGraph::State * > &lead, Motion *&soln, double duration)
Expand the tree of motions along a given lead for a given duration of time. Returns true if a solutio...
Definition: LTLPlanner.cpp:236
bool update()
Set the space information and problem definition this class operates on, based on the available plann...
Definition: Planner.cpp:176
A shared pointer wrapper for ompl::control::ProductGraph.
unsigned int getMaxControlDuration() const
Get the maximum number of steps a control is propagated for.
std::vector< ProductGraph::State * > getHighLevelPath(const std::vector< base::State * > &path, ProductGraph::State *start=nullptr) const
Helper debug method to return the sequence of high-level product graph states corresponding to a sequ...
Definition: LTLPlanner.cpp:151
virtual void setup(void)
Initializes LTLPlanner data structures.
Definition: LTLPlanner.cpp:66
A shared pointer wrapper for ompl::base::Goal.
virtual ~LTLPlanner(void)
Clears all memory belonging to this LTLPlanner .
Definition: LTLPlanner.cpp:61
SpaceInformationPtr si_
The space information for which planning is done.
Definition: Planner.h:398
Space information containing necessary information for planning with controls. setup() needs to be ca...
virtual ~Motion(void)
Motion destructor does not clear memory. Deletions should be performed by the LTLPlanner.
Definition: LTLPlanner.cpp:176
Motion * parent
The parent motion in the tree.
Definition: LTLPlanner.h:119
A structure to hold measurement information for a high-level state, as well as the set of tree motion...
Definition: LTLPlanner.h:131
T * as()
Cast this instance to a desired type.
Definition: Planner.h:248
_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
ProductGraph::State * abstractState
The high-level state to which this motion belongs.
Definition: LTLPlanner.h:125
A shared pointer wrapper for ompl::base::Path.
#define OMPL_INFORM(fmt,...)
Log a formatted information string.
Definition: Console.h:68
virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc)
Continues solving until a solution is found or a given planner termination condition is met...
Definition: LTLPlanner.cpp:79