board_gamma_update(): Export function
[pachi.git] / pattern.c
blob4ed534e0bf4ebd69b7629173f49322ae2a524a57
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <inttypes.h>
5 #include <stdio.h>
6 #include <stdlib.h>
8 #include "board.h"
9 #include "debug.h"
10 #include "pattern.h"
11 #include "patternsp.h"
12 #include "pattern3.h"
13 #include "tactics.h"
16 struct pattern_config DEFAULT_PATTERN_CONFIG = {
17 .spat_min = 3, .spat_max = MAX_PATTERN_DIST,
18 .bdist_max = 4,
19 .ldist_min = 0, .ldist_max = 256,
20 .mcsims = 0, /* Unsupported. */
23 struct pattern_config FAST_PATTERN_CONFIG = {
24 .spat_min = 3, .spat_max = 3,
25 .bdist_max = -1,
26 .ldist_min = 0, .ldist_max = 256,
27 .mcsims = 0,
30 pattern_spec PATTERN_SPEC_MATCHALL = {
31 [FEAT_PASS] = ~0,
32 [FEAT_CAPTURE] = ~0,
33 [FEAT_AESCAPE] = ~0,
34 [FEAT_SELFATARI] = ~0,
35 [FEAT_ATARI] = ~0,
36 [FEAT_BORDER] = ~0,
37 [FEAT_LDIST] = ~0,
38 [FEAT_LLDIST] = ~0,
39 [FEAT_CONTIGUITY] = 0,
40 [FEAT_SPATIAL] = ~0,
41 [FEAT_PATTERN3] = 0,
42 [FEAT_MCOWNER] = ~0,
45 /* !!! Note that in order for ELO playout policy to work correctly, this
46 * pattern specification MUST exactly match the features matched by the
47 * BOARD_GAMMA code! You cannot just tinker with this spec freely. */
48 #define FAST_NO_LADDER 1 /* 1: Don't match ladders in fast playouts */
49 pattern_spec PATTERN_SPEC_MATCHFAST = {
50 [FEAT_PASS] = ~0,
51 [FEAT_CAPTURE] = ~(1<<PF_CAPTURE_ATARIDEF | 1<<PF_CAPTURE_RECAPTURE | FAST_NO_LADDER<<PF_CAPTURE_LADDER),
52 [FEAT_AESCAPE] = ~(FAST_NO_LADDER<<PF_AESCAPE_LADDER),
53 [FEAT_SELFATARI] = ~(1<<PF_SELFATARI_SMART),
54 [FEAT_ATARI] = 0,
55 [FEAT_BORDER] = 0,
56 [FEAT_LDIST] = 0,
57 [FEAT_LLDIST] = 0,
58 [FEAT_CONTIGUITY] = ~0,
59 [FEAT_SPATIAL] = 0,
60 [FEAT_PATTERN3] = ~0,
61 [FEAT_MCOWNER] = 0,
64 static const struct feature_info {
65 char *name;
66 int payloads;
67 } features[FEAT_MAX] = {
68 [FEAT_PASS] = { .name = "pass", .payloads = 2 },
69 [FEAT_CAPTURE] = { .name = "capture", .payloads = 16 },
70 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 2 },
71 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 2 },
72 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
73 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
74 [FEAT_LDIST] = { .name = "ldist", .payloads = -1 },
75 [FEAT_LLDIST] = { .name = "lldist", .payloads = -1 },
76 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
77 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
78 [FEAT_PATTERN3] = { .name = "p", .payloads = 2<<16 },
79 [FEAT_MCOWNER] = { .name = "mcowner", .payloads = 16 },
82 char *
83 feature2str(char *str, struct feature *f)
85 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
88 char *
89 str2feature(char *str, struct feature *f)
91 while (isspace(*str)) str++;
93 int flen = strcspn(str, ":");
94 for (int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
95 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
96 f->id = i;
97 goto found;
99 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
100 exit(EXIT_FAILURE);
102 found:
103 str += flen + 1;
104 f->payload = strtoull(str, &str, 10);
105 return str;
108 char *
109 feature_name(enum feature_id f)
111 return features[f].name;
115 feature_payloads(struct pattern_config *pc, enum feature_id f)
117 switch (f) {
118 case FEAT_SPATIAL:
119 assert(features[f].payloads < 0);
120 return pc->spat_dict->nspatials;
121 case FEAT_LDIST:
122 case FEAT_LLDIST:
123 assert(features[f].payloads < 0);
124 return pc->ldist_max + 1;
125 case FEAT_BORDER:
126 assert(features[f].payloads < 0);
127 return pc->bdist_max + 1;
128 default:
129 assert(features[f].payloads > 0);
130 return features[f].payloads;
135 /* pattern_spec helpers */
136 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << 15))
137 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
139 static struct feature *
140 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
141 struct pattern *p, struct feature *f,
142 struct board *b, struct move *m)
144 f->id = FEAT_CAPTURE; f->payload = 0;
145 #ifdef BOARD_TRAITS
146 if (!trait_at(b, m->coord, m->color).cap)
147 return f;
148 /* Capturable! */
149 if (!(PS_PF(CAPTURE, LADDER)
150 || PS_PF(CAPTURE, RECAPTURE)
151 || PS_PF(CAPTURE, ATARIDEF)
152 || PS_PF(CAPTURE, KO))) {
153 (f++, p->n++);
154 return f;
156 /* We need to know details, so we still have to go through
157 * the neighbors. */
158 #endif
160 /* Furthermore, we will now create one feature per capturable
161 * neighbor. */
162 /* XXX: I'm not sure if this is really good idea. --pasky */
163 foreach_neighbor(b, m->coord, {
164 if (board_at(b, c) != stone_other(m->color))
165 continue;
166 group_t g = group_at(b, c);
167 if (!g || board_group_info(b, g).libs != 1)
168 continue;
170 /* Capture! */
172 if (PS_PF(CAPTURE, LADDER))
173 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
174 /* TODO: is_ladder() is too conservative in some
175 * very obvious situations, look at complete.gtp. */
177 /* TODO: PF_CAPTURE_RECAPTURE */
179 if (PS_PF(CAPTURE, ATARIDEF))
180 foreach_in_group(b, g) {
181 foreach_neighbor(b, c, {
182 assert(board_at(b, c) != S_NONE || c == m->coord);
183 if (board_at(b, c) != m->color)
184 continue;
185 group_t g = group_at(b, c);
186 if (!g || board_group_info(b, g).libs != 1)
187 continue;
188 /* A neighboring group of ours is in atari. */
189 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
191 } foreach_in_group_end;
193 if (PS_PF(CAPTURE, KO)
194 && group_is_onestone(b, g)
195 && neighbor_count_at(b, m->coord, stone_other(m->color))
196 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
197 f->payload |= 1 << PF_CAPTURE_KO;
199 (f++, p->n++);
200 f->id = FEAT_CAPTURE; f->payload = 0;
202 return f;
205 static struct feature *
206 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
207 struct pattern *p, struct feature *f,
208 struct board *b, struct move *m)
210 #ifdef BOARD_TRAITS
211 if (!trait_at(b, m->coord, stone_other(m->color)).cap
212 || !trait_at(b, m->coord, m->color).safe)
213 return f;
214 /* Opponent can capture something and this move is safe
215 * for us! */
216 if (!PS_PF(AESCAPE, LADDER)) {
217 f->id = FEAT_AESCAPE; f->payload = 0;
218 (f++, p->n++);
219 return f;
221 /* We need to know details, so we still have to go through
222 * the neighbors. */
223 #endif
225 /* Find if a neighboring group of ours is in atari, AND that we provide
226 * a liberty to connect out. XXX: No connect-and-die check. */
227 group_t in_atari = -1;
228 bool has_extra_lib = false;
229 int payload = 0;
231 foreach_neighbor(b, m->coord, {
232 if (board_at(b, c) != m->color) {
233 if (board_at(b, c) == S_NONE)
234 has_extra_lib = true; // free point
235 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1)
236 has_extra_lib = true; // capturable enemy group
237 continue;
239 group_t g = group_at(b, c); assert(g);
240 if (board_group_info(b, g).libs != 1) {
241 has_extra_lib = true;
242 continue;
245 /* In atari! */
246 in_atari = g;
248 if (PS_PF(AESCAPE, LADDER))
249 payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
250 /* TODO: is_ladder() is too conservative in some
251 * very obvious situations, look at complete.gtp. */
253 if (in_atari >= 0 && has_extra_lib) {
254 f->id = FEAT_AESCAPE; f->payload = payload;
255 (f++, p->n++);
257 return f;
260 static struct feature *
261 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
262 struct pattern *p, struct feature *f,
263 struct board *b, struct move *m)
265 foreach_neighbor(b, m->coord, {
266 if (board_at(b, c) != stone_other(m->color))
267 continue;
268 group_t g = group_at(b, c);
269 if (!g || board_group_info(b, g).libs != 2)
270 continue;
272 /* Can atari! */
273 f->id = FEAT_ATARI; f->payload = 0;
275 if (PS_PF(ATARI, LADDER)) {
276 /* Opponent will escape by the other lib. */
277 coord_t lib = board_group_info(b, g).lib[0];
278 if (lib == m->coord) lib = board_group_info(b, g).lib[1];
279 /* TODO: is_ladder() is too conservative in some
280 * very obvious situations, look at complete.gtp. */
281 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
284 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
285 f->payload |= 1 << PF_ATARI_KO;
287 (f++, p->n++);
289 return f;
292 #ifndef BOARD_SPATHASH
293 #undef BOARD_SPATHASH_MAXD
294 #define BOARD_SPATHASH_MAXD 1
295 #endif
297 /* Match spatial features that are too distant to be pre-matched
298 * incrementally. */
299 struct feature *
300 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
301 struct pattern *p, struct feature *f,
302 struct board *b, struct move *m, hash_t h)
304 /* We record all spatial patterns black-to-play; simply
305 * reverse all colors if we are white-to-play. */
306 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
307 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
308 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
310 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
311 /* Recompute missing outer circles:
312 * Go through all points in given distance. */
313 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
314 ptcoords_at(x, y, m->coord, b, j);
315 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
317 if (d < pc->spat_min)
318 continue;
319 /* Record spatial feature, one per distance. */
320 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
321 if (sid > 0) {
322 f->id = FEAT_SPATIAL;
323 f->payload = sid;
324 (f++, p->n++);
325 } /* else not found, ignore */
327 return f;
330 struct feature *
331 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
332 struct pattern *p, struct feature *f,
333 struct board *b, struct move *m)
335 /* XXX: This is partially duplicated from spatial_from_board(), but
336 * we build a hash instead of spatial record. */
338 assert(pc->spat_min > 0);
340 hash_t h = pthashes[0][0][S_NONE];
341 #ifdef BOARD_SPATHASH
342 bool w_to_play = m->color == S_WHITE;
343 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
344 /* Reuse all incrementally matched data. */
345 h ^= b->spathash[m->coord][d - 1][w_to_play];
346 if (d < pc->spat_min)
347 continue;
348 /* Record spatial feature, one per distance. */
349 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
350 if (sid > 0) {
351 f->id = FEAT_SPATIAL;
352 f->payload = sid;
353 (f++, p->n++);
354 } /* else not found, ignore */
356 #else
357 assert(BOARD_SPATHASH_MAXD < 2);
358 #endif
359 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
360 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
361 return f;
365 static bool
366 is_simple_selfatari(struct board *b, enum stone color, coord_t coord)
368 #ifdef BOARD_TRAITS
369 return !trait_at(b, coord, color).safe;
370 #endif
372 /* Very rough check, no connect-and-die checks or other trickery. */
373 int libs = immediate_liberty_count(b, coord);
374 if (libs >= 2) return false; // open space
376 group_t seen = -1;
377 foreach_neighbor(b, coord, {
378 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1) {
379 return false; // can capture
381 } else if (board_at(b, c) == color) {
382 // friendly group, does it have liberties?
383 group_t g = group_at(b, c);
384 if (board_group_info(b, g).libs == 1 || seen == g)
385 continue;
386 libs += board_group_info(b, g).libs - 1;
387 if (libs >= 2) return false;
388 // don't consider the same group twice
389 seen = g;
392 return true;
395 void
396 pattern_match(struct pattern_config *pc, pattern_spec ps,
397 struct pattern *p, struct board *b, struct move *m)
399 p->n = 0;
400 struct feature *f = &p->f[0];
402 /* TODO: We should match pretty much all of these features
403 * incrementally. */
405 if (is_pass(m->coord)) {
406 if (PS_ANY(PASS)) {
407 f->id = FEAT_PASS; f->payload = 0;
408 if (PS_PF(PASS, LASTPASS))
409 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
410 << PF_PASS_LASTPASS;
411 p->n++;
413 return;
416 if (PS_ANY(CAPTURE)) {
417 f = pattern_match_capture(pc, ps, p, f, b, m);
420 if (PS_ANY(AESCAPE)) {
421 f = pattern_match_aescape(pc, ps, p, f, b, m);
424 if (PS_ANY(SELFATARI)) {
425 bool simple = is_simple_selfatari(b, m->color, m->coord);
426 bool thorough = false;
427 if (PS_PF(SELFATARI, SMART)) {
428 thorough = is_bad_selfatari(b, m->color, m->coord);
430 if (simple || thorough) {
431 f->id = FEAT_SELFATARI;
432 f->payload = thorough << PF_SELFATARI_SMART;
433 (f++, p->n++);
437 if (PS_ANY(ATARI)) {
438 f = pattern_match_atari(pc, ps, p, f, b, m);
441 if (PS_ANY(BORDER)) {
442 int bdist = coord_edge_distance(m->coord, b);
443 if (bdist <= pc->bdist_max) {
444 f->id = FEAT_BORDER;
445 f->payload = bdist;
446 (f++, p->n++);
450 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
451 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
452 f->id = FEAT_CONTIGUITY;
453 f->payload = 1;
454 (f++, p->n++);
457 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
458 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
459 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
460 f->id = FEAT_LDIST;
461 f->payload = ldist;
462 (f++, p->n++);
466 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
467 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
468 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
469 f->id = FEAT_LLDIST;
470 f->payload = lldist;
471 (f++, p->n++);
475 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
476 f = pattern_match_spatial(pc, ps, p, f, b, m);
479 if (PS_ANY(PATTERN3) && !is_pass(m->coord)) {
480 #ifdef BOARD_PAT3
481 int pat = b->pat3[m->coord];
482 #else
483 int pat = pattern3_hash(b, m->coord);
484 #endif
485 if (m->color == S_WHITE) {
486 /* We work with the pattern3s as black-to-play. */
487 pat = pattern3_reverse(pat);
489 f->id = FEAT_PATTERN3;
490 f->payload = pat;
491 (f++, p->n++);
494 /* FEAT_MCOWNER: TODO */
495 assert(!pc->mcsims);
498 char *
499 pattern2str(char *str, struct pattern *p)
501 str = stpcpy(str, "(");
502 for (int i = 0; i < p->n; i++) {
503 if (i > 0) str = stpcpy(str, " ");
504 str = feature2str(str, &p->f[i]);
506 str = stpcpy(str, ")");
507 return str;
512 /*** Features gamma set */
514 static void
515 features_gamma_load(struct features_gamma *fg, const char *filename)
517 FILE *f = fopen(filename, "r");
518 if (!f) return;
519 char buf[256];
520 while (fgets(buf, 256, f)) {
521 char *bufp = buf;
522 struct feature f;
523 bufp = str2feature(bufp, &f);
524 while (isspace(*bufp)) bufp++;
525 float gamma = strtof(bufp, &bufp);
526 /* Record feature's gamma. */
527 feature_gamma(fg, &f, &gamma);
528 /* In case of 3x3 patterns, record gamma also
529 * for all rotations and transpositions. */
530 if (f.id == FEAT_PATTERN3) {
531 int transp[8];
532 pattern3_transpose(f.payload, &transp);
533 for (int i = 1; i < 8; i++) {
534 f.payload = transp[i];
535 feature_gamma(fg, &f, &gamma);
537 f.payload = transp[0];
540 fclose(f);
543 const char *features_gamma_filename = "patterns.gamma";
545 struct features_gamma *
546 features_gamma_init(struct pattern_config *pc, const char *file)
548 struct features_gamma *fg = calloc(1, sizeof(*fg));
549 fg->pc = pc;
550 for (int i = 0; i < FEAT_MAX; i++) {
551 int n = feature_payloads(pc, i);
552 fg->gamma[i] = malloc(n * sizeof(float));
553 for (int j = 0; j < n; j++) {
554 fg->gamma[i][j] = 1.0f;
557 features_gamma_load(fg, file ? file : features_gamma_filename);
558 return fg;
561 void
562 features_gamma_done(struct features_gamma *fg)
564 for (int i = 0; i < FEAT_MAX; i++)
565 free(fg->gamma[i]);
566 free(fg);