Example usage for java.lang Double parseDouble

List of usage examples for java.lang Double parseDouble

Introduction

In this page you can find the example usage for java.lang Double parseDouble.

Prototype

public static double parseDouble(String s) throws NumberFormatException 

Source Link

Document

Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .

Usage

From source file:de.peterspan.csv2db.converter.AbstractDataLine.java

public static Double string2double(String value) {
    try {//from  w  ww .  java  2 s.  c o  m
        value = value.replace(",", ".");
        return Double.parseDouble(value);
    } catch (NumberFormatException nfe) {
        if (!value.isEmpty()) {
            log.error("Could not convert string " + value + " to double.", nfe);
        }
        return null;
    }
}

From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w w w . j a  v  a 2s .  c om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    Double fontScale = null;
    if (cl.hasOption("font-scale")) {
        try {
            fontScale = Double.parseDouble(cl.getOptionValue("font-scale"));
        } catch (IllegalArgumentException e) {
            System.err.format("Argument for font-scale must be a floating point number.\n");
            System.exit(1);
        }
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        Set<String> includeIons = null;
        if (cl.hasOption("include-ions")) {
            String[] ionNames = cl.getOptionValues("include-ions");
            includeIons = new HashSet<>(Arrays.asList(ionNames));
            System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", "));
        }
        Set<String> excludeIons = null;
        if (cl.hasOption("exclude-ions")) {
            String[] ionNames = cl.getOptionValues("exclude-ions");
            excludeIons = new HashSet<>(Arrays.asList(ionNames));
            System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", "));
        }

        Set<Integer> takeSamplesFromPlateIds = null;
        if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) {
            String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE);
            System.out.format("Considering only sample wells in plates: %s\n",
                    StringUtils.join(plateBarcodes, ", "));
            takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length);
            for (String plateBarcode : plateBarcodes) {
                Plate p = Plate.getPlateByBarcode(db, plateBarcode);
                if (p == null) {
                    System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode);
                } else {
                    takeSamplesFromPlateIds.add(p.getId());
                }
            }
            // Allow filtering on barcode even if we couldn't find any in the DB.
        }

        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        System.out.format("Processing LCMS scans\n");
        Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS),
                takeSamplesFromPlateIds, false);
        List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft();
        if (positiveWells.size() == 0) {
            throw new RuntimeException("Found no LCMS wells for specified strains/constructs");
        }
        // Only take negative samples from the plates where we found the positive samples.
        Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS),
                positiveWellsAndPlateIds.getRight(), true);
        List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft();
        if (negativeWells == null || negativeWells.size() == 0) {
            System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n");
        }

        // Extract the reference MZ that will be used in the LCMS trace processing.
        List<Pair<String, Double>> searchMZs = null;
        Set<CuratedChemical> standardChemicals = null;
        List<ChemicalAssociatedWithPathway> pathwayChems = null;
        if (cl.hasOption(OPTION_SEARCH_MZ)) {
            // Assume mz can be an FP number of a chemical name.
            String massStr = cl.getOptionValue(OPTION_SEARCH_MZ);
            Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr);
            if (searchMZ != null) {
                searchMZs = Collections.singletonList(searchMZ);
            }
            standardChemicals = Utils.extractTargetsForWells(db, positiveWells);
        } else {
            CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells);
            if (targetChemical == null) {
                throw new RuntimeException(
                        "Unable to find a curated chemical entry for specified strains'/constructs' targets.  "
                                + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB.");
            }
            System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(),
                    targetChemical.getMass());
            searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass()));
            standardChemicals = Collections.singleton(targetChemical);
        }

        // Look up the standard by name, or use the target if none is specified.
        List<StandardWell> standardWells = null;
        if (cl.hasOption(OPTION_NO_STANDARD)) {
            System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n");
            standardWells = new ArrayList<>(0);
        } else if (cl.hasOption(OPTION_STANDARD_WELLS)) {
            String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS);
            standardWells = new ArrayList<>(standardCoordinates.length);
            Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
            List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length);
            for (String stringCoords : standardCoordinates) {
                Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords);
                StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db,
                        standardPlate.getId(), coords.getLeft(), coords.getRight());
                if (well == null) {
                    System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(),
                            stringCoords);
                    continue;
                }
                standardWells.add(well);
                foundCoordinates.add(stringCoords);
            }
            System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(),
                    StringUtils.join(foundCoordinates, ", "));
        } else if (cl.hasOption(OPTION_STANDARD_NAME)) {
            String standardName = cl.getOptionValue(OPTION_STANDARD_NAME);
            System.out.format("Using explicitly specified standard %s\n", standardName);
            standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db,
                    cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName));
        } else if (standardChemicals != null && standardChemicals.size() > 0) {
            // Default to using the target chemical(s) as a standard if none is specified.
            standardWells = new ArrayList<>(standardChemicals.size());
            for (CuratedChemical c : standardChemicals) {
                String standardName = c.getName();
                System.out.format("Searching for well containing standard %s\n", standardName);
                standardWells.add(Utils.extractStandardWellFromPlate(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName));
            }
        }

        boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz");
        boolean useSNR = cl.hasOption(OPTION_USE_SNR);

        /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be
         * iterated over for graph writing. */
        HashMap<Integer, Plate> plateCache = new HashMap<>();
        Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);

        String fmt = "pdf";
        String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt;
        String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data";
        System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg);

        produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans,
                fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR);
    }
}

