-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw.py
578 lines (472 loc) · 22 KB
/
hw.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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import bisect
"""
Дефинирање на класа за структурата на проблемот кој ќе го решаваме со пребарување.
Класата Problem е апстрактна класа од која правиме наследување за дефинирање на основните
карактеристики на секој проблем што сакаме да го решиме
"""
class Problem:
def __init__(self, initial, goal=None):
self.initial = initial
self.goal = goal
def successor(self, state):
"""За дадена состојба, врати речник од парови {акција : состојба}
достапни од оваа состојба. Ако има многу следбеници, употребете
итератор кој би ги генерирал следбениците еден по еден, наместо да
ги генерирате сите одеднаш.
:param state: дадена состојба
:return: речник од парови {акција : состојба} достапни од оваа
состојба
:rtype: dict
"""
raise NotImplementedError
def actions(self, state):
"""За дадена состојба state, врати листа од сите акции што може да
се применат над таа состојба
:param state: дадена состојба
:return: листа на акции
:rtype: list
"""
raise NotImplementedError
def result(self, state, action):
"""За дадена состојба state и акција action, врати ја состојбата
што се добива со примена на акцијата над состојбата
:param state: дадена состојба
:param action: дадена акција
:return: резултантна состојба
"""
raise NotImplementedError
def goal_test(self, state):
"""Врати True ако state е целна состојба. Даденава имплементација
на методот директно ја споредува state со self.goal, како што е
специфицирана во конструкторот. Имплементирајте го овој метод ако
проверката со една целна состојба self.goal не е доволна.
:param state: дадена состојба
:return: дали дадената состојба е целна состојба
:rtype: bool
"""
return state == self.goal
def path_cost(self, c, state1, action, state2):
"""Врати ја цената на решавачкиот пат кој пристигнува во состојбата
state2 од состојбата state1 преку акцијата action, претпоставувајќи
дека цената на патот до состојбата state1 е c. Ако проблемот е таков
што патот не е важен, оваа функција ќе ја разгледува само состојбата
state2. Ако патот е важен, ќе ја разгледува цената c и можеби и
state1 и action. Даденава имплементација му доделува цена 1 на секој
чекор од патот.
:param c: цена на патот до состојбата state1
:param state1: дадена моментална состојба
:param action: акција која треба да се изврши
:param state2: состојба во која треба да се стигне
:return: цена на патот по извршување на акцијата
:rtype: float
"""
return c + 1
def value(self):
"""За проблеми на оптимизација, секоја состојба си има вредност.
Hill-climbing и сличните алгоритми се обидуваат да ја максимизираат
оваа вредност.
:return: вредност на состојба
:rtype: float
"""
raise NotImplementedError
"""
Дефинирање на класата за структурата на јазел од пребарување.
Класата Node не се наследува
"""
class Node:
def __init__(self, state, parent=None, action=None, path_cost=0):
"""Креирај јазол од пребарувачкото дрво, добиен од parent со примена
на акцијата action
:param state: моментална состојба (current state)
:param parent: родителска состојба (parent state)
:param action: акција (action)
:param path_cost: цена на патот (path cost)
"""
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0 # search depth
if parent:
self.depth = parent.depth + 1
def __repr__(self):
return "<Node %s>" % (self.state,)
def __lt__(self, node):
return self.state < node.state
def expand(self, problem):
"""Излистај ги јазлите достапни во еден чекор од овој јазол.
:param problem: даден проблем
:return: листа на достапни јазли во еден чекор
:rtype: list(Node)
"""
return [self.child_node(problem, action)
for action in problem.actions(self.state)]
def child_node(self, problem, action):
"""Дете јазел
:param problem: даден проблем
:param action: дадена акција
:return: достапен јазел според дадената акција
:rtype: Node
"""
next_state = problem.result(self.state, action)
return Node(next_state, self, action,
problem.path_cost(self.path_cost, self.state,
action, next_state))
def solution(self):
"""Врати ја секвенцата од акции за да се стигне од коренот до овој јазол.
:return: секвенцата од акции
:rtype: list
"""
return [node.action for node in self.path()[1:]]
def solve(self):
"""Врати ја секвенцата од состојби за да се стигне од коренот до овој јазол.
:return: листа од состојби
:rtype: list
"""
return [node.state for node in self.path()[0:]]
def path(self):
"""Врати ја листата од јазли што го формираат патот од коренот до овој јазол.
:return: листа од јазли од патот
:rtype: list(Node)
"""
x, result = self, []
while x:
result.append(x)
x = x.parent
result.reverse()
return result
"""Сакаме редицата од јазли кај breadth_first_search или
astar_search да не содржи состојби - дупликати, па јазлите што
содржат иста состојба ги третираме како исти. [Проблем: ова може
да не биде пожелно во други ситуации.]"""
def __eq__(self, other):
return isinstance(other, Node) and self.state == other.state
def __hash__(self):
return hash(self.state)
"""
Дефинирање на помошни структури за чување на листата на генерирани, но непроверени јазли
"""
class Queue:
"""Queue е апстрактна класа / интерфејс. Постојат 3 типа:
Stack(): Last In First Out Queue (стек).
FIFOQueue(): First In First Out Queue (редица).
PriorityQueue(order, f): Queue во сортиран редослед (подразбирливо,од најмалиот кон
најголемиот јазол).
"""
def __init__(self):
raise NotImplementedError
def append(self, item):
"""Додади го елементот item во редицата
:param item: даден елемент
:return: None
"""
raise NotImplementedError
def extend(self, items):
"""Додади ги елементите items во редицата
:param items: дадени елементи
:return: None
"""
raise NotImplementedError
def pop(self):
"""Врати го првиот елемент од редицата
:return: прв елемент
"""
raise NotImplementedError
def __len__(self):
"""Врати го бројот на елементи во редицата
:return: број на елементи во редицата
:rtype: int
"""
raise NotImplementedError
def __contains__(self, item):
"""Проверка дали редицата го содржи елементот item
:param item: даден елемент
:return: дали queue го содржи item
:rtype: bool
"""
raise NotImplementedError
class Stack(Queue):
"""Last-In-First-Out Queue."""
def __init__(self):
self.data = []
def append(self, item):
self.data.append(item)
def extend(self, items):
self.data.extend(items)
def pop(self):
return self.data.pop()
def __len__(self):
return len(self.data)
def __contains__(self, item):
return item in self.data
class FIFOQueue(Queue):
"""First-In-First-Out Queue."""
def __init__(self):
self.data = []
def append(self, item):
self.data.append(item)
def extend(self, items):
self.data.extend(items)
def pop(self):
return self.data.pop(0)
def __len__(self):
return len(self.data)
def __contains__(self, item):
return item in self.data
class PriorityQueue(Queue):
"""Редица во која прво се враќа минималниот (или максималниот) елемент
(како што е определено со f и order). Оваа структура се користи кај
информирано пребарување"""
""""""
def __init__(self, order=min, f=lambda x: x):
"""
:param order: функција за подредување, ако order е min, се враќа елементот
со минимална f(x); ако order е max, тогаш се враќа елементот
со максимална f(x).
:param f: функција f(x)
"""
assert order in [min, max]
self.data = []
self.order = order
self.f = f
def append(self, item):
bisect.insort_right(self.data, (self.f(item), item))
def extend(self, items):
for item in items:
bisect.insort_right(self.data, (self.f(item), item))
def pop(self):
if self.order == min:
return self.data.pop(0)[1]
return self.data.pop()[1]
def __len__(self):
return len(self.data)
def __contains__(self, item):
return any(item == pair[1] for pair in self.data)
def __getitem__(self, key):
for _, item in self.data:
if item == key:
return item
def __delitem__(self, key):
for i, (value, item) in enumerate(self.data):
if item == key:
self.data.pop(i)
import sys
"""
Неинформирано пребарување во рамки на дрво.
Во рамки на дрвото не разрешуваме јамки.
"""
def tree_search(problem, fringe):
""" Пребарувај низ следбениците на даден проблем за да најдеш цел.
:param problem: даден проблем
:type problem: Problem
:param fringe: празна редица (queue)
:type fringe: FIFOQueue or Stack or PriorityQueue
:return: Node or None
:rtype: Node
"""
fringe.append(Node(problem.initial))
while fringe:
node = fringe.pop()
print(node.state)
if problem.goal_test(node.state):
return node
fringe.extend(node.expand(problem))
return None
def breadth_first_tree_search(problem):
"""Експандирај го прво најплиткиот јазол во пребарувачкото дрво.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
return tree_search(problem, FIFOQueue())
def depth_first_tree_search(problem):
"""Експандирај го прво најдлабокиот јазол во пребарувачкото дрво.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
return tree_search(problem, Stack())
"""
Неинформирано пребарување во рамки на граф
Основната разлика е во тоа што овде не дозволуваме јамки,
т.е. повторување на состојби
"""
def graph_search(problem, fringe):
"""Пребарувај низ следбениците на даден проблем за да најдеш цел.
Ако до дадена состојба стигнат два пата, употреби го најдобриот пат.
:param problem: даден проблем
:type problem: Problem
:param fringe: празна редица (queue)
:type fringe: FIFOQueue or Stack or PriorityQueue
:return: Node or None
:rtype: Node
"""
closed = set()
fringe.append(Node(problem.initial))
while fringe:
node = fringe.pop()
if problem.goal_test(node.state):
return node
if node.state not in closed:
closed.add(node.state)
fringe.extend(node.expand(problem))
return None
def breadth_first_graph_search(problem):
"""Експандирај го прво најплиткиот јазол во пребарувачкиот граф.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
return graph_search(problem, FIFOQueue())
def depth_first_graph_search(problem):
"""Експандирај го прво најдлабокиот јазол во пребарувачкиот граф.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
return graph_search(problem, Stack())
def depth_limited_search(problem, limit=50):
"""Експандирај го прво најдлабокиот јазол во пребарувачкиот граф
со ограничена длабочина.
:param problem: даден проблем
:type problem: Problem
:param limit: лимит за длабочината
:type limit: int
:return: Node or None
:rtype: Node
"""
def recursive_dls(node, problem, limit):
"""Помошна функција за depth limited"""
cutoff_occurred = False
if problem.goal_test(node.state):
return node
elif node.depth == limit:
return 'cutoff'
else:
for successor in node.expand(problem):
result = recursive_dls(successor, problem, limit)
if result == 'cutoff':
cutoff_occurred = True
elif result is not None:
return result
if cutoff_occurred:
return 'cutoff'
return None
return recursive_dls(Node(problem.initial), problem, limit)
def iterative_deepening_search(problem):
"""Експандирај го прво најдлабокиот јазол во пребарувачкиот граф
со ограничена длабочина, со итеративно зголемување на длабочината.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
for depth in range(sys.maxsize):
result = depth_limited_search(problem, depth)
if result != 'cutoff':
return result
def uniform_cost_search(problem):
"""Експандирај го прво јазолот со најниска цена во пребарувачкиот граф.
:param problem: даден проблем
:type problem: Problem
:return: Node or None
:rtype: Node
"""
return graph_search(problem, PriorityQueue(min, lambda a: a.path_cost))
def ghost_prodolziPravo(x,y,nasoka,table, obstacles):
if nasoka == 'desno':
if x+1<table[0] and (x+1,y) not in obstacles:
return tuple([tuple([x+1,y]),nasoka])
elif nasoka == 'levo':
if x-1 >= 0 and (x-1,y) not in obstacles:
return tuple([tuple([x-1,y]),nasoka])
elif nasoka == 'gore':
if y+1 < table[1] and (x,y+1) not in obstacles:
return tuple([tuple([x,y+1]),nasoka])
elif nasoka == 'dolu':
if y-1 >= 0 and (x,y-1) not in obstacles:
return tuple([tuple([x,y-1]),nasoka])
return None
def ghost_Levo(x,y,nasoka):
xy = tuple([x,y])
if nasoka == 'desno':
return tuple([xy, 'gore'])
elif nasoka == 'levo':
return tuple([xy, 'dolu'])
elif nasoka == 'gore':
return tuple([xy, 'levo'])
elif nasoka == 'dolu':
return tuple([xy, 'desno'])
def ghost_Desno(x,y,nasoka):
xy = tuple([x,y])
if nasoka == 'desno':
return tuple([xy, 'dolu'])
elif nasoka == 'levo':
return tuple([xy, 'gore'])
elif nasoka == 'gore':
return tuple([xy, 'desno'])
elif nasoka == 'dolu':
return tuple([xy, 'levo'])
class Pacman(Problem):
def __init__(self,initial,goal):
super().__init__(initial,goal)
self.table = (7,5)
self.obstacles = ((2,2), (3,2), (3,3), (3,4), (4,2))
self.Pacman = goal
def successor(self, state):
successors = dict()
ghostA_xy = list(state[0][0])
ghostB_xy = list(state[1][0])
ghost_A_orient = state[0][1]
ghost_B_orient = state[1][1]
ghost_A_new_Pravo = ghost_prodolziPravo(ghostA_xy[0],ghostA_xy[1],ghost_A_orient,self.table,self.obstacles)
ghost_B_new_Pravo = ghost_prodolziPravo(ghostB_xy[0],ghostB_xy[1],ghost_B_orient,self.table,self.obstacles)
ghost_A_new_Desno = ghost_Desno(ghostA_xy[0],ghostA_xy[1],ghost_A_orient)
ghost_B_new_Desno = ghost_Desno(ghostB_xy[0],ghostB_xy[1],ghost_B_orient)
ghost_A_new_Levo = ghost_Levo(ghostA_xy[0],ghostA_xy[1],ghost_A_orient)
ghost_B_new_Levo = ghost_Levo(ghostB_xy[0],ghostB_xy[1],ghost_B_orient)
if ghost_A_new_Pravo!=None:
if ghost_B_new_Pravo!=None and ghost_A_new_Pravo[0]!=ghost_B_new_Pravo[0]:
successors[('ProdolziPravo','ProdolziPravo')] = (ghost_A_new_Pravo,ghost_B_new_Pravo)
if ghost_A_new_Pravo[0] != ghost_B_new_Levo[0]:
successors[('ProdolziPravo','SvrtiLevo')] = (ghost_A_new_Pravo,ghost_B_new_Levo)
if ghost_A_new_Pravo[0] != ghost_B_new_Desno[0]:
successors[('ProdolziPravo', 'SvrtiDesno')] = (ghost_A_new_Pravo, ghost_B_new_Desno)
if ghost_A_new_Pravo[0] != tuple(ghostB_xy):
successors[('ProdolziPravo', 'Stop')] = (ghost_A_new_Pravo, tuple([tuple(ghostB_xy),ghost_B_orient]))
if ghost_B_new_Pravo!=None:
if ghost_B_new_Pravo[0]!=ghost_A_new_Levo[0]:
successors[('SvrtiLevo','ProdolziPravo')] = (ghost_A_new_Levo,ghost_B_new_Pravo)
if ghost_B_new_Pravo[0] != ghost_A_new_Desno[0]:
successors[( 'SvrtiDesno','ProdolziPravo')] = (ghost_A_new_Desno, ghost_B_new_Pravo)
if ghost_B_new_Pravo[0] != tuple(ghostA_xy):
successors[( 'Stop','ProdolziPravo',)] = (tuple([tuple(ghostA_xy),ghost_A_orient]), ghost_B_new_Pravo)
successors[('SvrtiDesno','SvrtiDesno')] = (ghost_A_new_Desno, ghost_B_new_Desno)
successors[('SvrtiDesno','SvrtiLevo')] = (ghost_A_new_Desno, ghost_B_new_Levo)
successors[('SvrtiDesno','Stop')] = (ghost_A_new_Desno, tuple([tuple(ghostB_xy),ghost_B_orient]))
successors[('SvrtiLevo', 'SvrtiDesno')] = (ghost_A_new_Levo, ghost_B_new_Desno)
successors[('SvrtiLevo', 'SvrtiLevo')] = (ghost_A_new_Levo, ghost_B_new_Levo)
successors[('SvrtiLevo', 'Stop')] = (ghost_A_new_Levo, tuple([tuple(ghostB_xy),ghost_B_orient]))
successors[('Stop', 'SvrtiDesno')] = (tuple([tuple(ghostA_xy),ghost_A_orient]), ghost_B_new_Desno)
successors[('Stop', 'SvrtiLevo')] = (tuple([tuple(ghostA_xy),ghost_A_orient]), ghost_B_new_Levo)
successors[('Stop', 'Stop')] = (tuple([tuple(ghostA_xy),ghost_A_orient]), tuple([tuple(ghostB_xy),ghost_B_orient]))
return successors
def actions(self, state):
return self.successor(state).keys()
def result(self, state, action):
return self.successor(state)[action]
def goal_test(self, state):
ghost_A = state[0][0]
ghost_B = state[1][0]
return ghost_A == self.goal or ghost_B == self.goal
if __name__ == "__main__":
ghost_A = (tuple([0,4]), 'desno')
ghost_B = (tuple([5,4]),'desno')
pacman = (6,3)
problem = Pacman((ghost_A, ghost_B), pacman)
result = breadth_first_graph_search(problem)
print(result.solution())