Search in sources :

Example 11 with UnicodeReader

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

the class About method installResource.

/**
	 * @param resource
	 * @param ijDirectory
	 * @param destinationName
	 * @param resourceTitle
	 * @param notes
	 * @param options
	 * @return -1 on error, 0 if installed, 1 if removed
	 */
private static int installResource(String resource, String ijDirectory, String destinationName, String resourceTitle, String notes, ConfigureOption... options) {
    Class<About> resourceClass = About.class;
    InputStream toolsetStream = resourceClass.getResourceAsStream(resource);
    if (toolsetStream == null)
        return -1;
    String dir = IJ.getDirectory(ijDirectory);
    if (dir == null) {
        IJ.error("Unable to locate " + ijDirectory + " directory");
        return -1;
    }
    EnumSet<ConfigureOption> opt = EnumSet.of(options[0], options);
    GenericDialog gd = new GenericDialog(TITLE);
    String filename = dir + destinationName;
    boolean fileExists = new File(filename).exists();
    StringBuilder sb = new StringBuilder();
    sb.append("Configure resource '").append(resourceTitle).append("' at:\n \n").append(filename);
    if (notes != null)
        sb.append("\n \n").append(XmlUtils.lineWrap(notes, 80, 0, null));
    gd.addMessage(sb.toString());
    // Configure the options
    String[] choices = new String[3];
    ConfigureOption[] optChoices = new ConfigureOption[choices.length];
    int count = 0;
    if (opt.contains(ConfigureOption.INSTALL)) {
        choices[count] = ConfigureOption.INSTALL.toString();
        if (fileExists)
            choices[count] += " (overwrite)";
        optChoices[count] = ConfigureOption.INSTALL;
        count++;
    }
    if (opt.contains(ConfigureOption.EDIT)) {
        choices[count] = ConfigureOption.EDIT.toString();
        if (fileExists)
            choices[count] += " (overwrite)";
        optChoices[count] = ConfigureOption.EDIT;
        count++;
    }
    if (opt.contains(ConfigureOption.REMOVE) && fileExists) {
        choices[count] = ConfigureOption.REMOVE.toString();
        optChoices[count] = ConfigureOption.REMOVE;
        count++;
    }
    if (count == 0)
        return -1;
    choices = Arrays.copyOf(choices, count);
    gd.addChoice("Option", choices, choices[0]);
    gd.showDialog();
    if (gd.wasCanceled())
        return -1;
    ConfigureOption choice = optChoices[gd.getNextChoiceIndex()];
    if (choice == ConfigureOption.REMOVE) {
        try {
            new File(filename).delete();
            return 1;
        } catch (SecurityException e) {
            IJ.error("Unable to remove existing file");
        }
        return -1;
    }
    // Read the file
    LinkedList<String> contents = new LinkedList<String>();
    BufferedReader input = null;
    try {
        // Read
        input = new BufferedReader(new UnicodeReader(toolsetStream, null));
        String line;
        while ((line = input.readLine()) != null) {
            contents.add(line);
        }
    } catch (IOException e) {
        IJ.error("Unable to install " + resourceTitle + ".\n \n" + e.getMessage());
        return -1;
    } finally {
        close(input);
    }
    if (choice == ConfigureOption.EDIT) {
        // Allow the user to edit the file contents
        gd = new GenericDialog(TITLE);
        gd.addMessage("Edit the file contents before install:");
        sb.setLength(0);
        for (String line : contents) sb.append(line).append("\n");
        gd.addTextAreas(sb.toString(), null, 20, 80);
        gd.showDialog();
        if (gd.wasOKed()) {
            contents.clear();
            String text = gd.getNextText();
            for (String line : text.split("\n")) contents.add(line);
        }
    }
    // Install the file
    BufferedWriter output = null;
    try {
        // Write
        FileOutputStream fos = new FileOutputStream(filename);
        output = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
        for (String content : contents) {
            output.write(content);
            output.newLine();
        }
    } catch (IOException e) {
        IJ.error("Unable to install " + resourceTitle + ".\n \n" + e.getMessage());
    } finally {
        close(output);
    }
    return 0;
}
Also used : InputStream(java.io.InputStream) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) LinkedList(java.util.LinkedList) BufferedWriter(java.io.BufferedWriter) GenericDialog(ij.gui.GenericDialog) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 12 with UnicodeReader

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

the class About method showAbout.

