Example usage for org.apache.commons.math3.linear EigenDecomposition getRealEigenvalues

List of usage examples for org.apache.commons.math3.linear EigenDecomposition getRealEigenvalues

Introduction

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

Prototype

public double[] getRealEigenvalues() 

Source Link

Document

Gets a copy of the real parts of the eigenvalues of the original matrix.

Usage

From source file:edu.ucla.stat.SOCR.analyses.gui.PrincipalComponentAnalysis.java

/**This method defines the specific statistical Analysis to be carried our on the user specified data. ANOVA is done in this case. */
public void doAnalysis() {

    if (dataTable.isEditing())
        dataTable.getCellEditor().stopCellEditing();

    if (!hasExample) {
        JOptionPane.showMessageDialog(this, DATA_MISSING_MESSAGE);
        return;//from ww  w  .  j  a v a 2 s.c o  m
    }

    Data data = new Data();

    String firstMessage = "Would you like to use all the data columns in this Principal Components Analysis?";
    String title = "SOCR - Principal Components Analysis";
    String secondMessage = "Please enter the column numbers (seperated by comma) that you would like to use.";
    String columnNumbers = "";

    int reply = JOptionPane.showConfirmDialog(null, firstMessage, title, JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {
        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        cellValue = null;
        int originalColumn = 0;

        for (int k = 0; k < dataTable.getColumnCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(0, k));

            if (cellValue != null && !cellValue.equals("")) {
                originalColumn++;

            }
        }

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, j) != null && !dataTable.getValueAt(k, j).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, j);
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues();

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }
        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }

        dependentHeader = "C1";
        independentHeader = "C2";
    }

    else { // start here
        try {
            columnNumbers = JOptionPane.showInputDialog(secondMessage);
        } catch (Exception e) {
        }

        String columnNumbersFinal = "," + columnNumbers.replaceAll("\\s", "") + ",";

        Vector<Integer> locationOfComma = new Vector<Integer>(100);

        for (int i = 0; i < columnNumbersFinal.length(); i++) {
            char d = columnNumbersFinal.charAt(i);
            if (d == ',')
                locationOfComma.add(i);
        }

        Vector<Integer> vector = new Vector<Integer>(100); // vector containing column selected numbers

        for (int i = 0; i < locationOfComma.size() - 1; i++) {
            String temp = columnNumbersFinal.substring(locationOfComma.get(i) + 1, locationOfComma.get(i + 1));
            if (temp == "")
                continue;
            vector.add((Integer.parseInt(temp) - 1));

        }

        dependentHeader = "C" + (vector.get(0) + 1);
        independentHeader = "C" + (vector.get(1) + 1);

        // System.out.println("Vector size is: " + vector.size() + "\n");                

        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        int originalColumn = vector.size();

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, vector.get(j)) != null
                        && !dataTable.getValueAt(k, vector.get(j)).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, vector.get(j));
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues(); // added              

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        /* for (int j = 0; j < dataTable.getColumnCount(); j++)
            for (int k = 0; k < dataTable.getRowCount(); k++)
            {
                System.out.println(finalArray[j][k] + " ");
            }*/

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }

        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }
    }

    map = new HashMap<Double, double[]>();

    for (int i = 0; i < dataColumn; i++) {
        map.put(EValueArray[i], storedData.getEigenvector(i).toArray());
    }

    Arrays.sort(EValueArray);

    xData1 = new double[EValueArray.length]; // for Scree Plot
    yData1 = new double[EValueArray.length];

    for (int i = 0; i < EValueArray.length; i++) {
        xData1[i] = i + 1;
    }

    for (int i = 0; i < EValueArray.length; i++) {
        yData1[i] = EValueArray[i];
    }

    for (int i = 0; i < yData1.length / 2; i++) {
        double temp = yData1[i];
        yData1[i] = yData1[yData1.length - i - 1];
        yData1[yData1.length - i - 1] = temp;
    }

    for (int i = 0; i < xData1.length; i++) {
        System.out.println("xData1 contains: " + xData1[i] + "\n");
    }

    for (int i = 0; i < yData1.length; i++) {
        System.out.println("yData1 contains: " + yData1[i] + "\n");
    }

    for (int i = 0; i < EValueArray.length / 2; i++) {
        double temp = EValueArray[i];
        EValueArray[i] = EValueArray[EValueArray.length - i - 1];
        EValueArray[EValueArray.length - i - 1] = temp;
    }

    resultPanelTextArea.append(
            "Click on \"PCA RESULT\" panel to view the transformed data (Eigenvector Transposed * Adjusted Data Transposed)");

    resultPanelTextArea.append("\n\nThe real eigenvalues (in descending order) are: \n\n");
    resultPanelTextArea.append("" + round(EValueArray[0], 3));

    for (int i = 1; i < EValueArray.length; i++) {
        resultPanelTextArea.append("\n" + round(EValueArray[i], 3));
    }
    resultPanelTextArea.append("\n\nThe corresponding eigenvectors (in columns) are: \n\n");

    double temp[] = new double[100];

    for (int j = 0; j < temp.length; j++)
        for (int i = 0; i < EValueArray.length; i++) {
            temp = map.get(EValueArray[i]);
            resultPanelTextArea.append("" + round(temp[j], 3) + "\t");
            if (i == EValueArray.length - 1) {
                resultPanelTextArea.append("\n");
            }
        }

    doGraph();
}

