1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127:
<?php
namespace Chippyash\Math\Matrix\Transformation;
use Chippyash\Matrix\Transformation\AbstractTransformation;
use Chippyash\Matrix\Matrix;
use Chippyash\Math\Matrix\Exceptions\UndefinedComputationException;
use Chippyash\Math\Matrix\Exceptions\ComputationException;
use Chippyash\Math\Matrix\Traits\CreateCorrectMatrixType;
use Chippyash\Math\Matrix\Traits\AssertMatrixIsNonSingular;
use Chippyash\Math\Matrix\Traits\AssertMatrixIsNumeric;
use Chippyash\Math\Matrix\Transformation\Strategy\Invert\Determinant;
use Chippyash\Math\Matrix\NumericMatrix;
use Chippyash\Math\Type\Calculator;
class Invert extends AbstractTransformation
{
use AssertMatrixIsNumeric;
use AssertMatrixIsNonSingular;
use CreateCorrectMatrixType;
const METHOD_AUTO = 0;
const METHOD_DET = 1;
protected $method;
private $supportedMethods = [self::METHOD_DET, self::METHOD_AUTO];
public function __construct($method = self::METHOD_AUTO)
{
if (in_array($method, $this->supportedMethods)) {
$this->method = $method;
} else {
throw new UndefinedComputationException('Unknown Inverse computation method');
}
}
protected function doTransform(Matrix $mA, $extra = null)
{
$this->assertMatrixIsNumeric($mA);
if ($mA->is('empty')) {
return $this->createCorrectMatrixType($mA);
}
if ($mA->is('singleitem')) {
$item = $mA->get(1,1)->get();
if ($item == 0 || $item == '0+0i') {
throw new ComputationException('Division by zero');
} else {
$calc = new Calculator();
return $this->createCorrectMatrixType($mA, [$calc->reciprocal($mA->get(1,1))]);
}
}
$this->assertMatrixIsNonSingular($mA,'Can only perform inversion on non singular matrix');
$I = $this->invert($mA);
return $I;
}
protected function invert(NumericMatrix $mA)
{
switch ($this->method) {
case self::METHOD_AUTO:
case self::METHOD_DET:
$strategy = new Determinant();
break;
}
return $strategy->invert($mA);
}
}