File: test_control.py

package info (click to toggle)
ompl 1.1.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 37,164 kB
  • ctags: 8,045
  • sloc: cpp: 55,692; python: 3,843; sh: 147; makefile: 60
file content (346 lines) | stat: -rwxr-xr-x 12,055 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python

######################################################################
# Software License Agreement (BSD License)
#
#  Copyright (c) 2010, Rice University
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above
#     copyright notice, this list of conditions and the following
#     disclaimer in the documentation and/or other materials provided
#     with the distribution.
#   * Neither the name of the Rice University nor the names of its
#     contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
######################################################################

# Author: Mark Moll

import sys
from os.path import abspath, dirname, join
sys.path.insert(0, join(dirname(dirname(dirname(abspath(__file__)))),'py-bindings') )
from functools import partial
from os.path import dirname
from time import clock
from math import fabs
import unittest
import copy
import ompl.util as ou
import ompl.base as ob
import ompl.control as oc
from ompl.util import setLogLevel, LogLevel

SOLUTION_TIME = 10.0
MAX_VELOCITY = 3.0

class Environment(object):
    def __init__(self, fname):
        fp = open(fname, 'r')
        lines = fp.readlines()
        fp.close()
        self.width, self.height = [int(i) for i in lines[0].split(' ')[1:3]]
        self.grid = []
        self.start = [int(i) for i in lines[1].split(' ')[1:3]]
        self.goal = [int(i) for i in lines[2].split(' ')[1:3]]
        for i in range(self.width):
            self.grid.append(
                [int(i) for i in lines[4+i].split(' ')[0:self.height]])
        self.char_mapping = ['__', '##', 'oo', 'XX']

    def __str__(self):
        result = ''
        for line in self.grid:
            result = result + ''.join([self.char_mapping[c] for c in line]) + '\n'
        return result

def isValid(grid, state):
    # planning is done in a continuous space, but our collision space
    # representation is discrete
    x = int(state[0])
    y = int(state[1])
    if x<0 or y<0 or x>=len(grid) or y>=len(grid[0]):
        return False
    return grid[x][y] == 0 # 0 means valid state

class MyStateSpace(ob.RealVectorStateSpace):
    def __init__(self):
        super(MyStateSpace, self).__init__(4)

    def distance(self, state1, state2):
        x1 = int(state1[0])
        y1 = int(state1[1])
        x2 = int(state2[0])
        y2 = int(state2[1])
        return fabs(x1-x2) + fabs(y1-y2)

class MyProjectionEvaluator(ob.ProjectionEvaluator):
    def __init__(self, space, cellSizes):
        super(MyProjectionEvaluator, self).__init__(space)
        self.setCellSizes(cellSizes)

    def getDimension(self):
        return 2

    def project(self, state, projection):
        projection[0] = state[0]
        projection[1] = state[1]

class MyStatePropagator(oc.StatePropagator):
    def __init__(self, spaceInformation):
        super(MyStatePropagator, self).__init__(spaceInformation)

    def propagate(self, state, control, duration, result):
        result[0] = state[0] + duration*control[0]
        result[1] = state[1] + duration*control[1]
        result[2] = control[0]
        result[3] = control[1]

class TestPlanner(object):

    def execute(self, env, time, pathLength, show = False):
        result = True

        sSpace = MyStateSpace()
        sbounds = ob.RealVectorBounds(4)
        # dimension 0 (x) spans between [0, width)
        # dimension 1 (y) spans between [0, height)
        # since sampling is continuous and we round down, we allow values until
        # just under the max limit
        # the resolution is 1.0 since we check cells only
        sbounds.low = ou.vectorDouble()
        sbounds.low.extend([0.0, 0.0, -MAX_VELOCITY, -MAX_VELOCITY])
        sbounds.high = ou.vectorDouble()
        sbounds.high.extend([float(env.width) - 0.000000001,
            float(env.height) - 0.000000001,
            MAX_VELOCITY, MAX_VELOCITY])
        sSpace.setBounds(sbounds)

        cSpace = oc.RealVectorControlSpace(sSpace, 2)
        cbounds = ob.RealVectorBounds(2)
        cbounds.low[0] = -MAX_VELOCITY
        cbounds.high[0] = MAX_VELOCITY
        cbounds.low[1] = -MAX_VELOCITY
        cbounds.high[1] = MAX_VELOCITY
        cSpace.setBounds(cbounds)

        ss = oc.SimpleSetup(cSpace)
        isValidFn = ob.StateValidityCheckerFn(partial(isValid, env.grid))
        ss.setStateValidityChecker(isValidFn)
        propagator = MyStatePropagator(ss.getSpaceInformation())
        ss.setStatePropagator(propagator)

        planner = self.newplanner(ss.getSpaceInformation())
        ss.setPlanner(planner)

        # the initial state
        start = ob.State(sSpace)
        start()[0] = env.start[0]
        start()[1] = env.start[1]
        start()[2] = 0.0
        start()[3] = 0.0

        goal = ob.State(sSpace)
        goal()[0] = env.goal[0]
        goal()[1] = env.goal[1]
        goal()[2] = 0.0
        goal()[3] = 0.0

        ss.setStartAndGoalStates(start, goal, 0.05)

        startTime = clock()
        if ss.solve(SOLUTION_TIME):
            elapsed = clock() - startTime
            time = time + elapsed
            if show:
                print('Found solution in %f seconds!' % elapsed)

            path = ss.getSolutionPath()
            path.interpolate()
            if not path.check():
                return (False, time, pathLength)
            pathLength = pathLength + path.length()

            if show:
                print(env, '\n')
                temp = copy.deepcopy(env)
                for i in range(len(path.states)):
                    x = int(path.states[i][0])
                    y = int(path.states[i][1])
                    if temp.grid[x][y] in [0,2]:
                        temp.grid[x][y] = 2
                    else:
                        temp.grid[x][y] = 3
                print(temp, '\n')
        else:
            result = False

        return (result, time, pathLength)

    def newPlanner(si):
        raise NotImplementedError('pure virtual method')

