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