Merge branch 'dist' into derm
[pachi/json.git] / uct / tree.c
blob947d02d88573a02e137ac272117e9600241958c7
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 = calloc(1, sizeof(*n));
53 if (!n) {
54 fprintf(stderr, "tree_init_node(): OUT OF MEMORY\n");
55 exit(1);
57 __sync_fetch_and_add(&t->nodes_size, sizeof(*n));
59 n->coord = coord;
60 n->depth = depth;
61 volatile static long c = 1000000;
62 n->hash = __sync_fetch_and_add(&c, 1);
63 if (depth > t->max_depth)
64 t->max_depth = depth;
65 return n;
68 /* Create a tree structure. Pre-allocate all nodes if max_tree_size is > 0. */
69 struct tree *
70 tree_init(struct board *board, enum stone color, unsigned long max_tree_size, float ltree_aging)
72 struct tree *t = calloc(1, sizeof(*t));
73 if (!t) {
74 fprintf(stderr, "tree_init(): OUT OF MEMORY\n");
75 exit(1);
77 t->board = board;
78 t->max_tree_size = max_tree_size;
79 if (max_tree_size != 0) {
80 /* Allocate one extra node, max_tree_size may not be multiple of node size. */
81 t->nodes = malloc(max_tree_size + sizeof(struct tree_node));
82 /* The nodes buffer doesn't need initialization. This is currently
83 * done by tree_init_node to spread the load. Doing a memset for the
84 * entire buffer here would be too slow for large trees (>10 GB). */
85 if (!t->nodes) {
86 fprintf(stderr, "tree_init(): OUT OF MEMORY\n");
87 exit(1);
90 /* The root PASS move is only virtual, we never play it. */
91 t->root = tree_init_node(t, pass, 0, t->nodes);
92 t->root_symmetry = board->symmetry;
93 t->root_color = stone_other(color); // to research black moves, root will be white
95 t->ltree_black = tree_init_node(t, pass, 0, false);
96 t->ltree_white = tree_init_node(t, pass, 0, false);
97 t->ltree_aging = ltree_aging;
98 return t;
102 /* This function may be called by multiple threads in parallel on the
103 * same tree, but not on node n. n may be detached from the tree but
104 * must have been created in this tree originally.
105 * It returns the remaining size of the tree after n has been freed. */
106 static unsigned long
107 tree_done_node(struct tree *t, struct tree_node *n)
109 struct tree_node *ni = n->children;
110 while (ni) {
111 struct tree_node *nj = ni->sibling;
112 tree_done_node(t, ni);
113 ni = nj;
115 free(n);
116 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
117 return old_size - sizeof(*n);
120 struct subtree_ctx {
121 struct tree *t;
122 struct tree_node *n;
125 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
126 static void *
127 tree_done_node_worker(void *ctx_)
129 struct subtree_ctx *ctx = ctx_;
130 char *str = coord2str(ctx->n->coord, ctx->t->board);
132 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
133 if (!tree_size)
134 free(ctx->t);
135 if (DEBUGL(2))
136 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
137 free(str);
138 free(ctx);
139 return NULL;
142 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
143 * empty free the tree also. Only for fast_alloc=false. */
144 static void
145 tree_done_node_detached(struct tree *t, struct tree_node *n)
147 if (n->u.playouts < 1000) { // no thread for small tree
148 if (!tree_done_node(t, n))
149 free(t);
150 return;
152 pthread_attr_t attr;
153 pthread_attr_init(&attr);
154 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
156 pthread_t thread;
157 struct subtree_ctx *ctx = malloc(sizeof(struct subtree_ctx));
158 if (!ctx) {
159 fprintf(stderr, "tree_done_node_detached(): OUT OF MEMORY\n");
160 exit(1);
162 ctx->t = t;
163 ctx->n = n;
164 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
165 pthread_attr_destroy(&attr);
168 void
169 tree_done(struct tree *t)
171 tree_done_node(t, t->ltree_black);
172 tree_done_node(t, t->ltree_white);
173 if (t->nodes) {
174 free(t->nodes);
175 free(t);
176 } else if (!tree_done_node(t, t->root)) {
177 free(t);
178 /* A tree_done_node_worker might still be running on this tree but
179 * it will free the tree later. It is also freeing nodes faster than
180 * we will create new ones. */
185 static void
186 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
188 for (int i = 0; i < l; i++) fputc(' ', stderr);
189 int children = 0;
190 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
191 children++;
192 /* We use 1 as parity, since for all nodes we want to know the
193 * win probability of _us_, not the node color. */
194 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
195 coord2sstr(node->coord, tree->board),
196 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
197 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
198 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
199 node->hints, children, node->hash);
201 /* Print nodes sorted by #playouts. */
203 struct tree_node *nbox[1000]; int nboxl = 0;
204 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
205 if (ni->u.playouts > thres)
206 nbox[nboxl++] = ni;
208 while (true) {
209 int best = -1;
210 for (int i = 0; i < nboxl; i++)
211 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
212 best = i;
213 if (best < 0)
214 break;
215 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
216 nbox[best] = NULL;
220 void
221 tree_dump(struct tree *tree, int thres)
223 if (thres && tree->root->u.playouts / thres > 100) {
224 /* Be a bit sensible about this; the opening book can create
225 * huge dumps at first. */
226 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
228 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
229 stone2str(tree->root_color), tree->extra_komi);
230 tree_node_dump(tree, tree->root, 0, thres);
232 if (DEBUGL(3) && tree->ltree_black) {
233 fprintf(stderr, "B local tree:\n");
234 tree_node_dump(tree, tree->ltree_black, 0, thres);
235 fprintf(stderr, "W local tree:\n");
236 tree_node_dump(tree, tree->ltree_white, 0, thres);
241 static char *
242 tree_book_name(struct board *b)
244 static char buf[256];
245 if (b->handicap > 0) {
246 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
247 } else {
248 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
250 return buf;
253 static void
254 tree_node_save(FILE *f, struct tree_node *node, int thres)
256 bool save_children = node->u.playouts >= thres;
258 if (!save_children)
259 node->is_expanded = 0;
261 fputc(1, f);
262 fwrite(((void *) node) + offsetof(struct tree_node, depth),
263 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
264 1, f);
266 if (save_children) {
267 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
268 tree_node_save(f, ni, thres);
269 } else {
270 if (node->children)
271 node->is_expanded = 1;
274 fputc(0, f);
277 void
278 tree_save(struct tree *tree, struct board *b, int thres)
280 char *filename = tree_book_name(b);
281 FILE *f = fopen(filename, "wb");
282 if (!f) {
283 perror("fopen");
284 return;
286 tree_node_save(f, tree->root, thres);
287 fputc(0, f);
288 fclose(f);
292 void
293 tree_node_load(FILE *f, struct tree_node *node, int *num)
295 (*num)++;
297 fread(((void *) node) + offsetof(struct tree_node, depth),
298 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
299 1, f);
301 /* Keep values in sane scale, otherwise we start overflowing. */
302 #define MAX_PLAYOUTS 10000000
303 if (node->u.playouts > MAX_PLAYOUTS) {
304 node->u.playouts = MAX_PLAYOUTS;
306 if (node->amaf.playouts > MAX_PLAYOUTS) {
307 node->amaf.playouts = MAX_PLAYOUTS;
309 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
310 memcpy(&node->pu, &node->u, sizeof(node->u));
312 struct tree_node *ni = NULL, *ni_prev = NULL;
313 while (fgetc(f)) {
314 ni_prev = ni; ni = calloc(1, sizeof(*ni));
315 if (!node->children)
316 node->children = ni;
317 else
318 ni_prev->sibling = ni;
319 ni->parent = node;
320 tree_node_load(f, ni, num);
324 void
325 tree_load(struct tree *tree, struct board *b)
327 char *filename = tree_book_name(b);
328 FILE *f = fopen(filename, "rb");
329 if (!f)
330 return;
332 fprintf(stderr, "Loading opening book %s...\n", filename);
334 int num = 0;
335 if (fgetc(f))
336 tree_node_load(f, tree->root, &num);
337 fprintf(stderr, "Loaded %d nodes.\n", num);
339 fclose(f);
343 static struct tree_node *
344 tree_node_copy(struct tree_node *node)
346 struct tree_node *n2 = malloc(sizeof(*n2));
347 *n2 = *node;
348 if (!node->children)
349 return n2;
350 struct tree_node *ni = node->children;
351 struct tree_node *ni2 = tree_node_copy(ni);
352 n2->children = ni2; ni2->parent = n2;
353 while ((ni = ni->sibling)) {
354 ni2->sibling = tree_node_copy(ni);
355 ni2 = ni2->sibling; ni2->parent = n2;
357 return n2;
360 struct tree *
361 tree_copy(struct tree *tree)
363 assert(!tree->nodes);
364 struct tree *t2 = malloc(sizeof(*t2));
365 *t2 = *tree;
366 t2->root = tree_node_copy(tree->root);
367 return t2;
370 /* Copy the subtree rooted at node: all nodes at or below depth
371 * or with at least threshold playouts. Only for fast_alloc.
372 * The code is destructive on src. The relative order of children of
373 * a given node is preserved (assumed by tree_get_node in particular).
374 * Returns the copy of node in the destination tree, or NULL
375 * if we could not copy it. */
376 static struct tree_node *
377 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
378 int threshold, int depth)
380 assert(dest->nodes && node);
381 struct tree_node *n2 = tree_fast_alloc_node(dest);
382 if (!n2)
383 return NULL;
384 *n2 = *node;
385 if (n2->depth > dest->max_depth)
386 dest->max_depth = n2->depth;
387 n2->children = NULL;
388 n2->is_expanded = false;
390 if (node->depth >= depth && node->u.playouts < threshold)
391 return n2;
392 /* For deep nodes with many playouts, we must copy all children,
393 * even those with zero playouts, because partially expanded
394 * nodes are not supported. Considering them as fully expanded
395 * would degrade the playing strength. The only exception is
396 * when dest becomes full, but this should never happen in practice
397 * if threshold is chosen to limit the number of nodes traversed. */
398 struct tree_node *ni = node->children;
399 if (!ni)
400 return n2;
401 struct tree_node **prev2 = &(n2->children);
402 while (ni) {
403 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
404 if (!ni2) break;
405 *prev2 = ni2;
406 prev2 = &(ni2->sibling);
407 ni2->parent = n2;
408 ni = ni->sibling;
410 if (!ni) {
411 n2->is_expanded = true;
412 } else {
413 n2->children = NULL; // avoid partially expanded nodes
415 return n2;
418 /* The following constants are used for garbage collection of nodes.
419 * A tree is considered large if the top node has >= 40K playouts.
420 * For such trees, we copy deep nodes only if they have enough
421 * playouts, with a gradually increasing threshold up to 40.
422 * These constants define how much time we're willing to spend
423 * scanning the source tree when promoting a move. The chosen values
424 * make worst case pruning in about 3s for 20 GB ram, and this
425 * is only for long thinking time (>1M playouts). For fast games the
426 * trees don't grow large. For small ram or fast game we copy the
427 * entire tree. These values do not degrade playing strength and are
428 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
429 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
430 * playing worse. */
431 #define LARGE_TREE_PLAYOUTS 40000LL
432 #define DEEP_PLAYOUTS_THRESHOLD 40
434 /* Garbage collect the tree early if the top node has < 5K playouts,
435 * to avoid having to do it later on a large subtree.
436 * This guarantees garbage collection in < 1s. */
437 #define SMALL_TREE_PLAYOUTS 5000
439 /* Free all the tree, keeping only the subtree rooted at node.
440 * Prune the subtree if necessary to fit in max_size bytes or
441 * to save time scanning the tree.
442 * Returns the moved node. Only for fast_alloc. */
443 struct tree_node *
444 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
446 assert(tree->nodes && !node->parent && !node->sibling);
447 double start_time = time_now();
449 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging);
450 temp_tree->nodes_size = 0; // We do not want the dummy pass node
451 struct tree_node *temp_node;
453 /* Find the maximum depth at which we can copy all nodes. */
454 int max_nodes = 1;
455 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
456 max_nodes++;
457 unsigned long nodes_size = max_nodes * sizeof(*node);
458 int max_depth = node->depth;
459 while (nodes_size < max_size && max_nodes > 1) {
460 max_nodes--;
461 nodes_size += max_nodes * nodes_size;
462 max_depth++;
465 /* Copy all nodes for small trees. For large trees, copy all nodes
466 * with depth <= max_depth, and all nodes with enough playouts.
467 * Avoiding going too deep (except for nodes with many playouts) is mostly
468 * to save time scanning the source tree. It can take over 20s to traverse
469 * completely a large source tree (20 GB) even without copying because
470 * the traversal is not friendly at all with the memory cache. */
471 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
472 if (threshold < 0) threshold = 0;
473 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
474 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
475 assert(temp_node);
477 /* Now copy back to original tree. */
478 tree->nodes_size = 0;
479 tree->max_depth = 0;
480 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
482 if (DEBUGL(1)) {
483 double now = time_now();
484 static double prev_time;
485 if (!prev_time) prev_time = start_time;
486 fprintf(stderr,
487 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
488 " max_size %lu, pruned size %lu, playouts %d\n",
489 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
490 max_size, temp_tree->nodes_size, new_node->u.playouts);
491 prev_time = start_time;
493 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
494 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
495 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
496 } else {
497 assert(tree->nodes_size == temp_tree->nodes_size);
498 assert(tree->max_depth == temp_tree->max_depth);
500 tree_done(temp_tree);
501 return new_node;
505 static void
506 tree_node_merge(struct tree_node *dest, struct tree_node *src)
508 /* Do not merge nodes that weren't touched at all. */
509 assert(dest->pamaf.playouts == src->pamaf.playouts);
510 assert(dest->pu.playouts == src->pu.playouts);
511 if (src->amaf.playouts - src->pamaf.playouts == 0
512 && src->u.playouts - src->pu.playouts == 0) {
513 return;
516 dest->hints |= src->hints;
518 /* Merge the children, both are coord-sorted lists. */
519 struct tree_node *di = dest->children, **dref = &dest->children;
520 struct tree_node *si = src->children, **sref = &src->children;
521 while (di && si) {
522 if (di->coord != si->coord) {
523 /* src has some extra items or misses di */
524 struct tree_node *si2 = si->sibling;
525 while (si2 && di->coord != si2->coord) {
526 si2 = si2->sibling;
528 if (!si2)
529 goto next_di; /* src misses di, move on */
530 /* chain the extra [si,si2) items before di */
531 (*dref) = si;
532 while (si->sibling != si2) {
533 si->parent = dest;
534 si = si->sibling;
536 si->parent = dest;
537 si->sibling = di;
538 si = si2;
539 (*sref) = si;
541 /* Matching nodes - recurse... */
542 tree_node_merge(di, si);
543 /* ...and move on. */
544 sref = &si->sibling; si = si->sibling;
545 next_di:
546 dref = &di->sibling; di = di->sibling;
548 if (si) {
549 /* Some outstanding nodes are left on src side, rechain
550 * them to dst. */
551 (*dref) = si;
552 while (si) {
553 si->parent = dest;
554 si = si->sibling;
556 (*sref) = NULL;
559 /* Priors should be constant. */
560 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
562 stats_merge(&dest->amaf, &src->amaf);
563 stats_merge(&dest->u, &src->u);
566 /* Merge two trees built upon the same board. Note that the operation is
567 * destructive on src. */
568 void
569 tree_merge(struct tree *dest, struct tree *src)
571 if (src->max_depth > dest->max_depth)
572 dest->max_depth = src->max_depth;
573 tree_node_merge(dest->root, src->root);
577 static void
578 tree_node_normalize(struct tree_node *node, int factor)
580 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
581 tree_node_normalize(ni, factor);
583 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
584 normalize(pamaf, amaf, playouts);
585 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
587 normalize(pu, u, playouts);
588 memcpy(&node->pu, &node->u, sizeof(node->u));
589 #undef normalize
592 /* Normalize a tree, dividing the amaf and u values by given
593 * factor; otherwise, simulations run in independent threads
594 * two trees built upon the same board. To correctly handle
595 * results taken from previous simulation run, they are backed
596 * up in tree. */
597 void
598 tree_normalize(struct tree *tree, int factor)
600 tree_node_normalize(tree->root, factor);
604 /* Get a node of given coordinate from within parent, possibly creating it
605 * if necessary - in a very raw form (no .d, priors, ...). */
606 /* FIXME: Adjust for board symmetry. */
607 struct tree_node *
608 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
610 if (!parent->children || parent->children->coord >= c) {
611 /* Special case: Insertion at the beginning. */
612 if (parent->children && parent->children->coord == c)
613 return parent->children;
614 if (!create)
615 return NULL;
617 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
618 nn->parent = parent; nn->sibling = parent->children;
619 parent->children = nn;
620 return nn;
623 /* No candidate at the beginning, look through all the children. */
625 struct tree_node *ni;
626 for (ni = parent->children; ni->sibling; ni = ni->sibling)
627 if (ni->sibling->coord >= c)
628 break;
630 if (ni->sibling && ni->sibling->coord == c)
631 return ni->sibling;
632 assert(ni->coord < c);
633 if (!create)
634 return NULL;
636 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
637 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
638 return nn;
641 /* Get local tree node corresponding to given node, given local node child
642 * iterator @lni (which points either at the corresponding node, or at the
643 * nearest local tree node after @ni). */
644 struct tree_node *
645 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
647 /* Now set up lnode, which is the actual local node
648 * corresponding to ni - either lni if it is an
649 * exact match and ni is not tenuki, <pass> local
650 * node if ni is tenuki, or NULL if there is no
651 * corresponding node available. */
653 if (is_pass(ni->coord)) {
654 /* Also, for sanity reasons we never use local
655 * tree for passes. (Maybe we could, but it's
656 * too hard to think about.) */
657 return NULL;
660 if (lni->coord == ni->coord) {
661 /* We don't consider tenuki a sequence play
662 * that we have in local tree even though
663 * ni->d is too high; this can happen if this
664 * occured in different board topology. */
665 return lni;
668 if (ni->d >= tenuki_d) {
669 /* Tenuki, pick a pass lsibling if available. */
670 assert(lni->parent && lni->parent->children);
671 if (is_pass(lni->parent->children->coord)) {
672 return lni->parent->children;
673 } else {
674 return NULL;
678 /* No corresponding local node, lnode stays NULL. */
679 return NULL;
683 /* Tree symmetry: When possible, we will localize the tree to a single part
684 * of the board in tree_expand_node() and possibly flip along symmetry axes
685 * to another part of the board in tree_promote_at(). We follow b->symmetry
686 * guidelines here. */
689 /* This function must be thread safe, given that board b is only modified by the calling thread. */
690 void
691 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
693 /* Get a Common Fate Graph distance map from parent node. */
694 int distances[board_size2(b)];
695 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
696 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
697 } else {
698 // Pass or resign - everything is too far.
699 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
702 /* Get a map of prior values to initialize the new nodes with. */
703 struct prior_map map = {
704 .b = b,
705 .to_play = color,
706 .parity = tree_parity(t, parity),
707 .distances = distances,
709 // Include pass in the prior map.
710 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
711 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
712 memset(map_prior, 0, sizeof(map_prior));
713 memset(map_consider, 0, sizeof(map_consider));
714 map.consider[pass] = true;
715 foreach_point(b) {
716 if (board_at(b, c) != S_NONE)
717 continue;
718 if (!board_is_valid_play(b, color, c))
719 continue;
720 map.consider[c] = true;
721 } foreach_point_end;
722 uct_prior(u, node, &map);
724 /* Now, create the nodes. */
725 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
726 /* In fast_alloc mode we might temporarily run out of nodes but
727 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
728 if (!ni) {
729 node->is_expanded = false;
730 return;
732 struct tree_node *first_child = ni;
733 ni->parent = node;
734 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
736 /* The loop considers only the symmetry playground. */
737 if (UDEBUGL(6)) {
738 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
739 coord2sstr(node->coord, b),
740 b->symmetry.x1, b->symmetry.y1,
741 b->symmetry.x2, b->symmetry.y2,
742 b->symmetry.type, b->symmetry.d);
744 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
745 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
746 if (b->symmetry.d) {
747 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
748 if (x > j) {
749 if (UDEBUGL(7))
750 fprintf(stderr, "drop %d,%d\n", i, j);
751 continue;
755 coord_t c = coord_xy_otf(i, j, t->board);
756 if (!map.consider[c]) // Filter out invalid moves
757 continue;
758 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
760 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
761 if (!nj) {
762 node->is_expanded = false;
763 return;
765 nj->parent = node; ni->sibling = nj; ni = nj;
767 ni->prior = map.prior[c];
768 ni->d = distances[c];
771 node->children = first_child; // must be done at the end to avoid race
775 static coord_t
776 flip_coord(struct board *b, coord_t c,
777 bool flip_horiz, bool flip_vert, int flip_diag)
779 int x = coord_x(c, b), y = coord_y(c, b);
780 if (flip_diag) {
781 int z = x; x = y; y = z;
783 if (flip_horiz) {
784 x = board_size(b) - 1 - x;
786 if (flip_vert) {
787 y = board_size(b) - 1 - y;
789 return coord_xy_otf(x, y, b);
792 static void
793 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
794 bool flip_horiz, bool flip_vert, int flip_diag)
796 if (!is_pass(node->coord))
797 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
799 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
800 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
803 static void
804 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
806 if (is_pass(c))
807 return;
809 struct board_symmetry *s = &tree->root_symmetry;
810 int cx = coord_x(c, b), cy = coord_y(c, b);
812 /* playground X->h->v->d normalization
813 * :::.. .d...
814 * .::.. v....
815 * ..:.. .....
816 * ..... h...X
817 * ..... ..... */
818 bool flip_horiz = cx < s->x1 || cx > s->x2;
819 bool flip_vert = cy < s->y1 || cy > s->y2;
821 bool flip_diag = 0;
822 if (s->d) {
823 bool dir = (s->type == SYM_DIAG_DOWN);
824 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
825 if (flip_vert ? x < cy : x > cy) {
826 flip_diag = 1;
830 if (DEBUGL(4)) {
831 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
832 coord2sstr(c, b),
833 cx, cy, s->x1, s->y1, s->x2, s->y2,
834 flip_horiz, flip_vert, flip_diag,
835 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
836 s->type, s->d, b->symmetry.type, b->symmetry.d);
838 if (flip_horiz || flip_vert || flip_diag)
839 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
843 static void
844 tree_unlink_node(struct tree_node *node)
846 struct tree_node *ni = node->parent;
847 if (ni->children == node) {
848 ni->children = node->sibling;
849 } else {
850 ni = ni->children;
851 while (ni->sibling != node)
852 ni = ni->sibling;
853 ni->sibling = node->sibling;
855 node->sibling = NULL;
856 node->parent = NULL;
859 /* Reduce weight of statistics on promotion. Remove nodes that
860 * get reduced to zero playouts; returns next node to consider
861 * in the children list (@node may get deleted). */
862 static struct tree_node *
863 tree_age_node(struct tree *tree, struct tree_node *node)
865 node->u.playouts /= tree->ltree_aging;
866 if (node->parent && !node->u.playouts) {
867 struct tree_node *sibling = node->sibling;
868 /* Delete node, no playouts. */
869 tree_unlink_node(node);
870 tree_done_node(tree, node);
871 return sibling;
874 struct tree_node *ni = node->children;
875 while (ni) ni = tree_age_node(tree, ni);
876 return node->sibling;
879 /* Promotes the given node as the root of the tree. In the fast_alloc
880 * mode, the node may be moved and some of its subtree may be pruned. */
881 void
882 tree_promote_node(struct tree *tree, struct tree_node **node)
884 assert((*node)->parent == tree->root);
885 tree_unlink_node(*node);
886 if (!tree->nodes) {
887 /* Freeing the rest of the tree can take several seconds on large
888 * trees, so we must do it asynchronously: */
889 tree_done_node_detached(tree, tree->root);
890 } else {
891 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
892 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
893 if (tree->nodes_size >= tree->max_tree_size - min_free_size
894 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
895 *node = tree_garbage_collect(tree, min_free_size, *node);
897 tree->root = *node;
898 tree->root_color = stone_other(tree->root_color);
900 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
901 /* See tree.score description for explanation on why don't we zero
902 * score on node promotion. */
903 // tree->score.playouts = 0;
905 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
906 * tree->max_depth is correct. Otherwise we could traverse the tree
907 * to recompute max_depth but it's not worth it: it's just for debugging
908 * and soon the tree will grow and max_depth will become correct again. */
910 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
911 tree_age_node(tree, tree->ltree_black);
912 tree_age_node(tree, tree->ltree_white);
916 bool
917 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
919 tree_fix_symmetry(tree, b, c);
921 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
922 if (ni->coord == c) {
923 tree_promote_node(tree, &ni);
924 return true;
927 return false;