Example usage for org.apache.commons.math3.linear RealMatrix getColumnDimension

List of usage examples for org.apache.commons.math3.linear RealMatrix getColumnDimension

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealMatrix getColumnDimension.

Prototype

int getColumnDimension();

Source Link

Document

Returns the number of columns in the matrix.

Usage

From source file:org.ssascaling.model.timeseries.learner.apache.OLSMultipleLinearRegression.java

/**
 * <p>Compute the "hat" matrix./*  w  w w . j  a  va  2 s.c o m*/
 * </p>
 * <p>The hat matrix is defined in terms of the design matrix X
 *  by X(X<sup>T</sup>X)<sup>-1</sup>X<sup>T</sup>
 * </p>
 * <p>The implementation here uses the QR decomposition to compute the
 * hat matrix as Q I<sub>p</sub>Q<sup>T</sup> where I<sub>p</sub> is the
 * p-dimensional identity matrix augmented by 0's.  This computational
 * formula is from "The Hat Matrix in Regression and ANOVA",
 * David C. Hoaglin and Roy E. Welsch,
 * <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
 *
 * @return the hat matrix
 */
public RealMatrix calculateHat() {
    // Create augmented identity matrix
    RealMatrix Q = qr.getQ();
    final int p = qr.getR().getColumnDimension();
    final int n = Q.getColumnDimension();
    Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n);
    double[][] augIData = augI.getDataRef();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j && i < p) {
                augIData[i][j] = 1d;
            } else {
                augIData[i][j] = 0d;
            }
        }
    }

    // Compute and return Hat matrix
    return Q.multiply(augI).multiply(Q.transpose());
}

From source file:org.ssascaling.model.timeseries.learner.apache.QRDecomposition.java

/**
 * Calculates the QR-decomposition of the given matrix.
 *
 * @param matrix The matrix to decompose.
 * @param threshold Singularity threshold.
 *//* w w w.j a v a2  s . c om*/
public QRDecomposition(RealMatrix matrix, double threshold) {
    this.threshold = threshold;

    final int m = matrix.getRowDimension();
    final int n = matrix.getColumnDimension();
    qrt = matrix.transpose().getData();
    rDiag = new double[FastMath.min(m, n)];
    cachedQ = null;
    cachedQT = null;
    cachedR = null;
    cachedH = null;

    /*
     * The QR decomposition of a matrix A is calculated using Householder
     * reflectors by repeating the following operations to each minor
     * A(minor,minor) of A:
     */
    for (int minor = 0; minor < FastMath.min(m, n); minor++) {

        final double[] qrtMinor = qrt[minor];

        /*
         * Let x be the first column of the minor, and a^2 = |x|^2.
         * x will be in the positions qr[minor][minor] through qr[m][minor].
         * The first column of the transformed minor will be (a,0,0,..)'
         * The sign of a is chosen to be opposite to the sign of the first
         * component of x. Let's find a:
         */
        double xNormSqr = 0;
        for (int row = minor; row < m; row++) {
            final double c = qrtMinor[row];
            xNormSqr += c * c;
        }
        final double a = (qrtMinor[minor] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr);
        rDiag[minor] = a;

        if (a != 0.0) {

            /*
             * Calculate the normalized reflection vector v and transform
             * the first column. We know the norm of v beforehand: v = x-ae
             * so |v|^2 = <x-ae,x-ae> = <x,x>-2a<x,e>+a^2<e,e> =
             * a^2+a^2-2a<x,e> = 2a*(a - <x,e>).
             * Here <x, e> is now qr[minor][minor].
             * v = x-ae is stored in the column at qr:
             */
            qrtMinor[minor] -= a; // now |v|^2 = -2a*(qr[minor][minor])

            /*
             * Transform the rest of the columns of the minor:
             * They will be transformed by the matrix H = I-2vv'/|v|^2.
             * If x is a column vector of the minor, then
             * Hx = (I-2vv'/|v|^2)x = x-2vv'x/|v|^2 = x - 2<x,v>/|v|^2 v.
             * Therefore the transformation is easily calculated by
             * subtracting the column vector (2<x,v>/|v|^2)v from x.
             *
             * Let 2<x,v>/|v|^2 = alpha. From above we have
             * |v|^2 = -2a*(qr[minor][minor]), so
             * alpha = -<x,v>/(a*qr[minor][minor])
             */
            for (int col = minor + 1; col < n; col++) {
                final double[] qrtCol = qrt[col];
                double alpha = 0;
                for (int row = minor; row < m; row++) {
                    alpha -= qrtCol[row] * qrtMinor[row];
                }
                alpha /= a * qrtMinor[minor];

                // Subtract the column vector alpha*v from x.
                for (int row = minor; row < m; row++) {
                    qrtCol[row] -= alpha * qrtMinor[row];
                }
            }
        }
    }
}

