]> git.sesse.net Git - foosball/blob - foosrank.cpp
25298e7ddfe0bdc16590ab98e806dd8150401a1e
[foosball] / foosrank.cpp
1 #include <cstdio>
2 #include <cmath>
3 #include <cassert>
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 static double prob_score(int k, int a, double rd);
20 static double prob_score_real(int k, int a, double binomial, double rd_norm);
21 static double prodai(int k, int a);
22 static 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 static 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 static 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 static 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 static 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 static 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 static void compute_opponent_rating_pdf(int k, int a, double mu2, double sigma2, double winfac, vector<pair<double, double> > &result)
91 {
92         double binomial_precompute = prodai(k, a) / fac(k-1);
93         winfac /= rating_constant;
94
95         int sz = (6000.0 - 0.0) / int_step_size;
96         double h = (6000.0 - 0.0) / sz;
97
98         fftw_plan f1, f2, b;
99         complex<double> *func1, *func2, *res;
100
101         func1 = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
102         func2 = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
103         res = reinterpret_cast<complex<double> *>(fftw_malloc(sz*2*sizeof(complex<double>)));
104         f1 = fftw_plan_dft_1d(sz*2,
105                 reinterpret_cast<fftw_complex*>(func1),
106                 reinterpret_cast<fftw_complex*>(func1),
107                 FFTW_FORWARD,
108                 FFTW_MEASURE);
109         f2 = fftw_plan_dft_1d(sz*2,
110                 reinterpret_cast<fftw_complex*>(func2),
111                 reinterpret_cast<fftw_complex*>(func2),
112                 FFTW_FORWARD,
113                 FFTW_MEASURE);
114         b = fftw_plan_dft_1d(sz*2,
115                 reinterpret_cast<fftw_complex*>(res),
116                 reinterpret_cast<fftw_complex*>(res),
117                 FFTW_BACKWARD,
118                 FFTW_MEASURE);
119         
120         // start off by zero
121         for (int i = 0; i < sz*2; ++i) {
122                 func1[i].real() = func1[i].imag() = func2[i].real() = func2[i].imag() = 0.0;
123         }
124
125         for (int i = 0; i < sz; ++i) {
126                 double x1 = 0.0 + h*i;
127                 double z = (x1 - mu2)/sigma2;
128                 func1[i].real() = exp(-(z*z/2.0));
129
130                 double x2 = -3000.0 + h*i;
131                 func2[(i - sz/2 + sz*2)%(sz*2)].real() = prob_score_real(k, a, binomial_precompute, x2*winfac);
132         }
133
134         result.reserve(sz*2);
135
136         // convolve
137         fftw_execute(f1);
138         fftw_execute(f2);
139         for (int i = 0; i < sz*2; ++i) {
140                 res[i] = func1[i] * func2[i];
141         }
142         fftw_execute(b);
143         for (int i = 0; i < sz; ++i) {
144                 double r1 = i*h;
145                 result.push_back(make_pair(r1, abs(res[i])));
146         }
147 }
148
149 // normalize the curve so we know that A ~= 1
150 static void normalize(vector<pair<double, double> > &curve)
151 {
152         double peak = 0.0;
153         for (vector<pair<double, double> >::const_iterator i = curve.begin(); i != curve.end(); ++i) {
154                 peak = max(peak, i->second);
155         }
156
157         double invpeak = 1.0 / peak;
158         for (vector<pair<double, double> >::iterator i = curve.begin(); i != curve.end(); ++i) {
159                 i->second *= invpeak;
160         }
161 }
162
163 // computes matA^T * matB
164 static void mat_mul_trans(double *matA, unsigned ah, unsigned aw,
165                           double *matB, unsigned bh, unsigned bw,
166                           double *result)
167 {
168         assert(ah == bh);
169         for (unsigned y = 0; y < bw; ++y) {
170                 for (unsigned x = 0; x < aw; ++x) {
171                         double sum = 0.0;
172                         for (unsigned c = 0; c < ah; ++c) {
173                                 sum += matA[x*ah + c] * matB[y*bh + c];
174                         }
175                         result[y*bw + x] = sum;
176                 }
177         }
178 }
179
180 // solves Ax = B by Gauss-Jordan elimination, where A is an NxN matrix,
181 // x is a column vector of length N and B is a row vector of length N.
182 // Destroys its input in the process.
183 template<int N>
184 static void solve_matrix(double *A, double *x, double *B)
185 {
186         for (int i = 0; i < N; ++i) {
187                 for (int j = i+1; j < N; ++j) {
188                         // row j -= row i * (a[i,j] / a[i,i])
189                         double f = A[j+i*N] / A[i+i*N];
190
191                         A[j+i*N] = 0.0;
192                         for (int k = i+1; k < N; ++k) {
193                                 A[j+k*N] -= A[i+k*N] * f;
194                         }
195
196                         B[j] -= B[i] * f;
197                 }
198         }
199
200         // back-substitute
201         for (int i = N; i --> 0; ) {
202                 for (int j = i; j --> 0; ) {
203                         // row j -= row i * (a[j,j] / a[j,i])
204                         double f = A[i+j*N] / A[j+j*N];
205                         
206                         // A[j+i*N] = 0.0;
207                         B[j] -= B[i] * f;
208                 }
209         }
210
211         // normalize
212         for (int i = 0; i < N; ++i) {
213                 x[i] = B[i] / A[i+i*N];
214         }
215 }
216
217 // Give an OK starting estimate for the least squares, by numerical integration
218 // of statistical moments.
219 static void estimate_musigma(vector<pair<double, double> > &curve, double &mu_result, double &sigma_result)
220 {
221         double h = (curve.back().first - curve.front().first) / (curve.size() - 1);
222
223         double area = curve.front().second;
224         double ex = curve.front().first * curve.front().second;
225         double ex2 = curve.front().first * curve.front().first * curve.front().second;
226
227         for (unsigned i = 1; i < curve.size() - 1; i += 2) {
228                 double x = curve[i].first;
229                 double y = curve[i].second;
230                 area += 4.0 * y;
231                 ex += 4.0 * x * y;
232                 ex2 += 4.0 * x * x * y;
233         }
234         for (unsigned i = 2; i < curve.size() - 1; i += 2) {
235                 double x = curve[i].first;
236                 double y = curve[i].second;
237                 area += 2.0 * y;
238                 ex += 2.0 * x * y;
239                 ex2 += 2.0 * x * x * y;
240         }
241         
242         area += curve.back().second;
243         ex += curve.back().first * curve.back().second;
244         ex2 += curve.back().first * curve.back().first * curve.back().second;
245
246         area = (h/3.0) * area;
247         ex = (h/3.0) * ex / area;
248         ex2 = (h/3.0) * ex2 / area;
249
250         mu_result = ex;
251         sigma_result = sqrt(ex2 - ex * ex);
252 }
253         
254 // Find best fit of the data in curves to a Gaussian pdf, based on the
255 // given initial estimates. Works by nonlinear least squares, iterating
256 // until we're below a certain threshold.
257 //
258 // Note that the algorithm blows up quite hard if the initial estimate is
259 // not good enough. Use estimate_musigma to get a reasonable starting
260 // estimate.
261 static void least_squares(vector<pair<double, double> > &curve, double mu1, double sigma1, double &mu_result, double &sigma_result)
262 {
263         double A = 1.0;
264         double mu = mu1;
265         double sigma = sigma1;
266
267         // column-major
268         double matA[curve.size() * 3];  // N x 3
269         double dbeta[curve.size()];     // N x 1
270
271         // A^T * A: 3xN * Nx3 = 3x3
272         double matATA[3*3];
273
274         // A^T * dβ: 3xN * Nx1 = 3x1
275         double matATdb[3];
276
277         double dlambda[3];
278
279         for ( ;; ) {
280                 //printf("A=%f mu=%f sigma=%f\n", A, mu, sigma);
281
282                 // fill in A (depends only on x_i, A, mu, sigma -- not y_i)
283                 for (unsigned i = 0; i < curve.size(); ++i) {
284                         double x = curve[i].first;
285
286                         // df/dA(x_i)
287                         matA[i + 0 * curve.size()] = 
288                                 exp(-(x-mu)*(x-mu)/(2.0*sigma*sigma));
289
290                         // df/dµ(x_i)
291                         matA[i + 1 * curve.size()] = 
292                                 A * (x-mu)/(sigma*sigma) * matA[i + 0 * curve.size()];
293
294                         // df/dσ(x_i)
295                         matA[i + 2 * curve.size()] = 
296                                 matA[i + 1 * curve.size()] * (x-mu)/sigma;
297                 }
298
299                 // find dβ
300                 for (unsigned i = 0; i < curve.size(); ++i) {
301                         double x = curve[i].first;
302                         double y = curve[i].second;
303
304                         dbeta[i] = y - A * exp(- (x-mu)*(x-mu)/(2.0*sigma*sigma));
305                 }
306
307                 // compute a and b
308                 mat_mul_trans(matA, curve.size(), 3, matA, curve.size(), 3, matATA);
309                 mat_mul_trans(matA, curve.size(), 3, dbeta, curve.size(), 1, matATdb);
310
311                 // solve
312                 solve_matrix<3>(matATA, dlambda, matATdb);
313
314                 A += dlambda[0];
315                 mu += dlambda[1];
316                 sigma += dlambda[2];
317
318                 // terminate when we're down to three digits
319                 if (fabs(dlambda[0]) <= 1e-3 && fabs(dlambda[1]) <= 1e-3 && fabs(dlambda[2]) <= 1e-3)
320                         break;
321         }
322
323         mu_result = mu;
324         sigma_result = sigma;
325 }
326
327 static void compute_new_rating(double mu1, double sigma1, double mu2, double sigma2, int score1, int score2, double &mu, double &sigma)
328 {
329         vector<pair<double, double> > curve;
330
331         if (score1 > score2) {
332                 compute_opponent_rating_pdf(score1, score2, mu2, sigma2, -1.0, curve);
333         } else {
334                 compute_opponent_rating_pdf(score2, score1, mu2, sigma2, 1.0, curve);
335         }
336
337         // multiply in the gaussian
338         for (unsigned i = 0; i < curve.size(); ++i) {
339                 double r1 = curve[i].first;
340                 double z = (r1 - mu1) / sigma1;
341                 double gaussian = exp(-(z*z/2.0));
342                 curve[i].second *= gaussian;
343         }
344
345         double mu_est, sigma_est;
346         normalize(curve);
347         estimate_musigma(curve, mu_est, sigma_est);
348         least_squares(curve, mu_est, sigma_est, mu, sigma);
349 }
350
351 static 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)
352 {
353         vector<pair<double, double> > curve, newcurve;
354         double mu_t = mu3 + mu4;
355         double sigma_t = sqrt(sigma3*sigma3 + sigma4*sigma4);
356                         
357         if (score1 > score2) {
358                 compute_opponent_rating_pdf(score1, score2, mu_t, sigma_t, -1.0, curve);
359         } else {
360                 compute_opponent_rating_pdf(score2, score1, mu_t, sigma_t, 1.0, curve);
361         }
362
363         // iterate over r1
364         double h = 3000.0 / curve.size();
365         for (unsigned i = 0; i < curve.size(); ++i) {
366                 double sum = 0.0;
367
368                 // could be anything, but this is a nice start
369                 //double r1 = curve[i].first;
370                 double r1 = i * h;
371
372                 // iterate over r2
373                 for (unsigned j = 0; j < curve.size(); ++j) {
374                         double r1plusr2 = curve[j].first;
375                         double r2 = r1plusr2 - r1;
376
377                         double z = (r2 - mu2) / sigma2;
378                         double gaussian = exp(-(z*z/2.0));
379                         sum += curve[j].second * gaussian;
380                 }
381
382                 double z = (r1 - mu1) / sigma1;
383                 double gaussian = exp(-(z*z/2.0));
384                 newcurve.push_back(make_pair(r1, gaussian * sum));
385         }
386
387
388         double mu_est, sigma_est;
389         normalize(newcurve);
390         estimate_musigma(newcurve, mu_est, sigma_est);
391         least_squares(newcurve, mu_est, sigma_est, mu, sigma);
392 }
393
394 int main(int argc, char **argv)
395 {
396         FILE *fp = fopen("fftw-wisdom", "rb");
397         if (fp != NULL) {
398                 fftw_import_wisdom_from_file(fp);
399                 fclose(fp);
400         }
401
402         double mu1 = atof(argv[1]);
403         double sigma1 = atof(argv[2]);
404         double mu2 = atof(argv[3]);
405         double sigma2 = atof(argv[4]);
406
407         if (argc > 10) {
408                 double mu3 = atof(argv[5]);
409                 double sigma3 = atof(argv[6]);
410                 double mu4 = atof(argv[7]);
411                 double sigma4 = atof(argv[8]);
412                 int score1 = atoi(argv[9]);
413                 int score2 = atoi(argv[10]);
414                 double mu, sigma;
415                 compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, score1, score2, mu, sigma);
416                 printf("%f %f\n", mu, sigma);
417         } else if (argc > 8) {
418                 double mu3 = atof(argv[5]);
419                 double sigma3 = atof(argv[6]);
420                 double mu4 = atof(argv[7]);
421                 double sigma4 = atof(argv[8]);
422                 int k = atoi(argv[9]);
423                 
424                 // assess all possible scores
425                 for (int i = 0; i < k; ++i) {
426                         double newmu1_1, newmu1_2, newmu2_1, newmu2_2;
427                         double newsigma1_1, newsigma1_2, newsigma2_1, newsigma2_2;
428                         compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, k, i, newmu1_1, newsigma1_1);
429                         compute_new_double_rating(mu2, sigma2, mu1, sigma1, mu3, sigma3, mu4, sigma4, k, i, newmu1_2, newsigma1_2);
430                         compute_new_double_rating(mu3, sigma3, mu4, sigma4, mu1, sigma1, mu2, sigma2, i, k, newmu2_1, newsigma2_1);
431                         compute_new_double_rating(mu4, sigma4, mu3, sigma3, mu1, sigma1, mu2, sigma2, i, k, newmu2_2, newsigma2_2);
432                         printf("%u-%u,%f,%+f,%+f,%+f,%+f\n",
433                                 k, i, prob_score(k, i, mu3+mu4-(mu1+mu2)), newmu1_1-mu1, newmu1_2-mu2,
434                                 newmu2_1-mu3, newmu2_2-mu4);
435                 }
436                 for (int i = k; i --> 0; ) {
437                         double newmu1_1, newmu1_2, newmu2_1, newmu2_2;
438                         double newsigma1_1, newsigma1_2, newsigma2_1, newsigma2_2;
439                         compute_new_double_rating(mu1, sigma1, mu2, sigma2, mu3, sigma3, mu4, sigma4, i, k, newmu1_1, newsigma1_1);
440                         compute_new_double_rating(mu2, sigma2, mu1, sigma1, mu3, sigma3, mu4, sigma4, i, k, newmu1_2, newsigma1_2);
441                         compute_new_double_rating(mu3, sigma3, mu4, sigma4, mu1, sigma1, mu2, sigma2, k, i, newmu2_1, newsigma2_1);
442                         compute_new_double_rating(mu4, sigma4, mu3, sigma3, mu1, sigma1, mu2, sigma2, k, i, newmu2_2, newsigma2_2);
443                         printf("%u-%u,%f,%+f,%+f,%+f,%+f\n",
444                                 i, k, prob_score(k, i, mu1+mu2-(mu3+mu4)), newmu1_1-mu1, newmu1_2-mu2,
445                                 newmu2_1-mu3, newmu2_2-mu4);
446                 }
447         } else if (argc > 6) {
448                 int score1 = atoi(argv[5]);
449                 int score2 = atoi(argv[6]);
450                 double mu, sigma;
451                 compute_new_rating(mu1, sigma1, mu2, sigma2, score1, score2, mu, sigma);
452                 printf("%f %f\n", mu, sigma);
453         } else {
454                 int k = atoi(argv[5]);
455
456                 // assess all possible scores
457                 for (int i = 0; i < k; ++i) {
458                         double newmu1, newmu2, newsigma1, newsigma2;
459                         compute_new_rating(mu1, sigma1, mu2, sigma2, k, i, newmu1, newsigma1);
460                         compute_new_rating(mu2, sigma2, mu1, sigma1, i, k, newmu2, newsigma2);
461                         printf("%u-%u,%f,%+f,%+f\n",
462                                 k, i, prob_score(k, i, mu2-mu1), newmu1-mu1, newmu2-mu2);
463                 }
464                 for (int i = k; i --> 0; ) {
465                         double newmu1, newmu2, newsigma1, newsigma2;
466                         compute_new_rating(mu1, sigma1, mu2, sigma2, i, k, newmu1, newsigma1);
467                         compute_new_rating(mu2, sigma2, mu1, sigma1, k, i, newmu2, newsigma2);
468                         printf("%u-%u,%f,%+f,%+f\n",
469                                 i, k, prob_score(k, i, mu1-mu2), newmu1-mu1, newmu2-mu2);
470                 }
471         }
472         
473         fp = fopen("fftw-wisdom", "wb");
474         if (fp != NULL) {
475                 fftw_export_wisdom_to_file(fp);
476                 fclose(fp);
477         }
478 }
479