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:
<?php
namespace Chippyash\Math\Matrix\Transformation;
use Chippyash\Math\Matrix\Exceptions\MathMatrixException;
use Chippyash\Matrix\Transformation\AbstractTransformation;
use Chippyash\Matrix\Matrix;
use Chippyash\Math\Matrix\Traits\AssertMatrixIsNumeric;
use Chippyash\Math\Matrix\NumericMatrix;
use Chippyash\Math\Type\Calculator;
use Chippyash\Math\Type\Comparator;
use Chippyash\Type\Interfaces\NumericTypeInterface;
use Chippyash\Type\Number\IntType;
use Chippyash\Type\TypeFactory;
class MarkovRandomWalk extends AbstractTransformation
{
use AssertMatrixIsNumeric;
protected function doTransform(Matrix $mA, $extra = null)
{
$this->assertMatrixIsNumeric($mA);
if (!array_key_exists('start', $extra)) {
throw new MathMatrixException('Supply start row');
}
if (!$extra['start'] instanceof IntType) {
throw new MathMatrixException('Start parameter must be IntType');
}
if (!array_key_exists('target', $extra)) {
throw new MathMatrixException('Supply target row');
}
if (!$extra['target'] instanceof IntType) {
throw new MathMatrixException('Target parameter must be IntType');
}
if (!array_key_exists('limit', $extra)) {
$extra['limit'] = TypeFactory::createInt(100);
}
if (!$extra['limit'] instanceof IntType) {
throw new MathMatrixException('Limit parameter must be IntType');
}
return $this->walk($mA, $extra['start'], $extra['target'], $extra['limit']);
}
protected function walk(
NumericMatrix $mA,
NumericTypeInterface $start,
NumericTypeInterface $target,
NumericTypeInterface $limit)
{
$zero = TypeFactory::createInt(0);
$one = TypeFactory::createInt(1);
$calc = new Calculator();
$comp = new Comparator();
$lim = $calc->sub($limit, $one);
$walk = [$start];
while ($comp->neq($start, $target) && $comp->neq($lim, $zero)) {
$start = $mA('MarkovWeightedRandom', $start);
$walk[] = $start;
$lim = $calc->sub($lim, $one);
}
return new NumericMatrix($walk);
}
}