]> git.sesse.net Git - wloh/blob - www/index.pl
4fef4a7e4e319abe764e9edf78b844412cbb753d
[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 use lib qw(../include);
15 require 'config.pm';
16 require 'common.pm';
17
18 my $cgi = CGI->new;
19
20 my $dbh = DBI->connect($config::local_connstr, $config::local_username, $config::local_password)
21         or die "connect: " . $DBI::errstr;
22 $dbh->{AutoCommit} = 0;
23 $dbh->{RaiseError} = 1;
24
25 my $trials = 25_000;
26
27 binmode STDOUT, ':utf8';
28
29 my %players = ();
30 my %ratings = ();
31 my %ratings_stddev = ();
32 my @matches = ();
33
34 sub color {
35         my $x = shift;
36         return int(255.0 * ($x ** (1.80)));
37 }
38
39 sub get_divisions {
40         my ($dbh, $locale, $season) = @_;
41
42         my @divisions = ();
43
44         my $q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier se JOIN fotballspraak sp ON se.spraak=sp.id WHERE kultur=? AND sesong=? ORDER BY divisjon');
45         $q->execute($locale, $season);
46
47         while (my $ref = $q->fetchrow_hashref) {
48                 push @divisions, $ref->{'divisjon'};
49         }
50
51         return @divisions;
52 }
53
54 sub get_subdivisions {
55         my ($dbh, $locale, $season, $division) = @_;
56
57         my @subdivisions = ();
58
59         my $q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier se JOIN fotballspraak sp ON se.spraak=sp.id WHERE kultur=? AND sesong=? AND divisjon=? ORDER BY avdeling');
60         $q->execute($locale, $season, $division);
61
62         while (my $ref = $q->fetchrow_hashref) {
63                 push @subdivisions, $ref->{'avdeling'};
64         }
65
66         return @subdivisions;
67 }
68
69 sub get_division_selector {
70         my ($divisions, $division) = @_;
71
72         my @ret = ();
73         for my $d (@$divisions) {
74                 my $parms = {
75                         'option' => $d,
76                         'option/value' => $d,
77                 };
78                 $parms->{'option/selected'} = 'selected' if ($d == $division);
79                 push @ret, $parms;
80         }
81         return \@ret;
82 }
83
84 sub get_players_and_ratings {
85         my ($dbh, $locale, $season, $division, $subdivision) = @_;
86
87         my $q = $dbh->prepare('SELECT fotballdeltagere.id,fotballdeltagere.navn,rating,rating_stddev FROM fotballdeltagere JOIN fotballserier ON fotballdeltagere.serie=fotballserier.nr NATURAL JOIN spiller_kultur LEFT JOIN ratings ON fotballdeltagere.id=ratings.id WHERE kultur=? AND sesong=? AND divisjon=? AND avdeling=?');
88         $q->execute($locale, $season, $division, $subdivision);
89
90         while (my $ref = $q->fetchrow_hashref) {
91                 my $id = $ref->{'id'};
92                 $players{$id} = Encode::decode_utf8($ref->{'navn'});
93                 $ratings{$id} = $ref->{'rating'};
94                 $ratings_stddev{$id} = $ref->{'rating_stddev'};
95         }
96         $q->finish;
97 }
98
99 sub get_matches {
100         my ($dbh, $locale, $season, $division, $subdivision) = @_;
101
102         my @matches = ();
103         my $q = $dbh->prepare('
104         SELECT
105           d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
106         FROM ( SELECT * FROM fotballresultater UNION ALL SELECT * FROM fotballresultater_2123 ) r
107           JOIN fotballserier s ON r.serie=s.nr
108           JOIN fotballspraak sp ON s.spraak=sp.id
109           JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
110           JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
111         WHERE
112           kultur=? AND sesong=? AND divisjon=? AND avdeling=?
113           AND lagrecno > motstander
114         ');
115         $q->execute($locale, $season, $division, $subdivision);
116
117         while (my $ref = $q->fetchrow_hashref) {
118                 push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
119         }
120         $q->finish;
121
122         return @matches;
123 }
124
125 sub get_covariance_matrix {
126         my ($dbh, @players) = @_;
127
128         my $player_sql = '{' . join(',', @players ) . '}';
129         my $q = $dbh->prepare('SELECT * FROM covariance WHERE player1=ANY(?::smallint[]) AND player2=ANY(?::smallint[])', { pg_prepare_now => 0 });
130         $q->execute($player_sql, $player_sql);
131
132         my $cov = {};
133         while (my $ref = $q->fetchrow_hashref) {
134                 $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
135         }
136
137         return $cov;
138 }
139
140 sub write_parms_to_file {
141         my ($locale, $aux_parms, $match_stddev, $used_ratings, $used_cov) = @_;
142
143         wloh_common::set_locale($locale);
144
145         my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
146
147         POSIX::setlocale(&POSIX::LC_ALL, 'C');
148
149         my $tmpnam = POSIX::tmpnam();
150         open MCCALC, ">", $tmpnam
151                 or die "$tmpnam: $!";
152
153         printf MCCALC "%f\n", $match_stddev;
154         printf MCCALC "%d\n", scalar keys %players;
155
156         for my $id (@sorted_players) {
157                 my $rating = $used_ratings->{$id} // 500.0;
158                 printf MCCALC "%s %f\n", $id, $rating;
159         }
160
161         # covariance matrix
162         for my $id1 (keys %players) {
163                 for my $id2 (keys %players) {
164                         if ($id1 == $id2) {
165                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{'rating_prior_stddev'});
166                         } else {
167                                 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
168                         }
169                 }
170                 printf MCCALC "\n";
171         }
172
173         for my $match (@matches) {
174                 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
175         }
176         close MCCALC;
177
178         wloh_common::set_locale($locale);
179
180         return $tmpnam;
181 }
182
183 sub make_table {
184         my ($locale, $aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov, $division, $subdivision, $table_id) = @_;
185
186         my $tmpnam = write_parms_to_file($locale, $aux_parms, $match_stddev, $used_ratings, $used_cov);
187         my %prob = ();
188
189         open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
190                 or die "mccalc: $!";
191         while (<MCCALC>) {
192                 chomp;
193                 my @x = split /\s+/;
194                 my $id = $x[0];
195                 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $aux_parms->{'rating_prior_stddev'});
196                 $prob{$player} = [ @x[1..$#x] ];
197         }
198         close MCCALC;
199         unlink $tmpnam;
200
201         my $num_games = scalar keys %prob;
202
203         # Make list of ranks.
204         my @ranks = ();
205         for my $i (1..$num_games) {
206                 push @ranks, { 'th' => "$i." };
207         }
208         push @ranks, { 'th' => 'NEDRYKK' } unless ($lowest_division);
209
210         my @players = ();
211
212         my $pnum = 0;
213         for my $player (sort { $a cmp $b } keys %prob) {
214                 ++$pnum;
215
216                 my @player_ranks = ();
217
218                 for my $i (1..$num_games) {
219                         my $pn = $prob{$player}->[$i - 1] / $trials;
220
221                         my $r = color(1.0 - $pn / 3);
222                         my $g = color(1.0 - $pn / 3);
223                         my $b = color(1.0);
224
225                         if ($i == 1) {
226                                 ($g, $b) = ($b, $g);
227                         } elsif ($i >= $num_games - 1 && !$lowest_division) {
228                                 ($r, $b) = ($b, $r);
229                         }
230
231                         my $num_total_games = ($num_games * ($num_games - 1)) / 2;
232                         if (scalar @matches == $num_total_games || $prob{$player}->[$i - 1] == $trials) {
233                                 push @player_ranks, {
234                                         'td/style' => "background-color: rgb($r, $g, $b)",
235                                         'td' => sprintf("%.1f%%", $pn * 100.0),
236                                         'link' => ''
237                                 };
238                         } else {
239                                 push @player_ranks, {
240                                         'td/style' => "background-color: rgb($r, $g, $b)",
241                                         'a' => sprintf("%.1f%%", $pn * 100.0),
242                                         'a/href' => "javascript:showScenario('$table_id', '/$locale/?divisjon=$division;avdeling=$subdivision;spiller=$pnum;posisjon=$i')"
243                                 };
244                         }
245                 }
246
247                 unless ($lowest_division) {
248                         my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
249
250                         my $r = color(1.0);
251                         my $g = color(1.0 - $pn / 3);
252                         my $b = color(1.0 - $pn / 3);
253                         push @player_ranks, {
254                                 'td/style' => "background-color: rgb($r, $g, $b)",
255                                 'td' => sprintf("%.1f%%", $pn * 100.0),
256                                 'link' => ''
257                         };
258                 }
259                 push @players, {
260                         'player' => $player,
261                         'player-ranks' => \@player_ranks
262                 };
263         }
264
265         return {
266                 'ranks' => \@ranks,
267                 'tbody' => \@players,
268         };
269 }
270
271 sub make_cov_table {
272         my ($cov) = @_;
273         my @players = (sort { $players{$a} cmp $players{$b} } keys %players);
274
275         my @player_list = ();
276         for my $player (@players) {
277                 push @player_list, { 'th' => $players{$player} };
278         }
279
280         my @player_rows = ();
281         for my $player (@players) {
282                 my @elements = ();
283                 for my $player2 (@players) {
284                         my $c = sprintf("%.2f", $cov->{$player}{$player2});
285                         push @elements, { 'td' => $c };
286                 }
287                 push @player_rows, {
288                         '#player' => $players{$player},
289                         'elements' => \@elements
290                 };
291         }
292
293         return {
294                 'player-list' => \@player_list,
295                 'tbody' => \@player_rows
296         };
297 }
298
299 sub find_avg_rating {
300         my ($ratings) = shift;
301
302         my $sum_rating = 0.0;
303         for my $r (values %$ratings) {
304                 $sum_rating += ($r // 500.0);
305         }
306         return $sum_rating / scalar keys %$ratings;
307 }
308
309 sub print_header {
310         my ($cgi, $title) = @_;
311         print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
312         print <<"EOF";
313 <?xml version="1.0" encoding="UTF-8" ?>
314 <!DOCTYPE
315   html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
316   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
317 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
318   <head>
319     <title>$title</title>
320     <link rel="stylesheet" href="style" type="text/css" />
321   </head>
322   <body>
323 EOF
324 }
325
326 sub print_footer {
327         print <<"EOF";
328   </body>
329 </html>
330 EOF
331 }
332
333 my $locale = wloh_common::get_locale($cgi);
334 my $aux_parms = wloh_common::get_auxillary_parameters($dbh, $locale);
335 my $match_stddev = $aux_parms->{'score_stddev'} * sqrt(2.0);
336
337 my $division = $cgi->param('divisjon') // -1;
338 my $subdivision = $cgi->param('avdeling') // -1;
339 my $match_player = $cgi->param('spiller');
340 my $match_position = $cgi->param('posisjon');
341
342 my $season = wloh_common::get_max_season($dbh, $locale);
343 die "Nonexistent locale!" if (!defined($season));
344
345 my @divisions = get_divisions($dbh, $locale, $season);
346 $division = $divisions[0] if (!grep { $_ == $division } @divisions);
347 my @subdivisions = get_subdivisions($dbh, $locale, $season, $division);
348 $subdivision = $subdivisions[0] if (!grep { $_ == $subdivision } @subdivisions);
349
350 get_players_and_ratings($dbh, $locale, $season, $division, $subdivision);
351 @matches = get_matches($dbh, $locale, $season, $division, $subdivision);
352 my $cov = get_covariance_matrix($dbh, keys %players);
353
354 if (defined($match_player) && defined($match_position)) {
355         my $tmpnam = write_parms_to_file($locale, $aux_parms, $match_stddev, \%ratings, $cov);
356
357         --$match_player;
358         --$match_position;
359
360         my @scenario = ();
361         open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
362                 or die "mccalc: $!";
363         while (<MCCALC>) {
364                 /(\d+) (\d+) (-?\d+)/ or next;
365                 chomp;
366                 push @scenario, {
367                         'player-1' => $players{$1},
368                         'player-2' => $players{$2},
369                         'result' => sprintf("%+d", $3),
370                 };
371         }
372         close MCCALC;
373         unlink $tmpnam;
374
375         my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
376         my $player_name = $players{$sorted_players[$match_player]};
377
378         if (scalar @scenario == 0) {
379                 print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
380                 wloh_common::process_template('scenario-not-found', $locale, {
381                         '#nick' => $player_name,
382                         '#rank' => sprintf("%d.", $match_position + 1)
383                 });
384         } else {
385                 print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
386                 wloh_common::process_template('scenario', $locale, {
387                         '#nick' => $player_name,
388                         '#rank' => sprintf("%d.", $match_position + 1),
389                         '#results' => \@scenario
390                 });
391         }
392 } else {
393         wloh_common::set_locale($locale);
394
395         my $max_division = $divisions[$#divisions];
396         my $lowest_division = ($division == $max_division);
397         my $basic_table = make_table($locale, $aux_parms, $match_stddev, $lowest_division, {}, {}, $division, $subdivision, 'scenario1');
398         my $adjusted_table = make_table($locale, $aux_parms, $match_stddev, $lowest_division, \%ratings, $cov, $division, $subdivision, 'scenario2');
399         my $cov_table = (defined($cgi->param('showcov'))) ? make_cov_table($cov) : '';
400
401         my $avg_rating = find_avg_rating(\%ratings);
402
403         print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
404         wloh_common::process_template('index', $locale, {
405                 '#navbar' => wloh_common::get_navbar($cgi, $dbh, $locale),
406                 '#division-selector/action' => "/$locale/",
407                 '#division' => get_division_selector(\@divisions, $division),
408                 '#subdivision' => get_division_selector(\@subdivisions, $subdivision),
409                 '#basic-probabilities' => $basic_table,
410                 '#adjusted-probabilities' => $adjusted_table,
411                 'cov-table' => $cov_table,
412                 'match-stddev' => sprintf("%.1f", $match_stddev),
413                 '#average-rating' => sprintf("%.1f", $avg_rating),
414                 'last-sync' => wloh_common::get_last_sync($dbh),
415         });
416 }
417