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:com.github.thorbenlindhauer.cluster.ep.TruncatedGaussianPotentialResolverTest.java

@Test
public void testTwoSidedTruncatedGaussianApproximation() {

    ContinuousVariable variable = new ContinuousVariable("A");
    Scope scope = new Scope(Collections.singleton(variable));

    GaussianFactor factor = StandaloneGaussiaFactorBuilder.withVariables(variable).scope("A").momentForm()
            .parameters(new ArrayRealVector(new double[] { 2.0d }),
                    new Array2DRowRealMatrix(new double[] { 4.0d }));

    TruncatedGaussianPotentialResolver resolver = new TruncatedGaussianPotentialResolver(variable, 0.5d, 6.0d);

    FactorSet<GaussianFactor> factorSet = new FactorSet<GaussianFactor>(Collections.singleton(factor));
    FactorSet<GaussianFactor> approximation = resolver.project(factorSet, scope);

    assertThat(approximation.getFactors()).hasSize(1);

    GaussianFactor approximationFactor = approximation.getFactors().iterator().next();
    RealVector meanVector = approximationFactor.getMeanVector();
    RealMatrix covarianceMatrix = approximationFactor.getCovarianceMatrix();

    assertThat(meanVector.getDimension()).isEqualTo(1);
    assertThat(meanVector.getEntry(0)).isEqualTo(2.658510664d, TestConstants.DOUBLE_VALUE_TOLERANCE);

    assertThat(covarianceMatrix.isSquare());
    assertThat(covarianceMatrix.getColumnDimension()).isEqualTo(1);

    assertThat(covarianceMatrix.getEntry(0, 0)).isEqualTo(1.787386921d, TestConstants.DOUBLE_VALUE_TOLERANCE);

}

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

@Test
public void testM255GeominOblique() {
    System.out.println("Oblique Geomin rotation test: m255 data");

    /**//w w  w.  jav a  2  s .c o  m
     * True result obtained form R using GPArotation package
     */
    double[][] true_Geomin_oblique = { { 0.814401032, -0.07246248, -0.02746737 },
            { 0.831474480, -0.01326628, 0.02443654 }, { 0.646042722, 0.11864079, -0.05620512 },
            { 0.604841472, 0.16035608, 0.04246413 }, { 0.429130847, 0.32919710, -0.11951339 },
            { 0.068651498, 0.74475428, -0.04555539 }, { -0.026759588, 0.84183379, 0.08633271 },
            { 0.111079049, 0.44919958, -0.05420552 }, { 0.130427210, 0.37116164, -0.31191986 },
            { -0.051932818, 0.47010788, -0.26735188 }, { 0.036623600, 0.01140911, -0.87276177 },
            { 0.002120624, 0.01879531, -0.73637231 }, };

    double[][] true_Phi = { { 1.0000000, 0.5565973, -0.7280542 }, { 0.5565973, 1.0000000, -0.6808553 },
            { -0.7280542, -0.6808553, 1.0000000 } };

    RealMatrix L = new Array2DRowRealMatrix(m255MINRESLoadings);
    GPArotation gpa = new GPArotation();
    RotationResults R = gpa.rotate(L, RotationMethod.GEOMIN_Q, false, 500, 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_Geomin_oblique[i][j], 4),
                    Precision.round(Lr.getEntry(i, j), 5), 1e-4);
        }
    }

    RealMatrix Phi = R.getPhi();
    for (int i = 0; i < Phi.getRowDimension(); i++) {
        for (int j = 0; j < Phi.getColumnDimension(); j++) {
            assertEquals("  factor correlation: ", Precision.round(true_Phi[i][j], 4),
                    Precision.round(Phi.getEntry(i, j), 5), 1e-4);
        }
    }

}

From source file:com.itemanalysis.psychometrics.cfa.AbstractConfirmatoryFactorAnalysisEstimator.java

public double sumSquaredElements(RealMatrix matrix) {
    double sum = 0.0;
    double v = 0.0;
    for (int i = 0; i < matrix.getRowDimension(); i++) {
        for (int j = 0; j < matrix.getColumnDimension(); j++) {
            v = matrix.getEntry(i, j);/* w w  w .  j  a v  a2 s .c o  m*/
            sum += (v * v);
        }
    }
    return sum;
}

