6 use CGI::Carp qw( fatalsToBrowser );
14 require '../config.pm';
15 require '../common.pm';
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;
26 binmode STDOUT, ':utf8';
30 my %ratings_stddev = ();
34 return HTML::Entities::encode_entities(shift);
39 return int(255.0 * ($x ** (1.80)));
44 my $ref = $dbh->selectrow_hashref('SELECT MAX(sesong) AS max_sesong FROM fotballserier');
45 return $ref->{'max_sesong'};
49 my ($dbh, $season) = @_;
53 my $q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier WHERE sesong=? ORDER BY divisjon');
56 while (my $ref = $q->fetchrow_hashref) {
57 push @divisions, $ref->{'divisjon'};
63 sub get_subdivisions {
64 my ($dbh, $season, $division) = @_;
66 my @subdivisions = ();
68 my $q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier WHERE sesong=? AND divisjon=? ORDER BY avdeling');
69 $q->execute($season, $division);
71 while (my $ref = $q->fetchrow_hashref) {
72 push @subdivisions, $ref->{'avdeling'};
78 sub print_division_selector {
79 my ($dbh, $divisions, $subdivisions, $division, $subdivision) = @_;
82 <form method="get" action="/">
85 my $max_division = $divisions->[(scalar @$divisions) - 1];
89 <select name="divisjon" onchange="form.submit();">
92 for my $d (@$divisions) {
93 if ($d == $division) {
94 print " <option value=\"$d\" selected=\"selected\">$d</option>\n";
96 print " <option value=\"$d\">$d</option>\n";
103 <select name="avdeling" onchange="form.submit();">
106 for my $sd (@$subdivisions) {
107 if ($sd == $subdivision) {
108 print " <option value=\"$sd\" selected=\"selected\">$sd</option>\n";
110 print " <option value=\"$sd\">$sd</option>\n";
116 <input type="submit" value="Vis" />
122 sub get_players_and_ratings {
123 my ($dbh, $season, $division, $subdivision) = @_;
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);
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'};
138 my ($dbh, $season, $division, $subdivision) = @_;
141 my $q = $dbh->prepare('
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
149 sesong=? AND divisjon=? AND avdeling=?
150 AND lagrecno > motstander
152 $q->execute($season, $division, $subdivision);
154 while (my $ref = $q->fetchrow_hashref) {
155 push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
162 sub get_covariance_matrix {
163 my ($dbh, @players) = @_;
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);
170 while (my $ref = $q->fetchrow_hashref) {
171 $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
177 sub write_parms_to_file {
178 my ($aux_parms, $match_stddev, $used_ratings, $used_cov) = @_;
180 POSIX::setlocale(&POSIX::LC_ALL, 'C');
182 my $tmpnam = POSIX::tmpnam();
183 open MCCALC, ">", $tmpnam
184 or die "$tmpnam: $!";
186 printf MCCALC "%f\n", $match_stddev;
187 printf MCCALC "%d\n", scalar keys %players;
189 for my $id (keys %players) {
190 my $rating = $used_ratings->{$id} // 500.0;
191 printf MCCALC "%s %f\n", $id, $rating;
195 for my $id1 (keys %players) {
196 for my $id2 (keys %players) {
198 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{-3});
200 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
206 for my $match (@matches) {
207 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
211 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
217 my ($aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov) = @_;
226 my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, $used_ratings, $used_cov);
229 open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
235 my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $aux_parms->{-3});
236 $prob{$player} = [ @x[1..$#x] ];
241 my $num_games = scalar keys %prob;
242 for my $i (1..$num_games) {
243 print " <th>$i.</th>\n";
245 print " <th>NEDRYKK</th>\n" unless ($lowest_division);
248 for my $player (sort { $a cmp $b } keys %prob) {
250 print " <th>$player</th>\n";
252 for my $i (1..$num_games) {
253 my $pn = $prob{$player}->[$i - 1] / $trials;
255 my $r = color(1.0 - $pn / 3);
256 my $g = color(1.0 - $pn / 3);
261 } elsif ($i >= $num_games - 1 && !$lowest_division) {
265 printf " <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
268 unless ($lowest_division) {
269 my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
272 my $g = color(1.0 - $pn / 3);
273 my $b = color(1.0 - $pn / 3);
274 printf " <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
284 sub find_avg_rating {
285 my ($ratings) = shift;
287 my $sum_rating = 0.0;
288 for my $r (values %$ratings) {
291 return $sum_rating / scalar keys %ratings;
294 sub get_auxillary_parameters {
295 my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
299 while (my $ref = $q->fetchrow_hashref) {
300 $aux_parms->{$ref->{'id'}} = $ref->{'rating'};
306 my ($cgi, $title) = @_;
307 print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
309 <?xml version="1.0" encoding="UTF-8" ?>
311 html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
312 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
313 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
315 <title>$title</title>
316 <link rel="stylesheet" href="/style" type="text/css" />
329 my $aux_parms = get_auxillary_parameters($dbh);
330 my $match_stddev = $aux_parms->{-2} * sqrt(2.0);
332 my $division = $cgi->param('divisjon') // -1;
333 my $subdivision = $cgi->param('avdeling') // -1;
334 my $match_player = $cgi->param('spiller');
335 my $match_position = $cgi->param('posisjon');
337 my $season = get_max_season($dbh);
338 my @divisions = get_divisions($dbh, $season);
339 $division = 1 if (!grep { $_ == $division } @divisions);
340 my @subdivisions = get_subdivisions($dbh, $season, $division);
341 $subdivision = 1 if (!grep { $_ == $subdivision } @subdivisions);
343 get_players_and_ratings($dbh, $season, $division, $subdivision);
344 @matches = get_matches($dbh, $season, $division, $subdivision);
345 my $cov = get_covariance_matrix($dbh, keys %players);
347 print_header($cgi, 'WLoH-plasseringsannsynlighetsberegning');
349 if (defined($match_player) && defined($match_position)) {
350 my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, \%ratings, $cov);
356 open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
359 /(\d+) (\d+) (-?\d+)/ or next;
361 push @scenario, [ $1, $2, $3 ];
366 if (scalar @scenario == 0) {
367 # FIXME: distinguish between "all played" and "none found"
368 print " <p>Fant ingen måte dette kunne skje på.</p>\n";
371 for my $m (@scenario) {
372 printf " <li>%s – %s: %+d</li>\n", $players{$m->[0]}, $players{$m->[1]}, $m->[2];
377 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
378 printf <<"EOF", $match_stddev;
379 <h1>WLoH-plasseringsannsynlighetsberegning</h1>
381 <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
382 <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
384 <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
385 den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
386 %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
387 Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.</p>
389 <p>Spillerne er sortert etter nick.</p>
392 print_division_selector($dbh, \@divisions, \@subdivisions, $division, $subdivision);
394 my $max_division = $divisions[$#divisions];
395 my $lowest_division = ($division == $max_division);
396 make_table($aux_parms, $match_stddev, $lowest_division, {}, {});
399 <p>Under er en variant som tar relativ spillestyrke med i beregningen;
400 se <a href="/rating">ratingsiden</a>.</p>
403 make_table($aux_parms, $match_stddev, $lowest_division, \%ratings, $cov);
405 my $avg_rating = find_avg_rating(\%ratings);
406 printf " <p>Gjennomsnittlig rating i denne avdelingen er <strong>%.1f</strong>.</p>\n", $avg_rating;
408 wloh_common::output_last_sync($dbh);