Pint applied for formatting

This commit is contained in:
Alex Wulf
2022-07-05 15:55:47 +02:00
parent bfc558d1f2
commit 7d4547df6a
68 changed files with 670 additions and 402 deletions

View File

@ -1,4 +1,6 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\Numerics\GaussianDistribution;
@ -16,4 +18,4 @@ final class DrawMargin
// n1 and n2 are the number of players on each team
return GaussianDistribution::inverseCumulativeTo(.5 * ($drawProbability + 1), 0, 1) * sqrt(1 + 1) * $beta;
}
}
}

View File

@ -1,9 +1,9 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\GameInfo;
use DNW\Skills\Guard;
use DNW\Skills\ISupportPartialPlay;
use DNW\Skills\ISupportPartialUpdate;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\Numerics\DiagonalMatrix;
use DNW\Skills\Numerics\Matrix;
@ -29,7 +29,7 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
array $teams,
array $teamRanks)
{
Guard::argumentNotNull($gameInfo, "gameInfo");
Guard::argumentNotNull($gameInfo, 'gameInfo');
$this->validateTeamCountAndPlayersCountPerTeam($teams);
RankSorter::sort($teams, $teamRanks);
@ -109,7 +109,7 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
// Helper function that gets a list of values for all player ratings
private static function getPlayerRatingValues(array $teamAssignmentsList, $playerRatingFunction)
{
$playerRatingValues = array();
$playerRatingValues = [];
foreach ($teamAssignmentsList as $currentTeam) {
foreach ($currentTeam->getAllRatings() as $currentRating) {
@ -138,7 +138,7 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
// | -0.75 0.75 |
// | 0.00 -1.00 |
$playerAssignments = array();
$playerAssignments = [];
$totalPreviousPlayers = 0;
$teamAssignmentsListCount = count($teamAssignmentsList);
@ -150,7 +150,7 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
// Need to add in 0's for all the previous players, since they're not
// on this team
$playerAssignments[$currentColumn] = ($totalPreviousPlayers > 0) ? \array_fill(0, $totalPreviousPlayers, 0) : array();
$playerAssignments[$currentColumn] = ($totalPreviousPlayers > 0) ? \array_fill(0, $totalPreviousPlayers, 0) : [];
foreach ($currentTeam->getAllPlayers() as $currentPlayer) {
$playerAssignments[$currentColumn][] = PartialPlay::getPartialPlayPercentage($currentPlayer);
@ -179,4 +179,4 @@ class FactorGraphTrueSkillCalculator extends SkillCalculator
return $playerTeamAssignmentsMatrix;
}
}
}

View File

@ -1,4 +1,6 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use DNW\Skills\FactorGraphs\Factor;
use DNW\Skills\FactorGraphs\Message;
@ -14,8 +16,9 @@ abstract class GaussianFactor extends Factor
/**
* Sends the factor-graph message with and returns the log-normalization constant.
* @param Message $message
* @param Variable $variable
*
* @param Message $message
* @param Variable $variable
* @return float|int
*/
protected function sendMessageVariable(Message $message, Variable $variable)
@ -24,6 +27,7 @@ abstract class GaussianFactor extends Factor
$messageValue = $message->getValue();
$logZ = GaussianDistribution::logProductNormalization($marginal, $messageValue);
$variable->setValue(GaussianDistribution::multiply($marginal, $messageValue));
return $logZ;
}
@ -33,7 +37,8 @@ abstract class GaussianFactor extends Factor
$binding = parent::createVariableToMessageBindingWithMessage($variable,
new Message(
$newDistribution,
sprintf("message from %s to %s", $this, $variable)));
sprintf('message from %s to %s', $this, $variable)));
return $binding;
}
}
}

View File

