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:microbiosima.Microbiosima.java

/**
 * @param args//from  www . j  ava 2 s .  c  o  m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:microbiosima.SelectiveMicrobiosima.java

/**
 * @param args/*from w ww  . ja v  a 2 s .co m*/
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    int populationSize = 500;//Integer.parseInt(parameters[1]);
    int microSize = 1000;//Integer.parseInt(parameters[2]);
    int numberOfSpecies = 150;//Integer.parseInt(parameters[3]);
    int numberOfGeneration = 10000;
    int Ngene = 10;
    int numberOfObservation = 100;
    int numberOfReplication = 10;
    double Ngenepm = 5;
    double pctEnv = 0;
    double pctPool = 0;
    double msCoeff = 1;
    double hsCoeff = 1;
    boolean HMS_or_TMS = true;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe"
                    + " [default: 500 1000 150 10000 10 5]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n"
            + "  msCoeff            Parameter related to microbe selection strength\n"
            + "  hsCoeff            Parameter related to host selection strength\n"
            + "  HMS_or_TMS         String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n"
            + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 5) {
            System.out.println(
                    "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got "
                            + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            msCoeff = Double.parseDouble(pct_config[2]);
            hsCoeff = Double.parseDouble(pct_config[3]);
            if (pct_config[4].equals("HMS"))
                HMS_or_TMS = true;
            if (pct_config[4].equals("TMS"))
                HMS_or_TMS = false;
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }
            if (msCoeff < 1) {
                System.out.println(
                        "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff="
                                + msCoeff + ")! EXIT");
                System.exit(3);
            }
            if (hsCoeff < 1) {
                System.out.println(
                        "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff="
                                + hsCoeff + ")! EXIT");
                System.exit(3);
            }
            if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) {
                System.out.println(
                        "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS="
                                + pct_config[4] + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
            Ngene = Integer.parseInt(configs[4]);
            Ngenepm = Double.parseDouble(configs[5]);
            if (Ngenepm > Ngene) {
                System.out.println(
                        "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT");
                System.exit(3);
            }
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication)
            .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ")
            .append(Ngenepm).append("\n");
    System.out.println(sb.toString());

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }
    int[] fitnessToHost = new int[Ngene];
    int[] fitnessToMicrobe = new int[Ngene];

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix;
        if (HMS_or_TMS)
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt";
        else
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt";
        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {
            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));
            PrintWriter file7 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix)));
            PrintWriter file8 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix)));
            PrintWriter file9 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix)));
            PrintWriter file10 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix)));
            PrintWriter file11 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix)));
            PrintWriter file12 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix)));
            for (int i = 0; i < Ngene; i++) {
                fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1;
                fitnessToHost[i] = MathUtil.getNextInt(2) - 1;
            }
            MathUtil.setSeed(rep % numberOfReplication);
            SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm,
                    msCoeff, fitnessToHost, fitnessToMicrobe);
            MathUtil.setSeed();
            SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize,
                    pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    //file1.print(population.gammaDiversity(false));
                    //file2.print(population.alphaDiversity(false));
                    //file1.print("\t");
                    //file2.print("\t");
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    //file3.print(population.betaDiversity(true));
                    //file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                    file7.print(population.averageHostFitness());
                    file7.print("\t");
                    file7.println(population.varianceHostFitness());
                    file8.println(population.cosOfMH());
                    file9.println(population.printOutHFitness());
                    file10.println(population.printOutMFitness());
                    file11.println(population.printBacteriaContents());
                }
                population.getNextGen();
            }
            for (SelectiveIndividual host : population.getIndividuals()) {
                file12.println(host.printBacteriaContents());
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
            file7.close();
            file8.close();
            file9.close();
            file10.close();
            file11.close();
            file12.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPNNFinder.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from   w w  w  .  j  a  v a 2 s  . c o  m
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp("Unknown param: " + args[0]);
    }

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

    int nCpu = 1;
    int maxNeighbors = 1;
    double minSim = 0D;

    String fpTag = cmd.getOptionValue("fpTag");
    String idTag = cmd.getOptionValue("idTag");
    boolean doMaxTanimoto = cmd.hasOption("maxTanimoto");
    boolean printAll = cmd.hasOption("printAll");

    String d = cmd.getOptionValue("nCpu");
    if (d != null)
        nCpu = Integer.parseInt(d);

    d = cmd.getOptionValue("maxNeighbors");
    if (d != null)
        maxNeighbors = Integer.parseInt(d);

    d = cmd.getOptionValue("minSimilarity");
    if (d != null)
        minSim = Double.parseDouble(d);

    String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove");

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    String tabOutput = cmd.getOptionValue("tabOutput");
    boolean outputDuplicates = cmd.hasOption("outputDuplicates");

    if (outputDuplicates && tabOutput != null)
        exitWithHelp("-outputDuplicates will not work with tabOutput");

    if (outputDuplicates && refFile == null)
        exitWithHelp("-outputDuplicates requires -ref ");

    if ("tab".equalsIgnoreCase(tabOutput) && refFile != null)
        exitWithHelp("-tabOutput tab: does not work with reference file");

    if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1)
        exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1");

    if (cmd.hasOption("countSimilarAbove") && tabOutput != null)
        exitWithHelp("-countSimilarAbove not supported for tab or vTab output");

    if (printAll && !(maxNeighbors > 1 || minSim > 0))
        exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0");

    if (printAll && tabOutput != null)
        System.err.println("WARNING: printAll ignored tor tab output!\n");

    SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto,
            fpTag);

    if (refFile == null) {
        perfromMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, printAll);

    } else {
        performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, outputDuplicates, printAll);
    }

}

From source file:it.geosolutions.unredd.apputil.AreaBuilder.java

