fbook: Properly flip not just sequences, but also the final coordinate
[pachi/derm.git] / uct / tree.c
blobac25fcfd2be0e417d6e771e3136a94de106b5d31
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,
80 unsigned long max_pruned_size, unsigned long pruning_threshold, float ltree_aging, int hbits)
82 struct tree *t = calloc2(1, sizeof(*t));
83 t->board = board;
84 t->max_tree_size = max_tree_size;
85 t->max_pruned_size = max_pruned_size;
86 t->pruning_threshold = pruning_threshold;
87 if (max_tree_size != 0) {
88 t->nodes = malloc2(max_tree_size);
89 /* The nodes buffer doesn't need initialization. This is currently
90 * done by tree_init_node to spread the load. Doing a memset for the
91 * entire buffer here would be too slow for large trees (>10 GB). */
93 /* The root PASS move is only virtual, we never play it. */
94 t->root = tree_init_node(t, pass, 0, t->nodes);
95 t->root_symmetry = board->symmetry;
96 t->root_color = stone_other(color); // to research black moves, root will be white
98 t->ltree_black = tree_init_node(t, pass, 0, false);
99 t->ltree_white = tree_init_node(t, pass, 0, false);
100 t->ltree_aging = ltree_aging;
102 t->hbits = hbits;
103 if (hbits) t->htable = uct_htable_alloc(hbits);
104 return t;
108 /* This function may be called by multiple threads in parallel on the
109 * same tree, but not on node n. n may be detached from the tree but
110 * must have been created in this tree originally.
111 * It returns the remaining size of the tree after n has been freed. */
112 static unsigned long
113 tree_done_node(struct tree *t, struct tree_node *n)
115 struct tree_node *ni = n->children;
116 while (ni) {
117 struct tree_node *nj = ni->sibling;
118 tree_done_node(t, ni);
119 ni = nj;
121 free(n);
122 unsigned long old_size = __sync_fetch_and_sub(&t->nodes_size, sizeof(*n));
123 return old_size - sizeof(*n);
126 struct subtree_ctx {
127 struct tree *t;
128 struct tree_node *n;
131 /* Worker thread for tree_done_node_detached(). Only for fast_alloc=false. */
132 static void *
133 tree_done_node_worker(void *ctx_)
135 struct subtree_ctx *ctx = ctx_;
136 char *str = coord2str(ctx->n->coord, ctx->t->board);
138 unsigned long tree_size = tree_done_node(ctx->t, ctx->n);
139 if (!tree_size)
140 free(ctx->t);
141 if (DEBUGL(2))
142 fprintf(stderr, "done freeing node at %s, tree size %lu\n", str, tree_size);
143 free(str);
144 free(ctx);
145 return NULL;
148 /* Asynchronously free the subtree of nodes rooted at n. If the tree becomes
149 * empty free the tree also. Only for fast_alloc=false. */
150 static void
151 tree_done_node_detached(struct tree *t, struct tree_node *n)
153 if (n->u.playouts < 1000) { // no thread for small tree
154 if (!tree_done_node(t, n))
155 free(t);
156 return;
158 pthread_attr_t attr;
159 pthread_attr_init(&attr);
160 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
162 pthread_t thread;
163 struct subtree_ctx *ctx = malloc2(sizeof(struct subtree_ctx));
164 ctx->t = t;
165 ctx->n = n;
166 pthread_create(&thread, &attr, tree_done_node_worker, ctx);
167 pthread_attr_destroy(&attr);
170 void
171 tree_done(struct tree *t)
173 tree_done_node(t, t->ltree_black);
174 tree_done_node(t, t->ltree_white);
176 if (t->htable) free(t->htable);
177 if (t->nodes) {
178 free(t->nodes);
179 free(t);
180 } else if (!tree_done_node(t, t->root)) {
181 free(t);
182 /* A tree_done_node_worker might still be running on this tree but
183 * it will free the tree later. It is also freeing nodes faster than
184 * we will create new ones. */
189 static void
190 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
192 for (int i = 0; i < l; i++) fputc(' ', stderr);
193 int children = 0;
194 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
195 children++;
196 /* We use 1 as parity, since for all nodes we want to know the
197 * win probability of _us_, not the node color. */
198 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
199 coord2sstr(node->coord, tree->board),
200 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
201 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
202 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
203 node->hints, children, node->hash);
205 /* Print nodes sorted by #playouts. */
207 struct tree_node *nbox[1000]; int nboxl = 0;
208 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
209 if (ni->u.playouts > thres)
210 nbox[nboxl++] = ni;
212 while (true) {
213 int best = -1;
214 for (int i = 0; i < nboxl; i++)
215 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
216 best = i;
217 if (best < 0)
218 break;
219 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
220 nbox[best] = NULL;
224 void
225 tree_dump(struct tree *tree, int thres)
227 if (thres && tree->root->u.playouts / thres > 100) {
228 /* Be a bit sensible about this; the opening tbook can create
229 * huge dumps at first. */
230 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
232 fprintf(stderr, "(UCT tree; root %s; extra komi %f; max depth %d)\n",
233 stone2str(tree->root_color), tree->extra_komi,
234 tree->max_depth - tree->root->depth);
235 tree_node_dump(tree, tree->root, 0, thres);
237 if (DEBUGL(3) && tree->ltree_black) {
238 fprintf(stderr, "B local tree:\n");
239 tree_node_dump(tree, tree->ltree_black, 0, thres);
240 fprintf(stderr, "W local tree:\n");
241 tree_node_dump(tree, tree->ltree_white, 0, thres);
246 static char *
247 tree_book_name(struct board *b)
249 static char buf[256];
250 if (b->handicap > 0) {
251 sprintf(buf, "ucttbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
252 } else {
253 sprintf(buf, "ucttbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
255 return buf;
258 static void
259 tree_node_save(FILE *f, struct tree_node *node, int thres)
261 bool save_children = node->u.playouts >= thres;
263 if (!save_children)
264 node->is_expanded = 0;
266 fputc(1, f);
267 fwrite(((void *) node) + offsetof(struct tree_node, depth),
268 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
269 1, f);
271 if (save_children) {
272 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
273 tree_node_save(f, ni, thres);
274 } else {
275 if (node->children)
276 node->is_expanded = 1;
279 fputc(0, f);
282 void
283 tree_save(struct tree *tree, struct board *b, int thres)
285 char *filename = tree_book_name(b);
286 FILE *f = fopen(filename, "wb");
287 if (!f) {
288 perror("fopen");
289 return;
291 tree_node_save(f, tree->root, thres);
292 fputc(0, f);
293 fclose(f);
297 void
298 tree_node_load(FILE *f, struct tree_node *node, int *num)
300 (*num)++;
302 fread(((void *) node) + offsetof(struct tree_node, depth),
303 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
304 1, f);
306 /* Keep values in sane scale, otherwise we start overflowing. */
307 #define MAX_PLAYOUTS 10000000
308 if (node->u.playouts > MAX_PLAYOUTS) {
309 node->u.playouts = MAX_PLAYOUTS;
311 if (node->amaf.playouts > MAX_PLAYOUTS) {
312 node->amaf.playouts = MAX_PLAYOUTS;
314 memcpy(&node->pu, &node->u, sizeof(node->u));
316 struct tree_node *ni = NULL, *ni_prev = NULL;
317 while (fgetc(f)) {
318 ni_prev = ni; ni = calloc2(1, sizeof(*ni));
319 if (!node->children)
320 node->children = ni;
321 else
322 ni_prev->sibling = ni;
323 ni->parent = node;
324 tree_node_load(f, ni, num);
328 void
329 tree_load(struct tree *tree, struct board *b)
331 char *filename = tree_book_name(b);
332 FILE *f = fopen(filename, "rb");
333 if (!f)
334 return;
336 fprintf(stderr, "Loading opening tbook %s...\n", filename);
338 int num = 0;
339 if (fgetc(f))
340 tree_node_load(f, tree->root, &num);
341 fprintf(stderr, "Loaded %d nodes.\n", num);
343 fclose(f);
347 /* Copy the subtree rooted at node: all nodes at or below depth
348 * or with at least threshold playouts. Only for fast_alloc.
349 * The code is destructive on src. The relative order of children of
350 * a given node is preserved (assumed by tree_get_node in particular).
351 * Returns the copy of node in the destination tree, or NULL
352 * if we could not copy it. */
353 static struct tree_node *
354 tree_prune(struct tree *dest, struct tree *src, struct tree_node *node,
355 int threshold, int depth)
357 assert(dest->nodes && node);
358 struct tree_node *n2 = tree_alloc_node(dest, 1, true, NULL);
359 if (!n2)
360 return NULL;
361 *n2 = *node;
362 if (n2->depth > dest->max_depth)
363 dest->max_depth = n2->depth;
364 n2->children = NULL;
365 n2->is_expanded = false;
367 if (node->depth >= depth && node->u.playouts < threshold)
368 return n2;
369 /* For deep nodes with many playouts, we must copy all children,
370 * even those with zero playouts, because partially expanded
371 * nodes are not supported. Considering them as fully expanded
372 * would degrade the playing strength. The only exception is
373 * when dest becomes full, but this should never happen in practice
374 * if threshold is chosen to limit the number of nodes traversed. */
375 struct tree_node *ni = node->children;
376 if (!ni)
377 return n2;
378 struct tree_node **prev2 = &(n2->children);
379 while (ni) {
380 struct tree_node *ni2 = tree_prune(dest, src, ni, threshold, depth);
381 if (!ni2) break;
382 *prev2 = ni2;
383 prev2 = &(ni2->sibling);
384 ni2->parent = n2;
385 ni = ni->sibling;
387 if (!ni) {
388 n2->is_expanded = true;
389 } else {
390 n2->children = NULL; // avoid partially expanded nodes
392 return n2;
395 /* The following constants are used for garbage collection of nodes.
396 * A tree is considered large if the top node has >= 40K playouts.
397 * For such trees, we copy deep nodes only if they have enough
398 * playouts, with a gradually increasing threshold up to 40.
399 * These constants define how much time we're willing to spend
400 * scanning the source tree when promoting a move. The chosen values
401 * make worst case pruning in about 3s for 20 GB ram, and this
402 * is only for long thinking time (>1M playouts). For fast games the
403 * trees don't grow large. For small ram or fast game we copy the
404 * entire tree. These values do not degrade playing strength and are
405 * necessary to avoid losing on time; increasing DEEP_PLAYOUTS_THRESHOLD
406 * or decreasing LARGE_TREE_PLAYOUTS will make the program faster but
407 * playing worse. */
408 #define LARGE_TREE_PLAYOUTS 40000LL
409 #define DEEP_PLAYOUTS_THRESHOLD 40
411 /* Garbage collect the tree early if the top node has < 5K playouts,
412 * to avoid having to do it later on a large subtree.
413 * This guarantees garbage collection in < 1s. */
414 #define SMALL_TREE_PLAYOUTS 5000
416 /* Free all the tree, keeping only the subtree rooted at node.
417 * Prune the subtree if necessary to fit in memory or
418 * to save time scanning the tree.
419 * Returns the moved node. Only for fast_alloc. */
420 struct tree_node *
421 tree_garbage_collect(struct tree *tree, struct tree_node *node)
423 assert(tree->nodes && !node->parent && !node->sibling);
424 double start_time = time_now();
425 unsigned long orig_size = tree->nodes_size;
427 struct tree *temp_tree = tree_init(tree->board, tree->root_color,
428 tree->max_pruned_size, 0, 0, tree->ltree_aging, 0);
429 temp_tree->nodes_size = 0; // We do not want the dummy pass node
430 struct tree_node *temp_node;
432 /* Find the maximum depth at which we can copy all nodes. */
433 int max_nodes = 1;
434 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
435 max_nodes++;
436 unsigned long nodes_size = max_nodes * sizeof(*node);
437 int max_depth = node->depth;
438 while (nodes_size < tree->max_pruned_size && max_nodes > 1) {
439 max_nodes--;
440 nodes_size += max_nodes * nodes_size;
441 max_depth++;
444 /* Copy all nodes for small trees. For large trees, copy all nodes
445 * with depth <= max_depth, and all nodes with enough playouts.
446 * Avoiding going too deep (except for nodes with many playouts) is mostly
447 * to save time scanning the source tree. It can take over 20s to traverse
448 * completely a large source tree (20 GB) even without copying because
449 * the traversal is not friendly at all with the memory cache. */
450 int threshold = (node->u.playouts - LARGE_TREE_PLAYOUTS) * DEEP_PLAYOUTS_THRESHOLD / LARGE_TREE_PLAYOUTS;
451 if (threshold < 0) threshold = 0;
452 if (threshold > DEEP_PLAYOUTS_THRESHOLD) threshold = DEEP_PLAYOUTS_THRESHOLD;
453 temp_node = tree_prune(temp_tree, tree, node, threshold, max_depth);
454 assert(temp_node);
456 /* Now copy back to original tree. */
457 tree->nodes_size = 0;
458 tree->max_depth = 0;
459 struct tree_node *new_node = tree_prune(tree, temp_tree, temp_node, 0, temp_tree->max_depth);
461 if (DEBUGL(1)) {
462 double now = time_now();
463 static double prev_time;
464 if (!prev_time) prev_time = start_time;
465 fprintf(stderr,
466 "tree pruned in %0.6g s, prev %0.3g s ago, dest depth %d wanted %d,"
467 " size %lu->%lu/%lu, playouts %d\n",
468 now - start_time, start_time - prev_time, temp_tree->max_depth, max_depth,
469 orig_size, temp_tree->nodes_size, tree->max_pruned_size, new_node->u.playouts);
470 prev_time = start_time;
472 if (temp_tree->nodes_size >= temp_tree->max_tree_size) {
473 fprintf(stderr, "temp tree overflow, max_tree_size %lu, pruning_threshold %lu\n",
474 tree->max_tree_size, tree->pruning_threshold);
475 /* This is not a serious problem, we will simply recompute the discarded nodes
476 * at the next move if necessary. This is better than frequently wasting memory. */
477 } else {
478 assert(tree->nodes_size == temp_tree->nodes_size);
479 assert(tree->max_depth == temp_tree->max_depth);
481 tree_done(temp_tree);
482 return new_node;
486 /* Get a node of given coordinate from within parent, possibly creating it
487 * if necessary - in a very raw form (no .d, priors, ...). */
488 /* FIXME: Adjust for board symmetry. */
489 struct tree_node *
490 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
492 if (!parent->children || parent->children->coord >= c) {
493 /* Special case: Insertion at the beginning. */
494 if (parent->children && parent->children->coord == c)
495 return parent->children;
496 if (!create)
497 return NULL;
499 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
500 nn->parent = parent; nn->sibling = parent->children;
501 parent->children = nn;
502 return nn;
505 /* No candidate at the beginning, look through all the children. */
507 struct tree_node *ni;
508 for (ni = parent->children; ni->sibling; ni = ni->sibling)
509 if (ni->sibling->coord >= c)
510 break;
512 if (ni->sibling && ni->sibling->coord == c)
513 return ni->sibling;
514 assert(ni->coord < c);
515 if (!create)
516 return NULL;
518 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1, false);
519 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
520 return nn;
523 /* Get local tree node corresponding to given node, given local node child
524 * iterator @lni (which points either at the corresponding node, or at the
525 * nearest local tree node after @ni). */
526 struct tree_node *
527 tree_lnode_for_node(struct tree *tree, struct tree_node *ni, struct tree_node *lni, int tenuki_d)
529 /* Now set up lnode, which is the actual local node
530 * corresponding to ni - either lni if it is an
531 * exact match and ni is not tenuki, <pass> local
532 * node if ni is tenuki, or NULL if there is no
533 * corresponding node available. */
535 if (is_pass(ni->coord)) {
536 /* Also, for sanity reasons we never use local
537 * tree for passes. (Maybe we could, but it's
538 * too hard to think about.) */
539 return NULL;
542 if (lni->coord == ni->coord) {
543 /* We don't consider tenuki a sequence play
544 * that we have in local tree even though
545 * ni->d is too high; this can happen if this
546 * occured in different board topology. */
547 return lni;
550 if (ni->d >= tenuki_d) {
551 /* Tenuki, pick a pass lsibling if available. */
552 assert(lni->parent && lni->parent->children);
553 if (is_pass(lni->parent->children->coord)) {
554 return lni->parent->children;
555 } else {
556 return NULL;
560 /* No corresponding local node, lnode stays NULL. */
561 return NULL;
565 /* Tree symmetry: When possible, we will localize the tree to a single part
566 * of the board in tree_expand_node() and possibly flip along symmetry axes
567 * to another part of the board in tree_promote_at(). We follow b->symmetry
568 * guidelines here. */
571 /* This function must be thread safe, given that board b is only modified by the calling thread. */
572 void
573 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
575 /* Get a Common Fate Graph distance map from parent node. */
576 int distances[board_size2(b)];
577 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
578 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
579 } else {
580 // Pass or resign - everything is too far.
581 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
584 /* Get a map of prior values to initialize the new nodes with. */
585 struct prior_map map = {
586 .b = b,
587 .to_play = color,
588 .parity = tree_parity(t, parity),
589 .distances = distances,
591 // Include pass in the prior map.
592 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
593 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
594 memset(map_prior, 0, sizeof(map_prior));
595 memset(map_consider, 0, sizeof(map_consider));
596 map.consider[pass] = true;
597 foreach_free_point(b) {
598 assert(board_at(b, c) == S_NONE);
599 if (!board_is_valid_play(b, color, c))
600 continue;
601 map.consider[c] = true;
602 } foreach_free_point_end;
603 uct_prior(u, node, &map);
605 /* Now, create the nodes. */
606 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1, t->nodes);
607 /* In fast_alloc mode we might temporarily run out of nodes but this should be rare. */
608 if (!ni) {
609 node->is_expanded = false;
610 return;
612 struct tree_node *first_child = ni;
613 ni->parent = node;
614 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
616 /* The loop considers only the symmetry playground. */
617 if (UDEBUGL(6)) {
618 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
619 coord2sstr(node->coord, b),
620 b->symmetry.x1, b->symmetry.y1,
621 b->symmetry.x2, b->symmetry.y2,
622 b->symmetry.type, b->symmetry.d);
624 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
625 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
626 if (b->symmetry.d) {
627 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
628 if (x > j) {
629 if (UDEBUGL(7))
630 fprintf(stderr, "drop %d,%d\n", i, j);
631 continue;
635 coord_t c = coord_xy(t->board, i, j);
636 if (!map.consider[c]) // Filter out invalid moves
637 continue;
638 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
640 struct tree_node *nj = tree_init_node(t, c, node->depth + 1, t->nodes);
641 if (!nj) {
642 node->is_expanded = false;
643 return;
645 nj->parent = node; ni->sibling = nj; ni = nj;
647 ni->prior = map.prior[c];
648 ni->d = distances[c];
651 node->children = first_child; // must be done at the end to avoid race
655 static coord_t
656 flip_coord(struct board *b, coord_t c,
657 bool flip_horiz, bool flip_vert, int flip_diag)
659 int x = coord_x(c, b), y = coord_y(c, b);
660 if (flip_diag) {
661 int z = x; x = y; y = z;
663 if (flip_horiz) {
664 x = board_size(b) - 1 - x;
666 if (flip_vert) {
667 y = board_size(b) - 1 - y;
669 return coord_xy(b, x, y);
672 static void
673 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
674 bool flip_horiz, bool flip_vert, int flip_diag)
676 if (!is_pass(node->coord))
677 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
679 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
680 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
683 static void
684 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
686 if (is_pass(c))
687 return;
689 struct board_symmetry *s = &tree->root_symmetry;
690 int cx = coord_x(c, b), cy = coord_y(c, b);
692 /* playground X->h->v->d normalization
693 * :::.. .d...
694 * .::.. v....
695 * ..:.. .....
696 * ..... h...X
697 * ..... ..... */
698 bool flip_horiz = cx < s->x1 || cx > s->x2;
699 bool flip_vert = cy < s->y1 || cy > s->y2;
701 bool flip_diag = 0;
702 if (s->d) {
703 bool dir = (s->type == SYM_DIAG_DOWN);
704 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
705 if (flip_vert ? x < cy : x > cy) {
706 flip_diag = 1;
710 if (DEBUGL(4)) {
711 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
712 coord2sstr(c, b),
713 cx, cy, s->x1, s->y1, s->x2, s->y2,
714 flip_horiz, flip_vert, flip_diag,
715 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
716 s->type, s->d, b->symmetry.type, b->symmetry.d);
718 if (flip_horiz || flip_vert || flip_diag)
719 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
723 static void
724 tree_unlink_node(struct tree_node *node)
726 struct tree_node *ni = node->parent;
727 if (ni->children == node) {
728 ni->children = node->sibling;
729 } else {
730 ni = ni->children;
731 while (ni->sibling != node)
732 ni = ni->sibling;
733 ni->sibling = node->sibling;
735 node->sibling = NULL;
736 node->parent = NULL;
739 /* Reduce weight of statistics on promotion. Remove nodes that
740 * get reduced to zero playouts; returns next node to consider
741 * in the children list (@node may get deleted). */
742 static struct tree_node *
743 tree_age_node(struct tree *tree, struct tree_node *node)
745 node->u.playouts /= tree->ltree_aging;
746 if (node->parent && !node->u.playouts) {
747 struct tree_node *sibling = node->sibling;
748 /* Delete node, no playouts. */
749 tree_unlink_node(node);
750 tree_done_node(tree, node);
751 return sibling;
754 struct tree_node *ni = node->children;
755 while (ni) ni = tree_age_node(tree, ni);
756 return node->sibling;
759 /* Promotes the given node as the root of the tree. In the fast_alloc
760 * mode, the node may be moved and some of its subtree may be pruned. */
761 void
762 tree_promote_node(struct tree *tree, struct tree_node **node)
764 assert((*node)->parent == tree->root);
765 tree_unlink_node(*node);
766 if (!tree->nodes) {
767 /* Freeing the rest of the tree can take several seconds on large
768 * trees, so we must do it asynchronously: */
769 tree_done_node_detached(tree, tree->root);
770 } else {
771 /* Garbage collect if we run out of memory, or it is cheap to do so now: */
772 if (tree->nodes_size >= tree->pruning_threshold
773 || (tree->nodes_size >= tree->max_tree_size / 10 && (*node)->u.playouts < SMALL_TREE_PLAYOUTS))
774 *node = tree_garbage_collect(tree, *node);
776 tree->root = *node;
777 tree->root_color = stone_other(tree->root_color);
779 board_symmetry_update(tree->board, &tree->root_symmetry, (*node)->coord);
780 /* See tree.score description for explanation on why don't we zero
781 * score on node promotion. */
782 // tree->score.playouts = 0;
784 /* If the tree deepest node was under node, or if we called tree_garbage_collect,
785 * tree->max_depth is correct. Otherwise we could traverse the tree
786 * to recompute max_depth but it's not worth it: it's just for debugging
787 * and soon the tree will grow and max_depth will become correct again. */
789 if (tree->ltree_aging != 1.0f) { // XXX: != should work here even with the float
790 tree_age_node(tree, tree->ltree_black);
791 tree_age_node(tree, tree->ltree_white);
795 bool
796 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
798 tree_fix_symmetry(tree, b, c);
800 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
801 if (ni->coord == c) {
802 tree_promote_node(tree, &ni);
803 return true;
806 return false;