-
Notifications
You must be signed in to change notification settings - Fork 15
/
ExampleUCT.java
309 lines (255 loc) · 7.98 KB
/
ExampleUCT.java
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package mcts;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import game.Game;
import main.collections.FastArrayList;
import other.AI;
import other.RankUtils;
import other.context.Context;
import other.move.Move;
/**
* A simple example implementation of a standard UCT approach.
*
* Only supports deterministic, alternating-move games.
*
* @author Dennis Soemers
*/
public class ExampleUCT extends AI
{
//-------------------------------------------------------------------------
/** Our player index */
protected int player = -1;
//-------------------------------------------------------------------------
/**
* Constructor
*/
public ExampleUCT()
{
this.friendlyName = "Example UCT";
}
//-------------------------------------------------------------------------
@Override
public Move selectAction
(
final Game game,
final Context context,
final double maxSeconds,
final int maxIterations,
final int maxDepth
)
{
// Start out by creating a new root node (no tree reuse in this example)
final Node root = new Node(null, null, context);
// We'll respect any limitations on max seconds and max iterations (don't care about max depth)
final long stopTime = (maxSeconds > 0.0) ? System.currentTimeMillis() + (long) (maxSeconds * 1000L) : Long.MAX_VALUE;
final int maxIts = (maxIterations >= 0) ? maxIterations : Integer.MAX_VALUE;
int numIterations = 0;
// Our main loop through MCTS iterations
while
(
numIterations < maxIts && // Respect iteration limit
System.currentTimeMillis() < stopTime && // Respect time limit
!wantsInterrupt // Respect GUI user clicking the pause button
)
{
// Start in root node
Node current = root;
// Traverse tree
while (true)
{
if (current.context.trial().over())
{
// We've reached a terminal state
break;
}
current = select(current);
if (current.visitCount == 0)
{
// We've expanded a new node, time for playout!
break;
}
}
Context contextEnd = current.context;
if (!contextEnd.trial().over())
{
// Run a playout if we don't already have a terminal game state in node
contextEnd = new Context(contextEnd);
game.playout
(
contextEnd,
null,
-1.0,
null,
0,
-1,
ThreadLocalRandom.current()
);
}
// This computes utilities for all players at the of the playout,
// which will all be values in [-1.0, 1.0]
final double[] utilities = RankUtils.utilities(contextEnd);
// Backpropagate utilities through the tree
while (current != null)
{
current.visitCount += 1;
for (int p = 1; p <= game.players().count(); ++p)
{
current.scoreSums[p] += utilities[p];
}
current = current.parent;
}
// Increment iteration count
++numIterations;
}
// Return the move we wish to play
return finalMoveSelection(root);
}
/**
* Selects child of the given "current" node according to UCB1 equation.
* This method also implements the "Expansion" phase of MCTS, and creates
* a new node if the given current node has unexpanded moves.
*
* @param current
* @return Selected node (if it has 0 visits, it will be a newly-expanded node).
*/
public static Node select(final Node current)
{
if (!current.unexpandedMoves.isEmpty())
{
// randomly select an unexpanded move
final Move move = current.unexpandedMoves.remove(
ThreadLocalRandom.current().nextInt(current.unexpandedMoves.size()));
// create a copy of context
final Context context = new Context(current.context);
// apply the move
context.game().apply(context, move);
// create new node and return it
return new Node(current, move, context);
}
// use UCB1 equation to select from all children, with random tie-breaking
Node bestChild = null;
double bestValue = Double.NEGATIVE_INFINITY;
final double twoParentLog = 2.0 * Math.log(Math.max(1, current.visitCount));
int numBestFound = 0;
final int numChildren = current.children.size();
final int mover = current.context.state().mover();
for (int i = 0; i < numChildren; ++i)
{
final Node child = current.children.get(i);
final double exploit = child.scoreSums[mover] / child.visitCount;
final double explore = Math.sqrt(twoParentLog / child.visitCount);
final double ucb1Value = exploit + explore;
if (ucb1Value > bestValue)
{
bestValue = ucb1Value;
bestChild = child;
numBestFound = 1;
}
else if
(
ucb1Value == bestValue &&
ThreadLocalRandom.current().nextInt() % ++numBestFound == 0
)
{
// this case implements random tie-breaking
bestChild = child;
}
}
return bestChild;
}
/**
* Selects the move we wish to play using the "Robust Child" strategy
* (meaning that we play the move leading to the child of the root node
* with the highest visit count).
*
* @param rootNode
* @return
*/
public static Move finalMoveSelection(final Node rootNode)
{
Node bestChild = null;
int bestVisitCount = Integer.MIN_VALUE;
int numBestFound = 0;
final int numChildren = rootNode.children.size();
for (int i = 0; i < numChildren; ++i)
{
final Node child = rootNode.children.get(i);
final int visitCount = child.visitCount;
if (visitCount > bestVisitCount)
{
bestVisitCount = visitCount;
bestChild = child;
numBestFound = 1;
}
else if
(
visitCount == bestVisitCount &&
ThreadLocalRandom.current().nextInt() % ++numBestFound == 0
)
{
// this case implements random tie-breaking
bestChild = child;
}
}
return bestChild.moveFromParent;
}
@Override
public void initAI(final Game game, final int playerID)
{
this.player = playerID;
}
@Override
public boolean supportsGame(final Game game)
{
if (game.isStochasticGame())
return false;
if (!game.isAlternatingMoveGame())
return false;
return true;
}
//-------------------------------------------------------------------------
/**
* Inner class for nodes used by example UCT
*
* @author Dennis Soemers
*/
private static class Node
{
/** Our parent node */
private final Node parent;
/** The move that led from parent to this node */
private final Move moveFromParent;
/** This objects contains the game state for this node (this is why we don't support stochastic games) */
private final Context context;
/** Visit count for this node */
private int visitCount = 0;
/** For every player, sum of utilities / scores backpropagated through this node */
private final double[] scoreSums;
/** Child nodes */
private final List<Node> children = new ArrayList<Node>();
/** List of moves for which we did not yet create a child node */
private final FastArrayList<Move> unexpandedMoves;
/**
* Constructor
*
* @param parent
* @param moveFromParent
* @param context
*/
public Node(final Node parent, final Move moveFromParent, final Context context)
{
this.parent = parent;
this.moveFromParent = moveFromParent;
this.context = context;
final Game game = context.game();
scoreSums = new double[game.players().count() + 1];
// For simplicity, we just take ALL legal moves.
// This means we do not support simultaneous-move games.
unexpandedMoves = new FastArrayList<Move>(game.moves(context).moves());
if (parent != null)
parent.children.add(this);
}
}
//-------------------------------------------------------------------------
}