Search in sources :

Example 16 with GlobalSettings

use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.

the class BenchmarkSpotFit method summariseResults.

private void summariseResults(TIntObjectHashMap<FilterCandidates> filterCandidates, long runTime, final PreprocessedPeakResult[] preprocessedPeakResults, int nUniqueIDs) {
    createTable();
    // Summarise the fitting results. N fits, N failures. 
    // Optimal match statistics if filtering is perfect (since fitting is not perfect).
    StoredDataStatistics distanceStats = new StoredDataStatistics();
    StoredDataStatistics depthStats = new StoredDataStatistics();
    // Get stats for all fitted results and those that match 
    // Signal, SNR, Width, xShift, yShift, Precision
    createFilterCriteria();
    StoredDataStatistics[][] stats = new StoredDataStatistics[3][filterCriteria.length];
    for (int i = 0; i < stats.length; i++) for (int j = 0; j < stats[i].length; j++) stats[i][j] = new StoredDataStatistics();
    final double nmPerPixel = simulationParameters.a;
    double tp = 0, fp = 0;
    int failcTP = 0, failcFP = 0;
    int cTP = 0, cFP = 0;
    int[] singleStatus = null, multiStatus = null, doubletStatus = null, multiDoubletStatus = null;
    singleStatus = new int[FitStatus.values().length];
    multiStatus = new int[singleStatus.length];
    doubletStatus = new int[singleStatus.length];
    multiDoubletStatus = new int[singleStatus.length];
    // Easier to materialise the values since we have a lot of non final variables to manipulate
    final int[] frames = new int[filterCandidates.size()];
    final FilterCandidates[] candidates = new FilterCandidates[filterCandidates.size()];
    final int[] counter = new int[1];
    filterCandidates.forEachEntry(new TIntObjectProcedure<FilterCandidates>() {

        public boolean execute(int a, FilterCandidates b) {
            frames[counter[0]] = a;
            candidates[counter[0]] = b;
            counter[0]++;
            return true;
        }
    });
    for (FilterCandidates result : candidates) {
        // Count the number of fit results that matched (tp) and did not match (fp)
        tp += result.tp;
        fp += result.fp;
        for (int i = 0; i < result.fitResult.length; i++) {
            if (result.spots[i].match)
                cTP++;
            else
                cFP++;
            final MultiPathFitResult fitResult = result.fitResult[i];
            if (singleStatus != null && result.spots[i].match) {
                // Debugging reasons for fit failure
                addStatus(singleStatus, fitResult.getSingleFitResult());
                addStatus(multiStatus, fitResult.getMultiFitResult());
                addStatus(doubletStatus, fitResult.getDoubletFitResult());
                addStatus(multiDoubletStatus, fitResult.getMultiDoubletFitResult());
            }
            if (noMatch(fitResult)) {
                if (result.spots[i].match)
                    failcTP++;
                else
                    failcFP++;
            }
            // We have multi-path results.
            // We want statistics for:
            // [0] all fitted spots
            // [1] fitted spots that match a result
            // [2] fitted spots that do not match a result
            addToStats(fitResult.getSingleFitResult(), stats);
            addToStats(fitResult.getMultiFitResult(), stats);
            addToStats(fitResult.getDoubletFitResult(), stats);
            addToStats(fitResult.getMultiDoubletFitResult(), stats);
        }
        // Statistics on spots that fit an actual result
        for (int i = 0; i < result.match.length; i++) {
            if (!result.match[i].isFitResult())
                // For now just ignore the candidates that matched
                continue;
            FitMatch fitMatch = (FitMatch) result.match[i];
            distanceStats.add(fitMatch.d * nmPerPixel);
            depthStats.add(fitMatch.z * nmPerPixel);
        }
    }
    // Store data for computing correlation
    double[] i1 = new double[depthStats.getN()];
    double[] i2 = new double[i1.length];
    double[] is = new double[i1.length];
    int ci = 0;
    for (FilterCandidates result : candidates) {
        for (int i = 0; i < result.match.length; i++) {
            if (!result.match[i].isFitResult())
                // For now just ignore the candidates that matched
                continue;
            FitMatch fitMatch = (FitMatch) result.match[i];
            ScoredSpot spot = result.spots[fitMatch.i];
            i1[ci] = fitMatch.predictedSignal;
            i2[ci] = fitMatch.actualSignal;
            is[ci] = spot.spot.intensity;
            ci++;
        }
    }
    // We want to compute the Jaccard against the spot metric
    // Filter the results using the multi-path filter
    ArrayList<MultiPathFitResults> multiPathResults = new ArrayList<MultiPathFitResults>(filterCandidates.size());
    for (int i = 0; i < frames.length; i++) {
        int frame = frames[i];
        MultiPathFitResult[] multiPathFitResults = candidates[i].fitResult;
        int totalCandidates = candidates[i].spots.length;
        int nActual = actualCoordinates.get(frame).size();
        multiPathResults.add(new MultiPathFitResults(frame, multiPathFitResults, totalCandidates, nActual));
    }
    // Score the results and count the number returned
    List<FractionalAssignment[]> assignments = new ArrayList<FractionalAssignment[]>();
    final TIntHashSet set = new TIntHashSet(nUniqueIDs);
    FractionScoreStore scoreStore = new FractionScoreStore() {

        public void add(int uniqueId) {
            set.add(uniqueId);
        }
    };
    MultiPathFitResults[] multiResults = multiPathResults.toArray(new MultiPathFitResults[multiPathResults.size()]);
    // Filter with no filter
    MultiPathFilter mpf = new MultiPathFilter(new SignalFilter(0), null, multiFilter.residualsThreshold);
    FractionClassificationResult fractionResult = mpf.fractionScoreSubset(multiResults, Integer.MAX_VALUE, this.results.size(), assignments, scoreStore, CoordinateStoreFactory.create(imp.getWidth(), imp.getHeight(), fitConfig.getDuplicateDistance()));
    double nPredicted = fractionResult.getTP() + fractionResult.getFP();
    final double[][] matchScores = new double[set.size()][];
    int count = 0;
    for (int i = 0; i < assignments.size(); i++) {
        FractionalAssignment[] a = assignments.get(i);
        if (a == null)
            continue;
        for (int j = 0; j < a.length; j++) {
            final PreprocessedPeakResult r = ((PeakFractionalAssignment) a[j]).peakResult;
            set.remove(r.getUniqueId());
            final double precision = Math.sqrt(r.getLocationVariance());
            final double signal = r.getSignal();
            final double snr = r.getSNR();
            final double width = r.getXSDFactor();
            final double xShift = r.getXRelativeShift2();
            final double yShift = r.getYRelativeShift2();
            // Since these two are combined for filtering and the max is what matters.
            final double shift = (xShift > yShift) ? Math.sqrt(xShift) : Math.sqrt(yShift);
            final double eshift = Math.sqrt(xShift + yShift);
            final double[] score = new double[8];
            score[FILTER_SIGNAL] = signal;
            score[FILTER_SNR] = snr;
            score[FILTER_MIN_WIDTH] = width;
            score[FILTER_MAX_WIDTH] = width;
            score[FILTER_SHIFT] = shift;
            score[FILTER_ESHIFT] = eshift;
            score[FILTER_PRECISION] = precision;
            score[FILTER_PRECISION + 1] = a[j].getScore();
            matchScores[count++] = score;
        }
    }
    // Add the rest
    set.forEach(new CustomTIntProcedure(count) {

        public boolean execute(int uniqueId) {
            // This should not be null or something has gone wrong
            PreprocessedPeakResult r = preprocessedPeakResults[uniqueId];
            if (r == null)
                throw new RuntimeException("Missing result: " + uniqueId);
            final double precision = Math.sqrt(r.getLocationVariance());
            final double signal = r.getSignal();
            final double snr = r.getSNR();
            final double width = r.getXSDFactor();
            final double xShift = r.getXRelativeShift2();
            final double yShift = r.getYRelativeShift2();
            // Since these two are combined for filtering and the max is what matters.
            final double shift = (xShift > yShift) ? Math.sqrt(xShift) : Math.sqrt(yShift);
            final double eshift = Math.sqrt(xShift + yShift);
            final double[] score = new double[8];
            score[FILTER_SIGNAL] = signal;
            score[FILTER_SNR] = snr;
            score[FILTER_MIN_WIDTH] = width;
            score[FILTER_MAX_WIDTH] = width;
            score[FILTER_SHIFT] = shift;
            score[FILTER_ESHIFT] = eshift;
            score[FILTER_PRECISION] = precision;
            matchScores[c++] = score;
            return true;
        }
    });
    // Debug the reasons the fit failed
    if (singleStatus != null) {
        String name = PeakFit.getSolverName(fitConfig);
        if (fitConfig.getFitSolver() == FitSolver.MLE && fitConfig.isModelCamera())
            name += " Camera";
        System.out.println("Failure counts: " + name);
        printFailures("Single", singleStatus);
        printFailures("Multi", multiStatus);
        printFailures("Doublet", doubletStatus);
        printFailures("Multi doublet", multiDoubletStatus);
    }
    StringBuilder sb = new StringBuilder(300);
    // Add information about the simulation
    //(simulationParameters.minSignal + simulationParameters.maxSignal) * 0.5;
    final double signal = simulationParameters.signalPerFrame;
    final int n = results.size();
    sb.append(imp.getStackSize()).append("\t");
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    sb.append(w).append("\t");
    sb.append(h).append("\t");
    sb.append(n).append("\t");
    double density = ((double) n / imp.getStackSize()) / (w * h) / (simulationParameters.a * simulationParameters.a / 1e6);
    sb.append(Utils.rounded(density)).append("\t");
    sb.append(Utils.rounded(signal)).append("\t");
    sb.append(Utils.rounded(simulationParameters.s)).append("\t");
    sb.append(Utils.rounded(simulationParameters.a)).append("\t");
    sb.append(Utils.rounded(simulationParameters.depth)).append("\t");
    sb.append(simulationParameters.fixedDepth).append("\t");
    sb.append(Utils.rounded(simulationParameters.gain)).append("\t");
    sb.append(Utils.rounded(simulationParameters.readNoise)).append("\t");
    sb.append(Utils.rounded(simulationParameters.b)).append("\t");
    sb.append(Utils.rounded(simulationParameters.b2)).append("\t");
    // Compute the noise
    double noise = simulationParameters.b2;
    if (simulationParameters.emCCD) {
        // The b2 parameter was computed without application of the EM-CCD noise factor of 2.
        //final double b2 = backgroundVariance + readVariance
        //                = simulationParameters.b + readVariance
        // This should be applied only to the background variance.
        final double readVariance = noise - simulationParameters.b;
        noise = simulationParameters.b * 2 + readVariance;
    }
    if (simulationParameters.fullSimulation) {
    // The total signal is spread over frames
    }
    sb.append(Utils.rounded(signal / Math.sqrt(noise))).append("\t");
    sb.append(Utils.rounded(simulationParameters.s / simulationParameters.a)).append("\t");
    sb.append(spotFilter.getDescription());
    // nP and nN is the fractional score of the spot candidates 
    addCount(sb, nP + nN);
    addCount(sb, nP);
    addCount(sb, nN);
    addCount(sb, fP);
    addCount(sb, fN);
    String name = PeakFit.getSolverName(fitConfig);
    if (fitConfig.getFitSolver() == FitSolver.MLE && fitConfig.isModelCamera())
        name += " Camera";
    add(sb, name);
    add(sb, config.getFitting());
    resultPrefix = sb.toString();
    // Q. Should I add other fit configuration here?
    // The fraction of positive and negative candidates that were included
    add(sb, (100.0 * cTP) / nP);
    add(sb, (100.0 * cFP) / nN);
    // Score the fitting results compared to the original simulation.
    // Score the candidate selection:
    add(sb, cTP + cFP);
    add(sb, cTP);
    add(sb, cFP);
    // TP are all candidates that can be matched to a spot
    // FP are all candidates that cannot be matched to a spot
    // FN = The number of missed spots
    FractionClassificationResult m = new FractionClassificationResult(cTP, cFP, 0, simulationParameters.molecules - cTP);
    add(sb, m.getRecall());
    add(sb, m.getPrecision());
    add(sb, m.getF1Score());
    add(sb, m.getJaccard());
    // Score the fitting results:
    add(sb, failcTP);
    add(sb, failcFP);
    // TP are all fit results that can be matched to a spot
    // FP are all fit results that cannot be matched to a spot
    // FN = The number of missed spots
    add(sb, tp);
    add(sb, fp);
    m = new FractionClassificationResult(tp, fp, 0, simulationParameters.molecules - tp);
    add(sb, m.getRecall());
    add(sb, m.getPrecision());
    add(sb, m.getF1Score());
    add(sb, m.getJaccard());
    // Do it again but pretend we can perfectly filter all the false positives
    //add(sb, tp);
    m = new FractionClassificationResult(tp, 0, 0, simulationParameters.molecules - tp);
    // Recall is unchanged
    // Precision will be 100%
    add(sb, m.getF1Score());
    add(sb, m.getJaccard());
    // The mean may be subject to extreme outliers so use the median
    double median = distanceStats.getMedian();
    add(sb, median);
    WindowOrganiser wo = new WindowOrganiser();
    String label = String.format("Recall = %s. n = %d. Median = %s nm. SD = %s nm", Utils.rounded(m.getRecall()), distanceStats.getN(), Utils.rounded(median), Utils.rounded(distanceStats.getStandardDeviation()));
    int id = Utils.showHistogram(TITLE, distanceStats, "Match Distance (nm)", 0, 0, 0, label);
    if (Utils.isNewWindow())
        wo.add(id);
    median = depthStats.getMedian();
    add(sb, median);
    // Sort by spot intensity and produce correlation
    int[] indices = Utils.newArray(i1.length, 0, 1);
    if (showCorrelation)
        Sort.sort(indices, is, rankByIntensity);
    double[] r = (showCorrelation) ? new double[i1.length] : null;
    double[] sr = (showCorrelation) ? new double[i1.length] : null;
    double[] rank = (showCorrelation) ? new double[i1.length] : null;
    ci = 0;
    FastCorrelator fastCorrelator = new FastCorrelator();
    ArrayList<Ranking> pc1 = new ArrayList<Ranking>();
    ArrayList<Ranking> pc2 = new ArrayList<Ranking>();
    for (int ci2 : indices) {
        fastCorrelator.add((long) Math.round(i1[ci2]), (long) Math.round(i2[ci2]));
        pc1.add(new Ranking(i1[ci2], ci));
        pc2.add(new Ranking(i2[ci2], ci));
        if (showCorrelation) {
            r[ci] = fastCorrelator.getCorrelation();
            sr[ci] = Correlator.correlation(rank(pc1), rank(pc2));
            if (rankByIntensity)
                rank[ci] = is[0] - is[ci];
            else
                rank[ci] = ci;
        }
        ci++;
    }
    final double pearsonCorr = fastCorrelator.getCorrelation();
    final double rankedCorr = Correlator.correlation(rank(pc1), rank(pc2));
    // Get the regression
    SimpleRegression regression = new SimpleRegression(false);
    for (int i = 0; i < pc1.size(); i++) regression.addData(pc1.get(i).value, pc2.get(i).value);
    //final double intercept = regression.getIntercept();
    final double slope = regression.getSlope();
    if (showCorrelation) {
        String title = TITLE + " Intensity";
        Plot plot = new Plot(title, "Candidate", "Spot");
        double[] limits1 = Maths.limits(i1);
        double[] limits2 = Maths.limits(i2);
        plot.setLimits(limits1[0], limits1[1], limits2[0], limits2[1]);
        label = String.format("Correlation=%s; Ranked=%s; Slope=%s", Utils.rounded(pearsonCorr), Utils.rounded(rankedCorr), Utils.rounded(slope));
        plot.addLabel(0, 0, label);
        plot.setColor(Color.red);
        plot.addPoints(i1, i2, Plot.DOT);
        if (slope > 1)
            plot.drawLine(limits1[0], limits1[0] * slope, limits1[1], limits1[1] * slope);
        else
            plot.drawLine(limits2[0] / slope, limits2[0], limits2[1] / slope, limits2[1]);
        PlotWindow pw = Utils.display(title, plot);
        if (Utils.isNewWindow())
            wo.add(pw);
        title = TITLE + " Correlation";
        plot = new Plot(title, "Spot Rank", "Correlation");
        double[] xlimits = Maths.limits(rank);
        double[] ylimits = Maths.limits(r);
        ylimits = Maths.limits(ylimits, sr);
        plot.setLimits(xlimits[0], xlimits[1], ylimits[0], ylimits[1]);
        plot.setColor(Color.red);
        plot.addPoints(rank, r, Plot.LINE);
        plot.setColor(Color.blue);
        plot.addPoints(rank, sr, Plot.LINE);
        plot.setColor(Color.black);
        plot.addLabel(0, 0, label);
        pw = Utils.display(title, plot);
        if (Utils.isNewWindow())
            wo.add(pw);
    }
    add(sb, pearsonCorr);
    add(sb, rankedCorr);
    add(sb, slope);
    label = String.format("n = %d. Median = %s nm", depthStats.getN(), Utils.rounded(median));
    id = Utils.showHistogram(TITLE, depthStats, "Match Depth (nm)", 0, 1, 0, label);
    if (Utils.isNewWindow())
        wo.add(id);
    // Plot histograms of the stats on the same window
    double[] lower = new double[filterCriteria.length];
    double[] upper = new double[lower.length];
    min = new double[lower.length];
    max = new double[lower.length];
    for (int i = 0; i < stats[0].length; i++) {
        double[] limits = showDoubleHistogram(stats, i, wo, matchScores, nPredicted);
        lower[i] = limits[0];
        upper[i] = limits[1];
        min[i] = limits[2];
        max[i] = limits[3];
    }
    // Reconfigure some of the range limits
    // Make this a bit bigger
    upper[FILTER_SIGNAL] *= 2;
    // Make this a bit bigger
    upper[FILTER_SNR] *= 2;
    double factor = 0.25;
    if (lower[FILTER_MIN_WIDTH] != 0)
        // (assuming lower is less than 1)
        upper[FILTER_MIN_WIDTH] = 1 - Math.max(0, factor * (1 - lower[FILTER_MIN_WIDTH]));
    if (upper[FILTER_MIN_WIDTH] != 0)
        // (assuming upper is more than 1)
        lower[FILTER_MAX_WIDTH] = 1 + Math.max(0, factor * (upper[FILTER_MAX_WIDTH] - 1));
    // Round the ranges
    final double[] interval = new double[stats[0].length];
    interval[FILTER_SIGNAL] = SignalFilter.DEFAULT_INCREMENT;
    interval[FILTER_SNR] = SNRFilter.DEFAULT_INCREMENT;
    interval[FILTER_MIN_WIDTH] = WidthFilter2.DEFAULT_MIN_INCREMENT;
    interval[FILTER_MAX_WIDTH] = WidthFilter.DEFAULT_INCREMENT;
    interval[FILTER_SHIFT] = ShiftFilter.DEFAULT_INCREMENT;
    interval[FILTER_ESHIFT] = EShiftFilter.DEFAULT_INCREMENT;
    interval[FILTER_PRECISION] = PrecisionFilter.DEFAULT_INCREMENT;
    interval[FILTER_ITERATIONS] = 0.1;
    interval[FILTER_EVALUATIONS] = 0.1;
    // Create a range increment
    double[] increment = new double[lower.length];
    for (int i = 0; i < increment.length; i++) {
        lower[i] = Maths.floor(lower[i], interval[i]);
        upper[i] = Maths.ceil(upper[i], interval[i]);
        double range = upper[i] - lower[i];
        // Allow clipping if the range is small compared to the min increment
        double multiples = range / interval[i];
        // Use 8 multiples for the equivalent of +/- 4 steps around the centre
        if (multiples < 8) {
            multiples = Math.ceil(multiples);
        } else
            multiples = 8;
        increment[i] = Maths.ceil(range / multiples, interval[i]);
        if (i == FILTER_MIN_WIDTH)
            // Requires clipping based on the upper limit
            lower[i] = upper[i] - increment[i] * multiples;
        else
            upper[i] = lower[i] + increment[i] * multiples;
    }
    for (int i = 0; i < stats[0].length; i++) {
        lower[i] = Maths.round(lower[i]);
        upper[i] = Maths.round(upper[i]);
        min[i] = Maths.round(min[i]);
        max[i] = Maths.round(max[i]);
        increment[i] = Maths.round(increment[i]);
        sb.append("\t").append(min[i]).append(':').append(lower[i]).append('-').append(upper[i]).append(':').append(max[i]);
    }
    // Disable some filters
    increment[FILTER_SIGNAL] = Double.POSITIVE_INFINITY;
    //increment[FILTER_SHIFT] = Double.POSITIVE_INFINITY;
    increment[FILTER_ESHIFT] = Double.POSITIVE_INFINITY;
    wo.tile();
    sb.append("\t").append(Utils.timeToString(runTime / 1000000.0));
    summaryTable.append(sb.toString());
    if (saveFilterRange) {
        GlobalSettings gs = SettingsManager.loadSettings();
        FilterSettings filterSettings = gs.getFilterSettings();
        String filename = (silent) ? filterSettings.filterSetFilename : Utils.getFilename("Filter_range_file", filterSettings.filterSetFilename);
        if (filename == null)
            return;
        // Remove extension to store the filename
        filename = Utils.replaceExtension(filename, ".xml");
        filterSettings.filterSetFilename = filename;
        // Create a filter set using the ranges
        ArrayList<Filter> filters = new ArrayList<Filter>(3);
        filters.add(new MultiFilter2(lower[0], (float) lower[1], lower[2], lower[3], lower[4], lower[5], lower[6]));
        filters.add(new MultiFilter2(upper[0], (float) upper[1], upper[2], upper[3], upper[4], upper[5], upper[6]));
        filters.add(new MultiFilter2(increment[0], (float) increment[1], increment[2], increment[3], increment[4], increment[5], increment[6]));
        if (saveFilters(filename, filters))
            SettingsManager.saveSettings(gs);
        // Create a filter set using the min/max and the initial bounds.
        // Set sensible limits
        min[FILTER_SIGNAL] = Math.max(min[FILTER_SIGNAL], 30);
        max[FILTER_PRECISION] = Math.min(max[FILTER_PRECISION], 100);
        // Commented this out so that the 4-set filters are the same as the 3-set filters.
        // The difference leads to differences when optimising.
        //			// Use half the initial bounds (hoping this is a good starting guess for the optimum)
        //			final boolean[] limitToLower = new boolean[min.length];
        //			limitToLower[FILTER_SIGNAL] = true;
        //			limitToLower[FILTER_SNR] = true;
        //			limitToLower[FILTER_MIN_WIDTH] = true;
        //			limitToLower[FILTER_MAX_WIDTH] = false;
        //			limitToLower[FILTER_SHIFT] = false;
        //			limitToLower[FILTER_ESHIFT] = false;
        //			limitToLower[FILTER_PRECISION] = true;
        //			for (int i = 0; i < limitToLower.length; i++)
        //			{
        //				final double range = (upper[i] - lower[i]) / 2;
        //				if (limitToLower[i])
        //					upper[i] = lower[i] + range;
        //				else
        //					lower[i] = upper[i] - range;
        //			}
        filters = new ArrayList<Filter>(4);
        filters.add(new MultiFilter2(min[0], (float) min[1], min[2], min[3], min[4], min[5], min[6]));
        filters.add(new MultiFilter2(lower[0], (float) lower[1], lower[2], lower[3], lower[4], lower[5], lower[6]));
        filters.add(new MultiFilter2(upper[0], (float) upper[1], upper[2], upper[3], upper[4], upper[5], upper[6]));
        filters.add(new MultiFilter2(max[0], (float) max[1], max[2], max[3], max[4], max[5], max[6]));
        saveFilters(Utils.replaceExtension(filename, ".4.xml"), filters);
    }
}
Also used : ArrayList(java.util.ArrayList) TIntHashSet(gnu.trove.set.hash.TIntHashSet) MultiPathFitResult(gdsc.smlm.results.filter.MultiPathFitResult) FractionalAssignment(gdsc.core.match.FractionalAssignment) PeakFractionalAssignment(gdsc.smlm.results.filter.PeakFractionalAssignment) ImmutableFractionalAssignment(gdsc.core.match.ImmutableFractionalAssignment) FractionClassificationResult(gdsc.core.match.FractionClassificationResult) BasePreprocessedPeakResult(gdsc.smlm.results.filter.BasePreprocessedPeakResult) PreprocessedPeakResult(gdsc.smlm.results.filter.PreprocessedPeakResult) SignalFilter(gdsc.smlm.results.filter.SignalFilter) FilterSettings(gdsc.smlm.ij.settings.FilterSettings) ScoredSpot(gdsc.smlm.ij.plugins.BenchmarkSpotFilter.ScoredSpot) FastCorrelator(gdsc.core.utils.FastCorrelator) Plot(ij.gui.Plot) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) PlotWindow(ij.gui.PlotWindow) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) WindowOrganiser(ij.plugin.WindowOrganiser) PeakResultPoint(gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint) BasePoint(gdsc.core.match.BasePoint) PeakFractionalAssignment(gdsc.smlm.results.filter.PeakFractionalAssignment) FractionScoreStore(gdsc.smlm.results.filter.MultiPathFilter.FractionScoreStore) SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) SignalFilter(gdsc.smlm.results.filter.SignalFilter) DirectFilter(gdsc.smlm.results.filter.DirectFilter) ShiftFilter(gdsc.smlm.results.filter.ShiftFilter) PrecisionFilter(gdsc.smlm.results.filter.PrecisionFilter) Filter(gdsc.smlm.results.filter.Filter) EShiftFilter(gdsc.smlm.results.filter.EShiftFilter) WidthFilter(gdsc.smlm.results.filter.WidthFilter) SNRFilter(gdsc.smlm.results.filter.SNRFilter) MultiPathFilter(gdsc.smlm.results.filter.MultiPathFilter) MaximaSpotFilter(gdsc.smlm.filters.MaximaSpotFilter) MultiFilter2(gdsc.smlm.results.filter.MultiFilter2) MultiPathFitResults(gdsc.smlm.results.filter.MultiPathFitResults) MultiPathFilter(gdsc.smlm.results.filter.MultiPathFilter)