From source file:eagle.security.userprofile.model.eigen.UserProfileEigenModeler.java

private RealMatrix normalizeData(RealMatrix matrix) {

    RealMatrix normalizedData = new Array2DRowRealMatrix(matrix.getRowDimension(), matrix.getColumnDimension());
    for (int i = 0; i < matrix.getRowDimension(); i++) {
        for (int j = 0; j < matrix.getColumnDimension(); j++) {
            // TODO:  statistics[j].getStddev() == 0 what should the value be if stddev is o?
            double value = statistics[j].getStddev() == 0 ? 0
                    : (matrix.getEntry(i, j) - statistics[j].getMean()) / statistics[j].getStddev();
            normalizedData.setEntry(i, j, value);
        }/*from  ww  w . j a v  a 2 s.c  om*/
    }
    return normalizedData;
}

From source file:ellipsoidFit.FitPoints.java

/**
 * Find the center of the ellipsoid.//  ww  w . j av  a2 s.c o  m
 * 
 * @param a
 *            the algebraic from of the polynomial.
 * @return a vector containing the center of the ellipsoid.
 */
private RealVector findCenter(RealMatrix a) {
    RealMatrix subA = a.getSubMatrix(0, 2, 0, 2);

    for (int q = 0; q < subA.getRowDimension(); q++) {
        for (int s = 0; s < subA.getColumnDimension(); s++) {
            subA.multiplyEntry(q, s, -1.0);
        }
    }

    RealVector subV = a.getRowVector(3).getSubVector(0, 3);

    // inv (dtd)
    DecompositionSolver solver = new SingularValueDecomposition(subA).getSolver();
    RealMatrix subAi = solver.getInverse();

    return subAi.operate(subV);
}

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

/**
 * Update the random columns in the specified design matrix with a new realization
 * of random values//from w w  w  .j a v  a 2s. c o  m
 *
 * @param fullDesignMatrix an instance of the full design matrix
 */
public void updateRandomColumns(RealMatrix fullDesignMatrix) throws IllegalArgumentException {
    if (fullDesignMatrix.getColumnDimension() != combinedMatrix.getColumnDimension())
        throw new IllegalArgumentException("Design matrix instance has invalid #columns");
    int fullDesignColumn = 0;
    if (fixedMatrix != null)
        fullDesignColumn = fixedMatrix.getColumnDimension();

    if (randomMatrix != null) {
        for (int col = 0; col < randomMatrix.getColumnDimension(); col++, fullDesignColumn++) {
            fillRandomColumn(col, fullDesignColumn, fullDesignMatrix);
        }
    }

}

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

/**
 * Create a null hypothesis matrix from the study design.
 * @param studyDesign study design object
 * @return theta null matrix/*from w w w .j a va  2s  .c  o m*/
 */
