Cleanup in src/, adding namespaces, removing php closing tag and general code cleanup

This commit is contained in:
Alexander Liljengård 2016-05-24 14:10:39 +02:00
parent 9f97eb1653
commit 5694a2fb30
64 changed files with 891 additions and 1328 deletions

@ -1,7 +1,4 @@
<?php <?php namespace Moserware\Skills\Elo;
namespace Moserware\Skills\Elo;
require_once(dirname(__FILE__) . '/../Rating.php');
use Moserware\Skills\Rating; use Moserware\Skills\Rating;
@ -15,5 +12,3 @@ class EloRating extends Rating
parent::__construct($rating, 0); parent::__construct($rating, 0);
} }
} }
?>

@ -1,11 +1,7 @@
<?php <?php namespace Moserware\Skills\Elo;
namespace Moserware\Skills\Elo; /**
* Including Elo's scheme as a simple comparison.
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 * See http://en.wikipedia.org/wiki/Elo_rating_system#Theory
* for more details * for more details
*/ */
@ -37,5 +33,3 @@ class FideEloCalculator extends TwoPlayerEloCalculator
); );
} }
} }
?>

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

@ -1,10 +1,4 @@
<?php <?php namespace Moserware\Skills\Elo;
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\Skills\GameInfo;
use Moserware\Numerics\GaussianDistribution; use Moserware\Numerics\GaussianDistribution;
@ -30,5 +24,3 @@ class GaussianEloCalculator extends TwoPlayerEloCalculator
(sqrt(2) * $gameInfo->getBeta())); (sqrt(2) * $gameInfo->getBeta()));
} }
} }
?>

@ -1,6 +1,4 @@
<?php <?php namespace Moserware\Skills\Elo;
namespace Moserware\Skills\Elo;
class KFactor class KFactor
{ {
@ -18,5 +16,3 @@ class KFactor
return $this->_value; return $this->_value;
} }
} }
?>

@ -0,0 +1,12 @@
<?php namespace Moserware\Skills\Elo;
/**
* Indicates someone who has played less than 30 games.
*/
class ProvisionalFideKFactor extends FideKFactor
{
public function getValueForRating($rating)
{
return 25;
}
}

@ -1,13 +1,4 @@
<?php <?php namespace Moserware\Skills\Elo;
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\PairwiseComparison;
use Moserware\Skills\RankSorter; use Moserware\Skills\RankSorter;
@ -101,5 +92,3 @@ abstract class TwoPlayerEloCalculator extends SkillCalculator
return (0.5 - $deltaFrom50Percent) / 0.5; return (0.5 - $deltaFrom50Percent) / 0.5;
} }
} }
?>

@ -0,0 +1,21 @@
<?php namespace Moserware\Skills\FactorGraphs;
use Exception;
class DefaultVariable extends Variable
{
public function __construct()
{
parent::__construct("Default", null);
}
public function &getValue()
{
return null;
}
public function setValue(&$value)
{
throw new Exception();
}
}

@ -1,11 +1,6 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
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 Exception;
use Moserware\Skills\Guard; use Moserware\Skills\Guard;
use Moserware\Skills\HashMap; use Moserware\Skills\HashMap;
@ -71,8 +66,7 @@ abstract class Factor
public function resetMarginals() public function resetMarginals()
{ {
$allValues = &$this->_messageToVariableBinding->getAllValues(); $allValues = &$this->_messageToVariableBinding->getAllValues();
foreach ($allValues as &$currentVariable) foreach ($allValues as &$currentVariable) {
{
$currentVariable->resetToPrior(); $currentVariable->resetToPrior();
} }
} }
@ -109,5 +103,3 @@ abstract class Factor
return ($this->_name != null) ? $this->_name : base::__toString(); return ($this->_name != null) ? $this->_name : base::__toString();
} }
} }
?>

@ -1,7 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/VariableFactory.php");
class FactorGraph class FactorGraph
{ {
@ -18,4 +15,3 @@ class FactorGraph
$this->_variableFactory = &$factory; $this->_variableFactory = &$factory;
} }
} }
?>

@ -1,9 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
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 abstract class FactorGraphLayer
{ {
@ -70,5 +65,3 @@ abstract class FactorGraphLayer
return null; return null;
} }
} }
?>

@ -1,8 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Factor.php");
/** /**
* Helper class for computing the factor graph's normalization constant. * Helper class for computing the factor graph's normalization constant.
@ -14,8 +10,7 @@ class FactorList
public function getLogNormalization() public function getLogNormalization()
{ {
$list = &$this->_list; $list = &$this->_list;
foreach($list as &$currentFactor) foreach ($list as &$currentFactor) {
{
$currentFactor->resetMarginals(); $currentFactor->resetMarginals();
} }
@ -23,22 +18,19 @@ class FactorList
$listCount = count($this->_list); $listCount = count($this->_list);
for ($i = 0; $i < $listCount; $i++) for ($i = 0; $i < $listCount; $i++) {
{
$f = $this->_list[$i]; $f = $this->_list[$i];
$numberOfMessages = $f->getNumberOfMessages(); $numberOfMessages = $f->getNumberOfMessages();
for ($j = 0; $j < $numberOfMessages; $j++) for ($j = 0; $j < $numberOfMessages; $j++) {
{
$sumLogZ += $f->sendMessageIndex($j); $sumLogZ += $f->sendMessageIndex($j);
} }
} }
$sumLogS = 0; $sumLogS = 0;
foreach($list as &$currentFactor) foreach ($list as &$currentFactor) {
{
$sumLogS = $sumLogS + $currentFactor->getLogNormalization(); $sumLogS = $sumLogS + $currentFactor->getLogNormalization();
} }
@ -56,5 +48,3 @@ class FactorList
return $factor; return $factor;
} }
} }
?>

@ -0,0 +1,18 @@
<?php namespace Moserware\Skills\FactorGraphs;
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;
}
}

@ -1,5 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
namespace Moserware\Skills\FactorGraphs;
class Message class Message
{ {
@ -25,8 +24,6 @@ class Message
public function __toString() public function __toString()
{ {
return $this->_name; return (string)$this->_name;
} }
} }
?>

@ -1,7 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Factor.php");
abstract class Schedule abstract class Schedule
{ {
@ -19,76 +16,3 @@ abstract class Schedule
return $this->_name; 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;
}
}
?>

@ -0,0 +1,26 @@
<?php namespace Moserware\Skills\FactorGraphs;
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;
}
}

@ -0,0 +1,25 @@
<?php namespace Moserware\Skills\FactorGraphs;
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;
}
}

@ -0,0 +1,21 @@
<?php namespace Moserware\Skills\FactorGraphs;
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;
}
}

@ -35,39 +35,3 @@ class Variable
return $this->_name; 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;
}
}
?>

@ -1,8 +1,4 @@
<?php <?php namespace Moserware\Skills\FactorGraphs;
namespace Moserware\Skills\FactorGraphs;
require_once(dirname(__FILE__) . "/Variable.php");
class VariableFactory class VariableFactory
{ {
@ -28,5 +24,3 @@ class VariableFactory
return $newVar; return $newVar;
} }
} }
?>

@ -1,9 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Rating.php");
/** /**
* Parameters about the game for calculating the TrueSkill. * Parameters about the game for calculating the TrueSkill.
@ -66,5 +61,3 @@ class GameInfo
return new Rating($this->_initialMean, $this->_initialStandardDeviation); return new Rating($this->_initialMean, $this->_initialStandardDeviation);
} }
} }
?>

@ -1,5 +1,6 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
use Exception;
/** /**
* Verifies argument contracts. * Verifies argument contracts.
@ -10,26 +11,22 @@ class Guard
{ {
public static function argumentNotNull($value, $parameterName) public static function argumentNotNull($value, $parameterName)
{ {
if ($value == null) if ($value == null) {
{
throw new Exception($parameterName . " can not be null"); throw new Exception($parameterName . " can not be null");
} }
} }
public static function argumentIsValidIndex($index, $count, $parameterName) public static function argumentIsValidIndex($index, $count, $parameterName)
{ {
if (($index < 0) || ($index >= $count)) if (($index < 0) || ($index >= $count)) {
{
throw new Exception($parameterName . " is an invalid index"); throw new Exception($parameterName . " is an invalid index");
} }
} }
public static function argumentInRangeInclusive($value, $min, $max, $parameterName) public static function argumentInRangeInclusive($value, $min, $max, $parameterName)
{ {
if (($value < $min) || ($value > $max)) if (($value < $min) || ($value > $max)) {
{
throw new Exception($parameterName . " is not in the valid range [" . $min . ", " . $max . "]"); throw new Exception($parameterName . " is not in the valid range [" . $min . ", " . $max . "]");
} }
} }
} }
?>

@ -1,6 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
/** /**
* Basic hashmap that supports object keys. * Basic hashmap that supports object keys.
@ -27,29 +25,27 @@ class HashMap
public function &getAllKeys() public function &getAllKeys()
{ {
$keys = &\array_values($this->_hashToKey); $keys = &array_values($this->_hashToKey);
return $keys; return $keys;
} }
public function getAllValues() public function getAllValues()
{ {
$values = &\array_values($this->_hashToValue); $values = &array_values($this->_hashToValue);
return $values; return $values;
} }
public function count() public function count()
{ {
return \count($this->_hashToKey); return count($this->_hashToKey);
} }
private static function getHash(&$key) private static function getHash(&$key)
{ {
if(\is_object($key)) if (is_object($key)) {
{ return spl_object_hash($key);
return \spl_object_hash($key);
} }
return $key; return $key;
} }
} }
?>

@ -1,10 +1,8 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
/** /**
* Indicates support for allowing partial play (where a player only plays a part of the time). * Indicates support for allowing partial play (where a player only plays a part of the time).
*/ */
interface ISupportPartialPlay interface ISupportPartialPlay
{ {
/** /**
@ -12,5 +10,3 @@ interface ISupportPartialPlay
*/ */
public function getPartialPlayPercentage(); public function getPartialPlayPercentage();
} }
?>

@ -1,5 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
interface ISupportPartialUpdate interface ISupportPartialUpdate
{ {
@ -8,4 +7,3 @@ interface ISupportPartialUpdate
*/ */
public function getPartialUpdatePercentage(); public function getPartialUpdatePercentage();
} }
?>

