Example usage for org.apache.commons.math3.linear QRDecomposition QRDecomposition

List of usage examples for org.apache.commons.math3.linear QRDecomposition QRDecomposition

Introduction

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

Prototype

public QRDecomposition(RealMatrix matrix) 

Source Link

Document

Calculates the QR-decomposition of the given matrix.

Usage

From source file:com.opengamma.strata.math.impl.linearalgebra.QRDecompositionCommons.java

@Override
public QRDecompositionResult apply(DoubleMatrix x) {
    ArgChecker.notNull(x, "x");
    RealMatrix temp = CommonsMathWrapper.wrap(x);
    QRDecomposition qr = new QRDecomposition(temp);
    return new QRDecompositionCommonsResult(qr);
}

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

public LinearModel(RealMatrix designMatrix, RealMatrix contrastValues) {
    this.designMatrix = designMatrix;
    this.contrastValues = contrastValues;
    qrDecomposition = new QRDecomposition(designMatrix);
    independentColumnIndices = IntStream.range(0, designMatrix.getColumnDimension()).toArray();
    RealMatrix matrixCrossproduct = computeMatrixCrossproduct(designMatrix, independentColumnIndices);
    matrixCrossproductInverse = new LUDecomposition(matrixCrossproduct).getSolver().getInverse();
}

From source file:com.joptimizer.algebra.QRSparseFactorizationTest.java

public void testDecompose() throws Exception {
    log.debug("testDecompose");
    final double[][] A = new double[][] { { 1, 0, 0, 2 }, { 0, 0, 2, 0 }, { 2, 3, 0, 0 }, { 0, 0, 4, 4 } };

    double[][] EQ = { { 0.447214, -0.894427, 0., 0. }, { 0., 0., 0.447214, -0.894427 },
            { 0.894427, 0.447214, 0., 0. }, { 0., 0., 0.894427, 0.447214 } };
    double[][] ER = { { 2.23607, 2.68328, 0., 0.894427 }, { 0., 1.34164, 0., -1.78885 },
            { 0., 0., 4.47214, 3.57771 }, { 0., 0., 0., 1.78885 } };

    QRDecomposition dFact = new QRDecomposition(new Array2DRowRealMatrix(A));
    RealMatrix Q = dFact.getQ();//w w  w .j  a  v a  2s .  c om
    RealMatrix R = dFact.getR();
    RealMatrix H = dFact.getH();
    log.debug("Q: " + ArrayUtils.toString(Q.getData()));
    log.debug("R: " + ArrayUtils.toString(R.getData()));
    //log.debug("H: " + ArrayUtils.toString(H.getData()));

    SparseDoubleMatrix2D S = new SparseDoubleMatrix2D(A);
    QRSparseFactorization qr = new QRSparseFactorization(S);
    qr.factorize();
    log.debug("R: " + ArrayUtils.toString(qr.getR().toArray()));
    for (int i = 0; i < R.getRowDimension(); i++) {
        for (int j = 0; j < R.getColumnDimension(); j++) {
            assertEquals(ER[i][j], qr.getR().getQuick(i, j), 1.e-5);
        }
    }
    assertTrue(qr.hasFullRank());
}

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

public void testQRdecomposition() throws Exception {
    log.debug("testQRdecomposition");
    double[][] A = new double[][] { { 1, 0, 0 }, { 2, 2, 0 }, { 3, 3, 3 } };
    QRDecomposition qrFact = new QRDecomposition(MatrixUtils.createRealMatrix(A));
    qrFact.getQ();//from  ww w .ja va 2  s .  co m
}

From source file:edu.cudenver.bios.matrix.OrthogonalPolynomials.java

/**
 * Computes orthogonal polynomial contrasts for the specified data values.  Currently only
 * supports fitting (not prediction contrasts).  
 * /*from   ww  w .ja  v  a  2 s. c  o m*/
 *    @param x the points at which the polynomials will be evaluated
 * @param maxDegree contrasts will be computed for degrees 1 to maxDegree
 * @return matrix containing 0th,1st, 2nd,...maxDegree-th degree contrasts in each column
 * @throws IllegalArgumentException
 */
