-
Notifications
You must be signed in to change notification settings - Fork 0
/
drone.py
283 lines (256 loc) · 6.97 KB
/
drone.py
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
# Patrolling drone demo of reactive control improvisation
# by Daniel J. Fremont
from collections import defaultdict
import random
import itertools
import time
import sys
import reactive
from DFALib import DFA, ExplicitDFA
k = 7
alphabet = { (1,0), (-1,0), (0,1), (0,-1) }
clamp = lambda x: max(0, min(k-1, x))
low = k // 3
mid = k // 2
high = (2 * k) // 3
assert low < mid
assert mid < high
targets = ((low, low), (low, high), (high, low), (high, high))
advNoFly = set(targets) | { (mid, mid) }
#print(targets)
#print(advNoFly)
def initialStateFor(mpos, apos):
return (tuple(mpos), tuple(apos), 0, tuple(False for t in targets))
def spec(advPos, disallowRepeats=False):
numLocs = len(targets)
failure = 0
success = 1
baseStates = set(
itertools.product(
itertools.product(range(k), repeat=2),
itertools.product(range(k), repeat=2),
range(2),
itertools.product((False, True), repeat=numLocs)
)
)
states = baseStates | { failure, success }
accepting = { success }
initial = ((0, 0), advPos, 0, tuple(False for i in range(numLocs)))
delta = defaultdict(dict)
for mx, my in itertools.product(range(k), repeat=2):
for ax, ay in itertools.product(range(k), repeat=2):
for p in range(2):
for v in itertools.product((False, True), repeat=numLocs):
t = [(mx, my), (ax, ay), p, v]
state = tuple(t)
loc = state[p]
transitions = delta[state]
for symbol in alphabet:
dx, dy = symbol
newLoc = (clamp(loc[0] + dx), clamp(loc[1] + dy))
o = 1 - p
if p == 1 and newLoc in advNoFly: # adv made illegal move
transitions[symbol] = success
elif t[o] == newLoc: # collision
transitions[symbol] = failure
else:
t[p] = newLoc
t[2] = o
fail = False
if p == 0:
for index, target in enumerate(targets):
if disallowRepeats and newLoc == target and v[index]:
fail = True
break
if loc == target:
nv = list(v)
nv[index] = True
t[3] = tuple(nv)
break
transitions[symbol] = failure if fail else tuple(t)
if all(v):
accepting.add(state)
tf = delta[failure]
ts = delta[success]
for symbol in alphabet:
tf[symbol] = failure
ts[symbol] = success
return ExplicitDFA(alphabet, states, accepting, initial, delta)
def createImpro(n=40, advPos=(k-1, k-1), verbose=False):
if verbose:
print('Generating improviser for n='+str(n)+'... (may take a minute)')
hard = spec(advPos)
soft = spec(advPos, disallowRepeats=True)
res = reactive.generate(alphabet, n, hard, soft, epsilon=0.25, softIncludesHard=True)
if res == None:
raise Exception('RCI instance infeasible')
impro, mi, ma, ropt, eopt, alpha, beta = res
if verbose:
print('Generated improviser achieving rho='+str(ropt)+', epsilon='+str(eopt))
print('W(I) = '+str(mi)+', W(A) = '+str(ma))
print('alpha = '+str(alpha)+', beta = '+str(beta))
return impro
def runAgainst(impro, adversary, advPos=(k-1, k-1), replanner=None):
it = impro()
mw = []
aw = []
w = []
mtraj = []
atraj = []
mpos = [0, 0]
apos = list(advPos)
mtraj.append(tuple(mpos))
atraj.append(advPos)
step = None
while True:
try:
step = it.send(step)
step = step[0]
mpos[0] = clamp(mpos[0] + step[0])
mpos[1] = clamp(mpos[1] + step[1])
mw.append(step)
w.append(step)
mtraj.append(tuple(mpos))
step = adversary(mpos, apos)
apos[0] = clamp(apos[0] + step[0])
apos[1] = clamp(apos[1] + step[1])
aw.append(step)
w.append(step)
atraj.append(tuple(apos))
except StopIteration:
proceed = False
if replanner != None:
it = replanner(mpos, apos)
if it != None:
proceed = True
step = None
if not proceed:
return (mw, aw, w, mtraj, atraj)
def loopAdvTester(n=60):
lb = low - 1
hb = high + 1
assert lb >= 0 and hb < k
advPos = (hb, hb)
def loopAdv(mpos, apos):
x, y = apos
if x == lb:
return (1, 0) if y == hb else (0, 1)
elif x == hb:
return (-1, 0) if y == lb else (0, -1)
elif y == lb:
return (-1, 0)
elif y == hb:
return (1, 0)
else:
assert 0
impro = createImpro(n, advPos, verbose=True)
return lambda: runAgainst(impro, loopAdv, advPos)
def chaseAdv(mpos, apos):
directions = [ (-1, 0), (0, -1), (1, 0), (0, 1) ]
def dist(ax, ay):
dx = mpos[0] - ax
dy = mpos[1] - ay
return abs(dx) + abs(dy)
x, y = apos
bestDir = None
bestDist = 1000
for d in directions:
nx = clamp(x + d[0])
ny = clamp(y + d[1])
if (nx, ny) not in advNoFly:
dt = dist(nx, ny)
if dt < bestDist:
bestDir = d
bestDist = dt
assert bestDir != None
return bestDir
def chaseAdvTester(n=60):
impro = createImpro(n, verbose=True)
return lambda: runAgainst(impro, chaseAdv)
def humanAdv(mpos, apos):
direction = {
'a': (-1,0),
'd': (1,0),
'w': (0,1),
's': (0,-1)
}
printGrid(mpos, apos)
d = input()
while d not in direction:
print('valid directions are: ', sorted(direction.keys()))
d = input()
return direction[d]
def printGrid(mpos, apos):
for y in range(k-1, -1, -1):
for x in range(k):
pos = [x, y]
if pos == mpos:
print('R', end='')
elif pos == apos:
print('A', end='')
elif tuple(pos) in advNoFly:
print('X', end='')
else:
print('.', end='')
print()
def interactiveTest(n=60):
advPos = (k-1, k-1)
impro = createImpro(n, advPos)
runAgainst(impro, humanAdv, advPos)
def gazeboPosition(pos):
workspaceSize = 10 # +/- from origin
x, y = pos
center = (k - 1) / 2.0
scale = lambda o: (o - center) * (workspaceSize / center)
return (scale(x), scale(y), 10)
def dumpPath(path, id=''):
with open('path'+str(id)+'.txt', 'w') as out:
for pos in path:
x, y, z = gazeboPosition(pos)
out.write(str(x)+' '+str(y)+' '+str(z)+'\n')
def genPaths(tester, paths=10):
for i in range(paths):
mw, aw, w, mtraj, atraj = tester()
dumpPath(mtraj, i)
dumpPath(atraj, str(i)+'a')
def humanDemo():
n = 60
assert n % 2 == 0 # so replanning doesn't skip someone's turn
advPos = (k-1, k-1)
impro = createImpro(n, advPos, verbose=True)
def replanner(mpos, apos):
while True:
a = input('Window completed. Continue playing? (y/n) ')
if a == 'y':
break
elif a == 'n':
return None
print('Replanning from current state.')
state = initialStateFor(mpos, apos)
return impro(si=state, sa=state, k=0)
print('Running improviser R against human adversary A.')
print('Use WASD keys + enter to move.')
print('Moving onto an X will violate an assumption.')
runAgainst(impro, humanAdv, advPos, replanner)
def usage():
print('USAGE: python3 drone.py (chase | loop | human) [seed] [numPaths]')
if __name__ == "__main__":
argc = len(sys.argv)
if argc < 2 or argc > 4 or sys.argv[1] in ('-h', '--help'):
usage()
else:
adv = sys.argv[1]
seed = int(sys.argv[2]) if argc > 2 else None
numPaths = int(sys.argv[3]) if argc > 3 else 1
random.seed(seed)
tester = None
if adv == 'chase':
tester = chaseAdvTester()
elif adv == 'loop':
tester = loopAdvTester()
elif adv == 'human':
humanDemo()
else:
usage()
if tester is not None:
genPaths(tester, paths=numPaths)