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[] v) 

Source Link

Document

Create a new (column) RealMatrix using v as the data for the unique column of the created matrix.

Usage

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

@Test
public void testM255Olimin() {
    System.out.println("Oblimin rotation test: m255 data");

    /**/* w ww .j  a  va  2 s. co m*/
     * True result obtained form R using GPArotation package
     */
    double[][] true_Oblimin = { { 0.818982935, -0.086728237, -0.03014828 },
            { 0.836948168, -0.028356336, 0.02072749 }, { 0.650083626, 0.102202784, -0.06494440 },
            { 0.609805424, 0.145551832, 0.03455997 }, { 0.432053641, 0.310356386, -0.13539510 },
            { 0.071824049, 0.723712703, -0.07186957 }, { -0.022431888, 0.822701356, 0.05997316 },
            { 0.113162767, 0.434661061, -0.07100987 }, { 0.129672215, 0.353260863, -0.33144976 },
            { -0.052966793, 0.454048208, -0.28827799 }, { 0.028011398, -0.006402917, -0.89108626 },
            { -0.005289128, 0.004084979, -0.75198003 } };

    RealMatrix L = new Array2DRowRealMatrix(m255MINRESLoadings);
    GPArotation gpa = new GPArotation();
    RotationResults R = gpa.rotate(L, RotationMethod.OBLIMIN, false, 60, 1e-5);
    RealMatrix Lr = R.getFactorLoadings();
    //        System.out.println(R.toString());

    for (int i = 0; i < Lr.getRowDimension(); i++) {
        for (int j = 0; j < Lr.getColumnDimension(); j++) {
            assertEquals("  loading: ", Precision.round(true_Oblimin[i][j], 4),
                    Precision.round(Lr.getEntry(i, j), 5), 1e-4);
        }

    }

}

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

@Test
public void testKernel() {
    final double[][] data = new double[][] { new double[] { 3.65816, 0.29518, 2.123316 },
            new double[] { 0.005, 0.182751, 0.1284 }, new double[] { 4.1234, 0.27395, 1.8900002 } };

    int[] labels;
    final Array2DRowRealMatrix mat = new Array2DRowRealMatrix(data);
    for (Linkage linkage : HierarchicalAgglomerative.Linkage.values()) {
        HierarchicalAgglomerative hac = new HierarchicalAgglomerative(mat,
                new HierarchicalAgglomerativeParameters().setLinkage(linkage).setMetric(new GaussianKernel())
                        .setVerbose(false)).fit();

        labels = hac.getLabels();//  w  ww.j  ava  2 s.c  om
        assertTrue(labels[0] == labels[2]);
    }
}

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

/**
 * Compare 2 sample t-test results between JavaStatistics,
 * POWERLIB, and simulation//from w w  w. j av a 2  s.co m
 */
public void testUnivariateWithConfidenceLimits() {
    GLMMPowerParameters params = new GLMMPowerParameters();

    // add tests
    params.addTest(Test.UNIREP);

    // add alpha values
    params.addAlpha(0.01);

    // build beta matrix
    double[][] beta = { { 0 }, { 1 } };
    params.setBeta(new FixedRandomMatrix(beta, null, false));
    // add beta scale values from 0 to 0.75
    for (double betaScale = 0; betaScale < 0.76; betaScale += 0.01)
        params.addBetaScale(betaScale);

    // build theta null matrix
    double[][] theta0 = { { 0 } };
    params.setTheta(new Array2DRowRealMatrix(theta0));

    // build sigma matrix
    double[][] sigma = { { 0.068 } };
    params.setSigmaError(new Array2DRowRealMatrix(sigma));
    // add sigma scale values
    params.addSigmaScale(1);

    // build design matrix
    params.setDesignEssence(MatrixUtils.createRealIdentityMatrix(2));
    // add sample size multipliers
    params.addSampleSize(12);

    // build between subject contrast
    double[][] between = { { 1, -1 } };
    params.setBetweenSubjectContrast(new FixedRandomMatrix(between, null, true));

    // parameters for confidence limits
    params.setConfidenceIntervalType(ConfidenceIntervalType.BETA_KNOWN_SIGMA_ESTIMATED);
    params.setSampleSizeForEstimates(24);
    params.setDesignMatrixRankForEstimates(2);

    // run the test
    // 2 sided CI
    params.setAlphaLowerConfidenceLimit(0.025);
    params.setAlphaUpperConfidenceLimit(0.025);
    checker.checkPower(params);
    // 1 sided lower CI
    params.setAlphaLowerConfidenceLimit(0.05);
    params.setAlphaUpperConfidenceLimit(0);
    checker.checkPower(params);
    // 1 sided upper CI
    params.setAlphaLowerConfidenceLimit(0);
    params.setAlphaUpperConfidenceLimit(0.05);
    checker.checkPower(params);
    // 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();
}

From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurementTest.java

