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