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

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

Introduction

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

Prototype

public Array2DRowRealMatrix(final double[][] d, final boolean copyArray)
        throws DimensionMismatchException, NoDataException, NullArgumentException 

Source Link

Document

Create a new RealMatrix using the input array as the underlying data array.

Usage

From source file:lanchester.MultiArena.java

public Array2DRowRealMatrix getMat() {
    int numFoes = forces.size();
    AthenaForce f1;//from   w  ww  .  ja va  2 s .  co m
    AthenaForce f2;
    Array2DRowRealMatrix mat = new Array2DRowRealMatrix(numFoes, numFoes);
    for (int i1 = 0; i1 < numFoes - 1; i1++) {
        f1 = forces.get(i1);
        for (int i2 = i1 + 1; i2 < numFoes; i2++) {
            f2 = forces.get(i2);
            if (f1.isFriend(f2)) {
                f1.setStance(AthenaConstants.ALLIED_POSTURE);
                f2.setStance(AthenaConstants.ALLIED_POSTURE);
                mat.setEntry(i1, i2, 0.);
                mat.setEntry(i2, i1, 0.);
            } else {
                //                    int oldStance1=f1.getCurrentStance();
                //                    int oldStance2=f2.getCurrentStance();
                setStances(f1, f2);
                //                    int newStance1=f1.getCurrentStance();
                //                    int newStance2=f2.getCurrentStance();
                //                    if(oldStance1!=newStance1||oldStance2!=newStance2){
                //                        System.out.println("Stance change at time = "+currentTime);
                //                        System.out.println("F1 - "+oldStance1+" to "+newStance1);
                //                        System.out.println("F2 - "+oldStance2+" to "+newStance2);
                //                    }
                //                    double x0 = f1.getForceSize();
                //                    double y0 = f2.getForceSize();
                double a1 = f2.getForceMultiplier();
                double b2 = f1.getForceMultiplier();
                if (isBattle) {
                    a1 *= AthenaConstants.battle[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.battle[stanceArray[i2][i1]][stanceArray[i1][i2]];
                } else {
                    a1 *= AthenaConstants.skirmish[stanceArray[i1][i2]][stanceArray[i2][i1]];
                    b2 *= AthenaConstants.skirmish[stanceArray[i2][i1]][stanceArray[i1][i2]];
                }

                mat.setEntry(i1, i2, -a1);
                mat.setEntry(i2, i1, -b2);
            }
        }
    }
    return mat;
}

From source file:ellipsoidFit.FitPoints.java

/**
 * Create a matrix in the algebraic form of the polynomial Ax^2 + By^2 +
 * Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz = 1.
 * //from w w w.j a  v  a  2s  . c  o  m
 * @param v
 *            the vector polynomial.
 * @return the matrix of the algebraic form of the polynomial.
 */
private RealMatrix formAlgebraicMatrix(RealVector v) {
    // a =
    // [ Ax^2 2Dxy 2Exz 2Gx ]
    // [ 2Dxy By^2 2Fyz 2Hy ]
    // [ 2Exz 2Fyz Cz^2 2Iz ]
    // [ 2Gx 2Hy 2Iz -1 ] ]
    RealMatrix a = new Array2DRowRealMatrix(4, 4);

    a.setEntry(0, 0, v.getEntry(0));
    a.setEntry(0, 1, v.getEntry(3));
    a.setEntry(0, 2, v.getEntry(4));
    a.setEntry(0, 3, v.getEntry(6));
    a.setEntry(1, 0, v.getEntry(3));
    a.setEntry(1, 1, v.getEntry(1));
    a.setEntry(1, 2, v.getEntry(5));
    a.setEntry(1, 3, v.getEntry(7));
    a.setEntry(2, 0, v.getEntry(4));
    a.setEntry(2, 1, v.getEntry(5));
    a.setEntry(2, 2, v.getEntry(2));
    a.setEntry(2, 3, v.getEntry(8));
    a.setEntry(3, 0, v.getEntry(6));
    a.setEntry(3, 1, v.getEntry(7));
    a.setEntry(3, 2, v.getEntry(8));
    a.setEntry(3, 3, -1);

    return a;
}

From source file:eagle.security.userprofile.model.eigen.UserProfileEigenModeler.java

private void computeCovarianceAndSVD(RealMatrix inputMat, int containsLowVariantCol) {

    int finalMatrixRow = 0;
    int finalMatrixCol = 0;

    LOG.info("containsLowVariantCol size: " + containsLowVariantCol);
    int colDimension = (inputMat.getColumnDimension() - containsLowVariantCol);
    try {//ww  w  .j ava2 s  .com
        finalMatrixWithoutLowVariantCmds = new Array2DRowRealMatrix(inputMat.getRowDimension(), colDimension);
    } catch (NotStrictlyPositiveException e) {
        LOG.error(String.format("Failed to build matrix [rowDimension:%s, columnDimension: %s]",
                inputMat.getRowDimension(), colDimension), e);
        throw e;
    }

    for (int i = 0; i < inputMat.getRowDimension(); i++) {
        for (int j = 0; j < inputMat.getColumnDimension(); j++) {
            if (!statistics[j].isLowVariant()) {
                finalMatrixWithoutLowVariantCmds.setEntry(finalMatrixRow, finalMatrixCol,
                        inputMat.getEntry(i, j));
                finalMatrixCol++;
            }
        }
        finalMatrixCol = 0;
        finalMatrixRow++;
    }

    Covariance cov;
    try {
        cov = new Covariance(finalMatrixWithoutLowVariantCmds.getData());
    } catch (Exception ex) {
        throw new IllegalArgumentException(String.format("Failed to create covariance from matrix [ %s x %s ]",
                finalMatrixWithoutLowVariantCmds.getRowDimension(),
                finalMatrixWithoutLowVariantCmds.getColumnDimension()), ex);
    }
    covarianceMatrix = cov.getCovarianceMatrix();
    SingularValueDecomposition svd = new SingularValueDecomposition(covarianceMatrix);
    diagonalMatrix = svd.getS();
    uMatrix = svd.getU();
    vMatrix = svd.getV();
}

From source file:com.clust4j.algo.preprocess.PCA.java

/**
 * Flip Eigenvectors' sign to enforce deterministic output
 * @param U//from   w ww .  j  a v a  2 s . c o  m
 * @param V
 * @return
 */
static EntryPair<RealMatrix, RealMatrix> eigenSignFlip(RealMatrix U, RealMatrix V) {
    // need to get column arg maxes of abs vals of U
    double[][] u = U.getData();
    double[][] v = V.getData();
    int[] max_abs_cols = MatUtils.argMax(MatUtils.abs(u), Axis.COL);

    // Get the signs of the diagonals in the rows corresponding to max_abs_cols
    int col_idx = 0;
    double val;
    double[] row;
    int[] signs = new int[U.getColumnDimension()];
    for (int row_idx : max_abs_cols) {
        row = u[row_idx];
        val = row[col_idx];
        signs[col_idx++] = val == 0 ? 0 : val < 0 ? -1 : 1;
    }

    // Multiply U by the signs... column-wise
    for (int i = 0; i < u.length; i++) {
        for (int j = 0; j < U.getColumnDimension(); j++) {
            u[i][j] *= signs[j];
        }
    }

    // Perform same op for V row-wise
    for (int j = 0; j < signs.length; j++) {
        for (int k = 0; k < V.getColumnDimension(); k++) {
            v[j][k] *= signs[j];
        }
    }

    return new EntryPair<RealMatrix, RealMatrix>(new Array2DRowRealMatrix(u, false),
            new Array2DRowRealMatrix(v, false));
}

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.
*//*from   w  w  w.  j av a 2s  .co  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:fp.overlapr.algorithmen.StressMajorization.java

@Deprecated
private static ArrayRealVector conjugateGradientsMethod(Array2DRowRealMatrix A, ArrayRealVector b,
        ArrayRealVector werte) {//w  w  w .  j a  va  2s.  com

    Array2DRowRealMatrix preJacobi = new Array2DRowRealMatrix(A.getRowDimension(), A.getColumnDimension());

    // Predconditioner berechnen
    preJacobi.walkInRowOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            if (row == column) {
                return 1 / A.getEntry(row, column);
            } else {
                return 0.0;
            }
        }
    });

    // x_k beliebig whlen
    ArrayRealVector x_k = new ArrayRealVector(werte);

    // r_k berechnen
    ArrayRealVector r_k = b.subtract(A.operate(x_k));

    // h_k berechnen
    ArrayRealVector h_k = (ArrayRealVector) preJacobi.operate(r_k);

    // d_k = r_k
    ArrayRealVector d_k = h_k;

    // x_k+1 und r_k+1 und d_k+1, sowie alpha und beta und z erzeugen
    ArrayRealVector x_k1;
    ArrayRealVector r_k1;
    ArrayRealVector d_k1;
    ArrayRealVector h_k1;
    double alpha;
    double beta;
    ArrayRealVector z;

    do {
        // Speichere Matrix-Vektor-Produkt, um es nur einmal auszurechnen
        z = (ArrayRealVector) A.operate(d_k);

        // Finde von x_k in Richtung d_k den Ort x_k1 des Minimums der
        // Funktion E
        // und aktualisere den Gradienten bzw. das Residuum
        alpha = r_k.dotProduct(h_k) / d_k.dotProduct(z);
        x_k1 = x_k.add(d_k.mapMultiply(alpha));
        r_k1 = r_k.subtract(z.mapMultiply(alpha));
        h_k1 = (ArrayRealVector) preJacobi.operate(r_k1);

        // Korrigiere die Suchrichtung d_k1
        beta = r_k1.dotProduct(h_k1) / r_k.dotProduct(h_k);
        d_k1 = h_k1.add(d_k.mapMultiply(beta));

        // Werte "eins" weitersetzen
        x_k = x_k1;
        r_k = r_k1;
        d_k = d_k1;
        h_k = h_k1;

    } while (r_k1.getNorm() > TOL);

    return x_k1;
}

