Search in sources :

Example 1 with DensityManager

use of gdsc.core.clustering.DensityManager in project GDSC-SMLM by aherbert.

the class DensityImage method createDensityManager.

private DensityManager createDensityManager(MemoryPeakResults results) {
    if (results == null || results.size() == 0)
        throw new IllegalArgumentException("Results are null or empty");
    final float[] xcoord = new float[results.size()];
    final float[] ycoord = new float[xcoord.length];
    ArrayList<PeakResult> peakResults = (ArrayList<PeakResult>) results.getResults();
    for (int i = 0; i < xcoord.length; i++) {
        PeakResult result = peakResults.get(i);
        xcoord[i] = result.getXPosition();
        ycoord[i] = result.getYPosition();
    }
    return new DensityManager(xcoord, ycoord, results.getBounds());
}
Also used : ArrayList(java.util.ArrayList) TDoubleArrayList(gnu.trove.list.array.TDoubleArrayList) DensityManager(gdsc.core.clustering.DensityManager) PeakResult(gdsc.smlm.results.PeakResult)

Example 2 with DensityManager

use of gdsc.core.clustering.DensityManager in project GDSC-SMLM by aherbert.

the class DensityImage method computeRipleysPlot.

/**
	 * Compute the Ripley's L-function for user selected radii and show it on a plot.
	 * 
	 * @param results
	 */
private void computeRipleysPlot(MemoryPeakResults results) {
    ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addMessage("Compute Ripley's L(r) - r plot");
    gd.addNumericField("Min_radius", minR, 2);
    gd.addNumericField("Max_radius", maxR, 2);
    gd.addNumericField("Increment", incrementR, 2);
    gd.addCheckbox("Confidence_intervals", confidenceIntervals);
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    minR = gd.getNextNumber();
    maxR = gd.getNextNumber();
    incrementR = gd.getNextNumber();
    confidenceIntervals = gd.getNextBoolean();
    if (minR > maxR || incrementR < 0 || gd.invalidNumber()) {
        IJ.error(TITLE, "Invalid radius parameters");
        return;
    }
    DensityManager dm = createDensityManager(results);
    double[][] values = calculateLScores(dm);
    // 99% confidence intervals
    final int iterations = (confidenceIntervals) ? 99 : 0;
    double[] upper = null;
    double[] lower = null;
    Rectangle bounds = results.getBounds();
    // Use a uniform distribution for the coordinates
    HaltonSequenceGenerator dist = new HaltonSequenceGenerator(2);
    dist.skipTo(new Well19937c(System.currentTimeMillis() + System.identityHashCode(this)).nextInt());
    for (int i = 0; i < iterations; i++) {
        IJ.showProgress(i, iterations);
        IJ.showStatus(String.format("L-score confidence interval %d / %d", i + 1, iterations));
        // Randomise coordinates
        float[] x = new float[results.size()];
        float[] y = new float[x.length];
        for (int j = x.length; j-- > 0; ) {
            final double[] d = dist.nextVector();
            x[j] = (float) (d[0] * bounds.width);
            y[j] = (float) (d[1] * bounds.height);
        }
        double[][] values2 = calculateLScores(new DensityManager(x, y, bounds));
        if (upper == null) {
            upper = values2[1];
            lower = new double[upper.length];
            System.arraycopy(upper, 0, lower, 0, upper.length);
        } else {
            for (int m = upper.length; m-- > 0; ) {
                if (upper[m] < values2[1][m])
                    upper[m] = values2[1][m];
                if (lower[m] > values2[1][m])
                    lower[m] = values2[1][m];
            }
        }
    }
    String title = results.getName() + " Ripley's (L(r) - r) / r";
    Plot2 plot = new Plot2(title, "Radius", "(L(r) - r) / r", values[0], values[1]);
    // Get the limits
    double yMin = min(0, values[1]);
    double yMax = max(0, values[1]);
    if (iterations > 0) {
        yMin = min(yMin, lower);
        yMax = max(yMax, upper);
    }
    plot.setLimits(0, values[0][values[0].length - 1], yMin, yMax);
    if (iterations > 0) {
        plot.setColor(Color.BLUE);
        plot.addPoints(values[0], upper, 1);
        plot.setColor(Color.RED);
        plot.addPoints(values[0], lower, 1);
        plot.setColor(Color.BLACK);
    }
    Utils.display(title, plot);
}
Also used : Rectangle(java.awt.Rectangle) ExtendedGenericDialog(ij.gui.ExtendedGenericDialog) DensityManager(gdsc.core.clustering.DensityManager) Plot2(ij.gui.Plot2) Well19937c(org.apache.commons.math3.random.Well19937c) HaltonSequenceGenerator(org.apache.commons.math3.random.HaltonSequenceGenerator)

Example 3 with DensityManager

use of gdsc.core.clustering.DensityManager in project GDSC-SMLM by aherbert.

the class CreateData method runDensityCalculation.

