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