@ -1,18 +1,19 @@
<?php <?php namespace Moserware\Skills\Numerics;
/** /**
* Basic math functions. * Basic math functions.
* *
* @author Jeff Moser <jeff@moserware.com> * @author Jeff Moser <jeff@moserware.com>
* @copyright 2010 Jeff Moser * @copyright 2010 Jeff Moser
*/ */
class BasicMatch {
/** /**
* Squares the input (x^2 = x * x) * Squares the input (x^2 = x * x)
* @param number $x Value to square (x) * @param number $x Value to square (x)
* @return number The squared value (x^2) * @return number The squared value (x^2)
*/ */
function square($x) public static function square($x) {
{
return $x * $x; return $x * $x;
} }
@ -22,10 +23,8 @@ function square($x)
* @param callback $callback The function to apply to each array element before summing. * @param callback $callback The function to apply to each array element before summing.
* @return number The sum. * @return number The sum.
*/ */
function sum(array $itemsToSum, $callback ) public static function sum(array $itemsToSum, $callback) {
{
$mappedItems = array_map($callback, $itemsToSum); $mappedItems = array_map($callback, $itemsToSum);
return array_sum($mappedItems); return array_sum($mappedItems);
} }
}
?>

@ -0,0 +1,23 @@
<?php namespace Moserware\Skills\Numerics;
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);
}
}
}
}
}

@ -1,8 +1,4 @@
<?php <?php namespace Moserware\Skills\Numerics;
namespace Moserware\Numerics;
require_once(dirname(__FILE__) . "/basicmath.php");
/** /**
* Computes Gaussian (bell curve) values. * Computes Gaussian (bell curve) values.
@ -21,27 +17,21 @@ class GaussianDistribution
private $_precisionMean; private $_precisionMean;
private $_variance; private $_variance;
function __construct($mean = 0.0, $standardDeviation = 1.0) public function __construct($mean = 0.0, $standardDeviation = 1.0)
{ {
$this->_mean = $mean; $this->_mean = $mean;
$this->_standardDeviation = $standardDeviation; $this->_standardDeviation = $standardDeviation;
$this->_variance = square($standardDeviation); $this->_variance = BasicMatch::square($standardDeviation);
if($this->_variance != 0) if ($this->_variance != 0) {
{
$this->_precision = 1.0 / $this->_variance; $this->_precision = 1.0 / $this->_variance;
$this->_precisionMean = $this->_precision * $this->_mean; $this->_precisionMean = $this->_precision * $this->_mean;
} } else {
else
{
$this->_precision = \INF; $this->_precision = \INF;
if($this->_mean == 0) if ($this->_mean == 0) {
{
$this->_precisionMean = 0; $this->_precisionMean = 0;
} } else {
else
{
$this->_precisionMean = \INF; $this->_precisionMean = \INF;
} }
} }
@ -95,14 +85,11 @@ class GaussianDistribution
$result->_precision = $precision; $result->_precision = $precision;
$result->_precisionMean = $precisionMean; $result->_precisionMean = $precisionMean;
if($precision != 0) if ($precision != 0) {
{
$result->_variance = 1.0 / $precision; $result->_variance = 1.0 / $precision;
$result->_standardDeviation = sqrt($result->_variance); $result->_standardDeviation = sqrt($result->_variance);
$result->_mean = $result->_precisionMean / $result->_precision; $result->_mean = $result->_precisionMean / $result->_precision;
} } else {
else
{
$result->_variance = \INF; $result->_variance = \INF;
$result->_standardDeviation = \INF; $result->_standardDeviation = \INF;
$result->_mean = \NAN; $result->_mean = \NAN;
@ -133,8 +120,7 @@ class GaussianDistribution
public static function logProductNormalization(GaussianDistribution $left, GaussianDistribution $right) public static function logProductNormalization(GaussianDistribution $left, GaussianDistribution $right)
{ {
if (($left->_precision == 0) || ($right->_precision == 0)) if (($left->_precision == 0) || ($right->_precision == 0)) {
{
return 0; return 0;
} }
@ -142,7 +128,7 @@ class GaussianDistribution
$meanDifference = $left->_mean - $right->_mean; $meanDifference = $left->_mean - $right->_mean;
$logSqrt2Pi = log(sqrt(2 * M_PI)); $logSqrt2Pi = log(sqrt(2 * M_PI));
return -$logSqrt2Pi - (log($varianceSum)/2.0) - (square($meanDifference)/(2.0*$varianceSum)); return -$logSqrt2Pi - (log($varianceSum) / 2.0) - (BasicMatch::square($meanDifference) / (2.0 * $varianceSum));
} }
public static function divide(GaussianDistribution $numerator, GaussianDistribution $denominator) public static function divide(GaussianDistribution $numerator, GaussianDistribution $denominator)
@ -153,8 +139,7 @@ class GaussianDistribution
public static function logRatioNormalization(GaussianDistribution $numerator, GaussianDistribution $denominator) public static function logRatioNormalization(GaussianDistribution $numerator, GaussianDistribution $denominator)
{ {
if (($numerator->_precision == 0) || ($denominator->_precision == 0)) if (($numerator->_precision == 0) || ($denominator->_precision == 0)) {
{
return 0; return 0;
} }
@ -164,7 +149,7 @@ class GaussianDistribution
$logSqrt2Pi = log(sqrt(2 * M_PI)); $logSqrt2Pi = log(sqrt(2 * M_PI));
return log($denominator->_variance) + $logSqrt2Pi - log($varianceDifference) / 2.0 + return log($denominator->_variance) + $logSqrt2Pi - log($varianceDifference) / 2.0 +
square($meanDifference)/(2*$varianceDifference); BasicMatch::square($meanDifference) / (2 * $varianceDifference);
} }
public static function at($x, $mean = 0.0, $standardDeviation = 1.0) public static function at($x, $mean = 0.0, $standardDeviation = 1.0)
@ -175,7 +160,7 @@ class GaussianDistribution
// stdDev * sqrt(2*pi) // stdDev * sqrt(2*pi)
$multiplier = 1.0 / ($standardDeviation * sqrt(2 * M_PI)); $multiplier = 1.0 / ($standardDeviation * sqrt(2 * M_PI));
$expPart = exp((-1.0*square($x - $mean))/(2*square($standardDeviation))); $expPart = exp((-1.0 * BasicMatch::square($x - $mean)) / (2 * BasicMatch::square($standardDeviation)));
$result = $multiplier * $expPart; $result = $multiplier * $expPart;
return $result; return $result;
} }
@ -229,8 +214,7 @@ class GaussianDistribution
$d = 0.0; $d = 0.0;
$dd = 0.0; $dd = 0.0;
for ($j = $ncof - 1; $j > 0; $j--) for ($j = $ncof - 1; $j > 0; $j--) {
{
$tmp = $d; $tmp = $d;
$d = $ty * $d - $dd + $coefficients[$j]; $d = $ty * $d - $dd + $coefficients[$j];
$dd = $tmp; $dd = $tmp;
@ -244,12 +228,10 @@ class GaussianDistribution
{ {
// From page 265 of numerical recipes // From page 265 of numerical recipes
if ($p >= 2.0) if ($p >= 2.0) {
{
return -100; return -100;
} }
if ($p <= 0.0) if ($p <= 0.0) {
{
return 100; return 100;
} }
@ -257,10 +239,9 @@ class GaussianDistribution
$t = sqrt(-2 * log($pp / 2.0)); // Initial guess $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); $x = -0.70711 * ((2.30753 + $t * 0.27061) / (1.0 + $t * (0.99229 + $t * 0.04481)) - $t);
for ($j = 0; $j < 2; $j++) for ($j = 0; $j < 2; $j++) {
{
$err = GaussianDistribution::errorFunctionCumulativeTo($x) - $pp; $err = GaussianDistribution::errorFunctionCumulativeTo($x) - $pp;
$x += $err/(1.12837916709551257*exp(-square($x)) - $x*$err); // Halley $x += $err / (1.12837916709551257 * exp(-BasicMatch::square($x)) - $x * $err); // Halley
} }
return ($p < 1.0) ? $x : -$x; return ($p < 1.0) ? $x : -$x;
@ -277,4 +258,3 @@ class GaussianDistribution
return sprintf("mean=%.4f standardDeviation=%.4f", $this->_mean, $this->_standardDeviation); return sprintf("mean=%.4f standardDeviation=%.4f", $this->_mean, $this->_standardDeviation);
} }
} }
?>

@ -0,0 +1,9 @@
<?php namespace Moserware\Skills\Numerics;
class IdentityMatrix extends DiagonalMatrix
{
public function __construct($rows)
{
parent::__construct(array_fill(0, $rows, 1));
}
}

@ -1,5 +1,4 @@
<?php <?php namespace Moserware\Skills\Numerics;
namespace Moserware\Numerics;
class Matrix class Matrix
{ {
@ -370,75 +369,3 @@ class Matrix
return true; 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));
}
}
?>

@ -1,10 +1,10 @@
<?php <?php namespace Moserware\Skills\Numerics;
namespace Moserware\Numerics;
// The whole purpose of this class is to make the code for the SkillCalculator(s) // The whole purpose of this class is to make the code for the SkillCalculator(s)
// look a little cleaner // look a little cleaner
use Exception;
class Range class Range
{ {
private $_min; private $_min;
@ -58,5 +58,3 @@ class Range
return ($this->_min <= $value) && ($value <= $this->_max); return ($this->_min <= $value) && ($value <= $this->_max);
} }
} }
?>

@ -0,0 +1,22 @@
<?php namespace Moserware\Skills\Numerics;
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);
}
}

14
src/Numerics/Vector.php Normal file

@ -0,0 +1,14 @@
<?php namespace Moserware\Skills\Numerics;
class Vector extends Matrix
{
public function __construct(array $vectorValues)
{
$columnValues = array();
foreach($vectorValues as $currentVectorValue)
{
$columnValues[] = array($currentVectorValue);
}
parent::__construct(count($vectorValues), 1, $columnValues);
}
}

@ -1,5 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
/** /**
* Represents a comparison between two players. * Represents a comparison between two players.
@ -23,5 +22,3 @@ class PairwiseComparison
} }
} }
} }
?>

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

@ -1,9 +1,4 @@
<?php <?php namespace Moserware\Skills;
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. * Represents a player who has a Rating.
@ -63,12 +58,10 @@ class Player implements ISupportPartialPlay, ISupportPartialUpdate
public function __toString() public function __toString()
{ {
if ($this->_Id != null) if ($this->_Id != null) {
{
return (string)$this->_Id; return (string)$this->_Id;
} }
return parent::__toString(); return parent::__toString();
} }
} }
?>

@ -1,9 +1,6 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Numerics/Range.php"); use Moserware\Skills\Numerics\Range;
use Moserware\Numerics\Range;
class PlayersRange extends Range class PlayersRange extends Range
{ {
@ -17,5 +14,3 @@ class PlayersRange extends Range
return new PlayersRange($min, $max); return new PlayersRange($min, $max);
} }
} }
?>

@ -1,6 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
/** /**
* Helper class to sort ranks in non-decreasing order. * Helper class to sort ranks in non-decreasing order.
@ -10,8 +8,9 @@ class RankSorter
/** /**
* Performs an in-place sort of the items in according to the ranks in non-decreasing order. * 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 array $teams The items to sort according to the order specified by ranks.
* @param $ranks The ranks for each item where 1 is first place. * @param array $teamRanks The ranks for each item where 1 is first place.
* @return array
*/ */
public static function sort(array &$teams, array &$teamRanks) public static function sort(array &$teams, array &$teamRanks)
{ {
@ -19,5 +18,3 @@ class RankSorter
return $teams; return $teams;
} }
} }
?>