public static void main(String[] args) {
    Option help = OptionBuilder.withLongOpt("help").withDescription("print help").create('?');

    Options helpOptions = new Options().addOption(help);

    Options options = new Options().addOption(help)
            .addOption(OptionBuilder.withLongOpt("extents").withArgName("n/e/s/w")
                    .withDescription("extents in the format n/e/s/w").hasArgs(4).withValueSeparator('/')
                    .isRequired().withType(Double.class).create(OPT_EXTENTS))
            .addOption(OptionBuilder.withLongOpt("size").withArgName("width,height")
                    .withDescription("size of output image in pixel in the format width,height").hasArgs(2)
                    .withValueSeparator(',').isRequired().withType(Integer.class).create(OPT_SIZE))
            .addOption(OptionBuilder.withLongOpt("outfile").withArgName("file")
                    .withDescription("the output tiff file").hasArg().isRequired().withType(String.class)
                    .create(OPT_OUTFILE))
            .addOption(OptionBuilder.withLongOpt("mem").withArgName("megabytes")
                    .withDescription("the max memory available for the operation").hasArg().create(OPT_MEM))
            .addOption(OptionBuilder.withLongOpt("threads").withArgName("numThreads")
                    .withDescription("number of threads JAI will use").hasArg().create(OPT_THREADS));

    try {//w  w w .j  a v a  2  s  .co m

        //=== Create parser
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        //=== Parse input params
        String sFile = cmd.getOptionValue(OPT_OUTFILE);

        String[] sSizeArr = cmd.getOptionValues(OPT_SIZE);
        if (sSizeArr.length != 2) {
            LOGGER.error("size requires 2 args");
            return;
        }
        String[] sExtArr = cmd.getOptionValues(OPT_EXTENTS);
        if (sExtArr.length != 4) {
            LOGGER.error("extents require 4 args");
            return;
        }

        File file = new File(sFile);
        LOGGER.info("Output file " + file);

        int w = Integer.parseInt(sSizeArr[0]);
        int h = Integer.parseInt(sSizeArr[1]);
        LOGGER.info("Image size " + w + " x " + h);

        double boxn = Double.parseDouble(sExtArr[0]);
        double boxe = Double.parseDouble(sExtArr[1]);
        double boxs = Double.parseDouble(sExtArr[2]);
        double boxw = Double.parseDouble(sExtArr[3]);
        LOGGER.info("Image bbox is n:" + boxn + "e:" + boxe + " s:" + boxs + " w:" + boxw);

        //=== Parse and set tilecache memory
        Long mega = 512l;
        if (cmd.hasOption(OPT_MEM)) {
            mega = Long.parseLong(cmd.getOptionValue(OPT_MEM));
            LOGGER.info("JAI tilecache memory set to " + mega + "MB");
        } else {
            LOGGER.info("JAI tilecache memory defaulting to " + mega + "MB");
        }

        JAI.getDefaultInstance().getTileCache().setMemoryCapacity(mega * MEGA);

        //=== Parse and set JAI parallelism level
        int threads = 4;
        if (cmd.hasOption(OPT_THREADS)) {
            threads = Integer.parseInt(cmd.getOptionValue(OPT_THREADS));
            LOGGER.info("JAI tile scheduler parallelism set to " + threads);
        } else {
            LOGGER.info("JAI tile scheduler parallelism defaulting to " + threads);
        }

        TileScheduler ts = JAI.getDefaultInstance().getTileScheduler();
        ts.setParallelism(threads);
        ts.setPrefetchParallelism(threads);

        //=== Create grid and save

        System.setProperty("org.geotools.referencing.forceXY", "true");
        GridCoverage2D grid = createAreaGrid(w, h, boxw, boxe, boxs, boxn);
        saveAreaGrid(grid, file);

    } catch (ParseException ex) {

        CommandLine cmd0 = null;
        try { // find out if an help was requested (it's missing mandatory params)
            CommandLineParser helpParser = new PosixParser();
            cmd0 = helpParser.parse(helpOptions, args);
        } catch (ParseException ex1) {
            LOGGER.error("Unexpected error: " + ex1);
        }

        if (cmd0 == null || !cmd0.hasOption("help")) {
            LOGGER.error("Parse error: " + ex);
        }

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("createAreaLayer", options);
    } catch (Exception e) {
        LOGGER.error("Unexpected exception", e);
    }
}

From source file:com.act.lcms.ExtractFromNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 || !args[0].endsWith(".nc")) {
        throw new RuntimeException(
                "Needs (1) NetCDF .nc file, " + "(2) mass value, e.g., 132.0772 for debugging, "
                        + "(3) how many timepoints to process (-1 for all), "
                        + "(4) prefix for .data and rendered .pdf, '-' for stdout");
    }/*from ww w.j a v a  2s . c  om*/

    String netCDF = args[0];
    Double mz = Double.parseDouble(args[1]);
    Integer numSpectraToProcess = Integer.parseInt(args[2]);
    String outPrefix = args[3];
    String outPDF = outPrefix.equals("-") ? null : outPrefix + ".pdf";
    String outDATA = outPrefix.equals("-") ? null : outPrefix + ".data";

    ExtractFromNetCDFAroundMass e = new ExtractFromNetCDFAroundMass();
    List<Triple<Double, Double, Double>> window = e.get2DWindow(netCDF, mz, numSpectraToProcess);

    // Write data output to outfile
    PrintStream whereTo = outDATA == null ? System.out : new PrintStream(new FileOutputStream(outDATA));
    for (Triple<Double, Double, Double> xyz : window) {
        whereTo.format("%.4f\t%.4f\t%.4f\n", xyz.getLeft(), xyz.getMiddle(), xyz.getRight());
        whereTo.flush();
    }

    if (outDATA != null) {
        // if outDATA is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        whereTo.close();

        // render outDATA to outPDF using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot3D(outDATA, outPDF, netCDF, mz);
    }
}