From source file:Main.java

private static void setterValue(PropertyDescriptor property, Object mapValue, Object object)
        throws InvocationTargetException, IllegalAccessException, ParseException {
    Method setter = property.getWriteMethod();
    if (mapValue == null) {
        setter.invoke(object, mapValue);
        return;/*w  ww  .ja  va2  s  . c om*/
    }

    Class propertyType = property.getPropertyType();
    String type = propertyType.getName();
    String value = mapValue.toString();

    if (type.equals("java.lang.String")) {
        setter.invoke(object, value);
    } else if (type.equals("java.lang.Integer")) {
        setter.invoke(object, Integer.parseInt(value));
    } else if (type.equals("java.lang.Long")) {
        setter.invoke(object, Long.parseLong(value));
    } else if (type.equals("java.math.BigDecimal")) {
        setter.invoke(object, BigDecimal.valueOf(Double.parseDouble(value)));
    } else if (type.equals("java.math.BigInteger")) {
        setter.invoke(object, BigInteger.valueOf(Long.parseLong(value)));
    } else if (type.equals("java.util.Date")) {
        setter.invoke(object, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value));
    } else if (type.equals("java.lang.Boolean")) {
        setter.invoke(object, Boolean.valueOf(value));
    } else if (type.equals("java.lang.Float")) {
        setter.invoke(object, Float.parseFloat(value));
    } else if (type.equals("java.lang.Double")) {
        setter.invoke(object, Double.parseDouble(value));
    } else if (type.equals("java.lang.byte[]")) {
        setter.invoke(object, value.getBytes());
    } else {
        setter.invoke(object, value);
    }
}

From source file:Main.java

public static long parseValue(String valueStr) throws NumberFormatException {
    return (long) (Double.parseDouble(valueStr) * 1e8);
}

From source file:Main.java

/**
 * Populate the key-value pair of map with the value specified. If the value is null or empty then the default value is used instead.
 * /*  w w  w  .ja va  2s.  c om*/
 * @param _map
 * @param _key
 * @param _value
 * @param _defaultValue
 */
public static void populateMap(Map<String, Double> _map, String _key, String _value, Double _defaultValue) {
    if (_value != null && _value.length() > 0) {
        _map.put(_key, Double.parseDouble(_value));
    } else {
        _map.put(_key, _defaultValue);
    }
}

From source file:Main.java

public static double getNodeValue(final Node parentNode, final String strNodeName, final double dDefaultValue) {
    final String strValue = getNodeValue(parentNode.getChildNodes(), strNodeName, null);

    if (strValue != null) {
        return Double.parseDouble(strValue);
    }//from  w w  w .  ja v a2 s .c  o m

    return dDefaultValue;
}

From source file:Main.java

/**
 * For a string containing a number as judged by
 * <code>isNumber()</code>, return the numerical value, rounded to
 * an integer.//from w  ww  . j  a  v  a2 s  . com
 *
 * @return the numeric value, rounded to an integer, or 0
 * if the string is not a valid number.
 */
public static int getNumber(String string) {
    String s = string.trim();
    if (!isNumber(s))
        return 0;
    double value = 0;
    try {
        value = Double.parseDouble(s);
    } catch (NumberFormatException e) {
        //logger.warn("Unexpected number value `" + s + "'");
    }
    return (int) Math.round(value);
}

From source file:com.mobileman.projecth.web.util.NumUtils.java

