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:gamlss.algorithm.Gamlss.java

/**
 * Main method.//from w ww  .  j a  v a 2  s  . c  o m
 * @param args -  command-line arguments
 */
public static void main(final String[] args) {

    //String fileName = "Data/dataReduced.csv";
    String fileName = "Data/oil.csv";
    // String fileName = "Data/sp.csv";
    //String fileName = "Data/dataReduced.csv";
    CSVFileReader readData = new CSVFileReader(fileName);
    readData.readFile();
    ArrayList<String> data = readData.storeValues;

    ArrayRealVector y = new ArrayRealVector(data.size());
    BlockRealMatrix muX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix sigmaX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix nuX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix tauX = new BlockRealMatrix(data.size(), 1);
    ArrayRealVector w = new ArrayRealVector(data.size());

    BlockRealMatrix muS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix sigmaS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix nuS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix tauS = new BlockRealMatrix(data.size(), 1);

    for (int i = 0; i < data.size(); i++) {
        String[] line = data.get(i).split(",");
        y.setEntry(i, Double.parseDouble(line[0]));
        muX.setEntry(i, 0, Double.parseDouble(line[1]));
        muS.setEntry(i, 0, Double.parseDouble(line[1]));
        sigmaX.setEntry(i, 0, Double.parseDouble(line[1]));
        sigmaS.setEntry(i, 0, Double.parseDouble(line[1]));
        nuX.setEntry(i, 0, Double.parseDouble(line[1]));
        nuS.setEntry(i, 0, Double.parseDouble(line[1]));
        tauX.setEntry(i, 0, Double.parseDouble(line[1]));
        tauS.setEntry(i, 0, Double.parseDouble(line[1]));
    }

    Hashtable<Integer, BlockRealMatrix> designMatrices = new Hashtable<Integer, BlockRealMatrix>();
    designMatrices.put(DistributionSettings.MU, muX);
    designMatrices.put(DistributionSettings.SIGMA, sigmaX);
    designMatrices.put(DistributionSettings.NU, nuX);
    designMatrices.put(DistributionSettings.TAU, tauX);

    HashMap<Integer, BlockRealMatrix> smoothMatrices = new HashMap<Integer, BlockRealMatrix>();
    smoothMatrices.put(DistributionSettings.MU, muS);
    smoothMatrices.put(DistributionSettings.SIGMA, sigmaS);
    smoothMatrices.put(DistributionSettings.NU, nuS);
    smoothMatrices.put(DistributionSettings.TAU, tauS);

    //smoothMatrices.put(DistributionSettings.MU, null);
    //smoothMatrices.put(DistributionSettings.SIGMA, null);
    //smoothMatrices.put(DistributionSettings.NU, null);
    //smoothMatrices.put(DistributionSettings.TAU, null);

    DistributionSettings.DISTR = DistributionSettings.SST;
    Controls.GLOB_DEVIANCE_TOL = 5500;
    Controls.INTER = 50;//only for the PB smoother
    Controls.SMOOTHER = Controls.PB; //or PB
    Controls.IS_SVD = true;
    Controls.BIG_DATA = true;
    Controls.JAVA_OPTIMIZATION = false;
    Controls.GAMLSS_NUM_CYCLES = 50;
    //Gamlss gamlss = new Gamlss(y, designMatrices, null);
    Gamlss gamlss = new Gamlss(y, designMatrices, null);
    //Gamlss gamlss = new Gamlss(y, null, smoothMatrices);      
    gamlss.saveFittedDistributionParameters("Data/oilresults.csv");
}

From source file:edu.duke.igsp.gkde.Main.java

