]> git.sesse.net Git - wloh/blob - www/index.pl
fb4d8ce87034cfd2107729f76ef94c8720ca4c10
[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, 'nb_NO.UTF-8');
181
182         my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
183
184         POSIX::setlocale(&POSIX::LC_ALL, 'C');
185
186         my $tmpnam = POSIX::tmpnam();
187         open MCCALC, ">", $tmpnam
188                 or die "$tmpnam: $!";
189
190         printf MCCALC "%f\n", $match_stddev;
191         printf MCCALC "%d\n", scalar keys %players;
192
193         for my $id (@sorted_players) {
194                 my $rating = $used_ratings->{$id} // 500.0;
195                 printf MCCALC "%s %f\n", $id, $rating;
196         }
197
198         # covariance matrix
199         for my $id1 (keys %players) {
200                 for my $id2 (keys %players) {
201                         if ($id1 == $id2) {
202                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{-3});
203                         } else {
204                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
205                         }
206                 }
207                 printf MCCALC "\n";
208         }
209
210         for my $match (@matches) {
211                 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
212         }
213         close MCCALC;
214
215         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
216
217         return $tmpnam;
218 }
219
220 my $num_tables = 0;
221
222 sub make_table {
223         my ($aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov, $division, $subdivision) = @_;
224         ++$num_tables;
225
226         print <<"EOF";
227     <script type="text/javascript">
228     <!--
229 function showScenario(element_id, url) {
230     var obj = document.getElementById(element_id);
231     var parent = obj.parentElement;
232     parent.removeChild(obj);
233     obj = obj.cloneNode(false);
234     obj.data = url;
235     parent.appendChild(obj);
236 }
237     //-->
238     </script>
239     <table class="probmatrix">
240       <tr>
241         <th></th>
242 EOF
243
244         my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, $used_ratings, $used_cov);
245         my %prob = ();
246
247         open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
248                 or die "mccalc: $!";
249         while (<MCCALC>) {
250                 chomp;
251                 my @x = split /\s+/;
252                 my $id = $x[0];
253                 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $aux_parms->{-3});
254                 $prob{$player} = [ @x[1..$#x] ];
255         }
256         close MCCALC;
257         #unlink $tmpnam;
258
259         my $num_games = scalar keys %prob;
260         for my $i (1..$num_games) {
261                 print "        <th>$i.</th>\n";
262         }
263         print "        <th>NEDRYKK</th>\n" unless ($lowest_division);
264         print "      </tr>\n";
265
266         my $pnum = 0;
267         for my $player (sort { $a cmp $b } keys %prob) {
268                 ++$pnum;
269                 print "      <tr>\n";
270                 print "        <th>$player</th>\n";
271
272                 for my $i (1..$num_games) {
273                         my $pn = $prob{$player}->[$i - 1] / $trials;
274
275                         my $r = color(1.0 - $pn / 3);
276                         my $g = color(1.0 - $pn / 3);
277                         my $b = color(1.0);
278
279                         if ($i == 1) {
280                                 ($g, $b) = ($b, $g);
281                         } elsif ($i >= $num_games - 1 && !$lowest_division) {
282                                 ($r, $b) = ($b, $r);
283                         }
284
285                         my $num_total_games = ($num_games * ($num_games - 1)) / 2;
286                         if (scalar @matches == $num_total_games || $prob{$player}->[$i - 1] == $trials) {
287                                 printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
288                         } else {
289                                 printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\"><a class=\"unmarkedlink\" href=\"javascript:showScenario('scenario$num_tables', '/?divisjon=$division;avdeling=$subdivision;spiller=$pnum;posisjon=$i');\">%.1f%%</a></td>\n", $pn * 100.0;
290                         }
291                 }
292
293                 unless ($lowest_division) {
294                         my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
295
296                         my $r = color(1.0);
297                         my $g = color(1.0 - $pn / 3);
298                         my $b = color(1.0 - $pn / 3);
299                         printf "        <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
300                 }
301                 print "      </tr>\n";
302         }
303
304         print << "EOF";
305     </table>
306     
307     <p class="scenario"><object id="scenario$num_tables" data="" type="text/html"></object></p>
308 EOF
309 }
310
311 sub find_avg_rating {
312         my ($ratings) = shift;
313
314         my $sum_rating = 0.0;
315         for my $r (values %$ratings) {
316                 $sum_rating += $r;
317         }
318         return $sum_rating / scalar keys %ratings;
319 }
320
321 sub get_auxillary_parameters {
322         my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
323         $q->execute;
324
325         my $aux_parms = {};
326         while (my $ref = $q->fetchrow_hashref) {
327                 $aux_parms->{$ref->{'id'}} = $ref->{'rating'};
328         }
329         return $aux_parms;
330 }
331
332 sub print_header {
333         my ($cgi, $title) = @_;
334         print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
335         print <<"EOF";
336 <?xml version="1.0" encoding="UTF-8" ?>
337 <!DOCTYPE
338   html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
339   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
340 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
341   <head>
342     <title>$title</title>
343     <link rel="stylesheet" href="/style" type="text/css" />
344   </head>
345   <body>
346 EOF
347 }
348
349 sub print_footer {
350         print <<"EOF";
351   </body>
352 </html>
353 EOF
354 }
355
356 my $aux_parms = get_auxillary_parameters($dbh);
357 my $match_stddev = $aux_parms->{-2} * sqrt(2.0);
358
359 my $division = $cgi->param('divisjon') // -1;
360 my $subdivision = $cgi->param('avdeling') // -1;
361 my $match_player = $cgi->param('spiller');
362 my $match_position = $cgi->param('posisjon');
363
364 my $season = get_max_season($dbh);
365 my @divisions = get_divisions($dbh, $season);
366 $division = 1 if (!grep { $_ == $division } @divisions);
367 my @subdivisions = get_subdivisions($dbh, $season, $division);
368 $subdivision = 1 if (!grep { $_ == $subdivision } @subdivisions);
369
370 get_players_and_ratings($dbh, $season, $division, $subdivision);
371 @matches = get_matches($dbh, $season, $division, $subdivision);
372 my $cov = get_covariance_matrix($dbh, keys %players);
373
374 print_header($cgi, 'WLoH-plasseringsannsynlighetsberegning');
375
376 if (defined($match_player) && defined($match_position)) {
377         my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, \%ratings, $cov);
378
379         --$match_player;
380         --$match_position;
381
382         my @scenario = ();
383         open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
384                 or die "mccalc: $!";
385         while (<MCCALC>) {
386                 /(\d+) (\d+) (-?\d+)/ or next;
387                 chomp;
388                 push @scenario, [ $1, $2, $3 ];
389         }
390         close MCCALC;
391         #unlink $tmpnam;
392
393         my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
394         my $player_name = $players{$sorted_players[$match_player]};
395
396         if (scalar @scenario == 0) {
397                 printf "    <p>Fant ingen m&aring;te <strong>%s</strong> kan ende p&aring; <strong>%d.</strong> plass p&aring;.</p>\n",
398                         $player_name, ($match_position + 1);
399         } else {
400                 printf "    <p>Scenario der <strong>%s</strong> ender p&aring; <strong>%d.</strong> plass:</p>\n",
401                         $player_name, ($match_position + 1);
402                 print "    <ul>\n";
403                 for my $m (@scenario) {
404                         printf "    <li>%s &ndash; %s: %+d</li>\n", $players{$m->[0]}, $players{$m->[1]}, $m->[2];
405                 }
406                 print "    </ul>\n";
407         }
408 } else {
409         POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
410         printf <<"EOF", $match_stddev;
411     <h1>WLoH-plasseringsannsynlighetsberegning</h1>
412
413     <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
414       <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
415
416     <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
417       den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
418       %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
419       Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.
420       For scenarioeksempel, klikk i en rute.</p>
421
422     <p>Spillerne er sortert etter nick.</p>
423 EOF
424
425         print_division_selector($dbh, \@divisions, \@subdivisions, $division, $subdivision);
426
427         my $max_division = $divisions[$#divisions];
428         my $lowest_division = ($division == $max_division);
429         make_table($aux_parms, $match_stddev, $lowest_division, {}, {}, $division, $subdivision);
430
431         print <<"EOF";
432     <p style="clear: both; padding-top: 1em;">Under er en variant som tar relativ spillestyrke med i beregningen;
433       se <a href="/rating">ratingsiden</a>.</p>
434 EOF
435
436         make_table($aux_parms, $match_stddev, $lowest_division, \%ratings, $cov, $division, $subdivision);
437
438         my $avg_rating = find_avg_rating(\%ratings);
439         printf "    <p style=\"clear: both; padding-top: 1em;\">Gjennomsnittlig rating i denne avdelingen er <strong>%.1f</strong>.</p>\n", $avg_rating;
440
441         wloh_common::output_last_sync($dbh);
442 }
443
444 print_footer();