]> git.sesse.net Git - foosball/blob - foosrank.cpp
Precompute the binomial as a single value instead of two separate ones.
[foosball] / foosrank.cpp
1 #include <stdio.h>
2 #include <math.h>
3 #include <assert.h>
4
5 #include <vector>
6 #include <algorithm>
7
8 // step sizes
9 static const double int_step_size = 50.0;
10 static const double pdf_step_size = 10.0;
11
12 // rating constant (see below)
13 static const double rating_constant = 455.0;
14
15 using namespace std;
16
17 double prob_score(int k, double a, double rd);
18 double prob_score_real(int k, double a, double binomial, double rd_norm);
19 double prodai(int k, double a);
20 double fac(int x);
21
22 // Numerical integration using Simpson's rule
23 template<class T>
24 double simpson_integrate(const T &evaluator, double from, double to, double step)
25 {
26         int n = int((to - from) / step + 0.5);
27         double h = (to - from) / n;
28         double sum = evaluator(from);
29
30         for (int i = 1; i < n; i += 2) {
31                 sum += 4.0 * evaluator(from + i * h);
32         }
33         for (int i = 2; i < n; i += 2) {
34                 sum += 2.0 * evaluator(from + i * h);
35         }
36         sum += evaluator(to);
37
38         return (h/3.0) * sum;
39 }
40
41 // probability of match ending k-a (k>a) when winnerR - loserR = RD
42 //
43 //   +inf  
44 //     / 
45 //    |
46 //    | Poisson[lambda1, t](a) * Erlang[lambda2, k](t) dt
47 //    |
48 //   /
49 // -inf
50 //
51 // where lambda1 = 1.0, lambda2 = 2^(rd/455)
52 //
53 // The constant of 455 is chosen carefully so to match with the
54 // Glicko/Bradley-Terry assumption that a player rated 400 points over
55 // his/her opponent will win with a probability of 10/11 =~ 0.90909. 
56 //
57 double prob_score(int k, double a, double rd)
58 {
59         return prob_score_real(k, a, prodai(k, a) / fac(k-1), rd/rating_constant);
60 }
61
62 // Same, but takes in binomial(a+k-1, k-1) as an argument in
63 // addition to a. Faster if you already have that precomputed, and assumes rd
64 // is already divided by 455.
65 double prob_score_real(int k, double a, double binomial, double rd_norm)
66 {
67         double nom = binomial * pow(2.0, rd_norm * a); 
68         double denom = pow(1.0 + pow(2.0, rd_norm), k+a);
69         return nom/denom;
70 }
71
72 // Calculates Product(a+i, i=1..k-1) (see above).
73 double prodai(int k, double a)
74 {
75         double prod = 1.0;
76         for (int i = 1; i < k; ++i)
77                 prod *= (a+i);
78         return prod;
79 }
80
81 double fac(int x)
82 {
83         double prod = 1.0;
84         for (int i = 2; i <= x; ++i)
85                 prod *= i;
86         return prod;
87 }
88
89 // 
90 // Computes the integral
91 //
92 //   +inf
93 //    /
94 //    |
95 //    | ProbScore[a] (r2-r1) Gaussian[mu2, sigma2] (dr2) dr2
96 //    |
97 //   /
98 // -inf
99 //
100 // For practical reasons, -inf and +inf are replaced by 0 and 3000, which
101 // is reasonable in the this context.
102 //
103 // The Gaussian is not normalized.
104 //
105 // Set the last parameter to 1.0 if player 1 won, or -1.0 if player 2 won.
106 // In the latter case, ProbScore will be given (r1-r2) instead of (r2-r1).
107 //
108 class ProbScoreEvaluator {
109 private:
110         int k;
111         double a;
112         double binomial_precompute, r1, mu2, sigma2, winfac;
113
114 public:
115         ProbScoreEvaluator(int k, double a, double binomial_precompute, double r1, double mu2, double sigma2, double winfac)
116                 : k(k), a(a), binomial_precompute(binomial_precompute), r1(r1), mu2(mu2), sigma2(sigma2), winfac(winfac) {}
117         inline double operator() (double x) const
118         {
119                 double probscore = prob_score_real(k, a, binomial_precompute, (x - r1)*winfac);
120                 double z = (x - mu2)/sigma2;
121                 double gaussian = exp(-(z*z/2.0));
122                 return probscore * gaussian;
123         }
124 };
125
126 double opponent_rating_pdf(int k, double a, double r1, double mu2, double sigma2, double winfac)
127 {
128         double binomial_precompute = prodai(k, a) / fac(k-1);
129         winfac /= rating_constant;
130
131         return simpson_integrate(ProbScoreEvaluator(k, a, binomial_precompute, r1, mu2, sigma2, winfac), 0.0, 3000.0, int_step_size);
132 }
133
134 // normalize the curve so we know that A ~= 1
135 void normalize(vector<pair<double, double> > &curve)
136 {
137         double peak = 0.0;
138         for (vector<pair<double, double> >::const_iterator i = curve.begin(); i != curve.end(); ++i) {
139                 peak = max(peak, i->second);
140         }
141
142         double invpeak = 1.0 / peak;
143         for (vector<pair<double, double> >::iterator i = curve.begin(); i != curve.end(); ++i) {
144                 i->second *= invpeak;
145         }
146 }
147
148 // computes matA * matB
149 void mat_mul(double *matA, unsigned ah, unsigned aw,
150              double *matB, unsigned bh, unsigned bw,
151              double *result)
152 {
153         assert(aw == bh);
154         for (unsigned y = 0; y < bw; ++y) {
155                 for (unsigned x = 0; x < ah; ++x) {
156                         double sum = 0.0;
157                         for (unsigned c = 0; c < aw; ++c) {
158                                 sum += matA[c*ah + x] * matB[y*bh + c];
159                         }
160                         result[y*bw + x] = sum;
161                 }
162         }
163 }
164                 
165 // computes matA^T * matB
166 void mat_mul_trans(double *matA, unsigned ah, unsigned aw,
167                    double *matB, unsigned bh, unsigned bw,
168                    double *result)
169 {
170         assert(ah == bh);
171         for (unsigned y = 0; y < bw; ++y) {
172                 for (unsigned x = 0; x < aw; ++x) {
173                         double sum = 0.0;
174                         for (unsigned c = 0; c < ah; ++c) {
175                                 sum += matA[x*ah + c] * matB[y*bh + c];
176                         }
177                         result[y*bw + x] = sum;
178                 }
179         }
180 }
181
182 void print3x3(double *M)
183 {
184         printf("%f %f %f\n", M[0], M[3], M[6]);
185         printf("%f %f %f\n", M[1], M[4], M[7]);
186         printf("%f %f %f\n", M[2], M[5], M[8]);
187 }
188
189 void print3x1(double *M)
190 {
191         printf("%f\n", M[0]);
192         printf("%f\n", M[1]);
193         printf("%f\n", M[2]);
194 }
195
196 // solves Ax = B by Gauss-Jordan elimination, where A is a 3x3 matrix,
197 // x is a column vector of length 3 and B is a row vector of length 3.
198 // Destroys its input in the process.
199 void solve3x3(double *A, double *x, double *B)
200 {
201         // row 1 -= row 0 * (a1/a0)
202         {
203                 double f = A[1] / A[0];
204                 A[1] = 0.0;
205                 A[4] -= A[3] * f;
206                 A[7] -= A[6] * f;
207
208                 B[1] -= B[0] * f;
209         }
210
211         // row 2 -= row 0 * (a2/a0)
212         {
213                 double f = A[2] / A[0];
214                 A[2] = 0.0;
215                 A[5] -= A[3] * f;
216                 A[8] -= A[6] * f;
217
218                 B[2] -= B[0] * f;
219         }
220
221         // row 2 -= row 1 * (a5/a4)
222         {
223                 double f = A[5] / A[4];
224                 A[5] = 0.0;
225                 A[8] -= A[7] * f;
226                 
227                 B[2] -= B[1] * f;
228         }
229
230         // back substitute:
231
232         // row 1 -= row 2 * (a7/a8)
233         {
234                 double f = A[7] / A[8];
235                 A[7] = 0.0;
236
237                 B[1] -= B[2] * f;
238         }
239
240         // row 0 -= row 2 * (a6/a8)
241         {
242                 double f = A[6] / A[8];
243                 A[6] = 0.0;
244
245                 B[0] -= B[2] * f;
246         }
247
248         // row 0 -= row 1 * (a3/a4)
249         {
250                 double f = A[3] / A[4];
251                 A[3] = 0.0;
252
253                 B[0] -= B[1] * f;
254         }
255
256         // normalize
257         x[0] = B[0] / A[0];
258         x[1] = B[1] / A[4];
259         x[2] = B[2] / A[8];
260 }
261
262 // Give an OK starting estimate for the least squares, by numerical integration
263 // of statistical moments.
264 void estimate_musigma(vector<pair<double, double> > &curve, double &mu_result, double &sigma_result)
265 {
266         double h = (curve.back().first - curve.front().first) / (curve.size() - 1);
267
268         double area = curve.front().second;
269         double ex = curve.front().first * curve.front().second;
270         double ex2 = curve.front().first * curve.front().first * curve.front().second;
271
272         for (unsigned i = 1; i < curve.size() - 1; i += 2) {
273                 double x = curve[i].first;
274                 double y = curve[i].second;
275                 area += 4.0 * y;
276                 ex += 4.0 * x * y;
277                 ex2 += 4.0 * x * x * y;
278         }
279         for (unsigned i = 2; i < curve.size() - 1; i += 2) {
280                 double x = curve[i].first;
281                 double y = curve[i].second;
282                 area += 2.0 * y;
283                 ex += 2.0 * x * y;
284                 ex2 += 2.0 * x * x * y;
285         }
286         
287         area += curve.back().second;
288         ex += curve.back().first * curve.back().second;
289         ex2 += curve.back().first * curve.back().first * curve.back().second;
290
291         area = (h/3.0) * area;
292         ex = (h/3.0) * ex / area;
293         ex2 = (h/3.0) * ex2 / area;
294
295         mu_result = ex;
296         sigma_result = sqrt(ex2 - ex * ex);
297 }
298         
299 // Find best fit of the data in curves to a Gaussian pdf, based on the
300 // given initial estimates. Works by nonlinear least squares, iterating
301 // until we're below a certain threshold.
302 //
303 // Note that the algorithm blows up quite hard if the initial estimate is
304 // not good enough. Use estimate_musigma to get a reasonable starting
305 // estimate.
306 void least_squares(vector<pair<double, double> > &curve, double mu1, double sigma1, double &mu_result, double &sigma_result)
307 {
308         double A = 1.0;
309         double mu = mu1;
310         double sigma = sigma1;
311
312         // column-major
313         double matA[curve.size() * 3];  // N x 3
314         double dbeta[curve.size()];     // N x 1
315
316         // A^T * A: 3xN * Nx3 = 3x3
317         double matATA[3*3];
318
319         // A^T * dβ: 3xN * Nx1 = 3x1
320         double matATdb[3];
321
322         double dlambda[3];
323
324         for ( ;; ) {
325                 //printf("A=%f mu=%f sigma=%f\n", A, mu, sigma);
326
327                 // fill in A (depends only on x_i, A, mu, sigma -- not y_i)
328                 for (unsigned i = 0; i < curve.size(); ++i) {
329                         double x = curve[i].first;
330
331                         // df/dA(x_i)
332                         matA[i + 0 * curve.size()] = 
333                                 exp(-(x-mu)*(x-mu)/(2.0*sigma*sigma));
334
335                         // df/dµ(x_i)
336                         matA[i + 1 * curve.size()] = 
337                                 A * (x-mu)/(sigma*sigma) * matA[i + 0 * curve.size()];
338
339                         // df/dσ(x_i)
340                         matA[i + 2 * curve.size()] = 
341                                 matA[i + 1 * curve.size()] * (x-mu)/sigma;
342                 }
343
344                 // find dβ
345                 for (unsigned i = 0; i < curve.size(); ++i) {
346                         double x = curve[i].first;
347                         double y = curve[i].second;
348
349                         dbeta[i] = y - A * exp(- (x-mu)*(x-mu)/(2.0*sigma*sigma));
350                 }
351
352                 // compute a and b
353                 mat_mul_trans(matA, curve.size(), 3, matA, curve.size(), 3, matATA);
354                 mat_mul_trans(matA, curve.size(), 3, dbeta, curve.size(), 1, matATdb);
355
356                 // solve
357                 solve3x3(matATA, dlambda, matATdb);
358
359                 A += dlambda[0];
360                 mu += dlambda[1];
361                 sigma += dlambda[2];
362
363                 // terminate when we're down to three digits
364                 if (fabs(dlambda[0]) <= 1e-3 && fabs(dlambda[1]) <= 1e-3 && fabs(dlambda[2]) <= 1e-3)
365                         break;
366         }
367
368         mu_result = mu;
369         sigma_result = sigma;
370 }
371
372 void compute_new_rating(double mu1, double sigma1, double mu2, double sigma2, int score1, int score2, double &mu, double &sigma)
373 {
374         vector<pair<double, double> > curve;
375
376         if (score1 > score2) {
377                 for (double r1 = 0.0; r1 < 3000.0; r1 += pdf_step_size) {
378                         double z = (r1 - mu1) / sigma1;
379                         double gaussian = exp(-(z*z/2.0));
380                         curve.push_back(make_pair(r1, gaussian * opponent_rating_pdf(score1, score2, r1, mu2, sigma2, 1.0)));
381                 }
382         } else {
383                 for (double r1 = 0.0; r1 < 3000.0; r1 += pdf_step_size) {
384                         double z = (r1 - mu1) / sigma1;
385                         double gaussian = exp(-(z*z/2.0));
386                         curve.push_back(make_pair(r1, gaussian * opponent_rating_pdf(score2, score1, r1, mu2, sigma2, -1.0)));
387                 }
388         }
389
390         double mu_est, sigma_est;
391         normalize(curve);
392         estimate_musigma(curve, mu_est, sigma_est);
393         least_squares(curve, mu_est, sigma_est, mu, sigma);
394 }
395
396 int main(int argc, char **argv)
397 {
398         double mu1 = atof(argv[1]);
399         double sigma1 = atof(argv[2]);
400         double mu2 = atof(argv[3]);
401         double sigma2 = atof(argv[4]);
402
403         if (argc > 6) {
404                 int score1 = atoi(argv[5]);
405                 int score2 = atoi(argv[6]);
406                 double mu, sigma;
407                 compute_new_rating(mu1, sigma1, mu2, sigma2, score1, score2, mu, sigma);
408                 printf("%f %f\n", mu, sigma);
409         } else {
410                 int k = atoi(argv[5]);
411
412                 // assess all possible scores
413                 for (int i = 0; i < k; ++i) {
414                         double newmu1, newmu2, newsigma1, newsigma2;
415                         compute_new_rating(mu1, sigma1, mu2, sigma2, k, i, newmu1, newsigma1);
416                         compute_new_rating(mu2, sigma2, mu1, sigma1, i, k, newmu2, newsigma2);
417                         printf("%u-%u,%f,%+f,%+f\n",
418                                 k, i, prob_score(k, i, mu2-mu1), newmu1-mu1, newmu2-mu2);
419                 }
420                 for (int i = k; i --> 0; ) {
421                         double newmu1, newmu2, newsigma1, newsigma2;
422                         compute_new_rating(mu1, sigma1, mu2, sigma2, i, k, newmu1, newsigma1);
423                         compute_new_rating(mu2, sigma2, mu1, sigma1, k, i, newmu2, newsigma2);
424                         printf("%u-%u,%f,%+f,%+f\n",
425                                 i, k, prob_score(k, i, mu1-mu2), newmu1-mu1, newmu2-mu2);
426                 }
427         }
428 }
429