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