Download the PHP package chippyash/math-matrix without Composer

On this page you can find all versions of the php package chippyash/math-matrix. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package math-matrix

chippyash/Math-Matrix

Quality

PHP 5.6 PHP 7 Build Status Test Coverage Code Climate

The above badges represent the current development branch. As a rule, I don't push to GitHub unless tests, coverage and usability are acceptable. This may not be true for short periods of time; on holiday, need code for some other downstream project etc. If you need stable code, use a tagged version. Read 'Further Documentation' and 'Installation'.

See the Test Contract (526 tests, 820 assertions)

See the API Documentation for further information

Please note that developer support for PHP5.4 & 5.5 was withdrawn at version 2.0.0 of this library. If you need support for PHP 5.4 or 5.5, please use a version >=1,<2

What?

Since the JAMA library, there has not been been a library to my knowledge that allows PHP devs to simply incorporate arithmetic Matrix functionality within an application.

If you are using reasonably small matrices then the complexity of having to compile in external Fortran or C based libraries is something you can do without. And even when you do, it transpires the PHP bindings are limited.

You need speed - PHP is never going to do it for you on big Matrices, start compiling. For everything else, give this a go.

This library aims to provide arithmetic matrix functionality in the most efficient way possible using PHP given that:

The library is released under the GNU GPL V3 or later license

Why?

This adds maths to the Chippyash/Matrix library giving you the ability to create and manipulate matrices containing numeric (float, int, rational and complex) values.

When

The current library covers basic matrix maths. It is a work in progress and has some limitations. Addition, subtraction and multiplication are straight forward and should work for any size matrix. Division relies on inversion which currently relies on the ability to determine the determinant of a matrix. The library supports two strategies for finding a determinant - Laplace expansion and LU. This places a realistic limit on the size of matrices that can be operated on. See the examples/example-laplace-bounds.php and examples/example-lu-determinant-bounds.php scripts to understand why. The limit is a 20x20 matrix when using the Determinant derivative in auto mode. The limit is arbitrary and based on what can computed on my laptop in about a second. Other brands of machinery may vary.

This may change in the future as I refactor for performance or incorporate more performant strategies for computing inverses and determinants. If you are good at maths computation, this is an area where you can really help out

If you want more, either suggest it, or better still, fork it and provide a pull request.

Check out chippyash/Matrix for underlying matrix operations

Check out chippyash/Logical-Matrix for logical matrix operations

Check out ZF4 Packages for more packages

How

The current version of this library utilises the PHP Native numeric Strong Types as the calculator that it uses can only deal with them at present. GMP support is on the roadmap once the calculator provides it. You can ensure that this is enforced by forcing its setting with a call to

use Chippyash\Type\RequiredType;
RequiredType::getInstance()->set(RequiredType::TYPE_NATIVE);

before any operation with the matrices.

Coding Basics

In PHP terms a matrix is an array of arrays, 2 dimensional i.e

As with any TDD application, the tests tell you everything you need to know about the SUT. Read them! However for the short of tempered amongst us the salient points are:

The library extends the Chippyash/Matrix library, so anything you can do on a basic matrix, you can do with a numeric matrix. The library utilises the Chippyash/Strong-Type strong types.

Three basic Matrix types are supplied

The NumericMatrix is fine for general purpose work, but not if you want prove that the inverse(M) * M = Identity. For that you'll need the RationalMatrix which is far more arithmetically stable. This is also the matrix that will benefit from forthcoming support of PHP's various maths extension libraries in the Chippyash/Strong-Type library.

The ComplexMatrix fully supports the Chippyash\Type\Numeric\Complex\ComplexType.

Both the RationalMatrix and ComplexMatrix extend the NumericMatrix.

Creating a numeric type matrix is straightforward:

    use Chippyash\Math\Matrix\NumericMatrix;
    use Chippyash\Math\Matrix\RationalMatrix;
    use Chippyash\Math\Matrix\ComplexMatrix;
    //create empty matrices
    $mA = new NumericMatrix([]);
    $mB = new RationalMatrix([]);
    $mC = new ComplexMatrix([]);

Supplying data to matrix construction will create data items inside the matrix according to the following rules:

Be aware that operations on a NumericMatrix will probably produce the result having different data type entries. This is inevitable given the constraints placed on computer based arithmetic. If any operation requires the item to be cast upwards then it is unlikely to be cast downwards again.

Some helpers are provided:

MatrixFactory

provides static methods:

FunctionMatrix

