TESTS: Few historical 19x19 results
[pachi.git] / uct / tree.c
blobfe74d788b15a329a5aea9ecbb54e3b05962f843e
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 #include "board.h"
10 #include "debug.h"
11 #include "engine.h"
12 #include "move.h"
13 #include "playout.h"
14 #include "tactics.h"
15 #include "uct/internal.h"
16 #include "uct/prior.h"
17 #include "uct/tree.h"
20 static struct tree_node *
21 tree_init_node(struct tree *t, coord_t coord, int depth)
23 struct tree_node *n = calloc(1, sizeof(*n));
24 if (!n) {
25 fprintf(stderr, "tree_init_node(): OUT OF MEMORY\n");
26 exit(1);
28 n->coord = coord;
29 n->depth = depth;
30 static long c = 1000000;
31 n->hash = c++;
32 if (depth > t->max_depth)
33 t->max_depth = depth;
34 return n;
37 struct tree *
38 tree_init(struct board *board, enum stone color)
40 struct tree *t = calloc(1, sizeof(*t));
41 t->board = board;
42 /* The root PASS move is only virtual, we never play it. */
43 t->root = tree_init_node(t, pass, 0);
44 t->root_symmetry = board->symmetry;
45 t->root_color = stone_other(color); // to research black moves, root will be white
46 return t;
50 static void
51 tree_done_node(struct tree *t, struct tree_node *n)
53 struct tree_node *ni = n->children;
54 while (ni) {
55 struct tree_node *nj = ni->sibling;
56 tree_done_node(t, ni);
57 ni = nj;
59 free(n);
62 void
63 tree_done(struct tree *t)
65 tree_done_node(t, t->root);
66 free(t);
70 static void
71 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
73 for (int i = 0; i < l; i++) fputc(' ', stderr);
74 int children = 0;
75 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
76 children++;
77 /* We use 1 as parity, since for all nodes we want to know the
78 * win probability of _us_, not the node color. */
79 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%lld>\n",
80 coord2sstr(node->coord, tree->board),
81 tree_node_get_value(tree, node, u, 1), node->u.playouts,
82 tree_node_get_value(tree, node, prior, 1), node->prior.playouts,
83 tree_node_get_value(tree, node, amaf, 1), node->amaf.playouts,
84 node->hints, children, node->hash);
86 /* Print nodes sorted by #playouts. */
88 struct tree_node *nbox[1000]; int nboxl = 0;
89 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
90 if (ni->u.playouts > thres)
91 nbox[nboxl++] = ni;
93 while (true) {
94 int best = -1;
95 for (int i = 0; i < nboxl; i++)
96 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
97 best = i;
98 if (best < 0)
99 break;
100 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
101 nbox[best] = NULL;
105 void
106 tree_dump(struct tree *tree, int thres)
108 if (thres && tree->root->u.playouts / thres > 100) {
109 /* Be a bit sensible about this; the opening book can create
110 * huge dumps at first. */
111 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
113 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
114 stone2str(tree->root_color), tree->extra_komi);
115 tree_node_dump(tree, tree->root, 0, thres);
119 static char *
120 tree_book_name(struct board *b)
122 static char buf[256];
123 if (b->handicap > 0) {
124 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
125 } else {
126 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
128 return buf;
131 static void
132 tree_node_save(FILE *f, struct tree_node *node, int thres)
134 fputc(1, f);
135 fwrite(((void *) node) + offsetof(struct tree_node, depth),
136 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
137 1, f);
139 if (node->u.playouts >= thres)
140 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
141 tree_node_save(f, ni, thres);
143 fputc(0, f);
146 void
147 tree_save(struct tree *tree, struct board *b, int thres)
149 char *filename = tree_book_name(b);
150 FILE *f = fopen(filename, "wb");
151 if (!f) {
152 perror("fopen");
153 return;
155 tree_node_save(f, tree->root, thres);
156 fputc(0, f);
157 fclose(f);
161 void
162 tree_node_load(FILE *f, struct tree_node *node, int *num)
164 (*num)++;
166 fread(((void *) node) + offsetof(struct tree_node, depth),
167 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
168 1, f);
170 /* Keep values in sane scale, otherwise we start overflowing. */
171 #define MAX_PLAYOUTS 10000000
172 if (node->u.playouts > MAX_PLAYOUTS) {
173 node->u.playouts = MAX_PLAYOUTS;
175 if (node->amaf.playouts > MAX_PLAYOUTS) {
176 node->amaf.playouts = MAX_PLAYOUTS;
179 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
180 memcpy(&node->pu, &node->u, sizeof(node->u));
182 struct tree_node *ni = NULL, *ni_prev = NULL;
183 while (fgetc(f)) {
184 ni_prev = ni; ni = calloc(1, sizeof(*ni));
185 if (!node->children)
186 node->children = ni;
187 else
188 ni_prev->sibling = ni;
189 ni->parent = node;
190 tree_node_load(f, ni, num);
194 void
195 tree_load(struct tree *tree, struct board *b)
197 char *filename = tree_book_name(b);
198 FILE *f = fopen(filename, "rb");
199 if (!f)
200 return;
202 fprintf(stderr, "Loading opening book %s...\n", filename);
204 int num = 0;
205 if (fgetc(f))
206 tree_node_load(f, tree->root, &num);
207 fprintf(stderr, "Loaded %d nodes.\n", num);
209 fclose(f);
213 static struct tree_node *
214 tree_node_copy(struct tree_node *node)
216 struct tree_node *n2 = malloc(sizeof(*n2));
217 *n2 = *node;
218 if (!node->children)
219 return n2;
220 struct tree_node *ni = node->children;
221 struct tree_node *ni2 = tree_node_copy(ni);
222 n2->children = ni2; ni2->parent = n2;
223 while ((ni = ni->sibling)) {
224 ni2->sibling = tree_node_copy(ni);
225 ni2 = ni2->sibling; ni2->parent = n2;
227 return n2;
230 struct tree *
231 tree_copy(struct tree *tree)
233 struct tree *t2 = malloc(sizeof(*t2));
234 *t2 = *tree;
235 t2->root = tree_node_copy(tree->root);
236 return t2;
240 static void
241 tree_node_merge(struct tree_node *dest, struct tree_node *src)
243 /* Do not merge nodes that weren't touched at all. */
244 assert(dest->pamaf.playouts == src->pamaf.playouts);
245 assert(dest->pu.playouts == src->pu.playouts);
246 if (src->amaf.playouts - src->pamaf.playouts == 0
247 && src->u.playouts - src->pu.playouts == 0) {
248 return;
251 dest->hints |= src->hints;
253 /* Merge the children, both are coord-sorted lists. */
254 struct tree_node *di = dest->children, **dref = &dest->children;
255 struct tree_node *si = src->children, **sref = &src->children;
256 while (di && si) {
257 if (di->coord != si->coord) {
258 /* src has some extra items or misses di */
259 struct tree_node *si2 = si->sibling;
260 while (si2 && di->coord != si2->coord) {
261 si2 = si2->sibling;
263 if (!si2)
264 goto next_di; /* src misses di, move on */
265 /* chain the extra [si,si2) items before di */
266 (*dref) = si;
267 while (si->sibling != si2) {
268 si->parent = dest;
269 si = si->sibling;
271 si->parent = dest;
272 si->sibling = di;
273 si = si2;
274 (*sref) = si;
276 /* Matching nodes - recurse... */
277 tree_node_merge(di, si);
278 /* ...and move on. */
279 sref = &si->sibling; si = si->sibling;
280 next_di:
281 dref = &di->sibling; di = di->sibling;
283 if (si) {
284 /* Some outstanding nodes are left on src side, rechain
285 * them to dst. */
286 (*dref) = si;
287 while (si) {
288 si->parent = dest;
289 si = si->sibling;
291 (*sref) = NULL;
294 /* Priors should be constant. */
295 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
297 stats_merge(&dest->amaf, &src->amaf);
298 stats_merge(&dest->u, &src->u);
301 /* Merge two trees built upon the same board. Note that the operation is
302 * destructive on src. */
303 void
304 tree_merge(struct tree *dest, struct tree *src)
306 if (src->max_depth > dest->max_depth)
307 dest->max_depth = src->max_depth;
308 tree_node_merge(dest->root, src->root);
312 static void
313 tree_node_normalize(struct tree_node *node, int factor)
315 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
316 tree_node_normalize(ni, factor);
318 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
319 normalize(pamaf, amaf, playouts);
320 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
322 normalize(pu, u, playouts);
323 memcpy(&node->pu, &node->u, sizeof(node->u));
324 #undef normalize
327 /* Normalize a tree, dividing the amaf and u values by given
328 * factor; otherwise, simulations run in independent threads
329 * two trees built upon the same board. To correctly handle
330 * results taken from previous simulation run, they are backed
331 * up in tree. */
332 void
333 tree_normalize(struct tree *tree, int factor)
335 tree_node_normalize(tree->root, factor);
339 /* Tree symmetry: When possible, we will localize the tree to a single part
340 * of the board in tree_expand_node() and possibly flip along symmetry axes
341 * to another part of the board in tree_promote_at(). We follow b->symmetry
342 * guidelines here. */
345 void
346 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, int radar, struct uct *u, int parity)
348 /* First, get a map of prior values to initialize the new
349 * nodes with. */
350 struct prior_map map = {
351 .b = b,
352 .to_play = color,
353 .parity = tree_parity(t, parity),
355 // Include pass in the prior map.
356 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
357 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
358 memset(map_prior, 0, sizeof(map_prior));
359 memset(map_consider, 0, sizeof(map_consider));
360 struct move pm = { .color = color };
361 map.consider[pass] = true;
362 foreach_point(b) {
363 if (board_at(b, c) != S_NONE)
364 continue;
365 /* This looks very useful on large boards - weeds out huge amount of crufty moves. */
366 if (b->hash /* not empty board */ && radar && !board_stone_radar(b, c, radar))
367 continue;
368 pm.coord = c;
369 if (!board_is_valid_move(b, &pm))
370 continue;
371 map.consider[c] = true;
372 } foreach_point_end;
373 uct_prior(u, node, &map);
375 /* Now, create the nodes. */
376 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1);
377 ni->parent = node; node->children = ni;
378 ni->prior = map.prior[pass];
380 /* The loop considers only the symmetry playground. */
381 if (UDEBUGL(6)) {
382 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
383 coord2sstr(node->coord, b),
384 b->symmetry.x1, b->symmetry.y1,
385 b->symmetry.x2, b->symmetry.y2,
386 b->symmetry.type, b->symmetry.d);
388 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
389 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
390 if (b->symmetry.d) {
391 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
392 if (x > j) {
393 if (UDEBUGL(7))
394 fprintf(stderr, "drop %d,%d\n", i, j);
395 continue;
399 coord_t c = coord_xy_otf(i, j, t->board);
400 if (!map.consider[c]) // Filter out invalid moves
401 continue;
402 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
404 struct tree_node *nj = tree_init_node(t, c, node->depth + 1);
405 nj->parent = node; ni->sibling = nj; ni = nj;
407 ni->prior = map.prior[c];
413 static coord_t
414 flip_coord(struct board *b, coord_t c,
415 bool flip_horiz, bool flip_vert, int flip_diag)
417 int x = coord_x(c, b), y = coord_y(c, b);
418 if (flip_diag) {
419 int z = x; x = y; y = z;
421 if (flip_horiz) {
422 x = board_size(b) - 1 - x;
424 if (flip_vert) {
425 y = board_size(b) - 1 - y;
427 return coord_xy_otf(x, y, b);
430 static void
431 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
432 bool flip_horiz, bool flip_vert, int flip_diag)
434 if (!is_pass(node->coord))
435 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
437 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
438 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
441 static void
442 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
444 if (is_pass(c))
445 return;
447 struct board_symmetry *s = &tree->root_symmetry;
448 int cx = coord_x(c, b), cy = coord_y(c, b);
450 /* playground X->h->v->d normalization
451 * :::.. .d...
452 * .::.. v....
453 * ..:.. .....
454 * ..... h...X
455 * ..... ..... */
456 bool flip_horiz = cx < s->x1 || cx > s->x2;
457 bool flip_vert = cy < s->y1 || cy > s->y2;
459 bool flip_diag = 0;
460 if (s->d) {
461 bool dir = (s->type == SYM_DIAG_DOWN);
462 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
463 if (flip_vert ? x < cy : x > cy) {
464 flip_diag = 1;
468 if (UDEBUGL(4)) {
469 fprintf(stderr, "%s will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
470 coord2sstr(c, b), flip_horiz, flip_vert, flip_diag,
471 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
472 s->type, s->d, b->symmetry.type, b->symmetry.d);
474 if (flip_horiz || flip_vert || flip_diag)
475 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
479 static void
480 tree_unlink_node(struct tree_node *node)
482 struct tree_node *ni = node->parent;
483 if (ni->children == node) {
484 ni->children = node->sibling;
485 } else {
486 ni = ni->children;
487 while (ni->sibling != node)
488 ni = ni->sibling;
489 ni->sibling = node->sibling;
491 node->sibling = NULL;
492 node->parent = NULL;
495 void
496 tree_delete_node(struct tree *tree, struct tree_node *node)
498 tree_unlink_node(node);
499 tree_done_node(tree, node);
502 void
503 tree_promote_node(struct tree *tree, struct tree_node *node)
505 assert(node->parent == tree->root);
506 tree_unlink_node(node);
507 tree_done_node(tree, tree->root);
508 tree->root = node;
509 tree->root_color = stone_other(tree->root_color);
510 board_symmetry_update(tree->board, &tree->root_symmetry, node->coord);
513 bool
514 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
516 tree_fix_symmetry(tree, b, c);
518 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
519 if (ni->coord == c) {
520 tree_promote_node(tree, ni);
521 return true;
524 return false;