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