@ -1,8 +1,8 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
// Container for a player's rating. // Container for a player's rating.
use Moserware\Skills\Numerics\GaussianDistribution;
class Rating class Rating
{ {
const CONSERVATIVE_STANDARD_DEVIATION_MULTIPLIER = 3; const CONSERVATIVE_STANDARD_DEVIATION_MULTIPLIER = 3;
@ -15,7 +15,7 @@ class Rating
* Constructs a rating. * Constructs a rating.
* @param double $mean The statistical mean value of the rating (also known as mu). * @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 $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. * @param float|int $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) public function __construct($mean, $standardDeviation, $conservativeStandardDeviationMultiplier = self::CONSERVATIVE_STANDARD_DEVIATION_MULTIPLIER)
{ {
@ -65,7 +65,8 @@ class Rating
$partialPosteriorGaussion = GaussianDistribution::fromPrecisionMean( $partialPosteriorGaussion = GaussianDistribution::fromPrecisionMean(
$priorGaussian->getPrecisionMean() + $partialPrecisionMeanDifference, $priorGaussian->getPrecisionMean() + $partialPrecisionMeanDifference,
$priorGaussian->getPrecision() + $partialPrecisionDifference); $priorGaussian->getPrecision() + $partialPrecisionDifference
);
return new Rating($partialPosteriorGaussion->getMean(), $partialPosteriorGaussion->getStandardDeviation(), $prior->_conservativeStandardDeviationMultiplier); return new Rating($partialPosteriorGaussion->getMean(), $partialPosteriorGaussion->getStandardDeviation(), $prior->_conservativeStandardDeviationMultiplier);
} }
@ -75,5 +76,3 @@ class Rating
return sprintf("mean=%.4f, standardDeviation=%.4f", $this->_mean, $this->_standardDeviation); return sprintf("mean=%.4f, standardDeviation=%.4f", $this->_mean, $this->_standardDeviation);
} }
} }
?>

@ -1,9 +1,4 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/HashMap.php");
require_once(dirname(__FILE__) . "/Player.php");
require_once(dirname(__FILE__) . "/Rating.php");
class RatingContainer class RatingContainer
{ {
@ -42,4 +37,3 @@ class RatingContainer
return $this->_playerToRating->count(); return $this->_playerToRating->count();
} }
} }
?>

@ -1,9 +1,6 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/GameInfo.php"); use Exception;
require_once(dirname(__FILE__) . "/PlayersRange.php");
require_once(dirname(__FILE__) . "/TeamsRange.php");
/** /**
* Base class for all skill calculator implementations. * Base class for all skill calculator implementations.
@ -23,9 +20,10 @@ abstract class SkillCalculator
/** /**
* Calculates new ratings based on the prior ratings and team ranks. * Calculates new ratings based on the prior ratings and team ranks.
* @param $gameInfo Parameters for the game. * @param GameInfo $gameInfo Parameters for the game.
* @param $teams A mapping of team players and their ratings. * @param array $teamsOfPlayerToRatings 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). * @param array $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. * @return All the players and their new ratings.
*/ */
public abstract function calculateNewRatings(GameInfo &$gameInfo, public abstract function calculateNewRatings(GameInfo &$gameInfo,
@ -35,8 +33,8 @@ abstract class SkillCalculator
/** /**
* Calculates the match quality as the likelihood of all teams drawing. * Calculates the match quality as the likelihood of all teams drawing.
* *
* @param $gameInfo Parameters for the game. * @param GameInfo $gameInfo Parameters for the game.
* @param $teams A mapping of team players and their ratings. * @param array $teamsOfPlayerToRatings 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). * @return The quality of the match between the teams as a percentage (0% = bad, 100% = well matched).
*/ */
public abstract function calculateMatchQuality(GameInfo &$gameInfo, public abstract function calculateMatchQuality(GameInfo &$gameInfo,
@ -59,17 +57,14 @@ abstract class SkillCalculator
{ {
$countOfTeams = 0; $countOfTeams = 0;
foreach ($teams as $currentTeam) foreach ($teams as $currentTeam) {
{ if (!$playersPerTeam->isInRange($currentTeam->count())) {
if (!$playersPerTeam->isInRange($currentTeam->count())) throw new Exception("Player count is not in range");
{
throw new \Exception("Player count is not in range");
} }
$countOfTeams++; $countOfTeams++;
} }
if (!$totalTeams->isInRange($countOfTeams)) if (!$totalTeams->isInRange($countOfTeams)) {
{
throw new Exception("Team range is not in range"); throw new Exception("Team range is not in range");
} }
} }
@ -81,4 +76,3 @@ class SkillCalculatorSupportedOptions
const PARTIAL_PLAY = 0x01; const PARTIAL_PLAY = 0x01;
const PARTIAL_UPDATE = 0x02; const PARTIAL_UPDATE = 0x02;
} }
?>

@ -1,9 +1,4 @@
<?php <?php namespace Moserware\Skills;
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 class Team extends RatingContainer
{ {
@ -11,7 +6,7 @@ class Team extends RatingContainer
{ {
parent::__construct(); parent::__construct();
if(!\is_null($player)) if(!is_null($player))
{ {
$this->addPlayer($player, $rating); $this->addPlayer($player, $rating);
} }
@ -23,5 +18,3 @@ class Team extends RatingContainer
return $this; return $this;
} }
} }
?>

@ -1,11 +1,10 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
class Teams class Teams
{ {
public static function concat(/*variable arguments*/) public static function concat(/*variable arguments*/)
{ {
$args = \func_get_args(); $args = func_get_args();
$result = array(); $result = array();
foreach ($args as &$currentTeam) { foreach ($args as &$currentTeam) {
@ -16,4 +15,3 @@ class Teams
return $result; return $result;
} }
} }
?>

@ -1,9 +1,6 @@
<?php <?php namespace Moserware\Skills;
namespace Moserware\Skills;
require_once(dirname(__FILE__) . "/Numerics/Range.php"); use Moserware\Skills\Numerics\Range;
use Moserware\Numerics\Range;
class TeamsRange extends Range class TeamsRange extends Range
{ {
@ -17,5 +14,3 @@ class TeamsRange extends Range
return new TeamsRange($min, $max); return new TeamsRange($min, $max);
} }
} }
?>

@ -1,9 +1,6 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
namespace Moserware\Skills\TrueSkill;
require_once(dirname(__FILE__) . "/../Numerics/GaussianDistribution.php"); use Moserware\Skills\Numerics\GaussianDistribution;
use Moserware\Numerics\GaussianDistribution;
final class DrawMargin final class DrawMargin
{ {
@ -17,10 +14,6 @@ final class DrawMargin
// //
// margin = inversecdf((draw probability + 1)/2) * sqrt(n1+n2) * beta // margin = inversecdf((draw probability + 1)/2) * sqrt(n1+n2) * beta
// n1 and n2 are the number of players on each team // n1 and n2 are the number of players on each team
$margin = GaussianDistribution::inverseCumulativeTo(.5*($drawProbability + 1), 0, 1)*sqrt(1 + 1)* return GaussianDistribution::inverseCumulativeTo(.5 * ($drawProbability + 1), 0, 1) * sqrt(1 + 1) * $beta;
$beta;
return $margin;
} }
} }
?>

