uct_search(): Determine number of simulations locally, not within uct_genmove()
[pachi.git] / uct / tree.c
blobc22593ba50f1f29db7a1491568945ec42c72a72a
1 #include <assert.h>
2 #include <math.h>
3 #include <stddef.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #define DEBUG
10 #include "board.h"
11 #include "debug.h"
12 #include "engine.h"
13 #include "move.h"
14 #include "playout.h"
15 #include "tactics.h"
16 #include "uct/internal.h"
17 #include "uct/prior.h"
18 #include "uct/tree.h"
21 /* This function may be called by multiple threads in parallel */
22 static struct tree_node *
23 tree_init_node(struct tree *t, coord_t coord, int depth)
25 struct tree_node *n = calloc(1, sizeof(*n));
26 if (!n) {
27 fprintf(stderr, "tree_init_node(): OUT OF MEMORY\n");
28 exit(1);
30 __sync_fetch_and_add(&t->nodes_size, sizeof(*n));
31 n->coord = coord;
32 n->depth = depth;
33 volatile static long c = 1000000;
34 n->hash = __sync_fetch_and_add(&c, 1);
35 if (depth > t->max_depth)
36 t->max_depth = depth;
37 return n;
40 struct tree *
41 tree_init(struct board *board, enum stone color)
43 struct tree *t = calloc(1, sizeof(*t));
44 t->board = board;
45 /* The root PASS move is only virtual, we never play it. */
46 t->root = tree_init_node(t, pass, 0);
47 t->root_symmetry = board->symmetry;
48 t->root_color = stone_other(color); // to research black moves, root will be white
49 return t;
53 static void
54 tree_done_node(struct tree *t, struct tree_node *n)
56 struct tree_node *ni = n->children;
57 while (ni) {
58 struct tree_node *nj = ni->sibling;
59 tree_done_node(t, ni);
60 ni = nj;
62 t->nodes_size -= sizeof(*n); // atomic operation not needed here
63 free(n);
66 void
67 tree_done(struct tree *t)
69 tree_done_node(t, t->root);
70 if (t->chchvals) free(t->chchvals);
71 if (t->chvals) free(t->chvals);
72 free(t);
76 static void
77 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
79 for (int i = 0; i < l; i++) fputc(' ', stderr);
80 int children = 0;
81 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
82 children++;
83 /* We use 1 as parity, since for all nodes we want to know the
84 * win probability of _us_, not the node color. */
85 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
86 coord2sstr(node->coord, tree->board),
87 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
88 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
89 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
90 node->hints, children, node->hash);
92 /* Print nodes sorted by #playouts. */
94 struct tree_node *nbox[1000]; int nboxl = 0;
95 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
96 if (ni->u.playouts > thres)
97 nbox[nboxl++] = ni;
99 while (true) {
100 int best = -1;
101 for (int i = 0; i < nboxl; i++)
102 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
103 best = i;
104 if (best < 0)
105 break;
106 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
107 nbox[best] = NULL;
111 void
112 tree_dump_chval(struct tree *tree, struct move_stats *v)
114 for (int y = board_size(tree->board) - 2; y > 1; y--) {
115 for (int x = 1; x < board_size(tree->board) - 1; x++) {
116 coord_t c = coord_xy(tree->board, x, y);
117 fprintf(stderr, "%.2f%%%05d ", v[c].value, v[c].playouts);
119 fprintf(stderr, "\n");
123 void
124 tree_dump(struct tree *tree, int thres)
126 if (thres && tree->root->u.playouts / thres > 100) {
127 /* Be a bit sensible about this; the opening book can create
128 * huge dumps at first. */
129 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
131 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
132 stone2str(tree->root_color), tree->extra_komi);
133 tree_node_dump(tree, tree->root, 0, thres);
135 if (DEBUGL(3) && tree->chvals) {
136 fprintf(stderr, "children stats:\n");
137 tree_dump_chval(tree, tree->chvals);
138 fprintf(stderr, "grandchildren stats:\n");
139 tree_dump_chval(tree, tree->chchvals);
144 static char *
145 tree_book_name(struct board *b)
147 static char buf[256];
148 if (b->handicap > 0) {
149 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
150 } else {
151 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
153 return buf;
156 static void
157 tree_node_save(FILE *f, struct tree_node *node, int thres)
159 fputc(1, f);
160 fwrite(((void *) node) + offsetof(struct tree_node, depth),
161 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
162 1, f);
164 if (node->u.playouts >= thres)
165 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
166 tree_node_save(f, ni, thres);
168 fputc(0, f);
171 void
172 tree_save(struct tree *tree, struct board *b, int thres)
174 char *filename = tree_book_name(b);
175 FILE *f = fopen(filename, "wb");
176 if (!f) {
177 perror("fopen");
178 return;
180 tree_node_save(f, tree->root, thres);
181 fputc(0, f);
182 fclose(f);
186 void
187 tree_node_load(FILE *f, struct tree_node *node, int *num)
189 (*num)++;
191 fread(((void *) node) + offsetof(struct tree_node, depth),
192 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
193 1, f);
195 /* Keep values in sane scale, otherwise we start overflowing. */
196 #define MAX_PLAYOUTS 10000000
197 if (node->u.playouts > MAX_PLAYOUTS) {
198 node->u.playouts = MAX_PLAYOUTS;
200 if (node->amaf.playouts > MAX_PLAYOUTS) {
201 node->amaf.playouts = MAX_PLAYOUTS;
204 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
205 memcpy(&node->pu, &node->u, sizeof(node->u));
207 struct tree_node *ni = NULL, *ni_prev = NULL;
208 while (fgetc(f)) {
209 ni_prev = ni; ni = calloc(1, sizeof(*ni));
210 if (!node->children)
211 node->children = ni;
212 else
213 ni_prev->sibling = ni;
214 ni->parent = node;
215 tree_node_load(f, ni, num);
219 void
220 tree_load(struct tree *tree, struct board *b)
222 char *filename = tree_book_name(b);
223 FILE *f = fopen(filename, "rb");
224 if (!f)
225 return;
227 fprintf(stderr, "Loading opening book %s...\n", filename);
229 int num = 0;
230 if (fgetc(f))
231 tree_node_load(f, tree->root, &num);
232 fprintf(stderr, "Loaded %d nodes.\n", num);
234 fclose(f);
238 static struct tree_node *
239 tree_node_copy(struct tree_node *node)
241 struct tree_node *n2 = malloc(sizeof(*n2));
242 *n2 = *node;
243 if (!node->children)
244 return n2;
245 struct tree_node *ni = node->children;
246 struct tree_node *ni2 = tree_node_copy(ni);
247 n2->children = ni2; ni2->parent = n2;
248 while ((ni = ni->sibling)) {
249 ni2->sibling = tree_node_copy(ni);
250 ni2 = ni2->sibling; ni2->parent = n2;
252 return n2;
255 struct tree *
256 tree_copy(struct tree *tree)
258 struct tree *t2 = malloc(sizeof(*t2));
259 *t2 = *tree;
260 t2->root = tree_node_copy(tree->root);
261 return t2;
265 static void
266 tree_node_merge(struct tree_node *dest, struct tree_node *src)
268 /* Do not merge nodes that weren't touched at all. */
269 assert(dest->pamaf.playouts == src->pamaf.playouts);
270 assert(dest->pu.playouts == src->pu.playouts);
271 if (src->amaf.playouts - src->pamaf.playouts == 0
272 && src->u.playouts - src->pu.playouts == 0) {
273 return;
276 dest->hints |= src->hints;
278 /* Merge the children, both are coord-sorted lists. */
279 struct tree_node *di = dest->children, **dref = &dest->children;
280 struct tree_node *si = src->children, **sref = &src->children;
281 while (di && si) {
282 if (di->coord != si->coord) {
283 /* src has some extra items or misses di */
284 struct tree_node *si2 = si->sibling;
285 while (si2 && di->coord != si2->coord) {
286 si2 = si2->sibling;
288 if (!si2)
289 goto next_di; /* src misses di, move on */
290 /* chain the extra [si,si2) items before di */
291 (*dref) = si;
292 while (si->sibling != si2) {
293 si->parent = dest;
294 si = si->sibling;
296 si->parent = dest;
297 si->sibling = di;
298 si = si2;
299 (*sref) = si;
301 /* Matching nodes - recurse... */
302 tree_node_merge(di, si);
303 /* ...and move on. */
304 sref = &si->sibling; si = si->sibling;
305 next_di:
306 dref = &di->sibling; di = di->sibling;
308 if (si) {
309 /* Some outstanding nodes are left on src side, rechain
310 * them to dst. */
311 (*dref) = si;
312 while (si) {
313 si->parent = dest;
314 si = si->sibling;
316 (*sref) = NULL;
319 /* Priors should be constant. */
320 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
322 stats_merge(&dest->amaf, &src->amaf);
323 stats_merge(&dest->u, &src->u);
326 /* Merge two trees built upon the same board. Note that the operation is
327 * destructive on src. */
328 void
329 tree_merge(struct tree *dest, struct tree *src)
331 if (src->max_depth > dest->max_depth)
332 dest->max_depth = src->max_depth;
333 tree_node_merge(dest->root, src->root);
337 static void
338 tree_node_normalize(struct tree_node *node, int factor)
340 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
341 tree_node_normalize(ni, factor);
343 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
344 normalize(pamaf, amaf, playouts);
345 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
347 normalize(pu, u, playouts);
348 memcpy(&node->pu, &node->u, sizeof(node->u));
349 #undef normalize
352 /* Normalize a tree, dividing the amaf and u values by given
353 * factor; otherwise, simulations run in independent threads
354 * two trees built upon the same board. To correctly handle
355 * results taken from previous simulation run, they are backed
356 * up in tree. */
357 void
358 tree_normalize(struct tree *tree, int factor)
360 tree_node_normalize(tree->root, factor);
364 /* Get a node of given coordinate from within parent, possibly creating it
365 * if necessary - in a very raw form (no .d, priors, ...). */
366 /* FIXME: Adjust for board symmetry. */
367 struct tree_node *
368 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
370 if (!parent->children || parent->children->coord >= c) {
371 /* Special case: Insertion at the beginning. */
372 if (parent->children && parent->children->coord == c)
373 return parent->children;
374 if (!create)
375 return NULL;
377 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
378 nn->parent = parent; nn->sibling = parent->children;
379 parent->children = nn;
380 return nn;
383 /* No candidate at the beginning, look through all the children. */
385 struct tree_node *ni;
386 for (ni = parent->children; ni->sibling; ni = ni->sibling)
387 if (ni->sibling->coord >= c)
388 break;
390 if (ni->sibling && ni->sibling->coord == c)
391 return ni->sibling;
392 assert(ni->coord < c);
393 if (!create)
394 return NULL;
396 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
397 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
398 return nn;
402 /* Tree symmetry: When possible, we will localize the tree to a single part
403 * of the board in tree_expand_node() and possibly flip along symmetry axes
404 * to another part of the board in tree_promote_at(). We follow b->symmetry
405 * guidelines here. */
408 void
409 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
411 /* Get a Common Fate Graph distance map from parent node. */
412 int distances[board_size2(b)];
413 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
414 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
415 } else {
416 // Pass or resign - everything is too far.
417 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
420 /* Get a map of prior values to initialize the new nodes with. */
421 struct prior_map map = {
422 .b = b,
423 .to_play = color,
424 .parity = tree_parity(t, parity),
425 .distances = distances,
427 // Include pass in the prior map.
428 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
429 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
430 memset(map_prior, 0, sizeof(map_prior));
431 memset(map_consider, 0, sizeof(map_consider));
432 struct move pm = { .color = color };
433 map.consider[pass] = true;
434 foreach_point(b) {
435 if (board_at(b, c) != S_NONE)
436 continue;
437 pm.coord = c;
438 if (!board_is_valid_move(b, &pm))
439 continue;
440 map.consider[c] = true;
441 } foreach_point_end;
442 uct_prior(u, node, &map);
444 /* Now, create the nodes. */
445 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1);
446 struct tree_node *first_child = ni;
447 ni->parent = node;
448 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
450 /* The loop considers only the symmetry playground. */
451 if (UDEBUGL(6)) {
452 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
453 coord2sstr(node->coord, b),
454 b->symmetry.x1, b->symmetry.y1,
455 b->symmetry.x2, b->symmetry.y2,
456 b->symmetry.type, b->symmetry.d);
458 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
459 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
460 if (b->symmetry.d) {
461 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
462 if (x > j) {
463 if (UDEBUGL(7))
464 fprintf(stderr, "drop %d,%d\n", i, j);
465 continue;
469 coord_t c = coord_xy_otf(i, j, t->board);
470 if (!map.consider[c]) // Filter out invalid moves
471 continue;
472 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
474 struct tree_node *nj = tree_init_node(t, c, node->depth + 1);
475 nj->parent = node; ni->sibling = nj; ni = nj;
477 ni->prior = map.prior[c];
478 ni->d = distances[c];
481 node->children = first_child; // must be done at the end to avoid race
485 static coord_t
486 flip_coord(struct board *b, coord_t c,
487 bool flip_horiz, bool flip_vert, int flip_diag)
489 int x = coord_x(c, b), y = coord_y(c, b);
490 if (flip_diag) {
491 int z = x; x = y; y = z;
493 if (flip_horiz) {
494 x = board_size(b) - 1 - x;
496 if (flip_vert) {
497 y = board_size(b) - 1 - y;
499 return coord_xy_otf(x, y, b);
502 static void
503 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
504 bool flip_horiz, bool flip_vert, int flip_diag)
506 if (!is_pass(node->coord))
507 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
509 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
510 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
513 static void
514 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
516 if (is_pass(c))
517 return;
519 struct board_symmetry *s = &tree->root_symmetry;
520 int cx = coord_x(c, b), cy = coord_y(c, b);
522 /* playground X->h->v->d normalization
523 * :::.. .d...
524 * .::.. v....
525 * ..:.. .....
526 * ..... h...X
527 * ..... ..... */
528 bool flip_horiz = cx < s->x1 || cx > s->x2;
529 bool flip_vert = cy < s->y1 || cy > s->y2;
531 bool flip_diag = 0;
532 if (s->d) {
533 bool dir = (s->type == SYM_DIAG_DOWN);
534 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
535 if (flip_vert ? x < cy : x > cy) {
536 flip_diag = 1;
540 if (DEBUGL(4)) {
541 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
542 coord2sstr(c, b),
543 cx, cy, s->x1, s->y1, s->x2, s->y2,
544 flip_horiz, flip_vert, flip_diag,
545 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
546 s->type, s->d, b->symmetry.type, b->symmetry.d);
548 if (flip_horiz || flip_vert || flip_diag)
549 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
553 static void
554 tree_unlink_node(struct tree_node *node)
556 struct tree_node *ni = node->parent;
557 if (ni->children == node) {
558 ni->children = node->sibling;
559 } else {
560 ni = ni->children;
561 while (ni->sibling != node)
562 ni = ni->sibling;
563 ni->sibling = node->sibling;
565 node->sibling = NULL;
566 node->parent = NULL;
569 void
570 tree_delete_node(struct tree *tree, struct tree_node *node)
572 tree_unlink_node(node);
573 tree_done_node(tree, node);
576 void
577 tree_promote_node(struct tree *tree, struct tree_node *node)
579 assert(node->parent == tree->root);
580 tree_unlink_node(node);
581 tree_done_node(tree, tree->root);
582 tree->root = node;
583 tree->root_color = stone_other(tree->root_color);
584 board_symmetry_update(tree->board, &tree->root_symmetry, node->coord);
585 tree->max_depth--;
586 if (tree->chchvals) { free(tree->chchvals); tree->chchvals = NULL; }
587 if (tree->chvals) { free(tree->chvals); tree->chvals = NULL; }
590 bool
591 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
593 tree_fix_symmetry(tree, b, c);
595 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
596 if (ni->coord == c) {
597 tree_promote_node(tree, ni);
598 return true;
601 return false;