[DEPRECATED - Use SpecialMatrix::create('functional', int:rows, int:cols, \Closure:f(int:rows, int:cols))] instead

Create a numeric matrix as a result of applying a function.

    $f = function($row, $col) {return TypeFactory::createInt($row * $col);};
    $mA = new FunctionMatrix($f, TypeFactory::createInt(3), TypeFactory::createInt(4));

IdentityMatrix

[DEPRECATED - Use SpecialMatrix::create('identity',int:size) instead]

Create a NumericMatrix Identity matrix

    //create 4x4 identity matrix with integer entries
    $mA = new IdentityMatrix(TypeFactory::createInt(4));
    //or more usually, use the factory method
    $mA - IdentityMatrix::numericIdentity(TypeFactory::createInt(4));

Create rational and complex identity matrices using factory methods:

    $mR = IdentityMatrix::rationalIdentity(TypeFactory::createInt(4));
    $mC = IdentityMatrix::complexIdentity(TypeFactory::createInt(4));

ZeroMatrix

[DEPRECATED - Use SpecialMatrix::create('zeros', int:rows[, int:cols])]

Create a NumericMatrix with all entries set to zero

    //create 2 x 4 zero matrix
    $mZ = new ZeroMatrix(TypeFactory::createInt(2), TypeFactory::createInt(4));

ShiftMatrix