@ -1,28 +1,13 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
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\GameInfo;
use Moserware\Skills\Guard; use Moserware\Skills\Guard;
use Moserware\Skills\ISupportPartialPlay; use Moserware\Skills\ISupportPartialPlay;
use Moserware\Skills\ISupportPartialUpdate; use Moserware\Skills\ISupportPartialUpdate;
use Moserware\Skills\Numerics\BasicMatch;
use Moserware\Skills\Numerics\DiagonalMatrix;
use Moserware\Skills\Numerics\Matrix;
use Moserware\Skills\Numerics\Vector;
use Moserware\Skills\PartialPlay; use Moserware\Skills\PartialPlay;
use Moserware\Skills\PlayersRange; use Moserware\Skills\PlayersRange;
use Moserware\Skills\RankSorter; use Moserware\Skills\RankSorter;
@ -70,17 +55,19 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
$playerTeamAssignmentsMatrix = $this->createPlayerTeamAssignmentMatrix($teamAssignmentsList, $meanVector->getRowCount()); $playerTeamAssignmentsMatrix = $this->createPlayerTeamAssignmentMatrix($teamAssignmentsList, $meanVector->getRowCount());
$playerTeamAssignmentsMatrixTranspose = $playerTeamAssignmentsMatrix->getTranspose(); $playerTeamAssignmentsMatrixTranspose = $playerTeamAssignmentsMatrix->getTranspose();
$betaSquared = square($gameInfo->getBeta()); $betaSquared = BasicMatch::square($gameInfo->getBeta());
$start = Matrix::multiply($meanVectorTranspose, $playerTeamAssignmentsMatrix); $start = Matrix::multiply($meanVectorTranspose, $playerTeamAssignmentsMatrix);
$aTa = Matrix::multiply( $aTa = Matrix::multiply(
Matrix::scalarMultiply($betaSquared, Matrix::scalarMultiply($betaSquared, $playerTeamAssignmentsMatrixTranspose),
$playerTeamAssignmentsMatrixTranspose), $playerTeamAssignmentsMatrix
$playerTeamAssignmentsMatrix); );
$aTSA = Matrix::multiply( $aTSA = Matrix::multiply(
Matrix::multiply($playerTeamAssignmentsMatrixTranspose, $skillsMatrix), Matrix::multiply($playerTeamAssignmentsMatrixTranspose, $skillsMatrix),
$playerTeamAssignmentsMatrix); $playerTeamAssignmentsMatrix
);
$middle = Matrix::add($aTa, $aTSA); $middle = Matrix::add($aTa, $aTSA);
@ -104,8 +91,7 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
{ {
// A simple vector of all the player means. // A simple vector of all the player means.
return new Vector(self::getPlayerRatingValues($teamAssignmentsList, return new Vector(self::getPlayerRatingValues($teamAssignmentsList,
function($rating) function ($rating) {
{
return $rating->getMean(); return $rating->getMean();
})); }));
} }
@ -116,9 +102,8 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
// players. // players.
return new DiagonalMatrix( return new DiagonalMatrix(
self::getPlayerRatingValues($teamAssignmentsList, self::getPlayerRatingValues($teamAssignmentsList,
function($rating) function ($rating) {
{ return BasicMatch::square($rating->getStandardDeviation());
return square($rating->getStandardDeviation());
})); }));
} }
@ -128,10 +113,8 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
{ {
$playerRatingValues = array(); $playerRatingValues = array();
foreach ($teamAssignmentsList as $currentTeam) foreach ($teamAssignmentsList as $currentTeam) {
{ foreach ($currentTeam->getAllRatings() as $currentRating) {
foreach ($currentTeam->getAllRatings() as $currentRating)
{
$playerRatingValues[] = $playerRatingFunction($currentRating); $playerRatingValues[] = $playerRatingFunction($currentRating);
} }
} }
@ -164,16 +147,14 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
$currentColumn = 0; $currentColumn = 0;
for ($i = 0; $i < $teamAssignmentsListCount - 1; $i++) for ($i = 0; $i < $teamAssignmentsListCount - 1; $i++) {
{
$currentTeam = $teamAssignmentsList[$i]; $currentTeam = $teamAssignmentsList[$i];
// Need to add in 0's for all the previous players, since they're not // Need to add in 0's for all the previous players, since they're not
// on this team // on this team
$playerAssignments[$currentColumn] = ($totalPreviousPlayers > 0) ? \array_fill(0, $totalPreviousPlayers, 0) : array(); $playerAssignments[$currentColumn] = ($totalPreviousPlayers > 0) ? \array_fill(0, $totalPreviousPlayers, 0) : array();
foreach ($currentTeam->getAllPlayers() as $currentPlayer) foreach ($currentTeam->getAllPlayers() as $currentPlayer) {
{
$playerAssignments[$currentColumn][] = PartialPlay::getPartialPlayPercentage($currentPlayer); $playerAssignments[$currentColumn][] = PartialPlay::getPartialPlayPercentage($currentPlayer);
// indicates the player is on the team // indicates the player is on the team
$totalPreviousPlayers++; $totalPreviousPlayers++;
@ -182,15 +163,13 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
$rowsRemaining = $totalPlayers - $totalPreviousPlayers; $rowsRemaining = $totalPlayers - $totalPreviousPlayers;
$nextTeam = $teamAssignmentsList[$i + 1]; $nextTeam = $teamAssignmentsList[$i + 1];
foreach ($nextTeam->getAllPlayers() as $nextTeamPlayer) foreach ($nextTeam->getAllPlayers() as $nextTeamPlayer) {
{
// Add a -1 * playing time to represent the difference // Add a -1 * playing time to represent the difference
$playerAssignments[$currentColumn][] = -1 * PartialPlay::getPartialPlayPercentage($nextTeamPlayer); $playerAssignments[$currentColumn][] = -1 * PartialPlay::getPartialPlayPercentage($nextTeamPlayer);
$rowsRemaining--; $rowsRemaining--;
} }
for ($ixAdditionalRow = 0; $ixAdditionalRow < $rowsRemaining; $ixAdditionalRow++) for ($ixAdditionalRow = 0; $ixAdditionalRow < $rowsRemaining; $ixAdditionalRow++) {
{
// Pad with zeros // Pad with zeros
$playerAssignments[$currentColumn][] = 0; $playerAssignments[$currentColumn][] = 0;
} }
@ -203,5 +182,3 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
return $playerTeamAssignmentsMatrix; return $playerTeamAssignmentsMatrix;
} }
} }
?>

@ -1,16 +1,9 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
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\Factor;
use Moserware\Skills\FactorGraphs\Message; use Moserware\Skills\FactorGraphs\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
use Moserware\Skills\Numerics\GaussianDistribution;
abstract class GaussianFactor extends Factor abstract class GaussianFactor extends Factor
{ {
@ -21,6 +14,9 @@ abstract class GaussianFactor extends Factor
/** /**
* Sends the factor-graph message with and returns the log-normalization constant. * Sends the factor-graph message with and returns the log-normalization constant.
* @param Message $message
* @param Variable $variable
* @return float|int
*/ */
protected function sendMessageVariable(Message &$message, Variable &$variable) protected function sendMessageVariable(Message &$message, Variable &$variable)
{ {
@ -41,5 +37,3 @@ abstract class GaussianFactor extends Factor
return $binding; return $binding;
} }
} }
?>

@ -1,13 +1,6 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
namespace Moserware\Skills\TrueSkill\Factors;
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php"); use Moserware\Skills\Numerics\GaussianDistribution;
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\TrueSkill\TruncatedGaussianCorrectionFunctions;
use Moserware\Skills\FactorGraphs\Message; use Moserware\Skills\FactorGraphs\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
@ -82,4 +75,3 @@ class GaussianGreaterThanFactor extends GaussianFactor
return GaussianDistribution::subtract($newMarginal, $oldMarginal); return GaussianDistribution::subtract($newMarginal, $oldMarginal);
} }
} }
?>

