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:net.sf.dsp4j.octave_3_2_4.Eig.java

public static Complex[] eig(RealMatrix d) {
    EigenDecomposition eig = new EigenDecomposition(d);
    double[] realEigenvalues = eig.getRealEigenvalues();
    double[] imagEigenvalues = eig.getImagEigenvalues();

    final Complex[] result = new Complex[realEigenvalues.length];
    for (int i = 0; i < realEigenvalues.length; i++) {
        result[i] = new Complex(realEigenvalues[i], imagEigenvalues[i]);
    }// w w w.j a  va  2 s.com
    return result;
}

From source file:edu.cmu.sphinx.speakerid.SpeakerIdentification.java

/**
 * @param mat/*from   w  w w .  ja va  2 s .co m*/
 *            A matrix with feature vectors as rows.
 * @return Returns the BICValue of the Gaussian model that approximates the
 *         the feature vectors data samples
 */
public static double getBICValue(Array2DRowRealMatrix mat) {
    double ret = 0;
    EigenDecomposition ed = new EigenDecomposition(new Covariance(mat).getCovarianceMatrix());
    double[] re = ed.getRealEigenvalues();
    for (int i = 0; i < re.length; i++)
        ret += Math.log(re[i]);
    return ret * (mat.getRowDimension() / 2);
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibCommonsMath.java

/**
 * Function to perform Eigen decomposition on a given matrix.
 * Input must be a symmetric matrix.//w w w. ja  v a 2s .c o  m
 * 
 * @param in
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock[] computeEigen(MatrixObject in) throws DMLRuntimeException {
    if (in.getNumRows() != in.getNumColumns()) {
        throw new DMLRuntimeException(
                "Eigen Decomposition can only be done on a square matrix. Input matrix is rectangular (rows="
                        + in.getNumRows() + ", cols=" + in.getNumColumns() + ")");
    }

    Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in);

    EigenDecomposition eigendecompose = new EigenDecomposition(matrixInput);
    RealMatrix eVectorsMatrix = eigendecompose.getV();
    double[][] eVectors = eVectorsMatrix.getData();
    double[] eValues = eigendecompose.getRealEigenvalues();

    //Sort the eigen values (and vectors) in increasing order (to be compatible w/ LAPACK.DSYEVR())
    int n = eValues.length;
    for (int i = 0; i < n; i++) {
        int k = i;
        double p = eValues[i];
        for (int j = i + 1; j < n; j++) {
            if (eValues[j] < p) {
                k = j;
                p = eValues[j];
            }
        }
        if (k != i) {
            eValues[k] = eValues[i];
            eValues[i] = p;
            for (int j = 0; j < n; j++) {
                p = eVectors[j][i];
                eVectors[j][i] = eVectors[j][k];
                eVectors[j][k] = p;
            }
        }
    }

    MatrixBlock mbValues = DataConverter.convertToMatrixBlock(eValues, true);
    MatrixBlock mbVectors = DataConverter.convertToMatrixBlock(eVectors);

    return new MatrixBlock[] { mbValues, mbVectors };
}

From source file:edu.cmu.tetrad.search.TimeSeriesUtils.java

public static boolean allEigenvaluesAreSmallerThanOneInModulus(TetradMatrix mat) {

    double[] realEigenvalues = new double[0];
    double[] imagEigenvalues = new double[0];
    try {//from  www. j  a  v  a  2  s.  c om
        EigenDecomposition dec = new EigenDecomposition(mat.getRealMatrix());
        realEigenvalues = dec.getRealEigenvalues();
        imagEigenvalues = dec.getImagEigenvalues();
    } catch (MaxCountExceededException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < realEigenvalues.length; i++) {
        double realEigenvalue = realEigenvalues[i];
        double imagEigenvalue = imagEigenvalues[i];
        System.out.println("Real eigenvalues are : " + realEigenvalue + " and imag part : " + imagEigenvalue);
        double modulus = Math.sqrt(Math.pow(realEigenvalue, 2) + Math.pow(imagEigenvalue, 2));

        if (modulus >= 1.0) {
            return false;
        }
    }
    return true;
}

From source file:com.joptimizer.functions.SDPLogarithmicBarrier.java

/**
 * Calculates the initial value for the s parameter in Phase I.
 * Return s so that F(x)-s.I is negative definite
 * @see "S.Boyd and L.Vandenberghe, Convex Optimization, 11.6.2"
 * @see "S.Boyd and L.Vandenberghe, Semidefinite programming, 6.1"
 *//*w  w  w .j  a va2s .  c o m*/
public double calculatePhase1InitialFeasiblePoint(double[] originalNotFeasiblePoint, double tolerance) {
    RealMatrix F = this.buildS(originalNotFeasiblePoint).scalarMultiply(-1);
    RealMatrix S = F.scalarMultiply(-1);
    try {
        new CholeskyDecomposition(S);
        //already feasible
        return -1;
    } catch (NonPositiveDefiniteMatrixException ee) {
        //it does NOT mean that F is negative, it can be not definite
        EigenDecomposition eFact = new EigenDecomposition(F, Double.NaN);
        double[] eValues = eFact.getRealEigenvalues();
        double minEigenValue = eValues[Utils.getMinIndex(eValues)];
        return -Math.min(minEigenValue * Math.pow(tolerance, -0.5), 0.);
    }
}

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./*from w w  w. j ava  2s. c  o  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.trickl.math.lanczos.TridiagonalMatrix.java

protected void compute() {
    err.clear();/*w ww .  j ava  2s  .  c  o m*/
    eigval_distinct.clear();
    multiplicty.clear();

    err_noghost.clear();
    eigval_distinct_noghost.clear();
    multiplicty_noghost.clear();

    computed = true;
    int n = alpha.length;
    EigenDecomposition eigenDecomposition = new EigenDecomposition(alpha, beta);
    double[] eval = eigenDecomposition.getRealEigenvalues();
    Arrays.sort(eval); // Consistent with IETL

    // tolerance values:
    multipleTolerance = Math.max(alpha_max, beta_max) * 2 * epsilon * (1000 + n);
    threshold = Math.max(eval[0], eval[n - 1]);
    threshold = Math.max(errorTolerance * threshold, 5 * multipleTolerance);

    // error estimates of eigen values starts:    
    // the unique eigen values selection, their multiplicities and corresponding errors calculation follows:
    double temp = eval[0];
    eigval_distinct.add(eval[0]);
    int multiple = 1;

    for (int i = 1; i < n; i++) {
        double[] eigenvector = eigenDecomposition.getEigenvector(eval.length - i).toArray();
        if (Math.abs(eval[i] - temp) > threshold) {
            eigval_distinct.add(eval[i]);
            temp = eval[i];
            multiplicty.add(multiple);
            if (multiple > 1) {
                err.add(0.);
            } else {
                err.add(Math.abs(beta[beta.length - 1] * eigenvector[n - 1])); // *beta.rbegin() = betaMplusOne.
            }
            multiple = 1;
        } else {
            multiple++;
        }
    }

    // for last eigen value.
    multiplicty.add(multiple);
    if (multiple > 1) {
        err.add(.0);
    } else {
        double[] eigenvector = eigenDecomposition.getEigenvector(eval.length - n).toArray();
        err.add(Math.abs(beta[beta.length - 1] * eigenvector[n - 1])); // *beta.rbegin() = betaMplusOne.
    }
    // the unique eigen values selection, their multiplicities and corresponding errors calculation ends.
    // ghosts calculations starts:
    double[] beta_g = Arrays.copyOfRange(beta, 1, beta.length);
    double[] alpha_g = Arrays.copyOfRange(alpha, 1, alpha.length);

    eigenDecomposition = new EigenDecomposition(alpha_g, beta_g);
    double[] eval_g = eigenDecomposition.getRealEigenvalues();
    Arrays.sort(eval_g); // Consistent with IETL

    int i = 0, t2 = 0;

    for (double eigval : eigval_distinct) {
        if (multiplicty.get(i) == 1) { // test of spuriousness for the eigenvalues whose multiplicity is one.
            for (int j = t2; j < n - 1; j++, t2++) { // since size of reduced matrix is n-1
                if (eval_g[j] - eigval >= multipleTolerance) {
                    break;
                }

                if (Math.abs(eigval - eval_g[j]) < multipleTolerance) {
                    multiplicty.set(i, 0);
                    err.set(i, .0); // if eigen value is a ghost => error calculation not required, 0=> ignore error.
                    t2++;
                    break;
                }
            }
        }
        i++;
    }

    i = 0;
    for (double eigval : eigval_distinct) {
        if (multiplicty.get(i) != 0) {
            eigval_distinct_noghost.add(eigval);
            multiplicty_noghost.add(multiplicty.get(i));
            err_noghost.add(err.get(i));
        }
        i++;
    }
}

