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