@Test(expected = IllegalArgumentException.class)
public void testWrongSizeCovarianceMatrix() {
    RealMatrix sigma = new Array2DRowRealMatrix(new double[][] { { 1.5, 0.0 }, { 1.0, 0.5 }, { 1.0, 0.02 } });
    m.setCovarianceMatrix(sigma);//w  ww  . j av a  2  s.  c om
}

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

License:asdf

@Test
public void DBSCANTest3() {
    final double[][] train_array = new double[][] { new double[] { 0.00504, 0.0001, 0.08172 },
            new double[] { 3.65816, 2.9471, 3.12331 }, new double[] { 4.12344, 3.0001, 2.89002 },
            new double[] { 0.00403, 0.0003, 0.08231 } };

    final Array2DRowRealMatrix mat = new Array2DRowRealMatrix(train_array);
    StandardScaler scaler = new StandardScaler().fit(mat);

    assertTrue(Distance.EUCLIDEAN.getDistance(train_array[1], train_array[2]) > 0.5);
    DBSCAN db = new DBSCAN(scaler.transform(mat), new DBSCANParameters(0.75).setMinPts(1).setVerbose(true))
            .fit();//from   w  w  w.  j  a  v a 2s.com
    System.out.println();

    assertTrue(db.getNumberOfIdentifiedClusters() == 2);
    assertTrue(db.getLabels()[1] == db.getLabels()[2]);
    assertTrue(db.getLabels()[0] == db.getLabels()[3]);
    assertFalse(db.hasWarnings());
    assertTrue(db.getMinPts() == 1);
}

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

/**
 * Compare 2 sample t-test results between JavaStatistics, 
 * POWERLIB, and simulation/*from  w w w . j  av  a 2s . co m*/
 */
public void testTwoSampleTTEst() {
    GLMMPowerParameters params = new GLMMPowerParameters();

    // add tests
    params.addTest(Test.UNIREP);

    // add alpha values
    params.addAlpha(0.05);

    // build beta matrix
    double[][] beta = { { 0 }, { 1 } };
    params.setBeta(new FixedRandomMatrix(beta, null, false));
    // add beta scale values
    for (double betaScale = 0; betaScale <= 2.5; betaScale += 0.05)
        params.addBetaScale(betaScale);

    // build theta null matrix
    double[][] theta0 = { { 0 } };
    params.setTheta(new Array2DRowRealMatrix(theta0));

    // build sigma matrix
    double[][] sigma = { { 1 } };
    params.setSigmaError(new Array2DRowRealMatrix(sigma));
    // add sigma scale values
    for (double sigmaScale : SIGMA_SCALE_LIST)
        params.addSigmaScale(sigmaScale);

    // build design matrix
    params.setDesignEssence(MatrixUtils.createRealIdentityMatrix(2));
    // add sample size multipliers
    for (int sampleSize : SAMPLE_SIZE_LIST)
        params.addSampleSize(sampleSize);

    // build between subject contrast
    double[][] between = { { 1, -1 } };
    params.setBetweenSubjectContrast(new FixedRandomMatrix(between, null, true));

    try {
        checker.checkPower(params);
        // output the results
        ValidationReportBuilder reportBuilder = new ValidationReportBuilder();
        reportBuilder.createValidationReportAsStdout(checker, TITLE, false);
        reportBuilder.createValidationReportAsLaTex(OUTPUT_FILE, TITLE, AUTHOR, STUDY_DESIGN_DESCRIPTION,
                params, checker);

        assertTrue(checker.isSASDeviationBelowTolerance());
        checker.reset();
    } catch (Exception e) {

    }
}

From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurement.java

@Override
public void reorderAlternatives(List<Alternative> alts) {
    final int n = alternatives.size();

    double permute[][] = new double[n][n];
    for (int i = 0; i < n; ++i) {
        int j = alternatives.indexOf(alts.get(i));
        permute[i][j] = 1;/*from w w w.  jav  a 2s  . c o  m*/
    }
    Array2DRowRealMatrix m = new Array2DRowRealMatrix(permute);

    alternatives.clear();
    alternatives.addAll(alts);

    final RealVector newMeanVector = m.operate(meanVector);
    final RealMatrix newCovarianceMatrix = covarianceMatrix.multiply(m.transpose()).preMultiply(m);
    fireEvents(setMeanVectorInternal(newMeanVector), setCovarianceMatrixInternal(newCovarianceMatrix));
}

From source file:com.joptimizer.solvers.KKTSolver.java

