]> git.sesse.net Git - wloh/blob - www/index.pl
Add clickable fun to the probability matrix.
[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
33 sub sanitize {
34         return HTML::Entities::encode_entities(shift);
35 }
36
37 sub color {
38         my $x = shift;
39         return int(255.0 * ($x ** (1.80)));
40 }
41
42 sub get_max_season {
43         my $dbh = shift;
44         my $ref = $dbh->selectrow_hashref('SELECT MAX(sesong) AS max_sesong FROM fotballserier');
45         return $ref->{'max_sesong'};
46 }
47
48 sub get_divisions {
49         my ($dbh, $season) = @_;
50
51         my @divisions = ();
52
53         my $q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier WHERE sesong=? ORDER BY divisjon');
54         $q->execute($season);
55
56         while (my $ref = $q->fetchrow_hashref) {
57                 push @divisions, $ref->{'divisjon'};
58         }
59
60         return @divisions;
61 }
62
63 sub get_subdivisions {
64         my ($dbh, $season, $division) = @_;
65
66         my @subdivisions = ();
67
68         my $q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier WHERE sesong=? AND divisjon=? ORDER BY avdeling');
69         $q->execute($season, $division);
70
71         while (my $ref = $q->fetchrow_hashref) {
72                 push @subdivisions, $ref->{'avdeling'};
73         }
74
75         return @subdivisions;
76 }
77
78 sub print_division_selector {
79         my ($dbh, $divisions, $subdivisions, $division, $subdivision) = @_;
80
81         print <<"EOF";
82     <form method="get" action="/">
83 EOF
84
85         my $max_division = $divisions->[(scalar @$divisions) - 1];
86
87         print <<"EOF";
88      <p>Divisjon:
89         <select name="divisjon" onchange="form.submit();">
90 EOF
91
92         for my $d (@$divisions) {
93                 if ($d == $division) {
94                         print "        <option value=\"$d\" selected=\"selected\">$d</option>\n";
95                 } else {
96                         print "        <option value=\"$d\">$d</option>\n";
97                 }
98         }
99
100         print <<"EOF";
101         </select>
102         Avdeling:
103         <select name="avdeling" onchange="form.submit();">
104 EOF
105
106         for my $sd (@$subdivisions) {
107                 if ($sd == $subdivision) {
108                         print "        <option value=\"$sd\" selected=\"selected\">$sd</option>\n";
109                 } else {
110                         print "        <option value=\"$sd\">$sd</option>\n";
111                 }
112         }
113
114         print <<"EOF";
115         </select>
116         <input type="submit" value="Vis" />
117       </p>
118     </form>
119 EOF
120 }
121
122 sub get_players_and_ratings {
123         my ($dbh, $season, $division, $subdivision) = @_;
124
125         my $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=?');
126         $q->execute($season, $division, $subdivision);
127
128         while (my $ref = $q->fetchrow_hashref) {
129                 my $id = $ref->{'id'};
130                 $players{$id} = sanitize(Encode::decode_utf8($ref->{'navn'}));
131                 $ratings{$id} = $ref->{'rating'};
132                 $ratings_stddev{$id} = $ref->{'rating_stddev'};
133         }
134         $q->finish;
135 }
136
137 sub get_matches {
138         my ($dbh, $season, $division, $subdivision) = @_;
139
140         my @matches = ();
141         my $q = $dbh->prepare('
142         SELECT
143           d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
144         FROM fotballresultater r
145           JOIN fotballserier s ON r.serie=s.nr
146           JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
147           JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
148         WHERE
149           sesong=? AND divisjon=? AND avdeling=?
150           AND lagrecno > motstander
151         ');
152         $q->execute($season, $division, $subdivision);
153
154         while (my $ref = $q->fetchrow_hashref) {
155                 push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
156         }
157         $q->finish;
158
159         return @matches;
160 }
161
162 sub get_covariance_matrix {
163         my ($dbh, @players) = @_;
164
165         my $player_sql = '{' . join(',', @players ) . '}';
166         my $q = $dbh->prepare('SELECT * FROM covariance WHERE player1=ANY(?::smallint[]) AND player2=ANY(?::smallint[])', { pg_prepare_now => 0 });
167         $q->execute($player_sql, $player_sql);
168
169         my $cov = {};
170         while (my $ref = $q->fetchrow_hashref) {
171                 $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
172         }
173
174         return $cov;
175 }
176
177 sub write_parms_to_file {
178         my ($aux_parms, $match_stddev, $used_ratings, $used_cov) = @_;
179
180         POSIX::setlocale(&POSIX::LC_ALL, 'C');
181
182         my $tmpnam = POSIX::tmpnam();
183         open MCCALC, ">", $tmpnam
184                 or die "$tmpnam: $!";
185
186         printf MCCALC "%f\n", $match_stddev;
187         printf MCCALC "%d\n", scalar keys %players;
188
189         for my $id (keys %players) {
190                 my $rating = $used_ratings->{$id} // 500.0;
191                 printf MCCALC "%s %f\n", $id, $rating;
192         }
193
194         # covariance matrix
195         for my $id1 (keys %players) {
196                 for my $id2 (keys %players) {
197                         if ($id1 == $id2) {
198                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{-3});
199                         } else {
200                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
201                         }
202                 }
203                 printf MCCALC "\n";
204         }
205
206         for my $match (@matches) {
207                 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
208         }
209         close MCCALC;
210
211         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
212
213         return $tmpnam;
214 }
215
216 my $num_tables = 0;
217
218 sub make_table {
219         my ($aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov, $division, $subdivision) = @_;
220         ++$num_tables;
221
222         print <<"EOF";
223
224     <table class="probmatrix">
225       <tr>
226         <th></th>
227 EOF
228
229         my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, $used_ratings, $used_cov);
230         my %prob = ();
231
232         open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
233                 or die "mccalc: $!";
234         while (<MCCALC>) {
235                 chomp;
236                 my @x = split /\s+/;
237                 my $id = $x[0];
238                 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $aux_parms->{-3});
239                 $prob{$player} = [ @x[1..$#x] ];
240         }
241         close MCCALC;
242         #unlink $tmpnam;
243
244         my $num_games = scalar keys %prob;
245         for my $i (1..$num_games) {
246                 print "        <th>$i.</th>\n";
247         }
248         print "        <th>NEDRYKK</th>\n" unless ($lowest_division);
249         print "      </tr>\n";
250
251         my $pnum = 0;
252         for my $player (sort { $a cmp $b } keys %prob) {
253                 ++$pnum;
254                 print "      <tr>\n";
255                 print "        <th>$player</th>\n";
256
257                 for my $i (1..$num_games) {
258                         my $pn = $prob{$player}->[$i - 1] / $trials;
259
260                         my $r = color(1.0 - $pn / 3);
261                         my $g = color(1.0 - $pn / 3);
262                         my $b = color(1.0);
263
264                         if ($i == 1) {
265                                 ($g, $b) = ($b, $g);
266                         } elsif ($i >= $num_games - 1 && !$lowest_division) {
267                                 ($r, $b) = ($b, $r);
268                         }
269
270                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\"><a class=\"unmarkedlink\" href=\"javascript:var obj=document.getElementById('scenario$num_tables');var parent=obj.parentElement;parent.removeChild(obj);obj=obj.cloneNode();obj.data = '/?divisjon=$division;avdeling=$subdivision;spiller=$pnum;posisjon=$i';parent.appendChild(obj);\">%.1f%%</a></td>\n", $pn * 100.0;
271                 }
272
273                 unless ($lowest_division) {
274                         my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
275
276                         my $r = color(1.0);
277                         my $g = color(1.0 - $pn / 3);
278                         my $b = color(1.0 - $pn / 3);
279                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
280                 }
281                 print "      </tr>\n";
282         }
283
284         print << "EOF";
285     </table>
286     
287     <p class="scenario"><object id="scenario$num_tables" data="" type="text/html"></object></p>
288 EOF
289 }
290
291 sub find_avg_rating {
292         my ($ratings) = shift;
293
294         my $sum_rating = 0.0;
295         for my $r (values %$ratings) {
296                 $sum_rating += $r;
297         }
298         return $sum_rating / scalar keys %ratings;
299 }
300
301 sub get_auxillary_parameters {
302         my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
303         $q->execute;
304
305         my $aux_parms = {};
306         while (my $ref = $q->fetchrow_hashref) {
307                 $aux_parms->{$ref->{'id'}} = $ref->{'rating'};
308         }
309         return $aux_parms;
310 }
311
312 sub print_header {
313         my ($cgi, $title) = @_;
314         print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
315         print <<"EOF";
316 <?xml version="1.0" encoding="UTF-8" ?>
317 <!DOCTYPE
318   html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
319   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
320 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
321   <head>
322     <title>$title</title>
323     <link rel="stylesheet" href="/style" type="text/css" />
324   </head>
325   <body>
326 EOF
327 }
328
329 sub print_footer {
330         print <<"EOF";
331   </body>
332 </html>
333 EOF
334 }
335
336 my $aux_parms = get_auxillary_parameters($dbh);
337 my $match_stddev = $aux_parms->{-2} * sqrt(2.0);
338
339 my $division = $cgi->param('divisjon') // -1;
340 my $subdivision = $cgi->param('avdeling') // -1;
341 my $match_player = $cgi->param('spiller');
342 my $match_position = $cgi->param('posisjon');
343
344 my $season = get_max_season($dbh);
345 my @divisions = get_divisions($dbh, $season);
346 $division = 1 if (!grep { $_ == $division } @divisions);
347 my @subdivisions = get_subdivisions($dbh, $season, $division);
348 $subdivision = 1 if (!grep { $_ == $subdivision } @subdivisions);
349
350 get_players_and_ratings($dbh, $season, $division, $subdivision);
351 @matches = get_matches($dbh, $season, $division, $subdivision);
352 my $cov = get_covariance_matrix($dbh, keys %players);
353
354 print_header($cgi, 'WLoH-plasseringsannsynlighetsberegning');
355
356 if (defined($match_player) && defined($match_position)) {
357         my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, \%ratings, $cov);
358
359         --$match_player;
360         --$match_position;
361
362         my @scenario = ();
363         open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
364                 or die "mccalc: $!";
365         while (<MCCALC>) {
366                 /(\d+) (\d+) (-?\d+)/ or next;
367                 chomp;
368                 push @scenario, [ $1, $2, $3 ];
369         }
370         close MCCALC;
371         #unlink $tmpnam;
372
373         if (scalar @scenario == 0) {
374                 # FIXME: distinguish between "all played" and "none found"
375                 print "    <p>Fant ingen m&aring;te dette kunne skje p&aring.</p>\n";
376         } else {
377                 print "    <ul>\n";
378                 for my $m (@scenario) {
379                         printf "    <li>%s &ndash; %s: %+d</li>\n", $players{$m->[0]}, $players{$m->[1]}, $m->[2];
380                 }
381                 print "    </ul>\n";
382         }
383 } else {
384         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
385         printf <<"EOF", $match_stddev;
386     <h1>WLoH-plasseringsannsynlighetsberegning</h1>
387
388     <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
389       <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
390
391     <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
392       den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
393       %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
394       Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.
395       For scenarioeksempel, klikk i en rute.</p>
396
397     <p>Spillerne er sortert etter nick.</p>
398 EOF
399
400         print_division_selector($dbh, \@divisions, \@subdivisions, $division, $subdivision);
401
402         my $max_division = $divisions[$#divisions];
403         my $lowest_division = ($division == $max_division);
404         make_table($aux_parms, $match_stddev, $lowest_division, {}, {}, $division, $subdivision);
405
406         print <<"EOF";
407     <p style="clear: both; padding-top: 1em;">Under er en variant som tar relativ spillestyrke med i beregningen;
408       se <a href="/rating">ratingsiden</a>.</p>
409 EOF
410
411         make_table($aux_parms, $match_stddev, $lowest_division, \%ratings, $cov, $division, $subdivision);
412
413         my $avg_rating = find_avg_rating(\%ratings);
414         printf "    <p style=\"clear: both; padding-top: 1em;\">Gjennomsnittlig rating i denne avdelingen er <strong>%.1f</strong>.</p>\n", $avg_rating;
415
416         wloh_common::output_last_sync($dbh);
417 }
418
419 print_footer();