pattern_match_{capture,aescape}: Fix trapped to work the same as board safety check
[pachi/pachi-r6144.git] / pattern.c
blob5e78c500194bfea086346747d620c8cb31c3b320
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 | 1<<PF_CAPTURE_KO),
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 = 64 },
70 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 8 },
71 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 4 },
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 unsigned flen = strcspn(str, ":");
94 for (unsigned 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 if (PS_PF(CAPTURE, 1STONE))
154 f->payload |= (trait_at(b, m->coord, m->color).cap1 == trait_at(b, m->coord, m->color).cap) << PF_CAPTURE_1STONE;
155 if (PS_PF(CAPTURE, TRAPPED))
156 f->payload |= (!trait_at(b, m->coord, stone_other(m->color)).safe) << PF_CAPTURE_TRAPPED;
157 (f++, p->n++);
158 return f;
160 /* We need to know details, so we still have to go through
161 * the neighbors. */
162 #endif
164 /* We look at neighboring groups we could capture, and also if the
165 * opponent could save them. */
166 /* This is very similar in spirit to board_safe_to_play(), and almost
167 * a color inverse of pattern_match_aescape(). */
169 /* Whether an escape move would be safe for the opponent. */
170 int captures = 0;
171 coord_t onelib = -1;
172 int extra_libs = 0;
173 bool onestone = false, multistone = false;
175 foreach_neighbor(b, m->coord, {
176 if (board_at(b, c) != stone_other(m->color)) {
177 if (board_at(b, c) == S_NONE)
178 extra_libs++; // free point
179 else if (board_at(b, c) == m->color && board_group_info(b, group_at(b, c)).libs == 1)
180 extra_libs += 2; // capturable enemy group
181 continue;
184 group_t g = group_at(b, c); assert(g);
185 if (board_group_info(b, g).libs > 1) {
186 if (board_group_info(b, g).libs > 2) {
187 extra_libs += 2; // connected out
188 } else {
189 /* This is a bit tricky; we connect our 2-lib
190 * group to another 2-lib group, which counts
191 * as one liberty, but only if the other lib
192 * is not shared too. */
193 if (onelib == -1) {
194 onelib = board_group_other_lib(b, g, c);
195 extra_libs++;
196 } else {
197 if (c == onelib)
198 extra_libs--; // take that back
199 else
200 extra_libs++;
203 continue;
206 /* Capture! */
207 captures++;
209 if (PS_PF(CAPTURE, LADDER))
210 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
211 /* TODO: is_ladder() is too conservative in some
212 * very obvious situations, look at complete.gtp. */
214 /* TODO: PF_CAPTURE_RECAPTURE */
216 if (PS_PF(CAPTURE, ATARIDEF))
217 foreach_in_group(b, g) {
218 foreach_neighbor(b, c, {
219 assert(board_at(b, c) != S_NONE || c == m->coord);
220 if (board_at(b, c) != m->color)
221 continue;
222 group_t g = group_at(b, c);
223 if (!g || board_group_info(b, g).libs != 1)
224 continue;
225 /* A neighboring group of ours is in atari. */
226 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
228 } foreach_in_group_end;
230 if (PS_PF(CAPTURE, KO)
231 && group_is_onestone(b, g)
232 && neighbor_count_at(b, m->coord, stone_other(m->color))
233 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
234 f->payload |= 1 << PF_CAPTURE_KO;
236 if (group_is_onestone(b, g))
237 onestone = true;
238 else
239 multistone = true;
242 if (captures > 0) {
243 if (PS_PF(CAPTURE, 1STONE))
244 f->payload |= (onestone && !multistone) << PF_CAPTURE_1STONE;
245 if (PS_PF(CAPTURE, TRAPPED))
246 f->payload |= (extra_libs < 2) << PF_CAPTURE_TRAPPED;
247 (f++, p->n++);
249 return f;
252 static struct feature *
253 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
254 struct pattern *p, struct feature *f,
255 struct board *b, struct move *m)
257 f->id = FEAT_AESCAPE; f->payload = 0;
258 #ifdef BOARD_TRAITS
259 if (!trait_at(b, m->coord, stone_other(m->color)).cap)
260 return f;
261 /* Opponent can capture something! */
262 if (!PS_PF(AESCAPE, LADDER)) {
263 if (PS_PF(AESCAPE, 1STONE))
264 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;
265 if (PS_PF(CAPTURE, TRAPPED))
266 f->payload |= (!trait_at(b, m->coord, m->color).safe) << PF_AESCAPE_TRAPPED;
267 (f++, p->n++);
268 return f;
270 /* We need to know details, so we still have to go through
271 * the neighbors. */
272 #endif
274 /* Find if a neighboring group of ours is in atari, AND that we provide
275 * a liberty to connect out. XXX: No connect-and-die check. */
276 /* This is very similar in spirit to board_safe_to_play(). */
277 group_t in_atari = -1;
278 coord_t onelib = -1;
279 int extra_libs = 0;
280 bool onestone = false, multistone = false;
282 foreach_neighbor(b, m->coord, {
283 if (board_at(b, c) != m->color) {
284 if (board_at(b, c) == S_NONE)
285 extra_libs++; // free point
286 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1) {
287 extra_libs += 2; // capturable enemy group
288 /* XXX: We just consider this move safe
289 * unconditionally. */
291 continue;
293 group_t g = group_at(b, c); assert(g);
294 if (board_group_info(b, g).libs > 1) {
295 if (board_group_info(b, g).libs > 2) {
296 extra_libs += 2; // connected out
297 } else {
298 /* This is a bit tricky; we connect our 2-lib
299 * group to another 2-lib group, which counts
300 * as one liberty, but only if the other lib
301 * is not shared too. */
302 if (onelib == -1) {
303 onelib = board_group_other_lib(b, g, c);
304 extra_libs++;
305 } else {
306 if (c == onelib)
307 extra_libs--; // take that back
308 else
309 extra_libs++;
312 continue;
315 /* In atari! */
316 in_atari = g;
318 if (PS_PF(AESCAPE, LADDER))
319 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
320 /* TODO: is_ladder() is too conservative in some
321 * very obvious situations, look at complete.gtp. */
323 if (group_is_onestone(b, g))
324 onestone = true;
325 else
326 multistone = true;
329 if (in_atari >= 0) {
330 if (PS_PF(AESCAPE, 1STONE))
331 f->payload |= (onestone && !multistone) << PF_AESCAPE_1STONE;
332 if (PS_PF(AESCAPE, TRAPPED))
333 f->payload |= (extra_libs < 2) << PF_AESCAPE_TRAPPED;
334 (f++, p->n++);
336 return f;
339 static struct feature *
340 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
341 struct pattern *p, struct feature *f,
342 struct board *b, struct move *m)
344 foreach_neighbor(b, m->coord, {
345 if (board_at(b, c) != stone_other(m->color))
346 continue;
347 group_t g = group_at(b, c);
348 if (!g || board_group_info(b, g).libs != 2)
349 continue;
351 /* Can atari! */
352 f->id = FEAT_ATARI; f->payload = 0;
354 if (PS_PF(ATARI, LADDER)) {
355 /* Opponent will escape by the other lib. */
356 coord_t lib = board_group_other_lib(b, g, m->coord);
357 /* TODO: is_ladder() is too conservative in some
358 * very obvious situations, look at complete.gtp. */
359 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
362 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
363 f->payload |= 1 << PF_ATARI_KO;
365 (f++, p->n++);
367 return f;
370 #ifndef BOARD_SPATHASH
371 #undef BOARD_SPATHASH_MAXD
372 #define BOARD_SPATHASH_MAXD 1
373 #endif
375 /* Match spatial features that are too distant to be pre-matched
376 * incrementally. */
377 struct feature *
378 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
379 struct pattern *p, struct feature *f,
380 struct board *b, struct move *m, hash_t h)
382 /* We record all spatial patterns black-to-play; simply
383 * reverse all colors if we are white-to-play. */
384 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
385 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
386 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
388 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
389 /* Recompute missing outer circles:
390 * Go through all points in given distance. */
391 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
392 ptcoords_at(x, y, m->coord, b, j);
393 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
395 if (d < pc->spat_min)
396 continue;
397 /* Record spatial feature, one per distance. */
398 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
399 if (sid > 0) {
400 f->id = FEAT_SPATIAL;
401 f->payload = sid;
402 (f++, p->n++);
403 } /* else not found, ignore */
405 return f;
408 struct feature *
409 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
410 struct pattern *p, struct feature *f,
411 struct board *b, struct move *m)
413 /* XXX: This is partially duplicated from spatial_from_board(), but
414 * we build a hash instead of spatial record. */
416 assert(pc->spat_min > 0);
418 hash_t h = pthashes[0][0][S_NONE];
419 #ifdef BOARD_SPATHASH
420 bool w_to_play = m->color == S_WHITE;
421 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
422 /* Reuse all incrementally matched data. */
423 h ^= b->spathash[m->coord][d - 1][w_to_play];
424 if (d < pc->spat_min)
425 continue;
426 /* Record spatial feature, one per distance. */
427 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
428 if (sid > 0) {
429 f->id = FEAT_SPATIAL;
430 f->payload = sid;
431 (f++, p->n++);
432 } /* else not found, ignore */
434 #else
435 assert(BOARD_SPATHASH_MAXD < 2);
436 #endif
437 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
438 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
439 return f;
443 void
444 pattern_match(struct pattern_config *pc, pattern_spec ps,
445 struct pattern *p, struct board *b, struct move *m)
447 p->n = 0;
448 struct feature *f = &p->f[0];
450 /* TODO: We should match pretty much all of these features
451 * incrementally. */
453 if (is_pass(m->coord)) {
454 if (PS_ANY(PASS)) {
455 f->id = FEAT_PASS; f->payload = 0;
456 if (PS_PF(PASS, LASTPASS))
457 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
458 << PF_PASS_LASTPASS;
459 p->n++;
461 return;
464 if (PS_ANY(CAPTURE)) {
465 f = pattern_match_capture(pc, ps, p, f, b, m);
468 if (PS_ANY(AESCAPE)) {
469 f = pattern_match_aescape(pc, ps, p, f, b, m);
472 if (PS_ANY(SELFATARI)) {
473 bool simple = false;
474 if (PS_PF(SELFATARI, STUPID)) {
475 #ifdef BOARD_TRAITS
476 if (!b->precise_selfatari)
477 simple = !trait_at(b, m->coord, m->color).safe;
478 else
479 #endif
480 simple = !board_safe_to_play(b, m->coord, m->color);
482 bool thorough = false;
483 if (PS_PF(SELFATARI, SMART)) {
484 #ifdef BOARD_TRAITS
485 if (b->precise_selfatari)
486 thorough = !trait_at(b, m->coord, m->color).safe;
487 else
488 #endif
489 thorough = is_bad_selfatari(b, m->color, m->coord);
491 if (simple || thorough) {
492 f->id = FEAT_SELFATARI;
493 f->payload = simple << PF_SELFATARI_STUPID;
494 f->payload |= thorough << PF_SELFATARI_SMART;
495 (f++, p->n++);
499 if (PS_ANY(ATARI)) {
500 f = pattern_match_atari(pc, ps, p, f, b, m);
503 if (PS_ANY(BORDER)) {
504 int bdist = coord_edge_distance(m->coord, b);
505 if (bdist <= pc->bdist_max) {
506 f->id = FEAT_BORDER;
507 f->payload = bdist;
508 (f++, p->n++);
512 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
513 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
514 f->id = FEAT_CONTIGUITY;
515 f->payload = 1;
516 (f++, p->n++);
519 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
520 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
521 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
522 f->id = FEAT_LDIST;
523 f->payload = ldist;
524 (f++, p->n++);
528 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
529 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
530 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
531 f->id = FEAT_LLDIST;
532 f->payload = lldist;
533 (f++, p->n++);
537 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
538 f = pattern_match_spatial(pc, ps, p, f, b, m);
541 if (PS_ANY(PATTERN3) && !is_pass(m->coord)) {
542 #ifdef BOARD_PAT3
543 hash3_t pat = b->pat3[m->coord];
544 #else
545 hash3_t pat = pattern3_hash(b, m->coord);
546 #endif
547 if (m->color == S_WHITE) {
548 /* We work with the pattern3s as black-to-play. */
549 pat = pattern3_reverse(pat);
551 f->id = FEAT_PATTERN3;
552 f->payload = pat;
553 (f++, p->n++);
556 /* FEAT_MCOWNER: TODO */
557 assert(!pc->mcsims);
560 char *
561 pattern2str(char *str, struct pattern *p)
563 str = stpcpy(str, "(");
564 for (int i = 0; i < p->n; i++) {
565 if (i > 0) str = stpcpy(str, " ");
566 str = feature2str(str, &p->f[i]);
568 str = stpcpy(str, ")");
569 return str;
574 /*** Features gamma set */
576 static void
577 features_gamma_load(struct features_gamma *fg, const char *filename)
579 FILE *f = fopen(filename, "r");
580 if (!f) return;
581 char buf[256];
582 while (fgets(buf, 256, f)) {
583 char *bufp = buf;
584 struct feature f;
585 bufp = str2feature(bufp, &f);
586 while (isspace(*bufp)) bufp++;
587 double gamma = strtod(bufp, &bufp);
588 /* Record feature's gamma. */
589 feature_gamma(fg, &f, &gamma);
590 /* In case of 3x3 patterns, record gamma also
591 * for all rotations and transpositions. */
592 if (f.id == FEAT_PATTERN3) {
593 hash3_t transp[8];
594 pattern3_transpose(f.payload, &transp);
595 for (int i = 1; i < 8; i++) {
596 f.payload = transp[i];
597 feature_gamma(fg, &f, &gamma);
599 f.payload = transp[0];
602 fclose(f);
605 const char *features_gamma_filename = "patterns.gamma";
607 struct features_gamma *
608 features_gamma_init(struct pattern_config *pc, const char *file)
610 struct features_gamma *fg = calloc2(1, sizeof(*fg));
611 fg->pc = pc;
612 for (int i = 0; i < FEAT_MAX; i++) {
613 int n = feature_payloads(pc, i);
614 fg->gamma[i] = malloc2(n * sizeof(fg->gamma[0][0]));
615 for (int j = 0; j < n; j++) {
616 fg->gamma[i][j] = 1.0f;
619 features_gamma_load(fg, file ? file : features_gamma_filename);
620 return fg;
623 void
624 features_gamma_done(struct features_gamma *fg)
626 for (int i = 0; i < FEAT_MAX; i++)
627 free(fg->gamma[i]);
628 free(fg);