Search in sources :

Example 1 with SimpleRegression

use of org.apache.commons.math3.stat.regression.SimpleRegression in project GDSC-SMLM by aherbert.

the class DiffusionRateTest method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    if (IJ.controlKeyDown()) {
        simpleTest();
        return;
    }
    extraOptions = Utils.isExtraOptions();
    if (!showDialog())
        return;
    lastSimulatedDataset[0] = lastSimulatedDataset[1] = "";
    lastSimulatedPrecision = 0;
    final int totalSteps = (int) Math.ceil(settings.seconds * settings.stepsPerSecond);
    conversionFactor = 1000000.0 / (settings.pixelPitch * settings.pixelPitch);
    // Diffusion rate is um^2/sec. Convert to pixels per simulation frame.
    final double diffusionRateInPixelsPerSecond = settings.diffusionRate * conversionFactor;
    final double diffusionRateInPixelsPerStep = diffusionRateInPixelsPerSecond / settings.stepsPerSecond;
    final double precisionInPixels = myPrecision / settings.pixelPitch;
    final boolean addError = myPrecision != 0;
    Utils.log(TITLE + " : D = %s um^2/sec, Precision = %s nm", Utils.rounded(settings.diffusionRate, 4), Utils.rounded(myPrecision, 4));
    Utils.log("Mean-displacement per dimension = %s nm/sec", Utils.rounded(1e3 * ImageModel.getRandomMoveDistance(settings.diffusionRate), 4));
    if (extraOptions)
        Utils.log("Step size = %s, precision = %s", Utils.rounded(ImageModel.getRandomMoveDistance(diffusionRateInPixelsPerStep)), Utils.rounded(precisionInPixels));
    // Convert diffusion co-efficient into the standard deviation for the random walk
    final double diffusionSigma = (settings.getDiffusionType() == DiffusionType.LINEAR_WALK) ? // Q. What should this be? At the moment just do 1D diffusion on a random vector
    ImageModel.getRandomMoveDistance(diffusionRateInPixelsPerStep) : ImageModel.getRandomMoveDistance(diffusionRateInPixelsPerStep);
    Utils.log("Simulation step-size = %s nm", Utils.rounded(settings.pixelPitch * diffusionSigma, 4));
    // Move the molecules and get the diffusion rate
    IJ.showStatus("Simulating ...");
    final long start = System.nanoTime();
    final long seed = System.currentTimeMillis() + System.identityHashCode(this);
    RandomGenerator[] random = new RandomGenerator[3];
    RandomGenerator[] random2 = new RandomGenerator[3];
    for (int i = 0; i < 3; i++) {
        random[i] = new Well19937c(seed + i * 12436);
        random2[i] = new Well19937c(seed + i * 678678 + 3);
    }
    Statistics[] stats2D = new Statistics[totalSteps];
    Statistics[] stats3D = new Statistics[totalSteps];
    StoredDataStatistics jumpDistances2D = new StoredDataStatistics(totalSteps);
    StoredDataStatistics jumpDistances3D = new StoredDataStatistics(totalSteps);
    for (int j = 0; j < totalSteps; j++) {
        stats2D[j] = new Statistics();
        stats3D[j] = new Statistics();
    }
    SphericalDistribution dist = new SphericalDistribution(settings.confinementRadius / settings.pixelPitch);
    Statistics asymptote = new Statistics();
    // Save results to memory
    MemoryPeakResults results = new MemoryPeakResults(totalSteps);
    Calibration cal = new Calibration(settings.pixelPitch, 1, 1000.0 / settings.stepsPerSecond);
    results.setCalibration(cal);
    results.setName(TITLE);
    int peak = 0;
    // Store raw coordinates
    ArrayList<Point> points = new ArrayList<Point>(totalSteps);
    StoredData totalJumpDistances1D = new StoredData(settings.particles);
    StoredData totalJumpDistances2D = new StoredData(settings.particles);
    StoredData totalJumpDistances3D = new StoredData(settings.particles);
    for (int i = 0; i < settings.particles; i++) {
        if (i % 16 == 0) {
            IJ.showProgress(i, settings.particles);
            if (Utils.isInterrupted())
                return;
        }
        // Increment the frame so that tracing analysis can distinguish traces
        peak++;
        double[] origin = new double[3];
        final int id = i + 1;
        MoleculeModel m = new MoleculeModel(id, origin.clone());
        if (addError)
            origin = addError(origin, precisionInPixels, random);
        if (useConfinement) {
            // Note: When using confinement the average displacement should asymptote
            // at the average distance of a point from the centre of a ball. This is 3r/4.
            // See: http://answers.yahoo.com/question/index?qid=20090131162630AAMTUfM
            // The equivalent in 2D is 2r/3. However although we are plotting 2D distance
            // this is a projection of the 3D position onto the plane and so the particles
            // will not be evenly spread (there will be clustering at centre caused by the
            // poles)
            final double[] axis = (settings.getDiffusionType() == DiffusionType.LINEAR_WALK) ? nextVector() : null;
            for (int j = 0; j < totalSteps; j++) {
                double[] xyz = m.getCoordinates();
                double[] originalXyz = xyz.clone();
                for (int n = confinementAttempts; n-- > 0; ) {
                    if (settings.getDiffusionType() == DiffusionType.GRID_WALK)
                        m.walk(diffusionSigma, random);
                    else if (settings.getDiffusionType() == DiffusionType.LINEAR_WALK)
                        m.slide(diffusionSigma, axis, random[0]);
                    else
                        m.move(diffusionSigma, random);
                    if (!dist.isWithin(m.getCoordinates())) {
                        // Reset position
                        for (int k = 0; k < 3; k++) xyz[k] = originalXyz[k];
                    } else {
                        // The move was allowed
                        break;
                    }
                }
                points.add(new Point(id, xyz));
                if (addError)
                    xyz = addError(xyz, precisionInPixels, random2);
                peak = record(xyz, id, peak, stats2D[j], stats3D[j], jumpDistances2D, jumpDistances3D, origin, results);
            }
            asymptote.add(distance(m.getCoordinates()));
        } else {
            if (settings.getDiffusionType() == DiffusionType.GRID_WALK) {
                for (int j = 0; j < totalSteps; j++) {
                    m.walk(diffusionSigma, random);
                    double[] xyz = m.getCoordinates();
                    points.add(new Point(id, xyz));
                    if (addError)
                        xyz = addError(xyz, precisionInPixels, random2);
                    peak = record(xyz, id, peak, stats2D[j], stats3D[j], jumpDistances2D, jumpDistances3D, origin, results);
                }
            } else if (settings.getDiffusionType() == DiffusionType.LINEAR_WALK) {
                final double[] axis = nextVector();
                for (int j = 0; j < totalSteps; j++) {
                    m.slide(diffusionSigma, axis, random[0]);
                    double[] xyz = m.getCoordinates();
                    points.add(new Point(id, xyz));
                    if (addError)
                        xyz = addError(xyz, precisionInPixels, random2);
                    peak = record(xyz, id, peak, stats2D[j], stats3D[j], jumpDistances2D, jumpDistances3D, origin, results);
                }
            } else {
                for (int j = 0; j < totalSteps; j++) {
                    m.move(diffusionSigma, random);
                    double[] xyz = m.getCoordinates();
                    points.add(new Point(id, xyz));
                    if (addError)
                        xyz = addError(xyz, precisionInPixels, random2);
                    peak = record(xyz, id, peak, stats2D[j], stats3D[j], jumpDistances2D, jumpDistances3D, origin, results);
                }
            }
        }
        // Debug: record all the particles so they can be analysed
        // System.out.printf("%f %f %f\n", m.getX(), m.getY(), m.getZ());
        final double[] xyz = m.getCoordinates();
        double d2 = 0;
        totalJumpDistances1D.add(d2 = xyz[0] * xyz[0]);
        totalJumpDistances2D.add(d2 += xyz[1] * xyz[1]);
        totalJumpDistances3D.add(d2 += xyz[2] * xyz[2]);
    }
    final double time = (System.nanoTime() - start) / 1000000.0;
    IJ.showProgress(1);
    MemoryPeakResults.addResults(results);
    lastSimulatedDataset[0] = results.getName();
    lastSimulatedPrecision = myPrecision;
    // Convert pixels^2/step to um^2/sec
    final double msd2D = (jumpDistances2D.getMean() / conversionFactor) / (results.getCalibration().getExposureTime() / 1000);
    final double msd3D = (jumpDistances3D.getMean() / conversionFactor) / (results.getCalibration().getExposureTime() / 1000);
    Utils.log("Raw data D=%s um^2/s, Precision = %s nm, N=%d, step=%s s, mean2D=%s um^2, MSD 2D = %s um^2/s, mean3D=%s um^2, MSD 3D = %s um^2/s", Utils.rounded(settings.diffusionRate), Utils.rounded(myPrecision), jumpDistances2D.getN(), Utils.rounded(results.getCalibration().getExposureTime() / 1000), Utils.rounded(jumpDistances2D.getMean() / conversionFactor), Utils.rounded(msd2D), Utils.rounded(jumpDistances3D.getMean() / conversionFactor), Utils.rounded(msd3D));
    aggregateIntoFrames(points, addError, precisionInPixels, random2);
    IJ.showStatus("Analysing results ...");
    if (showDiffusionExample) {
        showExample(totalSteps, diffusionSigma, random);
    }
    // Plot a graph of mean squared distance
    double[] xValues = new double[stats2D.length];
    double[] yValues2D = new double[stats2D.length];
    double[] yValues3D = new double[stats3D.length];
    double[] upper2D = new double[stats2D.length];
    double[] lower2D = new double[stats2D.length];
    double[] upper3D = new double[stats3D.length];
    double[] lower3D = new double[stats3D.length];
    SimpleRegression r2D = new SimpleRegression(false);
    SimpleRegression r3D = new SimpleRegression(false);
    final int firstN = (useConfinement) ? fitN : totalSteps;
    for (int j = 0; j < totalSteps; j++) {
        // Convert steps to seconds
        xValues[j] = (double) (j + 1) / settings.stepsPerSecond;
        // Convert values in pixels^2 to um^2
        final double mean2D = stats2D[j].getMean() / conversionFactor;
        final double mean3D = stats3D[j].getMean() / conversionFactor;
        final double sd2D = stats2D[j].getStandardDeviation() / conversionFactor;
        final double sd3D = stats3D[j].getStandardDeviation() / conversionFactor;
        yValues2D[j] = mean2D;
        yValues3D[j] = mean3D;
        upper2D[j] = mean2D + sd2D;
        lower2D[j] = mean2D - sd2D;
        upper3D[j] = mean3D + sd3D;
        lower3D[j] = mean3D - sd3D;
        if (j < firstN) {
            r2D.addData(xValues[j], yValues2D[j]);
            r3D.addData(xValues[j], yValues3D[j]);
        }
    }
    // TODO - Fit using the equation for 2D confined diffusion:
    // MSD = 4s^2 + R^2 (1 - 0.99e^(-1.84^2 Dt / R^2)
    // s = localisation precision
    // R = confinement radius
    // D = 2D diffusion coefficient
    // t = time
    final PolynomialFunction fitted2D, fitted3D;
    if (r2D.getN() > 0) {
        // Do linear regression to get diffusion rate
        final double[] best2D = new double[] { r2D.getIntercept(), r2D.getSlope() };
        fitted2D = new PolynomialFunction(best2D);
        final double[] best3D = new double[] { r3D.getIntercept(), r3D.getSlope() };
        fitted3D = new PolynomialFunction(best3D);
        // For 2D diffusion: d^2 = 4D
        // where: d^2 = mean-square displacement
        double D = best2D[1] / 4.0;
        String msg = "2D Diffusion rate = " + Utils.rounded(D, 4) + " um^2 / sec (" + Utils.timeToString(time) + ")";
        IJ.showStatus(msg);
        Utils.log(msg);
        D = best3D[1] / 6.0;
        Utils.log("3D Diffusion rate = " + Utils.rounded(D, 4) + " um^2 / sec (" + Utils.timeToString(time) + ")");
    } else {
        fitted2D = fitted3D = null;
    }
    // Create plots
    plotMSD(totalSteps, xValues, yValues2D, lower2D, upper2D, fitted2D, 2);
    plotMSD(totalSteps, xValues, yValues3D, lower3D, upper3D, fitted3D, 3);
    plotJumpDistances(TITLE, jumpDistances2D, 2, 1);
    plotJumpDistances(TITLE, jumpDistances3D, 3, 1);
    if (idCount > 0)
        new WindowOrganiser().tileWindows(idList);
    if (useConfinement)
        Utils.log("3D asymptote distance = %s nm (expected %.2f)", Utils.rounded(asymptote.getMean() * settings.pixelPitch, 4), 3 * settings.confinementRadius / 4);
}
Also used : SphericalDistribution(gdsc.smlm.model.SphericalDistribution) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) ArrayList(java.util.ArrayList) PolynomialFunction(org.apache.commons.math3.analysis.polynomials.PolynomialFunction) Calibration(gdsc.smlm.results.Calibration) WindowOrganiser(ij.plugin.WindowOrganiser) Well19937c(org.apache.commons.math3.random.Well19937c) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) Statistics(gdsc.core.utils.Statistics) RandomGenerator(org.apache.commons.math3.random.RandomGenerator) MoleculeModel(gdsc.smlm.model.MoleculeModel) SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) StoredData(gdsc.core.utils.StoredData) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults)

