mirror of
https://github.com/furyfire/trueskill.git
synced 2025-04-19 12:24:28 +00:00
Naming tweak
This commit is contained in:
26
Skills/TrueSkill/DrawMargin.php
Normal file
26
Skills/TrueSkill/DrawMargin.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../Numerics/GaussianDistribution.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
|
||||
final class DrawMargin
|
||||
{
|
||||
public static function getDrawMarginFromDrawProbability($drawProbability, $beta)
|
||||
{
|
||||
// Derived from TrueSkill technical report (MSR-TR-2006-80), page 6
|
||||
|
||||
// draw probability = 2 * CDF(margin/(sqrt(n1+n2)*beta)) -1
|
||||
|
||||
// implies
|
||||
//
|
||||
// margin = inversecdf((draw probability + 1)/2) * sqrt(n1+n2) * beta
|
||||
// n1 and n2 are the number of players on each team
|
||||
$margin = GaussianDistribution::inverseCumulativeTo(.5*($drawProbability + 1), 0, 1)*sqrt(1 + 1)*
|
||||
$beta;
|
||||
return $margin;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
207
Skills/TrueSkill/FactorGraphTrueSkillCalculator.php
Normal file
207
Skills/TrueSkill/FactorGraphTrueSkillCalculator.php
Normal file
@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../GameInfo.php");
|
||||
require_once(dirname(__FILE__) . "/../Guard.php");
|
||||
require_once(dirname(__FILE__) . "/../ISupportPartialPlay.php");
|
||||
require_once(dirname(__FILE__) . "/../ISupportPartialUpdate.php");
|
||||
require_once(dirname(__FILE__) . "/../PartialPlay.php");
|
||||
require_once(dirname(__FILE__) . "/../PlayersRange.php");
|
||||
require_once(dirname(__FILE__) . "/../RankSorter.php");
|
||||
require_once(dirname(__FILE__) . "/../SkillCalculator.php");
|
||||
require_once(dirname(__FILE__) . "/../TeamsRange.php");
|
||||
require_once(dirname(__FILE__) . "/../Numerics/BasicMath.php");
|
||||
require_once(dirname(__FILE__) . "/../Numerics/Matrix.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraph.php");
|
||||
|
||||
use Moserware\Numerics\DiagonalMatrix;
|
||||
use Moserware\Numerics\Matrix;
|
||||
use Moserware\Numerics\Vector;
|
||||
|
||||
use Moserware\Skills\GameInfo;
|
||||
use Moserware\Skills\Guard;
|
||||
use Moserware\Skills\ISupportPartialPlay;
|
||||
use Moserware\Skills\ISupportPartialUpdate;
|
||||
use Moserware\Skills\PartialPlay;
|
||||
use Moserware\Skills\PlayersRange;
|
||||
use Moserware\Skills\RankSorter;
|
||||
use Moserware\Skills\SkillCalculator;
|
||||
use Moserware\Skills\SkillCalculatorSupportedOptions;
|
||||
use Moserware\Skills\TeamsRange;
|
||||
|
||||
/**
|
||||
* Calculates TrueSkill using a full factor graph.
|
||||
*/
|
||||
class FactorGraphTrueSkillCalculator extends SkillCalculator
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(SkillCalculatorSupportedOptions::PARTIAL_PLAY | SkillCalculatorSupportedOptions::PARTIAL_UPDATE, TeamsRange::atLeast(2), PlayersRange::atLeast(1));
|
||||
}
|
||||
|
||||
public function calculateNewRatings(GameInfo &$gameInfo,
|
||||
array $teams,
|
||||
array $teamRanks)
|
||||
{
|
||||
Guard::argumentNotNull($gameInfo, "gameInfo");
|
||||
$this->validateTeamCountAndPlayersCountPerTeam($teams);
|
||||
|
||||
RankSorter::sort($teams, $teamRanks);
|
||||
|
||||
$factorGraph = new TrueSkillFactorGraph($gameInfo, $teams, $teamRanks);
|
||||
$factorGraph->buildGraph();
|
||||
$factorGraph->runSchedule();
|
||||
|
||||
$probabilityOfOutcome = $factorGraph->getProbabilityOfRanking();
|
||||
|
||||
return $factorGraph->getUpdatedRatings();
|
||||
}
|
||||
|
||||
public function calculateMatchQuality(GameInfo &$gameInfo,
|
||||
array &$teams)
|
||||
{
|
||||
// We need to create the A matrix which is the player team assigments.
|
||||
$teamAssignmentsList = $teams;
|
||||
$skillsMatrix = $this->getPlayerCovarianceMatrix($teamAssignmentsList);
|
||||
$meanVector = $this->getPlayerMeansVector($teamAssignmentsList);
|
||||
$meanVectorTranspose = $meanVector->getTranspose();
|
||||
|
||||
$playerTeamAssignmentsMatrix = $this->createPlayerTeamAssignmentMatrix($teamAssignmentsList, $meanVector->getRowCount());
|
||||
$playerTeamAssignmentsMatrixTranspose = $playerTeamAssignmentsMatrix->getTranspose();
|
||||
|
||||
$betaSquared = square($gameInfo->getBeta());
|
||||
|
||||
$start = Matrix::multiply($meanVectorTranspose, $playerTeamAssignmentsMatrix);
|
||||
$aTa = Matrix::multiply(
|
||||
Matrix::scalarMultiply($betaSquared,
|
||||
$playerTeamAssignmentsMatrixTranspose),
|
||||
$playerTeamAssignmentsMatrix);
|
||||
|
||||
$aTSA = Matrix::multiply(
|
||||
Matrix::multiply($playerTeamAssignmentsMatrixTranspose, $skillsMatrix),
|
||||
$playerTeamAssignmentsMatrix);
|
||||
|
||||
$middle = Matrix::add($aTa, $aTSA);
|
||||
|
||||
$middleInverse = $middle->getInverse();
|
||||
|
||||
$end = Matrix::multiply($playerTeamAssignmentsMatrixTranspose, $meanVector);
|
||||
|
||||
$expPartMatrix = Matrix::scalarMultiply(-0.5, (Matrix::multiply(Matrix::multiply($start, $middleInverse), $end)));
|
||||
$expPart = $expPartMatrix->getDeterminant();
|
||||
|
||||
$sqrtPartNumerator = $aTa->getDeterminant();
|
||||
$sqrtPartDenominator = $middle->getDeterminant();
|
||||
$sqrtPart = $sqrtPartNumerator / $sqrtPartDenominator;
|
||||
|
||||
$result = exp($expPart) * sqrt($sqrtPart);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function getPlayerMeansVector(array &$teamAssignmentsList)
|
||||
{
|
||||
// A simple vector of all the player means.
|
||||
return new Vector(self::getPlayerRatingValues($teamAssignmentsList,
|
||||
function($rating)
|
||||
{
|
||||
return $rating->getMean();
|
||||
}));
|
||||
}
|
||||
|
||||
private static function getPlayerCovarianceMatrix(array &$teamAssignmentsList)
|
||||
{
|
||||
// This is a square matrix whose diagonal values represent the variance (square of standard deviation) of all
|
||||
// players.
|
||||
return new DiagonalMatrix(
|
||||
self::getPlayerRatingValues($teamAssignmentsList,
|
||||
function($rating)
|
||||
{
|
||||
return square($rating->getStandardDeviation());
|
||||
}));
|
||||
}
|
||||
|
||||
// Helper function that gets a list of values for all player ratings
|
||||
private static function getPlayerRatingValues(array &$teamAssignmentsList,
|
||||
$playerRatingFunction)
|
||||
{
|
||||
$playerRatingValues = array();
|
||||
|
||||
foreach ($teamAssignmentsList as $currentTeam)
|
||||
{
|
||||
foreach ($currentTeam->getAllRatings() as $currentRating)
|
||||
{
|
||||
$playerRatingValues[] = $playerRatingFunction($currentRating);
|
||||
}
|
||||
}
|
||||
|
||||
return $playerRatingValues;
|
||||
}
|
||||
|
||||
private static function createPlayerTeamAssignmentMatrix(&$teamAssignmentsList, $totalPlayers)
|
||||
{
|
||||
// The team assignment matrix is often referred to as the "A" matrix. It's a matrix whose rows represent the players
|
||||
// and the columns represent teams. At Matrix[row, column] represents that player[row] is on team[col]
|
||||
// Positive values represent an assignment and a negative value means that we subtract the value of the next
|
||||
// team since we're dealing with pairs. This means that this matrix always has teams - 1 columns.
|
||||
// The only other tricky thing is that values represent the play percentage.
|
||||
|
||||
// For example, consider a 3 team game where team1 is just player1, team 2 is player 2 and player 3, and
|
||||
// team3 is just player 4. Furthermore, player 2 and player 3 on team 2 played 25% and 75% of the time
|
||||
// (e.g. partial play), the A matrix would be:
|
||||
|
||||
// A = this 4x2 matrix:
|
||||
// | 1.00 0.00 |
|
||||
// | -0.25 0.25 |
|
||||
// | -0.75 0.75 |
|
||||
// | 0.00 -1.00 |
|
||||
|
||||
$playerAssignments = array();
|
||||
$totalPreviousPlayers = 0;
|
||||
|
||||
$teamAssignmentsListCount = count($teamAssignmentsList);
|
||||
|
||||
$currentColumn = 0;
|
||||
|
||||
for ($i = 0; $i < $teamAssignmentsListCount - 1; $i++)
|
||||
{
|
||||
$currentTeam = $teamAssignmentsList[$i];
|
||||
|
||||
// Need to add in 0's for all the previous players, since they're not
|
||||
// on this team
|
||||
$playerAssignments[$currentColumn] = ($totalPreviousPlayers > 0) ? \array_fill(0, $totalPreviousPlayers, 0) : array();
|
||||
|
||||
foreach ($currentTeam->getAllPlayers() as $currentPlayer)
|
||||
{
|
||||
$playerAssignments[$currentColumn][] = PartialPlay::getPartialPlayPercentage($currentPlayer);
|
||||
// indicates the player is on the team
|
||||
$totalPreviousPlayers++;
|
||||
}
|
||||
|
||||
$rowsRemaining = $totalPlayers - $totalPreviousPlayers;
|
||||
|
||||
$nextTeam = $teamAssignmentsList[$i + 1];
|
||||
foreach ($nextTeam->getAllPlayers() as $nextTeamPlayer)
|
||||
{
|
||||
// Add a -1 * playing time to represent the difference
|
||||
$playerAssignments[$currentColumn][] = -1 * PartialPlay::getPartialPlayPercentage($nextTeamPlayer);
|
||||
$rowsRemaining--;
|
||||
}
|
||||
|
||||
for ($ixAdditionalRow = 0; $ixAdditionalRow < $rowsRemaining; $ixAdditionalRow++)
|
||||
{
|
||||
// Pad with zeros
|
||||
$playerAssignments[$currentColumn][] = 0;
|
||||
}
|
||||
|
||||
$currentColumn++;
|
||||
}
|
||||
|
||||
$playerTeamAssignmentsMatrix = Matrix::fromColumnValues($totalPlayers, $teamAssignmentsListCount - 1, $playerAssignments);
|
||||
|
||||
return $playerTeamAssignmentsMatrix;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
45
Skills/TrueSkill/Factors/GaussianFactor.php
Normal file
45
Skills/TrueSkill/Factors/GaussianFactor.php
Normal file
@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Factor.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\FactorGraphs\Factor;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
abstract class GaussianFactor extends Factor
|
||||
{
|
||||
protected function __construct($name)
|
||||
{
|
||||
parent::__construct($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the factor-graph message with and returns the log-normalization constant.
|
||||
*/
|
||||
protected function sendMessageVariable(Message &$message, Variable &$variable)
|
||||
{
|
||||
$marginal = &$variable->getValue();
|
||||
$messageValue = &$message->getValue();
|
||||
$logZ = GaussianDistribution::logProductNormalization($marginal, $messageValue);
|
||||
$variable->setValue(GaussianDistribution::multiply($marginal, $messageValue));
|
||||
return $logZ;
|
||||
}
|
||||
|
||||
public function &createVariableToMessageBinding(Variable &$variable)
|
||||
{
|
||||
$newDistribution = GaussianDistribution::fromPrecisionMean(0, 0);
|
||||
$binding = &parent::createVariableToMessageBindingWithMessage($variable,
|
||||
new Message(
|
||||
$newDistribution,
|
||||
sprintf("message from %s to %s", $this, $variable)));
|
||||
return $binding;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
85
Skills/TrueSkill/Factors/GaussianGreaterThanFactor.php
Normal file
85
Skills/TrueSkill/Factors/GaussianGreaterThanFactor.php
Normal file
@ -0,0 +1,85 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
require_once(dirname(__FILE__) . "/../TruncatedGaussianCorrectionFunctions.php");
|
||||
require_once(dirname(__FILE__) . "/GaussianFactor.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
/**
|
||||
* Factor representing a team difference that has exceeded the draw margin.
|
||||
*
|
||||
* See the accompanying math paper for more details.
|
||||
*/
|
||||
class GaussianGreaterThanFactor extends GaussianFactor
|
||||
{
|
||||
private $_epsilon;
|
||||
|
||||
public function __construct($epsilon, Variable &$variable)
|
||||
{
|
||||
parent::__construct(\sprintf("%s > %.2f", $variable, $epsilon));
|
||||
$this->_epsilon = $epsilon;
|
||||
$this->createVariableToMessageBinding($variable);
|
||||
}
|
||||
|
||||
public function getLogNormalization()
|
||||
{
|
||||
$vars = &$this->getVariables();
|
||||
$marginal = &$vars[0]->getValue();
|
||||
$messages = &$this->getMessages();
|
||||
$message = &$messages[0]->getValue();
|
||||
$messageFromVariable = GaussianDistribution::divide($marginal, $message);
|
||||
return -GaussianDistribution::logProductNormalization($messageFromVariable, $message)
|
||||
+
|
||||
log(
|
||||
GaussianDistribution::cumulativeTo(($messageFromVariable->getMean() - $this->_epsilon)/
|
||||
$messageFromVariable->getStandardDeviation()));
|
||||
|
||||
}
|
||||
|
||||
protected function updateMessageVariable(Message &$message, Variable &$variable)
|
||||
{
|
||||
$oldMarginal = clone $variable->getValue();
|
||||
$oldMessage = clone $message->getValue();
|
||||
$messageFromVar = GaussianDistribution::divide($oldMarginal, $oldMessage);
|
||||
|
||||
$c = $messageFromVar->getPrecision();
|
||||
$d = $messageFromVar->getPrecisionMean();
|
||||
|
||||
$sqrtC = sqrt($c);
|
||||
|
||||
$dOnSqrtC = $d/$sqrtC;
|
||||
|
||||
$epsilsonTimesSqrtC = $this->_epsilon*$sqrtC;
|
||||
$d = $messageFromVar->getPrecisionMean();
|
||||
|
||||
$denom = 1.0 - TruncatedGaussianCorrectionFunctions::wExceedsMargin($dOnSqrtC, $epsilsonTimesSqrtC);
|
||||
|
||||
$newPrecision = $c/$denom;
|
||||
$newPrecisionMean = ($d +
|
||||
$sqrtC*
|
||||
TruncatedGaussianCorrectionFunctions::vExceedsMargin($dOnSqrtC, $epsilsonTimesSqrtC))/
|
||||
$denom;
|
||||
|
||||
$newMarginal = GaussianDistribution::fromPrecisionMean($newPrecisionMean, $newPrecision);
|
||||
|
||||
$newMessage = GaussianDistribution::divide(
|
||||
GaussianDistribution::multiply($oldMessage, $newMarginal),
|
||||
$oldMarginal);
|
||||
|
||||
// Update the message and marginal
|
||||
$message->setValue($newMessage);
|
||||
|
||||
$variable->setValue($newMarginal);
|
||||
|
||||
// Return the difference in the new marginal
|
||||
return GaussianDistribution::subtract($newMarginal, $oldMarginal);
|
||||
}
|
||||
}
|
||||
?>
|
87
Skills/TrueSkill/Factors/GaussianLikelihoodFactor.php
Normal file
87
Skills/TrueSkill/Factors/GaussianLikelihoodFactor.php
Normal file
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
require_once(dirname(__FILE__) . "/GaussianFactor.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
/**
|
||||
* Connects two variables and adds uncertainty.
|
||||
*
|
||||
* See the accompanying math paper for more details.
|
||||
*/
|
||||
class GaussianLikelihoodFactor extends GaussianFactor
|
||||
{
|
||||
private $_precision;
|
||||
|
||||
public function __construct($betaSquared, Variable &$variable1, Variable &$variable2)
|
||||
{
|
||||
parent::__construct(sprintf("Likelihood of %s going to %s", $variable2, $variable1));
|
||||
$this->_precision = 1.0/$betaSquared;
|
||||
$this->createVariableToMessageBinding($variable1);
|
||||
$this->createVariableToMessageBinding($variable2);
|
||||
}
|
||||
|
||||
public function getLogNormalization()
|
||||
{
|
||||
$vars = &$this->getVariables();
|
||||
$messages = &$this->getMessages();
|
||||
|
||||
return GaussianDistribution::logRatioNormalization(
|
||||
$vars[0]->getValue(),
|
||||
$messages[0]->getValue());
|
||||
}
|
||||
|
||||
private function updateHelper(Message &$message1, Message &$message2,
|
||||
Variable &$variable1, Variable &$variable2)
|
||||
{
|
||||
$message1Value = clone $message1->getValue();
|
||||
$message2Value = clone $message2->getValue();
|
||||
|
||||
$marginal1 = clone $variable1->getValue();
|
||||
$marginal2 = clone $variable2->getValue();
|
||||
|
||||
$a = $this->_precision/($this->_precision + $marginal2->getPrecision() - $message2Value->getPrecision());
|
||||
|
||||
$newMessage = GaussianDistribution::fromPrecisionMean(
|
||||
$a*($marginal2->getPrecisionMean() - $message2Value->getPrecisionMean()),
|
||||
$a*($marginal2->getPrecision() - $message2Value->getPrecision()));
|
||||
|
||||
$oldMarginalWithoutMessage = GaussianDistribution::divide($marginal1, $message1Value);
|
||||
|
||||
$newMarginal = GaussianDistribution::multiply($oldMarginalWithoutMessage, $newMessage);
|
||||
|
||||
// Update the message and marginal
|
||||
|
||||
$message1->setValue($newMessage);
|
||||
$variable1->setValue($newMarginal);
|
||||
|
||||
// Return the difference in the new marginal
|
||||
return GaussianDistribution::subtract($newMarginal, $marginal1);
|
||||
}
|
||||
|
||||
public function updateMessageIndex($messageIndex)
|
||||
{
|
||||
$messages = &$this->getMessages();
|
||||
$vars = &$this->getVariables();
|
||||
|
||||
switch ($messageIndex)
|
||||
{
|
||||
case 0:
|
||||
return $this->updateHelper($messages[0], $messages[1],
|
||||
$vars[0], $vars[1]);
|
||||
case 1:
|
||||
return $this->updateHelper($messages[1], $messages[0],
|
||||
$vars[1], $vars[0]);
|
||||
default:
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
48
Skills/TrueSkill/Factors/GaussianPriorFactor.php
Normal file
48
Skills/TrueSkill/Factors/GaussianPriorFactor.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
require_once(dirname(__FILE__) . "/GaussianFactor.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
/**
|
||||
* Supplies the factor graph with prior information.
|
||||
*
|
||||
* See the accompanying math paper for more details.
|
||||
*/
|
||||
class GaussianPriorFactor extends GaussianFactor
|
||||
{
|
||||
private $_newMessage;
|
||||
|
||||
public function __construct($mean, $variance, Variable &$variable)
|
||||
{
|
||||
parent::__construct(sprintf("Prior value going to %s", $variable));
|
||||
$this->_newMessage = new GaussianDistribution($mean, sqrt($variance));
|
||||
$newMessage = new Message(GaussianDistribution::fromPrecisionMean(0, 0),
|
||||
sprintf("message from %s to %s", $this, $variable));
|
||||
|
||||
$this->createVariableToMessageBindingWithMessage($variable, $newMessage);
|
||||
}
|
||||
|
||||
protected function updateMessageVariable(Message &$message, Variable &$variable)
|
||||
{
|
||||
$oldMarginal = clone $variable->getValue();
|
||||
$oldMessage = $message;
|
||||
$newMarginal =
|
||||
GaussianDistribution::fromPrecisionMean(
|
||||
$oldMarginal->getPrecisionMean() + $this->_newMessage->getPrecisionMean() - $oldMessage->getValue()->getPrecisionMean(),
|
||||
$oldMarginal->getPrecision() + $this->_newMessage->getPrecision() - $oldMessage->getValue()->getPrecision());
|
||||
|
||||
$variable->setValue($newMarginal);
|
||||
$newMessage = &$this->_newMessage;
|
||||
$message->setValue($newMessage);
|
||||
return GaussianDistribution::subtract($oldMarginal, $newMarginal);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
272
Skills/TrueSkill/Factors/GaussianWeightedSumFactor.php
Normal file
272
Skills/TrueSkill/Factors/GaussianWeightedSumFactor.php
Normal file
@ -0,0 +1,272 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../Guard.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/BasicMath.php");
|
||||
require_once(dirname(__FILE__) . "/GaussianFactor.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\Guard;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
/**
|
||||
* Factor that sums together multiple Gaussians.
|
||||
*
|
||||
* See the accompanying math paper for more details.s
|
||||
*/
|
||||
class GaussianWeightedSumFactor extends GaussianFactor
|
||||
{
|
||||
private $_variableIndexOrdersForWeights = array();
|
||||
|
||||
// This following is used for convenience, for example, the first entry is [0, 1, 2]
|
||||
// corresponding to v[0] = a1*v[1] + a2*v[2]
|
||||
private $_weights;
|
||||
private $_weightsSquared;
|
||||
|
||||
public function __construct(Variable &$sumVariable, array &$variablesToSum, array &$variableWeights = null)
|
||||
{
|
||||
parent::__construct(self::createName($sumVariable, $variablesToSum, $variableWeights));
|
||||
$this->_weights = array();
|
||||
$this->_weightsSquared = array();
|
||||
|
||||
// The first weights are a straightforward copy
|
||||
// v_0 = a_1*v_1 + a_2*v_2 + ... + a_n * v_n
|
||||
$variableWeightsLength = count($variableWeights);
|
||||
$this->_weights[0] = \array_fill(0, count($variableWeights), 0);
|
||||
|
||||
for($i = 0; $i < $variableWeightsLength; $i++)
|
||||
{
|
||||
$weight = &$variableWeights[$i];
|
||||
$this->_weights[0][$i] = $weight;
|
||||
$this->_weightsSquared[0][$i] = square($weight);
|
||||
}
|
||||
|
||||
$variablesToSumLength = count($variablesToSum);
|
||||
|
||||
// 0..n-1
|
||||
$this->_variableIndexOrdersForWeights[0] = array();
|
||||
for($i = 0; $i < ($variablesToSumLength + 1); $i++)
|
||||
{
|
||||
$this->_variableIndexOrdersForWeights[0][] = $i;
|
||||
}
|
||||
|
||||
$variableWeightsLength = count($variableWeights);
|
||||
|
||||
// The rest move the variables around and divide out the constant.
|
||||
// For example:
|
||||
// v_1 = (-a_2 / a_1) * v_2 + (-a3/a1) * v_3 + ... + (1.0 / a_1) * v_0
|
||||
// By convention, we'll put the v_0 term at the end
|
||||
|
||||
$weightsLength = $variableWeightsLength + 1;
|
||||
for ($weightsIndex = 1; $weightsIndex < $weightsLength; $weightsIndex++)
|
||||
{
|
||||
$currentWeights = \array_fill(0, $variableWeightsLength, 0);
|
||||
|
||||
$variableIndices = \array_fill(0, $variableWeightsLength + 1, 0);
|
||||
$variableIndices[0] = $weightsIndex;
|
||||
|
||||
$currentWeightsSquared = \array_fill(0, $variableWeightsLength, 0);
|
||||
|
||||
// keep a single variable to keep track of where we are in the array.
|
||||
// This is helpful since we skip over one of the spots
|
||||
$currentDestinationWeightIndex = 0;
|
||||
|
||||
for ($currentWeightSourceIndex = 0;
|
||||
$currentWeightSourceIndex < $variableWeightsLength;
|
||||
$currentWeightSourceIndex++)
|
||||
{
|
||||
if ($currentWeightSourceIndex == ($weightsIndex - 1))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$currentWeight = (-$variableWeights[$currentWeightSourceIndex]/$variableWeights[$weightsIndex - 1]);
|
||||
|
||||
if ($variableWeights[$weightsIndex - 1] == 0)
|
||||
{
|
||||
// HACK: Getting around division by zero
|
||||
$currentWeight = 0;
|
||||
}
|
||||
|
||||
$currentWeights[$currentDestinationWeightIndex] = $currentWeight;
|
||||
$currentWeightsSquared[$currentDestinationWeightIndex] = $currentWeight*$currentWeight;
|
||||
|
||||
$variableIndices[$currentDestinationWeightIndex + 1] = $currentWeightSourceIndex + 1;
|
||||
$currentDestinationWeightIndex++;
|
||||
}
|
||||
|
||||
// And the final one
|
||||
$finalWeight = 1.0/$variableWeights[$weightsIndex - 1];
|
||||
|
||||
if ($variableWeights[$weightsIndex - 1] == 0)
|
||||
{
|
||||
// HACK: Getting around division by zero
|
||||
$finalWeight = 0;
|
||||
}
|
||||
$currentWeights[$currentDestinationWeightIndex] = $finalWeight;
|
||||
$currentWeightsSquared[$currentDestinationWeightIndex] = square($finalWeight);
|
||||
$variableIndices[count($variableWeights)] = 0;
|
||||
$this->_variableIndexOrdersForWeights[] = $variableIndices;
|
||||
|
||||
$this->_weights[$weightsIndex] = $currentWeights;
|
||||
$this->_weightsSquared[$weightsIndex] = $currentWeightsSquared;
|
||||
}
|
||||
|
||||
$this->createVariableToMessageBinding($sumVariable);
|
||||
|
||||
foreach ($variablesToSum as &$currentVariable)
|
||||
{
|
||||
$localCurrentVariable = &$currentVariable;
|
||||
$this->createVariableToMessageBinding($localCurrentVariable);
|
||||
}
|
||||
}
|
||||
|
||||
public function getLogNormalization()
|
||||
{
|
||||
$vars = &$this->getVariables();
|
||||
$messages = &$this->getMessages();
|
||||
|
||||
$result = 0.0;
|
||||
|
||||
// We start at 1 since offset 0 has the sum
|
||||
$varCount = count($vars);
|
||||
for ($i = 1; $i < $varCount; $i++)
|
||||
{
|
||||
$result += GaussianDistribution::logRatioNormalization($vars[$i]->getValue(), $messages[$i]->getValue());
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function updateHelper(array &$weights, array &$weightsSquared,
|
||||
array &$messages,
|
||||
array &$variables)
|
||||
{
|
||||
// Potentially look at http://mathworld.wolfram.com/NormalSumDistribution.html for clues as
|
||||
// to what it's doing
|
||||
|
||||
$message0 = clone $messages[0]->getValue();
|
||||
$marginal0 = clone $variables[0]->getValue();
|
||||
|
||||
// The math works out so that 1/newPrecision = sum of a_i^2 /marginalsWithoutMessages[i]
|
||||
$inverseOfNewPrecisionSum = 0.0;
|
||||
$anotherInverseOfNewPrecisionSum = 0.0;
|
||||
$weightedMeanSum = 0.0;
|
||||
$anotherWeightedMeanSum = 0.0;
|
||||
|
||||
$weightsSquaredLength = count($weightsSquared);
|
||||
|
||||
for ($i = 0; $i < $weightsSquaredLength; $i++)
|
||||
{
|
||||
// These flow directly from the paper
|
||||
|
||||
$inverseOfNewPrecisionSum += $weightsSquared[$i]/
|
||||
($variables[$i + 1]->getValue()->getPrecision() - $messages[$i + 1]->getValue()->getPrecision());
|
||||
|
||||
$diff = GaussianDistribution::divide($variables[$i + 1]->getValue(), $messages[$i + 1]->getValue());
|
||||
$anotherInverseOfNewPrecisionSum += $weightsSquared[$i]/$diff->getPrecision();
|
||||
|
||||
$weightedMeanSum += $weights[$i]
|
||||
*
|
||||
($variables[$i + 1]->getValue()->getPrecisionMean() - $messages[$i + 1]->getValue()->getPrecisionMean())
|
||||
/
|
||||
($variables[$i + 1]->getValue()->getPrecision() - $messages[$i + 1]->getValue()->getPrecision());
|
||||
|
||||
$anotherWeightedMeanSum += $weights[$i]*$diff->getPrecisionMean()/$diff->getPrecision();
|
||||
}
|
||||
|
||||
$newPrecision = 1.0/$inverseOfNewPrecisionSum;
|
||||
$anotherNewPrecision = 1.0/$anotherInverseOfNewPrecisionSum;
|
||||
|
||||
$newPrecisionMean = $newPrecision*$weightedMeanSum;
|
||||
$anotherNewPrecisionMean = $anotherNewPrecision*$anotherWeightedMeanSum;
|
||||
|
||||
$newMessage = GaussianDistribution::fromPrecisionMean($newPrecisionMean, $newPrecision);
|
||||
$oldMarginalWithoutMessage = GaussianDistribution::divide($marginal0, $message0);
|
||||
|
||||
$newMarginal = GaussianDistribution::multiply($oldMarginalWithoutMessage, $newMessage);
|
||||
|
||||
// Update the message and marginal
|
||||
|
||||
$messages[0]->setValue($newMessage);
|
||||
$variables[0]->setValue($newMarginal);
|
||||
|
||||
// Return the difference in the new marginal
|
||||
$finalDiff = GaussianDistribution::subtract($newMarginal, $marginal0);
|
||||
return $finalDiff;
|
||||
}
|
||||
|
||||
public function updateMessageIndex($messageIndex)
|
||||
{
|
||||
$allMessages = &$this->getMessages();
|
||||
$allVariables = &$this->getVariables();
|
||||
|
||||
Guard::argumentIsValidIndex($messageIndex, count($allMessages), "messageIndex");
|
||||
|
||||
$updatedMessages = array();
|
||||
$updatedVariables = array();
|
||||
|
||||
$indicesToUse = &$this->_variableIndexOrdersForWeights[$messageIndex];
|
||||
|
||||
// The tricky part here is that we have to put the messages and variables in the same
|
||||
// order as the weights. Thankfully, the weights and messages share the same index numbers,
|
||||
// so we just need to make sure they're consistent
|
||||
$allMessagesCount = count($allMessages);
|
||||
for ($i = 0; $i < $allMessagesCount; $i++)
|
||||
{
|
||||
$updatedMessages[] = &$allMessages[$indicesToUse[$i]];
|
||||
$updatedVariables[] = &$allVariables[$indicesToUse[$i]];
|
||||
}
|
||||
|
||||
return $this->updateHelper($this->_weights[$messageIndex],
|
||||
$this->_weightsSquared[$messageIndex],
|
||||
$updatedMessages,
|
||||
$updatedVariables);
|
||||
}
|
||||
|
||||
private static function createName($sumVariable, $variablesToSum, $weights)
|
||||
{
|
||||
// TODO: Perf? Use PHP equivalent of StringBuilder? implode on arrays?
|
||||
$result = (string)$sumVariable;
|
||||
$result .= ' = ';
|
||||
|
||||
$totalVars = count($variablesToSum);
|
||||
for($i = 0; $i < $totalVars; $i++)
|
||||
{
|
||||
$isFirst = ($i == 0);
|
||||
|
||||
if($isFirst && ($weights[$i] < 0))
|
||||
{
|
||||
$result .= '-';
|
||||
}
|
||||
|
||||
$absValue = sprintf("%.2f", \abs($weights[$i])); // 0.00?
|
||||
$result .= $absValue;
|
||||
$result .= "*[";
|
||||
$result .= (string)$variablesToSum[$i];
|
||||
$result .= ']';
|
||||
|
||||
$isLast = ($i == ($totalVars - 1));
|
||||
|
||||
if(!$isLast)
|
||||
{
|
||||
if($weights[$i + 1] >= 0)
|
||||
{
|
||||
$result .= ' + ';
|
||||
}
|
||||
else
|
||||
{
|
||||
$result .= ' - ';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
84
Skills/TrueSkill/Factors/GaussianWithinFactor.php
Normal file
84
Skills/TrueSkill/Factors/GaussianWithinFactor.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Factors;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../TruncatedGaussianCorrectionFunctions.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/GaussianDistribution.php");
|
||||
require_once(dirname(__FILE__) . "/GaussianFactor.php");
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
|
||||
use Moserware\Skills\FactorGraphs\Message;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
|
||||
/**
|
||||
* Factor representing a team difference that has not exceeded the draw margin.
|
||||
*
|
||||
* See the accompanying math paper for more details.
|
||||
*/
|
||||
class GaussianWithinFactor extends GaussianFactor
|
||||
{
|
||||
private $_epsilon;
|
||||
|
||||
public function __construct($epsilon, Variable &$variable)
|
||||
{
|
||||
parent::__construct(sprintf("%s <= %.2f", $variable, $epsilon));
|
||||
$this->_epsilon = $epsilon;
|
||||
$this->createVariableToMessageBinding($variable);
|
||||
}
|
||||
|
||||
public function getLogNormalization()
|
||||
{
|
||||
$variables = &$this->getVariables();
|
||||
$marginal = &$variables[0]->getValue();
|
||||
|
||||
$messages = &$this->getMessages();
|
||||
$message = &$messages[0]->getValue();
|
||||
$messageFromVariable = GaussianDistribution::divide($marginal, $message);
|
||||
$mean = $messageFromVariable->getMean();
|
||||
$std = $messageFromVariable->getStandardDeviation();
|
||||
$z = GaussianDistribution::cumulativeTo(($this->_epsilon - $mean)/$std)
|
||||
-
|
||||
GaussianDistribution::cumulativeTo((-$this->_epsilon - $mean)/$std);
|
||||
|
||||
return -GaussianDistribution::logProductNormalization($messageFromVariable, $message) + log($z);
|
||||
}
|
||||
|
||||
protected function updateMessageVariable(Message &$message, Variable &$variable)
|
||||
{
|
||||
$oldMarginal = clone $variable->getValue();
|
||||
$oldMessage = clone $message->getValue();
|
||||
$messageFromVariable = GaussianDistribution::divide($oldMarginal, $oldMessage);
|
||||
|
||||
$c = $messageFromVariable->getPrecision();
|
||||
$d = $messageFromVariable->getPrecisionMean();
|
||||
|
||||
$sqrtC = sqrt($c);
|
||||
$dOnSqrtC = $d/$sqrtC;
|
||||
|
||||
$epsilonTimesSqrtC = $this->_epsilon*$sqrtC;
|
||||
$d = $messageFromVariable->getPrecisionMean();
|
||||
|
||||
$denominator = 1.0 - TruncatedGaussianCorrectionFunctions::wWithinMargin($dOnSqrtC, $epsilonTimesSqrtC);
|
||||
$newPrecision = $c/$denominator;
|
||||
$newPrecisionMean = ($d +
|
||||
$sqrtC*
|
||||
TruncatedGaussianCorrectionFunctions::vWithinMargin($dOnSqrtC, $epsilonTimesSqrtC))/
|
||||
$denominator;
|
||||
|
||||
$newMarginal = GaussianDistribution::fromPrecisionMean($newPrecisionMean, $newPrecision);
|
||||
$newMessage = GaussianDistribution::divide(
|
||||
GaussianDistribution::multiply($oldMessage, $newMarginal),
|
||||
$oldMarginal);
|
||||
|
||||
// Update the message and marginal
|
||||
$message->setValue($newMessage);
|
||||
$variable->setValue($newMarginal);
|
||||
|
||||
// Return the difference in the new marginal
|
||||
return GaussianDistribution::subtract($newMarginal, $oldMarginal);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
189
Skills/TrueSkill/Layers/IteratedTeamDifferencesInnerLayer.php
Normal file
189
Skills/TrueSkill/Layers/IteratedTeamDifferencesInnerLayer.php
Normal file
@ -0,0 +1,189 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Schedule.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
require_once(dirname(__FILE__) . "/TeamPerformancesToTeamPerformanceDifferencesLayer.php");
|
||||
require_once(dirname(__FILE__) . "/TeamDifferencesComparisonLayer.php");
|
||||
|
||||
use Moserware\Skills\FactorGraphs\ScheduleLoop;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleSequence;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleStep;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
|
||||
// The whole purpose of this is to do a loop on the bottom
|
||||
class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
private $_TeamDifferencesComparisonLayer;
|
||||
private $_TeamPerformancesToTeamPerformanceDifferencesLayer;
|
||||
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph,
|
||||
TeamPerformancesToTeamPerformanceDifferencesLayer &$teamPerformancesToPerformanceDifferences,
|
||||
TeamDifferencesComparisonLayer &$teamDifferencesComparisonLayer)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
$this->_TeamPerformancesToTeamPerformanceDifferencesLayer = $teamPerformancesToPerformanceDifferences;
|
||||
$this->_TeamDifferencesComparisonLayer = $teamDifferencesComparisonLayer;
|
||||
}
|
||||
|
||||
public function &getLocalFactors()
|
||||
{
|
||||
$localFactors =
|
||||
\array_merge($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors(),
|
||||
$this->_TeamDifferencesComparisonLayer->getLocalFactors());
|
||||
return $localFactors;
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$inputVariablesGroups = &$this->getInputVariablesGroups();
|
||||
$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->setInputVariablesGroups($inputVariablesGroups);
|
||||
$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->buildLayer();
|
||||
|
||||
$teamDifferencesOutputVariablesGroups = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getOutputVariablesGroups();
|
||||
$this->_TeamDifferencesComparisonLayer->setInputVariablesGroups($teamDifferencesOutputVariablesGroups);
|
||||
$this->_TeamDifferencesComparisonLayer->buildLayer();
|
||||
}
|
||||
|
||||
public function createPriorSchedule()
|
||||
{
|
||||
switch (count($this->getInputVariablesGroups()))
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
throw new InvalidOperationException();
|
||||
case 2:
|
||||
$loop = $this->createTwoTeamInnerPriorLoopSchedule();
|
||||
break;
|
||||
default:
|
||||
$loop = $this->createMultipleTeamInnerPriorLoopSchedule();
|
||||
break;
|
||||
}
|
||||
|
||||
// When dealing with differences, there are always (n-1) differences, so add in the 1
|
||||
$totalTeamDifferences = count($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors());
|
||||
$totalTeams = $totalTeamDifferences + 1;
|
||||
|
||||
$localFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
|
||||
|
||||
$firstDifferencesFactor = &$localFactors[0];
|
||||
$lastDifferencesFactor = &$localFactors[$totalTeamDifferences - 1];
|
||||
$innerSchedule = new ScheduleSequence(
|
||||
"inner schedule",
|
||||
array(
|
||||
$loop,
|
||||
new ScheduleStep(
|
||||
"teamPerformanceToPerformanceDifferenceFactors[0] @ 1",
|
||||
$firstDifferencesFactor, 1),
|
||||
new ScheduleStep(
|
||||
sprintf("teamPerformanceToPerformanceDifferenceFactors[teamTeamDifferences = %d - 1] @ 2", $totalTeamDifferences),
|
||||
$lastDifferencesFactor, 2)
|
||||
)
|
||||
);
|
||||
|
||||
return $innerSchedule;
|
||||
}
|
||||
|
||||
private function createTwoTeamInnerPriorLoopSchedule()
|
||||
{
|
||||
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
|
||||
$teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors();
|
||||
|
||||
$firstPerfToTeamDiff = &$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[0];
|
||||
$firstTeamDiffComparison = &$teamDifferencesComparisonLayerLocalFactors[0];
|
||||
$itemsToSequence = array(
|
||||
new ScheduleStep(
|
||||
"send team perf to perf differences",
|
||||
$firstPerfToTeamDiff,
|
||||
0),
|
||||
new ScheduleStep(
|
||||
"send to greater than or within factor",
|
||||
$firstTeamDiffComparison,
|
||||
0)
|
||||
);
|
||||
|
||||
return $this->scheduleSequence(
|
||||
$itemsToSequence,
|
||||
"loop of just two teams inner sequence");
|
||||
}
|
||||
|
||||
private function createMultipleTeamInnerPriorLoopSchedule()
|
||||
{
|
||||
$totalTeamDifferences = count($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors());
|
||||
|
||||
$forwardScheduleList = array();
|
||||
|
||||
for ($i = 0; $i < $totalTeamDifferences - 1; $i++)
|
||||
{
|
||||
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
|
||||
$teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors();
|
||||
|
||||
$currentTeamPerfToTeamPerfDiff = &$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[$i];
|
||||
$currentTeamDiffComparison = &$teamDifferencesComparisonLayerLocalFactors[$i];
|
||||
|
||||
$currentForwardSchedulePiece =
|
||||
$this->scheduleSequence(
|
||||
array(
|
||||
new ScheduleStep(
|
||||
sprintf("team perf to perf diff %d", $i),
|
||||
$currentTeamPerfToTeamPerfDiff, 0),
|
||||
new ScheduleStep(
|
||||
sprintf("greater than or within result factor %d", $i),
|
||||
$currentTeamDiffComparison, 0),
|
||||
new ScheduleStep(
|
||||
sprintf("team perf to perf diff factors [%d], 2", $i),
|
||||
$currentTeamPerfToTeamPerfDiff, 2)
|
||||
), sprintf("current forward schedule piece %d", $i));
|
||||
|
||||
$forwardScheduleList[] = $currentForwardSchedulePiece;
|
||||
}
|
||||
|
||||
$forwardSchedule = new ScheduleSequence("forward schedule", $forwardScheduleList);
|
||||
|
||||
$backwardScheduleList = array();
|
||||
|
||||
for ($i = 0; $i < $totalTeamDifferences - 1; $i++)
|
||||
{
|
||||
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
|
||||
$teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors();
|
||||
|
||||
$differencesFactor = &$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[$totalTeamDifferences - 1 - $i];
|
||||
$comparisonFactor = &$teamDifferencesComparisonLayerLocalFactors[$totalTeamDifferences - 1 - $i];
|
||||
$performancesToDifferencesFactor = &$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[$totalTeamDifferences - 1 - $i];
|
||||
|
||||
$currentBackwardSchedulePiece = new ScheduleSequence(
|
||||
"current backward schedule piece",
|
||||
array(
|
||||
new ScheduleStep(
|
||||
sprintf("teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 0", $i),
|
||||
$differencesFactor, 0),
|
||||
new ScheduleStep(
|
||||
sprintf("greaterThanOrWithinResultFactors[totalTeamDifferences - 1 - %d] @ 0", $i),
|
||||
$comparisonFactor, 0),
|
||||
new ScheduleStep(
|
||||
sprintf("teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 1", $i),
|
||||
$performancesToDifferencesFactor, 1)
|
||||
));
|
||||
$backwardScheduleList[] = $currentBackwardSchedulePiece;
|
||||
}
|
||||
|
||||
$backwardSchedule = new ScheduleSequence("backward schedule", $backwardScheduleList);
|
||||
|
||||
$forwardBackwardScheduleToLoop =
|
||||
new ScheduleSequence(
|
||||
"forward Backward Schedule To Loop",
|
||||
array($forwardSchedule, $backwardSchedule));
|
||||
|
||||
$initialMaxDelta = 0.0001;
|
||||
|
||||
$loop = new ScheduleLoop(
|
||||
sprintf("loop with max delta of %f", $initialMaxDelta),
|
||||
$forwardBackwardScheduleToLoop,
|
||||
$initialMaxDelta);
|
||||
|
||||
return $loop;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@ -0,0 +1,106 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../PartialPlay.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Schedule.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianWeightedSumFactor.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
require_once(dirname(__FILE__) . "/TeamPerformancesToTeamPerformanceDifferencesLayer.php");
|
||||
require_once(dirname(__FILE__) . "/TeamDifferencesComparisonLayer.php");
|
||||
|
||||
use Moserware\Skills\PartialPlay;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleLoop;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleSequence;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleStep;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianWeightedSumFactor;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
|
||||
class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$inputVariablesGroups = &$this->getInputVariablesGroups();
|
||||
foreach ($inputVariablesGroups as &$currentTeam)
|
||||
{
|
||||
$localCurrentTeam = &$currentTeam;
|
||||
$teamPerformance = &$this->createOutputVariable($localCurrentTeam);
|
||||
$newSumFactor = $this->createPlayerToTeamSumFactor($localCurrentTeam, $teamPerformance);
|
||||
|
||||
$this->addLayerFactor($newSumFactor);
|
||||
|
||||
// REVIEW: Does it make sense to have groups of one?
|
||||
$outputVariablesGroups = &$this->getOutputVariablesGroups();
|
||||
$outputVariablesGroups[] = array($teamPerformance);
|
||||
}
|
||||
}
|
||||
|
||||
public function createPriorSchedule()
|
||||
{
|
||||
$localFactors = &$this->getLocalFactors();
|
||||
|
||||
$sequence = &$this->scheduleSequence(
|
||||
array_map(
|
||||
function($weightedSumFactor)
|
||||
{
|
||||
return new ScheduleStep("Perf to Team Perf Step", $weightedSumFactor, 0);
|
||||
},
|
||||
$localFactors),
|
||||
"all player perf to team perf schedule");
|
||||
return $sequence;
|
||||
}
|
||||
|
||||
protected function createPlayerToTeamSumFactor(&$teamMembers, &$sumVariable)
|
||||
{
|
||||
$weights = array_map(
|
||||
function($v)
|
||||
{
|
||||
$player = &$v->getKey();
|
||||
return PartialPlay::getPartialPlayPercentage($player);
|
||||
},
|
||||
$teamMembers);
|
||||
|
||||
return new GaussianWeightedSumFactor(
|
||||
$sumVariable,
|
||||
$teamMembers,
|
||||
$weights);
|
||||
|
||||
}
|
||||
|
||||
public function createPosteriorSchedule()
|
||||
{
|
||||
$allFactors = array();
|
||||
$localFactors = &$this->getLocalFactors();
|
||||
foreach($localFactors as &$currentFactor)
|
||||
{
|
||||
$localCurrentFactor = &$currentFactor;
|
||||
$numberOfMessages = $localCurrentFactor->getNumberOfMessages();
|
||||
for($currentIteration = 1; $currentIteration < $numberOfMessages; $currentIteration++)
|
||||
{
|
||||
$allFactors[] = new ScheduleStep("team sum perf @" . $currentIteration,
|
||||
$localCurrentFactor, $currentIteration);
|
||||
}
|
||||
}
|
||||
return $this->scheduleSequence($allFactors, "all of the team's sum iterations");
|
||||
}
|
||||
|
||||
private function &createOutputVariable(&$team)
|
||||
{
|
||||
$memberNames = \array_map(function ($currentPlayer)
|
||||
{
|
||||
return (string)($currentPlayer->getKey());
|
||||
},
|
||||
$team);
|
||||
|
||||
$teamMemberNames = \join(", ", $memberNames);
|
||||
$outputVariable = &$this->getParentFactorGraph()->getVariableFactory()->createBasicVariable("Team[" . $teamMemberNames . "]'s performance");
|
||||
return $outputVariable;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
87
Skills/TrueSkill/Layers/PlayerPriorValuesToSkillsLayer.php
Normal file
87
Skills/TrueSkill/Layers/PlayerPriorValuesToSkillsLayer.php
Normal file
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../Rating.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Schedule.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/BasicMath.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianPriorFactor.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
|
||||
use Moserware\Skills\Rating;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleLoop;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleSequence;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleStep;
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianPriorFactor;
|
||||
|
||||
// We intentionally have no Posterior schedule since the only purpose here is to
|
||||
// start the process.
|
||||
class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
private $_teams;
|
||||
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph, array &$teams)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
$this->_teams = $teams;
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$teams = &$this->_teams;
|
||||
foreach ($teams as &$currentTeam)
|
||||
{
|
||||
$localCurrentTeam = &$currentTeam;
|
||||
$currentTeamSkills = array();
|
||||
|
||||
$currentTeamAllPlayers = $localCurrentTeam->getAllPlayers();
|
||||
foreach ($currentTeamAllPlayers as &$currentTeamPlayer)
|
||||
{
|
||||
$localCurrentTeamPlayer = &$currentTeamPlayer;
|
||||
$currentTeamPlayerRating = $currentTeam->getRating($localCurrentTeamPlayer);
|
||||
$playerSkill = &$this->createSkillOutputVariable($localCurrentTeamPlayer);
|
||||
$priorFactor = &$this->createPriorFactor($localCurrentTeamPlayer, $currentTeamPlayerRating, $playerSkill);
|
||||
$this->addLayerFactor($priorFactor);
|
||||
$currentTeamSkills[] = $playerSkill;
|
||||
}
|
||||
|
||||
$outputVariablesGroups = &$this->getOutputVariablesGroups();
|
||||
$outputVariablesGroups[] = $currentTeamSkills;
|
||||
}
|
||||
}
|
||||
|
||||
public function createPriorSchedule()
|
||||
{
|
||||
$localFactors = &$this->getLocalFactors();
|
||||
return $this->scheduleSequence(
|
||||
array_map(
|
||||
function(&$prior)
|
||||
{
|
||||
return new ScheduleStep("Prior to Skill Step", $prior, 0);
|
||||
},
|
||||
$localFactors),
|
||||
"All priors");
|
||||
}
|
||||
|
||||
private function createPriorFactor(&$player, Rating &$priorRating, Variable &$skillsVariable)
|
||||
{
|
||||
return new GaussianPriorFactor($priorRating->getMean(),
|
||||
square($priorRating->getStandardDeviation()) +
|
||||
square($this->getParentFactorGraph()->getGameInfo()->getDynamicsFactor()),
|
||||
$skillsVariable);
|
||||
}
|
||||
|
||||
private function &createSkillOutputVariable(&$key)
|
||||
{
|
||||
$parentFactorGraph = &$this->getParentFactorGraph();
|
||||
$variableFactory = &$parentFactorGraph->getVariableFactory();
|
||||
$skillOutputVariable = &$variableFactory->createKeyedVariable($key, $key . "'s skill");
|
||||
return $skillOutputVariable;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
84
Skills/TrueSkill/Layers/PlayerSkillsToPerformancesLayer.php
Normal file
84
Skills/TrueSkill/Layers/PlayerSkillsToPerformancesLayer.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Schedule.php");
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../../Numerics/BasicMath.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianLikelihoodFactor.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
|
||||
use Moserware\Skills\FactorGraphs\ScheduleStep;
|
||||
use Moserware\Skills\FactorGraphs\KeyedVariable;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianLikelihoodFactor;
|
||||
|
||||
class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$inputVariablesGroups = &$this->getInputVariablesGroups();
|
||||
$outputVariablesGroups = &$this->getOutputVariablesGroups();
|
||||
|
||||
foreach ($inputVariablesGroups as &$currentTeam)
|
||||
{
|
||||
$currentTeamPlayerPerformances = array();
|
||||
|
||||
foreach ($currentTeam as &$playerSkillVariable)
|
||||
{
|
||||
$localPlayerSkillVariable = &$playerSkillVariable;
|
||||
$currentPlayer = &$localPlayerSkillVariable->getKey();
|
||||
$playerPerformance = &$this->createOutputVariable($currentPlayer);
|
||||
$newLikelihoodFactor = $this->createLikelihood($localPlayerSkillVariable, $playerPerformance);
|
||||
$this->addLayerFactor($newLikelihoodFactor);
|
||||
$currentTeamPlayerPerformances[] = $playerPerformance;
|
||||
}
|
||||
|
||||
$outputVariablesGroups[] = $currentTeamPlayerPerformances;
|
||||
}
|
||||
}
|
||||
|
||||
private function createLikelihood(KeyedVariable &$playerSkill, KeyedVariable &$playerPerformance)
|
||||
{
|
||||
return new GaussianLikelihoodFactor(square($this->getParentFactorGraph()->getGameInfo()->getBeta()), $playerPerformance, $playerSkill);
|
||||
}
|
||||
|
||||
private function &createOutputVariable(&$key)
|
||||
{
|
||||
$outputVariable = &$this->getParentFactorGraph()->getVariableFactory()->createKeyedVariable($key, $key . "'s performance");
|
||||
return $outputVariable;
|
||||
}
|
||||
|
||||
public function createPriorSchedule()
|
||||
{
|
||||
$localFactors = &$this->getLocalFactors();
|
||||
return $this->scheduleSequence(
|
||||
array_map(
|
||||
function($likelihood)
|
||||
{
|
||||
return new ScheduleStep("Skill to Perf step", $likelihood, 0);
|
||||
},
|
||||
$localFactors),
|
||||
"All skill to performance sending");
|
||||
}
|
||||
|
||||
public function createPosteriorSchedule()
|
||||
{
|
||||
$localFactors = &$this->getLocalFactors();
|
||||
return $this->scheduleSequence(
|
||||
array_map(
|
||||
function($likelihood)
|
||||
{
|
||||
return new ScheduleStep("name", $likelihood, 1);
|
||||
},
|
||||
$localFactors),
|
||||
"All skill to performance sending");
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
48
Skills/TrueSkill/Layers/TeamDifferencesComparisonLayer.php
Normal file
48
Skills/TrueSkill/Layers/TeamDifferencesComparisonLayer.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../DrawMargin.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianGreaterThanFactor.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianWithinFactor.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
|
||||
use Moserware\Skills\TrueSkill\DrawMargin;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianGreaterThanFactor;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianWithinFactor;
|
||||
|
||||
class TeamDifferencesComparisonLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
private $_epsilon;
|
||||
private $_teamRanks;
|
||||
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph, array &$teamRanks)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
$this->_teamRanks = $teamRanks;
|
||||
$gameInfo = &$this->getParentFactorGraph()->getGameInfo();
|
||||
$this->_epsilon = DrawMargin::getDrawMarginFromDrawProbability($gameInfo->getDrawProbability(), $gameInfo->getBeta());
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$inputVarGroups = &$this->getInputVariablesGroups();
|
||||
$inputVarGroupsCount = count($inputVarGroups);
|
||||
|
||||
for ($i = 0; $i < $inputVarGroupsCount; $i++)
|
||||
{
|
||||
$isDraw = ($this->_teamRanks[$i] == $this->_teamRanks[$i + 1]);
|
||||
$teamDifference = &$inputVarGroups[$i][0];
|
||||
|
||||
$factor =
|
||||
$isDraw
|
||||
? new GaussianWithinFactor($this->_epsilon, $teamDifference)
|
||||
: new GaussianGreaterThanFactor($this->_epsilon, $teamDifference);
|
||||
|
||||
$this->addLayerFactor($factor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@ -0,0 +1,56 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/Variable.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
require_once(dirname(__FILE__) . "/../Factors/GaussianWeightedSumFactor.php");
|
||||
require_once(dirname(__FILE__) . "/TrueSkillFactorGraphLayer.php");
|
||||
|
||||
use Moserware\Skills\FactorGraphs\Variable;
|
||||
use Moserware\Skills\TrueSkill\DrawMargin;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
use Moserware\Skills\TrueSkill\Factors\GaussianWeightedSumFactor;
|
||||
|
||||
class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorGraphLayer
|
||||
{
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
}
|
||||
|
||||
public function buildLayer()
|
||||
{
|
||||
$inputVariablesGroups = &$this->getInputVariablesGroups();
|
||||
$inputVariablesGroupsCount = count($inputVariablesGroups);
|
||||
$outputVariablesGroup = &$this->getOutputVariablesGroups();
|
||||
|
||||
for ($i = 0; $i < $inputVariablesGroupsCount - 1; $i++)
|
||||
{
|
||||
$strongerTeam = &$inputVariablesGroups[$i][0];
|
||||
$weakerTeam = &$inputVariablesGroups[$i + 1][0];
|
||||
|
||||
$currentDifference = &$this->createOutputVariable();
|
||||
$newDifferencesFactor = $this->createTeamPerformanceToDifferenceFactor($strongerTeam, $weakerTeam, $currentDifference);
|
||||
$this->addLayerFactor($newDifferencesFactor);
|
||||
|
||||
// REVIEW: Does it make sense to have groups of one?
|
||||
$outputVariablesGroup[] = array($currentDifference);
|
||||
}
|
||||
}
|
||||
|
||||
private function createTeamPerformanceToDifferenceFactor(
|
||||
Variable &$strongerTeam, Variable &$weakerTeam, Variable &$output)
|
||||
{
|
||||
$teams = array($strongerTeam, $weakerTeam);
|
||||
$weights = array(1.0, -1.0);
|
||||
return new GaussianWeightedSumFactor($output, $teams, $weights);
|
||||
}
|
||||
|
||||
private function &createOutputVariable()
|
||||
{
|
||||
$outputVariable = &$this->getParentFactorGraph()->getVariableFactory()->createBasicVariable("Team performance difference");
|
||||
return $outputVariable;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
18
Skills/TrueSkill/Layers/TrueSkillFactorGraphLayer.php
Normal file
18
Skills/TrueSkill/Layers/TrueSkillFactorGraphLayer.php
Normal file
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill\Layers;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../../FactorGraphs/FactorGraphLayer.php");
|
||||
require_once(dirname(__FILE__) . "/../TrueSkillFactorGraph.php");
|
||||
|
||||
use Moserware\Skills\FactorGraphs\FactorGraphLayer;
|
||||
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
|
||||
|
||||
abstract class TrueSkillFactorGraphLayer extends FactorGraphLayer
|
||||
{
|
||||
public function __construct(TrueSkillFactorGraph &$parentGraph)
|
||||
{
|
||||
parent::__construct($parentGraph);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
159
Skills/TrueSkill/TrueSkillFactorGraph.php
Normal file
159
Skills/TrueSkill/TrueSkillFactorGraph.php
Normal file
@ -0,0 +1,159 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . '/../GameInfo.php');
|
||||
require_once(dirname(__FILE__) . '/../Rating.php');
|
||||
require_once(dirname(__FILE__) . '/../RatingContainer.php');
|
||||
require_once(dirname(__FILE__) . '/../FactorGraphs/FactorGraph.php');
|
||||
require_once(dirname(__FILE__) . '/../FactorGraphs/FactorList.php');
|
||||
require_once(dirname(__FILE__) . '/../FactorGraphs/Schedule.php');
|
||||
require_once(dirname(__FILE__) . '/../FactorGraphs/VariableFactory.php');
|
||||
require_once(dirname(__FILE__) . '/../Numerics/GaussianDistribution.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/IteratedTeamDifferencesInnerLayer.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/PlayerPerformancesToTeamPerformancesLayer.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/PlayerPriorValuesToSkillsLayer.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/PlayerSkillsToPerformancesLayer.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/TeamDifferencesComparisonLayer.php');
|
||||
require_once(dirname(__FILE__) . '/Layers/TeamPerformancesToTeamPerformanceDifferencesLayer.php');
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
use Moserware\Skills\GameInfo;
|
||||
use Moserware\Skills\Rating;
|
||||
use Moserware\Skills\RatingContainer;
|
||||
use Moserware\Skills\FactorGraphs\FactorGraph;
|
||||
use Moserware\Skills\FactorGraphs\FactorList;
|
||||
use Moserware\Skills\FactorGraphs\ScheduleSequence;
|
||||
use Moserware\Skills\FactorGraphs\VariableFactory;
|
||||
use Moserware\Skills\TrueSkill\Layers\IteratedTeamDifferencesInnerLayer;
|
||||
use Moserware\Skills\TrueSkill\Layers\PlayerPerformancesToTeamPerformancesLayer;
|
||||
use Moserware\Skills\TrueSkill\Layers\PlayerPriorValuesToSkillsLayer;
|
||||
use Moserware\Skills\TrueSkill\Layers\PlayerSkillsToPerformancesLayer;
|
||||
use Moserware\Skills\TrueSkill\Layers\TeamDifferencesComparisonLayer;
|
||||
use Moserware\Skills\TrueSkill\Layers\TeamPerformancesToTeamPerformanceDifferencesLayer;
|
||||
|
||||
class TrueSkillFactorGraph extends FactorGraph
|
||||
{
|
||||
private $_gameInfo;
|
||||
private $_layers;
|
||||
private $_priorLayer;
|
||||
|
||||
public function __construct(GameInfo &$gameInfo, array &$teams, array $teamRanks)
|
||||
{
|
||||
$this->_priorLayer = new PlayerPriorValuesToSkillsLayer($this, $teams);
|
||||
$this->_gameInfo = $gameInfo;
|
||||
$newFactory = new VariableFactory(
|
||||
function()
|
||||
{
|
||||
return GaussianDistribution::fromPrecisionMean(0, 0);
|
||||
});
|
||||
|
||||
$this->setVariableFactory($newFactory);
|
||||
$this->_layers = array(
|
||||
$this->_priorLayer,
|
||||
new PlayerSkillsToPerformancesLayer($this),
|
||||
new PlayerPerformancesToTeamPerformancesLayer($this),
|
||||
new IteratedTeamDifferencesInnerLayer(
|
||||
$this,
|
||||
new TeamPerformancesToTeamPerformanceDifferencesLayer($this),
|
||||
new TeamDifferencesComparisonLayer($this, $teamRanks))
|
||||
);
|
||||
}
|
||||
|
||||
public function getGameInfo()
|
||||
{
|
||||
return $this->_gameInfo;
|
||||
}
|
||||
|
||||
public function buildGraph()
|
||||
{
|
||||
$lastOutput = null;
|
||||
|
||||
$layers = &$this->_layers;
|
||||
foreach ($layers as &$currentLayer)
|
||||
{
|
||||
if ($lastOutput != null)
|
||||
{
|
||||
$currentLayer->setInputVariablesGroups($lastOutput);
|
||||
}
|
||||
|
||||
$currentLayer->buildLayer();
|
||||
|
||||
$lastOutput = &$currentLayer->getOutputVariablesGroups();
|
||||
}
|
||||
}
|
||||
|
||||
public function runSchedule()
|
||||
{
|
||||
$fullSchedule = $this->createFullSchedule();
|
||||
$fullScheduleDelta = $fullSchedule->visit();
|
||||
}
|
||||
|
||||
public function getProbabilityOfRanking()
|
||||
{
|
||||
$factorList = new FactorList();
|
||||
|
||||
$layers = &$this->_layers;
|
||||
foreach ($layers as &$currentLayer)
|
||||
{
|
||||
$localFactors = &$currentLayer->getLocalFactors();
|
||||
foreach ($localFactors as &$currentFactor)
|
||||
{
|
||||
$localCurrentFactor = &$currentFactor;
|
||||
$factorList->addFactor($localCurrentFactor);
|
||||
}
|
||||
}
|
||||
|
||||
$logZ = $factorList->getLogNormalization();
|
||||
return exp($logZ);
|
||||
}
|
||||
|
||||
private function createFullSchedule()
|
||||
{
|
||||
$fullSchedule = array();
|
||||
|
||||
$layers = &$this->_layers;
|
||||
foreach ($layers as &$currentLayer)
|
||||
{
|
||||
$currentPriorSchedule = $currentLayer->createPriorSchedule();
|
||||
if ($currentPriorSchedule != null)
|
||||
{
|
||||
$fullSchedule[] = $currentPriorSchedule;
|
||||
}
|
||||
}
|
||||
|
||||
$allLayersReverse = \array_reverse($this->_layers);
|
||||
|
||||
foreach ($allLayersReverse as &$currentLayer)
|
||||
{
|
||||
$currentPosteriorSchedule = $currentLayer->createPosteriorSchedule();
|
||||
if ($currentPosteriorSchedule != null)
|
||||
{
|
||||
$fullSchedule[] = $currentPosteriorSchedule;
|
||||
}
|
||||
}
|
||||
|
||||
return new ScheduleSequence("Full schedule", $fullSchedule);
|
||||
}
|
||||
|
||||
public function getUpdatedRatings()
|
||||
{
|
||||
$result = new RatingContainer();
|
||||
|
||||
$priorLayerOutputVariablesGroups = &$this->_priorLayer->getOutputVariablesGroups();
|
||||
foreach ($priorLayerOutputVariablesGroups as &$currentTeam)
|
||||
{
|
||||
foreach ($currentTeam as &$currentPlayer)
|
||||
{
|
||||
$localCurrentPlayer = &$currentPlayer->getKey();
|
||||
$newRating = new Rating($currentPlayer->getValue()->getMean(),
|
||||
$currentPlayer->getValue()->getStandardDeviation());
|
||||
|
||||
$result->setRating($localCurrentPlayer, $newRating);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
133
Skills/TrueSkill/TruncatedGaussianCorrectionFunctions.php
Normal file
133
Skills/TrueSkill/TruncatedGaussianCorrectionFunctions.php
Normal file
@ -0,0 +1,133 @@
|
||||
<?php
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . '/../Numerics/GaussianDistribution.php');
|
||||
|
||||
use Moserware\Numerics\GaussianDistribution;
|
||||
|
||||
class TruncatedGaussianCorrectionFunctions
|
||||
{
|
||||
// These functions from the bottom of page 4 of the TrueSkill paper.
|
||||
|
||||
/**
|
||||
* The "V" function where the team performance difference is greater than the draw margin.
|
||||
*
|
||||
* In the reference F# implementation, this is referred to as "the additive
|
||||
* correction of a single-sided truncated Gaussian with unit variance."
|
||||
*
|
||||
* @param number $drawMargin In the paper, it's referred to as just "ε".
|
||||
*/
|
||||
public static function vExceedsMarginScaled($teamPerformanceDifference, $drawMargin, $c)
|
||||
{
|
||||
return self::vExceedsMargin($teamPerformanceDifference/$c, $drawMargin/$c);
|
||||
}
|
||||
|
||||
public static function vExceedsMargin($teamPerformanceDifference, $drawMargin)
|
||||
{
|
||||
$denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin);
|
||||
|
||||
if ($denominator < 2.222758749e-162)
|
||||
{
|
||||
return -$teamPerformanceDifference + $drawMargin;
|
||||
}
|
||||
|
||||
return GaussianDistribution::at($teamPerformanceDifference - $drawMargin)/$denominator;
|
||||
}
|
||||
|
||||
/**
|
||||
* The "W" function where the team performance difference is greater than the draw margin.
|
||||
*
|
||||
* In the reference F# implementation, this is referred to as "the multiplicative
|
||||
* correction of a single-sided truncated Gaussian with unit variance."
|
||||
*/
|
||||
|
||||
public static function wExceedsMarginScaled($teamPerformanceDifference, $drawMargin, $c)
|
||||
{
|
||||
return self::wExceedsMargin($teamPerformanceDifference/$c, $drawMargin/$c);
|
||||
}
|
||||
|
||||
public static function wExceedsMargin($teamPerformanceDifference, $drawMargin)
|
||||
{
|
||||
$denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin);
|
||||
|
||||
if ($denominator < 2.222758749e-162)
|
||||
{
|
||||
if ($teamPerformanceDifference < 0.0)
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$vWin = self::vExceedsMargin($teamPerformanceDifference, $drawMargin);
|
||||
return $vWin*($vWin + $teamPerformanceDifference - $drawMargin);
|
||||
}
|
||||
|
||||
// the additive correction of a double-sided truncated Gaussian with unit variance
|
||||
public static function vWithinMarginScaled($teamPerformanceDifference, $drawMargin, $c)
|
||||
{
|
||||
return self::vWithinMargin($teamPerformanceDifference/$c, $drawMargin/$c);
|
||||
}
|
||||
|
||||
// from F#:
|
||||
public static function vWithinMargin($teamPerformanceDifference, $drawMargin)
|
||||
{
|
||||
$teamPerformanceDifferenceAbsoluteValue = abs($teamPerformanceDifference);
|
||||
$denominator =
|
||||
GaussianDistribution::cumulativeTo($drawMargin - $teamPerformanceDifferenceAbsoluteValue) -
|
||||
GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue);
|
||||
|
||||
if ($denominator < 2.222758749e-162)
|
||||
{
|
||||
if ($teamPerformanceDifference < 0.0)
|
||||
{
|
||||
return -$teamPerformanceDifference - $drawMargin;
|
||||
}
|
||||
|
||||
return -$teamPerformanceDifference + $drawMargin;
|
||||
}
|
||||
|
||||
$numerator = GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue) -
|
||||
GaussianDistribution::at($drawMargin - $teamPerformanceDifferenceAbsoluteValue);
|
||||
|
||||
if ($teamPerformanceDifference < 0.0)
|
||||
{
|
||||
return -$numerator/$denominator;
|
||||
}
|
||||
|
||||
return $numerator/$denominator;
|
||||
}
|
||||
|
||||
// the multiplicative correction of a double-sided truncated Gaussian with unit variance
|
||||
public static function wWithinMarginScaled($teamPerformanceDifference, $drawMargin, $c)
|
||||
{
|
||||
return self::wWithinMargin($teamPerformanceDifference/$c, $drawMargin/$c);
|
||||
}
|
||||
|
||||
// From F#:
|
||||
public static function wWithinMargin($teamPerformanceDifference, $drawMargin)
|
||||
{
|
||||
$teamPerformanceDifferenceAbsoluteValue = abs($teamPerformanceDifference);
|
||||
$denominator = GaussianDistribution::cumulativeTo($drawMargin - $teamPerformanceDifferenceAbsoluteValue)
|
||||
-
|
||||
GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue);
|
||||
|
||||
if ($denominator < 2.222758749e-162)
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
$vt = self::vWithinMargin($teamPerformanceDifferenceAbsoluteValue, $drawMargin);
|
||||
|
||||
return $vt*$vt +
|
||||
(
|
||||
($drawMargin - $teamPerformanceDifferenceAbsoluteValue)
|
||||
*
|
||||
GaussianDistribution::at(
|
||||
$drawMargin - $teamPerformanceDifferenceAbsoluteValue)
|
||||
- (-$drawMargin - $teamPerformanceDifferenceAbsoluteValue)
|
||||
*
|
||||
GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue))/$denominator;
|
||||
}
|
||||
}
|
||||
?>
|
181
Skills/TrueSkill/TwoPlayerTrueSkillCalculator.php
Normal file
181
Skills/TrueSkill/TwoPlayerTrueSkillCalculator.php
Normal file
@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../GameInfo.php");
|
||||
require_once(dirname(__FILE__) . "/../Guard.php");
|
||||
require_once(dirname(__FILE__) . "/../PairwiseComparison.php");
|
||||
require_once(dirname(__FILE__) . "/../RankSorter.php");
|
||||
require_once(dirname(__FILE__) . "/../Rating.php");
|
||||
require_once(dirname(__FILE__) . "/../RatingContainer.php");
|
||||
require_once(dirname(__FILE__) . "/../SkillCalculator.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/../PlayersRange.php");
|
||||
require_once(dirname(__FILE__) . "/../TeamsRange.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/../Numerics/BasicMath.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/DrawMargin.php");
|
||||
require_once(dirname(__FILE__) . "/TruncatedGaussianCorrectionFunctions.php");
|
||||
|
||||
use Moserware\Skills\GameInfo;
|
||||
use Moserware\Skills\Guard;
|
||||
use Moserware\Skills\PairwiseComparison;
|
||||
use Moserware\Skills\RankSorter;
|
||||
use Moserware\Skills\Rating;
|
||||
use Moserware\Skills\RatingContainer;
|
||||
use Moserware\Skills\SkillCalculator;
|
||||
use Moserware\Skills\SkillCalculatorSupportedOptions;
|
||||
|
||||
use Moserware\Skills\PlayersRange;
|
||||
use Moserware\Skills\TeamsRange;
|
||||
|
||||
/**
|
||||
* Calculates the new ratings for only two players.
|
||||
*
|
||||
* When you only have two players, a lot of the math simplifies. The main purpose of this class
|
||||
* is to show the bare minimum of what a TrueSkill implementation should have.
|
||||
*/
|
||||
|
||||
class TwoPlayerTrueSkillCalculator extends SkillCalculator
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(SkillCalculatorSupportedOptions::NONE, TeamsRange::exactly(2), PlayersRange::exactly(1));
|
||||
}
|
||||
|
||||
public function calculateNewRatings(GameInfo &$gameInfo,
|
||||
array $teams,
|
||||
array $teamRanks)
|
||||
{
|
||||
// Basic argument checking
|
||||
Guard::argumentNotNull($gameInfo, "gameInfo");
|
||||
$this->validateTeamCountAndPlayersCountPerTeam($teams);
|
||||
|
||||
// Make sure things are in order
|
||||
RankSorter::sort($teams, $teamRanks);
|
||||
|
||||
// Since we verified that each team has one player, we know the player is the first one
|
||||
$winningTeamPlayers = $teams[0]->getAllPlayers();
|
||||
$winner = $winningTeamPlayers[0];
|
||||
$winnerPreviousRating = $teams[0]->getRating($winner);
|
||||
|
||||
$losingTeamPlayers = $teams[1]->getAllPlayers();
|
||||
$loser = $losingTeamPlayers[0];
|
||||
$loserPreviousRating = $teams[1]->getRating($loser);
|
||||
|
||||
$wasDraw = ($teamRanks[0] == $teamRanks[1]);
|
||||
|
||||
$results = new RatingContainer();
|
||||
|
||||
$results->setRating($winner, self::calculateNewRating($gameInfo,
|
||||
$winnerPreviousRating,
|
||||
$loserPreviousRating,
|
||||
$wasDraw ? PairwiseComparison::DRAW
|
||||
: PairwiseComparison::WIN));
|
||||
|
||||
$results->setRating($loser, self::calculateNewRating($gameInfo,
|
||||
$loserPreviousRating,
|
||||
$winnerPreviousRating,
|
||||
$wasDraw ? PairwiseComparison::DRAW
|
||||
: PairwiseComparison::LOSE));
|
||||
|
||||
// And we're done!
|
||||
return $results;
|
||||
}
|
||||
|
||||
private static function calculateNewRating(GameInfo $gameInfo, Rating $selfRating, Rating $opponentRating, $comparison)
|
||||
{
|
||||
$drawMargin = DrawMargin::getDrawMarginFromDrawProbability($gameInfo->getDrawProbability(),
|
||||
$gameInfo->getBeta());
|
||||
|
||||
$c =
|
||||
sqrt(
|
||||
square($selfRating->getStandardDeviation())
|
||||
+
|
||||
square($opponentRating->getStandardDeviation())
|
||||
+
|
||||
2*square($gameInfo->getBeta()));
|
||||
|
||||
$winningMean = $selfRating->getMean();
|
||||
$losingMean = $opponentRating->getMean();
|
||||
|
||||
switch ($comparison)
|
||||
{
|
||||
case PairwiseComparison::WIN:
|
||||
case PairwiseComparison::DRAW:
|
||||
// NOP
|
||||
break;
|
||||
case PairwiseComparison::LOSE:
|
||||
$winningMean = $opponentRating->getMean();
|
||||
$losingMean = $selfRating->getMean();
|
||||
break;
|
||||
}
|
||||
|
||||
$meanDelta = $winningMean - $losingMean;
|
||||
|
||||
if ($comparison != PairwiseComparison::DRAW)
|
||||
{
|
||||
// non-draw case
|
||||
$v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$rankMultiplier = (int) $comparison;
|
||||
}
|
||||
else
|
||||
{
|
||||
$v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$w = TruncatedGaussianCorrectionFunctions::wWithinMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$rankMultiplier = 1;
|
||||
}
|
||||
|
||||
$meanMultiplier = (square($selfRating->getStandardDeviation()) + square($gameInfo->getDynamicsFactor()))/$c;
|
||||
|
||||
$varianceWithDynamics = square($selfRating->getStandardDeviation()) + square($gameInfo->getDynamicsFactor());
|
||||
$stdDevMultiplier = $varianceWithDynamics/square($c);
|
||||
|
||||
$newMean = $selfRating->getMean() + ($rankMultiplier*$meanMultiplier*$v);
|
||||
$newStdDev = sqrt($varianceWithDynamics*(1 - $w*$stdDevMultiplier));
|
||||
|
||||
return new Rating($newMean, $newStdDev);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc }
|
||||
*/
|
||||
public function calculateMatchQuality(GameInfo &$gameInfo, array &$teams)
|
||||
{
|
||||
Guard::argumentNotNull($gameInfo, "gameInfo");
|
||||
$this->validateTeamCountAndPlayersCountPerTeam($teams);
|
||||
|
||||
$team1 = $teams[0];
|
||||
$team2 = $teams[1];
|
||||
|
||||
$team1Ratings = $team1->getAllRatings();
|
||||
$team2Ratings = $team2->getAllRatings();
|
||||
|
||||
$player1Rating = $team1Ratings[0];
|
||||
$player2Rating = $team2Ratings[0];
|
||||
|
||||
// We just use equation 4.1 found on page 8 of the TrueSkill 2006 paper:
|
||||
$betaSquared = square($gameInfo->getBeta());
|
||||
$player1SigmaSquared = square($player1Rating->getStandardDeviation());
|
||||
$player2SigmaSquared = square($player2Rating->getStandardDeviation());
|
||||
|
||||
// This is the square root part of the equation:
|
||||
$sqrtPart =
|
||||
sqrt(
|
||||
(2*$betaSquared)
|
||||
/
|
||||
(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared));
|
||||
|
||||
// This is the exponent part of the equation:
|
||||
$expPart =
|
||||
exp(
|
||||
(-1*square($player1Rating->getMean() - $player2Rating->getMean()))
|
||||
/
|
||||
(2*(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared)));
|
||||
|
||||
return $sqrtPart*$expPart;
|
||||
}
|
||||
}
|
||||
?>
|
226
Skills/TrueSkill/TwoTeamTrueSkillCalculator.php
Normal file
226
Skills/TrueSkill/TwoTeamTrueSkillCalculator.php
Normal file
@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
namespace Moserware\Skills\TrueSkill;
|
||||
|
||||
require_once(dirname(__FILE__) . "/../GameInfo.php");
|
||||
require_once(dirname(__FILE__) . "/../Guard.php");
|
||||
require_once(dirname(__FILE__) . "/../PairwiseComparison.php");
|
||||
require_once(dirname(__FILE__) . "/../RankSorter.php");
|
||||
require_once(dirname(__FILE__) . "/../Rating.php");
|
||||
require_once(dirname(__FILE__) . "/../RatingContainer.php");
|
||||
require_once(dirname(__FILE__) . "/../SkillCalculator.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/../Team.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/../PlayersRange.php");
|
||||
require_once(dirname(__FILE__) . "/../TeamsRange.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/../Numerics/BasicMath.php");
|
||||
|
||||
require_once(dirname(__FILE__) . "/DrawMargin.php");
|
||||
require_once(dirname(__FILE__) . "/TruncatedGaussianCorrectionFunctions.php");
|
||||
|
||||
use Moserware\Skills\GameInfo;
|
||||
use Moserware\Skills\Guard;
|
||||
use Moserware\Skills\PairwiseComparison;
|
||||
use Moserware\Skills\RankSorter;
|
||||
use Moserware\Skills\Rating;
|
||||
use Moserware\Skills\RatingContainer;
|
||||
use Moserware\Skills\SkillCalculator;
|
||||
use Moserware\Skills\SkillCalculatorSupportedOptions;
|
||||
|
||||
use Moserware\Skills\PlayersRange;
|
||||
use Moserware\Skills\TeamsRange;
|
||||
|
||||
use Moserware\Skills\Team;
|
||||
|
||||
/**
|
||||
* Calculates new ratings for only two teams where each team has 1 or more players.
|
||||
*
|
||||
* When you only have two teams, the math is still simple: no factor graphs are used yet.
|
||||
*/
|
||||
class TwoTeamTrueSkillCalculator extends SkillCalculator
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(SkillCalculatorSupportedOptions::NONE, TeamsRange::exactly(2), PlayersRange::atLeast(1));
|
||||
}
|
||||
|
||||
public function calculateNewRatings(GameInfo &$gameInfo,
|
||||
array $teams,
|
||||
array $teamRanks)
|
||||
{
|
||||
Guard::argumentNotNull($gameInfo, "gameInfo");
|
||||
$this->validateTeamCountAndPlayersCountPerTeam($teams);
|
||||
|
||||
RankSorter::sort($teams, $teamRanks);
|
||||
|
||||
$team1 = $teams[0];
|
||||
$team2 = $teams[1];
|
||||
|
||||
$wasDraw = ($teamRanks[0] == $teamRanks[1]);
|
||||
|
||||
$results = new RatingContainer();
|
||||
|
||||
self::updatePlayerRatings($gameInfo,
|
||||
$results,
|
||||
$team1,
|
||||
$team2,
|
||||
$wasDraw ? PairwiseComparison::DRAW : PairwiseComparison::WIN);
|
||||
|
||||
self::updatePlayerRatings($gameInfo,
|
||||
$results,
|
||||
$team2,
|
||||
$team1,
|
||||
$wasDraw ? PairwiseComparison::DRAW : PairwiseComparison::LOSE);
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
private static function updatePlayerRatings(GameInfo $gameInfo,
|
||||
RatingContainer &$newPlayerRatings,
|
||||
Team $selfTeam,
|
||||
Team $otherTeam,
|
||||
$selfToOtherTeamComparison)
|
||||
{
|
||||
$drawMargin = DrawMargin::getDrawMarginFromDrawProbability($gameInfo->getDrawProbability(),
|
||||
$gameInfo->getBeta());
|
||||
|
||||
$betaSquared = square($gameInfo->getBeta());
|
||||
$tauSquared = square($gameInfo->getDynamicsFactor());
|
||||
|
||||
$totalPlayers = $selfTeam->count() + $otherTeam->count();
|
||||
|
||||
$meanGetter =
|
||||
function($currentRating)
|
||||
{
|
||||
return $currentRating->getMean();
|
||||
};
|
||||
|
||||
$selfMeanSum = sum($selfTeam->getAllRatings(), $meanGetter);
|
||||
$otherTeamMeanSum = sum($otherTeam->getAllRatings(), $meanGetter);
|
||||
|
||||
$varianceGetter =
|
||||
function($currentRating)
|
||||
{
|
||||
return square($currentRating->getStandardDeviation());
|
||||
};
|
||||
|
||||
$c = sqrt(
|
||||
sum($selfTeam->getAllRatings(), $varianceGetter)
|
||||
+
|
||||
sum($otherTeam->getAllRatings(), $varianceGetter)
|
||||
+
|
||||
$totalPlayers*$betaSquared);
|
||||
|
||||
$winningMean = $selfMeanSum;
|
||||
$losingMean = $otherTeamMeanSum;
|
||||
|
||||
switch ($selfToOtherTeamComparison)
|
||||
{
|
||||
case PairwiseComparison::WIN:
|
||||
case PairwiseComparison::DRAW:
|
||||
// NOP
|
||||
break;
|
||||
case PairwiseComparison::LOSE:
|
||||
$winningMean = $otherTeamMeanSum;
|
||||
$losingMean = $selfMeanSum;
|
||||
break;
|
||||
}
|
||||
|
||||
$meanDelta = $winningMean - $losingMean;
|
||||
|
||||
if ($selfToOtherTeamComparison != PairwiseComparison::DRAW)
|
||||
{
|
||||
// non-draw case
|
||||
$v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$rankMultiplier = (int) $selfToOtherTeamComparison;
|
||||
}
|
||||
else
|
||||
{
|
||||
// assume draw
|
||||
$v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$w = TruncatedGaussianCorrectionFunctions::wWithinMarginScaled($meanDelta, $drawMargin, $c);
|
||||
$rankMultiplier = 1;
|
||||
}
|
||||
|
||||
$selfTeamAllPlayers = &$selfTeam->getAllPlayers();
|
||||
foreach ($selfTeamAllPlayers as &$selfTeamCurrentPlayer)
|
||||
{
|
||||
$localSelfTeamCurrentPlayer = &$selfTeamCurrentPlayer;
|
||||
$previousPlayerRating = $selfTeam->getRating($localSelfTeamCurrentPlayer);
|
||||
|
||||
$meanMultiplier = (square($previousPlayerRating->getStandardDeviation()) + $tauSquared)/$c;
|
||||
$stdDevMultiplier = (square($previousPlayerRating->getStandardDeviation()) + $tauSquared)/square($c);
|
||||
|
||||
$playerMeanDelta = ($rankMultiplier*$meanMultiplier*$v);
|
||||
$newMean = $previousPlayerRating->getMean() + $playerMeanDelta;
|
||||
|
||||
$newStdDev =
|
||||
sqrt((square($previousPlayerRating->getStandardDeviation()) + $tauSquared)*(1 - $w*$stdDevMultiplier));
|
||||
|
||||
$newPlayerRatings->setRating($localSelfTeamCurrentPlayer, new Rating($newMean, $newStdDev));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc }
|
||||
*/
|
||||
public function calculateMatchQuality(GameInfo &$gameInfo,
|
||||
array &$teams)
|
||||
{
|
||||
Guard::argumentNotNull($gameInfo, "gameInfo");
|
||||
$this->validateTeamCountAndPlayersCountPerTeam($teams);
|
||||
|
||||
// We've verified that there's just two teams
|
||||
$team1Ratings = $teams[0]->getAllRatings();
|
||||
$team1Count = count($team1Ratings);
|
||||
|
||||
$team2Ratings = $teams[1]->getAllRatings();
|
||||
$team2Count = count($team2Ratings);
|
||||
|
||||
$totalPlayers = $team1Count + $team2Count;
|
||||
|
||||
$betaSquared = square($gameInfo->getBeta());
|
||||
|
||||
$meanGetter =
|
||||
function($currentRating)
|
||||
{
|
||||
return $currentRating->getMean();
|
||||
};
|
||||
|
||||
$varianceGetter =
|
||||
function($currentRating)
|
||||
{
|
||||
return square($currentRating->getStandardDeviation());
|
||||
};
|
||||
|
||||
$team1MeanSum = sum($team1Ratings, $meanGetter);
|
||||
$team1StdDevSquared = sum($team1Ratings, $varianceGetter);
|
||||
|
||||
$team2MeanSum = sum($team2Ratings, $meanGetter);
|
||||
$team2SigmaSquared = sum($team2Ratings, $varianceGetter);
|
||||
|
||||
// This comes from equation 4.1 in the TrueSkill paper on page 8
|
||||
// The equation was broken up into the part under the square root sign and
|
||||
// the exponential part to make the code easier to read.
|
||||
|
||||
$sqrtPart
|
||||
= sqrt(
|
||||
($totalPlayers*$betaSquared)
|
||||
/
|
||||
($totalPlayers*$betaSquared + $team1StdDevSquared + $team2SigmaSquared)
|
||||
);
|
||||
|
||||
$expPart
|
||||
= exp(
|
||||
(-1*square($team1MeanSum - $team2MeanSum))
|
||||
/
|
||||
(2*($totalPlayers*$betaSquared + $team1StdDevSquared + $team2SigmaSquared))
|
||||
);
|
||||
|
||||
return $expPart*$sqrtPart;
|
||||
}
|
||||
}
|
||||
?>
|
Reference in New Issue
Block a user