Example 17 with GlobalSettings

use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.

the class BenchmarkFit method showDialog.

private boolean showDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    final double sa = getSa();
    gd.addMessage(String.format("Fits the benchmark image created by CreateData plugin.\nPSF width = %s, adjusted = %s", Utils.rounded(benchmarkParameters.s / benchmarkParameters.a), Utils.rounded(sa)));
    // For each new benchmark width, reset the PSF width to the square pixel adjustment
    if (lastS != benchmarkParameters.s) {
        lastS = benchmarkParameters.s;
        psfWidth = sa;
    }
    final String filename = SettingsManager.getSettingsFilename();
    GlobalSettings settings = SettingsManager.loadSettings(filename);
    fitConfig = settings.getFitEngineConfiguration().getFitConfiguration();
    fitConfig.setNmPerPixel(benchmarkParameters.a);
    gd.addSlider("Region_size", 2, 20, regionSize);
    gd.addNumericField("PSF_width", psfWidth, 3);
    String[] solverNames = SettingsManager.getNames((Object[]) FitSolver.values());
    gd.addChoice("Fit_solver", solverNames, solverNames[fitConfig.getFitSolver().ordinal()]);
    String[] functionNames = SettingsManager.getNames((Object[]) FitFunction.values());
    gd.addChoice("Fit_function", functionNames, functionNames[fitConfig.getFitFunction().ordinal()]);
    gd.addCheckbox("Offset_fit", offsetFitting);
    gd.addNumericField("Start_offset", startOffset, 3);
    gd.addCheckbox("Include_CoM_fit", comFitting);
    gd.addCheckbox("Background_fitting", backgroundFitting);
    gd.addMessage("Signal fitting can be disabled for " + FitFunction.FIXED.toString() + " function");
    gd.addCheckbox("Signal_fitting", signalFitting);
    gd.addCheckbox("Show_histograms", showHistograms);
    gd.addCheckbox("Save_raw_data", saveRawData);
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    regionSize = (int) Math.abs(gd.getNextNumber());
    psfWidth = Math.abs(gd.getNextNumber());
    fitConfig.setFitSolver(gd.getNextChoiceIndex());
    fitConfig.setFitFunction(gd.getNextChoiceIndex());
    offsetFitting = gd.getNextBoolean();
    startOffset = Math.abs(gd.getNextNumber());
    comFitting = gd.getNextBoolean();
    backgroundFitting = gd.getNextBoolean();
    signalFitting = gd.getNextBoolean();
    showHistograms = gd.getNextBoolean();
    saveRawData = gd.getNextBoolean();
    if (!comFitting && !offsetFitting) {
        IJ.error(TITLE, "No initial fitting positions");
        return false;
    }
    if (regionSize < 1)
        regionSize = 1;
    if (gd.invalidNumber())
        return false;
    // Initialise the correct calibration
    Calibration calibration = settings.getCalibration();
    calibration.setNmPerPixel(benchmarkParameters.a);
    calibration.setGain(benchmarkParameters.gain);
    calibration.setAmplification(benchmarkParameters.amplification);
    calibration.setBias(benchmarkParameters.bias);
    calibration.setEmCCD(benchmarkParameters.emCCD);
    calibration.setReadNoise(benchmarkParameters.readNoise);
    calibration.setExposureTime(1000);
    if (!PeakFit.configureFitSolver(settings, filename, false))
        return false;
    if (showHistograms) {
        gd = new GenericDialog(TITLE);
        gd.addMessage("Select the histograms to display");
        gd.addNumericField("Histogram_bins", histogramBins, 0);
        double[] convert = getConversionFactors();
        for (int i = 0; i < displayHistograms.length; i++) if (convert[i] != 0)
            gd.addCheckbox(NAMES[i].replace(' ', '_'), displayHistograms[i]);
        gd.showDialog();
        if (gd.wasCanceled())
            return false;
        histogramBins = (int) Math.abs(gd.getNextNumber());
        for (int i = 0; i < displayHistograms.length; i++) if (convert[i] != 0)
            displayHistograms[i] = gd.getNextBoolean();
    }
    return true;
}
Also used : GenericDialog(ij.gui.GenericDialog) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) Calibration(gdsc.smlm.results.Calibration)

