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, 'nb_NO.UTF-8');
182 my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
184 POSIX::setlocale(&POSIX::LC_ALL, 'C');
186 my $tmpnam = POSIX::tmpnam();
187 open MCCALC, ">", $tmpnam
188 or die "$tmpnam: $!";
190 printf MCCALC "%f\n", $match_stddev;
191 printf MCCALC "%d\n", scalar keys %players;
193 for my $id (@sorted_players) {
194 my $rating = $used_ratings->{$id} // 500.0;
195 printf MCCALC "%s %f\n", $id, $rating;
199 for my $id1 (keys %players) {
200 for my $id2 (keys %players) {
202 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{-3});
204 printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
210 for my $match (@matches) {
211 printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
215 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
223 my ($aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov, $division, $subdivision) = @_;
228 <table class="probmatrix">
233 my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, $used_ratings, $used_cov);
236 open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
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] ];
248 my $num_games = scalar keys %prob;
249 for my $i (1..$num_games) {
250 print " <th>$i.</th>\n";
252 print " <th>NEDRYKK</th>\n" unless ($lowest_division);
256 for my $player (sort { $a cmp $b } keys %prob) {
259 print " <th>$player</th>\n";
261 for my $i (1..$num_games) {
262 my $pn = $prob{$player}->[$i - 1] / $trials;
264 my $r = color(1.0 - $pn / 3);
265 my $g = color(1.0 - $pn / 3);
270 } elsif ($i >= $num_games - 1 && !$lowest_division) {
274 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;
277 unless ($lowest_division) {
278 my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;
281 my $g = color(1.0 - $pn / 3);
282 my $b = color(1.0 - $pn / 3);
283 printf " <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
291 <p class="scenario"><object id="scenario$num_tables" data="" type="text/html"></object></p>
295 sub find_avg_rating {
296 my ($ratings) = shift;
298 my $sum_rating = 0.0;
299 for my $r (values %$ratings) {
302 return $sum_rating / scalar keys %ratings;
305 sub get_auxillary_parameters {
306 my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
310 while (my $ref = $q->fetchrow_hashref) {
311 $aux_parms->{$ref->{'id'}} = $ref->{'rating'};
317 my ($cgi, $title) = @_;
318 print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
320 <?xml version="1.0" encoding="UTF-8" ?>
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">
326 <title>$title</title>
327 <link rel="stylesheet" href="/style" type="text/css" />
340 my $aux_parms = get_auxillary_parameters($dbh);
341 my $match_stddev = $aux_parms->{-2} * sqrt(2.0);
343 my $division = $cgi->param('divisjon') // -1;
344 my $subdivision = $cgi->param('avdeling') // -1;
345 my $match_player = $cgi->param('spiller');
346 my $match_position = $cgi->param('posisjon');
348 my $season = get_max_season($dbh);
349 my @divisions = get_divisions($dbh, $season);
350 $division = 1 if (!grep { $_ == $division } @divisions);
351 my @subdivisions = get_subdivisions($dbh, $season, $division);
352 $subdivision = 1 if (!grep { $_ == $subdivision } @subdivisions);
354 get_players_and_ratings($dbh, $season, $division, $subdivision);
355 @matches = get_matches($dbh, $season, $division, $subdivision);
356 my $cov = get_covariance_matrix($dbh, keys %players);
358 print_header($cgi, 'WLoH-plasseringsannsynlighetsberegning');
360 if (defined($match_player) && defined($match_position)) {
361 my $tmpnam = write_parms_to_file($aux_parms, $match_stddev, \%ratings, $cov);
367 open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
370 /(\d+) (\d+) (-?\d+)/ or next;
372 push @scenario, [ $1, $2, $3 ];
377 my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
378 my $player_name = $players{$sorted_players[$match_player]};
380 if (scalar @scenario == 0) {
381 # FIXME: distinguish between "all played" and "none found"
382 printf " <p>Fant ingen måte <strong>%s</strong> kan ende på <strong>%d.</strong> plass på.</p>\n",
383 $player_name, ($match_position + 1);
385 printf " <p>Scenario der <strong>%s</strong> ender på <strong>%d.</strong> plass:</p>\n",
386 $player_name, ($match_position + 1);
388 for my $m (@scenario) {
389 printf " <li>%s – %s: %+d</li>\n", $players{$m->[0]}, $players{$m->[1]}, $m->[2];
394 POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
395 printf <<"EOF", $match_stddev;
396 <h1>WLoH-plasseringsannsynlighetsberegning</h1>
398 <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
399 <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
401 <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
402 den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
403 %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
404 Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.
405 For scenarioeksempel, klikk i en rute.</p>
407 <p>Spillerne er sortert etter nick.</p>
410 print_division_selector($dbh, \@divisions, \@subdivisions, $division, $subdivision);
412 my $max_division = $divisions[$#divisions];
413 my $lowest_division = ($division == $max_division);
414 make_table($aux_parms, $match_stddev, $lowest_division, {}, {}, $division, $subdivision);
417 <p style="clear: both; padding-top: 1em;">Under er en variant som tar relativ spillestyrke med i beregningen;
418 se <a href="/rating">ratingsiden</a>.</p>
421 make_table($aux_parms, $match_stddev, $lowest_division, \%ratings, $cov, $division, $subdivision);
423 my $avg_rating = find_avg_rating(\%ratings);
424 printf " <p style=\"clear: both; padding-top: 1em;\">Gjennomsnittlig rating i denne avdelingen er <strong>%.1f</strong>.</p>\n", $avg_rating;
426 wloh_common::output_last_sync($dbh);