Search in sources :

Example 6 with ConversionException

use of uk.ac.sussex.gdsc.core.data.utils.ConversionException in project GDSC-SMLM by aherbert.

the class AstigmatismModelManager method viewModel.

private void viewModel() {
    final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    final String[] models = listAstigmatismModels(false);
    gd.addChoice("Model", models, pluginSettings.getSelected());
    gd.addChoice("z_distance_unit", SettingsManager.getDistanceUnitNames(), pluginSettings.getZDistanceUnitValue());
    gd.addChoice("s_distance_unit", SettingsManager.getDistanceUnitNames(), pluginSettings.getSDistanceUnitValue());
    gd.addCheckbox("Show_depth_of_focus", pluginSettings.getShowDepthOfFocus());
    gd.addCheckbox("Show_combined_width", pluginSettings.getShowCombinedWidth());
    gd.addCheckbox("Show_PSF", pluginSettings.getShowPsf());
    gd.addHelp(HelpUrls.getUrl("astigmatism-model-manager-view"));
    gd.showDialog();
    if (gd.wasCanceled()) {
        return;
    }
    final String name = gd.getNextChoice();
    pluginSettings.setSelected(name);
    pluginSettings.setZDistanceUnitValue(gd.getNextChoiceIndex());
    pluginSettings.setSDistanceUnitValue(gd.getNextChoiceIndex());
    pluginSettings.setShowDepthOfFocus(gd.getNextBoolean());
    pluginSettings.setShowCombinedWidth(gd.getNextBoolean());
    pluginSettings.setShowPsf(gd.getNextBoolean());
    // Try and get the named resource
    AstigmatismModel model = AstigmatismModelSettingsHolder.getSettings().getAstigmatismModelResourcesMap().get(name);
    if (model == null) {
        IJ.error(TITLE, "Failed to find astigmatism model: " + name);
        return;
    }
    try {
        model = convert(model, pluginSettings.getZDistanceUnit(), pluginSettings.getSDistanceUnit());
    } catch (final ConversionException ex) {
        ImageJUtils.log("Bad conversion (%s), defaulting to native model units", ex.getMessage());
    }
    ImageJUtils.log("Astigmatism model: %s\n%s", name, model);
    // Plot the curve. Do this so we encompass twice the depth-of-field.
    final double gamma = model.getGamma();
    final double d = model.getD();
    final double s0x = model.getS0X();
    final double Ax = model.getAx();
    final double Bx = model.getBx();
    final double s0y = model.getS0Y();
    final double Ay = model.getAy();
    final double By = model.getBy();
    final double range = Math.abs(gamma) + 1.5 * d;
    final int n = 200;
    final double step = range / n;
    final double[] z = new double[2 * n + 1];
    final double[] sx = new double[z.length];
    final double[] sy = new double[z.length];
    // Use the same class that is used during fitting
    final HoltzerAstigmatismZModel m = HoltzerAstigmatismZModel.create(s0x, s0y, gamma, d, Ax, Bx, Ay, By);
    for (int i = 0; i < z.length; i++) {
        final double zz = -range + i * step;
        z[i] = zz;
        sx[i] = m.getSx(zz);
        sy[i] = m.getSy(zz);
    }
    final String title = TITLE + " Width Curve";
    final Plot plot = new Plot(title, "Z (" + UnitHelper.getShortName(model.getZDistanceUnit()) + ")", "Width (" + UnitHelper.getShortName(model.getSDistanceUnit()) + ")");
    double[] limits = MathUtils.limits(sx);
    limits = MathUtils.limits(limits, sy);
    final double rangex = (z[z.length - 1] - z[0]) * 0.05;
    final double rangey = (limits[1] - limits[0]) * 0.05;
    final double miny = limits[0] - rangey;
    final double maxy = limits[1] + rangey;
    plot.setLimits(z[0] - rangex, z[z.length - 1] + rangex, miny, maxy);
    plot.setColor(Color.RED);
    plot.addPoints(z, sx, Plot.LINE);
    plot.setColor(Color.BLUE);
    plot.addPoints(z, sy, Plot.LINE);
    plot.setColor(Color.YELLOW);
    if (pluginSettings.getShowDepthOfFocus()) {
        final double z0x = gamma;
        final double z0y = -gamma;
        plot.setColor(Color.RED.darker());
        plot.drawDottedLine(z0x - d, miny, z0x - d, maxy, 4);
        plot.drawDottedLine(z0x + d, miny, z0x + d, maxy, 4);
        plot.setColor(Color.BLUE.darker());
        plot.drawDottedLine(z0y - d, miny, z0y - d, maxy, 4);
        plot.drawDottedLine(z0y + d, miny, z0y + d, maxy, 4);
    }
    String legend = "Sx\nSy";
    if (pluginSettings.getShowCombinedWidth()) {
        final double[] s = new double[z.length];
        for (int i = 0; i < z.length; i++) {
            s[i] = Gaussian2DPeakResultHelper.getStandardDeviation(sx[i], sy[i]);
        }
        plot.setColor(Color.GREEN);
        plot.addPoints(z, s, Plot.LINE);
        legend += "\tS";
    }
    plot.setColor(Color.BLACK);
    plot.addLegend(legend);
    plot.addLabel(0, 0, String.format("Model = %s (%s nm/pixel)", name, MathUtils.rounded(model.getNmPerPixel())));
    ImageJUtils.display(title, plot);
    if (!pluginSettings.getShowPsf()) {
        return;
    }
    // Get pixel range using 3x[max SD]
    final int width = 1 + 2 * ((int) Math.ceil(limits[1] * 3));
    new ModelRenderer(name, model, m, range, width, plot).run();
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) AstigmatismModel(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel) Plot(ij.gui.Plot) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) HoltzerAstigmatismZModel(uk.ac.sussex.gdsc.smlm.function.gaussian.HoltzerAstigmatismZModel)

