UCT tree_init_node(): Split out tree_setup_node()
[pachi/ann.git] / uct / tree.c
blob0a0fba97c57639eb15145cbae6805489f32fe6b6
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 /* Initialize a node at a given place in memory.
47 * This function may be called by multiple threads in parallel. */
48 static void
49 tree_setup_node(struct tree *t, struct tree_node *n, coord_t coord, int depth, hash_t hash)
51 n->coord = coord;
52 n->depth = depth;
53 n->hash = hash;
54 if (depth > t->max_depth)
55 t->max_depth = depth;
58 /* Allocate and initialize a node. Returns NULL (fast_alloc mode)
59 * or exits the main program if not enough memory.
60 * This function may be called by multiple threads in parallel. */
61 static struct tree_node *
62 tree_init_node(struct tree *t, coord_t coord, int depth, bool fast_alloc)
64 struct tree_node *n;
65 n = tree_alloc_node(t, fast_alloc);
66 if (!n) return NULL;
67 volatile static long c = 1000000;
68 hash_t hash = __sync_fetch_and_add(&c, 1);
69 tree_setup_node(t, n, coord, depth, hash);
70 return n;
73 /* Create a tree structure. Pre-allocate all nodes if max_tree_size is > 0. */
74 struct tree *
75 tree_init(struct board *board, enum stone color, unsigned long max_tree_size, float ltree_aging)
77 struct tree *t = calloc2(1, sizeof(*t));
78 t->board = board;
79 t->max_tree_size = max_tree_size;
80 if (max_tree_size != 0) {
81 /* Allocate one extra node, max_tree_size may not be multiple of node size. */
82 t->nodes = malloc2(max_tree_size + sizeof(struct tree_node));
83 /* The nodes buffer doesn't need initialization. This is currently
84 * done by tree_init_node to spread the load. Doing a memset for the
85 * entire buffer here would be too slow for large trees (>10 GB). */
87 /* The root PASS move is only virtual, we never play it. */
88 t->root = tree_init_node(t, pass, 0, t->nodes);
89 t->root_symmetry = board->symmetry;
90 t->root_color = stone_other(color); // to research black moves, root will be white
92 t->ltree_black = tree_init_node(t, pass, 0, false);
93 t->ltree_white = tree_init_node(t, pass, 0, false);
94 t->ltree_aging = ltree_aging;
95 return t;
99 /* This function may be called by multiple threads in parallel on the
100 * same tree, but not on node n. n may be detached from the tree but
101 * must have been created in this tree originally.
102 * It returns the remaining size of the tree after n has been freed. */
103 static unsigned long
104 tree_done_node(struct tree *t, struct tree_node *n)
106 struct tree_node *ni = n->children;
107 while (ni) {
108 struct tree_node *nj = ni->sibling;
109 tree_done_node(t, ni);
110 ni = nj;
112 free(n);
113 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
114 return old_size - sizeof(*n);
117 struct subtree_ctx {
118 struct tree *t;
119 struct tree_node *n;
122 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
123 static void *
124 tree_done_node_worker(void *ctx_)
126 struct subtree_ctx *ctx = ctx_;
127 char *str = coord2str(ctx->n->coord, ctx->t->board);
129 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
130 if (!tree_size)
131 free(ctx->t);
132 if (DEBUGL(2))
133 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
134 free(str);
135 free(ctx);
136 return NULL;
139 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
140 * empty free the tree also. Only for fast_alloc=false. */
141 static void
142 tree_done_node_detached(struct tree *t, struct tree_node *n)
144 if (n->u.playouts < 1000) { // no thread for small tree
145 if (!tree_done_node(t, n))
146 free(t);
147 return;
149 pthread_attr_t attr;
150 pthread_attr_init(&attr);
151 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
153 pthread_t thread;
154 struct subtree_ctx *ctx = malloc2(sizeof(struct subtree_ctx));
155 ctx->t = t;
156 ctx->n = n;
157 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
158 pthread_attr_destroy(&attr);
161 void
162 tree_done(struct tree *t)
164 tree_done_node(t, t->ltree_black);
165 tree_done_node(t, t->ltree_white);
166 if (t->nodes) {
167 free(t->nodes);
168 free(t);
169 } else if (!tree_done_node(t, t->root)) {
170 free(t);
171 /* A tree_done_node_worker might still be running on this tree but
172 * it will free the tree later. It is also freeing nodes faster than
173 * we will create new ones. */
178 static void
179 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
181 for (int i = 0; i < l; i++) fputc(' ', stderr);
182 int children = 0;
183 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
184 children++;
185 /* We use 1 as parity, since for all nodes we want to know the
186 * win probability of _us_, not the node color. */
187 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
188 coord2sstr(node->coord, tree->board),
189 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
190 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
191 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
192 node->hints, children, node->hash);
194 /* Print nodes sorted by #playouts. */
196 struct tree_node *nbox[1000]; int nboxl = 0;
197 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
198 if (ni->u.playouts > thres)
199 nbox[nboxl++] = ni;
201 while (true) {
202 int best = -1;
203 for (int i = 0; i < nboxl; i++)
204 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
205 best = i;
206 if (best < 0)
207 break;
208 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
209 nbox[best] = NULL;
213 void
214 tree_dump(struct tree *tree, int thres)
216 if (thres && tree->root->u.playouts / thres > 100) {
217 /* Be a bit sensible about this; the opening book can create
218 * huge dumps at first. */
219 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
221 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
222 stone2str(tree->root_color), tree->extra_komi);
223 tree_node_dump(tree, tree->root, 0, thres);
225 if (DEBUGL(3) && tree->ltree_black) {
226 fprintf(stderr, "B local tree:\n");
227 tree_node_dump(tree, tree->ltree_black, 0, thres);
228 fprintf(stderr, "W local tree:\n");
229 tree_node_dump(tree, tree->ltree_white, 0, thres);
234 static char *
235 tree_book_name(struct board *b)
237 static char buf[256];
238 if (b->handicap > 0) {
239 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
240 } else {
241 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
243 return buf;
246 static void
247 tree_node_save(FILE *f, struct tree_node *node, int thres)
249 bool save_children = node->u.playouts >= thres;
251 if (!save_children)
252 node->is_expanded = 0;
254 fputc(1, f);
255 fwrite(((void *) node) + offsetof(struct tree_node, depth),
256 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
257 1, f);
259 if (save_children) {
260 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
261 tree_node_save(f, ni, thres);
262 } else {
263 if (node->children)
264 node->is_expanded = 1;
267 fputc(0, f);
270 void
271 tree_save(struct tree *tree, struct board *b, int thres)
273 char *filename = tree_book_name(b);
274 FILE *f = fopen(filename, "wb");
275 if (!f) {
276 perror("fopen");
277 return;
279 tree_node_save(f, tree->root, thres);
280 fputc(0, f);
281 fclose(f);
285 void
286 tree_node_load(FILE *f, struct tree_node *node, int *num)
288 (*num)++;
290 fread(((void *) node) + offsetof(struct tree_node, depth),
291 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
292 1, f);
294 /* Keep values in sane scale, otherwise we start overflowing. */
295 #define MAX_PLAYOUTS 10000000
296 if (node->u.playouts > MAX_PLAYOUTS) {
297 node->u.playouts = MAX_PLAYOUTS;
299 if (node->amaf.playouts > MAX_PLAYOUTS) {
300 node->amaf.playouts = MAX_PLAYOUTS;
302 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
303 memcpy(&node->pu, &node->u, sizeof(node->u));
305 struct tree_node *ni = NULL, *ni_prev = NULL;
306 while (fgetc(f)) {
307 ni_prev = ni; ni = calloc2(1, sizeof(*ni));
308 if (!node->children)
309 node->children = ni;
310 else
311 ni_prev->sibling = ni;
312 ni->parent = node;
313 tree_node_load(f, ni, num);
317 void
318 tree_load(struct tree *tree, struct board *b)
320 char *filename = tree_book_name(b);
321 FILE *f = fopen(filename, "rb");
322 if (!f)
323 return;
325 fprintf(stderr, "Loading opening book %s...\n", filename);
327 int num = 0;
328 if (fgetc(f))
329 tree_node_load(f, tree->root, &num);
330 fprintf(stderr, "Loaded %d nodes.\n", num);
332 fclose(f);
336 static struct tree_node *
337 tree_node_copy(struct tree_node *node)
339 struct tree_node *n2 = malloc2(sizeof(*n2));
340 *n2 = *node;
341 if (!node->children)
342 return n2;
343 struct tree_node *ni = node->children;
344 struct tree_node *ni2 = tree_node_copy(ni);
345 n2->children = ni2; ni2->parent = n2;
346 while ((ni = ni->sibling)) {
347 ni2->sibling = tree_node_copy(ni);
348 ni2 = ni2->sibling; ni2->parent = n2;
350 return n2;
353 struct tree *
354 tree_copy(struct tree *tree)
356 assert(!tree->nodes);
357 struct tree *t2 = malloc2(sizeof(*t2));
358 *t2 = *tree;
359 t2->root = tree_node_copy(tree->root);
360 return t2;
363 /* Copy the subtree rooted at node: all nodes at or below depth
364 * or with at least threshold playouts. Only for fast_alloc.
365 * The code is destructive on src. The relative order of children of
366 * a given node is preserved (assumed by tree_get_node in particular).
367 * Returns the copy of node in the destination tree, or NULL
368 * if we could not copy it. */
369 static struct tree_node *
370 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
371 int threshold, int depth)
373 assert(dest->nodes && node);
374 struct tree_node *n2 = tree_alloc_node(dest, true);
375 if (!n2)
376 return NULL;
377 *n2 = *node;
378 if (n2->depth > dest->max_depth)
379 dest->max_depth = n2->depth;
380 n2->children = NULL;
381 n2->is_expanded = false;
383 if (node->depth >= depth && node->u.playouts < threshold)
384 return n2;
385 /* For deep nodes with many playouts, we must copy all children,
386 * even those with zero playouts, because partially expanded
387 * nodes are not supported. Considering them as fully expanded
388 * would degrade the playing strength. The only exception is
389 * when dest becomes full, but this should never happen in practice
390 * if threshold is chosen to limit the number of nodes traversed. */
391 struct tree_node *ni = node->children;
392 if (!ni)
393 return n2;
394 struct tree_node **prev2 = &(n2->children);
395 while (ni) {
396 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
397 if (!ni2) break;
398 *prev2 = ni2;
399 prev2 = &(ni2->sibling);
400 ni2->parent = n2;
401 ni = ni->sibling;
403 if (!ni) {
404 n2->is_expanded = true;
405 } else {
406 n2->children = NULL; // avoid partially expanded nodes
408 return n2;
411 /* The following constants are used for garbage collection of nodes.
412 * A tree is considered large if the top node has >= 40K playouts.
413 * For such trees, we copy deep nodes only if they have enough
414 * playouts, with a gradually increasing threshold up to 40.
415 * These constants define how much time we're willing to spend
416 * scanning the source tree when promoting a move. The chosen values
417 * make worst case pruning in about 3s for 20 GB ram, and this
418 * is only for long thinking time (>1M playouts). For fast games the
419 * trees don't grow large. For small ram or fast game we copy the
420 * entire tree. These values do not degrade playing strength and are
421 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
422 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
423 * playing worse. */
424 #define LARGE_TREE_PLAYOUTS 40000LL
425 #define DEEP_PLAYOUTS_THRESHOLD 40
427 /* Garbage collect the tree early if the top node has < 5K playouts,
428 * to avoid having to do it later on a large subtree.
429 * This guarantees garbage collection in < 1s. */
430 #define SMALL_TREE_PLAYOUTS 5000
432 /* Free all the tree, keeping only the subtree rooted at node.
433 * Prune the subtree if necessary to fit in max_size bytes or
434 * to save time scanning the tree.
435 * Returns the moved node. Only for fast_alloc. */
436 struct tree_node *
437 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
439 assert(tree->nodes && !node->parent && !node->sibling);
440 double start_time = time_now();
442 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging);
443 temp_tree->nodes_size = 0; // We do not want the dummy pass node
444 struct tree_node *temp_node;
446 /* Find the maximum depth at which we can copy all nodes. */
447 int max_nodes = 1;
448 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
449 max_nodes++;
450 unsigned long nodes_size = max_nodes * sizeof(*node);
451 int max_depth = node->depth;
452 while (nodes_size < max_size && max_nodes > 1) {
453 max_nodes--;
454 nodes_size += max_nodes * nodes_size;
455 max_depth++;
458 /* Copy all nodes for small trees. For large trees, copy all nodes
459 * with depth <= max_depth, and all nodes with enough playouts.
460 * Avoiding going too deep (except for nodes with many playouts) is mostly
461 * to save time scanning the source tree. It can take over 20s to traverse
462 * completely a large source tree (20 GB) even without copying because
463 * the traversal is not friendly at all with the memory cache. */
464 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
465 if (threshold < 0) threshold = 0;
466 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
467 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
468 assert(temp_node);
470 /* Now copy back to original tree. */
471 tree->nodes_size = 0;
472 tree->max_depth = 0;
473 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
475 if (DEBUGL(1)) {
476 double now = time_now();
477 static double prev_time;
478 if (!prev_time) prev_time = start_time;
479 fprintf(stderr,
480 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
481 " max_size %lu, pruned size %lu, playouts %d\n",
482 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
483 max_size, temp_tree->nodes_size, new_node->u.playouts);
484 prev_time = start_time;
486 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
487 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
488 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
489 } else {
490 assert(tree->nodes_size == temp_tree->nodes_size);
491 assert(tree->max_depth == temp_tree->max_depth);
493 tree_done(temp_tree);
494 return new_node;
498 static void
499 tree_node_merge(struct tree_node *dest, struct tree_node *src)
501 /* Do not merge nodes that weren't touched at all. */
502 assert(dest->pamaf.playouts == src->pamaf.playouts);
503 assert(dest->pu.playouts == src->pu.playouts);
504 if (src->amaf.playouts - src->pamaf.playouts == 0
505 && src->u.playouts - src->pu.playouts == 0) {
506 return;
509 dest->hints |= src->hints;
511 /* Merge the children, both are coord-sorted lists. */
512 struct tree_node *di = dest->children, **dref = &dest->children;
513 struct tree_node *si = src->children, **sref = &src->children;
514 while (di && si) {
515 if (di->coord != si->coord) {
516 /* src has some extra items or misses di */
517 struct tree_node *si2 = si->sibling;
518 while (si2 && di->coord != si2->coord) {
519 si2 = si2->sibling;
521 if (!si2)
522 goto next_di; /* src misses di, move on */
523 /* chain the extra [si,si2) items before di */
524 (*dref) = si;
525 while (si->sibling != si2) {
526 si->parent = dest;
527 si = si->sibling;
529 si->parent = dest;
530 si->sibling = di;
531 si = si2;
532 (*sref) = si;
534 /* Matching nodes - recurse... */
535 tree_node_merge(di, si);
536 /* ...and move on. */
537 sref = &si->sibling; si = si->sibling;
538 next_di:
539 dref = &di->sibling; di = di->sibling;
541 if (si) {
542 /* Some outstanding nodes are left on src side, rechain
543 * them to dst. */
544 (*dref) = si;
545 while (si) {
546 si->parent = dest;
547 si = si->sibling;
549 (*sref) = NULL;
552 /* Priors should be constant. */
553 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
555 stats_merge(&dest->amaf, &src->amaf);
556 stats_merge(&dest->u, &src->u);
559 /* Merge two trees built upon the same board. Note that the operation is
560 * destructive on src. */
561 void
562 tree_merge(struct tree *dest, struct tree *src)
564 if (src->max_depth > dest->max_depth)
565 dest->max_depth = src->max_depth;
566 tree_node_merge(dest->root, src->root);
570 static void
571 tree_node_normalize(struct tree_node *node, int factor)
573 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
574 tree_node_normalize(ni, factor);
576 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
577 normalize(pamaf, amaf, playouts);
578 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
580 normalize(pu, u, playouts);
581 memcpy(&node->pu, &node->u, sizeof(node->u));
582 #undef normalize
585 /* Normalize a tree, dividing the amaf and u values by given
586 * factor; otherwise, simulations run in independent threads
587 * two trees built upon the same board. To correctly handle
588 * results taken from previous simulation run, they are backed
589 * up in tree. */
590 void
591 tree_normalize(struct tree *tree, int factor)
593 tree_node_normalize(tree->root, factor);
597 /* Get a node of given coordinate from within parent, possibly creating it
598 * if necessary - in a very raw form (no .d, priors, ...). */
599 /* FIXME: Adjust for board symmetry. */
600 struct tree_node *
601 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
603 if (!parent->children || parent->children->coord >= c) {
604 /* Special case: Insertion at the beginning. */
605 if (parent->children && parent->children->coord == c)
606 return parent->children;
607 if (!create)
608 return NULL;
610 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
611 nn->parent = parent; nn->sibling = parent->children;
612 parent->children = nn;
613 return nn;
616 /* No candidate at the beginning, look through all the children. */
618 struct tree_node *ni;
619 for (ni = parent->children; ni->sibling; ni = ni->sibling)
620 if (ni->sibling->coord >= c)
621 break;
623 if (ni->sibling && ni->sibling->coord == c)
624 return ni->sibling;
625 assert(ni->coord < c);
626 if (!create)
627 return NULL;
629 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
630 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
631 return nn;
634 /* Get local tree node corresponding to given node, given local node child
635 * iterator @lni (which points either at the corresponding node, or at the
636 * nearest local tree node after @ni). */
637 struct tree_node *
638 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
640 /* Now set up lnode, which is the actual local node
641 * corresponding to ni - either lni if it is an
642 * exact match and ni is not tenuki, <pass> local
643 * node if ni is tenuki, or NULL if there is no
644 * corresponding node available. */
646 if (is_pass(ni->coord)) {
647 /* Also, for sanity reasons we never use local
648 * tree for passes. (Maybe we could, but it's
649 * too hard to think about.) */
650 return NULL;
653 if (lni->coord == ni->coord) {
654 /* We don't consider tenuki a sequence play
655 * that we have in local tree even though
656 * ni->d is too high; this can happen if this
657 * occured in different board topology. */
658 return lni;
661 if (ni->d >= tenuki_d) {
662 /* Tenuki, pick a pass lsibling if available. */
663 assert(lni->parent && lni->parent->children);
664 if (is_pass(lni->parent->children->coord)) {
665 return lni->parent->children;
666 } else {
667 return NULL;
671 /* No corresponding local node, lnode stays NULL. */
672 return NULL;
676 /* Tree symmetry: When possible, we will localize the tree to a single part
677 * of the board in tree_expand_node() and possibly flip along symmetry axes
678 * to another part of the board in tree_promote_at(). We follow b->symmetry
679 * guidelines here. */
682 /* This function must be thread safe, given that board b is only modified by the calling thread. */
683 void
684 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
686 /* Get a Common Fate Graph distance map from parent node. */
687 int distances[board_size2(b)];
688 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
689 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
690 } else {
691 // Pass or resign - everything is too far.
692 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
695 /* Get a map of prior values to initialize the new nodes with. */
696 struct prior_map map = {
697 .b = b,
698 .to_play = color,
699 .parity = tree_parity(t, parity),
700 .distances = distances,
702 // Include pass in the prior map.
703 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
704 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
705 memset(map_prior, 0, sizeof(map_prior));
706 memset(map_consider, 0, sizeof(map_consider));
707 map.consider[pass] = true;
708 foreach_point(b) {
709 if (board_at(b, c) != S_NONE)
710 continue;
711 if (!board_is_valid_play(b, color, c))
712 continue;
713 map.consider[c] = true;
714 } foreach_point_end;
715 uct_prior(u, node, &map);
717 /* Now, create the nodes. */
718 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
719 /* In fast_alloc mode we might temporarily run out of nodes but
720 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
721 if (!ni) {
722 node->is_expanded = false;
723 return;
725 struct tree_node *first_child = ni;
726 ni->parent = node;
727 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
729 /* The loop considers only the symmetry playground. */
730 if (UDEBUGL(6)) {
731 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
732 coord2sstr(node->coord, b),
733 b->symmetry.x1, b->symmetry.y1,
734 b->symmetry.x2, b->symmetry.y2,
735 b->symmetry.type, b->symmetry.d);
737 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
738 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
739 if (b->symmetry.d) {
740 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
741 if (x > j) {
742 if (UDEBUGL(7))
743 fprintf(stderr, "drop %d,%d\n", i, j);
744 continue;
748 coord_t c = coord_xy(t->board, i, j);
749 if (!map.consider[c]) // Filter out invalid moves
750 continue;
751 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
753 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
754 if (!nj) {
755 node->is_expanded = false;
756 return;
758 nj->parent = node; ni->sibling = nj; ni = nj;
760 ni->prior = map.prior[c];
761 ni->d = distances[c];
764 node->children = first_child; // must be done at the end to avoid race
768 static coord_t
769 flip_coord(struct board *b, coord_t c,
770 bool flip_horiz, bool flip_vert, int flip_diag)
772 int x = coord_x(c, b), y = coord_y(c, b);
773 if (flip_diag) {
774 int z = x; x = y; y = z;
776 if (flip_horiz) {
777 x = board_size(b) - 1 - x;
779 if (flip_vert) {
780 y = board_size(b) - 1 - y;
782 return coord_xy(b, x, y);
785 static void
786 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
787 bool flip_horiz, bool flip_vert, int flip_diag)
789 if (!is_pass(node->coord))
790 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
792 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
793 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
796 static void
797 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
799 if (is_pass(c))
800 return;
802 struct board_symmetry *s = &tree->root_symmetry;
803 int cx = coord_x(c, b), cy = coord_y(c, b);
805 /* playground X->h->v->d normalization
806 * :::.. .d...
807 * .::.. v....
808 * ..:.. .....
809 * ..... h...X
810 * ..... ..... */
811 bool flip_horiz = cx < s->x1 || cx > s->x2;
812 bool flip_vert = cy < s->y1 || cy > s->y2;
814 bool flip_diag = 0;
815 if (s->d) {
816 bool dir = (s->type == SYM_DIAG_DOWN);
817 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
818 if (flip_vert ? x < cy : x > cy) {
819 flip_diag = 1;
823 if (DEBUGL(4)) {
824 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
825 coord2sstr(c, b),
826 cx, cy, s->x1, s->y1, s->x2, s->y2,
827 flip_horiz, flip_vert, flip_diag,
828 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
829 s->type, s->d, b->symmetry.type, b->symmetry.d);
831 if (flip_horiz || flip_vert || flip_diag)
832 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
836 static void
837 tree_unlink_node(struct tree_node *node)
839 struct tree_node *ni = node->parent;
840 if (ni->children == node) {
841 ni->children = node->sibling;
842 } else {
843 ni = ni->children;
844 while (ni->sibling != node)
845 ni = ni->sibling;
846 ni->sibling = node->sibling;
848 node->sibling = NULL;
849 node->parent = NULL;
852 /* Reduce weight of statistics on promotion. Remove nodes that
853 * get reduced to zero playouts; returns next node to consider
854 * in the children list (@node may get deleted). */
855 static struct tree_node *
856 tree_age_node(struct tree *tree, struct tree_node *node)
858 node->u.playouts /= tree->ltree_aging;
859 if (node->parent && !node->u.playouts) {
860 struct tree_node *sibling = node->sibling;
861 /* Delete node, no playouts. */
862 tree_unlink_node(node);
863 tree_done_node(tree, node);
864 return sibling;
867 struct tree_node *ni = node->children;
868 while (ni) ni = tree_age_node(tree, ni);
869 return node->sibling;
872 /* Promotes the given node as the root of the tree. In the fast_alloc
873 * mode, the node may be moved and some of its subtree may be pruned. */
874 void
875 tree_promote_node(struct tree *tree, struct tree_node **node)
877 assert((*node)->parent == tree->root);
878 tree_unlink_node(*node);
879 if (!tree->nodes) {
880 /* Freeing the rest of the tree can take several seconds on large
881 * trees, so we must do it asynchronously: */
882 tree_done_node_detached(tree, tree->root);
883 } else {
884 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
885 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
886 if (tree->nodes_size >= tree->max_tree_size - min_free_size
887 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
888 *node = tree_garbage_collect(tree, min_free_size, *node);
890 tree->root = *node;
891 tree->root_color = stone_other(tree->root_color);
893 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
894 /* See tree.score description for explanation on why don't we zero
895 * score on node promotion. */
896 // tree->score.playouts = 0;
898 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
899 * tree->max_depth is correct. Otherwise we could traverse the tree
900 * to recompute max_depth but it's not worth it: it's just for debugging
901 * and soon the tree will grow and max_depth will become correct again. */
903 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
904 tree_age_node(tree, tree->ltree_black);
905 tree_age_node(tree, tree->ltree_white);
909 bool
910 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
912 tree_fix_symmetry(tree, b, c);
914 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
915 if (ni->coord == c) {
916 tree_promote_node(tree, &ni);
917 return true;
920 return false;