public static RealMatrix orthogonalPolynomialCoefficients(double[] x, int maxDegree)
        throws IllegalArgumentException {
    if (x == null)
        throw new IllegalArgumentException("no data specified");
    if (maxDegree < 1)
        throw new IllegalArgumentException("max polynomial degree must be greater than 1");
    // count number of unique values
    HashSet<Double> s = new HashSet<Double>();
    for (double i : x)
        s.add(i);
    int uniqueCount = s.size();
    if (maxDegree >= uniqueCount)
        throw new IllegalArgumentException(
                "max polynomial degree must be less than the number of unique points");

    // center the data
    double xBar = StatUtils.mean(x);
    double[] xCentered = new double[x.length];
    for (int i = 0; i < x.length; i++)
        xCentered[i] = x[i] - xBar;
    // compute an "outer product" of the centered x vector and a vector 
    // containing the sequence 0 to maxDegree-1, but raise the x values
    // to the power in the sequence array
    double[][] xOuter = new double[x.length][maxDegree + 1];
    int row = 0;
    for (double xValue : xCentered) {
        for (int col = 0; col <= maxDegree; col++) {
            xOuter[row][col] = Math.pow(xValue, col);
        }
        row++;
    }
    // do some mysterious QR decomposition stuff.  See Emerson (1968)
    RealMatrix outerVector = new Array2DRowRealMatrix(xOuter);
    QRDecomposition qrDecomp = new QRDecomposition(outerVector);

    RealMatrix z = MatrixUtils.getDiagonalMatrix(qrDecomp.getR());
    RealMatrix raw = qrDecomp.getQ().multiply(z);

    // column sum of squared elements in raw
    double[] normalizingConstants = new double[raw.getColumnDimension()];
    for (int col = 0; col < raw.getColumnDimension(); col++) {
        normalizingConstants[col] = 0;
        for (row = 0; row < raw.getRowDimension(); row++) {
            double value = raw.getEntry(row, col);
            normalizingConstants[col] += value * value;
        }
    }

    // now normalize the raw values
    for (int col = 0; col < raw.getColumnDimension(); col++) {
        double normalConstantSqrt = Math.sqrt(normalizingConstants[col]);
        for (row = 0; row < raw.getRowDimension(); row++) {
            raw.setEntry(row, col, raw.getEntry(row, col) / normalConstantSqrt);
        }
    }

    return raw;
}

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

/**
 * Function to solve a given system of equations.
 * // www.j  a va  2s.c  o m
 * @param in1
 * @param in2
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock computeSolve(MatrixObject in1, MatrixObject in2) throws DMLRuntimeException {
    Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in1);
    Array2DRowRealMatrix vectorInput = DataConverter.convertToArray2DRowRealMatrix(in2);

    /*LUDecompositionImpl ludecompose = new LUDecompositionImpl(matrixInput);
    DecompositionSolver lusolver = ludecompose.getSolver();
    RealMatrix solutionMatrix = lusolver.solve(vectorInput);*/

    // Setup a solver based on QR Decomposition
    QRDecomposition qrdecompose = new QRDecomposition(matrixInput);
    DecompositionSolver solver = qrdecompose.getSolver();
    // Invoke solve
    RealMatrix solutionMatrix = solver.solve(vectorInput);

    MatrixBlock solution = DataConverter.convertToMatrixBlock(solutionMatrix.getData());

    return solution;
}

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

/**
 * Function to perform QR decomposition on a given matrix.
 * /*from   w w w  .j a v  a2s .com*/
 * @param in
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock[] computeQR(MatrixObject in) throws DMLRuntimeException {
    Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in);

    // Perform QR decomposition
    QRDecomposition qrdecompose = new QRDecomposition(matrixInput);
    RealMatrix H = qrdecompose.getH();
    RealMatrix R = qrdecompose.getR();

    // Read the results into native format
    MatrixBlock mbH = DataConverter.convertToMatrixBlock(H.getData());
    MatrixBlock mbR = DataConverter.convertToMatrixBlock(R.getData());

    return new MatrixBlock[] { mbH, mbR };
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.BisquareLinearFit.java