Example 7 with ConversionException

use of uk.ac.sussex.gdsc.core.data.utils.ConversionException in project GDSC-SMLM by aherbert.

the class PeakResultTableModel method createTableStructure.

/**
 * Called when the structure of the table should be created. If the structure has not changed or
 * no live table are attached then this does nothing.
 *
 * @param changed Set to true if a property controlling the structure has changed
 */
private void createTableStructure(boolean changed) {
    if (changed) {
        columnsComputed.set(false);
    }
    // so it can be turned off by PeakResultTableModelFrame.
    if (liveCount.get() == 0 || columnsComputed.get()) {
        return;
    }
    columnsComputed.set(true);
    rounder = RounderUtils.create(tableSettings.getRoundingPrecision());
    // Create the converters
    final PeakResultConversionHelper helper = new PeakResultConversionHelper(calibration, psf);
    helper.setIntensityUnit(tableSettings.getIntensityUnit());
    helper.setDistanceUnit(tableSettings.getDistanceUnit());
    helper.setAngleUnit(tableSettings.getAngleUnit());
    final Converter[] converters = helper.getConverters();
    final Converter ic = converters[PeakResult.INTENSITY];
    final String[] paramNames = helper.getNames();
    final String[] unitNames = helper.getUnitNames();
    // Calibration tableCalibration = (helper.isCalibrationChanged()) ? helper.getCalibration() :
    // calibration;
    // Organise the data columns.
    // This is done as per the IJTablePeakResults for consistency
    final LocalList<PeakResultData<?>> valuesList = new LocalList<>();
    final LocalList<String> namesList = new LocalList<>();
    rowCounter = tableSettings.getShowRowCounter();
    if (rowCounter) {
        valuesList.add(new PeakResultDataFrame());
        namesList.add("#");
    }
    valuesList.add(new PeakResultDataFrame());
    addName(valuesList, namesList);
    if (showEndFrame) {
        valuesList.add(new PeakResultDataEndFrame());
        addName(valuesList, namesList);
    }
    if (showId) {
        valuesList.add(new PeakResultDataId());
        addName(valuesList, namesList);
    }
    if (showCategory) {
        valuesList.add(new PeakResultDataCategory());
        addName(valuesList, namesList);
    }
    if (tableSettings.getShowFittingData()) {
        valuesList.add(new PeakResultDataOrigX());
        addName(valuesList, namesList);
        valuesList.add(new PeakResultDataOrigY());
        addName(valuesList, namesList);
        valuesList.add(new PeakResultDataOrigValue());
        addName(valuesList, namesList);
        valuesList.add(new PeakResultDataError());
        addName(valuesList, namesList);
    }
    if (tableSettings.getShowNoiseData()) {
        // Must be converted
        valuesList.add(new PeakResultDataFloat() {

            @Override
            public Float getValue(PeakResult result) {
                return ic.convert(result.getNoise());
            }
        });
        addName("Noise", namesList, unitNames[PeakResult.INTENSITY]);
        valuesList.add(new PeakResultDataFloat() {

            @Override
            public Float getValue(PeakResult result) {
                return ic.convert(result.getMeanIntensity());
            }
        });
        addName("Mean" + paramNames[PeakResult.INTENSITY], namesList, unitNames[PeakResult.INTENSITY]);
        valuesList.add(new PeakResultDataSnr());
        addName(valuesList, namesList);
    }
    int[] outIndices = SimpleArrayUtils.natural(converters.length);
    if (!showZ) {
        final TIntArrayList list = new TIntArrayList(outIndices);
        list.remove(PeakResult.Z);
        outIndices = list.toArray();
    }
    for (final int i : outIndices) {
        // Must be converted
        valuesList.add(new PeakResultDataParameterConverter(converters[i], i));
        addName(paramNames[i], namesList, unitNames[i]);
        if (showDeviations) {
            valuesList.add(new PeakResultDataParameterDeviationConverter(converters[i], i));
            namesList.add("+/-");
        }
    }
    if (tableSettings.getShowPrecision()) {
        PeakResultDataPrecision precision = null;
        try {
            final Gaussian2DPeakResultCalculator calculator = Gaussian2DPeakResultHelper.create(getPsf(), calibration, Gaussian2DPeakResultHelper.LSE_PRECISION);
            precision = new PeakResultDataPrecision() {

                @Override
                public Double getValue(PeakResult result) {
                    if (result.hasPrecision()) {
                        return result.getPrecision();
                    }
                    if (calculator != null) {
                        return calculator.getLsePrecision(result.getParameters(), result.getNoise());
                    }
                    return 0.0;
                }
            };
        } catch (final ConfigurationException | ConversionException ex) {
        // Ignore
        }
        if (precision == null) {
            precision = new PeakResultDataPrecision();
        }
        valuesList.add(precision);
        namesList.add("Precision (nm)");
    }
    values = valuesList.toArray(new PeakResultData<?>[0]);
    names = namesList.toArray(new String[0]);
    fireTableStructureChanged();
}
Also used : PeakResultDataId(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataId) PeakResultDataParameterConverter(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataParameterConverter) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) Gaussian2DPeakResultCalculator(uk.ac.sussex.gdsc.smlm.results.Gaussian2DPeakResultCalculator) PeakResultDataOrigValue(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataOrigValue) ConfigurationException(uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException) PeakResultDataParameterDeviationConverter(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataParameterDeviationConverter) PeakResultDataParameterConverter(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataParameterConverter) Converter(uk.ac.sussex.gdsc.core.data.utils.Converter) PeakResultDataPrecision(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataPrecision) PeakResultData(uk.ac.sussex.gdsc.smlm.results.PeakResultData) ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) PeakResultDataFrame(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataFrame) PeakResultDataFloat(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataFloat) PeakResultDataSnr(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataSnr) PeakResultDataParameterDeviationConverter(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataParameterDeviationConverter) TIntArrayList(gnu.trove.list.array.TIntArrayList) PeakResultDataEndFrame(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataEndFrame) PeakResultDataOrigX(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataOrigX) PeakResultDataError(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataError) PeakResultDataFloat(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataFloat) PeakResultDataOrigY(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataOrigY) PeakResultDataCategory(uk.ac.sussex.gdsc.smlm.results.data.PeakResultDataCategory) PeakResultConversionHelper(uk.ac.sussex.gdsc.smlm.results.PeakResultConversionHelper)

