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