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