-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcts.go
163 lines (150 loc) · 4.25 KB
/
mcts.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
package MCTS
import (
"fmt"
"math"
"math/rand"
"time"
)
type State interface {
GetCurrentPlayer() int
GetPossibleActions() []any
TakeAction(a any) State
IsTerminal() bool
GetReward() int
}
type TreeNode struct {
State State
IsTerminal bool
IsFullyExpanded bool
Parent *TreeNode
NumVisits int
TotalReward int
Children map[any]*TreeNode
}
func NewTreeNode(state State, parent *TreeNode) *TreeNode {
node := TreeNode{}
node.State = state
node.IsTerminal = state.IsTerminal()
node.IsFullyExpanded = node.IsTerminal
node.Parent = parent
node.Children = map[any]*TreeNode{}
return &node
}
type MCTS struct {
TimeLimit int
IterationLimit int
LimitType string
ExplorationConstant float64
Rollout func(State, chan int)
Root *TreeNode
Jobs int
}
func NewMCTS(timeLimit int, iterationLimit int, explorationConstant float64, rollout func(State, chan int), Jobs int) *MCTS {
mcts := MCTS{}
if timeLimit > 0 {
if iterationLimit > 0 {
panic("Cannot have both a time limit and an iteration limit")
}
mcts.TimeLimit = timeLimit
mcts.LimitType = "time"
} else {
if iterationLimit == 0 {
panic("Must have either a time limit or an iteration limit")
}
mcts.IterationLimit = iterationLimit
mcts.LimitType = "iterations"
}
mcts.ExplorationConstant = explorationConstant
mcts.Rollout = rollout
mcts.Jobs = Jobs
return &mcts
}
func (mcts *MCTS) Search(initialState State, verbose int) any {
mcts.Root = NewTreeNode(initialState, nil)
if mcts.LimitType == "time" {
timeLimit := time.Now().UnixNano()/1000000 + int64(mcts.TimeLimit)
for time.Now().UnixNano()/1000000 < timeLimit {
mcts.executeRound()
}
} else {
for i := 0; i < mcts.IterationLimit; i++ {
mcts.executeRound()
}
}
bestChild := mcts.getBestChild(mcts.Root, 0)
bestMeanReward := getMeanReward(bestChild)
if verbose == 2 {
for action, child := range mcts.Root.Children {
fmt.Printf("Action: %v\t%.2f%% Visits\t%.3f%% Wins\n", action, 100*float64(child.NumVisits)/float64(mcts.Root.NumVisits), 100*(float64(child.TotalReward)/float64(child.NumVisits)+1)/2)
}
}
for action, child := range mcts.Root.Children {
if getMeanReward(child) == bestMeanReward {
if verbose == 1 {
fmt.Printf("Action: %v\t%.2f%% Visits\t%.3f%% Wins\n", action, 100*float64(child.NumVisits)/float64(mcts.Root.NumVisits), 100*(float64(child.TotalReward)/float64(child.NumVisits)+1)/2)
}
return action
}
}
panic("Should never reach here")
}
func (mcts *MCTS) executeRound() {
node := mcts.selectNode(mcts.Root)
reward := 0
ch := make(chan int)
for i := 0; i < mcts.Jobs; i++ {
go mcts.Rollout(node.State, ch)
}
for i := 0; i < mcts.Jobs; i++ {
reward += <-ch
}
mcts.backpropogate(node, reward)
}
func (mcts *MCTS) selectNode(node *TreeNode) *TreeNode {
for !node.IsTerminal {
if node.IsFullyExpanded {
node = mcts.getBestChild(node, mcts.ExplorationConstant)
} else {
return mcts.expand(node)
}
}
return node
}
func (mcts *MCTS) expand(node *TreeNode) *TreeNode {
actions := node.State.GetPossibleActions()
for _, action := range actions {
if _, ok := node.Children[action]; !ok {
newNode := NewTreeNode(node.State.TakeAction(action), node)
node.Children[action] = newNode
if len(actions) == len(node.Children) {
node.IsFullyExpanded = true
}
return newNode
}
}
panic("Should never reach here")
}
func (mcts *MCTS) backpropogate(node *TreeNode, reward int) {
for node != nil {
node.NumVisits += mcts.Jobs
node.TotalReward += reward
node = node.Parent
}
}
func (mcts *MCTS) getBestChild(node *TreeNode, explorationValue float64) *TreeNode {
bestValue := -math.MaxFloat64
bestNodes := []*TreeNode{}
for _, child := range node.Children {
nodeValue := float64(node.State.GetCurrentPlayer()*child.TotalReward)/float64(child.NumVisits) + explorationValue*math.Sqrt(2.0*math.Log(float64(node.NumVisits))/float64(child.NumVisits))
if nodeValue > bestValue {
bestValue = nodeValue
bestNodes = []*TreeNode{child}
} else if nodeValue == bestValue {
bestNodes = append(bestNodes, child)
}
}
return bestNodes[rand.Intn(len(bestNodes))]
}
func getMeanReward(node *TreeNode) float64 {
return float64(node.TotalReward) / float64(node.NumVisits)
}