@ -1,14 +1,9 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
namespace Moserware\Skills\TrueSkill\Factors;
require_once(dirname(__FILE__) . "/../../FactorGraphs/Message.php"); use Exception;
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\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
use Moserware\Skills\Numerics\GaussianDistribution;
/** /**
* Connects two variables and adds uncertainty. * Connects two variables and adds uncertainty.
@ -70,8 +65,7 @@ class GaussianLikelihoodFactor extends GaussianFactor
$messages = &$this->getMessages(); $messages = &$this->getMessages();
$vars = &$this->getVariables(); $vars = &$this->getVariables();
switch ($messageIndex) switch ($messageIndex) {
{
case 0: case 0:
return $this->updateHelper($messages[0], $messages[1], return $this->updateHelper($messages[0], $messages[1],
$vars[0], $vars[1]); $vars[0], $vars[1]);
@ -83,5 +77,3 @@ class GaussianLikelihoodFactor extends GaussianFactor
} }
} }
} }
?>

@ -1,14 +1,8 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
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\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
use Moserware\Skills\Numerics\GaussianDistribution;
/** /**
* Supplies the factor graph with prior information. * Supplies the factor graph with prior information.
@ -44,5 +38,3 @@ class GaussianPriorFactor extends GaussianFactor
return GaussianDistribution::subtract($oldMarginal, $newMarginal); return GaussianDistribution::subtract($oldMarginal, $newMarginal);
} }
} }
?>

@ -1,17 +1,10 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
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\Guard;
use Moserware\Skills\FactorGraphs\Message; use Moserware\Skills\FactorGraphs\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
use Moserware\Skills\Numerics\BasicMatch;
use Moserware\Skills\Numerics\GaussianDistribution;
/** /**
* Factor that sums together multiple Gaussians. * Factor that sums together multiple Gaussians.
@ -38,19 +31,17 @@ class GaussianWeightedSumFactor extends GaussianFactor
$variableWeightsLength = count($variableWeights); $variableWeightsLength = count($variableWeights);
$this->_weights[0] = \array_fill(0, count($variableWeights), 0); $this->_weights[0] = \array_fill(0, count($variableWeights), 0);
for($i = 0; $i < $variableWeightsLength; $i++) for ($i = 0; $i < $variableWeightsLength; $i++) {
{
$weight = &$variableWeights[$i]; $weight = &$variableWeights[$i];
$this->_weights[0][$i] = $weight; $this->_weights[0][$i] = $weight;
$this->_weightsSquared[0][$i] = square($weight); $this->_weightsSquared[0][$i] = BasicMatch::square($weight);
} }
$variablesToSumLength = count($variablesToSum); $variablesToSumLength = count($variablesToSum);
// 0..n-1 // 0..n-1
$this->_variableIndexOrdersForWeights[0] = array(); $this->_variableIndexOrdersForWeights[0] = array();
for($i = 0; $i < ($variablesToSumLength + 1); $i++) for ($i = 0; $i < ($variablesToSumLength + 1); $i++) {
{
$this->_variableIndexOrdersForWeights[0][] = $i; $this->_variableIndexOrdersForWeights[0][] = $i;
} }
@ -62,8 +53,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
// By convention, we'll put the v_0 term at the end // By convention, we'll put the v_0 term at the end
$weightsLength = $variableWeightsLength + 1; $weightsLength = $variableWeightsLength + 1;
for ($weightsIndex = 1; $weightsIndex < $weightsLength; $weightsIndex++) for ($weightsIndex = 1; $weightsIndex < $weightsLength; $weightsIndex++) {
{
$currentWeights = \array_fill(0, $variableWeightsLength, 0); $currentWeights = \array_fill(0, $variableWeightsLength, 0);
$variableIndices = \array_fill(0, $variableWeightsLength + 1, 0); $variableIndices = \array_fill(0, $variableWeightsLength + 1, 0);
@ -77,17 +67,14 @@ class GaussianWeightedSumFactor extends GaussianFactor
for ($currentWeightSourceIndex = 0; for ($currentWeightSourceIndex = 0;
$currentWeightSourceIndex < $variableWeightsLength; $currentWeightSourceIndex < $variableWeightsLength;
$currentWeightSourceIndex++) $currentWeightSourceIndex++) {
{ if ($currentWeightSourceIndex == ($weightsIndex - 1)) {
if ($currentWeightSourceIndex == ($weightsIndex - 1))
{
continue; continue;
} }
$currentWeight = (-$variableWeights[$currentWeightSourceIndex] / $variableWeights[$weightsIndex - 1]); $currentWeight = (-$variableWeights[$currentWeightSourceIndex] / $variableWeights[$weightsIndex - 1]);
if ($variableWeights[$weightsIndex - 1] == 0) if ($variableWeights[$weightsIndex - 1] == 0) {
{
// HACK: Getting around division by zero // HACK: Getting around division by zero
$currentWeight = 0; $currentWeight = 0;
} }
@ -102,13 +89,12 @@ class GaussianWeightedSumFactor extends GaussianFactor
// And the final one // And the final one
$finalWeight = 1.0 / $variableWeights[$weightsIndex - 1]; $finalWeight = 1.0 / $variableWeights[$weightsIndex - 1];
if ($variableWeights[$weightsIndex - 1] == 0) if ($variableWeights[$weightsIndex - 1] == 0) {
{
// HACK: Getting around division by zero // HACK: Getting around division by zero
$finalWeight = 0; $finalWeight = 0;
} }
$currentWeights[$currentDestinationWeightIndex] = $finalWeight; $currentWeights[$currentDestinationWeightIndex] = $finalWeight;
$currentWeightsSquared[$currentDestinationWeightIndex] = square($finalWeight); $currentWeightsSquared[$currentDestinationWeightIndex] = BasicMatch::square($finalWeight);
$variableIndices[count($variableWeights)] = 0; $variableIndices[count($variableWeights)] = 0;
$this->_variableIndexOrdersForWeights[] = $variableIndices; $this->_variableIndexOrdersForWeights[] = $variableIndices;
@ -118,8 +104,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
$this->createVariableToMessageBinding($sumVariable); $this->createVariableToMessageBinding($sumVariable);
foreach ($variablesToSum as &$currentVariable) foreach ($variablesToSum as &$currentVariable) {
{
$localCurrentVariable = &$currentVariable; $localCurrentVariable = &$currentVariable;
$this->createVariableToMessageBinding($localCurrentVariable); $this->createVariableToMessageBinding($localCurrentVariable);
} }
@ -134,8 +119,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
// We start at 1 since offset 0 has the sum // We start at 1 since offset 0 has the sum
$varCount = count($vars); $varCount = count($vars);
for ($i = 1; $i < $varCount; $i++) for ($i = 1; $i < $varCount; $i++) {
{
$result += GaussianDistribution::logRatioNormalization($vars[$i]->getValue(), $messages[$i]->getValue()); $result += GaussianDistribution::logRatioNormalization($vars[$i]->getValue(), $messages[$i]->getValue());
} }
@ -160,8 +144,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
$weightsSquaredLength = count($weightsSquared); $weightsSquaredLength = count($weightsSquared);
for ($i = 0; $i < $weightsSquaredLength; $i++) for ($i = 0; $i < $weightsSquaredLength; $i++) {
{
// These flow directly from the paper // These flow directly from the paper
$inverseOfNewPrecisionSum += $weightsSquared[$i] / $inverseOfNewPrecisionSum += $weightsSquared[$i] /
@ -216,8 +199,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
// order as the weights. Thankfully, the weights and messages share the same index numbers, // order as the weights. Thankfully, the weights and messages share the same index numbers,
// so we just need to make sure they're consistent // so we just need to make sure they're consistent
$allMessagesCount = count($allMessages); $allMessagesCount = count($allMessages);
for ($i = 0; $i < $allMessagesCount; $i++) for ($i = 0; $i < $allMessagesCount; $i++) {
{
$updatedMessages[] = &$allMessages[$indicesToUse[$i]]; $updatedMessages[] = &$allMessages[$indicesToUse[$i]];
$updatedVariables[] = &$allVariables[$indicesToUse[$i]]; $updatedVariables[] = &$allVariables[$indicesToUse[$i]];
} }
@ -235,12 +217,10 @@ class GaussianWeightedSumFactor extends GaussianFactor
$result .= ' = '; $result .= ' = ';
$totalVars = count($variablesToSum); $totalVars = count($variablesToSum);
for($i = 0; $i < $totalVars; $i++) for ($i = 0; $i < $totalVars; $i++) {
{
$isFirst = ($i == 0); $isFirst = ($i == 0);
if($isFirst && ($weights[$i] < 0)) if ($isFirst && ($weights[$i] < 0)) {
{
$result .= '-'; $result .= '-';
} }
@ -252,14 +232,10 @@ class GaussianWeightedSumFactor extends GaussianFactor
$isLast = ($i == ($totalVars - 1)); $isLast = ($i == ($totalVars - 1));
if(!$isLast) if (!$isLast) {
{ if ($weights[$i + 1] >= 0) {
if($weights[$i + 1] >= 0)
{
$result .= ' + '; $result .= ' + ';
} } else {
else
{
$result .= ' - '; $result .= ' - ';
} }
} }
@ -268,5 +244,3 @@ class GaussianWeightedSumFactor extends GaussianFactor
return $result; return $result;
} }
} }
?>

@ -1,13 +1,6 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Factors;
namespace Moserware\Skills\TrueSkill\Factors;
require_once(dirname(__FILE__) . "/../TruncatedGaussianCorrectionFunctions.php"); use Moserware\Skills\Numerics\GaussianDistribution;
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\TrueSkill\TruncatedGaussianCorrectionFunctions;
use Moserware\Skills\FactorGraphs\Message; use Moserware\Skills\FactorGraphs\Message;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
@ -80,5 +73,3 @@ class GaussianWithinFactor extends GaussianFactor
return GaussianDistribution::subtract($newMarginal, $oldMarginal); return GaussianDistribution::subtract($newMarginal, $oldMarginal);
} }
} }
?>

@ -1,11 +1,4 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\ScheduleLoop;
use Moserware\Skills\FactorGraphs\ScheduleSequence; use Moserware\Skills\FactorGraphs\ScheduleSequence;
@ -30,7 +23,7 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
public function &getLocalFactors() public function &getLocalFactors()
{ {
$localFactors = $localFactors =
\array_merge($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors(), array_merge($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors(),
$this->_TeamDifferencesComparisonLayer->getLocalFactors()); $this->_TeamDifferencesComparisonLayer->getLocalFactors());
return $localFactors; return $localFactors;
} }
@ -48,8 +41,7 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
public function createPriorSchedule() public function createPriorSchedule()
{ {
switch (count($this->getInputVariablesGroups())) switch (count($this->getInputVariablesGroups())) {
{
case 0: case 0:
case 1: case 1:
throw new InvalidOperationException(); throw new InvalidOperationException();
@ -114,8 +106,7 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$forwardScheduleList = array(); $forwardScheduleList = array();
for ($i = 0; $i < $totalTeamDifferences - 1; $i++) for ($i = 0; $i < $totalTeamDifferences - 1; $i++) {
{
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors(); $teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
$teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors(); $teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors();
@ -143,8 +134,7 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$backwardScheduleList = array(); $backwardScheduleList = array();
for ($i = 0; $i < $totalTeamDifferences - 1; $i++) for ($i = 0; $i < $totalTeamDifferences - 1; $i++) {
{
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors(); $teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = &$this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
$teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors(); $teamDifferencesComparisonLayerLocalFactors = &$this->_TeamDifferencesComparisonLayer->getLocalFactors();
@ -185,5 +175,3 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
return $loop; return $loop;
} }
} }
?>

@ -1,13 +1,4 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\PartialPlay;
use Moserware\Skills\FactorGraphs\ScheduleLoop; use Moserware\Skills\FactorGraphs\ScheduleLoop;
@ -26,8 +17,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
public function buildLayer() public function buildLayer()
{ {
$inputVariablesGroups = &$this->getInputVariablesGroups(); $inputVariablesGroups = &$this->getInputVariablesGroups();
foreach ($inputVariablesGroups as &$currentTeam) foreach ($inputVariablesGroups as &$currentTeam) {
{
$localCurrentTeam = &$currentTeam; $localCurrentTeam = &$currentTeam;
$teamPerformance = &$this->createOutputVariable($localCurrentTeam); $teamPerformance = &$this->createOutputVariable($localCurrentTeam);
$newSumFactor = $this->createPlayerToTeamSumFactor($localCurrentTeam, $teamPerformance); $newSumFactor = $this->createPlayerToTeamSumFactor($localCurrentTeam, $teamPerformance);
@ -46,8 +36,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
$sequence = &$this->scheduleSequence( $sequence = &$this->scheduleSequence(
array_map( array_map(
function($weightedSumFactor) function ($weightedSumFactor) {
{
return new ScheduleStep("Perf to Team Perf Step", $weightedSumFactor, 0); return new ScheduleStep("Perf to Team Perf Step", $weightedSumFactor, 0);
}, },
$localFactors), $localFactors),
@ -58,8 +47,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
protected function createPlayerToTeamSumFactor(&$teamMembers, &$sumVariable) protected function createPlayerToTeamSumFactor(&$teamMembers, &$sumVariable)
{ {
$weights = array_map( $weights = array_map(
function($v) function ($v) {
{
$player = &$v->getKey(); $player = &$v->getKey();
return PartialPlay::getPartialPlayPercentage($player); return PartialPlay::getPartialPlayPercentage($player);
}, },
@ -76,12 +64,10 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
{ {
$allFactors = array(); $allFactors = array();
$localFactors = &$this->getLocalFactors(); $localFactors = &$this->getLocalFactors();
foreach($localFactors as &$currentFactor) foreach ($localFactors as &$currentFactor) {
{
$localCurrentFactor = &$currentFactor; $localCurrentFactor = &$currentFactor;
$numberOfMessages = $localCurrentFactor->getNumberOfMessages(); $numberOfMessages = $localCurrentFactor->getNumberOfMessages();
for($currentIteration = 1; $currentIteration < $numberOfMessages; $currentIteration++) for ($currentIteration = 1; $currentIteration < $numberOfMessages; $currentIteration++) {
{
$allFactors[] = new ScheduleStep("team sum perf @" . $currentIteration, $allFactors[] = new ScheduleStep("team sum perf @" . $currentIteration,
$localCurrentFactor, $currentIteration); $localCurrentFactor, $currentIteration);
} }
@ -91,8 +77,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
private function &createOutputVariable(&$team) private function &createOutputVariable(&$team)
{ {
$memberNames = \array_map(function ($currentPlayer) $memberNames = \array_map(function ($currentPlayer) {
{
return (string)($currentPlayer->getKey()); return (string)($currentPlayer->getKey());
}, },
$team); $team);
@ -102,5 +87,3 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
return $outputVariable; return $outputVariable;
} }
} }
?>

@ -1,20 +1,9 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\Numerics\BasicMatch;
use Moserware\Skills\Rating; use Moserware\Skills\Rating;
use Moserware\Skills\FactorGraphs\ScheduleLoop;
use Moserware\Skills\FactorGraphs\ScheduleSequence;
use Moserware\Skills\FactorGraphs\ScheduleStep; use Moserware\Skills\FactorGraphs\ScheduleStep;
use Moserware\Skills\FactorGraphs\Variable; use Moserware\Skills\FactorGraphs\Variable;
use Moserware\Numerics\GaussianDistribution;
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph; use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
use Moserware\Skills\TrueSkill\Factors\GaussianPriorFactor; use Moserware\Skills\TrueSkill\Factors\GaussianPriorFactor;
@ -33,14 +22,12 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
public function buildLayer() public function buildLayer()
{ {
$teams = &$this->_teams; $teams = &$this->_teams;
foreach ($teams as &$currentTeam) foreach ($teams as &$currentTeam) {
{
$localCurrentTeam = &$currentTeam; $localCurrentTeam = &$currentTeam;
$currentTeamSkills = array(); $currentTeamSkills = array();
$currentTeamAllPlayers = $localCurrentTeam->getAllPlayers(); $currentTeamAllPlayers = $localCurrentTeam->getAllPlayers();
foreach ($currentTeamAllPlayers as &$currentTeamPlayer) foreach ($currentTeamAllPlayers as &$currentTeamPlayer) {
{
$localCurrentTeamPlayer = &$currentTeamPlayer; $localCurrentTeamPlayer = &$currentTeamPlayer;
$currentTeamPlayerRating = $currentTeam->getRating($localCurrentTeamPlayer); $currentTeamPlayerRating = $currentTeam->getRating($localCurrentTeamPlayer);
$playerSkill = &$this->createSkillOutputVariable($localCurrentTeamPlayer); $playerSkill = &$this->createSkillOutputVariable($localCurrentTeamPlayer);
@ -59,8 +46,7 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
$localFactors = &$this->getLocalFactors(); $localFactors = &$this->getLocalFactors();
return $this->scheduleSequence( return $this->scheduleSequence(
array_map( array_map(
function(&$prior) function (&$prior) {
{
return new ScheduleStep("Prior to Skill Step", $prior, 0); return new ScheduleStep("Prior to Skill Step", $prior, 0);
}, },
$localFactors), $localFactors),
@ -69,10 +55,12 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
private function createPriorFactor(&$player, Rating &$priorRating, Variable &$skillsVariable) private function createPriorFactor(&$player, Rating &$priorRating, Variable &$skillsVariable)
{ {
return new GaussianPriorFactor($priorRating->getMean(), return new GaussianPriorFactor(
square($priorRating->getStandardDeviation()) + $priorRating->getMean(),
square($this->getParentFactorGraph()->getGameInfo()->getDynamicsFactor()), BasicMatch::square($priorRating->getStandardDeviation()) +
$skillsVariable); BasicMatch::square($this->getParentFactorGraph()->getGameInfo()->getDynamicsFactor()),
$skillsVariable
);
} }
private function &createSkillOutputVariable(&$key) private function &createSkillOutputVariable(&$key)
@ -83,5 +71,3 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
return $skillOutputVariable; return $skillOutputVariable;
} }
} }
?>

@ -1,15 +1,8 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\ScheduleStep;
use Moserware\Skills\FactorGraphs\KeyedVariable; use Moserware\Skills\FactorGraphs\KeyedVariable;
use Moserware\Skills\Numerics\BasicMatch;
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph; use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
use Moserware\Skills\TrueSkill\Factors\GaussianLikelihoodFactor; use Moserware\Skills\TrueSkill\Factors\GaussianLikelihoodFactor;
@ -25,12 +18,10 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
$inputVariablesGroups = &$this->getInputVariablesGroups(); $inputVariablesGroups = &$this->getInputVariablesGroups();
$outputVariablesGroups = &$this->getOutputVariablesGroups(); $outputVariablesGroups = &$this->getOutputVariablesGroups();
foreach ($inputVariablesGroups as &$currentTeam) foreach ($inputVariablesGroups as &$currentTeam) {
{
$currentTeamPlayerPerformances = array(); $currentTeamPlayerPerformances = array();
foreach ($currentTeam as &$playerSkillVariable) foreach ($currentTeam as &$playerSkillVariable) {
{
$localPlayerSkillVariable = &$playerSkillVariable; $localPlayerSkillVariable = &$playerSkillVariable;
$currentPlayer = &$localPlayerSkillVariable->getKey(); $currentPlayer = &$localPlayerSkillVariable->getKey();
$playerPerformance = &$this->createOutputVariable($currentPlayer); $playerPerformance = &$this->createOutputVariable($currentPlayer);
@ -45,7 +36,11 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
private function createLikelihood(KeyedVariable &$playerSkill, KeyedVariable &$playerPerformance) private function createLikelihood(KeyedVariable &$playerSkill, KeyedVariable &$playerPerformance)
{ {
return new GaussianLikelihoodFactor(square($this->getParentFactorGraph()->getGameInfo()->getBeta()), $playerPerformance, $playerSkill); return new GaussianLikelihoodFactor(
BasicMatch::square($this->getParentFactorGraph()->getGameInfo()->getBeta()),
$playerPerformance,
$playerSkill
);
} }
private function &createOutputVariable(&$key) private function &createOutputVariable(&$key)
@ -59,8 +54,7 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
$localFactors = &$this->getLocalFactors(); $localFactors = &$this->getLocalFactors();
return $this->scheduleSequence( return $this->scheduleSequence(
array_map( array_map(
function($likelihood) function ($likelihood) {
{
return new ScheduleStep("Skill to Perf step", $likelihood, 0); return new ScheduleStep("Skill to Perf step", $likelihood, 0);
}, },
$localFactors), $localFactors),
@ -72,13 +66,10 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
$localFactors = &$this->getLocalFactors(); $localFactors = &$this->getLocalFactors();
return $this->scheduleSequence( return $this->scheduleSequence(
array_map( array_map(
function($likelihood) function ($likelihood) {
{
return new ScheduleStep("name", $likelihood, 1); return new ScheduleStep("name", $likelihood, 1);
}, },
$localFactors), $localFactors),
"All skill to performance sending"); "All skill to performance sending");
} }
} }
?>

@ -1,11 +1,4 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\DrawMargin;
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph; use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
@ -30,8 +23,7 @@ class TeamDifferencesComparisonLayer extends TrueSkillFactorGraphLayer
$inputVarGroups = &$this->getInputVariablesGroups(); $inputVarGroups = &$this->getInputVariablesGroups();
$inputVarGroupsCount = count($inputVarGroups); $inputVarGroupsCount = count($inputVarGroups);
for ($i = 0; $i < $inputVarGroupsCount; $i++) for ($i = 0; $i < $inputVarGroupsCount; $i++) {
{
$isDraw = ($this->_teamRanks[$i] == $this->_teamRanks[$i + 1]); $isDraw = ($this->_teamRanks[$i] == $this->_teamRanks[$i + 1]);
$teamDifference = &$inputVarGroups[$i][0]; $teamDifference = &$inputVarGroups[$i][0];
@ -44,5 +36,3 @@ class TeamDifferencesComparisonLayer extends TrueSkillFactorGraphLayer
} }
} }
} }
?>

@ -1,13 +1,6 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\FactorGraphs\Variable;
use Moserware\Skills\TrueSkill\DrawMargin;
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph; use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
use Moserware\Skills\TrueSkill\Factors\GaussianWeightedSumFactor; use Moserware\Skills\TrueSkill\Factors\GaussianWeightedSumFactor;
@ -52,5 +45,3 @@ class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorG
return $outputVariable; return $outputVariable;
} }
} }
?>

@ -1,8 +1,4 @@
<?php <?php namespace Moserware\Skills\TrueSkill\Layers;
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\FactorGraphs\FactorGraphLayer;
use Moserware\Skills\TrueSkill\TrueSkillFactorGraph; use Moserware\Skills\TrueSkill\TrueSkillFactorGraph;
@ -14,5 +10,3 @@ abstract class TrueSkillFactorGraphLayer extends FactorGraphLayer
parent::__construct($parentGraph); parent::__construct($parentGraph);
} }
} }
?>

@ -1,22 +1,5 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
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\GameInfo;
use Moserware\Skills\Rating; use Moserware\Skills\Rating;
use Moserware\Skills\RatingContainer; use Moserware\Skills\RatingContainer;
@ -42,8 +25,7 @@ class TrueSkillFactorGraph extends FactorGraph
$this->_priorLayer = new PlayerPriorValuesToSkillsLayer($this, $teams); $this->_priorLayer = new PlayerPriorValuesToSkillsLayer($this, $teams);
$this->_gameInfo = $gameInfo; $this->_gameInfo = $gameInfo;
$newFactory = new VariableFactory( $newFactory = new VariableFactory(
function() function () {
{
return GaussianDistribution::fromPrecisionMean(0, 0); return GaussianDistribution::fromPrecisionMean(0, 0);
}); });
@ -69,10 +51,8 @@ class TrueSkillFactorGraph extends FactorGraph
$lastOutput = null; $lastOutput = null;
$layers = &$this->_layers; $layers = &$this->_layers;
foreach ($layers as &$currentLayer) foreach ($layers as &$currentLayer) {
{ if ($lastOutput != null) {
if ($lastOutput != null)
{
$currentLayer->setInputVariablesGroups($lastOutput); $currentLayer->setInputVariablesGroups($lastOutput);
} }
@ -93,11 +73,9 @@ class TrueSkillFactorGraph extends FactorGraph
$factorList = new FactorList(); $factorList = new FactorList();
$layers = &$this->_layers; $layers = &$this->_layers;
foreach ($layers as &$currentLayer) foreach ($layers as &$currentLayer) {
{
$localFactors = &$currentLayer->getLocalFactors(); $localFactors = &$currentLayer->getLocalFactors();
foreach ($localFactors as &$currentFactor) foreach ($localFactors as &$currentFactor) {
{
$localCurrentFactor = &$currentFactor; $localCurrentFactor = &$currentFactor;
$factorList->addFactor($localCurrentFactor); $factorList->addFactor($localCurrentFactor);
} }
@ -112,22 +90,18 @@ class TrueSkillFactorGraph extends FactorGraph
$fullSchedule = array(); $fullSchedule = array();
$layers = &$this->_layers; $layers = &$this->_layers;
foreach ($layers as &$currentLayer) foreach ($layers as &$currentLayer) {
{
$currentPriorSchedule = $currentLayer->createPriorSchedule(); $currentPriorSchedule = $currentLayer->createPriorSchedule();
if ($currentPriorSchedule != null) if ($currentPriorSchedule != null) {
{
$fullSchedule[] = $currentPriorSchedule; $fullSchedule[] = $currentPriorSchedule;
} }
} }
$allLayersReverse = \array_reverse($this->_layers); $allLayersReverse = \array_reverse($this->_layers);
foreach ($allLayersReverse as &$currentLayer) foreach ($allLayersReverse as &$currentLayer) {
{
$currentPosteriorSchedule = $currentLayer->createPosteriorSchedule(); $currentPosteriorSchedule = $currentLayer->createPosteriorSchedule();
if ($currentPosteriorSchedule != null) if ($currentPosteriorSchedule != null) {
{
$fullSchedule[] = $currentPosteriorSchedule; $fullSchedule[] = $currentPosteriorSchedule;
} }
} }
@ -140,10 +114,8 @@ class TrueSkillFactorGraph extends FactorGraph
$result = new RatingContainer(); $result = new RatingContainer();
$priorLayerOutputVariablesGroups = &$this->_priorLayer->getOutputVariablesGroups(); $priorLayerOutputVariablesGroups = &$this->_priorLayer->getOutputVariablesGroups();
foreach ($priorLayerOutputVariablesGroups as &$currentTeam) foreach ($priorLayerOutputVariablesGroups as &$currentTeam) {
{ foreach ($currentTeam as &$currentPlayer) {
foreach ($currentTeam as &$currentPlayer)
{
$localCurrentPlayer = &$currentPlayer->getKey(); $localCurrentPlayer = &$currentPlayer->getKey();
$newRating = new Rating($currentPlayer->getValue()->getMean(), $newRating = new Rating($currentPlayer->getValue()->getMean(),
$currentPlayer->getValue()->getStandardDeviation()); $currentPlayer->getValue()->getStandardDeviation());
@ -155,5 +127,3 @@ class TrueSkillFactorGraph extends FactorGraph
return $result; return $result;
} }
} }
?>

@ -1,9 +1,6 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
namespace Moserware\Skills\TrueSkill;
require_once(dirname(__FILE__) . '/../Numerics/GaussianDistribution.php'); use Moserware\Skills\Numerics\GaussianDistribution;
use Moserware\Numerics\GaussianDistribution;
class TruncatedGaussianCorrectionFunctions class TruncatedGaussianCorrectionFunctions
{ {
@ -15,7 +12,10 @@ class TruncatedGaussianCorrectionFunctions
* In the reference F# implementation, this is referred to as "the additive * In the reference F# implementation, this is referred to as "the additive
* correction of a single-sided truncated Gaussian with unit variance." * correction of a single-sided truncated Gaussian with unit variance."
* *
* @param $teamPerformanceDifference
* @param number $drawMargin In the paper, it's referred to as just "ε". * @param number $drawMargin In the paper, it's referred to as just "ε".
* @param $c
* @return float
*/ */
public static function vExceedsMarginScaled($teamPerformanceDifference, $drawMargin, $c) public static function vExceedsMarginScaled($teamPerformanceDifference, $drawMargin, $c)
{ {
@ -26,8 +26,7 @@ class TruncatedGaussianCorrectionFunctions
{ {
$denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin); $denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin);
if ($denominator < 2.222758749e-162) if ($denominator < 2.222758749e-162) {
{
return -$teamPerformanceDifference + $drawMargin; return -$teamPerformanceDifference + $drawMargin;
} }
@ -50,10 +49,8 @@ class TruncatedGaussianCorrectionFunctions
{ {
$denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin); $denominator = GaussianDistribution::cumulativeTo($teamPerformanceDifference - $drawMargin);
if ($denominator < 2.222758749e-162) if ($denominator < 2.222758749e-162) {
{ if ($teamPerformanceDifference < 0.0) {
if ($teamPerformanceDifference < 0.0)
{
return 1.0; return 1.0;
} }
return 0.0; return 0.0;
@ -77,10 +74,8 @@ class TruncatedGaussianCorrectionFunctions
GaussianDistribution::cumulativeTo($drawMargin - $teamPerformanceDifferenceAbsoluteValue) - GaussianDistribution::cumulativeTo($drawMargin - $teamPerformanceDifferenceAbsoluteValue) -
GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue); GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue);
if ($denominator < 2.222758749e-162) if ($denominator < 2.222758749e-162) {
{ if ($teamPerformanceDifference < 0.0) {
if ($teamPerformanceDifference < 0.0)
{
return -$teamPerformanceDifference - $drawMargin; return -$teamPerformanceDifference - $drawMargin;
} }
@ -90,8 +85,7 @@ class TruncatedGaussianCorrectionFunctions
$numerator = GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue) - $numerator = GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue) -
GaussianDistribution::at($drawMargin - $teamPerformanceDifferenceAbsoluteValue); GaussianDistribution::at($drawMargin - $teamPerformanceDifferenceAbsoluteValue);
if ($teamPerformanceDifference < 0.0) if ($teamPerformanceDifference < 0.0) {
{
return -$numerator / $denominator; return -$numerator / $denominator;
} }
@ -112,8 +106,7 @@ class TruncatedGaussianCorrectionFunctions
- -
GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue); GaussianDistribution::cumulativeTo(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue);
if ($denominator < 2.222758749e-162) if ($denominator < 2.222758749e-162) {
{
return 1.0; return 1.0;
} }
@ -130,4 +123,3 @@ class TruncatedGaussianCorrectionFunctions
GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue)) / $denominator; GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue)) / $denominator;
} }
} }
?>

