]> git.sesse.net Git - wloh/blob - www/index.pl
Factor out the division selector 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 make_table {
125         my ($lowest_division, $used_ratings, $used_cov) = @_;
126
127         print <<"EOF";
128
129     <table>
130       <tr>
131         <th></th>
132 EOF
133
134         POSIX::setlocale(&POSIX::LC_ALL, 'C');
135
136         my $tmpnam = POSIX::tmpnam();
137         open MCCALC, ">", $tmpnam
138                 or die "$tmpnam: $!";
139
140         printf MCCALC "%f\n", $match_stddev;
141         printf MCCALC "%d\n", scalar keys %players;
142
143         for my $id (keys %players) {
144                 my $rating = $used_ratings->{$id} // 500.0;
145                 printf MCCALC "%s %f\n", $id, $rating;
146         }
147
148         # covariance matrix
149         for my $id1 (keys %players) {
150                 for my $id2 (keys %players) {
151                         if ($id1 == $id2) {
152                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $parms{-3});
153                         } else {
154                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
155                         }
156                 }
157                 printf MCCALC "\n";
158         }
159
160         for my $match (@matches) {
161                 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
162         }
163         close MCCALC;
164
165         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
166
167         my %prob = ();
168
169         open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
170                 or die "mccalc: $!";
171         while (<MCCALC>) {
172                 chomp;
173                 my @x = split /\s+/;
174                 my $id = $x[0];
175                 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $parms{-3});
176                 $prob{$player} = [ @x[1..$#x] ];
177         }
178         close MCCALC;
179         #unlink $tmpnam;
180
181         my $num_games = scalar keys %prob;
182         for my $i (1..$num_games) {
183                 print "        <th>$i.</th>\n";
184         }
185         print "        <th>NEDRYKK</th>\n" unless ($lowest_division);
186         print "      </tr>\n";
187
188         for my $player (sort { $a cmp $b } keys %prob) {
189                 print "      <tr>\n";
190                 print "        <th>$player</th>\n";
191
192                 for my $i (1..$num_games) {
193                         my $pn = $prob{$player}->[$i - 1] / $trials;
194
195                         my $r = color(1.0 - $pn / 3);
196                         my $g = color(1.0 - $pn / 3);
197                         my $b = color(1.0);
198
199                         if ($i == 1) {
200                                 ($g, $b) = ($b, $g);
201                         } elsif ($i >= $num_games - 1 && !$lowest_division) {
202                                 ($r, $b) = ($b, $r);
203                         }
204
205                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
206                 }
207
208                 unless ($lowest_division) {
209                         my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
210
211                         my $r = color(1.0);
212                         my $g = color(1.0 - $pn / 3);
213                         my $b = color(1.0 - $pn / 3);
214                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
215                 }
216                 print "      </tr>\n";
217         }
218
219         print << "EOF";
220     </table>
221 EOF
222 }
223
224 # Get auxillary parameters
225 my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
226 $q->execute;
227
228 while (my $ref = $q->fetchrow_hashref) {
229         $parms{$ref->{'id'}} = $ref->{'rating'};
230 }
231 $match_stddev = $parms{-2} * sqrt(2.0);
232
233 my $season;
234 my $division = $cgi->param('divisjon') // -1;
235 my $subdivision = $cgi->param('avdeling') // -1;
236 my $last_division = 0;
237
238 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
239
240 print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
241 printf <<"EOF", $match_stddev;
242 <?xml version="1.0" encoding="UTF-8" ?>
243 <!DOCTYPE
244   html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
245   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
246 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
247   <head>
248     <title>WLoH-plasseringsannsynlighetsberegning</title>
249     <link rel="stylesheet" href="/style" type="text/css" />
250   </head>
251   <body>
252     <h1>WLoH-plasseringsannsynlighetsberegning</h1>
253
254     <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
255       <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
256
257     <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
258       den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
259       %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
260       Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.</p>
261
262     <p>Spillerne er sortert etter nick.</p>
263 EOF
264
265 my $season = get_max_season($dbh);
266 my @divisions = get_divisions($dbh, $season);
267 $division = 1 if (!grep { $_ == $division } @divisions);
268 my @subdivisions = get_subdivisions($dbh, $season, $division);
269 $subdivision = 1 if (!grep { $_ == $subdivision } @subdivisions);
270
271 print_division_selector($dbh, \@divisions, \@subdivisions, $division, $subdivision);
272
273 # Get players and ratings
274 my $sum_rating = 0.0;
275
276 $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=?');
277 $q->execute($season, $division, $subdivision);
278
279 while (my $ref = $q->fetchrow_hashref) {
280         my $id = $ref->{'id'};
281         $players{$id} = sanitize(Encode::decode_utf8($ref->{'navn'}));
282         $ratings{$id} = $ref->{'rating'};
283         $ratings_stddev{$id} = $ref->{'rating_stddev'};
284         $sum_rating += $ref->{'rating'};
285 }
286 $q->finish;
287
288 $q = $dbh->prepare('
289 SELECT
290   d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
291 FROM fotballresultater r
292   JOIN fotballserier s ON r.serie=s.nr
293   JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
294   JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
295 WHERE
296   sesong=? AND divisjon=? AND avdeling=?
297   AND lagrecno > motstander
298 ');
299 $q->execute($season, $division, $subdivision);
300
301 while (my $ref = $q->fetchrow_hashref) {
302         push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
303 }
304 $q->finish;
305
306 # Pick up covariance matrix
307 my $player_sql = '{' . join(',', keys %players ) . '}';
308 my $q = $dbh->prepare('SELECT * FROM covariance WHERE player1=ANY(?::smallint[]) AND player2=ANY(?::smallint[])', { pg_prepare_now => 0 });
309 $q->execute($player_sql, $player_sql);
310
311 my $cov = {};
312 while (my $ref = $q->fetchrow_hashref) {
313         $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
314 }
315
316 my $max_division = $divisions[$#divisions];
317 my $lowest_division = ($division == $max_division);
318 make_table($lowest_division, {}, {});
319
320 print <<"EOF";
321     <p>Under er en variant som tar relativ spillestyrke med i beregningen;
322       se <a href="/rating">ratingsiden</a>.</p>
323 EOF
324
325 make_table($lowest_division, \%ratings, $cov);
326
327 my $avg_rating = $sum_rating / scalar keys %players;
328 printf "    <p>Gjennomsnittlig rating i denne avdelingen er <strong>%.1f</strong>.</p>\n", $avg_rating;
329
330 wloh_common::output_last_sync($dbh);
331
332 print <<"EOF";
333   </body>
334 </html>
335 EOF