From source file:hivemall.anomaly.SingularSpectrumTransform.java

/**
 * Implicit Krylov Approximation (IKA) based naive scoring.
 *
 * Number of iterations for the Power method and QR method is fixed to 1 for efficiency. This
 * may cause failure (i.e. meaningless scores) depending on datasets and initial values.
 *
 *///w  w  w  .  j  av  a2s .  c  o m
private double computeScoreIKA(@Nonnull final RealMatrix H, @Nonnull final RealMatrix G) {
    // assuming n = m = window, and keep track the left singular vector as `q`
    MatrixUtils.power1(G, q, 1, q, new double[window]);

    RealMatrix T = new Array2DRowRealMatrix(k, k);
    MatrixUtils.lanczosTridiagonalization(H.multiply(H.transpose()), q, T);

    double[] eigvals = new double[k];
    RealMatrix eigvecs = new Array2DRowRealMatrix(k, k);
    MatrixUtils.tridiagonalEigen(T, 1, eigvals, eigvecs);

    // tridiagonalEigen() returns unordered eigenvalues,
    // so the top-r eigenvectors should be picked carefully
    TreeMap<Double, Integer> map = new TreeMap<Double, Integer>(Collections.reverseOrder());
    for (int i = 0; i < k; i++) {
        map.put(eigvals[i], i);
    }
    Iterator<Integer> indices = map.values().iterator();

    double s = 0.d;
    for (int i = 0; i < r; i++) {
        if (!indices.hasNext()) {
            throw new IllegalStateException("Should not happen");
        }
        double v = eigvecs.getEntry(0, indices.next().intValue());
        s += v * v;
    }
    return 1.d - Math.sqrt(s);
}

