Example usage for org.apache.commons.math3.linear MatrixUtils createRealDiagonalMatrix

List of usage examples for org.apache.commons.math3.linear MatrixUtils createRealDiagonalMatrix

Introduction

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

Prototype

public static RealMatrix createRealDiagonalMatrix(final double[] diagonal) 

Source Link

Document

Returns a diagonal matrix with specified elements.

Usage

From source file:edu.washington.gs.skyline.model.quantification.WeightedRegression.java

public static double[] weighted(double[][] x, double[] y, double[] weights, boolean intercept) {
    RealMatrix predictor;//from ww  w. j  av  a  2  s .co m
    if (intercept) {
        int nRows = x.length;
        int nCols = x[0].length + 1;
        predictor = MatrixUtils.createRealMatrix(nRows, nCols);
        for (int iRow = 0; iRow < nRows; iRow++) {
            predictor.setEntry(iRow, 0, 1.0);
            for (int iCol = 1; iCol < nCols; iCol++) {
                predictor.setEntry(iRow, iCol, x[iRow][iCol - 1]);
            }
        }
    } else {
        predictor = MatrixUtils.createRealMatrix(x);
    }
    RealVector responseVector = MatrixUtils.createRealVector(y);
    RealMatrix weightsMatrix = MatrixUtils.createRealDiagonalMatrix(weights);
    RealMatrix predictorTransposed = predictor.transpose();
    RealMatrix predictorTransposedTimesWeights = predictorTransposed
            .multiply(weightsMatrix.multiply(predictor));
    CholeskyDecomposition choleskyDecomposition = new CholeskyDecomposition(predictorTransposedTimesWeights);
    RealVector vectorToSolve = predictorTransposed.operate(weightsMatrix.operate(responseVector));
    RealVector result = choleskyDecomposition.getSolver().solve(vectorToSolve);
    return result.toArray();
}

From source file:com.github.thorbenlindhauer.test.util.LinearAlgebraUtil.java

public static RealMatrix diagonalMatrix(double value, int size) {
    double[] values = new double[size];
    for (int i = 0; i < size; i++) {
        values[i] = value;/* w  w w. ja v a2  s  .  c om*/
    }

    return MatrixUtils.createRealDiagonalMatrix(values);
}

From source file:com.caseystella.analytics.outlier.batch.rpca.RidgeRegression.java

