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