Spatial: Accurate analysis of hashing function performance
[pachi/t.git] / patternsp.c
blobae2bd6e5bfd935beb868db12cc2a0593c05233c9
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"
13 /* Mapping from point sequence to coordinate offsets (to determine
14 * coordinates relative to pattern center). The array is ordered
15 * in the gridcular metric order so that we can go through it
16 * and incrementally match spatial features in nested circles.
17 * Within one circle, coordinates are ordered by rows to keep
18 * good cache behavior. */
19 struct ptcoord ptcoords[MAX_PATTERN_AREA];
21 /* For each radius, starting index in ptcoords[]. */
22 int ptind[MAX_PATTERN_DIST + 2];
24 /* ptcoords[], ptind[] setup */
25 static void
26 ptcoords_init(void)
28 int i = 0; /* Indexing ptcoords[] */
30 /* First, center point. */
31 ptind[0] = ptind[1] = 0;
32 ptcoords[i].x = ptcoords[i].y = 0; i++;
34 for (int d = 2; d <= MAX_PATTERN_DIST; d++) {
35 ptind[d] = i;
36 /* For each y, examine all integer solutions
37 * of d = |x| + |y| + max(|x|, |y|). */
38 /* TODO: (Stern, 2006) uses a hand-modified
39 * circles that are finer for small d and more
40 * coarse for large d. */
41 for (short y = d / 2; y >= 0; y--) {
42 short x;
43 if (y > d / 3) {
44 /* max(|x|, |y|) = |y|, non-zero x */
45 x = d - y * 2;
46 if (x + y * 2 != d) continue;
47 } else {
48 /* max(|x|, |y|) = |x| */
49 /* Or, max(|x|, |y|) = |y| and x is zero */
50 x = (d - y) / 2;
51 if (x * 2 + y != d) continue;
54 assert((x > y ? x : y) + x + y == d);
56 ptcoords[i].x = x; ptcoords[i].y = y; i++;
57 if (x != 0) { ptcoords[i].x = -x; ptcoords[i].y = y; i++; }
58 if (y != 0) { ptcoords[i].x = x; ptcoords[i].y = -y; i++; }
59 if (x != 0 && y != 0) { ptcoords[i].x = -x; ptcoords[i].y = -y; i++; }
62 ptind[MAX_PATTERN_DIST + 1] = i;
64 #if 0
65 for (int d = 0; d <= MAX_PATTERN_DIST; d++) {
66 fprintf(stderr, "d=%d (%d) ", d, ptind[d]);
67 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
68 fprintf(stderr, "%d,%d ", ptcoords[j].x, ptcoords[j].y);
70 fprintf(stderr, "\n");
72 #endif
76 /* Zobrist hashes used for points in patterns. */
77 hash_t pthashes[PTH__ROTATIONS][MAX_PATTERN_AREA][S_MAX];
79 static void
80 pthashes_init(void)
82 /* We need fixed hashes for all pattern-relative in
83 * all pattern users! This is a simple way to generate
84 * hopefully good ones. Park-Miller powa. :) */
86 /* We create a virtual board (centered at the sequence start),
87 * plant the hashes there, then pick them up into the sequence
88 * with correct coordinates. It would be possible to generate
89 * the sequence point hashes directly, but the rotations would
90 * make for enormous headaches. */
91 #define PATTERN_BOARD_SIZE ((MAX_PATTERN_DIST + 1) * (MAX_PATTERN_DIST + 1))
92 hash_t pthboard[PATTERN_BOARD_SIZE][4];
93 int pthbc = PATTERN_BOARD_SIZE / 2; // tengen coord
95 /* The magic numbers are tuned for minimal collisions. */
96 hash_t h1 = 0xd6d6d6d1;
97 hash_t h2 = 0xd6d6d6d2;
98 hash_t h3 = 0xd6d6d6d3;
99 hash_t h4 = 0xd6d6d6d4;
100 for (int i = 0; i < PATTERN_BOARD_SIZE; i++) {
101 pthboard[i][S_NONE] = (h1 = h1 * 16787);
102 pthboard[i][S_BLACK] = (h2 = h2 * 16823);
103 pthboard[i][S_WHITE] = (h3 = h3 * 16811 - 13);
104 pthboard[i][S_OFFBOARD] = (h4 = h4 * 16811);
107 /* Virtual board with hashes created, now fill
108 * pthashes[] with hashes for points in actual
109 * sequences, also considering various rotations. */
110 #define PTH_VMIRROR 1
111 #define PTH_HMIRROR 2
112 #define PTH_90ROT 4
113 for (int r = 0; r < PTH__ROTATIONS; r++) {
114 for (int i = 0; i < MAX_PATTERN_AREA; i++) {
115 /* Rotate appropriately. */
116 int rx = ptcoords[i].x;
117 int ry = ptcoords[i].y;
118 if (r & PTH_VMIRROR) ry = -ry;
119 if (r & PTH_HMIRROR) rx = -rx;
120 if (r & PTH_90ROT) {
121 int rs = rx; rx = -ry; ry = rs;
123 int bi = pthbc + ry * (MAX_PATTERN_DIST + 1) + rx;
125 /* Copy info. */
126 pthashes[r][i][S_NONE] = pthboard[bi][S_NONE];
127 pthashes[r][i][S_BLACK] = pthboard[bi][S_BLACK];
128 pthashes[r][i][S_WHITE] = pthboard[bi][S_WHITE];
129 pthashes[r][i][S_OFFBOARD] = pthboard[bi][S_OFFBOARD];
134 static void __attribute__((constructor))
135 spatial_init(void)
137 /* Initialization of various static data structures for
138 * fast pattern processing. */
139 ptcoords_init();
140 pthashes_init();
143 inline hash_t
144 spatial_hash(int rotation, struct spatial *s)
146 hash_t h = 0;
147 for (int i = 0; i < ptind[s->dist + 1]; i++) {
148 h ^= pthashes[rotation][i][spatial_point_at(*s, i)];
150 return h & spatial_hash_mask;
153 char *
154 spatial2str(struct spatial *s)
156 static char buf[1024];
157 for (int i = 0; i < ptind[s->dist + 1]; i++) {
158 buf[i] = stone2char(spatial_point_at(*s, i));
160 buf[ptind[s->dist + 1]] = 0;
161 return buf;
164 void
165 spatial_from_board(struct pattern_config *pc, struct spatial *s,
166 struct board *b, struct move *m)
168 assert(pc->spat_min > 0);
170 /* We record all spatial patterns black-to-play; simply
171 * reverse all colors if we are white-to-play. */
172 static enum stone bt_black[4] = { S_NONE, S_BLACK, S_WHITE, S_OFFBOARD };
173 static enum stone bt_white[4] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
174 enum stone (*bt)[4] = m->color == S_WHITE ? &bt_white : &bt_black;
176 memset(s, 0, sizeof(*s));
177 for (int j = 0; j < ptind[pc->spat_max + 1]; j++) {
178 ptcoords_at(x, y, m->coord, b, j);
179 s->points[j / 4] |= (*bt)[board_atxy(b, x, y)] << ((j % 4) * 2);
181 s->dist = pc->spat_max;
184 /* Compare two spatials, allowing for differences up to isomorphism.
185 * True means the spatials are equivalent. */
186 static bool
187 spatial_cmp(struct spatial *s1, struct spatial *s2)
189 /* Quick preliminary check. */
190 if (s1->dist != s2->dist)
191 return false;
193 /* We could create complex transposition tables, but it seems most
194 * foolproof to just check if the sets of rotation hashes are the
195 * same for both. */
196 hash_t s1r[PTH__ROTATIONS];
197 for (int r = 0; r < PTH__ROTATIONS; r++)
198 s1r[r] = spatial_hash(r, s1);
199 for (int r = 0; r < PTH__ROTATIONS; r++) {
200 hash_t s2r = spatial_hash(r, s2);
201 for (int p = 0; p < PTH__ROTATIONS; p++)
202 if (s2r == s1r[p])
203 goto found_rot;
204 /* Rotation hash s2r does not correspond to s1r. */
205 return false;
206 found_rot:;
209 /* All rotation hashes of s2 occur in s1. Hopefully that
210 * indicates something. */
211 return true;
215 /* Spatial dict manipulation. */
217 static unsigned int
218 spatial_dict_addc(struct spatial_dict *dict, struct spatial *s)
220 /* Allocate space in 1024 blocks. */
221 #define SPATIALS_ALLOC 1024
222 if (!(dict->nspatials % SPATIALS_ALLOC)) {
223 dict->spatials = realloc(dict->spatials,
224 (dict->nspatials + SPATIALS_ALLOC)
225 * sizeof(*dict->spatials));
227 dict->spatials[dict->nspatials] = *s;
228 return dict->nspatials++;
231 bool
232 spatial_dict_addh(struct spatial_dict *dict, hash_t hash, unsigned int id)
234 if (dict->hash[hash]) {
235 if (dict->hash[hash] != id)
236 dict->collisions++;
237 } else {
238 dict->fills++;
240 dict->hash[hash] = id;
241 return true;
244 /* Spatial dictionary file format:
245 * /^#/ - comments
246 * INDEX RADIUS STONES HASH...
247 * INDEX: index in the spatial table
248 * RADIUS: @d of the pattern
249 * STONES: string of ".XO#" chars
250 * HASH...: space-separated 18bit hash-table indices for the pattern */
252 static void
253 spatial_dict_read(struct spatial_dict *dict, char *buf, bool hash)
255 /* XXX: We trust the data. Bad data will crash us. */
256 char *bufp = buf;
258 unsigned int index, radius;
259 index = strtoul(bufp, &bufp, 10);
260 radius = strtoul(bufp, &bufp, 10);
261 while (isspace(*bufp)) bufp++;
263 /* Load the stone configuration. */
264 struct spatial s = { .dist = radius };
265 int sl = 0;
266 while (!isspace(*bufp)) {
267 s.points[sl / 4] |= char2stone(*bufp++) << ((sl % 4)*2);
268 sl++;
270 while (isspace(*bufp)) bufp++;
272 /* Sanity check. */
273 if (sl != ptind[s.dist + 1]) {
274 fprintf(stderr, "Spatial dictionary: Invalid number of stones (%d != %d) on this line: %s\n",
275 sl, ptind[radius + 1] - 1, buf);
276 exit(EXIT_FAILURE);
279 /* Add to collection. */
280 unsigned int id = spatial_dict_addc(dict, &s);
281 assert(id == index);
283 /* Add to specified hash places. */
284 if (hash)
285 for (int r = 0; r < PTH__ROTATIONS; r++)
286 spatial_dict_addh(dict, spatial_hash(r, &s), id);
289 void
290 spatial_write(struct spatial_dict *dict, struct spatial *s, int id, FILE *f)
292 fprintf(f, "%d %d ", id, s->dist);
293 fputs(spatial2str(s), f);
294 for (int r = 0; r < PTH__ROTATIONS; r++) {
295 hash_t rhash = spatial_hash(r, s);
296 int id2 = dict->hash[rhash];
297 if (id2 != id) {
298 /* This hash does not belong to us. Decide whether
299 * we or the current owner is better owner. */
300 /* TODO: Compare also # of patternscan encounters? */
301 struct spatial *s2 = &dict->spatials[id2];
302 if (s2->dist < s->dist)
303 continue;
304 if (s2->dist == s->dist && id2 < id)
305 continue;
307 fprintf(f, " %"PRIhash"", spatial_hash(r, s));
309 fputc('\n', f);
312 static void
313 spatial_dict_load(struct spatial_dict *dict, FILE *f, bool hash)
315 char buf[1024];
316 while (fgets(buf, sizeof(buf), f)) {
317 if (buf[0] == '#') continue;
318 spatial_dict_read(dict, buf, hash);
320 if (DEBUGL(1)) {
321 fprintf(stderr, "Loaded spatial dictionary of %d patterns.\n", dict->nspatials);
322 if (hash)
323 spatial_dict_hashstats(dict);
327 void
328 spatial_dict_hashstats(struct spatial_dict *dict)
330 /* m hash size, n number of patterns; is zobrist universal hash?
332 * Not so rigorous analysis, but it should give a good approximation:
333 * Probability of empty bucket is (1-1/m)^n ~ e^(-n/m)
334 * Probability of non-empty bucket is 1-e^(-n/m)
335 * Expected number of non-empty buckets is m*(1-e^(-n/m))
336 * Number of collisions is n-m*(1-e^(-n/m)). */
338 /* The result: Reality matches these expectations pretty well!
340 * Actual:
341 * Loaded spatial dictionary of 1064482 patterns.
342 * (Spatial dictionary hash: 513997 collisions (incl. repetitions), 11.88% (7970033/67108864) fill rate).
344 * Theoretical:
345 * m = 2^26
346 * n <= 8*1064482 (some patterns may have some identical rotations)
347 * n = 513997+7970033 = 8484030 should be the correct number
348 * n-m*(1-e^(-n/m)) = 514381
350 * To verify, make sure to turn patternprob off (e.g. use
351 * -e patternscan), since it will insert a pattern multiple times,
352 * multiplying the reported number of collisions. */
354 unsigned long buckets = (sizeof(dict->hash) / sizeof(dict->hash[0]));
355 fprintf(stderr, "\t(Spatial dictionary hash: %d collisions (incl. repetitions), %.2f%% (%d/%lu) fill rate).\n",
356 dict->collisions,
357 (double) dict->fills * 100 / buckets,
358 dict->fills, buckets);
361 void
362 spatial_dict_writeinfo(struct spatial_dict *dict, FILE *f)
364 /* New file. First, create a comment describing order
365 * of points in the array. This is just for purposes
366 * of external tools, Pachi never interprets it itself. */
367 fprintf(f, "# Pachi spatial patterns dictionary v1.0 maxdist %d\n",
368 MAX_PATTERN_DIST);
369 for (int d = 0; d <= MAX_PATTERN_DIST; d++) {
370 fprintf(f, "# Point order: d=%d ", d);
371 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
372 fprintf(f, "%d,%d ", ptcoords[j].x, ptcoords[j].y);
374 fprintf(f, "\n");
378 /* We try to avoid needlessly reloading spatial dictionary
379 * since it may take rather long time. */
380 static struct spatial_dict *cached_dict;
382 const char *spatial_dict_filename = "patterns.spat";
383 struct spatial_dict *
384 spatial_dict_init(bool will_append, bool hash)
386 if (cached_dict && !will_append)
387 return cached_dict;
389 FILE *f = fopen(spatial_dict_filename, "r");
390 if (!f && !will_append) {
391 if (DEBUGL(1))
392 fprintf(stderr, "No spatial dictionary, will not match spatial pattern features.\n");
393 return NULL;
396 struct spatial_dict *dict = calloc2(1, sizeof(*dict));
397 /* We create a dummy record for index 0 that we will
398 * never reference. This is so that hash value 0 can
399 * represent "no value". */
400 struct spatial dummy = { .dist = 0 };
401 spatial_dict_addc(dict, &dummy);
403 if (f) {
404 spatial_dict_load(dict, f, hash);
405 fclose(f); f = NULL;
406 } else {
407 assert(will_append);
410 cached_dict = dict;
411 return dict;
415 spatial_dict_put(struct spatial_dict *dict, struct spatial *s, hash_t h)
417 /* We avoid spatial_dict_get() here, since we want to ignore radius
418 * differences - we have custom collision detection. */
419 int id = dict->hash[h];
420 if (id > 0) {
421 /* Is this the same or isomorphous spatial? */
422 if (spatial_cmp(s, &dict->spatials[id]))
423 return id;
425 /* Look a bit harder - perhaps one of our rotations still
426 * points at the correct spatial. */
427 for (int r = 0; r < PTH__ROTATIONS; r++) {
428 hash_t rhash = spatial_hash(r, s);
429 int rid = dict->hash[rhash];
430 /* No match means we definitely aren't stored yet. */
431 if (!rid)
432 break;
433 if (id != rid && spatial_cmp(s, &dict->spatials[rid])) {
434 /* Yay, this is us! */
435 if (DEBUGL(3))
436 fprintf(stderr, "Repeated collision %d vs %d\n", id, rid);
437 id = rid;
438 /* Point the hashes back to us. */
439 goto hash_store;
443 if (DEBUGL(1))
444 fprintf(stderr, "Collision %d vs %d\n", id, dict->nspatials);
445 id = 0;
446 /* dict->collisions++; gets done by addh */
449 /* Add new pattern! */
450 id = spatial_dict_addc(dict, s);
451 if (DEBUGL(4)) {
452 fprintf(stderr, "new spat %d(%d) %s <%"PRIhash"> ", id, s->dist, spatial2str(s), h);
453 for (int r = 0; r < 8; r++)
454 fprintf(stderr,"[%"PRIhash"] ", spatial_hash(r, s));
455 fprintf(stderr, "\n");
458 /* Store new pattern in the hash. */
459 hash_store:
460 for (int r = 0; r < PTH__ROTATIONS; r++)
461 spatial_dict_addh(dict, spatial_hash(r, s), id);
463 return id;