-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrlagent.go
265 lines (222 loc) · 5.71 KB
/
rlagent.go
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
package main
import (
"encoding/gob"
"fmt"
"math/rand"
"os"
)
type RLAgent struct {
// Agent PlayerID
id int
// View settings
Sign string
// Game definition
m, n, k int
// RL parameters
Learning bool
LearningRate float64 //alpha
DiscountFactor float64
ExplorationFactor float64 //epsilon
// States stash
values map[string]float64
prev struct {
state MNKState
action MNKAction
reward float64
}
message string
}
type RLAgentKnowledge struct {
Values map[string]float64
Iterations uint
randomDispersion []int
}
var rlKnowledge RLAgentKnowledge
func NewRLAgent(id int, sign string, m, n, k int, learn bool) (agent *RLAgent) {
agent = new(RLAgent)
agent.id = id
agent.Sign = sign
agent.m = m
agent.n = n
agent.k = k
// Default values
agent.Learning = learn
agent.LearningRate = 0.2
agent.DiscountFactor = 0.8
agent.ExplorationFactor = 0.25
// Initiate stash
if rlKnowledge.Iterations == 0 {
rlKnowledge.Values = make(map[string]float64)
rlKnowledge.randomDispersion = make([]int, m*n)
} else {
var tmp []int = make([]int, len(rlKnowledge.randomDispersion))
copy(tmp, rlKnowledge.randomDispersion)
rlKnowledge.randomDispersion = make([]int, m*n)
copy(rlKnowledge.randomDispersion, tmp)
}
agent.values = rlKnowledge.Values
return
}
func (agent *RLAgent) FetchMessage() (message string) {
message = agent.message
agent.message = ""
return
}
func (agent *RLAgent) FetchMove(state State, possibleActions []Action) (Action, error) {
// REVIEW: Rename to Move, and accept a function to do it, which returns the reward
var s MNKState = state.(MNKState)
var action MNKAction
var qMax float64
var e = rand.Float64()
if e < agent.ExplorationFactor {
agent.message = fmt.Sprintf("Exploratory action (%f)", e)
// Choose a random move
rndi := rand.Intn(len(possibleActions))
action = possibleActions[rndi].GetParams().(MNKAction)
rlKnowledge.randomDispersion[action.Y*agent.m+action.X]++
qMax = agent.lookup(s, action)
} else {
agent.message = fmt.Sprintf("Greedy action (%f)", e)
// Choose a greedy move
var first = true
for i := range s {
for j := range s[i] {
if s[i][j] == 0 {
a := MNKAction{i, j}
v := agent.lookup(s, a)
if v > qMax || first {
qMax = v
action = a
first = false
}
}
}
}
}
if agent.Learning {
agent.learn(qMax)
}
agent.prev.state = s //.Clone()
agent.prev.action = action
agent.prev.reward = agent.value(agent.prev.state, agent.prev.action)
return action, nil
}
func (agent *RLAgent) GameOver(state State) {
var s MNKState = state.(MNKState)
if agent.Learning {
// Bypass the marshaller's action addition with (-1, -1)
agent.learn(agent.lookup(s, MNKAction{-1, -1}))
}
// Restart for the next episode
agent.prev.state = MNKState{}
agent.prev.action = MNKAction{}
agent.prev.reward = 0
agent.message = ""
rlKnowledge.Iterations++
}
func (agent *RLAgent) GetSign() string {
return agent.Sign
}
// learn calculates new value for given state
func (agent *RLAgent) learn(qMax float64) {
// Ignore an empty state-action (happens on first move)
if len(agent.prev.state) == 0 {
return
}
var mState = marshallState(agent.id, agent.prev.state, agent.prev.action)
var oldVal = agent.values[mState]
// REVIEW: Learning Rate may decrease gradually (for stochastic environments)
// REVIEW: Discount Factor may increase gradually (when estimating reward)
agent.values[mState] = oldVal + (agent.LearningRate *
(agent.prev.reward + (agent.DiscountFactor * qMax) - oldVal))
}
// lookup returns the Q-value for the given state
func (agent *RLAgent) lookup(state MNKState, action MNKAction) float64 {
var mState = marshallState(agent.id, state, action) // Marshalled state
val, ok := agent.values[mState]
if !ok {
val = agent.value(state, action)
agent.values[mState] = val
}
return val
}
// value returns the reward for the given state
func (agent *RLAgent) value(state MNKState, action MNKAction) float64 {
// TODO: Fix this. The agent must have real access to the evaluation function
if action != (MNKAction{-1, -1}) {
switch board.EvaluateAction(agent.id, action) {
case 1: // Agent won
return 1
case 0: // Game goes on
return 0
case -1: // Draw
return -0.5
}
}
switch board.Evaluate() {
case agent.id: // Agent won
return 1
case 0: // Game goes on
return 0
case -1: // Draw
return -0.5
default: // Agent lost
return -1
}
}
// storeKnowledge writes the knowledge map to given path
func (k *RLAgentKnowledge) saveToFile(path string) bool {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fmt.Println("[error] Could not open writable knowledge file on disk!")
fmt.Println(err)
return false
}
defer file.Close()
enc := gob.NewEncoder(file)
err = enc.Encode(k)
if err != nil {
fmt.Println("[error] Encoding of knowledge failed!")
fmt.Println(err)
return false
}
return true
}
// retrieveKnowledge reads the knowledge from given path to knowledge map
func (k *RLAgentKnowledge) loadFromFile(path string) bool {
file, err := os.Open(path)
if err != nil {
fmt.Println("[error] Could not open readable knowledge file on disk!")
fmt.Println(err)
return false
}
defer file.Close()
dec := gob.NewDecoder(file)
err = dec.Decode(k)
if err != nil {
fmt.Println("[error] Decoding of knowledge failed!")
fmt.Println(err)
return false
}
return true
}
func marshallState(agentID int, state MNKState, action MNKAction) (m string) {
for i := range state {
for j := range state[i] {
// Include action in state
if i == action.Y && j == action.X {
m += "X"
continue
}
switch state[i][j] {
case 0:
m += "-"
case agentID:
m += "X"
default:
m += "O"
}
}
}
return
}