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

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

Introduction

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

Prototype

RealMatrix multiply(RealMatrix m) throws DimensionMismatchException;

Source Link

Document

Returns the result of postmultiplying this by m .

Usage

From source file:com.joptimizer.algebra.CholeskyFactorizationTest.java

public void testInvert1() throws Exception {
    log.debug("testInvert1");
    double[][] QData = new double[][] { { 1, .12, .13, .14, .15 }, { .12, 2, .23, .24, .25 },
            { .13, .23, 3, 0, 0 }, { .14, .24, 0, 4, 0 }, { .15, .25, 0, 0, 5 } };
    RealMatrix Q = MatrixUtils.createRealMatrix(QData);

    CholeskyFactorization myc = new CholeskyFactorization(DoubleFactory2D.dense.make(QData));
    myc.factorize();/*from   w  ww.  j  ava 2  s.com*/
    RealMatrix L = new Array2DRowRealMatrix(myc.getL().toArray());
    RealMatrix LT = new Array2DRowRealMatrix(myc.getLT().toArray());
    log.debug("L: " + ArrayUtils.toString(L.getData()));
    log.debug("LT: " + ArrayUtils.toString(LT.getData()));
    log.debug("L.LT: " + ArrayUtils.toString(L.multiply(LT).getData()));
    log.debug("LT.L: " + ArrayUtils.toString(LT.multiply(L).getData()));

    // check Q = L.LT
    double norm = L.multiply(LT).subtract(Q).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 1.E-15);

    RealMatrix LInv = new SingularValueDecomposition(L).getSolver().getInverse();
    log.debug("LInv: " + ArrayUtils.toString(LInv.getData()));
    RealMatrix LInvT = LInv.transpose();
    log.debug("LInvT: " + ArrayUtils.toString(LInvT.getData()));
    RealMatrix LTInv = new SingularValueDecomposition(LT).getSolver().getInverse();
    log.debug("LTInv: " + ArrayUtils.toString(LTInv.getData()));
    RealMatrix LTInvT = LTInv.transpose();
    log.debug("LTInvT: " + ArrayUtils.toString(LTInvT.getData()));
    log.debug("LInv.LInvT: " + ArrayUtils.toString(LInv.multiply(LInvT).getData()));
    log.debug("LTInv.LTInvT: " + ArrayUtils.toString(LTInv.multiply(LTInvT).getData()));

    RealMatrix Id = MatrixUtils.createRealIdentityMatrix(Q.getRowDimension());
    //check Q.(LTInv * LInv) = 1
    norm = Q.multiply(LTInv.multiply(LInv)).subtract(Id).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 5.E-15);

    // check Q.QInv = 1
    RealMatrix QInv = MatrixUtils.createRealMatrix(myc.getInverse().toArray());
    norm = Q.multiply(QInv).subtract(Id).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 1.E-15);
}

From source file:com.joptimizer.algebra.CholeskyFactorizationTest.java

/**
 * The same as before, but with rescaling.
 *///from www. j  a va2s  .  c  om
public void testInvert2() throws Exception {
    log.debug("testInvert2");
    double[][] QData = new double[][] { { 1, .12, .13, .14, .15 }, { .12, 2, .23, .24, .25 },
            { .13, .23, 3, 0, 0 }, { .14, .24, 0, 4, 0 }, { .15, .25, 0, 0, 5 } };
    RealMatrix Q = MatrixUtils.createRealMatrix(QData);

    CholeskyFactorization myc = new CholeskyFactorization(DoubleFactory2D.dense.make(QData),
            new Matrix1NormRescaler());
    myc.factorize();
    RealMatrix L = new Array2DRowRealMatrix(myc.getL().toArray());
    RealMatrix LT = new Array2DRowRealMatrix(myc.getLT().toArray());
    log.debug("L: " + ArrayUtils.toString(L.getData()));
    log.debug("LT: " + ArrayUtils.toString(LT.getData()));
    log.debug("L.LT: " + ArrayUtils.toString(L.multiply(LT).getData()));
    log.debug("LT.L: " + ArrayUtils.toString(LT.multiply(L).getData()));

    // check Q = L.LT
    double norm = L.multiply(LT).subtract(Q).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 1.E-15);

    RealMatrix LInv = new SingularValueDecomposition(L).getSolver().getInverse();
    log.debug("LInv: " + ArrayUtils.toString(LInv.getData()));
    RealMatrix LInvT = LInv.transpose();
    log.debug("LInvT: " + ArrayUtils.toString(LInvT.getData()));
    RealMatrix LTInv = new SingularValueDecomposition(LT).getSolver().getInverse();
    log.debug("LTInv: " + ArrayUtils.toString(LTInv.getData()));
    RealMatrix LTInvT = LTInv.transpose();
    log.debug("LTInvT: " + ArrayUtils.toString(LTInvT.getData()));
    log.debug("LInv.LInvT: " + ArrayUtils.toString(LInv.multiply(LInvT).getData()));
    log.debug("LTInv.LTInvT: " + ArrayUtils.toString(LTInv.multiply(LTInvT).getData()));

    RealMatrix Id = MatrixUtils.createRealIdentityMatrix(Q.getRowDimension());
    //check Q.(LTInv * LInv) = 1
    norm = Q.multiply(LTInv.multiply(LInv)).subtract(Id).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 5.E-15);

    // check Q.QInv = 1
    RealMatrix QInv = MatrixUtils.createRealMatrix(myc.getInverse().toArray());
    norm = Q.multiply(QInv).subtract(Id).getNorm();
    log.debug("norm: " + norm);
    assertTrue(norm < 1.E-15);
}