@ -1,25 +1,8 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
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\GameInfo;
use Moserware\Skills\Guard; use Moserware\Skills\Guard;
use Moserware\Skills\Numerics\BasicMatch;
use Moserware\Skills\PairwiseComparison; use Moserware\Skills\PairwiseComparison;
use Moserware\Skills\RankSorter; use Moserware\Skills\RankSorter;
use Moserware\Skills\Rating; use Moserware\Skills\Rating;
@ -36,7 +19,6 @@ use Moserware\Skills\TeamsRange;
* When you only have two players, a lot of the math simplifies. The main purpose of this class * 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. * is to show the bare minimum of what a TrueSkill implementation should have.
*/ */
class TwoPlayerTrueSkillCalculator extends SkillCalculator class TwoPlayerTrueSkillCalculator extends SkillCalculator
{ {
public function __construct() public function __construct()
@ -86,16 +68,18 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
private static function calculateNewRating(GameInfo $gameInfo, Rating $selfRating, Rating $opponentRating, $comparison) private static function calculateNewRating(GameInfo $gameInfo, Rating $selfRating, Rating $opponentRating, $comparison)
{ {
$drawMargin = DrawMargin::getDrawMarginFromDrawProbability($gameInfo->getDrawProbability(), $drawMargin = DrawMargin::getDrawMarginFromDrawProbability(
$gameInfo->getBeta()); $gameInfo->getDrawProbability(),
$gameInfo->getBeta()
);
$c = $c = sqrt(
sqrt( BasicMatch::square($selfRating->getStandardDeviation())
square($selfRating->getStandardDeviation())
+ +
square($opponentRating->getStandardDeviation()) BasicMatch::square($opponentRating->getStandardDeviation())
+ +
2*square($gameInfo->getBeta())); 2 * BasicMatch::square($gameInfo->getBeta())
);
$winningMean = $selfRating->getMean(); $winningMean = $selfRating->getMean();
$losingMean = $opponentRating->getMean(); $losingMean = $opponentRating->getMean();
@ -128,10 +112,10 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
$rankMultiplier = 1; $rankMultiplier = 1;
} }
$meanMultiplier = (square($selfRating->getStandardDeviation()) + square($gameInfo->getDynamicsFactor()))/$c; $meanMultiplier = (BasicMatch::square($selfRating->getStandardDeviation()) + BasicMatch::square($gameInfo->getDynamicsFactor()))/$c;
$varianceWithDynamics = square($selfRating->getStandardDeviation()) + square($gameInfo->getDynamicsFactor()); $varianceWithDynamics = BasicMatch::square($selfRating->getStandardDeviation()) + BasicMatch::square($gameInfo->getDynamicsFactor());
$stdDevMultiplier = $varianceWithDynamics/square($c); $stdDevMultiplier = $varianceWithDynamics/BasicMatch::square($c);
$newMean = $selfRating->getMean() + ($rankMultiplier*$meanMultiplier*$v); $newMean = $selfRating->getMean() + ($rankMultiplier*$meanMultiplier*$v);
$newStdDev = sqrt($varianceWithDynamics*(1 - $w*$stdDevMultiplier)); $newStdDev = sqrt($varianceWithDynamics*(1 - $w*$stdDevMultiplier));
@ -157,9 +141,9 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
$player2Rating = $team2Ratings[0]; $player2Rating = $team2Ratings[0];
// We just use equation 4.1 found on page 8 of the TrueSkill 2006 paper: // We just use equation 4.1 found on page 8 of the TrueSkill 2006 paper:
$betaSquared = square($gameInfo->getBeta()); $betaSquared = BasicMatch::square($gameInfo->getBeta());
$player1SigmaSquared = square($player1Rating->getStandardDeviation()); $player1SigmaSquared = BasicMatch::square($player1Rating->getStandardDeviation());
$player2SigmaSquared = square($player2Rating->getStandardDeviation()); $player2SigmaSquared = BasicMatch::square($player2Rating->getStandardDeviation());
// This is the square root part of the equation: // This is the square root part of the equation:
$sqrtPart = $sqrtPart =
@ -171,11 +155,10 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
// This is the exponent part of the equation: // This is the exponent part of the equation:
$expPart = $expPart =
exp( exp(
(-1*square($player1Rating->getMean() - $player2Rating->getMean())) (-1*BasicMatch::square($player1Rating->getMean() - $player2Rating->getMean()))
/ /
(2*(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared))); (2*(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared)));
return $sqrtPart*$expPart; return $sqrtPart*$expPart;
} }
} }
?>

