]> git.sesse.net Git - wloh/blob - www/index.pl
Use covariance matrix under Monte Carlo simulation, to draw better strengths.
[wloh] / www / index.pl
1 #! /usr/bin/perl
2 use strict;
3 use warnings;
4 no warnings qw(once);
5 use CGI;
6 use CGI::Carp qw( fatalsToBrowser );
7 use DBI;
8 use POSIX;
9 use Devel::Peek;
10 use HTML::Entities;
11 use Encode;
12 use utf8;
13 use locale;
14 require '../config.pm';
15
16 my $cgi = CGI->new;
17
18 my $dbh = DBI->connect($config::local_connstr, $config::local_username, $config::local_password)
19         or die "connect: " . $DBI::errstr;
20 $dbh->{AutoCommit} = 0;
21 $dbh->{RaiseError} = 1;
22
23 my $trials = 25_000;
24
25 binmode STDOUT, ':utf8';
26
27 my %players = ();
28 my %ratings = ();
29 my %ratings_stddev = ();
30 my @matches = ();
31 my %parms = ();
32 my $match_stddev;
33
34 sub sanitize {
35         return HTML::Entities::encode_entities(shift);
36 }
37
38 sub color {
39         my $x = shift;
40         return int(255.0 * ($x ** (1.80)));
41 }
42
43 sub make_table {
44         my ($lowest_division, $used_ratings, $used_cov) = @_;
45
46         print <<"EOF";
47
48     <table>
49       <tr>
50         <th></th>
51 EOF
52
53         POSIX::setlocale(&POSIX::LC_ALL, 'C');
54
55         my $tmpnam = POSIX::tmpnam();
56         open MCCALC, ">", $tmpnam
57                 or die "$tmpnam: $!";
58
59         printf MCCALC "%f\n", $match_stddev;
60         printf MCCALC "%d\n", scalar keys %players;
61
62         for my $id (keys %players) {
63                 my $rating = $used_ratings->{$id} // 1500.0;
64                 printf MCCALC "%s %f\n", $id, $rating;
65         }
66
67         # covariance matrix
68         for my $id1 (keys %players) {
69                 for my $id2 (keys %players) {
70                         if ($id1 == $id2) {
71                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $parms{-3});
72                         } else {
73                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
74                         }
75                 }
76                 printf MCCALC "\n";
77         }
78
79         for my $match (@matches) {
80                 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
81         }
82         close MCCALC;
83
84         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
85
86         my %prob = ();
87
88         open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
89                 or die "mccalc: $!";
90         while (<MCCALC>) {
91                 chomp;
92                 my @x = split /\s+/;
93                 my $id = $x[0];
94                 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 1500.0), ($ratings_stddev{$id} // $parms{-3});
95                 $prob{$player} = [ @x[1..$#x] ];
96         }
97         close MCCALC;
98         #unlink $tmpnam;
99
100         my $num_games = scalar keys %prob;
101         for my $i (1..$num_games) {
102                 print "        <th>$i.</th>\n";
103         }
104         print "        <th>NEDRYKK</th>\n" unless ($lowest_division);
105         print "      </tr>\n";
106
107         for my $player (sort { $a cmp $b } keys %prob) {
108                 print "      <tr>\n";
109                 print "        <th>$player</th>\n";
110
111                 for my $i (1..$num_games) {
112                         my $pn = $prob{$player}->[$i - 1] / $trials;
113
114                         my $r = color(1.0 - $pn / 3);
115                         my $g = color(1.0 - $pn / 3);
116                         my $b = color(1.0);
117
118                         if ($i == 1) {
119                                 ($g, $b) = ($b, $g);
120                         } elsif ($i >= $num_games - 1 && !$lowest_division) {
121                                 ($r, $b) = ($b, $r);
122                         }
123
124                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
125                 }
126
127                 unless ($lowest_division) {
128                         my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
129
130                         my $r = color(1.0);
131                         my $g = color(1.0 - $pn / 3);
132                         my $b = color(1.0 - $pn / 3);
133                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
134                 }
135                 print "      </tr>\n";
136         }
137
138         print << "EOF";
139     </table>
140 EOF
141 }
142
143 # Get auxillary parameters
144 my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
145 $q->execute;
146
147 while (my $ref = $q->fetchrow_hashref) {
148         $parms{$ref->{'id'}} = $ref->{'rating'};
149 }
150 $match_stddev = $parms{-2} * sqrt(2.0);
151
152 my $season;
153 my $division = $cgi->param('divisjon') // -1;
154 my $subdivision = $cgi->param('avdeling') // -1;
155 my $last_division = 0;
156
157 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
158
159 print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
160 printf <<"EOF", $match_stddev;
161 <?xml version="1.0" encoding="UTF-8" ?>
162 <!DOCTYPE
163   html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
164   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
165 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
166   <head>
167     <title>WLoH-plasseringsannsynlighetsberegning</title>
168     <link rel="stylesheet" href="/style" type="text/css" />
169   </head>
170   <body>
171     <h1>WLoH-plasseringsannsynlighetsberegning</h1>
172
173     <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
174       <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
175
176     <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
177       den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
178       %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
179       Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.</p>
180
181     <p>Spillerne er sortert etter nick.</p>
182
183     <form method="get" action="/">
184 EOF
185
186 $q = $dbh->prepare('SELECT MAX(sesong) AS max_sesong FROM fotballserier');
187 $q->execute;
188 my $season;
189 while (my $ref = $q->fetchrow_hashref) {
190         $season = $ref->{'max_sesong'};
191 }
192
193 print <<"EOF";
194      <p>Divisjon:
195         <select name="divisjon" onchange="form.submit();">
196 EOF
197
198 $q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier WHERE sesong=? ORDER BY divisjon');
199 $q->execute($season);
200
201 my $found_division = 0;
202 my $max_division;
203
204 while (my $ref = $q->fetchrow_hashref) {
205         my $d = $ref->{'divisjon'};
206         if ($d == $division) {
207                 print "        <option value=\"$d\" selected=\"selected\">$d</option>\n";
208                 $found_division = 1;
209         } else {
210                 print "        <option value=\"$d\">$d</option>\n";
211         }
212         $max_division = $d;
213 }
214
215 $division = 1 if (!$found_division);
216
217 print <<"EOF";
218         </select>
219         Avdeling:
220         <select name="avdeling" onchange="form.submit();">
221 EOF
222
223 $q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier WHERE sesong=? AND divisjon=? ORDER BY avdeling');
224 $q->execute($season, $division);
225
226 my $found_subdivision = 0;
227
228 while (my $ref = $q->fetchrow_hashref) {
229         my $sd = $ref->{'avdeling'};
230         if ($sd == $subdivision) {
231                 print "        <option value=\"$sd\" selected=\"selected\">$sd</option>\n";
232                 $found_subdivision = 1;
233         } else {
234                 print "        <option value=\"$sd\">$sd</option>\n";
235         }
236 }
237
238 $subdivision = 1 if (!$found_subdivision);
239
240 print <<"EOF";
241         </select>
242         <input type="submit" value="Vis" />
243       </p>
244     </form>
245 EOF
246
247 # Get players and ratings
248 $q = $dbh->prepare('SELECT fotballdeltagere.id,fotballdeltagere.navn,rating,rating_stddev FROM fotballdeltagere JOIN fotballserier ON fotballdeltagere.serie=fotballserier.nr LEFT JOIN ratings ON fotballdeltagere.id=ratings.id WHERE sesong=? AND divisjon=? AND avdeling=?');
249 $q->execute($season, $division, $subdivision);
250
251 while (my $ref = $q->fetchrow_hashref) {
252         my $id = $ref->{'id'};
253         $players{$id} = sanitize(Encode::decode_utf8($ref->{'navn'}));
254         $ratings{$id} = $ref->{'rating'};
255         $ratings_stddev{$id} = $ref->{'rating_stddev'};
256 }
257 $q->finish;
258
259 $q = $dbh->prepare('
260 SELECT
261   d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
262 FROM fotballresultater r
263   JOIN fotballserier s ON r.serie=s.nr
264   JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
265   JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
266 WHERE
267   sesong=? AND divisjon=? AND avdeling=?
268   AND lagrecno > motstander
269 ');
270 $q->execute($season, $division, $subdivision);
271
272 while (my $ref = $q->fetchrow_hashref) {
273         push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
274 }
275 $q->finish;
276
277 # Pick up covariance matrix
278 my $player_sql = '{' . join(',', keys %players ) . '}';
279 my $q = $dbh->prepare('SELECT * FROM covariance WHERE player1=ANY(?::smallint[]) AND player2=ANY(?::smallint[])', { pg_prepare_now => 0 });
280 $q->execute($player_sql, $player_sql);
281
282 my $cov = {};
283 while (my $ref = $q->fetchrow_hashref) {
284         $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
285 }
286
287 my $lowest_division = ($division == $max_division);
288 make_table($lowest_division, {}, {});
289
290 print <<"EOF";
291     <p>Under er en variant som tar relativ spillestyrke med i beregningen;
292       se <a href="/rating">ratingsiden</a>.</p>
293 EOF
294
295 make_table($lowest_division, \%ratings, $cov);
296
297 print <<"EOF";
298   </body>
299 </html>
300 EOF