public static void showAbout() {
    // Locate the README.txt file and load that into the dialog. Include revision
    Class<About> resourceClass = About.class;
    InputStream readmeStream = resourceClass.getResourceAsStream("/gdsc/smlm/README.txt");
    StringBuilder msg = new StringBuilder();
    String helpURL = HELP_URL;
    String version = Version.getVersion();
    String buildDate = Version.getBuildDate();
    BufferedReader input = null;
    try {
        // Read the contents of the README file
        input = new BufferedReader(new UnicodeReader(readmeStream, null));
        String line;
        while ((line = input.readLine()) != null) {
            if (line.contains("http:")) {
                helpURL = line;
            } else {
                if (line.equals(""))
                    // Required to insert a line in the GenericDialog
                    line = " ";
                msg.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        // 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");
    } finally {
        try {
            input.close();
        } catch (IOException e) {
        }
    }
    // Build final message
    msg = new StringBuilder(msg.toString().trim());
    if (version != Version.UNKNOWN || buildDate != Version.UNKNOWN)
        msg.append("\n \n");
    if (version != Version.UNKNOWN)
        msg.append("Version : ").append(version).append("\n");
    if (buildDate != Version.UNKNOWN)
        msg.append("Build Date : ").append(buildDate).append("\n");
    if (helpURL != null)
        msg.append("\n \n(Click help for more information)");
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage(msg.toString());
    gd.addHelp(helpURL);
    gd.hideCancelButton();
    gd.showDialog();
}
Also used : InputStream(java.io.InputStream) GenericDialog(ij.gui.GenericDialog) BufferedReader(java.io.BufferedReader) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException)

Example 13 with UnicodeReader

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

the class DriftCalculator method readDriftFile.

/**
	 * Read the drift file storing the T,X,Y into the class level calculatedTimepoints, lastdx and lastdy
	 * arrays. Ignore any records where T is outside the limits.
	 * 
	 * @param limits
	 * @return The number of records read
	 */
private int readDriftFile(int[] limits) {
    int ok = 0;
    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(driftFilename);
        input = new BufferedReader(new UnicodeReader(fis, null));
        String line;
        Pattern pattern = Pattern.compile("[\t, ]+");
        while ((line = input.readLine()) != null) {
            if (line.length() == 0)
                continue;
            if (Character.isDigit(line.charAt(0))) {
                try {
                    Scanner scanner = new Scanner(line);
                    scanner.useDelimiter(pattern);
                    scanner.useLocale(Locale.US);
                    final int t = scanner.nextInt();
                    if (t < limits[0] || t > limits[1])
                        continue;
                    final double x = scanner.nextDouble();
                    final double y = scanner.nextDouble();
                    calculatedTimepoints[t] = ++ok;
                    lastdx[t] = x;
                    lastdy[t] = y;
                    scanner.close();
                } catch (InputMismatchException e) {
                } catch (NoSuchElementException e) {
                }
            }
        }
    } catch (IOException e) {
    // ignore
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        // Ignore
        }
    }
    return ok;
}
Also used : Pattern(java.util.regex.Pattern) Scanner(java.util.Scanner) BufferedReader(java.io.BufferedReader) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) InputMismatchException(java.util.InputMismatchException) Point(java.awt.Point) FileInputStream(java.io.FileInputStream) NoSuchElementException(java.util.NoSuchElementException)

Example 14 with UnicodeReader

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

the class PCPALMFitting method loadCorrelationCurve.

/**
	 * Load a correlation curve from file. Will set the global gr, peakDensity and spatialDomain variables. If the data
	 * fails to be loaded then the method will return false.
	 * 
	 * @return True if loaded
	 */
