Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

util.py 15 KB

You have to be logged in to leave a comment. Sign In
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
  1. # util.py
  2. # -------
  3. # Licensing Information: Please do not distribute or publish solutions to this
  4. # project. You are free to use and extend these projects for educational
  5. # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
  6. # John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
  7. # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
  8. import sys
  9. import inspect
  10. import heapq, random
  11. """
  12. Data structures useful for implementing SearchAgents
  13. """
  14. class Stack:
  15. "A container with a last-in-first-out (LIFO) queuing policy."
  16. def __init__(self):
  17. self.list = []
  18. def push(self, item):
  19. "Push 'item' onto the stack"
  20. self.list.append(item)
  21. def pop(self):
  22. "Pop the most recently pushed item from the stack"
  23. return self.list.pop()
  24. def isEmpty(self):
  25. "Returns true if the stack is empty"
  26. return len(self.list) == 0
  27. class Queue:
  28. "A container with a first-in-first-out (FIFO) queuing policy."
  29. def __init__(self):
  30. self.list = []
  31. def push(self, item):
  32. "Enqueue the 'item' into the queue"
  33. self.list.insert(0, item)
  34. def pop(self):
  35. """
  36. Dequeue the earliest enqueued item still in the queue. This
  37. operation removes the item from the queue.
  38. """
  39. return self.list.pop()
  40. def isEmpty(self):
  41. "Returns true if the queue is empty"
  42. return len(self.list) == 0
  43. class PriorityQueue:
  44. """
  45. Implements a priority queue data structure. Each inserted item
  46. has a priority associated with it and the client is usually interested
  47. in quick retrieval of the lowest-priority item in the queue. This
  48. data structure allows O(1) access to the lowest-priority item.
  49. Note that this PriorityQueue does not allow you to change the priority
  50. of an item. However, you may insert the same item multiple times with
  51. different priorities.
  52. """
  53. def __init__(self):
  54. self.heap = []
  55. self.init = False
  56. def push(self, item, priority):
  57. if not self.init:
  58. self.init = True
  59. try:
  60. item < item
  61. except:
  62. item.__class__.__lt__ = lambda x, y: (True)
  63. pair = (priority, item)
  64. heapq.heappush(self.heap, pair)
  65. def pop(self):
  66. (priority, item) = heapq.heappop(self.heap)
  67. return item
  68. def isEmpty(self):
  69. return len(self.heap) == 0
  70. class PriorityQueueWithFunction(PriorityQueue):
  71. """
  72. Implements a priority queue with the same push/pop signature of the
  73. Queue and the Stack classes. This is designed for drop-in replacement for
  74. those two classes. The caller has to provide a priority function, which
  75. extracts each item's priority.
  76. """
  77. def __init__(self, priorityFunction):
  78. "priorityFunction (item) -> priority"
  79. self.priorityFunction = priorityFunction # store the priority function
  80. PriorityQueue.__init__(self) # super-class initializer
  81. def push(self, item):
  82. "Adds an item to the queue with priority from the priority function"
  83. PriorityQueue.push(self, item, self.priorityFunction(item))
  84. def manhattanDistance(xy1, xy2):
  85. "Returns the Manhattan distance between points xy1 and xy2"
  86. return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
  87. """
  88. Data structures and functions useful for various course projects
  89. The search project should not need anything below this line.
  90. """
  91. class Counter(dict):
  92. """
  93. A counter keeps track of counts for a set of keys.
  94. The counter class is an extension of the standard python
  95. dictionary type. It is specialized to have number values
  96. (integers or floats), and includes a handful of additional
  97. functions to ease the task of counting data. In particular,
  98. all keys are defaulted to have value 0. Using a dictionary:
  99. a = {}
  100. print(a['test'])
  101. would give an error, while the Counter class analogue:
  102. >>> a = Counter()
  103. >>> print(a['test'])
  104. 0
  105. returns the default 0 value. Note that to reference a key
  106. that you know is contained in the counter,
  107. you can still use the dictionary syntax:
  108. >>> a = Counter()
  109. >>> a['test'] = 2
  110. >>> print(a['test'])
  111. 2
  112. This is very useful for counting things without initializing their counts,
  113. see for example:
  114. >>> a['blah'] += 1
  115. >>> print(a['blah'])
  116. 1
  117. The counter also includes additional functionality useful in implementing
  118. the classifiers for this assignment. Two counters can be added,
  119. subtracted or multiplied together. See below for details. They can
  120. also be normalized and their total count and arg max can be extracted.
  121. """
  122. def __getitem__(self, idx):
  123. self.setdefault(idx, 0)
  124. return dict.__getitem__(self, idx)
  125. def incrementAll(self, keys, count):
  126. """
  127. Increments all elements of keys by the same count.
  128. >>> a = Counter()
  129. >>> a.incrementAll(['one','two', 'three'], 1)
  130. >>> a['one']
  131. 1
  132. >>> a['two']
  133. 1
  134. """
  135. for key in keys:
  136. self[key] += count
  137. def argMax(self):
  138. """
  139. Returns the key with the highest value.
  140. """
  141. if len(self.keys()) == 0: return None
  142. all = list(self.items())
  143. values = [x[1] for x in all]
  144. maxIndex = values.index(max(values))
  145. return all[maxIndex][0]
  146. def sortedKeys(self):
  147. """
  148. Returns a list of keys sorted by their values. Keys
  149. with the highest values will appear first.
  150. >>> a = Counter()
  151. >>> a['first'] = -2
  152. >>> a['second'] = 4
  153. >>> a['third'] = 1
  154. >>> a.sortedKeys()
  155. ['second', 'third', 'first']
  156. """
  157. sortedItems = list(self.items())
  158. sortedItems.sort(key=lambda item: -item[1])
  159. return [x[0] for x in sortedItems]
  160. def totalCount(self):
  161. """
  162. Returns the sum of counts for all keys.
  163. """
  164. return sum(self.values())
  165. def normalize(self):
  166. """
  167. Edits the counter such that the total count of all
  168. keys sums to 1. The ratio of counts for all keys
  169. will remain the same. Note that normalizing an empty
  170. Counter will result in an error.
  171. """
  172. total = float(self.totalCount())
  173. if total == 0: return
  174. for key in self.keys():
  175. self[key] = self[key] / total
  176. def divideAll(self, divisor):
  177. """
  178. Divides all counts by divisor
  179. """
  180. divisor = float(divisor)
  181. for key in self:
  182. self[key] /= divisor
  183. def copy(self):
  184. """
  185. Returns a copy of the counter
  186. """
  187. return Counter(dict.copy(self))
  188. def __mul__(self, y):
  189. """
  190. Multiplying two counters gives the dot product of their vectors where
  191. each unique label is a vector element.
  192. >>> a = Counter()
  193. >>> b = Counter()
  194. >>> a['first'] = -2
  195. >>> a['second'] = 4
  196. >>> b['first'] = 3
  197. >>> b['second'] = 5
  198. >>> a['third'] = 1.5
  199. >>> a['fourth'] = 2.5
  200. >>> a * b
  201. 14
  202. """
  203. sum = 0
  204. x = self
  205. if len(x) > len(y):
  206. x, y = y, x
  207. for key in x:
  208. if key not in y:
  209. continue
  210. sum += x[key] * y[key]
  211. return sum
  212. def __radd__(self, y):
  213. """
  214. Adding another counter to a counter increments the current counter
  215. by the values stored in the second counter.
  216. >>> a = Counter()
  217. >>> b = Counter()
  218. >>> a['first'] = -2
  219. >>> a['second'] = 4
  220. >>> b['first'] = 3
  221. >>> b['third'] = 1
  222. >>> a += b
  223. >>> a['first']
  224. 1
  225. """
  226. for key, value in y.items():
  227. self[key] += value
  228. def __add__(self, y):
  229. """
  230. Adding two counters gives a counter with the union of all keys and
  231. counts of the second added to counts of the first.
  232. >>> a = Counter()
  233. >>> b = Counter()
  234. >>> a['first'] = -2
  235. >>> a['second'] = 4
  236. >>> b['first'] = 3
  237. >>> b['third'] = 1
  238. >>> (a + b)['first']
  239. 1
  240. """
  241. addend = Counter()
  242. for key in self:
  243. if key in y:
  244. addend[key] = self[key] + y[key]
  245. else:
  246. addend[key] = self[key]
  247. for key in y:
  248. if key in self:
  249. continue
  250. addend[key] = y[key]
  251. return addend
  252. def __sub__(self, y):
  253. """
  254. Subtracting a counter from another gives a counter with the union of all keys and
  255. counts of the second subtracted from counts of the first.
  256. >>> a = Counter()
  257. >>> b = Counter()
  258. >>> a['first'] = -2
  259. >>> a['second'] = 4
  260. >>> b['first'] = 3
  261. >>> b['third'] = 1
  262. >>> (a - b)['first']
  263. -5
  264. """
  265. addend = Counter()
  266. for key in self:
  267. if key in y:
  268. addend[key] = self[key] - y[key]
  269. else:
  270. addend[key] = self[key]
  271. for key in y:
  272. if key in self:
  273. continue
  274. addend[key] = -1 * y[key]
  275. return addend
  276. def raiseNotDefined():
  277. print("Method not implemented: %s" % inspect.stack()[1][3])
  278. sys.exit(1)
  279. def normalize(vectorOrCounter):
  280. """
  281. normalize a vector or counter by dividing each value by the sum of all values
  282. """
  283. normalizedCounter = Counter()
  284. if type(vectorOrCounter) == type(normalizedCounter):
  285. counter = vectorOrCounter
  286. total = float(counter.totalCount())
  287. if total == 0: return counter
  288. for key in counter.keys():
  289. value = counter[key]
  290. normalizedCounter[key] = value / total
  291. return normalizedCounter
  292. else:
  293. vector = vectorOrCounter
  294. s = float(sum(vector))
  295. if s == 0: return vector
  296. return [el / s for el in vector]
  297. def nSample(distribution, values, n):
  298. if sum(distribution) != 1:
  299. distribution = normalize(distribution)
  300. rand = [random.random() for i in range(n)]
  301. rand.sort()
  302. samples = []
  303. samplePos, distPos, cdf = 0, 0, distribution[0]
  304. while samplePos < n:
  305. if rand[samplePos] < cdf:
  306. samplePos += 1
  307. samples.append(values[distPos])
  308. else:
  309. distPos += 1
  310. cdf += distribution[distPos]
  311. return samples
  312. def sample(distribution, values=None):
  313. if type(distribution) == Counter:
  314. items = distribution.items()
  315. distribution = [i[1] for i in items]
  316. values = [i[0] for i in items]
  317. if sum(distribution) != 1:
  318. distribution = normalize(distribution)
  319. choice = random.random()
  320. i, total = 0, distribution[0]
  321. while choice > total:
  322. i += 1
  323. total += distribution[i]
  324. return values[i]
  325. def sampleFromCounter(ctr):
  326. items = ctr.items()
  327. return sample([v for k, v in items], [k for k, v in items])
  328. def getProbability(value, distribution, values):
  329. """
  330. Gives the probability of a value under a discrete distribution
  331. defined by (distributions, values).
  332. """
  333. total = 0.0
  334. for prob, val in zip(distribution, values):
  335. if val == value:
  336. total += prob
  337. return total
  338. def flipCoin(p):
  339. r = random.random()
  340. return r < p
  341. def chooseFromDistribution(distribution):
  342. """
  343. Takes either a counter or a list of (prob, key) pairs and samples
  344. """
  345. if type(distribution) == dict or type(distribution) == Counter:
  346. return sample(distribution)
  347. r = random.random()
  348. base = 0.0
  349. for prob, element in distribution:
  350. base += prob
  351. if r <= base: return element
  352. def nearestPoint(pos):
  353. """
  354. Finds the nearest grid point to a position (discretizes).
  355. """
  356. (current_row, current_col) = pos
  357. grid_row = int(current_row + 0.5)
  358. grid_col = int(current_col + 0.5)
  359. return (grid_row, grid_col)
  360. def sign(x):
  361. """
  362. Returns 1 or -1 depending on the sign of x
  363. """
  364. if (x >= 0):
  365. return 1
  366. else:
  367. return -1
  368. def arrayInvert(array):
  369. """
  370. Inverts a matrix stored as a list of lists.
  371. """
  372. result = [[] for i in array]
  373. for outer in array:
  374. for inner in range(len(outer)):
  375. result[inner].append(outer[inner])
  376. return result
  377. def matrixAsList(matrix, value=True):
  378. """
  379. Turns a matrix into a list of coordinates matching the specified value
  380. """
  381. rows, cols = len(matrix), len(matrix[0])
  382. cells = []
  383. for row in range(rows):
  384. for col in range(cols):
  385. if matrix[row][col] == value:
  386. cells.append((row, col))
  387. return cells
  388. def lookup(name, namespace):
  389. """
  390. Get a method or class from any imported module from its name.
  391. Usage: lookup(functionName, globals())
  392. """
  393. dots = name.count('.')
  394. if dots > 0:
  395. moduleName, objName = '.'.join(name.split('.')[:-1]), name.split('.')[-1]
  396. module = __import__(moduleName)
  397. return getattr(module, objName)
  398. else:
  399. modules = [obj for obj in namespace.values() if str(type(obj)) == "<type 'module'>"]
  400. options = [getattr(module, name) for module in modules if name in dir(module)]
  401. options += [obj[1] for obj in namespace.items() if obj[0] == name]
  402. if len(options) == 1: return options[0]
  403. if len(options) > 1: raise Exception('Name conflict for %s')
  404. raise Exception('%s not found as a method or class' % name)
  405. def pause():
  406. """
  407. Pauses the output stream awaiting user feedback.
  408. """
  409. print("<Press enter/return to continue>")
  410. input()
  411. ## code to handle timeouts
  412. import signal
  413. class TimeoutFunctionException(Exception):
  414. """
  415. Exception to raise on a timeout
  416. """
  417. pass
  418. class TimeoutFunction:
  419. def __init__(self, function, timeout):
  420. """
  421. timeout must be at least 1 second. WHY??
  422. """
  423. self.timeout = timeout
  424. self.function = function
  425. def handle_timeout(self, signum, frame):
  426. raise TimeoutFunctionException()
  427. def __call__(self, *args):
  428. if not 'SIGALRM' in dir(signal):
  429. return self.function(*args)
  430. old = signal.signal(signal.SIGALRM, self.handle_timeout)
  431. signal.alarm(self.timeout)
  432. try:
  433. result = self.function(*args)
  434. finally:
  435. signal.signal(signal.SIGALRM, old)
  436. signal.alarm(0)
  437. return result
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...