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