From source file:org.ujmp.commonsmath.AbstractCommonsMathDenseDoubleMatrix2D.java

public AbstractCommonsMathDenseDoubleMatrix2D(RealMatrix matrix) {
    super(matrix.getRowDimension(), matrix.getColumnDimension());
    this.matrix = matrix;
}

From source file:pl.matrix.core.MatrixCalculator.java

public Matrix transformToTriangularUpperMatrix(Matrix a) throws Exception {
    RealMatrix aRealMatrix = a.toRealMatrix();

    if (aRealMatrix.getRowDimension() != aRealMatrix.getColumnDimension()) {
        throw new Exception();
    }//ww  w.jav a2 s  .com

    int n = aRealMatrix.getRowDimension();
    // iteracja (zerowanie i-tej kolumny)
    for (int i = 0; i < n - 1; i++) {
        // po wierszach
        for (int j = i + 1; j < n; j++) {
            double factor = aRealMatrix.getEntry(j, i) / aRealMatrix.getEntry(i, i);

            // po kolumnach
            for (int k = i; k < n; k++) {
                double newValue = aRealMatrix.getEntry(j, k) - factor * aRealMatrix.getEntry(i, k);
                aRealMatrix.setEntry(j, k, newValue);
            }
        }
    }
    Matrix result = new Matrix(aRealMatrix);

    return result;
}

From source file:playground.sergioo.facilitiesGenerator2012.WorkFacilitiesGeneration.java

private static Set<PointPerson> getPCATransformation(Collection<PointPerson> points) {
    RealMatrix pointsM = new Array2DRowRealMatrix(points.iterator().next().getDimension(), points.size());
    int k = 0;/*from w w  w . j  a  v  a2s. c om*/
    for (PointND<Double> point : points) {
        for (int f = 0; f < point.getDimension(); f++)
            pointsM.setEntry(f, k, point.getElement(f));
        k++;
    }
    RealMatrix means = new Array2DRowRealMatrix(pointsM.getRowDimension(), 1);
    for (int r = 0; r < means.getRowDimension(); r++) {
        double mean = 0;
        for (int c = 0; c < pointsM.getColumnDimension(); c++)
            mean += pointsM.getEntry(r, c) / pointsM.getColumnDimension();
        means.setEntry(r, 0, mean);
    }
    RealMatrix deviations = new Array2DRowRealMatrix(pointsM.getRowDimension(), pointsM.getColumnDimension());
    for (int r = 0; r < deviations.getRowDimension(); r++)
        for (int c = 0; c < deviations.getColumnDimension(); c++)
            deviations.setEntry(r, c, pointsM.getEntry(r, c) - means.getEntry(r, 0));
    RealMatrix covariance = deviations.multiply(deviations.transpose())
            .scalarMultiply(1 / (double) pointsM.getColumnDimension());
    EigenDecomposition eigenDecomposition = new EigenDecomposition(covariance, 0);
    RealMatrix eigenVectorsT = eigenDecomposition.getVT();
    RealVector eigenValues = new ArrayRealVector(eigenDecomposition.getD().getRowDimension());
    for (int r = 0; r < eigenDecomposition.getD().getRowDimension(); r++)
        eigenValues.setEntry(r, eigenDecomposition.getD().getEntry(r, r));
    for (int i = 0; i < eigenValues.getDimension(); i++) {
        for (int j = i + 1; j < eigenValues.getDimension(); j++)
            if (eigenValues.getEntry(i) < eigenValues.getEntry(j)) {
                double tempValue = eigenValues.getEntry(i);
                eigenValues.setEntry(i, eigenValues.getEntry(j));
                eigenValues.setEntry(j, tempValue);
                RealVector tempVector = eigenVectorsT.getRowVector(i);
                eigenVectorsT.setRowVector(i, eigenVectorsT.getRowVector(j));
                eigenVectorsT.setRowVector(j, tempVector);
            }
        eigenVectorsT.setRowVector(i,
                eigenVectorsT.getRowVector(i).mapMultiply(Math.sqrt(1 / eigenValues.getEntry(i))));
    }
    RealVector standardDeviations = new ArrayRealVector(pointsM.getRowDimension());
    for (int r = 0; r < covariance.getRowDimension(); r++)
        standardDeviations.setEntry(r, Math.sqrt(covariance.getEntry(r, r)));
    double zValue = standardDeviations.dotProduct(new ArrayRealVector(pointsM.getRowDimension(), 1));
    RealMatrix zScore = deviations.scalarMultiply(1 / zValue);
    pointsM = eigenVectorsT.multiply(zScore);
    Set<PointPerson> pointsC = new HashSet<PointPerson>();
    k = 0;
    for (PointPerson point : points) {
        PointPerson pointC = new PointPerson(point.getId(), point.getOccupation(),
                new Double[] { pointsM.getEntry(0, k), pointsM.getEntry(1, k) }, point.getPlaceType());
        pointC.setWeight(point.getWeight());
        pointsC.add(pointC);
        k++;
    }
    return pointsC;
}

