/
randomForest.py
242 lines (177 loc) · 6.82 KB
/
randomForest.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
import agentBase
import visualize
import numpy as np
import heapq
import math
import random
import copy
# required for animation. Put this wherever you want
expanded_nodes = []
class Node:
def __init__(self,agent):
self.location = agent.current
self.numOfWins = 0
self.parent = None
def setValue(self, val):
self.valueOfVisits = val
def setNum(self, num):
self.numOfVisits = num
def addWinRate(self, incr):
self.numOfWins += incr
def getWinRate(self):
return self.numOfWins
"""
get_path from mapf project
"""
def get_path(node):
path = []
curr = node
while curr is not None:
path.append(curr['loc'])
curr = curr['parent']
path.reverse()
print("LENGTH:", len(path))
return path
class MCTSearch:
def __init__(self, agent):
self.map = agent.map
self.currentNode = Node(agent)
self.visited = np.ndarray(agent.start)
def move(self, direction,agent):
agent.current = direction
def moveOld(self, direction,agent):
if direction == 1:
agent.current[1] += 1
if direction == 2:
agent.current[0] += 1
if direction == 3:
agent.current[1] -= 1
if direction == 4:
agent.current[0] -= 1
return agent.current
def randPlayDFS(self, movePosition, agent):
start_pos = (agent.start[0], agent.start[1])
goal_pos = (agent.goal[0], agent.goal[1])
current_pos = start_pos
agentScout = copy.deepcopy(agent)
open_stack = list()
closed_list = dict()
root = {'loc': start_pos, 'parent': None}
open_stack.append(root)
closed_list[(root['loc'])] = root
nodes_expanded = 0
max_size_of_open = len(open_stack)
penalty = 0
while len(open_stack) > 0:
penalty += 1
nodes_expanded += 1 # time complexity
if len(open_stack) > max_size_of_open: # space complexity
max_size_of_open = len(open_stack)
random.shuffle(open_stack)
node = open_stack.pop() # LIFO
current_pos = node['loc']
agentScout.current[0] = current_pos[0]
agentScout.current[1] = current_pos[1]
# path to goal state has been found
if current_pos == goal_pos:
return 10000 - penalty
# take movement option indices in agentBase.nextStep()...
# map out viable indices to locations in map
move_options = agentScout.nextStep()
random.shuffle(move_options)
move_list = []
for i in range(len(move_options)):
#if len(move_options) > 0:
if move_options[i] == 1:
move_list.append((node['loc'][0], node['loc'][1]+1))
if move_options[i] == 2:
move_list.append((node['loc'][0]+1, node['loc'][1]))
if move_options[i] == 3:
move_list.append((node['loc'][0], node['loc'][1]-1))
if move_options[i] == 4:
move_list.append((node['loc'][0]-1, node['loc'][1]))
# end of for in loop
# for valid locations, create movement child
for moveOption in move_list:
child = {'loc': moveOption,
'parent': node}
if not (child['loc']) in closed_list: # pruning
closed_list[(child['loc'])] = child
open_stack.append(child)
# end of for in loop
# end of while loop
return -10 - penalty
def randPlayBlind(self, movePosition, agent):
agentScout = copy.deepcopy(agent)
closed_list = []
counter = 0
while counter < 100:
counter += 1
direction = agentScout.randomMove()
if (type(agent.current) is tuple):
agent.current = np.asarray(agent.current)
self.moveOld(direction, agent)
if agentScout.map[agentScout.current[0]][agentScout.current[1]] != '1':
return 10000
return -10
def treeSearch(self, agent):
move_options = agent.nextStep()
validMoves = []
node = Node(agent)
for i in range(len(move_options)):
if move_options[i] == 1:
validMoves.append((node.location[0], node.location[1]+1))
if move_options[i] == 2:
validMoves.append((node.location[0]+1, node.location[1]))
if move_options[i] == 3:
validMoves.append((node.location[0], node.location[1]-1))
if move_options[i] == 4:
validMoves.append((node.location[0]-1, node.location[1]))
# end of for in loop
winRates = []
for i in range(len(validMoves)):
node = Node(agent)
winRates.append(node)
for i in range(len(validMoves)):
for k in range(50):
res = self.randPlayBlind(validMoves[i], agent)
winRates[i].addWinRate(res)
if len(validMoves) == 0:
return agent.current
bestChoice = validMoves[0]
maxVal = 0
for i in range(len(validMoves)):
if winRates[i].getWinRate() > winRates[maxVal].getWinRate():
maxVal = i
bestChoice = validMoves[i]
return bestChoice
def random_forest(self,agent):
counter = 0
path = []
print("START")
while agent.map[agent.current[0]][agent.current[1]] != '1' and counter < 10:
counter += 1
direction = self.treeSearch(agent)
path.append(agent.current)
self.move(direction,agent)
print("DONE")
return path, expanded_nodes
def main():
#TODO - add time measurements!!!!!!!
maze_instance = ("maze_instances/maze1.txt")
algorithm = "a_star algorithm"
my_map = agentBase.Map(maze_instance)
my_map.getMap()
agent = agentBase.Agent(my_map)
print("\nCoordinate Configuration: (Y, X)")
print("Start State:", agent.start)
print("Goal State:", agent.goal, "\n")
mtc = MCTSearch(agent)
#mtc.treeSearch()
path, expanded_nodes = mtc.random_forest(agent)
print(path)
#sol_path, exp_nodes = random_forest(agent)
#animation = visualize.Visualize(algorithm, maze_instance, my_map.start, my_map.goal, sol_path, exp_nodes)
#animation.StartAnimation()
if __name__ == '__main__':
main()