List of usage examples for org.apache.commons.math3.linear RealMatrix isSquare
boolean isSquare();
From source file:lirmm.inria.fr.math.BigSparseRealMatrixTest.java
/** * extracts the l and u matrices from compact lu representation *///from w w w .ja v a 2 s . co m protected void splitLU(RealMatrix lu, double[][] lowerData, double[][] upperData) { if (!lu.isSquare()) { throw new NonSquareMatrixException(lu.getRowDimension(), lu.getColumnDimension()); } if (lowerData.length != lowerData[0].length) { throw new DimensionMismatchException(lowerData.length, lowerData[0].length); } if (upperData.length != upperData[0].length) { throw new DimensionMismatchException(upperData.length, upperData[0].length); } if (lowerData.length != upperData.length) { throw new DimensionMismatchException(lowerData.length, upperData.length); } if (lowerData.length != lu.getRowDimension()) { throw new DimensionMismatchException(lowerData.length, lu.getRowDimension()); } int n = lu.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j < i) { lowerData[i][j] = lu.getEntry(i, j); upperData[i][j] = 0d; } else if (i == j) { lowerData[i][j] = 1d; upperData[i][j] = lu.getEntry(i, j); } else { lowerData[i][j] = 0d; upperData[i][j] = lu.getEntry(i, j); } } } }
From source file:edu.cudenver.bios.power.GLMMPowerCalculator.java
/** * Ensure that all required matrices are specified, and that conformance is correct * @param params GLMM input parameters//from ww w. j a v a 2 s. com * @throws IllegalArgumentException */ protected void validateMatrices(GLMMPowerParameters params) throws PowerException { if (params.getConfidenceIntervalType() != ConfidenceIntervalType.NONE && params.getSampleSizeForEstimates() <= params.getDesignMatrixRankForEstimates()) { throw new PowerException(NEGATIVE_NU_EST_MESSAGE, PowerErrorEnum.POWER_CI_NEGATIVE_NU_EST); } // convenience variables RealMatrix beta = params.getBeta().getCombinedMatrix(); RealMatrix theta0 = params.getTheta(); RealMatrix XEssence = params.getDesignEssence(); RealMatrix C = params.getBetweenSubjectContrast().getCombinedMatrix(); RealMatrix U = params.getWithinSubjectContrast(); RealMatrix sigmaE = params.getSigmaError(); RealMatrix sigmaG = params.getSigmaGaussianRandom(); RealMatrix sigmaY = params.getSigmaOutcome(); RealMatrix sigmaYG = params.getSigmaOutcomeGaussianRandom(); int numRandom = sigmaG != null ? sigmaG.getRowDimension() : 0; // only allow at most 1 random predictor // TODO: handle multiple random predictors if (numRandom > 1) throw new PowerException("Too many random predictors - at most 1 is allowed", PowerErrorEnum.MAX_RANDOM_PREDICTORS_EXCEEDED); // make sure all required matrices have been specified // note, we don't check U (within subject contrast), since it may be null in univariate cases if (beta == null) throw new PowerException("No beta (regression coefficients) matrix specified", PowerErrorEnum.MISSING_MATRIX_BETA); if (XEssence == null) throw new PowerException("No design essence matrix specified", PowerErrorEnum.MISSING_MATRIX_DESIGN); if (C == null) throw new PowerException("No between subject contrast (C) matrix specified", PowerErrorEnum.MISSING_MATRIX_C); if (theta0 == null) throw new PowerException("No theta_null (null hypothesis) matrix specified", PowerErrorEnum.MISSING_MATRIX_THETA_NULL); // create a default U if not specified if (U == null) { U = org.apache.commons.math3.linear.MatrixUtils.createRealIdentityMatrix(beta.getColumnDimension()); params.setWithinSubjectContrast(U); } // different variance/covariance matrices are specified depending on the presence // of random covariate if (numRandom == 0) { if (sigmaE == null) throw new PowerException("No sigma (error) matrix specified", PowerErrorEnum.MISSING_MATRIX_SIGMA_E); if (!sigmaE.isSquare()) throw new PowerException("Sigma error matrix must be square", PowerErrorEnum.MATRIX_NONSQUARE_SIGMA_E); if (U.getRowDimension() != sigmaE.getRowDimension()) throw new PowerException( "Within subject contrast matrix " + "(" + U.getRowDimension() + " x " + U.getColumnDimension() + ")" + " does not conform with " + "sigma matrix " + "(" + sigmaE.getRowDimension() + " x " + sigmaE.getColumnDimension() + ")", PowerErrorEnum.MATRIX_CONFORMANCE_U_SIGMA_E); } else if (numRandom == 1) { // covariate (results not published for Wilk's Lambda or Pillai-Bartlett for (Test test : params.getTestList()) { if (test != Test.HOTELLING_LAWLEY_TRACE && test != Test.UNIREP && test != Test.UNIREP_BOX && test != Test.UNIREP_GEISSER_GREENHOUSE && test != Test.UNIREP_HUYNH_FELDT) throw new PowerException( "With a random covariate, " + "only Hotelling-Lawley and Unirep test statistics are supported", PowerErrorEnum.UNKNOWN_TEST_REQUESTED_RANDOM); } if (sigmaG == null) throw new PowerException("No variance/covariance matrix specified for gaussian predictors", PowerErrorEnum.MISSING_MATRIX_SIGMA_G); if (sigmaY == null) throw new PowerException("No variance/covariance matrix specified for response variables", PowerErrorEnum.MISSING_MATRIX_SIGMA_Y); if (sigmaYG == null) throw new PowerException("No outcome / gaussian predictor covariance matrix specified", PowerErrorEnum.MISSING_MATRIX_SIGMA_YG); // check conformance if (U.getRowDimension() != sigmaY.getRowDimension()) throw new PowerException( "Within subject contrast matrix " + "(" + U.getRowDimension() + " x " + U.getColumnDimension() + ")" + " does not conform with " + "sigma matrix " + "(" + sigmaY.getRowDimension() + " x " + sigmaY.getColumnDimension() + ")", PowerErrorEnum.MATRIX_CONFORMANCE_U_SIGMA_Y); if (sigmaG.getRowDimension() != sigmaYG.getColumnDimension()) throw new PowerException( "Outcome / Gaussian predictor covariance " + "matrix does not conform with variance matrix for the gaussian predictor", PowerErrorEnum.MATRIX_CONFORMANCE_SIGMA_G_SIGMA_YG); if (!sigmaY.isSquare()) throw new PowerException("Variance/covariance matrix for " + "response variables must be square", PowerErrorEnum.MATRIX_NONSQUARE_SIGMA_Y); if (!sigmaG.isSquare()) throw new PowerException("Variance/covariance matrix " + "for gaussian predictors must be square", PowerErrorEnum.MATRIX_NONSQUARE_SIGMA_G); } // check dimensionality if (C.getColumnDimension() != beta.getRowDimension()) throw new PowerException("Between subject contrast matrix does not conform with beta matrix", PowerErrorEnum.MATRIX_CONFORMANCE_C_BETA); if (beta.getColumnDimension() != U.getRowDimension()) throw new PowerException("Within subject contrast matrix does not conform with beta matrix", PowerErrorEnum.MATRIX_CONFORMANCE_BETA_U); if ((XEssence.getColumnDimension() != beta.getRowDimension() && numRandom == 0) || (XEssence.getColumnDimension() + 1 != beta.getRowDimension() && numRandom > 0)) throw new PowerException("Design matrix does not conform with beta matrix", PowerErrorEnum.MATRIX_CONFORMANCE_X_BETA); if (C.getRowDimension() > C.getColumnDimension()) throw new PowerException( "Number of rows in between subject " + "contrast must be less than or equal to the number of columns", PowerErrorEnum.MATRIX_DIMENSION_C_TOO_MANY_ROWS); if (U.getColumnDimension() > U.getRowDimension()) throw new PowerException( "Number of columns in within " + "subject contrast must be less than or equal to the number of rows", PowerErrorEnum.MATRIX_DIMENSION_U_TOO_MANY_COLUMNS); if (theta0.getRowDimension() != C.getRowDimension()) throw new PowerException( "Number of rows in theta null " + "must equal number of rows in between subject contrast", PowerErrorEnum.MATRIX_CONFORMANCE_C_THETA_NULL); if (theta0.getColumnDimension() != U.getColumnDimension()) throw new PowerException( "Number of columns in theta null " + "must equal number of columns in within subject contrast", PowerErrorEnum.MATRIX_CONFORMANCE_U_THETA_NULL); // check rank of the design matrix int rankX = new SingularValueDecomposition(XEssence).getRank(); if (rankX != Math.min(XEssence.getColumnDimension(), XEssence.getRowDimension())) throw new PowerException("Design matrix is not full rank: it is of rank " + rankX, PowerErrorEnum.MATRIX_RANK_DESIGN_LTFR); // make sure design matrix is symmetric and positive definite // TODO: how to check this? }
From source file:org.knime.al.util.noveltydetection.knfst.KNFST.java
public static RealMatrix projection(final RealMatrix kernelMatrix, final String[] labels) throws KNFSTException { final ClassWrapper[] classes = ClassWrapper.classes(labels); // check labels if (classes.length == 1) { throw new IllegalArgumentException( "not able to calculate a nullspace from data of a single class using KNFST (input variable \"labels\" only contains a single value)"); }//from w w w . j a va 2 s. c om // check kernel matrix if (!kernelMatrix.isSquare()) { throw new IllegalArgumentException("The KernelMatrix must be quadratic!"); } // calculate weights of orthonormal basis in kernel space final RealMatrix centeredK = centerKernelMatrix(kernelMatrix); final EigenDecomposition eig = new EigenDecomposition(centeredK); final double[] eigVals = eig.getRealEigenvalues(); final ArrayList<Integer> nonZeroEigValIndices = new ArrayList<Integer>(); for (int i = 0; i < eigVals.length; i++) { if (eigVals[i] > 1e-12) { nonZeroEigValIndices.add(i); } } int eigIterator = 0; final RealMatrix eigVecs = eig.getV(); RealMatrix basisvecs = null; try { basisvecs = MatrixUtils.createRealMatrix(eigVecs.getRowDimension(), nonZeroEigValIndices.size()); } catch (final Exception e) { throw new KNFSTException("Something went wrong. Try different parameters or a different kernel."); } for (final Integer index : nonZeroEigValIndices) { final double normalizer = 1 / Math.sqrt(eigVals[index]); final RealVector basisVec = eigVecs.getColumnVector(eigIterator).mapMultiply(normalizer); basisvecs.setColumnVector(eigIterator++, basisVec); } // calculate transformation T of within class scatter Sw: // T= B'*K*(I-L) and L a block matrix final RealMatrix L = kernelMatrix.createMatrix(kernelMatrix.getRowDimension(), kernelMatrix.getColumnDimension()); int start = 0; for (final ClassWrapper cl : classes) { final int count = cl.getCount(); L.setSubMatrix(MatrixFunctions.ones(count, count).scalarMultiply(1.0 / count).getData(), start, start); start += count; } // need Matrix M with all entries 1/m to modify basisvecs which allows // usage of // uncentered kernel values (eye(size(M)).M)*basisvecs final RealMatrix M = MatrixFunctions .ones(kernelMatrix.getColumnDimension(), kernelMatrix.getColumnDimension()) .scalarMultiply(1.0 / kernelMatrix.getColumnDimension()); final RealMatrix I = MatrixUtils.createRealIdentityMatrix(M.getColumnDimension()); // compute helper matrix H final RealMatrix H = ((I.subtract(M)).multiply(basisvecs)).transpose().multiply(kernelMatrix) .multiply(I.subtract(L)); // T = H*H' = B'*Sw*B with B=basisvecs final RealMatrix T = H.multiply(H.transpose()); // calculate weights for null space RealMatrix eigenvecs = MatrixFunctions.nullspace(T); if (eigenvecs == null) { final EigenDecomposition eigenComp = new EigenDecomposition(T); final double[] eigenvals = eigenComp.getRealEigenvalues(); eigenvecs = eigenComp.getV(); final int minId = MatrixFunctions.argmin(MatrixFunctions.abs(eigenvals)); final double[] eigenvecsData = eigenvecs.getColumn(minId); eigenvecs = MatrixUtils.createColumnRealMatrix(eigenvecsData); } // System.out.println("eigenvecs:"); // test.printMatrix(eigenvecs); // calculate null space projection final RealMatrix proj = ((I.subtract(M)).multiply(basisvecs)).multiply(eigenvecs); return proj; }
From source file:org.pmad.gmm.HessenbergTransformer.java
/** * Build the transformation to Hessenberg form of a general matrix. * * @param matrix matrix to transform/*from w w w.j av a 2 s . c o m*/ * @throws NonSquareMatrixException if the matrix is not square */ public HessenbergTransformer(final RealMatrix matrix) { if (!matrix.isSquare()) { throw new NonSquareMatrixException(matrix.getRowDimension(), matrix.getColumnDimension()); } final int m = matrix.getRowDimension(); householderVectors = matrix.getData(); ort = new double[m]; cachedP = null; cachedPt = null; cachedH = null; // transform matrix transform(); }
From source file:org.pmad.gmm.SchurTransformer.java
/** * Build the transformation to Schur form of a general real matrix. * * @param matrix matrix to transform//from w ww.j a va 2 s . c o m * @throws NonSquareMatrixException if the matrix is not square */ public SchurTransformer(final RealMatrix matrix) { if (!matrix.isSquare()) { throw new NonSquareMatrixException(matrix.getRowDimension(), matrix.getColumnDimension()); } HessenbergTransformer transformer = new HessenbergTransformer(matrix); matrixT = transformer.getH().getData(); matrixP = transformer.getP().getData(); cachedT = null; cachedP = null; cachedPt = null; // transform matrix transform(); }
From source file:org.pmad.gmm.TriDiagonalTransformer.java
/** * Build the transformation to tridiagonal shape of a symmetrical matrix. * <p>The specified matrix is assumed to be symmetrical without any check. * Only the upper triangular part of the matrix is used.</p> * * @param matrix Symmetrical matrix to transform. * @throws NonSquareMatrixException if the matrix is not square. *//*from www .j a v a 2s .c o m*/ public TriDiagonalTransformer(RealMatrix matrix) { if (!matrix.isSquare()) { throw new NonSquareMatrixException(matrix.getRowDimension(), matrix.getColumnDimension()); } final int m = matrix.getRowDimension(); householderVectors = matrix.getData(); main = new double[m]; secondary = new double[m - 1]; cachedQ = null; cachedQt = null; cachedT = null; // transform matrix transform(); }