Example 8 with ConversionException

use of uk.ac.sussex.gdsc.core.data.utils.ConversionException in project GDSC-SMLM by aherbert.

the class CropResults method addStandardFields.

private void addStandardFields(final ExtendedGenericDialog gd) {
    if (minMax != null) {
        // 3D crop options
        double min = minMax.getMinimum();
        double max = minMax.getMaximum();
        final double maxz = Math.min(settings.getMaxZ(), max);
        final double minz = Math.max(settings.getMinZ(), min);
        // Display in nm
        converter = new IdentityTypeConverter<>(null);
        String unit = "";
        final DistanceUnit nativeUnit = results.getDistanceUnit();
        if (nativeUnit != null) {
            unit = UnitHelper.getShortName(nativeUnit);
            try {
                converter = CalibrationHelper.getDistanceConverter(results.getCalibration(), DistanceUnit.NM);
                unit = UnitHelper.getShortName(DistanceUnit.NM);
            } catch (final ConversionException ex) {
            // No native units
            }
        }
        min = converter.convert(min);
        max = converter.convert(max);
        final String msg = String.format("%.2f <= z <= %.2f (%s)", min, max, unit);
        min = Math.floor(min);
        max = Math.ceil(max);
        gd.addMessage(msg);
        gd.addCheckbox("Limit Z-depth", settings.getLimitZ());
        gd.addSlider("minZ", min, max, converter.convert(minz));
        gd.addSlider("maxZ", min, max, converter.convert(maxz));
    }
    gd.addChoice("Name_option", NAME_OPTIONS, settings.getNameOption(), new OptionListener<Integer>() {

        @Override
        public boolean collectOptions(Integer value) {
            settings.setNameOption(value);
            return collectOptions(false);
        }

        @Override
        public boolean collectOptions() {
            return collectOptions(true);
        }

        private boolean collectOptions(boolean silent) {
            final ExtendedGenericDialog egd = new ExtendedGenericDialog(TITLE);
            if (settings.getNameOption() == NAME_OPTION_NAME) {
                final String name = (TextUtils.isNullOrEmpty(settings.getOutputName())) ? (results.getName() + " Cropped") : settings.getOutputName();
                egd.addStringField("Output_name", name, MathUtils.clip(60, 120, name.length()));
            } else if (settings.getNameOption() == NAME_OPTION_SUFFIX) {
                final String name = (TextUtils.isNullOrEmpty(settings.getNameSuffix())) ? " Cropped" : settings.getNameSuffix();
                egd.addStringField("Name_suffix", name, MathUtils.clip(20, 60, name.length()));
            } else if (settings.getNameOption() == NAME_OPTION_SEQUENCE) {
                final String name = settings.getNameSuffix();
                egd.addStringField("Name_suffix", name, MathUtils.clip(20, 60, name.length()));
                int counter = settings.getNameCounter();
                if (counter < 1) {
                    counter = 1;
                }
                egd.addNumericField("Name_counter", counter, 0);
            } else {
                throw new IllegalStateException("Unknown name option: " + settings.getNameOption());
            }
            egd.setSilent(silent);
            egd.showDialog(true, gd);
            if (egd.wasCanceled()) {
                return false;
            }
            if (settings.getNameOption() == NAME_OPTION_NAME) {
                settings.setOutputName(egd.getNextString());
            } else if (settings.getNameOption() == NAME_OPTION_SUFFIX) {
                settings.setNameSuffix(egd.getNextString());
            } else if (settings.getNameOption() == NAME_OPTION_SEQUENCE) {
                settings.setNameSuffix(egd.getNextString());
                settings.setNameCounter(Math.max(1, (int) egd.getNextNumber()));
            }
            return true;
        }
    });
    gd.addCheckbox("Preserve_bounds", settings.getPreserveBounds());
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)

