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

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

Introduction

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

Prototype

double[][] getData();

Source Link

Document

Returns matrix entries as a two-dimensional array.

Usage

From source file:org.wso2.extension.siddhi.execution.var.models.parametric.ParametricVaRCalculator.java

/**
 * @return the var of the portfolio Calculate var for the given portfolio using updated covariances and means
 *///from  ww w .j a  va 2 s .co  m
@Override
public Double processData(Portfolio portfolio, Event event) {
    Asset asset = getAssetPool().get(event.getSymbol());

    if (asset.getNumberOfReturnValues() > 1) {

        RealMatrix varCovarMatrix = new Array2DRowRealMatrix(getVarCovarMatrix(portfolio));
        RealMatrix weightageMatrix = new Array2DRowRealMatrix(getWeightageMatrix(portfolio));
        RealMatrix meanMatrix = new Array2DRowRealMatrix(getMeanMatrix(portfolio));

        RealMatrix portfolioVarianceMatrix = weightageMatrix.multiply(varCovarMatrix)
                .multiply(weightageMatrix.transpose());
        RealMatrix portfolioMeanMatrix = weightageMatrix.multiply(meanMatrix.transpose());

        double portfolioVariance = portfolioVarianceMatrix.getData()[0][0];
        double portfolioMean = portfolioMeanMatrix.getData()[0][0];

        if (portfolioVariance == 0) { // a normal distribution cannot be defined when sd = 0
            return null;
        }

        double portfolioStandardDeviation = Math.sqrt(portfolioVariance);

        NormalDistribution normalDistribution = new NormalDistribution(portfolioMean,
                portfolioStandardDeviation);
        double zValue = normalDistribution.inverseCumulativeProbability(1 - getConfidenceInterval());
        double var = zValue * portfolio.getTotalPortfolioValue();

        return var;
    }
    return null;

}

From source file:pl.matrix.core.Matrix.java

public Matrix(RealMatrix rm) {
    data = rm.getData();
}

From source file:qupath.lib.algorithms.color.EstimateStainVectors.java

/**
 * // w ww  . j  av  a  2 s  .  c o  m
 * Check colors only currently applies to H&E.
 * 
 * @param rgbPacked
 * @param redOD
 * @param greenOD
 * @param blueOD
 * @param stainsOriginal
 * @param minStain
 * @param maxStain
 * @param ignorePercentage
 * @param checkColors
 * @return
 */