@ -1,27 +1,8 @@
<?php <?php namespace Moserware\Skills\TrueSkill;
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\GameInfo;
use Moserware\Skills\Guard; use Moserware\Skills\Guard;
use Moserware\Skills\Numerics\BasicMatch;
use Moserware\Skills\PairwiseComparison; use Moserware\Skills\PairwiseComparison;
use Moserware\Skills\RankSorter; use Moserware\Skills\RankSorter;
use Moserware\Skills\Rating; use Moserware\Skills\Rating;
@ -83,41 +64,39 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
Team $otherTeam, Team $otherTeam,
$selfToOtherTeamComparison) $selfToOtherTeamComparison)
{ {
$drawMargin = DrawMargin::getDrawMarginFromDrawProbability($gameInfo->getDrawProbability(), $drawMargin = DrawMargin::getDrawMarginFromDrawProbability(
$gameInfo->getBeta()); $gameInfo->getDrawProbability(),
$gameInfo->getBeta()
);
$betaSquared = square($gameInfo->getBeta()); $betaSquared = BasicMatch::square($gameInfo->getBeta());
$tauSquared = square($gameInfo->getDynamicsFactor()); $tauSquared = BasicMatch::square($gameInfo->getDynamicsFactor());
$totalPlayers = $selfTeam->count() + $otherTeam->count(); $totalPlayers = $selfTeam->count() + $otherTeam->count();
$meanGetter = $meanGetter = function ($currentRating) {
function($currentRating)
{
return $currentRating->getMean(); return $currentRating->getMean();
}; };
$selfMeanSum = sum($selfTeam->getAllRatings(), $meanGetter); $selfMeanSum = BasicMatch::sum($selfTeam->getAllRatings(), $meanGetter);
$otherTeamMeanSum = sum($otherTeam->getAllRatings(), $meanGetter); $otherTeamMeanSum = BasicMatch::sum($otherTeam->getAllRatings(), $meanGetter);
$varianceGetter = $varianceGetter = function ($currentRating) {
function($currentRating) return BasicMatch::square($currentRating->getStandardDeviation());
{
return square($currentRating->getStandardDeviation());
}; };
$c = sqrt( $c = sqrt(
sum($selfTeam->getAllRatings(), $varianceGetter) BasicMatch::sum($selfTeam->getAllRatings(), $varianceGetter)
+ +
sum($otherTeam->getAllRatings(), $varianceGetter) BasicMatch::sum($otherTeam->getAllRatings(), $varianceGetter)
+ +
$totalPlayers*$betaSquared); $totalPlayers * $betaSquared
);
$winningMean = $selfMeanSum; $winningMean = $selfMeanSum;
$losingMean = $otherTeamMeanSum; $losingMean = $otherTeamMeanSum;
switch ($selfToOtherTeamComparison) switch ($selfToOtherTeamComparison) {
{
case PairwiseComparison::WIN: case PairwiseComparison::WIN:
case PairwiseComparison::DRAW: case PairwiseComparison::DRAW:
// NOP // NOP
@ -130,15 +109,12 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
$meanDelta = $winningMean - $losingMean; $meanDelta = $winningMean - $losingMean;
if ($selfToOtherTeamComparison != PairwiseComparison::DRAW) if ($selfToOtherTeamComparison != PairwiseComparison::DRAW) {
{
// non-draw case // non-draw case
$v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c); $v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c);
$w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c); $w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c);
$rankMultiplier = (int)$selfToOtherTeamComparison; $rankMultiplier = (int)$selfToOtherTeamComparison;
} } else {
else
{
// assume draw // assume draw
$v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c); $v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c);
$w = TruncatedGaussianCorrectionFunctions::wWithinMarginScaled($meanDelta, $drawMargin, $c); $w = TruncatedGaussianCorrectionFunctions::wWithinMarginScaled($meanDelta, $drawMargin, $c);
@ -146,19 +122,18 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
} }
$selfTeamAllPlayers = &$selfTeam->getAllPlayers(); $selfTeamAllPlayers = &$selfTeam->getAllPlayers();
foreach ($selfTeamAllPlayers as &$selfTeamCurrentPlayer) foreach ($selfTeamAllPlayers as &$selfTeamCurrentPlayer) {
{
$localSelfTeamCurrentPlayer = &$selfTeamCurrentPlayer; $localSelfTeamCurrentPlayer = &$selfTeamCurrentPlayer;
$previousPlayerRating = $selfTeam->getRating($localSelfTeamCurrentPlayer); $previousPlayerRating = $selfTeam->getRating($localSelfTeamCurrentPlayer);
$meanMultiplier = (square($previousPlayerRating->getStandardDeviation()) + $tauSquared)/$c; $meanMultiplier = (BasicMatch::square($previousPlayerRating->getStandardDeviation()) + $tauSquared) / $c;
$stdDevMultiplier = (square($previousPlayerRating->getStandardDeviation()) + $tauSquared)/square($c); $stdDevMultiplier = (BasicMatch::square($previousPlayerRating->getStandardDeviation()) + $tauSquared) / BasicMatch::square($c);
$playerMeanDelta = ($rankMultiplier * $meanMultiplier * $v); $playerMeanDelta = ($rankMultiplier * $meanMultiplier * $v);
$newMean = $previousPlayerRating->getMean() + $playerMeanDelta; $newMean = $previousPlayerRating->getMean() + $playerMeanDelta;
$newStdDev = $newStdDev =
sqrt((square($previousPlayerRating->getStandardDeviation()) + $tauSquared)*(1 - $w*$stdDevMultiplier)); sqrt((BasicMatch::square($previousPlayerRating->getStandardDeviation()) + $tauSquared) * (1 - $w * $stdDevMultiplier));
$newPlayerRatings->setRating($localSelfTeamCurrentPlayer, new Rating($newMean, $newStdDev)); $newPlayerRatings->setRating($localSelfTeamCurrentPlayer, new Rating($newMean, $newStdDev));
} }
@ -182,40 +157,34 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
$totalPlayers = $team1Count + $team2Count; $totalPlayers = $team1Count + $team2Count;
$betaSquared = square($gameInfo->getBeta()); $betaSquared = BasicMatch::square($gameInfo->getBeta());
$meanGetter = $meanGetter = function ($currentRating) {
function($currentRating)
{
return $currentRating->getMean(); return $currentRating->getMean();
}; };
$varianceGetter = $varianceGetter = function ($currentRating) {
function($currentRating) return BasicMatch::square($currentRating->getStandardDeviation());
{
return square($currentRating->getStandardDeviation());
}; };
$team1MeanSum = sum($team1Ratings, $meanGetter); $team1MeanSum = BasicMatch::sum($team1Ratings, $meanGetter);
$team1StdDevSquared = sum($team1Ratings, $varianceGetter); $team1StdDevSquared = BasicMatch::sum($team1Ratings, $varianceGetter);
$team2MeanSum = sum($team2Ratings, $meanGetter); $team2MeanSum = BasicMatch::sum($team2Ratings, $meanGetter);
$team2SigmaSquared = sum($team2Ratings, $varianceGetter); $team2SigmaSquared = BasicMatch::sum($team2Ratings, $varianceGetter);
// This comes from equation 4.1 in the TrueSkill paper on page 8 // 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 equation was broken up into the part under the square root sign and
// the exponential part to make the code easier to read. // the exponential part to make the code easier to read.
$sqrtPart $sqrtPart = sqrt(
= sqrt(
($totalPlayers * $betaSquared) ($totalPlayers * $betaSquared)
/ /
($totalPlayers * $betaSquared + $team1StdDevSquared + $team2SigmaSquared) ($totalPlayers * $betaSquared + $team1StdDevSquared + $team2SigmaSquared)
); );
$expPart $expPart = exp(
= exp( (-1 * BasicMatch::square($team1MeanSum - $team2MeanSum))
(-1*square($team1MeanSum - $team2MeanSum))
/ /
(2 * ($totalPlayers * $betaSquared + $team1StdDevSquared + $team2SigmaSquared)) (2 * ($totalPlayers * $betaSquared + $team1StdDevSquared + $team2SigmaSquared))
); );
@ -223,4 +192,3 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
return $expPart * $sqrtPart; return $expPart * $sqrtPart;
} }
} }
?>

