Michael Bommarito (g0thm0g) wrote in php,
Michael Bommarito

JAMA (for PHP)

If you ever did any physics, engineering, or statistics work in Java, I'm sure you'll remember the classic Java Matrix package. We just finished porting it over to PHP over at phpMath.com, and the results are pretty cool. Anyone who's ever done clickstream modelling or any sort of complex online data analysis will really benefit from this package too. Just a few examples:

  • With JAMA, you can perform a least-squares regression for an n-th degree polynomial - this function returns the coefficients of the polynomial. $X and $Y are arrays of x- and y-values and $n is the degree of the polynomial. Make sure you provide at least $n+1 values for each. Check out the test script here: http://phpmath.com/~jama/add-ons/polyfit.php.

  • function polyfit($X, $Y, $n) {  
      if(count($X)!=count($Y) || count($X) < $n)
        return false;
      for ($i = 0; $i < sizeof($X); $i++)
    	for ($j = 0; $j <= $n; $j++)
    	  $A[$i][$j] = pow($X[$i], $j);
      for ($i=0; $i < sizeof($Y); $i++)
    	$B[$i] = array($Y[$i]);   
      $matrixA = new Matrix($A);
      $matrixB = new Matrix($B);
      return $matrixA->solve($matrixB);

  • Multivariate distributions are also a real breeze with JAMA. Check out how easy it is to calculate values for the probability distribution of a multivariate normal distribution, even when the correlation between variates is non-zero (e.g., not just the sum of the marginal probabilities). $a is the covariance matrix and $mu is the vector of means. This little snippet just iterates through [0,1] with Δ0.1, calculating the PDF for the standardized bivariate normal.

  • $a = new Matrix(array(array(1, 0), array(0, 1)));
    $ai = $a->inverse();
    $sqadet = sqrt(pow(2*pi(), 2) * $a->det());
    $mu = new Matrix(1, 2, 0);
    for($i = 0; $i < 1; $i += 0.1) {
    $y = new Matrix(array(array_fill(0, 2, $i)));
    $yt = $y->transpose();
    $y = $y->times($ai);
    $y = $y->times($yt);
    $Q = -$y->get(0, 0) / 2;
    echo exp($Q)/$sqadet . '

    We're also doing some work on implementing a complete statistical distribution library. They're both open-source community works, so if you're into this sort of thing, feel free to sign up for the mailing list and contribute too.
    • Post a new comment


      default userpic

      Your IP address will be recorded