Moved UnitTests to tests/ and Skills to src/

This commit is contained in:
Alexander Liljengård
2016-05-24 13:53:56 +02:00
parent 11b5033c8a
commit 4ab0c5d719
64 changed files with 0 additions and 0 deletions

19
src/Elo/EloRating.php Normal file
View File

@ -0,0 +1,19 @@
<?php
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . '/../Rating.php');
use Moserware\Skills\Rating;
/**
* An Elo rating represented by a single number (mean).
*/
class EloRating extends Rating
{
public function __construct($rating)
{
parent::__construct($rating, 0);
}
}
?>

View File

@ -0,0 +1,41 @@
<?php
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . "/FideKFactor.php");
require_once(dirname(__FILE__) . "/TwoPlayerEloCalculator.php");
/** Including Elo's scheme as a simple comparison.
* See http://en.wikipedia.org/wiki/Elo_rating_system#Theory
* for more details
*/
class FideEloCalculator extends TwoPlayerEloCalculator
{
public function __construct(FideKFactor $kFactor)
{
parent::__construct($kFactor);
}
public static function createWithDefaultKFactor()
{
return new FideEloCalculator(new FideKFactor());
}
public static function createWithProvisionalKFactor()
{
return new FideEloCalculator(new ProvisionalFideKFactor());
}
public function getPlayerWinProbability($gameInfo, $playerRating, $opponentRating)
{
$ratingDifference = $opponentRating - $playerRating;
return 1.0
/
(
1.0 + pow(10.0, $ratingDifference / (2 * $gameInfo->getBeta()))
);
}
}
?>

30
src/Elo/FideKFactor.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . "/KFactor.php");
// see http://ratings.fide.com/calculator_rtd.phtml for details
class FideKFactor extends KFactor
{
public function getValueForRating($rating)
{
if ($rating < 2400)
{
return 15;
}
return 10;
}
}
/**
* Indicates someone who has played less than 30 games.
*/
class ProvisionalFideKFactor extends FideKFactor
{
public function getValueForRating($rating)
{
return 25;
}
}
?>

View File

@ -0,0 +1,34 @@
<?php
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . "/../GameInfo.php");
require_once(dirname(__FILE__) . "/../Numerics/GaussianDistribution.php");
require_once(dirname(__FILE__) . "/KFactor.php");
require_once(dirname(__FILE__) . "/TwoPlayerEloCalculator.php");
use Moserware\Skills\GameInfo;
use Moserware\Numerics\GaussianDistribution;
class GaussianEloCalculator extends TwoPlayerEloCalculator
{
// From the paper
const STABLE_KFACTOR = 24;
public function __construct()
{
parent::__construct(new KFactor(self::STABLE_KFACTOR));
}
public function getPlayerWinProbability(GameInfo $gameInfo, $playerRating, $opponentRating)
{
$ratingDifference = $playerRating - $opponentRating;
// See equation 1.1 in the TrueSkill paper
return GaussianDistribution::cumulativeTo(
$ratingDifference
/
(sqrt(2) * $gameInfo->getBeta()));
}
}
?>

22
src/Elo/KFactor.php Normal file
View File

@ -0,0 +1,22 @@
<?php
namespace Moserware\Skills\Elo;
class KFactor
{
const DEFAULT_KFACTOR = 24;
private $_value;
public function __construct($exactKFactor = self::DEFAULT_KFACTOR)
{
$this->_value = $exactKFactor;
}
public function getValueForRating($rating)
{
return $this->_value;
}
}
?>

View File

@ -0,0 +1,105 @@
<?php
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . "/../PairwiseComparison.php");
require_once(dirname(__FILE__) . "/../RankSorter.php");
require_once(dirname(__FILE__) . "/../SkillCalculator.php");
require_once(dirname(__FILE__) . "/../PlayersRange.php");
require_once(dirname(__FILE__) . "/../TeamsRange.php");
use Moserware\Skills\PairwiseComparison;
use Moserware\Skills\RankSorter;
use Moserware\Skills\SkillCalculator;
use Moserware\Skills\SkillCalculatorSupportedOptions;
use Moserware\Skills\PlayersRange;
use Moserware\Skills\TeamsRange;
abstract class TwoPlayerEloCalculator extends SkillCalculator
{
protected $_kFactor;
protected function __construct(KFactor $kFactor)
{
parent::__construct(SkillCalculatorSupportedOptions::NONE, TeamsRange::exactly(2), PlayersRange::exactly(1));
$this->_kFactor = $kFactor;
}
public function calculateNewRatings($gameInfo,
array $teamsOfPlayerToRatings,
array $teamRanks)
{
$this->validateTeamCountAndPlayersCountPerTeam($teamsOfPlayerToRatings);
RankSorter::sort($teamsOfPlayerToRatings, $teamRanks);
$result = array();
$isDraw = ($teamRanks[0] === $teamRanks[1]);
$team1 = $teamsOfPlayerToRatings[0];
$team2 = $teamsOfPlayerToRatings[1];
$player1 = each($team1);
$player2 = each($team2);
$player1Rating = $player1["value"]->getMean();
$player2Rating = $player2["value"]->getMean();
$result[$player1["key"]] = $this->calculateNewRating($gameInfo, $player1Rating, $player2Rating, $isDraw ? PairwiseComparison::DRAW : PairwiseComparison::WIN);
$result[$player2["key"]] = $this->calculateNewRating($gameInfo, $player2Rating, $player1Rating, $isDraw ? PairwiseComparison::DRAW : PairwiseComparison::LOSE);
return $result;
}
protected function calculateNewRating($gameInfo, $selfRating, $opponentRating, $selfToOpponentComparison)
{
$expectedProbability = $this->getPlayerWinProbability($gameInfo, $selfRating, $opponentRating);
$actualProbability = $this->getScoreFromComparison($selfToOpponentComparison);
$k = $this->_kFactor->getValueForRating($selfRating);
$ratingChange = $k * ($actualProbability - $expectedProbability);
$newRating = $selfRating + $ratingChange;
return new EloRating($newRating);
}
private static function getScoreFromComparison($comparison)
{
switch ($comparison)
{
case PairwiseComparison::WIN:
return 1;
case PairwiseComparison::DRAW:
return 0.5;
case PairwiseComparison::LOSE:
return 0;
default:
throw new Exception("Unexpected comparison");
}
}
public abstract function getPlayerWinProbability($gameInfo, $playerRating, $opponentRating);
public function calculateMatchQuality($gameInfo, array $teamsOfPlayerToRatings)
{
validateTeamCountAndPlayersCountPerTeam($teamsOfPlayerToRatings);
$team1 = $teamsOfPlayerToRatings[0];
$team2 = $teamsOfPlayerToRatings[1];
$player1 = $team1[0];
$player2 = $team2[0];
$player1Rating = $player1[1]->getMean();
$player2Rating = $player2[1]->getMean();
$ratingDifference = $player1Rating - $player2Rating;
// The TrueSkill paper mentions that they used s1 - s2 (rating difference) to
// determine match quality. I convert that to a percentage as a delta from 50%
// using the cumulative density function of the specific curve being used
$deltaFrom50Percent = abs(getPlayerWinProbability($gameInfo, $player1Rating, $player2Rating) - 0.5);
return (0.5 - $deltaFrom50Percent) / 0.5;
}
}
?>