@ -1,6 +1,5 @@
<?php namespace Moserware\Skills\Tests\Numerics; <?php namespace Moserware\Skills\Tests\Numerics;
use Moserware\Numerics\GaussianDistribution; use Moserware\Numerics\GaussianDistribution;
use Moserware\Skills\Tests\TestCase; use Moserware\Skills\Tests\TestCase;
@ -37,10 +36,10 @@ class GaussianDistributionTest extends TestCase
$product2 = GaussianDistribution::multiply($m4s5, $m6s7); $product2 = GaussianDistribution::multiply($m4s5, $m6s7);
$expectedMean = (4 * square(7) + 6 * square(5)) / (square(5) + square(7)); $expectedMean = (4 * BasicMatch::square(7) + 6 * BasicMatch::square(5)) / (BasicMatch::square(5) + BasicMatch::square(7));
$this->assertEquals($expectedMean, $product2->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE); $this->assertEquals($expectedMean, $product2->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE);
$expectedSigma = sqrt(((square(5) * square(7)) / (square(5) + square(7)))); $expectedSigma = sqrt(((BasicMatch::square(5) * BasicMatch::square(7)) / (BasicMatch::square(5) + BasicMatch::square(7))));
$this->assertEquals($expectedSigma, $product2->getStandardDeviation(), '', GaussianDistributionTest::ERROR_TOLERANCE); $this->assertEquals($expectedSigma, $product2->getStandardDeviation(), '', GaussianDistributionTest::ERROR_TOLERANCE);
} }
@ -54,7 +53,7 @@ class GaussianDistributionTest extends TestCase
$this->assertEquals(2.0, $productDividedByStandardNormal->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE); $this->assertEquals(2.0, $productDividedByStandardNormal->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE);
$this->assertEquals(3.0, $productDividedByStandardNormal->getStandardDeviation(),'', GaussianDistributionTest::ERROR_TOLERANCE); $this->assertEquals(3.0, $productDividedByStandardNormal->getStandardDeviation(),'', GaussianDistributionTest::ERROR_TOLERANCE);
$product2 = new GaussianDistribution((4 * square(7) + 6 * square(5)) / (square(5) + square(7)), sqrt(((square(5) * square(7)) / (square(5) + square(7))))); $product2 = new GaussianDistribution((4 * BasicMatch::square(7) + 6 * BasicMatch::square(5)) / (BasicMatch::square(5) + BasicMatch::square(7)), sqrt(((BasicMatch::square(5) * BasicMatch::square(7)) / (BasicMatch::square(5) + BasicMatch::square(7)))));
$m4s5 = new GaussianDistribution(4,5); $m4s5 = new GaussianDistribution(4,5);
$product2DividedByM4S5 = GaussianDistribution::divide($product2, $m4s5); $product2DividedByM4S5 = GaussianDistribution::divide($product2, $m4s5);
$this->assertEquals(6.0, $product2DividedByM4S5->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE); $this->assertEquals(6.0, $product2DividedByM4S5->getMean(), '', GaussianDistributionTest::ERROR_TOLERANCE);