Example usage for org.apache.commons.math3.linear RealMatrix operate

List of usage examples for org.apache.commons.math3.linear RealMatrix operate

Introduction

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

Prototype

RealVector operate(RealVector v) throws DimensionMismatchException;

Source Link

Document

Returns the result of multiplying this by the vector v .

Usage

From source file:edu.oregonstate.eecs.mcplan.ml.KulisLowRankKernelLearner.java

/**
 * @param args//from  w  w w.  j  a va 2  s .  c  o m
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int d = 2;
    final double u = 5.0;
    final double ell = 7.0;
    final double gamma = 1.0;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final RealMatrix A0 = MatrixUtils.createRealIdentityMatrix(d);

    for (final int w : new int[] { 0, 5 }) {
        for (final int h : new int[] { 0, 5 }) {
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    X.add(new ArrayRealVector(new double[] { x + w, y + h }));
                }
            }
        }
    }

    final ArrayList<int[]> S = new ArrayList<int[]>();
    S.add(new int[] { 4, 31 }); // Must link diagonally
    final ArrayList<int[]> D = new ArrayList<int[]>();
    D.add(new int[] { 4, 13 });
    D.add(new int[] { 22, 31 });
    D.add(new int[] { 13, 22 }); // Cannot link vertically

    final KulisLowRankKernelLearner itml = new KulisLowRankKernelLearner(X, S, D, u, ell, A0, gamma, rng);
    itml.run();

    final RealMatrix A = itml.A();

    System.out.println(A0.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }

    System.out.println(A.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }

    //      int i = 0;
    //      for( final int w : new int[] { 0, 5 } ) {
    //         for( final int h : new int[] { 0, 5 } ) {
    //            for( int x = -1; x <= 1; ++x ) {
    //               for( int y = -1; y <= 1; ++y ) {
    //                  System.out.println( itml.A().operate( X.get( i++ ) ) );
    //               }
    //            }
    //         }
    //      }
}

From source file:net.liuxuan.temp.filterTest.java

public static void main(String[] args) {
    double constantVoltage = 10d;
    double measurementNoise = 0.1d;
    double processNoise = 1e-5d;

    // A = [ 1 ]/*  w w w.  j a  va  2s.c  om*/
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // B = null
    RealMatrix B = null;
    // H = [ 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d });
    // x = [ 10 ]
    RealVector x = new ArrayRealVector(new double[] { constantVoltage });
    // Q = [ 1e-5 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { processNoise });
    // P = [ 1 ]
    RealMatrix P0 = new Array2DRowRealMatrix(new double[] { 1d });
    // R = [ 0.1 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { measurementNoise });

    ProcessModel pm = new DefaultProcessModel(A, B, Q, x, P0);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    KalmanFilter filter = new KalmanFilter(pm, mm);

    // process and measurement noise vectors
    RealVector pNoise = new ArrayRealVector(1);
    RealVector mNoise = new ArrayRealVector(1);

    RandomGenerator rand = new JDKRandomGenerator();
    // iterate 60 steps
    for (int i = 0; i < 60; i++) {
        filter.predict();

        // simulate the process
        //            pNoise.setEntry(0, processNoise * rand.nextGaussian());
        pNoise.setEntry(0, Math.sin(Math.PI * 2 * i / 6));
        //            System.out.println("============");
        //            System.out.println(Math.sin(Math.PI*2*i/6));

        // x = A * x + p_noise
        x = A.operate(x).add(pNoise);
        // simulate the measurement
        //            mNoise.setEntry(0, measurementNoise * rand.nextGaussian());
        mNoise.setEntry(0, 0);

        // z = H * x + m_noise
        RealVector z = H.operate(x).add(mNoise);
        filter.correct(z);

        double voltage = filter.getStateEstimation()[0];
        System.out.println(voltage);

        // state estimate shouldn't be larger than the measurement noise
        double diff = Math.abs(x.getEntry(0) - filter.getStateEstimation()[0]);
        System.out.println("diff = " + diff);

    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.InformationTheoreticMetricLearner.java

/**
 * @param args//from w  w  w  .  j  a va  2s. c o  m
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int d = 2;
    final double u = 5.0;
    final double ell = 7.0;
    final double gamma = 1.0;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final RealMatrix A0 = MatrixUtils.createRealIdentityMatrix(d);

    for (final int w : new int[] { 0, 5 }) {
        for (final int h : new int[] { 0, 50 }) {
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    X.add(new ArrayRealVector(new double[] { x + w, y + h }));
                }
            }
        }
    }

    final ArrayList<int[]> S = new ArrayList<int[]>();
    S.add(new int[] { 4, 12 }); // Must link diagonally
    S.add(new int[] { 21, 31 });
    final ArrayList<double[]> Sd = new ArrayList<double[]>();
    for (final int[] s : S) {
        final double[] a = X.get(s[0]).subtract(X.get(s[1])).toArray();
        Sd.add(a);
    }

    final ArrayList<int[]> D = new ArrayList<int[]>();
    D.add(new int[] { 5, 23 });
    D.add(new int[] { 13, 32 }); // Cannot link vertically
    final ArrayList<double[]> Dd = new ArrayList<double[]>();
    for (final int[] dd : D) {
        final double[] a = X.get(dd[0]).subtract(X.get(dd[1])).toArray();
        Dd.add(a);
    }

    final InformationTheoreticMetricLearner itml = new InformationTheoreticMetricLearner(Sd, Dd, u, ell, A0,
            gamma, rng);
    itml.run();

    final RealMatrix A = itml.A();

    System.out.println(A0.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }

    System.out.println(A.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }

    //      int i = 0;
    //      for( final int w : new int[] { 0, 5 } ) {
    //         for( final int h : new int[] { 0, 5 } ) {
    //            for( int x = -1; x <= 1; ++x ) {
    //               for( int y = -1; y <= 1; ++y ) {
    //                  System.out.println( itml.A().operate( X.get( i++ ) ) );
    //               }
    //            }
    //         }
    //      }
}

From source file:hulo.localization.utils.ArrayUtils.java

public static double[] multiply(double[][] X1, double[] x2) {
    RealMatrix M1 = MatrixUtils.createRealMatrix(X1);
    return M1.operate(x2);
}

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  www  . ja v  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.factor.CanonicalGaussianFactor.java

public static CanonicalGaussianFactor fromMomentForm(Scope scope, RealVector meanVector,
        RealMatrix covarianceMatrix) {/*from w ww  . java  2 s. c o m*/

    // TODO: perform cardinality checks etc.

    MathUtil mathUtil = new MathUtil(covarianceMatrix);
    RealMatrix precisionMatrix = mathUtil.invert();
    RealVector scaledMeanVector = precisionMatrix.operate(meanVector);
    int dimension = meanVector.getDimension();
    double normalizationConstant = -(0.5d * scaledMeanVector.dotProduct(meanVector)) - (Math
            .log(Math.pow(2.0d * Math.PI, (double) dimension / 2.0d) * Math.sqrt(mathUtil.determinant())));

    return new CanonicalGaussianFactor(scope, precisionMatrix, scaledMeanVector, normalizationConstant);
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Find the first singular vector/value of a matrix A based on the Power method.
 *
 * @see http/*from w  w  w  . j  a va 2s  .  c om*/
 *      ://www.cs.yale.edu/homes/el327/datamining2013aFiles/07_singular_value_decomposition.pdf
 * @param A target matrix
 * @param x0 initial vector
 * @param nIter number of iterations for the Power method
 * @param u 1st left singular vector
 * @param v 1st right singular vector
 * @return 1st singular value
 */
public static double power1(@Nonnull final RealMatrix A, @Nonnull final double[] x0, final int nIter,
        @Nonnull final double[] u, @Nonnull final double[] v) {
    Preconditions.checkArgument(A.getColumnDimension() == x0.length,
            "Column size of A and length of x should be same");
    Preconditions.checkArgument(A.getRowDimension() == u.length,
            "Row size of A and length of u should be same");
    Preconditions.checkArgument(x0.length == v.length, "Length of x and u should be same");
    Preconditions.checkArgument(nIter >= 1, "Invalid number of iterations: " + nIter);

    RealMatrix AtA = A.transpose().multiply(A);

    RealVector x = new ArrayRealVector(x0);
    for (int i = 0; i < nIter; i++) {
        x = AtA.operate(x);
    }

    double xNorm = x.getNorm();
    for (int i = 0, n = v.length; i < n; i++) {
        v[i] = x.getEntry(i) / xNorm;
    }

    RealVector Av = new ArrayRealVector(A.operate(v));
    double s = Av.getNorm();

    for (int i = 0, n = u.length; i < n; i++) {
        u[i] = Av.getEntry(i) / s;
    }

    return s;
}

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);
    }//from  w w w. j a va 2  s.  c  o 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:com.joptimizer.solvers.BasicKKTSolver.java