113
src/FactorGraphs/Factor.php Normal file
View File

@ -0,0 +1,113 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/../Guard.php");
require_once(dirname(__FILE__) . "/../HashMap.php");
require_once(dirname(__FILE__) . "/Message.php");
require_once(dirname(__FILE__) . "/Variable.php");
use Moserware\Skills\Guard;
use Moserware\Skills\HashMap;
abstract class Factor
{
private $_messages = array();
private $_messageToVariableBinding;
private $_name;
private $_variables = array();
protected function __construct($name)
{
$this->_name = "Factor[" . $name . "]";
$this->_messageToVariableBinding = new HashMap();
}
/**
* @return The log-normalization constant of that factor
*/
public function getLogNormalization()
{
return 0;
}
/**
* @return The number of messages that the factor has
*/
public function getNumberOfMessages()
{
return count($this->_messages);
}
protected function &getVariables()
{
return $this->_variables;
}
protected function &getMessages()
{
return $this->_messages;
}
/**
* Update the message and marginal of the i-th variable that the factor is connected to
*/
public function updateMessageIndex($messageIndex)
{
Guard::argumentIsValidIndex($messageIndex, count($this->_messages), "messageIndex");
$message = &$this->_messages[$messageIndex];
$variable = &$this->_messageToVariableBinding->getValue($message);
return $this->updateMessageVariable($message, $variable);
}
protected function updateMessageVariable(Message $message, Variable $variable)
{
throw new Exception();
}
/**
* Resets the marginal of the variables a factor is connected to
*/
public function resetMarginals()
{
$allValues = &$this->_messageToVariableBinding->getAllValues();
foreach ($allValues as &$currentVariable)
{
$currentVariable->resetToPrior();
}
}
/**
* Sends the ith message to the marginal and returns the log-normalization constant
*/
public function sendMessageIndex($messageIndex)
{
Guard::argumentIsValidIndex($messageIndex, count($this->_messages), "messageIndex");
$message = &$this->_messages[$messageIndex];
$variable = &$this->_messageToVariableBinding->getValue($message);
return $this->sendMessageVariable($message, $variable);
}
protected abstract function sendMessageVariable(Message &$message, Variable &$variable);
public abstract function &createVariableToMessageBinding(Variable &$variable);
protected function &createVariableToMessageBindingWithMessage(Variable &$variable, Message &$message)
{
$index = count($this->_messages);
$localMessages = &$this->_messages;
$localMessages[] = &$message;
$this->_messageToVariableBinding->setValue($message, $variable);
$localVariables = &$this->_variables;
$localVariables[] = &$variable;
return $message;
}
public function __toString()
{
return ($this->_name != null) ? $this->_name : base::__toString();
}
}
?>

View File

@ -0,0 +1,21 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/VariableFactory.php");
class FactorGraph
{
private $_variableFactory;
public function &getVariableFactory()
{
$factory = &$this->_variableFactory;
return $factory;
}
public function setVariableFactory(VariableFactory &$factory)
{
$this->_variableFactory = &$factory;
}
}
?>

View File

@ -0,0 +1,74 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Factor.php");
require_once(dirname(__FILE__) . "/FactorGraph.php");
require_once(dirname(__FILE__) . "/Schedule.php");
abstract class FactorGraphLayer
{
private $_localFactors = array();
private $_outputVariablesGroups = array();
private $_inputVariablesGroups = array();
private $_parentFactorGraph;
protected function __construct(FactorGraph &$parentGraph)
{
$this->_parentFactorGraph = &$parentGraph;
}
protected function &getInputVariablesGroups()
{
$inputVariablesGroups = &$this->_inputVariablesGroups;
return $inputVariablesGroups;
}
// HACK
public function &getParentFactorGraph()
{
$parentFactorGraph = &$this->_parentFactorGraph;
return $parentFactorGraph;
}
public function &getOutputVariablesGroups()
{
$outputVariablesGroups = &$this->_outputVariablesGroups;
return $outputVariablesGroups;
}
public function &getLocalFactors()
{
$localFactors = &$this->_localFactors;
return $localFactors;
}
public function setInputVariablesGroups(&$value)
{
$this->_inputVariablesGroups = $value;
}
protected function scheduleSequence(array $itemsToSequence, $name)
{
return new ScheduleSequence($name, $itemsToSequence);
}
protected function addLayerFactor(Factor &$factor)
{
$this->_localFactors[] = $factor;
}
public abstract function buildLayer();
public function createPriorSchedule()
{
return null;
}
public function createPosteriorSchedule()
{
return null;
}
}
?>

View File

@ -0,0 +1,60 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Factor.php");
/**
* Helper class for computing the factor graph's normalization constant.
*/
class FactorList
{
private $_list = array();
public function getLogNormalization()
{
$list = &$this->_list;
foreach($list as &$currentFactor)
{
$currentFactor->resetMarginals();
}
$sumLogZ = 0.0;
$listCount = count($this->_list);
for ($i = 0; $i < $listCount; $i++)
{
$f = $this->_list[$i];
$numberOfMessages = $f->getNumberOfMessages();
for ($j = 0; $j < $numberOfMessages; $j++)
{
$sumLogZ += $f->sendMessageIndex($j);
}
}
$sumLogS = 0;
foreach($list as &$currentFactor)
{
$sumLogS = $sumLogS + $currentFactor->getLogNormalization();
}
return $sumLogZ + $sumLogS;
}
public function count()
{
return count($this->_list);
}
public function &addFactor(Factor &$factor)
{
$this->_list[] = $factor;
return $factor;
}
}
?>

View File

@ -0,0 +1,32 @@
<?php
namespace Moserware\Skills\FactorGraphs;
class Message
{
private $_name;
private $_value;
public function __construct(&$value = null, $name = null)
{
$this->_name = $name;
$this->_value = $value;
}
public function& getValue()
{
$value = &$this->_value;
return $value;
}
public function setValue(&$value)
{
$this->_value = &$value;
}
public function __toString()
{
return $this->_name;
}
}
?>

View File