From source file:edu.ntnu.EASY.Main.java

public static void main(String[] args) {

    CommandLine cl = null;//from   www  .  j  a  va 2  s  . co  m
    CommandLineParser clp = new BasicParser();
    HelpFormatter hf = new HelpFormatter();
    try {
        cl = clp.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        hf.printHelp(USAGE, options);
        System.exit(1);
    }

    if (cl.hasOption('h') || cl.hasOption('?')) {
        hf.printHelp(USAGE, options);
        System.exit(0);
    }

    Environment env = new Environment();

    env.populationSize = Integer.parseInt(cl.getOptionValue('p', "200"));
    env.maxGenerations = Integer.parseInt(cl.getOptionValue('g', "1000"));
    env.fitnessThreshold = 2.0;
    env.mutationRate = Double.parseDouble(cl.getOptionValue('m', "0.01"));
    env.crossoverRate = Double.parseDouble(cl.getOptionValue('c', "0.01"));
    env.numChildren = Integer.parseInt(cl.getOptionValue('b', "200"));
    env.numParents = Integer.parseInt(cl.getOptionValue('f', "20"));
    env.rank = Integer.parseInt(cl.getOptionValue('r', "10"));
    env.elitism = Integer.parseInt(cl.getOptionValue('e', "3"));

    ParentSelector<double[]> parentSelector = null;
    int parent = Integer.parseInt(cl.getOptionValue('P', "1"));
    switch (parent) {
    case 1:
        parentSelector = new FitnessProportionateSelector<double[]>(env.numParents);
        break;
    case 2:
        parentSelector = new RankSelector<double[]>(env.rank);
        break;
    case 3:
        parentSelector = new SigmaScaledSelector<double[]>(env.numParents);
        break;
    case 4:
        parentSelector = new TournamentSelector<double[]>(env.rank, env.numParents);
        break;
    case 5:
        parentSelector = new StochasticTournamentSelector<double[]>(env.rank, env.numParents, 0.3);
        break;
    case 6:
        parentSelector = new BoltzmanSelector<double[]>(env.numParents);
        break;
    default:
        System.out.printf("No such parent selector: %d%n", parent);
        hf.printHelp(USAGE, options);
        System.exit(1);
    }

    AdultSelector<double[]> adultSelector = null;
    int adult = Integer.parseInt(cl.getOptionValue('A', "1"));
    switch (adult) {
    case 1:
        adultSelector = new FullGenerationalReplacement<double[]>();
        break;
    case 2:
        adultSelector = new GenerationalMixing<double[]>(env.numAdults);
        break;
    case 3:
        adultSelector = new Overproduction<double[]>(env.numAdults);
        break;
    default:
        System.out.printf("No such adult selector: %d%n", adult);
        hf.printHelp(USAGE, options);
        System.exit(1);
    }

    String targetFile = cl.getOptionValue('t', "target.dat");

    double[] target = null;
    try {
        target = Util.readTargetSpikeTrain(targetFile);
    } catch (IOException e) {
        System.out.printf("Couldn't read target file: %s%n", targetFile);
        hf.printHelp(USAGE, options);
        System.exit(1);
    }

    FitnessCalculator<double[]> fitCalc = null;
    int calc = Integer.parseInt(cl.getOptionValue('C', "1"));
    switch (calc) {
    case 1:
        fitCalc = new SpikeTimeFitnessCalculator(target);
        break;
    case 2:
        fitCalc = new SpikeIntervalFitnessCalculator(target);
        break;
    case 3:
        fitCalc = new WaveformFitnessCalculator(target);
        break;
    default:
        System.out.printf("No such fitness calculator: %d%n", calc);
        hf.printHelp(USAGE, options);
        System.exit(1);
    }

    String output = cl.getOptionValue('o', "neuron");

    Incubator<double[], double[]> incubator = new NeuronIncubator(
            new NeuronReplicator(env.mutationRate, env.crossoverRate), env.numChildren);

    Evolution<double[], double[]> evo = new Evolution<double[], double[]>(fitCalc, adultSelector,
            parentSelector, incubator);

    NeuronReport report = new NeuronReport(env.maxGenerations);
    evo.runEvolution(env, report);

    try {
        PrintStream ps = new PrintStream(new FileOutputStream(output + ".log"));
        report.writeToStream(ps);
    } catch (FileNotFoundException e) {
        System.out.printf("Could not write to %s.log%n", output);
    }

    double[] bestPhenome = report.getBestPhenome();
    Plot train = Plot.newPlot("Neuron").setAxis("x", "ms").setAxis("y", "activation")
            .with("bestPhenome", bestPhenome).with("target", target).make();

    double[] averageFitness = report.getAverageFitness();
    double[] bestFitness = report.getBestFitness();

    Plot fitness = Plot.newPlot("Fitness").setAxis("x", "generation").setAxis("y", "fitness")
            .with("average", averageFitness).with("best", bestFitness).make();

    train.plot();
    fitness.plot();
    train.writeToFile(output + "-train");
    fitness.writeToFile(output + "-fitness");
}