Example 2 with SimpleRegression

use of org.apache.commons.math3.stat.regression.SimpleRegression in project lucene-solr by apache.

the class RegressionEvaluator method evaluate.

public Tuple evaluate(Tuple tuple) throws IOException {
    if (subEvaluators.size() != 2) {
        throw new IOException("Regress expects 2 columns as parameters");
    }
    StreamEvaluator colEval1 = subEvaluators.get(0);
    StreamEvaluator colEval2 = subEvaluators.get(1);
    List<Number> numbers1 = (List<Number>) colEval1.evaluate(tuple);
    List<Number> numbers2 = (List<Number>) colEval2.evaluate(tuple);
    double[] column1 = new double[numbers1.size()];
    double[] column2 = new double[numbers2.size()];
    for (int i = 0; i < numbers1.size(); i++) {
        column1[i] = numbers1.get(i).doubleValue();
    }
    for (int i = 0; i < numbers2.size(); i++) {
        column2[i] = numbers2.get(i).doubleValue();
    }
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < column1.length; i++) {
        regression.addData(column1[i], column2[i]);
    }
    Map map = new HashMap();
    map.put("slope", regression.getSlope());
    map.put("intercept", regression.getIntercept());
    map.put("R", regression.getR());
    map.put("N", regression.getN());
    map.put("regressionSumSquares", regression.getRegressionSumSquares());
    map.put("slopeConfidenceInterval", regression.getSlopeConfidenceInterval());
    map.put("interceptStdErr", regression.getInterceptStdErr());
    map.put("totalSumSquares", regression.getTotalSumSquares());
    map.put("significance", regression.getSignificance());
    map.put("meanSquareError", regression.getMeanSquareError());
    return new RegressionTuple(regression, map);
}
Also used : SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) HashMap(java.util.HashMap) List(java.util.List) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with SimpleRegression

