Merge remote-tracking branch 'origin/master' into patterns
[pachi.git] / patternprob.c
blob0270a60c0d7af3198e48db30d23275b8e7356824
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <stdlib.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "pattern.h"
10 #include "patternsp.h"
11 #include "patternprob.h"
14 /* We try to avoid needlessly reloading probability dictionary
15 * since it may take rather long time. */
16 static struct pattern_pdict *cached_dict;
18 struct pattern_pdict *
19 pattern_pdict_init(char *filename, struct pattern_config *pc)
21 if (cached_dict)
22 return cached_dict;
24 if (!filename)
25 filename = "patterns.prob";
26 FILE *f = fopen(filename, "r");
27 if (!f) {
28 if (DEBUGL(1))
29 fprintf(stderr, "No pattern probtable, will not use learned patterns.\n");
30 return NULL;
33 struct pattern_pdict *dict = calloc2(1, sizeof(*dict));
34 dict->pc = pc;
35 dict->table = calloc2(pc->spat_dict->nspatials + 1, sizeof(*dict->table));
37 int i = 0;
38 char sbuf[1024];
39 while (fgets(sbuf, sizeof(sbuf), f)) {
40 struct pattern_prob *pb = calloc2(1, sizeof(*pb));
41 int c, o;
43 char *buf = sbuf;
44 if (buf[0] == '#') continue;
45 while (isspace(*buf)) buf++;
46 while (!isspace(*buf)) buf++; // we recompute the probability
47 while (isspace(*buf)) buf++;
48 c = strtol(buf, &buf, 10);
49 while (isspace(*buf)) buf++;
50 o = strtol(buf, &buf, 10);
51 pb->prob = (floating_t) c / o;
52 while (isspace(*buf)) buf++;
53 str2pattern(buf, &pb->p);
55 uint32_t spi = pattern2spatial(dict, &pb->p);
56 if (!dict->table[spi]) {
57 dict->table[spi] = pb;
58 } else {
59 struct pattern_prob *ppb = dict->table[spi];
60 while (ppb->next) ppb = ppb->next;
61 ppb->next = pb;
63 i++;
66 fclose(f);
67 if (DEBUGL(1))
68 fprintf(stderr, "Loaded %d pattern-probability pairs.\n", i);
69 cached_dict = dict;
70 return dict;