From source file:ffnn.FFNNTubesAI.java

@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    RealMatrix input_matrix = new BlockRealMatrix(1, input_layer + 1);

    instance = filterNominalNumeric(instance);

    for (int k = 0; k < input_layer; k++) {
        input_matrix.setEntry(0, k, instance.value(k));
    }/*from  w ww .j a v  a  2 s.c  om*/
    input_matrix.setEntry(0, input_layer, 1.0); // bias

    RealMatrix hidden_matrix = input_matrix.multiply(weight1);
    for (int y = 0; y < hidden_layer; ++y) {
        hidden_matrix.setEntry(0, y, sig(hidden_matrix.getEntry(0, y)));
    }
    RealMatrix output_matrix = hidden_matrix.multiply(weight2).add(bias2);
    for (int y = 0; y < output_layer; ++y) {
        output_matrix.setEntry(0, y, sig(output_matrix.getEntry(0, y)));
    }
    double[][] m = output_matrix.getData();

    return m[0];
}

From source file:com.itemanalysis.psychometrics.factoranalysis.FactorAnalysisTest.java

@Test
public void eigenValues() {
    RealMatrix R = new Array2DRowRealMatrix(readHarman74Data());

    int nFactors = 2;
    int nVariables = 24;
    double[] x = new double[nVariables];
    for (int i = 0; i < nVariables; i++) {
        x[i] = .5;/*from   w  ww .j  a v a 2 s. c o m*/
    }

    for (int i = 0; i < nVariables; i++) {
        R.setEntry(i, i, 1.0 - x[i]);
    }

    EigenDecomposition eigen = new EigenDecomposition(R);
    RealMatrix eigenVectors = eigen.getV().getSubMatrix(0, nVariables - 1, 0, nFactors - 1);

    double[] ev = new double[nFactors];
    for (int i = 0; i < nFactors; i++) {
        ev[i] = Math.sqrt(eigen.getRealEigenvalue(i));
    }
    DiagonalMatrix evMatrix = new DiagonalMatrix(ev);// USE Apache version
    // of Diagonal
    // matrix when
    // upgrade to
    // version 3.2
    RealMatrix LAMBDA = eigenVectors.multiply(evMatrix);
    RealMatrix SIGMA = (LAMBDA.multiply(LAMBDA.transpose()));
    RealMatrix RESID = R.subtract(SIGMA);

    double sum = 0.0;
    double squared = 0.0;
    for (int i = 0; i < RESID.getRowDimension(); i++) {
        for (int j = 0; j < RESID.getColumnDimension(); j++) {
            if (i != j) {
                sum += Math.pow(RESID.getEntry(i, j), 2);
            }
        }
    }

    System.out.println(sum);

    // RealMatrix SIGMA = (LAMBDA.multiply(LAMBDA.transpose()));
    //
    // System.out.println("SIGMA");
    // for(int i=0;i<SIGMA.getRowDimension();i++){
    // for(int j=0;j<SIGMA.getColumnDimension();j++){
    // System.out.print(SIGMA.getEntry(i, j) + " ");
    // }
    // System.out.println();
    // }
}