@ -0,0 +1,94 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Factor.php");
abstract class Schedule
{
private $_name;
protected function __construct($name)
{
$this->_name = $name;
}
public abstract function visit($depth = -1, $maxDepth = 0);
public function __toString()
{
return $this->_name;
}
}
class ScheduleStep extends Schedule
{
private $_factor;
private $_index;
public function __construct($name, Factor &$factor, $index)
{
parent::__construct($name);
$this->_factor = $factor;
$this->_index = $index;
}
public function visit($depth = -1, $maxDepth = 0)
{
$currentFactor = &$this->_factor;
$delta = $currentFactor->updateMessageIndex($this->_index);
return $delta;
}
}
class ScheduleSequence extends Schedule
{
private $_schedules;
public function __construct($name, array $schedules)
{
parent::__construct($name);
$this->_schedules = $schedules;
}
public function visit($depth = -1, $maxDepth = 0)
{
$maxDelta = 0;
$schedules = &$this->_schedules;
foreach ($schedules as &$currentSchedule)
{
$currentVisit = $currentSchedule->visit($depth + 1, $maxDepth);
$maxDelta = max($currentVisit, $maxDelta);
}
return $maxDelta;
}
}
class ScheduleLoop extends Schedule
{
private $_maxDelta;
private $_scheduleToLoop;
public function __construct($name, Schedule &$scheduleToLoop, $maxDelta)
{
parent::__construct($name);
$this->_scheduleToLoop = $scheduleToLoop;
$this->_maxDelta = $maxDelta;
}
public function visit($depth = -1, $maxDepth = 0)
{
$totalIterations = 1;
$delta = $this->_scheduleToLoop->visit($depth + 1, $maxDepth);
while ($delta > $this->_maxDelta)
{
$delta = $this->_scheduleToLoop->visit($depth + 1, $maxDepth);
$totalIterations++;
}
return $delta;
}
}
?>

View File

@ -0,0 +1,73 @@
<?php
namespace Moserware\Skills\FactorGraphs;
class Variable
{
private $_name;
private $_prior;
private $_value;
public function __construct($name, &$prior)
{
$this->_name = "Variable[" . $name . "]";
$this->_prior = $prior;
$this->resetToPrior();
}
public function &getValue()
{
$value = &$this->_value;
return $value;
}
public function setValue(&$value)
{
$this->_value = &$value;
}
public function resetToPrior()
{
$this->_value = $this->_prior;
}
public function __toString()
{
return $this->_name;
}
}
class DefaultVariable extends Variable
{
public function __construct()
{
parent::__construct("Default", null);
}
public function &getValue()
{
return null;
}
public function setValue(&$value)
{
throw new Exception();
}
}
class KeyedVariable extends Variable
{
private $_key;
public function __construct(&$key, $name, &$prior)
{
parent::__construct($name, $prior);
$this->_key = &$key;
}
public function &getKey()
{
$key = &$this->_key;
return $key;
}
}
?>

View File

@ -0,0 +1,32 @@
<?php
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Variable.php");
class VariableFactory
{
// using a Func<TValue> to encourage fresh copies in case it's overwritten
private $_variablePriorInitializer;
public function __construct($variablePriorInitializer)
{
$this->_variablePriorInitializer = &$variablePriorInitializer;
}
public function &createBasicVariable($name)
{
$initializer = $this->_variablePriorInitializer;
$newVar = new Variable($name, $initializer());
return $newVar;
}
public function &createKeyedVariable(&$key, $name)
{
$initializer = $this->_variablePriorInitializer;
$newVar = new KeyedVariable($key, $name, $initializer());
return $newVar;
}
}
?>

70
src/GameInfo.php Normal file
View File

@ -0,0 +1,70 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Rating.php");
/**
* Parameters about the game for calculating the TrueSkill.
*/
class GameInfo
{
const DEFAULT_BETA = 4.1666666666666666666666666666667; // Default initial mean / 6
const DEFAULT_DRAW_PROBABILITY = 0.10;
const DEFAULT_DYNAMICS_FACTOR = 0.083333333333333333333333333333333; // Default initial mean / 300
const DEFAULT_INITIAL_MEAN = 25.0;
const DEFAULT_INITIAL_STANDARD_DEVIATION = 8.3333333333333333333333333333333; // Default initial mean / 3
private $_initialMean;
private $_initialStandardDeviation;
private $_beta;
private $_dynamicsFactor;
private $_drawProbability;
public function __construct($initialMean = self::DEFAULT_INITIAL_MEAN,
$initialStandardDeviation = self::DEFAULT_INITIAL_STANDARD_DEVIATION,
$beta = self::DEFAULT_BETA,
$dynamicsFactor = self::DEFAULT_DYNAMICS_FACTOR,
$drawProbability = self::DEFAULT_DRAW_PROBABILITY)
{
$this->_initialMean = $initialMean;
$this->_initialStandardDeviation = $initialStandardDeviation;
$this->_beta = $beta;
$this->_dynamicsFactor = $dynamicsFactor;
$this->_drawProbability = $drawProbability;
}
public function getInitialMean()
{
return $this->_initialMean;
}
public function getInitialStandardDeviation()
{
return $this->_initialStandardDeviation;
}
public function getBeta()
{
return $this->_beta;
}
public function getDynamicsFactor()
{
return $this->_dynamicsFactor;
}
public function getDrawProbability()
{
return $this->_drawProbability;
}
public function getDefaultRating()
{
return new Rating($this->_initialMean, $this->_initialStandardDeviation);
}
}
?>

35
src/Guard.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace Moserware\Skills;
/**
* Verifies argument contracts.
*
* @see http://www.moserware.com/2008/01/borrowing-ideas-from-3-interesting.html
*/
class Guard
{
public static function argumentNotNull($value, $parameterName)
{
if ($value == null)
{
throw new Exception($parameterName . " can not be null");
}
}
public static function argumentIsValidIndex($index, $count, $parameterName)
{
if (($index < 0) || ($index >= $count))
{
throw new Exception($parameterName . " is an invalid index");
}
}
public static function argumentInRangeInclusive($value, $min, $max, $parameterName)
{
if (($value < $min) || ($value > $max))
{
throw new Exception($parameterName . " is not in the valid range [" . $min . ", " . $max . "]");
}
}
}
?>

55
src/HashMap.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace Moserware\Skills;
/**
* Basic hashmap that supports object keys.
*/
class HashMap
{
private $_hashToValue = array();
private $_hashToKey = array();
public function &getValue(&$key)
{
$hash = self::getHash($key);
$hashValue = &$this->_hashToValue[$hash];
return $hashValue;
}
public function setValue(&$key, &$value)
{
$hash = self::getHash($key);
$this->_hashToKey[$hash] = &$key;
$this->_hashToValue[$hash] = &$value;
return $this;
}
public function &getAllKeys()
{
$keys = &\array_values($this->_hashToKey);
return $keys;
}
public function getAllValues()
{
$values = &\array_values($this->_hashToValue);
return $values;
}
public function count()
{
return \count($this->_hashToKey);
}
private static function getHash(&$key)
{
if(\is_object($key))
{
return \spl_object_hash($key);
}
return $key;
}
}
?>

View File

