Search in sources :

Example 1 with DensityManager

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

the class CreateData method runDensityCalculation.

private static int runDensityCalculation(ExecutorService threadPool, List<Future<?>> futures, final TFloatArrayList coordsX, final TFloatArrayList coordsY, final Statistics densityStats, final float radius, final double area, final int[] allDensity, final int allIndex, Ticker ticker) {
    final int size = coordsX.size();
    final float[] xCoords = coordsX.toArray();
    final float[] yCoords = coordsY.toArray();
    coordsX.resetQuick();
    coordsY.resetQuick();
    futures.add(threadPool.submit(() -> {
        final DensityManager dm = new DensityManager(xCoords, yCoords, area);
        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];
        }
        ticker.tick();
    }));
    return size;
}
Also used : DensityManager(uk.ac.sussex.gdsc.core.clustering.DensityManager) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint)

Example 2 with DensityManager

use of uk.ac.sussex.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 the results
 */
private void computeRipleysPlot(MemoryPeakResults results) {
    final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addMessage("Compute Ripley's L(r) - r plot");
    gd.addNumericField("Min_radius", settings.minR, 2);
    gd.addNumericField("Max_radius", settings.maxR, 2);
    gd.addNumericField("Increment", settings.incrementR, 2);
    gd.addCheckbox("Confidence_intervals", settings.confidenceIntervals);
    gd.showDialog();
    if (gd.wasCanceled()) {
        return;
    }
    settings.minR = gd.getNextNumber();
    settings.maxR = gd.getNextNumber();
    settings.incrementR = gd.getNextNumber();
    settings.confidenceIntervals = gd.getNextBoolean();
    if (settings.minR > settings.maxR || settings.incrementR < 0 || gd.invalidNumber()) {
        IJ.error(TITLE, "Invalid radius parameters");
        return;
    }
    final DensityManager dm = createDensityManager(results);
    final double[][] values = calculateLScores(dm);
    // 99% confidence intervals
    final int iterations = (settings.confidenceIntervals) ? 99 : 0;
    double[] upper = null;
    double[] lower = null;
    final Rectangle bounds = results.getBounds();
    final double area = (double) bounds.width * bounds.height;
    // Use a uniform distribution for the coordinates
    final HaltonSequenceGenerator dist = new HaltonSequenceGenerator(2);
    dist.skipTo(SeedFactory.createInt());
    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
        final float[] x = new float[results.size()];
        final 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);
        }
        final double[][] values2 = calculateLScores(new DensityManager(x, y, area));
        if (upper == null || lower == null) {
            upper = values2[1];
            lower = upper.clone();
        } 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];
                }
            }
        }
    }
    final String title = results.getName() + " Ripley's (L(r) - r) / r";
    final Plot plot = new Plot(title, "Radius", "(L(r) - r) / r");
    plot.addPoints(values[0], values[1], Plot.LINE);
    // 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);
    }
    ImageJUtils.display(title, plot);
}
Also used : Plot(ij.gui.Plot) Rectangle(java.awt.Rectangle) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) DensityManager(uk.ac.sussex.gdsc.core.clustering.DensityManager) HaltonSequenceGenerator(org.apache.commons.math3.random.HaltonSequenceGenerator)

Example 3 with DensityManager

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

the class DensityImage method createDensityManager.

private static DensityManager createDensityManager(MemoryPeakResults results) {
    if (MemoryPeakResults.isEmpty(results)) {
        throw new IllegalArgumentException("Results are null or empty");
    }
    final StandardResultProcedure sp = new StandardResultProcedure(results, DistanceUnit.PIXEL);
    sp.getXy();
    final Rectangle bounds = results.getBounds();
    final double area = (double) bounds.width * bounds.height;
    return new DensityManager(sp.x, sp.y, area);
}
Also used : Rectangle(java.awt.Rectangle) StandardResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.StandardResultProcedure) DensityManager(uk.ac.sussex.gdsc.core.clustering.DensityManager)

Example 4 with DensityManager

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

the class DensityImage method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    // Require some fit results and selected regions
    final 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(settings.inputOption, false, DistanceUnit.PIXEL, null);
    if (MemoryPeakResults.isEmpty(results)) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }
    final 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;
    }
    final long start = System.currentTimeMillis();
    IJ.showStatus("Calculating density ...");
    final boolean useAdjustment = settings.adjustForBorder && !isWithin[0];
    final DensityManager dm = createDensityManager(results);
    int[] density = null;
    if (settings.useSquareApproximation) {
        density = dm.calculateSquareDensity(settings.radius, settings.resolution, useAdjustment);
    } else {
        density = dm.calculateDensity(settings.radius, useAdjustment);
    }
    density = cropBorder(results, density);
    // Convert to float
    final ScoreCalculator calc = createCalculator(results);
    final float[] densityScore = calc.calculate(density);
    final int filtered = plotResults(results, densityScore, calc);
    logDensityResults(results, density, settings.radius, filtered);
    if (settings.computeRipleysPlot) {
        computeRipleysPlot(results);
    }
    final double seconds = (System.currentTimeMillis() - start) / 1000.0;
    IJ.showStatus(TITLE + " complete : " + seconds + "s");
}
Also used : MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) DensityManager(uk.ac.sussex.gdsc.core.clustering.DensityManager)

Example 5 with DensityManager

use of uk.ac.sussex.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 the results
 * @param density the density
 * @param radius the radius
 * @param filtered the filtered
 * @return the summary statistics
 */
private SummaryStatistics logDensityResults(MemoryPeakResults results, int[] density, float radius, int filtered) {
    final float region = (float) (radius * radius * ((settings.useSquareApproximation) ? 4 : Math.PI));
    final Rectangle bounds = results.getBounds();
    final float area = (float) bounds.width * bounds.height;
    final float expected = results.size() * region / area;
    final SummaryStatistics summary = new SummaryStatistics();
    for (int i = 0; i < results.size(); i++) {
        summary.addValue(density[i]);
    }
    final DensityManager dm = createDensityManager(results);
    // Compute this using the input density scores since the radius is the same.
    final double l = (settings.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 (settings.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(uk.ac.sussex.gdsc.core.clustering.DensityManager)

Aggregations

DensityManager (uk.ac.sussex.gdsc.core.clustering.DensityManager)5 Rectangle (java.awt.Rectangle)3 Plot (ij.gui.Plot)1 HaltonSequenceGenerator (org.apache.commons.math3.random.HaltonSequenceGenerator)1 SummaryStatistics (org.apache.commons.math3.stat.descriptive.SummaryStatistics)1 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)1 ReadHint (uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint)1 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)1 StandardResultProcedure (uk.ac.sussex.gdsc.smlm.results.procedures.StandardResultProcedure)1