public static ColorDeconvolutionStains estimateStains(final int[] rgbPacked, final float[] redOD,
        final float[] greenOD, final float[] blueOD, final ColorDeconvolutionStains stainsOriginal,
        final double minStain, final double maxStain, final double ignorePercentage,
        final boolean checkColors) {

    double alpha = ignorePercentage / 100;

    int n = rgbPacked.length;
    if (redOD.length != n || greenOD.length != n || blueOD.length != n)
        throw new IllegalArgumentException("All pixel arrays must be the same length!");
    int[] rgb = Arrays.copyOf(rgbPacked, n);
    float[] red = Arrays.copyOf(redOD, n);
    float[] green = Arrays.copyOf(greenOD, n);
    float[] blue = Arrays.copyOf(blueOD, n);

    // Check if we do color sanity test
    boolean doColorTestForHE = checkColors && stainsOriginal.isH_E();
    //      boolean doColorTestForHDAB = checkColors && stainsOriginal.isH_DAB();
    boolean doGrayTest = checkColors && (stainsOriginal.isH_E() || stainsOriginal.isH_DAB());
    double sqrt3 = 1 / Math.sqrt(3);
    double grayThreshold = Math.cos(0.15);

    // Loop through and discard pixels that are too faintly or densely stained
    int keepCount = 0;
    double maxStainSq = maxStain * maxStain;
    for (int i = 0; i < rgb.length; i++) {
        float r = red[i];
        float g = green[i];
        float b = blue[i];
        double magSquared = r * r + g * g + b * b;
        if (magSquared > maxStainSq || r < minStain || g < minStain || b < minStain)
            continue;
        // Check for consistency with H&E staining, if required (i.e. only keep red/pink/purple/blue pixels and the like)
        if (doColorTestForHE && (r > g || b > g)) {
            continue;
        }
        //         // Check for consistency with H-DAB staining, if required (i.e. only keep red/pink/purple/blue pixels and the like)
        //         if (doColorTestForHDAB && (r > g)) {
        //            continue;
        //         }
        // Exclude very 'gray' pixels
        if (doGrayTest && (r * sqrt3 + g * sqrt3 + b * sqrt3) / Math.sqrt(magSquared) >= grayThreshold) {
            continue;
        }
        // Update the arrays
        red[keepCount] = r;
        green[keepCount] = g;
        blue[keepCount] = b;
        rgb[keepCount] = rgb[i];
        keepCount++;
    }
    if (keepCount <= 1)
        throw new IllegalArgumentException("Not enough pixels remain after applying stain thresholds!");

    // Trim the arrays
    if (keepCount < rgb.length) {
        red = Arrays.copyOf(red, keepCount);
        green = Arrays.copyOf(green, keepCount);
        blue = Arrays.copyOf(blue, keepCount);
        rgb = Arrays.copyOf(rgb, keepCount);
    }

    double[][] cov = new double[3][3];
    cov[0][0] = covariance(red, red);
    cov[1][1] = covariance(green, green);
    cov[2][2] = covariance(blue, blue);
    cov[0][1] = covariance(red, green);
    cov[0][2] = covariance(red, blue);
    cov[1][2] = covariance(green, blue);
    cov[2][1] = cov[1][2];
    cov[2][0] = cov[0][2];
    cov[1][0] = cov[0][1];

    RealMatrix mat = MatrixUtils.createRealMatrix(cov);
    logger.debug("Covariance matrix:\n {}", getMatrixAsString(mat.getData()));

    EigenDecomposition eigen = new EigenDecomposition(mat);

    double[] eigenValues = eigen.getRealEigenvalues();
    int[] eigenOrder = rank(eigenValues);
    double[] eigen1 = eigen.getEigenvector(eigenOrder[2]).toArray();
    double[] eigen2 = eigen.getEigenvector(eigenOrder[1]).toArray();
    logger.debug("First eigenvector: " + getVectorAsString(eigen1));
    logger.debug("Second eigenvector: " + getVectorAsString(eigen2));

    double[] phi = new double[keepCount];
    for (int i = 0; i < keepCount; i++) {
        double r = red[i];
        double g = green[i];
        double b = blue[i];
        phi[i] = Math.atan2(r * eigen1[0] + g * eigen1[1] + b * eigen1[2],
                r * eigen2[0] + g * eigen2[1] + b * eigen2[2]);
    }

    /*
     * Rather than projecting onto the plane (which might be a bit wrong),
     * select the vectors directly from the data.
     * This is effectively like a region selection, but where the region has
     * been chosen automatically.
     */
    int[] inds = rank(phi);
    int ind1 = inds[(int) (alpha * keepCount + .5)];
    int ind2 = inds[(int) ((1 - alpha) * keepCount + .5)];

    // Create new stain vectors
    StainVector s1 = new StainVector(stainsOriginal.getStain(1).getName(), red[ind1], green[ind1], blue[ind1]);
    StainVector s2 = new StainVector(stainsOriginal.getStain(2).getName(), red[ind2], green[ind2], blue[ind2]);

    // If working with H&E, we can use the simple heuristic of comparing the red values
    if (stainsOriginal.isH_E()) {
        // Need to check within the stain vectors (*not* original indexed values) because normalisation is important (I think... there were errors before)
        if (s1.getRed() < s2.getRed()) {
            s1 = new StainVector(stainsOriginal.getStain(1).getName(), red[ind2], green[ind2], blue[ind2]);
            s2 = new StainVector(stainsOriginal.getStain(2).getName(), red[ind1], green[ind1], blue[ind1]);
        }
    } else {
        // Check we've got the closest match - if not, switch the order
        double angle11 = StainVector.computeAngle(s1, stainsOriginal.getStain(1));
        double angle12 = StainVector.computeAngle(s1, stainsOriginal.getStain(2));
        double angle21 = StainVector.computeAngle(s2, stainsOriginal.getStain(1));
        double angle22 = StainVector.computeAngle(s2, stainsOriginal.getStain(2));
        if (Math.min(angle12, angle21) < Math.min(angle11, angle22)) {
            s1 = new StainVector(stainsOriginal.getStain(1).getName(), red[ind2], green[ind2], blue[ind2]);
            s2 = new StainVector(stainsOriginal.getStain(2).getName(), red[ind1], green[ind1], blue[ind1]);
        }
    }

    ColorDeconvolutionStains stains = new ColorDeconvolutionStains(stainsOriginal.getName(), s1, s2,
            stainsOriginal.getMaxRed(), stainsOriginal.getMaxGreen(), stainsOriginal.getMaxBlue());

    return stains;

}