From source file:edu.oregonstate.eecs.mcplan.util.Csv.java

public static RealMatrix readMatrix(final File f) {
    try {/* www  .j  av a2s.  c  o m*/
        final BufferedReader r = new BufferedReader(new FileReader(f));
        String line;
        final ArrayList<String[]> rows = new ArrayList<String[]>();
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            rows.add(line.split(","));
        }
        final Array2DRowRealMatrix M = new Array2DRowRealMatrix(rows.size(), rows.get(0).length);
        for (int i = 0; i < rows.size(); ++i) {
            final String[] row = rows.get(i);
            for (int j = 0; j < row.length; ++j) {
                M.setEntry(i, j, Double.parseDouble(row[j]));
            }
        }

        return M;
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:edu.stanford.cfuller.colocalization3d.correction.PositionCorrector.java

/**
* Creates a correction from a set of objects whose positions should be the same in each channel.
* 
* @param imageObjects                  A Vector containing all the ImageObjects to be used for the correction
*                                      or in the order it appears in a multiwavelength image file.
* @return                              A Correction object that can be used to correct the positions of other objects based upon the standards provided.
*//*from w w  w . j a v  a 2  s .  c  o m*/
public Correction getCorrection(java.util.List<ImageObject> imageObjects) {

    int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM);

    int channelToCorrect = this.parameters.getIntValueForKey(CORR_CH_PARAM);

    if (!this.parameters.hasKeyAndTrue(DET_CORR_PARAM)) {
        try {
            return Correction.readFromDisk(FileUtils.getCorrectionFilename(this.parameters));
        } catch (java.io.IOException e) {

            java.util.logging.Logger
                    .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME)
                    .severe("Exception encountered while reading correction from disk: ");
            e.printStackTrace();

        } catch (ClassNotFoundException e) {

            java.util.logging.Logger
                    .getLogger(edu.stanford.cfuller.colocalization3d.Colocalization3DMain.LOGGER_NAME)
                    .severe("Exception encountered while reading correction from disk: ");
            e.printStackTrace();

        }

        return null;
    }

    int numberOfPointsToFit = this.parameters.getIntValueForKey(NUM_POINT_PARAM);

    RealMatrix correctionX = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters);
    RealMatrix correctionY = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters);
    RealMatrix correctionZ = new Array2DRowRealMatrix(imageObjects.size(), numberOfCorrectionParameters);

    RealVector distanceCutoffs = new ArrayRealVector(imageObjects.size(), 0.0);

    RealVector ones = new ArrayRealVector(numberOfPointsToFit, 1.0);

    RealVector distancesToObjects = new ArrayRealVector(imageObjects.size(), 0.0);

    RealMatrix allCorrectionParametersMatrix = new Array2DRowRealMatrix(numberOfPointsToFit,
            numberOfCorrectionParameters);

    for (int i = 0; i < imageObjects.size(); i++) {

        RealVector ithPos = imageObjects.get(i).getPositionForChannel(referenceChannel);

        for (int j = 0; j < imageObjects.size(); j++) {

            double d = imageObjects.get(j).getPositionForChannel(referenceChannel).subtract(ithPos).getNorm();

            distancesToObjects.setEntry(j, d);

        }

        //the sorting becomes a bottleneck once the number of points gets large

        //reverse comparator so we can use the priority queue and get the max element at the head

        Comparator<Double> cdReverse = new Comparator<Double>() {

            public int compare(Double o1, Double o2) {

                if (o1.equals(o2))
                    return 0;
                if (o1 > o2)
                    return -1;
                return 1;
            }

        };

        PriorityQueue<Double> pq = new PriorityQueue<Double>(numberOfPointsToFit + 2, cdReverse);

        double maxElement = Double.MAX_VALUE;

        for (int p = 0; p < numberOfPointsToFit + 1; p++) {

            pq.add(distancesToObjects.getEntry(p));

        }

        maxElement = pq.peek();

        for (int p = numberOfPointsToFit + 1; p < distancesToObjects.getDimension(); p++) {

            double value = distancesToObjects.getEntry(p);

            if (value < maxElement) {

                pq.poll();

                pq.add(value);

                maxElement = pq.peek();

            }

        }

        double firstExclude = pq.poll();
        double lastDist = pq.poll();

        double distanceCutoff = (lastDist + firstExclude) / 2.0;

        distanceCutoffs.setEntry(i, distanceCutoff);

        RealVector xPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0);
        RealVector yPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0);
        RealVector zPositionsToFit = new ArrayRealVector(numberOfPointsToFit, 0.0);

        RealMatrix differencesToFit = new Array2DRowRealMatrix(numberOfPointsToFit,
                imageObjects.get(0).getPositionForChannel(referenceChannel).getDimension());

        int toFitCounter = 0;

        for (int j = 0; j < imageObjects.size(); j++) {
            if (distancesToObjects.getEntry(j) < distanceCutoff) {
                xPositionsToFit.setEntry(toFitCounter,
                        imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(0));
                yPositionsToFit.setEntry(toFitCounter,
                        imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(1));
                zPositionsToFit.setEntry(toFitCounter,
                        imageObjects.get(j).getPositionForChannel(referenceChannel).getEntry(2));

                differencesToFit.setRowVector(toFitCounter, imageObjects.get(j)
                        .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect));

                toFitCounter++;
            }
        }

        RealVector x = xPositionsToFit.mapSubtractToSelf(ithPos.getEntry(0));
        RealVector y = yPositionsToFit.mapSubtractToSelf(ithPos.getEntry(1));

        allCorrectionParametersMatrix.setColumnVector(0, ones);
        allCorrectionParametersMatrix.setColumnVector(1, x);
        allCorrectionParametersMatrix.setColumnVector(2, y);
        allCorrectionParametersMatrix.setColumnVector(3, x.map(new Power(2)));
        allCorrectionParametersMatrix.setColumnVector(4, y.map(new Power(2)));
        allCorrectionParametersMatrix.setColumnVector(5, x.ebeMultiply(y));

        DecompositionSolver solver = (new QRDecomposition(allCorrectionParametersMatrix)).getSolver();

        RealVector cX = solver.solve(differencesToFit.getColumnVector(0));
        RealVector cY = solver.solve(differencesToFit.getColumnVector(1));
        RealVector cZ = solver.solve(differencesToFit.getColumnVector(2));

        correctionX.setRowVector(i, cX);
        correctionY.setRowVector(i, cY);
        correctionZ.setRowVector(i, cZ);

    }

    Correction c = new Correction(correctionX, correctionY, correctionZ, distanceCutoffs, imageObjects,
            referenceChannel, channelToCorrect);

    return c;

}