@ -0,0 +1,16 @@
<?php
namespace Moserware\Skills;
/**
* Indicates support for allowing partial play (where a player only plays a part of the time).
*/
interface ISupportPartialPlay
{
/**
* Indicates the percent of the time the player should be weighted where 0.0 indicates the player didn't play and 1.0 indicates the player played 100% of the time.
*/
public function getPartialPlayPercentage();
}
?>

View File

@ -0,0 +1,11 @@
<?php
namespace Moserware\Skills;
interface ISupportPartialUpdate
{
/**
* Indicated how much of a skill update a player should receive where 0.0 represents no update and 1.0 represents 100% of the update.
*/
public function getPartialUpdatePercentage();
}
?>

View File

@ -0,0 +1,31 @@
<?php
/**
* Basic math functions.
*
* @author Jeff Moser <jeff@moserware.com>
* @copyright 2010 Jeff Moser
*/
/**
* Squares the input (x^2 = x * x)
* @param number $x Value to square (x)
* @return number The squared value (x^2)
*/
function square($x)
{
return $x * $x;
}
/**
* Sums the items in $itemsToSum
* @param array $itemsToSum The items to sum,
* @param callback $callback The function to apply to each array element before summing.
* @return number The sum.
*/
function sum(array $itemsToSum, $callback )
{
$mappedItems = array_map($callback, $itemsToSum);
return array_sum($mappedItems);
}
?>

View File

@ -0,0 +1,280 @@
<?php
namespace Moserware\Numerics;
require_once(dirname(__FILE__) . "/basicmath.php");
/**
* Computes Gaussian (bell curve) values.
*
* @author Jeff Moser <jeff@moserware.com>
* @copyright 2010 Jeff Moser
*/
class GaussianDistribution
{
private $_mean;
private $_standardDeviation;
// precision and precisionMean are used because they make multiplying and dividing simpler
// (the the accompanying math paper for more details)
private $_precision;
private $_precisionMean;
private $_variance;
function __construct($mean = 0.0, $standardDeviation = 1.0)
{
$this->_mean = $mean;
$this->_standardDeviation = $standardDeviation;
$this->_variance = square($standardDeviation);
if($this->_variance != 0)
{
$this->_precision = 1.0/$this->_variance;
$this->_precisionMean = $this->_precision*$this->_mean;
}
else
{
$this->_precision = \INF;
if($this->_mean == 0)
{
$this->_precisionMean = 0;
}
else
{
$this->_precisionMean = \INF;
}
}
}
public function getMean()
{
return $this->_mean;
}
public function getVariance()
{
return $this->_variance;
}
public function getStandardDeviation()
{
return $this->_standardDeviation;
}
public function getPrecision()
{
return $this->_precision;
}
public function getPrecisionMean()
{
return $this->_precisionMean;
}
public function getNormalizationConstant()
{
// Great derivation of this is at http://www.astro.psu.edu/~mce/A451_2/A451/downloads/notes0.pdf
return 1.0/(sqrt(2*M_PI)*$this->_standardDeviation);
}
public function __clone()
{
$result = new GaussianDistribution();
$result->_mean = $this->_mean;
$result->_standardDeviation = $this->_standardDeviation;
$result->_variance = $this->_variance;
$result->_precision = $this->_precision;
$result->_precisionMean = $this->_precisionMean;
return $result;
}
public static function fromPrecisionMean($precisionMean, $precision)
{
$result = new GaussianDistribution();
$result->_precision = $precision;
$result->_precisionMean = $precisionMean;
if($precision != 0)
{
$result->_variance = 1.0/$precision;
$result->_standardDeviation = sqrt($result->_variance);
$result->_mean = $result->_precisionMean/$result->_precision;
}
else
{
$result->_variance = \INF;
$result->_standardDeviation = \INF;
$result->_mean = \NAN;
}
return $result;
}
// For details, see http://www.tina-vision.net/tina-knoppix/tina-memo/2003-003.pdf
// for multiplication, the precision mean ones are easier to write :)
public static function multiply(GaussianDistribution $left, GaussianDistribution $right)
{
return GaussianDistribution::fromPrecisionMean($left->_precisionMean + $right->_precisionMean, $left->_precision + $right->_precision);
}
// Computes the absolute difference between two Gaussians
public static function absoluteDifference(GaussianDistribution $left, GaussianDistribution $right)
{
return max(
abs($left->_precisionMean - $right->_precisionMean),
sqrt(abs($left->_precision - $right->_precision)));
}
// Computes the absolute difference between two Gaussians
public static function subtract(GaussianDistribution $left, GaussianDistribution $right)
{
return GaussianDistribution::absoluteDifference($left, $right);
}
public static function logProductNormalization(GaussianDistribution $left, GaussianDistribution $right)
{
if (($left->_precision == 0) || ($right->_precision == 0))
{
return 0;
}
$varianceSum = $left->_variance + $right->_variance;
$meanDifference = $left->_mean - $right->_mean;
$logSqrt2Pi = log(sqrt(2*M_PI));
return -$logSqrt2Pi - (log($varianceSum)/2.0) - (square($meanDifference)/(2.0*$varianceSum));
}
public static function divide(GaussianDistribution $numerator, GaussianDistribution $denominator)
{
return GaussianDistribution::fromPrecisionMean($numerator->_precisionMean - $denominator->_precisionMean,
$numerator->_precision - $denominator->_precision);
}
public static function logRatioNormalization(GaussianDistribution $numerator, GaussianDistribution $denominator)
{
if (($numerator->_precision == 0) || ($denominator->_precision == 0))
{
return 0;
}
$varianceDifference = $denominator->_variance - $numerator->_variance;
$meanDifference = $numerator->_mean - $denominator->_mean;
$logSqrt2Pi = log(sqrt(2*M_PI));
return log($denominator->_variance) + $logSqrt2Pi - log($varianceDifference)/2.0 +
square($meanDifference)/(2*$varianceDifference);
}
public static function at($x, $mean = 0.0, $standardDeviation = 1.0)
{
// See http://mathworld.wolfram.com/NormalDistribution.html
// 1 -(x-mean)^2 / (2*stdDev^2)
// P(x) = ------------------- * e
// stdDev * sqrt(2*pi)
$multiplier = 1.0/($standardDeviation*sqrt(2*M_PI));
$expPart = exp((-1.0*square($x - $mean))/(2*square($standardDeviation)));
$result = $multiplier*$expPart;
return $result;
}
public static function cumulativeTo($x, $mean = 0.0, $standardDeviation = 1.0)
{
$invsqrt2 = -0.707106781186547524400844362104;
$result = GaussianDistribution::errorFunctionCumulativeTo($invsqrt2*$x);
return 0.5*$result;
}
private static function errorFunctionCumulativeTo($x)
{
// Derived from page 265 of Numerical Recipes 3rd Edition
$z = abs($x);
$t = 2.0/(2.0 + $z);
$ty = 4*$t - 2;
$coefficients = array(
-1.3026537197817094,
6.4196979235649026e-1,
1.9476473204185836e-2,
-9.561514786808631e-3,
-9.46595344482036e-4,
3.66839497852761e-4,
4.2523324806907e-5,
-2.0278578112534e-5,
-1.624290004647e-6,
1.303655835580e-6,
1.5626441722e-8,
-8.5238095915e-8,
6.529054439e-9,
5.059343495e-9,
-9.91364156e-10,
-2.27365122e-10,
9.6467911e-11,
2.394038e-12,
-6.886027e-12,
8.94487e-13,
3.13092e-13,
-1.12708e-13,
3.81e-16,
7.106e-15,
-1.523e-15,
-9.4e-17,
1.21e-16,
-2.8e-17 );
$ncof = count($coefficients);
$d = 0.0;
$dd = 0.0;
for ($j = $ncof - 1; $j > 0; $j--)
{
$tmp = $d;
$d = $ty*$d - $dd + $coefficients[$j];
$dd = $tmp;
}
$ans = $t*exp(-$z*$z + 0.5*($coefficients[0] + $ty*$d) - $dd);
return ($x >= 0.0) ? $ans : (2.0 - $ans);
}
private static function inverseErrorFunctionCumulativeTo($p)
{
// From page 265 of numerical recipes
if ($p >= 2.0)
{
return -100;
}
if ($p <= 0.0)
{
return 100;
}
$pp = ($p < 1.0) ? $p : 2 - $p;
$t = sqrt(-2*log($pp/2.0)); // Initial guess
$x = -0.70711*((2.30753 + $t*0.27061)/(1.0 + $t*(0.99229 + $t*0.04481)) - $t);
for ($j = 0; $j < 2; $j++)
{
$err = GaussianDistribution::errorFunctionCumulativeTo($x) - $pp;
$x += $err/(1.12837916709551257*exp(-square($x)) - $x*$err); // Halley
}
return ($p < 1.0) ? $x : -$x;
}
public static function inverseCumulativeTo($x, $mean = 0.0, $standardDeviation = 1.0)
{
// From numerical recipes, page 320
return $mean - sqrt(2)*$standardDeviation*GaussianDistribution::inverseErrorFunctionCumulativeTo(2*$x);
}
public function __toString()
{
return sprintf("mean=%.4f standardDeviation=%.4f", $this->_mean, $this->_standardDeviation);
}
}
?>

