uct_progress_json(): Condense territstatus data (per Jonathan's request)
[pachi.git] / uct / walk.c
blob7f2f006b31ffe21cff6bc3a4cf19139b91409b53
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #define DEBUG
11 #include "debug.h"
12 #include "board.h"
13 #include "move.h"
14 #include "playout.h"
15 #include "probdist.h"
16 #include "random.h"
17 #include "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
20 #include "uct/tree.h"
21 #include "uct/uct.h"
22 #include "uct/walk.h"
24 #define DESCENT_DLEN 512
27 void
28 uct_progress_text(struct uct *u, struct tree *t, enum stone color, int playouts, bool final)
30 if (!UDEBUGL(0))
31 return;
33 /* Best move */
34 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
35 if (!best) {
36 fprintf(stderr, "... No moves left\n");
37 return;
39 fprintf(stderr, "[%d] ", playouts);
40 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
42 /* Dynamic komi */
43 if (t->use_extra_komi)
44 fprintf(stderr, "komi %.1f ", t->extra_komi);
46 /* Best sequence */
47 fprintf(stderr, "| seq ");
48 for (int depth = 0; depth < 4; depth++) {
49 if (best && best->u.playouts >= 25) {
50 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
51 best = u->policy->choose(u->policy, best, t->board, color, resign);
52 } else {
53 fprintf(stderr, " ");
57 /* Best candidates */
58 fprintf(stderr, "| can ");
59 int cans = 4;
60 struct tree_node *can[cans];
61 memset(can, 0, sizeof(can));
62 best = t->root->children;
63 while (best) {
64 int c = 0;
65 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
66 for (int d = 0; d < c; d++) can[d] = can[d + 1];
67 if (c > 0) can[c - 1] = best;
68 best = best->sibling;
70 while (--cans >= 0) {
71 if (can[cans]) {
72 fprintf(stderr, "%3s(%.3f) ",
73 coord2sstr(can[cans]->coord, t->board),
74 tree_node_get_value(t, 1, can[cans]->u.value));
75 } else {
76 fprintf(stderr, " ");
80 fprintf(stderr, "\n");
83 void
84 uct_progress_json(struct uct *u, struct tree *t, enum stone color, int playouts, bool final, bool big)
86 /* Prefix indicating JSON line. */
87 fprintf(stderr, "{\"%s\": {", final ? "move" : "frame");
89 /* Plaout count */
90 fprintf(stderr, "\"playouts\": %d", playouts);
92 /* Dynamic komi */
93 if (t->use_extra_komi)
94 fprintf(stderr, ", \"extrakomi\": %.1f", t->extra_komi);
96 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
97 if (best) {
98 /* Best move */
99 fprintf(stderr, ", \"best\": {\"%s\": %f}",
100 coord2sstr(best->coord, t->board),
101 tree_node_get_value(t, 1, best->u.value));
103 /* Best sequence */
104 fprintf(stderr, ", \"seq\": [");
105 for (int depth = 0; depth < 4; depth++) {
106 if (!best || best->u.playouts < 25) break;
107 fprintf(stderr, "%s\"%s\"", depth > 0 ? "," : "",
108 coord2sstr(best->coord, t->board));
109 best = u->policy->choose(u->policy, best, t->board, color, resign);
111 fprintf(stderr, "]");
114 /* Best candidates */
115 int cans = 4;
116 struct tree_node *can[cans];
117 memset(can, 0, sizeof(can));
118 best = t->root->children;
119 while (best) {
120 int c = 0;
121 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
122 for (int d = 0; d < c; d++) can[d] = can[d + 1];
123 if (c > 0) can[c - 1] = best;
124 best = best->sibling;
126 fprintf(stderr, ", \"can\": [");
127 while (--cans >= 0) {
128 if (!can[cans]) break;
129 fprintf(stderr, "%s{\"%s\":%.3f}",
130 cans < 3 ? "," : "",
131 coord2sstr(can[cans]->coord, t->board),
132 tree_node_get_value(t, 1, can[cans]->u.value));
134 fprintf(stderr, "]");
136 if (big) {
137 /* Ownership statistics. {"b":val,"w":val,"d":val}
138 * where each val is in range [0,1] describes likelihood
139 * of this point becoming black, white and dame.
140 * If dame rate would be 0, only black rate is sent and
141 * white rate can be computed as 1-blackrate. */
142 fprintf(stderr, ", \"territstatus\": [");
143 int f = 0;
144 foreach_point(t->board) {
145 if (board_at(t->board, c) != S_NONE) continue;
146 int rate = u->ownermap.map[c][S_BLACK] * 1000 / u->ownermap.playouts;
147 int drate = u->ownermap.map[c][S_NONE] * 1000 / u->ownermap.playouts;
148 fprintf(stderr, "%s[%d,%d]", f++ > 0 ? "," : "", rate, drate);
149 } foreach_point_end;
150 fprintf(stderr, "]");
152 /* Chain status statistics. Each chain is identified
153 * by some stone within, and bound to a value in range
154 * [0,1] describing likelihood of survival. */
155 fprintf(stderr, ", \"chainstatus\": [");
156 f = 0;
157 foreach_point(t->board) {
158 group_t g = group_at(t->board, c);
159 if (!g || groupnext_at(t->board, c)) continue;
160 /* Last stone in some group. */
161 fprintf(stderr, "%s{\"%s\":%.3f}",
162 f++ > 0 ? "," : "",
163 coord2sstr(c, t->board),
164 (floating_t) u->ownermap.map[c][board_at(t->board, c)] / u->ownermap.playouts);
165 } foreach_point_end;
166 fprintf(stderr, "]");
169 fprintf(stderr, "}}\n");
172 void
173 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts, bool final)
175 switch (u->reporting) {
176 case UR_TEXT:
177 uct_progress_text(u, t, color, playouts, final);
178 break;
179 case UR_JSON:
180 case UR_JSON_BIG:
181 uct_progress_json(u, t, color, playouts, final,
182 u->reporting == UR_JSON_BIG);
183 break;
184 default: assert(0);
189 static void
190 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, enum stone color)
192 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
193 amaf->map[coord] = color;
194 } else { // XXX: Respect amaf->record_nakade
195 amaf_op(amaf->map[coord], +);
197 amaf->game[amaf->gamelen].coord = coord;
198 amaf->game[amaf->gamelen].color = color;
199 amaf->gamelen++;
200 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
204 struct uct_playout_callback {
205 struct uct *uct;
206 struct tree *tree;
207 struct tree_node *lnode;
211 static coord_t
212 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
214 /* XXX: This is used in some non-master branches. */
215 return pass;
218 static coord_t
219 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
221 return uct_playout_hook(playout, setup, b, color, 0);
224 static coord_t
225 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
227 return uct_playout_hook(playout, setup, b, color, 1);
231 static int
232 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
233 struct playout_amafmap *amaf,
234 struct uct_descent *descent, int *dlen,
235 struct tree_node *significant[2],
236 struct tree *t, struct tree_node *n, enum stone node_color,
237 char *spaces)
239 enum stone next_color = stone_other(node_color);
240 int parity = (next_color == player_color ? 1 : -1);
242 /* We need to make sure only one thread expands the node. If
243 * we are unlucky enough for two threads to meet in the same
244 * node, the latter one will simply do another simulation from
245 * the node itself, no big deal. t->nodes_size may exceed
246 * the maximum in multi-threaded case but not by much so it's ok.
247 * The size test must be before the test&set not after, to allow
248 * expansion of the node later if enough nodes have been freed. */
249 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
250 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
251 tree_expand_node(t, n, b, next_color, u, parity);
253 if (UDEBUGL(7))
254 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
255 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
256 tree_node_get_value(t, parity, n->u.value));
258 struct uct_playout_callback upc = {
259 .uct = u,
260 .tree = t,
261 /* TODO: Don't necessarily restart the sequence walk when
262 * entering playout. */
263 .lnode = NULL,
266 struct playout_setup ps = {
267 .gamelen = u->gamelen,
268 .mercymin = u->mercymin,
269 .prepolicy_hook = uct_playout_prepolicy,
270 .postpolicy_hook = uct_playout_postpolicy,
271 .hook_data = &upc,
273 int result = play_random_game(&ps, b, next_color,
274 u->playout_amaf ? amaf : NULL,
275 &u->ownermap, u->playout);
276 if (next_color == S_WHITE) {
277 /* We need the result from black's perspective. */
278 result = - result;
280 if (UDEBUGL(7))
281 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
282 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
284 return result;
287 static floating_t
288 scale_value(struct uct *u, struct board *b, int result)
290 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
291 if (u->val_scale && result != 0) {
292 int vp = u->val_points;
293 if (!vp) {
294 vp = board_size(b) - 1; vp *= vp; vp *= 2;
297 floating_t sval = (floating_t) abs(result) / vp;
298 sval = sval > 1 ? 1 : sval;
299 if (result < 0) sval = 1 - sval;
300 if (u->val_extra)
301 rval += u->val_scale * sval;
302 else
303 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
304 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
306 return rval;
309 static void
310 record_local_sequence(struct uct *u, struct tree *t,
311 struct uct_descent *descent, int dlen, int di,
312 enum stone seq_color, floating_t rval)
314 #define LTREE_DEBUG if (UDEBUGL(6))
316 /* Ignore pass sequences. */
317 if (is_pass(descent[di].node->coord))
318 return;
320 /* Transform the rval appropriately, based on the expected
321 * result at the root of the sequence. */
322 if (u->local_tree_rootseqval) {
323 float expval = descent[di - 1].value.value;
324 rval = stats_temper_value(rval, expval, u->local_tree);
327 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
328 rval, stone2str(seq_color));
330 /* Sequences starting deeper are less relevant in general. */
331 int pval = LTREE_PLAYOUTS_MULTIPLIER;
332 if (u->local_tree && u->local_tree_depth_decay > 0)
333 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
334 if (!pval) {
335 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
336 return;
339 /* Pick the right local tree root... */
340 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
341 lnode->u.playouts++;
343 /* ...and record the sequence. */
344 int di0 = di;
345 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
346 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
347 coord2sstr(descent[di].node->coord, t->board),
348 descent[di].node->d);
349 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
350 assert(lnode);
351 stats_add_result(&lnode->u, rval, pval);
354 /* Add lnode for tenuki (pass) if we descended further. */
355 if (di < dlen) {
356 LTREE_DEBUG fprintf(stderr, "pass ");
357 lnode = tree_get_node(t, lnode, pass, true);
358 assert(lnode);
359 stats_add_result(&lnode->u, rval, pval);
362 LTREE_DEBUG fprintf(stderr, "\n");
367 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
369 struct board b2;
370 board_copy(&b2, b);
372 struct playout_amafmap *amaf = NULL;
373 if (u->policy->wants_amaf) {
374 amaf = calloc2(1, sizeof(*amaf));
375 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
376 amaf->map++; // -1 is pass
379 /* Walk the tree until we find a leaf, then expand it and do
380 * a random playout. */
381 struct tree_node *n = t->root;
382 enum stone node_color = stone_other(player_color);
383 assert(node_color == t->root_color);
385 /* Tree descent history. */
386 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
387 * redundant. */
388 struct uct_descent descent[DESCENT_DLEN];
389 descent[0].node = n; descent[0].lnode = NULL;
390 int dlen = 1;
391 /* Total value of the sequence. */
392 struct move_stats seq_value = { .playouts = 0 };
393 /* The last "significant" node along the descent (i.e. node
394 * with higher than configured number of playouts). For black
395 * and white. */
396 struct tree_node *significant[2] = { NULL, NULL };
397 if (n->u.playouts >= u->significant_threshold)
398 significant[node_color - 1] = n;
400 int result;
401 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
402 int passes = is_pass(b->last_move.coord) && b->moves > 0;
404 /* debug */
405 static char spaces[] = "\0 ";
406 /* /debug */
407 if (UDEBUGL(8))
408 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
410 while (!tree_leaf_node(n) && passes < 2) {
411 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
414 /*** Choose a node to descend to: */
416 /* Parity is chosen already according to the child color, since
417 * it is applied to children. */
418 node_color = stone_other(node_color);
419 int parity = (node_color == player_color ? 1 : -1);
421 assert(dlen < DESCENT_DLEN);
422 descent[dlen] = descent[dlen - 1];
423 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
424 /* Start new local sequence. */
425 /* Remember that node_color already holds color of the
426 * to-be-found child. */
427 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
430 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
431 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
432 else
433 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
436 /*** Perform the descent: */
438 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
439 significant[node_color - 1] = descent[dlen].node;
442 seq_value.playouts += descent[dlen].value.playouts;
443 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
444 n = descent[dlen++].node;
445 assert(n == t->root || n->parent);
446 if (UDEBUGL(7))
447 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
448 spaces, coord2sstr(n->coord, t->board),
449 n->coord, n->u.playouts,
450 tree_node_get_value(t, parity, n->u.value));
452 /* Add virtual loss if we need to; this is used to discourage
453 * other threads from visiting this node in case of multiple
454 * threads doing the tree search. */
455 if (u->virtual_loss)
456 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
458 assert(n->coord >= -1);
459 if (amaf && !is_pass(n->coord))
460 record_amaf_move(amaf, n->coord, node_color);
462 struct move m = { n->coord, node_color };
463 int res = board_play(&b2, &m);
465 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
466 || b2.superko_violation) {
467 if (UDEBUGL(4)) {
468 for (struct tree_node *ni = n; ni; ni = ni->parent)
469 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
470 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
471 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
472 res, group_at(&b2, m.coord), b2.superko_violation);
474 n->hints |= TREE_HINT_INVALID;
475 result = 0;
476 goto end;
479 if (is_pass(n->coord))
480 passes++;
481 else
482 passes = 0;
485 if (amaf) {
486 amaf->game_baselen = amaf->gamelen;
487 amaf->record_nakade = u->playout_amaf_nakade;
490 if (t->use_extra_komi && u->dynkomi->persim) {
491 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
494 if (passes >= 2) {
495 /* XXX: No dead groups support. */
496 floating_t score = board_official_score(&b2, NULL);
497 /* Result from black's perspective (no matter who
498 * the player; black's perspective is always
499 * what the tree stores. */
500 result = - (score * 2);
502 if (UDEBUGL(5))
503 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
504 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
505 if (UDEBUGL(6))
506 board_print(&b2, stderr);
508 board_ownermap_fill(&u->ownermap, &b2);
510 } else { // assert(tree_leaf_node(n));
511 /* In case of parallel tree search, the assertion might
512 * not hold if two threads chew on the same node. */
513 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
516 if (amaf && u->playout_amaf_cutoff) {
517 unsigned int cutoff = amaf->game_baselen;
518 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
519 /* Now, reconstruct the amaf map. */
520 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
521 for (unsigned int i = 0; i < cutoff; i++) {
522 coord_t coord = amaf->game[i].coord;
523 enum stone color = amaf->game[i].color;
524 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
525 amaf->map[coord] = color;
526 /* Nakade always recorded for in-tree part */
527 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
528 amaf_op(amaf->map[n->coord], +);
533 /* Record the result. */
535 assert(n == t->root || n->parent);
536 floating_t rval = scale_value(u, b, result);
537 u->policy->update(u->policy, t, n, node_color, player_color, amaf, &b2, rval);
539 if (t->use_extra_komi) {
540 stats_add_result(&u->dynkomi->score, result / 2, 1);
541 stats_add_result(&u->dynkomi->value, rval, 1);
544 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
545 /* Possibly transform the rval appropriately. */
546 if (!u->local_tree_rootseqval) {
547 floating_t expval = seq_value.value / seq_value.playouts;
548 rval = stats_temper_value(rval, expval, u->local_tree);
551 /* Get the local sequences and record them in ltree. */
552 /* We will look for sequence starts in our descent
553 * history, then run record_local_sequence() for each
554 * found sequence start; record_local_sequence() may
555 * pick longer sequences from descent history then,
556 * which is expected as it will create new lnodes. */
557 enum stone seq_color = player_color;
558 /* First move always starts a sequence. */
559 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
560 seq_color = stone_other(seq_color);
561 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
562 if (u->local_tree_allseq) {
563 /* We are configured to record all subsequences. */
564 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
565 continue;
567 if (descent[dseqi].node->d >= u->tenuki_d) {
568 /* Tenuki! Record the fresh sequence. */
569 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
570 continue;
572 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
573 /* Record result for in-descent picked sequence. */
574 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
575 continue;
580 end:
581 /* We need to undo the virtual loss we added during descend. */
582 if (u->virtual_loss) {
583 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
584 for (; n->parent; n = n->parent) {
585 stats_rm_result(&n->u, loss, u->virtual_loss);
586 loss = 1.0 - loss;
590 if (amaf) {
591 free(amaf->map - 1);
592 free(amaf);
594 board_done_noalloc(&b2);
595 return result;
599 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
601 int i;
602 if (ti && ti->dim == TD_GAMES) {
603 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
604 uct_playout(u, b, color, t);
605 } else {
606 for (i = 0; !uct_halt; i++)
607 uct_playout(u, b, color, t);
609 return i;