tree_node_normalize(): Don't divide the values too :-)
[pachi.git] / uct / tree.c
blob35d98f785a5eb59c11d1270286632bee8c063e0b
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 "uct/internal.h"
15 #include "uct/tree.h"
18 static struct tree_node *
19 tree_init_node(struct tree *t, coord_t coord, int depth)
21 struct tree_node *n = calloc(1, sizeof(*n));
22 n->coord = coord;
23 n->depth = depth;
24 static long c = 1000000;
25 n->hash = c++;
26 if (depth > t->max_depth)
27 t->max_depth = depth;
28 return n;
31 struct tree *
32 tree_init(struct board *board, enum stone color)
34 struct tree *t = calloc(1, sizeof(*t));
35 t->board = board;
36 /* The root PASS move is only virtual, we never play it. */
37 t->root = tree_init_node(t, pass, 0);
38 t->root_symmetry = board->symmetry;
39 t->root_color = stone_other(color); // to research black moves, root will be white
40 return t;
44 static void
45 tree_done_node(struct tree *t, struct tree_node *n)
47 struct tree_node *ni = n->children;
48 while (ni) {
49 struct tree_node *nj = ni->sibling;
50 tree_done_node(t, ni);
51 ni = nj;
53 free(n);
56 void
57 tree_done(struct tree *t)
59 tree_done_node(t, t->root);
60 free(t);
64 static void
65 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
67 for (int i = 0; i < l; i++) fputc(' ', stderr);
68 int children = 0;
69 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
70 children++;
71 /* We use 1 as parity, since for all nodes we want to know the
72 * win probability of _us_, not the node color. */
73 fprintf(stderr, "[%s] %f (%d/%d playouts [prior %d/%d amaf %d/%d]; hints %x; %d children) <%lld>\n",
74 coord2sstr(node->coord, tree->board),
75 tree_node_get_value(tree, node, u, 1),
76 tree_node_get_wins(tree, node, u, 1), node->u.playouts,
77 tree_node_get_wins(tree, node, prior, 1), node->prior.playouts,
78 tree_node_get_wins(tree, node, amaf, 1), node->amaf.playouts,
79 node->hints, children, node->hash);
81 /* Print nodes sorted by #playouts. */
83 struct tree_node *nbox[1000]; int nboxl = 0;
84 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
85 if (ni->u.playouts > thres)
86 nbox[nboxl++] = ni;
88 while (true) {
89 int best = -1;
90 for (int i = 0; i < nboxl; i++)
91 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
92 best = i;
93 if (best < 0)
94 break;
95 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
96 nbox[best] = NULL;
100 void
101 tree_dump(struct tree *tree, int thres)
103 if (thres && tree->root->u.playouts / thres > 100) {
104 /* Be a bit sensible about this; the opening book can create
105 * huge dumps at first. */
106 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
108 tree_node_dump(tree, tree->root, 0, thres);
112 static char *
113 tree_book_name(struct board *b)
115 static char buf[256];
116 if (b->handicap > 0) {
117 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
118 } else {
119 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
121 return buf;
124 static void
125 tree_node_save(FILE *f, struct tree_node *node, int thres)
127 fputc(1, f);
128 fwrite(((void *) node) + offsetof(struct tree_node, depth),
129 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
130 1, f);
132 if (node->u.playouts >= thres)
133 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
134 tree_node_save(f, ni, thres);
136 fputc(0, f);
139 void
140 tree_save(struct tree *tree, struct board *b, int thres)
142 char *filename = tree_book_name(b);
143 FILE *f = fopen(filename, "wb");
144 if (!f) {
145 perror("fopen");
146 return;
148 tree_node_save(f, tree->root, thres);
149 fputc(0, f);
150 fclose(f);
154 void
155 tree_node_load(FILE *f, struct tree_node *node, int *num)
157 (*num)++;
159 fread(((void *) node) + offsetof(struct tree_node, depth),
160 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
161 1, f);
163 /* Keep values in sane scale, otherwise we start overflowing.
164 * We may go slow here but we must be careful about not getting
165 * too huge integers.*/
166 #define MAX_PLAYOUTS 10000000
167 if (node->u.playouts > MAX_PLAYOUTS) {
168 int over = node->u.playouts - MAX_PLAYOUTS;
169 node->u.wins -= ((double) node->u.wins / node->u.playouts) * over;
170 node->u.playouts = MAX_PLAYOUTS;
172 if (node->amaf.playouts > MAX_PLAYOUTS) {
173 int over = node->amaf.playouts - MAX_PLAYOUTS;
174 node->amaf.wins -= ((double) node->amaf.wins / node->amaf.playouts) * over;
175 node->amaf.playouts = MAX_PLAYOUTS;
178 struct tree_node *ni = NULL, *ni_prev = NULL;
179 while (fgetc(f)) {
180 ni_prev = ni; ni = calloc(1, sizeof(*ni));
181 if (!node->children)
182 node->children = ni;
183 else
184 ni_prev->sibling = ni;
185 ni->parent = node;
186 tree_node_load(f, ni, num);
190 void
191 tree_load(struct tree *tree, struct board *b)
193 char *filename = tree_book_name(b);
194 FILE *f = fopen(filename, "rb");
195 if (!f)
196 return;
198 fprintf(stderr, "Loading opening book %s...\n", filename);
200 int num = 0;
201 if (fgetc(f))
202 tree_node_load(f, tree->root, &num);
203 fprintf(stderr, "Loaded %d nodes.\n", num);
205 fclose(f);
209 static struct tree_node *
210 tree_node_copy(struct tree_node *node)
212 struct tree_node *n2 = malloc(sizeof(*n2));
213 *n2 = *node;
214 if (!node->children)
215 return n2;
216 struct tree_node *ni = node->children;
217 struct tree_node *ni2 = tree_node_copy(ni);
218 n2->children = ni2; ni2->parent = n2;
219 while ((ni = ni->sibling)) {
220 ni2->sibling = tree_node_copy(ni);
221 ni2 = ni2->sibling; ni2->parent = n2;
223 return n2;
226 struct tree *
227 tree_copy(struct tree *tree)
229 struct tree *t2 = malloc(sizeof(*t2));
230 *t2 = *tree;
231 t2->root = tree_node_copy(tree->root);
232 return t2;
236 static void
237 tree_node_merge(struct tree_node *dest, struct tree_node *src)
239 dest->hints |= src->hints;
241 /* Merge the children, both are coord-sorted lists. */
242 struct tree_node *di = dest->children, **dref = &dest->children;
243 struct tree_node *si = src->children, **sref = &src->children;
244 while (di && si) {
245 if (di->coord != si->coord) {
246 /* src has some extra items or misses di */
247 struct tree_node *si2 = si->sibling;
248 while (si2 && di->coord != si2->coord) {
249 si2 = si2->sibling;
251 if (!si2)
252 goto next_di; /* src misses di, move on */
253 /* chain the extra [si,si2) items before di */
254 (*dref) = si;
255 while (si->sibling != si2) {
256 si->parent = dest;
257 si = si->sibling;
259 si->parent = dest;
260 si->sibling = di;
261 si = si2;
262 (*sref) = si;
264 /* Matching nodes - recurse... */
265 tree_node_merge(di, si);
266 /* ...and move on. */
267 sref = &si->sibling; si = si->sibling;
268 next_di:
269 dref = &di->sibling; di = di->sibling;
271 if (si) {
272 /* Some outstanding nodes are left on src side, rechain
273 * them to dst. */
274 (*dref) = si;
275 while (si) {
276 si->parent = dest;
277 si = si->sibling;
279 (*sref) = NULL;
282 /* Priors should be constant. */
283 assert(dest->prior.playouts == src->prior.playouts && dest->prior.wins == src->prior.wins);
285 dest->amaf.playouts += src->amaf.playouts;
286 dest->amaf.wins += src->amaf.wins;
287 if (dest->amaf.playouts)
288 dest->amaf.value = (float) dest->amaf.wins / dest->amaf.playouts;
290 dest->u.playouts += src->u.playouts;
291 dest->u.wins += src->u.wins;
292 if (dest->prior.playouts + dest->amaf.playouts + dest->u.playouts)
293 tree_update_node_value(dest);
296 /* Merge two trees built upon the same board. Note that the operation is
297 * destructive on src. */
298 void
299 tree_merge(struct tree *dest, struct tree *src)
301 if (src->max_depth > dest->max_depth)
302 dest->max_depth = src->max_depth;
303 tree_node_merge(dest->root, src->root);
307 static void
308 tree_node_normalize(struct tree_node *node, int factor)
310 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
311 tree_node_normalize(ni, factor);
313 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
314 normalize(pamaf, amaf, playouts);
315 normalize(pamaf, amaf, wins);
316 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
318 normalize(pu, u, playouts);
319 normalize(pu, u, wins);
320 memcpy(&node->pu, &node->u, sizeof(node->u));
321 #undef normalize
324 /* Normalize a tree, dividing the amaf and u values by given
325 * factor; otherwise, simulations run in independent threads
326 * two trees built upon the same board. To correctly handle
327 * results taken from previous simulation run, they are backed
328 * up in tree. */
329 void
330 tree_normalize(struct tree *tree, int factor)
332 tree_node_normalize(tree->root, factor);
336 /* Tree symmetry: When possible, we will localize the tree to a single part
337 * of the board in tree_expand_node() and possibly flip along symmetry axes
338 * to another part of the board in tree_promote_at(). We follow b->symmetry
339 * guidelines here. */
342 void
343 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, int radar, struct uct_policy *policy, int parity)
345 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1);
346 ni->parent = node; node->children = ni;
347 if (policy->prior)
348 policy->prior(policy, t, ni, b, color, parity);
350 /* The loop considers only the symmetry playground. */
351 if (UDEBUGL(6)) {
352 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
353 coord2sstr(node->coord, b),
354 b->symmetry.x1, b->symmetry.y1,
355 b->symmetry.x2, b->symmetry.y2,
356 b->symmetry.type, b->symmetry.d);
358 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
359 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
360 if (b->symmetry.d) {
361 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
362 if (x > j) {
363 if (UDEBUGL(7))
364 fprintf(stderr, "drop %d,%d\n", i, j);
365 continue;
369 coord_t c = coord_xy_otf(i, j, t->board);
370 if (board_at(b, c) != S_NONE)
371 continue;
372 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
373 /* This looks very useful on large boards - weeds out huge amount of crufty moves. */
374 if (b->hash /* not empty board */ && radar && !board_stone_radar(b, c, radar))
375 continue;
377 struct tree_node *nj = tree_init_node(t, c, node->depth + 1);
378 nj->parent = node; ni->sibling = nj; ni = nj;
380 if (policy->prior)
381 policy->prior(policy, t, ni, b, color, parity);
387 static coord_t
388 flip_coord(struct board *b, coord_t c,
389 bool flip_horiz, bool flip_vert, int flip_diag)
391 int x = coord_x(c, b), y = coord_y(c, b);
392 if (flip_diag) {
393 int z = x; x = y; y = z;
395 if (flip_horiz) {
396 x = board_size(b) - 1 - x;
398 if (flip_vert) {
399 y = board_size(b) - 1 - y;
401 return coord_xy_otf(x, y, b);
404 static void
405 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
406 bool flip_horiz, bool flip_vert, int flip_diag)
408 if (!is_pass(node->coord))
409 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
411 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
412 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
415 static void
416 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
418 if (is_pass(c))
419 return;
421 struct board_symmetry *s = &tree->root_symmetry;
422 int cx = coord_x(c, b), cy = coord_y(c, b);
424 /* playground X->h->v->d normalization
425 * :::.. .d...
426 * .::.. v....
427 * ..:.. .....
428 * ..... h...X
429 * ..... ..... */
430 bool flip_horiz = cx < s->x1 || cx > s->x2;
431 bool flip_vert = cy < s->y1 || cy > s->y2;
433 bool flip_diag = 0;
434 if (s->d) {
435 bool dir = (s->type == SYM_DIAG_DOWN);
436 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
437 if (flip_vert ? x < cy : x > cy) {
438 flip_diag = 1;
442 if (UDEBUGL(4)) {
443 fprintf(stderr, "%s will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
444 coord2sstr(c, b), flip_horiz, flip_vert, flip_diag,
445 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
446 s->type, s->d, b->symmetry.type, b->symmetry.d);
448 if (flip_horiz || flip_vert || flip_diag)
449 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
453 static void
454 tree_unlink_node(struct tree_node *node)
456 struct tree_node *ni = node->parent;
457 if (ni->children == node) {
458 ni->children = node->sibling;
459 } else {
460 ni = ni->children;
461 while (ni->sibling != node)
462 ni = ni->sibling;
463 ni->sibling = node->sibling;
465 node->sibling = NULL;
466 node->parent = NULL;
469 void
470 tree_delete_node(struct tree *tree, struct tree_node *node)
472 tree_unlink_node(node);
473 tree_done_node(tree, node);
476 void
477 tree_promote_node(struct tree *tree, struct tree_node *node)
479 assert(node->parent == tree->root);
480 tree_unlink_node(node);
481 tree_done_node(tree, tree->root);
482 tree->root = node;
483 tree->root_color = stone_other(tree->root_color);
484 board_symmetry_update(tree->board, &tree->root_symmetry, node->coord);
487 bool
488 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
490 tree_fix_symmetry(tree, b, c);
492 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
493 if (ni->coord == c) {
494 tree_promote_node(tree, ni);
495 return true;
498 return false;
501 bool
502 tree_leaf_node(struct tree_node *node)
504 return !(node->children);
507 void
508 tree_update_node_value(struct tree_node *node)
510 bool noamaf = node->hints & NODE_HINT_NOAMAF;
511 node->u.value = (float)(node->u.wins + node->prior.wins + (!noamaf ? node->amaf.wins : 0))
512 / (node->u.playouts + node->prior.playouts + (!noamaf ? node->amaf.playouts : 0));
513 #if 0
514 { struct board b2; board_size(&b2) = 9+2;
515 fprintf(stderr, "%s->%s %d/%d %d/%d %f\n", node->parent ? coord2sstr(node->parent->coord, &b2) : NULL, coord2sstr(node->coord, &b2), node->u.wins, node->u.playouts, node->prior.wins, node->prior.playouts, node->u.value); }
516 #endif