uct_pattern -> pattern_setup, introduce patterns_init()
[pachi.git] / pattern.c
blob571b438033ba65dc8f8667703a80652f923d04d3
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, 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 (load_prob && pat->pc.spat_dict) {
110 pat->pd = pattern_pdict_init(NULL, &pat->pc);
115 /* pattern_spec helpers */
116 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << PF_MATCH))
117 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
119 static struct feature *
120 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
121 struct pattern *p, struct feature *f,
122 struct board *b, struct move *m)
124 f->id = FEAT_CAPTURE; f->payload = 0;
125 #ifdef BOARD_TRAITS
126 if (!trait_at(b, m->coord, m->color).cap)
127 return f;
128 /* Capturable! */
129 if ((ps[FEAT_CAPTURE] & ~(1<<PF_CAPTURE_1STONE | 1<<PF_CAPTURE_TRAPPED | 1<<PF_CAPTURE_CONNECTION)) == 1<<PF_MATCH) {
130 if (PS_PF(CAPTURE, 1STONE))
131 f->payload |= (trait_at(b, m->coord, m->color).cap1 == trait_at(b, m->coord, m->color).cap) << PF_CAPTURE_1STONE;
132 if (PS_PF(CAPTURE, TRAPPED))
133 f->payload |= (!trait_at(b, m->coord, stone_other(m->color)).safe) << PF_CAPTURE_TRAPPED;
134 if (PS_PF(CAPTURE, CONNECTION))
135 f->payload |= (trait_at(b, m->coord, m->color).cap < neighbor_count_at(b, m->coord, stone_other(m->color))) << PF_CAPTURE_CONNECTION;
136 (f++, p->n++);
137 return f;
139 /* We need to know details, so we still have to go through
140 * the neighbors. */
141 #endif
143 /* We look at neighboring groups we could capture, and also if the
144 * opponent could save them. */
145 /* This is very similar in spirit to board_safe_to_play(), and almost
146 * a color inverse of pattern_match_aescape(). */
148 /* Whether an escape move would be safe for the opponent. */
149 int captures = 0;
150 coord_t onelib = -1;
151 int extra_libs = 0, connectable_groups = 0;
152 bool onestone = false, multistone = false;
154 foreach_neighbor(b, m->coord, {
155 if (board_at(b, c) != stone_other(m->color)) {
156 if (board_at(b, c) == S_NONE)
157 extra_libs++; // free point
158 else if (board_at(b, c) == m->color && board_group_info(b, group_at(b, c)).libs == 1)
159 extra_libs += 2; // capturable enemy group
160 continue;
163 group_t g = group_at(b, c); assert(g);
164 if (board_group_info(b, g).libs > 1) {
165 connectable_groups++;
166 if (board_group_info(b, g).libs > 2) {
167 extra_libs += 2; // connected out
168 } else {
169 /* This is a bit tricky; we connect our 2-lib
170 * group to another 2-lib group, which counts
171 * as one liberty, but only if the other lib
172 * is not shared too. */
173 if (onelib == -1) {
174 onelib = board_group_other_lib(b, g, c);
175 extra_libs++;
176 } else {
177 if (c == onelib)
178 extra_libs--; // take that back
179 else
180 extra_libs++;
183 continue;
186 /* Capture! */
187 captures++;
189 if (PS_PF(CAPTURE, LADDER))
190 f->payload |= is_ladder(b, m->coord, g) << PF_CAPTURE_LADDER;
191 /* TODO: is_ladder() is too conservative in some
192 * very obvious situations, look at complete.gtp. */
194 if (PS_PF(CAPTURE, ATARIDEF))
195 foreach_in_group(b, g) {
196 foreach_neighbor(b, c, {
197 assert(board_at(b, c) != S_NONE || c == m->coord);
198 if (board_at(b, c) != m->color)
199 continue;
200 group_t g = group_at(b, c);
201 if (!g || board_group_info(b, g).libs != 1)
202 continue;
203 /* A neighboring group of ours is in atari. */
204 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
206 } foreach_in_group_end;
208 if (PS_PF(CAPTURE, KO)
209 && group_is_onestone(b, g)
210 && neighbor_count_at(b, m->coord, stone_other(m->color))
211 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
212 f->payload |= 1 << PF_CAPTURE_KO;
214 if (group_is_onestone(b, g))
215 onestone = true;
216 else
217 multistone = true;
220 if (captures > 0) {
221 if (PS_PF(CAPTURE, 1STONE))
222 f->payload |= (onestone && !multistone) << PF_CAPTURE_1STONE;
223 if (PS_PF(CAPTURE, TRAPPED))
224 f->payload |= (extra_libs < 2) << PF_CAPTURE_TRAPPED;
225 if (PS_PF(CAPTURE, CONNECTION))
226 f->payload |= (connectable_groups > 0) << PF_CAPTURE_CONNECTION;
227 (f++, p->n++);
229 return f;
232 static struct feature *
233 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
234 struct pattern *p, struct feature *f,
235 struct board *b, struct move *m)
237 f->id = FEAT_AESCAPE; f->payload = 0;
238 #ifdef BOARD_TRAITS
239 if (!trait_at(b, m->coord, stone_other(m->color)).cap)
240 return f;
241 /* Opponent can capture something! */
242 if ((ps[FEAT_AESCAPE] & ~(1<<PF_AESCAPE_1STONE | 1<<PF_AESCAPE_TRAPPED | 1<<PF_AESCAPE_CONNECTION)) == 1<<PF_MATCH) {
243 if (PS_PF(AESCAPE, 1STONE))
244 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;
245 if (PS_PF(AESCAPE, TRAPPED))
246 f->payload |= (!trait_at(b, m->coord, m->color).safe) << PF_AESCAPE_TRAPPED;
247 if (PS_PF(AESCAPE, CONNECTION))
248 f->payload |= (trait_at(b, m->coord, stone_other(m->color)).cap < neighbor_count_at(b, m->coord, m->color)) << PF_AESCAPE_CONNECTION;
249 (f++, p->n++);
250 return f;
252 /* We need to know details, so we still have to go through
253 * the neighbors. */
254 #endif
256 /* Find if a neighboring group of ours is in atari, AND that we provide
257 * a liberty to connect out. XXX: No connect-and-die check. */
258 /* This is very similar in spirit to board_safe_to_play(). */
259 group_t in_atari = -1;
260 coord_t onelib = -1;
261 int extra_libs = 0, connectable_groups = 0;
262 bool onestone = false, multistone = false;
264 foreach_neighbor(b, m->coord, {
265 if (board_at(b, c) != m->color) {
266 if (board_at(b, c) == S_NONE)
267 extra_libs++; // free point
268 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1) {
269 extra_libs += 2; // capturable enemy group
270 /* XXX: We just consider this move safe
271 * unconditionally. */
273 continue;
275 group_t g = group_at(b, c); assert(g);
276 if (board_group_info(b, g).libs > 1) {
277 connectable_groups++;
278 if (board_group_info(b, g).libs > 2) {
279 extra_libs += 2; // connected out
280 } else {
281 /* This is a bit tricky; we connect our 2-lib
282 * group to another 2-lib group, which counts
283 * as one liberty, but only if the other lib
284 * is not shared too. */
285 if (onelib == -1) {
286 onelib = board_group_other_lib(b, g, c);
287 extra_libs++;
288 } else {
289 if (c == onelib)
290 extra_libs--; // take that back
291 else
292 extra_libs++;
295 continue;
298 /* In atari! */
299 in_atari = g;
301 if (PS_PF(AESCAPE, LADDER))
302 f->payload |= is_ladder(b, m->coord, g) << PF_AESCAPE_LADDER;
303 /* TODO: is_ladder() is too conservative in some
304 * very obvious situations, look at complete.gtp. */
306 if (group_is_onestone(b, g))
307 onestone = true;
308 else
309 multistone = true;
312 if (in_atari >= 0) {
313 if (PS_PF(AESCAPE, 1STONE))
314 f->payload |= (onestone && !multistone) << PF_AESCAPE_1STONE;
315 if (PS_PF(AESCAPE, TRAPPED))
316 f->payload |= (extra_libs < 2) << PF_AESCAPE_TRAPPED;
317 if (PS_PF(AESCAPE, CONNECTION))
318 f->payload |= (connectable_groups > 0) << PF_AESCAPE_CONNECTION;
319 (f++, p->n++);
321 return f;
324 static struct feature *
325 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
326 struct pattern *p, struct feature *f,
327 struct board *b, struct move *m)
329 foreach_neighbor(b, m->coord, {
330 if (board_at(b, c) != stone_other(m->color))
331 continue;
332 group_t g = group_at(b, c);
333 if (!g || board_group_info(b, g).libs != 2)
334 continue;
336 /* Can atari! */
337 f->id = FEAT_ATARI; f->payload = 0;
339 if (PS_PF(ATARI, LADDER)) {
340 /* Opponent will escape by the other lib. */
341 coord_t lib = board_group_other_lib(b, g, m->coord);
342 /* TODO: is_ladder() is too conservative in some
343 * very obvious situations, look at complete.gtp. */
344 f->payload |= is_ladder(b, lib, g) << PF_ATARI_LADDER;
347 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
348 f->payload |= 1 << PF_ATARI_KO;
350 (f++, p->n++);
352 return f;
355 #ifndef BOARD_SPATHASH
356 #undef BOARD_SPATHASH_MAXD
357 #define BOARD_SPATHASH_MAXD 1
358 #endif
360 /* Match spatial features that are too distant to be pre-matched
361 * incrementally. */
362 struct feature *
363 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
364 struct pattern *p, struct feature *f,
365 struct board *b, struct move *m, hash_t h)
367 /* We record all spatial patterns black-to-play; simply
368 * reverse all colors if we are white-to-play. */
369 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
370 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
371 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
373 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
374 /* Recompute missing outer circles:
375 * Go through all points in given distance. */
376 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
377 ptcoords_at(x, y, m->coord, b, j);
378 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
380 if (d < pc->spat_min)
381 continue;
382 /* Record spatial feature, one per distance. */
383 unsigned int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
384 if (sid > 0) {
385 f->id = FEAT_SPATIAL;
386 f->payload = sid;
387 if (!pc->spat_largest)
388 (f++, p->n++);
389 } /* else not found, ignore */
391 return f;
394 struct feature *
395 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
396 struct pattern *p, struct feature *f,
397 struct board *b, struct move *m)
399 /* XXX: This is partially duplicated from spatial_from_board(), but
400 * we build a hash instead of spatial record. */
402 assert(pc->spat_min > 0);
403 f->id = -1;
405 hash_t h = pthashes[0][0][S_NONE];
406 #ifdef BOARD_SPATHASH
407 bool w_to_play = m->color == S_WHITE;
408 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
409 /* Reuse all incrementally matched data. */
410 h ^= b->spathash[m->coord][d - 1][w_to_play];
411 if (d < pc->spat_min)
412 continue;
413 /* Record spatial feature, one per distance. */
414 unsigned int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
415 if (sid > 0) {
416 f->id = FEAT_SPATIAL;
417 f->payload = sid;
418 if (!pc->spat_largest)
419 (f++, p->n++);
420 } /* else not found, ignore */
422 #else
423 assert(BOARD_SPATHASH_MAXD < 2);
424 #endif
425 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
426 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
427 if (pc->spat_largest && f->id == FEAT_SPATIAL)
428 (f++, p->n++);
429 return f;
433 void
434 pattern_match(struct pattern_config *pc, pattern_spec ps,
435 struct pattern *p, struct board *b, struct move *m)
437 p->n = 0;
438 struct feature *f = &p->f[0];
440 /* TODO: We should match pretty much all of these features
441 * incrementally. */
443 if (PS_ANY(CAPTURE)) {
444 f = pattern_match_capture(pc, ps, p, f, b, m);
447 if (PS_ANY(AESCAPE)) {
448 f = pattern_match_aescape(pc, ps, p, f, b, m);
451 if (PS_ANY(SELFATARI)) {
452 bool simple = false;
453 if (PS_PF(SELFATARI, STUPID)) {
454 #ifdef BOARD_TRAITS
455 if (!b->precise_selfatari)
456 simple = !trait_at(b, m->coord, m->color).safe;
457 else
458 #endif
459 simple = !board_safe_to_play(b, m->coord, m->color);
461 bool thorough = false;
462 if (PS_PF(SELFATARI, SMART)) {
463 #ifdef BOARD_TRAITS
464 if (b->precise_selfatari)
465 thorough = !trait_at(b, m->coord, m->color).safe;
466 else
467 #endif
468 thorough = is_bad_selfatari(b, m->color, m->coord);
470 if (simple || thorough) {
471 f->id = FEAT_SELFATARI;
472 f->payload = simple << PF_SELFATARI_STUPID;
473 f->payload |= thorough << PF_SELFATARI_SMART;
474 (f++, p->n++);
478 if (PS_ANY(ATARI)) {
479 f = pattern_match_atari(pc, ps, p, f, b, m);
482 if (PS_ANY(BORDER)) {
483 int bdist = coord_edge_distance(m->coord, b);
484 if (bdist <= pc->bdist_max) {
485 f->id = FEAT_BORDER;
486 f->payload = bdist;
487 (f++, p->n++);
491 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
492 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
493 f->id = FEAT_CONTIGUITY;
494 f->payload = 1;
495 (f++, p->n++);
498 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
499 f = pattern_match_spatial(pc, ps, p, f, b, m);
503 char *
504 pattern2str(char *str, struct pattern *p)
506 str = stpcpy(str, "(");
507 for (int i = 0; i < p->n; i++) {
508 if (i > 0) str = stpcpy(str, " ");
509 str = feature2str(str, &p->f[i]);
511 str = stpcpy(str, ")");
512 return str;
515 char *
516 str2pattern(char *str, struct pattern *p)
518 p->n = 0;
519 while (isspace(*str)) str++;
520 if (*str++ != '(') {
521 fprintf(stderr, "invalid patternspec: %s\n", str);
522 exit(EXIT_FAILURE);
525 while (*str != ')') {
526 str = str2feature(str, &p->f[p->n++]);
529 str++;
530 return str;