use of org.apache.commons.math3.stat.regression.SimpleRegression in project atav by igm-team.

the class CoverageComparison method processExon.

@Override
public void processExon(HashMap<Integer, Integer> sampleCoveredLengthMap, Gene gene, Exon exon) {
    try {
        SimpleRegression sr = new SimpleRegression(true);
        SummaryStatistics lss = new SummaryStatistics();
        float caseAvg = 0;
        float ctrlAvg = 0;
        for (Sample sample : SampleManager.getList()) {
            Integer coveredLength = sampleCoveredLengthMap.get(sample.getId());
            if (coveredLength != null) {
                if (sample.isCase()) {
                    caseAvg += coveredLength;
                } else {
                    ctrlAvg += coveredLength;
                }
            } else {
                coveredLength = 0;
            }
            addRegressionData(sr, lss, sample, coveredLength, exon.getLength());
        }
        caseAvg = MathManager.devide(caseAvg, SampleManager.getCaseNum());
        caseAvg = MathManager.devide(caseAvg, exon.getLength());
        ctrlAvg = MathManager.devide(ctrlAvg, SampleManager.getCtrlNum());
        ctrlAvg = MathManager.devide(ctrlAvg, exon.getLength());
        if (CoverageCommand.isMinCoverageFractionValid(caseAvg) && CoverageCommand.isMinCoverageFractionValid(ctrlAvg)) {
            StringBuilder sb = new StringBuilder();
            String name = gene.getName() + "_" + exon.getIdStr();
            sb.append(name).append(",");
            sb.append(gene.getChr()).append(",");
            sb.append(FormatManager.getFloat(caseAvg)).append(",");
            sb.append(FormatManager.getFloat(ctrlAvg)).append(",");
            float covDiff = Data.NA;
            if (CoverageCommand.isRelativeDifference) {
                covDiff = MathManager.relativeDiff(caseAvg, ctrlAvg);
            } else {
                covDiff = MathManager.abs(caseAvg, ctrlAvg);
            }
            sb.append(FormatManager.getFloat(covDiff)).append(",");
            sb.append(exon.getLength());
            addExon(sb, name, caseAvg, ctrlAvg, covDiff, exon.getLength(), sr, lss);
            bwCoverageSummaryByExon.write(sb.toString());
            bwCoverageSummaryByExon.newLine();
        }
    } catch (Exception e) {
        ErrorManager.send(e);
    }
}
Also used : SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) Sample(function.genotype.base.Sample) SummaryStatistics(org.apache.commons.math3.stat.descriptive.SummaryStatistics)