From source file:RBFNN.MainFrame.java

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
    // TODO add your handling code here:
    double len = data.size();
    double hNum = Double.parseDouble(hiddenNum.getText());
    double per = hNum / len;
    K = (int) hNum;
    centers = pickdata(data, per);/*  ww w  . j a va 2 s  .c  o m*/
    ArrayList<instance> trainingdata = pickdata(data, 0.9);
    ArrayList<instance> testingdata = new ArrayList<instance>();
    for (int i = 0; i < len; i++) {
        if (!trainingdata.contains(data.get(i)))
            testingdata.add(data.get(i));
    }
    trainNum.setText(Integer.toString((int) ((int) len * 0.9)));
    testNum.setText(Integer.toString((int) ((int) len * 0.1)));
    RealMatrix W = RBFtrain(trainingdata);
    //String Ws=Arrays.toString(W.getData());
    String dataValues[][] = new String[W.getData().length + 1][2];
    String table = "Num       Weights" + "\n";
    for (int i = 0; i < W.getData().length; i++) {
        dataValues[i][0] = "" + i;
        dataValues[i][1] = Double.toString(W.getData()[i][0]);
        table = table + dataValues[i][0] + "          " + dataValues[i][1] + "\n";
    }
    weightsTable.setText(table);
    float acc = 0;
    confusion = RBFtest(W, testingdata, acc);
    String confs = "             " + "positive" + "   " + "negative" + "\n";
    confs = confs + "positive" + "   " + Integer.toString(confusion[0]) + "            "
            + Integer.toString(confusion[1]) + "\n";
    confs = confs + "negative" + "   " + Integer.toString(confusion[2]) + "            "
            + Integer.toString(confusion[3]) + "\n";
    confusionM.setText(confs);
    acc = ((float) confusion[0] + (float) confusion[3])
            / ((float) confusion[0] + (float) confusion[1] + (float) confusion[2] + (float) confusion[3]);
    String accs = Float.toString(acc * 100);
    accuracy.setText(accs + "%");
}

From source file:se.toxbee.sleepfighter.challenge.math.MatrixProblem.java

private String renderMatrix(RealMatrix m) {

    double[][] matrixData = m.getData();

    // begin table
    String str = "(\\table ";

    for (int i = 0; i < MATRIX_SIZE; ++i) {
        for (int j = 0; j < MATRIX_SIZE; ++j) {
            str += Integer.toString((int) matrixData[i][j]) + " ";
            if (j != MATRIX_SIZE - 1) {
                str += " , ";
            }//from   ww  w  . j av a 2 s  .com
        }

        // no ";" necessary for the last row. 
        if (i != MATRIX_SIZE - 1)
            // start new row.  
            str += " ; ";
    }

    // finish table
    str += ")";

    return str;
}

From source file:shapeCompare.ResultsFromEvaluateCost.java

@Override
public int hashCode() {

    float unit = 3 * algoParameters.getCELL_DIMENSION_OF_THE_PROBABILITY_MAP_ANGSTROM();

    RealVector trans = this.getTranslationVector();
    double x = trans.getEntry(0);
    double y = trans.getEntry(1);
    double z = trans.getEntry(2);
    int xInt = (int) Math.round(x / unit);
    int yInt = (int) Math.round(y / unit);
    int zInt = (int) Math.round(z / unit);

    RealMatrix rotMat = this.getRotationMatrix();
    Rotation rotation = new Rotation(rotMat.getData(), 0.01);

    int unitAngleDegrees = 8;
    double angle = rotation.getAngle();
    int angleInt = (int) Math.round((angle * 180 / Math.PI) / unitAngleDegrees);

    int hashcode = xInt;
    hashcode = hashcode * 71 + yInt;/*from w ww .  j  a  va 2s.  c om*/
    hashcode = hashcode * 71 + zInt;
    hashcode = hashcode * 71 + angleInt;
    return hashcode;
}

From source file:uk.ac.sanger.mig.xray.trendline.utils.Fitter.java

/** Converts the matrix provided trend line calculator into a string */
private String matrixToString(RealMatrix matrix) {
    double[][] data = matrix.getData();

    String res = "";

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            res += data[i][j] + ",";
        }/*from ww  w.  j  a v  a  2  s  .c  o m*/
    }

    return res;
}