Example 18 with GlobalSettings

use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.

the class BenchmarkFilterAnalysis method saveTemplate.

/**
	 * Save PeakFit configuration template using the current benchmark settings.
	 * 
	 * @param topFilterSummary
	 */
private void saveTemplate(String topFilterSummary) {
    FitEngineConfiguration config = new FitEngineConfiguration(new FitConfiguration());
    if (!updateAllConfiguration(config, true)) {
        IJ.log("Unable to create the template configuration");
        return;
    }
    // Remove the PSF width to make the template generic
    config.getFitConfiguration().setInitialPeakStdDev(0);
    String filename = getFilename("Template_File", templateFilename);
    if (filename != null) {
        templateFilename = filename;
        Prefs.set(KEY_TEMPLATE_FILENAME, filename);
        GlobalSettings settings = new GlobalSettings();
        settings.setNotes(getNotes(topFilterSummary));
        settings.setFitEngineConfiguration(config);
        if (!SettingsManager.saveSettings(settings, filename, true)) {
            IJ.log("Unable to save the template configuration");
            return;
        }
        // Save some random frames from the test image data
        ImagePlus imp = CreateData.getImage();
        if (imp == null)
            return;
        // Get the number of frames
        final ImageStack stack = imp.getImageStack();
        if (sampler == null || sampler.getResults() != results) {
            sampler = new ResultsImageSampler(results, stack, 32);
            sampler.analyse();
        }
        if (!sampler.isValid())
            return;
        // Iteratively show the example until the user is happy.
        // Yes = OK, No = Repeat, Cancel = Do not save
        String keyNo = "nNo";
        String keyLow = "nLower";
        String keyHigh = "nHigher";
        if (Utils.isMacro()) {
            // Collect the options if running in a macro
            String options = Macro.getOptions();
            nNo = Integer.parseInt(Macro.getValue(options, keyNo, Integer.toString(nNo)));
            nLow = Integer.parseInt(Macro.getValue(options, keyLow, Integer.toString(nLow)));
            nHigh = Integer.parseInt(Macro.getValue(options, keyHigh, Integer.toString(nHigh)));
        } else {
            if (nLow + nHigh == 0)
                nLow = nHigh = 1;
        }
        final ImagePlus[] out = new ImagePlus[1];
        out[0] = sampler.getSample(nNo, nLow, nHigh);
        if (!Utils.isMacro()) {
            // Show the template results
            final ConfigurationTemplate configTemplate = new ConfigurationTemplate();
            // Interactively show the sample image data
            final boolean[] close = new boolean[1];
            final ImagePlus[] outImp = new ImagePlus[1];
            if (out[0] != null) {
                outImp[0] = display(out[0]);
                if (Utils.isNewWindow()) {
                    close[0] = true;
                    // Zoom a bit
                    ImageWindow iw = outImp[0].getWindow();
                    for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                        iw.getCanvas().zoomIn(0, 0);
                    }
                }
                configTemplate.createResults(outImp[0]);
            }
            // TODO - fix this when a second sample is made as the results are not updated.
            ImageListener listener = new ImageListener() {

                public void imageOpened(ImagePlus imp) {
                }

                public void imageClosed(ImagePlus imp) {
                }

                public void imageUpdated(ImagePlus imp) {
                    if (imp != null && imp == outImp[0]) {
                        configTemplate.updateResults(imp.getCurrentSlice());
                    }
                }
            };
            ImagePlus.addImageListener(listener);
            // For the dialog
            String msg = String.format("Showing image data for the template example.\n \nSample Frames:\nEmpty = %d\nLower density = %d\nHigher density = %d\n", sampler.getNumberOfEmptySamples(), sampler.getNumberOfLowDensitySamples(), sampler.getNumberOfHighDensitySamples());
            // Turn off the recorder when the dialog is showing
            boolean record = Recorder.record;
            Recorder.record = false;
            NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
            gd.addMessage(msg);
            //gd.enableYesNoCancel(" Save ", " Resample ");
            gd.addSlider(keyNo, 0, 10, nNo);
            gd.addSlider(keyLow, 0, 10, nLow);
            gd.addSlider(keyHigh, 0, 10, nHigh);
            gd.addDialogListener(new DialogListener() {

                public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
                    // image the user has not seen.
                    if (e == null)
                        return true;
                    nNo = (int) gd.getNextNumber();
                    nLow = (int) gd.getNextNumber();
                    nHigh = (int) gd.getNextNumber();
                    out[0] = sampler.getSample(nNo, nLow, nHigh);
                    if (out[0] != null) {
                        outImp[0] = display(out[0]);
                        if (Utils.isNewWindow()) {
                            close[0] = true;
                            // Zoom a bit
                            ImageWindow iw = outImp[0].getWindow();
                            for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                                iw.getCanvas().zoomIn(0, 0);
                            }
                        }
                        configTemplate.createResults(outImp[0]);
                    }
                    return true;
                }
            });
            gd.showDialog();
            if (gd.wasCanceled()) {
                out[0] = null;
                // For the recorder
                nNo = nLow = nHigh = 0;
            }
            if (close[0]) {
                // Because closing the image sets the stack pixels array to null
                if (out[0] != null)
                    out[0] = out[0].duplicate();
                outImp[0].close();
            }
            configTemplate.closeResults();
            ImagePlus.removeImageListener(listener);
            if (record) {
                Recorder.record = true;
                Recorder.recordOption(keyNo, Integer.toString(nNo));
                Recorder.recordOption(keyLow, Integer.toString(nLow));
                Recorder.recordOption(keyHigh, Integer.toString(nHigh));
            }
        }
        if (out[0] == null)
            return;
        ImagePlus example = out[0];
        filename = Utils.replaceExtension(filename, ".tif");
        IJ.save(example, filename);
    }
}
Also used : ResultsImageSampler(gdsc.smlm.ij.results.ResultsImageSampler) ImageWindow(ij.gui.ImageWindow) ImageStack(ij.ImageStack) ImageListener(ij.ImageListener) FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) FitConfiguration(gdsc.smlm.fitting.FitConfiguration) DialogListener(ij.gui.DialogListener) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) AWTEvent(java.awt.AWTEvent)

