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

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

Introduction

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

Prototype

void setEntry(int row, int column, double value) throws OutOfRangeException;

Source Link

Document

Set the entry in the specified row and column.

Usage

From source file:edu.ucdenver.bios.powersvc.resource.ContrastHelper.java

/**
 * Create a trend contrast of the specified type
 * @param spacing list of integer positions representing spacing of measurements
 * @param trendType type of trend contrast
 * @param transpose if true, return the transpose of the contrast
 * @return trend contrast//from  ww w  .  jav  a 2 s .c  om
 */
private static RealMatrix getTrendContrast(double[] spacing, HypothesisTrendTypeEnum trendType,
        boolean transpose) {
    int levels = spacing.length;
    // get all possible polynomial trends
    RealMatrix allTrendContrast = OrthogonalPolynomials.orthogonalPolynomialCoefficients(spacing, levels - 1);
    // select a subset of the polynomial trends based on the hypothesis of interest
    RealMatrix trendContrast = null;
    switch (trendType) {
    case NONE:
        RealMatrix negIdentity = org.apache.commons.math3.linear.MatrixUtils
                .createRealIdentityMatrix(levels - 1).scalarMultiply(-1);
        RealMatrix column1s = MatrixUtils.getRealMatrixWithFilledValue(levels - 1, 1, 1);
        trendContrast = MatrixUtils.getHorizontalAppend(column1s, negIdentity).transpose();
        break;
    case CHANGE_FROM_BASELINE:
        trendContrast = MatrixUtils.getRealMatrixWithFilledValue(levels, 1, 0);
        trendContrast.setEntry(0, 0, 1);
        trendContrast.setEntry(levels - 1, 0, -1);
        break;
    case ALL_POLYNOMIAL:
        trendContrast = allTrendContrast;
        break;
    case LINEAR:
        if (allTrendContrast.getRowDimension() > 1) {
            trendContrast = allTrendContrast.getColumnMatrix(1);
        }
        break;
    case QUADRATIC:
        if (allTrendContrast.getRowDimension() > 2) {
            trendContrast = allTrendContrast.getColumnMatrix(2);
        }
        break;
    case CUBIC:
        if (allTrendContrast.getRowDimension() > 3) {
            trendContrast = allTrendContrast.getColumnMatrix(3);
        }
        break;
    }
    if (transpose) {
        return trendContrast.transpose();
    } else {
        return trendContrast;
    }
}

From source file:edu.ucdenver.bios.powersvc.resource.PowerResourceHelper.java

/**
 * Create a sigma covariate matrix from the study design.
 * @param studyDesign study design object
 * @return sigma covariate matrix//from  ww  w .  ja v a 2s  . c  o m
 */
public static RealMatrix sigmaCovariateMatrixFromStudyDesign(StudyDesign studyDesign) {
    if (studyDesign.getViewTypeEnum() == StudyDesignViewTypeEnum.MATRIX_MODE) {
        return toRealMatrix(studyDesign.getNamedMatrix(PowerConstants.MATRIX_SIGMA_GAUSSIAN));
    } else {
        // in Guided Mode, the user specifies this as a standard deviation, so we square it
        RealMatrix sigmaG = toRealMatrix(studyDesign.getNamedMatrix(PowerConstants.MATRIX_SIGMA_GAUSSIAN));
        if (sigmaG != null && sigmaG.getRowDimension() > 0 && sigmaG.getColumnDimension() > 0) {
            double stddev = sigmaG.getEntry(0, 0);
            sigmaG.setEntry(0, 0, stddev * stddev);
        }
        return sigmaG;
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static RealMatrix[] unflatten(@Nonnull final double[] data, final int rows, final int cols,
        final int len) {
    final RealMatrix[] grid = new RealMatrix[len];
    int offset = 0;
    for (int k = 0; k < len; k++) {
        RealMatrix cell = new BlockRealMatrix(rows, cols);
        grid[k] = cell;// w w w. j av  a  2 s .c o  m
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (offset >= data.length) {
                    throw new IndexOutOfBoundsException(
                            "Offset " + offset + " exceeded data.length " + data.length);
                }
                double value = data[offset];
                cell.setEntry(i, j, value);
                offset++;
            }
        }
    }
    if (offset != data.length) {
        throw new IllegalArgumentException("Invalid data for unflatten");
    }
    return grid;
}