public static RealMatrix thetaNullMatrixFromStudyDesign(StudyDesign studyDesign, FixedRandomMatrix C,
        RealMatrix U) {
    if (studyDesign.getViewTypeEnum() == StudyDesignViewTypeEnum.MATRIX_MODE) {
        return toRealMatrix(studyDesign.getNamedMatrix(PowerConstants.MATRIX_THETA_NULL));
    } else {
        RealMatrix thetaNull = toRealMatrix(studyDesign.getNamedMatrix(PowerConstants.MATRIX_THETA_NULL));
        if (thetaNull == null) {
            if (C != null && C.getFixedMatrix() != null && U != null) {
                int rows = C.getFixedMatrix().getRowDimension();
                int columns = U.getColumnDimension();
                thetaNull = MatrixUtils.getRealMatrixWithFilledValue(rows, columns, 0);
            }
        }
        return thetaNull;
    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.SequentialProjectionHashLearner.java

@Override
public void run() {
    final RealMatrix cov_reg = MatrixUtils.createRealIdentityMatrix(X.getRowDimension())
            .scalarMultiply(shrinkage);//from  w ww .  jav a2s  .c  o m
    for (int k = 0; k < K; ++k) {
        System.out.println("k = " + k);
        System.out.println("\tCovariance");
        final RealMatrix cov = Xi_.multiply(Xi_.transpose()).add(cov_reg);
        //         System.out.println( cov );
        System.out.println("\tM");
        final RealMatrix M = cov; // XL.multiply( Si_ ).multiply( XLt ).add( cov.scalarMultiply( eta ) );
        // TODO: You only need the largest eigenvalue, so the full
        // decomposition is a ton of unnecessary work.
        System.out.println("\tM[" + M.getRowDimension() + "x" + M.getColumnDimension() + "]");
        final EigenDecomposition evd = new EigenDecomposition(M);
        final RealVector w = evd.getEigenvector(0);
        w.mapMultiplyToSelf(1.0 / w.getNorm());
        //         if( Math.abs( w.getNorm() - 1.0 ) > 1e-2 ) {
        //            System.out.println( "! Non-unit eigenvector: ||w|| = " + w.getNorm() );
        //            System.out.println( Math.abs( w.getNorm() - 1.0 ) );
        //            assert( false );
        //         }
        W.add(w);
        final RealMatrix w_wt = w.outerProduct(w);
        final RealMatrix S_tilde = XLt.multiply(w_wt).multiply(XL);
        T(S_tilde, Si_);
        Si_ = Si_.subtract(S_tilde.scalarMultiply(alpha));
        Xi_ = Xi_.subtract(w_wt.multiply(Xi_));
    }
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.BisquareLinearFit.java

/**
* Calculates the leverages of data points for least squares fitting (assuming equal variances).
* 
* @param indVarValues The values of the independent variable used for the fitting.
* @return a RealVector containing a leverage value for each independent variable value.
*//*from   w w  w  .j  a  va  2 s .  c  om*/
protected RealVector calculateLeverages(RealVector indVarValues) {

    RealMatrix indVarMatrix = null;

    if (this.noIntercept) {
        indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 1);
    } else {
        indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 2);
    }

    indVarMatrix.setColumnVector(0, indVarValues);

    if (!this.noIntercept) {
        indVarMatrix.setColumnVector(1, indVarValues.mapMultiply(0).mapAdd(1));
    }

    RealVector leverages = new ArrayRealVector(indVarValues.getDimension());

    QRDecomposition xQR = new QRDecomposition(indVarMatrix);

    RealMatrix xR = xQR.getR();

    int smallerDim = xR.getRowDimension() < xR.getColumnDimension() ? xR.getRowDimension()
            : xR.getColumnDimension();

    RealMatrix xRSq = xR.getSubMatrix(0, smallerDim - 1, 0, smallerDim - 1);

    QRDecomposition xRQR = new QRDecomposition(xRSq);

    RealMatrix xRInv = xRQR.getSolver().getInverse();

    RealMatrix xxRInv = indVarMatrix.multiply(xRInv);

    for (int i = 0; i < indVarValues.getDimension(); i++) {
        double sum = 0;
        for (int j = 0; j < xxRInv.getColumnDimension(); j++) {
            sum += Math.pow(xxRInv.getEntry(i, j), 2);
        }
        leverages.setEntry(i, sum);
    }

    return leverages;

}

From source file:hello.UserProfileEigenModeler.java

public void generate(String site, String user, RealMatrix matrix) {
    LOG.info(String.format("Receive aggregated user activity matrix: %s size: %s x %s", user,
            matrix.getRowDimension(), matrix.getColumnDimension()));
    computeStats(matrix);// ww  w.j  av  a  2  s. co m
    RealMatrix normalizedInputMatrix = normalizeData(matrix);
    int lowVariantColumnCount = 0;
    for (int j = 0; j < normalizedInputMatrix.getColumnDimension(); j++) {
        if (statistics[j].isLowVariant()) {
            lowVariantColumnCount++;
        }
    }

    if (normalizedInputMatrix.getColumnDimension() == lowVariantColumnCount) {
        LOG.info("found user: " + user + " with all features being low variant. Nothing to do...");
        return;
    } else {
        computeCovarianceAndSVD(normalizedInputMatrix, lowVariantColumnCount);//??
        computeDimensionWithMaxVariance();
        computePrincipalComponents();
        maximumL2Norm = new ArrayRealVector(principalComponents.length);
        minimumL2Norm = new ArrayRealVector(principalComponents.length);

        for (int i = 0; i < principalComponents.length; i++) {
            RealMatrix trainingDataTranspose = computeMaxDistanceOnPCs(i);
        }

        return;
    }
}