Moggy: Remove old, dusty and ineffective assess_local
[pachi.git] / uct / tree.c
blob95018053a6a9c27fc4dfb4f497dafe80b5c03aa0
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/util.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; max depth %d)\n",
230 stone2str(tree->root_color), tree->extra_komi,
231 tree->max_depth - tree->root->depth);
232 tree_node_dump(tree, tree->root, 0, thres);
234 if (DEBUGL(3) && tree->ltree_black) {
235 fprintf(stderr, "B local tree:\n");
236 tree_node_dump(tree, tree->ltree_black, 0, thres);
237 fprintf(stderr, "W local tree:\n");
238 tree_node_dump(tree, tree->ltree_white, 0, thres);
243 static char *
244 tree_book_name(struct board *b)
246 static char buf[256];
247 if (b->handicap > 0) {
248 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
249 } else {
250 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
252 return buf;
255 static void
256 tree_node_save(FILE *f, struct tree_node *node, int thres)
258 bool save_children = node->u.playouts >= thres;
260 if (!save_children)
261 node->is_expanded = 0;
263 fputc(1, f);
264 fwrite(((void *) node) + offsetof(struct tree_node, depth),
265 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
266 1, f);
268 if (save_children) {
269 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
270 tree_node_save(f, ni, thres);
271 } else {
272 if (node->children)
273 node->is_expanded = 1;
276 fputc(0, f);
279 void
280 tree_save(struct tree *tree, struct board *b, int thres)
282 char *filename = tree_book_name(b);
283 FILE *f = fopen(filename, "wb");
284 if (!f) {
285 perror("fopen");
286 return;
288 tree_node_save(f, tree->root, thres);
289 fputc(0, f);
290 fclose(f);
294 void
295 tree_node_load(FILE *f, struct tree_node *node, int *num)
297 (*num)++;
299 fread(((void *) node) + offsetof(struct tree_node, depth),
300 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
301 1, f);
303 /* Keep values in sane scale, otherwise we start overflowing. */
304 #define MAX_PLAYOUTS 10000000
305 if (node->u.playouts > MAX_PLAYOUTS) {
306 node->u.playouts = MAX_PLAYOUTS;
308 if (node->amaf.playouts > MAX_PLAYOUTS) {
309 node->amaf.playouts = MAX_PLAYOUTS;
311 memcpy(&node->pu, &node->u, sizeof(node->u));
313 struct tree_node *ni = NULL, *ni_prev = NULL;
314 while (fgetc(f)) {
315 ni_prev = ni; ni = calloc2(1, sizeof(*ni));
316 if (!node->children)
317 node->children = ni;
318 else
319 ni_prev->sibling = ni;
320 ni->parent = node;
321 tree_node_load(f, ni, num);
325 void
326 tree_load(struct tree *tree, struct board *b)
328 char *filename = tree_book_name(b);
329 FILE *f = fopen(filename, "rb");
330 if (!f)
331 return;
333 fprintf(stderr, "Loading opening book %s...\n", filename);
335 int num = 0;
336 if (fgetc(f))
337 tree_node_load(f, tree->root, &num);
338 fprintf(stderr, "Loaded %d nodes.\n", num);
340 fclose(f);
344 /* Copy the subtree rooted at node: all nodes at or below depth
345 * or with at least threshold playouts. Only for fast_alloc.
346 * The code is destructive on src. The relative order of children of
347 * a given node is preserved (assumed by tree_get_node in particular).
348 * Returns the copy of node in the destination tree, or NULL
349 * if we could not copy it. */
350 static struct tree_node *
351 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
352 int threshold, int depth)
354 assert(dest->nodes && node);
355 struct tree_node *n2 = tree_alloc_node(dest, 1, true, NULL);
356 if (!n2)
357 return NULL;
358 *n2 = *node;
359 if (n2->depth > dest->max_depth)
360 dest->max_depth = n2->depth;
361 n2->children = NULL;
362 n2->is_expanded = false;
364 if (node->depth >= depth && node->u.playouts < threshold)
365 return n2;
366 /* For deep nodes with many playouts, we must copy all children,
367 * even those with zero playouts, because partially expanded
368 * nodes are not supported. Considering them as fully expanded
369 * would degrade the playing strength. The only exception is
370 * when dest becomes full, but this should never happen in practice
371 * if threshold is chosen to limit the number of nodes traversed. */
372 struct tree_node *ni = node->children;
373 if (!ni)
374 return n2;
375 struct tree_node **prev2 = &(n2->children);
376 while (ni) {
377 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
378 if (!ni2) break;
379 *prev2 = ni2;
380 prev2 = &(ni2->sibling);
381 ni2->parent = n2;
382 ni = ni->sibling;
384 if (!ni) {
385 n2->is_expanded = true;
386 } else {
387 n2->children = NULL; // avoid partially expanded nodes
389 return n2;
392 /* The following constants are used for garbage collection of nodes.
393 * A tree is considered large if the top node has >= 40K playouts.
394 * For such trees, we copy deep nodes only if they have enough
395 * playouts, with a gradually increasing threshold up to 40.
396 * These constants define how much time we're willing to spend
397 * scanning the source tree when promoting a move. The chosen values
398 * make worst case pruning in about 3s for 20 GB ram, and this
399 * is only for long thinking time (>1M playouts). For fast games the
400 * trees don't grow large. For small ram or fast game we copy the
401 * entire tree. These values do not degrade playing strength and are
402 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
403 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
404 * playing worse. */
405 #define LARGE_TREE_PLAYOUTS 40000LL
406 #define DEEP_PLAYOUTS_THRESHOLD 40
408 /* Garbage collect the tree early if the top node has < 5K playouts,
409 * to avoid having to do it later on a large subtree.
410 * This guarantees garbage collection in < 1s. */
411 #define SMALL_TREE_PLAYOUTS 5000
413 /* Free all the tree, keeping only the subtree rooted at node.
414 * Prune the subtree if necessary to fit in max_size bytes or
415 * to save time scanning the tree.
416 * Returns the moved node. Only for fast_alloc. */
417 struct tree_node *
418 tree_garbage_collect(struct tree *tree, unsigned long max_size, struct tree_node *node)
420 assert(tree->nodes && !node->parent && !node->sibling);
421 double start_time = time_now();
423 struct tree *temp_tree = tree_init(tree->board, tree->root_color, max_size, tree->ltree_aging, 0);
424 temp_tree->nodes_size = 0; // We do not want the dummy pass node
425 struct tree_node *temp_node;
427 /* Find the maximum depth at which we can copy all nodes. */
428 int max_nodes = 1;
429 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
430 max_nodes++;
431 unsigned long nodes_size = max_nodes * sizeof(*node);
432 int max_depth = node->depth;
433 while (nodes_size < max_size && max_nodes > 1) {
434 max_nodes--;
435 nodes_size += max_nodes * nodes_size;
436 max_depth++;
439 /* Copy all nodes for small trees. For large trees, copy all nodes
440 * with depth <= max_depth, and all nodes with enough playouts.
441 * Avoiding going too deep (except for nodes with many playouts) is mostly
442 * to save time scanning the source tree. It can take over 20s to traverse
443 * completely a large source tree (20 GB) even without copying because
444 * the traversal is not friendly at all with the memory cache. */
445 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
446 if (threshold < 0) threshold = 0;
447 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
448 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
449 assert(temp_node);
451 /* Now copy back to original tree. */
452 tree->nodes_size = 0;
453 tree->max_depth = 0;
454 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
456 if (DEBUGL(1)) {
457 double now = time_now();
458 static double prev_time;
459 if (!prev_time) prev_time = start_time;
460 fprintf(stderr,
461 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
462 " max_size %lu, pruned size %lu, playouts %d\n",
463 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
464 max_size, temp_tree->nodes_size, new_node->u.playouts);
465 prev_time = start_time;
467 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
468 fprintf(stderr, "temp tree overflow, increase max_tree_size %lu or MIN_FREE_MEM_PERCENT %llu\n",
469 tree->max_tree_size, MIN_FREE_MEM_PERCENT);
470 } else {
471 assert(tree->nodes_size == temp_tree->nodes_size);
472 assert(tree->max_depth == temp_tree->max_depth);
474 tree_done(temp_tree);
475 return new_node;
479 /* Get a node of given coordinate from within parent, possibly creating it
480 * if necessary - in a very raw form (no .d, priors, ...). */
481 /* FIXME: Adjust for board symmetry. */
482 struct tree_node *
483 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
485 if (!parent->children || parent->children->coord >= c) {
486 /* Special case: Insertion at the beginning. */
487 if (parent->children && parent->children->coord == c)
488 return parent->children;
489 if (!create)
490 return NULL;
492 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
493 nn->parent = parent; nn->sibling = parent->children;
494 parent->children = nn;
495 return nn;
498 /* No candidate at the beginning, look through all the children. */
500 struct tree_node *ni;
501 for (ni = parent->children; ni->sibling; ni = ni->sibling)
502 if (ni->sibling->coord >= c)
503 break;
505 if (ni->sibling && ni->sibling->coord == c)
506 return ni->sibling;
507 assert(ni->coord < c);
508 if (!create)
509 return NULL;
511 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
512 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
513 return nn;
516 /* Get local tree node corresponding to given node, given local node child
517 * iterator @lni (which points either at the corresponding node, or at the
518 * nearest local tree node after @ni). */
519 struct tree_node *
520 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
522 /* Now set up lnode, which is the actual local node
523 * corresponding to ni - either lni if it is an
524 * exact match and ni is not tenuki, <pass> local
525 * node if ni is tenuki, or NULL if there is no
526 * corresponding node available. */
528 if (is_pass(ni->coord)) {
529 /* Also, for sanity reasons we never use local
530 * tree for passes. (Maybe we could, but it's
531 * too hard to think about.) */
532 return NULL;
535 if (lni->coord == ni->coord) {
536 /* We don't consider tenuki a sequence play
537 * that we have in local tree even though
538 * ni->d is too high; this can happen if this
539 * occured in different board topology. */
540 return lni;
543 if (ni->d >= tenuki_d) {
544 /* Tenuki, pick a pass lsibling if available. */
545 assert(lni->parent && lni->parent->children);
546 if (is_pass(lni->parent->children->coord)) {
547 return lni->parent->children;
548 } else {
549 return NULL;
553 /* No corresponding local node, lnode stays NULL. */
554 return NULL;
558 /* Tree symmetry: When possible, we will localize the tree to a single part
559 * of the board in tree_expand_node() and possibly flip along symmetry axes
560 * to another part of the board in tree_promote_at(). We follow b->symmetry
561 * guidelines here. */
564 /* This function must be thread safe, given that board b is only modified by the calling thread. */
565 void
566 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
568 /* Get a Common Fate Graph distance map from parent node. */
569 int distances[board_size2(b)];
570 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
571 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
572 } else {
573 // Pass or resign - everything is too far.
574 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
577 /* Get a map of prior values to initialize the new nodes with. */
578 struct prior_map map = {
579 .b = b,
580 .to_play = color,
581 .parity = tree_parity(t, parity),
582 .distances = distances,
584 // Include pass in the prior map.
585 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
586 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
587 memset(map_prior, 0, sizeof(map_prior));
588 memset(map_consider, 0, sizeof(map_consider));
589 map.consider[pass] = true;
590 foreach_free_point(b) {
591 assert(board_at(b, c) == S_NONE);
592 if (!board_is_valid_play(b, color, c))
593 continue;
594 map.consider[c] = true;
595 } foreach_free_point_end;
596 uct_prior(u, node, &map);
598 /* Now, create the nodes. */
599 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
600 /* In fast_alloc mode we might temporarily run out of nodes but
601 * this should be rare if MIN_FREE_MEM_PERCENT is set correctly. */
602 if (!ni) {
603 node->is_expanded = false;
604 return;
606 struct tree_node *first_child = ni;
607 ni->parent = node;
608 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
610 /* The loop considers only the symmetry playground. */
611 if (UDEBUGL(6)) {
612 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
613 coord2sstr(node->coord, b),
614 b->symmetry.x1, b->symmetry.y1,
615 b->symmetry.x2, b->symmetry.y2,
616 b->symmetry.type, b->symmetry.d);
618 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
619 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
620 if (b->symmetry.d) {
621 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
622 if (x > j) {
623 if (UDEBUGL(7))
624 fprintf(stderr, "drop %d,%d\n", i, j);
625 continue;
629 coord_t c = coord_xy(t->board, i, j);
630 if (!map.consider[c]) // Filter out invalid moves
631 continue;
632 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
634 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
635 if (!nj) {
636 node->is_expanded = false;
637 return;
639 nj->parent = node; ni->sibling = nj; ni = nj;
641 ni->prior = map.prior[c];
642 ni->d = distances[c];
645 node->children = first_child; // must be done at the end to avoid race
649 static coord_t
650 flip_coord(struct board *b, coord_t c,
651 bool flip_horiz, bool flip_vert, int flip_diag)
653 int x = coord_x(c, b), y = coord_y(c, b);
654 if (flip_diag) {
655 int z = x; x = y; y = z;
657 if (flip_horiz) {
658 x = board_size(b) - 1 - x;
660 if (flip_vert) {
661 y = board_size(b) - 1 - y;
663 return coord_xy(b, x, y);
666 static void
667 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
668 bool flip_horiz, bool flip_vert, int flip_diag)
670 if (!is_pass(node->coord))
671 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
673 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
674 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
677 static void
678 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
680 if (is_pass(c))
681 return;
683 struct board_symmetry *s = &tree->root_symmetry;
684 int cx = coord_x(c, b), cy = coord_y(c, b);
686 /* playground X->h->v->d normalization
687 * :::.. .d...
688 * .::.. v....
689 * ..:.. .....
690 * ..... h...X
691 * ..... ..... */
692 bool flip_horiz = cx < s->x1 || cx > s->x2;
693 bool flip_vert = cy < s->y1 || cy > s->y2;
695 bool flip_diag = 0;
696 if (s->d) {
697 bool dir = (s->type == SYM_DIAG_DOWN);
698 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
699 if (flip_vert ? x < cy : x > cy) {
700 flip_diag = 1;
704 if (DEBUGL(4)) {
705 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
706 coord2sstr(c, b),
707 cx, cy, s->x1, s->y1, s->x2, s->y2,
708 flip_horiz, flip_vert, flip_diag,
709 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
710 s->type, s->d, b->symmetry.type, b->symmetry.d);
712 if (flip_horiz || flip_vert || flip_diag)
713 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
717 static void
718 tree_unlink_node(struct tree_node *node)
720 struct tree_node *ni = node->parent;
721 if (ni->children == node) {
722 ni->children = node->sibling;
723 } else {
724 ni = ni->children;
725 while (ni->sibling != node)
726 ni = ni->sibling;
727 ni->sibling = node->sibling;
729 node->sibling = NULL;
730 node->parent = NULL;
733 /* Reduce weight of statistics on promotion. Remove nodes that
734 * get reduced to zero playouts; returns next node to consider
735 * in the children list (@node may get deleted). */
736 static struct tree_node *
737 tree_age_node(struct tree *tree, struct tree_node *node)
739 node->u.playouts /= tree->ltree_aging;
740 if (node->parent && !node->u.playouts) {
741 struct tree_node *sibling = node->sibling;
742 /* Delete node, no playouts. */
743 tree_unlink_node(node);
744 tree_done_node(tree, node);
745 return sibling;
748 struct tree_node *ni = node->children;
749 while (ni) ni = tree_age_node(tree, ni);
750 return node->sibling;
753 /* Promotes the given node as the root of the tree. In the fast_alloc
754 * mode, the node may be moved and some of its subtree may be pruned. */
755 void
756 tree_promote_node(struct tree *tree, struct tree_node **node)
758 assert((*node)->parent == tree->root);
759 tree_unlink_node(*node);
760 if (!tree->nodes) {
761 /* Freeing the rest of the tree can take several seconds on large
762 * trees, so we must do it asynchronously: */
763 tree_done_node_detached(tree, tree->root);
764 } else {
765 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
766 unsigned long min_free_size = (MIN_FREE_MEM_PERCENT * tree->max_tree_size) / 100;
767 if (tree->nodes_size >= tree->max_tree_size - min_free_size
768 || (tree->nodes_size >= min_free_size && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
769 *node = tree_garbage_collect(tree, min_free_size, *node);
771 tree->root = *node;
772 tree->root_color = stone_other(tree->root_color);
774 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
775 /* See tree.score description for explanation on why don't we zero
776 * score on node promotion. */
777 // tree->score.playouts = 0;
779 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
780 * tree->max_depth is correct. Otherwise we could traverse the tree
781 * to recompute max_depth but it's not worth it: it's just for debugging
782 * and soon the tree will grow and max_depth will become correct again. */
784 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
785 tree_age_node(tree, tree->ltree_black);
786 tree_age_node(tree, tree->ltree_white);
790 bool
791 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
793 tree_fix_symmetry(tree, b, c);
795 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
796 if (ni->coord == c) {
797 tree_promote_node(tree, &ni);
798 return true;
801 return false;