From source file:edu.cmu.tetrad.util.MatrixUtils1.java

public static double[][] pseudoInverse(double[][] x) {
    SingularValueDecomposition svd = new SingularValueDecomposition(new BlockRealMatrix(x));

    RealMatrix U = svd.getU();/*from   ww w.j  a  v a  2 s.c om*/
    RealMatrix V = svd.getV();
    RealMatrix S = svd.getS();

    for (int i = 0; i < S.getRowDimension(); i++) {
        for (int j = 0; j < S.getColumnDimension(); j++) {
            double v = S.getEntry(i, j);
            S.setEntry(i, j, v == 0 ? 0.0 : 1.0 / v);
        }
    }

    return V.multiply(S.multiply(U.transpose())).getData();
}

From source file:edu.ucdenver.bios.powersvc.resource.CovarianceHelper.java

/**
 * Convert a correlation into a covariance matrix
 * @param covariance/*from  w w  w  .j  ava2s.  c o m*/
 * @return
 */
private static RealMatrix buildCovarianceFromCorrelation(Covariance covariance) {
    RealMatrix covarianceData = null;
    Blob2DArray blob = covariance.getBlob();

    if (blob != null && blob.getData() != null) {
        List<StandardDeviation> stddevList = covariance.getStandardDeviationList();
        if (stddevList.size() == covariance.getRows()) {
            covarianceData = new Array2DRowRealMatrix(covariance.getBlob().getData());
            /* For each diagonal cell, square the standard deviation
             * For each off-diagonal cell, use formula
             * covariance = correlation * sqrt (var1 * var2) 
             */
            for (int row = 0; row < covariance.getRows(); row++) {
                for (int col = 0; col < covariance.getColumns(); col++) {
                    double value = covarianceData.getEntry(row, col);
                    if (row == col) {
                        double stddev = stddevList.get(row).getValue();
                        covarianceData.setEntry(row, col, stddev * stddev);
                    } else {
                        double stddevRow = stddevList.get(row).getValue();
                        double stddevCol = stddevList.get(col).getValue();
                        covarianceData.setEntry(row, col,
                                value * Math.sqrt(stddevRow * stddevRow * stddevCol * stddevCol));
                    }
                }
            }
        }
    }
    return covarianceData;
}

From source file:edu.stanford.cfuller.imageanalysistools.filter.GradientFilter.java

/**
 * Applies the GradientFilter to the specified Image.
 * @param im    The Image that will be replaced by its gradient.
 *///from w ww. j  a  va  2  s .  co m