class RRTTest(TestPlanner):
    def newplanner(self, si):
        planner = oc.RRT(si)
        return planner

class ESTTest(TestPlanner):
    def newplanner(self, si):
        planner = oc.EST(si)
        cdim = ou.vectorDouble()
        cdim.extend([1, 1])
        ope = MyProjectionEvaluator(si.getStateSpace(), cdim)
        planner.setProjectionEvaluator(ope)
        return planner

class SyclopDecomposition(oc.GridDecomposition):
    def __init__(self, len, bounds):
        super(SyclopDecomposition, self).__init__(len, 2, bounds)

    def project(self, state, coord):
        coord[0] = state[0]
        coord[1] = state[1]

    def sampleFullState(self, sampler, coord, s):
        sampler.sampleUniform(s)
        s[0] = coord[0]
        s[1] = coord[1]

class SyclopRRTTest(TestPlanner):
    def newplanner(self, si):
        spacebounds = si.getStateSpace().getBounds()

        bounds = ob.RealVectorBounds(2)
        bounds.setLow(0, spacebounds.low[0]);
        bounds.setLow(1, spacebounds.low[1]);
        bounds.setHigh(0, spacebounds.high[0]);
        bounds.setHigh(1, spacebounds.high[1]);

        # Create a 10x10 grid decomposition for Syclop
        decomp = SyclopDecomposition(10, bounds)
        planner = oc.SyclopRRT(si, decomp)
        # Set syclop parameters conducive to a tiny workspace
        planner.setNumFreeVolumeSamples(1000)
        planner.setNumRegionExpansions(10)
        planner.setNumTreeExpansions(5)
        return planner

class SyclopESTTest(TestPlanner):
    def newplanner(self, si):
        spacebounds = si.getStateSpace().getBounds()

        bounds = ob.RealVectorBounds(2)
        bounds.setLow(0, spacebounds.low[0]);
        bounds.setLow(1, spacebounds.low[1]);
        bounds.setHigh(0, spacebounds.high[0]);
        bounds.setHigh(1, spacebounds.high[1]);

        # Create a 10x10 grid decomposition for Syclop
        decomp = SyclopDecomposition(10, bounds)
        planner = oc.SyclopEST(si, decomp)
        # Set syclop parameters conducive to a tiny workspace
        planner.setNumFreeVolumeSamples(1000)
        planner.setNumRegionExpansions(10)
        planner.setNumTreeExpansions(5)
        return planner

class KPIECE1Test(TestPlanner):
    def newplanner(self, si):
        planner = oc.KPIECE1(si)
        cdim = ou.vectorDouble()
        cdim.extend([1, 1])
        ope = MyProjectionEvaluator(si.getStateSpace(), cdim)
        planner.setProjectionEvaluator(ope)
        return planner

class PlanTest(unittest.TestCase):
    def setUp(self):
        self.env = Environment(dirname(abspath(__file__))+'/../../tests/resources/env1.txt')
        if self.env.width * self.env.height == 0:
            self.fail('The environment has a 0 dimension. Cannot continue')
        self.verbose = True

    def runPlanTest(self, planner):
        time = 0.0
        length = 0.0
        good = 0
        N = 25

        for i in range(N):
            (result, time, length) = planner.execute(self.env, time, length, False)
            if result: good = good + 1

        success = 100.0 * float(good) / float(N)
        avgruntime = time / float(N)
        avglength = length / float(N)

        if self.verbose:
            print('    Success rate: %f%%' % success)
            print('    Average runtime: %f' % avgruntime)
            print('    Average path length: %f' % avglength)

        return (success, avgruntime, avglength)

    def testControl_RRT(self):
        planner = RRTTest()
        (success, avgruntime, avglength) = self.runPlanTest(planner)
        self.assertTrue(success >= 99.0)
        self.assertTrue(avgruntime < 5)
        self.assertTrue(avglength < 100.0)

    def testControl_EST(self):
        planner = ESTTest()
        (success, avgruntime, avglength) = self.runPlanTest(planner)
        self.assertTrue(success >= 99.0)
        self.assertTrue(avgruntime < 5)
        self.assertTrue(avglength < 100.0)

    def testControl_KPIECE1(self):
        planner = KPIECE1Test()
        (success, avgruntime, avglength) = self.runPlanTest(planner)
        self.assertTrue(success >= 99.0)
        self.assertTrue(avgruntime < 2.5)
        self.assertTrue(avglength < 100.0)

    def testControl_SyclopRRT(self):
        planner = SyclopRRTTest()
        (success, avgruntime, avglength) = self.runPlanTest(planner)
        self.assertTrue(success >= 99.0)
        self.assertTrue(avgruntime < 2.5)
        self.assertTrue(avglength < 100.0)

    def testControl_SyclopEST(self):
        planner = SyclopESTTest()
        (success, avgruntime, avglength) = self.runPlanTest(planner)
        self.assertTrue(success >= 99.0)
        self.assertTrue(avgruntime < 2.5)
        self.assertTrue(avglength < 100.0)


def suite():
    suites = ( unittest.makeSuite(PlanTest) )
    return unittest.TestSuite(suites)

if __name__ == '__main__':
    setLogLevel(LogLevel.LOG_ERROR)
    unittest.main()