Example usage for org.apache.commons.math3.linear Array2DRowRealMatrix Array2DRowRealMatrix

List of usage examples for org.apache.commons.math3.linear Array2DRowRealMatrix Array2DRowRealMatrix

Introduction

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

Prototype

public Array2DRowRealMatrix(final double[][] d, final boolean copyArray)
        throws DimensionMismatchException, NoDataException, NullArgumentException 

Source Link

Document

Create a new RealMatrix using the input array as the underlying data array.

Usage

From source file:com.clust4j.algo.preprocess.BoxCoxTransformer.java

@Override
public RealMatrix transform(RealMatrix data) {
    return new Array2DRowRealMatrix(transform(data.getData()), false);
}

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

private RealMatrix getNormalizingWeights(RealMatrix A, boolean normalize) {
    int nrow = A.getRowDimension();
    int ncol = A.getColumnDimension();
    final double[] w = new double[nrow];

    RealMatrix W = new Array2DRowRealMatrix(nrow, ncol);
    if (!normalize) {
        W.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
            @Override/*from  w w w  .  j  a  v a2s  . co m*/
            public double visit(int row, int column, double value) {
                return 1.0;
            }
        });
        return W;
    }

    //compute row sum of squared loadings
    A.walkInRowOrder(new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            w[row] += value * value;
        }
    });

    //compute normalizing weights for the matrix
    W.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return Math.sqrt(w[row]);
        }
    });
    return W;
}

From source file:lanchester.MultiArena4.java

