board_gamma_update: Fix FEAT_AESCAPE construction
[pachi.git] / uct / tree.c
blobe21f778841e7cf787e239029ad12272f183c1b97
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"
20 #include "uct/slave.h"
23 /* Allocate tree node(s). The returned nodes are _not_ initialized.
24 * Returns NULL if not enough memory.
25 * This function may be called by multiple threads in parallel. */
26 static struct tree_node *
27 tree_alloc_node(struct tree *t, int count, bool fast_alloc, hash_t *hash)
29 struct tree_node *n = NULL;
30 size_t nsize = count * sizeof(*n);
31 unsigned long old_size = __sync_fetch_and_add(&t->nodes_size, nsize);
33 if (fast_alloc) {
34 if (old_size + nsize > t->max_tree_size)
35 return NULL;
36 assert(t->nodes != NULL);
37 n = (struct tree_node *)(t->nodes + old_size);
38 memset(n, 0, sizeof(*n));
39 } else {
40 n = calloc2(count, sizeof(*n));
43 if (hash) {
44 volatile static long c = 1000000;
45 *hash = __sync_fetch_and_add(&c, count);
48 return n;
51 /* Initialize a node at a given place in memory.
52 * This function may be called by multiple threads in parallel. */
53 static void
54 tree_setup_node(struct tree *t, struct tree_node *n, coord_t coord, int depth, hash_t hash)
56 n->coord = coord;
57 n->depth = depth;
58 n->hash = hash;
59 if (depth > t->max_depth)
60 t->max_depth = depth;
63 /* Allocate and initialize a node. Returns NULL (fast_alloc mode)
64 * or exits the main program if not enough memory.
65 * This function may be called by multiple threads in parallel. */
66 static struct tree_node *
67 tree_init_node(struct tree *t, coord_t coord, int depth, bool fast_alloc)
69 struct tree_node *n;
70 hash_t hash;
71 n = tree_alloc_node(t, 1, fast_alloc, &hash);
72 if (!n) return NULL;
73 tree_setup_node(t, n, coord, depth, hash);
74 return n;
77 /* Create a tree structure. Pre-allocate all nodes if max_tree_size is > 0. */
78 struct tree *
79 tree_init(struct board *board, enum stone color, unsigned long max_tree_size, float ltree_aging, int hbits)
81 struct tree *t = calloc2(1, sizeof(*t));
82 t->board = board;
83 t->max_tree_size = max_tree_size;
84 if (max_tree_size != 0) {
85 t->nodes = malloc2(max_tree_size);
86 /* The nodes buffer doesn't need initialization. This is currently
87 * done by tree_init_node to spread the load. Doing a memset for the
88 * entire buffer here would be too slow for large trees (>10 GB). */
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;
99 t->hbits = hbits;
100 if (hbits) t->htable = uct_htable_alloc(hbits);
101 return t;
105 /* This function may be called by multiple threads in parallel on the
106 * same tree, but not on node n. n may be detached from the tree but
107 * must have been created in this tree originally.
108 * It returns the remaining size of the tree after n has been freed. */
109 static unsigned long
110 tree_done_node(struct tree *t, struct tree_node *n)
112 struct tree_node *ni = n->children;
113 while (ni) {
114 struct tree_node *nj = ni->sibling;
115 tree_done_node(t, ni);
116 ni = nj;
118 free(n);
119 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
120 return old_size - sizeof(*n);
123 struct subtree_ctx {
124 struct tree *t;
125 struct tree_node *n;
128 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
129 static void *
130 tree_done_node_worker(void *ctx_)
132 struct subtree_ctx *ctx = ctx_;
133 char *str = coord2str(ctx->n->coord, ctx->t->board);
135 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
136 if (!tree_size)
137 free(ctx->t);
138 if (DEBUGL(2))
139 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
140 free(str);
141 free(ctx);
142 return NULL;
145 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
146 * empty free the tree also. Only for fast_alloc=false. */
147 static void
148 tree_done_node_detached(struct tree *t, struct tree_node *n)
150 if (n->u.playouts < 1000) { // no thread for small tree
151 if (!tree_done_node(t, n))
152 free(t);
153 return;
155 pthread_attr_t attr;
156 pthread_attr_init(&attr);
157 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
159 pthread_t thread;
160 struct subtree_ctx *ctx = malloc2(sizeof(struct subtree_ctx));
161 ctx->t = t;
162 ctx->n = n;
163 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
164 pthread_attr_destroy(&attr);
167 void
168 tree_done(struct tree *t)
170 tree_done_node(t, t->ltree_black);
171 tree_done_node(t, t->ltree_white);
173 if (t->htable) free(t->htable);
174 if (t->nodes) {
175 free(t->nodes);
176 free(t);
177 } else if (!tree_done_node(t, t->root)) {
178 free(t);
179 /* A tree_done_node_worker might still be running on this tree but
180 * it will free the tree later. It is also freeing nodes faster than
181 * we will create new ones. */
186 static void
187 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
189 for (int i = 0; i < l; i++) fputc(' ', stderr);
190 int children = 0;
191 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
192 children++;
193 /* We use 1 as parity, since for all nodes we want to know the
194 * win probability of _us_, not the node color. */
195 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
196 coord2sstr(node->coord, tree->board),
197 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
198 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
199 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
200 node->hints, children, node->hash);
202 /* Print nodes sorted by #playouts. */
204 struct tree_node *nbox[1000]; int nboxl = 0;
205 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
206 if (ni->u.playouts > thres)
207 nbox[nboxl++] = ni;
209 while (true) {
210 int best = -1;
211 for (int i = 0; i < nboxl; i++)
212 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
213 best = i;
214 if (best < 0)
215 break;
216 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
217 nbox[best] = NULL;
221 void
222 tree_dump(struct tree *tree, int thres)
224 if (thres && tree->root->u.playouts / thres > 100) {
225 /* Be a bit sensible about this; the opening book can create
226 * huge dumps at first. */
227 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
229 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
230 stone2str(tree->root_color), tree->extra_komi);
231 tree_node_dump(tree, tree->root, 0, thres);
233 if (DEBUGL(3) && tree->ltree_black) {
234 fprintf(stderr, "B local tree:\n");
235 tree_node_dump(tree, tree->ltree_black, 0, thres);
236 fprintf(stderr, "W local tree:\n");
237 tree_node_dump(tree, tree->ltree_white, 0, thres);
242 static char *
243 tree_book_name(struct board *b)
245 static char buf[256];
246 if (b->handicap > 0) {
247 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
248 } else {
249 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
251 return buf;
254 static void
255 tree_node_save(FILE *f, struct tree_node *node, int thres)
257 bool save_children = node->u.playouts >= thres;
259 if (!save_children)
260 node->is_expanded = 0;
262 fputc(1, f);
263 fwrite(((void *) node) + offsetof(struct tree_node, depth),
264 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
265 1, f);
267 if (save_children) {
268 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
269 tree_node_save(f, ni, thres);
270 } else {
271 if (node->children)
272 node->is_expanded = 1;
275 fputc(0, f);
278 void
279 tree_save(struct tree *tree, struct board *b, int thres)
281 char *filename = tree_book_name(b);
282 FILE *f = fopen(filename, "wb");
283 if (!f) {
284 perror("fopen");
285 return;
287 tree_node_save(f, tree->root, thres);
288 fputc(0, f);
289 fclose(f);
293 void
294 tree_node_load(FILE *f, struct tree_node *node, int *num)
296 (*num)++;
298 fread(((void *) node) + offsetof(struct tree_node, depth),
299 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
300 1, f);
302 /* Keep values in sane scale, otherwise we start overflowing. */
303 #define MAX_PLAYOUTS 10000000
304 if (node->u.playouts > MAX_PLAYOUTS) {
305 node->u.playouts = MAX_PLAYOUTS;
307 if (node->amaf.playouts > MAX_PLAYOUTS) {
308 node->amaf.playouts = MAX_PLAYOUTS;
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 = calloc2(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 /* Copy the subtree rooted at node: all nodes at or below depth
344 * or with at least threshold playouts. Only for fast_alloc.
345 * The code is destructive on src. The relative order of children of
346 * a given node is preserved (assumed by tree_get_node in particular).
347 * Returns the copy of node in the destination tree, or NULL
348 * if we could not copy it. */
349 static struct tree_node *
350 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
351 int threshold, int depth)
353 assert(dest->nodes && node);
354 struct tree_node *n2 = tree_alloc_node(dest, 1, true, NULL);
355 if (!n2)
356 return NULL;
357 *n2 = *node;
358 if (n2->depth > dest->max_depth)
359 dest->max_depth = n2->depth;
360 n2->children = NULL;
361 n2->is_expanded = false;
363 if (node->depth >= depth && node->u.playouts < threshold)
364 return n2;
365 /* For deep nodes with many playouts, we must copy all children,
366 * even those with zero playouts, because partially expanded
367 * nodes are not supported. Considering them as fully expanded
368 * would degrade the playing strength. The only exception is
369 * when dest becomes full, but this should never happen in practice
370 * if threshold is chosen to limit the number of nodes traversed. */
371 struct tree_node *ni = node->children;
372 if (!ni)
373 return n2;
374 struct tree_node **prev2 = &(n2->children);
375 while (ni) {
376 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
377 if (!ni2) break;
378 *prev2 = ni2;
379 prev2 = &(ni2->sibling);
380 ni2->parent = n2;
381 ni = ni->sibling;
383 if (!ni) {
384 n2->is_expanded = true;
385 } else {
386 n2->children = NULL; // avoid partially expanded nodes
388 return n2;
391 /* The following constants are used for garbage collection of nodes.
392 * A tree is considered large if the top node has >= 40K playouts.
393 * For such trees, we copy deep nodes only if they have enough
394 * playouts, with a gradually increasing threshold up to 40.
395 * These constants define how much time we're willing to spend
396 * scanning the source tree when promoting a move. The chosen values
397 * make worst case pruning in about 3s for 20 GB ram, and this
398 * is only for long thinking time (>1M playouts). For fast games the
399 * trees don't grow large. For small ram or fast game we copy the
400 * entire tree. These values do not degrade playing strength and are
401 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
402 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
403 * playing worse. */
404 #define LARGE_TREE_PLAYOUTS 40000LL
405 #define DEEP_PLAYOUTS_THRESHOLD 40
407 /* Garbage collect the tree early if the top node has < 5K playouts,
408 * to avoid having to do it later on a large subtree.
409 * This guarantees garbage collection in < 1s. */
410 #define SMALL_TREE_PLAYOUTS 5000
412 /* Free all the tree, keeping only the subtree rooted at node.
413 * Prune the subtree if necessary to fit in max_size bytes or
414 * to save time scanning the tree.
415 * Returns the moved node. Only for fast_alloc. */
416 struct tree_node *
417 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
419 assert(tree->nodes && !node->parent && !node->sibling);
420 double start_time = time_now();
422 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging, 0);
423 temp_tree->nodes_size = 0; // We do not want the dummy pass node
424 struct tree_node *temp_node;
426 /* Find the maximum depth at which we can copy all nodes. */
427 int max_nodes = 1;
428 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
429 max_nodes++;
430 unsigned long nodes_size = max_nodes * sizeof(*node);
431 int max_depth = node->depth;
432 while (nodes_size < max_size && max_nodes > 1) {
433 max_nodes--;
434 nodes_size += max_nodes * nodes_size;
435 max_depth++;
438 /* Copy all nodes for small trees. For large trees, copy all nodes
439 * with depth <= max_depth, and all nodes with enough playouts.
440 * Avoiding going too deep (except for nodes with many playouts) is mostly
441 * to save time scanning the source tree. It can take over 20s to traverse
442 * completely a large source tree (20 GB) even without copying because
443 * the traversal is not friendly at all with the memory cache. */
444 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
445 if (threshold < 0) threshold = 0;
446 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
447 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
448 assert(temp_node);
450 /* Now copy back to original tree. */
451 tree->nodes_size = 0;
452 tree->max_depth = 0;
453 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
455 if (DEBUGL(1)) {
456 double now = time_now();
457 static double prev_time;
458 if (!prev_time) prev_time = start_time;
459 fprintf(stderr,
460 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
461 " max_size %lu, pruned size %lu, playouts %d\n",
462 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
463 max_size, temp_tree->nodes_size, new_node->u.playouts);
464 prev_time = start_time;
466 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
467 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
468 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
469 } else {
470 assert(tree->nodes_size == temp_tree->nodes_size);
471 assert(tree->max_depth == temp_tree->max_depth);
473 tree_done(temp_tree);
474 return new_node;
478 /* Get a node of given coordinate from within parent, possibly creating it
479 * if necessary - in a very raw form (no .d, priors, ...). */
480 /* FIXME: Adjust for board symmetry. */
481 struct tree_node *
482 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
484 if (!parent->children || parent->children->coord >= c) {
485 /* Special case: Insertion at the beginning. */
486 if (parent->children && parent->children->coord == c)
487 return parent->children;
488 if (!create)
489 return NULL;
491 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
492 nn->parent = parent; nn->sibling = parent->children;
493 parent->children = nn;
494 return nn;
497 /* No candidate at the beginning, look through all the children. */
499 struct tree_node *ni;
500 for (ni = parent->children; ni->sibling; ni = ni->sibling)
501 if (ni->sibling->coord >= c)
502 break;
504 if (ni->sibling && ni->sibling->coord == c)
505 return ni->sibling;
506 assert(ni->coord < c);
507 if (!create)
508 return NULL;
510 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
511 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
512 return nn;
515 /* Get local tree node corresponding to given node, given local node child
516 * iterator @lni (which points either at the corresponding node, or at the
517 * nearest local tree node after @ni). */
518 struct tree_node *
519 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
521 /* Now set up lnode, which is the actual local node
522 * corresponding to ni - either lni if it is an
523 * exact match and ni is not tenuki, <pass> local
524 * node if ni is tenuki, or NULL if there is no
525 * corresponding node available. */
527 if (is_pass(ni->coord)) {
528 /* Also, for sanity reasons we never use local
529 * tree for passes. (Maybe we could, but it's
530 * too hard to think about.) */
531 return NULL;
534 if (lni->coord == ni->coord) {
535 /* We don't consider tenuki a sequence play
536 * that we have in local tree even though
537 * ni->d is too high; this can happen if this
538 * occured in different board topology. */
539 return lni;
542 if (ni->d >= tenuki_d) {
543 /* Tenuki, pick a pass lsibling if available. */
544 assert(lni->parent && lni->parent->children);
545 if (is_pass(lni->parent->children->coord)) {
546 return lni->parent->children;
547 } else {
548 return NULL;
552 /* No corresponding local node, lnode stays NULL. */
553 return NULL;
557 /* Tree symmetry: When possible, we will localize the tree to a single part
558 * of the board in tree_expand_node() and possibly flip along symmetry axes
559 * to another part of the board in tree_promote_at(). We follow b->symmetry
560 * guidelines here. */
563 /* This function must be thread safe, given that board b is only modified by the calling thread. */
564 void
565 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
567 /* Get a Common Fate Graph distance map from parent node. */
568 int distances[board_size2(b)];
569 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
570 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
571 } else {
572 // Pass or resign - everything is too far.
573 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
576 /* Get a map of prior values to initialize the new nodes with. */
577 struct prior_map map = {
578 .b = b,
579 .to_play = color,
580 .parity = tree_parity(t, parity),
581 .distances = distances,
583 // Include pass in the prior map.
584 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
585 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
586 memset(map_prior, 0, sizeof(map_prior));
587 memset(map_consider, 0, sizeof(map_consider));
588 map.consider[pass] = true;
589 foreach_free_point(b) {
590 assert(board_at(b, c) == S_NONE);
591 if (!board_is_valid_play(b, color, c))
592 continue;
593 map.consider[c] = true;
594 } foreach_free_point_end;
595 uct_prior(u, node, &map);
597 /* Now, create the nodes. */
598 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
599 /* In fast_alloc mode we might temporarily run out of nodes but
600 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
601 if (!ni) {
602 node->is_expanded = false;
603 return;
605 struct tree_node *first_child = ni;
606 ni->parent = node;
607 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
609 /* The loop considers only the symmetry playground. */
610 if (UDEBUGL(6)) {
611 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
612 coord2sstr(node->coord, b),
613 b->symmetry.x1, b->symmetry.y1,
614 b->symmetry.x2, b->symmetry.y2,
615 b->symmetry.type, b->symmetry.d);
617 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
618 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
619 if (b->symmetry.d) {
620 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
621 if (x > j) {
622 if (UDEBUGL(7))
623 fprintf(stderr, "drop %d,%d\n", i, j);
624 continue;
628 coord_t c = coord_xy(t->board, i, j);
629 if (!map.consider[c]) // Filter out invalid moves
630 continue;
631 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
633 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
634 if (!nj) {
635 node->is_expanded = false;
636 return;
638 nj->parent = node; ni->sibling = nj; ni = nj;
640 ni->prior = map.prior[c];
641 ni->d = distances[c];
644 node->children = first_child; // must be done at the end to avoid race
648 static coord_t
649 flip_coord(struct board *b, coord_t c,
650 bool flip_horiz, bool flip_vert, int flip_diag)
652 int x = coord_x(c, b), y = coord_y(c, b);
653 if (flip_diag) {
654 int z = x; x = y; y = z;
656 if (flip_horiz) {
657 x = board_size(b) - 1 - x;
659 if (flip_vert) {
660 y = board_size(b) - 1 - y;
662 return coord_xy(b, x, y);
665 static void
666 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
667 bool flip_horiz, bool flip_vert, int flip_diag)
669 if (!is_pass(node->coord))
670 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
672 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
673 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
676 static void
677 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
679 if (is_pass(c))
680 return;
682 struct board_symmetry *s = &tree->root_symmetry;
683 int cx = coord_x(c, b), cy = coord_y(c, b);
685 /* playground X->h->v->d normalization
686 * :::.. .d...
687 * .::.. v....
688 * ..:.. .....
689 * ..... h...X
690 * ..... ..... */
691 bool flip_horiz = cx < s->x1 || cx > s->x2;
692 bool flip_vert = cy < s->y1 || cy > s->y2;
694 bool flip_diag = 0;
695 if (s->d) {
696 bool dir = (s->type == SYM_DIAG_DOWN);
697 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
698 if (flip_vert ? x < cy : x > cy) {
699 flip_diag = 1;
703 if (DEBUGL(4)) {
704 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
705 coord2sstr(c, b),
706 cx, cy, s->x1, s->y1, s->x2, s->y2,
707 flip_horiz, flip_vert, flip_diag,
708 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
709 s->type, s->d, b->symmetry.type, b->symmetry.d);
711 if (flip_horiz || flip_vert || flip_diag)
712 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
716 static void
717 tree_unlink_node(struct tree_node *node)
719 struct tree_node *ni = node->parent;
720 if (ni->children == node) {
721 ni->children = node->sibling;
722 } else {
723 ni = ni->children;
724 while (ni->sibling != node)
725 ni = ni->sibling;
726 ni->sibling = node->sibling;
728 node->sibling = NULL;
729 node->parent = NULL;
732 /* Reduce weight of statistics on promotion. Remove nodes that
733 * get reduced to zero playouts; returns next node to consider
734 * in the children list (@node may get deleted). */
735 static struct tree_node *
736 tree_age_node(struct tree *tree, struct tree_node *node)
738 node->u.playouts /= tree->ltree_aging;
739 if (node->parent && !node->u.playouts) {
740 struct tree_node *sibling = node->sibling;
741 /* Delete node, no playouts. */
742 tree_unlink_node(node);
743 tree_done_node(tree, node);
744 return sibling;
747 struct tree_node *ni = node->children;
748 while (ni) ni = tree_age_node(tree, ni);
749 return node->sibling;
752 /* Promotes the given node as the root of the tree. In the fast_alloc
753 * mode, the node may be moved and some of its subtree may be pruned. */
754 void
755 tree_promote_node(struct tree *tree, struct tree_node **node)
757 assert((*node)->parent == tree->root);
758 tree_unlink_node(*node);
759 if (!tree->nodes) {
760 /* Freeing the rest of the tree can take several seconds on large
761 * trees, so we must do it asynchronously: */
762 tree_done_node_detached(tree, tree->root);
763 } else {
764 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
765 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
766 if (tree->nodes_size >= tree->max_tree_size - min_free_size
767 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
768 *node = tree_garbage_collect(tree, min_free_size, *node);
770 tree->root = *node;
771 tree->root_color = stone_other(tree->root_color);
773 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
774 /* See tree.score description for explanation on why don't we zero
775 * score on node promotion. */
776 // tree->score.playouts = 0;
778 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
779 * tree->max_depth is correct. Otherwise we could traverse the tree
780 * to recompute max_depth but it's not worth it: it's just for debugging
781 * and soon the tree will grow and max_depth will become correct again. */
783 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
784 tree_age_node(tree, tree->ltree_black);
785 tree_age_node(tree, tree->ltree_white);
789 bool
790 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
792 tree_fix_symmetry(tree, b, c);
794 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
795 if (ni->coord == c) {
796 tree_promote_node(tree, &ni);
797 return true;
800 return false;