public static void main(String[] argv) throws Exception {

    Options opts = new Options();
    opts.addOption("s", true, "wiggle track step (default=1)");
    opts.addOption("l", true, "feature length (default=600)");
    opts.addOption("f", true, "fragment size (default=estimated from data)");
    //    opts.addOption("b", true, "bandwidth (default=200)");
    //    opts.addOption("w", true, "window (default=3800");
    opts.addOption("wg", true, "wg threshold set (defualt = calculated)");
    opts.addOption("c", true, "genomic total read weight (defualt = calculated)");
    opts.addOption("h", false, "print usage");
    opts.addOption(OptionBuilder.withArgName("input dir").hasArg()
            .withDescription("input directory (default=current directory)").isRequired(false).create("d"));
    opts.addOption(OptionBuilder.withArgName("output dir").hasArg()
            .withDescription("output directory (default=current directory)").isRequired(false).create("o"));
    opts.addOption(OptionBuilder.withArgName("background dir").hasArg()
            .withDescription("background directory (default=none)").isRequired(false).create("b"));
    opts.addOption(OptionBuilder.withArgName("ploidy dir").hasArg()
            .withDescription("ploidy/input directory (default=none)").isRequired(false).create("p"));
    opts.addOption(OptionBuilder.withArgName("wig | bed | npf").hasArg()
            .withDescription("output format (default wig)").isRequired(false).create("of"));
    opts.addOption(OptionBuilder.withArgName("dnase | chip | faire | atac").hasArg()
            .withDescription("input data").isRequired(true).create("in"));
    opts.addOption(OptionBuilder.withArgName("weight clip").hasArg()
            .withDescription("weight clip value (default none)").isRequired(false).create("wc"));
    opts.addOption("t", true, "threshold (standard deviations) (default=4.0)");
    //    opts.addOption("r", true, "background ratio (default=2.0)");
    opts.addOption("v", false, "verbose output");

    CommandLineParser parser = new GnuParser();
    int fragment_size = -1;
    int fragment_offset = 0;
    long featureLength = 600l;
    //    float thresh = 2;
    float threshold = KDEChromosome.Settings.DEFAULT_THRESHOLD;
    int step = 1;
    boolean showHelp = false;
    boolean verbose = false;
    String inputDirectory = null;
    String backgroundDirectory = null;
    String ploidyDirectory = null;
    String[] files = null;/*w w  w. ja v  a  2s . c  om*/
    String[] bgfiles = {};
    String[] ipfiles = {};
    String outputFormat = "wig";
    String inputDataType = "dnase";
    File outputDirectory = new File(System.getProperty("user.dir"));

    long bandwidth = 0l;
    long window = 0l;
    double ncuts = 0.0d;
    float temp_threshold = 0f;
    int weight_clip = 0;

    System.out.println("F-Seq Version 1.85");

    try {
        CommandLine cmd = parser.parse(opts, argv);
        showHelp = (cmd.hasOption("h"));
        verbose = (cmd.hasOption("v"));
        if (cmd.hasOption("s"))
            step = Integer.parseInt(cmd.getOptionValue("s"));
        if (cmd.hasOption("f"))
            fragment_size = Integer.parseInt(cmd.getOptionValue("f"));
        if (cmd.hasOption("d")) //input directory
            inputDirectory = cmd.getOptionValue("d");
        if (cmd.hasOption("b")) //background directory
            backgroundDirectory = cmd.getOptionValue("b");
        if (cmd.hasOption("p")) //ploidy|input directory
            ploidyDirectory = cmd.getOptionValue("p");
        if (cmd.hasOption("l")) // bandwidth
            featureLength = Long.parseLong(cmd.getOptionValue("l"));
        if (cmd.hasOption("of")) { // output format
            outputFormat = cmd.getOptionValue("of");
            if (!outputFormat.equals("wig") && !outputFormat.equals("bed") && !outputFormat.equals("npf")) {
                System.out.println("Parameter error: output format must be 'wig' or 'bed'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("in")) { // input data type
            inputDataType = cmd.getOptionValue("in");
            if (!inputDataType.equals("dnase") && !inputDataType.equals("chip")
                    && !inputDataType.equals("faire") && !inputDataType.equals("atac")) {
                System.out.println(
                        "Parameter error: input data type must be 'dnase', 'chip', 'faire', or 'atac'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("wc")) { // weight clip
            weight_clip = Integer.parseInt(cmd.getOptionValue("wc"));
        }
        if (cmd.hasOption("t")) { // threshold (standard deviations)
            threshold = Float.parseFloat(cmd.getOptionValue("t"));
        }
        if (cmd.hasOption("o")) { // output directory
            String out = cmd.getOptionValue("o");
            outputDirectory = new File(out);
            if (!outputDirectory.exists() && !outputDirectory.isDirectory()) {
                System.out.println("Output directory '" + out + "' is not a valid directory.");
                showHelp = true;
            }
        }

        if (cmd.hasOption("wg"))
            temp_threshold = Float.parseFloat(cmd.getOptionValue("wg"));
        if (cmd.hasOption("c"))
            ncuts = Double.parseDouble(cmd.getOptionValue("c"));

        // TESTING ONLY
        //   if(cmd.hasOption("w")) // window
        //     window = Long.parseLong(cmd.getOptionValue("w"));
        //if(cmd.hasOption("b")) // window
        //  bandwidth = Long.parseLong(cmd.getOptionValue("b"));

        files = cmd.getArgs(); // input files
        //bgfiles = cmd.getArgs(); // background files
    } catch (Exception e) {
        System.out.println("Error parsing arguments: " + e.getMessage());
        e.printStackTrace();
        showHelp = true;
    }

    if (showHelp || (inputDirectory == null && files.length == 0)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fseq [options]... [file(s)]...", opts);
        System.exit(1);
    }

    File[] pfiles = getFiles(inputDirectory, files);
    File[] background_files = getFiles(backgroundDirectory, bgfiles);
    File[] ploidy_files = getFiles(ploidyDirectory, ipfiles);

    KDEChromosome[] chrs = null;
    // assume all files are of the same type, if not we'll get parsing errors
    String path = pfiles[0].getPath();
    String extension = path.substring(path.lastIndexOf('.')).toLowerCase();
    System.out.println("Path: " + path + ", extension: " + extension);
    if (extension.equals(".bed")) {
        System.out.println("Parsing BED file.");
        chrs = BedReader.read(pfiles);
    } else if (extension.equals(".sam") || extension.equals(".bam")) {
        System.out.println("Parsing SAM/BAM file.");
        chrs = SamReader.read(pfiles, weight_clip);
    }
    //KDEChromosome[] input = BedReader.read(ifiles);

    //compute fragment offset
    if (fragment_size == -1) {
        fragment_size = wgShiftCalc(chrs);
    }
    fragment_offset = (int) (fragment_size / 2);

    if (ncuts == 0.0d) {
        for (int i = 0; i < chrs.length; ++i) {
            // computes the total read weight of all cuts on a chromosome
            ncuts += chrs[i].getTotalWeight();
        }
    }

    KDEChromosome.Settings settings = null;
    if (bandwidth > 0 || window > 0) {
        settings = new KDEChromosome.Settings(bandwidth, window, threshold, fragment_offset, ncuts,
                inputDataType);
    } else {
        settings = new KDEChromosome.Settings(featureLength, threshold, fragment_offset, ncuts, inputDataType);
    }

    float wg_threshold = wgThreshold(settings, chrs);
    if (temp_threshold != 0f) {
        wg_threshold = temp_threshold;
    }
    //KDEChromosome.Settings bg_settings = null;
    //bg_settings = new KDEChromosome.Settings(featureLength*2, threshold, fragment_offset);

    //int background_size = 0;
    //int input_size = 0;
    //float bg_ratio = 0;
    //float sd = 0;

    if (verbose) {
        System.out.println("Settings: ");
        System.out.println("\twindow=" + (settings.window * 2));
        System.out.println("\tbandwidth=" + (settings.bandwidth));
        //System.out.println("\tfragment offset=" + (settings.offset));
        System.out.println("\tthreshold = " + wg_threshold);
        System.out.println("\test. fragment size = " + fragment_size);
        System.out.println("\tsequence length = " + chrs[0].getSequenceLength());
    }

    //    if(backgroundDirectory != null) {
    //       for(int i = 0; i < input.length; ++i) {
    //          background_size += input[i].getLength();
    //       }
    //       for(int i = 0; i < chrs.length; ++i) {
    //          input_size += chrs[i].getLength();
    //       }
    //       bg_ratio = (float)input_size/(float)background_size;
    //       sd = computeSD(bg_settings, input);
    //       //System.out.println("Sample Ratio: " + bg_ratio);
    //       //System.out.println("Input Size: " + input_size);
    //       //System.out.println("Background Size: " + background_size);
    //       //System.out.println("Input standard deviation: " + (settings.threshold * (float)Math.sqrt((double)bg_ratio * (double)sd * (double)sd)));
    //       //System.out.println("Data standard deviation: " + settings.threshold * computeSD(settings, chrs));
    //    }

    for (int i = 0; i < chrs.length; ++i) {
        if (chrs[i].getFirstPos() == chrs[i].getLastPos()) {
            System.out.println("Warning: " + chrs[i].getChromosome() + " has size zero.  Skipping.");
            continue;
        }
        File ofile = Util.makeUniqueFileWithExtension(outputDirectory, chrs[i].getChromosome(), outputFormat);

        DensityWriter dw = null;
        if (outputFormat.equals("wig")) {
            dw = new WiggleDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
        } else {
            if (outputFormat.equals("npf")) {
                dw = new NpfDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            } else {
                dw = new BedDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            }
        }

        //Function takes all? or new function for each?
        //      if(backgroundDirectory != null) {
        //         boolean hit = false;
        //         for(int j = 0; j < background_files.length; ++j) {
        //            if(background_files[j].getName().equals(chrs[i].getChromosome() + ".bff")) {
        //               System.out.println("Running background on Chromosome " + chrs[i].getChromosome());
        //               chrs[i].runBG(settings, dw, verbose, wg_threshold, background_files[j]);
        //               hit = true;
        //            }
        //         }
        //         if(!hit)
        //            System.out.println("No background for Chromosome " + chrs[i].getChromosome());
        //      } else {
        //         if(ploidyDirectory !=)
        //         chrs[i].run(settings, dw, verbose, wg_threshold);
        //      }
        chrs[i].run(settings, dw, verbose, wg_threshold, background_files, ploidy_files);
        dw.close();
    }

    //kde.showGraph();
}

From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java

public static void main(String... args) throws IOException {
    Options options = new Options();
    Option opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(true);//from   ww  w.j  av  a  2s .c o m
    options.addOption(opt);

    opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens");
    options.addOption(opt);

    opt = new Option("correctValences", false, "Correct valences after the enumeration");
    options.addOption(opt);

    opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products");
    options.addOption(opt);

    opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent.");
    options.addOption(opt);

    opt = new Option("randomFraction", true, "Only output a fraction of the products.");
    options.addOption(opt);

    opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms.");
    options.addOption(opt);

    opt = new Option("notReacted", true,
            "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp("", options);
    }

    args = cmd.getArgs();
    if (args.length < 2) {
        exitWithHelp("Transformation and/or reagentFiles missing", options);
    }
    String smirks = args[0];
    if (new File(smirks).canRead())
        smirks = IOUtil.fileToString(smirks).trim();
    if (!smirks.contains(">>"))
        smirks = scaffoldToSmirks(smirks);
    String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length);

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String outFile = cmd.getOptionValue("out");
    OELibraryGen lg = new OELibraryGen();
    lg.Init(smirks);
    if (!lg.IsValid())
        exitWithHelp("Invalid Transform: " + smirks, options);

    lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit"));
    lg.SetValenceCorrection(cmd.hasOption("correctValences"));
    lg.SetRemoveUnmappedFragments(true);

    boolean regenerate2D = cmd.hasOption("regenerate2D");
    boolean reactAllSites = cmd.hasOption("reactAllSites");
    String unreactedFile = null;
    if (cmd.hasOption("notReacted")) {
        unreactedFile = cmd.getOptionValue("notReacted");
    }

    double randomFract = 2;
    if (cmd.hasOption("randomFraction"))
        randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction"));

    int maxAtoms = 0;
    if (cmd.hasOption("maxAtoms"))
        maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms"));

    SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles);
    en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile);
    en.delete();
}

From source file:com.twentyn.bioreactor.pH.ControlSystem.java

public static void main(String[] args) throws Exception {

    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from ww  w .j  a va  2  s . co m
    }

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

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

    SOLUTION solution = null;
    String acidOrBase = cl.getOptionValue(OPTION_CONTROL_SOLUTION);

    if (acidOrBase.equals(SOLUTION.ACID.name())) {
        solution = SOLUTION.ACID;
    }

    if (acidOrBase.equals(SOLUTION.BASE.name())) {
        solution = SOLUTION.BASE;
    }

    if (solution == null) {
        LOGGER.error("Input solution is neither %s or %s", SOLUTION.ACID.name(), SOLUTION.BASE.name());
        return;
    }

    Double targetPH = Double.parseDouble(cl.getOptionValue(OPTION_TARGET_PH));

    File sensorReadingDataFile = new File(
            cl.getOptionValue(OPTION_SENSOR_READING_FILE_LOCATION, SENSOR_READING_FILE_LOCATION));

    MotorPinConfiguration motorPinConfiguration = new MotorPinConfiguration(
            MotorPinConfiguration.PinNumberingScheme.BOARD);
    motorPinConfiguration.initializeGPIOPinsAndSetConfigToStartState();

    ControlSystem controlSystem = new ControlSystem(motorPinConfiguration, solution, targetPH,
            sensorReadingDataFile);
    controlSystem.registerModuleForObjectMapper(new JodaModule());
    try {
        controlSystem.run();
    } finally {
        LOGGER.info("Shutting down");
        controlSystem.shutdownFermentation();
    }
}

