Example usage for org.apache.commons.math3.linear RealVector ebeMultiply

List of usage examples for org.apache.commons.math3.linear RealVector ebeMultiply

Introduction

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

Prototype

@Deprecated
public abstract RealVector ebeMultiply(RealVector v) throws DimensionMismatchException;

Source Link

Document

Element-by-element multiplication.

Usage

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

/**
 * Applies an existing correction to a single x-y position in the Image plane.
 *
 * @param x     The x-position at which to apply the correction.
 * @param y     The y-position at which to apply the correction.
 * @return      A RealVector containing 3 elements-- the magnitude of the correction in the x, y, and z dimensions, in that order.
 *///w w  w. j  a v  a  2 s . co m
public RealVector correctPosition(double x, double y) throws UnableToCorrectException {

    RealVector corrections = new ArrayRealVector(3, 0.0);

    RealVector distsToCentroids = this.getPositionsForCorrection().getColumnVector(0).mapSubtract(x)
            .mapToSelf(new Power(2));
    distsToCentroids = distsToCentroids
            .add(this.getPositionsForCorrection().getColumnVector(1).mapSubtract(y).mapToSelf(new Power(2)));
    distsToCentroids.mapToSelf(new Sqrt());

    RealVector distRatio = distsToCentroids.ebeDivide(this.getDistanceCutoffs());

    RealVector distRatioBin = new ArrayRealVector(distRatio.getDimension(), 0.0);

    for (int i = 0; i < distRatio.getDimension(); i++) {
        if (distRatio.getEntry(i) <= 1)
            distRatioBin.setEntry(i, 1.0);
    }

    RealVector weights = distRatio.map(new Power(2.0)).mapMultiplyToSelf(-3).mapAddToSelf(1)
            .add(distRatio.map(new Power(3.0)).mapMultiplyToSelf(2));

    weights = weights.ebeMultiply(distRatioBin);

    double sumWeights = 0;

    int countWeights = 0;

    for (int i = 0; i < weights.getDimension(); i++) {
        if (weights.getEntry(i) > 0) {
            sumWeights += weights.getEntry(i);
            countWeights++;
        }
    }

    if (countWeights == 0) { // this means there were no points in the correction dataset near the position being corrected.
        throw (new UnableToCorrectException(
                "Incomplete coverage in correction dataset at (x,y) = (" + x + ", " + y + ")."));
    }

    RealMatrix cX = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());
    RealMatrix cY = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());
    RealMatrix cZ = new Array2DRowRealMatrix(countWeights, this.getCorrectionX().getColumnDimension());

    RealVector xVec = new ArrayRealVector(countWeights, 0.0);
    RealVector yVec = new ArrayRealVector(countWeights, 0.0);

    RealVector keptWeights = new ArrayRealVector(countWeights, 0.0);

    int keptCounter = 0;

    for (int i = 0; i < weights.getDimension(); i++) {
        if (weights.getEntry(i) > 0) {

            cX.setRowVector(keptCounter, this.getCorrectionX().getRowVector(i));
            cY.setRowVector(keptCounter, this.getCorrectionY().getRowVector(i));
            cZ.setRowVector(keptCounter, this.getCorrectionZ().getRowVector(i));

            xVec.setEntry(keptCounter, x - this.getPositionsForCorrection().getEntry(i, 0));
            yVec.setEntry(keptCounter, y - this.getPositionsForCorrection().getEntry(i, 1));

            keptWeights.setEntry(keptCounter, weights.getEntry(i));

            keptCounter++;
        }
    }

    double xCorr = 0;
    double yCorr = 0;
    double zCorr = 0;

    RealMatrix allCorrectionParameters = new Array2DRowRealMatrix(countWeights, numberOfCorrectionParameters);

    RealVector ones = new ArrayRealVector(countWeights, 1.0);

    allCorrectionParameters.setColumnVector(0, ones);
    allCorrectionParameters.setColumnVector(1, xVec);
    allCorrectionParameters.setColumnVector(2, yVec);
    allCorrectionParameters.setColumnVector(3, xVec.map(new Power(2)));
    allCorrectionParameters.setColumnVector(4, yVec.map(new Power(2)));
    allCorrectionParameters.setColumnVector(5, xVec.ebeMultiply(yVec));

    for (int i = 0; i < countWeights; i++) {

        xCorr += allCorrectionParameters.getRowVector(i).dotProduct(cX.getRowVector(i))
                * keptWeights.getEntry(i);
        yCorr += allCorrectionParameters.getRowVector(i).dotProduct(cY.getRowVector(i))
                * keptWeights.getEntry(i);
        zCorr += allCorrectionParameters.getRowVector(i).dotProduct(cZ.getRowVector(i))
                * keptWeights.getEntry(i);

    }

    xCorr /= sumWeights;
    yCorr /= sumWeights;
    zCorr /= sumWeights;

    corrections.setEntry(0, xCorr);
    corrections.setEntry(1, yCorr);
    corrections.setEntry(2, zCorr);

    return corrections;
}

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

/**
 * Gets the scalar difference between the position of the object in two channels.
 * //from  w  w w . j av a 2s  . com
 * Units are converted from image units to real units using the supplied vector of conversions.
 * 
 * @param channel0    The index of one channel to use for the difference.
 * @param channel1   The index of the other channel to use for the difference.
 * @param pixelToDistanceConversions   A vector containing the number of realspace distance units per pixel or section, one element per dimension.
 * @return         The scalar distance between the position of the object in each channel (that is, the length of the vector representing the vector distance), or null if either channel is out of range or has not yet been fit.
 */