/**
 * Returns the two vectors v and w.//  w w w  .j ava 2s . com
 */
@Override
public double[][] solve() throws Exception {

    RealVector v = null;// dim equals cols of A
    RealVector w = null;// dim equals rank of A

    if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "H: " + ArrayUtils.toString(H.getData()));
        Log.d(MainActivity.JOPTIMIZER_LOGTAG, "g: " + ArrayUtils.toString(g.toArray()));
    }
    RealMatrix HInv;
    try {
        HInv = Utils.squareMatrixInverse(H);
    } catch (SingularMatrixException e) {
        HInv = null;
    }

    if (HInv != null) {
        // Solving KKT system via elimination
        if (A != null) {
            if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) {
                Log.d(MainActivity.JOPTIMIZER_LOGTAG, "A: " + ArrayUtils.toString(A.getData()));
                if (h != null) {
                    Log.d(MainActivity.JOPTIMIZER_LOGTAG, "h: " + ArrayUtils.toString(h.toArray()));
                }
            }
            RealMatrix AHInv = A.multiply(HInv);
            RealMatrix MenoS = AHInv.multiply(AT);
            RealMatrix MenoSInv = Utils.squareMatrixInverse(MenoS);
            if (h == null || Double.compare(h.getNorm(), 0.) == 0) {
                w = MenoSInv.operate(AHInv.operate(g)).mapMultiply(-1.);
            } else {
                w = MenoSInv.operate(h.subtract(AHInv.operate(g)));
            }
            v = HInv.operate(g.add(AT.operate(w)).mapMultiply(-1.));
        } else {
            w = null;
            v = HInv.operate(g).mapMultiply(-1.);
        }
    } else {
        // Solving the full KKT system
        if (A != null) {
            KKTSolver kktSolver = new BasicKKTSolver();
            kktSolver.setCheckKKTSolutionAccuracy(false);
            double[][] fullSol = this.solveFullKKT(new BasicKKTSolver());
            v = new ArrayRealVector(fullSol[0]);
            w = new ArrayRealVector(fullSol[1]);
        } else {
            //@TODO: try with rescaled H
            throw new Exception("KKT solution failed");
        }
    }

    // solution checking
    if (this.checkKKTSolutionAccuracy && !this.checkKKTSolutionAccuracy(v, w)) {
        Log.e(MainActivity.JOPTIMIZER_LOGTAG, "KKT solution failed");
        throw new Exception("KKT solution failed");
    }

    double[][] ret = new double[2][];
    ret[0] = v.toArray();
    ret[1] = (w != null) ? w.toArray() : null;
    return ret;
}

From source file:com.datumbox.framework.machinelearning.regression.MatrixLinearRegression.java

@Override
protected void predictDataset(Dataset newData) {
    //read model params
    ModelParameters modelParameters = knowledgeBase.getModelParameters();

    int d = modelParameters.getD();

    Map<Object, Double> thitas = modelParameters.getThitas();
    Map<Object, Integer> featureIds = modelParameters.getFeatureIds();

    RealVector coefficients = new ArrayRealVector(d);
    for (Map.Entry<Object, Double> entry : thitas.entrySet()) {
        Integer featureId = featureIds.get(entry.getKey());
        coefficients.setEntry(featureId, entry.getValue());
    }/*ww  w  . ja  va2  s. co m*/

    MatrixDataset matrixDataset = MatrixDataset.parseDataset(newData, featureIds);

    RealMatrix X = matrixDataset.getX();

    RealVector Y = X.operate(coefficients);
    for (Record r : newData) {
        r.setYPredicted(Y.getEntry(r.getId()));
    }

    matrixDataset = null;
}