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:net.cliftonsnyder.svgchart.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")");
    options.addOption("h", "height", true, "chart height");
    options.addOption("i", "input-file", true, "input file [default: stdin]");
    options.addOption("o", "output-file", true, "output file [default: stdout]");
    options.addOption("w", "width", true, "chart width");
    options.addOption("?", "help", false, "print a brief help message");

    Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES));
    type.setRequired(true);//from w ww . ja  va 2 s . c  om
    options.addOption(type);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp(USAGE, options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("unable to parse command line: " + exp.getMessage());
        formatter.printHelp(USAGE, options);
        System.exit(1);
    }

    SVGChart chart = null;
    String tmp = line.getOptionValue("type");
    Matcher m = null;
    for (Pattern p : SVGChart.TYPE_PATTERNS) {
        if ((m = p.matcher(tmp)).matches()) {
            switch (m.group().charAt(0)) {
            case 'l':
                // DEBUG
                System.err.println("line");
                break;
            case 'b':
                System.err.println("bar");
                chart = new BarChart();
                break;
            case 'p':
                System.err.println("pie");
                break;
            default:
                System.err.println("unknown or unimplemented chart type: '" + tmp + "'");
                System.exit(1);
            }
        }
    }

    try {
        chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'");
        System.exit(1);
    }

    try {
        chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'");
        System.exit(1);
    }

    InputStream in = System.in;
    tmp = line.getOptionValue("input-file", "-");
    if ("-".equals(tmp)) {
        in = System.in;
    } else {
        try {
            in = new FileInputStream(tmp);
        } catch (FileNotFoundException e) {
            System.err.println("input file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    PrintStream out = System.out;
    tmp = line.getOptionValue("output-file", "-");
    if ("-".equals(tmp)) {
        out = System.out;
    } else {
        try {
            out = new PrintStream(new FileOutputStream(tmp));
        } catch (FileNotFoundException e) {
            System.err.println("output file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET);
    chart.setStyleSheet(tmp);

    try {
        chart.parseInput(in);
    } catch (IOException e) {
        System.err.println("I/O error while reading input");
        System.exit(1);
    } catch (net.cliftonsnyder.svgchart.parse.ParseException e) {
        System.err.println("error parsing input: " + e.getMessage());
    }

    chart.createChart();

    try {
        chart.printChart(out, true);
    } catch (IOException e) {
        System.err.println("error serializing output");
        System.exit(1);
    }
}

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

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

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

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact;
    compFact = getComparatorFactory(cmd);

    SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>(
            compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:msi.gaml.operators.Maths.java

public static void main(final String[] args) throws ParseException {
    java.lang.System.out.println("Various format tests");
    java.lang.System.out.println("NumberFormat.parse1e1 = " + NumberFormat.getInstance(Locale.US).parse("1e1"));
    java.lang.System.out.println("Double.parse 1e1 = " + Double.parseDouble("1e1"));
    java.lang.System.out//from w w  w.  j a va2  s.co  m
            .println("NumberFormat.parse 1E1 = " + NumberFormat.getInstance(Locale.US).parse("1E1"));
    java.lang.System.out.println("Double.parse 1E1 = " + Double.parseDouble("1E1"));
    java.lang.System.out
            .println("NumberFormat.parse 1.0e1 = " + NumberFormat.getInstance(Locale.US).parse("1.0e1"));
    java.lang.System.out.println("Double.parse 1.0e1 = " + Double.parseDouble("1.0e1"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E+10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E+10"));
    java.lang.System.out.println("Double.parse 0.001E+10 = " + Double.parseDouble("0.001E+10"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E-10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E-10"));
    java.lang.System.out.println("Double.parse 0.001E-10 = " + Double.parseDouble("0.001E-10"));
    java.lang.System.out
            .println("NumberFormat.parse 0.001e-10 =" + NumberFormat.getInstance(Locale.US).parse("0.001e-10"));
    java.lang.System.out.println("Double.parse 0.001e-10 = " + Double.parseDouble("0.001e-10"));
    java.lang.System.out.println("Various arithmetic tests");
    java.lang.System.out.println("cos(PI) = " + Maths.cos_rad(PI));
    java.lang.System.out.println("sin_rad(0.0) = " + sin_rad(0.0));
    java.lang.System.out.println("tan_rad(0.0) = " + tan_rad(0.0));
    java.lang.System.out.println("sin(360) = " + sin(360));
    java.lang.System.out.println("sin(-720) = " + sin(-720));
    java.lang.System.out.println("sin(360.0) = " + sin(360.0));
    java.lang.System.out.println("sin(-720.0) = " + sin(-720.0));
    java.lang.System.out.println("sin(90) = " + sin(90));
    java.lang.System.out.println("sin(45) = " + sin(45));
    java.lang.System.out.println("sin(0) = " + sin(0));
    java.lang.System.out.println("sin(135) = " + sin(135));

    java.lang.System.out.println("Math.sin(360.0) = " + Math.sin(2 * Math.PI));
    // java.lang.System.out.println("3.0 = 3" + (3d == 3));
    // java.lang.System.out.println("3.0 != 3" + (3d != 3));
    java.lang.System.out.println("floor and ceil 2.7 " + floor(2.7) + " and " + ceil(2.7));
    java.lang.System.out.println("floor and ceil -2.7 " + floor(-2.7) + " and " + ceil(-2.7));
    java.lang.System.out.println("floor and ceil -2 " + floor(-2) + " and " + ceil(-2));
    java.lang.System.out.println("floor and ceil 3 " + floor(3) + " and " + ceil(3));
    double atan2diff = 0;
    double atan2diff2 = 0;
    Random rand = new Random();
    long s1 = 0;
    long t1 = 0;
    long t2 = 0;
    long t3 = 0;
    // for ( int i = 0; i < 10000000; i++ ) {
    // double x = rand.nextDouble();
    // double y = rand.nextDouble();
    // s1 = java.lang.System.currentTimeMillis();
    // double a1 = Math.atan2(x, y);
    // t1 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a2 = FastMath.atan2(x, y);
    // t2 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a3 = Maths.atan2Opt2(x, y);
    // t3 += java.lang.System.currentTimeMillis() - s1;
    //
    // atan2diff += Math.abs(a1 - a2);
    // atan2diff2 += Math.abs(a1 - a3);
    // }
    // java.lang.System.out.println("atan2diff : " + atan2diff + "  atan2diff2 : " + atan2diff2 + " t1 : " + t1 +
    // " t2 : " + t2 + " t3 : " + t3);

    long t4 = 0;
    long t5 = 0;
    long t6 = 0;
    double distDiff1 = 0;
    double distDiff2 = 0;
    for (int i = 0; i < 1000000; i++) {
        double x1 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y2 = rand.nextDouble();
        Coordinate c1 = new Coordinate(x1, y1);
        Coordinate c2 = new Coordinate(x2, y2);

        s1 = java.lang.System.currentTimeMillis();
        double a1 = Math.hypot(x2 - x1, y2 - y1);
        t4 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a2 = FastMath.hypot(x2 - x1, y2 - y1);
        t5 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a3 = c1.distance(c2);
        t6 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
        distDiff2 += Math.abs(a1 - a3);
    }
    java.lang.System.out.println("distDiff1 : " + distDiff1 + "  distDiff2 : " + distDiff2 + " t4 : " + t4
            + " t5 : " + t5 + " t6 : " + t6);

    long t7 = 0;
    long t8 = 0;
    distDiff1 = 0;

    for (int i = 0; i < 1000000; i++) {
        double a1, a2;
        double x1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double y2 = rand.nextDouble();
        double z1 = 0.0;
        double z2 = 0.0;
        GamaPoint c2 = new GamaPoint(x2, y2, z2);

        s1 = java.lang.System.currentTimeMillis();
        if (z1 == 0d && c2.getZ() == 0d) {
            a1 = hypot(x1, x2, y1, y2);
        } else {
            a1 = hypot(x1, x2, y1, y2, z1, z2);
        }
        t7 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        a2 = hypot(x1, x2, y1, y2, z1, c2.getZ());
        t8 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
    }
    java.lang.System.out.println(
            "with 0.0 check : " + t7 + "  with direct 3 parameters call : " + t8 + " distance : " + distDiff1);
    // java.lang.System.out.println("Infinity to int:" + (int) Double.POSITIVE_INFINITY);
    // java.lang.System.out.println("NaN to int:" + (int) Double.NaN);
    // GuiUtils.debug("(int) (1.0/0.0):" + (int) (1.0 / 0.0));
    // GuiUtils.debug("(int) (1.0/0):" + (int) (1.0 / 0));
    // GuiUtils.debug("(int) (1.0/0d):" + (int) (1 / 0d));
    // GuiUtils.debug("(int) (1/0):" + 1 / 0);
}

From source file:com.yahoo.semsearch.fastlinking.EntityContextFastEntityLinker.java

/**
 * Context-aware command line entity linker
 * @param args arguments (see -help for further info)
 * @throws Exception// www.j  a  v a 2s. co m
 */
public static void main(String args[]) throws Exception {
    SimpleJSAP jsap = new SimpleJSAP(EntityContextFastEntityLinker.class.getName(),
            "Interactive mode for entity linking",
            new Parameter[] {
                    new FlaggedOption("hash", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'h', "hash",
                            "quasi succint hash"),
                    new FlaggedOption("vectors", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'v',
                            "vectors", "Word vectors file"),
                    new FlaggedOption("labels", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'l',
                            "labels", "File containing query2entity labels"),
                    new FlaggedOption("id2type", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'i',
                            "id2type", "File with the id2type mapping"),
                    new Switch("centroid", 'c', "centroid", "Use centroid-based distances and not LR"),
                    new FlaggedOption("map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'm', "map",
                            "Entity 2 type mapping "),
                    new FlaggedOption("threshold", JSAP.STRING_PARSER, "-20", JSAP.NOT_REQUIRED, 'd',
                            "threshold", "Score threshold value "),
                    new FlaggedOption("entities", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'e',
                            "entities", "Entities word vectors file"), });

    JSAPResult jsapResult = jsap.parse(args);
    if (jsap.messagePrinted())
        return;

    double threshold = Double.parseDouble(jsapResult.getString("threshold"));
    QuasiSuccinctEntityHash hash = (QuasiSuccinctEntityHash) BinIO.loadObject(jsapResult.getString("hash"));
    EntityContext queryContext;
    if (!jsapResult.getBoolean("centroid")) {
        queryContext = new LREntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"),
                hash);
    } else {
        queryContext = new CentroidEntityContext(jsapResult.getString("vectors"),
                jsapResult.getString("entities"), hash);
    }
    HashMap<String, ArrayList<EntityRelevanceJudgment>> labels = null;
    if (jsapResult.getString("labels") != null) {
        labels = readTrainingData(jsapResult.getString("labels"));
    }

    String map = jsapResult.getString("map");

    HashMap<String, String> entities2Type = null;

    if (map != null)
        entities2Type = readEntity2IdFile(map);

    EntityContextFastEntityLinker linker = new EntityContextFastEntityLinker(hash, queryContext);

    final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String q;
    for (;;) {
        System.out.print(">");
        q = br.readLine();
        if (q == null) {
            System.err.println();
            break; // CTRL-D
        }
        if (q.length() == 0)
            continue;
        long time = -System.nanoTime();
        try {
            List<EntityResult> results = linker.getResults(q, threshold);
            //List<EntityResult> results = linker.getResultsGreedy( q, 5 );
            //int rank = 0;

            for (EntityResult er : results) {
                if (entities2Type != null) {
                    String name = er.text.toString().trim();
                    String newType = entities2Type.get(name);
                    if (newType == null)
                        newType = "NF";
                    System.out.println(q + "\t span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id
                            + " ( t= " + newType + ")" + "  score: " + er.score + " ( " + er.s.span + " ) ");

                    //System.out.println( newType + "\t" + q + "\t" + StringUtils.remove( q, er.s.span.toString() ) + " \t " + er.text );
                    break;
                    /* } else {
                       System.out.print( "[" + er.text + "(" + String.format("%.2f",er.score) +")] ");
                    System.out.println( "span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + typeMapping.get( hash.getEntity( er.id ).type )
                    + "  score: " + er.score + " ( " + er.s.span + " ) " );
                    }
                    rank++;
                    */
                } else {
                    if (labels == null) {
                        System.out.println(q + "\t" + er.text + "\t" + er.score);
                    } else {
                        ArrayList<EntityRelevanceJudgment> jds = labels.get(q);
                        String label = "NF";
                        if (jds != null) {
                            EntityRelevanceJudgment relevanceOfEntity = relevanceOfEntity(er.text, jds);
                            label = relevanceOfEntity.label;
                        }
                        System.out.println(q + "\t" + er.text + "\t" + label + "\t" + er.score);
                        break;
                    }
                }
                System.out.println();
            }
            time += System.nanoTime();
            System.out.println("Time to rank and print the candidates:" + time / 1000000. + " ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:fr.tpt.s3.mcdag.bench.MainBench.java

public static void main(String[] args) throws IOException, InterruptedException {

    // Command line options
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML models");
    input.setRequired(true);/*from w  ww . j a  va  2s  .c  o  m*/
    input.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(input);

    Option output = new Option("o", "output", true, "Folder where results have to be written.");
    output.setRequired(true);
    options.addOption(output);

    Option uUti = new Option("u", "utilization", true, "Utilization.");
    uUti.setRequired(true);
    options.addOption(uUti);

    Option output2 = new Option("ot", "output-total", true, "File where total results are being written");
    output2.setRequired(true);
    options.addOption(output2);

    Option oCores = new Option("c", "cores", true, "Cores given to the test");
    oCores.setRequired(true);
    options.addOption(oCores);

    Option oLvls = new Option("l", "levels", true, "Levels tested for the system");
    oLvls.setRequired(true);
    options.addOption(oLvls);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debug = new Option("d", "debug", false, "Debug logs.");
    debug.setRequired(false);
    options.addOption(debug);

    /*
     * Parsing of the command line
     */
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("Benchmarks MultiDAG", options);
        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    String outputFilePath = cmd.getOptionValue("output");
    String outputFilePathTotal = cmd.getOptionValue("output-total");
    double utilization = Double.parseDouble(cmd.getOptionValue("utilization"));
    boolean boolDebug = cmd.hasOption("debug");
    int nbLvls = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbJobs = 1;
    int nbFiles = inputFilePath.length;

    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    int nbCores = Integer.parseInt(cmd.getOptionValue("cores"));

    /*
     *  While files need to be allocated
     *  run the tests in the pool of threads
     */

    // For dual-criticality systems we call a specific thread
    if (nbLvls == 2) {

        System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls);

        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile,
                    nbCores, boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int fedTotal = 0;
        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int fedPreempts = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int fedActiv = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            fedTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            fedPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            fedActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 11) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 12) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 13) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double fedPerc = (double) fedTotal / nbFiles;
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double fedPercPreempts = (double) fedPreempts / fedActiv;
        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; "
                + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts
                + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; "
                + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else if (nbLvls > 2) {
        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores,
                    boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; "
                + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts
                + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else {
        System.err.println("Wrong number of levels");
        System.exit(-1);
    }

    System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls);
}

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

public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.sdf,...]");
    opt.setRequired(true);//  ww  w  .j  av  a  2s. com
    options.addOption(opt);

    opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("ref", true, "refrence file to be loaded before starting");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("fpTag", true, "field containing fingerpPrint");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("maxTanimoto", false,
            "If given the modified maxTanimoto will be used = common/(2*Max(na,nb)-common).");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("radius", true, "radius of exclusion sphere, exclude anything with similarity >= radius.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("printSphereMatchCount", false,
            "check and print membership of candidates not "
                    + " only to the first centroid which has sim >= radius but to all centroids"
                    + " found up to that input. This will output a candidate multiple times."
                    + " Implies checkSpheresInOrder.");
    options.addOption(opt);

    opt = new Option("checkSpheresInOrder", false,
            "For each candiate: compare to centroids from first to last (default is last to first)");
    options.addOption(opt);

    opt = new Option("printAll", false, "print all molecule, check includeIdx tag");
    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();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    boolean doMaxTanimoto = cmd.hasOption("maxTanimoto");
    String fpTag = cmd.getOptionValue("fpTag");
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto,
            fpTag);
    SphereExclusion<FPComparator, FPComparator> alg = new SphereExclusion<FPComparator, FPComparator>(compFact,
            refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:graticules2wld.Main.java

/**
 * @param args//from   ww  w .  jav a  2  s  . c o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    /* parse the command line arguments */
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("x", "originx", true, "x component of projected coordinates of upper left pixel");
    options.addOption("y", "originy", true, "y component of projected coordinates of upper left pixel");
    options.addOption("u", "tometers", true, "multiplication factor to get source units into meters");
    options.addOption("h", "help", false, "prints this usage page");
    options.addOption("d", "debug", false, "prints debugging information to stdout");

    double originNorthing = 0;
    double originEasting = 0;

    String inputFileName = null;
    String outputFileName = null;

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printUsage(0); // print usage then exit using a non error exit status

        if (line.hasOption("debug"))
            debug = true;

        // these arguments are required
        if (!line.hasOption("originy") || !line.hasOption("originx"))
            printUsage(1);

        originNorthing = Double.parseDouble(line.getOptionValue("originy"));
        originEasting = Double.parseDouble(line.getOptionValue("originx"));

        if (line.hasOption("tometers"))
            unitsToMeters = Double.parseDouble(line.getOptionValue("tometers"));

        // two args should be left. the input csv file name and the output wld file name.
        String[] iofiles = line.getArgs();
        if (iofiles.length < 2) {
            printUsage(1);
        }

        inputFileName = iofiles[0];
        outputFileName = iofiles[1];
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    // try to open the input file for reading and the output file for writing
    File graticulesCsvFile;
    BufferedReader csvReader = null;

    File wldFile;
    BufferedWriter wldWriter = null;

    try {
        graticulesCsvFile = new File(inputFileName);
        csvReader = new BufferedReader(new FileReader(graticulesCsvFile));
    } catch (IOException exp) {
        System.err.println("Could not open input file for reading: " + inputFileName);
        System.exit(1);
    }

    try {
        wldFile = new File(outputFileName);
        wldWriter = new BufferedWriter(new FileWriter(wldFile));
    } catch (IOException exp) {
        System.err.println("Could not open output file for writing: " + outputFileName);
        System.exit(1);
    }

    // list of lon graticules and lat graticules
    ArrayList<Graticule> lonGrats = new ArrayList<Graticule>();
    ArrayList<Graticule> latGrats = new ArrayList<Graticule>();

    // read the source CSV and convert its information into the two ArrayList<Graticule> data structures
    readCSV(csvReader, lonGrats, latGrats);

    // we now need to start finding the world file paramaters
    DescriptiveStatistics stats = new DescriptiveStatistics();

    // find theta and phi
    for (Graticule g : latGrats) {
        stats.addValue(g.angle());
    }

    double theta = stats.getMean(); // we use the mean of the lat angles as theta
    if (debug)
        System.out.println("theta range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    for (Graticule g : lonGrats) {
        stats.addValue(g.angle());
    }

    double phi = stats.getMean(); // ... and the mean of the lon angles for phi
    if (debug)
        System.out.println("phi range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    // print these if in debug mode
    if (debug) {
        System.out.println("theta = " + Math.toDegrees(theta) + "deg");
        System.out.println("phi = " + Math.toDegrees(phi) + "deg");
    }

    // find x and y (distance beteen pixels in map units)
    Collections.sort(latGrats);
    Collections.sort(lonGrats);
    int prevMapValue = 0; //fixme: how to stop warning about not being initilised?
    Line2D prevGratPixelSys = new Line2D.Double();

    boolean first = true;
    for (Graticule g : latGrats) {
        if (!first) {
            int deltaMapValue = Math.abs(g.realValue() - prevMapValue);
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double y = stats.getMean();
    if (debug)
        System.out.println("y range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    first = true;
    for (Graticule g : lonGrats) {
        if (!first) {
            int deltaMapValue = g.realValue() - prevMapValue;
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double x = stats.getMean();
    if (debug)
        System.out.println("x range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    if (debug) {
        System.out.println("x = " + x);
        System.out.println("y = " + y);
    }

    SimpleRegression regression = new SimpleRegression();

    // C, F are translation terms: x, y map coordinates of the center of the upper-left pixel
    for (Graticule g : latGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * y; // perpMapDist / perpPixelDist = y

        regression.addData(perpMapDist, g.realValue());
    }

    double F = regression.getIntercept();
    regression.clear();

    for (Graticule g : lonGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * x; // perpMapDist / perpPixelDist = x

        regression.addData(perpMapDist, g.realValue());
    }

    double C = regression.getIntercept();
    regression.clear();

    if (debug) {
        System.out.println("Upper Left pixel has coordinates " + C + ", " + F);
    }

    // convert to meters
    C *= unitsToMeters;
    F *= unitsToMeters;

    // C,F store the projected (in map units) coordinates of the upper left pixel.
    // originNorthing,originEasting is the offset we need to apply to 0,0 to push the offsets into our global coordinate system 
    C = originEasting + C;
    F = originNorthing + F;

    // calculate the affine transformation matrix elements
    double D = -1 * x * unitsToMeters * Math.sin(theta);
    double A = x * unitsToMeters * Math.cos(theta);
    double B = y * unitsToMeters * Math.sin(phi); // if should be negative, it'll formed by negative sin
    double E = -1 * y * unitsToMeters * Math.cos(phi);

    /*
     * Line 1: A: pixel size in the x-direction in map units/pixel
     * Line 2: D: rotation about y-axis
     * Line 3: B: rotation about x-axis
     * Line 4: E: pixel size in the y-direction in map units, almost always negative[3]
     * Line 5: C: x-coordinate of the center of the upper left pixel
     * Line 6: F: y-coordinate of the center of the upper left pixel
     */
    if (debug) {
        System.out.println("A = " + A);
        System.out.println("D = " + D);
        System.out.println("B = " + B);
        System.out.println("E = " + E);
        System.out.println("C = " + C);
        System.out.println("F = " + F);

        // write the world file
        System.out.println();
        System.out.println("World File:");
        System.out.println(A);
        System.out.println(D);
        System.out.println(B);
        System.out.println(E);
        System.out.println(C);
        System.out.println(F);
    }

    // write to the .wld file
    wldWriter.write(A + "\n");
    wldWriter.write(D + "\n");
    wldWriter.write(B + "\n");
    wldWriter.write(E + "\n");
    wldWriter.write(C + "\n");
    wldWriter.write(F + "\n");

    wldWriter.close();
}

From source file:gov.lanl.adore.djatoka.DjatokaExtract.java

/**
 * Uses apache commons cli to parse input args. Passes parsed
 * parameters to IExtract implementation.
 * @param args command line parameters to defined input,output,etc.
 *///from   ww  w.  j ava2  s.c om
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", "input", true, "Filepath of the input file.");
    options.addOption("o", "output", true, "Filepath of the output file.");
    options.addOption("l", "level", true, "Resolution level to extract.");
    options.addOption("d", "reduce", true, "Resolution levels to subtract from max resolution.");
    options.addOption("r", "region", true, "Format: Y,X,H,W. ");
    options.addOption("c", "cLayer", true, "Compositing Layer Index.");
    options.addOption("s", "scale", true,
            "Format: Option 1. Define a long-side dimension (e.g. 96); Option 2. Define absolute w,h values (e.g. 1024,768); Option 3. Define a single dimension (e.g. 1024,0) with or without Level Parameter; Option 4. Use a single decimal scaling factor (e.g. 0.854)");
    options.addOption("t", "rotate", true, "Number of degrees to rotate image (i.e. 90, 180, 270).");
    options.addOption("f", "format", true,
            "Mimetype of the image format to be provided as response. Default: image/jpeg");
    options.addOption("a", "AltImpl", true, "Alternate IExtract Implemenation");

    try {
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gov.lanl.adore.djatoka.DjatokaExtract", options);
            System.exit(0);
        }

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String input = line.getOptionValue("i");
        String output = line.getOptionValue("o");

        DjatokaDecodeParam p = new DjatokaDecodeParam();
        String level = line.getOptionValue("l");
        if (level != null)
            p.setLevel(Integer.parseInt(level));
        String reduce = line.getOptionValue("d");
        if (level == null && reduce != null)
            p.setLevelReductionFactor(Integer.parseInt(reduce));
        String region = line.getOptionValue("r");
        if (region != null)
            p.setRegion(region);
        String cl = line.getOptionValue("c");
        if (cl != null) {
            int clayer = Integer.parseInt(cl);
            if (clayer > 0)
                p.setCompositingLayer(clayer);
        }
        String scale = line.getOptionValue("s");
        if (scale != null) {
            String[] v = scale.split(",");
            if (v.length == 1) {
                if (v[0].contains("."))
                    p.setScalingFactor(Double.parseDouble(v[0]));
                else {
                    int[] dims = new int[] { -1, Integer.parseInt(v[0]) };
                    p.setScalingDimensions(dims);
                }
            } else if (v.length == 2) {
                int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) };
                p.setScalingDimensions(dims);
            }
        }
        String rotate = line.getOptionValue("t");
        if (rotate != null)
            p.setRotationDegree(Integer.parseInt(rotate));
        String format = line.getOptionValue("f");
        if (format == null)
            format = "image/jpeg";
        String alt = line.getOptionValue("a");
        if (output == null)
            output = input + ".jpg";

        long x = System.currentTimeMillis();
        IExtract ex = new KduExtractExe();
        if (alt != null)
            ex = (IExtract) Class.forName(alt).newInstance();
        DjatokaExtractProcessor e = new DjatokaExtractProcessor(ex);
        e.extractImage(input, output, p, format);
        logger.info("Extraction Time: " + ((double) (System.currentTimeMillis() - x) / 1000) + " seconds");

    } catch (ParseException e) {
        logger.error("Parse exception:" + e.getMessage(), e);
    } catch (DjatokaException e) {
        logger.error("djatoka Extraction exception:" + e.getMessage(), e);
    } catch (InstantiationException e) {
        logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("Unexpected exception:" + e.getMessage(), e);
    }
}

From source file:cnxchecker.Client.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("H", "host", true, "Remote IP address");
    options.addOption("p", "port", true, "Remote TCP port");
    options.addOption("s", "size", true, "Packet size in bytes (1 KiB)");
    options.addOption("f", "freq", true, "Packets per seconds  (1 Hz)");
    options.addOption("w", "workers", true, "Number of Workers (1)");
    options.addOption("d", "duration", true, "Duration of the test in seconds (60 s)");
    options.addOption("h", "help", false, "Print help");
    CommandLineParser parser = new GnuParser();
    try {// w  ww . ja  v  a  2 s.  c om
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("client", options);
            System.exit(0);
        }

        // host
        InetAddress ia = null;
        if (cmd.hasOption("H")) {
            String host = cmd.getOptionValue("H");

            try {
                ia = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                printAndExit("Unknown host: " + host);
            }
        } else {
            printAndExit("Host option is mandatory");
        }

        // port
        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        // size
        int size = 1024;
        if (cmd.hasOption("s")) {
            try {
                size = Integer.parseInt(cmd.getOptionValue("s"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid packet size " + cmd.getOptionValue("s"));
            }

            if (size < 0) {
                printAndExit("Invalid packet size: " + port);
            }
        }

        // freq
        double freq = 1;
        if (cmd.hasOption("f")) {
            try {
                freq = Double.parseDouble(cmd.getOptionValue("f"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid frequency: " + cmd.getOptionValue("f"));
            }

            if (freq <= 0) {
                printAndExit("Invalid frequency: " + freq);
            }
        }

        // workers
        int workers = 1;
        if (cmd.hasOption("w")) {
            try {
                workers = Integer.parseInt(cmd.getOptionValue("w"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid number of workers: " + cmd.getOptionValue("w"));
            }

            if (workers < 0) {
                printAndExit("Invalid number of workers: " + workers);
            }
        }

        // duration
        int duration = 60000;
        if (cmd.hasOption("d")) {
            try {
                duration = Integer.parseInt(cmd.getOptionValue("d")) * 1000;
            } catch (NumberFormatException e) {
                printAndExit("Invalid duration: " + cmd.getOptionValue("d"));
            }

            if (duration < 0) {
                printAndExit("Invalid duration: " + duration);
            }
        }

        Client client = new Client(ia, port, size, freq, workers, duration);
        client.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }

    System.exit(0);
}

From source file:eu.amidst.core.inference.ImportanceSamplingExperiments.java

/**
 * The class constructor./* ww  w.  j  a va  2  s  .c  o  m*/
 * @param args Array of options: "filename variable a b N useVMP" if variable is continuous or "filename variable w N useVMP" for discrete
 */
public static void main(String[] args) throws Exception {

    //if (Main.VERBOSE) System.out.println("CONTINUOUS VARIABLE");
    boolean discrete = false;

    String filename = ""; //Filename with the Bayesian Network
    String varname = ""; // Variable of interest in the BN
    double a = 0; // Lower endpoint of the interval
    double b = 0; // Upper endpoint of the interval
    int N = 0; // Sample size
    boolean useVMP = false; // Boolean indicating whether use VMP or not

    // FOR A CONTINUOUS VARIABLE OF INTEREST
    if (args.length == 6) {

        filename = args[0]; //Filename with the Bayesian Network
        varname = args[1]; // Variable of interest in the BN
        String aa = args[2]; // Lower endpoint of the interval
        String bb = args[3]; // Upper endpoint of the interval
        String NN = args[4]; // Sample size
        String useVMParg = args[5]; // Boolean indicating whether use VMP or not

        try {
            a = Double.parseDouble(aa);
            b = Double.parseDouble(bb);
            N = Integer.parseInt(NN);
            useVMP = Boolean.parseBoolean(useVMParg);
        } catch (NumberFormatException e) {
            if (Main.VERBOSE)
                System.out.println(e.toString());
        }

    }
    // FOR A DISCRETE VARIABLE OF INTEREST
    else if (args.length == 5) {
        //if (Main.VERBOSE) System.out.println("DISCRETE VARIABLE");
        discrete = true;
        if (Main.VERBOSE)
            System.out.println("Not available yet");
        System.exit(1);
    } else if (args.length == 0) {
        filename = "networks/simulated/Bayesian10Vars15Links.bn"; //Filename with the Bayesian Network
        //filename="networks/Bayesian2Vars1Link.bn";
        varname = "GaussianVar1"; // Variable of interest in the BN
        a = 0; // Lower endpoint of the interval
        b = 1; // Upper endpoint of the interval
        N = 10000; // Sample size
        useVMP = false; // Boolean indicating whether use VMP or not
    } else {
        if (Main.VERBOSE)
            System.out.println("Invalid number of arguments. See comments in main");
        System.exit(1);
    }

    BayesianNetwork bn;

    VMP vmp = new VMP();

    ImportanceSampling importanceSampling = new ImportanceSampling();

    try {

        bn = BayesianNetworkLoader.loadFromFile(filename);
        if (Main.VERBOSE)
            System.out.println(bn.toString());
        Variable varInterest = bn.getVariables().getVariableByName(varname);

        vmp.setModel(bn);
        vmp.runInference();

        importanceSampling.setModel(bn);
        //importanceSampling.setSamplingModel(vmp.getSamplingModel());
        importanceSampling.setSamplingModel(bn);
        importanceSampling.setParallelMode(true);
        importanceSampling.setKeepDataOnMemory(true);
        importanceSampling.setSampleSize(N);

        // Including evidence:
        Assignment assignment = randomEvidence(1823716125, 0.05, bn, varInterest);
        importanceSampling.setEvidence(assignment);

        //importanceSampling.setSamplingModel(vmp.getSamplingModel());
        //importanceSampling.runInference(vmp);
        //if (Main.VERBOSE) System.out.println("Posterior of " + varInterest.getName() + "  (IS w. Evidence VMP) :" + importanceSampling.getPosterior(varInterest).toString());

        //importanceSampling.setSamplingModel(bn);
        importanceSampling.runInference();
        if (Main.VERBOSE)
            System.out.println("Posterior of " + varInterest.getName() + "  (IS w. Evidence) :"
                    + importanceSampling.getPosterior(varInterest).toString());

        if (Main.VERBOSE)
            System.out.println("Posterior of " + varInterest.getName() + " (VMP) :"
                    + vmp.getPosterior(varInterest).toString());

        if (Main.VERBOSE)
            System.out.println();

        if (Main.VERBOSE)
            System.out.println("Variable of interest: " + varInterest.getName());
        if (Main.VERBOSE)
            System.out.println();

        a = 1.5; // Lower endpoint of the interval
        b = 10000; // Upper endpoint of the interval

        final double finalA = a;
        final double finalB = b;

        double result = importanceSampling.getExpectedValue(varInterest,
                v -> (finalA < v && v < finalB) ? 1.0 : 0.0);
        if (Main.VERBOSE)
            System.out.println("Query: P(" + Double.toString(a) + " < " + varInterest.getName() + " < "
                    + Double.toString(b) + ")");
        if (Main.VERBOSE)
            System.out.println("Probability result: " + result);

        /*
        if (Main.VERBOSE) System.out.println();
                
                
        varname = "DiscreteVar2";
        if (Main.VERBOSE) System.out.println();
        Variable discreteVarInterest = bn.getVariables().getVariableByName(varname);
        if (Main.VERBOSE) System.out.println("Variable of interest: " + discreteVarInterest.getName());
                
        importanceSampling.runInference();
                
        int w=1; // Value of interest
        double result2 = importanceSampling.runQuery(discreteVarInterest, w);
        if (Main.VERBOSE) System.out.println("Query: P(" + discreteVarInterest.getName() + " = " + Integer.toString(w) + ")");
        if (Main.VERBOSE) System.out.println("Probability result: " + result2);*/

    } catch (Exception e) {
        if (Main.VERBOSE)
            System.out.println("Error loading Bayesian Network from file");
        if (Main.VERBOSE)
            System.out.println(e.toString());
    }

}