zzgo.c: Add verbose_logs variable to avoid huge logs.
[pachi/ann.git] / uct / tree.c
blobf6270c347815309b5358cb0298c9b6207be71f42
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 "timeinfo.h"
17 #include "uct/internal.h"
18 #include "uct/prior.h"
19 #include "uct/tree.h"
22 /* Allocate one node in the fast_alloc mode. The returned node
23 * is _not_ initialized. Returns NULL if not enough memory.
24 * This function may be called by multiple threads in parallel. */
25 static struct tree_node *
26 tree_fast_alloc_node(struct tree *t)
28 assert(t->nodes != NULL);
29 struct tree_node *n = NULL;
30 unsigned long old_size =__sync_fetch_and_add(&t->nodes_size, sizeof(*n));
32 /* The test below works even if max_tree_size is not a
33 * multiple of the node size because tree_init() allocates
34 * space for an extra node. */
35 if (old_size < t->max_tree_size)
36 n = (struct tree_node *)(t->nodes + old_size);
37 return n;
40 /* Allocate and initialize a node. Returns NULL (fast_alloc mode)
41 * or exits the main program if not enough memory.
42 * This function may be called by multiple threads in parallel. */
43 static struct tree_node *
44 tree_init_node(struct tree *t, coord_t coord, int depth, bool fast_alloc)
46 struct tree_node *n;
47 if (fast_alloc) {
48 n = tree_fast_alloc_node(t);
49 if (!n) return n;
50 memset(n, 0, sizeof(*n));
51 } else {
52 n = calloc2(1, sizeof(*n));
53 __sync_fetch_and_add(&t->nodes_size, sizeof(*n));
55 n->coord = coord;
56 n->depth = depth;
57 volatile static long c = 1000000;
58 n->hash = __sync_fetch_and_add(&c, 1);
59 if (depth > t->max_depth)
60 t->max_depth = depth;
61 return n;
64 /* Create a tree structure. Pre-allocate all nodes if max_tree_size is > 0. */
65 struct tree *
66 tree_init(struct board *board, enum stone color, unsigned long max_tree_size, float ltree_aging)
68 struct tree *t = calloc2(1, sizeof(*t));
69 t->board = board;
70 t->max_tree_size = max_tree_size;
71 if (max_tree_size != 0) {
72 /* Allocate one extra node, max_tree_size may not be multiple of node size. */
73 t->nodes = malloc2(max_tree_size + sizeof(struct tree_node));
74 /* The nodes buffer doesn't need initialization. This is currently
75 * done by tree_init_node to spread the load. Doing a memset for the
76 * entire buffer here would be too slow for large trees (>10 GB). */
78 /* The root PASS move is only virtual, we never play it. */
79 t->root = tree_init_node(t, pass, 0, t->nodes);
80 t->root_symmetry = board->symmetry;
81 t->root_color = stone_other(color); // to research black moves, root will be white
83 t->ltree_black = tree_init_node(t, pass, 0, false);
84 t->ltree_white = tree_init_node(t, pass, 0, false);
85 t->ltree_aging = ltree_aging;
86 return t;
90 /* This function may be called by multiple threads in parallel on the
91 * same tree, but not on node n. n may be detached from the tree but
92 * must have been created in this tree originally.
93 * It returns the remaining size of the tree after n has been freed. */
94 static unsigned long
95 tree_done_node(struct tree *t, struct tree_node *n)
97 struct tree_node *ni = n->children;
98 while (ni) {
99 struct tree_node *nj = ni->sibling;
100 tree_done_node(t, ni);
101 ni = nj;
103 free(n);
104 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
105 return old_size - sizeof(*n);
108 struct subtree_ctx {
109 struct tree *t;
110 struct tree_node *n;
113 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
114 static void *
115 tree_done_node_worker(void *ctx_)
117 struct subtree_ctx *ctx = ctx_;
118 char *str = coord2str(ctx->n->coord, ctx->t->board);
120 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
121 if (!tree_size)
122 free(ctx->t);
123 if (DEBUGL(2))
124 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
125 free(str);
126 free(ctx);
127 return NULL;
130 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
131 * empty free the tree also. Only for fast_alloc=false. */
132 static void
133 tree_done_node_detached(struct tree *t, struct tree_node *n)
135 if (n->u.playouts < 1000) { // no thread for small tree
136 if (!tree_done_node(t, n))
137 free(t);
138 return;
140 pthread_attr_t attr;
141 pthread_attr_init(&attr);
142 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
144 pthread_t thread;
145 struct subtree_ctx *ctx = malloc2(sizeof(struct subtree_ctx));
146 ctx->t = t;
147 ctx->n = n;
148 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
149 pthread_attr_destroy(&attr);
152 void
153 tree_done(struct tree *t)
155 tree_done_node(t, t->ltree_black);
156 tree_done_node(t, t->ltree_white);
157 if (t->nodes) {
158 free(t->nodes);
159 free(t);
160 } else if (!tree_done_node(t, t->root)) {
161 free(t);
162 /* A tree_done_node_worker might still be running on this tree but
163 * it will free the tree later. It is also freeing nodes faster than
164 * we will create new ones. */
169 static void
170 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
172 for (int i = 0; i < l; i++) fputc(' ', stderr);
173 int children = 0;
174 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
175 children++;
176 /* We use 1 as parity, since for all nodes we want to know the
177 * win probability of _us_, not the node color. */
178 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
179 coord2sstr(node->coord, tree->board),
180 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
181 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
182 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
183 node->hints, children, node->hash);
185 /* Print nodes sorted by #playouts. */
187 struct tree_node *nbox[1000]; int nboxl = 0;
188 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
189 if (ni->u.playouts > thres)
190 nbox[nboxl++] = ni;
192 while (true) {
193 int best = -1;
194 for (int i = 0; i < nboxl; i++)
195 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
196 best = i;
197 if (best < 0)
198 break;
199 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
200 nbox[best] = NULL;
204 void
205 tree_dump(struct tree *tree, int thres)
207 if (thres && tree->root->u.playouts / thres > 100) {
208 /* Be a bit sensible about this; the opening book can create
209 * huge dumps at first. */
210 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
212 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
213 stone2str(tree->root_color), tree->extra_komi);
214 tree_node_dump(tree, tree->root, 0, thres);
216 if (DEBUGL(3) && tree->ltree_black) {
217 fprintf(stderr, "B local tree:\n");
218 tree_node_dump(tree, tree->ltree_black, 0, thres);
219 fprintf(stderr, "W local tree:\n");
220 tree_node_dump(tree, tree->ltree_white, 0, thres);
225 static char *
226 tree_book_name(struct board *b)
228 static char buf[256];
229 if (b->handicap > 0) {
230 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
231 } else {
232 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
234 return buf;
237 static void
238 tree_node_save(FILE *f, struct tree_node *node, int thres)
240 bool save_children = node->u.playouts >= thres;
242 if (!save_children)
243 node->is_expanded = 0;
245 fputc(1, f);
246 fwrite(((void *) node) + offsetof(struct tree_node, depth),
247 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
248 1, f);
250 if (save_children) {
251 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
252 tree_node_save(f, ni, thres);
253 } else {
254 if (node->children)
255 node->is_expanded = 1;
258 fputc(0, f);
261 void
262 tree_save(struct tree *tree, struct board *b, int thres)
264 char *filename = tree_book_name(b);
265 FILE *f = fopen(filename, "wb");
266 if (!f) {
267 perror("fopen");
268 return;
270 tree_node_save(f, tree->root, thres);
271 fputc(0, f);
272 fclose(f);
276 void
277 tree_node_load(FILE *f, struct tree_node *node, int *num)
279 (*num)++;
281 fread(((void *) node) + offsetof(struct tree_node, depth),
282 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
283 1, f);
285 /* Keep values in sane scale, otherwise we start overflowing. */
286 #define MAX_PLAYOUTS 10000000
287 if (node->u.playouts > MAX_PLAYOUTS) {
288 node->u.playouts = MAX_PLAYOUTS;
290 if (node->amaf.playouts > MAX_PLAYOUTS) {
291 node->amaf.playouts = MAX_PLAYOUTS;
293 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
294 memcpy(&node->pu, &node->u, sizeof(node->u));
296 struct tree_node *ni = NULL, *ni_prev = NULL;
297 while (fgetc(f)) {
298 ni_prev = ni; ni = calloc2(1, sizeof(*ni));
299 if (!node->children)
300 node->children = ni;
301 else
302 ni_prev->sibling = ni;
303 ni->parent = node;
304 tree_node_load(f, ni, num);
308 void
309 tree_load(struct tree *tree, struct board *b)
311 char *filename = tree_book_name(b);
312 FILE *f = fopen(filename, "rb");
313 if (!f)
314 return;
316 fprintf(stderr, "Loading opening book %s...\n", filename);
318 int num = 0;
319 if (fgetc(f))
320 tree_node_load(f, tree->root, &num);
321 fprintf(stderr, "Loaded %d nodes.\n", num);
323 fclose(f);
327 static struct tree_node *
328 tree_node_copy(struct tree_node *node)
330 struct tree_node *n2 = malloc2(sizeof(*n2));
331 *n2 = *node;
332 if (!node->children)
333 return n2;
334 struct tree_node *ni = node->children;
335 struct tree_node *ni2 = tree_node_copy(ni);
336 n2->children = ni2; ni2->parent = n2;
337 while ((ni = ni->sibling)) {
338 ni2->sibling = tree_node_copy(ni);
339 ni2 = ni2->sibling; ni2->parent = n2;
341 return n2;
344 struct tree *
345 tree_copy(struct tree *tree)
347 assert(!tree->nodes);
348 struct tree *t2 = malloc2(sizeof(*t2));
349 *t2 = *tree;
350 t2->root = tree_node_copy(tree->root);
351 return t2;
354 /* Copy the subtree rooted at node: all nodes at or below depth
355 * or with at least threshold playouts. Only for fast_alloc.
356 * The code is destructive on src. The relative order of children of
357 * a given node is preserved (assumed by tree_get_node in particular).
358 * Returns the copy of node in the destination tree, or NULL
359 * if we could not copy it. */
360 static struct tree_node *
361 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
362 int threshold, int depth)
364 assert(dest->nodes && node);
365 struct tree_node *n2 = tree_fast_alloc_node(dest);
366 if (!n2)
367 return NULL;
368 *n2 = *node;
369 if (n2->depth > dest->max_depth)
370 dest->max_depth = n2->depth;
371 n2->children = NULL;
372 n2->is_expanded = false;
374 if (node->depth >= depth && node->u.playouts < threshold)
375 return n2;
376 /* For deep nodes with many playouts, we must copy all children,
377 * even those with zero playouts, because partially expanded
378 * nodes are not supported. Considering them as fully expanded
379 * would degrade the playing strength. The only exception is
380 * when dest becomes full, but this should never happen in practice
381 * if threshold is chosen to limit the number of nodes traversed. */
382 struct tree_node *ni = node->children;
383 if (!ni)
384 return n2;
385 struct tree_node **prev2 = &(n2->children);
386 while (ni) {
387 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
388 if (!ni2) break;
389 *prev2 = ni2;
390 prev2 = &(ni2->sibling);
391 ni2->parent = n2;
392 ni = ni->sibling;
394 if (!ni) {
395 n2->is_expanded = true;
396 } else {
397 n2->children = NULL; // avoid partially expanded nodes
399 return n2;
402 /* The following constants are used for garbage collection of nodes.
403 * A tree is considered large if the top node has >= 40K playouts.
404 * For such trees, we copy deep nodes only if they have enough
405 * playouts, with a gradually increasing threshold up to 40.
406 * These constants define how much time we're willing to spend
407 * scanning the source tree when promoting a move. The chosen values
408 * make worst case pruning in about 3s for 20 GB ram, and this
409 * is only for long thinking time (>1M playouts). For fast games the
410 * trees don't grow large. For small ram or fast game we copy the
411 * entire tree. These values do not degrade playing strength and are
412 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
413 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
414 * playing worse. */
415 #define LARGE_TREE_PLAYOUTS 40000LL
416 #define DEEP_PLAYOUTS_THRESHOLD 40
418 /* Garbage collect the tree early if the top node has < 5K playouts,
419 * to avoid having to do it later on a large subtree.
420 * This guarantees garbage collection in < 1s. */
421 #define SMALL_TREE_PLAYOUTS 5000
423 /* Free all the tree, keeping only the subtree rooted at node.
424 * Prune the subtree if necessary to fit in max_size bytes or
425 * to save time scanning the tree.
426 * Returns the moved node. Only for fast_alloc. */
427 struct tree_node *
428 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
430 assert(tree->nodes && !node->parent && !node->sibling);
431 double start_time = time_now();
433 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging);
434 temp_tree->nodes_size = 0; // We do not want the dummy pass node
435 struct tree_node *temp_node;
437 /* Find the maximum depth at which we can copy all nodes. */
438 int max_nodes = 1;
439 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
440 max_nodes++;
441 unsigned long nodes_size = max_nodes * sizeof(*node);
442 int max_depth = node->depth;
443 while (nodes_size < max_size && max_nodes > 1) {
444 max_nodes--;
445 nodes_size += max_nodes * nodes_size;
446 max_depth++;
449 /* Copy all nodes for small trees. For large trees, copy all nodes
450 * with depth <= max_depth, and all nodes with enough playouts.
451 * Avoiding going too deep (except for nodes with many playouts) is mostly
452 * to save time scanning the source tree. It can take over 20s to traverse
453 * completely a large source tree (20 GB) even without copying because
454 * the traversal is not friendly at all with the memory cache. */
455 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
456 if (threshold < 0) threshold = 0;
457 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
458 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
459 assert(temp_node);
461 /* Now copy back to original tree. */
462 tree->nodes_size = 0;
463 tree->max_depth = 0;
464 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
466 if (DEBUGL(1)) {
467 double now = time_now();
468 static double prev_time;
469 if (!prev_time) prev_time = start_time;
470 fprintf(stderr,
471 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
472 " max_size %lu, pruned size %lu, playouts %d\n",
473 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
474 max_size, temp_tree->nodes_size, new_node->u.playouts);
475 prev_time = start_time;
477 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
478 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
479 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
480 } else {
481 assert(tree->nodes_size == temp_tree->nodes_size);
482 assert(tree->max_depth == temp_tree->max_depth);
484 tree_done(temp_tree);
485 return new_node;
489 static void
490 tree_node_merge(struct tree_node *dest, struct tree_node *src)
492 /* Do not merge nodes that weren't touched at all. */
493 assert(dest->pamaf.playouts == src->pamaf.playouts);
494 assert(dest->pu.playouts == src->pu.playouts);
495 if (src->amaf.playouts - src->pamaf.playouts == 0
496 && src->u.playouts - src->pu.playouts == 0) {
497 return;
500 dest->hints |= src->hints;
502 /* Merge the children, both are coord-sorted lists. */
503 struct tree_node *di = dest->children, **dref = &dest->children;
504 struct tree_node *si = src->children, **sref = &src->children;
505 while (di && si) {
506 if (di->coord != si->coord) {
507 /* src has some extra items or misses di */
508 struct tree_node *si2 = si->sibling;
509 while (si2 && di->coord != si2->coord) {
510 si2 = si2->sibling;
512 if (!si2)
513 goto next_di; /* src misses di, move on */
514 /* chain the extra [si,si2) items before di */
515 (*dref) = si;
516 while (si->sibling != si2) {
517 si->parent = dest;
518 si = si->sibling;
520 si->parent = dest;
521 si->sibling = di;
522 si = si2;
523 (*sref) = si;
525 /* Matching nodes - recurse... */
526 tree_node_merge(di, si);
527 /* ...and move on. */
528 sref = &si->sibling; si = si->sibling;
529 next_di:
530 dref = &di->sibling; di = di->sibling;
532 if (si) {
533 /* Some outstanding nodes are left on src side, rechain
534 * them to dst. */
535 (*dref) = si;
536 while (si) {
537 si->parent = dest;
538 si = si->sibling;
540 (*sref) = NULL;
543 /* Priors should be constant. */
544 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
546 stats_merge(&dest->amaf, &src->amaf);
547 stats_merge(&dest->u, &src->u);
550 /* Merge two trees built upon the same board. Note that the operation is
551 * destructive on src. */
552 void
553 tree_merge(struct tree *dest, struct tree *src)
555 if (src->max_depth > dest->max_depth)
556 dest->max_depth = src->max_depth;
557 tree_node_merge(dest->root, src->root);
561 static void
562 tree_node_normalize(struct tree_node *node, int factor)
564 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
565 tree_node_normalize(ni, factor);
567 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
568 normalize(pamaf, amaf, playouts);
569 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
571 normalize(pu, u, playouts);
572 memcpy(&node->pu, &node->u, sizeof(node->u));
573 #undef normalize
576 /* Normalize a tree, dividing the amaf and u values by given
577 * factor; otherwise, simulations run in independent threads
578 * two trees built upon the same board. To correctly handle
579 * results taken from previous simulation run, they are backed
580 * up in tree. */
581 void
582 tree_normalize(struct tree *tree, int factor)
584 tree_node_normalize(tree->root, factor);
588 /* Get a node of given coordinate from within parent, possibly creating it
589 * if necessary - in a very raw form (no .d, priors, ...). */
590 /* FIXME: Adjust for board symmetry. */
591 struct tree_node *
592 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
594 if (!parent->children || parent->children->coord >= c) {
595 /* Special case: Insertion at the beginning. */
596 if (parent->children && parent->children->coord == c)
597 return parent->children;
598 if (!create)
599 return NULL;
601 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
602 nn->parent = parent; nn->sibling = parent->children;
603 parent->children = nn;
604 return nn;
607 /* No candidate at the beginning, look through all the children. */
609 struct tree_node *ni;
610 for (ni = parent->children; ni->sibling; ni = ni->sibling)
611 if (ni->sibling->coord >= c)
612 break;
614 if (ni->sibling && ni->sibling->coord == c)
615 return ni->sibling;
616 assert(ni->coord < c);
617 if (!create)
618 return NULL;
620 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
621 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
622 return nn;
625 /* Get local tree node corresponding to given node, given local node child
626 * iterator @lni (which points either at the corresponding node, or at the
627 * nearest local tree node after @ni). */
628 struct tree_node *
629 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
631 /* Now set up lnode, which is the actual local node
632 * corresponding to ni - either lni if it is an
633 * exact match and ni is not tenuki, <pass> local
634 * node if ni is tenuki, or NULL if there is no
635 * corresponding node available. */
637 if (is_pass(ni->coord)) {
638 /* Also, for sanity reasons we never use local
639 * tree for passes. (Maybe we could, but it's
640 * too hard to think about.) */
641 return NULL;
644 if (lni->coord == ni->coord) {
645 /* We don't consider tenuki a sequence play
646 * that we have in local tree even though
647 * ni->d is too high; this can happen if this
648 * occured in different board topology. */
649 return lni;
652 if (ni->d >= tenuki_d) {
653 /* Tenuki, pick a pass lsibling if available. */
654 assert(lni->parent && lni->parent->children);
655 if (is_pass(lni->parent->children->coord)) {
656 return lni->parent->children;
657 } else {
658 return NULL;
662 /* No corresponding local node, lnode stays NULL. */
663 return NULL;
667 /* Tree symmetry: When possible, we will localize the tree to a single part
668 * of the board in tree_expand_node() and possibly flip along symmetry axes
669 * to another part of the board in tree_promote_at(). We follow b->symmetry
670 * guidelines here. */
673 /* This function must be thread safe, given that board b is only modified by the calling thread. */
674 void
675 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
677 /* Get a Common Fate Graph distance map from parent node. */
678 int distances[board_size2(b)];
679 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
680 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
681 } else {
682 // Pass or resign - everything is too far.
683 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
686 /* Get a map of prior values to initialize the new nodes with. */
687 struct prior_map map = {
688 .b = b,
689 .to_play = color,
690 .parity = tree_parity(t, parity),
691 .distances = distances,
693 // Include pass in the prior map.
694 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
695 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
696 memset(map_prior, 0, sizeof(map_prior));
697 memset(map_consider, 0, sizeof(map_consider));
698 map.consider[pass] = true;
699 foreach_point(b) {
700 if (board_at(b, c) != S_NONE)
701 continue;
702 if (!board_is_valid_play(b, color, c))
703 continue;
704 map.consider[c] = true;
705 } foreach_point_end;
706 uct_prior(u, node, &map);
708 /* Now, create the nodes. */
709 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
710 /* In fast_alloc mode we might temporarily run out of nodes but
711 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
712 if (!ni) {
713 node->is_expanded = false;
714 return;
716 struct tree_node *first_child = ni;
717 ni->parent = node;
718 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
720 /* The loop considers only the symmetry playground. */
721 if (UDEBUGL(6)) {
722 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
723 coord2sstr(node->coord, b),
724 b->symmetry.x1, b->symmetry.y1,
725 b->symmetry.x2, b->symmetry.y2,
726 b->symmetry.type, b->symmetry.d);
728 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
729 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
730 if (b->symmetry.d) {
731 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
732 if (x > j) {
733 if (UDEBUGL(7))
734 fprintf(stderr, "drop %d,%d\n", i, j);
735 continue;
739 coord_t c = coord_xy(t->board, i, j);
740 if (!map.consider[c]) // Filter out invalid moves
741 continue;
742 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
744 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
745 if (!nj) {
746 node->is_expanded = false;
747 return;
749 nj->parent = node; ni->sibling = nj; ni = nj;
751 ni->prior = map.prior[c];
752 ni->d = distances[c];
755 node->children = first_child; // must be done at the end to avoid race
759 static coord_t
760 flip_coord(struct board *b, coord_t c,
761 bool flip_horiz, bool flip_vert, int flip_diag)
763 int x = coord_x(c, b), y = coord_y(c, b);
764 if (flip_diag) {
765 int z = x; x = y; y = z;
767 if (flip_horiz) {
768 x = board_size(b) - 1 - x;
770 if (flip_vert) {
771 y = board_size(b) - 1 - y;
773 return coord_xy(b, x, y);
776 static void
777 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
778 bool flip_horiz, bool flip_vert, int flip_diag)
780 if (!is_pass(node->coord))
781 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
783 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
784 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
787 static void
788 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
790 if (is_pass(c))
791 return;
793 struct board_symmetry *s = &tree->root_symmetry;
794 int cx = coord_x(c, b), cy = coord_y(c, b);
796 /* playground X->h->v->d normalization
797 * :::.. .d...
798 * .::.. v....
799 * ..:.. .....
800 * ..... h...X
801 * ..... ..... */
802 bool flip_horiz = cx < s->x1 || cx > s->x2;
803 bool flip_vert = cy < s->y1 || cy > s->y2;
805 bool flip_diag = 0;
806 if (s->d) {
807 bool dir = (s->type == SYM_DIAG_DOWN);
808 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
809 if (flip_vert ? x < cy : x > cy) {
810 flip_diag = 1;
814 if (DEBUGL(4)) {
815 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
816 coord2sstr(c, b),
817 cx, cy, s->x1, s->y1, s->x2, s->y2,
818 flip_horiz, flip_vert, flip_diag,
819 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
820 s->type, s->d, b->symmetry.type, b->symmetry.d);
822 if (flip_horiz || flip_vert || flip_diag)
823 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
827 static void
828 tree_unlink_node(struct tree_node *node)
830 struct tree_node *ni = node->parent;
831 if (ni->children == node) {
832 ni->children = node->sibling;
833 } else {
834 ni = ni->children;
835 while (ni->sibling != node)
836 ni = ni->sibling;
837 ni->sibling = node->sibling;
839 node->sibling = NULL;
840 node->parent = NULL;
843 /* Reduce weight of statistics on promotion. Remove nodes that
844 * get reduced to zero playouts; returns next node to consider
845 * in the children list (@node may get deleted). */
846 static struct tree_node *
847 tree_age_node(struct tree *tree, struct tree_node *node)
849 node->u.playouts /= tree->ltree_aging;
850 if (node->parent && !node->u.playouts) {
851 struct tree_node *sibling = node->sibling;
852 /* Delete node, no playouts. */
853 tree_unlink_node(node);
854 tree_done_node(tree, node);
855 return sibling;
858 struct tree_node *ni = node->children;
859 while (ni) ni = tree_age_node(tree, ni);
860 return node->sibling;
863 /* Promotes the given node as the root of the tree. In the fast_alloc
864 * mode, the node may be moved and some of its subtree may be pruned. */
865 void
866 tree_promote_node(struct tree *tree, struct tree_node **node)
868 assert((*node)->parent == tree->root);
869 tree_unlink_node(*node);
870 if (!tree->nodes) {
871 /* Freeing the rest of the tree can take several seconds on large
872 * trees, so we must do it asynchronously: */
873 tree_done_node_detached(tree, tree->root);
874 } else {
875 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
876 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
877 if (tree->nodes_size >= tree->max_tree_size - min_free_size
878 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
879 *node = tree_garbage_collect(tree, min_free_size, *node);
881 tree->root = *node;
882 tree->root_color = stone_other(tree->root_color);
884 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
885 /* See tree.score description for explanation on why don't we zero
886 * score on node promotion. */
887 // tree->score.playouts = 0;
889 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
890 * tree->max_depth is correct. Otherwise we could traverse the tree
891 * to recompute max_depth but it's not worth it: it's just for debugging
892 * and soon the tree will grow and max_depth will become correct again. */
894 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
895 tree_age_node(tree, tree->ltree_black);
896 tree_age_node(tree, tree->ltree_white);
900 bool
901 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
903 tree_fix_symmetry(tree, b, c);
905 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
906 if (ni->coord == c) {
907 tree_promote_node(tree, &ni);
908 return true;
911 return false;