-
Notifications
You must be signed in to change notification settings - Fork 0
/
textGridworldDisplay.py
324 lines (281 loc) · 12.9 KB
/
textGridworldDisplay.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
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
# textGridworldDisplay.py
# -----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import util
from functools import reduce
class TextGridworldDisplay:
def __init__(self, gridworld):
self.gridworld = gridworld
def start(self):
pass
def pause(self):
pass
def displayValues(self, agent, currentState = None, message = None):
if message != None:
print(message)
values = util.Counter()
policy = {}
states = self.gridworld.getStates()
for state in states:
values[state] = agent.getValue(state)
policy[state] = agent.getPolicy(state)
prettyPrintValues(self.gridworld, values, policy, currentState)
def displayNullValues(self, agent, currentState = None, message = None):
if message != None: print(message)
prettyPrintNullValues(self.gridworld, currentState)
def displayQValues(self, agent, currentState = None, message = None):
if message != None: print(message)
qValues = util.Counter()
states = self.gridworld.getStates()
for state in states:
for action in self.gridworld.getPossibleActions(state):
qValues[(state, action)] = agent.getQValue(state, action)
prettyPrintQValues(self.gridworld, qValues, currentState)
def prettyPrintValues(gridWorld, values, policy=None, currentState = None):
grid = gridWorld.grid
maxLen = 11
newRows = []
for y in range(grid.height):
newRow = []
for x in range(grid.width):
state = (x, y)
value = values[state]
action = None
if policy != None and state in policy:
action = policy[state]
actions = gridWorld.getPossibleActions(state)
if action not in actions and 'exit' in actions:
action = 'exit'
valString = None
if action == 'exit':
valString = border('%.2f' % value)
else:
valString = '\n\n%.2f\n\n' % value
valString += ' '*maxLen
if grid[x][y] == 'S':
valString = '\n\nS: %.2f\n\n' % value
valString += ' '*maxLen
if grid[x][y] == '#':
valString = '\n#####\n#####\n#####\n'
valString += ' '*maxLen
pieces = [valString]
text = ("\n".join(pieces)).split('\n')
if currentState == state:
l = len(text[1])
if l == 0:
text[1] = '*'
else:
text[1] = "|" + ' ' * int((l-1)/2-1) + '*' + ' ' * int((l)/2-1) + "|"
if action == 'east':
text[2] = ' ' + text[2] + ' >'
elif action == 'west':
text[2] = '< ' + text[2] + ' '
elif action == 'north':
text[0] = ' ' * int(maxLen/2) + '^' +' ' * int(maxLen/2)
elif action == 'south':
text[4] = ' ' * int(maxLen/2) + 'v' +' ' * int(maxLen/2)
newCell = "\n".join(text)
newRow.append(newCell)
newRows.append(newRow)
numCols = grid.width
for rowNum, row in enumerate(newRows):
row.insert(0,"\n\n"+str(rowNum))
newRows.reverse()
colLabels = [str(colNum) for colNum in range(numCols)]
colLabels.insert(0,' ')
finalRows = [colLabels] + newRows
print(indent(finalRows,separateRows=True,delim='|', prefix='|',postfix='|', justify='center',hasHeader=True))
def prettyPrintNullValues(gridWorld, currentState = None):
grid = gridWorld.grid
maxLen = 11
newRows = []
for y in range(grid.height):
newRow = []
for x in range(grid.width):
state = (x, y)
# value = values[state]
action = None
# if policy != None and state in policy:
# action = policy[state]
#
actions = gridWorld.getPossibleActions(state)
if action not in actions and 'exit' in actions:
action = 'exit'
valString = None
# if action == 'exit':
# valString = border('%.2f' % value)
# else:
# valString = '\n\n%.2f\n\n' % value
# valString += ' '*maxLen
if grid[x][y] == 'S':
valString = '\n\nS\n\n'
valString += ' '*maxLen
elif grid[x][y] == '#':
valString = '\n#####\n#####\n#####\n'
valString += ' '*maxLen
elif type(grid[x][y]) == float or type(grid[x][y]) == int:
valString = border('%.2f' % float(grid[x][y]))
else: valString = border(' ')
pieces = [valString]
text = ("\n".join(pieces)).split('\n')
if currentState == state:
l = len(text[1])
if l == 0:
text[1] = '*'
else:
text[1] = "|" + ' ' * int((l-1)/2-1) + '*' + ' ' * int((l)/2-1) + "|"
if action == 'east':
text[2] = ' ' + text[2] + ' >'
elif action == 'west':
text[2] = '< ' + text[2] + ' '
elif action == 'north':
text[0] = ' ' * int(maxLen/2) + '^' +' ' * int(maxLen/2)
elif action == 'south':
text[4] = ' ' * int(maxLen/2) + 'v' +' ' * int(maxLen/2)
newCell = "\n".join(text)
newRow.append(newCell)
newRows.append(newRow)
numCols = grid.width
for rowNum, row in enumerate(newRows):
row.insert(0,"\n\n"+str(rowNum))
newRows.reverse()
colLabels = [str(colNum) for colNum in range(numCols)]
colLabels.insert(0,' ')
finalRows = [colLabels] + newRows
print(indent(finalRows,separateRows=True,delim='|', prefix='|',postfix='|', justify='center',hasHeader=True))
def prettyPrintQValues(gridWorld, qValues, currentState=None):
grid = gridWorld.grid
maxLen = 11
newRows = []
for y in range(grid.height):
newRow = []
for x in range(grid.width):
state = (x, y)
actions = gridWorld.getPossibleActions(state)
if actions == None or len(actions) == 0:
actions = [None]
bestQ = max([qValues[(state, action)] for action in actions])
bestActions = [action for action in actions if qValues[(state, action)] == bestQ]
# display cell
qStrings = dict([(action, "%.2f" % qValues[(state, action)]) for action in actions])
northString = ('north' in qStrings and qStrings['north']) or ' '
southString = ('south' in qStrings and qStrings['south']) or ' '
eastString = ('east' in qStrings and qStrings['east']) or ' '
westString = ('west' in qStrings and qStrings['west']) or ' '
exitString = ('exit' in qStrings and qStrings['exit']) or ' '
eastLen = len(eastString)
westLen = len(westString)
if eastLen < westLen:
eastString = ' '*(westLen-eastLen)+eastString
if westLen < eastLen:
westString = westString+' '*(eastLen-westLen)
if 'north' in bestActions:
northString = '/'+northString+'\\'
if 'south' in bestActions:
southString = '\\'+southString+'/'
if 'east' in bestActions:
eastString = ''+eastString+'>'
else:
eastString = ''+eastString+' '
if 'west' in bestActions:
westString = '<'+westString+''
else:
westString = ' '+westString+''
if 'exit' in bestActions:
exitString = '[ '+exitString+' ]'
ewString = westString + " " + eastString
if state == currentState:
ewString = westString + " * " + eastString
if state == gridWorld.getStartState():
ewString = westString + " S " + eastString
if state == currentState and state == gridWorld.getStartState():
ewString = westString + " S:* " + eastString
text = [northString, "\n"+exitString, ewString, ' '*maxLen+"\n", southString]
if grid[x][y] == '#':
text = ['', '\n#####\n#####\n#####', '']
newCell = "\n".join(text)
newRow.append(newCell)
newRows.append(newRow)
numCols = grid.width
for rowNum, row in enumerate(newRows):
row.insert(0,"\n\n\n"+str(rowNum))
newRows.reverse()
colLabels = [str(colNum) for colNum in range(numCols)]
colLabels.insert(0,' ')
finalRows = [colLabels] + newRows
print(indent(finalRows,separateRows=True,delim='|',prefix='|',postfix='|', justify='center',hasHeader=True))
def border(text):
length = len(text)
pieces = ['-' * (length+2), '|'+' ' * (length+2)+'|', ' | '+text+' | ', '|'+' ' * (length+2)+'|','-' * (length+2)]
return '\n'.join(pieces)
# INDENTING CODE
# Indenting code based on a post from George Sakkis
# (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662)
import io,operator
def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
"""Indents a table by column.
- rows: A sequence of sequences of items, one sequence per row.
- hasHeader: True if the first row consists of the columns' names.
- headerChar: Character to be used for the row separator line
(if hasHeader==True or separateRows==True).
- delim: The column delimiter.
- justify: Determines how are data justified in their column.
Valid values are 'left','right' and 'center'.
- separateRows: True if rows are to be separated by a line
of 'headerChar's.
- prefix: A string prepended to each printed row.
- postfix: A string appended to each printed row.
- wrapfunc: A function f(text) for wrapping text; each element in
the table is first wrapped by this function."""
# closure for breaking logical rows to physical, using wrapfunc
def rowWrapper(row):
newRows = [wrapfunc(item).split('\n') for item in row]
return [[substr or '' for substr in item] for item in list(*newRows)]
# break each logical row into one or more physical ones
logicalRows = [rowWrapper(row) for row in rows]
# columns of physical rows
columns = list(*reduce(operator.add,logicalRows))
# get the maximum of each column by the string length of its items
maxWidths = [max([len(str(item)) for item in column]) for column in columns]
rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
len(delim)*(len(maxWidths)-1))
# select the appropriate justify method
justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
output=io.StringIO()
if separateRows: print(rowSeparator, file=output)
for physicalRows in logicalRows:
for row in physicalRows:
print(prefix \
+ delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
+ postfix, file=output)
if separateRows or hasHeader: print(rowSeparator, file=output); hasHeader=False
return output.getvalue()
import math
def wrap_always(text, width):
"""A simple word-wrap function that wraps text on exactly width characters.
It doesn't split the text in words."""
return '\n'.join([ text[width*i:width*(i+1)] \
for i in range(int(math.ceil(1.*len(text)/width))) ])
# TEST OF DISPLAY CODE
if __name__ == '__main__':
import gridworld, util
grid = gridworld.getCliffGrid3()
print(grid.getStates())
policy = dict([(state,'east') for state in grid.getStates()])
values = util.Counter(dict([(state,1000.23) for state in grid.getStates()]))
prettyPrintValues(grid, values, policy, currentState = (0,0))
stateCrossActions = [[(state, action) for action in grid.getPossibleActions(state)] for state in grid.getStates()]
qStates = reduce(lambda x,y: x+y, stateCrossActions, [])
qValues = util.Counter(dict([((state, action), 10.5) for state, action in qStates]))
qValues = util.Counter(dict([((state, action), 10.5) for state, action in reduce(lambda x,y: x+y, stateCrossActions, [])]))
prettyPrintQValues(grid, qValues, currentState = (0,0))