From source file:lanchester.MultiArena.java

public void step() {
    int numFoes = forces.size();
    if (isMyTurn == null) {
        isMyTurn = new boolean[numFoes][numFoes];
        stanceArray = new int[numFoes][numFoes];
        currentFloor = 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.;
                } else {
                    stanceArray[i1][i2] = initializeStance(forces.get(i1), forces.get(i2));
                    setFloor(i1, i2);//from   ww  w. jav  a 2 s  .  c  o  m
                }
            }
        }
    }
    Array2DRowRealMatrix mat = getMat();
    EigenDecomposition eigen = new EigenDecomposition(mat);
    double det = eigen.getDeterminant();
    double[] eVals = eigen.getRealEigenvalues();
    //        for(int i1=0;i1<eVals.length;i1++){
    //            System.out.println("eVals["+i1+"] = "+eVals[i1]);
    //        }
    if (eigen.hasComplexEigenvalues()) {
        System.out.println("Complex eigenvalues");
        for (int i1 = 0; i1 < forces.size(); i1++) {
            AthenaForce f = forces.get(i1);
            System.out.println(f.getName() + " has " + f.getForceSize() + " 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;
    }
    MultiTimeStep currentStep = new MultiTimeStep(numFoes);
    currentTime += timeStep;
    currentStep.setTime(currentTime);
    for (int i1 = 0; i1 < numFoes; i1++) {
        double updatedForce = 0.;
        for (int i2 = 0; i2 < numFoes; i2++) {
            updatedForce += coeffs[i2] * eVectors.getEntry(i1, i2) * Math.exp(eVals[i2] * timeStep);
            //                updatedForce+=coeffs[i2]*eVectors.getEntry(i2, i1)*Math.exp(eVals[i2]*timeStep);
            //                updatedForce+=coeffs[i1]*eVectors.getEntry(i2, i1)*Math.exp(eVals[i1]*timeStep);
        }
        forces.get(i1).updateForce(updatedForce);
        currentStep.setForceNumber(updatedForce, i1);
    }
    history.add(currentStep);
    //        eVectors.
    //        this.currentTime++;
    //                Truncator truncator = new Truncator();
    if (true) {
        //            System.out.println("time = " + time);
    }
}

From source file:GeMSE.GS.Analysis.Stats.OneSamplePCAPanel.java

private void computePrincipalComponents() {
    RealMatrix realMatrix = MatrixUtils.createRealMatrix(_data);
    Covariance covariance = new Covariance(realMatrix);
    _covariance = covariance.getCovarianceMatrix();
    EigenDecomposition ed = new EigenDecomposition(_covariance);
    double[] realEigenvalues = ed.getRealEigenvalues();

    int pcaCols = numPCAIndices(realEigenvalues, _level);
    int eigenCount = realEigenvalues.length;
    _principalComponents = new Array2DRowRealMatrix(eigenCount, pcaCols);
    _variance = new ArrayRealVector(pcaCols);

    for (int i = 0; i < pcaCols; i++) {
        RealVector eigenVec = ed.getEigenvector(i);
        for (int j = 0; j < eigenCount; j++)
            _principalComponents.setEntry(j, i, eigenVec.getEntry(j));
        _variance.setEntry(i, realEigenvalues[i]);
    }//w w  w.  jav  a 2 s  . c o m
}

From source file:com.trickl.math.lanczos.LanczosSolver.java

private void findM1M2(double[] eigenvalues) {

    int m2counter = 0;
    int n = 1;//from www  .  j  a  va 2 s. com
    int pos = 0;
    M1 = new int[eigenvalues.length];
    Arrays.fill(M1, 0);
    M2 = new int[eigenvalues.length];
    Arrays.fill(M2, 0);

    while (m2counter < (eigenvalues.length) && (n < alpha.length)) {
        n++; // n++ == 2, at first time in this loop.

        EigenDecomposition eigenDecomposition = new EigenDecomposition(alpha, beta);
        double[] eval = eigenDecomposition.getRealEigenvalues();
        Arrays.sort(eval); // Consistent with IETL

        int M1_itr = 0;
        int M2_itr = 0;

        while (pos != eigenvalues.length) {
            if (M1[M1_itr] == 0 || M2[M2_itr] == 0) {
                double eigenvalue = eigenvalues[pos];
                int ub = Sorting.LowerBound(eval, eigenvalue + threshold);
                int lb = Sorting.UpperBound(eval, eigenvalue - threshold);

                if (M1[M1_itr] == 0 && ub - lb >= 1) {
                    M1[M1_itr] = n;
                }
                if (M2[M2_itr] == 0 && ub - lb >= 2) {
                    M2[M2_itr] = n;
                    m2counter++;
                }
            }
            pos++;
            M1_itr++;
            M2_itr++;
        }
    }
}