probdist_pick(): Make the ignore list pass-terminated
[pachi/json.git] / playout / elo.c
blob183d0f94e52427aea0eee025c171fd5f3f9ca131
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 "pattern.h"
29 #include "patternsp.h"
30 #include "playout.h"
31 #include "playout/elo.h"
32 #include "random.h"
33 #include "tactics.h"
34 #include "uct/prior.h"
36 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
39 /* Note that the context can be shared by multiple threads! */
41 struct patternset {
42 pattern_spec ps;
43 struct pattern_config pc;
44 struct features_gamma *fg;
47 struct elo_policy {
48 float selfatari;
49 struct patternset choose, assess;
50 playout_elo_callbackp callback; void *callback_data;
54 /* This is the core of the policy - initializes and constructs the
55 * probability distribution over the move candidates. */
57 int
58 elo_get_probdist(struct playout_policy *p, struct patternset *ps, struct board *b, enum stone to_play, struct probdist *pd)
60 //struct elo_policy *pp = p->data;
61 int moves = 0;
63 /* First, assign per-point probabilities. */
65 for (int f = 0; f < b->flen; f++) {
66 struct move m = { .coord = b->f[f], .color = to_play };
68 /* Skip pass (for now)? */
69 if (is_pass(m.coord)) {
70 skip_move:
71 probdist_set(pd, m.coord, 0);
72 continue;
74 //fprintf(stderr, "<%d> %s\n", f, coord2sstr(m.coord, b));
76 /* Skip invalid moves. */
77 if (!board_is_valid_move(b, &m))
78 goto skip_move;
80 /* We shall never fill our own single-point eyes. */
81 /* XXX: In some rare situations, this prunes the best move:
82 * Bulk-five nakade with eye at 1-1 point. */
83 if (board_is_one_point_eye(b, m.coord, to_play)) {
84 goto skip_move;
87 moves++;
88 /* Each valid move starts with gamma 1. */
89 double g = 1.f;
91 /* Some easy features: */
92 /* XXX: We just disable them for now since we call the
93 * pattern matcher; you need the gammas file. */
94 #if 0
95 if (is_bad_selfatari(b, to_play, m.coord))
96 g *= pp->selfatari;
97 #endif
99 /* Match pattern features: */
100 struct pattern p;
101 pattern_match(&ps->pc, ps->ps, &p, b, &m);
102 for (int i = 0; i < p.n; i++) {
103 /* Multiply together gammas of all pattern features. */
104 double gamma = feature_gamma(ps->fg, &p.f[i], NULL);
105 //char buf[256] = ""; feature2str(buf, &p.f[i]);
106 //fprintf(stderr, "<%d> %s feat %s gamma %f\n", f, coord2sstr(m.coord, b), buf, gamma);
107 g *= gamma;
110 probdist_set(pd, m.coord, g);
111 //fprintf(stderr, "<%d> %s %f (E %f)\n", f, coord2sstr(m.coord, b), probdist_one(pd, m.coord), pd->items[f]);
114 return moves;
118 struct lprobdist {
119 int n;
120 #define LPD_MAX 8
121 coord_t coords[LPD_MAX];
122 double items[LPD_MAX];
123 double total;
125 /* Backups of original totals for restoring. */
126 double btotal;
127 double browtotals_v[10];
128 int browtotals_i[10];
129 int browtotals_n;
132 #ifdef BOARD_GAMMA
134 static void
135 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)
137 #if 0
138 struct elo_policy *pp = p->data;
139 if (pd->total < PROBDIST_EPSILON)
140 return;
142 /* Compare to the manually created distribution. */
143 /* XXX: This is now broken if callback is used. */
145 double pdi[board_size2(b)]; memset(pdi, 0, sizeof(pdi));
146 double pdr[board_size(b)]; memset(pdr, 0, sizeof(pdr));
147 struct probdist pdx = { .n = board_size2(b), .n1 = board_size(b), .items = pdi, .rowtotals = pdr, .total = 0 };
148 elo_get_probdist(p, &pp->choose, b, to_play, &pdx);
149 for (int i = 0; i < b->flen; i++) {
150 coord_t c = b->f[i];
151 if (is_pass(c)) continue;
152 // XXX: Hardcoded ignores[] structure
153 if (ignores[0] == c) continue;
154 double val = pd->items[c];
155 if (!is_pass(lc) && coord_is_8adjecent(lc, c, b))
156 for (int j = 0; j < lpd->n; j++)
157 if (lpd->coords[j] == c)
158 val = lpd->items[j];
159 if (fabs(pdx.items[c] - val) < PROBDIST_EPSILON)
160 continue;
161 printf("[%s %d] manual %f board %f ", coord2sstr(c, b), b->pat3[c], pdx.items[c], pd->items[c]);
162 board_gamma_update(b, c, to_play);
163 printf("plainboard %f\n", pd->items[c]);
164 assert(0);
166 #endif
169 coord_t
170 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
172 struct elo_policy *pp = p->data;
173 /* The base board probdist. */
174 struct probdist *pd = &b->prob[to_play - 1];
175 /* The list of moves we do not consider in pd. */
176 int ignores[10]; int ignores_n = 0;
177 /* The list of local moves; we consider these separately. */
178 struct lprobdist lpd = { .n = 0, .total = 0, .btotal = pd->total, .browtotals_n = 0 };
180 /* The engine might want to adjust our probdist. */
181 if (pp->callback)
182 pp->callback(pp->callback_data, b, to_play, pd);
184 #define ignore_move(c_) do { \
185 ignores[ignores_n++] = c_; \
186 int rowi = c_ / pd->n1; \
187 lpd.browtotals_i[lpd.browtotals_n] = rowi; \
188 lpd.browtotals_v[lpd.browtotals_n++] = pd->rowtotals[rowi]; \
189 probdist_mute(pd, c_); \
190 } while (0)
192 /* Make sure ko-prohibited move does not get picked. */
193 if (!is_pass(b->ko.coord)) {
194 assert(b->ko.color == to_play);
195 ignore_move(b->ko.coord);
198 /* Contiguity detection. */
199 if (!is_pass(b->last_move.coord)) {
200 foreach_8neighbor(b, b->last_move.coord) {
201 ignore_move(c);
203 double val = probdist_one(pd, c) * b->gamma->gamma[FEAT_CONTIGUITY][1];
204 lpd.coords[lpd.n] = c;
205 lpd.items[lpd.n++] = val;
206 lpd.total += val;
207 } foreach_8neighbor_end;
210 ignores[ignores_n] = pass;
212 /* Verify sanity, possibly. */
213 elo_check_probdist(p, b, to_play, pd, ignores, &lpd, b->last_move.coord);
215 /* Pick a move. */
216 coord_t c = pass;
217 double stab = fast_frandom() * (lpd.total + pd->total);
218 if (stab < lpd.total - PROBDIST_EPSILON) {
219 /* Local probdist. */
220 for (int i = 0; i < lpd.n; i++) {
221 if (stab <= lpd.items[i]) {
222 c = lpd.coords[i];
223 break;
225 stab -= lpd.items[i];
227 if (is_pass(c)) {
228 fprintf(stderr, "elo: local overstab [%lf]\n", stab);
229 abort();
232 } else if (pd->total >= PROBDIST_EPSILON) {
233 /* Global probdist. */
234 /* XXX: We re-stab inside. */
235 c = probdist_pick(pd, ignores);
237 } else {
238 c = pass;
241 /* Repair the damage. */
242 if (pp->callback) {
243 /* XXX: Do something less horribly inefficient
244 * than just recomputing the whole pd. */
245 pd->total = 0;
246 for (int i = 0; i < pd->n / pd->n1; i++)
247 pd->rowtotals[i] = 0;
248 for (int i = 0; i < b->flen; i++) {
249 pd->items[b->f[i]] = 0;
250 board_gamma_update(b, b->f[i], to_play);
252 assert(fabs(pd->total - lpd.btotal) < PROBDIST_EPSILON);
254 } else {
255 pd->total = lpd.btotal;
256 /* If we touched a row multiple times (and we sure will),
257 * the latter value is obsolete; but since we go through
258 * the backups in reverse order, all is good. */
259 for (int j = lpd.browtotals_n - 1; j >= 0; j--)
260 pd->rowtotals[lpd.browtotals_i[j]] = lpd.browtotals_v[j];
262 return c;
265 #else
267 coord_t
268 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
270 struct elo_policy *pp = p->data;
271 double pdi[board_size2(b)]; memset(pdi, 0, sizeof(pdi));
272 double pdr[board_size(b)]; memset(pdr, 0, sizeof(pdr));
273 struct probdist pd = { .n = board_size2(b), .n1 = board_size(b), .items = pdi, .rowtotals = pdr, .total = 0 };
274 elo_get_probdist(p, &pp->choose, b, to_play, &pd);
275 if (pp->callback)
276 pp->callback(pp->callback_data, b, to_play, &pd);
277 if (pd.total < PROBDIST_EPSILON)
278 return pass;
279 int ignores[1] = { pass };
280 coord_t c = probdist_pick(&pd, ignores);
281 return c;
284 #endif
286 void
287 playout_elo_assess(struct playout_policy *p, struct prior_map *map, int games)
289 struct elo_policy *pp = p->data;
290 double pdi[board_size2(map->b)]; memset(pdi, 0, sizeof(pdi));
291 double pdr[board_size(map->b)]; memset(pdr, 0, sizeof(pdr));
292 struct probdist pd = { .n = board_size2(map->b), .n1 = board_size(map->b), .items = pdi, .rowtotals = pdr, .total = 0 };
294 int moves;
295 moves = elo_get_probdist(p, &pp->assess, map->b, map->to_play, &pd);
297 /* It is a question how to transform the gamma to won games; we use
298 * a naive approach currently, but not sure how well it works. */
299 /* TODO: Try sqrt(p), atan(p)/pi*2. */
301 for (int f = 0; f < map->b->flen; f++) {
302 coord_t c = map->b->f[f];
303 if (!map->consider[c])
304 continue;
305 add_prior_value(map, c, probdist_one(&pd, c) / probdist_total(&pd), games);
309 void
310 playout_elo_done(struct playout_policy *p)
312 struct elo_policy *pp = p->data;
313 features_gamma_done(pp->choose.fg);
314 features_gamma_done(pp->assess.fg);
318 void
319 playout_elo_callback(struct playout_policy *p, playout_elo_callbackp callback, void *data)
321 struct elo_policy *pp = p->data;
322 pp->callback = callback;
323 pp->callback_data = data;
326 struct playout_policy *
327 playout_elo_init(char *arg, struct board *b)
329 struct playout_policy *p = calloc2(1, sizeof(*p));
330 struct elo_policy *pp = calloc2(1, sizeof(*pp));
331 p->data = pp;
332 p->choose = playout_elo_choose;
333 p->assess = playout_elo_assess;
334 p->done = playout_elo_done;
336 const char *gammafile = features_gamma_filename;
337 /* Some defaults based on the table in Remi Coulom's paper. */
338 pp->selfatari = 0.06;
340 struct pattern_config pc = DEFAULT_PATTERN_CONFIG;
341 int xspat = -1;
342 bool precise_selfatari = false;
344 if (arg) {
345 char *optspec, *next = arg;
346 while (*next) {
347 optspec = next;
348 next += strcspn(next, ":");
349 if (*next) { *next++ = 0; } else { *next = 0; }
351 char *optname = optspec;
352 char *optval = strchr(optspec, '=');
353 if (optval) *optval++ = 0;
355 if (!strcasecmp(optname, "selfatari") && optval) {
356 pp->selfatari = atof(optval);
357 } else if (!strcasecmp(optname, "precisesa")) {
358 /* Use precise self-atari detection within
359 * fast patterns. */
360 precise_selfatari = !optval || atoi(optval);
361 } else if (!strcasecmp(optname, "gammafile") && optval) {
362 /* patterns.gamma by default. We use this,
363 * and need also ${gammafile}f (e.g.
364 * patterns.gammaf) for fast (MC) features. */
365 gammafile = strdup(optval);
366 } else if (!strcasecmp(optname, "xspat") && optval) {
367 /* xspat==0: don't match spatial features
368 * xspat==1: match *only* spatial features */
369 xspat = atoi(optval);
370 } else {
371 fprintf(stderr, "playout-elo: Invalid policy argument %s or missing value\n", optname);
372 exit(1);
377 pc.spat_dict = spatial_dict_init(false);
379 pp->assess.pc = pc;
380 pp->assess.fg = features_gamma_init(&pp->assess.pc, gammafile);
381 memcpy(pp->assess.ps, PATTERN_SPEC_MATCHALL, sizeof(pattern_spec));
382 for (int i = 0; i < FEAT_MAX; i++)
383 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
384 pp->assess.ps[i] = 0;
386 /* In playouts, we need to operate with much smaller set of features
387 * in order to keep reasonable speed. */
388 /* TODO: Configurable. */ /* TODO: Tune. */
389 pp->choose.pc = FAST_PATTERN_CONFIG;
390 pp->choose.pc.spat_dict = pc.spat_dict;
391 char cgammafile[256]; strcpy(stpcpy(cgammafile, gammafile), "f");
392 pp->choose.fg = features_gamma_init(&pp->choose.pc, cgammafile);
393 memcpy(pp->choose.ps, PATTERN_SPEC_MATCHFAST, sizeof(pattern_spec));
394 for (int i = 0; i < FEAT_MAX; i++)
395 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
396 pp->choose.ps[i] = 0;
397 if (precise_selfatari)
398 pp->choose.ps[FEAT_SELFATARI] = ~(1<<PF_SELFATARI_STUPID);
399 board_gamma_set(b, pp->choose.fg, precise_selfatari);
401 return p;