From source file:Pruning.Experiments.KendallsCorrelation.java

/**
 * Computes the Kendall's Tau rank correlation matrix for the columns of
 * the input matrix.//  w  w  w .  jav  a2  s. c o m
 *
 * @param matrix matrix with columns representing variables to correlate
 * @return correlation matrix
 */
public RealMatrix computeCorrelationMatrix(final RealMatrix matrix) {
    int nVars = matrix.getColumnDimension();
    RealMatrix outMatrix = new BlockRealMatrix(nVars, nVars);
    for (int i = 0; i < nVars; i++) {
        for (int j = 0; j < i; j++) {
            double corr = correlation(matrix.getColumn(i), matrix.getColumn(j), matrix.getColumn(i).length);
            outMatrix.setEntry(i, j, corr);
            outMatrix.setEntry(j, i, corr);
        }
        outMatrix.setEntry(i, i, 1d);
    }
    return outMatrix;
}

From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java

/**
 * @param m Input matrix//  w  w  w. j  av a2s .  co  m
 * @return Matrix representing the element-wise logarithm of m.
 */
private static RealMatrix log(final RealMatrix m) {
    final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()];
    for (int r = 0; r < m.getRowDimension(); r++) {
        for (int c = 0; c < m.getColumnDimension(); c++) {
            d[r][c] = FastMath.log(m.getEntry(r, c));
        }
    }
    return new Array2DRowRealMatrix(d, false);
}

From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java

/**
 * @param m Input matrix./* w  w w  .java  2s .  co m*/
 * @return Matrix representing the element-wise square root of m.
 */
private static RealMatrix sqrt(final RealMatrix m) {
    final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()];
    for (int r = 0; r < m.getRowDimension(); r++) {
        for (int c = 0; c < m.getColumnDimension(); c++) {
            d[r][c] = FastMath.sqrt(m.getEntry(r, c));
        }
    }
    return new Array2DRowRealMatrix(d, false);
}

From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java

/**
 * @param m Input matrix.//from   ww  w .  ja  v a2s  .c  om
 * @return Matrix representing the element-wise square of m.
 */
private static RealMatrix square(final RealMatrix m) {
    final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()];
    for (int r = 0; r < m.getRowDimension(); r++) {
        for (int c = 0; c < m.getColumnDimension(); c++) {
            double e = m.getEntry(r, c);
            d[r][c] = e * e;
        }
    }
    return new Array2DRowRealMatrix(d, false);
}

From source file:put.ci.cevo.framework.algorithms.ApacheCMAES.java

/**
 * @param m Input matrix 1./*from  w  w w  .  j a v a2  s  .  c o m*/
 * @param n Input matrix 2.
 * @return the matrix where the elements of m and n are element-wise multiplied.
 */
private static RealMatrix times(final RealMatrix m, final RealMatrix n) {
    final double[][] d = new double[m.getRowDimension()][m.getColumnDimension()];
    for (int r = 0; r < m.getRowDimension(); r++) {
        for (int c = 0; c < m.getColumnDimension(); c++) {
            d[r][c] = m.getEntry(r, c) * n.getEntry(r, c);
        }
    }
    return new Array2DRowRealMatrix(d, false);
}