Example 4 with SimpleRegression

use of org.apache.commons.math3.stat.regression.SimpleRegression in project cloudsim-plus by manoelcampos.

the class MathUtil method getRobustLoessParameterEstimates.

/**
 * Gets the robust loess parameter estimates.
 *
 * @param y the y array
 * @return the robust loess parameter estimates
 */
public static double[] getRobustLoessParameterEstimates(final double... y) {
    final int n = y.length;
    final double[] x = new double[n];
    for (int i = 0; i < n; i++) {
        x[i] = i + 1;
    }
    final SimpleRegression tricubeRegression = createWeigthedLinearRegression(x, y, getTricubeWeights(n));
    final double[] residuals = new double[n];
    for (int i = 0; i < n; i++) {
        residuals[i] = y[i] - tricubeRegression.predict(x[i]);
    }
    final SimpleRegression tricubeBySqrRegression = createWeigthedLinearRegression(x, y, getTricubeBisquareWeights(residuals));
    final double[] estimates = tricubeBySqrRegression.regress().getParameterEstimates();
    if (Double.isNaN(estimates[0]) || Double.isNaN(estimates[1])) {
        return tricubeRegression.regress().getParameterEstimates();
    }
    return estimates;
}
Also used : SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression)

Example 5 with SimpleRegression