Create a Shift Matrix

    $mA - IdentityMatrix::numericIdentity(TypeFactory::createInt(5));

    //create 5 x 5 shift matrices
    $mSupper = new ShiftMatrix(new IntType(5), new StringType(ShiftMatrix::SM_TYPE_UPPER);
    $mSlower = new ShiftMatrix(new IntType(5), new StringType(ShiftMatrix::SM_TYPE_LOWER);
    //optionally specify the matrix content type
    $mSupper = new ShiftMatrix(new IntType(5), new StringType(ShiftMatrix::SM_TYPE_UPPER, new IntType(IdentityMatrix::IDM_TYPE_COMPLEX));

    $mC = $mA('Mul\Matrix', $mSupper);
    $mD = $mLower('Mul\Matrix', $mA);

SpecialMatrix

Provides numerous special matrices:

Adopting an idea from Octave Gallery Matrices

//inline creation if your version of PHP allows it
use Chippyash\Math\Matrix\SpecialMatrix;
$mS = (new SpecialMatrix())->create(new StringType('NameOfMatrix')[, $arg1, $arg2]);

//or as an invokable class
$factory = new SpecialMatrix();
$mS = $factory(new StringType('nameOfMatrix')[, $arg1, $arg2]);
//or
$mS = $factory('NameOfMatrix'[, $arg1, $arg2]);

Matrices provided:

All returned matrices are NumericMatrices.

Really important: We don't do this shit by ourselves. So read the tests and read the source files where you'll find attribution to some far cleverer people than me. I just try to translate into the PHP world.

Numeric matrices have additional attributes

Remember, you can use the is() method to test for an attribute on a matrix.

Matrices can be computed

On the whole, computations, will work with any scalar but:

All matrix computations follow the natural laws

The following computations are provided (using the magic invoke interface method):

    $mC = $mA('Mul\Matrix', $mB);
    //same as
    $fMul = new Chippyash\Math\Matrix\Computation\Mul\Matrix();
    $mC = $mA->compute($fMul, $mB)
    //same as
    $mC = $fMul->compute($mA, $mB);

You can derive other information from a matrix

Four derivatives are currently supplied.

    $det = $mA("Determinant");
    //same as
    $fDet = new Chippyash\Math\Matrix\Derivative\Determinant();
    $det = $mA->derive($fDet);
    //same as
    $det = $fDet($mA);

As noted above, the Determinant derivative currently only supports up to a 20x20 matrix in auto mode. It will bork if you supply a matrix bigger than that. This will be ok for most purposes. If you are happy to wait a while to compute determinants for bigger matrices, create the determinant by construction (second way above) and specify Determinant::METHOD_LU as a construction parameter. Determinant::METHOD_LAPLACE is left for historical reasons, as there is very little likelihood you will want to use it!

    $tr = $mA('Trace');
    //or other variations as with Determinant
    $sum = $mA('Sum');
    //or other variations as with Determinant
    $mA = new NumericMatrix(
        [
            [0,2,0,8]  //row 1
            [1,0,0,0]  //row 2
            [0,0,5,5]  //row 3
            [0,1,6,3]  //row 4
        ]
    )

    $next = $mA('MarkovWeightedRandom', TypeFactory::createInt(3));
    //will return IntType(3) or IntType(4) with 50% chance of either being returned

A NotMarkovException will be thrown if the supplied Matrix does not conform to the IsMarkov Attribute. Please note, that whilst you can supply a matrix with floats, the nature of mt_rand() function used to generate the next number means that, for the time being, you should provide integer values. As long as you supply a square matrix where each row row sums to the same number, you have a Markov Chain expressed as a Matrix.

Additional transformations are supported by numeric matrices

    try {
        $mI = $mA('Invert');
        //same as
        $fInvert = new Chippyash\Math\Matrix\Transformation\Invert();
        $mI = $mA->transform($fInvert);
        //same as
        $mI = $fInvert($mA);
    } catch (Chippyash\Math\Matrix\Exceptions\ComputationException $e) {
        //cannot invert
    }

If you want to break the 20x20 limit, you can do the following:

    $det = new Chippyash\Math\Matrix\Derivative\Determinant();
    $det->tune('luLimit', 40); //or whatever you are prepared to put up with
    $mI = $mA('Invert');
    $det = new Chippyash\Math\Matrix\Derivative\MarkovRandomWalk();
    $res = $det->transform(
        $mA, 
        array(
            'start'=>TypeFactory::createInt(2), 
            'target'=>TypeFactory::createInt(4)
        )
    );

You can supply an optional third parameter, limit to limit the steps that can be taken. This is set to 100 by default.

    $res = $mA(
        'MarkovRandomWalk', 
        array(
            'start'=>TypeFactory::createInt(2), 
            'target'=>TypeFactory::createInt(4),
            'limit'=>TypeFactory::createInt(10)
        )
    );

Matrices can be decomposed

The library currently supports:

LU

    $lu = $mA('Lu');
    //same as
    $fLu = new Chippyash\Math\Matrix\Decomposition\Lu()
    $lu = $mA->decompose($fLu);
    //same as
    $lu = $fLu($mA);

The LU products are:

Accessing the products is either via the product() method or more simply as an attribute of the decomposition:

    $pv = $lu->product('PivotVector');
    //same as
    $pv = $lu->PivotVector;

N.B. Product names for any decomposition are case sensitive

Gauss Jordan Elimination

    $mA = new NumericMatrix(
                [[1, 1, 1],
                 [2, 3, 5],
                 [4, 0, 5]]
                );
    $mB = new NumericMatrix(
            [[5],
             [8],
             [2]]
            );
    $elim = $mA('GaussJordonElimination', $mB);
    //same as
    $fElim = new Chippyash\Math\Matrix\Decomposition\GaussJordonElimination()
    $elim = $mA->decompose($fElim, $mB);
    //same as
    $elim = $fElim($mA, $mB);

The products are:

Using the above example then $elim->left should == an identity matrix and $elim->right == [[3],[4],[-2]] as we've just solved

    x + y + z = 5
    2x + 3y + 5z = 8
    4x + 5z = 2
where
    x = 3, y = 4, z = -2

Formatting for numeric display

An additional display formatter is supported by the library:

\Chippyash\Math\Matrix\Formatter\AsciiNumeric

It extends the \Chippyash\Matrix\Formatter\Ascii. An additional option 'outputType' is provided that should take one of the following values:

    AsciiNumeric::TP_NONE      //behave as base formatter - default behaviour
    AsciiNumeric::TP_INT       //convert all entries to int.  This will floor() if possible
    AsciiNumeric::TP_FLOAT     //convert all entries to float if possible
    AsciiNumeric::TP_RATIONAL  //convert all entries to rational if possible
    AsciiNumeric::TP_COMPLEX   //convert all entries to complex (always possible)

Please note that although you instruct to convert to a particular numeric type the actual display may result in a simpler form if possible.

Example:

    echo $mA->setFormatter(new AsciiNumeric())
        ->display(['outputType' => AsciiNumeric::TP_FLOAT]);

Formatting for a directed graph

To use this functionality you need to include

    "clue/graph": "^0.9",
    "graphp/graphviz": "0.2.*"

to your composer requires section and run a composer update.

This adds the functionality to use the GraphViz suite of programs to create image files from a NumericMatrix that describes a graph.

The simplest use of the renderer is to simply supply it a NumericMatrix:

$mA = new NumericMatrix([[0,0,1],[0,1,0],[1,0,0]]);
$dot = $mA->setFormatter(new DirectedGraph())->display();

will produce a GraphViz .dot file content string such as:

digraph G {
  0 -> 2 [label=1]
  1 -> 1 [label=1 dir="none"]
  2 -> 0 [label=1]
}

Mot often however, you'll want to give some meaning to your vertices. To do this, you can pass in a Monad\Collection of VertexDescription objects. For example

use Monad\Collection;
use Chippyash\Math\Matrix\Formatter\DirectedGraph\VertexDescription;

$attribs = new Collection(
    [
        new VertexDescription(new StringType('A')),
        new VertexDescription(new StringType('B')),
        new VertexDescription(new StringType('C')),
    ]
);
$dot = $mA->setFormatter(new DirectedGraph())->display(['attribs' => $attribs]);

gives

'digraph G {
  "A" -> "C" [label=1]
  "B" -> "B" [label=1 dir="none"]
  "C" -> "A" [label=1]
}

You can also set things like colours and shapes via the VertexDescription. Take a look at the tests.

If you want to do some additional processing prior to generating something through GraphViz, you can pass in an optional parameter:

$graph = $mA->setFormatter(new DirectedGraph())->display(['output' => 'object']);

will return a Fhaculty\Graph\Graph object that you can process further before sending into Graphp\GraphViz\GraphViz. You may also want to get a Graph so that you can do some graph processing via the Graphp\Algorithms library.

Finally, with the DirectedGraph renderer, you can provide an optional callable function that will be applied to the values of the edges. This is often useful to reformat the value in some way. For instance:

$mA = new NumericMatrix([[0,50,50],[33,33,33],[100,0,0]]);
$func = function($origValue) {return \round($origValue / 100, 2);};
$dot = $mA->setFormatter(new DirectedGraph())->display(['edgeFunc' => $func]);

will produce

digraph G {
  0 -> 1 [label=0.5]
  0 -> 2 [label=0.5]
  1 -> 0 [label=0.33]
  1 -> 1 [label=0.33 dir="none"]
  1 -> 2 [label=0.33]
  2 -> 0 [label=1]
}

Exception handling

As matrix maths can throw up problems, particularly when inverting or decomposing, it is always a good idea to wrap whatever you are doing in a try - catch block. The following exceptions are supported by the library. They all extend from the Chippyash\Matrix\Exceptions\MatrixException. The base namespace is Chippyash\Math\Matrix\Exceptions

  MathMatrixException
  ComputationException
  NoInverseException
  SingularMatrixException
  UndefinedComputationException
  NotMarkovException

Changing the library

  1. fork it
  2. write the test
  3. amend it
  4. do a pull request

Found a bug you can't figure out?

  1. fork it
  2. write the test
  3. do a pull request

NB. Make sure you rebase to HEAD before your pull request

Where?

The library is hosted at Github. It is available at Packagist.org as a Composable module

Installation

Install [Composer] (https://getcomposer.org/)

For production

add

    "chippyash/math-matrix": ">=2,<3"

to your composer.json "requires" section.

For development

Clone this repo, and then run Composer in local repo root to pull in dependencies

    git clone [email protected]:chippyash/Math-Matrix.git Math-Matrix
    cd Math-Matrix
    composer install

To run the tests:

    cd Math-Matrix
    vendor/bin/phpunit -c test/phpunit.xml test/

License

This software library is released under the BSD 3 Clause license

This software library is Copyright (c) 2014-2018, Ashley Kitson, UK

History

V1.0.0 Initial Release - after 2 years of development - yippee!

V1.1.0 Update dependencies

V1.2.0 Add Entrywise calculations

V1.2.1 Eradicate calls to plain numeric strong types - use the factories

V1.2.2 Fix AsciiNumeric formatter - don't format strings

V1.2.3 Add link to packages

V1.3.0 Add Directed Graph from Matrix rendering

V1.4.0 Add ShiftMatrix

V1.5.0 Add Special Matrices

V1.5.1 dependency update

V1.5.2 dependency update

V1.5.3 build script update

V1.5.4 update composer - forced by packagist composer.json format change

V2.0.0 BC Break. Withdraw support for old PHP versions

V2.1.0 Change of license from GPL V3 to BSD 3 Clause


All versions of math-matrix with dependencies

PHP Build Version
Package Version
Requires php Version >=5.6
chippyash/matrix Version >=3,<4
chippyash/math-type-calculator Version >=3.0,<4
chippyash/assembly-builder Version >=2,<=3
chippyash/monad Version >=2,<3
chippyash/validation Version >=2,<3
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package chippyash/math-matrix contains the following files

Loading the files please wait ....