From source file:net2.N2MultiArena.java

public void step() {
    boolean aboveFloor = true;
    double currentCycle = 0.;
    int numFoes = forces.size();
    System.out.println("Num foes = " + numFoes);
    if (isMyTurn == null) {
        isMyTurn = new boolean[numFoes][numFoes];
        stanceArray = new int[numFoes][numFoes];
        currentFloor = new double[numFoes][numFoes];
        currentCeiling = new double[numFoes][numFoes];
        for (int i1 = 0; i1 < numFoes; i1++) {
            //                int ind1 = forceMap.get(forces.get(i1));
            for (int i2 = 0; i2 < numFoes; i2++) {
                //                    int ind2 = forceMap.get(forces.get(i2));
                isMyTurn[i1][i2] = true;
                if (i1 == i2) {
                    stanceArray[i1][i2] = AthenaConstants.ALLIED_POSTURE;
                    currentFloor[i1][i2] = 0.;
                    currentCeiling[i1][i2] = 1000000.;
                } else {
                    stanceArray[i1][i2] = initializeStance(forces.get(i1), forces.get(i2));
                    setFloor(i1, i2);//w  w  w .  j  av  a 2  s .  co m
                    setCeiling(i1, i2);
                }
            }
        }
    }
    Array2DRowRealMatrix mat = getMat();
    EigenDecomposition eigen = new EigenDecomposition(mat);
    double det = eigen.getDeterminant();
    double[] eVals = eigen.getRealEigenvalues();
    if (eigen.hasComplexEigenvalues()) {
        System.out.println("Complex eigenvalues");
        for (int i1 = 0; i1 < forces.size(); i1++) {
            N2ForceUnit f = forces.get(i1);
            System.out.println(f.getName() + " has " + f.getNumber() + " forces remaining");
        }
    }
    double[] initialNums = getInitialNumbers(forces);
    Array2DRowRealMatrix eVectors = (Array2DRowRealMatrix) eigen.getV();
    LUDecomposition lu = new LUDecomposition(eVectors);
    double det2 = lu.getDeterminant();
    double[] coeffs = new double[numFoes];
    for (int i1 = 0; i1 < numFoes; i1++) {
        Array2DRowRealMatrix tmpMat = (Array2DRowRealMatrix) eVectors.copy();
        tmpMat.setColumn(i1, initialNums);
        LUDecomposition tmpLU = new LUDecomposition(tmpMat);
        double tmpDet = tmpLU.getDeterminant();
        coeffs[i1] = tmpDet / det2;
    }
    aboveFloor = true;
    boolean belowCeiling = true;
    //        int cntr = 0;
    int numGone;
    //        do {
    timeStep = determineTimeStep();
    MultiTimeStep currentStep = new MultiTimeStep(numFoes);
    currentTime += timeStep;
    currentCycle += timeStep;
    currentStep.setTime(currentTime);
    numGone = 0;
    for (int i1 = 0; i1 < numFoes; i1++) {
        double updatedForce = 0.;
        //                if (forces.get(i1).getForceSize() > lb) {
        if (stillAlive[i1]) {
            for (int i2 = 0; i2 < numFoes; i2++) {
                //                    updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * timeStep);
                updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * currentCycle);

            }
            if (updatedForce < 1.) {
                updatedForce = lb;
                stillAlive[i1] = false;
                numGone++;
            }
        } else {
            updatedForce = lb;
            numGone++;
        }
        forces.get(i1).updateForce(updatedForce);
        currentStep.setForceNumber(updatedForce, i1);
    }
    history.add(currentStep);
    aboveFloor = checkAboveFloors();
    belowCeiling = checkBelowCeilings();
    //            cntr++;
    //        } while (aboveFloor && belowCeiling && cntr < 2000 && (numFoes - numGone) > 1);
    for (int i1 = 0; i1 < numFoes; i1++) {
        for (int i2 = 0; i2 < numFoes; i2++) {
            if (i1 == i2) {
                stanceArray[i1][i2] = AthenaConstants.ALLIED_POSTURE;
                currentFloor[i1][i2] = 0.;
            } else {
                //                    stanceArray[i1][i2] = initializeStance(forces.get(i1), forces.get(i2));
                setStances(i1, i2);
                setFloor(i1, i2);
                setCeiling(i1, i2);
            }
        }
    }

    if (numFoes - numGone == 1) {
        loneSurvivor = true;
        //            System.out.println("time = " + time);
    }
}

