]> git.sesse.net Git - wloh/blob - bayeswf.cpp
Minor constantification.
[wloh] / bayeswf.cpp
1 #include <stdio.h>
2 #include <math.h>
3 #include <string.h>
4 #include <stdlib.h>
5
6 #include <map>
7 #include <vector>
8 #include <string>
9 #include <algorithm>
10
11 using namespace std;
12
13 #define PRIOR_MU 1500
14 #define MAX_PLAYERS 4096
15 #define DUMP_RAW 0
16
17 float mu[MAX_PLAYERS];
18 float sigma[MAX_PLAYERS];
19 float prior_sigma = 70.0f;
20
21 #define EPSILON 1e-3
22
23 /*
24  * L(mu_vec, sigma_vec, matches) = product[ L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ]
25  * log-likelihood = sum[ log( L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ) ]
26  * 
27  * L(mu1, sigma1, mu2, sigma2, score2 - score1) = sigmoid(mu2 - mu1, sqrt(sigma1² + sigma2²), (score2 - score1))
28  *
29  * pdf := 1/(sigma * sqrt(2*Pi)) * exp(-(x - mu)^2 / (2 * sigma^2));        
30  * pdfs := subs({ mu = mu1 - mu2, sigma = sqrt(sigma1^2 + sigma2^2) }, pdf);
31  * diff(log(pdfs), mu1); 
32  */
33
34 struct match {
35         int other_player;
36         int margin;
37         float weight;
38 };
39 map<int, vector<match> > matches_for_player;
40
41 void dump_scores(const vector<string> &players, const float *mu, const float *sigma, int num_players)
42 {
43 #if 0
44         for (int i = 0; i < num_players; ++i) {
45                 printf("%s=[%5.1f, %4.1f] ", players[i].c_str(), mu[i], sigma[i]);
46         }
47         printf("\n");
48 #elif 0
49         for (int i = 0; i < num_players; ++i) {
50                 printf("%5.1f ", mu[i]);
51         }
52         printf("\n");
53 #else
54         for (int i = 0; i < num_players; ++i) {
55                 printf("%f %s\n", mu[i], players[i].c_str());
56         }
57 #endif
58 }
59
60 /*
61  * diff(logL, mu1) = -w * (mu1 - mu2 - x) / sigma_c^2
62  * maximizer for mu1 is given by: sum_i[ (w_i/sigma_c_i)^2 (mu1 - mu2_i - x_i) ] = 0
63  *                                sum_i[ (w_i/sigma_c_i)^2 mu1 ] = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ]
64  *                                mu1 = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ] / sum_i[ (w_i/sigma_c_i)^2 ]
65  */
66 void update_mu(float *mu, float *sigma, int player_num, const vector<match> &matches)
67 {
68         if (matches.empty()) {
69                 return;
70         }
71
72         float nom = 0.0f, denom = 0.0f;
73
74         // Prior.
75         {
76                 float inv_sigma2 = 1.0f / (prior_sigma * prior_sigma);
77                 nom += PRIOR_MU * inv_sigma2;
78                 denom += inv_sigma2;
79         }
80
81         // All matches.
82         for (unsigned i = 0; i < matches.size(); ++i) {
83                 float sigma1 = sigma[player_num];
84                 float sigma2 = sigma[matches[i].other_player];
85                 float inv_sigma_c2 = matches[i].weight / (sigma1 * sigma1 + sigma2 * sigma2);
86                 float x = matches[i].margin; // / 70.0f;
87         
88                 nom += (mu[matches[i].other_player] + x) * inv_sigma_c2;
89                 denom += inv_sigma_c2;
90         }
91         mu[player_num] = nom / denom;
92 }
93
94 void dump_raw(const float *mu, const float *sigma, int num_players)
95 {
96         for (int i = 0; i < num_players; ++i) {
97                 for (unsigned j = 0; j < matches_for_player[i].size(); ++j) {
98                         const match& m = matches_for_player[i][j];
99
100                         // Only count each match once.
101                         if (m.other_player <= i) {
102                                 continue;
103                         }
104
105                         float mu1 = mu[i];
106                         float mu2 = mu[m.other_player];
107                         float sigma1 = sigma[i];
108                         float sigma2 = sigma[m.other_player];
109                         float sigma = sqrt(sigma1 * sigma1 + sigma2 * sigma2);
110                         float mu = mu1 - mu2;
111                         float x = m.margin;
112                         float w = m.weight;
113
114                         printf("%f %f\n", (x - mu) / sigma, w);
115                 }
116         }
117 }
118
119 /*
120  * diff(logL, sigma1) = sigma1 (-sigma1² - sigma2² + (x - mu)²) / sigma_c²
121  * maximizer for sigma1 is given by: sum_i[ (1/sigma_c_i)² sigma1 ((x - mu)² - (sigma1² + sigma2²) ] = 0
122  *                                   sum_i[ (x - mu)² - sigma1² - sigma2² ] = 0                                  |: sigma1 != 0, sigma2 != 0
123  *                                   sum_i[ (x - mu)² - sigma2² ] = sum[ sigma1² ]
124  *                                   sigma1 = sqrt( sum_i[ (x - mu)² - sigma2² ] / N )
125  */
126 void update_sigma(float *mu, float *sigma, int player_num, const vector<match> &matches)
127 {
128         if (matches.size() < 2) {
129                 return;
130         }
131
132         float sum = 0.0f;
133         for (unsigned i = 0; i < matches.size(); ++i) {
134                 float mu1 = mu[player_num];
135                 float mu2 = mu[matches[i].other_player];
136                 float mu = mu1 - mu2;
137                 float sigma2 = sigma[matches[i].other_player];
138                 float x = matches[i].margin;
139
140                 //fprintf(stderr, "x=%f mu=%f sigma2=%f   add %f-%f = %f\n", x, mu, sigma2, (x-mu)*(x-mu), sigma2*sigma2, (x - mu) * (x - mu) - sigma2 * sigma2);
141                 sum += (x - mu) * (x - mu) - sigma2 * sigma2;
142         }
143
144         if (sum <= 0) {
145                 return;
146         }
147         //fprintf(stderr, "sum=%f\n", sum);
148         sigma[player_num] = sqrt(sum / matches.size());
149 }
150
151 /*
152  * diff(logL, sigma) = w ( (x - mu)² - sigma² ) / sigma³
153  * maximizer for sigma is given by: sum_i[ (w_i/sigma)³ ((x - mu)² - sigma²) ] = 0
154  *                                   sum_i[ w_i ( (x - mu)² - sigma² ) ] = 0                            |: sigma != 0
155  *                                   sum_i[ w_i (x - mu)² ] = sum[ w_i sigma² ]
156  *                                   sigma = sqrt( sum_i[ w_i (x - mu)² ] / sum[w_i] )
157  */
158 void update_global_sigma(float *mu, float *sigma, int num_players)
159 {
160         float nom = 0.0f, denom = 0.0f;
161         for (int i = 0; i < num_players; ++i) {
162                 for (unsigned j = 0; j < matches_for_player[i].size(); ++j) {
163                         const match& m = matches_for_player[i][j];
164
165                         // Only count each match once.
166                         if (m.other_player <= i) {
167                                 continue;
168                         }
169
170                         float mu1 = mu[i];
171                         float mu2 = mu[m.other_player];
172                         float mu = mu1 - mu2;
173                         float x = m.margin;
174                         float w = m.weight;
175
176                         nom += w * ((x - mu) * (x - mu));
177                         denom += w;
178                 }
179         }
180
181         float best_sigma = sqrt(nom / denom) / sqrt(2.0f);  // Divide evenly between the two players.
182         for (int i = 0; i < num_players; ++i) {
183                 sigma[i] = best_sigma;
184         }
185 }
186
187 /*
188  * diff(priorlogL, sigma) = w ( (x - mu)² - sigma² ) / sigma³
189  * maximizer for sigma is given by: sum_i[ (w_i/sigma)³ ((x - mu)² - sigma²) ] = 0
190  *                                   sum_i[ w_i ( (x - mu)² - sigma² ) ] = 0                            |: sigma != 0
191  *                                   sum_i[ w_i (x - mu)² ] = sum[ w_i sigma² ]
192  *                                   sigma = sqrt( sum_i[ w_i (x - mu)² ] / sum[w_i] )
193  */
194 void update_prior_sigma(float *mu, float *sigma, int num_players)
195 {
196         float nom = 0.0f, denom = 0.0f;
197         for (int i = 0; i < num_players; ++i) {
198                 for (unsigned j = 0; j < matches_for_player[i].size(); ++j) {
199                         const match& m = matches_for_player[i][j];
200
201                         // Only count each match once.
202                         if (m.other_player <= i) {
203                                 continue;
204                         }
205
206                         float mu1 = mu[i];
207
208                         float w = m.weight;
209                         nom += w * ((mu1 - PRIOR_MU) * (mu1 - PRIOR_MU));
210                         denom += w * 1.0f;
211                 }
212         }
213
214         prior_sigma = sqrt(nom / denom);
215 }
216
217 /*
218  * Compute Hessian matrix of the negative log-likelihood, ie. for each term in logL:
219  *
220  * M_ij = D_i D_j (- logL) = -w / sigma²                                for i != j
221  *                            w / sigma²                                for i == j
222  *
223  * Note that this does not depend on mu or the margin at all.
224  */
225 double hessian[MAX_PLAYERS][MAX_PLAYERS];
226 void construct_hessian(const float *mu, const float *sigma, int num_players)
227 {
228         memset(hessian, 0, sizeof(hessian));
229
230         for (int i = 0; i < num_players; ++i) {
231                 double sigma1 = sigma[i];
232
233                 for (unsigned k = 0; k < matches_for_player[i].size(); ++k) {
234                         int j = matches_for_player[i][k].other_player;
235
236                         double sigma2 = sigma[j];
237                         double sigma_sq = sigma1 * sigma1 + sigma2 * sigma2;
238
239                         float w = matches_for_player[i][k].weight;
240
241                         hessian[i][j] -= w / sigma_sq;
242                         hessian[i][i] += w / sigma_sq;
243                 }
244         }
245
246         for (int i = 0; i < num_players; ++i) {
247                 for (int j = 0; j < num_players; ++j) {
248                         printf("%.12f ", hessian[i][j]);
249                 }
250                 printf("\n");
251         }
252 }
253
254 int main(int argc, char **argv)
255 {
256         int num_players;
257         if (scanf("%d", &num_players) != 1) {
258                 fprintf(stderr, "Could't read number of players\n");
259                 exit(1);
260         }
261
262         if (num_players > MAX_PLAYERS) {
263                 fprintf(stderr, "Max %d players supported\n", MAX_PLAYERS);
264                 exit(1);
265         }
266
267         vector<string> players;
268         map<string, int> player_map;
269
270         for (int i = 0; i < num_players; ++i) {
271                 char buf[256];
272                 if (scanf("%s", buf) != 1) {
273                         fprintf(stderr, "Couldn't read player %d\n", i);
274                         exit(1);
275                 }
276
277                 players.push_back(buf);
278                 player_map[buf] = i;
279         }
280
281         int num_matches = 0;
282         for ( ;; ) {
283                 char pl1[256], pl2[256];
284                 int score1, score2;
285                 float weight;
286
287                 if (scanf("%s %s %d %d %f", pl1, pl2, &score1, &score2, &weight) != 5) {
288                         //fprintf(stderr, "Read %d matches.\n", num_matches);
289                         break;
290                 }
291
292                 ++num_matches;
293
294                 if (player_map.count(pl1) == 0) {
295                         fprintf(stderr, "Unknown player '%s'\n", pl1);
296                         exit(1);
297                 }
298                 if (player_map.count(pl2) == 0) {
299                         fprintf(stderr, "Unknown player '%s'\n", pl2);
300                         exit(1);
301                 }
302
303                 match m1;
304                 m1.other_player = player_map[pl2];
305                 m1.margin = score1 - score2;
306                 m1.weight = weight;
307                 matches_for_player[player_map[pl1]].push_back(m1);
308
309                 match m2;
310                 m2.other_player = player_map[pl1];
311                 m2.margin = score2 - score1;
312                 m2.weight = weight;
313                 matches_for_player[player_map[pl2]].push_back(m2);
314         }
315
316         float mu[MAX_PLAYERS];
317         float sigma[MAX_PLAYERS];
318
319         for (int i = 0; i < num_players; ++i) {
320                 mu[i] = PRIOR_MU;
321                 sigma[i] = 70.0f / sqrt(2.0f);
322         }
323
324         for (int j = 0; j < 1000; ++j) {
325                 float old_mu[MAX_PLAYERS];
326                 float old_sigma[MAX_PLAYERS];
327                 float old_prior_sigma = prior_sigma;
328                 memcpy(old_mu, mu, sizeof(mu));
329                 memcpy(old_sigma, sigma, sizeof(sigma));
330                 for (int i = 0; i < num_players; ++i) {
331                         update_mu(mu, sigma, i, matches_for_player[i]);
332                 }
333                 update_global_sigma(mu, sigma, num_players);
334                 update_prior_sigma(mu, sigma, num_players);
335                 /* for (int i = 0; i < num_players; ++i) {
336                         update_sigma(mu, sigma, i, matches_for_player[i]);
337                         dump_scores(players, mu, sigma, num_players);
338                 } */
339
340                 float sumdiff = 0.0f;
341                 for (int i = 0; i < num_players; ++i) {
342                         sumdiff += (mu[i] - old_mu[i]) * (mu[i] - old_mu[i]);
343                         sumdiff += (sigma[i] - old_sigma[i]) * (sigma[i] - old_sigma[i]);
344                 }
345                 sumdiff += (prior_sigma - old_prior_sigma) * (prior_sigma - old_prior_sigma);
346                 if (sumdiff < EPSILON) {
347                         //fprintf(stderr, "Converged after %d iterations. Stopping.\n", j);
348                         printf("%d -1\n", j + 1);
349                         break;
350                 }
351         }
352
353 #if DUMP_RAW
354         dump_raw(mu, sigma, num_players);
355 #else
356         dump_scores(players, mu, sigma, num_players);
357         //fprintf(stderr, "Optimal sigma: %f (two-player: %f)\n", sigma[0], sigma[0] * sqrt(2.0f));
358         printf("%f -2\n", sigma[0]);
359         printf("%f -3\n", prior_sigma);
360
361 //      construct_hessian(mu, sigma, num_players);
362 #endif
363 }