Search in sources :

Example 6 with UnicodeReader

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

the class SmlmTools method createFrame.

private boolean createFrame() {
    final ArrayList<String[]> configPlugins = new ArrayList<>();
    // Locate all the GDSC SMLM plugins using the plugins.config:
    try (InputStream readmeStream = getToolsPluginsConfig()) {
        // Read into memory
        int gaps = 0;
        try (BufferedReader input = new BufferedReader(new UnicodeReader(readmeStream, null))) {
            String line;
            while ((line = input.readLine()) != null) {
                if (line.startsWith("#")) {
                    continue;
                }
                final String[] tokens = line.split(",");
                if (tokens.length == 3) {
                    // Only copy the entries from the Plugins menu
                    if (!ignore(tokens)) {
                        if (!configPlugins.isEmpty() && // Multiple gaps indicates a new column
                        gaps > 1) {
                            configPlugins.add(new String[] { "next", "" });
                        }
                        gaps = 0;
                        configPlugins.add(new String[] { tokens[1].trim(), tokens[2].trim() });
                    }
                } else {
                    gaps++;
                }
                // Put a spacer between plugins if specified
                if ((tokens.length == 2 && tokens[0].startsWith("Plugins") && tokens[1].trim().equals("\"-\"")) || line.length() == 0) {
                    configPlugins.add(new String[] { "spacer", "" });
                }
            }
        }
    } catch (final IOException ex) {
    // Ignore
    }
    if (configPlugins.isEmpty()) {
        return false;
    }
    // Put a spacer on the menu
    ij.Menus.installPlugin("", ij.Menus.PLUGINS_MENU, "-", "", IJ.getInstance());
    // Arrange on a grid.
    final Panel mainPanel = new Panel();
    final GridBagLayout grid = new GridBagLayout();
    mainPanel.setLayout(grid);
    addSpacer = false;
    int col = 0;
    int row = 0;
    for (final String[] plugin : configPlugins) {
        if (plugin[0].equals("next")) {
            col++;
            row = 0;
        } else if (plugin[0].equals("spacer")) {
            addSpacer = true;
        } else {
            row = addPlugin(mainPanel, grid, plugin[0], plugin[1], col, row);
        }
    }
    // Allow scrollbars to handle small screens.
    // Appropriately size the scrollpane from the default of 100x100.
    // The preferred size is only obtained if the panel is packed.
    add(mainPanel);
    pack();
    final Dimension d = mainPanel.getPreferredSize();
    // Assume this is the only component
    remove(0);
    final ScrollPane scroll = new ScrollPane();
    scroll.getHAdjustable().setUnitIncrement(16);
    scroll.getVAdjustable().setUnitIncrement(16);
    scroll.add(mainPanel);
    add(scroll, BorderLayout.CENTER);
    // Scale to the screen size
    d.width = Math.min(d.width, screenDimension.width - 100);
    d.height = Math.min(d.height, screenDimension.height - 150);
    final Insets insets = scroll.getInsets();
    d.width += insets.left + insets.right;
    d.height += insets.top + insets.bottom;
    if (IJ.isMacintosh()) {
        // This is needed as the OSX scroll pane adds scrollbars when the panel
        // is close in size to the scroll pane
        final int padding = 15;
        d.width += padding;
        d.height += padding;
    }
    scroll.setPreferredSize(d);
    scroll.setSize(d);
    return true;
}
Also used : Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) Dimension(java.awt.Dimension) Point(java.awt.Point) Panel(java.awt.Panel) ScrollPane(java.awt.ScrollPane) BufferedReader(java.io.BufferedReader)

Example 7 with UnicodeReader

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

the class About method showAbout.

/**
 * Show about dialog.
 */