use of org.apache.commons.math3.stat.regression.SimpleRegression in project TeeTime by teetime-framework.

the class RegressionAlgorithm method doAnalysis.

@Override
protected double doAnalysis(final ThroughputHistory history) {
    final SimpleRegression regression = new SimpleRegression();
    for (int i = 1; i <= this.window; i++) {
        final double xaxis = history.getTimestampOfEntry(i);
        final double yaxis = history.getThroughputOfEntry(i);
        regression.addData(xaxis, yaxis);
    }
    final double currentTime = history.getTimestampOfEntry(0);
    double prediction = regression.predict(currentTime);
    if (Double.isNaN(prediction) || prediction < 0 || Double.isInfinite(prediction)) {
        prediction = 0;
    }
    return prediction;
}
Also used : SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression)

Aggregations

SimpleRegression (org.apache.commons.math3.stat.regression.SimpleRegression)32 ArrayList (java.util.ArrayList)13 Test (org.junit.Test)4 FractionClassificationResult (gdsc.core.match.FractionClassificationResult)3 List (java.util.List)3 Sample (function.genotype.base.Sample)2 BasePoint (gdsc.core.match.BasePoint)2 FractionalAssignment (gdsc.core.match.FractionalAssignment)2 FastCorrelator (gdsc.core.utils.FastCorrelator)2 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)2 PeakResultPoint (gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint)2 BasePreprocessedPeakResult (gdsc.smlm.results.filter.BasePreprocessedPeakResult)2 DirectFilter (gdsc.smlm.results.filter.DirectFilter)2 PeakFractionalAssignment (gdsc.smlm.results.filter.PeakFractionalAssignment)2 PreprocessedPeakResult (gdsc.smlm.results.filter.PreprocessedPeakResult)2 TIntHashSet (gnu.trove.set.hash.TIntHashSet)2 Plot (ij.gui.Plot)2 PlotWindow (ij.gui.PlotWindow)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2