public Array2DRowRealMatrix getMat() {
    int numFoes = forces.size();
    MultiForce f1;/*from w  w w . ja v a2s .  c o m*/
    MultiForce f2;
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(numFoes, numFoes);
    for (int i1 = 0; i1 < numFoes - 1; i1++) {
        f1 = forces.get(i1);
        for (int i2 = i1 + 1; i2 < numFoes; i2++) {
            f2 = forces.get(i2);
            if (f1.isFriend(f2)) {
                //                    f1.setStance(AthenaConstants.ALLIED_POSTURE);
                //                    f2.setStance(AthenaConstants.ALLIED_POSTURE);
                //                    stanceArray[i1][i2] = (AthenaConstants.ALLIED_POSTURE);
                //                    stanceArray[i2][i1] = (AthenaConstants.ALLIED_POSTURE);
                mat.setEntry(i1, i2, 0.);
                mat.setEntry(i2, i1, 0.);
            } else {
                //                    setStances(f1, f2);
                setStances(i1, i2);
                double a1 = f2.getForceMultiplier();
                double b2 = f1.getForceMultiplier();
                if (isBattle) {
                    a1 *= AthenaConstants.battle[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.battle[stanceArray[i2][i1]][stanceArray[i1][i2]];
                } else {
                    a1 *= AthenaConstants.skirmish[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.skirmish[stanceArray[i2][i1]][stanceArray[i1][i2]];
                }

                mat.setEntry(i1, i2, -a1);
                mat.setEntry(i2, i1, -b2);
            }
        }
    }
    return mat;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * This method will return the element-wise product of matrixA
 * and matrixB./*w ww  . j  av a 2s .  c  om*/
 * In order to perform element-wise multiplication, the incoming
 * matrices must have the same dimensions.
 * @param matrixA
 * @param matrixB
 * @return RealMatrix which is the element-wise product of A and B.
 */
public static RealMatrix getElementWiseProduct(RealMatrix matrixA, RealMatrix matrixB)
        throws IllegalArgumentException {
    if (matrixA == null || matrixB == null || !areDimensionsEqual(matrixA, matrixB)) {
        throw new IllegalArgumentException("Both matrices must be non-null "
                + "and matrix dimensions must be equal" + " for element-wise multiplication.");
    }

    int numRows = matrixA.getRowDimension();
    int numCols = matrixA.getColumnDimension();
    RealMatrix product = new Array2DRowRealMatrix(numRows, numCols);
    double aVal, bVal;

    //loop through each row
    for (int r = 0; r < numRows; r++) {
        //multiply each element of A by same element of B
        for (int c = 0; c < numCols; c++) {
            aVal = matrixA.getEntry(r, c);
            bVal = matrixB.getEntry(r, c);
            product.setEntry(r, c, aVal * bVal);
        }
    }
    return product;
}

From source file:com.clust4j.algo.preprocess.PreProcessorTests.java

@Test
public void testMinMaxScalerBadMinMax() {
    boolean a = false;

    try {//  w  w w. j a  va  2s. c om
        double[][] d = new double[][] { new double[] { 1, 2, 3 }, new double[] { 1, 2, 3 } };

        final Array2DRowRealMatrix data = new Array2DRowRealMatrix(d, false);
        new MinMaxScaler(1, 0).fit(data);
    } catch (IllegalStateException i) {
        a = true;
    } finally {
        assertTrue(a);
    }
}

From source file:com.clust4j.algo.NearestCentroidTests.java

/**
 * Asser that when all of the matrix entries are exactly the same,
 * the algorithm will still converge, yet produce one label: 0
 *///from  w w  w  .ja v  a2 s.  c o  m
@Override
@Test
public void testAllSame() {
    final double[][] x = MatUtils.rep(-1, 3, 3);
    final Array2DRowRealMatrix X = new Array2DRowRealMatrix(x, false);

    int[] labels = new NearestCentroid(X, new int[] { 0, 1, 2 },
            new NearestCentroidParameters().setVerbose(true)).fit().getLabels();
    assertTrue(new VecUtils.IntSeries(labels, Inequality.EQUAL_TO, 0).all());
    System.out.println();

    labels = new NearestCentroid(X, new int[] { 0, 1, 2 }, new NearestCentroidParameters().setVerbose(true))
            .fit().predict(X);
    assertTrue(new VecUtils.IntSeries(labels, Inequality.EQUAL_TO, 0).all());
    System.out.println();
}

From source file:com.clust4j.utils.MatTests.java

@Test
public void testKNearestStatic() {
    final double[][] mat = new double[][] { new double[] { -1.000, -1.000, -1.000 },
            new double[] { 10.000, 10.000, 10.000 }, new double[] { 90.000, 90.000, 90.000 } };

    final double[] record = new double[] { 0, 0, 0 };
    NearestNeighbors nn = new NearestNeighborsParameters(1).fitNewModel(new Array2DRowRealMatrix(mat, false));
    assertTrue(nn.getNeighbors(new Array2DRowRealMatrix(new double[][] { record }, false))
            .getIndices()[0][0] == 0);/*from   www.ja v  a  2 s.c  o m*/
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * This method will return vech(matrix).
 * matrix must be symmetric in order to perform vech operation.
 * @param RealMatrix matrix/*  w w  w .  j  ava  2s  . c  o  m*/
 * @return vech(matrix)
 */
public static RealMatrix getVechMatrix(RealMatrix matrix) throws IllegalArgumentException {
    if (matrix == null || !isSymmetric(matrix)) {
        throw new IllegalArgumentException("Matrix must be non-null and " + "symmetrical.");
    }
    int newRow = 0;
    int numRows = matrix.getRowDimension();
    RealMatrix vech = new Array2DRowRealMatrix(numRows * (numRows + 1) / 2, 1);
    for (int c = 0; c < matrix.getColumnDimension(); c++) {
        for (int r = c; r < matrix.getRowDimension(); r++, newRow++) {
            vech.setEntry(newRow, 0, matrix.getEntry(r, c));
        }
    }
    return vech;
}

From source file:com.github.thorbenlindhauer.factor.CanonicalGaussianFactor.java

/**
 * Transforms a conditional linear gaussian (i.e. a Gaussian of the form N(x; a + B^T * Y, C) into canonical form.
 *
 * @param meanVector a//from  w w  w . ja  v a 2 s  . c om
 * @param weightMatrix B
 * @param covarianceMatrix C
 */
public static CanonicalGaussianFactor fromConditionalForm(Scope scope, Scope conditioningScope,
        RealVector meanVector, RealMatrix covarianceMatrix, RealMatrix weightMatrix) {

    // TODO: perform cardinality checks etc.

    // the following assumes that the resulting precision matrix (and mean vector) can be restructured as follows:
    // ( SUBMATRIX_XX SUBMATRIX_XY )
    // ( SUBMATRIX_YX SUBMATRIX_YY )
    // where X indicates variables that are part of the prediction scope and Y are variables being part of the conditioning scope

    // assuming
    //   meanVector: a; |x| vector
    //   covarianceMatrix: C; |x| cross |x| matrix
    //   weightMatrix: B;  |x| cross |y| matrix

    // XX = C^-1
    // XY = -C^-1 * B
    // YX = -B^T * C^-1
    // YY = B^T * C^-1 * B^T

    MathUtil mathUtil = new MathUtil(covarianceMatrix);

    // C^(-1)
    RealMatrix xxMatrix = null;

    xxMatrix = mathUtil.invert();

    //    if (!mathUtil.isZeroMatrix()) {
    //      xxMatrix = mathUtil.invert();
    //    } else {
    //
    //      // this is a special case for convolution in which the "summing" variable has no variance itself
    //      // although a 0 variance is not valid in general
    //      xxMatrix = covarianceMatrix;
    //    }

    // B^T * C^(-1)
    RealMatrix weightedXXMatrix = weightMatrix.transpose().multiply(xxMatrix);

    // -B^T * C^(-1)
    RealMatrix yxMatrix = weightedXXMatrix.scalarMultiply(-1.0d);

    // -C^(-1)^T * B
    RealMatrix xyMatrix = xxMatrix.transpose().multiply(weightMatrix).scalarMultiply(-1.0d);

    // B^T * C^(-1) * B
    RealMatrix yyMatrix = weightedXXMatrix.multiply(weightMatrix);

    // K
    RealMatrix conditionedPrecisionMatrix = new Array2DRowRealMatrix(scope.size(), scope.size());

    // Matrix to generate h
    RealMatrix conditionedMeanTransformationMatrix = new Array2DRowRealMatrix(scope.size(), scope.size());

    Scope predictionScope = scope.reduceBy(conditioningScope);
    int[] predictionMapping = scope.createContinuousVariableMapping(predictionScope);
    int[] conditioningMapping = scope.createContinuousVariableMapping(conditioningScope);

    for (int i = 0; i < scope.size(); i++) {
        RealVector precisionColumn = conditionedPrecisionMatrix.getColumnVector(i);

        if (predictionMapping[i] >= 0) {
            precisionColumn = precisionColumn.add(
                    padVector(xxMatrix.getColumnVector(predictionMapping[i]), scope.size(), predictionMapping));

            conditionedMeanTransformationMatrix.setColumnVector(i, precisionColumn);

            precisionColumn = precisionColumn.add(padVector(yxMatrix.getColumnVector(predictionMapping[i]),
                    scope.size(), conditioningMapping));

            conditionedPrecisionMatrix.setColumnVector(i, precisionColumn);
        }

        if (conditioningMapping[i] >= 0) {
            precisionColumn = precisionColumn.add(padVector(xyMatrix.getColumnVector(conditioningMapping[i]),
                    scope.size(), predictionMapping));

            conditionedMeanTransformationMatrix.setColumnVector(i, precisionColumn);

            precisionColumn = precisionColumn.add(padVector(yyMatrix.getColumnVector(conditioningMapping[i]),
                    scope.size(), conditioningMapping));

            conditionedPrecisionMatrix.setColumnVector(i, precisionColumn);
        }
    }

    // h = (a, 0)^T * (XX, XY; 0, 0)
    RealMatrix scaledMeanMatrix = new Array2DRowRealMatrix(1, scope.size());
    scaledMeanMatrix.setRowVector(0, padVector(meanVector, scope.size(), predictionMapping));

    scaledMeanMatrix = scaledMeanMatrix.multiply(conditionedMeanTransformationMatrix);
    RealVector scaledMeanVector = scaledMeanMatrix.getRowVector(0);

    // g = a^T * C^-1 * a - log((2 * PI) ^ m/2 * det(C)^0.5) where m is the size of the prediction scope
    RealMatrix meanMatrix = new Array2DRowRealMatrix(predictionScope.size(), 1);
    meanMatrix.setColumnVector(0, meanVector);
    double normalizationConstant = -0.5d * meanVector.dotProduct(xxMatrix.operate(meanVector)) - Math.log(
            Math.pow(2 * Math.PI, (double) predictionScope.size() / 2.0d) * Math.sqrt(mathUtil.determinant()));

    return new CanonicalGaussianFactor(scope, conditionedPrecisionMatrix, scaledMeanVector,
            normalizationConstant);

}

From source file:com.clust4j.algo.AffinityPropagationTests.java

/**
 * Asser that when all of the matrix entries are exactly the same,
 * the algorithm will still converge, yet produce one label: 0
 *//*from  www  .ja v  a2 s.  c  om*/
@Override
@Test
public void testAllSame() {
    final double[][] x = MatUtils.rep(-1, 3, 3);
    final Array2DRowRealMatrix X = new Array2DRowRealMatrix(x, false);

    int[] labels = new AffinityPropagation(X, new AffinityPropagationParameters().setVerbose(true)).fit()
            .getLabels();
    assertTrue(new VecUtils.IntSeries(labels, Inequality.EQUAL_TO, 0).all());
    System.out.println();
}