@Override
public void apply(WritableImage im) {

    final int kernelSize = 3;
    int halfKernelSize = (kernelSize - 1) / 2;

    RealMatrix kernel1 = new Array2DRowRealMatrix(kernelSize, kernelSize);

    kernel1.setEntry(0, 0, 1);
    kernel1.setEntry(1, 0, 0);
    kernel1.setEntry(2, 0, -1);
    kernel1.setEntry(0, 1, 1);
    kernel1.setEntry(1, 1, 0);
    kernel1.setEntry(2, 1, -1);
    kernel1.setEntry(0, 2, 1);
    kernel1.setEntry(1, 2, 0);
    kernel1.setEntry(2, 2, -1);

    RealMatrix kernel2 = new Array2DRowRealMatrix(kernelSize, kernelSize);

    kernel2.setEntry(0, 0, -1);
    kernel2.setEntry(1, 0, -1);
    kernel2.setEntry(2, 0, -1);
    kernel2.setEntry(0, 1, 0);
    kernel2.setEntry(1, 1, 0);
    kernel2.setEntry(2, 1, 0);
    kernel2.setEntry(0, 2, 1);
    kernel2.setEntry(1, 2, 1);
    kernel2.setEntry(2, 2, 1);

    Image copy = ImageFactory.create(im);

    ImageCoordinate ic = ImageCoordinate.createCoordXYZCT(0, 0, 0, 0, 0);

    for (ImageCoordinate i : im) {

        double outputVal = 0;
        double output1 = 0;
        double output2 = 0;

        if (i.get(ImageCoordinate.X) == 0 || i.get(ImageCoordinate.Y) == 0
                || i.get(ImageCoordinate.X) == copy.getDimensionSizes().get(ImageCoordinate.X) - 1
                || i.get(ImageCoordinate.Y) == copy.getDimensionSizes().get(ImageCoordinate.Y) - 1) {
            outputVal = 0;
        } else {
            for (int p = -1 * halfKernelSize; p < halfKernelSize + 1; p++) {
                for (int q = -1 * halfKernelSize; q < halfKernelSize + 1; q++) {
                    ic.set(ImageCoordinate.X, i.get(ImageCoordinate.X) + p);
                    ic.set(ImageCoordinate.Y, i.get(ImageCoordinate.Y) + q);
                    output1 += kernel1.getEntry(p + halfKernelSize, q + halfKernelSize) * copy.getValue(ic);
                    output2 += kernel2.getEntry(p + halfKernelSize, q + halfKernelSize) * copy.getValue(ic);
                }
            }

            outputVal = FastMath.hypot(output1, output2);
        }

        im.setValue(i, (float) Math.floor(outputVal));

    }

    ic.recycle();

}

From source file:edu.ucdenver.bios.power.ConditionalMultivariateWithConfidenceLimitsTest.java

/**
 * Test valid inputs for a univariate linear model with only fixed predictors
 *//* www  . ja  v  a  2 s  .c o  m*/
@Test
public void testMultivariateWithConfidenceLimits() {
    GLMMTestFactory.Test[] testList = { GLMMTestFactory.Test.UNIREP_GEISSER_GREENHOUSE };
    for (GLMMTestFactory.Test test : testList) {
        GLMMPowerParameters params = buildInputs(test);

        for (double delta = 0.0008; delta < 0.2001; delta += 0.0008) {
            // increase the gender difference by 2 * delta
            RealMatrix betaMatrix = params.getBeta().getFixedMatrix();
            for (int row = 0; row < 5; row++)
                betaMatrix.setEntry(row, 2, beta[row][2] + delta);
            for (int row = 5; row < 10; row++)
                betaMatrix.setEntry(row, 2, beta[row][2] - delta);

            checker.checkPower(params);
        }
    }

    // we add all of the tests back into the params to ensure the report lists them all
    // we do this to ensure the order of results in the SAS output matches the order
    // in the JavaStatistics calls.
    GLMMPowerParameters params = buildInputs(GLMMTestFactory.Test.UNIREP);
    params.clearTestList();
    for (GLMMTestFactory.Test test : testList) {
        params.addTest(test);
    }

    // output the results
    ValidationReportBuilder reportBuilder = new ValidationReportBuilder();
    reportBuilder.createValidationReportAsStdout(checker, TITLE, false);
    assertTrue("SAS deviation " + checker.getMaxSasDeviation() + " is not below tolerance " + TOLERANCE,
            checker.isSASDeviationBelowTolerance(TOLERANCE));
}

From source file:ellipsoidFit.FitPoints.java

/**
 * Create a matrix in the algebraic form of the polynomial Ax^2 + By^2 +
 * Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz = 1.
 * //from w w w.  j av a  2s . co  m
 * @param v
 *            the vector polynomial.
 * @return the matrix of the algebraic form of the polynomial.
 */
