UCT tree: Unify tree allocation in tree_alloc_node()
[pachi/ann.git] / uct / tree.c
blobc775e4db1f3d06abd1f70e6802e517aea68a3504
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_alloc_node(struct tree *t, bool fast_alloc)
28 struct tree_node *n = NULL;
29 unsigned long old_size = __sync_fetch_and_add(&t->nodes_size, sizeof(*n));
31 if (fast_alloc) {
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 return NULL;
37 assert(t->nodes != NULL);
38 n = (struct tree_node *)(t->nodes + old_size);
39 memset(n, 0, sizeof(*n));
40 } else {
41 n = calloc2(1, sizeof(*n));
43 return n;
46 /* Allocate and initialize a node. Returns NULL (fast_alloc mode)
47 * or exits the main program if not enough memory.
48 * This function may be called by multiple threads in parallel. */
49 static struct tree_node *
50 tree_init_node(struct tree *t, coord_t coord, int depth, bool fast_alloc)
52 struct tree_node *n;
53 n = tree_alloc_node(t, fast_alloc);
54 if (!n)
55 return NULL;
56 n->coord = coord;
57 n->depth = depth;
58 volatile static long c = 1000000;
59 n->hash = __sync_fetch_and_add(&c, 1);
60 if (depth > t->max_depth)
61 t->max_depth = depth;
62 return n;
65 /* Create a tree structure. Pre-allocate all nodes if max_tree_size is > 0. */
66 struct tree *
67 tree_init(struct board *board, enum stone color, unsigned long max_tree_size, float ltree_aging)
69 struct tree *t = calloc2(1, sizeof(*t));
70 t->board = board;
71 t->max_tree_size = max_tree_size;
72 if (max_tree_size != 0) {
73 /* Allocate one extra node, max_tree_size may not be multiple of node size. */
74 t->nodes = malloc2(max_tree_size + sizeof(struct tree_node));
75 /* The nodes buffer doesn't need initialization. This is currently
76 * done by tree_init_node to spread the load. Doing a memset for the
77 * entire buffer here would be too slow for large trees (>10 GB). */
79 /* The root PASS move is only virtual, we never play it. */
80 t->root = tree_init_node(t, pass, 0, t->nodes);
81 t->root_symmetry = board->symmetry;
82 t->root_color = stone_other(color); // to research black moves, root will be white
84 t->ltree_black = tree_init_node(t, pass, 0, false);
85 t->ltree_white = tree_init_node(t, pass, 0, false);
86 t->ltree_aging = ltree_aging;
87 return t;
91 /* This function may be called by multiple threads in parallel on the
92 * same tree, but not on node n. n may be detached from the tree but
93 * must have been created in this tree originally.
94 * It returns the remaining size of the tree after n has been freed. */
95 static unsigned long
96 tree_done_node(struct tree *t, struct tree_node *n)
98 struct tree_node *ni = n->children;
99 while (ni) {
100 struct tree_node *nj = ni->sibling;
101 tree_done_node(t, ni);
102 ni = nj;
104 free(n);
105 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
106 return old_size - sizeof(*n);
109 struct subtree_ctx {
110 struct tree *t;
111 struct tree_node *n;
114 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
115 static void *
116 tree_done_node_worker(void *ctx_)
118 struct subtree_ctx *ctx = ctx_;
119 char *str = coord2str(ctx->n->coord, ctx->t->board);
121 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
122 if (!tree_size)
123 free(ctx->t);
124 if (DEBUGL(2))
125 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
126 free(str);
127 free(ctx);
128 return NULL;
131 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
132 * empty free the tree also. Only for fast_alloc=false. */
133 static void
134 tree_done_node_detached(struct tree *t, struct tree_node *n)
136 if (n->u.playouts < 1000) { // no thread for small tree
137 if (!tree_done_node(t, n))
138 free(t);
139 return;
141 pthread_attr_t attr;
142 pthread_attr_init(&attr);
143 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
145 pthread_t thread;
146 struct subtree_ctx *ctx = malloc2(sizeof(struct subtree_ctx));
147 ctx->t = t;
148 ctx->n = n;
149 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
150 pthread_attr_destroy(&attr);
153 void
154 tree_done(struct tree *t)
156 tree_done_node(t, t->ltree_black);
157 tree_done_node(t, t->ltree_white);
158 if (t->nodes) {
159 free(t->nodes);
160 free(t);
161 } else if (!tree_done_node(t, t->root)) {
162 free(t);
163 /* A tree_done_node_worker might still be running on this tree but
164 * it will free the tree later. It is also freeing nodes faster than
165 * we will create new ones. */
170 static void
171 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
173 for (int i = 0; i < l; i++) fputc(' ', stderr);
174 int children = 0;
175 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
176 children++;
177 /* We use 1 as parity, since for all nodes we want to know the
178 * win probability of _us_, not the node color. */
179 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
180 coord2sstr(node->coord, tree->board),
181 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
182 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
183 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
184 node->hints, children, node->hash);
186 /* Print nodes sorted by #playouts. */
188 struct tree_node *nbox[1000]; int nboxl = 0;
189 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
190 if (ni->u.playouts > thres)
191 nbox[nboxl++] = ni;
193 while (true) {
194 int best = -1;
195 for (int i = 0; i < nboxl; i++)
196 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
197 best = i;
198 if (best < 0)
199 break;
200 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
201 nbox[best] = NULL;
205 void
206 tree_dump(struct tree *tree, int thres)
208 if (thres && tree->root->u.playouts / thres > 100) {
209 /* Be a bit sensible about this; the opening book can create
210 * huge dumps at first. */
211 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
213 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
214 stone2str(tree->root_color), tree->extra_komi);
215 tree_node_dump(tree, tree->root, 0, thres);
217 if (DEBUGL(3) && tree->ltree_black) {
218 fprintf(stderr, "B local tree:\n");
219 tree_node_dump(tree, tree->ltree_black, 0, thres);
220 fprintf(stderr, "W local tree:\n");
221 tree_node_dump(tree, tree->ltree_white, 0, thres);
226 static char *
227 tree_book_name(struct board *b)
229 static char buf[256];
230 if (b->handicap > 0) {
231 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
232 } else {
233 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
235 return buf;
238 static void
239 tree_node_save(FILE *f, struct tree_node *node, int thres)
241 bool save_children = node->u.playouts >= thres;
243 if (!save_children)
244 node->is_expanded = 0;
246 fputc(1, f);
247 fwrite(((void *) node) + offsetof(struct tree_node, depth),
248 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
249 1, f);
251 if (save_children) {
252 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
253 tree_node_save(f, ni, thres);
254 } else {
255 if (node->children)
256 node->is_expanded = 1;
259 fputc(0, f);
262 void
263 tree_save(struct tree *tree, struct board *b, int thres)
265 char *filename = tree_book_name(b);
266 FILE *f = fopen(filename, "wb");
267 if (!f) {
268 perror("fopen");
269 return;
271 tree_node_save(f, tree->root, thres);
272 fputc(0, f);
273 fclose(f);
277 void
278 tree_node_load(FILE *f, struct tree_node *node, int *num)
280 (*num)++;
282 fread(((void *) node) + offsetof(struct tree_node, depth),
283 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
284 1, f);
286 /* Keep values in sane scale, otherwise we start overflowing. */
287 #define MAX_PLAYOUTS 10000000
288 if (node->u.playouts > MAX_PLAYOUTS) {
289 node->u.playouts = MAX_PLAYOUTS;
291 if (node->amaf.playouts > MAX_PLAYOUTS) {
292 node->amaf.playouts = MAX_PLAYOUTS;
294 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
295 memcpy(&node->pu, &node->u, sizeof(node->u));
297 struct tree_node *ni = NULL, *ni_prev = NULL;
298 while (fgetc(f)) {
299 ni_prev = ni; ni = calloc2(1, sizeof(*ni));
300 if (!node->children)
301 node->children = ni;
302 else
303 ni_prev->sibling = ni;
304 ni->parent = node;
305 tree_node_load(f, ni, num);
309 void
310 tree_load(struct tree *tree, struct board *b)
312 char *filename = tree_book_name(b);
313 FILE *f = fopen(filename, "rb");
314 if (!f)
315 return;
317 fprintf(stderr, "Loading opening book %s...\n", filename);
319 int num = 0;
320 if (fgetc(f))
321 tree_node_load(f, tree->root, &num);
322 fprintf(stderr, "Loaded %d nodes.\n", num);
324 fclose(f);
328 static struct tree_node *
329 tree_node_copy(struct tree_node *node)
331 struct tree_node *n2 = malloc2(sizeof(*n2));
332 *n2 = *node;
333 if (!node->children)
334 return n2;
335 struct tree_node *ni = node->children;
336 struct tree_node *ni2 = tree_node_copy(ni);
337 n2->children = ni2; ni2->parent = n2;
338 while ((ni = ni->sibling)) {
339 ni2->sibling = tree_node_copy(ni);
340 ni2 = ni2->sibling; ni2->parent = n2;
342 return n2;
345 struct tree *
346 tree_copy(struct tree *tree)
348 assert(!tree->nodes);
349 struct tree *t2 = malloc2(sizeof(*t2));
350 *t2 = *tree;
351 t2->root = tree_node_copy(tree->root);
352 return t2;
355 /* Copy the subtree rooted at node: all nodes at or below depth
356 * or with at least threshold playouts. Only for fast_alloc.
357 * The code is destructive on src. The relative order of children of
358 * a given node is preserved (assumed by tree_get_node in particular).
359 * Returns the copy of node in the destination tree, or NULL
360 * if we could not copy it. */
361 static struct tree_node *
362 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
363 int threshold, int depth)
365 assert(dest->nodes && node);
366 struct tree_node *n2 = tree_alloc_node(dest, true);
367 if (!n2)
368 return NULL;
369 *n2 = *node;
370 if (n2->depth > dest->max_depth)
371 dest->max_depth = n2->depth;
372 n2->children = NULL;
373 n2->is_expanded = false;
375 if (node->depth >= depth && node->u.playouts < threshold)
376 return n2;
377 /* For deep nodes with many playouts, we must copy all children,
378 * even those with zero playouts, because partially expanded
379 * nodes are not supported. Considering them as fully expanded
380 * would degrade the playing strength. The only exception is
381 * when dest becomes full, but this should never happen in practice
382 * if threshold is chosen to limit the number of nodes traversed. */
383 struct tree_node *ni = node->children;
384 if (!ni)
385 return n2;
386 struct tree_node **prev2 = &(n2->children);
387 while (ni) {
388 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
389 if (!ni2) break;
390 *prev2 = ni2;
391 prev2 = &(ni2->sibling);
392 ni2->parent = n2;
393 ni = ni->sibling;
395 if (!ni) {
396 n2->is_expanded = true;
397 } else {
398 n2->children = NULL; // avoid partially expanded nodes
400 return n2;
403 /* The following constants are used for garbage collection of nodes.
404 * A tree is considered large if the top node has >= 40K playouts.
405 * For such trees, we copy deep nodes only if they have enough
406 * playouts, with a gradually increasing threshold up to 40.
407 * These constants define how much time we're willing to spend
408 * scanning the source tree when promoting a move. The chosen values
409 * make worst case pruning in about 3s for 20 GB ram, and this
410 * is only for long thinking time (>1M playouts). For fast games the
411 * trees don't grow large. For small ram or fast game we copy the
412 * entire tree. These values do not degrade playing strength and are
413 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
414 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
415 * playing worse. */
416 #define LARGE_TREE_PLAYOUTS 40000LL
417 #define DEEP_PLAYOUTS_THRESHOLD 40
419 /* Garbage collect the tree early if the top node has < 5K playouts,
420 * to avoid having to do it later on a large subtree.
421 * This guarantees garbage collection in < 1s. */
422 #define SMALL_TREE_PLAYOUTS 5000
424 /* Free all the tree, keeping only the subtree rooted at node.
425 * Prune the subtree if necessary to fit in max_size bytes or
426 * to save time scanning the tree.
427 * Returns the moved node. Only for fast_alloc. */
428 struct tree_node *
429 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
431 assert(tree->nodes && !node->parent && !node->sibling);
432 double start_time = time_now();
434 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging);
435 temp_tree->nodes_size = 0; // We do not want the dummy pass node
436 struct tree_node *temp_node;
438 /* Find the maximum depth at which we can copy all nodes. */
439 int max_nodes = 1;
440 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
441 max_nodes++;
442 unsigned long nodes_size = max_nodes * sizeof(*node);
443 int max_depth = node->depth;
444 while (nodes_size < max_size && max_nodes > 1) {
445 max_nodes--;
446 nodes_size += max_nodes * nodes_size;
447 max_depth++;
450 /* Copy all nodes for small trees. For large trees, copy all nodes
451 * with depth <= max_depth, and all nodes with enough playouts.
452 * Avoiding going too deep (except for nodes with many playouts) is mostly
453 * to save time scanning the source tree. It can take over 20s to traverse
454 * completely a large source tree (20 GB) even without copying because
455 * the traversal is not friendly at all with the memory cache. */
456 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
457 if (threshold < 0) threshold = 0;
458 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
459 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
460 assert(temp_node);
462 /* Now copy back to original tree. */
463 tree->nodes_size = 0;
464 tree->max_depth = 0;
465 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
467 if (DEBUGL(1)) {
468 double now = time_now();
469 static double prev_time;
470 if (!prev_time) prev_time = start_time;
471 fprintf(stderr,
472 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
473 " max_size %lu, pruned size %lu, playouts %d\n",
474 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
475 max_size, temp_tree->nodes_size, new_node->u.playouts);
476 prev_time = start_time;
478 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
479 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
480 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
481 } else {
482 assert(tree->nodes_size == temp_tree->nodes_size);
483 assert(tree->max_depth == temp_tree->max_depth);
485 tree_done(temp_tree);
486 return new_node;
490 static void
491 tree_node_merge(struct tree_node *dest, struct tree_node *src)
493 /* Do not merge nodes that weren't touched at all. */
494 assert(dest->pamaf.playouts == src->pamaf.playouts);
495 assert(dest->pu.playouts == src->pu.playouts);
496 if (src->amaf.playouts - src->pamaf.playouts == 0
497 && src->u.playouts - src->pu.playouts == 0) {
498 return;
501 dest->hints |= src->hints;
503 /* Merge the children, both are coord-sorted lists. */
504 struct tree_node *di = dest->children, **dref = &dest->children;
505 struct tree_node *si = src->children, **sref = &src->children;
506 while (di && si) {
507 if (di->coord != si->coord) {
508 /* src has some extra items or misses di */
509 struct tree_node *si2 = si->sibling;
510 while (si2 && di->coord != si2->coord) {
511 si2 = si2->sibling;
513 if (!si2)
514 goto next_di; /* src misses di, move on */
515 /* chain the extra [si,si2) items before di */
516 (*dref) = si;
517 while (si->sibling != si2) {
518 si->parent = dest;
519 si = si->sibling;
521 si->parent = dest;
522 si->sibling = di;
523 si = si2;
524 (*sref) = si;
526 /* Matching nodes - recurse... */
527 tree_node_merge(di, si);
528 /* ...and move on. */
529 sref = &si->sibling; si = si->sibling;
530 next_di:
531 dref = &di->sibling; di = di->sibling;
533 if (si) {
534 /* Some outstanding nodes are left on src side, rechain
535 * them to dst. */
536 (*dref) = si;
537 while (si) {
538 si->parent = dest;
539 si = si->sibling;
541 (*sref) = NULL;
544 /* Priors should be constant. */
545 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
547 stats_merge(&dest->amaf, &src->amaf);
548 stats_merge(&dest->u, &src->u);
551 /* Merge two trees built upon the same board. Note that the operation is
552 * destructive on src. */
553 void
554 tree_merge(struct tree *dest, struct tree *src)
556 if (src->max_depth > dest->max_depth)
557 dest->max_depth = src->max_depth;
558 tree_node_merge(dest->root, src->root);
562 static void
563 tree_node_normalize(struct tree_node *node, int factor)
565 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
566 tree_node_normalize(ni, factor);
568 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
569 normalize(pamaf, amaf, playouts);
570 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
572 normalize(pu, u, playouts);
573 memcpy(&node->pu, &node->u, sizeof(node->u));
574 #undef normalize
577 /* Normalize a tree, dividing the amaf and u values by given
578 * factor; otherwise, simulations run in independent threads
579 * two trees built upon the same board. To correctly handle
580 * results taken from previous simulation run, they are backed
581 * up in tree. */
582 void
583 tree_normalize(struct tree *tree, int factor)
585 tree_node_normalize(tree->root, factor);
589 /* Get a node of given coordinate from within parent, possibly creating it
590 * if necessary - in a very raw form (no .d, priors, ...). */
591 /* FIXME: Adjust for board symmetry. */
592 struct tree_node *
593 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
595 if (!parent->children || parent->children->coord >= c) {
596 /* Special case: Insertion at the beginning. */
597 if (parent->children && parent->children->coord == c)
598 return parent->children;
599 if (!create)
600 return NULL;
602 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
603 nn->parent = parent; nn->sibling = parent->children;
604 parent->children = nn;
605 return nn;
608 /* No candidate at the beginning, look through all the children. */
610 struct tree_node *ni;
611 for (ni = parent->children; ni->sibling; ni = ni->sibling)
612 if (ni->sibling->coord >= c)
613 break;
615 if (ni->sibling && ni->sibling->coord == c)
616 return ni->sibling;
617 assert(ni->coord < c);
618 if (!create)
619 return NULL;
621 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
622 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
623 return nn;
626 /* Get local tree node corresponding to given node, given local node child
627 * iterator @lni (which points either at the corresponding node, or at the
628 * nearest local tree node after @ni). */
629 struct tree_node *
630 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
632 /* Now set up lnode, which is the actual local node
633 * corresponding to ni - either lni if it is an
634 * exact match and ni is not tenuki, <pass> local
635 * node if ni is tenuki, or NULL if there is no
636 * corresponding node available. */
638 if (is_pass(ni->coord)) {
639 /* Also, for sanity reasons we never use local
640 * tree for passes. (Maybe we could, but it's
641 * too hard to think about.) */
642 return NULL;
645 if (lni->coord == ni->coord) {
646 /* We don't consider tenuki a sequence play
647 * that we have in local tree even though
648 * ni->d is too high; this can happen if this
649 * occured in different board topology. */
650 return lni;
653 if (ni->d >= tenuki_d) {
654 /* Tenuki, pick a pass lsibling if available. */
655 assert(lni->parent && lni->parent->children);
656 if (is_pass(lni->parent->children->coord)) {
657 return lni->parent->children;
658 } else {
659 return NULL;
663 /* No corresponding local node, lnode stays NULL. */
664 return NULL;
668 /* Tree symmetry: When possible, we will localize the tree to a single part
669 * of the board in tree_expand_node() and possibly flip along symmetry axes
670 * to another part of the board in tree_promote_at(). We follow b->symmetry
671 * guidelines here. */
674 /* This function must be thread safe, given that board b is only modified by the calling thread. */
675 void
676 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
678 /* Get a Common Fate Graph distance map from parent node. */
679 int distances[board_size2(b)];
680 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
681 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
682 } else {
683 // Pass or resign - everything is too far.
684 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
687 /* Get a map of prior values to initialize the new nodes with. */
688 struct prior_map map = {
689 .b = b,
690 .to_play = color,
691 .parity = tree_parity(t, parity),
692 .distances = distances,
694 // Include pass in the prior map.
695 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
696 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
697 memset(map_prior, 0, sizeof(map_prior));
698 memset(map_consider, 0, sizeof(map_consider));
699 map.consider[pass] = true;
700 foreach_point(b) {
701 if (board_at(b, c) != S_NONE)
702 continue;
703 if (!board_is_valid_play(b, color, c))
704 continue;
705 map.consider[c] = true;
706 } foreach_point_end;
707 uct_prior(u, node, &map);
709 /* Now, create the nodes. */
710 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
711 /* In fast_alloc mode we might temporarily run out of nodes but
712 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
713 if (!ni) {
714 node->is_expanded = false;
715 return;
717 struct tree_node *first_child = ni;
718 ni->parent = node;
719 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
721 /* The loop considers only the symmetry playground. */
722 if (UDEBUGL(6)) {
723 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
724 coord2sstr(node->coord, b),
725 b->symmetry.x1, b->symmetry.y1,
726 b->symmetry.x2, b->symmetry.y2,
727 b->symmetry.type, b->symmetry.d);
729 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
730 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
731 if (b->symmetry.d) {
732 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
733 if (x > j) {
734 if (UDEBUGL(7))
735 fprintf(stderr, "drop %d,%d\n", i, j);
736 continue;
740 coord_t c = coord_xy(t->board, i, j);
741 if (!map.consider[c]) // Filter out invalid moves
742 continue;
743 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
745 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
746 if (!nj) {
747 node->is_expanded = false;
748 return;
750 nj->parent = node; ni->sibling = nj; ni = nj;
752 ni->prior = map.prior[c];
753 ni->d = distances[c];
756 node->children = first_child; // must be done at the end to avoid race
760 static coord_t
761 flip_coord(struct board *b, coord_t c,
762 bool flip_horiz, bool flip_vert, int flip_diag)
764 int x = coord_x(c, b), y = coord_y(c, b);
765 if (flip_diag) {
766 int z = x; x = y; y = z;
768 if (flip_horiz) {
769 x = board_size(b) - 1 - x;
771 if (flip_vert) {
772 y = board_size(b) - 1 - y;
774 return coord_xy(b, x, y);
777 static void
778 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
779 bool flip_horiz, bool flip_vert, int flip_diag)
781 if (!is_pass(node->coord))
782 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
784 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
785 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
788 static void
789 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
791 if (is_pass(c))
792 return;
794 struct board_symmetry *s = &tree->root_symmetry;
795 int cx = coord_x(c, b), cy = coord_y(c, b);
797 /* playground X->h->v->d normalization
798 * :::.. .d...
799 * .::.. v....
800 * ..:.. .....
801 * ..... h...X
802 * ..... ..... */
803 bool flip_horiz = cx < s->x1 || cx > s->x2;
804 bool flip_vert = cy < s->y1 || cy > s->y2;
806 bool flip_diag = 0;
807 if (s->d) {
808 bool dir = (s->type == SYM_DIAG_DOWN);
809 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
810 if (flip_vert ? x < cy : x > cy) {
811 flip_diag = 1;
815 if (DEBUGL(4)) {
816 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
817 coord2sstr(c, b),
818 cx, cy, s->x1, s->y1, s->x2, s->y2,
819 flip_horiz, flip_vert, flip_diag,
820 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
821 s->type, s->d, b->symmetry.type, b->symmetry.d);
823 if (flip_horiz || flip_vert || flip_diag)
824 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
828 static void
829 tree_unlink_node(struct tree_node *node)
831 struct tree_node *ni = node->parent;
832 if (ni->children == node) {
833 ni->children = node->sibling;
834 } else {
835 ni = ni->children;
836 while (ni->sibling != node)
837 ni = ni->sibling;
838 ni->sibling = node->sibling;
840 node->sibling = NULL;
841 node->parent = NULL;
844 /* Reduce weight of statistics on promotion. Remove nodes that
845 * get reduced to zero playouts; returns next node to consider
846 * in the children list (@node may get deleted). */
847 static struct tree_node *
848 tree_age_node(struct tree *tree, struct tree_node *node)
850 node->u.playouts /= tree->ltree_aging;
851 if (node->parent && !node->u.playouts) {
852 struct tree_node *sibling = node->sibling;
853 /* Delete node, no playouts. */
854 tree_unlink_node(node);
855 tree_done_node(tree, node);
856 return sibling;
859 struct tree_node *ni = node->children;
860 while (ni) ni = tree_age_node(tree, ni);
861 return node->sibling;
864 /* Promotes the given node as the root of the tree. In the fast_alloc
865 * mode, the node may be moved and some of its subtree may be pruned. */
866 void
867 tree_promote_node(struct tree *tree, struct tree_node **node)
869 assert((*node)->parent == tree->root);
870 tree_unlink_node(*node);
871 if (!tree->nodes) {
872 /* Freeing the rest of the tree can take several seconds on large
873 * trees, so we must do it asynchronously: */
874 tree_done_node_detached(tree, tree->root);
875 } else {
876 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
877 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
878 if (tree->nodes_size >= tree->max_tree_size - min_free_size
879 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
880 *node = tree_garbage_collect(tree, min_free_size, *node);
882 tree->root = *node;
883 tree->root_color = stone_other(tree->root_color);
885 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
886 /* See tree.score description for explanation on why don't we zero
887 * score on node promotion. */
888 // tree->score.playouts = 0;
890 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
891 * tree->max_depth is correct. Otherwise we could traverse the tree
892 * to recompute max_depth but it's not worth it: it's just for debugging
893 * and soon the tree will grow and max_depth will become correct again. */
895 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
896 tree_age_node(tree, tree->ltree_black);
897 tree_age_node(tree, tree->ltree_white);
901 bool
902 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
904 tree_fix_symmetry(tree, b, c);
906 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
907 if (ni->coord == c) {
908 tree_promote_node(tree, &ni);
909 return true;
912 return false;