PS_ANY(): Fix for reduced patternspec size
[pachi.git] / pattern.c
bloba0b37cec208b526ee25066bc5914d126427ca759
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 "tactics.h"
15 struct pattern_config DEFAULT_PATTERN_CONFIG = {
16 .spat_min = 3, .spat_max = MAX_PATTERN_DIST,
17 .bdist_max = 4,
18 .ldist_min = 0, .ldist_max = 256,
19 .mcsims = 0, /* Unsupported. */
22 struct pattern_config FAST_PATTERN_CONFIG = {
23 .spat_min = 3, .spat_max = 3,
24 .bdist_max = -1,
25 .ldist_min = 0, .ldist_max = 256,
26 .mcsims = 0,
29 pattern_spec PATTERN_SPEC_MATCHALL = {
30 [FEAT_PASS] = ~0,
31 [FEAT_CAPTURE] = ~0,
32 [FEAT_AESCAPE] = ~0,
33 [FEAT_SELFATARI] = ~0,
34 [FEAT_ATARI] = ~0,
35 [FEAT_BORDER] = ~0,
36 [FEAT_LDIST] = ~0,
37 [FEAT_LLDIST] = ~0,
38 [FEAT_CONTIGUITY] = ~0,
39 [FEAT_SPATIAL] = ~0,
40 [FEAT_MCOWNER] = ~0,
43 #define FAST_NO_LADDER 1 /* 1: Don't match ladders in fast playouts */
44 pattern_spec PATTERN_SPEC_MATCHFAST = {
45 [FEAT_PASS] = ~0,
46 [FEAT_CAPTURE] = ~(1<<PF_CAPTURE_ATARIDEF | 1<<PF_CAPTURE_RECAPTURE | FAST_NO_LADDER<<PF_CAPTURE_LADDER),
47 [FEAT_AESCAPE] = ~(FAST_NO_LADDER<<PF_AESCAPE_LADDER),
48 [FEAT_SELFATARI] = ~(1<<PF_SELFATARI_SMART),
49 [FEAT_ATARI] = ~(FAST_NO_LADDER<<PF_ATARI_LADDER),
50 [FEAT_BORDER] = 0,
51 [FEAT_LDIST] = 0,
52 [FEAT_LLDIST] = 0,
53 [FEAT_CONTIGUITY] = ~0,
54 [FEAT_SPATIAL] = ~0,
55 [FEAT_MCOWNER] = ~0,
58 static const struct feature_info {
59 char *name;
60 int payloads;
61 } features[FEAT_MAX] = {
62 [FEAT_PASS] = { .name = "pass", .payloads = 2 },
63 [FEAT_CAPTURE] = { .name = "capture", .payloads = 16 },
64 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 2 },
65 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 2 },
66 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
67 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
68 [FEAT_LDIST] = { .name = "ldist", .payloads = -1 },
69 [FEAT_LLDIST] = { .name = "lldist", .payloads = -1 },
70 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
71 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
72 [FEAT_MCOWNER] = { .name = "mcowner", .payloads = 16 },
75 char *
76 feature2str(char *str, struct feature *f)
78 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
81 char *
82 str2feature(char *str, struct feature *f)
84 while (isspace(*str)) str++;
86 int flen = strcspn(str, ":");
87 for (int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
88 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
89 f->id = i;
90 goto found;
92 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
93 exit(EXIT_FAILURE);
95 found:
96 str += flen + 1;
97 f->payload = strtoull(str, &str, 10);
98 return str;
102 feature_payloads(struct pattern_config *pc, enum feature_id f)
104 switch (f) {
105 case FEAT_SPATIAL:
106 assert(features[f].payloads < 0);
107 return pc->spat_dict->nspatials;
108 case FEAT_LDIST:
109 case FEAT_LLDIST:
110 assert(features[f].payloads < 0);
111 return pc->ldist_max + 1;
112 case FEAT_BORDER:
113 assert(features[f].payloads < 0);
114 return pc->bdist_max + 1;
115 default:
116 assert(features[f].payloads > 0);
117 return features[f].payloads;
122 /* pattern_spec helpers */
123 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << 15))
124 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
126 static struct feature *
127 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
128 struct pattern *p, struct feature *f,
129 struct board *b, struct move *m)
131 foreach_neighbor(b, m->coord, {
132 if (board_at(b, c) != stone_other(m->color))
133 continue;
134 group_t g = group_at(b, c);
135 if (!g || board_group_info(b, g).libs != 1)
136 continue;
138 /* Capture! */
139 f->id = FEAT_CAPTURE; f->payload = 0;
141 if (PS_PF(CAPTURE, LADDER))
142 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
143 /* TODO: is_ladder() is too conservative in some
144 * very obvious situations, look at complete.gtp. */
146 /* TODO: PF_CAPTURE_RECAPTURE */
148 if (PS_PF(CAPTURE, ATARIDEF))
149 foreach_in_group(b, g) {
150 foreach_neighbor(b, c, {
151 assert(board_at(b, c) != S_NONE || c == m->coord);
152 if (board_at(b, c) != m->color)
153 continue;
154 group_t g = group_at(b, c);
155 if (!g || board_group_info(b, g).libs != 1)
156 continue;
157 /* A neighboring group of ours is in atari. */
158 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
160 } foreach_in_group_end;
162 if (PS_PF(CAPTURE, KO)
163 && group_is_onestone(b, g)
164 && neighbor_count_at(b, m->coord, stone_other(m->color))
165 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
166 f->payload |= 1 << PF_CAPTURE_KO;
168 (f++, p->n++);
170 return f;
173 static struct feature *
174 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
175 struct pattern *p, struct feature *f,
176 struct board *b, struct move *m)
178 /* Find if a neighboring group of ours is in atari, AND that we provide
179 * a liberty to connect out. XXX: No connect-and-die check. */
180 group_t in_atari = -1;
181 bool has_extra_lib = false;
182 int payload = 0;
184 foreach_neighbor(b, m->coord, {
185 if (board_at(b, c) != m->color) {
186 if (board_at(b, c) == S_NONE)
187 has_extra_lib = true; // free point
188 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1)
189 has_extra_lib = true; // capturable enemy group
190 continue;
192 group_t g = group_at(b, c); assert(g);
193 if (board_group_info(b, g).libs != 1) {
194 has_extra_lib = true;
195 continue;
198 /* In atari! */
199 in_atari = g;
201 if (PS_PF(AESCAPE, LADDER))
202 payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
203 /* TODO: is_ladder() is too conservative in some
204 * very obvious situations, look at complete.gtp. */
206 if (in_atari >= 0 && has_extra_lib) {
207 f->id = FEAT_AESCAPE; f->payload = payload;
208 (f++, p->n++);
210 return f;
213 static struct feature *
214 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
215 struct pattern *p, struct feature *f,
216 struct board *b, struct move *m)
218 foreach_neighbor(b, m->coord, {
219 if (board_at(b, c) != stone_other(m->color))
220 continue;
221 group_t g = group_at(b, c);
222 if (!g || board_group_info(b, g).libs != 2)
223 continue;
225 /* Can atari! */
226 f->id = FEAT_ATARI; f->payload = 0;
228 if (PS_PF(ATARI, LADDER)) {
229 /* Opponent will escape by the other lib. */
230 coord_t lib = board_group_info(b, g).lib[0];
231 if (lib == m->coord) lib = board_group_info(b, g).lib[1];
232 /* TODO: is_ladder() is too conservative in some
233 * very obvious situations, look at complete.gtp. */
234 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
237 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
238 f->payload |= 1 << PF_ATARI_KO;
240 (f++, p->n++);
242 return f;
245 #ifndef BOARD_SPATHASH
246 #undef BOARD_SPATHASH_MAXD
247 #define BOARD_SPATHASH_MAXD 1
248 #endif
250 /* Match spatial features that are too distant to be pre-matched
251 * incrementally. */
252 struct feature *
253 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
254 struct pattern *p, struct feature *f,
255 struct board *b, struct move *m, hash_t h)
257 /* We record all spatial patterns black-to-play; simply
258 * reverse all colors if we are white-to-play. */
259 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
260 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
261 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
263 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
264 /* Recompute missing outer circles:
265 * Go through all points in given distance. */
266 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
267 ptcoords_at(x, y, m->coord, b, j);
268 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
270 if (d < pc->spat_min)
271 continue;
272 /* Record spatial feature, one per distance. */
273 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
274 if (sid > 0) {
275 f->id = FEAT_SPATIAL;
276 f->payload = sid;
277 (f++, p->n++);
278 } /* else not found, ignore */
280 return f;
283 struct feature *
284 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
285 struct pattern *p, struct feature *f,
286 struct board *b, struct move *m)
288 /* XXX: This is partially duplicated from spatial_from_board(), but
289 * we build a hash instead of spatial record. */
291 assert(pc->spat_min > 0);
293 bool w_to_play = m->color == S_WHITE;
294 hash_t h = pthashes[0][0][S_NONE];
295 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
296 /* Reuse all incrementally matched data. */
297 h ^= b->spathash[m->coord][d - 1][w_to_play];
298 if (d < pc->spat_min)
299 continue;
300 /* Record spatial feature, one per distance. */
301 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
302 if (sid > 0) {
303 f->id = FEAT_SPATIAL;
304 f->payload = sid;
305 (f++, p->n++);
306 } /* else not found, ignore */
308 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
309 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
310 return f;
314 static bool
315 is_simple_selfatari(struct board *b, enum stone color, coord_t coord)
317 /* Very rough check, no connect-and-die checks or other trickery. */
318 int libs = immediate_liberty_count(b, coord);
319 if (libs >= 2) return false; // open space
321 group_t seen = -1;
322 foreach_neighbor(b, coord, {
323 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1) {
324 return false; // can capture
326 } else if (board_at(b, c) == color) {
327 // friendly group, does it have liberties?
328 group_t g = group_at(b, c);
329 if (board_group_info(b, g).libs == 1 || seen == g)
330 continue;
331 libs += board_group_info(b, g).libs - 1;
332 if (libs >= 2) return false;
333 // don't consider the same group twice
334 seen = g;
337 return true;
340 void
341 pattern_match(struct pattern_config *pc, pattern_spec ps,
342 struct pattern *p, struct board *b, struct move *m)
344 p->n = 0;
345 struct feature *f = &p->f[0];
347 /* TODO: We should match pretty much all of these features
348 * incrementally. */
350 if (is_pass(m->coord)) {
351 if (PS_ANY(PASS)) {
352 f->id = FEAT_PASS; f->payload = 0;
353 if (PS_PF(PASS, LASTPASS))
354 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
355 << PF_PASS_LASTPASS;
356 p->n++;
358 return;
361 if (PS_ANY(CAPTURE)) {
362 f = pattern_match_capture(pc, ps, p, f, b, m);
365 if (PS_ANY(AESCAPE)) {
366 f = pattern_match_aescape(pc, ps, p, f, b, m);
369 if (PS_ANY(SELFATARI)) {
370 bool simple = is_simple_selfatari(b, m->color, m->coord);
371 bool thorough = false;
372 if (PS_PF(SELFATARI, SMART)) {
373 thorough = is_bad_selfatari(b, m->color, m->coord);
375 if (simple || thorough) {
376 f->id = FEAT_SELFATARI;
377 f->payload = thorough << PF_SELFATARI_SMART;
378 (f++, p->n++);
382 if (PS_ANY(ATARI)) {
383 f = pattern_match_atari(pc, ps, p, f, b, m);
386 if (PS_ANY(BORDER)) {
387 int bdist = coord_edge_distance(m->coord, b);
388 if (bdist <= pc->bdist_max) {
389 f->id = FEAT_BORDER;
390 f->payload = bdist;
391 (f++, p->n++);
395 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
396 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
397 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
398 f->id = FEAT_LDIST;
399 f->payload = ldist;
400 (f++, p->n++);
404 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
405 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
406 f->id = FEAT_CONTIGUITY;
407 f->payload = 1;
408 (f++, p->n++);
411 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
412 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
413 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
414 f->id = FEAT_LLDIST;
415 f->payload = lldist;
416 (f++, p->n++);
420 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
421 f = pattern_match_spatial(pc, ps, p, f, b, m);
424 /* FEAT_MCOWNER: TODO */
425 assert(!pc->mcsims);
428 char *
429 pattern2str(char *str, struct pattern *p)
431 str = stpcpy(str, "(");
432 for (int i = 0; i < p->n; i++) {
433 if (i > 0) str = stpcpy(str, " ");
434 str = feature2str(str, &p->f[i]);
436 str = stpcpy(str, ")");
437 return str;
442 /*** Features gamma set */
444 static void
445 features_gamma_load(struct features_gamma *fg, const char *filename)
447 FILE *f = fopen(filename, "r");
448 if (!f) return;
449 char buf[256];
450 while (fgets(buf, 256, f)) {
451 char *bufp = buf;
452 struct feature f;
453 bufp = str2feature(bufp, &f);
454 while (isspace(*bufp)) bufp++;
455 float gamma = strtof(bufp, &bufp);
456 feature_gamma(fg, &f, &gamma);
458 fclose(f);
461 const char *features_gamma_filename = "patterns.gamma";
463 struct features_gamma *
464 features_gamma_init(struct pattern_config *pc, const char *file)
466 struct features_gamma *fg = calloc(1, sizeof(*fg));
467 fg->pc = pc;
468 for (int i = 0; i < FEAT_MAX; i++) {
469 int n = feature_payloads(pc, i);
470 fg->gamma[i] = malloc(n * sizeof(float));
471 for (int j = 0; j < n; j++) {
472 fg->gamma[i][j] = 1.0f;
475 features_gamma_load(fg, file ? file : features_gamma_filename);
476 return fg;