-
Notifications
You must be signed in to change notification settings - Fork 0
/
Agent.py
183 lines (160 loc) · 6.53 KB
/
Agent.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
import numpy as np
import copy
from MineSweeper import *
class Agent:
def __init__(self, Q_Matrix = None, lr = 0.1, gamma = 0.9, gameObject = None):
self.gameObject = gameObject
# Initializing Q_Matrix: dict{state: 8 actions Mtrix}
# 0 1 2
# 3 4 5
# 6 7 8
if Q_Matrix is None:
self.Q_Matrix = {}
else:
self.Q_Matrix = Q_Matrix
# learning rate
self.lr = lr
#gamma
self.gamma = gamma
# create a state from loc and grid, it will return a loc and its neighbor as
# 0 1 2
# 3 4 5
# 6 7 8
def createState(self, loc, grid):
state = np.array([['-1']*3]*3)
i,j = loc
maxI = len(grid)
maxJ = len(grid[0])
state[1][1] = grid[i][j]
if 0 <= i - 1:
state[0][1] = grid[i-1][j]
if 0 <= j-1:
state[0][0] = grid[i-1][j-1]
if maxJ > j+1:
state[0][2] = grid[i-1][j+1]
if 0 <= j-1:
state[1][0] = grid[i][j-1]
if maxJ > j + 1:
state[1][2] = grid[i][j+1]
if maxI > i+1:
state[2][1] = grid[i+1][j]
if 0 <= j-1:
state[2][0] = grid[i+1][j-1]
if maxJ > j+1:
state[2][2] = grid[i+1][j+1]
return state
# convert an array to a string
def arrayToString(self, array):
return ".".join(str(x) for x in array)
# get cells along border of uncovered and covered cells.
def getBorderCells(self, grid):
result = []
maxI = len(grid)
maxJ = len(grid[0])
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if 0 <= i - 1:
if grid[i - 1][j] == 'E':
result.append([i,j])
continue
if 0 <= j - 1:
if grid[i - 1][j - 1] == 'E':
result.append([i,j])
continue
if maxJ > j + 1:
if grid[i - 1][j + 1] == 'E':
result.append([i,j])
continue
if 0 <= j - 1:
if grid[i][j - 1] == 'E':
result.append([i,j])
continue
if maxJ > j + 1:
if grid[i][j + 1] == 'E':
result.append([i,j])
continue
if maxI > i + 1:
if grid[i + 1][j] == 'E':
result.append([i,j])
continue
if 0 <= j - 1:
if grid[i + 1][j - 1] == 'E':
result.append([i,j])
continue
if maxJ > j + 1:
if grid[i + 1][j + 1] == 'E':
result.append([i,j])
continue
return result
# this function for testing,
def play(self):
currentStates = self.getBorderCells(self.gameObject.currgrid)
chosenState, location = self.stateHavingMaxQ_Val(currentStates)
# if the state is not in Q_Matrix, it will choose random action for that state.
if not chosenState in self.Q_Matrix:
newState = self.createState(location, self.gameObject.currgrid)
action = np.random.choice(newState[newState=='E'], 1, replace=False)
else:
action = np.argmax(self.Q_Matrix[chosenState])
newLocation = [location[0]+int(action/3)-1, location[1]+action%3-1]
return newLocation
def addNewState(self, state):
# get current state
newState = state.ravel().tolist()
key = self.arrayToString(newState)
if not key in self.Q_Matrix:
self.Q_Matrix.update({key: np.zeros(9, dtype=np.float)})
tmpState = np.zeros(9, dtype=np.float)
for i, row in enumerate(newState):
if row != 'E':
tmpState[i] = -np.inf
key = self.arrayToString(newState)
self.Q_Matrix.update({key: tmpState})
return self.Q_Matrix[key]
# get next state with a specific action
# def nextState(self, action):
# return self.gameObject.playgame(action)
def stateHavingMaxQ_Val(self, currentStates):
comp = -99999
state = ''
location = currentStates[np.random.choice(np.array(currentStates).shape[0], 1, replace=False)[0]]
for currentState in currentStates:
tmpState = self.createState(currentState, self.gameObject.currgrid)
newState = tmpState.ravel().tolist()
key = self.arrayToString(newState)
if not key in self.Q_Matrix:
continue
a = np.max(self.Q_Matrix[key])
if a > comp:
comp = a
state = key
location = currentState
return state, location
def Q_s_b(self, action):
a = self.gameObject.playgame(action)
if a == -1:
return [-1], -1
currentStates = self.getBorderCells(self.gameObject.currgrid)
for currentState in currentStates:
newState = self.createState(currentState, self.gameObject.currgrid)
self.addNewState(newState)
# choosing an action from current states
chosenState, location = self.stateHavingMaxQ_Val(currentStates)
return self.Q_Matrix[chosenState], a
def train(self, epsilon = 0.1):
# epsilon
self.epsilon = epsilon
currentStates = self.getBorderCells(self.gameObject.currgrid)
for currentState in currentStates:
newState = self.createState(currentState,self.gameObject.currgrid)
self.addNewState(newState)
# choosing an action from current states
chosenState, location = self.stateHavingMaxQ_Val(currentStates)
action = np.argmax((self.Q_Matrix[chosenState] + np.random.randn(1, 9) * (1. / (self.epsilon + 1)))[0])
newLocation = [location[0]+int(action/3)-1, location[1]+action%3-1]
print(newLocation)
Q_s_b, reward = self.Q_s_b(newLocation)
self.Q_Matrix[chosenState][action] = self.Q_Matrix[chosenState][action] + self.lr * (reward + self.gamma * (np.max(Q_s_b)) - self.Q_Matrix[chosenState][action])
if reward == -1 or reward == 1:
self.gameObject = MineSweeper(gridsize=self.gameObject.gridsize, numberOfMines=self.gameObject.numberofmines)
return reward