protected boolean checkKKTSolutionAccuracy(RealVector v, RealVector w) {
    // build the full KKT matrix
    double norm;/*  www .  j a v a2 s  .  c  om*/

    DoubleMatrix2D M = F2.make(this.H.getData());
    if (this.A != null) {
        if (h != null) {
            DoubleMatrix2D[][] parts = { { F2.make(this.H.getData()), F2.make(this.AT.getData()) },
                    { F2.make(this.A.getData()), null } };
            M = F2.compose(parts);
            RealMatrix KKT = new Array2DRowRealMatrix(M.toArray());
            RealVector X = v.append(w);
            RealVector Y = g.append(h);
            // check ||KKT.X+Y||<tolerance
            norm = KKT.operate(X).add(Y).getNorm();
        } else {
            //H.v + [A]T.w = -g
            norm = H.operate(v).add(AT.operate(w)).add(g).getNorm();
        }
    } else {
        // check ||H.X+h||<tolerance
        norm = H.operate(v).add(g).getNorm();
    }
    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "KKT solution error: " + norm);
    return norm < toleranceKKT;
}

From source file:eagle.security.userprofile.model.UserProfileEigenModelEntity.java

public static UserProfileEigenModel deserializeModel(MLModelAPIEntity entity) throws IOException {
    if (entity == null)
        return null;
    String user = entity.getTags() == null ? null : entity.getTags().get(UserProfileConstants.USER_TAG);
    String site = entity.getTags() == null ? null : entity.getTags().get(UserProfileConstants.SITE_TAG);

    UserProfileEigenModelEntity content = TaggedLogAPIEntity.buildObjectMapper().readValue(entity.getContent(),
            UserProfileEigenModelEntity.class);
    RealVector[] principalComponents = null;
    if (content.getPrincipalComponents() != null) {
        principalComponents = new RealVector[content.getPrincipalComponents().size()];
        int i = 0;
        for (double[] array : content.getPrincipalComponents()) {
            principalComponents[i] = new ArrayRealVector(array);
            i++;/*  w  ww. j  a v  a 2 s  . c  o  m*/
        }
    }
    UserCommandStatistics[] statistics = null;
    if (content.getStatistics() != null) {
        statistics = new UserCommandStatistics[content.getStatistics().size()];
        int i = 0;
        for (Map<String, Object> map : content.getStatistics()) {
            statistics[i++] = new UserCommandStatistics(map);
        }
    }

    return new UserProfileEigenModel(entity.getVersion(), site, user,
            content.getUMatrix() == null ? null : new Array2DRowRealMatrix(content.getUMatrix()),
            content.getDiagonalMatrix() == null ? null : new Array2DRowRealMatrix(content.getDiagonalMatrix()),
            content.getDimension(),
            content.getMinVector() == null ? null : new ArrayRealVector(content.getMinVector()),
            content.getMaxVector() == null ? null : new ArrayRealVector(content.getMaxVector()),
            principalComponents,
            content.getMaximumL2Norm() == null ? null : new ArrayRealVector(content.getMaximumL2Norm()),
            content.getMinimumL2Norm() == null ? null : new ArrayRealVector(content.getMinimumL2Norm()),
            statistics);
}

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

/**
 * Builds matrices for a multivariate GLM with fixed predictors
 *//*w w w . j  a v a2 s.  co m*/
private GLMMPowerParameters buildValidMultivariateFixedInputs() {
    GLMMPowerParameters params = new GLMMPowerParameters();

    // add tests
    for (Test test : Test.values()) {
        params.addTest(test);
    }

    // add alpha values
    for (double alpha : ALPHA_LIST)
        params.addAlpha(alpha);

    int Q = 4;
    // create design matrix
    params.setDesignEssence(MatrixUtils.createRealIdentityMatrix(Q));
    // add sample size multipliers
    for (int sampleSize : SAMPLE_SIZE_LIST)
        params.addSampleSize(sampleSize);

    // build sigma matrix
    double rho = 0.4;
    double[][] sigma = { { 1, rho, rho }, { rho, 1, rho }, { rho, rho, 1 } }; // compound symmetry
    // double [][] sigma = {{1,0.2,0.3},{0.2,1,0.2},{0.3,0.2,1}}; // toeplitz
    params.setSigmaError(new Array2DRowRealMatrix(sigma));
    // add sigma scale values
    for (double sigmaScale : SIGMA_SCALE_LIST)
        params.addSigmaScale(sigmaScale);

    // build beta matrix
    double[][] beta = { { 1, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
    params.setBeta(new FixedRandomMatrix(beta, null, false));
    // add beta scale values
    for (double betaScale : BETA_SCALE_LIST)
        params.addBetaScale(betaScale);

    // build theta null matrix
    double[][] theta0 = { { 0, 0 }, { 0, 0 }, { 0, 0 } };
    params.setTheta(new Array2DRowRealMatrix(theta0));

    // build between subject contrast
    double[][] between = { { 1, -1, 0, 0 }, { 1, 0, -1, 0 }, { 1, 0, 0, -1 } };
    params.setBetweenSubjectContrast(new FixedRandomMatrix(between, null, true));

    // build within subject contrast
    double[][] within = { { 1, 1 }, { -1, 0 }, { 0, -1 } };
    params.setWithinSubjectContrast(new Array2DRowRealMatrix(within));

    //RealMatrix U = params.getWithinSubjectContrast();
    //RealMatrix upu = U.multiply(U.transpose());

    return params;
}