444
src/Numerics/Matrix.php Normal file
View File

@ -0,0 +1,444 @@
<?php
namespace Moserware\Numerics;
class Matrix
{
const ERROR_TOLERANCE = 0.0000000001;
private $_matrixRowData;
private $_rowCount;
private $_columnCount;
public function __construct($rows = 0, $columns = 0, $matrixData = null)
{
$this->_rowCount = $rows;
$this->_columnCount = $columns;
$this->_matrixRowData = $matrixData;
}
public static function fromColumnValues($rows, $columns, $columnValues)
{
$data = array();
$result = new Matrix($rows, $columns, $data);
for($currentColumn = 0; $currentColumn < $columns; $currentColumn++)
{
$currentColumnData = $columnValues[$currentColumn];
for($currentRow = 0; $currentRow < $rows; $currentRow++)
{
$result->setValue($currentRow, $currentColumn, $currentColumnData[$currentRow]);
}
}
return $result;
}
public static function fromRowsColumns()
{
$args = \func_get_args();
$rows = $args[0];
$cols = $args[1];
$result = new Matrix($rows, $cols);
$currentIndex = 2;
for($currentRow = 0; $currentRow < $rows; $currentRow++)
{
for($currentCol = 0; $currentCol < $cols; $currentCol++)
{
$result->setValue($currentRow, $currentCol, $args[$currentIndex++]);
}
}
return $result;
}
public function getRowCount()
{
return $this->_rowCount;
}
public function getColumnCount()
{
return $this->_columnCount;
}
public function getValue($row, $col)
{
return $this->_matrixRowData[$row][$col];
}
public function setValue($row, $col, $value)
{
$this->_matrixRowData[$row][$col] = $value;
}
public function getTranspose()
{
// Just flip everything
$transposeMatrix = array();
$rowMatrixData = $this->_matrixRowData;
for ($currentRowTransposeMatrix = 0;
$currentRowTransposeMatrix < $this->_columnCount;
$currentRowTransposeMatrix++)
{
for ($currentColumnTransposeMatrix = 0;
$currentColumnTransposeMatrix < $this->_rowCount;
$currentColumnTransposeMatrix++)
{
$transposeMatrix[$currentRowTransposeMatrix][$currentColumnTransposeMatrix] =
$rowMatrixData[$currentColumnTransposeMatrix][$currentRowTransposeMatrix];
}
}
return new Matrix($this->_columnCount, $this->_rowCount, $transposeMatrix);
}
private function isSquare()
{
return ($this->_rowCount == $this->_columnCount) && ($this->_rowCount > 0);
}
public function getDeterminant()
{
// Basic argument checking
if (!$this->isSquare())
{
throw new Exception("Matrix must be square!");
}
if ($this->_rowCount == 1)
{
// Really happy path :)
return $this->_matrixRowData[0][0];
}
if ($this->_rowCount == 2)
{
// Happy path!
// Given:
// | a b |
// | c d |
// The determinant is ad - bc
$a = $this->_matrixRowData[0][0];
$b = $this->_matrixRowData[0][1];
$c = $this->_matrixRowData[1][0];
$d = $this->_matrixRowData[1][1];
return $a*$d - $b*$c;
}
// I use the Laplace expansion here since it's straightforward to implement.
// It's O(n^2) and my implementation is especially poor performing, but the
// core idea is there. Perhaps I should replace it with a better algorithm
// later.
// See http://en.wikipedia.org/wiki/Laplace_expansion for details
$result = 0.0;
// I expand along the first row
for ($currentColumn = 0; $currentColumn < $this->_columnCount; $currentColumn++)
{
$firstRowColValue = $this->_matrixRowData[0][$currentColumn];
$cofactor = $this->getCofactor(0, $currentColumn);
$itemToAdd = $firstRowColValue*$cofactor;
$result = $result + $itemToAdd;
}
return $result;
}
public function getAdjugate()
{
if (!$this->isSquare())
{
throw new Exception("Matrix must be square!");
}
// See http://en.wikipedia.org/wiki/Adjugate_matrix
if ($this->_rowCount == 2)
{
// Happy path!
// Adjugate of:
// | a b |
// | c d |
// is
// | d -b |
// | -c a |
$a = $this->_matrixRowData[0][0];
$b = $this->_matrixRowData[0][1];
$c = $this->_matrixRowData[1][0];
$d = $this->_matrixRowData[1][1];
return new SquareMatrix( $d, -$b,
-$c, $a);
}
// The idea is that it's the transpose of the cofactors
$result = array();
for ($currentColumn = 0; $currentColumn < $this->_columnCount; $currentColumn++)
{
for ($currentRow = 0; $currentRow < $this->_rowCount; $currentRow++)
{
$result[$currentColumn][$currentRow] = $this->getCofactor($currentRow, $currentColumn);
}
}
return new Matrix($this->_columnCount, $this->_rowCount, $result);
}
public function getInverse()
{
if (($this->_rowCount == 1) && ($this->_columnCount == 1))
{
return new SquareMatrix(1.0/$this->_matrixRowData[0][0]);
}
// Take the simple approach:
// http://en.wikipedia.org/wiki/Cramer%27s_rule#Finding_inverse_matrix
$determinantInverse = 1.0 / $this->getDeterminant();
$adjugate = $this->getAdjugate();
return self::scalarMultiply($determinantInverse, $adjugate);
}
public static function scalarMultiply($scalarValue, $matrix)
{
$rows = $matrix->getRowCount();
$columns = $matrix->getColumnCount();
$newValues = array();
for ($currentRow = 0; $currentRow < $rows; $currentRow++)
{
for ($currentColumn = 0; $currentColumn < $columns; $currentColumn++)
{
$newValues[$currentRow][$currentColumn] = $scalarValue*$matrix->getValue($currentRow, $currentColumn);
}
}
return new Matrix($rows, $columns, $newValues);
}
public static function add($left, $right)
{
if (
($left->getRowCount() != $right->getRowCount())
||
($left->getColumnCount() != $right->getColumnCount())
)
{
throw new Exception("Matrices must be of the same size");
}
// simple addition of each item
$resultMatrix = array();
for ($currentRow = 0; $currentRow < $left->getRowCount(); $currentRow++)
{
for ($currentColumn = 0; $currentColumn < $right->getColumnCount(); $currentColumn++)
{
$resultMatrix[$currentRow][$currentColumn] =
$left->getValue($currentRow, $currentColumn)
+
$right->getValue($currentRow, $currentColumn);
}
}
return new Matrix($left->getRowCount(), $right->getColumnCount(), $resultMatrix);
}
public static function multiply($left, $right)
{
// Just your standard matrix multiplication.
// See http://en.wikipedia.org/wiki/Matrix_multiplication for details
if ($left->getColumnCount() != $right->getRowCount())
{
throw new Exception("The width of the left matrix must match the height of the right matrix");
}
$resultRows = $left->getRowCount();
$resultColumns = $right->getColumnCount();
$resultMatrix = array();
for ($currentRow = 0; $currentRow < $resultRows; $currentRow++)
{
for ($currentColumn = 0; $currentColumn < $resultColumns; $currentColumn++)
{
$productValue = 0;
for ($vectorIndex = 0; $vectorIndex < $left->getColumnCount(); $vectorIndex++)
{
$leftValue = $left->getValue($currentRow, $vectorIndex);
$rightValue = $right->getValue($vectorIndex, $currentColumn);
$vectorIndexProduct = $leftValue*$rightValue;
$productValue = $productValue + $vectorIndexProduct;
}
$resultMatrix[$currentRow][$currentColumn] = $productValue;
}
}
return new Matrix($resultRows, $resultColumns, $resultMatrix);
}
private function getMinorMatrix($rowToRemove, $columnToRemove)
{
// See http://en.wikipedia.org/wiki/Minor_(linear_algebra)
// I'm going to use a horribly naïve algorithm... because I can :)
$result = array();
$actualRow = 0;
for ($currentRow = 0; $currentRow < $this->_rowCount; $currentRow++)
{
if ($currentRow == $rowToRemove)
{
continue;
}
$actualCol = 0;
for ($currentColumn = 0; $currentColumn < $this->_columnCount; $currentColumn++)
{
if ($currentColumn == $columnToRemove)
{
continue;
}
$result[$actualRow][$actualCol] = $this->_matrixRowData[$currentRow][$currentColumn];
$actualCol++;
}
$actualRow++;
}
return new Matrix($this->_rowCount - 1, $this->_columnCount - 1, $result);
}
public function getCofactor($rowToRemove, $columnToRemove)
{
// See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for details
// REVIEW: should things be reversed since I'm 0 indexed?
$sum = $rowToRemove + $columnToRemove;
$isEven = ($sum%2 == 0);
if ($isEven)
{
return $this->getMinorMatrix($rowToRemove, $columnToRemove)->getDeterminant();
}
else
{
return -1.0*$this->getMinorMatrix($rowToRemove, $columnToRemove)->getDeterminant();
}
}
public function equals($otherMatrix)
{
// If one is null, but not both, return false.
if ($otherMatrix == null)
{
return false;
}
if (($this->_rowCount != $otherMatrix->getRowCount()) || ($this->_columnCount != $otherMatrix->getColumnCount()))
{
return false;
}
for ($currentRow = 0; $currentRow < $this->_rowCount; $currentRow++)
{
for ($currentColumn = 0; $currentColumn < $this->_columnCount; $currentColumn++)
{
$delta =
abs($this->_matrixRowData[$currentRow][$currentColumn] -
$otherMatrix->getValue($currentRow, $currentColumn));
if ($delta > self::ERROR_TOLERANCE)
{
return false;
}
}
}
return true;
}
}
class Vector extends Matrix
{
public function __construct(array $vectorValues)
{
$columnValues = array();
foreach($vectorValues as $currentVectorValue)
{
$columnValues[] = array($currentVectorValue);
}
parent::__construct(count($vectorValues), 1, $columnValues);
}
}
class SquareMatrix extends Matrix
{
public function __construct()
{
$allValues = \func_get_args();
$rows = (int) sqrt(count($allValues));
$cols = $rows;
$matrixData = array();
$allValuesIndex = 0;
for ($currentRow = 0; $currentRow < $rows; $currentRow++)
{
for ($currentColumn = 0; $currentColumn < $cols; $currentColumn++)
{
$matrixData[$currentRow][$currentColumn] = $allValues[$allValuesIndex++];
}
}
parent::__construct($rows, $cols, $matrixData);
}
}
class DiagonalMatrix extends Matrix
{
public function __construct(array $diagonalValues)
{
$diagonalCount = count($diagonalValues);
$rowCount = $diagonalCount;
$colCount = $rowCount;
parent::__construct($rowCount, $colCount);
for($currentRow = 0; $currentRow < $rowCount; $currentRow++)
{
for($currentCol = 0; $currentCol < $colCount; $currentCol++)
{
if($currentRow == $currentCol)
{
$this->setValue($currentRow, $currentCol, $diagonalValues[$currentRow]);
}
else
{
$this->setValue($currentRow, $currentCol, 0);
}
}
}
}
}
class IdentityMatrix extends DiagonalMatrix
{
public function __construct($rows)
{
parent::__construct(\array_fill(0, $rows, 1));
}
}
?>