Example 19 with GlobalSettings

use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.

the class PSFCreator method fitPSF.

/**
	 * Fit the new PSF image and show a graph of the amplitude/width
	 * 
	 * @param psf
	 * @param loess
	 * @param averageRange
	 * @param fitCom
	 * @return The width of the PSF in the z-centre
	 */
private double fitPSF(ImageStack psf, LoessInterpolator loess, int cz, double averageRange, double[][] fitCom) {
    IJ.showStatus("Fitting final PSF");
    // is not appropriate for a normalised PSF. 
    if (fitConfig.getFitSolver() == FitSolver.MLE) {
        Utils.log("  Maximum Likelihood Estimation (MLE) is not appropriate for final PSF fitting.");
        Utils.log("  Switching to Least Square Estimation");
        fitConfig.setFitSolver(FitSolver.LVM);
        if (interactiveMode) {
            GlobalSettings settings = new GlobalSettings();
            settings.setFitEngineConfiguration(config);
            PeakFit.configureFitSolver(settings, null, false, false);
        }
    }
    // Update the box radius since this is used in the fitSpot method.
    boxRadius = psf.getWidth() / 2;
    int x = boxRadius, y = boxRadius;
    FitConfiguration fitConfig = config.getFitConfiguration();
    final double shift = fitConfig.getCoordinateShiftFactor();
    fitConfig.setInitialPeakStdDev0(fitConfig.getInitialPeakStdDev0() * magnification);
    fitConfig.setInitialPeakStdDev1(fitConfig.getInitialPeakStdDev1() * magnification);
    // Need to be updated after the widths have been set
    fitConfig.setCoordinateShiftFactor(shift);
    fitConfig.setBackgroundFitting(false);
    // Since the PSF will be normalised
    fitConfig.setMinPhotons(0);
    //fitConfig.setLog(new IJLogger());
    MemoryPeakResults results = fitSpot(psf, psf.getWidth(), psf.getHeight(), x, y);
    if (results.size() < 5) {
        Utils.log("  Final PSF: Not enough fit results %d", results.size());
        return 0;
    }
    // Get the results for the spot centre and width
    double[] z = new double[results.size()];
    double[] xCoord = new double[z.length];
    double[] yCoord = new double[z.length];
    double[] sd = new double[z.length];
    double[] a = new double[z.length];
    int i = 0;
    // Set limits for the fit
    final float maxWidth = (float) (FastMath.max(fitConfig.getInitialPeakStdDev0(), fitConfig.getInitialPeakStdDev1()) * magnification * 4);
    // PSF is normalised to 1  
    final float maxSignal = 2;
    for (PeakResult peak : results.getResults()) {
        // Remove bad fits where the width/signal is above the expected
        final float w = FastMath.max(peak.getXSD(), peak.getYSD());
        if (peak.getSignal() > maxSignal || w > maxWidth)
            continue;
        z[i] = peak.getFrame();
        fitCom[0][peak.getFrame() - 1] = xCoord[i] = peak.getXPosition() - x;
        fitCom[1][peak.getFrame() - 1] = yCoord[i] = peak.getYPosition() - y;
        sd[i] = w;
        a[i] = peak.getAmplitude();
        i++;
    }
    // Truncate
    z = Arrays.copyOf(z, i);
    xCoord = Arrays.copyOf(xCoord, i);
    yCoord = Arrays.copyOf(yCoord, i);
    sd = Arrays.copyOf(sd, i);
    a = Arrays.copyOf(a, i);
    // Extract the average smoothed range from the individual fits
    int r = (int) Math.ceil(averageRange / 2);
    int start = 0, stop = z.length - 1;
    for (int j = 0; j < z.length; j++) {
        if (z[j] > cz - r) {
            start = j;
            break;
        }
    }
    for (int j = z.length; j-- > 0; ) {
        if (z[j] < cz + r) {
            stop = j;
            break;
        }
    }
    // Extract xy centre coords and smooth
    double[] smoothX = new double[stop - start + 1];
    double[] smoothY = new double[smoothX.length];
    double[] smoothSd = new double[smoothX.length];
    double[] smoothA = new double[smoothX.length];
    double[] newZ = new double[smoothX.length];
    int smoothCzIndex = 0;
    for (int j = start, k = 0; j <= stop; j++, k++) {
        smoothX[k] = xCoord[j];
        smoothY[k] = yCoord[j];
        smoothSd[k] = sd[j];
        smoothA[k] = a[j];
        newZ[k] = z[j];
        if (newZ[k] == cz)
            smoothCzIndex = k;
    }
    smoothX = loess.smooth(newZ, smoothX);
    smoothY = loess.smooth(newZ, smoothY);
    smoothSd = loess.smooth(newZ, smoothSd);
    smoothA = loess.smooth(newZ, smoothA);
    // Update the widths and positions using the magnification
    final double scale = 1.0 / magnification;
    for (int j = 0; j < xCoord.length; j++) {
        xCoord[j] *= scale;
        yCoord[j] *= scale;
        sd[j] *= scale;
    }
    for (int j = 0; j < smoothX.length; j++) {
        smoothX[j] *= scale;
        smoothY[j] *= scale;
        smoothSd[j] *= scale;
    }
    showPlots(z, a, newZ, smoothA, xCoord, yCoord, sd, newZ, smoothX, smoothY, smoothSd, cz);
    // Store the data for replotting
    this.z = z;
    this.a = a;
    this.smoothAz = newZ;
    this.smoothA = smoothA;
    this.xCoord = xCoord;
    this.yCoord = yCoord;
    this.sd = sd;
    this.newZ = newZ;
    this.smoothX = smoothX;
    this.smoothY = smoothY;
    this.smoothSd = smoothSd;
    //maximumIndex = findMinimumIndex(smoothSd, maximumIndex - start);
    return smoothSd[smoothCzIndex];
}
Also used : FitConfiguration(gdsc.smlm.fitting.FitConfiguration) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) Point(java.awt.Point) BasePoint(gdsc.core.match.BasePoint) PeakResult(gdsc.smlm.results.PeakResult)

