Check all memory allocations to avoid core dump when running out of memory.
[pachi/peepo.git] / playout / elo.c
blob47a5a807fb65bc08c87db0defb77952351ad7446
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, f, 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, f, g);
111 //fprintf(stderr, "<%d> %s %f (E %f)\n", f, coord2sstr(m.coord, b), probdist_one(pd, f), pd->items[f]);
114 return moves;
118 coord_t
119 playout_elo_choose(struct playout_policy *p, struct board *b, enum stone to_play)
121 struct elo_policy *pp = p->data;
122 #ifdef BOARD_GAMMA
123 struct probdist *pd = &b->prob[to_play - 1];
124 /* Make sure ko-prohibited move does not get picked. */
125 if (!is_pass(b->ko.coord)) {
126 assert(b->ko.color == to_play);
127 probdist_set(pd, b->ko.coord, 0);
129 /* Contiguity detection. */
130 if (!is_pass(b->last_move.coord)) {
131 foreach_8neighbor(b, b->last_move.coord) {
132 probdist_set(pd, c, pd->items[c] * b->gamma->gamma[FEAT_CONTIGUITY][1]);
133 } foreach_8neighbor_end;
135 #if 0
136 /* Compare to the manually created distribution. */
137 if (pd->total >= PROBDIST_EPSILON) {
138 double pdi[b->flen]; memset(pdi, 0, sizeof(pdi));
139 struct probdist pdx = { .n = b->flen, .items = pdi, .total = 0 };
140 elo_get_probdist(p, &pp->choose, b, to_play, &pdx);
141 for (int i = 0; i < pdx.n; i++) {
142 if (is_pass(b->f[i])) continue;
143 if (fabs(pdx.items[i] - pd->items[b->f[i]]) >= PROBDIST_EPSILON) {
144 printf("[%s %d] manual %f board %f ", coord2sstr(b->f[i], b), b->pat3[b->f[i]], pdx.items[i], pd->items[b->f[i]]);
145 board_gamma_update(b, b->f[i], to_play);
146 printf("plainboard %f\n", pd->items[b->f[i]]);
147 assert(0);
151 #endif
152 /* The engine might want to adjust our probdist. */
153 if (pp->callback)
154 pp->callback(pp->callback_data, b, to_play, pd);
155 /* Pick a move. */
156 coord_t c = pd->total >= PROBDIST_EPSILON ? probdist_pick(pd) : pass;
157 /* Repair the damage. */
158 if (pp->callback) {
159 /* XXX: Do something less horribly inefficient
160 * than just recomputing the whole pd. */
161 pd->total = 0;
162 for (int i = 0; i < b->flen; i++) {
163 pd->items[b->f[i]] = 0;
164 board_gamma_update(b, b->f[i], to_play);
167 if (!is_pass(b->ko.coord))
168 board_gamma_update(b, b->ko.coord, to_play);
169 if (!is_pass(b->last_move.coord)) {
170 foreach_8neighbor(b, b->last_move.coord) {
171 board_gamma_update(b, c, to_play);
172 } foreach_8neighbor_end;
174 return c;
176 #else
177 double pdi[b->flen]; memset(pdi, 0, sizeof(pdi));
178 struct probdist pd = { .n = b->flen, .items = pdi, .total = 0 };
179 elo_get_probdist(p, &pp->choose, b, to_play, &pd);
180 if (pp->callback)
181 pp->callback(pp->callback_data, b, to_play, &pd);
182 if (pd.total < PROBDIST_EPSILON)
183 return pass;
184 int f = probdist_pick(&pd);
185 return b->f[f];
186 #endif
189 void
190 playout_elo_assess(struct playout_policy *p, struct prior_map *map, int games)
192 struct elo_policy *pp = p->data;
193 double pdi[map->b->flen]; memset(pdi, 0, sizeof(pdi));
194 struct probdist pd = { .n = map->b->flen, .items = pdi, .total = 0 };
196 int moves;
197 moves = elo_get_probdist(p, &pp->assess, map->b, map->to_play, &pd);
199 /* It is a question how to transform the gamma to won games; we use
200 * a naive approach currently, but not sure how well it works. */
201 /* TODO: Try sqrt(p), atan(p)/pi*2. */
203 for (int f = 0; f < map->b->flen; f++) {
204 coord_t c = map->b->f[f];
205 if (!map->consider[c])
206 continue;
207 add_prior_value(map, c, probdist_one(&pd, f) / probdist_total(&pd), games);
211 void
212 playout_elo_done(struct playout_policy *p)
214 struct elo_policy *pp = p->data;
215 features_gamma_done(pp->choose.fg);
216 features_gamma_done(pp->assess.fg);
220 void
221 playout_elo_callback(struct playout_policy *p, playout_elo_callbackp callback, void *data)
223 struct elo_policy *pp = p->data;
224 pp->callback = callback;
225 pp->callback_data = data;
228 struct playout_policy *
229 playout_elo_init(char *arg, struct board *b)
231 struct playout_policy *p = calloc2(1, sizeof(*p));
232 struct elo_policy *pp = calloc2(1, sizeof(*pp));
233 p->data = pp;
234 p->choose = playout_elo_choose;
235 p->assess = playout_elo_assess;
236 p->done = playout_elo_done;
238 const char *gammafile = features_gamma_filename;
239 /* Some defaults based on the table in Remi Coulom's paper. */
240 pp->selfatari = 0.06;
242 struct pattern_config pc = DEFAULT_PATTERN_CONFIG;
243 int xspat = -1;
244 bool precise_selfatari = false;
246 if (arg) {
247 char *optspec, *next = arg;
248 while (*next) {
249 optspec = next;
250 next += strcspn(next, ":");
251 if (*next) { *next++ = 0; } else { *next = 0; }
253 char *optname = optspec;
254 char *optval = strchr(optspec, '=');
255 if (optval) *optval++ = 0;
257 if (!strcasecmp(optname, "selfatari") && optval) {
258 pp->selfatari = atof(optval);
259 } else if (!strcasecmp(optname, "precisesa")) {
260 /* Use precise self-atari detection within
261 * fast patterns. */
262 precise_selfatari = !optval || atoi(optval);
263 } else if (!strcasecmp(optname, "gammafile") && optval) {
264 /* patterns.gamma by default. We use this,
265 * and need also ${gammafile}f (e.g.
266 * patterns.gammaf) for fast (MC) features. */
267 gammafile = strdup(optval);
268 } else if (!strcasecmp(optname, "xspat") && optval) {
269 /* xspat==0: don't match spatial features
270 * xspat==1: match *only* spatial features */
271 xspat = atoi(optval);
272 } else {
273 fprintf(stderr, "playout-elo: Invalid policy argument %s or missing value\n", optname);
274 exit(1);
279 pc.spat_dict = spatial_dict_init(false);
281 pp->assess.pc = pc;
282 pp->assess.fg = features_gamma_init(&pp->assess.pc, gammafile);
283 memcpy(pp->assess.ps, PATTERN_SPEC_MATCHALL, sizeof(pattern_spec));
284 for (int i = 0; i < FEAT_MAX; i++)
285 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
286 pp->assess.ps[i] = 0;
288 /* In playouts, we need to operate with much smaller set of features
289 * in order to keep reasonable speed. */
290 /* TODO: Configurable. */ /* TODO: Tune. */
291 pp->choose.pc = FAST_PATTERN_CONFIG;
292 pp->choose.pc.spat_dict = pc.spat_dict;
293 char cgammafile[256]; strcpy(stpcpy(cgammafile, gammafile), "f");
294 pp->choose.fg = features_gamma_init(&pp->choose.pc, cgammafile);
295 memcpy(pp->choose.ps, PATTERN_SPEC_MATCHFAST, sizeof(pattern_spec));
296 for (int i = 0; i < FEAT_MAX; i++)
297 if ((xspat == 0 && i == FEAT_SPATIAL) || (xspat == 1 && i != FEAT_SPATIAL))
298 pp->choose.ps[i] = 0;
299 if (precise_selfatari)
300 pp->choose.ps[FEAT_SELFATARI] = ~(1<<PF_SELFATARI_STUPID);
301 board_gamma_set(b, pp->choose.fg, precise_selfatari);
303 return p;