From source file:edu.cudenver.bios.power.glmm.GLMMTestHotellingLawley.java

/**
 * Compute a Hotelling-Lawley Trace statistic
 *
 * @param H hypothesis sum of squares matrix
 * @param E error sum of squares matrix/*ww w.j  a v  a2s . c o m*/
 * @returns F statistic
 */
private double getHotellingLawleyTrace(RealMatrix H, RealMatrix E) throws IllegalArgumentException {
    if (!H.isSquare() || !E.isSquare() || H.getColumnDimension() != E.getRowDimension())
        throw new IllegalArgumentException(
                "Failed to compute Hotelling-Lawley Trace: hypothesis and error matrices must be square and same dimensions");

    RealMatrix inverseE = new LUDecomposition(E).getSolver().getInverse();
    RealMatrix HinverseE = H.multiply(inverseE);

    return HinverseE.getTrace();
}

From source file:com.itemanalysis.psychometrics.factoranalysis.GeneralizedLeastSquaresMethod.java

private void computeFactorLoadings(double[] x) {
    uniqueness = x;// www  .  j a  v a  2s .com
    communality = new double[nVariables];

    for (int i = 0; i < nVariables; i++) {
        R.setEntry(i, i, 1.0 - x[i]);
    }

    EigenDecomposition E = new EigenDecomposition(R);
    RealMatrix L = E.getV().getSubMatrix(0, nVariables - 1, 0, nFactors - 1);
    double[] ev = new double[nFactors];
    for (int i = 0; i < nFactors; i++) {
        ev[i] = Math.sqrt(E.getRealEigenvalue(i));
    }
    DiagonalMatrix M = new DiagonalMatrix(ev);
    RealMatrix LOAD = L.multiply(M);

    //rotate factor loadings
    if (rotationMethod != RotationMethod.NONE) {
        GPArotation gpa = new GPArotation();
        RotationResults results = gpa.rotate(LOAD, rotationMethod);
        LOAD = results.getFactorLoadings();
    }

    Sum[] colSums = new Sum[nFactors];
    Sum[] colSumsSquares = new Sum[nFactors];

    for (int j = 0; j < nFactors; j++) {
        colSums[j] = new Sum();
        colSumsSquares[j] = new Sum();
    }

    factorLoading = new double[nVariables][nFactors];

    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            factorLoading[i][j] = LOAD.getEntry(i, j);
            colSums[j].increment(factorLoading[i][j]);
            colSumsSquares[j].increment(Math.pow(factorLoading[i][j], 2));
            communality[i] += Math.pow(factorLoading[i][j], 2);
        }
    }

    //check sign of factor
    double sign = 1.0;
    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            if (colSums[j].getResult() < 0) {
                sign = -1.0;
            } else {
                sign = 1.0;
            }
            factorLoading[i][j] = factorLoading[i][j] * sign;
        }
    }

    double totSumOfSquares = 0.0;
    sumsOfSquares = new double[nFactors];
    proportionOfExplainedVariance = new double[nFactors];
    proportionOfVariance = new double[nFactors];
    for (int j = 0; j < nFactors; j++) {
        sumsOfSquares[j] = colSumsSquares[j].getResult();
        totSumOfSquares += sumsOfSquares[j];
    }
    for (int j = 0; j < nFactors; j++) {
        proportionOfExplainedVariance[j] = sumsOfSquares[j] / totSumOfSquares;
        proportionOfVariance[j] = sumsOfSquares[j] / nVariables;
    }

}

From source file:com.itemanalysis.psychometrics.factoranalysis.MaximumLikelihoodMethod.java