62
src/Numerics/Range.php Normal file
View File

@ -0,0 +1,62 @@
<?php
namespace Moserware\Numerics;
// The whole purpose of this class is to make the code for the SkillCalculator(s)
// look a little cleaner
class Range
{
private $_min;
private $_max;
public function __construct($min, $max)
{
if ($min > $max)
{
throw new Exception("min > max");
}
$this->_min = $min;
$this->_max = $max;
}
public function getMin()
{
return $this->_min;
}
public function getMax()
{
return $this->_max;
}
protected static function create($min, $max)
{
return new Range($min, $max);
}
// REVIEW: It's probably bad form to have access statics via a derived class, but the syntax looks better :-)
public static function inclusive($min, $max)
{
return static::create($min, $max);
}
public static function exactly($value)
{
return static::create($value, $value);
}
public static function atLeast($minimumValue)
{
return static::create($minimumValue, PHP_INT_MAX );
}
public function isInRange($value)
{
return ($this->_min <= $value) && ($value <= $this->_max);
}
}
?>

View File

@ -0,0 +1,27 @@
<?php
namespace Moserware\Skills;
/**
* Represents a comparison between two players.
* @internal The actual values for the enum were chosen so that the also correspond to the multiplier for updates to means.
*/
class PairwiseComparison
{
const WIN = 1;
const DRAW = 0;
const LOSE = -1;
public static function getRankFromComparison($comparison)
{
switch ($comparison) {
case PairwiseComparison::WIN:
return array(1,2);
case PairwiseComparison::LOSE:
return array(2,1);
default:
return array(1,1);
}
}
}
?>