Example 9 with ConversionException

use of uk.ac.sussex.gdsc.core.data.utils.ConversionException in project GDSC-SMLM by aherbert.

the class CreateData method getAstigmatismHwhm.

private double getAstigmatismHwhm() {
    AstigmatismModel model = AstigmatismModelManager.getModel(settings.getAstigmatismModel());
    if (model == null) {
        IJ.error(TITLE, "Unknown PSF model: " + settings.getAstigmatismModel());
        return -1;
    }
    try {
        // Get the width at z=0 in pixels
        model = AstigmatismModelManager.convert(model, model.getZDistanceUnit(), DistanceUnit.PIXEL);
        final AstigmatismZModel zModel = AstigmatismModelManager.create(model);
        final double sx = zModel.getSx(0);
        final double sy = zModel.getSy(0);
        return Gaussian2DPeakResultHelper.getStandardDeviation(sx, sy) * Gaussian2DFunction.SD_TO_HWHM_FACTOR * // Scale appropriately
        model.getNmPerPixel() / settings.getPixelPitch();
    } catch (final ConversionException ex) {
        IJ.error(TITLE, "Unknown PSF FWHM setting for model: " + settings.getAstigmatismModel());
        return -1;
    }
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) AstigmatismModel(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel) AstigmatismZModel(uk.ac.sussex.gdsc.smlm.function.gaussian.AstigmatismZModel) HoltzerAstigmatismZModel(uk.ac.sussex.gdsc.smlm.function.gaussian.HoltzerAstigmatismZModel)