From source file:org.bonej.ops.ellipsoid.QuadricToEllipsoid.java

@Override
public Optional<Ellipsoid> calculate(final Matrix4dc quadricSolution) {
    final Vector3dc center = findCenter(quadricSolution);
    final Matrix4dc translated = translateToCenter(quadricSolution, center);
    final EigenDecomposition decomposition = solveEigenDecomposition(translated);
    final boolean invalidEv = Arrays.stream(decomposition.getRealEigenvalues()).anyMatch(e -> e <= 0.0);
    if (invalidEv) {
        return Optional.empty();
    }//from   w ww  .ja  v a2  s .c  om
    final double[] radii = Arrays.stream(decomposition.getRealEigenvalues()).map(ev -> Math.sqrt(1.0 / ev))
            .toArray();
    final Ellipsoid ellipsoid = new Ellipsoid(radii[0], radii[1], radii[2]);
    ellipsoid.setCentroid(center);
    final Matrix3dc orientation = toOrientationMatrix(decomposition);
    ellipsoid.setOrientation(orientation);
    return Optional.of(ellipsoid);
}

From source file:org.briljantframework.array.netlib.NetlibLinearAlgebraRoutinesTest.java

@Test
public void testCi() throws Exception {
    final int n = 3;
    // DoubleArray a =
    // bj.newDoubleVector(-1.01, 3.98, 3.30, 4.43, 7.31, 0.86, 0.53, 8.26, 4.96, -6.43, -4.60,
    // -7.04, -3.89, -7.66, -6.16, 3.31, 5.29, 8.20, -7.33, 2.47, -4.81, 3.55, -1.51, 6.18,
    // 5.58).reshape(n, n);
    // System.out.println(a);

    DoubleArray a = bj.newDoubleMatrix(new double[][] { { 0, 2, 3 }, { 2, 0, 2 }, { 3, 2, 0 } });

    DoubleArray wr = bj.newDoubleArray(n);
    DoubleArray wi = bj.newDoubleArray(n);
    DoubleArray vl = bj.newDoubleArray(n, n);
    DoubleArray vr = bj.newDoubleArray(n, n);
    DoubleArray copy = a.copy();/*w  w  w . ja  v  a2 s .  c o  m*/
    // linalg.geev('v', 'v', copy, wr, wi, vl, vr);
    linalg.syev('v', 'u', copy, wr);

    wr.sort((i, j) -> Double.compare(j, i));
    System.out.println(copy);
    System.out.println(wr);

    ComplexArray v = bj.newComplexArray(n, n);
    for (int i = 0; i < n; i++) {
        if (Precision.equals(wi.get(i), 0, 1e-6)) {
            v.setColumn(i, vr.getColumn(i).asComplex());
        } else {
            DoubleArray real = vr.getColumn(i);
            DoubleArray imag = vr.getColumn(i + 1);
            v.setColumn(i, toComplex(real, imag));
            v.setColumn(i + 1, toComplex(real, imag.negate()));
            i++;
        }
    }
    //    System.out.println(v);

    RealMatrix matrix = Matrices.asRealMatrix(a);
    EigenDecomposition d = new EigenDecomposition(matrix);
    System.out.println(Matrices.toArray(d.getD()));
    System.out.println(Matrices.toArray(d.getV()));
    // System.out.println(d.getEigenvector(0));
    System.out.println(Arrays.toString(d.getRealEigenvalues()));
    // System.out.println(Arrays.toString(d.getImagEigenvalues()));
}

From source file:org.eclipse.dataset.LinearAlgebra.java

/**
 * @param a//from   ww w . j  a va2 s  . com
 * @return dataset of eigenvalues (can be double or complex double)
 */
