uct_search_stop_early(): Assume best is non-NULL
[pachi/t.git] / pattern.c
blobcc649026de7fd54f846f3d17902ca31fdf531016
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 #define FAST_NO_LADDER 1 /* 1: Don't match ladders in fast playouts */
46 pattern_spec PATTERN_SPEC_MATCHFAST = {
47 [FEAT_PASS] = ~0,
48 [FEAT_CAPTURE] = ~(1<<PF_CAPTURE_ATARIDEF | 1<<PF_CAPTURE_RECAPTURE | FAST_NO_LADDER<<PF_CAPTURE_LADDER),
49 [FEAT_AESCAPE] = ~(FAST_NO_LADDER<<PF_AESCAPE_LADDER),
50 [FEAT_SELFATARI] = ~(1<<PF_SELFATARI_SMART),
51 [FEAT_ATARI] = ~(FAST_NO_LADDER<<PF_ATARI_LADDER),
52 [FEAT_BORDER] = 0,
53 [FEAT_LDIST] = 0,
54 [FEAT_LLDIST] = 0,
55 [FEAT_CONTIGUITY] = ~0,
56 [FEAT_SPATIAL] = 0,
57 [FEAT_PATTERN3] = ~0,
58 [FEAT_MCOWNER] = 0,
61 static const struct feature_info {
62 char *name;
63 int payloads;
64 } features[FEAT_MAX] = {
65 [FEAT_PASS] = { .name = "pass", .payloads = 2 },
66 [FEAT_CAPTURE] = { .name = "capture", .payloads = 16 },
67 [FEAT_AESCAPE] = { .name = "atariescape", .payloads = 2 },
68 [FEAT_SELFATARI] = { .name = "selfatari", .payloads = 2 },
69 [FEAT_ATARI] = { .name = "atari", .payloads = 4 },
70 [FEAT_BORDER] = { .name = "border", .payloads = -1 },
71 [FEAT_LDIST] = { .name = "ldist", .payloads = -1 },
72 [FEAT_LLDIST] = { .name = "lldist", .payloads = -1 },
73 [FEAT_CONTIGUITY] = { .name = "cont", .payloads = 2 },
74 [FEAT_SPATIAL] = { .name = "s", .payloads = -1 },
75 [FEAT_PATTERN3] = { .name = "p", .payloads = 2<<16 },
76 [FEAT_MCOWNER] = { .name = "mcowner", .payloads = 16 },
79 char *
80 feature2str(char *str, struct feature *f)
82 return str + sprintf(str + strlen(str), "%s:%d", features[f->id].name, f->payload);
85 char *
86 str2feature(char *str, struct feature *f)
88 while (isspace(*str)) str++;
90 int flen = strcspn(str, ":");
91 for (int i = 0; i < sizeof(features)/sizeof(features[0]); i++)
92 if (strlen(features[i].name) == flen && !strncmp(features[i].name, str, flen)) {
93 f->id = i;
94 goto found;
96 fprintf(stderr, "invalid featurespec: %s[%d]\n", str, flen);
97 exit(EXIT_FAILURE);
99 found:
100 str += flen + 1;
101 f->payload = strtoull(str, &str, 10);
102 return str;
105 char *
106 feature_name(enum feature_id f)
108 return features[f].name;
112 feature_payloads(struct pattern_config *pc, enum feature_id f)
114 switch (f) {
115 case FEAT_SPATIAL:
116 assert(features[f].payloads < 0);
117 return pc->spat_dict->nspatials;
118 case FEAT_LDIST:
119 case FEAT_LLDIST:
120 assert(features[f].payloads < 0);
121 return pc->ldist_max + 1;
122 case FEAT_BORDER:
123 assert(features[f].payloads < 0);
124 return pc->bdist_max + 1;
125 default:
126 assert(features[f].payloads > 0);
127 return features[f].payloads;
132 /* pattern_spec helpers */
133 #define PS_ANY(F) (ps[FEAT_ ## F] & (1 << 15))
134 #define PS_PF(F, P) (ps[FEAT_ ## F] & (1 << PF_ ## F ## _ ## P))
136 static struct feature *
137 pattern_match_capture(struct pattern_config *pc, pattern_spec ps,
138 struct pattern *p, struct feature *f,
139 struct board *b, struct move *m)
141 f->id = FEAT_CAPTURE; f->payload = 0;
142 #ifdef BOARD_TRAITS
143 if (!b->t[m->coord].cap)
144 return f;
145 /* Capturable! */
146 if (!(PS_PF(CAPTURE, LADDER)
147 || PS_PF(CAPTURE, RECAPTURE)
148 || PS_PF(CAPTURE, ATARIDEF)
149 || PS_PF(CAPTURE, KO))) {
150 (f++, p->n++);
151 return f;
153 #endif
155 /* Ok, we need to look at the neighbors anyway. */
156 /* Furthermore, we will now create one feature per capturable
157 * neighbor. */
158 /* XXX: I'm not sure if this is really good idea. --pasky */
159 foreach_neighbor(b, m->coord, {
160 if (board_at(b, c) != stone_other(m->color))
161 continue;
162 group_t g = group_at(b, c);
163 if (!g || board_group_info(b, g).libs != 1)
164 continue;
166 /* Capture! */
168 if (PS_PF(CAPTURE, LADDER))
169 f->payload |= is_ladder(b, m->coord, g, true, true) << PF_CAPTURE_LADDER;
170 /* TODO: is_ladder() is too conservative in some
171 * very obvious situations, look at complete.gtp. */
173 /* TODO: PF_CAPTURE_RECAPTURE */
175 if (PS_PF(CAPTURE, ATARIDEF))
176 foreach_in_group(b, g) {
177 foreach_neighbor(b, c, {
178 assert(board_at(b, c) != S_NONE || c == m->coord);
179 if (board_at(b, c) != m->color)
180 continue;
181 group_t g = group_at(b, c);
182 if (!g || board_group_info(b, g).libs != 1)
183 continue;
184 /* A neighboring group of ours is in atari. */
185 f->payload |= 1 << PF_CAPTURE_ATARIDEF;
187 } foreach_in_group_end;
189 if (PS_PF(CAPTURE, KO)
190 && group_is_onestone(b, g)
191 && neighbor_count_at(b, m->coord, stone_other(m->color))
192 + neighbor_count_at(b, m->coord, S_OFFBOARD) == 4)
193 f->payload |= 1 << PF_CAPTURE_KO;
195 (f++, p->n++);
196 f->id = FEAT_CAPTURE; f->payload = 0;
198 return f;
201 static struct feature *
202 pattern_match_aescape(struct pattern_config *pc, pattern_spec ps,
203 struct pattern *p, struct feature *f,
204 struct board *b, struct move *m)
206 /* Find if a neighboring group of ours is in atari, AND that we provide
207 * a liberty to connect out. XXX: No connect-and-die check. */
208 group_t in_atari = -1;
209 bool has_extra_lib = false;
210 int payload = 0;
212 foreach_neighbor(b, m->coord, {
213 if (board_at(b, c) != m->color) {
214 if (board_at(b, c) == S_NONE)
215 has_extra_lib = true; // free point
216 else if (board_at(b, c) == stone_other(m->color) && board_group_info(b, group_at(b, c)).libs == 1)
217 has_extra_lib = true; // capturable enemy group
218 continue;
220 group_t g = group_at(b, c); assert(g);
221 if (board_group_info(b, g).libs != 1) {
222 has_extra_lib = true;
223 continue;
226 /* In atari! */
227 in_atari = g;
229 if (PS_PF(AESCAPE, LADDER))
230 payload |= is_ladder(b, m->coord, g, true, true) << PF_AESCAPE_LADDER;
231 /* TODO: is_ladder() is too conservative in some
232 * very obvious situations, look at complete.gtp. */
234 if (in_atari >= 0 && has_extra_lib) {
235 f->id = FEAT_AESCAPE; f->payload = payload;
236 (f++, p->n++);
238 return f;
241 static struct feature *
242 pattern_match_atari(struct pattern_config *pc, pattern_spec ps,
243 struct pattern *p, struct feature *f,
244 struct board *b, struct move *m)
246 foreach_neighbor(b, m->coord, {
247 if (board_at(b, c) != stone_other(m->color))
248 continue;
249 group_t g = group_at(b, c);
250 if (!g || board_group_info(b, g).libs != 2)
251 continue;
253 /* Can atari! */
254 f->id = FEAT_ATARI; f->payload = 0;
256 if (PS_PF(ATARI, LADDER)) {
257 /* Opponent will escape by the other lib. */
258 coord_t lib = board_group_info(b, g).lib[0];
259 if (lib == m->coord) lib = board_group_info(b, g).lib[1];
260 /* TODO: is_ladder() is too conservative in some
261 * very obvious situations, look at complete.gtp. */
262 f->payload |= is_ladder(b, lib, g, true, true) << PF_ATARI_LADDER;
265 if (PS_PF(ATARI, KO) && !is_pass(b->ko.coord))
266 f->payload |= 1 << PF_ATARI_KO;
268 (f++, p->n++);
270 return f;
273 #ifndef BOARD_SPATHASH
274 #undef BOARD_SPATHASH_MAXD
275 #define BOARD_SPATHASH_MAXD 1
276 #endif
278 /* Match spatial features that are too distant to be pre-matched
279 * incrementally. */
280 struct feature *
281 pattern_match_spatial_outer(struct pattern_config *pc, pattern_spec ps,
282 struct pattern *p, struct feature *f,
283 struct board *b, struct move *m, hash_t h)
285 /* We record all spatial patterns black-to-play; simply
286 * reverse all colors if we are white-to-play. */
287 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
288 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
289 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
291 for (int d = BOARD_SPATHASH_MAXD + 1; d <= pc->spat_max; d++) {
292 /* Recompute missing outer circles:
293 * Go through all points in given distance. */
294 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
295 ptcoords_at(x, y, m->coord, b, j);
296 h ^= pthashes[0][j][(*bt)[board_atxy(b, x, y)]];
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 return f;
311 struct feature *
312 pattern_match_spatial(struct pattern_config *pc, pattern_spec ps,
313 struct pattern *p, struct feature *f,
314 struct board *b, struct move *m)
316 /* XXX: This is partially duplicated from spatial_from_board(), but
317 * we build a hash instead of spatial record. */
319 assert(pc->spat_min > 0);
321 hash_t h = pthashes[0][0][S_NONE];
322 #ifdef BOARD_SPATHASH
323 bool w_to_play = m->color == S_WHITE;
324 for (int d = 2; d <= BOARD_SPATHASH_MAXD; d++) {
325 /* Reuse all incrementally matched data. */
326 h ^= b->spathash[m->coord][d - 1][w_to_play];
327 if (d < pc->spat_min)
328 continue;
329 /* Record spatial feature, one per distance. */
330 int sid = spatial_dict_get(pc->spat_dict, d, h & spatial_hash_mask);
331 if (sid > 0) {
332 f->id = FEAT_SPATIAL;
333 f->payload = sid;
334 (f++, p->n++);
335 } /* else not found, ignore */
337 #else
338 assert(BOARD_SPATHASH_MAXD < 2);
339 #endif
340 if (unlikely(pc->spat_max > BOARD_SPATHASH_MAXD))
341 f = pattern_match_spatial_outer(pc, ps, p, f, b, m, h);
342 return f;
346 static bool
347 is_simple_selfatari(struct board *b, enum stone color, coord_t coord)
349 /* Very rough check, no connect-and-die checks or other trickery. */
350 int libs = immediate_liberty_count(b, coord);
351 if (libs >= 2) return false; // open space
353 group_t seen = -1;
354 foreach_neighbor(b, coord, {
355 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1) {
356 return false; // can capture
358 } else if (board_at(b, c) == color) {
359 // friendly group, does it have liberties?
360 group_t g = group_at(b, c);
361 if (board_group_info(b, g).libs == 1 || seen == g)
362 continue;
363 libs += board_group_info(b, g).libs - 1;
364 if (libs >= 2) return false;
365 // don't consider the same group twice
366 seen = g;
369 return true;
372 void
373 pattern_match(struct pattern_config *pc, pattern_spec ps,
374 struct pattern *p, struct board *b, struct move *m)
376 p->n = 0;
377 struct feature *f = &p->f[0];
379 /* TODO: We should match pretty much all of these features
380 * incrementally. */
382 if (is_pass(m->coord)) {
383 if (PS_ANY(PASS)) {
384 f->id = FEAT_PASS; f->payload = 0;
385 if (PS_PF(PASS, LASTPASS))
386 f->payload |= (b->moves > 0 && is_pass(b->last_move.coord))
387 << PF_PASS_LASTPASS;
388 p->n++;
390 return;
393 if (PS_ANY(CAPTURE)) {
394 f = pattern_match_capture(pc, ps, p, f, b, m);
397 if (PS_ANY(AESCAPE)) {
398 f = pattern_match_aescape(pc, ps, p, f, b, m);
401 if (PS_ANY(SELFATARI)) {
402 bool simple = is_simple_selfatari(b, m->color, m->coord);
403 bool thorough = false;
404 if (PS_PF(SELFATARI, SMART)) {
405 thorough = is_bad_selfatari(b, m->color, m->coord);
407 if (simple || thorough) {
408 f->id = FEAT_SELFATARI;
409 f->payload = thorough << PF_SELFATARI_SMART;
410 (f++, p->n++);
414 if (PS_ANY(ATARI)) {
415 f = pattern_match_atari(pc, ps, p, f, b, m);
418 if (PS_ANY(BORDER)) {
419 int bdist = coord_edge_distance(m->coord, b);
420 if (bdist <= pc->bdist_max) {
421 f->id = FEAT_BORDER;
422 f->payload = bdist;
423 (f++, p->n++);
427 if (PS_ANY(CONTIGUITY) && !is_pass(b->last_move.coord)
428 && coord_is_8adjecent(m->coord, b->last_move.coord, b)) {
429 f->id = FEAT_CONTIGUITY;
430 f->payload = 1;
431 (f++, p->n++);
434 if (PS_ANY(LDIST) && pc->ldist_max > 0 && !is_pass(b->last_move.coord)) {
435 int ldist = coord_gridcular_distance(m->coord, b->last_move.coord, b);
436 if (pc->ldist_min <= ldist && ldist <= pc->ldist_max) {
437 f->id = FEAT_LDIST;
438 f->payload = ldist;
439 (f++, p->n++);
443 if (PS_ANY(LLDIST) && pc->ldist_max > 0 && !is_pass(b->last_move2.coord)) {
444 int lldist = coord_gridcular_distance(m->coord, b->last_move2.coord, b);
445 if (pc->ldist_min <= lldist && lldist <= pc->ldist_max) {
446 f->id = FEAT_LLDIST;
447 f->payload = lldist;
448 (f++, p->n++);
452 if (PS_ANY(SPATIAL) && pc->spat_max > 0 && pc->spat_dict) {
453 f = pattern_match_spatial(pc, ps, p, f, b, m);
456 if (PS_ANY(PATTERN3) && !is_pass(m->coord)) {
457 #ifdef BOARD_PAT3
458 int pat = b->pat3[m->coord];
459 #else
460 int pat = pattern3_hash(b, m->coord);
461 #endif
462 if (m->color == S_WHITE) {
463 /* We work with the pattern3s as black-to-play. */
464 pat = pattern3_reverse(pat);
466 f->id = FEAT_PATTERN3;
467 f->payload = pat;
468 (f++, p->n++);
471 /* FEAT_MCOWNER: TODO */
472 assert(!pc->mcsims);
475 char *
476 pattern2str(char *str, struct pattern *p)
478 str = stpcpy(str, "(");
479 for (int i = 0; i < p->n; i++) {
480 if (i > 0) str = stpcpy(str, " ");
481 str = feature2str(str, &p->f[i]);
483 str = stpcpy(str, ")");
484 return str;
489 /*** Features gamma set */
491 static void
492 features_gamma_load(struct features_gamma *fg, const char *filename)
494 FILE *f = fopen(filename, "r");
495 if (!f) return;
496 char buf[256];
497 while (fgets(buf, 256, f)) {
498 char *bufp = buf;
499 struct feature f;
500 bufp = str2feature(bufp, &f);
501 while (isspace(*bufp)) bufp++;
502 float gamma = strtof(bufp, &bufp);
503 /* Record feature's gamma. */
504 feature_gamma(fg, &f, &gamma);
505 /* In case of 3x3 patterns, record gamma also
506 * for all rotations and transpositions. */
507 if (f.id == FEAT_PATTERN3) {
508 int transp[8];
509 pattern3_transpose(f.payload, &transp);
510 for (int i = 1; i < 8; i++) {
511 f.payload = transp[i];
512 feature_gamma(fg, &f, &gamma);
514 f.payload = transp[0];
517 fclose(f);
520 const char *features_gamma_filename = "patterns.gamma";
522 struct features_gamma *
523 features_gamma_init(struct pattern_config *pc, const char *file)
525 struct features_gamma *fg = calloc(1, sizeof(*fg));
526 fg->pc = pc;
527 for (int i = 0; i < FEAT_MAX; i++) {
528 int n = feature_payloads(pc, i);
529 fg->gamma[i] = malloc(n * sizeof(float));
530 for (int j = 0; j < n; j++) {
531 fg->gamma[i][j] = 1.0f;
534 features_gamma_load(fg, file ? file : features_gamma_filename);
535 return fg;
538 void
539 features_gamma_done(struct features_gamma *fg)
541 for (int i = 0; i < FEAT_MAX; i++)
542 free(fg->gamma[i]);
543 free(fg);