Example 10 with ConversionException

use of uk.ac.sussex.gdsc.core.data.utils.ConversionException in project GDSC-SMLM by aherbert.

the class MalkFilePeakResults method begin.

@Override
public synchronized void begin() {
    // Ensure we write out in nm and photons if possible.
    if (hasCalibration()) {
        // Copy it so it can be modified
        final CalibrationWriter cw = new CalibrationWriter(getCalibration());
        // Create converters
        try {
            toNmConverter = cw.getDistanceConverter(DistanceUnit.NM);
            cw.setDistanceUnit(DistanceUnit.NM);
        } catch (final ConversionException ex) {
        // Gracefully fail so ignore this
        }
        try {
            toPhotonConverter = cw.getIntensityConverter(IntensityUnit.PHOTON);
            cw.setIntensityUnit(IntensityUnit.PHOTON);
        } catch (final ConversionException ex) {
        // Gracefully fail so ignore this
        }
        setCalibration(cw.getCalibration());
    }
    // The data loses PSF information so reset this to a custom type with
    // no additional parameters.
    setPsf(PsfHelper.create(PSFType.CUSTOM));
    super.begin();
    // Create converters to avoid null pointers
    if (toNmConverter == null) {
        toNmConverter = new IdentityTypeConverter<>(null);
    }
    if (toPhotonConverter == null) {
        toPhotonConverter = new IdentityTypeConverter<>(null);
    }
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter)

Aggregations

ConversionException (uk.ac.sussex.gdsc.core.data.utils.ConversionException)10 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)3 AstigmatismModel (uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel)3 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)3 HoltzerAstigmatismZModel (uk.ac.sussex.gdsc.smlm.function.gaussian.HoltzerAstigmatismZModel)3 TIntArrayList (gnu.trove.list.array.TIntArrayList)2 ConfigurationException (uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException)2 PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)2 PeakResultConversionHelper (uk.ac.sussex.gdsc.smlm.results.PeakResultConversionHelper)2 TFloatArrayList (gnu.trove.list.array.TFloatArrayList)1 ImagePlus (ij.ImagePlus)1 GenericDialog (ij.gui.GenericDialog)1 Overlay (ij.gui.Overlay)1 Plot (ij.gui.Plot)1 PointRoi (ij.gui.PointRoi)1 Rectangle2D (java.awt.geom.Rectangle2D)1 Converter (uk.ac.sussex.gdsc.core.data.utils.Converter)1 NonBlockingExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog)1 OffsetPointRoi (uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)1 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)1