public static Dataset calcEigenvalues(Dataset a) {
    EigenDecomposition evd = new EigenDecomposition(createRealMatrix(a));
    double[] rev = evd.getRealEigenvalues();

    if (evd.hasComplexEigenvalues()) {
        double[] iev = evd.getImagEigenvalues();
        return new ComplexDoubleDataset(rev, iev);
    }
    return new DoubleDataset(rev);
}

From source file:org.eclipse.dataset.LinearAlgebra.java

/**
 * Calculate eigen-decomposition A = V D V^T
 * @param a//from w w w. ja  va2  s .  co  m
 * @return array of D eigenvalues (can be double or complex double) and V eigenvectors
 */
public static Dataset[] calcEigenDecomposition(Dataset a) {
    EigenDecomposition evd = new EigenDecomposition(createRealMatrix(a));
    Dataset[] results = new Dataset[2];

    double[] rev = evd.getRealEigenvalues();
    if (evd.hasComplexEigenvalues()) {
        double[] iev = evd.getImagEigenvalues();
        results[0] = new ComplexDoubleDataset(rev, iev);
    } else {
        results[0] = new DoubleDataset(rev);
    }
    results[1] = createDataset(evd.getV());
    return results;
}

From source file:org.eclipse.january.dataset.LinearAlgebra.java

/**
 * @param a/*w  ww .ja v a 2s . c  o  m*/
 * @return dataset of eigenvalues (can be double or complex double)
 */
public static Dataset calcEigenvalues(Dataset a) {
    EigenDecomposition evd = new EigenDecomposition(createRealMatrix(a));
    double[] rev = evd.getRealEigenvalues();

    if (evd.hasComplexEigenvalues()) {
        double[] iev = evd.getImagEigenvalues();
        return DatasetFactory.createComplexDataset(ComplexDoubleDataset.class, rev, iev);
    }
    return DatasetFactory.createFromObject(rev);
}

From source file:org.eclipse.january.dataset.LinearAlgebra.java

/**
 * Calculate eigen-decomposition A = V D V^T
 * @param a/*from  w  ww.  j  av a 2  s . c o  m*/
 * @return array of D eigenvalues (can be double or complex double) and V eigenvectors
 */
public static Dataset[] calcEigenDecomposition(Dataset a) {
    EigenDecomposition evd = new EigenDecomposition(createRealMatrix(a));
    Dataset[] results = new Dataset[2];

    double[] rev = evd.getRealEigenvalues();
    if (evd.hasComplexEigenvalues()) {
        double[] iev = evd.getImagEigenvalues();
        results[0] = DatasetFactory.createComplexDataset(ComplexDoubleDataset.class, rev, iev);
    } else {
        results[0] = DatasetFactory.createFromObject(rev);
    }
    results[1] = createDataset(evd.getV());
    return results;
}

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  v a2s .  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.meteoinfo.math.linalg.LinalgUtil.java

/**
 * Calculates the eigen decomposition of a real matrix.
 * The eigen decomposition of matrix A is a set of two matrices: V and D such that 
 * A = V  D  VT. A, V and D are all m  m matrices.
 * @param a Given matrix.//  ww w .j  a va 2  s  .c om
 * @return Result W/V arrays.
 */
public static Array[] eigen(Array a) {
    int m = a.getShape()[0];
    Array Wa;
    Array Va = Array.factory(DataType.DOUBLE, new int[] { m, m });
    double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray(a);
    RealMatrix matrix = new Array2DRowRealMatrix(aa, false);
    EigenDecomposition decomposition = new EigenDecomposition(matrix);
    double[] rev = decomposition.getRealEigenvalues();
    double[] iev = decomposition.getImagEigenvalues();
    if (decomposition.hasComplexEigenvalues()) {
        Wa = Array.factory(DataType.OBJECT, new int[] { m });
        for (int i = 0; i < m; i++) {
            Wa.setObject(i, new Complex(rev[i], iev[i]));
            RealVector v = decomposition.getEigenvector(i);
            for (int j = 0; j < v.getDimension(); j++) {
                Va.setDouble(i * m + j, v.getEntry(j));
            }
        }
    } else {
        Wa = Array.factory(DataType.DOUBLE, new int[] { m });
        for (int i = 0; i < m; i++) {
            Wa.setDouble(i, rev[i]);
            RealVector v = decomposition.getEigenvector(i);
            for (int j = 0; j < v.getDimension(); j++) {
                Va.setDouble(i * m + j, v.getEntry(j));
            }
        }
    }

    return new Array[] { Wa, Va };
}