Exemplo n.º 1
0
 function TestMatrix()
 {
     // define test variables
     $errorCount = 0;
     $warningCount = 0;
     $columnwise = array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
     $rowwise = array(1.0, 4.0, 7.0, 10.0, 2.0, 5.0, 8.0, 11.0, 3.0, 6.0, 9.0, 12.0);
     $avals = array(array(1.0, 4.0, 7.0, 10.0), array(2.0, 5.0, 8.0, 11.0), array(3.0, 6.0, 9.0, 12.0));
     $rankdef = $avals;
     $tvals = array(array(1.0, 2.0, 3.0), array(4.0, 5.0, 6.0), array(7.0, 8.0, 9.0), array(10.0, 11.0, 12.0));
     $subavals = array(array(5.0, 8.0, 11.0), array(6.0, 9.0, 12.0));
     $rvals = array(array(1.0, 4.0, 7.0), array(2.0, 5.0, 8.0, 11.0), array(3.0, 6.0, 9.0, 12.0));
     $pvals = array(array(1.0, 1.0, 1.0), array(1.0, 2.0, 3.0), array(1.0, 3.0, 6.0));
     $ivals = array(array(1.0, 0.0, 0.0, 0.0), array(0.0, 1.0, 0.0, 0.0), array(0.0, 0.0, 1.0, 0.0));
     $evals = array(array(0.0, 1.0, 0.0, 0.0), array(1.0, 0.0, 2.0E-7, 0.0), array(0.0, -2.0E-7, 0.0, 1.0), array(0.0, 0.0, 1.0, 0.0));
     $square = array(array(166.0, 188.0, 210.0), array(188.0, 214.0, 240.0), array(210.0, 240.0, 270.0));
     $sqSolution = array(array(13.0), array(15.0));
     $condmat = array(array(1.0, 3.0), array(7.0, 9.0));
     $rows = 3;
     $cols = 4;
     $invalidID = 5;
     /* should trigger bad shape for construction with val        */
     $raggedr = 0;
     /* (raggedr,raggedc) should be out of bounds in ragged array */
     $raggedc = 4;
     $validID = 3;
     /* leading dimension of intended test Matrices               */
     $nonconformld = 4;
     /* leading dimension which is valid, but nonconforming       */
     $ib = 1;
     /* index ranges for sub Matrix                               */
     $ie = 2;
     $jb = 1;
     $je = 3;
     $rowindexset = array(1, 2);
     $badrowindexset = array(1, 3);
     $columnindexset = array(1, 2, 3);
     $badcolumnindexset = array(1, 2, 4);
     $columnsummax = 33.0;
     $rowsummax = 30.0;
     $sumofdiagonals = 15;
     $sumofsquares = 650;
     /**
      * Test matrix methods
      */
     /**
      * Constructors and constructor-like methods:
      *
      *   Matrix(double[], int)
      *   Matrix(double[][])
      *   Matrix(int, int)
      *   Matrix(int, int, double)
      *   Matrix(int, int, double[][])
      *   constructWithCopy(double[][])
      *   random(int,int)
      *   identity(int)
      */
     echo "<p>Testing constructors and constructor-like methods...</p>";
     $A = new Matrix($columnwise, 3);
     if ($A instanceof Matrix) {
         $this->try_success("Column-packed constructor...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Column-packed constructor...", "Unable to construct Matrix");
     }
     $T = new Matrix($tvals);
     if ($T instanceof Matrix) {
         $this->try_success("2D array constructor...");
     } else {
         $errorCount = $this->try_failure($errorCount, "2D array constructor...", "Unable to construct Matrix");
     }
     $A = new Matrix($columnwise, $validID);
     $B = new Matrix($avals);
     $tmp = $B->get(0, 0);
     $avals[0][0] = 0.0;
     $C = $B->minus($A);
     $avals[0][0] = $tmp;
     $B = Matrix::constructWithCopy($avals);
     $tmp = $B->get(0, 0);
     $avals[0][0] = 0.0;
     /** check that constructWithCopy behaves properly **/
     if ($tmp - $B->get(0, 0) != 0.0) {
         $errorCount = $this->try_failure($errorCount, "constructWithCopy... ", "copy not effected... data visible outside");
     } else {
         $this->try_success("constructWithCopy... ", "");
     }
     $I = new Matrix($ivals);
     if ($this->checkMatrices($I, Matrix::identity(3, 4))) {
         $this->try_success("identity... ", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "identity... ", "identity Matrix not successfully created");
     }
     /**
      * Access Methods:
      *
      *   getColumnDimension()
      *   getRowDimension()
      *   getArray()
      *   getArrayCopy()
      *   getColumnPackedCopy()
      *   getRowPackedCopy()
      *   get(int,int)
      *   getMatrix(int,int,int,int)
      *   getMatrix(int,int,int[])
      *   getMatrix(int[],int,int)
      *   getMatrix(int[],int[])
      *   set(int,int,double)
      *   setMatrix(int,int,int,int,Matrix)
      *   setMatrix(int,int,int[],Matrix)
      *   setMatrix(int[],int,int,Matrix)
      *   setMatrix(int[],int[],Matrix)
      */
     print "<p>Testing access methods...</p>";
     $B = new Matrix($avals);
     if ($B->getRowDimension() == $rows) {
         $this->try_success("getRowDimension...");
     } else {
         $errorCount = $this->try_failure($errorCount, "getRowDimension...");
     }
     if ($B->getColumnDimension() == $cols) {
         $this->try_success("getColumnDimension...");
     } else {
         $errorCount = $this->try_failure($errorCount, "getColumnDimension...");
     }
     $barray = $B->getArray();
     if ($this->checkArrays($barray, $avals)) {
         $this->try_success("getArray...");
     } else {
         $errorCount = $this->try_failure($errorCount, "getArray...");
     }
     $bpacked = $B->getColumnPackedCopy();
     if ($this->checkArrays($bpacked, $columnwise)) {
         $this->try_success("getColumnPackedCopy...");
     } else {
         $errorCount = $this->try_failure($errorCount, "getColumnPackedCopy...");
     }
     $bpacked = $B->getRowPackedCopy();
     if ($this->checkArrays($bpacked, $rowwise)) {
         $this->try_success("getRowPackedCopy...");
     } else {
         $errorCount = $this->try_failure($errorCount, "getRowPackedCopy...");
     }
     /**
      * Array-like methods:
      *   minus
      *   minusEquals
      *   plus
      *   plusEquals
      *   arrayLeftDivide
      *   arrayLeftDivideEquals
      *   arrayRightDivide
      *   arrayRightDivideEquals
      *   arrayTimes
      *   arrayTimesEquals
      *   uminus
      */
     print "<p>Testing array-like methods...</p>";
     /**
      * I/O methods:
      *   read
      *   print
      *   serializable:
      *   writeObject
      *   readObject
      */
     print "<p>Testing I/O methods...</p>";
     /**
      * Test linear algebra methods
      */
     echo "<p>Testing linear algebra methods...<p>";
     $A = new Matrix($columnwise, 3);
     if ($this->checkMatrices($A->transpose(), $T)) {
         $this->try_success("Transpose check...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Transpose check...", "Matrices are not equal");
     }
     if ($this->checkScalars($A->norm1(), $columnsummax)) {
         $this->try_success("Maximum column sum...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Maximum column sum...", "Incorrect: " . $A->norm1() . " != " . $columnsummax);
     }
     if ($this->checkScalars($A->normInf(), $rowsummax)) {
         $this->try_success("Maximum row sum...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Maximum row sum...", "Incorrect: " . $A->normInf() . " != " . $rowsummax);
     }
     if ($this->checkScalars($A->normF(), sqrt($sumofsquares))) {
         $this->try_success("Frobenius norm...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Frobenius norm...", "Incorrect:" . $A->normF() . " != " . sqrt($sumofsquares));
     }
     if ($this->checkScalars($A->trace(), $sumofdiagonals)) {
         $this->try_success("Matrix trace...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Matrix trace...", "Incorrect: " . $A->trace() . " != " . $sumofdiagonals);
     }
     $B = $A->getMatrix(0, $A->getRowDimension(), 0, $A->getRowDimension());
     if ($B->det() == 0) {
         $this->try_success("Matrix determinant...");
     } else {
         $errorCount = $this->try_failure($errorCount, "Matrix determinant...", "Incorrect: " . $B->det() . " != " . 0);
     }
     $A = new Matrix($columnwise, 3);
     $SQ = new Matrix($square);
     if ($this->checkMatrices($SQ, $A->times($A->transpose()))) {
         $this->try_success("times(Matrix)...");
     } else {
         $errorCount = $this->try_failure($errorCount, "times(Matrix)...", "Unable to multiply matrices");
         $SQ->toHTML();
         $AT->toHTML();
     }
     $A = new Matrix($columnwise, 4);
     $QR = $A->qr();
     $R = $QR->getR();
     $Q = $QR->getQ();
     if ($this->checkMatrices($A, $Q->times($R))) {
         $this->try_success("QRDecomposition...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "QRDecomposition...", "incorrect qr decomposition calculation");
     }
     $A = new Matrix($columnwise, 4);
     $SVD = $A->svd();
     $U = $SVD->getU();
     $S = $SVD->getS();
     $V = $SVD->getV();
     if ($this->checkMatrices($A, $U->times($S->times($V->transpose())))) {
         $this->try_success("SingularValueDecomposition...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation");
     }
     $n = $A->getColumnDimension();
     $A = $A->getMatrix(0, $n - 1, 0, $n - 1);
     $A->set(0, 0, 0.0);
     $LU = $A->lu();
     $L = $LU->getL();
     if ($this->checkMatrices($A->getMatrix($LU->getPivot(), 0, $n - 1), $L->times($LU->getU()))) {
         $this->try_success("LUDecomposition...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "LUDecomposition...", "incorrect LU decomposition calculation");
     }
     $X = $A->inverse();
     if ($this->checkMatrices($A->times($X), Matrix::identity(3, 3))) {
         $this->try_success("inverse()...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "inverse()...", "incorrect inverse calculation");
     }
     $DEF = new Matrix($rankdef);
     if ($this->checkScalars($DEF->rank(), min($DEF->getRowDimension(), $DEF->getColumnDimension()) - 1)) {
         $this->try_success("Rank...");
     } else {
         $this->try_failure("Rank...", "incorrect rank calculation");
     }
     $B = new Matrix($condmat);
     $SVD = $B->svd();
     $singularvalues = $SVD->getSingularValues();
     if ($this->checkScalars($B->cond(), $singularvalues[0] / $singularvalues[min($B->getRowDimension(), $B->getColumnDimension()) - 1])) {
         $this->try_success("Condition number...");
     } else {
         $this->try_failure("Condition number...", "incorrect condition number calculation");
     }
     $SUB = new Matrix($subavals);
     $O = new Matrix($SUB->getRowDimension(), 1, 1.0);
     $SOL = new Matrix($sqSolution);
     $SQ = $SUB->getMatrix(0, $SUB->getRowDimension() - 1, 0, $SUB->getRowDimension() - 1);
     if ($this->checkMatrices($SQ->solve($SOL), $O)) {
         $this->try_success("solve()...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "solve()...", "incorrect lu solve calculation");
     }
     $A = new Matrix($pvals);
     $Chol = $A->chol();
     $L = $Chol->getL();
     if ($this->checkMatrices($A, $L->times($L->transpose()))) {
         $this->try_success("CholeskyDecomposition...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation");
     }
     $X = $Chol->solve(Matrix::identity(3, 3));
     if ($this->checkMatrices($A->times($X), Matrix::identity(3, 3))) {
         $this->try_success("CholeskyDecomposition solve()...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation");
     }
     $Eig = $A->eig();
     $D = $Eig->getD();
     $V = $Eig->getV();
     if ($this->checkMatrices($A->times($V), $V->times($D))) {
         $this->try_success("EigenvalueDecomposition (symmetric)...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation");
     }
     $A = new Matrix($evals);
     $Eig = $A->eig();
     $D = $Eig->getD();
     $V = $Eig->getV();
     if ($this->checkMatrices($A->times($V), $V->times($D))) {
         $this->try_success("EigenvalueDecomposition (nonsymmetric)...", "");
     } else {
         $errorCount = $this->try_failure($errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation");
     }
     print "<b>{$errorCount} total errors</b>.";
 }
Exemplo n.º 2
0
 /**
  *	Least squares solution of A*X = B
  *
  *	@param Matrix $B A Matrix with as many rows as A and any number of columns.
  *	@return Matrix Matrix that minimizes the two norm of Q*R*X-B.
  */
 public function solve($B)
 {
     if ($B->getRowDimension() == $this->m) {
         if ($this->isFullRank()) {
             // Copy right hand side
             $nx = $B->getColumnDimension();
             $X = $B->getArrayCopy();
             // Compute Y = transpose(Q)*B
             for ($k = 0; $k < $this->n; ++$k) {
                 for ($j = 0; $j < $nx; ++$j) {
                     $s = 0.0;
                     for ($i = $k; $i < $this->m; ++$i) {
                         $s += $this->QR[$i][$k] * $X[$i][$j];
                     }
                     $s = -$s / $this->QR[$k][$k];
                     for ($i = $k; $i < $this->m; ++$i) {
                         $X[$i][$j] += $s * $this->QR[$i][$k];
                     }
                 }
             }
             // Solve R*X = Y;
             for ($k = $this->n - 1; $k >= 0; --$k) {
                 for ($j = 0; $j < $nx; ++$j) {
                     $X[$k][$j] /= $this->Rdiag[$k];
                 }
                 for ($i = 0; $i < $k; ++$i) {
                     for ($j = 0; $j < $nx; ++$j) {
                         $X[$i][$j] -= $X[$k][$j] * $this->QR[$i][$k];
                     }
                 }
             }
             $X = new Matrix($X);
             return $X->getMatrix(0, $this->n - 1, 0, $nx);
         } else {
             throw new Exception(JAMAError(MatrixRankException));
         }
     } else {
         throw new Exception(JAMAError(MatrixDimensionException));
     }
 }
 /**
  * @dataProvider dataProviderForDirectProduct
  */
 public function testDirectProduct(array $A, array $B, array $expected)
 {
     $A = new Vector($A);
     $B = new Vector($B);
     $AB = $A->directProduct($B);
     $expected = new Matrix($expected);
     $this->assertEquals($expected->getMatrix(), $AB->getMatrix());
 }
Exemplo n.º 4
0
 function MatrixFitRoute($route)
 {
     require_once 'matrix.php';
     $this->refreshPosibleTruck();
     $route_possible_trucks = $this->getPossibleTrucks($route);
     $copy_possible_trucks = $this->truck_possible;
     $list_all_possible_trucks = array();
     foreach ($copy_possible_trucks as $value) {
         $list_all_possible_trucks = array_merge($list_all_possible_trucks, $value);
     }
     $list_all_possible_trucks = array_unique(array_merge($list_all_possible_trucks, $route_possible_trucks));
     $pending_routes = array_keys($this->routes);
     array_push($pending_routes, "new");
     $assigned_trucks = array();
     //create white_matrix
     $white_matrix = array();
     foreach ($list_all_possible_trucks as $truck_id) {
         $white_matrix[$truck_id] = array();
         foreach ($pending_routes as $route_id) {
             if ($route_id == "new") {
                 $white_matrix[$truck_id][$route_id] = in_array($truck_id, $route_possible_trucks) ? 1 : 0;
             } else {
                 $white_matrix[$truck_id][$route_id] = in_array($truck_id, $copy_possible_trucks[$route_id]) ? 1 : 0;
             }
         }
     }
     $grey_matrix = new Matrix($white_matrix);
     //basic required condition for solution
     if (!$grey_matrix->possible()) {
         return false;
     }
     //cardinality==1 check for $route. this means that the route has only one truck that it can use.
     foreach ($grey_matrix->getColumnKeys() as $route_id) {
         if ($grey_matrix->getColumnCardinal($route_id) == 1) {
             $truck_id = $grey_matrix->getFirstPositiveRow($route_id);
             if ($truck_id === false) {
                 trigger_error("Looked for positive row but found none", E_USER_ERROR);
             } else {
                 $assigned_trucks[$truck_id] = $route_id;
                 $grey_matrix->deleteRow($truck_id);
                 $grey_matrix->deleteColumn($route_id);
             }
         }
     }
     //cardinality==1 check for $truck. this means that there is only one route that can use this truck
     foreach ($grey_matrix->getRowKeys() as $truck_id) {
         if ($grey_matrix->getRowCardinal($truck_id) == 1) {
             $route_id = $grey_matrix->getFirstPositiveColumn($truck_id);
             if ($route_id === false) {
                 trigger_error("Looked for positive col but found none", E_USER_ERROR);
             } else {
                 $assigned_trucks[$truck_id] = $route_id;
                 $grey_matrix->deleteRow($truck_id);
                 $grey_matrix->deleteColumn($route_id);
             }
         }
     }
     //trivial solution found
     if (count($grey_matrix->getColumnKeys()) < 1) {
         return $assigned_trucks;
     }
     //check again for basic condition before continuing
     if (!$grey_matrix->possible()) {
         return false;
     }
     //iterate while there are still routes to be fit, we will include exit statments under certain conditions inside the loop
     $black_matrix = new Matrix($grey_matrix->getMatrix());
     $ignores = array();
     $routes_ids = $black_matrix->getColumnKeys();
     $last_route_id = end($routes_ids);
     $first_route_id = reset($routes_ids);
     $max_loop = $black_matrix->maximumIterations();
     $loop_count = 0;
     while (true) {
         if ($loop_count >= $max_loop) {
             trigger_error("loops count exceeded logical max loop, please check the code for errors", E_USER_ERROR);
         }
         $black_matrix = new Matrix($grey_matrix->getMatrix());
         //recreate for loop
         $routes_ids = $black_matrix->getColumnKeys();
         //recreate for loop
         $assignments = array();
         // list of assignments for solution
         $previous_route_id = false;
         $previous_route_value = false;
         $n = 1;
         //for slice porpuses
         foreach ($routes_ids as $route_id) {
             if ($black_matrix->possible() === false) {
                 return false;
             }
             if (count($black_matrix->getColumnKeys()) == 0 || count($black_matrix->getRowKeys()) == 0) {
                 return false;
             }
             if (!isset($ignores[$route_id])) {
                 $ignores[$route_id] = array();
             }
             $fix_truck = $black_matrix->getFirstPositiveRow($route_id, $ignores[$route_id]);
             //there are no more positive values availables
             if ($fix_truck === false) {
                 //no more subsitituions left
                 if ($route_id == $first_route_id) {
                     return false;
                 } else {
                     $previous_step = $previous_route_value;
                     if ($previous_step === false) {
                         trigger_error("something went wrong while searching for the previous positive of {$previous_route_id}", E_USER_ERROR);
                     } else {
                         array_push($ignores[$previous_route_id], $previous_step);
                     }
                     $ignores = array_slice($ignores, 0, $n, TRUE);
                     break;
                     //restart loop
                 }
             } else {
                 $n += 1;
                 $assignments[$fix_truck] = $route_id;
                 $black_matrix->deleteRow($fix_truck);
                 $black_matrix->deleteColumn($route_id);
                 $previous_route_id = $route_id;
                 $previous_route_value = $fix_truck;
                 //A solution was found, hurray!
                 if ($route_id == $last_route_id) {
                     return array_merge($assigned_trucks, $assignments);
                 }
             }
         }
     }
 }
 /**
  * @dataProvider dataProviderForKroneckerProduct
  */
 public function testKroneckerProduct(array $A, array $B, array $expected)
 {
     $A = new Matrix($A);
     $B = new Matrix($B);
     $A⊗B = $A->kroneckerProduct($B);
     $expected = new Matrix($expected);
     $this->assertEquals($expected->getMatrix(), $A⊗B->getMatrix());
 }
Exemplo n.º 6
0
 /**
  * @dataProvider dataProviderMulti
  */
 public function testGetMatrix(array $A)
 {
     $S = new SquareMatrix($A);
     $M = new Matrix($A);
     $this->assertEquals($M->getMatrix(), $S->getMatrix());
 }