private int runDensityCalculation(ExecutorService threadPool, List<Future<?>> futures, final ArrayList<float[]> coords, final Statistics densityStats, final float radius, final Rectangle bounds, final int[] allDensity, final int allIndex) {
    final int size = coords.size();
    final float[] xCoords = new float[size];
    final float[] yCoords = new float[size];
    for (int i = 0; i < xCoords.length; i++) {
        float[] xy = coords.get(i);
        xCoords[i] = xy[0];
        yCoords[i] = xy[1];
    }
    futures.add(threadPool.submit(new Runnable() {

        public void run() {
            incrementProgress();
            final DensityManager dm = new DensityManager(xCoords, yCoords, bounds);
            final int[] density = dm.calculateDensity(radius, true);
            addDensity(densityStats, density);
            // since the indices in different threads are unique.
            for (int i = 0, index = allIndex; i < density.length; i++, index++) allDensity[index] = density[i];
        }
    }));
    coords.clear();
    return size;
}
Also used : DensityManager(gdsc.core.clustering.DensityManager)

Example 4 with DensityManager

use of gdsc.core.clustering.DensityManager in project GDSC-SMLM by aherbert.

the class DensityImage method logDensityResults.

/**
	 * Output a log message of the results including the average density for localisations and the expected average.
	 * 
	 * @param results
	 * @param density
	 * @param radius
	 * @param filtered
	 * @return
	 */
private SummaryStatistics logDensityResults(MemoryPeakResults results, int[] density, float radius, int filtered) {
    float region = (float) (radius * radius * ((useSquareApproximation) ? 4 : Math.PI));
    Rectangle bounds = results.getBounds();
    float area = bounds.width * bounds.height;
    float expected = results.size() * region / area;
    SummaryStatistics summary = new SummaryStatistics();
    for (int i = 0; i < results.size(); i++) {
        summary.addValue(density[i]);
    }
    DensityManager dm = createDensityManager(results);
    // Compute this using the input density scores since the radius is the same.
    final double l = (useSquareApproximation) ? dm.ripleysLFunction(radius) : dm.ripleysLFunction(density, radius);
    String msg = String.format("Density %s : N=%d, %.0fpx : Radius=%s : L(r) - r = %s : E = %s, Obs = %s (%sx)", results.getName(), summary.getN(), area, rounded(radius), rounded(l - radius), rounded(expected), rounded(summary.getMean()), rounded(summary.getMean() / expected));
    if (filterLocalisations)
        msg += String.format(" : Filtered=%d (%s%%)", filtered, rounded(filtered * 100.0 / density.length));
    IJ.log(msg);
    return summary;
}
Also used : Rectangle(java.awt.Rectangle) SummaryStatistics(org.apache.commons.math3.stat.descriptive.SummaryStatistics) DensityManager(gdsc.core.clustering.DensityManager)

Example 5 with DensityManager

use of gdsc.core.clustering.DensityManager in project GDSC-SMLM by aherbert.

the class DensityImage method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    // Require some fit results and selected regions
    int size = MemoryPeakResults.countMemorySize();
    if (size == 0) {
        IJ.error(TITLE, "There are no fitting results in memory");
        return;
    }
    if (!showDialog())
        return;
    MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }
    boolean[] isWithin = new boolean[1];
    results = cropWithBorder(results, isWithin);
    if (results.size() == 0) {
        IJ.error(TITLE, "No results within the crop region");
        IJ.showStatus("");
        return;
    }
    long start = System.currentTimeMillis();
    IJ.showStatus("Calculating density ...");
    boolean useAdjustment = adjustForBorder && !isWithin[0];
    DensityManager dm = createDensityManager(results);
    int[] density = null;
    if (useSquareApproximation)
        density = dm.calculateSquareDensity(radius, resolution, useAdjustment);
    else
        density = dm.calculateDensity(radius, useAdjustment);
    density = cropBorder(results, density);
    // Convert to float
    ScoreCalculator calc = createCalculator(results);
    float[] densityScore = calc.calculate(density);
    int filtered = plotResults(results, densityScore, calc);
    logDensityResults(results, density, radius, filtered);
    if (computeRipleysPlot)
        computeRipleysPlot(results);
    double seconds = (System.currentTimeMillis() - start) / 1000.0;
    IJ.showStatus(TITLE + " complete : " + seconds + "s");
}
Also used : MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) DensityManager(gdsc.core.clustering.DensityManager)

Aggregations

DensityManager (gdsc.core.clustering.DensityManager)5 Rectangle (java.awt.Rectangle)2 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)1 PeakResult (gdsc.smlm.results.PeakResult)1 TDoubleArrayList (gnu.trove.list.array.TDoubleArrayList)1 ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)1 Plot2 (ij.gui.Plot2)1 ArrayList (java.util.ArrayList)1 HaltonSequenceGenerator (org.apache.commons.math3.random.HaltonSequenceGenerator)1 Well19937c (org.apache.commons.math3.random.Well19937c)1 SummaryStatistics (org.apache.commons.math3.stat.descriptive.SummaryStatistics)1