private RealMatrix formAlgebraicMatrix(RealVector v) {
    // a =
    // [ Ax^2 2Dxy 2Exz 2Gx ]
    // [ 2Dxy By^2 2Fyz 2Hy ]
    // [ 2Exz 2Fyz Cz^2 2Iz ]
    // [ 2Gx 2Hy 2Iz -1 ] ]
    RealMatrix a = new Array2DRowRealMatrix(4, 4);

    a.setEntry(0, 0, v.getEntry(0));
    a.setEntry(0, 1, v.getEntry(3));
    a.setEntry(0, 2, v.getEntry(4));
    a.setEntry(0, 3, v.getEntry(6));
    a.setEntry(1, 0, v.getEntry(3));
    a.setEntry(1, 1, v.getEntry(1));
    a.setEntry(1, 2, v.getEntry(5));
    a.setEntry(1, 3, v.getEntry(7));
    a.setEntry(2, 0, v.getEntry(4));
    a.setEntry(2, 1, v.getEntry(5));
    a.setEntry(2, 2, v.getEntry(2));
    a.setEntry(2, 3, v.getEntry(8));
    a.setEntry(3, 0, v.getEntry(6));
    a.setEntry(3, 1, v.getEntry(7));
    a.setEntry(3, 2, v.getEntry(8));
    a.setEntry(3, 3, -1);

    return a;
}

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

/**
 * Computes the function value for varimax rotation.
 *
 * @param L matrix of factor loadings./*from www.  j av a2s.  com*/
 */
public void computeValues(RealMatrix L) {
    //initialize dimensions and column mean array
    int nrow = L.getRowDimension();
    int ncol = L.getColumnDimension();
    Mean[] colMean = new Mean[ncol];
    for (int i = 0; i < ncol; i++) {
        colMean[i] = new Mean();
    }

    //square each element in matrix
    RealMatrix L2 = L.copy();
    double value = 0.0;
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            value = L.getEntry(i, j);
            value *= value;
            L2.setEntry(i, j, value);
            colMean[j].increment(value);
        }
    }

    double dif = 0.0;
    RealMatrix QL = new Array2DRowRealMatrix(nrow, ncol);
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            dif = L2.getEntry(i, j) - colMean[j].getResult();
            QL.setEntry(i, j, dif);
        }
    }

    //compute gradientAt
    gradient = new Array2DRowRealMatrix(nrow, ncol);
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            value = -L.getEntry(i, j) * QL.getEntry(i, j);
            gradient.setEntry(i, j, value);
        }
    }

    //compute function value
    RealMatrix B = QL.transpose().multiply(QL);
    double sum = B.getTrace();
    functionValue = -sum / 4.0;

}

From source file:edu.cudenver.bios.power.test.paper.TestConditionalMultivariateWithConfidenceLimits.java

/**
 * Test valid inputs for a univariate linear model with only fixed predictors
 *//*from   ww  w  . ja  v  a  2s.  c  om*/
public void testMultivariateWithConfidenceLimits() {
    Test[] testList = { Test.UNIREP_GEISSER_GREENHOUSE };
    for (Test test : testList) {
        GLMMPowerParameters params = buildInputs(test);

        for (double delta = 0.0008; delta < 0.2001; delta += 0.0008) {
            // increase the gender difference by 2 * delta
            RealMatrix betaMatrix = params.getBeta().getFixedMatrix();
            for (int row = 0; row < 5; row++)
                betaMatrix.setEntry(row, 2, beta[row][2] + delta);
            for (int row = 5; row < 10; row++)
                betaMatrix.setEntry(row, 2, beta[row][2] - delta);

            checker.checkPower(params);
        }
    }

    // we add all of the tests back into the params to ensure the report lists them all
    // we do this to ensure the order of results in the SAS output matches the order
    // in the JavaStatistics calls.
    GLMMPowerParameters params = buildInputs(Test.UNIREP);
    params.clearTestList();
    for (Test test : testList) {
        params.addTest(test);
    }
    // output the results
    try {
        ValidationReportBuilder reportBuilder = new ValidationReportBuilder();
        reportBuilder.createValidationReportAsStdout(checker, TITLE, false);
        reportBuilder.createValidationReportAsLaTex(OUTPUT_FILE, TITLE, AUTHOR, STUDY_DESIGN_DESCRIPTION,
                params, checker);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    assertTrue(checker.isSASDeviationBelowTolerance());
    checker.reset();
}