From source file:apps.LuceneQuery.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("d", null, true, "index directory");
    options.addOption("i", null, true, "input file");
    options.addOption("s", null, true, "stop word file");
    options.addOption("n", null, true, "max # of results");
    options.addOption("o", null, true, "a TREC-style output file");
    options.addOption("r", null, true, "an optional QREL file, if specified,"
            + "we save results only for queries for which we find at least one relevant entry.");

    options.addOption("prob", null, true, "question sampling probability");
    options.addOption("max_query_qty", null, true, "a maximum number of queries to run");
    options.addOption("bm25_b", null, true, "BM25 parameter: b");
    options.addOption("bm25_k1", null, true, "BM25 parameter: k1");
    options.addOption("bm25fixed", null, false, "use the fixed BM25 similarity");

    options.addOption("seed", null, true, "random seed");

    Joiner commaJoin = Joiner.on(',');
    Joiner spaceJoin = Joiner.on(' ');

    options.addOption("source_type", null, true,
            "query source type: " + commaJoin.join(SourceFactory.getQuerySourceList()));

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    QrelReader qrels = null;//from  w  w w . ja  v  a2 s .com

    try {

        CommandLine cmd = parser.parse(options, args);

        String indexDir = null;

        if (cmd.hasOption("d")) {
            indexDir = cmd.getOptionValue("d");
        } else {
            Usage("Specify 'index directory'", options);
        }

        String inputFileName = null;

        if (cmd.hasOption("i")) {
            inputFileName = cmd.getOptionValue("i");
        } else {
            Usage("Specify 'input file'", options);
        }

        DictNoComments stopWords = null;

        if (cmd.hasOption("s")) {
            String stopWordFileName = cmd.getOptionValue("s");
            stopWords = new DictNoComments(new File(stopWordFileName), true /* lowercasing */);
            System.out.println("Using the stopword file: " + stopWordFileName);
        }

        String sourceName = cmd.getOptionValue("source_type");

        if (sourceName == null)
            Usage("Specify document source type", options);

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
            System.out.println("Retrieving at most " + numRet + " candidate entries.");
        }

        String trecOutFileName = null;

        if (cmd.hasOption("o")) {
            trecOutFileName = cmd.getOptionValue("o");
        } else {
            Usage("Specify 'a TREC-style output file'", options);
        }

        double fProb = 1.0f;

        if (cmd.hasOption("prob")) {
            try {
                fProb = Double.parseDouble(cmd.getOptionValue("prob"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'question sampling probability'", options);
            }
        }

        if (fProb <= 0 || fProb > 1) {
            Usage("Question sampling probability should be >0 and <=1", options);
        }

        System.out.println("Sample the following fraction of questions: " + fProb);

        float bm25_k1 = UtilConst.BM25_K1_DEFAULT, bm25_b = UtilConst.BM25_B_DEFAULT;

        if (cmd.hasOption("bm25_k1")) {
            try {
                bm25_k1 = Float.parseFloat(cmd.getOptionValue("bm25_k1"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'bm25_k1'", options);
            }
        }

        if (cmd.hasOption("bm25_b")) {
            try {
                bm25_b = Float.parseFloat(cmd.getOptionValue("bm25_b"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'bm25_b'", options);
            }
        }

        long seed = 0;

        String tmpl = cmd.getOptionValue("seed");

        if (tmpl != null)
            seed = Long.parseLong(tmpl);

        System.out.println("Using seed: " + seed);

        Random randGen = new Random(seed);

        System.out.println(String.format("BM25 parameters k1=%f b=%f ", bm25_k1, bm25_b));

        boolean useFixedBM25 = cmd.hasOption("bm25fixed");

        EnglishAnalyzer analyzer = new EnglishAnalyzer();
        Similarity similarity = null;

        if (useFixedBM25) {
            System.out.println(String.format("Using fixed BM25Simlarity, k1=%f b=%f", bm25_k1, bm25_b));
            similarity = new BM25SimilarityFix(bm25_k1, bm25_b);
        } else {
            System.out.println(String.format("Using Lucene BM25Similarity, k1=%f b=%f", bm25_k1, bm25_b));
            similarity = new BM25Similarity(bm25_k1, bm25_b);
        }

        int maxQueryQty = Integer.MAX_VALUE;

        if (cmd.hasOption("max_query_qty")) {
            try {
                maxQueryQty = Integer.parseInt(cmd.getOptionValue("max_query_qty"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'max_query_qty'", options);
            }
        }

        System.out.println(String.format("Executing at most %d queries", maxQueryQty));

        if (cmd.hasOption("r")) {
            String qrelFile = cmd.getOptionValue("r");
            System.out.println("Using the qrel file: '" + qrelFile
                    + "', queries not returning a relevant entry will be ignored.");
            qrels = new QrelReader(qrelFile);
        }

        System.out.println(String.format("Using indexing directory %s", indexDir));

        LuceneCandidateProvider candProvider = new LuceneCandidateProvider(indexDir, analyzer, similarity);
        TextCleaner textCleaner = new TextCleaner(stopWords);

        QuerySource inpQuerySource = SourceFactory.createQuerySource(sourceName, inputFileName);
        QueryEntry inpQuery = null;

        BufferedWriter trecOutFile = new BufferedWriter(new FileWriter(new File(trecOutFileName)));

        int questNum = 0, questQty = 0;

        long totalTimeMS = 0;

        while ((inpQuery = inpQuerySource.next()) != null) {
            if (questQty >= maxQueryQty)
                break;
            ++questNum;

            String queryID = inpQuery.mQueryId;

            if (randGen.nextDouble() <= fProb) {
                ++questQty;

                String tokQuery = spaceJoin.join(textCleaner.cleanUp(inpQuery.mQueryText));
                String query = TextCleaner.luceneSafeCleanUp(tokQuery).trim();

                ResEntry[] results = null;

                if (query.isEmpty()) {
                    results = new ResEntry[0];
                    System.out.println(String.format("WARNING, empty query id = '%s'", inpQuery.mQueryId));
                } else {

                    try {
                        long start = System.currentTimeMillis();

                        results = candProvider.getCandidates(questNum, query, numRet);

                        long end = System.currentTimeMillis();
                        long searchTimeMS = end - start;
                        totalTimeMS += searchTimeMS;

                        System.out.println(String.format(
                                "Obtained results for the query # %d (answered %d queries), queryID %s the search took %d ms, we asked for max %d entries got %d",
                                questNum, questQty, queryID, searchTimeMS, numRet, results.length));

                    } catch (ParseException e) {
                        e.printStackTrace();
                        System.err.println(
                                "Error parsing query: " + query + " orig question is :" + inpQuery.mQueryText);
                        System.exit(1);
                    }
                }

                boolean bSave = true;

                if (qrels != null) {
                    boolean bOk = false;
                    for (ResEntry r : results) {
                        String label = qrels.get(queryID, r.mDocId);
                        if (candProvider.isRelevLabel(label, 1)) {
                            bOk = true;
                            break;
                        }
                    }
                    if (!bOk)
                        bSave = false;
                }

                //            System.out.println(String.format("Ranking results the query # %d queryId='%s' save results? %b", 
                //                                              questNum, queryID, bSave));          
                if (bSave) {
                    saveTrecResults(queryID, results, trecOutFile, TREC_RUN, numRet);
                }
            }

            if (questNum % 1000 == 0)
                System.out.println(String.format("Proccessed %d questions", questNum));

        }

        System.out.println(String.format("Proccessed %d questions, the search took %f MS on average", questQty,
                (float) totalTimeMS / questQty));

        trecOutFile.close();

    } catch (ParseException e) {
        e.printStackTrace();
        Usage("Cannot parse arguments: " + e, options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:edu.uiowa.javatm.JavaTM.java

/**
 * @param args First one indicates which topic model to use
 *//*from w w w . ja  va2  s.c o  m*/
public static void main(String[] args) {
    TMGibbsSampler tmGibbsSampler = null;

    Option modelType = Option.builder("model").longOpt("model-type").desc("Type of topic models to use")
            .hasArg().required().build();

    Option dataName = Option.builder("name").longOpt("data-name").desc("Data name: used for saving outputs")
            .hasArg().required().build();

    Option alpha = Option.builder("a").longOpt("alpha")
            .desc("Dirichlet prior for document (author) over topic multinomial").hasArg().required().build();

    Option beta = Option.builder("b").longOpt("beta").desc("Dirichlet prior for topic over word multinomial")
            .hasArg().required().build();

    Option pi = Option.builder("p").longOpt("pi").desc("Dirichlet prior for topic over time multinomial")
            .hasArg().build();

    Option K = Option.builder("K").longOpt("K").desc("The number of timestamp indices").hasArg().build();

    /*Option tau = Option.builder("tau").longOpt("tau")
    .desc("Smoothing constant for topic time")
    .hasArg().build();*/

    Option doc = Option.builder("doc").longOpt("document-file").desc("WD matrix to use").hasArg().required()
            .build();

    Option voc = Option.builder("voc").longOpt("vocabulary-file")
            .desc("Vocabulary file of the corpus of interest").hasArg().required().build();

    Option auth = Option.builder("auth").longOpt("auth-file").desc("Author indices for each token").hasArg()
            .build();

    Option authArray = Option.builder("authArray").longOpt("author-list-file").desc("Author list").hasArg()
            .build();

    Option dkArray = Option.builder("dk").longOpt("document-time-file").desc("Document timestamp file").hasArg()
            .build();

    Option citationMat = Option.builder("cm").longOpt("citation-matrix")
            .desc("Citation overtime for the corpus").hasArg().build();

    Option numTopics = Option.builder("topic").longOpt("num-topics").desc("The total number of topics").hasArg()
            .required().build();

    Option numIters = Option.builder("iter").longOpt("num-iters").desc("The total number of iterations")
            .hasArg().required().build();

    Option outputDir = Option.builder("odir").longOpt("output-dir").desc("Output directory").hasArg().required()
            .build();

    Options options = new Options();
    options.addOption(modelType).addOption(alpha).addOption(beta).addOption(numTopics).addOption(K)
            .addOption(pi).addOption(citationMat).addOption(numIters).addOption(doc).addOption(voc)
            .addOption(dkArray).addOption(outputDir).addOption(auth).addOption(authArray).addOption(dataName);

    CommandLineParser parser = new DefaultParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String model = line.getOptionValue("model");
        String name = line.getOptionValue("name");
        String docFile = line.getOptionValue("doc");
        String vocFile = line.getOptionValue("voc");
        int topics = Integer.parseInt(line.getOptionValue("topic"));
        int iters = Integer.parseInt(line.getOptionValue("iter"));
        double a = Double.parseDouble(line.getOptionValue("a"));
        double b = Double.parseDouble(line.getOptionValue("b"));

        String modelLower = model.toLowerCase();
        if (modelLower.equals("lda")) {
            tmGibbsSampler = new LDAGibbsSampler(topics, iters, a, b, docFile, vocFile);
        } else if (modelLower.equals("at")) {
            String authFile = line.getOptionValue("auth");
            String authArrayFile = line.getOptionValue("authArray");
            //double tau_val = Double.parseDouble(line.getOptionValue("tau"));
            tmGibbsSampler = new ATGibbsSampler(topics, iters, a, b, docFile, vocFile, authFile, authArrayFile);
        } else if (modelLower.equals("tot")) {
            String dkFile = line.getOptionValue("dk");
            //double tau_val = Double.parseDouble(line.getOptionValue("tau"));
            tmGibbsSampler = new ToTGibbsSampler(topics, iters, a, b, docFile, vocFile, dkFile);
        } else if (modelLower.equals("tiot")) {
            String timeFile = line.getOptionValue("dk");
            String citationFile = line.getOptionValue("cm");
            double p = Double.parseDouble(line.getOptionValue("p"));
            //int k = Integer.parseInt(line.getOptionValue("K"));
            tmGibbsSampler = new TIOTGibbsSampler(topics, iters, a, b, p, docFile, vocFile, timeFile,
                    citationFile);
        } else {
            System.err.println("Invalid model type selection. Must be lda, at, tot or atot.");
            System.exit(ExitStatus.ILLEGAL_ARGUMENT);
        }

        long startTime = System.nanoTime();
        tmGibbsSampler.fit();
        TMOutcome outcome = tmGibbsSampler.get_outcome();
        long endTime = System.nanoTime();
        long duration = (endTime - startTime);
        System.out.println("Overall elapsed time: " + duration / 1000000000. + " seconds");

        tmGibbsSampler.showTopics(10);
        outcome.showTopicDistribution();

        String oDir = line.getOptionValue("odir");
        if (!oDir.endsWith("/")) {
            oDir = oDir + "/";
        }
        // append name to `oDir`
        oDir = oDir + name + "-";

        if (modelLower.contains("tot")) {
            // topic over time (tot and atot) has beta distribution parameters to write
            Utils.write2DArray(((ToTOutcome) outcome).getPsi(), oDir + "psi-" + modelLower + ".csv");
        }

        if (modelLower.contains("tiot")) {
            // topic over time (tot and atot) has beta distribution parameters to write
            Utils.write2DArray(((TIOTOutcome) outcome).getPsi(), oDir + "psi-" + modelLower + ".csv");
            double[][][] ga = ((TIOTOutcome) outcome).getGa();
            for (int t = 0; t < ga.length; t++) {
                Utils.write2DArray(ga[t], oDir + "gamma-" + t + "-" + modelLower + ".csv");
            }
        }

        Utils.write2DArray(outcome.getPhi(), oDir + "phi-" + modelLower + ".csv");
        Utils.write2DArray(outcome.getTheta(), oDir + "theta-" + modelLower + ".csv");

        System.out.println("Output files saved to " + oDir);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
    }

}

From source file:biomine.nodeimportancecompression.ImportanceCompressionReport.java

public static void main(String[] args) throws IOException, java.text.ParseException {
    opts.addOption("algorithm", true,
            "Used algorithm for compression. Possible values are 'brute-force', "
                    + "'brute-force-edges','brute-force-merges','randomized','randomized-merges',"
                    + "'randomized-edges'," + "'fast-brute-force',"
                    + "'fast-brute-force-merges','fast-brute-force-merge-edges'. Default is 'brute-force'.");
    opts.addOption("query", true, "Query nodes ids, separated by comma.");
    opts.addOption("queryfile", true, "Read query nodes from file.");
    opts.addOption("ratio", true, "Goal ratio");
    opts.addOption("importancefile", true, "Read importances straight from file");
    opts.addOption("keepedges", false, "Don't remove edges during merges");
    opts.addOption("connectivity", false, "Compute and output connectivities in edge oriented case");
    opts.addOption("paths", false, "Do path oriented compression");
    opts.addOption("edges", false, "Do edge oriented compression");
    // opts.addOption( "a",

    double sigma = 1.0;
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from   w ww.  j  a va  2s  .  c om*/

    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(0);
    }

    String queryStr = cmd.getOptionValue("query");
    String[] queryNodeIDs = {};
    double[] queryNodeIMP = {};
    if (queryStr != null) {
        queryNodeIDs = queryStr.split(",");
        queryNodeIMP = new double[queryNodeIDs.length];
        for (int i = 0; i < queryNodeIDs.length; i++) {
            String s = queryNodeIDs[i];
            String[] es = s.split("=");
            queryNodeIMP[i] = 1;
            if (es.length == 2) {
                queryNodeIDs[i] = es[0];
                queryNodeIMP[i] = Double.parseDouble(es[1]);
            } else if (es.length > 2) {
                System.out.println("Too many '=' in querynode specification: " + s);
            }
        }
    }

    String queryFile = cmd.getOptionValue("queryfile");
    Map<String, Double> queryNodes = Collections.EMPTY_MAP;
    if (queryFile != null) {
        File in = new File(queryFile);
        BufferedReader read = new BufferedReader(new FileReader(in));

        queryNodes = readMap(read);
        read.close();
    }

    String impfile = cmd.getOptionValue("importancefile");
    Map<String, Double> importances = null;
    if (impfile != null) {
        File in = new File(impfile);
        BufferedReader read = new BufferedReader(new FileReader(in));

        importances = readMap(read);
        read.close();
    }

    String algoStr = cmd.getOptionValue("algorithm");
    CompressionAlgorithm algo = null;

    if (algoStr == null || algoStr.equals("brute-force")) {
        algo = new BruteForceCompression();
    } else if (algoStr.equals("brute-force-edges")) {
        algo = new BruteForceCompressionOnlyEdges();
    } else if (algoStr.equals("brute-force-merges")) {
        algo = new BruteForceCompressionOnlyMerges();
    } else if (algoStr.equals("fast-brute-force-merges")) {
        //algo = new FastBruteForceCompressionOnlyMerges();
        algo = new FastBruteForceCompression(true, false);
    } else if (algoStr.equals("fast-brute-force-edges")) {
        algo = new FastBruteForceCompression(false, true);
        //algo = new FastBruteForceCompressionOnlyEdges();
    } else if (algoStr.equals("fast-brute-force")) {
        algo = new FastBruteForceCompression(true, true);
    } else if (algoStr.equals("randomized-edges")) {
        algo = new RandomizedCompressionOnlyEdges(); //modified
    } else if (algoStr.equals("randomized")) {
        algo = new RandomizedCompression();
    } else if (algoStr.equals("randomized-merges")) {
        algo = new RandomizedCompressionOnlyMerges();
    } else {
        System.out.println("Unsupported algorithm: " + algoStr);
        printHelp();
    }

    String ratioStr = cmd.getOptionValue("ratio");
    double ratio = 0;
    if (ratioStr != null) {
        ratio = Double.parseDouble(ratioStr);
    } else {
        System.out.println("Goal ratio not specified");
        printHelp();
    }

    String infile = null;
    if (cmd.getArgs().length != 0) {
        infile = cmd.getArgs()[0];
    } else {
        printHelp();
    }

    BMGraph bmg = BMGraphUtils.readBMGraph(new File(infile));
    HashMap<BMNode, Double> queryBMNodes = new HashMap<BMNode, Double>();
    for (String id : queryNodes.keySet()) {
        queryBMNodes.put(bmg.getNode(id), queryNodes.get(id));
    }

    long startMillis = System.currentTimeMillis();
    ImportanceGraphWrapper wrap = QueryImportance.queryImportanceGraph(bmg, queryBMNodes);

    if (importances != null) {
        for (String id : importances.keySet()) {
            wrap.setImportance(bmg.getNode(id), importances.get(id));
        }
    }

    ImportanceMerger merger = null;
    if (cmd.hasOption("edges")) {
        merger = new ImportanceMergerEdges(wrap.getImportanceGraph());
    } else if (cmd.hasOption("paths")) {
        merger = new ImportanceMergerPaths(wrap.getImportanceGraph());
    } else {
        System.out.println("Specify either 'paths' or 'edges'.");
        System.exit(1);
    }

    if (cmd.hasOption("keepedges")) {
        merger.setKeepEdges(true);
    }

    algo.compress(merger, ratio);
    long endMillis = System.currentTimeMillis();

    // write importance

    {
        BufferedWriter wr = new BufferedWriter(new FileWriter("importance.txt", false));
        for (BMNode nod : bmg.getNodes()) {
            wr.write(nod + " " + wrap.getImportance(nod) + "\n");
        }
        wr.close();
    }

    // write sum of all pairs of node importance    added by Fang
    /*   {
    BufferedWriter wr = new BufferedWriter(new FileWriter("sum_of_all_pairs_importance.txt", true));
    ImportanceGraph orig = wrap.getImportanceGraph();
    double sum = 0;
            
    for (int i = 0; i <= orig.getMaxNodeId(); i++) {
        for (int j = i+1; j <= orig.getMaxNodeId(); j++) {
            sum = sum+ wrap.getImportance(i)* wrap.getImportance(j);
        }
    }
            
    wr.write(""+sum);
    wr.write("\n");
    wr.close();
       }
            
    */

    // write uncompressed edges
    {
        BufferedWriter wr = new BufferedWriter(new FileWriter("edges.txt", false));
        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph ucom = merger.getUncompressedGraph();
        for (int i = 0; i <= orig.getMaxNodeId(); i++) {
            String iname = wrap.intToNode(i).toString();
            HashSet<Integer> ne = new HashSet<Integer>();
            ne.addAll(orig.getNeighbors(i));
            ne.addAll(ucom.getNeighbors(i));
            for (int j : ne) {
                if (i < j)
                    continue;
                String jname = wrap.intToNode(j).toString();
                double a = orig.getEdgeWeight(i, j);
                double b = ucom.getEdgeWeight(i, j);
                wr.write(iname + " " + jname + " " + a + " " + b + " " + Math.abs(a - b));
                wr.write("\n");
            }
        }
        wr.close();
    }
    // write distance
    {
        // BufferedWriter wr = new BufferedWriter(new
        // FileWriter("distance.txt",false));
        BufferedWriter wr = new BufferedWriter(new FileWriter("distance.txt", true)); //modified by Fang

        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph ucom = merger.getUncompressedGraph();
        double error = 0;
        for (int i = 0; i <= orig.getMaxNodeId(); i++) {
            HashSet<Integer> ne = new HashSet<Integer>();
            ne.addAll(orig.getNeighbors(i));
            ne.addAll(ucom.getNeighbors(i));
            for (int j : ne) {
                if (i <= j)
                    continue;
                double a = orig.getEdgeWeight(i, j);
                double b = ucom.getEdgeWeight(i, j);
                error += (a - b) * (a - b) * wrap.getImportance(i) * wrap.getImportance(j);
                // modify by Fang: multiply imp(u)imp(v)

            }
        }
        error = Math.sqrt(error);
        //////////error = Math.sqrt(error / 2); // modified by Fang: the error of each
        // edge is counted twice
        wr.write("" + error);
        wr.write("\n");
        wr.close();
    }
    // write sizes
    {
        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph comp = merger.getCurrentGraph();
        // BufferedWriter wr = new BufferedWriter(new
        // FileWriter("sizes.txt",false));
        BufferedWriter wr = new BufferedWriter(new FileWriter("sizes.txt", true)); //modified by Fang

        wr.write(orig.getNodeCount() + " " + orig.getEdgeCount() + " " + comp.getNodeCount() + " "
                + comp.getEdgeCount());
        wr.write("\n");
        wr.close();
    }
    //write time
    {
        System.out.println("writing time");
        BufferedWriter wr = new BufferedWriter(new FileWriter("time.txt", true)); //modified by Fang
        double secs = (endMillis - startMillis) * 0.001;
        wr.write("" + secs + "\n");
        wr.close();
    }

    //write change of connectivity for edge-oriented case       // added by Fang
    {
        if (cmd.hasOption("connectivity")) {

            BufferedWriter wr = new BufferedWriter(new FileWriter("connectivity.txt", true));
            ImportanceGraph orig = wrap.getImportanceGraph();
            ImportanceGraph ucom = merger.getUncompressedGraph();

            double diff = 0;

            for (int i = 0; i <= orig.getMaxNodeId(); i++) {
                ProbDijkstra pdori = new ProbDijkstra(orig, i);
                ProbDijkstra pducom = new ProbDijkstra(ucom, i);

                for (int j = i + 1; j <= orig.getMaxNodeId(); j++) {
                    double oriconn = pdori.getProbTo(j);
                    double ucomconn = pducom.getProbTo(j);

                    diff = diff + (oriconn - ucomconn) * (oriconn - ucomconn) * wrap.getImportance(i)
                            * wrap.getImportance(j);

                }
            }

            diff = Math.sqrt(diff);
            wr.write("" + diff);
            wr.write("\n");
            wr.close();

        }
    }

    //write output graph
    {
        BMGraph output = bmg;//new BMGraph(bmg);

        int no = 0;
        BMNode[] nodes = new BMNode[merger.getGroups().size()];
        for (ArrayList<Integer> gr : merger.getGroups()) {
            BMNode bmgroup = new BMNode("Group", "" + (no + 1));
            bmgroup.setAttributes(new HashMap<String, String>());
            bmgroup.put("autoedges", "0");
            nodes[no] = bmgroup;
            no++;
            if (gr.size() == 0)
                continue;
            for (int x : gr) {
                BMNode nod = output.getNode(wrap.intToNode(x).toString());
                BMEdge belongs = new BMEdge(nod, bmgroup, "belongs_to");
                output.ensureHasEdge(belongs);
            }
            output.ensureHasNode(bmgroup);
        }
        for (int i = 0; i < nodes.length; i++) {
            for (int x : merger.getCurrentGraph().getNeighbors(i)) {
                if (x == i) {
                    nodes[x].put("selfedge", "" + merger.getCurrentGraph().getEdgeWeight(i, x));
                    //ge.put("goodness", ""+merger.getCurrentGraph().getEdgeWeight(i, x));
                    continue;
                }
                BMEdge ge = new BMEdge(nodes[x], nodes[i], "groupedge");
                ge.setAttributes(new HashMap<String, String>());
                ge.put("goodness", "" + merger.getCurrentGraph().getEdgeWeight(i, x));
                output.ensureHasEdge(ge);
            }
        }
        System.out.println(output.getGroupNodes());

        BMGraphUtils.writeBMGraph(output, "output.bmg");
    }
}

From source file:ch.algotrader.starter.SimulationStarter.java

public static void main(String[] args) throws ConvergenceException, FunctionEvaluationException {

    if (args[0].equals("simulateWithCurrentParams")) {

        runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                .simulateWithCurrentParams(strategyGroup));

    } else if (args[0].equals("simulateBySingleParam")) {

        for (int i = 1; i < args.length; i++) {
            String[] params = args[i].split(":");
            runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                    .simulateBySingleParam(strategyGroup, params[0], params[1]));

        }/*from www. ja  va 2s . co  m*/

    } else if (args[0].equals("simulateByMultiParam")) {

        for (int i = 1; i < args.length; i++) {
            String[] touples = args[i].split(",");
            String[] parameters = new String[touples.length];
            String[] values = new String[touples.length];
            for (int j = 0; j < touples.length; j++) {
                parameters[j] = touples[j].split(":")[0];
                values[j] = touples[j].split(":")[1];
            }
            runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                    .simulateByMultiParam(strategyGroup, parameters, values));

        }

    } else if (args[0].equals("optimizeSingleParamLinear")) {

        for (int i = 1; i < args.length; i++) {
            String[] params = args[i].split(":");
            String parameter = params[0];
            double min = Double.parseDouble(params[1]);
            double max = Double.parseDouble(params[2]);
            double increment = Double.parseDouble(params[3]);

            runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                    .optimizeSingleParamLinear(strategyGroup, parameter, min, max, increment));

        }

    } else if (args[0].equals("optimizeSingleParamByValues")) {

        for (int i = 1; i < args.length; i++) {
            String[] params = args[i].split(":");
            String parameter = params[0];
            double[] values = new double[params.length - 1];
            for (int j = 1; j < params.length; j++) {
                values[j - 1] = Double.valueOf(params[j]);
            }

            runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                    .optimizeSingleParamByValues(strategyGroup, parameter, values));

        }
    } else if (args[0].equals("optimizeSingleParam")) {

        String[] params = args[1].split(":");
        String parameter = params[0];
        double min = Double.valueOf(params[1]);
        double max = Double.valueOf(params[2]);
        double accuracy = Double.valueOf(params[3]);

        runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                .optimizeSingleParam(strategyGroup, parameter, min, max, accuracy));

    } else if (args[0].equals("optimizeMultiParamLinear")) {

        String[] parameters = new String[args.length - 1];
        double[] mins = new double[args.length - 1];
        double[] maxs = new double[args.length - 1];
        double[] increments = new double[args.length - 1];
        for (int i = 1; i < args.length; i++) {

            String[] params = args[i].split(":");
            String parameter = params[0];
            double min = Double.valueOf(params[1]);
            double max = Double.valueOf(params[2]);
            double increment = Double.valueOf(params[3]);

            parameters[i - 1] = parameter;
            mins[i - 1] = min;
            maxs[i - 1] = max;
            increments[i - 1] = increment;
        }

        runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                .optimizeMultiParamLinear(strategyGroup, parameters, mins, maxs, increments));

    } else if (args[0].equals("optimizeMultiParam")) {

        String[] parameters = new String[args.length - 1];
        double[] starts = new double[args.length - 1];
        for (int i = 1; i < args.length; i++) {

            String[] params = args[i].split(":");
            String parameter = params[0];
            double start = Double.valueOf(params[1]);
            parameters[i - 1] = parameter;
            starts[i - 1] = start;
        }

        runSimulation((simulationExecutor, strategyGroup) -> simulationExecutor
                .optimizeMultiParam(strategyGroup, parameters, starts));

    } else {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("invalid command {}", args[0]);
        }
    }
}