Patternscan: Use patterns_init()
[pachi.git] / pattern.c
blob6894387546fa16835f2334dc11d163315ed0da1a
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 "patternprob.h"
13 #include "tactics/ladder.h"
14 #include "tactics/selfatari.h"
15 #include "tactics/util.h"
18 struct pattern_config DEFAULT_PATTERN_CONFIG = {
19 .bdist_max = 4,
21 .spat_min = 3, .spat_max = MAX_PATTERN_DIST,
22 .spat_largest = true,
25 #define PF_MATCH 15
27 pattern_spec PATTERN_SPEC_MATCH_DEFAULT = {
28 [FEAT_CAPTURE] = ~0,
29 [FEAT_AESCAPE] = ~0,
30 [FEAT_SELFATARI] = ~0,
31 [FEAT_ATARI] = ~0,
32 [FEAT_BORDER] = ~0,
33 [FEAT_CONTIGUITY] = 0,
34 [FEAT_SPATIAL] = ~0,
37 static const struct feature_info {
38 char *name;
39 int payloads;
40 } features[FEAT_MAX] = {
41 [FEAT_CAPTURE] = { .name = "capture", .payloads = 64 },
42 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 16 },
43 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 4 },
44 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
45 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
46 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
47 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
50 char *
51 feature2str(char *str, struct feature *f)
53 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
56 char *
57 str2feature(char *str, struct feature *f)
59 while (isspace(*str)) str++;
61 int unsigned flen = strcspn(str, ":");
62 for (unsigned int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
63 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
64 f->id = i;
65 goto found;
67 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
68 exit(EXIT_FAILURE);
70 found:
71 str += flen + 1;
72 f->payload = strtoull(str, &str, 10);
73 return str;
76 char *
77 feature_name(enum feature_id f)
79 return features[f].name;
82 int
83 feature_payloads(struct pattern_config *pc, enum feature_id f)
85 switch (f) {
86 case FEAT_SPATIAL:
87 assert(features[f].payloads < 0);
88 return pc->spat_dict->nspatials;
89 case FEAT_BORDER:
90 assert(features[f].payloads < 0);
91 return pc->bdist_max + 1;
92 default:
93 assert(features[f].payloads > 0);
94 return features[f].payloads;
99 void
100 patterns_init(struct pattern_setup *pat, char *arg, bool will_append, bool load_prob)
102 memset(pat, 0, sizeof(*pat));
104 pat->pc = DEFAULT_PATTERN_CONFIG;
105 pat->pc.spat_dict = spatial_dict_init(will_append, !load_prob);
107 memcpy(&pat->ps, PATTERN_SPEC_MATCH_DEFAULT, sizeof(pattern_spec));
109 if (arg) {
110 char *optspec, *next = arg;
111 while (*next) {
112 optspec = next;
113 next += strcspn(next, ":");
114 if (*next) { *next++ = 0; } else { *next = 0; }
116 char *optname = optspec;
117 char *optval = strchr(optspec, '=');
118 if (optval) *optval++ = 0;
120 /* See pattern.h:pattern_config for description and
121 * pattern.c:DEFAULT_PATTERN_CONFIG for default values
122 * of the following options. */
123 if (!strcasecmp(optname, "bdist_max") && optval) {
124 pat->pc.bdist_max = atoi(optval);
125 } else if (!strcasecmp(optname, "spat_min") && optval) {
126 pat->pc.spat_min = atoi(optval);
127 } else if (!strcasecmp(optname, "spat_max") && optval) {
128 pat->pc.spat_max = atoi(optval);
129 } else if (!strcasecmp(optname, "spat_largest")) {
130 pat->pc.spat_largest = !optval || atoi(optval);
132 } else {
133 fprintf(stderr, "patterns: Invalid argument %s or missing value\n", optname);
134 exit(EXIT_FAILURE);
139 if (load_prob && pat->pc.spat_dict) {
140 pat->pd = pattern_pdict_init(NULL, &pat->pc);
145 /* pattern_spec helpers */
146 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << PF_MATCH))
147 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
149 static struct feature *
150 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
151 struct pattern *p, struct feature *f,
152 struct board *b, struct move *m)
154 f->id = FEAT_CAPTURE; f->payload = 0;
155 #ifdef BOARD_TRAITS
156 if (!trait_at(b, m->coord, m->color).cap)
157 return f;
158 /* Capturable! */
159 if ((ps[FEAT_CAPTURE] & ~(1<<PF_CAPTURE_1STONE | 1<<PF_CAPTURE_TRAPPED | 1<<PF_CAPTURE_CONNECTION)) == 1<<PF_MATCH) {
160 if (PS_PF(CAPTURE, 1STONE))
161 f->payload |= (trait_at(b, m->coord, m->color).cap1 == trait_at(b, m->coord, m->color).cap) << PF_CAPTURE_1STONE;
162 if (PS_PF(CAPTURE, TRAPPED))
163 f->payload |= (!trait_at(b, m->coord, stone_other(m->color)).safe) << PF_CAPTURE_TRAPPED;
164 if (PS_PF(CAPTURE, CONNECTION))
165 f->payload |= (trait_at(b, m->coord, m->color).cap < neighbor_count_at(b, m->coord, stone_other(m->color))) << PF_CAPTURE_CONNECTION;
166 (f++, p->n++);
167 return f;
169 /* We need to know details, so we still have to go through
170 * the neighbors. */
171 #endif
173 /* We look at neighboring groups we could capture, and also if the
174 * opponent could save them. */
175 /* This is very similar in spirit to board_safe_to_play(), and almost
176 * a color inverse of pattern_match_aescape(). */
178 /* Whether an escape move would be safe for the opponent. */
179 int captures = 0;
180 coord_t onelib = -1;
181 int extra_libs = 0, connectable_groups = 0;
182 bool onestone = false, multistone = false;
184 foreach_neighbor(b, m->coord, {
185 if (board_at(b, c) != stone_other(m->color)) {
186 if (board_at(b, c) == S_NONE)
187 extra_libs++; // free point
188 else if (board_at(b, c) == m->color && board_group_info(b, group_at(b, c)).libs == 1)
189 extra_libs += 2; // capturable enemy group
190 continue;
193 group_t g = group_at(b, c); assert(g);
194 if (board_group_info(b, g).libs > 1) {
195 connectable_groups++;
196 if (board_group_info(b, g).libs > 2) {
197 extra_libs += 2; // connected out
198 } else {
199 /* This is a bit tricky; we connect our 2-lib
200 * group to another 2-lib group, which counts
201 * as one liberty, but only if the other lib
202 * is not shared too. */
203 if (onelib == -1) {
204 onelib = board_group_other_lib(b, g, c);
205 extra_libs++;
206 } else {
207 if (c == onelib)
208 extra_libs--; // take that back
209 else
210 extra_libs++;
213 continue;
216 /* Capture! */
217 captures++;
219 if (PS_PF(CAPTURE, LADDER))
220 f->payload |= is_ladder(b, m->coord, g) << PF_CAPTURE_LADDER;
221 /* TODO: is_ladder() is too conservative in some
222 * very obvious situations, look at complete.gtp. */
224 if (PS_PF(CAPTURE, ATARIDEF))
225 foreach_in_group(b, g) {
226 foreach_neighbor(b, c, {
227 assert(board_at(b, c) != S_NONE || c == m->coord);
228 if (board_at(b, c) != m->color)
229 continue;
230 group_t g = group_at(b, c);
231 if (!g || board_group_info(b, g).libs != 1)
232 continue;
233 /* A neighboring group of ours is in atari. */
234 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
236 } foreach_in_group_end;
238 if (PS_PF(CAPTURE, KO)
239 && group_is_onestone(b, g)
240 && neighbor_count_at(b, m->coord, stone_other(m->color))
241 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
242 f->payload |= 1 << PF_CAPTURE_KO;
244 if (group_is_onestone(b, g))
245 onestone = true;
246 else
247 multistone = true;
250 if (captures > 0) {
251 if (PS_PF(CAPTURE, 1STONE))
252 f->payload |= (onestone && !multistone) << PF_CAPTURE_1STONE;
253 if (PS_PF(CAPTURE, TRAPPED))
254 f->payload |= (extra_libs < 2) << PF_CAPTURE_TRAPPED;
255 if (PS_PF(CAPTURE, CONNECTION))
256 f->payload |= (connectable_groups > 0) << PF_CAPTURE_CONNECTION;
257 (f++, p->n++);
259 return f;
262 static struct feature *
263 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
264 struct pattern *p, struct feature *f,
265 struct board *b, struct move *m)
267 f->id = FEAT_AESCAPE; f->payload = 0;
268 #ifdef BOARD_TRAITS
269 if (!trait_at(b, m->coord, stone_other(m->color)).cap)
270 return f;
271 /* Opponent can capture something! */
272 if ((ps[FEAT_AESCAPE] & ~(1<<PF_AESCAPE_1STONE | 1<<PF_AESCAPE_TRAPPED | 1<<PF_AESCAPE_CONNECTION)) == 1<<PF_MATCH) {
273 if (PS_PF(AESCAPE, 1STONE))
274 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;
275 if (PS_PF(AESCAPE, TRAPPED))
276 f->payload |= (!trait_at(b, m->coord, m->color).safe) << PF_AESCAPE_TRAPPED;
277 if (PS_PF(AESCAPE, CONNECTION))
278 f->payload |= (trait_at(b, m->coord, stone_other(m->color)).cap < neighbor_count_at(b, m->coord, m->color)) << PF_AESCAPE_CONNECTION;
279 (f++, p->n++);
280 return f;
282 /* We need to know details, so we still have to go through
283 * the neighbors. */
284 #endif
286 /* Find if a neighboring group of ours is in atari, AND that we provide
287 * a liberty to connect out. XXX: No connect-and-die check. */
288 /* This is very similar in spirit to board_safe_to_play(). */
289 group_t in_atari = -1;
290 coord_t onelib = -1;
291 int extra_libs = 0, connectable_groups = 0;
292 bool onestone = false, multistone = false;
294 foreach_neighbor(b, m->coord, {
295 if (board_at(b, c) != m->color) {
296 if (board_at(b, c) == S_NONE)
297 extra_libs++; // free point
298 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1) {
299 extra_libs += 2; // capturable enemy group
300 /* XXX: We just consider this move safe
301 * unconditionally. */
303 continue;
305 group_t g = group_at(b, c); assert(g);
306 if (board_group_info(b, g).libs > 1) {
307 connectable_groups++;
308 if (board_group_info(b, g).libs > 2) {
309 extra_libs += 2; // connected out
310 } else {
311 /* This is a bit tricky; we connect our 2-lib
312 * group to another 2-lib group, which counts
313 * as one liberty, but only if the other lib
314 * is not shared too. */
315 if (onelib == -1) {
316 onelib = board_group_other_lib(b, g, c);
317 extra_libs++;
318 } else {
319 if (c == onelib)
320 extra_libs--; // take that back
321 else
322 extra_libs++;
325 continue;
328 /* In atari! */
329 in_atari = g;
331 if (PS_PF(AESCAPE, LADDER))
332 f->payload |= is_ladder(b, m->coord, g) << PF_AESCAPE_LADDER;
333 /* TODO: is_ladder() is too conservative in some
334 * very obvious situations, look at complete.gtp. */
336 if (group_is_onestone(b, g))
337 onestone = true;
338 else
339 multistone = true;
342 if (in_atari >= 0) {
343 if (PS_PF(AESCAPE, 1STONE))
344 f->payload |= (onestone && !multistone) << PF_AESCAPE_1STONE;
345 if (PS_PF(AESCAPE, TRAPPED))
346 f->payload |= (extra_libs < 2) << PF_AESCAPE_TRAPPED;
347 if (PS_PF(AESCAPE, CONNECTION))
348 f->payload |= (connectable_groups > 0) << PF_AESCAPE_CONNECTION;
349 (f++, p->n++);
351 return f;
354 static struct feature *
355 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
356 struct pattern *p, struct feature *f,
357 struct board *b, struct move *m)
359 foreach_neighbor(b, m->coord, {
360 if (board_at(b, c) != stone_other(m->color))
361 continue;
362 group_t g = group_at(b, c);
363 if (!g || board_group_info(b, g).libs != 2)
364 continue;
366 /* Can atari! */
367 f->id = FEAT_ATARI; f->payload = 0;
369 if (PS_PF(ATARI, LADDER)) {
370 /* Opponent will escape by the other lib. */
371 coord_t lib = board_group_other_lib(b, g, m->coord);
372 /* TODO: is_ladder() is too conservative in some
373 * very obvious situations, look at complete.gtp. */
374 f->payload |= is_ladder(b, lib, g) << PF_ATARI_LADDER;
377 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
378 f->payload |= 1 << PF_ATARI_KO;
380 (f++, p->n++);
382 return f;
385 #ifndef BOARD_SPATHASH
386 #undef BOARD_SPATHASH_MAXD
387 #define BOARD_SPATHASH_MAXD 1
388 #endif
390 /* Match spatial features that are too distant to be pre-matched
391 * incrementally. */
392 struct feature *
393 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
394 struct pattern *p, struct feature *f,
395 struct board *b, struct move *m, hash_t h)
397 /* We record all spatial patterns black-to-play; simply
398 * reverse all colors if we are white-to-play. */
399 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
400 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
401 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
403 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
404 /* Recompute missing outer circles:
405 * Go through all points in given distance. */
406 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
407 ptcoords_at(x, y, m->coord, b, j);
408 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
410 if (d < pc->spat_min)
411 continue;
412 /* Record spatial feature, one per distance. */
413 unsigned int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
414 if (sid > 0) {
415 f->id = FEAT_SPATIAL;
416 f->payload = sid;
417 if (!pc->spat_largest)
418 (f++, p->n++);
419 } /* else not found, ignore */
421 return f;
424 struct feature *
425 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
426 struct pattern *p, struct feature *f,
427 struct board *b, struct move *m)
429 /* XXX: This is partially duplicated from spatial_from_board(), but
430 * we build a hash instead of spatial record. */
432 assert(pc->spat_min > 0);
433 f->id = -1;
435 hash_t h = pthashes[0][0][S_NONE];
436 #ifdef BOARD_SPATHASH
437 bool w_to_play = m->color == S_WHITE;
438 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
439 /* Reuse all incrementally matched data. */
440 h ^= b->spathash[m->coord][d - 1][w_to_play];
441 if (d < pc->spat_min)
442 continue;
443 /* Record spatial feature, one per distance. */
444 unsigned int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
445 if (sid > 0) {
446 f->id = FEAT_SPATIAL;
447 f->payload = sid;
448 if (!pc->spat_largest)
449 (f++, p->n++);
450 } /* else not found, ignore */
452 #else
453 assert(BOARD_SPATHASH_MAXD < 2);
454 #endif
455 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
456 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
457 if (pc->spat_largest && f->id == FEAT_SPATIAL)
458 (f++, p->n++);
459 return f;
463 void
464 pattern_match(struct pattern_config *pc, pattern_spec ps,
465 struct pattern *p, struct board *b, struct move *m)
467 p->n = 0;
468 struct feature *f = &p->f[0];
470 /* TODO: We should match pretty much all of these features
471 * incrementally. */
473 if (PS_ANY(CAPTURE)) {
474 f = pattern_match_capture(pc, ps, p, f, b, m);
477 if (PS_ANY(AESCAPE)) {
478 f = pattern_match_aescape(pc, ps, p, f, b, m);
481 if (PS_ANY(SELFATARI)) {
482 bool simple = false;
483 if (PS_PF(SELFATARI, STUPID)) {
484 #ifdef BOARD_TRAITS
485 if (!b->precise_selfatari)
486 simple = !trait_at(b, m->coord, m->color).safe;
487 else
488 #endif
489 simple = !board_safe_to_play(b, m->coord, m->color);
491 bool thorough = false;
492 if (PS_PF(SELFATARI, SMART)) {
493 #ifdef BOARD_TRAITS
494 if (b->precise_selfatari)
495 thorough = !trait_at(b, m->coord, m->color).safe;
496 else
497 #endif
498 thorough = is_bad_selfatari(b, m->color, m->coord);
500 if (simple || thorough) {
501 f->id = FEAT_SELFATARI;
502 f->payload = simple << PF_SELFATARI_STUPID;
503 f->payload |= thorough << PF_SELFATARI_SMART;
504 (f++, p->n++);
508 if (PS_ANY(ATARI)) {
509 f = pattern_match_atari(pc, ps, p, f, b, m);
512 if (PS_ANY(BORDER)) {
513 int bdist = coord_edge_distance(m->coord, b);
514 if (bdist <= pc->bdist_max) {
515 f->id = FEAT_BORDER;
516 f->payload = bdist;
517 (f++, p->n++);
521 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
522 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
523 f->id = FEAT_CONTIGUITY;
524 f->payload = 1;
525 (f++, p->n++);
528 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
529 f = pattern_match_spatial(pc, ps, p, f, b, m);
533 char *
534 pattern2str(char *str, struct pattern *p)
536 str = stpcpy(str, "(");
537 for (int i = 0; i < p->n; i++) {
538 if (i > 0) str = stpcpy(str, " ");
539 str = feature2str(str, &p->f[i]);
541 str = stpcpy(str, ")");
542 return str;
545 char *
546 str2pattern(char *str, struct pattern *p)
548 p->n = 0;
549 while (isspace(*str)) str++;
550 if (*str++ != '(') {
551 fprintf(stderr, "invalid patternspec: %s\n", str);
552 exit(EXIT_FAILURE);
555 while (*str != ')') {
556 str = str2feature(str, &p->f[p->n++]);
559 str++;
560 return str;