public void updateCoefficients(double l2penalty) {
    if (this.X_svd == null) {
        this.X_svd = new SingularValueDecomposition(X);
    }/* w  ww .  ja va  2s .  co m*/
    RealMatrix V = this.X_svd.getV();
    double[] s = this.X_svd.getSingularValues();
    RealMatrix U = this.X_svd.getU();

    for (int i = 0; i < s.length; i++) {
        s[i] = s[i] / (s[i] * s[i] + l2penalty);
    }
    RealMatrix S = MatrixUtils.createRealDiagonalMatrix(s);

    RealMatrix Z = V.multiply(S).multiply(U.transpose());

    this.coefficients = Z.operate(this.Y);

    this.fitted = this.X.operate(this.coefficients);
    double errorVariance = 0;
    for (int i = 0; i < residuals.length; i++) {
        this.residuals[i] = this.Y[i] - this.fitted[i];
        errorVariance += this.residuals[i] * this.residuals[i];
    }
    errorVariance = errorVariance / (X.getRowDimension() - X.getColumnDimension());

    RealMatrix errorVarianceMatrix = MatrixUtils.createRealIdentityMatrix(this.Y.length)
            .scalarMultiply(errorVariance);
    RealMatrix coefficientsCovarianceMatrix = Z.multiply(errorVarianceMatrix).multiply(Z.transpose());
    this.standarderrors = getDiagonal(coefficientsCovarianceMatrix);
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
 * Build identity matrix./*from   ww  w. j a v  a2s  . c o  m*/
 * @param size - size of the matrix
 * @return identity matrix
 */
public static BlockRealMatrix buildIdentityMatrix(final int size) {
    double[] tempArr = new double[size];
    for (int i = 0; i < size; i++) {
        tempArr[i] = 1;
    }
    return new BlockRealMatrix(MatrixUtils.createRealDiagonalMatrix(tempArr).getData());
}

From source file:com.joptimizer.util.CholeskyFactorization.java

public double[][] getInverse() {

    //QInv = LTInv * LInv, but for symmetry (QInv=QInvT)
    //QInv = LInvT * LTInvT = LInvT * LInv, so
    //LInvT = LTInv, and we calculate
    //QInv = LInvT * LInv

    double[][] lTData = getLT();
    int dim = lTData.length;

    // LTInv calculation (it will be x)
    double[] diag = new double[dim];
    Arrays.fill(diag, 1.);//from  www  . j a  v  a  2  s .c  o m
    double[][] x = MatrixUtils.createRealDiagonalMatrix(diag).getData();
    for (int j = 0; j < dim; j++) {
        final double[] lTJ = lTData[j];
        final double lTJJ = lTJ[j];
        final double[] xJ = x[j];
        for (int k = 0; k < dim; ++k) {
            xJ[k] /= lTJJ;
        }
        for (int i = j + 1; i < dim; i++) {
            final double[] xI = x[i];
            final double lTJI = lTJ[i];
            for (int k = 0; k < dim; ++k) {
                xI[k] -= xJ[k] * lTJI;
            }
        }
    }

    // transposition (L is upper-triangular)
    double[][] LInvTData = new double[dim][dim];
    for (int i = 0; i < dim; i++) {
        double[] LInvTDatai = LInvTData[i];
        for (int j = i; j < dim; j++) {
            LInvTDatai[j] = x[j][i];
        }
    }

    // QInv
    // NB: LInvT is upper-triangular, so LInvT[i][j]=0 if i>j
    final double[][] QInvData = new double[dim][dim];
    for (int row = 0; row < dim; row++) {
        final double[] LInvTDataRow = LInvTData[row];
        final double[] QInvDataRow = QInvData[row];
        for (int col = row; col < dim; col++) {// symmetry of QInv
            final double[] LInvTDataCol = LInvTData[col];
            double sum = 0;
            for (int i = col; i < dim; i++) {// upper triangular
                sum += LInvTDataRow[i] * LInvTDataCol[i];
            }
            QInvDataRow[col] = sum;
            QInvData[col][row] = sum;// symmetry of QInv
        }
    }

    return QInvData;
}

From source file:fi.smaa.jsmaa.model.RelativeGaussianCriterionMeasurementTest.java

@Test
public void testRange() {
    delta.setMeanVector(new ArrayRealVector(new double[] { 1.0, 2.0, 3.0 }));
    delta.setCovarianceMatrix(MatrixUtils.createRealDiagonalMatrix(new double[] { 14.0, 10.2, 3.6 }));
    baseline.setMean(-2.0);/*  www.  j  a  v a2 s. co  m*/
    baseline.setStDev(2.5);

    assertEquals(delta.getRange().getStart() + baseline.getRange().getStart(), m.getRange().getStart(), 1e-7);
    assertEquals(delta.getRange().getEnd() + baseline.getRange().getEnd(), m.getRange().getEnd(), 1e-7);
}

From source file:com.caseystella.analytics.outlier.batch.rpca.RPCA.java

private double computeL(double mu) {
    double LPenalty = lpenalty * mu;
    SingularValueDecomposition svd = new SingularValueDecomposition(X.subtract(S));
    double[] penalizedD = softThreshold(svd.getSingularValues(), LPenalty);
    RealMatrix D_matrix = MatrixUtils.createRealDiagonalMatrix(penalizedD);
    L = svd.getU().multiply(D_matrix).multiply(svd.getVT());
    return sum(penalizedD) * LPenalty;
}

From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurementTest.java

@Test
public void testDeepCopy() {
    List<Alternative> newAlts = new ArrayList<Alternative>();
    for (Alternative a : alternatives) {
        newAlts.add(a.deepCopy());/*from  w ww . ja  va  2  s . com*/
    }
    m.setMeanVector(new ArrayRealVector(new double[] { 666, 8, 665 }));
    m.setCovarianceMatrix(MatrixUtils.createRealDiagonalMatrix(new double[] { 4, 3, 2 }));

    MultivariateGaussianCriterionMeasurement clone = m.deepCopy(newAlts);
    assertNotSame(m, clone);
    assertEquals(newAlts, clone.getAlternatives());
    assertSame(newAlts.get(0), clone.getAlternatives().get(0));
    assertEquals(m.getMeanVector(), clone.getMeanVector());
    assertNotSame(m.getMeanVector(), clone.getMeanVector());
    assertEquals(m.getCovarianceMatrix(), clone.getCovarianceMatrix());
    assertNotSame(m.getCovarianceMatrix(), clone.getCovarianceMatrix());
}

From source file:gamlss.smoothing.PB.java

/**
 * Constructs the penalty matrix./*from  w w w. j  a va2 s .co  m*/
 * @param xM - base matrix
 * @return penalty matrix
 */
private BlockRealMatrix formD(final BlockRealMatrix xM) {
    tempArr = new double[xM.getColumnDimension()];
    for (int i = 0; i < tempArr.length; i++) {
        tempArr[i] = 1.0;
    }
    if (Controls.ORDER == 0) {
        return new BlockRealMatrix(MatrixUtils.createRealDiagonalMatrix(tempArr).getData());
    } else {
        return MatrixFunctions.diff(
                new BlockRealMatrix(MatrixUtils.createRealDiagonalMatrix(tempArr).getData()), Controls.ORDER);
    }
}

From source file:org.pmad.gmm.MyEDC.java

/**
 * Gets the block diagonal matrix D of the decomposition.
 * D is a block diagonal matrix.//  ww  w .ja  v  a2 s  .c o  m
 * Real eigenvalues are on the diagonal while complex values are on
 * 2x2 blocks { {real +imaginary}, {-imaginary, real} }.
 *
 * @return the D matrix.
 *
 * @see #getRealEigenvalues()
 * @see #getImagEigenvalues()
 */
public RealMatrix getD() {

    if (cachedD == null) {
        // cache the matrix for subsequent calls
        cachedD = MatrixUtils.createRealDiagonalMatrix(realEigenvalues);

        for (int i = 0; i < imagEigenvalues.length; i++) {
            if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) > 0) {
                cachedD.setEntry(i, i + 1, imagEigenvalues[i]);
            } else if (Precision.compareTo(imagEigenvalues[i], 0.0, EPSILON) < 0) {
                cachedD.setEntry(i, i - 1, imagEigenvalues[i]);
            }
        }
    }
    return cachedD;
}