pattern_match_{capture,aescape}: Simplify trait-based PF test
[pachi.git] / pattern.c
blob07511020ab2d3a87ffc7cb42c4fa1f33a8f722d9
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 pattern_spec PATTERN_SPEC_MATCHFAST = {
49 [FEAT_PASS] = 0,
50 [FEAT_CAPTURE] = (1<<PF_CAPTURE_1STONE | 1<<PF_CAPTURE_TRAPPED),
51 [FEAT_AESCAPE] = (1<<PF_AESCAPE_1STONE | 1<<PF_AESCAPE_TRAPPED),
52 [FEAT_SELFATARI] = (1<<PF_SELFATARI_STUPID),
53 [FEAT_ATARI] = 0,
54 [FEAT_BORDER] = 0,
55 [FEAT_LDIST] = 0,
56 [FEAT_LLDIST] = 0,
57 [FEAT_CONTIGUITY] = ~0,
58 [FEAT_SPATIAL] = 0,
59 [FEAT_PATTERN3] = ~0,
60 [FEAT_MCOWNER] = 0,
63 static const struct feature_info {
64 char *name;
65 int payloads;
66 } features[FEAT_MAX] = {
67 [FEAT_PASS] = { .name = "pass", .payloads = 2 },
68 [FEAT_CAPTURE] = { .name = "capture", .payloads = 64 },
69 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 8 },
70 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 4 },
71 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
72 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
73 [FEAT_LDIST] = { .name = "ldist", .payloads = -1 },
74 [FEAT_LLDIST] = { .name = "lldist", .payloads = -1 },
75 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
76 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
77 [FEAT_PATTERN3] = { .name = "p", .payloads = 2<<16 },
78 [FEAT_MCOWNER] = { .name = "mcowner", .payloads = 16 },
81 char *
82 feature2str(char *str, struct feature *f)
84 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
87 char *
88 str2feature(char *str, struct feature *f)
90 while (isspace(*str)) str++;
92 int unsigned flen = strcspn(str, ":");
93 for (unsigned int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
94 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
95 f->id = i;
96 goto found;
98 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
99 exit(EXIT_FAILURE);
101 found:
102 str += flen + 1;
103 f->payload = strtoull(str, &str, 10);
104 return str;
107 char *
108 feature_name(enum feature_id f)
110 return features[f].name;
114 feature_payloads(struct pattern_config *pc, enum feature_id f)
116 switch (f) {
117 case FEAT_SPATIAL:
118 assert(features[f].payloads < 0);
119 return pc->spat_dict->nspatials;
120 case FEAT_LDIST:
121 case FEAT_LLDIST:
122 assert(features[f].payloads < 0);
123 return pc->ldist_max + 1;
124 case FEAT_BORDER:
125 assert(features[f].payloads < 0);
126 return pc->bdist_max + 1;
127 default:
128 assert(features[f].payloads > 0);
129 return features[f].payloads;
134 /* pattern_spec helpers */
135 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << 15))
136 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
138 static struct feature *
139 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
140 struct pattern *p, struct feature *f,
141 struct board *b, struct move *m)
143 f->id = FEAT_CAPTURE; f->payload = 0;
144 #ifdef BOARD_TRAITS
145 if (!trait_at(b, m->coord, m->color).cap)
146 return f;
147 /* Capturable! */
148 if (!(ps[FEAT_CAPTURE] & ~PATTERN_SPEC_MATCHFAST[FEAT_CAPTURE])) {
149 if (PS_PF(CAPTURE, 1STONE))
150 f->payload |= (trait_at(b, m->coord, m->color).cap1 == trait_at(b, m->coord, m->color).cap) << PF_CAPTURE_1STONE;
151 if (PS_PF(CAPTURE, TRAPPED))
152 f->payload |= (!trait_at(b, m->coord, stone_other(m->color)).safe) << PF_CAPTURE_TRAPPED;
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 /* We look at neighboring groups we could capture, and also if the
161 * opponent could save them. */
162 /* This is very similar in spirit to board_safe_to_play(), and almost
163 * a color inverse of pattern_match_aescape(). */
165 /* Whether an escape move would be safe for the opponent. */
166 int captures = 0;
167 coord_t onelib = -1;
168 int extra_libs = 0;
169 bool onestone = false, multistone = false;
171 foreach_neighbor(b, m->coord, {
172 if (board_at(b, c) != stone_other(m->color)) {
173 if (board_at(b, c) == S_NONE)
174 extra_libs++; // free point
175 else if (board_at(b, c) == m->color && board_group_info(b, group_at(b, c)).libs == 1)
176 extra_libs += 2; // capturable enemy group
177 continue;
180 group_t g = group_at(b, c); assert(g);
181 if (board_group_info(b, g).libs > 1) {
182 if (board_group_info(b, g).libs > 2) {
183 extra_libs += 2; // connected out
184 } else {
185 /* This is a bit tricky; we connect our 2-lib
186 * group to another 2-lib group, which counts
187 * as one liberty, but only if the other lib
188 * is not shared too. */
189 if (onelib == -1) {
190 onelib = board_group_other_lib(b, g, c);
191 extra_libs++;
192 } else {
193 if (c == onelib)
194 extra_libs--; // take that back
195 else
196 extra_libs++;
199 continue;
202 /* Capture! */
203 captures++;
205 if (PS_PF(CAPTURE, LADDER))
206 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
207 /* TODO: is_ladder() is too conservative in some
208 * very obvious situations, look at complete.gtp. */
210 /* TODO: PF_CAPTURE_RECAPTURE */
212 if (PS_PF(CAPTURE, ATARIDEF))
213 foreach_in_group(b, g) {
214 foreach_neighbor(b, c, {
215 assert(board_at(b, c) != S_NONE || c == m->coord);
216 if (board_at(b, c) != m->color)
217 continue;
218 group_t g = group_at(b, c);
219 if (!g || board_group_info(b, g).libs != 1)
220 continue;
221 /* A neighboring group of ours is in atari. */
222 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
224 } foreach_in_group_end;
226 if (PS_PF(CAPTURE, KO)
227 && group_is_onestone(b, g)
228 && neighbor_count_at(b, m->coord, stone_other(m->color))
229 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
230 f->payload |= 1 << PF_CAPTURE_KO;
232 if (group_is_onestone(b, g))
233 onestone = true;
234 else
235 multistone = true;
238 if (captures > 0) {
239 if (PS_PF(CAPTURE, 1STONE))
240 f->payload |= (onestone && !multistone) << PF_CAPTURE_1STONE;
241 if (PS_PF(CAPTURE, TRAPPED))
242 f->payload |= (extra_libs < 2) << PF_CAPTURE_TRAPPED;
243 (f++, p->n++);
245 return f;
248 static struct feature *
249 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
250 struct pattern *p, struct feature *f,
251 struct board *b, struct move *m)
253 f->id = FEAT_AESCAPE; f->payload = 0;
254 #ifdef BOARD_TRAITS
255 if (!trait_at(b, m->coord, stone_other(m->color)).cap)
256 return f;
257 /* Opponent can capture something! */
258 if (!(ps[FEAT_AESCAPE] & ~PATTERN_SPEC_MATCHFAST[FEAT_AESCAPE])) {
259 if (PS_PF(AESCAPE, 1STONE))
260 f->payload |= (trait_at(b, m->coord, stone_other(m->color)).cap1 == trait_at(b, m->coord, stone_other(m->color)).cap) << PF_AESCAPE_1STONE;
261 if (PS_PF(CAPTURE, TRAPPED))
262 f->payload |= (!trait_at(b, m->coord, m->color).safe) << PF_AESCAPE_TRAPPED;
263 (f++, p->n++);
264 return f;
266 /* We need to know details, so we still have to go through
267 * the neighbors. */
268 #endif
270 /* Find if a neighboring group of ours is in atari, AND that we provide
271 * a liberty to connect out. XXX: No connect-and-die check. */
272 /* This is very similar in spirit to board_safe_to_play(). */
273 group_t in_atari = -1;
274 coord_t onelib = -1;
275 int extra_libs = 0;
276 bool onestone = false, multistone = false;
278 foreach_neighbor(b, m->coord, {
279 if (board_at(b, c) != m->color) {
280 if (board_at(b, c) == S_NONE)
281 extra_libs++; // free point
282 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1) {
283 extra_libs += 2; // capturable enemy group
284 /* XXX: We just consider this move safe
285 * unconditionally. */
287 continue;
289 group_t g = group_at(b, c); assert(g);
290 if (board_group_info(b, g).libs > 1) {
291 if (board_group_info(b, g).libs > 2) {
292 extra_libs += 2; // connected out
293 } else {
294 /* This is a bit tricky; we connect our 2-lib
295 * group to another 2-lib group, which counts
296 * as one liberty, but only if the other lib
297 * is not shared too. */
298 if (onelib == -1) {
299 onelib = board_group_other_lib(b, g, c);
300 extra_libs++;
301 } else {
302 if (c == onelib)
303 extra_libs--; // take that back
304 else
305 extra_libs++;
308 continue;
311 /* In atari! */
312 in_atari = g;
314 if (PS_PF(AESCAPE, LADDER))
315 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
316 /* TODO: is_ladder() is too conservative in some
317 * very obvious situations, look at complete.gtp. */
319 if (group_is_onestone(b, g))
320 onestone = true;
321 else
322 multistone = true;
325 if (in_atari >= 0) {
326 if (PS_PF(AESCAPE, 1STONE))
327 f->payload |= (onestone && !multistone) << PF_AESCAPE_1STONE;
328 if (PS_PF(AESCAPE, TRAPPED))
329 f->payload |= (extra_libs < 2) << PF_AESCAPE_TRAPPED;
330 (f++, p->n++);
332 return f;
335 static struct feature *
336 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
337 struct pattern *p, struct feature *f,
338 struct board *b, struct move *m)
340 foreach_neighbor(b, m->coord, {
341 if (board_at(b, c) != stone_other(m->color))
342 continue;
343 group_t g = group_at(b, c);
344 if (!g || board_group_info(b, g).libs != 2)
345 continue;
347 /* Can atari! */
348 f->id = FEAT_ATARI; f->payload = 0;
350 if (PS_PF(ATARI, LADDER)) {
351 /* Opponent will escape by the other lib. */
352 coord_t lib = board_group_other_lib(b, g, m->coord);
353 /* TODO: is_ladder() is too conservative in some
354 * very obvious situations, look at complete.gtp. */
355 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
358 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
359 f->payload |= 1 << PF_ATARI_KO;
361 (f++, p->n++);
363 return f;
366 #ifndef BOARD_SPATHASH
367 #undef BOARD_SPATHASH_MAXD
368 #define BOARD_SPATHASH_MAXD 1
369 #endif
371 /* Match spatial features that are too distant to be pre-matched
372 * incrementally. */
373 struct feature *
374 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
375 struct pattern *p, struct feature *f,
376 struct board *b, struct move *m, hash_t h)
378 /* We record all spatial patterns black-to-play; simply
379 * reverse all colors if we are white-to-play. */
380 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
381 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
382 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
384 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
385 /* Recompute missing outer circles:
386 * Go through all points in given distance. */
387 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
388 ptcoords_at(x, y, m->coord, b, j);
389 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
391 if (d < pc->spat_min)
392 continue;
393 /* Record spatial feature, one per distance. */
394 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
395 if (sid > 0) {
396 f->id = FEAT_SPATIAL;
397 f->payload = sid;
398 (f++, p->n++);
399 } /* else not found, ignore */
401 return f;
404 struct feature *
405 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
406 struct pattern *p, struct feature *f,
407 struct board *b, struct move *m)
409 /* XXX: This is partially duplicated from spatial_from_board(), but
410 * we build a hash instead of spatial record. */
412 assert(pc->spat_min > 0);
414 hash_t h = pthashes[0][0][S_NONE];
415 #ifdef BOARD_SPATHASH
416 bool w_to_play = m->color == S_WHITE;
417 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
418 /* Reuse all incrementally matched data. */
419 h ^= b->spathash[m->coord][d - 1][w_to_play];
420 if (d < pc->spat_min)
421 continue;
422 /* Record spatial feature, one per distance. */
423 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
424 if (sid > 0) {
425 f->id = FEAT_SPATIAL;
426 f->payload = sid;
427 (f++, p->n++);
428 } /* else not found, ignore */
430 #else
431 assert(BOARD_SPATHASH_MAXD < 2);
432 #endif
433 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
434 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
435 return f;
439 void
440 pattern_match(struct pattern_config *pc, pattern_spec ps,
441 struct pattern *p, struct board *b, struct move *m)
443 p->n = 0;
444 struct feature *f = &p->f[0];
446 /* TODO: We should match pretty much all of these features
447 * incrementally. */
449 if (is_pass(m->coord)) {
450 if (PS_ANY(PASS)) {
451 f->id = FEAT_PASS; f->payload = 0;
452 if (PS_PF(PASS, LASTPASS))
453 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
454 << PF_PASS_LASTPASS;
455 p->n++;
457 return;
460 if (PS_ANY(CAPTURE)) {
461 f = pattern_match_capture(pc, ps, p, f, b, m);
464 if (PS_ANY(AESCAPE)) {
465 f = pattern_match_aescape(pc, ps, p, f, b, m);
468 if (PS_ANY(SELFATARI)) {
469 bool simple = false;
470 if (PS_PF(SELFATARI, STUPID)) {
471 #ifdef BOARD_TRAITS
472 if (!b->precise_selfatari)
473 simple = !trait_at(b, m->coord, m->color).safe;
474 else
475 #endif
476 simple = !board_safe_to_play(b, m->coord, m->color);
478 bool thorough = false;
479 if (PS_PF(SELFATARI, SMART)) {
480 #ifdef BOARD_TRAITS
481 if (b->precise_selfatari)
482 thorough = !trait_at(b, m->coord, m->color).safe;
483 else
484 #endif
485 thorough = is_bad_selfatari(b, m->color, m->coord);
487 if (simple || thorough) {
488 f->id = FEAT_SELFATARI;
489 f->payload = simple << PF_SELFATARI_STUPID;
490 f->payload |= thorough << PF_SELFATARI_SMART;
491 (f++, p->n++);
495 if (PS_ANY(ATARI)) {
496 f = pattern_match_atari(pc, ps, p, f, b, m);
499 if (PS_ANY(BORDER)) {
500 int bdist = coord_edge_distance(m->coord, b);
501 if (bdist <= pc->bdist_max) {
502 f->id = FEAT_BORDER;
503 f->payload = bdist;
504 (f++, p->n++);
508 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
509 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
510 f->id = FEAT_CONTIGUITY;
511 f->payload = 1;
512 (f++, p->n++);
515 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
516 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
517 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
518 f->id = FEAT_LDIST;
519 f->payload = ldist;
520 (f++, p->n++);
524 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
525 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
526 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
527 f->id = FEAT_LLDIST;
528 f->payload = lldist;
529 (f++, p->n++);
533 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
534 f = pattern_match_spatial(pc, ps, p, f, b, m);
537 if (PS_ANY(PATTERN3) && !is_pass(m->coord)) {
538 #ifdef BOARD_PAT3
539 hash3_t pat = b->pat3[m->coord];
540 #else
541 hash3_t pat = pattern3_hash(b, m->coord);
542 #endif
543 if (m->color == S_WHITE) {
544 /* We work with the pattern3s as black-to-play. */
545 pat = pattern3_reverse(pat);
547 f->id = FEAT_PATTERN3;
548 f->payload = pat;
549 (f++, p->n++);
552 /* FEAT_MCOWNER: TODO */
553 assert(!pc->mcsims);
556 char *
557 pattern2str(char *str, struct pattern *p)
559 str = stpcpy(str, "(");
560 for (int i = 0; i < p->n; i++) {
561 if (i > 0) str = stpcpy(str, " ");
562 str = feature2str(str, &p->f[i]);
564 str = stpcpy(str, ")");
565 return str;
570 /*** Features gamma set */
572 static void
573 features_gamma_load(struct features_gamma *fg, const char *filename)
575 FILE *f = fopen(filename, "r");
576 if (!f) return;
577 char buf[256];
578 while (fgets(buf, 256, f)) {
579 char *bufp = buf;
580 struct feature f;
581 bufp = str2feature(bufp, &f);
582 while (isspace(*bufp)) bufp++;
583 double gamma = strtod(bufp, &bufp);
584 /* Record feature's gamma. */
585 feature_gamma(fg, &f, &gamma);
586 /* In case of 3x3 patterns, record gamma also
587 * for all rotations and transpositions. */
588 if (f.id == FEAT_PATTERN3) {
589 hash3_t transp[8];
590 pattern3_transpose(f.payload, &transp);
591 for (int i = 1; i < 8; i++) {
592 f.payload = transp[i];
593 feature_gamma(fg, &f, &gamma);
595 f.payload = transp[0];
598 fclose(f);
601 const char *features_gamma_filename = "patterns.gamma";
603 struct features_gamma *
604 features_gamma_init(struct pattern_config *pc, const char *file)
606 struct features_gamma *fg = calloc2(1, sizeof(*fg));
607 fg->pc = pc;
608 for (int i = 0; i < FEAT_MAX; i++) {
609 int n = feature_payloads(pc, i);
610 fg->gamma[i] = malloc2(n * sizeof(fg->gamma[0][0]));
611 for (int j = 0; j < n; j++) {
612 fg->gamma[i][j] = 1.0f;
615 features_gamma_load(fg, file ? file : features_gamma_filename);
616 return fg;
619 void
620 features_gamma_done(struct features_gamma *fg)
622 for (int i = 0; i < FEAT_MAX; i++)
623 free(fg->gamma[i]);
624 free(fg);