fast_irandom(): Fix for largest stabs
[pachi.git] / uct / tree.c
blob6fb36f7d0e48747278b073fe2f760f03fd6d59f2
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_point(b) {
590 if (board_at(b, c) != S_NONE)
591 continue;
592 if (!board_is_valid_play(b, color, c))
593 continue;
594 map.consider[c] = true;
595 } foreach_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;