Elo: Fix elo_get_probdist() compilation with DEBUG
[pachi/derm.git] / playout / elo.c
blob43586a615bc3bd609201d9422f43577ac11ae4b1
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 float selfatari;
50 struct patternset choose, assess;
51 playout_elo_callbackp callback; void *callback_data;
55 /* This is the core of the policy - initializes and constructs the
56 * probability distribution over the move candidates. */
58 int
59 elo_get_probdist(struct playout_policy *p, struct patternset *ps, struct board *b, enum stone to_play, struct probdist *pd)
61 //struct elo_policy *pp = p->data;
62 int moves = 0;
64 /* First, assign per-point probabilities. */
66 for (int f = 0; f < b->flen; f++) {
67 struct move m = { .coord = b->f[f], .color = to_play };
69 /* Skip pass (for now)? */
70 if (is_pass(m.coord)) {
71 skip_move:
72 probdist_set(pd, m.coord, 0);
73 continue;
75 if (PLDEBUGL(7))
76 fprintf(stderr, "<%d> %s\n", f, coord2sstr(m.coord, b));
78 /* Skip invalid moves. */
79 if (!board_is_valid_move(b, &m))
80 goto skip_move;
82 /* We shall never fill our own single-point eyes. */
83 /* XXX: In some rare situations, this prunes the best move:
84 * Bulk-five nakade with eye at 1-1 point. */
85 if (board_is_one_point_eye(b, m.coord, to_play)) {
86 goto skip_move;
89 moves++;
90 /* Each valid move starts with gamma 1. */
91 double g = 1.f;
93 /* Some easy features: */
94 /* XXX: We just disable them for now since we call the
95 * pattern matcher; you need the gammas file. */
96 #if 0
97 if (is_bad_selfatari(b, to_play, m.coord))
98 g *= pp->selfatari;
99 #endif
101 /* Match pattern features: */
102 struct pattern pat;
103 pattern_match(&ps->pc, ps->ps, &pat, b, &m);
104 for (int i = 0; i < pat.n; i++) {
105 /* Multiply together gammas of all pattern features. */
106 double gamma = feature_gamma(ps->fg, &pat.f[i], NULL);
107 if (PLDEBUGL(7)) {
108 char buf[256] = ""; feature2str(buf, &pat.f[i]);
109 fprintf(stderr, "<%d> %s feat %s gamma %f\n", f, coord2sstr(m.coord, b), buf, gamma);
111 g *= gamma;
114 probdist_set(pd, m.coord, double_to_fixp(g));
115 if (PLDEBUGL(7))
116 fprintf(stderr, "<%d> %s %f (E %f)\n", f, coord2sstr(m.coord, b), fixp_to_double(probdist_one(pd, m.coord)), g);
119 return moves;
123 struct lprobdist {
124 int n;
125 #define LPD_MAX 8
126 coord_t coords[LPD_MAX];
127 fixp_t items[LPD_MAX];
128 fixp_t total;
130 /* Backups of original totals for restoring. */
131 fixp_t btotal;
132 fixp_t browtotals_v[10];
133 int browtotals_i[10];
134 int browtotals_n;
137 #ifdef BOARD_GAMMA
139 static void
140 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)
142 #if 0
143 #define PROBDIST_EPSILON double_to_fixp(0.01)
144 struct elo_policy *pp = p->data;
145 if (pd->total == 0)
146 return;
148 /* Compare to the manually created distribution. */
149 /* XXX: This is now broken if callback is used. */
151 probdist_alloca(pdx, b);
152 elo_get_probdist(p, &pp->choose, b, to_play, &pdx);
153 for (int i = 0; i < b->flen; i++) {
154 coord_t c = b->f[i];
155 if (is_pass(c)) continue;
156 if (c == b->ko.coord) continue;
157 fixp_t val = pd->items[c];
158 if (!is_pass(lc) && coord_is_8adjecent(lc, c, b))
159 for (int j = 0; j < lpd->n; j++)
160 if (lpd->coords[j] == c) {
161 val = lpd->items[j];
162 probdist_mute(&pdx, c);
165 if (abs(pdx.items[c] - val) < PROBDIST_EPSILON)
166 continue;
167 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]));
168 board_gamma_update(b, c, to_play);
169 printf("plainboard %f\n", fixp_to_double(pd->items[c]));
170 assert(0);
172 for (int r = 0; r < board_size(b); r++) {
173 if (abs(pdx.rowtotals[r] - pd->rowtotals[r]) < PROBDIST_EPSILON)
174 continue;
175 fprintf(stderr, "row %d: manual %f board %f\n", r, fixp_to_double(pdx.rowtotals[r]), fixp_to_double(pd->rowtotals[r]));
176 assert(0);
178 assert(abs(pdx.total - pd->total) < PROBDIST_EPSILON);
179 #undef PROBDIST_EPSILON
180 #endif
183 coord_t
184 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
186 struct elo_policy *pp = p->data;
187 /* The base board probdist. */
188 struct probdist *pd = &b->prob[to_play - 1];
189 /* The list of moves we do not consider in pd. */
190 int ignores[10]; int ignores_n = 0;
191 /* The list of local moves; we consider these separately. */
192 struct lprobdist lpd = { .n = 0, .total = 0, .btotal = pd->total, .browtotals_n = 0 };
194 /* The engine might want to adjust our probdist. */
195 if (pp->callback)
196 pp->callback(pp->callback_data, b, to_play, pd);
198 if (PLDEBUGL(5)) {
199 fprintf(stderr, "pd total pre %f lpd %f\n", fixp_to_double(pd->total), fixp_to_double(lpd.total));
202 #define ignore_move(c_) do { \
203 ignores[ignores_n++] = c_; \
204 if (ignores_n > 1 && ignores[ignores_n - 1] < ignores[ignores_n - 2]) { \
205 /* Keep ignores[] sorted. We abuse the fact that we know \
206 * only one item can be out-of-order. */ \
207 coord_t cc = ignores[ignores_n - 2]; \
208 ignores[ignores_n - 2] = ignores[ignores_n - 1]; \
209 ignores[ignores_n - 1] = cc; \
211 int rowi = coord_y(c_, pd->b); \
212 lpd.browtotals_i[lpd.browtotals_n] = rowi; \
213 lpd.browtotals_v[lpd.browtotals_n++] = pd->rowtotals[rowi]; \
214 probdist_mute(pd, c_); \
215 if (PLDEBUGL(6)) \
216 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)); \
217 } while (0)
219 /* Make sure ko-prohibited move does not get picked. */
220 if (!is_pass(b->ko.coord)) {
221 assert(b->ko.color == to_play);
222 ignore_move(b->ko.coord);
225 /* Contiguity detection. */
226 if (!is_pass(b->last_move.coord)) {
227 foreach_8neighbor(b, b->last_move.coord) {
228 if (c == b->ko.coord)
229 continue; // already ignored
230 if (board_at(b, c) != S_NONE) {
231 assert(probdist_one(pd, c) == 0);
232 continue;
234 ignore_move(c);
236 fixp_t val = double_to_fixp(fixp_to_double(probdist_one(pd, c)) * b->gamma->gamma[FEAT_CONTIGUITY][1]);
237 lpd.coords[lpd.n] = c;
238 lpd.items[lpd.n++] = val;
239 lpd.total += val;
240 } foreach_8neighbor_end;
243 ignores[ignores_n] = pass;
244 if (PLDEBUGL(5))
245 fprintf(stderr, "pd total post %f lpd %f\n", fixp_to_double(pd->total), fixp_to_double(lpd.total));
247 /* Verify sanity, possibly. */
248 elo_check_probdist(p, b, to_play, pd, ignores, &lpd, b->last_move.coord);
250 /* Pick a move. */
251 coord_t c = pass;
252 fixp_t stab = fast_irandom(lpd.total + pd->total);
253 if (PLDEBUGL(5))
254 fprintf(stderr, "stab %f / (%f + %f)\n", fixp_to_double(stab), fixp_to_double(lpd.total), fixp_to_double(pd->total));
255 if (stab < lpd.total) {
256 /* Local probdist. */
257 if (PLDEBUGL(6)) {
258 /* Some debug prints. */
259 fixp_t tot = 0;
260 for (int i = 0; i < lpd.n; i++) {
261 tot += lpd.items[i];
262 struct pattern p;
263 struct move m = { .color = to_play, .coord = lpd.coords[i] };
264 if (board_at(b, m.coord) != S_NONE) {
265 assert(lpd.items[i] == 0);
266 continue;
268 pattern_match(&pp->choose.pc, pp->choose.ps, &p, b, &m);
269 char s[256] = ""; pattern2str(s, &p);
270 fprintf(stderr, "coord %s <%f> [tot %f] %s (p3:%d)\n",
271 coord2sstr(lpd.coords[i], b), fixp_to_double(lpd.items[i]),
272 fixp_to_double(tot), s,
273 pattern3_by_spatial(pp->choose.pc.spat_dict, b->pat3[lpd.coords[i]]));
276 for (int i = 0; i < lpd.n; i++) {
277 if (stab <= lpd.items[i]) {
278 c = lpd.coords[i];
279 break;
281 stab -= lpd.items[i];
283 if (is_pass(c)) {
284 fprintf(stderr, "elo: local overstab [%f]\n", fixp_to_double(stab));
285 abort();
288 } else if (pd->total > 0) {
289 /* Global probdist. */
290 /* XXX: We re-stab inside. */
291 c = probdist_pick(pd, ignores);
293 } else {
294 if (PLDEBUGL(5))
295 fprintf(stderr, "ding!\n");
296 c = pass;
299 /* Repair the damage. */
300 if (pp->callback) {
301 /* XXX: Do something less horribly inefficient
302 * than just recomputing the whole pd. */
303 pd->total = 0;
304 for (int i = 0; i < board_size(pd->b); i++)
305 pd->rowtotals[i] = 0;
306 for (int i = 0; i < b->flen; i++) {
307 pd->items[b->f[i]] = 0;
308 board_gamma_update(b, b->f[i], to_play);
310 assert(pd->total == lpd.btotal);
312 } else {
313 pd->total = lpd.btotal;
314 /* If we touched a row multiple times (and we sure will),
315 * the latter value is obsolete; but since we go through
316 * the backups in reverse order, all is good. */
317 for (int j = lpd.browtotals_n - 1; j >= 0; j--)
318 pd->rowtotals[lpd.browtotals_i[j]] = lpd.browtotals_v[j];
320 return c;
323 #else
325 coord_t
326 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
328 struct elo_policy *pp = p->data;
329 probdist_alloca(pd, b);
330 elo_get_probdist(p, &pp->choose, b, to_play, &pd);
331 if (pp->callback)
332 pp->callback(pp->callback_data, b, to_play, &pd);
333 if (pd.total == 0)
334 return pass;
335 int ignores[1] = { pass };
336 coord_t c = probdist_pick(&pd, ignores);
337 return c;
340 #endif
342 void
343 playout_elo_assess(struct playout_policy *p, struct prior_map *map, int games)
345 struct elo_policy *pp = p->data;
346 probdist_alloca(pd, map->b);
348 int moves;
349 moves = elo_get_probdist(p, &pp->assess, map->b, map->to_play, &pd);
351 /* It is a question how to transform the gamma to won games; we use
352 * a naive approach currently, but not sure how well it works. */
353 /* TODO: Try sqrt(p), atan(p)/pi*2. */
355 for (int f = 0; f < map->b->flen; f++) {
356 coord_t c = map->b->f[f];
357 if (!map->consider[c])
358 continue;
359 add_prior_value(map, c, fixp_to_double(probdist_one(&pd, c)) / fixp_to_double(probdist_total(&pd)), games);
363 void
364 playout_elo_done(struct playout_policy *p)
366 struct elo_policy *pp = p->data;
367 features_gamma_done(pp->choose.fg);
368 features_gamma_done(pp->assess.fg);
372 void
373 playout_elo_callback(struct playout_policy *p, playout_elo_callbackp callback, void *data)
375 struct elo_policy *pp = p->data;
376 pp->callback = callback;
377 pp->callback_data = data;
380 struct playout_policy *
381 playout_elo_init(char *arg, struct board *b)
383 struct playout_policy *p = calloc2(1, sizeof(*p));
384 struct elo_policy *pp = calloc2(1, sizeof(*pp));
385 p->data = pp;
386 p->choose = playout_elo_choose;
387 p->assess = playout_elo_assess;
388 p->done = playout_elo_done;
390 const char *gammafile = features_gamma_filename;
391 /* Some defaults based on the table in Remi Coulom's paper. */
392 pp->selfatari = 0.06;
394 struct pattern_config pc = DEFAULT_PATTERN_CONFIG;
395 int xspat = -1;
396 bool precise_selfatari = false;
398 if (arg) {
399 char *optspec, *next = arg;
400 while (*next) {
401 optspec = next;
402 next += strcspn(next, ":");
403 if (*next) { *next++ = 0; } else { *next = 0; }
405 char *optname = optspec;
406 char *optval = strchr(optspec, '=');
407 if (optval) *optval++ = 0;
409 if (!strcasecmp(optname, "selfatari") && optval) {
410 pp->selfatari = atof(optval);
411 } else if (!strcasecmp(optname, "precisesa")) {
412 /* Use precise self-atari detection within
413 * fast patterns. */
414 precise_selfatari = !optval || atoi(optval);
415 } else if (!strcasecmp(optname, "gammafile") && optval) {
416 /* patterns.gamma by default. We use this,
417 * and need also ${gammafile}f (e.g.
418 * patterns.gammaf) for fast (MC) features. */
419 gammafile = strdup(optval);
420 } else if (!strcasecmp(optname, "xspat") && optval) {
421 /* xspat==0: don't match spatial features
422 * xspat==1: match *only* spatial features */
423 xspat = atoi(optval);
424 } else {
425 fprintf(stderr, "playout-elo: Invalid policy argument %s or missing value\n", optname);
426 exit(1);
431 pc.spat_dict = spatial_dict_init(false);
433 pp->assess.pc = pc;
434 pp->assess.fg = features_gamma_init(&pp->assess.pc, gammafile);
435 memcpy(pp->assess.ps, PATTERN_SPEC_MATCHALL, sizeof(pattern_spec));
436 for (int i = 0; i < FEAT_MAX; i++)
437 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
438 pp->assess.ps[i] = 0;
440 /* In playouts, we need to operate with much smaller set of features
441 * in order to keep reasonable speed. */
442 /* TODO: Configurable. */ /* TODO: Tune. */
443 pp->choose.pc = FAST_PATTERN_CONFIG;
444 pp->choose.pc.spat_dict = pc.spat_dict;
445 char cgammafile[256]; strcpy(stpcpy(cgammafile, gammafile), "f");
446 pp->choose.fg = features_gamma_init(&pp->choose.pc, cgammafile);
447 memcpy(pp->choose.ps, PATTERN_SPEC_MATCHFAST, sizeof(pattern_spec));
448 for (int i = 0; i < FEAT_MAX; i++)
449 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
450 pp->choose.ps[i] = 0;
451 if (precise_selfatari)
452 pp->choose.ps[FEAT_SELFATARI] = ~(1<<PF_SELFATARI_STUPID);
453 board_gamma_set(b, pp->choose.fg, precise_selfatari);
455 return p;