@ -1,9 +1,11 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
use DNW\Skills\FactorGraphs\Message;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
/**
* Factor representing a team difference that has exceeded the draw margin.
@ -16,7 +18,7 @@ class GaussianGreaterThanFactor extends GaussianFactor
public function __construct($epsilon, Variable $variable)
{
parent::__construct(\sprintf("%s > %.2f", $variable, $epsilon));
parent::__construct(\sprintf('%s > %.2f', $variable, $epsilon));
$this->_epsilon = $epsilon;
$this->createVariableToMessageBinding($variable);
}
@ -31,6 +33,7 @@ class GaussianGreaterThanFactor extends GaussianFactor
$messages = $this->getMessages();
$message = $messages[0]->getValue();
$messageFromVariable = GaussianDistribution::divide($marginal, $message);
return -GaussianDistribution::logProductNormalization($messageFromVariable, $message)
+
log(
@ -39,7 +42,6 @@ class GaussianGreaterThanFactor extends GaussianFactor
$messageFromVariable->getStandardDeviation()
)
);
}
protected function updateMessageVariable(Message $message, Variable $variable)
@ -82,4 +84,4 @@ class GaussianGreaterThanFactor extends GaussianFactor
// Return the difference in the new marginal
return GaussianDistribution::subtract($newMarginal, $oldMarginal);
}
}
}

View File

@ -1,10 +1,12 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use Exception;
use DNW\Skills\FactorGraphs\KeyedVariable;
use DNW\Skills\FactorGraphs\Message;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\Numerics\GaussianDistribution;
use Exception;
/**
* Connects two variables and adds uncertainty.
@ -17,7 +19,7 @@ class GaussianLikelihoodFactor extends GaussianFactor
public function __construct($betaSquared, Variable $variable1, Variable $variable2)
{
parent::__construct(sprintf("Likelihood of %s going to %s", $variable2, $variable1));
parent::__construct(sprintf('Likelihood of %s going to %s', $variable2, $variable1));
$this->_precision = 1.0 / $betaSquared;
$this->createVariableToMessageBinding($variable1);
$this->createVariableToMessageBinding($variable2);
@ -80,4 +82,4 @@ class GaussianLikelihoodFactor extends GaussianFactor
throw new Exception();
}
}
}
}

View File

@ -1,4 +1,6 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use DNW\Skills\FactorGraphs\Message;
use DNW\Skills\FactorGraphs\Variable;
@ -15,10 +17,10 @@ class GaussianPriorFactor extends GaussianFactor
public function __construct($mean, $variance, Variable $variable)
{
parent::__construct(sprintf("Prior value going to %s", $variable));
parent::__construct(sprintf('Prior value going to %s', $variable));
$this->_newMessage = new GaussianDistribution($mean, sqrt($variance));
$newMessage = new Message(GaussianDistribution::fromPrecisionMean(0, 0),
sprintf("message from %s to %s", $this, $variable));
sprintf('message from %s to %s', $this, $variable));
$this->createVariableToMessageBindingWithMessage($variable, $newMessage);
}
@ -34,6 +36,7 @@ class GaussianPriorFactor extends GaussianFactor
$variable->setValue($newMarginal);
$message->setValue($this->_newMessage);
return GaussianDistribution::subtract($oldMarginal, $newMarginal);
}
}
}

View File

@ -1,8 +1,10 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use DNW\Skills\Guard;
use DNW\Skills\FactorGraphs\Message;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\Guard;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\Numerics\GaussianDistribution;
@ -13,18 +15,19 @@ use DNW\Skills\Numerics\GaussianDistribution;
*/
class GaussianWeightedSumFactor extends GaussianFactor
{
private $_variableIndexOrdersForWeights = array();
private $_variableIndexOrdersForWeights = [];
// This following is used for convenience, for example, the first entry is [0, 1, 2]
// corresponding to v[0] = a1*v[1] + a2*v[2]
private $_weights;
private $_weightsSquared;
public function __construct(Variable $sumVariable, array $variablesToSum, array $variableWeights = null)
{
parent::__construct(self::createName($sumVariable, $variablesToSum, $variableWeights));
$this->_weights = array();
$this->_weightsSquared = array();
$this->_weights = [];
$this->_weightsSquared = [];
// The first weights are a straightforward copy
// v_0 = a_1*v_1 + a_2*v_2 + ... + a_n * v_n
@ -40,7 +43,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
$variablesToSumLength = count($variablesToSum);
// 0..n-1
$this->_variableIndexOrdersForWeights[0] = array();
$this->_variableIndexOrdersForWeights[0] = [];
for ($i = 0; $i < ($variablesToSumLength + 1); $i++) {
$this->_variableIndexOrdersForWeights[0][] = $i;
}
@ -178,6 +181,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
// Return the difference in the new marginal
$finalDiff = GaussianDistribution::subtract($newMarginal, $marginal0);
return $finalDiff;
}
@ -186,10 +190,10 @@ class GaussianWeightedSumFactor extends GaussianFactor
$allMessages = $this->getMessages();
$allVariables = $this->getVariables();
Guard::argumentIsValidIndex($messageIndex, count($allMessages), "messageIndex");
Guard::argumentIsValidIndex($messageIndex, count($allMessages), 'messageIndex');
$updatedMessages = array();
$updatedVariables = array();
$updatedMessages = [];
$updatedVariables = [];
$indicesToUse = $this->_variableIndexOrdersForWeights[$messageIndex];
@ -211,7 +215,7 @@ class GaussianWeightedSumFactor extends GaussianFactor
private static function createName($sumVariable, $variablesToSum, $weights)
{
// TODO: Perf? Use PHP equivalent of StringBuilder? implode on arrays?
$result = (string)$sumVariable;
$result = (string) $sumVariable;
$result .= ' = ';
$totalVars = count($variablesToSum);
@ -222,15 +226,15 @@ class GaussianWeightedSumFactor extends GaussianFactor
$result .= '-';
}
$absValue = sprintf("%.2f", \abs($weights[$i])); // 0.00?
$absValue = sprintf('%.2f', \abs($weights[$i])); // 0.00?
$result .= $absValue;
$result .= "*[";
$result .= (string)$variablesToSum[$i];
$result .= '*[';
$result .= (string) $variablesToSum[$i];
$result .= ']';
$isLast = ($i == ($totalVars - 1));
if (!$isLast) {
if (! $isLast) {
if ($weights[$i + 1] >= 0) {
$result .= ' + ';
} else {
@ -241,4 +245,4 @@ class GaussianWeightedSumFactor extends GaussianFactor
return $result;
}
}
}

View File

@ -1,9 +1,11 @@
<?php namespace DNW\Skills\TrueSkill\Factors;
<?php
namespace DNW\Skills\TrueSkill\Factors;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
use DNW\Skills\FactorGraphs\Message;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\TrueSkill\TruncatedGaussianCorrectionFunctions;
/**
* Factor representing a team difference that has not exceeded the draw margin.
@ -16,7 +18,7 @@ class GaussianWithinFactor extends GaussianFactor
public function __construct($epsilon, Variable $variable)
{
parent::__construct(sprintf("%s <= %.2f", $variable, $epsilon));
parent::__construct(sprintf('%s <= %.2f', $variable, $epsilon));
$this->_epsilon = $epsilon;
$this->createVariableToMessageBinding($variable);
}
@ -57,7 +59,7 @@ class GaussianWithinFactor extends GaussianFactor
$denominator = 1.0 - TruncatedGaussianCorrectionFunctions::wWithinMargin($dOnSqrtC, $epsilonTimesSqrtC);
$newPrecision = $c / $denominator;
$newPrecisionMean = ( $d +
$newPrecisionMean = ($d +
$sqrtC *
TruncatedGaussianCorrectionFunctions::vWithinMargin($dOnSqrtC, $epsilonTimesSqrtC)
) / $denominator;
@ -75,4 +77,4 @@ class GaussianWithinFactor extends GaussianFactor
// Return the difference in the new marginal
return GaussianDistribution::subtract($newMarginal, $oldMarginal);
}
}
}

View File

@ -1,15 +1,18 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use Exception;
use DNW\Skills\FactorGraphs\ScheduleLoop;
use DNW\Skills\FactorGraphs\ScheduleSequence;
use DNW\Skills\FactorGraphs\ScheduleStep;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
use Exception;
// The whole purpose of this is to do a loop on the bottom
class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
{
private $_TeamDifferencesComparisonLayer;
private $_TeamPerformancesToTeamPerformanceDifferencesLayer;
public function __construct(TrueSkillFactorGraph $parentGraph,
@ -65,16 +68,16 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$lastDifferencesFactor = $localFactors[$totalTeamDifferences - 1];
$innerSchedule = new ScheduleSequence(
"inner schedule",
array(
'inner schedule',
[
$loop,
new ScheduleStep(
"teamPerformanceToPerformanceDifferenceFactors[0] @ 1",
'teamPerformanceToPerformanceDifferenceFactors[0] @ 1',
$firstDifferencesFactor, 1),
new ScheduleStep(
sprintf("teamPerformanceToPerformanceDifferenceFactors[teamTeamDifferences = %d - 1] @ 2", $totalTeamDifferences),
$lastDifferencesFactor, 2)
)
sprintf('teamPerformanceToPerformanceDifferenceFactors[teamTeamDifferences = %d - 1] @ 2', $totalTeamDifferences),
$lastDifferencesFactor, 2),
]
);
return $innerSchedule;
@ -87,27 +90,27 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$firstPerfToTeamDiff = $teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[0];
$firstTeamDiffComparison = $teamDifferencesComparisonLayerLocalFactors[0];
$itemsToSequence = array(
$itemsToSequence = [
new ScheduleStep(
"send team perf to perf differences",
'send team perf to perf differences',
$firstPerfToTeamDiff,
0),
new ScheduleStep(
"send to greater than or within factor",
'send to greater than or within factor',
$firstTeamDiffComparison,
0)
);
0),
];
return $this->scheduleSequence(
$itemsToSequence,
"loop of just two teams inner sequence");
'loop of just two teams inner sequence');
}
private function createMultipleTeamInnerPriorLoopSchedule()
{
$totalTeamDifferences = count($this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors());
$forwardScheduleList = array();
$forwardScheduleList = [];
for ($i = 0; $i < $totalTeamDifferences - 1; $i++) {
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = $this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
@ -118,24 +121,24 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$currentForwardSchedulePiece =
$this->scheduleSequence(
array(
[
new ScheduleStep(
sprintf("team perf to perf diff %d", $i),
sprintf('team perf to perf diff %d', $i),
$currentTeamPerfToTeamPerfDiff, 0),
new ScheduleStep(
sprintf("greater than or within result factor %d", $i),
sprintf('greater than or within result factor %d', $i),
$currentTeamDiffComparison, 0),
new ScheduleStep(
sprintf("team perf to perf diff factors [%d], 2", $i),
$currentTeamPerfToTeamPerfDiff, 2)
), sprintf("current forward schedule piece %d", $i));
sprintf('team perf to perf diff factors [%d], 2', $i),
$currentTeamPerfToTeamPerfDiff, 2),
], sprintf('current forward schedule piece %d', $i));
$forwardScheduleList[] = $currentForwardSchedulePiece;
}
$forwardSchedule = new ScheduleSequence("forward schedule", $forwardScheduleList);
$forwardSchedule = new ScheduleSequence('forward schedule', $forwardScheduleList);
$backwardScheduleList = array();
$backwardScheduleList = [];
for ($i = 0; $i < $totalTeamDifferences - 1; $i++) {
$teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors = $this->_TeamPerformancesToTeamPerformanceDifferencesLayer->getLocalFactors();
@ -146,35 +149,35 @@ class IteratedTeamDifferencesInnerLayer extends TrueSkillFactorGraphLayer
$performancesToDifferencesFactor = $teamPerformancesToTeamPerformanceDifferencesLayerLocalFactors[$totalTeamDifferences - 1 - $i];
$currentBackwardSchedulePiece = new ScheduleSequence(
"current backward schedule piece",
array(
'current backward schedule piece',
[
new ScheduleStep(
sprintf("teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 0", $i),
sprintf('teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 0', $i),
$differencesFactor, 0),
new ScheduleStep(
sprintf("greaterThanOrWithinResultFactors[totalTeamDifferences - 1 - %d] @ 0", $i),
sprintf('greaterThanOrWithinResultFactors[totalTeamDifferences - 1 - %d] @ 0', $i),
$comparisonFactor, 0),
new ScheduleStep(
sprintf("teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 1", $i),
$performancesToDifferencesFactor, 1)
));
sprintf('teamPerformanceToPerformanceDifferenceFactors[totalTeamDifferences - 1 - %d] @ 1', $i),
$performancesToDifferencesFactor, 1),
]);
$backwardScheduleList[] = $currentBackwardSchedulePiece;
}
$backwardSchedule = new ScheduleSequence("backward schedule", $backwardScheduleList);
$backwardSchedule = new ScheduleSequence('backward schedule', $backwardScheduleList);
$forwardBackwardScheduleToLoop =
new ScheduleSequence(
"forward Backward Schedule To Loop",
array($forwardSchedule, $backwardSchedule));
'forward Backward Schedule To Loop',
[$forwardSchedule, $backwardSchedule]);
$initialMaxDelta = 0.0001;
$loop = new ScheduleLoop(
sprintf("loop with max delta of %f", $initialMaxDelta),
sprintf('loop with max delta of %f', $initialMaxDelta),
$forwardBackwardScheduleToLoop,
$initialMaxDelta);
return $loop;
}
}
}

View File

@ -1,9 +1,9 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\PartialPlay;
use DNW\Skills\FactorGraphs\ScheduleLoop;
use DNW\Skills\FactorGraphs\ScheduleSequence;
use DNW\Skills\FactorGraphs\ScheduleStep;
use DNW\Skills\PartialPlay;
use DNW\Skills\TrueSkill\Factors\GaussianWeightedSumFactor;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
@ -26,7 +26,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
// REVIEW: Does it make sense to have groups of one?
$outputVariablesGroups = &$this->getOutputVariablesGroups();
$outputVariablesGroups[] = array($teamPerformance);
$outputVariablesGroups[] = [$teamPerformance];
}
}
@ -37,10 +37,11 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
$sequence = $this->scheduleSequence(
array_map(
function ($weightedSumFactor) {
return new ScheduleStep("Perf to Team Perf Step", $weightedSumFactor, 0);
return new ScheduleStep('Perf to Team Perf Step', $weightedSumFactor, 0);
},
$localFactors),
"all player perf to team perf schedule");
'all player perf to team perf schedule');
return $sequence;
}
@ -49,6 +50,7 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
$weights = array_map(
function ($v) {
$player = $v->getKey();
return PartialPlay::getPartialPlayPercentage($player);
},
$teamMembers);
@ -57,32 +59,33 @@ class PlayerPerformancesToTeamPerformancesLayer extends TrueSkillFactorGraphLaye
$sumVariable,
$teamMembers,
$weights);
}
public function createPosteriorSchedule()
{
$allFactors = array();
$allFactors = [];
$localFactors = $this->getLocalFactors();
foreach ($localFactors as $currentFactor) {
$localCurrentFactor = $currentFactor;
$numberOfMessages = $localCurrentFactor->getNumberOfMessages();
for ($currentIteration = 1; $currentIteration < $numberOfMessages; $currentIteration++) {
$allFactors[] = new ScheduleStep("team sum perf @" . $currentIteration,
$allFactors[] = new ScheduleStep('team sum perf @'.$currentIteration,
$localCurrentFactor, $currentIteration);
}
}
return $this->scheduleSequence($allFactors, "all of the team's sum iterations");
}
private function createOutputVariable($team)
{
$memberNames = array_map(function ($currentPlayer) {
return (string)($currentPlayer->getKey());
return (string) ($currentPlayer->getKey());
}, $team);
$teamMemberNames = \join(", ", $memberNames);
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createBasicVariable("Team[" . $teamMemberNames . "]'s performance");
$teamMemberNames = \implode(', ', $memberNames);
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createBasicVariable('Team['.$teamMemberNames."]'s performance");
return $outputVariable;
}
}
}

View File

@ -1,11 +1,13 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\Rating;
use DNW\Skills\FactorGraphs\ScheduleStep;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\Rating;
use DNW\Skills\TrueSkill\Factors\GaussianPriorFactor;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
// We intentionally have no Posterior schedule since the only purpose here is to
// start the process.
@ -24,7 +26,7 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
$teams = $this->_teams;
foreach ($teams as $currentTeam) {
$localCurrentTeam = $currentTeam;
$currentTeamSkills = array();
$currentTeamSkills = [];
$currentTeamAllPlayers = $localCurrentTeam->getAllPlayers();
foreach ($currentTeamAllPlayers as $currentTeamPlayer) {
@ -44,13 +46,14 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
public function createPriorSchedule()
{
$localFactors = $this->getLocalFactors();
return $this->scheduleSequence(
array_map(
function ($prior) {
return new ScheduleStep("Prior to Skill Step", $prior, 0);
return new ScheduleStep('Prior to Skill Step', $prior, 0);
},
$localFactors),
"All priors");
'All priors');
}
private function createPriorFactor($player, Rating $priorRating, Variable $skillsVariable)
@ -67,7 +70,8 @@ class PlayerPriorValuesToSkillsLayer extends TrueSkillFactorGraphLayer
{
$parentFactorGraph = $this->getParentFactorGraph();
$variableFactory = $parentFactorGraph->getVariableFactory();
$skillOutputVariable = $variableFactory->createKeyedVariable($key, $key . "'s skill");
$skillOutputVariable = $variableFactory->createKeyedVariable($key, $key."'s skill");
return $skillOutputVariable;
}
}
}

View File

@ -1,10 +1,12 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\FactorGraphs\ScheduleStep;
use DNW\Skills\FactorGraphs\KeyedVariable;
use DNW\Skills\FactorGraphs\ScheduleStep;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
use DNW\Skills\TrueSkill\Factors\GaussianLikelihoodFactor;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
{
@ -19,7 +21,7 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
$outputVariablesGroups = &$this->getOutputVariablesGroups();
foreach ($inputVariablesGroups as $currentTeam) {
$currentTeamPlayerPerformances = array();
$currentTeamPlayerPerformances = [];
foreach ($currentTeam as $playerSkillVariable) {
$localPlayerSkillVariable = $playerSkillVariable;
@ -45,31 +47,34 @@ class PlayerSkillsToPerformancesLayer extends TrueSkillFactorGraphLayer
private function createOutputVariable($key)
{
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createKeyedVariable($key, $key . "'s performance");
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createKeyedVariable($key, $key."'s performance");
return $outputVariable;
}
public function createPriorSchedule()
{
$localFactors = $this->getLocalFactors();
return $this->scheduleSequence(
array_map(
function ($likelihood) {
return new ScheduleStep("Skill to Perf step", $likelihood, 0);
return new ScheduleStep('Skill to Perf step', $likelihood, 0);
},
$localFactors),
"All skill to performance sending");
'All skill to performance sending');
}
public function createPosteriorSchedule()
{
$localFactors = $this->getLocalFactors();
return $this->scheduleSequence(
array_map(
function ($likelihood) {
return new ScheduleStep("name", $likelihood, 1);
return new ScheduleStep('name', $likelihood, 1);
},
$localFactors),
"All skill to performance sending");
'All skill to performance sending');
}
}

View File

@ -1,13 +1,16 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\TrueSkill\DrawMargin;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
use DNW\Skills\TrueSkill\Factors\GaussianGreaterThanFactor;
use DNW\Skills\TrueSkill\Factors\GaussianWithinFactor;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
class TeamDifferencesComparisonLayer extends TrueSkillFactorGraphLayer
{
private $_epsilon;
private $_teamRanks;
public function __construct(TrueSkillFactorGraph $parentGraph, array $teamRanks)
@ -35,4 +38,4 @@ class TeamDifferencesComparisonLayer extends TrueSkillFactorGraphLayer
$this->addLayerFactor($factor);
}
}
}
}

View File

@ -1,8 +1,10 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\FactorGraphs\Variable;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
use DNW\Skills\TrueSkill\Factors\GaussianWeightedSumFactor;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorGraphLayer
{
@ -17,8 +19,7 @@ class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorG
$inputVariablesGroupsCount = count($inputVariablesGroups);
$outputVariablesGroup = &$this->getOutputVariablesGroups();
for ($i = 0; $i < $inputVariablesGroupsCount - 1; $i++)
{
for ($i = 0; $i < $inputVariablesGroupsCount - 1; $i++) {
$strongerTeam = $inputVariablesGroups[$i][0];
$weakerTeam = $inputVariablesGroups[$i + 1][0];
@ -27,7 +28,7 @@ class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorG
$this->addLayerFactor($newDifferencesFactor);
// REVIEW: Does it make sense to have groups of one?
$outputVariablesGroup[] = array($currentDifference);
$outputVariablesGroup[] = [$currentDifference];
}
}
@ -35,14 +36,16 @@ class TeamPerformancesToTeamPerformanceDifferencesLayer extends TrueSkillFactorG
Variable $weakerTeam,
Variable $output)
{
$teams = array($strongerTeam, $weakerTeam);
$weights = array(1.0, -1.0);
$teams = [$strongerTeam, $weakerTeam];
$weights = [1.0, -1.0];
return new GaussianWeightedSumFactor($output, $teams, $weights);
}
private function createOutputVariable()
{
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createBasicVariable("Team performance difference");
$outputVariable = $this->getParentFactorGraph()->getVariableFactory()->createBasicVariable('Team performance difference');
return $outputVariable;
}
}
}

View File

@ -1,4 +1,6 @@
<?php namespace DNW\Skills\TrueSkill\Layers;
<?php
namespace DNW\Skills\TrueSkill\Layers;
use DNW\Skills\FactorGraphs\FactorGraphLayer;
use DNW\Skills\TrueSkill\TrueSkillFactorGraph;
@ -9,4 +11,4 @@ abstract class TrueSkillFactorGraphLayer extends FactorGraphLayer
{
parent::__construct($parentGraph);
}
}
}

View File

@ -1,13 +1,15 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\GameInfo;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\Rating;
use DNW\Skills\RatingContainer;
use DNW\Skills\FactorGraphs\FactorGraph;
use DNW\Skills\FactorGraphs\FactorList;
use DNW\Skills\FactorGraphs\ScheduleSequence;
use DNW\Skills\FactorGraphs\VariableFactory;
use DNW\Skills\GameInfo;
use DNW\Skills\Numerics\GaussianDistribution;
use DNW\Skills\Rating;
use DNW\Skills\RatingContainer;
use DNW\Skills\TrueSkill\Layers\IteratedTeamDifferencesInnerLayer;
use DNW\Skills\TrueSkill\Layers\PlayerPerformancesToTeamPerformancesLayer;
use DNW\Skills\TrueSkill\Layers\PlayerPriorValuesToSkillsLayer;
@ -18,7 +20,9 @@ use DNW\Skills\TrueSkill\Layers\TeamPerformancesToTeamPerformanceDifferencesLaye
class TrueSkillFactorGraph extends FactorGraph
{
private $_gameInfo;
private $_layers;
private $_priorLayer;
public function __construct(GameInfo $gameInfo, array $teams, array $teamRanks)
@ -31,15 +35,15 @@ class TrueSkillFactorGraph extends FactorGraph
});
$this->setVariableFactory($newFactory);
$this->_layers = array(
$this->_layers = [
$this->_priorLayer,
new PlayerSkillsToPerformancesLayer($this),
new PlayerPerformancesToTeamPerformancesLayer($this),
new IteratedTeamDifferencesInnerLayer(
$this,
new TeamPerformancesToTeamPerformanceDifferencesLayer($this),
new TeamDifferencesComparisonLayer($this, $teamRanks))
);
new TeamDifferencesComparisonLayer($this, $teamRanks)),
];
}
public function getGameInfo()
@ -83,12 +87,13 @@ class TrueSkillFactorGraph extends FactorGraph
}
$logZ = $factorList->getLogNormalization();
return exp($logZ);
}
private function createFullSchedule()
{
$fullSchedule = array();
$fullSchedule = [];
$layers = $this->_layers;
foreach ($layers as $currentLayer) {
@ -107,7 +112,7 @@ class TrueSkillFactorGraph extends FactorGraph
}
}
return new ScheduleSequence("Full schedule", $fullSchedule);
return new ScheduleSequence('Full schedule', $fullSchedule);
}
public function getUpdatedRatings()
@ -127,4 +132,4 @@ class TrueSkillFactorGraph extends FactorGraph
return $result;
}
}
}

View File

@ -1,4 +1,6 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\Numerics\GaussianDistribution;
@ -13,7 +15,7 @@ class TruncatedGaussianCorrectionFunctions
* 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
*/
@ -57,10 +59,12 @@ class TruncatedGaussianCorrectionFunctions
if ($teamPerformanceDifference < 0.0) {
return 1.0;
}
return 0.0;
}
$vWin = self::vExceedsMargin($teamPerformanceDifference, $drawMargin);
return $vWin * ($vWin + $teamPerformanceDifference - $drawMargin);
}
@ -126,4 +130,4 @@ class TruncatedGaussianCorrectionFunctions
*
GaussianDistribution::at(-$drawMargin - $teamPerformanceDifferenceAbsoluteValue)) / $denominator;
}
}
}

