List of usage examples for org.apache.commons.math3.linear RealMatrix getRowDimension
int getRowDimension();
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 av a 2 s .c o 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:edu.cudenver.bios.power.test.paper.TestConditionalOrthogonalPolynomial2Factor.java
/** * //from w w w . j av a 2 s . c o m * @param checker * @param outputFilename * @param params */ private void checkPower(PowerChecker checker, String title, String description, String outputFilename, GLMMPowerParameters params) { /* * get orthogonal contrasts for within subject factors * Log base 2 spacing Clip (2,4,16) and Region(2,8,32) */ ArrayList<Factor> factorList = new ArrayList<Factor>(); factorList.add(factorA); factorList.add(factorB); OrthogonalPolynomialContrastCollection collection = OrthogonalPolynomials.withinSubjectContrast(factorList); params.setWithinSubjectContrast(collection.getInteractionContrast(factorList).getContrastMatrix()); // theta critical matrix used to back-tranform beta from U // THETA = {.25}#{.5 1 -1 .5}; * =Theta(cr) from 1st sentence *after* // equation 7, Coffey and Muller (2003); double[][] thetaData = { { 0.5, 1, -1, 0.5 } }; RealMatrix thetaCr = (new Array2DRowRealMatrix(thetaData)).scalarMultiply(0.25); // loop over the various sigma matrices //Test[] testList = Test.values(); Test[] testList = { Test.UNIREP, Test.UNIREP_BOX, Test.UNIREP_GEISSER_GREENHOUSE, Test.UNIREP_HUYNH_FELDT }; for (Test test : testList) { params.clearTestList(); params.addTest(test); for (RealMatrix sigStar : sigmaStars) { RealMatrix U = params.getWithinSubjectContrast(); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix sigmaTemp = U.multiply(sigStar).multiply(U.transpose()); int dimension = sigmaTemp.getRowDimension(); RealMatrix Uother = MatrixUtils.getRealMatrixWithFilledValue(dimension, 1, 1 / Math.sqrt(U.getColumnDimension())); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorA).getContrastMatrix()); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorB).getContrastMatrix()); double varianceMean = (double) sigStar.getTrace() / (double) sigStar.getColumnDimension(); RealMatrix sigmaError = sigmaTemp .add(Uother.multiply(Uother.transpose()).scalarMultiply(varianceMean)); if (verbose) printMatrix("Sigma Error", sigmaError); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix beta = thetaCr.multiply(U.transpose()); params.setSigmaError(sigmaError); params.setBeta(new FixedRandomMatrix(beta.getData(), null, false)); checker.checkPower(params); } } // output the results try { ValidationReportBuilder reportBuilder = new ValidationReportBuilder(); reportBuilder.createValidationReportAsStdout(checker, title, false); reportBuilder.createValidationReportAsLaTex(outputFilename, title, AUTHOR, description, params, checker); } catch (Exception e) { System.err.println(e.getMessage()); } assertTrue(checker.isSASDeviationBelowTolerance()); checker.reset(); }
From source file:edu.cudenver.bios.matrix.test.TestMatrixOrthonormalization.java
/** * Verify that the Q'Q = I for the Q matrix produced by the * orthonormalization//from w ww . j a va 2 s .com */ public void testQQisIdentity() { RealMatrix Q = norm.getQ(); // verify that Q'Q = identity RealMatrix shouldBeIdentityMatrix = Q.transpose().multiply(Q); // make sure the matrix is sqaure if (!shouldBeIdentityMatrix.isSquare()) { fail(); } // make sure the diagonal elements are one (within tolerance), and off diagonals // are zero (within tolerance) for (int r = 0; r < shouldBeIdentityMatrix.getRowDimension(); r++) { for (int c = 0; c < shouldBeIdentityMatrix.getColumnDimension(); c++) { double shouldBeValue = (r == c) ? 1 : 0; if (Precision.compareTo(shouldBeIdentityMatrix.getEntry(r, c), shouldBeValue, TOLERANCE) != 0) fail(); } } assertTrue(true); }
From source file:edu.cudenver.bios.power.test.paper.TestConditionalOrthogonalPolynomial2Factor.java
/** * Write the matrix to std out/* w ww . java 2 s . c o m*/ * @param m */ private void printMatrix(String title, RealMatrix m) { System.out.println(title); DecimalFormat Number = new DecimalFormat("#0.00000000000000000000"); for (int row = 0; row < m.getRowDimension(); row++) { for (int col = 0; col < m.getColumnDimension(); col++) { System.out.print(Number.format(m.getEntry(row, col)) + "\t"); } System.out.print("\n"); } }
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);/*from ww w .ja va2 s .c o 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; } }
From source file:com.clust4j.algo.DBSCAN.java
/** * Constructs an instance of DBSCAN from the provided builder * @param builder//from www. j ava 2 s .com * @param data */ protected DBSCAN(final RealMatrix data, final DBSCANParameters planner) { super(data, planner); this.m = data.getRowDimension(); this.eps = planner.getEps(); // Error handle... if (this.eps <= 0.0) error(new IllegalArgumentException("eps " + "must be greater than 0.0")); if (!isValidMetric(this.dist_metric)) { warn(this.dist_metric.getName() + " is not valid for " + getName() + ". " + "Falling back to default Euclidean dist"); setSeparabilityMetric(DEF_DIST); } logModelSummary(); }
From source file:ellipsoidFit.FitPoints.java
/** * Fit points to the polynomial expression Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz * + 2Fyz + 2Gx + 2Hy + 2Iz = 1 and determine the center and radii of the * fit ellipsoid.// w ww.ja v a 2s. co m * * @param points * the points to be fit to the ellipsoid. */ public void fitEllipsoid(ArrayList<ThreeSpacePoint> points) { // Fit the points to Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz // + 2Fyz + 2Gx + 2Hy + 2Iz = 1 and solve the system. // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); RealVector v = solveSystem(points); // Form the algebraic form of the ellipsoid. RealMatrix a = formAlgebraicMatrix(v); // Find the center of the ellipsoid. center = findCenter(a); // Translate the algebraic form of the ellipsoid to the center. RealMatrix r = translateToCenter(center, a); // Generate a submatrix of r. RealMatrix subr = r.getSubMatrix(0, 2, 0, 2); // subr[i][j] = subr[i][j] / -r[3][3]). double divr = -r.getEntry(3, 3); for (int i = 0; i < subr.getRowDimension(); i++) { for (int j = 0; j < subr.getRowDimension(); j++) { subr.setEntry(i, j, subr.getEntry(i, j) / divr); } } // Get the eigenvalues and eigenvectors. EigenDecomposition ed = new EigenDecomposition(subr, 0); evals = ed.getRealEigenvalues(); evecs = ed.getEigenvector(0); evecs1 = ed.getEigenvector(1); evecs2 = ed.getEigenvector(2); // Find the radii of the ellipsoid. radii = findRadii(evals); }
From source file:com.clust4j.algo.preprocess.BoxCoxTransformer.java
/** * Inverse transform your matrix. Note: this suffers some * accuracy issues due to the log base// ww w . jav a 2s . co m */ @Override public RealMatrix inverseTransform(RealMatrix X) { checkFit(); final int m = X.getRowDimension(); final int n = X.getColumnDimension(); if (n != shift.length) throw new DimensionMismatchException(n, shift.length); double[][] x = X.getData(); for (int j = 0; j < n; j++) { double lam = lambdas[j]; double ool = 1.0 / lam; for (int i = 0; i < m; i++) { // If the lambda is near zero, exp to reverse the log: if (lam < zero) { x[i][j] = FastMath.exp(x[i][j]); } else { x[i][j] *= lam; x[i][j] += 1; x[i][j] = FastMath.pow(x[i][j], ool); } // Add back the shift value: x[i][j] += shift[j]; } } // Implicit copy in the getData() return new Array2DRowRealMatrix(x, false); }
From source file:gamlss.utilities.WLSMultipleLinearRegression.java
/** * //w w w . j a va 2 s . c o m * @param y * @param x * @param w */ private void newSampleDataNoCopy(ArrayRealVector y, RealMatrix x, ArrayRealVector w) { for (int row = 0; row < x.getRowDimension(); row++) { x.setRowVector(row, x.getRowVector(row).mapMultiplyToSelf(w.getEntry(row))); } //double[][] xw=x.getData(); //double[] yw= y.ebeMultiply(w).getDataRef(); //validateSampleData(xw, yw); //we have already checked this in the gamlss algorithm. newYSampleData(y.ebeMultiply(w)); newXSampleData(x.getData(), w); }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
/** * Create the barrier function for the Phase I. * It is an instance of this class for the constraints: * <br>||Ai.x+bi|| < ci.x+di+t, i=1,...,m * @see "S.Boyd and L.Vandenberghe, Convex Optimization, 11.6.2" *//*from www . j ava2 s .co m*/ public BarrierFunction createPhase1BarrierFunction() { final int dimPh1 = dim + 1; List<SOCPConstraintParameters> socpConstraintParametersPh1List = new ArrayList<SOCPConstraintParameters>(); SOCPLogarithmicBarrier bfPh1 = new SOCPLogarithmicBarrier(socpConstraintParametersPh1List, dimPh1); for (int i = 0; i < socpConstraintParametersList.size(); i++) { SOCPConstraintParameters param = socpConstraintParametersList.get(i); RealMatrix A = param.getA(); RealVector b = param.getB(); RealVector c = param.getC(); double d = param.getD(); RealMatrix APh1 = MatrixUtils.createRealMatrix(A.getRowDimension(), dimPh1); APh1.setSubMatrix(A.getData(), 0, 0); RealVector bPh1 = b; RealVector cPh1 = new ArrayRealVector(c.getDimension() + 1); cPh1.setSubVector(0, c); cPh1.setEntry(c.getDimension(), 1); double dPh1 = d; SOCPConstraintParameters paramsPh1 = new SOCPConstraintParameters(APh1.getData(), bPh1.toArray(), cPh1.toArray(), dPh1); socpConstraintParametersPh1List.add(socpConstraintParametersPh1List.size(), paramsPh1); } return bfPh1; }