Moved UnitTests to tests/ and Skills to src/

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

View File

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

View File

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

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

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

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

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