public static Double convert2double(String str) {
    try {/*from   w  w w.  j a va  2 s . c o m*/
        if (StringUtils.isNotBlank(str)) {
            return Double.parseDouble(str.replace(',', '.'));
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:ctlogger.CTlogger.java

public static void main(String args[]) {

    /**/* www.  j av  a2  s. c om*/
     * 
     * Original code for command line parsing
     * (This has been replaced by code using Apache Commons CLI, see below)
     *
    String helpMsg = "CTlogger -x -r -z -g -k <skiplines> -f <flush_sec> -p <poll_sec> -n <nanVal> -i <leadingID> -s <SourceName> -H <HeaderLine> <logger.dat> <CTfolder>";
      int dirArg = 0;
      while((dirArg<args.length) && args[dirArg].startsWith("-")) {      // arg parsing
         if(args[dirArg].equals("-h"))    { 
     System.err.println(helpMsg);
     System.exit(0);
         }
         if(args[dirArg].equals("-x"))    { debug = true;   }
         if(args[dirArg].equals("-b"))    { noBackwards = true;   }
         if(args[dirArg].equals("-g"))    { gzipmode = true;   }         // default false
         if(args[dirArg].equals("-a"))    { appendMode = false;   }      // default true
         if(args[dirArg].equals("-z"))     { zipmode = false; }          // default true
         if(args[dirArg].equals("-N"))    { newFileMode = true;   }      // default false
         if(args[dirArg].equals("-f"))   { autoflush = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-p"))   { pollInterval = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-k"))   { skipLines = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-r"))   { repeatFetch = true; }   
         if(args[dirArg].equals("-B"))   { blockMode = true; }   
         if(args[dirArg].equals("-t"))   { storeTime = true; }   
         if(args[dirArg].equals("-T"))   { trimTime = Double.parseDouble(args[++dirArg]); }
         if(args[dirArg].equals("-n"))   { nanVal = args[++dirArg]; }
         if(args[dirArg].equals("-i"))   { leadingID = args[++dirArg]; }
         if(args[dirArg].equals("-s"))   { SourceName = args[++dirArg]; }
         if(args[dirArg].equals("-H"))   { HeaderLine = args[++dirArg]; }
         dirArg++;
      }
    if(args.length < (dirArg+2)) {
       System.err.println(helpMsg);
       System.exit(0);
    }
    loggerFileName = args[dirArg++];      // args[0]:  logger.dat file
    CTrootfolder = args[dirArg++];         // args[1]:  CT destination folder        
    */

    //
    // Parse command line arguments
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Boolean options (only the flag, no argument)
    options.addOption("h", "help", false, "Print this message");
    options.addOption("x", "debug", false, "turn on debug output");
    options.addOption("b", "nobackwards", false, "no backwards-going time allowed");
    options.addOption("g", "gzipmode", false, "turn on gzip for extra compression");
    options.addOption("a", "noappend", false,
            "turn off append mode (i.e., do not append to end of existing CT data)");
    options.addOption("z", "nozip", false, "turn off zip mode (it is on by default)");
    options.addOption("N", "newfilemode", false, "re-parse entire logger file every time it is checked");
    options.addOption("r", "repeatFetch", false, "turn on repeat fetch (auto-fetch data loop)");
    options.addOption("B", "blockMode", false,
            "turn on CloudTurbine writer block mode (multiple points per output data file, packed data)");
    options.addOption("t", "storeTime", false,
            "store time string as a channel; time is the first data entry in each line; if this option is not specified, then the time channel is skipped/not saved to CloudTurbine");
    // Options with an argument
    Option outputFolderOption = Option.builder("f").argName("autoflush").hasArg()
            .desc("flush interval (sec); default = \"" + autoflush + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("p").argName("pollInterval").hasArg().desc(
            "if repeatFetch option has been specified, recheck the logger data file at this polling interval (sec); default = \""
                    + pollInterval + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("k").argName("skipLines").hasArg().desc(
            "in logger file, the num lines to skip after the header line to get to the first line of data; default = \""
                    + skipLines + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("T").argName("trimTime").hasArg().desc(
            "trim (ring-buffer loop) time (sec) (trimTime=0 for indefinite); default = \"" + trimTime + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("n").argName("nanVal").hasArg()
            .desc("replace NAN with this; default = \"" + nanVal + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("i").argName("leadingID").hasArg()
            .desc("leading ID string (IWG1 compliant)").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("s").argName("sourceName").hasArg()
            .desc("CloudTurbine source name; default = \"" + SourceName + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("H").argName("HeaderLine").hasArg().desc(
            "optional CSV list of channel names; if not supplied, this is read from the first line in the logger file")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("l").argName("loggerfilename").hasArg()
            .desc("name of the logger data file; required argument").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("o").longOpt("outputfolder").argName("folder").hasArg()
            .desc("Location of output files (source is created under this folder); default = " + CTrootfolder)
            .build();
    options.addOption(outputFolderOption);

    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("help")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("CTlogger", options);
        return;
    }
    debug = line.hasOption("x");
    noBackwards = line.hasOption("b");
    gzipmode = line.hasOption("g");
    appendMode = !line.hasOption("a");
    zipmode = !line.hasOption("z");
    newFileMode = line.hasOption("N");
    repeatFetch = line.hasOption("r");
    blockMode = line.hasOption("B");
    storeTime = line.hasOption("t");
    autoflush = Long.parseLong(line.getOptionValue("f", Long.toString(autoflush)));
    pollInterval = Long.parseLong(line.getOptionValue("p", Long.toString(pollInterval)));
    skipLines = Long.parseLong(line.getOptionValue("k", Long.toString(skipLines)));
    trimTime = Double.parseDouble(line.getOptionValue("T", Double.toString(trimTime)));
    nanVal = line.getOptionValue("n", nanVal);
    if (line.hasOption("i")) {
        leadingID = line.getOptionValue("i");
    }
    SourceName = line.getOptionValue("s", SourceName);
    if (line.hasOption("H")) {
        HeaderLine = line.getOptionValue("H");
    }
    if (line.hasOption("l")) {
        loggerFileName = line.getOptionValue("l");
    } else {
        System.err.println("ERROR: you must supply the logger file name.");
        return;
    }
    CTrootfolder = line.getOptionValue("o", CTrootfolder);

    if (!debug) {
        System.err.println("CTlogger: " + loggerFileName + ", CTrootfolder: " + CTrootfolder
                + ", pollInterval: " + pollInterval);
    } else {
        System.err.println("debug = " + debug);
        System.err.println("noBackwards = " + noBackwards);
        System.err.println("gzipmode = " + gzipmode);
        System.err.println("appendMode = " + appendMode);
        System.err.println("zipmode = " + zipmode);
        System.err.println("newFileMode = " + newFileMode);
        System.err.println("repeatFetch = " + repeatFetch);
        System.err.println("blockMode = " + blockMode);
        System.err.println("storeTime = " + storeTime);
        System.err.println("autoflush = " + autoflush);
        System.err.println("pollInterval = " + pollInterval);
        System.err.println("skipLines = " + skipLines);
        System.err.println("trimTime = " + trimTime);
        System.err.println("nanVal = " + nanVal);
        System.err.println("leadingID = " + leadingID);
        System.err.println("SourceName = " + SourceName);
        System.err.println("HeaderLine = " + HeaderLine);
        System.err.println("loggerFileName = " + loggerFileName);
        System.err.println("CTrootfolder = " + CTrootfolder);
    }

    //
    // Run CTlogger
    //
    if (!repeatFetch)
        getData(true); // run once
    else {
        Timer timer = new Timer();
        TimerTask fetchTask = new TimerTask() {
            @Override
            public void run() {
                if (newFileMode)
                    getData(true);
                else if (getData(false)) { // pick up from old data if you can
                    System.err.println("Failed to pick up from old data, refetch from start of file...");
                    boolean status = getData(true);
                    System.err.println("refetch status: " + status);
                }
                if (debug)
                    System.err.println("Waiting for data, pollInterval: " + pollInterval + " sec...");
            };
        };
        // repeatFetch@autoflush interval, convert to msec
        if ((autoflush > 0) && (pollInterval > autoflush))
            pollInterval = autoflush;
        timer.scheduleAtFixedRate(fetchTask, 0, pollInterval * 1000);
    }
}

From source file:Main.java

/**
 * For a string containing a number delta as judged by
 * <code>isNumberDelta()</code>, return the numerical value, rounded to
 * an integer./*from   ww  w  . j a v a2  s  . com*/
 *
 * @return the numeric value, rounded to an integer, or 0
 * if the string is not a valid number delta.
 */
public static int getNumberDelta(String string) {
    String s = string.trim();
    if (!isNumberDelta(s))
        return 0;
    double value = 0;
    try {
        value = Double.parseDouble(s);
    } catch (NumberFormatException e) {
        //logger.warn("Unexpected number value `" + s + "'");
    }
    return (int) Math.round(value);

}