private void computeFactorLoadings(double[] x) {
    uniqueness = x;/*from  ww  w  . j av  a2  s.c  o m*/
    communality = new double[nVariables];

    double[] sqrtPsi = new double[nVariables];
    double[] invSqrtPsi = new double[nVariables];
    for (int i = 0; i < nVariables; i++) {
        sqrtPsi[i] = Math.sqrt(x[i]);
        invSqrtPsi[i] = 1.0 / Math.sqrt(x[i]);
    }
    DiagonalMatrix diagPsi = new DiagonalMatrix(x);
    DiagonalMatrix diagSqtPsi = new DiagonalMatrix(sqrtPsi);
    DiagonalMatrix diagInvSqrtPsi = new DiagonalMatrix(invSqrtPsi);

    RealMatrix Sstar = diagInvSqrtPsi.multiply(R).multiply(diagInvSqrtPsi);
    EigenDecomposition E = new EigenDecomposition(Sstar);
    RealMatrix L = E.getV().getSubMatrix(0, nVariables - 1, 0, nFactors - 1);
    double[] ev = new double[nFactors];
    for (int i = 0; i < nFactors; i++) {
        ev[i] = Math.sqrt(Math.max(E.getRealEigenvalue(i) - 1, 0));
    }
    DiagonalMatrix M = new DiagonalMatrix(ev);
    RealMatrix LOAD2 = L.multiply(M);
    RealMatrix LOAD = diagSqtPsi.multiply(LOAD2);

    //rotate factor loadings
    if (rotationMethod != RotationMethod.NONE) {
        GPArotation gpa = new GPArotation();
        RotationResults results = gpa.rotate(LOAD, rotationMethod);
        LOAD = results.getFactorLoadings();
    }

    Sum[] colSums = new Sum[nFactors];
    Sum[] colSumsSquares = new Sum[nFactors];

    for (int j = 0; j < nFactors; j++) {
        colSums[j] = new Sum();
        colSumsSquares[j] = new Sum();
    }

    factorLoading = new double[nVariables][nFactors];

    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            factorLoading[i][j] = LOAD.getEntry(i, j);
            colSums[j].increment(factorLoading[i][j]);
            colSumsSquares[j].increment(Math.pow(factorLoading[i][j], 2));
            communality[i] += Math.pow(factorLoading[i][j], 2);
        }
    }

    //check sign of factor
    double sign = 1.0;
    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            if (colSums[j].getResult() < 0) {
                sign = -1.0;
            } else {
                sign = 1.0;
            }
            factorLoading[i][j] = factorLoading[i][j] * sign;
        }
    }

    double totSumOfSquares = 0.0;
    sumsOfSquares = new double[nFactors];
    proportionOfExplainedVariance = new double[nFactors];
    proportionOfVariance = new double[nFactors];
    for (int j = 0; j < nFactors; j++) {
        sumsOfSquares[j] = colSumsSquares[j].getResult();
        totSumOfSquares += sumsOfSquares[j];
    }
    for (int j = 0; j < nFactors; j++) {
        proportionOfExplainedVariance[j] = sumsOfSquares[j] / totSumOfSquares;
        proportionOfVariance[j] = sumsOfSquares[j] / nVariables;
    }

}

From source file:com.itemanalysis.psychometrics.factoranalysis.MINRESmethod.java

private void computeFactorLoadings(double[] x) {
    uniqueness = x;//from   w  ww  . j a v  a2 s.c  o m
    communality = new double[nVariables];

    double[] sqrtPsi = new double[nVariables];
    double[] invSqrtPsi = new double[nVariables];
    for (int i = 0; i < nVariables; i++) {
        sqrtPsi[i] = Math.sqrt(x[i]);
        invSqrtPsi[i] = 1.0 / Math.sqrt(x[i]);
    }
    DiagonalMatrix diagPsi = new DiagonalMatrix(x);
    DiagonalMatrix diagSqtPsi = new DiagonalMatrix(sqrtPsi);
    DiagonalMatrix diagInvSqrtPsi = new DiagonalMatrix(invSqrtPsi);

    RealMatrix Sstar = diagInvSqrtPsi.multiply(R2).multiply(diagInvSqrtPsi);
    EigenDecomposition E = new EigenDecomposition(Sstar);
    RealMatrix L = E.getV().getSubMatrix(0, nVariables - 1, 0, nFactors - 1);
    double[] ev = new double[nFactors];
    for (int i = 0; i < nFactors; i++) {
        ev[i] = Math.sqrt(Math.max(E.getRealEigenvalue(i) - 1, 0));
    }
    DiagonalMatrix M = new DiagonalMatrix(ev);
    RealMatrix LOAD2 = L.multiply(M);
    RealMatrix LOAD = diagSqtPsi.multiply(LOAD2);

    //rotate factor loadings
    if (rotationMethod != RotationMethod.NONE) {
        GPArotation gpa = new GPArotation();
        RotationResults results = gpa.rotate(LOAD, rotationMethod);
        LOAD = results.getFactorLoadings();
    }

    Sum[] colSums = new Sum[nFactors];
    Sum[] colSumsSquares = new Sum[nFactors];

    for (int j = 0; j < nFactors; j++) {
        colSums[j] = new Sum();
        colSumsSquares[j] = new Sum();
    }

    factorLoading = new double[nVariables][nFactors];

    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            factorLoading[i][j] = LOAD.getEntry(i, j);
            colSums[j].increment(factorLoading[i][j]);
            colSumsSquares[j].increment(Math.pow(factorLoading[i][j], 2));
            communality[i] += Math.pow(factorLoading[i][j], 2);
        }
    }

    //check sign of factor
    double sign = 1.0;
    for (int i = 0; i < nVariables; i++) {
        for (int j = 0; j < nFactors; j++) {
            if (colSums[j].getResult() < 0) {
                sign = -1.0;
            } else {
                sign = 1.0;
            }
            factorLoading[i][j] = factorLoading[i][j] * sign;
        }
    }

    double totSumOfSquares = 0.0;
    sumsOfSquares = new double[nFactors];
    proportionOfExplainedVariance = new double[nFactors];
    proportionOfVariance = new double[nFactors];
    for (int j = 0; j < nFactors; j++) {
        sumsOfSquares[j] = colSumsSquares[j].getResult();
        totSumOfSquares += sumsOfSquares[j];
    }
    for (int j = 0; j < nFactors; j++) {
        proportionOfExplainedVariance[j] = sumsOfSquares[j] / totSumOfSquares;
        proportionOfVariance[j] = sumsOfSquares[j] / nVariables;
    }

}