public static void showAbout() {
    // Locate the README.txt file and load that into the dialog. Include revision
    final Class<About> resourceClass = About.class;
    StringBuilder msg = new StringBuilder();
    try (BufferedReader input = new BufferedReader(new UnicodeReader(resourceClass.getResourceAsStream("/uk/ac/sussex/gdsc/smlm/ij/README.txt"), null))) {
        // Read the contents of the README file
        String line;
        while ((line = input.readLine()) != null) {
            if (line.equals("")) {
                // Required to insert a line in the GenericDialog
                line = " ";
            }
            msg.append(line).append('\n');
        }
    } catch (final IOException ex) {
        // Default message
        msg.append("GDSC SMLM Plugins for ImageJ\n");
        msg.append(" \n");
        msg.append("Copyright (C) ").append(YEAR).append(" Alex Herbert\n");
        msg.append("MRC Genome Damage and Stability Centre\n");
        msg.append("University of Sussex, UK\n");
    }
    // Build final message
    msg = new StringBuilder(msg.toString().trim());
    addVersion(msg, "GDSC-SMLM", Version.getVersion(), Version.getBuildDate(), Version.getBuildNumber());
    addVersion(msg, "GDSC-Core", uk.ac.sussex.gdsc.core.VersionUtils.getVersion(), uk.ac.sussex.gdsc.core.VersionUtils.getBuildDate(), uk.ac.sussex.gdsc.core.VersionUtils.getBuildNumber());
    final GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage(msg.toString());
    gd.addHelp(HelpUrls.getUrl());
    gd.hideCancelButton();
    gd.showDialog();
}
Also used : GenericDialog(ij.gui.GenericDialog) BufferedReader(java.io.BufferedReader) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) IOException(java.io.IOException)

Example 8 with UnicodeReader

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

the class CreateData method createPhotonDistribution.

/**
 * Creates the photon distribution.
 *
 * @return A photon distribution loaded from a file of floating-point values with the specified
 *         population mean.
 */
private RealDistribution createPhotonDistribution() {
    if (PHOTON_DISTRIBUTION[PHOTON_CUSTOM].equals(settings.getPhotonDistribution())) {
        // Get the distribution file
        final String filename = ImageJUtils.getFilename("Photon_distribution", settings.getPhotonDistributionFile());
        if (filename != null) {
            settings.setPhotonDistributionFile(filename);
            try (BufferedReader in = new BufferedReader(new UnicodeReader(new FileInputStream(new File(settings.getPhotonDistributionFile())), null))) {
                final StoredDataStatistics stats = new StoredDataStatistics();
                String str = in.readLine();
                double val = 0.0d;
                while (str != null) {
                    val = Double.parseDouble(str);
                    stats.add(val);
                    str = in.readLine();
                }
                if (stats.getSum() > 0) {
                    // Update the statistics to the desired mean.
                    final double scale = settings.getPhotonsPerSecond() / stats.getMean();
                    final double[] values = stats.getValues();
                    for (int i = 0; i < values.length; i++) {
                        values[i] *= scale;
                    }
                    // TODO - Investigate the limits of this distribution.
                    // How far above and below the input data will values be generated.
                    // Create the distribution using the recommended number of bins
                    final int binCount = stats.getN() / 10;
                    final EmpiricalDistribution dist = new EmpiricalDistribution(binCount, new RandomGeneratorAdapter(createRandomGenerator()));
                    dist.load(values);
                    return dist;
                }
            } catch (final IOException | NullArgumentException | NumberFormatException ex) {
            // Ignore
            }
        }
        ImageJUtils.log("Failed to load custom photon distribution from file: %s. Default to fixed.", settings.getPhotonDistributionFile());
    } else if (PHOTON_DISTRIBUTION[PHOTON_UNIFORM].equals(settings.getPhotonDistribution())) {
        if (settings.getPhotonsPerSecond() < settings.getPhotonsPerSecondMaximum()) {
            return new UniformRealDistribution(new RandomGeneratorAdapter(createRandomGenerator()), settings.getPhotonsPerSecond(), settings.getPhotonsPerSecondMaximum());
        }
    } else if (PHOTON_DISTRIBUTION[PHOTON_GAMMA].equals(settings.getPhotonDistribution())) {
        final double scaleParameter = settings.getPhotonsPerSecond() / settings.getPhotonShape();
        return new GammaDistribution(new RandomGeneratorAdapter(createRandomGenerator()), settings.getPhotonShape(), scaleParameter, ExponentialDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    } else if (PHOTON_DISTRIBUTION[PHOTON_CORRELATED].equals(settings.getPhotonDistribution())) {
        // No distribution required
        return null;
    }
    settings.setPhotonDistribution(PHOTON_DISTRIBUTION[PHOTON_FIXED]);
    return null;
}
Also used : RandomGeneratorAdapter(uk.ac.sussex.gdsc.core.utils.rng.RandomGeneratorAdapter) EmpiricalDistribution(org.apache.commons.math3.random.EmpiricalDistribution) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) UniformRealDistribution(org.apache.commons.math3.distribution.UniformRealDistribution) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) NullArgumentException(org.apache.commons.math3.exception.NullArgumentException) FileInputStream(java.io.FileInputStream) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) BufferedReader(java.io.BufferedReader) File(java.io.File) GammaDistribution(org.apache.commons.math3.distribution.GammaDistribution)