View File

@ -1,15 +1,17 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\GameInfo;
use DNW\Skills\Guard;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\PairwiseComparison;
use DNW\Skills\PlayersRange;
use DNW\Skills\RankSorter;
use DNW\Skills\Rating;
use DNW\Skills\RatingContainer;
use DNW\Skills\SkillCalculator;
use DNW\Skills\SkillCalculatorSupportedOptions;
use DNW\Skills\PlayersRange;
use DNW\Skills\TeamsRange;
/**
@ -30,7 +32,7 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
array $teamRanks)
{
// Basic argument checking
Guard::argumentNotNull($gameInfo, "gameInfo");
Guard::argumentNotNull($gameInfo, 'gameInfo');
$this->validateTeamCountAndPlayersCountPerTeam($teams);
// Make sure things are in order
@ -83,8 +85,7 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
$winningMean = $selfRating->getMean();
$losingMean = $opponentRating->getMean();
switch ($comparison)
{
switch ($comparison) {
case PairwiseComparison::WIN:
case PairwiseComparison::DRAW:
// NOP
@ -97,37 +98,34 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
$meanDelta = $winningMean - $losingMean;
if ($comparison != PairwiseComparison::DRAW)
{
if ($comparison != PairwiseComparison::DRAW) {
// non-draw case
$v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c);
$w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c);
$rankMultiplier = (int) $comparison;
}
else
{
} else {
$v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c);
$w = TruncatedGaussianCorrectionFunctions::wWithinMarginScaled($meanDelta, $drawMargin, $c);
$rankMultiplier = 1;
}
$meanMultiplier = (BasicMath::square($selfRating->getStandardDeviation()) + BasicMath::square($gameInfo->getDynamicsFactor()))/$c;
$meanMultiplier = (BasicMath::square($selfRating->getStandardDeviation()) + BasicMath::square($gameInfo->getDynamicsFactor())) / $c;
$varianceWithDynamics = BasicMath::square($selfRating->getStandardDeviation()) + BasicMath::square($gameInfo->getDynamicsFactor());
$stdDevMultiplier = $varianceWithDynamics/BasicMath::square($c);
$stdDevMultiplier = $varianceWithDynamics / BasicMath::square($c);
$newMean = $selfRating->getMean() + ($rankMultiplier*$meanMultiplier*$v);
$newStdDev = sqrt($varianceWithDynamics*(1 - $w*$stdDevMultiplier));
$newMean = $selfRating->getMean() + ($rankMultiplier * $meanMultiplier * $v);
$newStdDev = sqrt($varianceWithDynamics * (1 - $w * $stdDevMultiplier));
return new Rating($newMean, $newStdDev);
}
/**
* {@inheritdoc }
* {@inheritdoc}
*/
public function calculateMatchQuality(GameInfo $gameInfo, array $teams)
{
Guard::argumentNotNull($gameInfo, "gameInfo");
Guard::argumentNotNull($gameInfo, 'gameInfo');
$this->validateTeamCountAndPlayersCountPerTeam($teams);
$team1 = $teams[0];
@ -146,18 +144,18 @@ class TwoPlayerTrueSkillCalculator extends SkillCalculator
// This is the square root part of the equation:
$sqrtPart = sqrt(
(2*$betaSquared)
(2 * $betaSquared)
/
(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared)
(2 * $betaSquared + $player1SigmaSquared + $player2SigmaSquared)
);
// This is the exponent part of the equation:
$expPart = exp(
(-1*BasicMath::square($player1Rating->getMean() - $player2Rating->getMean()))
(-1 * BasicMath::square($player1Rating->getMean() - $player2Rating->getMean()))
/
(2*(2*$betaSquared + $player1SigmaSquared + $player2SigmaSquared))
(2 * (2 * $betaSquared + $player1SigmaSquared + $player2SigmaSquared))
);
return $sqrtPart*$expPart;
return $sqrtPart * $expPart;
}
}
}

