]> git.sesse.net Git - foosball/blob - foosrank.cpp
45c08cc1479264adf49909c28f210c8683fa31f7
[foosball] / foosrank.cpp
1 #include <stdio.h>
2 #include <math.h>
3 #include <assert.h>
4
5 #include <vector>
6 #include <algorithm>
7
8 #include <complex>
9 #include <fftw3.h>
10
11 // step sizes
12 static const double int_step_size = 75.0;
13
14 // rating constant (see below)
15 static const double rating_constant = 455.0;
16
17 using namespace std;
18
19 double prob_score(int k, int a, double rd);
20 double prob_score_real(int k, int a, double binomial, double rd_norm);
21 double prodai(int k, int a);
22 double fac(int x);
23
24
25 // probability of match ending k-a (k>a) when winnerR - loserR = RD
26 //
27 //   +inf  
28 //     / 
29 //    |
30 //    | Poisson[lambda1, t](a) * Erlang[lambda2, k](t) dt
31 //    |
32 //   /
33 // -inf
34 //
35 // where lambda1 = 1.0, lambda2 = 2^(rd/455)
36 //
37 // The constant of 455 is chosen carefully so to match with the
38 // Glicko/Bradley-Terry assumption that a player rated 400 points over
39 // his/her opponent will win with a probability of 10/11 =~ 0.90909. 
40 //
41 double prob_score(int k, int a, double rd)
42 {
43         return prob_score_real(k, a, prodai(k, a) / fac(k-1), rd/rating_constant);
44 }
45
46 // computes x^a, probably more efficiently than pow(x, a) (but requires that a
47 // is n unsigned integer)
48 double intpow(double x, unsigned a)
49 {
50         double result = 1.0;
51
52         while (a > 0) {
53                 if (a & 1) {
54                         result *= x;
55                 }
56                 a >>= 1;
57                 x *= x;
58         }
59
60         return result;
61 }
62
63 // Same, but takes in binomial(a+k-1, k-1) as an argument in
64 // addition to a. Faster if you already have that precomputed, and assumes rd
65 // is already divided by 455.
66 double prob_score_real(int k, int a, double binomial, double rd_norm)
67 {
68         double nom = binomial * intpow(pow(2.0, rd_norm), a); 
69         double denom = intpow(1.0 + pow(2.0, rd_norm), k+a);
70         return nom/denom;
71 }
72
73 // Calculates Product(a+i, i=1..k-1) (see above).
74 double prodai(int k, int a)
75 {
76         double prod = 1.0;
77         for (int i = 1; i < k; ++i)
78                 prod *= (a+i);
79         return prod;
80 }
81
82 double fac(int x)
83 {
84         double prod = 1.0;
85         for (int i = 2; i <= x; ++i)
86                 prod *= i;
87         return prod;
88 }
89
90 void convolve(int size)
91 {
92 }
93
94 void compute_opponent_rating_pdf(int k, int a, double mu2, double sigma2, double winfac, vector<pair<double, double> > &result)
95 {
96         double binomial_precompute = prodai(k, a) / fac(k-1);
97         winfac /= rating_constant;
98
99         int sz = (6000.0 - 0.0) / int_step_size;
100         double h = (6000.0 - 0.0) / sz;
101
102         fftw_plan f1, f2, b;
103         complex<double> *func1, *func2, *res;
104
105         func1 = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
106         func2 = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
107         res = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
108         f1 = fftw_plan_dft_1d(sz*2,
109                 reinterpret_cast<fftw_complex*>(func1),
110                 reinterpret_cast<fftw_complex*>(func1),
111                 FFTW_FORWARD,
112                 FFTW_MEASURE);
113         f2 = fftw_plan_dft_1d(sz*2,
114                 reinterpret_cast<fftw_complex*>(func2),
115                 reinterpret_cast<fftw_complex*>(func2),
116                 FFTW_FORWARD,
117                 FFTW_MEASURE);
118         b = fftw_plan_dft_1d(sz*2,
119                 reinterpret_cast<fftw_complex*>(res),
120                 reinterpret_cast<fftw_complex*>(res),
121                 FFTW_BACKWARD,
122                 FFTW_MEASURE);
123         
124         // start off by zero
125         for (int i = 0; i < sz*2; ++i) {
126                 func1[i].real() = func1[i].imag() = func2[i].real() = func2[i].imag() = 0.0;
127         }
128
129         for (int i = 0; i < sz; ++i) {
130                 double x1 = 0.0 + h*i;
131                 double z = (x1 - mu2)/sigma2;
132                 func1[i].real() = exp(-(z*z/2.0));
133
134                 double x2 = -3000.0 + h*i;
135                 func2[(i - sz/2 + sz*2)%(sz*2)].real() = prob_score_real(k, a, binomial_precompute, x2*winfac);
136         }
137
138         result.reserve(sz*2);
139
140         // convolve
141         fftw_execute(f1);
142         fftw_execute(f2);
143         for (int i = 0; i < sz*2; ++i) {
144                 res[i] = func1[i] * func2[i];
145         }
146         fftw_execute(b);
147         for (int i = 0; i < sz; ++i) {
148                 double r1 = i*h;
149                 result.push_back(make_pair(r1, abs(res[i])));
150         }
151 }
152
153 // normalize the curve so we know that A ~= 1
154 void normalize(vector<pair<double, double> > &curve)
155 {
156         double peak = 0.0;
157         for (vector<pair<double, double> >::const_iterator i = curve.begin(); i != curve.end(); ++i) {
158                 peak = max(peak, i->second);
159         }
160
161         double invpeak = 1.0 / peak;
162         for (vector<pair<double, double> >::iterator i = curve.begin(); i != curve.end(); ++i) {
163                 i->second *= invpeak;
164         }
165 }
166
167 // computes matA * matB
168 void mat_mul(double *matA, unsigned ah, unsigned aw,
169              double *matB, unsigned bh, unsigned bw,
170              double *result)
171 {
172         assert(aw == bh);
173         for (unsigned y = 0; y < bw; ++y) {
174                 for (unsigned x = 0; x < ah; ++x) {
175                         double sum = 0.0;
176                         for (unsigned c = 0; c < aw; ++c) {
177                                 sum += matA[c*ah + x] * matB[y*bh + c];
178                         }
179                         result[y*bw + x] = sum;
180                 }
181         }
182 }
183                 
184 // computes matA^T * matB
185 void mat_mul_trans(double *matA, unsigned ah, unsigned aw,
186                    double *matB, unsigned bh, unsigned bw,
187                    double *result)
188 {
189         assert(ah == bh);
190         for (unsigned y = 0; y < bw; ++y) {
191                 for (unsigned x = 0; x < aw; ++x) {
192                         double sum = 0.0;
193                         for (unsigned c = 0; c < ah; ++c) {
194                                 sum += matA[x*ah + c] * matB[y*bh + c];
195                         }
196                         result[y*bw + x] = sum;
197                 }
198         }
199 }
200
201 void print3x3(double *M)
202 {
203         printf("%f %f %f\n", M[0], M[3], M[6]);
204         printf("%f %f %f\n", M[1], M[4], M[7]);
205         printf("%f %f %f\n", M[2], M[5], M[8]);
206 }
207
208 void print3x1(double *M)
209 {
210         printf("%f\n", M[0]);
211         printf("%f\n", M[1]);
212         printf("%f\n", M[2]);
213 }
214
215 // solves Ax = B by Gauss-Jordan elimination, where A is a 3x3 matrix,
216 // x is a column vector of length 3 and B is a row vector of length 3.
217 // Destroys its input in the process.
218 void solve3x3(double *A, double *x, double *B)
219 {
220         // row 1 -= row 0 * (a1/a0)
221         {
222                 double f = A[1] / A[0];
223                 A[1] = 0.0;
224                 A[4] -= A[3] * f;
225                 A[7] -= A[6] * f;
226
227                 B[1] -= B[0] * f;
228         }
229
230         // row 2 -= row 0 * (a2/a0)
231         {
232                 double f = A[2] / A[0];
233                 A[2] = 0.0;
234                 A[5] -= A[3] * f;
235                 A[8] -= A[6] * f;
236
237                 B[2] -= B[0] * f;
238         }
239
240         // row 2 -= row 1 * (a5/a4)
241         {
242                 double f = A[5] / A[4];
243                 A[5] = 0.0;
244                 A[8] -= A[7] * f;
245                 
246                 B[2] -= B[1] * f;
247         }
248
249         // back substitute:
250
251         // row 1 -= row 2 * (a7/a8)
252         {
253                 double f = A[7] / A[8];
254                 A[7] = 0.0;
255
256                 B[1] -= B[2] * f;
257         }
258
259         // row 0 -= row 2 * (a6/a8)
260         {
261                 double f = A[6] / A[8];
262                 A[6] = 0.0;
263
264                 B[0] -= B[2] * f;
265         }
266
267         // row 0 -= row 1 * (a3/a4)
268         {
269                 double f = A[3] / A[4];
270                 A[3] = 0.0;
271
272                 B[0] -= B[1] * f;
273         }
274
275         // normalize
276         x[0] = B[0] / A[0];
277         x[1] = B[1] / A[4];
278         x[2] = B[2] / A[8];
279 }
280
281 // Give an OK starting estimate for the least squares, by numerical integration
282 // of statistical moments.
283 void estimate_musigma(vector<pair<double, double> > &curve, double &mu_result, double &sigma_result)
284 {
285         double h = (curve.back().first - curve.front().first) / (curve.size() - 1);
286
287         double area = curve.front().second;
288         double ex = curve.front().first * curve.front().second;
289         double ex2 = curve.front().first * curve.front().first * curve.front().second;
290
291         for (unsigned i = 1; i < curve.size() - 1; i += 2) {
292                 double x = curve[i].first;
293                 double y = curve[i].second;
294                 area += 4.0 * y;
295                 ex += 4.0 * x * y;
296                 ex2 += 4.0 * x * x * y;
297         }
298         for (unsigned i = 2; i < curve.size() - 1; i += 2) {
299                 double x = curve[i].first;
300                 double y = curve[i].second;
301                 area += 2.0 * y;
302                 ex += 2.0 * x * y;
303                 ex2 += 2.0 * x * x * y;
304         }
305         
306         area += curve.back().second;
307         ex += curve.back().first * curve.back().second;
308         ex2 += curve.back().first * curve.back().first * curve.back().second;
309
310         area = (h/3.0) * area;
311         ex = (h/3.0) * ex / area;
312         ex2 = (h/3.0) * ex2 / area;
313
314         mu_result = ex;
315         sigma_result = sqrt(ex2 - ex * ex);
316 }
317         
318 // Find best fit of the data in curves to a Gaussian pdf, based on the
319 // given initial estimates. Works by nonlinear least squares, iterating
320 // until we're below a certain threshold.
321 //
322 // Note that the algorithm blows up quite hard if the initial estimate is
323 // not good enough. Use estimate_musigma to get a reasonable starting
324 // estimate.
325 void least_squares(vector<pair<double, double> > &curve, double mu1, double sigma1, double &mu_result, double &sigma_result)
326 {
327         double A = 1.0;
328         double mu = mu1;
329         double sigma = sigma1;
330
331         // column-major
332         double matA[curve.size() * 3];  // N x 3
333         double dbeta[curve.size()];     // N x 1
334
335         // A^T * A: 3xN * Nx3 = 3x3
336         double matATA[3*3];
337
338         // A^T * dβ: 3xN * Nx1 = 3x1
339         double matATdb[3];
340
341         double dlambda[3];
342
343         for ( ;; ) {
344                 //printf("A=%f mu=%f sigma=%f\n", A, mu, sigma);
345
346                 // fill in A (depends only on x_i, A, mu, sigma -- not y_i)
347                 for (unsigned i = 0; i < curve.size(); ++i) {
348                         double x = curve[i].first;
349
350                         // df/dA(x_i)
351                         matA[i + 0 * curve.size()] = 
352                                 exp(-(x-mu)*(x-mu)/(2.0*sigma*sigma));
353
354                         // df/dµ(x_i)
355                         matA[i + 1 * curve.size()] = 
356                                 A * (x-mu)/(sigma*sigma) * matA[i + 0 * curve.size()];
357
358                         // df/dσ(x_i)
359                         matA[i + 2 * curve.size()] = 
360                                 matA[i + 1 * curve.size()] * (x-mu)/sigma;
361                 }
362
363                 // find dβ
364                 for (unsigned i = 0; i < curve.size(); ++i) {
365                         double x = curve[i].first;
366                         double y = curve[i].second;
367
368                         dbeta[i] = y - A * exp(- (x-mu)*(x-mu)/(2.0*sigma*sigma));
369                 }
370
371                 // compute a and b
372                 mat_mul_trans(matA, curve.size(), 3, matA, curve.size(), 3, matATA);
373                 mat_mul_trans(matA, curve.size(), 3, dbeta, curve.size(), 1, matATdb);
374
375                 // solve
376                 solve3x3(matATA, dlambda, matATdb);
377
378                 A += dlambda[0];
379                 mu += dlambda[1];
380                 sigma += dlambda[2];
381
382                 // terminate when we're down to three digits
383                 if (fabs(dlambda[0]) <= 1e-3 && fabs(dlambda[1]) <= 1e-3 && fabs(dlambda[2]) <= 1e-3)
384                         break;
385         }
386
387         mu_result = mu;
388         sigma_result = sigma;
389 }
390
391 void compute_new_rating(double mu1, double sigma1, double mu2, double sigma2, int score1, int score2, double &mu, double &sigma)
392 {
393         vector<pair<double, double> > curve;
394
395         if (score1 > score2) {
396                 compute_opponent_rating_pdf(score1, score2, mu2, sigma2, -1.0, curve);
397         } else {
398                 compute_opponent_rating_pdf(score2, score1, mu2, sigma2, 1.0, curve);
399         }
400
401         // multiply in the gaussian
402         for (unsigned i = 0; i < curve.size(); ++i) {
403                 double r1 = curve[i].first;
404                 double z = (r1 - mu1) / sigma1;
405                 double gaussian = exp(-(z*z/2.0));
406                 curve[i].second *= gaussian;
407         }
408
409         double mu_est, sigma_est;
410         normalize(curve);
411         estimate_musigma(curve, mu_est, sigma_est);
412         least_squares(curve, mu_est, sigma_est, mu, sigma);
413 }
414
415 void compute_new_double_rating(double mu1, double sigma1, double mu2, double sigma2, double mu3, double sigma3, double mu4, double sigma4, int score1, int score2, double &mu, double &sigma)
416 {
417         vector<pair<double, double> > curve, newcurve;
418         double mu_t = mu3 + mu4;
419         double sigma_t = sqrt(sigma3*sigma3 + sigma4*sigma4);
420                         
421         if (score1 > score2) {
422                 compute_opponent_rating_pdf(score1, score2, mu_t, sigma_t, -1.0, curve);
423         } else {
424                 compute_opponent_rating_pdf(score2, score1, mu_t, sigma_t, 1.0, curve);
425         }
426
427         // iterate over r1
428         double h = 3000.0 / curve.size();
429         for (unsigned i = 0; i < curve.size(); ++i) {
430                 double sum = 0.0;
431
432                 // could be anything, but this is a nice start
433                 //double r1 = curve[i].first;
434                 double r1 = i * h;
435
436                 // iterate over r2
437                 for (unsigned j = 0; j < curve.size(); ++j) {
438                         double r1plusr2 = curve[j].first;
439                         double r2 = r1plusr2 - r1;
440
441                         double z = (r2 - mu2) / sigma2;
442                         double gaussian = exp(-(z*z/2.0));
443                         sum += curve[j].second * gaussian;
444                 }
445
446                 double z = (r1 - mu1) / sigma1;
447                 double gaussian = exp(-(z*z/2.0));
448                 newcurve.push_back(make_pair(r1, gaussian * sum));
449         }
450
451
452         double mu_est, sigma_est;
453         normalize(newcurve);
454         estimate_musigma(newcurve, mu_est, sigma_est);
455         least_squares(newcurve, mu_est, sigma_est, mu, sigma);
456 }
457
458 int main(int argc, char **argv)
459 {
460         FILE *fp = fopen("fftw-wisdom", "rb");
461         if (fp != NULL) {
462                 fftw_import_wisdom_from_file(fp);
463                 fclose(fp);
464         }
465
466         double mu1 = atof(argv[1]);
467         double sigma1 = atof(argv[2]);
468         double mu2 = atof(argv[3]);
469         double sigma2 = atof(argv[4]);
470
471         if (argc > 10) {
472                 double mu3 = atof(argv[5]);
473                 double sigma3 = atof(argv[6]);
474                 double mu4 = atof(argv[7]);
475                 double sigma4 = atof(argv[8]);
476                 int score1 = atoi(argv[9]);
477                 int score2 = atoi(argv[10]);
478                 double mu, sigma;
479                 compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, score1, score2, mu, sigma);
480                 printf("%f %f\n", mu, sigma);
481         } else if (argc > 8) {
482                 double mu3 = atof(argv[5]);
483                 double sigma3 = atof(argv[6]);
484                 double mu4 = atof(argv[7]);
485                 double sigma4 = atof(argv[8]);
486                 int k = atoi(argv[9]);
487                 
488                 // assess all possible scores
489                 for (int i = 0; i < k; ++i) {
490                         double newmu1_1, newmu1_2, newmu2_1, newmu2_2;
491                         double newsigma1_1, newsigma1_2, newsigma2_1, newsigma2_2;
492                         compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, k, i, newmu1_1, newsigma1_1);
493                         compute_new_double_rating(mu2, sigma2, mu1, sigma1, mu3, sigma3, mu4, sigma4, k, i, newmu1_2, newsigma1_2);
494                         compute_new_double_rating(mu3, sigma3, mu4, sigma4, mu1, sigma1, mu2, sigma2, i, k, newmu2_1, newsigma2_1);
495                         compute_new_double_rating(mu4, sigma4, mu3, sigma3, mu1, sigma1, mu2, sigma2, i, k, newmu2_2, newsigma2_2);
496                         printf("%u-%u,%f,%+f,%+f,%+f,%+f\n",
497                                 k, i, prob_score(k, i, mu3+mu4-(mu1+mu2)), newmu1_1-mu1, newmu1_2-mu2,
498                                 newmu2_1-mu3, newmu2_2-mu4);
499                 }
500                 for (int i = k; i --> 0; ) {
501                         double newmu1_1, newmu1_2, newmu2_1, newmu2_2;
502                         double newsigma1_1, newsigma1_2, newsigma2_1, newsigma2_2;
503                         compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, i, k, newmu1_1, newsigma1_1);
504                         compute_new_double_rating(mu2, sigma2, mu1, sigma1, mu3, sigma3, mu4, sigma4, i, k, newmu1_2, newsigma1_2);
505                         compute_new_double_rating(mu3, sigma3, mu4, sigma4, mu1, sigma1, mu2, sigma2, k, i, newmu2_1, newsigma2_1);
506                         compute_new_double_rating(mu4, sigma4, mu3, sigma3, mu1, sigma1, mu2, sigma2, k, i, newmu2_2, newsigma2_2);
507                         printf("%u-%u,%f,%+f,%+f,%+f,%+f\n",
508                                 i, k, prob_score(k, i, mu1+mu2-(mu3+mu4)), newmu1_1-mu1, newmu1_2-mu2,
509                                 newmu2_1-mu3, newmu2_2-mu4);
510                 }
511         } else if (argc > 6) {
512                 int score1 = atoi(argv[5]);
513                 int score2 = atoi(argv[6]);
514                 double mu, sigma;
515                 compute_new_rating(mu1, sigma1, mu2, sigma2, score1, score2, mu, sigma);
516                 printf("%f %f\n", mu, sigma);
517         } else {
518                 int k = atoi(argv[5]);
519
520                 // assess all possible scores
521                 for (int i = 0; i < k; ++i) {
522                         double newmu1, newmu2, newsigma1, newsigma2;
523                         compute_new_rating(mu1, sigma1, mu2, sigma2, k, i, newmu1, newsigma1);
524                         compute_new_rating(mu2, sigma2, mu1, sigma1, i, k, newmu2, newsigma2);
525                         printf("%u-%u,%f,%+f,%+f\n",
526                                 k, i, prob_score(k, i, mu2-mu1), newmu1-mu1, newmu2-mu2);
527                 }
528                 for (int i = k; i --> 0; ) {
529                         double newmu1, newmu2, newsigma1, newsigma2;
530                         compute_new_rating(mu1, sigma1, mu2, sigma2, i, k, newmu1, newsigma1);
531                         compute_new_rating(mu2, sigma2, mu1, sigma1, k, i, newmu2, newsigma2);
532                         printf("%u-%u,%f,%+f,%+f\n",
533                                 i, k, prob_score(k, i, mu1-mu2), newmu1-mu1, newmu2-mu2);
534                 }
535         }
536         
537         fp = fopen("fftw-wisdom", "wb");
538         if (fp != NULL) {
539                 fftw_export_wisdom_to_file(fp);
540                 fclose(fp);
541         }
542 }
543