30
src/PartialPlay.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/ISupportPartialPlay.php");
class PartialPlay
{
public static function getPartialPlayPercentage($player)
{
// If the player doesn't support the interface, assume 1.0 == 100%
$supportsPartialPlay = $player instanceof ISupportPartialPlay;
if (!$supportsPartialPlay)
{
return 1.0;
}
$partialPlayPercentage = $player->getPartialPlayPercentage();
// HACK to get around bug near 0
$smallestPercentage = 0.0001;
if ($partialPlayPercentage < $smallestPercentage)
{
$partialPlayPercentage = $smallestPercentage;
}
return $partialPlayPercentage;
}
}
?>

74
src/Player.php Normal file
View File

@ -0,0 +1,74 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Guard.php");
require_once(dirname(__FILE__) . "/ISupportPartialPlay.php");
require_once(dirname(__FILE__) . "/ISupportPartialUpdate.php");
/**
* Represents a player who has a Rating.
*/
class Player implements ISupportPartialPlay, ISupportPartialUpdate
{
const DEFAULT_PARTIAL_PLAY_PERCENTAGE = 1.0; // = 100% play time
const DEFAULT_PARTIAL_UPDATE_PERCENTAGE = 1.0; // = receive 100% update
private $_Id;
private $_PartialPlayPercentage;
private $_PartialUpdatePercentage;
/**
* Constructs a player.
*
* @param mixed $id The identifier for the player, such as a name.
* @param number $partialPlayPercentage The weight percentage to give this player when calculating a new rank.
* @param number $partialUpdatePercentage Indicated how much of a skill update a player should receive where 0 represents no update and 1.0 represents 100% of the update.
*/
public function __construct($id,
$partialPlayPercentage = self::DEFAULT_PARTIAL_PLAY_PERCENTAGE,
$partialUpdatePercentage = self::DEFAULT_PARTIAL_UPDATE_PERCENTAGE)
{
// If they don't want to give a player an id, that's ok...
Guard::argumentInRangeInclusive($partialPlayPercentage, 0.0, 1.0, "partialPlayPercentage");
Guard::argumentInRangeInclusive($partialUpdatePercentage, 0, 1.0, "partialUpdatePercentage");
$this->_Id = $id;
$this->_PartialPlayPercentage = $partialPlayPercentage;
$this->_PartialUpdatePercentage = $partialUpdatePercentage;
}
/**
* The identifier for the player, such as a name.
*/
public function &getId()
{
$id = &$this->_Id;
return $this->_Id;
}
/**
* Indicates the percent of the time the player should be weighted where 0.0 indicates the player didn't play and 1.0 indicates the player played 100% of the time.
*/
public function getPartialPlayPercentage()
{
return $this->_PartialPlayPercentage;
}
/**
* Indicated how much of a skill update a player should receive where 0.0 represents no update and 1.0 represents 100% of the update.
*/
public function getPartialUpdatePercentage()
{
return $this->_PartialUpdatePercentage;
}
public function __toString()
{
if ($this->_Id != null)
{
return (string)$this->_Id;
}
return parent::__toString();
}
}
?>

21
src/PlayersRange.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Numerics/Range.php");
use Moserware\Numerics\Range;
class PlayersRange extends Range
{
public function __construct($min, $max)
{
parent::__construct($min, $max);
}
protected static function create($min, $max)
{
return new PlayersRange($min, $max);
}
}
?>

23
src/RankSorter.php Normal file
View File

@ -0,0 +1,23 @@
<?php
namespace Moserware\Skills;
/**
* Helper class to sort ranks in non-decreasing order.
*/
class RankSorter
{
/**
* Performs an in-place sort of the items in according to the ranks in non-decreasing order.
*
* @param $items The items to sort according to the order specified by ranks.
* @param $ranks The ranks for each item where 1 is first place.
*/
public static function sort(array &$teams, array &$teamRanks)
{
array_multisort($teamRanks, $teams);
return $teams;
}
}
?>

79
src/Rating.php Normal file
View File

