Pattern Probability Table: Introduce basic infrastructure
[pachi.git] / patternprob.c
blob6173417a2392ff249273f65d156e6823f18e378b
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 struct pattern_pdict *
15 pattern_pdict_init(char *filename, struct pattern_config *pc)
17 if (!filename)
18 filename = "patterns.prob";
19 FILE *f = fopen(filename, "r");
20 if (!f) {
21 if (DEBUGL(1))
22 fprintf(stderr, "No pattern probtable, will not use learned patterns.\n");
23 return NULL;
26 struct pattern_pdict *dict = calloc2(1, sizeof(*dict));
27 dict->pc = pc;
28 dict->table = calloc2(pc->spat_dict->nspatials + 1, sizeof(*dict->table));
30 char sbuf[1024];
31 while (fgets(sbuf, sizeof(sbuf), f)) {
32 struct pattern_prob *pb = calloc2(1, sizeof(*pb));
33 int c, o;
35 char *buf = sbuf;
36 if (buf[0] == '#') continue;
37 while (isspace(*buf)) buf++;
38 while (!isspace(*buf)) buf++; // we recompute the probability
39 while (isspace(*buf)) buf++;
40 c = strtol(buf, &buf, 10);
41 while (isspace(*buf)) buf++;
42 o = strtol(buf, &buf, 10);
43 pb->prob = (floating_t) c / o;
44 while (isspace(*buf)) buf++;
45 str2pattern(buf, &pb->p);
47 uint32_t spi = pattern2spatial(dict, &pb->p);
48 if (!dict->table[spi]) {
49 dict->table[spi] = pb;
50 } else {
51 struct pattern_prob *ppb = dict->table[spi];
52 while (ppb->next) ppb = ppb->next;
53 ppb->next = pb;
57 fclose(f);
58 return dict;