Allow defining total time not just time per move.
[pachi.git] / pattern.c
blobd947fda5e64f1224166362537d9c50078c898de6
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 #define FAST_NO_LADDER 1 /* 1: Don't match ladders in fast playouts */
46 pattern_spec PATTERN_SPEC_MATCHFAST = {
47 [FEAT_PASS] = ~0,
48 [FEAT_CAPTURE] = ~(1<<PF_CAPTURE_ATARIDEF | 1<<PF_CAPTURE_RECAPTURE | FAST_NO_LADDER<<PF_CAPTURE_LADDER),
49 [FEAT_AESCAPE] = ~(FAST_NO_LADDER<<PF_AESCAPE_LADDER),
50 [FEAT_SELFATARI] = ~(1<<PF_SELFATARI_SMART),
51 [FEAT_ATARI] = ~(FAST_NO_LADDER<<PF_ATARI_LADDER),
52 [FEAT_BORDER] = 0,
53 [FEAT_LDIST] = 0,
54 [FEAT_LLDIST] = 0,
55 [FEAT_CONTIGUITY] = ~0,
56 [FEAT_SPATIAL] = 0,
57 [FEAT_PATTERN3] = ~0,
58 [FEAT_MCOWNER] = 0,
61 static const struct feature_info {
62 char *name;
63 int payloads;
64 } features[FEAT_MAX] = {
65 [FEAT_PASS] = { .name = "pass", .payloads = 2 },
66 [FEAT_CAPTURE] = { .name = "capture", .payloads = 16 },
67 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 2 },
68 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 2 },
69 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
70 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
71 [FEAT_LDIST] = { .name = "ldist", .payloads = -1 },
72 [FEAT_LLDIST] = { .name = "lldist", .payloads = -1 },
73 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
74 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
75 [FEAT_PATTERN3] = { .name = "p", .payloads = 2<<16 },
76 [FEAT_MCOWNER] = { .name = "mcowner", .payloads = 16 },
79 char *
80 feature2str(char *str, struct feature *f)
82 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
85 char *
86 str2feature(char *str, struct feature *f)
88 while (isspace(*str)) str++;
90 int flen = strcspn(str, ":");
91 for (int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
92 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
93 f->id = i;
94 goto found;
96 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
97 exit(EXIT_FAILURE);
99 found:
100 str += flen + 1;
101 f->payload = strtoull(str, &str, 10);
102 return str;
105 char *
106 feature_name(enum feature_id f)
108 return features[f].name;
112 feature_payloads(struct pattern_config *pc, enum feature_id f)
114 switch (f) {
115 case FEAT_SPATIAL:
116 assert(features[f].payloads < 0);
117 return pc->spat_dict->nspatials;
118 case FEAT_LDIST:
119 case FEAT_LLDIST:
120 assert(features[f].payloads < 0);
121 return pc->ldist_max + 1;
122 case FEAT_BORDER:
123 assert(features[f].payloads < 0);
124 return pc->bdist_max + 1;
125 default:
126 assert(features[f].payloads > 0);
127 return features[f].payloads;
132 /* pattern_spec helpers */
133 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << 15))
134 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
136 static struct feature *
137 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
138 struct pattern *p, struct feature *f,
139 struct board *b, struct move *m)
141 foreach_neighbor(b, m->coord, {
142 if (board_at(b, c) != stone_other(m->color))
143 continue;
144 group_t g = group_at(b, c);
145 if (!g || board_group_info(b, g).libs != 1)
146 continue;
148 /* Capture! */
149 f->id = FEAT_CAPTURE; f->payload = 0;
151 if (PS_PF(CAPTURE, LADDER))
152 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
153 /* TODO: is_ladder() is too conservative in some
154 * very obvious situations, look at complete.gtp. */
156 /* TODO: PF_CAPTURE_RECAPTURE */
158 if (PS_PF(CAPTURE, ATARIDEF))
159 foreach_in_group(b, g) {
160 foreach_neighbor(b, c, {
161 assert(board_at(b, c) != S_NONE || c == m->coord);
162 if (board_at(b, c) != m->color)
163 continue;
164 group_t g = group_at(b, c);
165 if (!g || board_group_info(b, g).libs != 1)
166 continue;
167 /* A neighboring group of ours is in atari. */
168 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
170 } foreach_in_group_end;
172 if (PS_PF(CAPTURE, KO)
173 && group_is_onestone(b, g)
174 && neighbor_count_at(b, m->coord, stone_other(m->color))
175 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
176 f->payload |= 1 << PF_CAPTURE_KO;
178 (f++, p->n++);
180 return f;
183 static struct feature *
184 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
185 struct pattern *p, struct feature *f,
186 struct board *b, struct move *m)
188 /* Find if a neighboring group of ours is in atari, AND that we provide
189 * a liberty to connect out. XXX: No connect-and-die check. */
190 group_t in_atari = -1;
191 bool has_extra_lib = false;
192 int payload = 0;
194 foreach_neighbor(b, m->coord, {
195 if (board_at(b, c) != m->color) {
196 if (board_at(b, c) == S_NONE)
197 has_extra_lib = true; // free point
198 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1)
199 has_extra_lib = true; // capturable enemy group
200 continue;
202 group_t g = group_at(b, c); assert(g);
203 if (board_group_info(b, g).libs != 1) {
204 has_extra_lib = true;
205 continue;
208 /* In atari! */
209 in_atari = g;
211 if (PS_PF(AESCAPE, LADDER))
212 payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
213 /* TODO: is_ladder() is too conservative in some
214 * very obvious situations, look at complete.gtp. */
216 if (in_atari >= 0 && has_extra_lib) {
217 f->id = FEAT_AESCAPE; f->payload = payload;
218 (f++, p->n++);
220 return f;
223 static struct feature *
224 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
225 struct pattern *p, struct feature *f,
226 struct board *b, struct move *m)
228 foreach_neighbor(b, m->coord, {
229 if (board_at(b, c) != stone_other(m->color))
230 continue;
231 group_t g = group_at(b, c);
232 if (!g || board_group_info(b, g).libs != 2)
233 continue;
235 /* Can atari! */
236 f->id = FEAT_ATARI; f->payload = 0;
238 if (PS_PF(ATARI, LADDER)) {
239 /* Opponent will escape by the other lib. */
240 coord_t lib = board_group_info(b, g).lib[0];
241 if (lib == m->coord) lib = board_group_info(b, g).lib[1];
242 /* TODO: is_ladder() is too conservative in some
243 * very obvious situations, look at complete.gtp. */
244 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
247 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
248 f->payload |= 1 << PF_ATARI_KO;
250 (f++, p->n++);
252 return f;
255 #ifndef BOARD_SPATHASH
256 #undef BOARD_SPATHASH_MAXD
257 #define BOARD_SPATHASH_MAXD 1
258 #endif
260 /* Match spatial features that are too distant to be pre-matched
261 * incrementally. */
262 struct feature *
263 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
264 struct pattern *p, struct feature *f,
265 struct board *b, struct move *m, hash_t h)
267 /* We record all spatial patterns black-to-play; simply
268 * reverse all colors if we are white-to-play. */
269 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
270 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
271 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
273 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
274 /* Recompute missing outer circles:
275 * Go through all points in given distance. */
276 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
277 ptcoords_at(x, y, m->coord, b, j);
278 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
280 if (d < pc->spat_min)
281 continue;
282 /* Record spatial feature, one per distance. */
283 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
284 if (sid > 0) {
285 f->id = FEAT_SPATIAL;
286 f->payload = sid;
287 (f++, p->n++);
288 } /* else not found, ignore */
290 return f;
293 struct feature *
294 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
295 struct pattern *p, struct feature *f,
296 struct board *b, struct move *m)
298 /* XXX: This is partially duplicated from spatial_from_board(), but
299 * we build a hash instead of spatial record. */
301 assert(pc->spat_min > 0);
303 hash_t h = pthashes[0][0][S_NONE];
304 #ifdef BOARD_SPATHASH
305 bool w_to_play = m->color == S_WHITE;
306 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
307 /* Reuse all incrementally matched data. */
308 h ^= b->spathash[m->coord][d - 1][w_to_play];
309 if (d < pc->spat_min)
310 continue;
311 /* Record spatial feature, one per distance. */
312 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
313 if (sid > 0) {
314 f->id = FEAT_SPATIAL;
315 f->payload = sid;
316 (f++, p->n++);
317 } /* else not found, ignore */
319 #else
320 assert(BOARD_SPATHASH_MAXD < 2);
321 #endif
322 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
323 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
324 return f;
328 static bool
329 is_simple_selfatari(struct board *b, enum stone color, coord_t coord)
331 /* Very rough check, no connect-and-die checks or other trickery. */
332 int libs = immediate_liberty_count(b, coord);
333 if (libs >= 2) return false; // open space
335 group_t seen = -1;
336 foreach_neighbor(b, coord, {
337 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1) {
338 return false; // can capture
340 } else if (board_at(b, c) == color) {
341 // friendly group, does it have liberties?
342 group_t g = group_at(b, c);
343 if (board_group_info(b, g).libs == 1 || seen == g)
344 continue;
345 libs += board_group_info(b, g).libs - 1;
346 if (libs >= 2) return false;
347 // don't consider the same group twice
348 seen = g;
351 return true;
354 void
355 pattern_match(struct pattern_config *pc, pattern_spec ps,
356 struct pattern *p, struct board *b, struct move *m)
358 p->n = 0;
359 struct feature *f = &p->f[0];
361 /* TODO: We should match pretty much all of these features
362 * incrementally. */
364 if (is_pass(m->coord)) {
365 if (PS_ANY(PASS)) {
366 f->id = FEAT_PASS; f->payload = 0;
367 if (PS_PF(PASS, LASTPASS))
368 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
369 << PF_PASS_LASTPASS;
370 p->n++;
372 return;
375 if (PS_ANY(CAPTURE)) {
376 f = pattern_match_capture(pc, ps, p, f, b, m);
379 if (PS_ANY(AESCAPE)) {
380 f = pattern_match_aescape(pc, ps, p, f, b, m);
383 if (PS_ANY(SELFATARI)) {
384 bool simple = is_simple_selfatari(b, m->color, m->coord);
385 bool thorough = false;
386 if (PS_PF(SELFATARI, SMART)) {
387 thorough = is_bad_selfatari(b, m->color, m->coord);
389 if (simple || thorough) {
390 f->id = FEAT_SELFATARI;
391 f->payload = thorough << PF_SELFATARI_SMART;
392 (f++, p->n++);
396 if (PS_ANY(ATARI)) {
397 f = pattern_match_atari(pc, ps, p, f, b, m);
400 if (PS_ANY(BORDER)) {
401 int bdist = coord_edge_distance(m->coord, b);
402 if (bdist <= pc->bdist_max) {
403 f->id = FEAT_BORDER;
404 f->payload = bdist;
405 (f++, p->n++);
409 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
410 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
411 f->id = FEAT_CONTIGUITY;
412 f->payload = 1;
413 (f++, p->n++);
416 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
417 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
418 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
419 f->id = FEAT_LDIST;
420 f->payload = ldist;
421 (f++, p->n++);
425 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
426 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
427 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
428 f->id = FEAT_LLDIST;
429 f->payload = lldist;
430 (f++, p->n++);
434 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
435 f = pattern_match_spatial(pc, ps, p, f, b, m);
438 if (PS_ANY(PATTERN3) && !is_pass(m->coord)) {
439 #ifdef BOARD_PAT3
440 int pat = b->pat3[m->coord];
441 #else
442 int pat = pattern3_hash(b, m->coord);
443 #endif
444 if (m->color == S_WHITE) {
445 /* We work with the pattern3s as black-to-play. */
446 pat = pattern3_reverse(pat);
448 f->id = FEAT_PATTERN3;
449 f->payload = pat;
450 (f++, p->n++);
453 /* FEAT_MCOWNER: TODO */
454 assert(!pc->mcsims);
457 char *
458 pattern2str(char *str, struct pattern *p)
460 str = stpcpy(str, "(");
461 for (int i = 0; i < p->n; i++) {
462 if (i > 0) str = stpcpy(str, " ");
463 str = feature2str(str, &p->f[i]);
465 str = stpcpy(str, ")");
466 return str;
471 /*** Features gamma set */
473 static void
474 features_gamma_load(struct features_gamma *fg, const char *filename)
476 FILE *f = fopen(filename, "r");
477 if (!f) return;
478 char buf[256];
479 while (fgets(buf, 256, f)) {
480 char *bufp = buf;
481 struct feature f;
482 bufp = str2feature(bufp, &f);
483 while (isspace(*bufp)) bufp++;
484 float gamma = strtof(bufp, &bufp);
485 /* Record feature's gamma. */
486 feature_gamma(fg, &f, &gamma);
487 /* In case of 3x3 patterns, record gamma also
488 * for all rotations and transpositions. */
489 if (f.id == FEAT_PATTERN3) {
490 int transp[8];
491 pattern3_transpose(f.payload, &transp);
492 for (int i = 1; i < 8; i++) {
493 f.payload = transp[i];
494 feature_gamma(fg, &f, &gamma);
496 f.payload = transp[0];
499 fclose(f);
502 const char *features_gamma_filename = "patterns.gamma";
504 struct features_gamma *
505 features_gamma_init(struct pattern_config *pc, const char *file)
507 struct features_gamma *fg = calloc(1, sizeof(*fg));
508 fg->pc = pc;
509 for (int i = 0; i < FEAT_MAX; i++) {
510 int n = feature_payloads(pc, i);
511 fg->gamma[i] = malloc(n * sizeof(float));
512 for (int j = 0; j < n; j++) {
513 fg->gamma[i][j] = 1.0f;
516 features_gamma_load(fg, file ? file : features_gamma_filename);
517 return fg;
520 void
521 features_gamma_done(struct features_gamma *fg)
523 for (int i = 0; i < FEAT_MAX; i++)
524 free(fg->gamma[i]);
525 free(fg);