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