From source file:com.clust4j.algo.preprocess.impute.NearestNeighborImputation.java

@Override
public double[][] transform(final double[][] dat) {
    checkMat(dat);/*from ww w  . j  av  a  2s. c o  m*/

    final LogTimer timer = new LogTimer();
    final int m = dat.length, n = dat[0].length, nc;
    final double[][] copy = MatUtils.copy(dat);

    final ArrayList<Integer> incompleteIndices = new ArrayList<>();
    final ArrayList<double[]> completeRecords = new ArrayList<>();

    // Get complete/non-complete matrices
    double[] row;
    info("separating complete from incomplete records");
    for (int i = 0; i < m; i++) {
        row = copy[i];
        if (VecUtils.containsNaN(row))
            incompleteIndices.add(i);
        else
            completeRecords.add(row);
    }

    // Check k
    nc = completeRecords.size();
    String error;
    info(nc + " complete record" + (nc != 1 ? "s" : "") + " extracted from input matrix");
    if (nc == 0) {
        error(new NaNException("no complete records in input matrix"));
    } else if (k > nc) {
        warn("number of complete records (" + nc + ") is less than k (" + k + "); setting k to " + nc);
        k = nc;
    }

    // Build matrix
    final double[][] complete = MatUtils.fromList(completeRecords);
    final boolean mn = cent.equals(CentralTendencyMethod.MEAN);

    // Impute!
    info("imputing k nearest; method=" + cent);
    int replacements;
    int[] nearest;
    NearestNeighbors nbrs;
    ArrayList<Integer> impute_indices;
    double[][] completeCols, nearestMat;
    double[] incomplete, completeRecord, col;
    for (Integer record : incompleteIndices) {
        incomplete = copy[record];
        impute_indices = new ArrayList<>(); // Hold the indices of columns which need to be imputed

        // Identify columns that need imputing
        for (int j = 0; j < n; j++)
            if (Double.isNaN(incomplete[j]))
                impute_indices.add(j);

        // Get complete cols
        replacements = impute_indices.size();
        if (replacements == n) {
            error = "record " + record + " is completely NaN";
            throw new NaNException(error);
        }

        completeRecord = exclude(incomplete, impute_indices);
        completeCols = excludeCols(complete, impute_indices);

        nbrs = new NearestNeighborsParameters(k).setVerbose(false).setSeed(getSeed()).setMetric(this.sep)
                .fitNewModel(new Array2DRowRealMatrix(completeCols, false)); // fits

        nearest = nbrs.getNeighbors(new Array2DRowRealMatrix(new double[][] { completeRecord }, false))
                .getIndices()[0];

        nearestMat = MatUtils.getRows(complete, nearest);

        // Perform the imputation
        for (Integer imputationIdx : impute_indices) {
            col = MatUtils.getColumn(nearestMat, imputationIdx);
            incomplete[imputationIdx] = mn ? VecUtils.mean(col) : VecUtils.median(col);
        }

        info("record number " + record + " imputed in " + replacements + " position"
                + (replacements != 1 ? "s" : ""));
    }

    sayBye(timer);
    return copy;
}