View File

@ -1,19 +1,19 @@
<?php namespace DNW\Skills\TrueSkill;
<?php
namespace DNW\Skills\TrueSkill;
use DNW\Skills\GameInfo;
use DNW\Skills\Guard;
use DNW\Skills\Numerics\BasicMath;
use DNW\Skills\PairwiseComparison;
use DNW\Skills\PlayersRange;
use DNW\Skills\RankSorter;
use DNW\Skills\Rating;
use DNW\Skills\RatingContainer;
use DNW\Skills\SkillCalculator;
use DNW\Skills\SkillCalculatorSupportedOptions;
use DNW\Skills\PlayersRange;
use DNW\Skills\TeamsRange;
use DNW\Skills\Team;
use DNW\Skills\TeamsRange;
/**
* Calculates new ratings for only two teams where each team has 1 or more players.
@ -29,7 +29,7 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
public function calculateNewRatings(GameInfo $gameInfo, array $teams, array $teamRanks)
{
Guard::argumentNotNull($gameInfo, "gameInfo");
Guard::argumentNotNull($gameInfo, 'gameInfo');
$this->validateTeamCountAndPlayersCountPerTeam($teams);
RankSorter::sort($teams, $teamRanks);
@ -111,7 +111,7 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
// non-draw case
$v = TruncatedGaussianCorrectionFunctions::vExceedsMarginScaled($meanDelta, $drawMargin, $c);
$w = TruncatedGaussianCorrectionFunctions::wExceedsMarginScaled($meanDelta, $drawMargin, $c);
$rankMultiplier = (int)$selfToOtherTeamComparison;
$rankMultiplier = (int) $selfToOtherTeamComparison;
} else {
// assume draw
$v = TruncatedGaussianCorrectionFunctions::vWithinMarginScaled($meanDelta, $drawMargin, $c);
@ -143,7 +143,7 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
*/
public function calculateMatchQuality(GameInfo $gameInfo, array $teams)
{
Guard::argumentNotNull($gameInfo, "gameInfo");
Guard::argumentNotNull($gameInfo, 'gameInfo');
$this->validateTeamCountAndPlayersCountPerTeam($teams);
// We've verified that there's just two teams
@ -189,4 +189,4 @@ class TwoTeamTrueSkillCalculator extends SkillCalculator
return $expPart * $sqrtPart;
}
}
}