Example 9 with UnicodeReader

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

the class PeakResultsReader method readTable.

private MemoryPeakResults readTable() {
    try (FileInputStream fis = new FileInputStream(filename);
        BufferedReader input = new BufferedReader(new UnicodeReader(fis, null))) {
        // Skip over the single line header
        final String tableHeader = input.readLine();
        if (tableHeader == null) {
            return null;
        }
        Objects.requireNonNull(tableHeader, "GDSC SMLM Table header should exist");
        // V1: had the Signal and Amplitude. Parameters
        // V2: have only the Signal.
        // V3: Has variable columns with units for the PSF parameters. Signal was renamed to
        // Intensity.
        int tableVersion;
        if (tableHeader.contains("Signal")) {
            tableVersion = 1;
        } else if (tableHeader.contains("Amplitude")) {
            tableVersion = 2;
        } else {
            // as guessing the column format is not supported.
            return null;
        }
        final ProgressReporter reporter = createProgressReporter(fis);
        final MemoryPeakResults results = createResults();
        results.setName(FileUtils.getName(filename));
        String line;
        int errors = 0;
        while ((line = input.readLine()) != null) {
            if (line.isEmpty()) {
                continue;
            }
            if (!addTableResult(results, line, tableVersion) && ++errors >= 10) {
                break;
            }
            reporter.showProgress();
        }
        return results;
    } catch (final IOException ex) {
        logError(ex);
    }
    return null;
}
Also used : BufferedReader(java.io.BufferedReader) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 10 with UnicodeReader

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

the class PeakResultsReader method readText.

private MemoryPeakResults readText() {
    final MemoryPeakResults results = createResults();
    // Units were added in version 3
    int fieldCount;
    if (smlmVersion < 3) {
        fieldCount = 7;
        calibration.setIntensityUnit(IntensityUnit.COUNT);
        calibration.setDistanceUnit(DistanceUnit.PIXEL);
        calibration.setAngleUnit(AngleUnit.DEGREE);
    // Note that in older versions the background included the bias.
    // The bias is not included in the table and so the user will have to
    // add this manually. They will also have to add the gain.
    } else {
        // The number of fields should be within the PSF object
        fieldCount = new PeakResultConversionHelper(null, psf).getNames().length;
    }
    try (FileInputStream fis = new FileInputStream(filename)) {
        try (BufferedReader input = new BufferedReader(new UnicodeReader(fis, null))) {
            final ProgressReporter reporter = createProgressReporter(fis);
            String line;
            int errors = 0;
            final LineReader reader = createLineReader(results, smlmVersion, fieldCount);
            // Skip the header
            while ((line = input.readLine()) != null) {
                if (line.isEmpty()) {
                    continue;
                }
                if (line.charAt(0) != '#') {
                    // This is the first record
                    if (!reader.addPeakResult(line)) {
                        errors = 1;
                    }
                    break;
                }
            }
            while ((line = input.readLine()) != null) {
                if (line.isEmpty() || line.charAt(0) == '#') {
                    continue;
                }
                if (!reader.addPeakResult(line) && ++errors >= 10) {
                    break;
                }
                reporter.showProgress();
            }
        }
    } catch (final IOException ex) {
        logError(ex);
    }
    return results;
}
Also used : BufferedReader(java.io.BufferedReader) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Aggregations

BufferedReader (java.io.BufferedReader)12 UnicodeReader (uk.ac.sussex.gdsc.core.utils.UnicodeReader)12 IOException (java.io.IOException)11 FileInputStream (java.io.FileInputStream)10 GenericDialog (ij.gui.GenericDialog)3 File (java.io.File)3 ArrayList (java.util.ArrayList)2 LinkedList (java.util.LinkedList)2 Pattern (java.util.regex.Pattern)2 Nullable (uk.ac.sussex.gdsc.core.annotation.Nullable)2 CalibrationWriter (uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter)2 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 JsonFormat (com.google.protobuf.util.JsonFormat)1 NonBlockingGenericDialog (ij.gui.NonBlockingGenericDialog)1 Dimension (java.awt.Dimension)1 GridBagLayout (java.awt.GridBagLayout)1 Insets (java.awt.Insets)1 Panel (java.awt.Panel)1 Point (java.awt.Point)1 Rectangle (java.awt.Rectangle)1