8 my $dbh = DBI->connect("dbi:Pg:dbname=foosball;host=127.0.0.1", "foosball", "cleanrun", {AutoCommit => 0});
9 $dbh->{RaiseError} = 1;
13 sub find_single_rating {
14 my ($dbh, $username, $limit) = @_;
15 my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM single_rating WHERE username=? '.$limit.' ORDER BY ratetime DESC LIMIT 1',
17 $rd = apply_aging($rd, $age / 86400.0);
18 return ($rating, $rd);
21 sub find_double_rating {
22 my ($dbh, $username, $limit) = @_;
23 my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM double_rating WHERE username=? '.$limit.'ORDER BY ratetime DESC LIMIT 1',
25 $rd = apply_aging($rd, $age / 86400.0);
26 return ($rating, $rd);
29 sub create_user_if_not_exists {
30 my ($dbh, $username) = @_;
31 my $count = $dbh->selectrow_array('SELECT count(*) FROM users WHERE username=?',
33 return if ($count > 0);
34 $dbh->do('INSERT INTO users (username) VALUES (?)',
36 $dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
38 $dbh->do('INSERT INTO double_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
46 my ($score1, $score2) = @_;
49 return 0.60 + 0.40 * (9.0-$score2)/9.0;
53 return 0.40 - 0.40 * (9.0-$score1)/9.0;
58 # c=8 => RD=50 moves to RD=350 over approx. five years
63 $rd = sqrt($rd*$rd + $c * $c * ($age / 86400.0));
64 $rd = 350.0 if ($rd > 350.0);
68 our $q = log(10)/400.0;
69 our $pi = 3.1415926535897932384626433832795;
75 # a^b = exp(log(a^b)) = exp(b log a)
76 return exp($b * log($a));
81 return 1.0 / sqrt(1.0 + 3.0 * $q * $q * $rd * $rd / ($pi*$pi));
85 my ($r, $rating, $rd) = @_;
86 return 1.0 / (1.0 + pow(10.0, - g($rd) * ($r - $rating) / 400.0));
90 my ($r, $rating, $rd) = @_;
91 return 1.0 / ($q*$q * g($rd) * g($rd) * E($r, $rating, $rd) * (1 - E($r, $rating, $rd)));
95 my ($rating1, $rd1, $rating2, $rd2, $score1, $score2) = @_;
96 my $s1 = find_score($score1, $score2);
97 my $d1sq = dsq($rating1, $rating2, $rd2);
98 my $newr1 = $rating1 + ($q / (1.0/($rd1*$rd1) + 1.0 / $d1sq)) * g($rd2) * ($s1 - E($rating1, $rating2, $rd2));
99 my $newrd1 = sqrt(1.0 / (1.0 / ($rd1*$rd1) + 1.0 / $d1sq));
101 $newrd1 = 30.0 if ($newrd1 < 30.0);
103 return ($newr1, $newrd1);