Merge pull request #25 from sthalik/pull-req/tree-node-size-padding
[pachi.git] / uct / uct.c
blobfc42a9acf231fa0bc79e7025af58a78dc7790f51
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <time.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "board.h"
12 #include "gtp.h"
13 #include "chat.h"
14 #include "move.h"
15 #include "mq.h"
16 #include "joseki/base.h"
17 #include "playout.h"
18 #include "playout/moggy.h"
19 #include "playout/light.h"
20 #include "tactics/util.h"
21 #include "timeinfo.h"
22 #include "uct/dynkomi.h"
23 #include "uct/internal.h"
24 #include "uct/plugins.h"
25 #include "uct/prior.h"
26 #include "uct/search.h"
27 #include "uct/slave.h"
28 #include "uct/tree.h"
29 #include "uct/uct.h"
30 #include "uct/walk.h"
32 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
33 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg, struct board *board);
34 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
36 /* Maximal simulation length. */
37 #define MC_GAMELEN MAX_GAMELEN
40 static void
41 setup_state(struct uct *u, struct board *b, enum stone color)
43 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
44 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, u->stats_hbits);
45 if (u->initial_extra_komi)
46 u->t->extra_komi = u->initial_extra_komi;
47 if (u->force_seed)
48 fast_srandom(u->force_seed);
49 if (UDEBUGL(3))
50 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
51 if (!u->no_tbook && b->moves == 0) {
52 if (color == S_BLACK) {
53 tree_load(u->t, b);
54 } else if (DEBUGL(0)) {
55 fprintf(stderr, "Warning: First move appears to be white\n");
60 static void
61 reset_state(struct uct *u)
63 assert(u->t);
64 tree_done(u->t); u->t = NULL;
67 static void
68 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
70 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
71 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
72 else if (!u->t->use_extra_komi)
73 u->t->extra_komi = 0;
76 void
77 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
79 if (u->t) {
80 /* Verify that we have sane state. */
81 assert(b->es == u);
82 assert(u->t && b->moves);
83 if (color != stone_other(u->t->root_color)) {
84 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
85 color, u->t->root_color);
86 exit(1);
88 uct_htable_reset(u->t);
90 } else {
91 /* We need fresh state. */
92 b->es = u;
93 setup_state(u, b, color);
96 u->ownermap.playouts = 0;
97 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
98 u->played_own = u->played_all = 0;
101 static void
102 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
104 enum gj_state gs_array[board_size2(b)];
105 struct group_judgement gj = { .thres = GJ_THRES, .gs = gs_array };
106 board_ownermap_judge_groups(b, &u->ownermap, &gj);
107 groups_of_status(b, &gj, GS_DEAD, mq);
110 bool
111 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
113 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
114 while (u->ownermap.playouts < GJ_MINGAMES)
115 uct_playout(u, b, color, u->t);
117 struct move_queue mq = { .moves = 0 };
118 dead_group_list(u, b, &mq);
119 if (pass_all_alive) {
120 for (unsigned int i = 0; i < mq.moves; i++) {
121 if (board_at(b, mq.move[i]) == stone_other(color)) {
122 return false; // We need to remove opponent dead groups first.
125 mq.moves = 0; // our dead stones are alive when pass_all_alive is true
127 if (u->allow_losing_pass) {
128 foreach_point(b) {
129 if (board_at(b, c) == S_OFFBOARD)
130 continue;
131 if (board_ownermap_judge_point(&u->ownermap, c, GJ_THRES) == PJ_UNKNOWN) {
132 if (UDEBUGL(3))
133 fprintf(stderr, "uct_pass_is_safe fails at %s[%d]\n", coord2sstr(c, b), c);
134 return false; // Unclear point, clarify first.
136 } foreach_point_end;
137 return true;
139 return pass_is_safe(b, color, &mq);
142 static char *
143 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
145 struct uct *u = board->es;
146 if (!u) {
147 strcat(s, ". ");
148 return s + 2;
150 const char chr[] = ":XO,"; // dame, black, white, unclear
151 const char chm[] = ":xo,";
152 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
153 if (ch == ',') { // less precise estimate then?
154 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
156 s += snprintf(s, end - s, "%c ", ch);
157 return s;
160 static float
161 uct_owner_map(struct engine *e, struct board *b, coord_t c)
163 struct uct *u = b->es;
164 return board_ownermap_estimate_point(&u->ownermap, c);
167 static char *
168 uct_notify_play(struct engine *e, struct board *b, struct move *m, char *enginearg)
170 struct uct *u = e->data;
171 if (!u->t) {
172 /* No state, create one - this is probably game beginning
173 * and we need to load the opening tbook right now. */
174 uct_prepare_move(u, b, m->color);
175 assert(u->t);
178 /* Stop pondering, required by tree_promote_at() */
179 uct_pondering_stop(u);
180 if (UDEBUGL(2) && u->slave)
181 tree_dump(u->t, u->dumpthres);
183 if (is_resign(m->coord)) {
184 /* Reset state. */
185 reset_state(u);
186 return NULL;
189 /* Promote node of the appropriate move to the tree root. */
190 assert(u->t->root);
191 if (u->t->untrustworthy_tree | !tree_promote_at(u->t, b, m->coord)) {
192 if (UDEBUGL(3)) {
193 if (u->t->untrustworthy_tree)
194 fprintf(stderr, "Not promoting move node in untrustworthy tree.\n");
195 else
196 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
198 /* Preserve dynamic komi information, though, that is important. */
199 u->initial_extra_komi = u->t->extra_komi;
200 reset_state(u);
201 return NULL;
204 /* If we are a slave in a distributed engine, start pondering once
205 * we know which move we actually played. See uct_genmove() about
206 * the check for pass. */
207 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
208 uct_pondering_start(u, b, u->t, stone_other(m->color));
210 return NULL;
213 static char *
214 uct_undo(struct engine *e, struct board *b)
216 struct uct *u = e->data;
218 if (!u->t) return NULL;
219 uct_pondering_stop(u);
220 u->initial_extra_komi = u->t->extra_komi;
221 reset_state(u);
222 return NULL;
225 static char *
226 uct_result(struct engine *e, struct board *b)
228 struct uct *u = e->data;
229 static char reply[1024];
231 if (!u->t)
232 return NULL;
233 enum stone color = u->t->root_color;
234 struct tree_node *n = u->t->root;
235 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
236 stone2str(color), coord2sstr(node_coord(n), b),
237 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
238 u->t->use_extra_komi ? u->t->extra_komi : 0);
239 return reply;
242 static char *
243 uct_chat(struct engine *e, struct board *b, bool opponent, char *from, char *cmd)
245 struct uct *u = e->data;
247 if (!u->t)
248 return generic_chat(b, opponent, from, cmd, S_NONE, pass, 0, 1, u->threads, 0.0, 0.0);
250 struct tree_node *n = u->t->root;
251 double winrate = tree_node_get_value(u->t, -1, n->u.value);
252 double extra_komi = u->t->use_extra_komi && fabs(u->t->extra_komi) >= 0.5 ? u->t->extra_komi : 0;
254 return generic_chat(b, opponent, from, cmd, u->t->root_color, node_coord(n), n->u.playouts, 1,
255 u->threads, winrate, extra_komi);
258 static void
259 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
261 struct uct *u = e->data;
263 /* This means the game is probably over, no use pondering on. */
264 uct_pondering_stop(u);
266 if (u->pass_all_alive)
267 return; // no dead groups
269 bool mock_state = false;
271 if (!u->t) {
272 /* No state, but we cannot just back out - we might
273 * have passed earlier, only assuming some stones are
274 * dead, and then re-connected, only to lose counting
275 * when all stones are assumed alive. */
276 uct_prepare_move(u, b, S_BLACK); assert(u->t);
277 mock_state = true;
279 /* Make sure the ownermap is well-seeded. */
280 while (u->ownermap.playouts < GJ_MINGAMES)
281 uct_playout(u, b, S_BLACK, u->t);
282 /* Show the ownermap: */
283 if (DEBUGL(2))
284 board_print_custom(b, stderr, uct_printhook_ownermap);
286 dead_group_list(u, b, mq);
288 if (mock_state) {
289 /* Clean up the mock state in case we will receive
290 * a genmove; we could get a non-alternating-move
291 * error from uct_prepare_move() in that case otherwise. */
292 reset_state(u);
296 static void
297 playout_policy_done(struct playout_policy *p)
299 if (p->done) p->done(p);
300 if (p->data) free(p->data);
301 free(p);
304 static void
305 uct_stop(struct engine *e)
307 /* This is called on game over notification. However, an undo
308 * and game resume can follow, so don't panic yet and just
309 * relax and stop thinking so that we don't waste CPU. */
310 struct uct *u = e->data;
311 uct_pondering_stop(u);
314 static void
315 uct_done(struct engine *e)
317 /* This is called on engine reset, especially when clear_board
318 * is received and new game should begin. */
319 free(e->comment);
321 struct uct *u = e->data;
322 uct_pondering_stop(u);
323 if (u->t) reset_state(u);
324 if (u->dynkomi) u->dynkomi->done(u->dynkomi);
325 free(u->ownermap.map);
327 if (u->policy) u->policy->done(u->policy);
328 if (u->random_policy) u->random_policy->done(u->random_policy);
329 playout_policy_done(u->playout);
330 uct_prior_done(u->prior);
331 joseki_done(u->jdict);
332 pluginset_done(u->plugins);
337 /* Run time-limited MCTS search on foreground. */
338 static int
339 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t, bool print_progress)
341 struct uct_search_state s;
342 uct_search_start(u, b, color, t, ti, &s);
343 if (UDEBUGL(2) && s.base_playouts > 0)
344 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
346 /* The search tree is ctx->t. This is currently == . It is important
347 * to reference ctx->t directly since the
348 * thread manager will swap the tree pointer asynchronously. */
350 /* Now, just periodically poll the search tree. */
351 /* Note that in case of TD_GAMES, threads will not wait for
352 * the uct_search_check_stop() signalization. */
353 while (1) {
354 time_sleep(TREE_BUSYWAIT_INTERVAL);
355 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
356 * time control is broken. But if it happens to be less, we still search
357 * at least 100ms otherwise the move is completely random. */
359 int i = uct_search_games(&s);
360 /* Print notifications etc. */
361 uct_search_progress(u, b, color, t, ti, &s, i);
362 /* Check if we should stop the search. */
363 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
364 break;
367 struct uct_thread_ctx *ctx = uct_search_stop();
368 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
369 if (UDEBUGL(2))
370 fprintf(stderr, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
371 t->avg_score.value, t->avg_score.playouts,
372 u->dynkomi->score.value, u->dynkomi->score.playouts,
373 u->dynkomi->value.value, u->dynkomi->value.playouts);
374 if (print_progress)
375 uct_progress_status(u, t, color, ctx->games, NULL);
377 if (u->debug_after.playouts > 0) {
378 /* Now, start an additional run of playouts, single threaded. */
379 struct time_info debug_ti = {
380 .period = TT_MOVE,
381 .dim = TD_GAMES,
383 debug_ti.len.games = t->root->u.playouts + u->debug_after.playouts;
385 board_print_custom(b, stderr, uct_printhook_ownermap);
386 fprintf(stderr, "--8<-- UCT debug post-run begin (%d:%d) --8<--\n", u->debug_after.level, u->debug_after.playouts);
388 int debug_level_save = debug_level;
389 int u_debug_level_save = u->debug_level;
390 int p_debug_level_save = u->playout->debug_level;
391 debug_level = u->debug_after.level;
392 u->debug_level = u->debug_after.level;
393 u->playout->debug_level = u->debug_after.level;
394 uct_halt = false;
396 uct_playouts(u, b, color, t, &debug_ti);
397 tree_dump(t, u->dumpthres);
399 uct_halt = true;
400 debug_level = debug_level_save;
401 u->debug_level = u_debug_level_save;
402 u->playout->debug_level = p_debug_level_save;
404 fprintf(stderr, "--8<-- UCT debug post-run finished --8<--\n");
407 u->played_own += ctx->games;
408 return ctx->games;
411 /* Start pondering background with @color to play. */
412 static void
413 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
415 if (UDEBUGL(1))
416 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
417 u->pondering = true;
419 /* We need a local board copy to ponder upon. */
420 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
422 /* *b0 did not have the genmove'd move played yet. */
423 struct move m = { node_coord(t->root), t->root_color };
424 int res = board_play(b, &m);
425 assert(res >= 0);
426 setup_dynkomi(u, b, stone_other(m.color));
428 /* Start MCTS manager thread "headless". */
429 static struct uct_search_state s;
430 uct_search_start(u, b, color, t, NULL, &s);
433 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
434 * to stop the background search for a slave in the distributed engine. */
435 void
436 uct_pondering_stop(struct uct *u)
438 if (!thread_manager_running)
439 return;
441 /* Stop the thread manager. */
442 struct uct_thread_ctx *ctx = uct_search_stop();
443 if (UDEBUGL(1)) {
444 if (u->pondering) fprintf(stderr, "(pondering) ");
445 uct_progress_status(u, ctx->t, ctx->color, ctx->games, NULL);
447 if (u->pondering) {
448 free(ctx->b);
449 u->pondering = false;
454 void
455 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
457 if (b->superko_violation) {
458 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
459 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
460 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
461 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
462 b->superko_violation = false;
465 uct_prepare_move(u, b, color);
467 assert(u->t);
468 u->my_color = color;
470 /* How to decide whether to use dynkomi in this game? Since we use
471 * pondering, it's not simple "who-to-play" matter. Decide based on
472 * the last genmove issued. */
473 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
474 setup_dynkomi(u, b, color);
476 if (b->rules == RULES_JAPANESE)
477 u->territory_scoring = true;
479 /* Make pessimistic assumption about komi for Japanese rules to
480 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
481 * The rules usually give the same winner if the integer part of komi
482 * is odd so we adjust the komi only if it is even (for a board of
483 * odd size). We are not trying to get an exact evaluation for rare
484 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
485 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
486 b->komi += (color == S_BLACK ? 1.0 : -1.0);
487 if (UDEBUGL(0))
488 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
489 b->komi);
493 static void
494 uct_live_gfx_hook(struct engine *e)
496 struct uct *u = e->data;
497 /* Hack: Override reportfreq to get decent update rates in GoGui */
498 u->reportfreq = 1000;
501 /* Kindof like uct_genmove() but just find the best candidates */
502 static void
503 uct_best_moves(struct engine *e, struct board *b, enum stone color)
505 struct time_info ti = { .period = TT_NULL };
506 double start_time = time_now();
507 struct uct *u = e->data;
508 uct_pondering_stop(u);
509 if (u->t)
510 reset_state(u);
511 uct_genmove_setup(u, b, color);
513 /* Start the Monte Carlo Tree Search! */
514 int base_playouts = u->t->root->u.playouts;
515 int played_games = uct_search(u, b, &ti, color, u->t, false);
517 coord_t best_coord;
518 uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
520 if (UDEBUGL(2)) {
521 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
522 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
523 time, (int)(played_games/time), (int)(played_games/time/u->threads));
526 uct_progress_status(u, u->t, color, played_games, &best_coord);
527 reset_state(u);
530 static coord_t *
531 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
533 double start_time = time_now();
534 struct uct *u = e->data;
535 u->pass_all_alive |= pass_all_alive;
536 uct_pondering_stop(u);
537 uct_genmove_setup(u, b, color);
539 /* Start the Monte Carlo Tree Search! */
540 int base_playouts = u->t->root->u.playouts;
541 int played_games = uct_search(u, b, ti, color, u->t, false);
543 coord_t best_coord;
544 struct tree_node *best;
545 best = uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
547 if (UDEBUGL(2)) {
548 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
549 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
550 time, (int)(played_games/time), (int)(played_games/time/u->threads));
553 uct_progress_status(u, u->t, color, played_games, &best_coord);
555 if (!best) {
556 /* Pass or resign. */
557 if (is_pass(best_coord))
558 u->initial_extra_komi = u->t->extra_komi;
559 reset_state(u);
560 return coord_copy(best_coord);
563 if (!u->t->untrustworthy_tree) {
564 tree_promote_node(u->t, &best);
565 } else {
566 /* Throw away an untrustworthy tree. */
567 /* Preserve dynamic komi information, though, that is important. */
568 u->initial_extra_komi = u->t->extra_komi;
569 reset_state(u);
572 /* After a pass, pondering is harmful for two reasons:
573 * (i) We might keep pondering even when the game is over.
574 * Of course this is the case for opponent resign as well.
575 * (ii) More importantly, the ownermap will get skewed since
576 * the UCT will start cutting off any playouts. */
577 if (u->pondering_opt && u->t && !is_pass(node_coord(best))) {
578 uct_pondering_start(u, b, u->t, stone_other(color));
580 return coord_copy(best_coord);
584 bool
585 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
587 struct uct *u = e->data;
588 if (!u->t) uct_prepare_move(u, b, color);
589 assert(u->t);
591 if (ti->dim == TD_GAMES) {
592 /* Don't count in games that already went into the tbook. */
593 ti->len.games += u->t->root->u.playouts;
595 uct_search(u, b, ti, color, u->t, true);
597 assert(ti->dim == TD_GAMES);
598 tree_save(u->t, b, ti->len.games / 100);
600 return true;
603 void
604 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
606 struct uct *u = e->data;
607 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
608 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
609 tree_load(t, b);
610 tree_dump(t, 0);
611 tree_done(t);
615 floating_t
616 uct_evaluate_one(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
618 struct uct *u = e->data;
620 struct board b2;
621 board_copy(&b2, b);
622 struct move m = { c, color };
623 int res = board_play(&b2, &m);
624 if (res < 0)
625 return NAN;
626 color = stone_other(color);
628 if (u->t) reset_state(u);
629 uct_prepare_move(u, &b2, color);
630 assert(u->t);
632 floating_t bestval;
633 uct_search(u, &b2, ti, color, u->t, true);
634 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
635 if (!best) {
636 bestval = NAN; // the opponent has no reply!
637 } else {
638 bestval = tree_node_get_value(u->t, 1, best->u.value);
641 reset_state(u); // clean our junk
643 return isnan(bestval) ? NAN : 1.0f - bestval;
646 void
647 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, floating_t *vals, enum stone color)
649 for (int i = 0; i < b->flen; i++) {
650 if (is_pass(b->f[i]))
651 vals[i] = NAN;
652 else
653 vals[i] = uct_evaluate_one(e, b, ti, b->f[i], color);
658 struct uct *
659 uct_state_init(char *arg, struct board *b)
661 struct uct *u = calloc2(1, sizeof(struct uct));
662 bool pat_setup = false;
664 u->debug_level = debug_level;
665 u->reportfreq = 10000;
666 u->gamelen = MC_GAMELEN;
667 u->resign_threshold = 0.2;
668 u->sure_win_threshold = 0.95;
669 u->mercymin = 0;
670 u->significant_threshold = 50;
671 u->expand_p = 8;
672 u->dumpthres = 0.01;
673 u->playout_amaf = true;
674 u->amaf_prior = false;
675 u->max_tree_size = 1408ULL * 1048576;
676 u->fast_alloc = true;
677 u->pruning_threshold = 0;
679 u->threads = 1;
680 u->thread_model = TM_TREEVL;
681 u->virtual_loss = 1;
683 u->pondering_opt = true;
685 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
686 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
687 u->bestr_ratio = 0.02;
688 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
689 // TODO: Further tuning and experiments with better time allocation schemes.
690 u->best2_ratio = 2.5;
691 // Higher values of max_maintime_ratio sometimes cause severe time trouble in tournaments
692 // It might be necessary to reduce it to 1.5 on large board, but more tuning is needed.
693 u->max_maintime_ratio = 2.0;
695 u->val_scale = 0; u->val_points = 40;
696 u->dynkomi_interval = 1000;
697 u->dynkomi_mask = S_BLACK | S_WHITE;
699 u->tenuki_d = 4;
700 u->local_tree_aging = 80;
701 u->local_tree_depth_decay = 1.5;
702 u->local_tree_eval = LTE_ROOT;
703 u->local_tree_neival = true;
705 u->max_slaves = -1;
706 u->slave_index = -1;
707 u->stats_delay = 0.01; // 10 ms
708 u->shared_levels = 1;
710 u->plugins = pluginset_init(b);
712 u->jdict = joseki_load(b->size);
714 if (arg) {
715 char *optspec, *next = arg;
716 while (*next) {
717 optspec = next;
718 next += strcspn(next, ",");
719 if (*next) { *next++ = 0; } else { *next = 0; }
721 char *optname = optspec;
722 char *optval = strchr(optspec, '=');
723 if (optval) *optval++ = 0;
725 /** Basic options */
727 if (!strcasecmp(optname, "debug")) {
728 if (optval)
729 u->debug_level = atoi(optval);
730 else
731 u->debug_level++;
732 } else if (!strcasecmp(optname, "reporting") && optval) {
733 /* The format of output for detailed progress
734 * information (such as current best move and
735 * its value, etc.). */
736 if (!strcasecmp(optval, "text")) {
737 /* Plaintext traditional output. */
738 u->reporting = UR_TEXT;
739 } else if (!strcasecmp(optval, "json")) {
740 /* JSON output. Implies debug=0. */
741 u->reporting = UR_JSON;
742 u->debug_level = 0;
743 } else if (!strcasecmp(optval, "jsonbig")) {
744 /* JSON output, but much more detailed.
745 * Implies debug=0. */
746 u->reporting = UR_JSON_BIG;
747 u->debug_level = 0;
748 } else {
749 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
750 exit(1);
752 } else if (!strcasecmp(optname, "reportfreq") && optval) {
753 /* The progress information line will be shown
754 * every <reportfreq> simulations. */
755 u->reportfreq = atoi(optval);
756 } else if (!strcasecmp(optname, "dumpthres") && optval) {
757 /* When dumping the UCT tree on output, include
758 * nodes with at least this many playouts.
759 * (A fraction of the total # of playouts at the
760 * tree root.) */
761 /* Use 0 to list all nodes with at least one
762 * simulation, and -1 to list _all_ nodes. */
763 u->dumpthres = atof(optval);
764 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
765 /* Resign when this ratio of games is lost
766 * after GJ_MINGAMES sample is taken. */
767 u->resign_threshold = atof(optval);
768 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
769 /* Stop reading when this ratio of games is won
770 * after PLAYOUT_EARLY_BREAK_MIN sample is
771 * taken. (Prevents stupid time losses,
772 * friendly to human opponents.) */
773 u->sure_win_threshold = atof(optval);
774 } else if (!strcasecmp(optname, "force_seed") && optval) {
775 /* Set RNG seed at the tree setup. */
776 u->force_seed = atoi(optval);
777 } else if (!strcasecmp(optname, "no_tbook")) {
778 /* Disable UCT opening tbook. */
779 u->no_tbook = true;
780 } else if (!strcasecmp(optname, "pass_all_alive")) {
781 /* Whether to consider passing only after all
782 * dead groups were removed from the board;
783 * this is like all genmoves are in fact
784 * kgs-genmove_cleanup. */
785 u->pass_all_alive = !optval || atoi(optval);
786 } else if (!strcasecmp(optname, "allow_losing_pass")) {
787 /* Whether to consider passing in a clear
788 * but losing situation, to be scored as a loss
789 * for us. */
790 u->allow_losing_pass = !optval || atoi(optval);
791 } else if (!strcasecmp(optname, "territory_scoring")) {
792 /* Use territory scoring (default is area scoring).
793 * An explicit kgs-rules command overrides this. */
794 u->territory_scoring = !optval || atoi(optval);
795 } else if (!strcasecmp(optname, "stones_only")) {
796 /* Do not count eyes. Nice to teach go to kids.
797 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
798 b->rules = RULES_STONES_ONLY;
799 u->pass_all_alive = true;
800 } else if (!strcasecmp(optname, "debug_after")) {
801 /* debug_after=9:1000 will make Pachi think under
802 * the normal conditions, but at the point when
803 * a move is to be chosen, the tree is dumped and
804 * another 1000 simulations are run single-threaded
805 * with debug level 9, allowing inspection of Pachi's
806 * behavior after it has thought a lot. */
807 if (optval) {
808 u->debug_after.level = atoi(optval);
809 char *playouts = strchr(optval, ':');
810 if (playouts)
811 u->debug_after.playouts = atoi(playouts+1);
812 else
813 u->debug_after.playouts = 1000;
814 } else {
815 u->debug_after.level = 9;
816 u->debug_after.playouts = 1000;
818 } else if (!strcasecmp(optname, "banner") && optval) {
819 /* Additional banner string. This must come as the
820 * last engine parameter. You can use '+' instead
821 * of ' ' if you are wrestling with kgsGtp. */
822 if (*next) *--next = ',';
823 u->banner = strdup(optval);
824 for (char *b = u->banner; *b; b++) {
825 if (*b == '+') *b = ' ';
827 break;
828 } else if (!strcasecmp(optname, "plugin") && optval) {
829 /* Load an external plugin; filename goes before the colon,
830 * extra arguments after the colon. */
831 char *pluginarg = strchr(optval, ':');
832 if (pluginarg)
833 *pluginarg++ = 0;
834 plugin_load(u->plugins, optval, pluginarg);
836 /** UCT behavior and policies */
838 } else if ((!strcasecmp(optname, "policy")
839 /* Node selection policy. ucb1amaf is the
840 * default policy implementing RAVE, while
841 * ucb1 is the simple exploration/exploitation
842 * policy. Policies can take further extra
843 * options. */
844 || !strcasecmp(optname, "random_policy")) && optval) {
845 /* A policy to be used randomly with small
846 * chance instead of the default policy. */
847 char *policyarg = strchr(optval, ':');
848 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
849 if (policyarg)
850 *policyarg++ = 0;
851 if (!strcasecmp(optval, "ucb1")) {
852 *p = policy_ucb1_init(u, policyarg);
853 } else if (!strcasecmp(optval, "ucb1amaf")) {
854 *p = policy_ucb1amaf_init(u, policyarg, b);
855 } else {
856 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
857 exit(1);
859 } else if (!strcasecmp(optname, "playout") && optval) {
860 /* Random simulation (playout) policy.
861 * moggy is the default policy with large
862 * amount of domain-specific knowledge and
863 * heuristics. light is a simple uniformly
864 * random move selection policy. */
865 char *playoutarg = strchr(optval, ':');
866 if (playoutarg)
867 *playoutarg++ = 0;
868 if (!strcasecmp(optval, "moggy")) {
869 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
870 } else if (!strcasecmp(optval, "light")) {
871 u->playout = playout_light_init(playoutarg, b);
872 } else {
873 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
874 exit(1);
876 } else if (!strcasecmp(optname, "prior") && optval) {
877 /* Node priors policy. When expanding a node,
878 * it will seed node values heuristically
879 * (most importantly, based on playout policy
880 * opinion, but also with regard to other
881 * things). See uct/prior.c for details.
882 * Use prior=eqex=0 to disable priors. */
883 u->prior = uct_prior_init(optval, b, u);
884 } else if (!strcasecmp(optname, "mercy") && optval) {
885 /* Minimal difference of black/white captures
886 * to stop playout - "Mercy Rule". Speeds up
887 * hopeless playouts at the expense of some
888 * accuracy. */
889 u->mercymin = atoi(optval);
890 } else if (!strcasecmp(optname, "gamelen") && optval) {
891 /* Maximum length of single simulation
892 * in moves. */
893 u->gamelen = atoi(optval);
894 } else if (!strcasecmp(optname, "expand_p") && optval) {
895 /* Expand UCT nodes after it has been
896 * visited this many times. */
897 u->expand_p = atoi(optval);
898 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
899 /* If specified (N), with probability 1/N, random_policy policy
900 * descend is used instead of main policy descend; useful
901 * if specified policy (e.g. UCB1AMAF) can make unduly biased
902 * choices sometimes, you can fall back to e.g.
903 * random_policy=UCB1. */
904 u->random_policy_chance = atoi(optval);
906 /** General AMAF behavior */
907 /* (Only relevant if the policy supports AMAF.
908 * More variables can be tuned as policy
909 * parameters.) */
911 } else if (!strcasecmp(optname, "playout_amaf")) {
912 /* Whether to include random playout moves in
913 * AMAF as well. (Otherwise, only tree moves
914 * are included in AMAF. Of course makes sense
915 * only in connection with an AMAF policy.) */
916 /* with-without: 55.5% (+-4.1) */
917 if (optval && *optval == '0')
918 u->playout_amaf = false;
919 else
920 u->playout_amaf = true;
921 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
922 /* Keep only first N% of playout stage AMAF
923 * information. */
924 u->playout_amaf_cutoff = atoi(optval);
925 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
926 /* In node policy, consider prior values
927 * part of the real result term or part
928 * of the AMAF term? */
929 u->amaf_prior = atoi(optval);
931 /** Performance and memory management */
933 } else if (!strcasecmp(optname, "threads") && optval) {
934 /* By default, Pachi will run with only single
935 * tree search thread! */
936 u->threads = atoi(optval);
937 } else if (!strcasecmp(optname, "thread_model") && optval) {
938 if (!strcasecmp(optval, "tree")) {
939 /* Tree parallelization - all threads
940 * grind on the same tree. */
941 u->thread_model = TM_TREE;
942 u->virtual_loss = 0;
943 } else if (!strcasecmp(optval, "treevl")) {
944 /* Tree parallelization, but also
945 * with virtual losses - this discou-
946 * rages most threads choosing the
947 * same tree branches to read. */
948 u->thread_model = TM_TREEVL;
949 } else {
950 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
951 exit(1);
953 } else if (!strcasecmp(optname, "virtual_loss") && optval) {
954 /* Number of virtual losses added before evaluating a node. */
955 u->virtual_loss = atoi(optval);
956 } else if (!strcasecmp(optname, "pondering")) {
957 /* Keep searching even during opponent's turn. */
958 u->pondering_opt = !optval || atoi(optval);
959 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
960 /* Maximum amount of memory [MiB] consumed by the move tree.
961 * For fast_alloc it includes the temp tree used for pruning.
962 * Default is 3072 (3 GiB). */
963 u->max_tree_size = atol(optval) * 1048576;
964 } else if (!strcasecmp(optname, "fast_alloc")) {
965 u->fast_alloc = !optval || atoi(optval);
966 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
967 /* Force pruning at beginning of a move if the tree consumes
968 * more than this [MiB]. Default is 10% of max_tree_size.
969 * Increase to reduce pruning time overhead if memory is plentiful.
970 * This option is meaningful only for fast_alloc. */
971 u->pruning_threshold = atol(optval) * 1048576;
973 /** Time control */
975 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
976 /* If set, prolong simulating while
977 * first_best/second_best playouts ratio
978 * is less than best2_ratio. */
979 u->best2_ratio = atof(optval);
980 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
981 /* If set, prolong simulating while
982 * best,best_best_child values delta
983 * is more than bestr_ratio. */
984 u->bestr_ratio = atof(optval);
985 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
986 /* If set and while not in byoyomi, prolong simulating no more than
987 * max_maintime_ratio times the normal desired thinking time. */
988 u->max_maintime_ratio = atof(optval);
989 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
990 /* At the very beginning it's not worth thinking
991 * too long because the playout evaluations are
992 * very noisy. So gradually increase the thinking
993 * time up to maximum when fuseki_end percent
994 * of the board has been played.
995 * This only applies if we are not in byoyomi. */
996 u->fuseki_end = atoi(optval);
997 } else if (!strcasecmp(optname, "yose_start") && optval) {
998 /* When yose_start percent of the board has been
999 * played, or if we are in byoyomi, stop spending
1000 * more time and spread the remaining time
1001 * uniformly.
1002 * Between fuseki_end and yose_start, we spend
1003 * a constant proportion of the remaining time
1004 * on each move. (yose_start should actually
1005 * be much earlier than when real yose start,
1006 * but "yose" is a good short name to convey
1007 * the idea.) */
1008 u->yose_start = atoi(optval);
1010 /** Dynamic komi */
1012 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1013 /* Dynamic komi approach; there are multiple
1014 * ways to adjust komi dynamically throughout
1015 * play. We currently support two: */
1016 char *dynkomiarg = strchr(optval, ':');
1017 if (dynkomiarg)
1018 *dynkomiarg++ = 0;
1019 if (!strcasecmp(optval, "none")) {
1020 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1021 } else if (!strcasecmp(optval, "linear")) {
1022 /* You should set dynkomi_mask=1 or a very low
1023 * handicap_value for white. */
1024 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1025 } else if (!strcasecmp(optval, "adaptive")) {
1026 /* There are many more knobs to
1027 * crank - see uct/dynkomi.c. */
1028 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1029 } else {
1030 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1031 exit(1);
1033 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1034 /* Bitmask of colors the player must be
1035 * for dynkomi be applied; the default dynkomi_mask=3 allows
1036 * dynkomi even in games where Pachi is white. */
1037 u->dynkomi_mask = atoi(optval);
1038 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1039 /* If non-zero, re-adjust dynamic komi
1040 * throughout a single genmove reading,
1041 * roughly every N simulations. */
1042 /* XXX: Does not work with tree
1043 * parallelization. */
1044 u->dynkomi_interval = atoi(optval);
1045 } else if (!strcasecmp(optname, "extra_komi") && optval) {
1046 /* Initial dynamic komi settings. This
1047 * is useful for the adaptive dynkomi
1048 * policy as the value to start with
1049 * (this is NOT kept fixed) in case
1050 * there is not enough time in the search
1051 * to adjust the value properly (e.g. the
1052 * game was interrupted). */
1053 u->initial_extra_komi = atof(optval);
1055 /** Node value result scaling */
1057 } else if (!strcasecmp(optname, "val_scale") && optval) {
1058 /* How much of the game result value should be
1059 * influenced by win size. Zero means it isn't. */
1060 u->val_scale = atof(optval);
1061 } else if (!strcasecmp(optname, "val_points") && optval) {
1062 /* Maximum size of win to be scaled into game
1063 * result value. Zero means boardsize^2. */
1064 u->val_points = atoi(optval) * 2; // result values are doubled
1065 } else if (!strcasecmp(optname, "val_extra")) {
1066 /* If false, the score coefficient will be simply
1067 * added to the value, instead of scaling the result
1068 * coefficient because of it. */
1069 u->val_extra = !optval || atoi(optval);
1070 } else if (!strcasecmp(optname, "val_byavg")) {
1071 /* If true, the score included in the value will
1072 * be relative to average score in the current
1073 * search episode inst. of jigo. */
1074 u->val_byavg = !optval || atoi(optval);
1075 } else if (!strcasecmp(optname, "val_bytemp")) {
1076 /* If true, the value scaling coefficient
1077 * is different based on value extremity
1078 * (dist. from 0.5), linear between
1079 * val_bytemp_min, val_scale. */
1080 u->val_bytemp = !optval || atoi(optval);
1081 } else if (!strcasecmp(optname, "val_bytemp_min") && optval) {
1082 /* Minimum val_scale in case of val_bytemp. */
1083 u->val_bytemp_min = atof(optval);
1085 /** Local trees */
1086 /* (Purely experimental. Does not work - yet!) */
1088 } else if (!strcasecmp(optname, "local_tree")) {
1089 /* Whether to bias exploration by local tree values. */
1090 u->local_tree = !optval || atoi(optval);
1091 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1092 /* Tenuki distance at which to break the local tree. */
1093 u->tenuki_d = atoi(optval);
1094 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1095 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1096 exit(1);
1098 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1099 /* How much to reduce local tree values between moves. */
1100 u->local_tree_aging = atof(optval);
1101 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
1102 /* With value x>0, during the descent the node
1103 * contributes 1/x^depth playouts in
1104 * the local tree. I.e., with x>1, nodes more
1105 * distant from local situation contribute more
1106 * than nodes near the root. */
1107 u->local_tree_depth_decay = atof(optval);
1108 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1109 /* If disabled, only complete sequences are stored
1110 * in the local tree. If this is on, also
1111 * subsequences starting at each move are stored. */
1112 u->local_tree_allseq = !optval || atoi(optval);
1113 } else if (!strcasecmp(optname, "local_tree_neival")) {
1114 /* If disabled, local node value is not
1115 * computed just based on terminal status
1116 * of the coordinate, but also its neighbors. */
1117 u->local_tree_neival = !optval || atoi(optval);
1118 } else if (!strcasecmp(optname, "local_tree_eval")) {
1119 /* How is the value inserted in the local tree
1120 * determined. */
1121 if (!strcasecmp(optval, "root"))
1122 /* All moves within a tree branch are
1123 * considered wrt. their merit
1124 * reaching tachtical goal of making
1125 * the first move in the branch
1126 * survive. */
1127 u->local_tree_eval = LTE_ROOT;
1128 else if (!strcasecmp(optval, "each"))
1129 /* Each move is considered wrt.
1130 * its own survival. */
1131 u->local_tree_eval = LTE_EACH;
1132 else if (!strcasecmp(optval, "total"))
1133 /* The tactical goal is the survival
1134 * of all the moves of my color and
1135 * non-survival of all the opponent
1136 * moves. Local values (and their
1137 * inverses) are averaged. */
1138 u->local_tree_eval = LTE_TOTAL;
1139 else {
1140 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
1141 exit(1);
1143 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
1144 /* If disabled, only moves within the local
1145 * tree branch are considered; the values
1146 * of the branch roots (i.e. root children)
1147 * are ignored. This may make sense together
1148 * with eval!=each, we consider only moves
1149 * that influence the goal, not the "rating"
1150 * of the goal itself. (The real solution
1151 * will be probably using criticality to pick
1152 * local tree branches.) */
1153 u->local_tree_rootchoose = !optval || atoi(optval);
1155 /** Other heuristics */
1156 } else if (!strcasecmp(optname, "patterns")) {
1157 /* Load pattern database. Various modules
1158 * (priors, policies etc.) may make use
1159 * of this database. They will request
1160 * it automatically in that case, but you
1161 * can use this option to tweak the pattern
1162 * parameters. */
1163 patterns_init(&u->pat, optval, false, true);
1164 u->want_pat = pat_setup = true;
1165 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
1166 /* Some heuristics (XXX: none in mainline) rely
1167 * on the knowledge of the last "significant"
1168 * node in the descent. Such a node is
1169 * considered reasonably trustworthy to carry
1170 * some meaningful information in the values
1171 * of the node and its children. */
1172 u->significant_threshold = atoi(optval);
1174 /** Distributed engine slaves setup */
1176 } else if (!strcasecmp(optname, "slave")) {
1177 /* Act as slave for the distributed engine. */
1178 u->slave = !optval || atoi(optval);
1179 } else if (!strcasecmp(optname, "slave_index") && optval) {
1180 /* Optional index if per-slave behavior is desired.
1181 * Must be given as index/max */
1182 u->slave_index = atoi(optval);
1183 char *p = strchr(optval, '/');
1184 if (p) u->max_slaves = atoi(++p);
1185 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1186 /* Share at most shared_nodes between master and slave at each genmoves.
1187 * Must use the same value in master and slaves. */
1188 u->shared_nodes = atoi(optval);
1189 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1190 /* Share only nodes of level <= shared_levels. */
1191 u->shared_levels = atoi(optval);
1192 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1193 /* Set hash table size to 2^stats_hbits for the shared stats. */
1194 u->stats_hbits = atoi(optval);
1195 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1196 /* How long to wait in slave for initial stats to build up before
1197 * replying to the genmoves command (in ms) */
1198 u->stats_delay = 0.001 * atof(optval);
1200 /** Presets */
1202 } else if (!strcasecmp(optname, "maximize_score")) {
1203 /* A combination of settings that will make
1204 * Pachi try to maximize his points (instead
1205 * of playing slack yose) or minimize his loss
1206 * (and proceed to counting even when losing). */
1207 /* Please note that this preset might be
1208 * somewhat weaker than normal Pachi, and the
1209 * score maximization is approximate; point size
1210 * of win/loss still should not be used to judge
1211 * strength of Pachi or the opponent. */
1212 /* See README for some further notes. */
1213 if (!optval || atoi(optval)) {
1214 /* Allow scoring a lost game. */
1215 u->allow_losing_pass = true;
1216 /* Make Pachi keep his calm when losing
1217 * and/or maintain winning marging. */
1218 /* Do not play games that are losing
1219 * by too much. */
1220 /* XXX: komi_ratchet_age=40000 is necessary
1221 * with losing_komi_ratchet, but 40000
1222 * is somewhat arbitrary value. */
1223 char dynkomi_args[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1224 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomi_args, b);
1225 /* XXX: Values arbitrary so far. */
1226 /* XXX: Also, is bytemp sensible when
1227 * combined with dynamic komi?! */
1228 u->val_scale = 0.01;
1229 u->val_bytemp = true;
1230 u->val_bytemp_min = 0.001;
1231 u->val_byavg = true;
1234 } else {
1235 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1236 exit(1);
1241 if (!u->policy)
1242 u->policy = policy_ucb1amaf_init(u, NULL, b);
1244 if (!!u->random_policy_chance ^ !!u->random_policy) {
1245 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1246 exit(1);
1249 if (!u->local_tree) {
1250 /* No ltree aging. */
1251 u->local_tree_aging = 1.0f;
1254 if (u->fast_alloc) {
1255 if (u->pruning_threshold < u->max_tree_size / 10)
1256 u->pruning_threshold = u->max_tree_size / 10;
1257 if (u->pruning_threshold > u->max_tree_size / 2)
1258 u->pruning_threshold = u->max_tree_size / 2;
1260 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1261 * the nodes and recompute them at the next move if necessary. */
1262 u->max_pruned_size = u->max_tree_size / 5;
1263 u->max_tree_size -= u->max_pruned_size;
1264 } else {
1265 /* Reserve 5% memory in case the background free() are slower
1266 * than the concurrent allocations. */
1267 u->max_tree_size -= u->max_tree_size / 20;
1270 if (!u->prior)
1271 u->prior = uct_prior_init(NULL, b, u);
1273 if (!u->playout)
1274 u->playout = playout_moggy_init(NULL, b, u->jdict);
1275 if (!u->playout->debug_level)
1276 u->playout->debug_level = u->debug_level;
1278 if (u->want_pat && !pat_setup)
1279 patterns_init(&u->pat, NULL, false, true);
1281 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1283 if (u->slave) {
1284 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1285 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1286 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1289 if (!u->dynkomi)
1290 u->dynkomi = board_small(b) ? uct_dynkomi_init_none(u, NULL, b)
1291 : uct_dynkomi_init_linear(u, NULL, b);
1293 /* Some things remain uninitialized for now - the opening tbook
1294 * is not loaded and the tree not set up. */
1295 /* This will be initialized in setup_state() at the first move
1296 * received/requested. This is because right now we are not aware
1297 * about any komi or handicap setup and such. */
1299 return u;
1302 struct engine *
1303 engine_uct_init(char *arg, struct board *b)
1305 struct uct *u = uct_state_init(arg, b);
1306 struct engine *e = calloc2(1, sizeof(struct engine));
1307 e->name = "UCT";
1308 e->printhook = uct_printhook_ownermap;
1309 e->notify_play = uct_notify_play;
1310 e->chat = uct_chat;
1311 e->undo = uct_undo;
1312 e->result = uct_result;
1313 e->genmove = uct_genmove;
1314 e->genmoves = uct_genmoves;
1315 e->evaluate = uct_evaluate;
1316 e->dead_group_list = uct_dead_group_list;
1317 e->stop = uct_stop;
1318 e->done = uct_done;
1319 e->owner_map = uct_owner_map;
1320 e->best_moves = uct_best_moves;
1321 e->live_gfx_hook = uct_live_gfx_hook;
1322 e->data = u;
1323 if (u->slave)
1324 e->notify = uct_notify;
1326 const char banner[] = "If you believe you have won but I am still playing, "
1327 "please help me understand by capturing all dead stones. "
1328 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1329 if (!u->banner) u->banner = "";
1330 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1331 sprintf(e->comment, "%s %s", banner, u->banner);
1333 return e;