From source file:com.jug.MotherMachine.java

/**
 * PROJECT MAIN/*from  w  w  w.  j a va2  s .  com*/
 * ============
 *
 * @param args
 *            muh!
 */
public static void main(final String[] args) {
    try {

        final MotherMachine main = new MotherMachine();
        guiFrame = new JFrame("Interactive MotherMachine");
        main.initMainWindow(guiFrame);

        props = main.loadParams();
        BGREM_TEMPLATE_XMIN = Integer
                .parseInt(props.getProperty("BGREM_TEMPLATE_XMIN", Integer.toString(BGREM_TEMPLATE_XMIN)));
        BGREM_TEMPLATE_XMAX = Integer
                .parseInt(props.getProperty("BGREM_TEMPLATE_XMAX", Integer.toString(BGREM_TEMPLATE_XMAX)));
        BGREM_X_OFFSET = Integer
                .parseInt(props.getProperty("BGREM_X_OFFSET", Integer.toString(BGREM_X_OFFSET)));
        GL_OFFSET_BOTTOM = Integer
                .parseInt(props.getProperty("GL_OFFSET_BOTTOM", Integer.toString(GL_OFFSET_BOTTOM)));
        GL_OFFSET_TOP = Integer.parseInt(props.getProperty("GL_OFFSET_TOP", Integer.toString(GL_OFFSET_TOP)));
        GL_OFFSET_LATERAL = Integer
                .parseInt(props.getProperty("GL_OFFSET_LATERAL", Integer.toString(GL_OFFSET_LATERAL)));
        MIN_CELL_LENGTH = Integer
                .parseInt(props.getProperty("MIN_CELL_LENGTH", Integer.toString(MIN_CELL_LENGTH)));
        MIN_GAP_CONTRAST = Double
                .parseDouble(props.getProperty("MIN_GAP_CONTRAST", Double.toString(MIN_GAP_CONTRAST)));
        SIGMA_PRE_SEGMENTATION_X = Double.parseDouble(
                props.getProperty("SIGMA_PRE_SEGMENTATION_X", Double.toString(SIGMA_PRE_SEGMENTATION_X)));
        SIGMA_PRE_SEGMENTATION_Y = Double.parseDouble(
                props.getProperty("SIGMA_PRE_SEGMENTATION_Y", Double.toString(SIGMA_PRE_SEGMENTATION_Y)));
        SIGMA_GL_DETECTION_X = Double
                .parseDouble(props.getProperty("SIGMA_GL_DETECTION_X", Double.toString(SIGMA_GL_DETECTION_X)));
        SIGMA_GL_DETECTION_Y = Double
                .parseDouble(props.getProperty("SIGMA_GL_DETECTION_Y", Double.toString(SIGMA_GL_DETECTION_Y)));
        DEFAULT_PATH = props.getProperty("DEFAULT_PATH", DEFAULT_PATH);

        GUI_POS_X = Integer.parseInt(props.getProperty("GUI_POS_X", Integer.toString(DEFAULT_GUI_POS_X)));
        GUI_POS_Y = Integer.parseInt(props.getProperty("GUI_POS_Y", Integer.toString(DEFAULT_GUI_POS_X)));
        GUI_WIDTH = Integer.parseInt(props.getProperty("GUI_WIDTH", Integer.toString(GUI_WIDTH)));
        GUI_HEIGHT = Integer.parseInt(props.getProperty("GUI_HEIGHT", Integer.toString(GUI_HEIGHT)));
        GUI_CONSOLE_WIDTH = Integer
                .parseInt(props.getProperty("GUI_CONSOLE_WIDTH", Integer.toString(GUI_CONSOLE_WIDTH)));
        // Iterate over all currently attached monitors and check if sceen position is actually possible,
        // otherwise fall back to the DEFAULT values and ignore the ones coming from the properties-file.
        boolean pos_ok = false;
        final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        final GraphicsDevice[] gs = ge.getScreenDevices();
        for (int i = 0; i < gs.length; i++) {
            final DisplayMode dm = gs[i].getDisplayMode();
            if (gs[i].getDefaultConfiguration().getBounds()
                    .contains(new java.awt.Point(GUI_POS_X, GUI_POS_Y))) {
                pos_ok = true;
            }
        }
        // None of the screens contained the top-left window coordinates --> fall back onto default values...
        if (!pos_ok) {
            GUI_POS_X = DEFAULT_GUI_POS_X;
            GUI_POS_Y = DEFAULT_GUI_POS_Y;
        }

        String path = props.getProperty("import_path", System.getProperty("user.home"));
        final File fPath = main.showStartupDialog(guiFrame, path);
        path = fPath.getAbsolutePath();
        props.setProperty("import_path", fPath.getAbsolutePath());

        // Setting up console window and window snapper...
        main.initConsoleWindow();
        main.showConsoleWindow();
        final JFrameSnapper snapper = new JFrameSnapper();
        snapper.addFrame(main.frameConsoleWindow);
        snapper.addFrame(guiFrame);

        // ---------------------------------------------------
        main.processDataFromFolder(path);
        // ---------------------------------------------------

        System.out.print("Build and show GUI...");
        // show loaded and annotated data
        ImageJFunctions.show(main.imgRaw, "Rotated & cropped raw data");
        ImageJFunctions.show(main.imgTemp, "Temporary");
        ImageJFunctions.show(main.imgAnnotated, "Annotated ARGB data");

        final MotherMachineGui gui = new MotherMachineGui(new MotherMachineModel(main));
        gui.setVisible(true);

        main.ij = new ImageJ();
        guiFrame.add(gui);
        guiFrame.setSize(GUI_WIDTH, GUI_HEIGHT);
        guiFrame.setLocation(GUI_POS_X, GUI_POS_Y);
        guiFrame.setVisible(true);

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                snapper.snapFrames(main.frameConsoleWindow, guiFrame, JFrameSnapper.EAST);
            }
        });

        System.out.println(" done!");
    } catch (final UnsatisfiedLinkError ulr) {
        JOptionPane.showMessageDialog(MotherMachine.guiFrame,
                "Could initialize Gurobi.\n"
                        + "You might not have installed Gurobi properly or you miss a valid license.\n"
                        + "Please visit 'www.gurobi.com' for further information.\n\n" + ulr.getMessage(),
                "Gurobi Error?", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:net.myrrix.online.eval.ParameterOptimizer.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.err.println(//from www.j av a  2  s.c  o m
                "Usage: dataDirectory numSteps evaluationPercentage property=min:max [property2=min2:max2 ...]");
        return;
    }

    final File dataDir = new File(args[0]);
    Preconditions.checkArgument(dataDir.exists() && dataDir.isDirectory(), "Not a directory: %s", dataDir);
    Preconditions.checkArgument(dataDir.listFiles().length > 0, "No files in: %s", dataDir);
    int numSteps = Integer.parseInt(args[1]);
    Preconditions.checkArgument(numSteps >= 2, "# steps must be at least 2: %s", numSteps);
    final double evaluationPercentage = Double.parseDouble(args[2]);
    Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0,
            "evaluationPercentage must be in (0,1]: %s", evaluationPercentage);

    Map<String, ParameterRange> parameterRanges = Maps.newHashMapWithExpectedSize(args.length);
    for (int i = 3; i < args.length; i++) {
        String[] propValue = EQUALS.split(args[i]);
        String systemProperty = propValue[0];
        String[] minMax = COLON.split(propValue[1]);
        ParameterRange range;
        try {
            int min = Integer.parseInt(minMax[0]);
            int max = Integer.parseInt(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        } catch (NumberFormatException ignored) {
            double min = Double.parseDouble(minMax[0]);
            double max = Double.parseDouble(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        }
        parameterRanges.put(systemProperty, range);
    }

    Callable<Number> evaluator = new Callable<Number>() {
        @Override
        public Number call() throws IOException, TasteException, InterruptedException {
            MyrrixIRStatistics stats = (MyrrixIRStatistics) new PrecisionRecallEvaluator().evaluate(dataDir,
                    0.9, evaluationPercentage, null);
            return stats == null ? null : stats.getMeanAveragePrecision();
        }
    };

    ParameterOptimizer optimizer = new ParameterOptimizer(parameterRanges, numSteps, evaluator, false);
    Map<String, Number> optimalValues = optimizer.findGoodParameterValues();
    System.out.println(optimalValues);
}

From source file:com.genentech.chemistry.openEye.apps.SdfRMSDSphereExclusion.java

/**
 * @param args/* w ww.  j a va2s  .  c o  m*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_REFFILE, true,
            "Reference file of molecules which define pre-existign exclusion spheres.");
    options.addOption(opt);

    opt = new Option(OPT_RADIUS, true, "Radius of exclusion spehre in A2.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_GROUPBY, true,
            "Group by fieldname, run sphere exclusion for consecutive groups of records with same value for this field.");
    options.addOption(opt);

    opt = new Option(OPT_DONotOpt, false,
            "If specified the RMSD is computed without trying to optimize the alignment.");
    options.addOption(opt);

    opt = new Option(OPT_PRINT_All, false, "print all molecule, check includeIdx tag");
    options.addOption(opt);

    opt = new Option(OPT_MIRROR, false, "For non-chiral molecules also try mirror image");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String refFile = cmd.getOptionValue(OPT_REFFILE);
    String groupBy = cmd.getOptionValue(OPT_GROUPBY);
    boolean doOptimize = !cmd.hasOption(OPT_DONotOpt);
    double radius = Double.parseDouble(cmd.getOptionValue(OPT_RADIUS));
    boolean printAll = cmd.hasOption(OPT_PRINT_All);
    boolean doMirror = cmd.hasOption(OPT_MIRROR);

    SdfRMSDSphereExclusion sphereExclusion = new SdfRMSDSphereExclusion(refFile, outFile, radius, printAll,
            doMirror, doOptimize, groupBy);

    sphereExclusion.run(inFile);
    sphereExclusion.close();
}

From source file:com.oltpbenchmark.multitenancy.MuTeBench.java

/**
 * @param args/*from   www  . j a  v a 2  s  . c  o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String duration = null;
    String scenarioFile = null;

    // -------------------------------------------------------------------
    // INITIALIZE LOGGING
    // -------------------------------------------------------------------
    String log4jPath = System.getProperty("log4j.configuration");
    if (log4jPath != null) {
        org.apache.log4j.PropertyConfigurator.configure(log4jPath);
    } else {
        throw new RuntimeException("Missing log4j.properties file");
    }

    // -------------------------------------------------------------------
    // PARSE COMMAND LINE PARAMETERS
    // -------------------------------------------------------------------
    CommandLineParser parser = new PosixParser();
    XMLConfiguration pluginConfig = null;
    try {
        pluginConfig = new XMLConfiguration("config/plugin.xml");
    } catch (ConfigurationException e1) {
        LOG.info("Plugin configuration file config/plugin.xml is missing");
        e1.printStackTrace();
    }
    pluginConfig.setExpressionEngine(new XPathExpressionEngine());
    Options options = new Options();
    options.addOption("s", "scenario", true, "[required] Workload scenario file");
    options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation");
    options.addOption("r", "runtime", true,
            "maximum runtime  (no events will be started after finishing runtime)");
    options.addOption("v", "verbose", false, "Display Messages");
    options.addOption("g", "gui", false, "Show controlling GUI");
    options.addOption("h", "help", false, "Print this help");
    options.addOption("o", "output", true, "Output file (default System.out)");
    options.addOption("b", "baseline", true, "Output files of previous baseline run");
    options.addOption(null, "histograms", false, "Print txn histograms");
    options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file");

    // parse the command line arguments
    CommandLine argsLine = parser.parse(options, args);
    if (argsLine.hasOption("h")) {
        printUsage(options);
        return;
    } else if (!argsLine.hasOption("scenario")) {
        INIT_LOG.fatal("Missing scenario description file");
        System.exit(-1);
    } else
        scenarioFile = argsLine.getOptionValue("scenario");
    if (argsLine.hasOption("r"))
        duration = argsLine.getOptionValue("r");
    if (argsLine.hasOption("runtime"))
        duration = argsLine.getOptionValue("runtime");

    // -------------------------------------------------------------------
    // CREATE TENANT SCHEDULE
    // -------------------------------------------------------------------
    INIT_LOG.info("Create schedule");
    Schedule schedule = new Schedule(duration, scenarioFile);
    HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents();
    ArrayList<Integer> tenantList = schedule.getTenantList();

    List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>();

    for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) {
        int tenantID = tenantList.get(tenInd);
        for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) {

            BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID)
                    .getBenchmarkSettings(tenEvent);

            // update benchmark Settings
            benchmarkSettings.setTenantID(tenantID);

            // -------------------------------------------------------------------
            // GET PLUGIN LIST
            // -------------------------------------------------------------------
            String plugins = benchmarkSettings.getBenchmark();
            String[] pluginList = plugins.split(",");

            String configFile = benchmarkSettings.getConfigFile();
            XMLConfiguration xmlConfig = new XMLConfiguration(configFile);
            xmlConfig.setExpressionEngine(new XPathExpressionEngine());
            int lastTxnId = 0;

            for (String plugin : pluginList) {

                // ----------------------------------------------------------------
                // WORKLOAD CONFIGURATION
                // ----------------------------------------------------------------

                String pluginTest = "";

                pluginTest = "[@bench='" + plugin + "']";

                WorkloadConfiguration wrkld = new WorkloadConfiguration();
                wrkld.setTenantId(tenantID);
                wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID));
                wrkld.setXmlConfig(xmlConfig);
                wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID)));
                wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID));
                wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID));
                wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID));
                wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID));
                wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID));
                String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"),
                        tenantID);
                int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString));
                wrkld.setTerminals(terminals);
                int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1"));
                if (taSize < 0)
                    INIT_LOG.fatal("taSize must not be negative!");
                wrkld.setTaSize(taSize);
                wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false));
                wrkld.setIsolationMode(setTenantIDinString(
                        xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID));
                wrkld.setScaleFactor(Double
                        .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID)));
                wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false));

                int size = xmlConfig.configurationsAt("/works/work").size();

                for (int i = 1; i < size + 1; i++) {
                    SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]");
                    List<String> weight_strings;

                    // use a workaround if there multiple workloads or
                    // single
                    // attributed workload
                    if (pluginList.length > 1 || work.containsKey("weights[@bench]")) {
                        weight_strings = get_weights(plugin, work);
                    } else {
                        weight_strings = work.getList("weights[not(@bench)]");
                    }
                    int rate = 1;
                    boolean rateLimited = true;
                    boolean disabled = false;

                    // can be "disabled", "unlimited" or a number
                    String rate_string;
                    rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID);
                    rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string),
                            tenantID);
                    if (rate_string.equals(RATE_DISABLED)) {
                        disabled = true;
                    } else if (rate_string.equals(RATE_UNLIMITED)) {
                        rateLimited = false;
                    } else if (rate_string.isEmpty()) {
                        LOG.fatal(String.format(
                                "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s",
                                i, plugin));
                        System.exit(-1);
                    } else {
                        try {
                            rate = Integer.parseInt(rate_string);
                            if (rate < 1) {
                                LOG.fatal("Tenant " + tenantID
                                        + ": Rate limit must be at least 1. Use unlimited or disabled values instead.");
                                System.exit(-1);
                            }
                        } catch (NumberFormatException e) {
                            LOG.fatal(String.format(
                                    "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number",
                                    RATE_DISABLED, RATE_UNLIMITED));
                            System.exit(-1);
                        }
                    }
                    Phase.Arrival arrival = Phase.Arrival.REGULAR;
                    String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID);
                    if (arrive.toUpperCase().equals("POISSON"))
                        arrival = Phase.Arrival.POISSON;

                    int activeTerminals;
                    activeTerminals = Integer.parseInt(setTenantIDinString(
                            work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)),
                            tenantID));
                    activeTerminals = Integer.parseInt(setTenantIDinString(
                            work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)),
                            tenantID));
                    if (activeTerminals > terminals) {
                        LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i
                                + ": number of active terminals" + ""
                                + "is bigger than the total number of terminals");
                        System.exit(-1);
                    }
                    wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)),
                            rate, weight_strings, rateLimited, disabled, activeTerminals, arrival);
                } // FOR

                int numTxnTypes = xmlConfig
                        .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
                if (numTxnTypes == 0 && pluginList.length == 1) {
                    // if it is a single workload run, <transactiontypes />
                    // w/o attribute is used
                    pluginTest = "[not(@bench)]";
                    numTxnTypes = xmlConfig
                            .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
                }
                wrkld.setNumTxnTypes(numTxnTypes);

                // CHECKING INPUT PHASES
                int j = 0;
                for (Phase p : wrkld.getAllPhases()) {
                    j++;
                    if (p.getWeightCount() != wrkld.getNumTxnTypes()) {
                        LOG.fatal(String.format("Tenant " + tenantID
                                + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types",
                                j, p.getWeightCount(), wrkld.getNumTxnTypes()));
                        System.exit(-1);
                    }
                } // FOR

                // Generate the dialect map
                wrkld.init();

                assert (wrkld.getNumTxnTypes() >= 0);
                assert (xmlConfig != null);

                // ----------------------------------------------------------------
                // BENCHMARK MODULE
                // ----------------------------------------------------------------

                String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']");

                if (classname == null) {
                    throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml");
                }
                BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld },
                        new Class<?>[] { WorkloadConfiguration.class });
                assert (benchList.get(0) != null);

                Map<String, Object> initDebug = new ListOrderedMap<String, Object>();
                initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname));
                initDebug.put("Configuration", configFile);
                initDebug.put("Type", wrkld.getDBType());
                initDebug.put("Driver", wrkld.getDBDriver());
                initDebug.put("URL", wrkld.getDBConnection());
                initDebug.put("Isolation", setTenantIDinString(
                        xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID));
                initDebug.put("Scale Factor", wrkld.getScaleFactor());
                INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug));
                INIT_LOG.info(SINGLE_LINE);

                // Load TransactionTypes
                List<TransactionType> ttypes = new ArrayList<TransactionType>();

                // Always add an INVALID type for Carlo
                ttypes.add(TransactionType.INVALID);
                int txnIdOffset = lastTxnId;
                for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) {
                    String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]";
                    String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID);
                    int txnId = i + 1;
                    if (xmlConfig.containsKey(key + "/id")) {
                        txnId = Integer
                                .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID));
                    }
                    ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset));
                    lastTxnId = i;
                } // FOR
                TransactionTypes tt = new TransactionTypes(ttypes);
                wrkld.setTransTypes(tt);
                if (benchmarkSettings.getBenchmarkSlaFile() != null)
                    wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile());
                LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt);

                bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent));
                bench.setTenantID(tenantID);
                bench.setBenchmarkSettings(benchmarkSettings);
                benchList.add(bench);
            }
        }
    }
    // create result collector
    ResultCollector rCollector = new ResultCollector(tenantList);

    // execute benchmarks in parallel
    ArrayList<Thread> benchThreads = new ArrayList<Thread>();
    for (BenchmarkModule benchmark : benchList) {
        BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine);
        Thread t = new Thread(benchThread);
        t.start();
        benchThreads.add(t);
        benchmark.getWorkloadConfiguration().setrCollector(rCollector);
    }

    // waiting for completion of all benchmarks
    for (Thread t : benchThreads) {
        t.join();
    }

    // print statistics
    int analysisBuckets = -1;
    if (argsLine.hasOption("analysis-buckets"))
        analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets"));
    String output = null;
    if (argsLine.hasOption("o"))
        output = argsLine.getOptionValue("o");
    String baseline = null;
    if (argsLine.hasOption("b"))
        baseline = argsLine.getOptionValue("b");

    rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline);

    // create GUI
    if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) {
        try {
            Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector,
                    output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static double AmountShowBug(String sum) {
    return Double.parseDouble(sum.replace(",", ""));
}

From source file:Main.java

public static double getCashSum(String cashFlowSum) {
    return Double.parseDouble(cashFlowSum);
}