public Double getScalarDifferenceBetweenChannels(int channel0, int channel1,
        RealVector pixelToDistanceConversions) {

    int key = this.numberOfChannels * channel0 + channel1;

    if (!this.scalarDifferencesBetweenChannels.containsKey(key)) {

        RealVector vecDifference = this.getVectorDifferenceBetweenChannels(channel0, channel1);

        if (vecDifference == null) {
            return null;
        }

        this.scalarDifferencesBetweenChannels.put(key,
                vecDifference.ebeMultiply(pixelToDistanceConversions).getNorm());

    }

    return this.scalarDifferencesBetweenChannels.get(key);

}

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

/**
* Applies an in situ cellular aberration correction to a dataset.
* 
* @param toCorrect a list of ImageObjects to be corrected.
* @param slopes the slopes of a linear fit between the channel pair used to correct and the channel pair being corrected (as calculated by {@link #determineInSituAberrationCorrection()}, for instance).
* @return a List of RealVectors that are the corrected vector distances between each object's images in the channel pair being corrected.
*///from   www  .  j  a v  a 2  s  .c om
public java.util.List<RealVector> applyInSituAberrationCorrection(java.util.List<ImageObject> toCorrect,
        RealVector slopes) {

    int referenceChannel = this.parameters.getIntValueForKey(REF_CH_PARAM);
    int inSituAberrCorrChannel = this.parameters.getIntValueForKey(IN_SITU_ABERR_SECOND_CH_PARAM);
    int measurementChannel = this.parameters.getIntValueForKey(CORR_CH_PARAM);

    java.util.List<RealVector> correctedDifferences = new java.util.ArrayList<RealVector>();

    for (ImageObject iobj : toCorrect) {
        RealVector corrDiff = iobj
                .getCorrectedVectorDifferenceBetweenChannels(referenceChannel, inSituAberrCorrChannel)
                .ebeMultiply(this.pixelToDistanceConversions);
        RealVector exptDiff = iobj
                .getCorrectedVectorDifferenceBetweenChannels(referenceChannel, measurementChannel)
                .ebeMultiply(this.pixelToDistanceConversions);

        RealVector correction = corrDiff.ebeMultiply(slopes);

        correctedDifferences.add(exptDiff.subtract(correction));
    }

    return correctedDifferences;

}

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  av  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:edu.stanford.cfuller.colocalization3d.correction.PositionCorrector.java

/**
* Applies an existing correction to the positions of a set of objects, using a specified reference
* and correction channel./*  ww  w  . j av  a2  s .c o  m*/
* 
* @param imageObjects                  A Vector containing all the ImageObjects to be corrected.
* @param c                             The Correction object to be used, which could have been generated with determineCorrection, or loaded from disk.
* @return                              A RealVector with one entry per ImageObject, containing the corrected scalar distance between the object in the reference channel and the channel being corrected.
*/
public RealVector applyCorrection(Correction c, java.util.List<ImageObject> imageObjects) {

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

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

    RealVector diffs = new ArrayRealVector(imageObjects.size(), 0.0);
    RealVector averageVectorDiffs = null;

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

        diffs.setEntry(i, imageObjects.get(i).getScalarDifferenceBetweenChannels(referenceChannel,
                channelToCorrect, this.pixelToDistanceConversions));

        if (i == 0) {
            averageVectorDiffs = imageObjects.get(i)
                    .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).copy();

        } else {
            averageVectorDiffs = averageVectorDiffs.add(imageObjects.get(i)
                    .getVectorDifferenceBetweenChannels(referenceChannel, channelToCorrect).map(new Abs()));
        }

    }

    averageVectorDiffs.mapDivideToSelf(imageObjects.size());
    averageVectorDiffs = averageVectorDiffs.ebeMultiply(this.pixelToDistanceConversions);

    java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
            .info("mean separation uncorrected = " + diffs.getL1Norm() / diffs.getDimension());
    java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
            .info("mean separation components uncorrected = " + averageVectorDiffs.toString());

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

    if (this.parameters.getBooleanValueForKey("correct_images")) {

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

            try {

                newDiffs.setEntry(i, this.correctSingleObjectVectorDifference(c, imageObjects.get(i),
                        referenceChannel, channelToCorrect).getNorm());

                imageObjects.get(i).setCorrectionSuccessful(true);

            } catch (UnableToCorrectException e) {

                newDiffs.setEntry(i, -1.0 * Double.MAX_VALUE);

                imageObjects.get(i).setCorrectionSuccessful(false);

            }

        }

        java.util.logging.Logger.getLogger("edu.stanford.cfuller.colocalization3d")
                .info("mean separation corrected = " + newDiffs.getL1Norm() / newDiffs.getDimension());

    } else {
        newDiffs = diffs;
    }

    return newDiffs;
}

From source file:org.wallerlab.yoink.math.linear.CommonsMatrix.java

/**
 * Element-by-element multiplication of two 3D vectors.
 */// w  w  w . ja  va 2s.c  o m
@Override
public Matrix ebeMultiply(Matrix m) {
    double[] v1 = this.internalMatrix.getRow(0);
    RealVector vector1 = new ArrayRealVector(v1);
    double[] v2 = ((RealMatrix) m.getInternalMatrix()).getRow(0);
    RealVector vector2 = new ArrayRealVector(v2);
    RealVector vectorEBE = vector1.ebeMultiply(vector2);
    double[] vEBE = vectorEBE.toArray();
    tempMatrix = MatrixUtils.createRealMatrix(1, 3);
    tempMatrix.setRow(0, vEBE);
    Matrix newMatrix = new CommonsMatrix();
    newMatrix.setInternalMatrix(tempMatrix);
    return newMatrix;
}