-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathN-step Sarsa.kt
76 lines (71 loc) · 2 KB
/
N-step Sarsa.kt
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
@file:Suppress("NAME_SHADOWING")
package lab.mars.rl.algo.ntd
import lab.mars.rl.algo.V_from_Q
import lab.mars.rl.algo.`ε-greedy`
import lab.mars.rl.model.impl.mdp.*
import lab.mars.rl.model.isTerminal
import lab.mars.rl.model.log
import lab.mars.rl.util.buf.newBuf
import lab.mars.rl.util.log.debug
import lab.mars.rl.util.math.Σ
import lab.mars.rl.util.tuples.tuple3
import org.apache.commons.math3.util.FastMath.min
import org.apache.commons.math3.util.FastMath.pow
fun IndexedMDP.`N-step Sarsa`(
n: Int,
ε: Double,
α: (IndexedState, IndexedAction) -> Double,
episodes: Int): OptimalSolution {
val π = IndexedPolicy(QFunc { 0.0 })
val Q = QFunc { 0.0 }
val _R = newBuf<Double>(min(n, MAX_N))
val _S = newBuf<IndexedState>(min(n, MAX_N))
val _A = newBuf<IndexedAction>(min(n, MAX_N))
for (episode in 1..episodes) {
log.debug { "$episode/$episodes" }
var n = n
var T = Int.MAX_VALUE
var t = 0
var s = started()
`ε-greedy`(s, Q, π, ε)
var a = π(s)
_R.clear();_R.append(0.0)
_S.clear();_S.append(s)
_A.clear();_A.append(a)
do {
if (t >= n) {
_R.removeFirst()
_S.removeFirst()
_A.removeFirst()
}
if (t < T) {
val (s_next, reward) = a.sample()
_R.append(reward)
_S.append(s_next)
s = s_next
if (s.isTerminal) {
T = t + 1
val τ = t - n + 1
if (τ < 0) n = T //n is too large
} else {
`ε-greedy`(s, Q, π, ε)
a = π(s)
_A.append(a)
}
}
val τ = t - n + 1
if (τ >= 0) {
var G = Σ(1..min(n, T - τ)) { pow(γ, it - 1) * _R[it] }
if (τ + n < T) G += pow(γ, n) * Q[_S[n], _A[n]]
Q[_S[0], _A[0]] += α(_S[0], _A[0]) * (G - Q[_S[0], _A[0]])
`ε-greedy`(_S[0], Q, π, ε)
}
t++
} while (τ < T - 1)
log.debug { "n=$n,T=$T" }
}
val V = VFunc { 0.0 }
val result = tuple3(π, V, Q)
V_from_Q(states, result)
return result
}