@ -0,0 +1,79 @@
<?php
namespace Moserware\Skills;
// Container for a player's rating.
class Rating
{
const CONSERVATIVE_STANDARD_DEVIATION_MULTIPLIER = 3;
private $_conservativeStandardDeviationMultiplier;
private $_mean;
private $_standardDeviation;
/**
* Constructs a rating.
* @param double $mean The statistical mean value of the rating (also known as mu).
* @param double $standardDeviation The standard deviation of the rating (also known as s).
* @param double $conservativeStandardDeviationMultiplier optional The number of standardDeviations to subtract from the mean to achieve a conservative rating.
*/
public function __construct($mean, $standardDeviation, $conservativeStandardDeviationMultiplier = self::CONSERVATIVE_STANDARD_DEVIATION_MULTIPLIER)
{
$this->_mean = $mean;
$this->_standardDeviation = $standardDeviation;
$this->_conservativeStandardDeviationMultiplier = $conservativeStandardDeviationMultiplier;
}
/**
* The statistical mean value of the rating (also known as <20>).
*/
public function getMean()
{
return $this->_mean;
}
/**
* The standard deviation (the spread) of the rating. This is also known as s.
*/
public function getStandardDeviation()
{
return $this->_standardDeviation;
}
/**
* A conservative estimate of skill based on the mean and standard deviation.
*/
public function getConservativeRating()
{
return $this->_mean - $this->_conservativeStandardDeviationMultiplier*$this->_standardDeviation;
}
public function getPartialUpdate(Rating $prior, Rating $fullPosterior, $updatePercentage)
{
$priorGaussian = new GaussianDistribution($prior->getMean(), $prior->getStandardDeviation());
$posteriorGaussian = new GaussianDistribution($fullPosterior->getMean(), $fullPosterior.getStandardDeviation());
// From a clarification email from Ralf Herbrich:
// "the idea is to compute a linear interpolation between the prior and posterior skills of each player
// ... in the canonical space of parameters"
$precisionDifference = $posteriorGaussian->getPrecision() - $priorGaussian->getPrecision();
$partialPrecisionDifference = $updatePercentage*$precisionDifference;
$precisionMeanDifference = $posteriorGaussian->getPrecisionMean() - $priorGaussian.getPrecisionMean();
$partialPrecisionMeanDifference = $updatePercentage*$precisionMeanDifference;
$partialPosteriorGaussion = GaussianDistribution::fromPrecisionMean(
$priorGaussian->getPrecisionMean() + $partialPrecisionMeanDifference,
$priorGaussian->getPrecision() + $partialPrecisionDifference);
return new Rating($partialPosteriorGaussion->getMean(), $partialPosteriorGaussion->getStandardDeviation(), $prior->_conservativeStandardDeviationMultiplier);
}
public function __toString()
{
return sprintf("mean=%.4f, standardDeviation=%.4f", $this->_mean, $this->_standardDeviation);
}
}
?>

45
src/RatingContainer.php Normal file
View File

@ -0,0 +1,45 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/HashMap.php");
require_once(dirname(__FILE__) . "/Player.php");
require_once(dirname(__FILE__) . "/Rating.php");
class RatingContainer
{
private $_playerToRating;
public function __construct()
{
$this->_playerToRating = new HashMap();
}
public function &getRating(Player &$player)
{
$rating = &$this->_playerToRating->getValue($player);
return $rating;
}
public function setRating(Player &$player, Rating $rating)
{
return $this->_playerToRating->setValue($player, $rating);
}
public function &getAllPlayers()
{
$allPlayers = &$this->_playerToRating->getAllKeys();
return $allPlayers;
}
public function &getAllRatings()
{
$allRatings = &$this->_playerToRating->getAllValues();
return $allRatings;
}
public function count()
{
return $this->_playerToRating->count();
}
}
?>

84
src/SkillCalculator.php Normal file
View File

@ -0,0 +1,84 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/GameInfo.php");
require_once(dirname(__FILE__) . "/PlayersRange.php");
require_once(dirname(__FILE__) . "/TeamsRange.php");
/**
* Base class for all skill calculator implementations.
*/
abstract class SkillCalculator
{
private $_supportedOptions;
private $_playersPerTeamAllowed;
private $_totalTeamsAllowed;
protected function __construct($supportedOptions, TeamsRange $totalTeamsAllowed, PlayersRange $playerPerTeamAllowed)
{
$this->_supportedOptions = $supportedOptions;
$this->_totalTeamsAllowed = $totalTeamsAllowed;
$this->_playersPerTeamAllowed = $playerPerTeamAllowed;
}
/**
* Calculates new ratings based on the prior ratings and team ranks.
* @param $gameInfo Parameters for the game.
* @param $teams A mapping of team players and their ratings.
* @param $teamRanks The ranks of the teams where 1 is first place. For a tie, repeat the number (e.g. 1, 2, 2).
* @return All the players and their new ratings.
*/
public abstract function calculateNewRatings(GameInfo &$gameInfo,
array $teamsOfPlayerToRatings,
array $teamRanks);
/**
* Calculates the match quality as the likelihood of all teams drawing.
*
* @param $gameInfo Parameters for the game.
* @param $teams A mapping of team players and their ratings.
* @return The quality of the match between the teams as a percentage (0% = bad, 100% = well matched).
*/
public abstract function calculateMatchQuality(GameInfo &$gameInfo,
array &$teamsOfPlayerToRatings);
public function isSupported($option)
{
return ($this->_supportedOptions & $option) == $option;
}
protected function validateTeamCountAndPlayersCountPerTeam(array &$teamsOfPlayerToRatings)
{
self::validateTeamCountAndPlayersCountPerTeamWithRanges($teamsOfPlayerToRatings, $this->_totalTeamsAllowed, $this->_playersPerTeamAllowed);
}
private static function validateTeamCountAndPlayersCountPerTeamWithRanges(
array &$teams,
TeamsRange &$totalTeams,
PlayersRange &$playersPerTeam)
{
$countOfTeams = 0;
foreach ($teams as $currentTeam)
{
if (!$playersPerTeam->isInRange($currentTeam->count()))
{
throw new \Exception("Player count is not in range");
}
$countOfTeams++;
}
if (!$totalTeams->isInRange($countOfTeams))
{
throw new Exception("Team range is not in range");
}
}
}
class SkillCalculatorSupportedOptions
{
const NONE = 0x00;
const PARTIAL_PLAY = 0x01;
const PARTIAL_UPDATE = 0x02;
}
?>

27
src/Team.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . '/Player.php');
require_once(dirname(__FILE__) . '/Rating.php');
require_once(dirname(__FILE__) . '/RatingContainer.php');
class Team extends RatingContainer
{
public function __construct(Player &$player = null, Rating $rating = null)
{
parent::__construct();
if(!\is_null($player))
{
$this->addPlayer($player, $rating);
}
}
public function addPlayer(Player &$player, Rating $rating)
{
$this->setRating($player, $rating);
return $this;
}
}
?>

19
src/Teams.php Normal file
View File

@ -0,0 +1,19 @@
<?php
namespace Moserware\Skills;
class Teams
{
public static function concat(/*variable arguments*/)
{
$args = \func_get_args();
$result = array();
foreach ($args as &$currentTeam) {
$localCurrentTeam = &$currentTeam;
$result[] = $localCurrentTeam;
}
return $result;
}
}
?>

21
src/TeamsRange.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Numerics/Range.php");
use Moserware\Numerics\Range;
class TeamsRange extends Range
{
public function __construct($min, $max)
{
parent::__construct($min, $max);
}
protected static function create($min, $max)
{
return new TeamsRange($min, $max);
}
}
?>

View 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;
}
}
?>

View 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;
}
}
?>

View 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;
}
}
?>

View 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);
}
}
?>

View 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();
}
}
}
?>

View 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);
}
}
?>

View 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;
}
}
?>

View 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);
}
}
?>

View 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;
}
}
?>

View File

@ -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;
}
}
?>

View 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;
}
}
?>

View 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");
}
}
?>

View 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);
}
}
}
?>

View File

@ -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;
}
}
?>

View 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);
}
}
?>

View 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;
}
}
?>

View 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;
}
}
?>

View 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;
}
}
?>

View 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;
}
}
?>