Example 20 with GlobalSettings

use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.

the class PSFDrift method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    // Build a list of suitable images
    List<String> titles = createImageList();
    if (titles.isEmpty()) {
        IJ.error(TITLE, "No suitable PSF images");
        return;
    }
    if ("hwhm".equals(arg)) {
        showHWHM(titles);
        return;
    }
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage("Select the input PSF image");
    gd.addChoice("PSF", titles.toArray(new String[titles.size()]), title);
    gd.addCheckbox("Use_offset", useOffset);
    gd.addNumericField("Scale", scale, 2);
    gd.addNumericField("z_depth", zDepth, 2, 6, "nm");
    gd.addNumericField("Grid_size", gridSize, 0);
    gd.addSlider("Recall_limit", 0.01, 1, recallLimit);
    gd.addSlider("Region_size", 2, 20, regionSize);
    gd.addCheckbox("Background_fitting", backgroundFitting);
    String[] solverNames = SettingsManager.getNames((Object[]) FitSolver.values());
    gd.addChoice("Fit_solver", solverNames, solverNames[fitConfig.getFitSolver().ordinal()]);
    String[] functionNames = SettingsManager.getNames((Object[]) FitFunction.values());
    gd.addChoice("Fit_function", functionNames, functionNames[fitConfig.getFitFunction().ordinal()]);
    // We need these to set bounds for any bounded fitters
    gd.addSlider("Min_width_factor", 0, 0.99, fitConfig.getMinWidthFactor());
    gd.addSlider("Width_factor", 1.01, 5, fitConfig.getWidthFactor());
    gd.addCheckbox("Offset_fit", offsetFitting);
    gd.addNumericField("Start_offset", startOffset, 3);
    gd.addCheckbox("Include_CoM_fit", comFitting);
    gd.addCheckbox("Use_sampling", useSampling);
    gd.addNumericField("Photons", photons, 0);
    gd.addSlider("Photon_limit", 0, 1, photonLimit);
    gd.addSlider("Smoothing", 0, 0.5, smoothing);
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    title = gd.getNextChoice();
    useOffset = gd.getNextBoolean();
    scale = gd.getNextNumber();
    zDepth = gd.getNextNumber();
    gridSize = (int) gd.getNextNumber();
    recallLimit = gd.getNextNumber();
    regionSize = (int) Math.abs(gd.getNextNumber());
    backgroundFitting = gd.getNextBoolean();
    fitConfig.setFitSolver(gd.getNextChoiceIndex());
    fitConfig.setFitFunction(gd.getNextChoiceIndex());
    fitConfig.setMinWidthFactor(gd.getNextNumber());
    fitConfig.setWidthFactor(gd.getNextNumber());
    offsetFitting = gd.getNextBoolean();
    startOffset = Math.abs(gd.getNextNumber());
    comFitting = gd.getNextBoolean();
    useSampling = gd.getNextBoolean();
    photons = Math.abs(gd.getNextNumber());
    photonLimit = Math.abs(gd.getNextNumber());
    smoothing = Math.abs(gd.getNextNumber());
    if (!comFitting && !offsetFitting) {
        IJ.error(TITLE, "No initial fitting positions");
        return;
    }
    if (regionSize < 1)
        regionSize = 1;
    if (gd.invalidNumber())
        return;
    GlobalSettings settings = new GlobalSettings();
    settings.setFitEngineConfiguration(new FitEngineConfiguration(fitConfig));
    if (!PeakFit.configureFitSolver(settings, null, false, true))
        return;
    imp = WindowManager.getImage(title);
    if (imp == null) {
        IJ.error(TITLE, "No PSF image for image: " + title);
        return;
    }
    psfSettings = getPSFSettings(imp);
    if (psfSettings == null) {
        IJ.error(TITLE, "No PSF settings for image: " + title);
        return;
    }
    computeDrift();
}
Also used : FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GenericDialog(ij.gui.GenericDialog) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings)

Aggregations

GlobalSettings (gdsc.smlm.ij.settings.GlobalSettings)34 FitEngineConfiguration (gdsc.smlm.engine.FitEngineConfiguration)9 GenericDialog (ij.gui.GenericDialog)9 FitConfiguration (gdsc.smlm.fitting.FitConfiguration)8 Checkbox (java.awt.Checkbox)7 ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)6 Choice (java.awt.Choice)6 BasePoint (gdsc.core.match.BasePoint)5 FilterSettings (gdsc.smlm.ij.settings.FilterSettings)5 PeakResultPoint (gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint)4 Calibration (gdsc.smlm.results.Calibration)4 Point (java.awt.Point)4 TextField (java.awt.TextField)4 Vector (java.util.Vector)4 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)3 DirectFilter (gdsc.smlm.results.filter.DirectFilter)3 MultiPathFilter (gdsc.smlm.results.filter.MultiPathFilter)3 ImagePlus (ij.ImagePlus)3 OpenDialog (ij.io.OpenDialog)3 File (java.io.File)3