From source file:edu.cudenver.bios.power.glmm.GLMMTestPillaiBartlett.java

/**
 * Compute a Pillai Bartlett Trace statistic
 * /*from ww w  . j  a  va2 s . c  om*/
 * @param H hypothesis sum of squares matrix
 * @param E error sum of squares matrix
 * @returns F statistic
 */
private double getPillaiBartlettTrace(RealMatrix H, RealMatrix E) {
    if (!H.isSquare() || !E.isSquare() || H.getColumnDimension() != E.getRowDimension())
        throw new IllegalArgumentException(
                "Failed to compute Pillai-Bartlett Trace: hypothesis and error matrices must be square and same dimensions");

    double a = C.getRowDimension();
    double b = U.getColumnDimension();
    double s = (a < b) ? a : b;
    double p = beta.getColumnDimension();

    RealMatrix adjustedH = H;
    if ((s == 1 && p > 1) || fMethod == FApproximation.PILLAI_ONE_MOMENT_OMEGA_MULT
            || fMethod == FApproximation.MULLER_TWO_MOMENT_OMEGA_MULT) {
        adjustedH = H.scalarMultiply(((double) (totalN - rank) / (double) totalN));
    }

    RealMatrix T = adjustedH.add(E);
    RealMatrix inverseT = new LUDecomposition(T).getSolver().getInverse();

    RealMatrix HinverseT = adjustedH.multiply(inverseT);

    return HinverseT.getTrace();
}

From source file:hulo.localization.models.obs.GaussianProcessLDPLMean.java

@Override
public double looPredLogLikelihood() {

    double[][] Y = getY();
    double[][] dY = getdY();
    double[][] mask = getMask();

    int ns = Y.length;
    int ny = Y[0].length;

    RealMatrix Ky = MatrixUtils.createRealMatrix(this.Ky);
    RealMatrix invK = new LUDecomposition(Ky).getSolver().getInverse();

    RealMatrix dYmat = MatrixUtils.createRealMatrix(dY);

    double[] LOOPredLL = new double[ny];
    for (int j = 0; j < ny; j++) {
        RealMatrix dy = MatrixUtils.createColumnRealMatrix(dYmat.getColumn(j));
        RealMatrix invKdy = invK.multiply(dy);
        double sum = 0;
        for (int i = 0; i < ns; i++) {
            double mu_i = dYmat.getEntry(i, j) - invKdy.getEntry(i, 0) / invK.getEntry(i, i);
            double sigma_i2 = 1 / invK.getEntry(i, i);
            double logLL = StatUtils.logProbaNormal(dYmat.getEntry(i, j), mu_i, Math.sqrt(sigma_i2));
            sum += logLL * mask[i][j];/*from  ww  w.j  a v a  2s . c  o  m*/
        }
        LOOPredLL[j] = sum;
    }

    double sumLOOPredLL = 0;
    for (int j = 0; j < ny; j++) {
        sumLOOPredLL += LOOPredLL[j];
    }

    return sumLOOPredLL;
}