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