pattern3_show.pl: Add useful debugging script
[pachi/derm.git] / playout / elo.c
blobd883d107760c927f58c5c9fd105eae1c184a3494
1 /* Playout player based on probability distribution generated over
2 * the available moves. */
4 /* We use the ELO-based (Coulom, 2007) approach, where each board
5 * feature (matched pattern, self-atari, capture, MC owner?, ...)
6 * is pre-assigned "playing strength" (gamma).
8 * Then, the problem of choosing a move is basically a team
9 * competition in ELO terms - each spot is represented by a team
10 * of features appearing there; the team gamma is product of feature
11 * gammas. The team gammas make for a probability distribution of
12 * moves to be played.
14 * We use the general pattern classifier that will find the features
15 * for us, and external datasets that can be harvested from a set
16 * of game records (see the HACKING file for details): patterns.spat
17 * as a dictionary of spatial stone configurations, and patterns.gamma
18 * with strengths of particular features. */
20 #include <assert.h>
21 #include <math.h>
22 #include <stdio.h>
23 #include <stdlib.h>
25 //#define DEBUG
26 #include "board.h"
27 #include "debug.h"
28 #include "fixp.h"
29 #include "pattern.h"
30 #include "patternsp.h"
31 #include "playout.h"
32 #include "playout/elo.h"
33 #include "random.h"
34 #include "tactics.h"
35 #include "uct/prior.h"
37 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
40 /* Note that the context can be shared by multiple threads! */
42 struct patternset {
43 pattern_spec ps;
44 struct pattern_config pc;
45 struct features_gamma *fg;
48 struct elo_policy {
49 bool assess_fastpat;
50 float selfatari;
51 struct patternset choose, assess;
52 playout_elo_callbackp callback; void *callback_data;
54 enum {
55 EAV_TOTAL,
56 EAV_BEST,
57 } assess_eval;
58 enum {
59 EAT_LINEAR,
60 EAT_ATAN,
61 EAT_SIGMOID,
62 } assess_transform;
63 double assess_sigmb;
67 /* This is the core of the policy - initializes and constructs the
68 * probability distribution over the move candidates. */
70 int
71 elo_get_probdist(struct playout_policy *p, struct patternset *ps, struct board *b, enum stone to_play, struct probdist *pd)
73 //struct elo_policy *pp = p->data;
74 int moves = 0;
76 /* First, assign per-point probabilities. */
78 for (int f = 0; f < b->flen; f++) {
79 struct move m = { .coord = b->f[f], .color = to_play };
81 /* Skip pass (for now)? */
82 if (is_pass(m.coord)) {
83 skip_move:
84 probdist_set(pd, m.coord, 0);
85 continue;
87 if (PLDEBUGL(7))
88 fprintf(stderr, "<%d> %s\n", f, coord2sstr(m.coord, b));
90 /* Skip invalid moves. */
91 if (!board_is_valid_move(b, &m))
92 goto skip_move;
94 /* We shall never fill our own single-point eyes. */
95 /* XXX: In some rare situations, this prunes the best move:
96 * Bulk-five nakade with eye at 1-1 point. */
97 if (board_is_one_point_eye(b, m.coord, to_play)) {
98 goto skip_move;
101 moves++;
102 /* Each valid move starts with gamma 1. */
103 double g = 1.f;
105 /* Some easy features: */
106 /* XXX: We just disable them for now since we call the
107 * pattern matcher; you need the gammas file. */
108 #if 0
109 if (is_bad_selfatari(b, to_play, m.coord))
110 g *= pp->selfatari;
111 #endif
113 /* Match pattern features: */
114 struct pattern pat;
115 pattern_match(&ps->pc, ps->ps, &pat, b, &m);
116 for (int i = 0; i < pat.n; i++) {
117 /* Multiply together gammas of all pattern features. */
118 double gamma = feature_gamma(ps->fg, &pat.f[i], NULL);
119 if (PLDEBUGL(7)) {
120 char buf[256] = ""; feature2str(buf, &pat.f[i]);
121 fprintf(stderr, "<%d> %s feat %s gamma %f\n", f, coord2sstr(m.coord, b), buf, gamma);
123 g *= gamma;
126 probdist_set(pd, m.coord, double_to_fixp(g));
127 if (PLDEBUGL(7))
128 fprintf(stderr, "<%d> %s %f (E %f)\n", f, coord2sstr(m.coord, b), fixp_to_double(probdist_one(pd, m.coord)), g);
131 return moves;
135 struct lprobdist {
136 int n;
137 #define LPD_MAX 8
138 coord_t coords[LPD_MAX];
139 fixp_t items[LPD_MAX];
140 fixp_t total;
142 /* Backups of original totals for restoring. */
143 fixp_t btotal;
144 fixp_t browtotals_v[10];
145 int browtotals_i[10];
146 int browtotals_n;
149 #ifdef BOARD_GAMMA
151 static void
152 elo_check_probdist(struct playout_policy *p, struct board *b, enum stone to_play, struct probdist *pd, int *ignores, struct lprobdist *lpd, coord_t lc)
154 #if 0
155 #define PROBDIST_EPSILON double_to_fixp(0.01)
156 struct elo_policy *pp = p->data;
157 if (pd->total == 0)
158 return;
160 /* Compare to the manually created distribution. */
161 /* XXX: This is now broken if callback is used. */
163 probdist_alloca(pdx, b);
164 elo_get_probdist(p, &pp->choose, b, to_play, &pdx);
165 for (int i = 0; i < b->flen; i++) {
166 coord_t c = b->f[i];
167 if (is_pass(c)) continue;
168 if (c == b->ko.coord) continue;
169 fixp_t val = pd->items[c];
170 if (!is_pass(lc) && coord_is_8adjecent(lc, c, b))
171 for (int j = 0; j < lpd->n; j++)
172 if (lpd->coords[j] == c) {
173 val = lpd->items[j];
174 probdist_mute(&pdx, c);
177 if (abs(pdx.items[c] - val) < PROBDIST_EPSILON)
178 continue;
179 printf("[%s %d] manual %f board %f (base %f) ", coord2sstr(c, b), b->pat3[c], fixp_to_double(pdx.items[c]), fixp_to_double(val), fixp_to_double(pd->items[c]));
180 board_gamma_update(b, c, to_play);
181 printf("plainboard %f\n", fixp_to_double(pd->items[c]));
182 assert(0);
184 for (int r = 0; r < board_size(b); r++) {
185 if (abs(pdx.rowtotals[r] - pd->rowtotals[r]) < PROBDIST_EPSILON)
186 continue;
187 fprintf(stderr, "row %d: manual %f board %f\n", r, fixp_to_double(pdx.rowtotals[r]), fixp_to_double(pd->rowtotals[r]));
188 assert(0);
190 assert(abs(pdx.total - pd->total) < PROBDIST_EPSILON);
191 #undef PROBDIST_EPSILON
192 #endif
195 coord_t
196 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
198 struct elo_policy *pp = p->data;
199 /* The base board probdist. */
200 struct probdist *pd = &b->prob[to_play - 1];
201 /* The list of moves we do not consider in pd. */
202 int ignores[10]; int ignores_n = 0;
203 /* The list of local moves; we consider these separately. */
204 struct lprobdist lpd = { .n = 0, .total = 0, .btotal = pd->total, .browtotals_n = 0 };
206 /* The engine might want to adjust our probdist. */
207 if (pp->callback)
208 pp->callback(pp->callback_data, b, to_play, pd);
210 if (PLDEBUGL(5)) {
211 fprintf(stderr, "pd total pre %f lpd %f\n", fixp_to_double(pd->total), fixp_to_double(lpd.total));
214 #define ignore_move(c_) do { \
215 ignores[ignores_n++] = c_; \
216 if (ignores_n > 1 && ignores[ignores_n - 1] < ignores[ignores_n - 2]) { \
217 /* Keep ignores[] sorted. We abuse the fact that we know \
218 * only one item can be out-of-order. */ \
219 coord_t cc = ignores[ignores_n - 2]; \
220 ignores[ignores_n - 2] = ignores[ignores_n - 1]; \
221 ignores[ignores_n - 1] = cc; \
223 int rowi = coord_y(c_, pd->b); \
224 lpd.browtotals_i[lpd.browtotals_n] = rowi; \
225 lpd.browtotals_v[lpd.browtotals_n++] = pd->rowtotals[rowi]; \
226 probdist_mute(pd, c_); \
227 if (PLDEBUGL(6)) \
228 fprintf(stderr, "ignored move %s(%f) => tot pd %f lpd %f\n", coord2sstr(c_, pd->b), fixp_to_double(pd->items[c_]), fixp_to_double(pd->total), fixp_to_double(lpd.total)); \
229 } while (0)
231 /* Make sure ko-prohibited move does not get picked. */
232 if (!is_pass(b->ko.coord)) {
233 assert(b->ko.color == to_play);
234 ignore_move(b->ko.coord);
237 /* Contiguity detection. */
238 if (!is_pass(b->last_move.coord)) {
239 foreach_8neighbor(b, b->last_move.coord) {
240 if (c == b->ko.coord)
241 continue; // already ignored
242 if (board_at(b, c) != S_NONE) {
243 assert(probdist_one(pd, c) == 0);
244 continue;
246 ignore_move(c);
248 fixp_t val = double_to_fixp(fixp_to_double(probdist_one(pd, c)) * b->gamma->gamma[FEAT_CONTIGUITY][1]);
249 lpd.coords[lpd.n] = c;
250 lpd.items[lpd.n++] = val;
251 lpd.total += val;
252 } foreach_8neighbor_end;
255 ignores[ignores_n] = pass;
256 if (PLDEBUGL(5))
257 fprintf(stderr, "pd total post %f lpd %f\n", fixp_to_double(pd->total), fixp_to_double(lpd.total));
259 /* Verify sanity, possibly. */
260 elo_check_probdist(p, b, to_play, pd, ignores, &lpd, b->last_move.coord);
262 /* Pick a move. */
263 coord_t c = pass;
264 fixp_t stab = fast_irandom(lpd.total + pd->total);
265 if (PLDEBUGL(5))
266 fprintf(stderr, "stab %f / (%f + %f)\n", fixp_to_double(stab), fixp_to_double(lpd.total), fixp_to_double(pd->total));
267 if (stab < lpd.total) {
268 /* Local probdist. */
269 if (PLDEBUGL(6)) {
270 /* Some debug prints. */
271 fixp_t tot = 0;
272 for (int i = 0; i < lpd.n; i++) {
273 tot += lpd.items[i];
274 struct pattern p;
275 struct move m = { .color = to_play, .coord = lpd.coords[i] };
276 if (board_at(b, m.coord) != S_NONE) {
277 assert(lpd.items[i] == 0);
278 continue;
280 pattern_match(&pp->choose.pc, pp->choose.ps, &p, b, &m);
281 char s[256] = ""; pattern2str(s, &p);
282 fprintf(stderr, "coord %s <%f> [tot %f] %s (p3:%d)\n",
283 coord2sstr(lpd.coords[i], b), fixp_to_double(lpd.items[i]),
284 fixp_to_double(tot), s,
285 pattern3_by_spatial(pp->choose.pc.spat_dict, b->pat3[lpd.coords[i]]));
288 for (int i = 0; i < lpd.n; i++) {
289 if (stab <= lpd.items[i]) {
290 c = lpd.coords[i];
291 break;
293 stab -= lpd.items[i];
295 if (is_pass(c)) {
296 fprintf(stderr, "elo: local overstab [%f]\n", fixp_to_double(stab));
297 abort();
300 } else if (pd->total > 0) {
301 /* Global probdist. */
302 /* XXX: We re-stab inside. */
303 c = probdist_pick(pd, ignores);
305 } else {
306 if (PLDEBUGL(5))
307 fprintf(stderr, "ding!\n");
308 c = pass;
311 /* Repair the damage. */
312 if (pp->callback) {
313 /* XXX: Do something less horribly inefficient
314 * than just recomputing the whole pd. */
315 pd->total = 0;
316 for (int i = 0; i < board_size(pd->b); i++)
317 pd->rowtotals[i] = 0;
318 for (int i = 0; i < b->flen; i++) {
319 pd->items[b->f[i]] = 0;
320 board_gamma_update(b, b->f[i], to_play);
322 assert(pd->total == lpd.btotal);
324 } else {
325 pd->total = lpd.btotal;
326 /* If we touched a row multiple times (and we sure will),
327 * the latter value is obsolete; but since we go through
328 * the backups in reverse order, all is good. */
329 for (int j = lpd.browtotals_n - 1; j >= 0; j--)
330 pd->rowtotals[lpd.browtotals_i[j]] = lpd.browtotals_v[j];
332 return c;
335 #else
337 coord_t
338 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
340 struct elo_policy *pp = p->data;
341 probdist_alloca(pd, b);
342 elo_get_probdist(p, &pp->choose, b, to_play, &pd);
343 if (pp->callback)
344 pp->callback(pp->callback_data, b, to_play, &pd);
345 if (pd.total == 0)
346 return pass;
347 int ignores[1] = { pass };
348 coord_t c = probdist_pick(&pd, ignores);
349 return c;
352 #endif
354 void
355 playout_elo_assess(struct playout_policy *p, struct prior_map *map, int games)
357 struct elo_policy *pp = p->data;
358 probdist_alloca(pd, map->b);
360 int moves;
361 moves = elo_get_probdist(p, &pp->assess, map->b, map->to_play, &pd);
363 /* It is a question how to transform the gamma to won games; we use
364 * a naive approach currently, but not sure how well it works. */
365 /* TODO: Try sqrt(p), atan(p)/pi*2. */
367 double pd_best = 0;
368 if (pp->assess_eval == EAV_BEST) {
369 for (int f = 0; f < map->b->flen; f++) {
370 double pd_one = fixp_to_double(probdist_one(&pd, map->b->f[f]));
371 if (pd_one > pd_best)
372 pd_best = pd_one;
375 double pd_total = fixp_to_double(probdist_total(&pd));
377 for (int f = 0; f < map->b->flen; f++) {
378 coord_t c = map->b->f[f];
379 if (!map->consider[c])
380 continue;
382 double pd_one = fixp_to_double(probdist_one(&pd, c));
383 double val = 0;
384 switch (pp->assess_eval) {
385 case EAV_TOTAL:
386 val = pd_one / pd_total;
387 break;
388 case EAV_BEST:
389 val = pd_one / pd_best;
390 break;
391 default:
392 assert(0);
395 switch (pp->assess_transform) {
396 case EAT_LINEAR:
397 val = val;
398 break;
399 case EAT_ATAN:
400 val = atan(val)/M_PI;
401 break;
402 case EAT_SIGMOID:
403 val = 1.0 / (1.0 + exp(-pp->assess_sigmb * (val - 0.5)));
404 break;
405 default:
406 assert(0);
409 add_prior_value(map, c, val, games);
413 void
414 playout_elo_done(struct playout_policy *p)
416 struct elo_policy *pp = p->data;
417 features_gamma_done(pp->choose.fg);
418 features_gamma_done(pp->assess.fg);
422 void
423 playout_elo_callback(struct playout_policy *p, playout_elo_callbackp callback, void *data)
425 struct elo_policy *pp = p->data;
426 pp->callback = callback;
427 pp->callback_data = data;
430 struct playout_policy *
431 playout_elo_init(char *arg, struct board *b)
433 struct playout_policy *p = calloc2(1, sizeof(*p));
434 struct elo_policy *pp = calloc2(1, sizeof(*pp));
435 p->data = pp;
436 p->choose = playout_elo_choose;
437 p->assess = playout_elo_assess;
438 p->done = playout_elo_done;
440 const char *gammafile = features_gamma_filename;
441 pp->assess_sigmb = 10.0;
442 /* Some defaults based on the table in Remi Coulom's paper. */
443 pp->selfatari = 0.06;
445 struct pattern_config pc = DEFAULT_PATTERN_CONFIG;
446 int xspat = -1;
447 bool precise_selfatari = false;
449 if (arg) {
450 char *optspec, *next = arg;
451 while (*next) {
452 optspec = next;
453 next += strcspn(next, ":");
454 if (*next) { *next++ = 0; } else { *next = 0; }
456 char *optname = optspec;
457 char *optval = strchr(optspec, '=');
458 if (optval) *optval++ = 0;
460 if (!strcasecmp(optname, "selfatari") && optval) {
461 pp->selfatari = atof(optval);
462 } else if (!strcasecmp(optname, "precisesa")) {
463 /* Use precise self-atari detection within
464 * fast patterns. */
465 precise_selfatari = !optval || atoi(optval);
466 } else if (!strcasecmp(optname, "gammafile") && optval) {
467 /* patterns.gamma by default. We use this,
468 * and need also ${gammafile}f (e.g.
469 * patterns.gammaf) for fast (MC) features. */
470 gammafile = strdup(optval);
471 } else if (!strcasecmp(optname, "xspat") && optval) {
472 /* xspat==0: don't match spatial features
473 * xspat==1: match *only* spatial features */
474 xspat = atoi(optval);
475 } else if (!strcasecmp(optname, "assess_fastpat")) {
476 /* Use just fast pattern set even for the
477 * node prior value assessment. */
478 pp->assess_fastpat = !optval || atoi(optval);
479 } else if (!strcasecmp(optname, "assess_sigmb") && optval) {
480 pp->assess_sigmb = atof(optval);
481 } else if (!strcasecmp(optname, "assess_eval") && optval) {
482 /* Evaluation method for prior node value
483 * assessment. */
484 if (!strcasecmp(optval, "total")) {
485 /* Proportion prob/totprob. */
486 pp->assess_eval = EAV_TOTAL;
487 } else if (!strcasecmp(optval, "best")) {
488 /* Proportion prob/bestprob. */
489 pp->assess_eval = EAV_BEST;
490 } else {
491 fprintf(stderr, "playout-elo: Invalid eval mode %s\n", optval);
492 exit(1);
494 } else if (!strcasecmp(optname, "assess_transform") && optval) {
495 /* Transformation of evaluation for prior
496 * node value assessment. */
497 if (!strcasecmp(optval, "linear")) {
498 /* No additional transformation. */
499 pp->assess_transform = EAT_LINEAR;
500 } else if (!strcasecmp(optval, "atan")) {
501 /* atan-shape transformation;
502 * pumps up low values. */
503 pp->assess_transform = EAT_ATAN;
504 } else if (!strcasecmp(optval, "sigmoid")) {
505 /* Sigmoid transformation
506 * according to assess_sigmb. */
507 pp->assess_transform = EAT_SIGMOID;
508 } else {
509 fprintf(stderr, "playout-elo: Invalid eval mode %s\n", optval);
510 exit(1);
512 } else {
513 fprintf(stderr, "playout-elo: Invalid policy argument %s or missing value\n", optname);
514 exit(1);
519 pc.spat_dict = spatial_dict_init(false);
521 /* In playouts, we need to operate with much smaller set of features
522 * in order to keep reasonable speed. */
523 /* TODO: Configurable. */ /* TODO: Tune. */
524 pp->choose.pc = FAST_PATTERN_CONFIG;
525 pp->choose.pc.spat_dict = pc.spat_dict;
526 char cgammafile[256]; strcpy(stpcpy(cgammafile, gammafile), "f");
527 pp->choose.fg = features_gamma_init(&pp->choose.pc, cgammafile);
528 memcpy(pp->choose.ps, PATTERN_SPEC_MATCHFAST, sizeof(pattern_spec));
529 for (int i = 0; i < FEAT_MAX; i++)
530 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
531 pp->choose.ps[i] = 0;
532 if (precise_selfatari) {
533 pp->choose.ps[FEAT_SELFATARI] &= ~(1<<PF_SELFATARI_STUPID);
534 pp->choose.ps[FEAT_SELFATARI] |= (1<<PF_SELFATARI_SMART);
536 board_gamma_set(b, pp->choose.fg, precise_selfatari);
538 if (pp->assess_fastpat) {
539 pp->assess = pp->choose;
540 pp->assess.fg = features_gamma_init(&pp->assess.pc, cgammafile);
541 } else {
542 /* More detailed set of features. */
543 pp->assess.pc = pc;
544 pp->assess.fg = features_gamma_init(&pp->assess.pc, gammafile);
545 memcpy(pp->assess.ps, PATTERN_SPEC_MATCHALL, sizeof(pattern_spec));
546 for (int i = 0; i < FEAT_MAX; i++)
547 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
548 pp->assess.ps[i] = 0;
551 return p;