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