private boolean loadCorrelationCurve() {
    inputFilename = Utils.getFilename("Input_Correlation_File", inputFilename);
    if (inputFilename == null)
        return false;
    // Set the analysis variables
    boolean spatialDomainSet = false;
    boolean peakDensitySet = false;
    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(inputFilename);
        input = new BufferedReader(new UnicodeReader(fis, null));
        String line;
        int count = 0;
        Pattern pattern = Pattern.compile("#([^=]+) = ([^ ]+)");
        // Read the header
        while ((line = input.readLine()) != null) {
            count++;
            if (line.length() == 0)
                continue;
            if (line.charAt(0) != '#') {
                // This is the first record
                break;
            }
            // This is a header line. Extract the key-value pair
            Matcher match = pattern.matcher(line);
            if (match.find()) {
                if (match.group(1).equals(HEADER_SPATIAL_DOMAIN)) {
                    // Do not use Boolean.parseBoolean because this will not fail if the field is 
                    // neither true/false - it only return true for a match to true
                    spatialDomainSet = true;
                    if (match.group(2).equalsIgnoreCase("true"))
                        spatialDomain = true;
                    else if (match.group(2).equalsIgnoreCase("false"))
                        spatialDomain = false;
                    else
                        // We want to know if the field is not true/false
                        spatialDomainSet = false;
                } else if (match.group(1).equals(HEADER_PEAK_DENSITY)) {
                    try {
                        peakDensity = Double.parseDouble(match.group(2));
                        peakDensitySet = true;
                    } catch (NumberFormatException e) {
                    // Ignore this.
                    }
                }
            }
        }
        if (!peakDensitySet) {
            IJ.error(TITLE, "No valid " + HEADER_PEAK_DENSITY + " record in file " + inputFilename);
            return false;
        }
        if (!spatialDomainSet) {
            IJ.error(TITLE, "No valid " + HEADER_SPATIAL_DOMAIN + " record in file " + inputFilename);
            return false;
        }
        // Read the data: gr[0][i], gr[1][i], gr[2][i]
        ArrayList<double[]> data = new ArrayList<double[]>();
        while (line != null) {
            if (line.length() == 0)
                continue;
            if (line.charAt(0) == '#')
                continue;
            // Extract the first 3 fields
            Scanner scanner = new Scanner(line);
            scanner.useDelimiter("[\t ,]+");
            double r, g;
            try {
                r = scanner.nextDouble();
                g = scanner.nextDouble();
            } catch (InputMismatchException e) {
                IJ.error(TITLE, "Incorrect fields on line " + count);
                scanner.close();
                return false;
            } catch (NoSuchElementException e) {
                IJ.error(TITLE, "Incorrect fields on line " + count);
                scanner.close();
                return false;
            }
            // Allow the file to be missing the curve error. This is only used for plotting anyway.
            double error = 0;
            try {
                error = scanner.nextDouble();
            } catch (InputMismatchException e) {
            } catch (NoSuchElementException e) {
            }
            scanner.close();
            data.add(new double[] { r, g, error });
            // Read the next line
            line = input.readLine();
            count++;
        }
        if (data.isEmpty()) {
            IJ.error(TITLE, "No data in file " + inputFilename);
            return false;
        }
        gr = new double[3][data.size()];
        for (int i = 0; i < data.size(); i++) {
            final double[] d = data.get(i);
            gr[0][i] = d[0];
            gr[1][i] = d[1];
            gr[2][i] = d[2];
        }
    } catch (IOException e) {
        IJ.error(TITLE, "Unable to read from file " + inputFilename);
        return false;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        // Ignore
        }
    }
    return true;
}
Also used : Pattern(java.util.regex.Pattern) Scanner(java.util.Scanner) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) InputMismatchException(java.util.InputMismatchException) FileInputStream(java.io.FileInputStream) BufferedReader(java.io.BufferedReader) NoSuchElementException(java.util.NoSuchElementException)

Example 15 with UnicodeReader

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

the class PeakResultsReader method readTable.

private MemoryPeakResults readTable() {
    MemoryPeakResults results = createResults();
    results.setName(new File(filename).getName());
    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(filename);
        FileChannel channel = fis.getChannel();
        input = new BufferedReader(new UnicodeReader(fis, null));
        String line;
        int errors = 0;
        // Skip over the single line header
        String header = input.readLine();
        // Old table results had the Signal and Amplitude.
        // New table results have only the Signal.
        int version = 2;
        if (header.contains("Amplitude"))
            version = 1;
        int c = 0;
        while ((line = input.readLine()) != null) {
            if (line.length() == 0)
                continue;
            if (!addTableResult(results, line, version)) {
                if (++errors >= 10) {
                    break;
                }
            }
            if (++c % 512 == 0)
                showProgress(channel);
        }
    } catch (IOException e) {
    // ignore
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        // Ignore
        }
    }
    return results;
}
Also used : FileChannel(java.nio.channels.FileChannel) BufferedReader(java.io.BufferedReader) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

UnicodeReader (gdsc.core.utils.UnicodeReader)16 BufferedReader (java.io.BufferedReader)16 IOException (java.io.IOException)16 FileInputStream (java.io.FileInputStream)14 File (java.io.File)6 FileChannel (java.nio.channels.FileChannel)5 ArrayList (java.util.ArrayList)5 InputStream (java.io.InputStream)4 Pattern (java.util.regex.Pattern)4 GenericDialog (ij.gui.GenericDialog)3 InputMismatchException (java.util.InputMismatchException)3 LinkedList (java.util.LinkedList)3 NoSuchElementException (java.util.NoSuchElementException)3 Scanner (java.util.Scanner)3 FilterSettings (gdsc.smlm.ij.settings.FilterSettings)2 GlobalSettings (gdsc.smlm.ij.settings.GlobalSettings)2 Point (java.awt.Point)2 List (java.util.List)2 ClusterPoint (gdsc.core.clustering.ClusterPoint)1 Statistics (gdsc.core.utils.Statistics)1