Merge branch 'time' into derm
[pachi/derm.git] / uct / uct.c
blobbc2aefb40041205ad42b52ddf720e248e577bbe6
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <time.h>
10 #define DEBUG
12 #include "debug.h"
13 #include "board.h"
14 #include "gtp.h"
15 #include "move.h"
16 #include "mq.h"
17 #include "playout.h"
18 #include "playout/elo.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
21 #include "random.h"
22 #include "tactics.h"
23 #include "timeinfo.h"
24 #include "distributed/distributed.h"
25 #include "uct/dynkomi.h"
26 #include "uct/internal.h"
27 #include "uct/prior.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);
34 static void uct_pondering_stop(struct uct *u);
35 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
38 /* Default number of simulations to perform per move.
39 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
40 #define MC_GAMES 80000
41 #define MC_GAMELEN MAX_GAMELEN
42 static const struct time_info default_ti = {
43 .period = TT_MOVE,
44 .dim = TD_GAMES,
45 .len = { .games = MC_GAMES },
48 /* How big proportion of ownermap counts must be of one color to consider
49 * the point sure. */
50 #define GJ_THRES 0.8
51 /* How many games to consider at minimum before judging groups. */
52 #define GJ_MINGAMES 500
54 /* How often to inspect the tree from the main thread to check for playout
55 * stop, progress reports, etc. (in seconds) */
56 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
58 /* Once per how many simulations (per thread) to show a progress report line. */
59 #define TREE_SIMPROGRESS_INTERVAL 10000
61 /* When terminating uct_search() early, the safety margin to add to the
62 * remaining playout number estimate when deciding whether the result can
63 * still change. */
64 #define PLAYOUT_DELTA_SAFEMARGIN 1000
67 static void
68 setup_state(struct uct *u, struct board *b, enum stone color)
70 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
71 if (u->force_seed)
72 fast_srandom(u->force_seed);
73 if (UDEBUGL(0))
74 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
75 //board_print(b, stderr);
76 if (!u->no_book && b->moves == 0) {
77 assert(color == S_BLACK);
78 tree_load(u->t, b);
82 static void
83 reset_state(struct uct *u)
85 assert(u->t);
86 tree_done(u->t); u->t = NULL;
89 static void
90 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
92 if (u->t->use_extra_komi && u->dynkomi->permove)
93 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
96 static void
97 prepare_move(struct engine *e, struct board *b, enum stone color)
99 struct uct *u = e->data;
101 if (u->t) {
102 /* Verify that we have sane state. */
103 assert(b->es == u);
104 assert(u->t && b->moves);
105 if (color != stone_other(u->t->root_color)) {
106 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
107 color, u->t->root_color);
108 exit(1);
111 } else {
112 /* We need fresh state. */
113 b->es = u;
114 setup_state(u, b, color);
117 u->ownermap.playouts = 0;
118 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
121 static void
122 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
124 struct group_judgement gj;
125 gj.thres = GJ_THRES;
126 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
127 board_ownermap_judge_group(b, &u->ownermap, &gj);
128 groups_of_status(b, &gj, GS_DEAD, mq);
131 bool
132 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
134 if (u->ownermap.playouts < GJ_MINGAMES)
135 return false;
137 struct move_queue mq = { .moves = 0 };
138 if (!pass_all_alive)
139 dead_group_list(u, b, &mq);
140 return pass_is_safe(b, color, &mq);
143 /* This function is called only when running as slave in the distributed version. */
144 static enum parse_code
145 uct_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
147 struct uct *u = e->data;
149 /* Force resending the whole command history if we are out of sync
150 * but do it only once, not if already getting the history. */
151 if ((move_number(id) != b->moves || !b->size)
152 && !reply_disabled(id) && !is_reset(cmd)) {
153 if (UDEBUGL(0))
154 fprintf(stderr, "Out of sync, id %d, move %d\n", id, b->moves);
155 static char buf[128];
156 snprintf(buf, sizeof(buf), "out of sync, move %d expected", b->moves);
157 *reply = buf;
158 return P_DONE_ERROR;
160 return reply_disabled(id) ? P_NOREPLY : P_OK;
163 static void
164 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
166 struct uct *u = board->es;
167 assert(u);
168 const char chr[] = ":XO,"; // dame, black, white, unclear
169 const char chm[] = ":xo,";
170 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
171 if (ch == ',') { // less precise estimate then?
172 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
174 fprintf(f, "%c ", ch);
177 static char *
178 uct_notify_play(struct engine *e, struct board *b, struct move *m)
180 struct uct *u = e->data;
181 if (!u->t) {
182 /* No state, create one - this is probably game beginning
183 * and we need to load the opening book right now. */
184 prepare_move(e, b, m->color);
185 assert(u->t);
188 /* Stop pondering, required by tree_promote_at() */
189 uct_pondering_stop(u);
191 if (is_resign(m->coord)) {
192 /* Reset state. */
193 reset_state(u);
194 return NULL;
197 /* Promote node of the appropriate move to the tree root. */
198 assert(u->t->root);
199 if (!tree_promote_at(u->t, b, m->coord)) {
200 if (UDEBUGL(0))
201 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
202 reset_state(u);
203 return NULL;
206 /* If we are a slave in a distributed engine, start pondering once
207 * we know which move we actually played. See uct_genmove() about
208 * the check for pass. */
209 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
210 uct_pondering_start(u, b, u->t, stone_other(m->color));
212 return NULL;
215 static char *
216 uct_chat(struct engine *e, struct board *b, char *cmd)
218 struct uct *u = e->data;
219 static char reply[1024];
221 cmd += strspn(cmd, " \n\t");
222 if (!strncasecmp(cmd, "winrate", 7)) {
223 if (!u->t)
224 return "no game context (yet?)";
225 enum stone color = u->t->root_color;
226 struct tree_node *n = u->t->root;
227 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
228 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
229 tree_node_get_value(u->t, -1, n->u.value) * 100);
230 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
231 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
232 u->t->extra_komi);
234 strcat(reply, ".");
235 return reply;
237 return NULL;
240 static void
241 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
243 struct uct *u = e->data;
245 /* This means the game is probably over, no use pondering on. */
246 uct_pondering_stop(u);
248 if (u->pass_all_alive)
249 return; // no dead groups
251 bool mock_state = false;
253 if (!u->t) {
254 /* No state, but we cannot just back out - we might
255 * have passed earlier, only assuming some stones are
256 * dead, and then re-connected, only to lose counting
257 * when all stones are assumed alive. */
258 /* Mock up some state and seed the ownermap by few
259 * simulations. */
260 prepare_move(e, b, S_BLACK); assert(u->t);
261 for (int i = 0; i < GJ_MINGAMES; i++)
262 uct_playout(u, b, S_BLACK, u->t);
263 mock_state = true;
266 dead_group_list(u, b, mq);
268 if (mock_state) {
269 /* Clean up the mock state in case we will receive
270 * a genmove; we could get a non-alternating-move
271 * error from prepare_move() in that case otherwise. */
272 reset_state(u);
276 static void
277 playout_policy_done(struct playout_policy *p)
279 if (p->done) p->done(p);
280 if (p->data) free(p->data);
281 free(p);
284 static void
285 uct_done(struct engine *e)
287 /* This is called on engine reset, especially when clear_board
288 * is received and new game should begin. */
289 struct uct *u = e->data;
290 uct_pondering_stop(u);
291 if (u->t) reset_state(u);
292 free(u->ownermap.map);
294 free(u->policy);
295 free(u->random_policy);
296 playout_policy_done(u->playout);
297 uct_prior_done(u->prior);
301 /* Pachi threading structure (if uct_playouts_parallel() is used):
303 * main thread
304 * | main(), GTP communication, ...
305 * | starts and stops the search managed by thread_manager
307 * thread_manager
308 * | spawns and collects worker threads
310 * worker0
311 * worker1
312 * ...
313 * workerK
314 * uct_playouts() loop, doing descend-playout until uct_halt
316 * Another way to look at it is by functions (lines denote thread boundaries):
318 * | uct_genmove()
319 * | uct_search() (uct_search_start() .. uct_search_stop())
320 * | -----------------------
321 * | spawn_thread_manager()
322 * | -----------------------
323 * | spawn_worker()
324 * V uct_playouts() */
326 /* Set in thread manager in case the workers should stop. */
327 volatile sig_atomic_t uct_halt = 0;
328 /* ID of the running worker thread. */
329 __thread int thread_id = -1;
330 /* ID of the thread manager. */
331 static pthread_t thread_manager;
332 static bool thread_manager_running;
334 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
335 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
336 static volatile int finish_thread;
337 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
339 struct spawn_ctx {
340 int tid;
341 struct uct *u;
342 struct board *b;
343 enum stone color;
344 struct tree *t;
345 unsigned long seed;
346 int games;
349 static void *
350 spawn_worker(void *ctx_)
352 struct spawn_ctx *ctx = ctx_;
353 /* Setup */
354 fast_srandom(ctx->seed);
355 thread_id = ctx->tid;
356 /* Run */
357 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
358 /* Finish */
359 pthread_mutex_lock(&finish_serializer);
360 pthread_mutex_lock(&finish_mutex);
361 finish_thread = ctx->tid;
362 pthread_cond_signal(&finish_cond);
363 pthread_mutex_unlock(&finish_mutex);
364 return ctx;
367 /* Thread manager, controlling worker threads. It must be called with
368 * finish_mutex lock held, but it will unlock it itself before exiting;
369 * this is necessary to be completely deadlock-free. */
370 /* The finish_cond can be signalled for it to stop; in that case,
371 * the caller should set finish_thread = -1. */
372 /* After it is started, it will update mctx->t to point at some tree
373 * used for the actual search (matters only for TM_ROOT), on return
374 * it will set mctx->games to the number of performed simulations. */
375 static void *
376 spawn_thread_manager(void *ctx_)
378 /* In thread_manager, we use only some of the ctx fields. */
379 struct spawn_ctx *mctx = ctx_;
380 struct uct *u = mctx->u;
381 struct tree *t = mctx->t;
382 bool shared_tree = u->parallel_tree;
383 fast_srandom(mctx->seed);
385 int played_games = 0;
386 pthread_t threads[u->threads];
387 int joined = 0;
389 uct_halt = 0;
391 /* Garbage collect the tree by preference when pondering. */
392 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
393 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
394 t->root = tree_garbage_collect(t, temp_size, t->root);
397 /* Spawn threads... */
398 for (int ti = 0; ti < u->threads; ti++) {
399 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
400 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
401 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
402 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
403 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
404 if (UDEBUGL(3))
405 fprintf(stderr, "Spawned worker %d\n", ti);
408 /* ...and collect them back: */
409 while (joined < u->threads) {
410 /* Wait for some thread to finish... */
411 pthread_cond_wait(&finish_cond, &finish_mutex);
412 if (finish_thread < 0) {
413 /* Stop-by-caller. Tell the workers to wrap up. */
414 uct_halt = 1;
415 continue;
417 /* ...and gather its remnants. */
418 struct spawn_ctx *ctx;
419 pthread_join(threads[finish_thread], (void **) &ctx);
420 played_games += ctx->games;
421 joined++;
422 if (!shared_tree) {
423 if (ctx->t == mctx->t) mctx->t = t;
424 tree_merge(t, ctx->t);
425 tree_done(ctx->t);
427 free(ctx);
428 if (UDEBUGL(3))
429 fprintf(stderr, "Joined worker %d\n", finish_thread);
430 pthread_mutex_unlock(&finish_serializer);
433 pthread_mutex_unlock(&finish_mutex);
435 if (!shared_tree)
436 tree_normalize(mctx->t, u->threads);
438 mctx->games = played_games;
439 return mctx;
442 static struct spawn_ctx *
443 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
445 assert(u->threads > 0);
446 assert(!thread_manager_running);
448 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
449 static struct spawn_ctx mctx; mctx = ctx;
450 pthread_mutex_lock(&finish_mutex);
451 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
452 thread_manager_running = true;
453 return &mctx;
456 static struct spawn_ctx *
457 uct_search_stop(void)
459 assert(thread_manager_running);
461 /* Signal thread manager to stop the workers. */
462 pthread_mutex_lock(&finish_mutex);
463 finish_thread = -1;
464 pthread_cond_signal(&finish_cond);
465 pthread_mutex_unlock(&finish_mutex);
467 /* Collect the thread manager. */
468 struct spawn_ctx *pctx;
469 thread_manager_running = false;
470 pthread_join(thread_manager, (void **) &pctx);
471 return pctx;
475 /* Determine whether we should terminate the search early. */
476 static bool
477 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
478 struct time_info *ti, struct time_stop *stop,
479 struct tree_node *best, struct tree_node *best2,
480 int base_playouts, int i)
482 /* Always use at least half the desired time. It is silly
483 * to lose a won game because we played a bad move in 0.1s. */
484 double elapsed = 0;
485 if (ti->dim == TD_WALLTIME) {
486 elapsed = time_now() - ti->len.t.timer_start;
487 if (elapsed < 0.5 * stop->desired.time) return false;
490 /* Early break in won situation. */
491 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
492 return true;
493 /* Earlier break in super-won situation. */
494 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
495 return true;
497 /* Break early if we estimate the second-best move cannot
498 * catch up in assigned time anymore. We use all our time
499 * if we are in byoyomi with single stone remaining in our
500 * period, however - it's better to pre-ponder. */
501 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
502 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
503 double remaining = stop->worst.time - elapsed;
504 double pps = ((double)i - base_playouts) / elapsed;
505 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
506 if (best->u.playouts > best2->u.playouts + estplayouts) {
507 if (UDEBUGL(2))
508 fprintf(stderr, "Early stop, result cannot change: "
509 "best %d, best2 %d, estimated %f simulations to go\n",
510 best->u.playouts, best2->u.playouts, estplayouts);
511 return true;
515 return false;
518 /* Determine whether we should terminate the search later. */
519 static bool
520 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
521 struct time_info *ti, struct time_stop *stop,
522 struct tree_node *best, struct tree_node *best2,
523 struct tree_node *bestr, struct tree_node *winner, int i)
525 if (!best) {
526 if (UDEBUGL(2))
527 fprintf(stderr, "Did not find best move, still trying...\n");
528 return true;
531 /* Do not waste time if we are winning. Spend up to worst time if
532 * we are unsure, but only desired time if we are sure of winning. */
533 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
534 if (ti->dim == TD_WALLTIME && beta > 0) {
535 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
536 double elapsed = time_now() - ti->len.t.timer_start;
537 if (elapsed > good_enough) return false;
540 if (u->best2_ratio > 0) {
541 /* Check best/best2 simulations ratio. If the
542 * two best moves give very similar results,
543 * keep simulating. */
544 if (best2 && best2->u.playouts
545 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
546 if (UDEBUGL(2))
547 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
548 (double)best->u.playouts / best2->u.playouts,
549 u->best2_ratio);
550 return true;
554 if (u->bestr_ratio > 0) {
555 /* Check best, best_best value difference. If the best move
556 * and its best child do not give similar enough results,
557 * keep simulating. */
558 if (bestr && bestr->u.playouts
559 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
560 if (UDEBUGL(2))
561 fprintf(stderr, "Bestr delta %f > threshold %f\n",
562 fabs((double)best->u.value - bestr->u.value),
563 u->bestr_ratio);
564 return true;
568 if (winner && winner != best) {
569 /* Keep simulating if best explored
570 * does not have also highest value. */
571 if (UDEBUGL(2))
572 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
573 coord2sstr(best->coord, t->board),
574 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
575 coord2sstr(winner->coord, t->board),
576 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
577 return true;
580 /* No reason to keep simulating, bye. */
581 return false;
584 /* Run time-limited MCTS search on foreground. */
585 static int
586 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
588 int base_playouts = u->t->root->u.playouts;
589 if (UDEBUGL(2) && base_playouts > 0)
590 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
592 /* Set up time conditions. */
593 if (ti->period == TT_NULL) *ti = default_ti;
594 struct time_stop stop;
595 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
597 /* Number of last dynkomi adjustment. */
598 int last_dynkomi = t->root->u.playouts;
599 /* Number of last game with progress print. */
600 int last_print = t->root->u.playouts;
601 /* Number of simulations to wait before next print. */
602 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
603 /* Printed notification about full memory? */
604 bool print_fullmem = false;
606 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
608 /* The search tree is ctx->t. This is normally == t, but in case of
609 * TM_ROOT, it is one of the trees belonging to the independent
610 * workers. It is important to reference ctx->t directly since the
611 * thread manager will swap the tree pointer asynchronously. */
612 /* XXX: This means TM_ROOT support is suboptimal since single stalled
613 * thread can stall the others in case of limiting the search by game
614 * count. However, TM_ROOT just does not deserve any more extra code
615 * right now. */
617 struct tree_node *best = NULL;
618 struct tree_node *best2 = NULL; // Second-best move.
619 struct tree_node *bestr = NULL; // best's best child.
620 struct tree_node *winner = NULL;
622 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
624 /* Now, just periodically poll the search tree. */
625 while (1) {
626 time_sleep(busywait_interval);
627 /* busywait_interval should never be less than desired time, or the
628 * time control is broken. But if it happens to be less, we still search
629 * at least 100ms otherwise the move is completely random. */
631 int i = ctx->t->root->u.playouts;
633 /* Adjust dynkomi? */
634 if (ctx->t->use_extra_komi && u->dynkomi->permove
635 && u->dynkomi_interval
636 && i > last_dynkomi + u->dynkomi_interval) {
637 float old_dynkomi = ctx->t->extra_komi;
638 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
639 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
640 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
643 /* Print progress? */
644 if (i - last_print > print_interval) {
645 last_print += print_interval; // keep the numbers tidy
646 uct_progress_status(u, ctx->t, color, last_print);
648 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
649 if (UDEBUGL(2))
650 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
651 print_fullmem = true;
654 /* Never consider stopping if we played too few simulations.
655 * Maybe we risk losing on time when playing in super-extreme
656 * time pressure but the tree is going to be just too messed
657 * up otherwise - we might even play invalid suicides or pass
658 * when we mustn't. */
659 if (i < GJ_MINGAMES)
660 continue;
662 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
663 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
665 /* Possibly stop search early if it's no use to try on. */
666 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
667 break;
669 /* Check against time settings. */
670 bool desired_done = false;
671 if (ti->dim == TD_WALLTIME) {
672 double elapsed = time_now() - ti->len.t.timer_start;
673 if (elapsed > stop.worst.time) break;
674 desired_done = elapsed > stop.desired.time;
676 } else { assert(ti->dim == TD_GAMES);
677 if (i > stop.worst.playouts) break;
678 desired_done = i > stop.desired.playouts;
681 /* We want to stop simulating, but are willing to keep trying
682 * if we aren't completely sure about the winner yet. */
683 if (desired_done) {
684 if (u->policy->winner && u->policy->evaluate) {
685 struct uct_descent descent = { .node = ctx->t->root };
686 u->policy->winner(u->policy, ctx->t, &descent);
687 winner = descent.node;
689 if (best)
690 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
691 if (!uct_search_keep_looking(u, ctx->t, b, ti, &stop, best, best2, bestr, winner, i))
692 break;
695 /* TODO: Early break if best->variance goes under threshold and we already
696 * have enough playouts (possibly thanks to book or to pondering)? */
699 ctx = uct_search_stop();
701 if (UDEBUGL(2))
702 tree_dump(t, u->dumpthres);
703 if (UDEBUGL(0))
704 uct_progress_status(u, t, color, ctx->games);
706 return ctx->games;
710 /* Start pondering background with @color to play. */
711 static void
712 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
714 if (UDEBUGL(1))
715 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
716 u->pondering = true;
718 /* We need a local board copy to ponder upon. */
719 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
721 /* *b0 did not have the genmove'd move played yet. */
722 struct move m = { t->root->coord, t->root_color };
723 int res = board_play(b, &m);
724 assert(res >= 0);
725 setup_dynkomi(u, b, stone_other(m.color));
727 /* Start MCTS manager thread "headless". */
728 uct_search_start(u, b, color, t);
731 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
732 static void
733 uct_pondering_stop(struct uct *u)
735 u->pondering = false;
736 if (!thread_manager_running)
737 return;
739 /* Stop the thread manager. */
740 struct spawn_ctx *ctx = uct_search_stop();
741 if (UDEBUGL(1)) {
742 fprintf(stderr, "(pondering) ");
743 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
745 free(ctx->b);
749 static coord_t *
750 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
752 double start_time = time_now();
753 struct uct *u = e->data;
755 if (b->superko_violation) {
756 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
757 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
758 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
759 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
760 b->superko_violation = false;
763 /* Seed the tree. */
764 uct_pondering_stop(u);
765 prepare_move(e, b, color);
766 assert(u->t);
767 u->my_color = color;
769 /* How to decide whether to use dynkomi in this game? Since we use
770 * pondering, it's not simple "who-to-play" matter. Decide based on
771 * the last genmove issued. */
772 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
773 setup_dynkomi(u, b, color);
775 /* Make pessimistic assumption about komi for Japanese rules to
776 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
777 * The rules usually give the same winner if the integer part of komi
778 * is odd so we adjust the komi only if it is even (for a board of
779 * odd size). We are not trying to get an exact evaluation for rare
780 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html
781 * TODO: Support the kgs-rules command once available. */
782 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
783 b->komi += (color == S_BLACK ? 1.0 : -1.0);
784 if (UDEBUGL(0))
785 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
786 b->komi);
789 int base_playouts = u->t->root->u.playouts;
790 /* Perform the Monte Carlo Tree Search! */
791 int played_games = uct_search(u, b, ti, color, u->t);
793 /* Choose the best move from the tree. */
794 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
795 if (!best) {
796 if (!u->slave) reset_state(u);
797 return coord_copy(pass);
799 if (UDEBUGL(1))
800 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
801 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
802 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
803 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
804 u->t->extra_komi);
806 /* Do not resign if we're so short of time that evaluation of best
807 * move is completely unreliable, we might be winning actually.
808 * In this case best is almost random but still better than resign.
809 * Also do not resign if we are getting bad results while actually
810 * giving away extra komi points (dynkomi). */
811 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
812 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
813 && u->t->extra_komi <= 1 /* XXX we assume dynamic komi == we are black */) {
814 if (!u->slave) reset_state(u);
815 return coord_copy(resign);
818 /* If the opponent just passed and we win counting, always
819 * pass as well. */
820 if (b->moves > 1 && is_pass(b->last_move.coord)) {
821 /* Make sure enough playouts are simulated. */
822 while (u->ownermap.playouts < GJ_MINGAMES)
823 uct_playout(u, b, color, u->t);
824 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
825 if (UDEBUGL(0))
826 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
827 best->coord = pass;
831 /* If we are a slave in the distributed engine, we'll soon get
832 * a "play" command later telling us which move was chosen,
833 * and pondering now will not gain much. */
834 if (!u->slave) {
835 tree_promote_node(u->t, &best);
837 /* After a pass, pondering is harmful for two reasons:
838 * (i) We might keep pondering even when the game is over.
839 * Of course this is the case for opponent resign as well.
840 * (ii) More importantly, the ownermap will get skewed since
841 * the UCT will start cutting off any playouts. */
842 if (u->pondering_opt && !is_pass(best->coord)) {
843 uct_pondering_start(u, b, u->t, stone_other(color));
846 if (UDEBUGL(2)) {
847 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
848 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
849 time, (int)(played_games/time), (int)(played_games/time/u->threads));
851 return coord_copy(best->coord);
855 static char *
856 uct_genmoves(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
858 struct uct *u = e->data;
859 assert(u->slave);
861 coord_t *c = uct_genmove(e, b, ti, color, pass_all_alive);
863 /* Return a buffer with one line "total_playouts threads" then a list of lines
864 * "coord playouts value". Keep this code in sync with select_best_move(). */
865 static char reply[10240];
866 char *r = reply;
867 char *end = reply + sizeof(reply);
868 struct tree_node *root = u->t->root;
869 r += snprintf(r, end - r, "%d %d", root->u.playouts, u->threads);
870 int min_playouts = root->u.playouts / 100;
872 // Give a large weight to pass or resign, but still allow other moves.
873 if (is_pass(*c) || is_resign(*c))
874 r += snprintf(r, end - r, "\n%s %d %.1f", coord2sstr(*c, b), root->u.playouts,
875 (float)is_pass(*c));
876 coord_done(c);
878 for (struct tree_node *ni = root->children; ni; ni = ni->sibling) {
879 if (ni->u.playouts <= min_playouts
880 || ni->hints & TREE_HINT_INVALID
881 || is_pass(ni->coord))
882 continue;
883 char *coord = coord2sstr(ni->coord, b);
884 // We return the values as stored in the tree, so from black's view.
885 r += snprintf(r, end - r, "\n%s %d %.7f", coord, ni->u.playouts, ni->u.value);
887 return reply;
891 bool
892 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
894 struct uct *u = e->data;
895 if (!u->t) prepare_move(e, b, color);
896 assert(u->t);
898 if (ti->dim == TD_GAMES) {
899 /* Don't count in games that already went into the book. */
900 ti->len.games += u->t->root->u.playouts;
902 uct_search(u, b, ti, color, u->t);
904 assert(ti->dim == TD_GAMES);
905 tree_save(u->t, b, ti->len.games / 100);
907 return true;
910 void
911 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
913 struct uct *u = e->data;
914 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
915 tree_load(t, b);
916 tree_dump(t, 0);
917 tree_done(t);
921 struct uct *
922 uct_state_init(char *arg, struct board *b)
924 struct uct *u = calloc(1, sizeof(struct uct));
925 bool using_elo = false;
927 u->debug_level = debug_level;
928 u->gamelen = MC_GAMELEN;
929 u->mercymin = 0;
930 u->expand_p = 2;
931 u->dumpthres = 1000;
932 u->playout_amaf = true;
933 u->playout_amaf_nakade = false;
934 u->amaf_prior = false;
935 u->max_tree_size = 3072ULL * 1048576;
937 u->dynkomi_mask = S_BLACK;
939 u->threads = 1;
940 u->thread_model = TM_TREEVL;
941 u->parallel_tree = true;
942 u->virtual_loss = true;
944 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
945 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
946 u->bestr_ratio = 0.02;
947 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
948 // TODO: Further tuning and experiments with better time allocation schemes.
949 u->best2_ratio = 2.5;
951 u->val_scale = 0.04; u->val_points = 40;
953 u->tenuki_d = 4;
954 u->local_tree_aging = 2;
956 if (arg) {
957 char *optspec, *next = arg;
958 while (*next) {
959 optspec = next;
960 next += strcspn(next, ",");
961 if (*next) { *next++ = 0; } else { *next = 0; }
963 char *optname = optspec;
964 char *optval = strchr(optspec, '=');
965 if (optval) *optval++ = 0;
967 if (!strcasecmp(optname, "debug")) {
968 if (optval)
969 u->debug_level = atoi(optval);
970 else
971 u->debug_level++;
972 } else if (!strcasecmp(optname, "mercy") && optval) {
973 /* Minimal difference of black/white captures
974 * to stop playout - "Mercy Rule". Speeds up
975 * hopeless playouts at the expense of some
976 * accuracy. */
977 u->mercymin = atoi(optval);
978 } else if (!strcasecmp(optname, "gamelen") && optval) {
979 u->gamelen = atoi(optval);
980 } else if (!strcasecmp(optname, "expand_p") && optval) {
981 u->expand_p = atoi(optval);
982 } else if (!strcasecmp(optname, "dumpthres") && optval) {
983 u->dumpthres = atoi(optval);
984 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
985 /* If set, prolong simulating while
986 * first_best/second_best playouts ratio
987 * is less than best2_ratio. */
988 u->best2_ratio = atof(optval);
989 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
990 /* If set, prolong simulating while
991 * best,best_best_child values delta
992 * is more than bestr_ratio. */
993 u->bestr_ratio = atof(optval);
994 } else if (!strcasecmp(optname, "playout_amaf")) {
995 /* Whether to include random playout moves in
996 * AMAF as well. (Otherwise, only tree moves
997 * are included in AMAF. Of course makes sense
998 * only in connection with an AMAF policy.) */
999 /* with-without: 55.5% (+-4.1) */
1000 if (optval && *optval == '0')
1001 u->playout_amaf = false;
1002 else
1003 u->playout_amaf = true;
1004 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
1005 /* Whether to include nakade moves from playouts
1006 * in the AMAF statistics; this tends to nullify
1007 * the playout_amaf effect by adding too much
1008 * noise. */
1009 if (optval && *optval == '0')
1010 u->playout_amaf_nakade = false;
1011 else
1012 u->playout_amaf_nakade = true;
1013 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
1014 /* Keep only first N% of playout stage AMAF
1015 * information. */
1016 u->playout_amaf_cutoff = atoi(optval);
1017 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
1018 char *policyarg = strchr(optval, ':');
1019 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
1020 if (policyarg)
1021 *policyarg++ = 0;
1022 if (!strcasecmp(optval, "ucb1")) {
1023 *p = policy_ucb1_init(u, policyarg);
1024 } else if (!strcasecmp(optval, "ucb1amaf")) {
1025 *p = policy_ucb1amaf_init(u, policyarg);
1026 } else {
1027 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
1028 exit(1);
1030 } else if (!strcasecmp(optname, "playout") && optval) {
1031 char *playoutarg = strchr(optval, ':');
1032 if (playoutarg)
1033 *playoutarg++ = 0;
1034 if (!strcasecmp(optval, "moggy")) {
1035 u->playout = playout_moggy_init(playoutarg, b);
1036 } else if (!strcasecmp(optval, "light")) {
1037 u->playout = playout_light_init(playoutarg, b);
1038 } else if (!strcasecmp(optval, "elo")) {
1039 u->playout = playout_elo_init(playoutarg, b);
1040 using_elo = true;
1041 } else {
1042 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1043 exit(1);
1045 } else if (!strcasecmp(optname, "prior") && optval) {
1046 u->prior = uct_prior_init(optval, b);
1047 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1048 u->amaf_prior = atoi(optval);
1049 } else if (!strcasecmp(optname, "threads") && optval) {
1050 /* By default, Pachi will run with only single
1051 * tree search thread! */
1052 u->threads = atoi(optval);
1053 } else if (!strcasecmp(optname, "thread_model") && optval) {
1054 if (!strcasecmp(optval, "root")) {
1055 /* Root parallelization - each thread
1056 * does independent search, trees are
1057 * merged at the end. */
1058 u->thread_model = TM_ROOT;
1059 u->parallel_tree = false;
1060 u->virtual_loss = false;
1061 } else if (!strcasecmp(optval, "tree")) {
1062 /* Tree parallelization - all threads
1063 * grind on the same tree. */
1064 u->thread_model = TM_TREE;
1065 u->parallel_tree = true;
1066 u->virtual_loss = false;
1067 } else if (!strcasecmp(optval, "treevl")) {
1068 /* Tree parallelization, but also
1069 * with virtual losses - this discou-
1070 * rages most threads choosing the
1071 * same tree branches to read. */
1072 u->thread_model = TM_TREEVL;
1073 u->parallel_tree = true;
1074 u->virtual_loss = true;
1075 } else {
1076 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1077 exit(1);
1079 } else if (!strcasecmp(optname, "pondering")) {
1080 /* Keep searching even during opponent's turn. */
1081 u->pondering_opt = !optval || atoi(optval);
1082 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1083 /* At the very beginning it's not worth thinking
1084 * too long because the playout evaluations are
1085 * very noisy. So gradually increase the thinking
1086 * time up to maximum when fuseki_end percent
1087 * of the board has been played.
1088 * This only applies if we are not in byoyomi. */
1089 u->fuseki_end = atoi(optval);
1090 } else if (!strcasecmp(optname, "yose_start") && optval) {
1091 /* When yose_start percent of the board has been
1092 * played, or if we are in byoyomi, stop spending
1093 * more time and spread the remaining time
1094 * uniformly.
1095 * Between fuseki_end and yose_start, we spend
1096 * a constant proportion of the remaining time
1097 * on each move. (yose_start should actually
1098 * be much earlier than when real yose start,
1099 * but "yose" is a good short name to convey
1100 * the idea.) */
1101 u->yose_start = atoi(optval);
1102 } else if (!strcasecmp(optname, "force_seed") && optval) {
1103 u->force_seed = atoi(optval);
1104 } else if (!strcasecmp(optname, "no_book")) {
1105 u->no_book = true;
1106 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1107 /* Dynamic komi approach; there are multiple
1108 * ways to adjust komi dynamically throughout
1109 * play. We currently support two: */
1110 char *dynkomiarg = strchr(optval, ':');
1111 if (dynkomiarg)
1112 *dynkomiarg++ = 0;
1113 if (!strcasecmp(optval, "none")) {
1114 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1115 } else if (!strcasecmp(optval, "linear")) {
1116 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1117 } else if (!strcasecmp(optval, "adaptive")) {
1118 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1119 } else {
1120 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1121 exit(1);
1123 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1124 /* Bitmask of colors the player must be
1125 * for dynkomi be applied; you may want
1126 * to use dynkomi_mask=3 to allow dynkomi
1127 * even in games where Pachi is white. */
1128 u->dynkomi_mask = atoi(optval);
1129 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1130 /* If non-zero, re-adjust dynamic komi
1131 * throughout a single genmove reading,
1132 * roughly every N simulations. */
1133 u->dynkomi_interval = atoi(optval);
1134 } else if (!strcasecmp(optname, "val_scale") && optval) {
1135 /* How much of the game result value should be
1136 * influenced by win size. Zero means it isn't. */
1137 u->val_scale = atof(optval);
1138 } else if (!strcasecmp(optname, "val_points") && optval) {
1139 /* Maximum size of win to be scaled into game
1140 * result value. Zero means boardsize^2. */
1141 u->val_points = atoi(optval) * 2; // result values are doubled
1142 } else if (!strcasecmp(optname, "val_extra")) {
1143 /* If false, the score coefficient will be simply
1144 * added to the value, instead of scaling the result
1145 * coefficient because of it. */
1146 u->val_extra = !optval || atoi(optval);
1147 } else if (!strcasecmp(optname, "local_tree") && optval) {
1148 /* Whether to bias exploration by local tree values
1149 * (must be supported by the used policy).
1150 * 0: Don't.
1151 * 1: Do, value = result.
1152 * Try to temper the result:
1153 * 2: Do, value = 0.5+(result-expected)/2.
1154 * 3: Do, value = 0.5+bzz((result-expected)^2).
1155 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1156 u->local_tree = atoi(optval);
1157 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1158 /* Tenuki distance at which to break the local tree. */
1159 u->tenuki_d = atoi(optval);
1160 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1161 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1162 exit(1);
1164 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1165 /* How much to reduce local tree values between moves. */
1166 u->local_tree_aging = atof(optval);
1167 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1168 /* By default, only complete sequences are stored
1169 * in the local tree. If this is on, also
1170 * subsequences starting at each move are stored. */
1171 u->local_tree_allseq = !optval || atoi(optval);
1172 } else if (!strcasecmp(optname, "local_tree_playout")) {
1173 /* Whether to adjust ELO playout probability
1174 * distributions according to matched localtree
1175 * information. */
1176 u->local_tree_playout = !optval || atoi(optval);
1177 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1178 /* By default, when we have no sequence move
1179 * to suggest in-playout, we give up. If this
1180 * is on, we make probability distribution from
1181 * sequences first moves instead. */
1182 u->local_tree_pseqroot = !optval || atoi(optval);
1183 } else if (!strcasecmp(optname, "pass_all_alive")) {
1184 /* Whether to consider all stones alive at the game
1185 * end instead of marking dead groupd. */
1186 u->pass_all_alive = !optval || atoi(optval);
1187 } else if (!strcasecmp(optname, "territory_scoring")) {
1188 /* Use territory scoring (default is area scoring).
1189 * An explicit kgs-rules command overrides this. */
1190 u->territory_scoring = !optval || atoi(optval);
1191 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1192 /* If specified (N), with probability 1/N, random_policy policy
1193 * descend is used instead of main policy descend; useful
1194 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1195 * choices sometimes, you can fall back to e.g.
1196 * random_policy=UCB1. */
1197 u->random_policy_chance = atoi(optval);
1198 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1199 /* Maximum amount of memory [MiB] consumed by the move tree.
1200 * For fast_alloc it includes the temp tree used for pruning.
1201 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1202 * this limits size of only one of the trees, not all of them
1203 * together. */
1204 u->max_tree_size = atol(optval) * 1048576;
1205 } else if (!strcasecmp(optname, "fast_alloc")) {
1206 u->fast_alloc = !optval || atoi(optval);
1207 } else if (!strcasecmp(optname, "slave")) {
1208 /* Act as slave for the distributed engine. */
1209 u->slave = !optval || atoi(optval);
1210 } else if (!strcasecmp(optname, "banner") && optval) {
1211 /* Additional banner string. This must come as the
1212 * last engine parameter. */
1213 if (*next) *--next = ',';
1214 u->banner = strdup(optval);
1215 break;
1216 } else {
1217 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1218 exit(1);
1223 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1224 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1225 if (!u->policy)
1226 u->policy = policy_ucb1amaf_init(u, NULL);
1228 if (!!u->random_policy_chance ^ !!u->random_policy) {
1229 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1230 exit(1);
1233 if (!u->local_tree) {
1234 /* No ltree aging. */
1235 u->local_tree_aging = 1.0f;
1237 if (!using_elo)
1238 u->local_tree_playout = false;
1240 if (u->fast_alloc && !u->parallel_tree) {
1241 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1242 exit(1);
1244 if (u->fast_alloc)
1245 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1247 if (!u->prior)
1248 u->prior = uct_prior_init(NULL, b);
1250 if (!u->playout)
1251 u->playout = playout_moggy_init(NULL, b);
1252 u->playout->debug_level = u->debug_level;
1254 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1256 if (!u->dynkomi)
1257 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1259 /* Some things remain uninitialized for now - the opening book
1260 * is not loaded and the tree not set up. */
1261 /* This will be initialized in setup_state() at the first move
1262 * received/requested. This is because right now we are not aware
1263 * about any komi or handicap setup and such. */
1265 return u;
1268 struct engine *
1269 engine_uct_init(char *arg, struct board *b)
1271 struct uct *u = uct_state_init(arg, b);
1272 struct engine *e = calloc(1, sizeof(struct engine));
1273 e->name = "UCT Engine";
1274 e->printhook = uct_printhook_ownermap;
1275 e->notify_play = uct_notify_play;
1276 e->chat = uct_chat;
1277 e->genmove = uct_genmove;
1278 e->genmoves = uct_genmoves;
1279 e->dead_group_list = uct_dead_group_list;
1280 e->done = uct_done;
1281 e->data = u;
1282 if (u->slave)
1283 e->notify = uct_notify;
1285 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1286 "if I think I win, I play until you pass. "
1287 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1288 if (!u->banner) u->banner = "";
1289 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1290 sprintf(e->comment, "%s %s", banner, u->banner);
1292 return e;