use Encode;
use utf8;
use locale;
-require '../config.pm';
+use lib qw(../include);
+require 'config.pm';
+require 'common.pm';
my $cgi = CGI->new;
my %ratings = ();
my %ratings_stddev = ();
my @matches = ();
-my %parms = ();
-my $match_stddev;
-
-sub sanitize {
- return HTML::Entities::encode_entities(shift);
-}
sub color {
my $x = shift;
return int(255.0 * ($x ** (1.80)));
}
-sub make_table {
- my ($lowest_division, $used_ratings, $used_ratings_stddev) = @_;
+sub get_divisions {
+ my ($dbh, $locale, $season) = @_;
- print <<"EOF";
+ my @divisions = ();
- <table>
- <tr>
- <th></th>
-EOF
+ 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');
+ $q->execute($locale, $season);
+
+ while (my $ref = $q->fetchrow_hashref) {
+ push @divisions, $ref->{'divisjon'};
+ }
+
+ return @divisions;
+}
+
+sub get_subdivisions {
+ my ($dbh, $locale, $season, $division) = @_;
+
+ my @subdivisions = ();
+
+ 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');
+ $q->execute($locale, $season, $division);
+
+ while (my $ref = $q->fetchrow_hashref) {
+ push @subdivisions, $ref->{'avdeling'};
+ }
+
+ return @subdivisions;
+}
+
+sub get_division_selector {
+ my ($divisions, $division) = @_;
+
+ my @ret = ();
+ for my $d (@$divisions) {
+ my $parms = {
+ 'option' => $d,
+ 'option/value' => $d,
+ };
+ $parms->{'option/selected'} = 'selected' if ($d == $division);
+ push @ret, $parms;
+ }
+ return \@ret;
+}
+
+sub get_players_and_ratings {
+ my ($dbh, $locale, $season, $division, $subdivision) = @_;
+
+ 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=?');
+ $q->execute($locale, $season, $division, $subdivision);
+
+ while (my $ref = $q->fetchrow_hashref) {
+ my $id = $ref->{'id'};
+ $players{$id} = Encode::decode_utf8($ref->{'navn'});
+ $ratings{$id} = $ref->{'rating'};
+ $ratings_stddev{$id} = $ref->{'rating_stddev'};
+ }
+ $q->finish;
+}
+
+sub get_matches {
+ my ($dbh, $locale, $season, $division, $subdivision) = @_;
+
+ my @matches = ();
+ my $q = $dbh->prepare('
+ SELECT
+ d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
+ FROM ( SELECT * FROM fotballresultater UNION ALL SELECT * FROM fotballresultater_2123 ) r
+ JOIN fotballserier s ON r.serie=s.nr
+ JOIN fotballspraak sp ON s.spraak=sp.id
+ JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
+ JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
+ WHERE
+ kultur=? AND sesong=? AND divisjon=? AND avdeling=?
+ AND lagrecno > motstander
+ ');
+ $q->execute($locale, $season, $division, $subdivision);
+
+ while (my $ref = $q->fetchrow_hashref) {
+ push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
+ }
+ $q->finish;
+
+ return @matches;
+}
+
+sub get_covariance_matrix {
+ my ($dbh, @players) = @_;
+
+ my $player_sql = '{' . join(',', @players ) . '}';
+ my $q = $dbh->prepare('SELECT * FROM covariance WHERE player1=ANY(?::smallint[]) AND player2=ANY(?::smallint[])', { pg_prepare_now => 0 });
+ $q->execute($player_sql, $player_sql);
+
+ my $cov = {};
+ while (my $ref = $q->fetchrow_hashref) {
+ $cov->{$ref->{'player1'}}{$ref->{'player2'}} = $ref->{'cov'};
+ }
+
+ return $cov;
+}
+
+sub write_parms_to_file {
+ my ($locale, $aux_parms, $match_stddev, $used_ratings, $used_cov) = @_;
+
+ wloh_common::set_locale($locale);
+
+ my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
POSIX::setlocale(&POSIX::LC_ALL, 'C');
printf MCCALC "%f\n", $match_stddev;
printf MCCALC "%d\n", scalar keys %players;
- for my $id (keys %players) {
- my $rating = $used_ratings->{$id} // 1500.0;
- my $rating_stddev = $used_ratings_stddev->{$id} // $parms{-3};
- printf MCCALC "%s %f %f\n", $id, $rating, $rating_stddev;
+ for my $id (@sorted_players) {
+ my $rating = $used_ratings->{$id} // 500.0;
+ printf MCCALC "%s %f\n", $id, $rating;
+ }
+
+ # covariance matrix
+ for my $id1 (keys %players) {
+ for my $id2 (keys %players) {
+ if ($id1 == $id2) {
+ printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // $aux_parms->{'rating_prior_stddev'});
+ } else {
+ printf MCCALC "%f ", ($used_cov->{$id1}{$id2} // 0.0);
+ }
+ }
+ printf MCCALC "\n";
}
for my $match (@matches) {
}
close MCCALC;
- POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
+ wloh_common::set_locale($locale);
+ return $tmpnam;
+}
+
+sub make_table {
+ my ($locale, $aux_parms, $match_stddev, $lowest_division, $used_ratings, $used_cov, $division, $subdivision, $table_id) = @_;
+
+ my $tmpnam = write_parms_to_file($locale, $aux_parms, $match_stddev, $used_ratings, $used_cov);
my %prob = ();
open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
chomp;
my @x = split /\s+/;
my $id = $x[0];
- my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 1500.0), ($ratings_stddev{$id} // $parms{-3});
+ my $player = sprintf "%s (%.0f ± %.0f)", $players{$id}, ($ratings{$id} // 500.0), ($ratings_stddev{$id} // $aux_parms->{'rating_prior_stddev'});
$prob{$player} = [ @x[1..$#x] ];
}
close MCCALC;
- #unlink $tmpnam;
+ unlink $tmpnam;
my $num_games = scalar keys %prob;
+
+ # Make list of ranks. (Relegation is handled specially.)
+ my @ranks = ();
for my $i (1..$num_games) {
- print " <th>$i.</th>\n";
+ push @ranks, { 'th' => "$i." };
}
- print " <th>NEDRYKK</th>\n" unless ($lowest_division);
- print " </tr>\n";
+ my @players = ();
+
+ my $pnum = 0;
for my $player (sort { $a cmp $b } keys %prob) {
- print " <tr>\n";
- print " <th>$player</th>\n";
+ ++$pnum;
+
+ my @player_ranks = ();
for my $i (1..$num_games) {
my $pn = $prob{$player}->[$i - 1] / $trials;
($r, $b) = ($b, $r);
}
- printf " <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
+ my $num_total_games = ($num_games * ($num_games - 1)) / 2;
+ if (scalar @matches == $num_total_games || $prob{$player}->[$i - 1] == $trials) {
+ push @player_ranks, {
+ 'td/style' => "background-color: rgb($r, $g, $b)",
+ 'td' => sprintf("%.1f%%", $pn * 100.0),
+ 'link' => ''
+ };
+ } else {
+ push @player_ranks, {
+ 'td/style' => "background-color: rgb($r, $g, $b)",
+ 'a' => sprintf("%.1f%%", $pn * 100.0),
+ 'a/href' => "javascript:showScenario('$table_id', '/$locale/?divisjon=$division;avdeling=$subdivision;spiller=$pnum;posisjon=$i')"
+ };
+ }
}
unless ($lowest_division) {
my $r = color(1.0);
my $g = color(1.0 - $pn / 3);
my $b = color(1.0 - $pn / 3);
- printf " <td style=\"background-color: rgb($r, $g, $b)\" class=\"num\">%.1f%%</td>\n", $pn * 100.0;
+ push @player_ranks, {
+ 'td/style' => "background-color: rgb($r, $g, $b)",
+ 'td' => sprintf("%.1f%%", $pn * 100.0),
+ 'link' => ''
+ };
}
- print " </tr>\n";
+ push @players, {
+ 'player' => $player,
+ 'player-ranks' => \@player_ranks
+ };
}
- print << "EOF";
- </table>
-EOF
+ my $parms = {
+ 'ranks' => \@ranks,
+ 'tbody' => \@players,
+ };
+ $parms->{'relegation'} = '' if ($lowest_division);
+ return $parms;
}
-# Get auxillary parameters
-my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
-$q->execute;
+sub make_cov_table {
+ my ($cov) = @_;
+ my @players = (sort { $players{$a} cmp $players{$b} } keys %players);
+
+ my @player_list = ();
+ for my $player (@players) {
+ push @player_list, { 'th' => $players{$player} };
+ }
+
+ my @player_rows = ();
+ for my $player (@players) {
+ my @elements = ();
+ for my $player2 (@players) {
+ my $c = sprintf("%.2f", $cov->{$player}{$player2});
+ push @elements, { 'td' => $c };
+ }
+ push @player_rows, {
+ '#player' => $players{$player},
+ 'elements' => \@elements
+ };
+ }
-while (my $ref = $q->fetchrow_hashref) {
- $parms{$ref->{'id'}} = $ref->{'rating'};
+ return {
+ 'player-list' => \@player_list,
+ 'tbody' => \@player_rows
+ };
}
-$match_stddev = $parms{-2} * sqrt(2.0);
-my $season;
-my $division = $cgi->param('divisjon') // -1;
-my $subdivision = $cgi->param('avdeling') // -1;
-my $last_division = 0;
+sub find_avg_rating {
+ my ($ratings) = shift;
-POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');
+ my $sum_rating = 0.0;
+ for my $r (values %$ratings) {
+ $sum_rating += ($r // 500.0);
+ }
+ return $sum_rating / scalar keys %$ratings;
+}
-print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
-printf <<"EOF", $match_stddev;
+sub print_header {
+ my ($cgi, $title) = @_;
+ print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
+ print <<"EOF";
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="no">
<head>
- <title>WLoH-plasseringsannsynlighetsberegning</title>
- <link rel="stylesheet" href="/style" type="text/css" />
+ <title>$title</title>
+ <link rel="stylesheet" href="style" type="text/css" />
</head>
<body>
- <h1>WLoH-plasseringsannsynlighetsberegning</h1>
-
- <p><em>Dette er et hobbyprosjekt fra tredjepart, og ikke en offisiell del av
- <a href="http://wordfeud.aasmul.net/">Wordfeud Leage of Honour</a>.</em></p>
-
- <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
- den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
- %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
- Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.</p>
-
- <p>Spillerne er sortert etter nick.</p>
-
- <form method="get" action="/">
EOF
-
-$q = $dbh->prepare('SELECT MAX(sesong) AS max_sesong FROM fotballserier');
-$q->execute;
-my $season;
-while (my $ref = $q->fetchrow_hashref) {
- $season = $ref->{'max_sesong'};
}
-print <<"EOF";
- <p>Divisjon:
- <select name="divisjon" onchange="form.submit();">
+sub print_footer {
+ print <<"EOF";
+ </body>
+</html>
EOF
+}
-$q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier WHERE sesong=? ORDER BY divisjon');
-$q->execute($season);
+my $locale = wloh_common::get_locale($cgi);
+my $aux_parms = wloh_common::get_auxillary_parameters($dbh, $locale);
+my $match_stddev = $aux_parms->{'score_stddev'} * sqrt(2.0);
-my $found_division = 0;
-my $max_division;
+my $division = $cgi->param('divisjon') // -1;
+my $subdivision = $cgi->param('avdeling') // -1;
+my $match_player = $cgi->param('spiller');
+my $match_position = $cgi->param('posisjon');
-while (my $ref = $q->fetchrow_hashref) {
- my $d = $ref->{'divisjon'};
- if ($d == $division) {
- print " <option value=\"$d\" selected=\"selected\">$d</option>\n";
- $found_division = 1;
- } else {
- print " <option value=\"$d\">$d</option>\n";
- }
- $max_division = $d;
-}
+my $season = wloh_common::get_max_season($dbh, $locale);
+die "Nonexistent locale!" if (!defined($season));
-$division = 1 if (!$found_division);
+my @divisions = get_divisions($dbh, $locale, $season);
+$division = $divisions[0] if (!grep { $_ == $division } @divisions);
+my @subdivisions = get_subdivisions($dbh, $locale, $season, $division);
+$subdivision = $subdivisions[0] if (!grep { $_ == $subdivision } @subdivisions);
-print <<"EOF";
- </select>
- Avdeling:
- <select name="avdeling" onchange="form.submit();">
-EOF
+get_players_and_ratings($dbh, $locale, $season, $division, $subdivision);
+@matches = get_matches($dbh, $locale, $season, $division, $subdivision);
+my $cov = get_covariance_matrix($dbh, keys %players);
-$q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier WHERE sesong=? AND divisjon=? ORDER BY avdeling');
-$q->execute($season, $division);
+if (defined($match_player) && defined($match_position)) {
+ my $tmpnam = write_parms_to_file($locale, $aux_parms, $match_stddev, \%ratings, $cov);
-my $found_subdivision = 0;
+ --$match_player;
+ --$match_position;
-while (my $ref = $q->fetchrow_hashref) {
- my $sd = $ref->{'avdeling'};
- if ($sd == $subdivision) {
- print " <option value=\"$sd\" selected=\"selected\">$sd</option>\n";
- $found_subdivision = 1;
- } else {
- print " <option value=\"$sd\">$sd</option>\n";
+ my @scenario = ();
+ open MCCALC, "$config::base_dir/mcwordfeud $trials $match_player $match_position < $tmpnam |"
+ or die "mccalc: $!";
+ while (<MCCALC>) {
+ /(\d+) (\d+) (-?\d+)/ or next;
+ chomp;
+ push @scenario, {
+ 'player-1' => $players{$1},
+ 'player-2' => $players{$2},
+ 'result' => sprintf("%+d", $3),
+ };
}
-}
-
-$subdivision = 1 if (!$found_subdivision);
-
-print <<"EOF";
- </select>
- <input type="submit" value="Vis" />
- </p>
- </form>
-EOF
+ close MCCALC;
+ unlink $tmpnam;
-# Get players and ratings
-$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=?');
-$q->execute($season, $division, $subdivision);
+ my @sorted_players = sort { $players{$a} cmp $players{$b} } keys %players;
+ my $player_name = $players{$sorted_players[$match_player]};
-while (my $ref = $q->fetchrow_hashref) {
- my $id = $ref->{'id'};
- $players{$id} = sanitize(Encode::decode_utf8($ref->{'navn'}));
- $ratings{$id} = $ref->{'rating'};
- $ratings_stddev{$id} = $ref->{'rating_stddev'};
-}
-$q->finish;
-
-$q = $dbh->prepare('
-SELECT
- d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
-FROM fotballresultater r
- JOIN fotballserier s ON r.serie=s.nr
- JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
- JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
-WHERE
- sesong=? AND divisjon=? AND avdeling=?
- AND lagrecno > motstander
-');
-$q->execute($season, $division, $subdivision);
-
-while (my $ref = $q->fetchrow_hashref) {
- push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
+ if (scalar @scenario == 0) {
+ print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
+ wloh_common::process_template('scenario-not-found', $locale, {
+ '#nick' => $player_name,
+ '#rank' => sprintf("%d.", $match_position + 1)
+ });
+ } else {
+ print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
+ wloh_common::process_template('scenario', $locale, {
+ '#nick' => $player_name,
+ '#rank' => sprintf("%d.", $match_position + 1),
+ '#results' => \@scenario
+ });
+ }
+} else {
+ wloh_common::set_locale($locale);
+
+ my $max_division = $divisions[$#divisions];
+ my $lowest_division = ($division == $max_division);
+ my $basic_table = make_table($locale, $aux_parms, $match_stddev, $lowest_division, {}, {}, $division, $subdivision, 'scenario1');
+ my $adjusted_table = make_table($locale, $aux_parms, $match_stddev, $lowest_division, \%ratings, $cov, $division, $subdivision, 'scenario2');
+ my $cov_table = (defined($cgi->param('showcov'))) ? make_cov_table($cov) : '';
+
+ my $avg_rating = find_avg_rating(\%ratings);
+
+ print CGI->header(-type=>'text/html; charset=utf-8', -expires=>'+5m');
+ wloh_common::process_template('index', $locale, {
+ '#navbar' => wloh_common::get_navbar($cgi, $dbh, $locale),
+ '#division-selector/action' => "/$locale/",
+ '#division' => get_division_selector(\@divisions, $division),
+ '#subdivision' => get_division_selector(\@subdivisions, $subdivision),
+ '#basic-probabilities' => $basic_table,
+ '#adjusted-probabilities' => $adjusted_table,
+ 'cov-table' => $cov_table,
+ 'match-stddev' => sprintf("%.1f", $match_stddev),
+ '#average-rating' => sprintf("%.1f", $avg_rating),
+ 'last-sync' => wloh_common::get_last_sync($dbh),
+ });
}
-$q->finish;
-
-my $lowest_division = ($division == $max_division);
-make_table($lowest_division, {}, {});
-print <<"EOF";
- <p>Under er en variant som tar relativ spillestyrke med i beregningen;
- se <a href="/rating">ratingsiden</a>.</p>
-EOF
-
-make_table($lowest_division, \%ratings, \%ratings_stddev);
-
-print << "EOF";
- </body>
-</html>
-EOF