/**
* Calculates the leverages of data points for least squares fitting (assuming equal variances).
* 
* @param indVarValues The values of the independent variable used for the fitting.
* @return a RealVector containing a leverage value for each independent variable value.
*//* w  w w.  ja  v a  2s . c  o m*/
protected RealVector calculateLeverages(RealVector indVarValues) {

    RealMatrix indVarMatrix = null;

    if (this.noIntercept) {
        indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 1);
    } else {
        indVarMatrix = new Array2DRowRealMatrix(indVarValues.getDimension(), 2);
    }

    indVarMatrix.setColumnVector(0, indVarValues);

    if (!this.noIntercept) {
        indVarMatrix.setColumnVector(1, indVarValues.mapMultiply(0).mapAdd(1));
    }

    RealVector leverages = new ArrayRealVector(indVarValues.getDimension());

    QRDecomposition xQR = new QRDecomposition(indVarMatrix);

    RealMatrix xR = xQR.getR();

    int smallerDim = xR.getRowDimension() < xR.getColumnDimension() ? xR.getRowDimension()
            : xR.getColumnDimension();

    RealMatrix xRSq = xR.getSubMatrix(0, smallerDim - 1, 0, smallerDim - 1);

    QRDecomposition xRQR = new QRDecomposition(xRSq);

    RealMatrix xRInv = xRQR.getSolver().getInverse();

    RealMatrix xxRInv = indVarMatrix.multiply(xRInv);

    for (int i = 0; i < indVarValues.getDimension(); i++) {
        double sum = 0;
        for (int j = 0; j < xxRInv.getColumnDimension(); j++) {
            sum += Math.pow(xxRInv.getEntry(i, j), 2);
        }
        leverages.setEntry(i, sum);
    }

    return leverages;

}

From source file:gamlss.utilities.WLSMultipleLinearRegression.java

/**
* {@inheritDoc}/*from  w  w  w.ja  va 2 s .  c om*/
* <p>This implementation computes and caches the QR decomposition of the X matrix
* once it is successfully loaded.</p>
*/
protected void newXSampleData(double[][] x, ArrayRealVector w) {
    if (x == null) {
        throw new NullArgumentException();
    }
    if (x.length == 0) {
        throw new NoDataException();
    }
    if (this.isNoIntercept()) {
        this.xMatrix = new Array2DRowRealMatrix(x, true);
    } else { // Augment design matrix with initial unitary column
        final int nVars = x[0].length;
        final double[][] xAug = new double[x.length][nVars + 1];
        for (int i = 0; i < x.length; i++) {
            if (x[i].length != nVars) {
                throw new DimensionMismatchException(x[i].length, nVars);
            }
            xAug[i][0] = w.getEntry(i);
            System.arraycopy(x[i], 0, xAug[i], 1, nVars);
        }
        this.xMatrix = new Array2DRowRealMatrix(xAug, false);
    }
    this.qr = new QRDecomposition(getX());
}

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

/**
 * Function to compute matrix inverse via matrix decomposition.
 * //from   ww w. j  a  v  a  2  s .c o m
 * @param in
 * @return
 * @throws DMLRuntimeException
 */
private static MatrixBlock computeMatrixInverse(Array2DRowRealMatrix in) throws DMLRuntimeException {

    if (!in.isSquare())
        throw new DMLRuntimeException("Input to inv() must be square matrix -- given: a " + in.getRowDimension()
                + "x" + in.getColumnDimension() + " matrix.");

    QRDecomposition qrdecompose = new QRDecomposition(in);
    DecompositionSolver solver = qrdecompose.getSolver();
    RealMatrix inverseMatrix = solver.getInverse();

    MatrixBlock inverse = DataConverter.convertToMatrixBlock(inverseMatrix.getData());

    return inverse;
}