Example usage for java.lang NumberFormatException toString

List of usage examples for java.lang NumberFormatException toString

Introduction

In this page you can find the example usage for java.lang NumberFormatException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.openml.weka.experiment.RandomBot.java

public static void main(String[] args) {
    RandomBot bot = new RandomBot();
    int taskType;
    try {/*  ww  w  .j a va2  s .c  om*/
        taskType = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        showErrorMessage(TAG + ":" + e.toString());
        return;
    }
    String taskTag = args[1];
    String classifierCategory = args[2];
    // get a random task id given the task filters
    int taskId = bot.getRandomTaskId(taskType, taskTag);
    // start a run on the task  if we have a correct task id
    if (taskId == -1) {
        return;
    }
    bot.startTask(taskId, classifierCategory);
}

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

/**
 * The class constructor.//w w  w .j a  v a2s .  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());
    }

}

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

/**
 * The class constructor./*from www. j a  va2 s . co  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 { // args: seedNetwork numberGaussians numberDiscrete seedAlgorithms

    int seedNetwork = 23423523;
    int numberOfGaussians = 20;
    int numberOfMultinomials = 20;

    int seed = 634634534;

    int parallelSamples = 100;
    int samplingMethodSize = 10000;

    int repetitions = 10;

    int numberOfIterations = 200;

    if (args.length != 8) {
        if (Main.VERBOSE)
            System.out.println("Invalid number of parameters. Using default values");
    } else {
        try {
            seedNetwork = Integer.parseInt(args[0]);
            numberOfGaussians = Integer.parseInt(args[1]);
            numberOfMultinomials = Integer.parseInt(args[2]);

            seed = Integer.parseInt(args[3]);

            parallelSamples = Integer.parseInt(args[4]);
            samplingMethodSize = Integer.parseInt(args[5]);

            repetitions = Integer.parseInt(args[6]);

            numberOfIterations = Integer.parseInt(args[7]);

        } catch (NumberFormatException ex) {
            if (Main.VERBOSE)
                System.out.println(
                        "Invalid parameters. Provide integers: seedNetwork numberGaussians numberDiscrete seedAlgorithms parallelSamples sampleSize repetitions");
            if (Main.VERBOSE)
                System.out.println("Using default parameters");
            if (Main.VERBOSE)
                System.out.println(ex.toString());
            System.exit(20);
        }
    }
    int numberOfLinks = (int) 1.3 * (numberOfGaussians + numberOfMultinomials);

    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks(numberOfLinks);

    String filename = "./networks/simulated/RandomBN_" + Integer.toString(numberOfMultinomials) + "D_"
            + Integer.toString(numberOfGaussians) + "C_" + Integer.toString(seedNetwork) + "_Seed.bn";
    //BayesianNetworkGenerator.generateBNtoFile(numberOfMultinomials,2,numberOfGaussians,numberOfLinks,seedNetwork,filename);
    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    //if (Main.VERBOSE) System.out.println(bn.getDAG());
    //if (Main.VERBOSE) System.out.println(bn.toString());

    MPEInference mpeInference = new MPEInference();
    mpeInference.setModel(bn);
    mpeInference.setParallelMode(true);

    //if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getCausalOrder(mpeInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray()));
    List<Variable> modelVariables = Utils.getTopologicalOrder(bn.getDAG());
    if (Main.VERBOSE)
        System.out.println();

    // Including evidence:
    //double observedVariablesRate = 0.00;
    //Assignment evidence = randomEvidence(seed, observedVariablesRate, bn);
    //mpeInference.setEvidence(evidence);

    mpeInference.setSampleSize(parallelSamples);
    mpeInference.setSeed(seed);
    mpeInference.setNumberOfIterations(numberOfIterations);

    double[] SA_All_prob = new double[repetitions];
    double[] SA_Some_prob = new double[repetitions];
    double[] HC_All_prob = new double[repetitions];
    double[] HC_Some_prob = new double[repetitions];
    double[] sampling_prob = new double[repetitions];

    double[] SA_All_time = new double[repetitions];
    double[] SA_Some_time = new double[repetitions];
    double[] HC_All_time = new double[repetitions];
    double[] HC_Some_time = new double[repetitions];
    double[] sampling_time = new double[repetitions];

    long timeStart;
    long timeStop;
    double execTime;

    Assignment mpeEstimate;

    mpeInference.setParallelMode(true);

    for (int k = 0; k < repetitions; k++) {

        mpeInference.setSampleSize(parallelSamples);

        /***********************************************
         *        SIMULATED ANNEALING
         ************************************************/

        // MPE INFERENCE WITH SIMULATED ANNEALING, ALL VARIABLES
        //if (Main.VERBOSE) System.out.println();
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SA.All): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_All_time[k] = execTime;

        // MPE INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (SA.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: "+ Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_Some_time[k] = execTime;

        /***********************************************
         *        HILL CLIMBING
         ************************************************/

        // MPE INFERENCE WITH HILL CLIMBING, ALL VARIABLES
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (HC.All): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_All_time[k] = execTime;

        //  MPE INFERENCE WITH HILL CLIMBING, ONE VARIABLE AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (HC.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_Some_time[k] = execTime;

        /***********************************************
         *        SAMPLING AND DETERMINISTIC
         ************************************************/

        // MPE INFERENCE WITH SIMULATION AND PICKING MAX

        mpeInference.setSampleSize(samplingMethodSize);

        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SAMPLING);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SAMPLING): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        sampling_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        sampling_time[k] = execTime;
    }

    double determ_prob = 0;
    double determ_time = 0;

    if (bn.getNumberOfVars() <= 50) {

        // MPE INFERENCE, DETERMINISTIC
        timeStart = System.nanoTime();
        //mpeInference.runInference(-2);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (DETERM.): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();

        determ_prob = mpeInference.getLogProbabilityOfEstimate();
        determ_time = execTime;
        determ_prob = -34.64743236365595;
        determ_time = 0;

    } else {
        if (Main.VERBOSE)
            System.out.println("Too many variables for deterministic method");
    }

    /***********************************************
     *        DISPLAY OF RESULTS
     ************************************************/

    if (Main.VERBOSE)
        System.out.println("*** RESULTS ***");

    //        if (Main.VERBOSE) System.out.println("SA_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_prob));
    //        if (Main.VERBOSE) System.out.println("SA_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_prob));
    //        if (Main.VERBOSE) System.out.println("HC_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_prob));
    //        if (Main.VERBOSE) System.out.println("HC_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_prob));
    //        if (Main.VERBOSE) System.out.println("Sampling log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_prob));
    //
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic log-probability");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_prob));
    //        }
    //        if (Main.VERBOSE) System.out.println();

    final double determ_prob_FINAL = determ_prob;

    //        int SA_All_success = (int) Arrays.stream(SA_All_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int SA_Some_success = (int) Arrays.stream(SA_Some_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int HC_All_success = (int) Arrays.stream(HC_All_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int HC_Some_success = (int) Arrays.stream(HC_Some_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int sampling_success = (int) Arrays.stream(sampling_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //
    //        if (Main.VERBOSE) System.out.println("SA_All % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * SA_All_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("SA_Some % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * SA_Some_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("HC_All % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * HC_All_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("HC_Some % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * HC_Some_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("Sampling % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * sampling_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(SA_All_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(SA_Some_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(HC_All_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(HC_Some_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(sampling_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(SA_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(SA_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(HC_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(HC_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(sampling_time).average().getAsDouble()));

    if (bn.getNumberOfVars() <= 50) {
        if (Main.VERBOSE)
            System.out.println("Deterministic time");
        if (Main.VERBOSE)
            System.out.println(Double.toString(determ_time));
        if (Main.VERBOSE)
            System.out.println("and probability");
        if (Main.VERBOSE)
            System.out.println(determ_prob);
    }

}

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

/**
 * The class constructor.//from w  w  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 { // args: seedNetwork numberGaussians numberDiscrete seedAlgorithms

    int seedNetwork = 234235;
    int numberOfGaussians = 100;
    int numberOfMultinomials = 100;

    int seed = 125634;

    int parallelSamples = 100;
    int samplingMethodSize = 10000;

    int repetitions = 10;

    int numberOfIterations = 200;

    if (args.length != 8) {
        if (Main.VERBOSE)
            System.out.println("Invalid number of parameters. Using default values");
    } else {
        try {
            seedNetwork = Integer.parseInt(args[0]);
            numberOfGaussians = Integer.parseInt(args[1]);
            numberOfMultinomials = Integer.parseInt(args[2]);

            seed = Integer.parseInt(args[3]);

            parallelSamples = Integer.parseInt(args[4]);
            samplingMethodSize = Integer.parseInt(args[5]);

            repetitions = Integer.parseInt(args[6]);

            numberOfIterations = Integer.parseInt(args[7]);

        } catch (NumberFormatException ex) {
            if (Main.VERBOSE)
                System.out.println(
                        "Invalid parameters. Provide integers: seedNetwork numberGaussians numberDiscrete seedAlgorithms parallelSamples sampleSize repetitions");
            if (Main.VERBOSE)
                System.out.println("Using default parameters");
            if (Main.VERBOSE)
                System.out.println(ex.toString());
            System.exit(20);
        }
    }
    int numberOfLinks = (int) 1.3 * (numberOfGaussians + numberOfMultinomials);

    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks(numberOfLinks);

    String filename = "./networks/simulated/RandomBN_" + Integer.toString(numberOfMultinomials) + "D_"
            + Integer.toString(numberOfGaussians) + "C_" + Integer.toString(seedNetwork) + "_Seed.bn";
    //BayesianNetworkGenerator.generateBNtoFile(numberOfMultinomials,2,numberOfGaussians,numberOfLinks,seedNetwork,filename);
    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    //if (Main.VERBOSE) System.out.println(bn.getDAG());
    //if (Main.VERBOSE) System.out.println(bn.toString());

    MPEInference mpeInference = new MPEInference();
    mpeInference.setModel(bn);
    mpeInference.setParallelMode(true);

    //if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getCausalOrder(mpeInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray()));
    List<Variable> modelVariables = Utils.getTopologicalOrder(bn.getDAG());
    if (Main.VERBOSE)
        System.out.println();

    // Including evidence:
    //double observedVariablesRate = 0.00;
    //Assignment evidence = randomEvidence(seed, observedVariablesRate, bn);
    //mpeInference.setEvidence(evidence);

    mpeInference.setNumberOfIterations(numberOfIterations);

    mpeInference.setSampleSize(parallelSamples);
    mpeInference.setSeed(seed);

    double[] SA_All_prob = new double[repetitions];
    double[] SA_Some_prob = new double[repetitions];
    double[] HC_All_prob = new double[repetitions];
    double[] HC_Some_prob = new double[repetitions];
    double[] sampling_prob = new double[repetitions];

    double[] SA_All_time = new double[repetitions];
    double[] SA_Some_time = new double[repetitions];
    double[] HC_All_time = new double[repetitions];
    double[] HC_Some_time = new double[repetitions];
    double[] sampling_time = new double[repetitions];

    long timeStart;
    long timeStop;
    double execTime;

    Assignment bestMpeEstimate = new HashMapAssignment(bn.getNumberOfVars());
    double bestMpeEstimateLogProb = -100000;
    int bestMpeEstimateMethod = -5;

    mpeInference.setParallelMode(true);

    final double bestProbability = -171.81983739975342;
    //        BEST MPE ESTIMATE FOUND:
    //        {DiscreteVar0 = 0, DiscreteVar1 = 0, DiscreteVar2 = 1, DiscreteVar3 = 0, DiscreteVar4 = 0, DiscreteVar5 = 0, DiscreteVar6 = 0, DiscreteVar7 = 0, DiscreteVar8 = 0, DiscreteVar9 = 0, DiscreteVar10 = 0, DiscreteVar11 = 1, DiscreteVar12 = 1, DiscreteVar13 = 1, DiscreteVar14 = 0, DiscreteVar15 = 0, DiscreteVar16 = 0, DiscreteVar17 = 1, DiscreteVar18 = 1, DiscreteVar19 = 0, DiscreteVar20 = 0, DiscreteVar21 = 0, DiscreteVar22 = 1, DiscreteVar23 = 1, DiscreteVar24 = 0, DiscreteVar25 = 0, DiscreteVar26 = 0, DiscreteVar27 = 0, DiscreteVar28 = 1, DiscreteVar29 = 1, DiscreteVar30 = 0, DiscreteVar31 = 0, DiscreteVar32 = 1, DiscreteVar33 = 1, DiscreteVar34 = 0, DiscreteVar35 = 1, DiscreteVar36 = 0, DiscreteVar37 = 0, DiscreteVar38 = 0, DiscreteVar39 = 0, DiscreteVar40 = 0, DiscreteVar41 = 1, DiscreteVar42 = 1, DiscreteVar43 = 1, DiscreteVar44 = 0, DiscreteVar45 = 1, DiscreteVar46 = 1, DiscreteVar47 = 0, DiscreteVar48 = 1, DiscreteVar49 = 1, DiscreteVar50 = 0, DiscreteVar51 = 0, DiscreteVar52 = 0, DiscreteVar53 = 1, DiscreteVar54 = 0, DiscreteVar55 = 1, DiscreteVar56 = 1, DiscreteVar57 = 0, DiscreteVar58 = 1, DiscreteVar59 = 0, DiscreteVar60 = 0, DiscreteVar61 = 1, DiscreteVar62 = 0, DiscreteVar63 = 0, DiscreteVar64 = 0, DiscreteVar65 = 1, DiscreteVar66 = 1, DiscreteVar67 = 1, DiscreteVar68 = 1, DiscreteVar69 = 1, DiscreteVar70 = 1, DiscreteVar71 = 0, DiscreteVar72 = 0, DiscreteVar73 = 0, DiscreteVar74 = 0, DiscreteVar75 = 1, DiscreteVar76 = 0, DiscreteVar77 = 1, DiscreteVar78 = 1, DiscreteVar79 = 0, DiscreteVar80 = 1, DiscreteVar81 = 1, DiscreteVar82 = 1, DiscreteVar83 = 0, DiscreteVar84 = 1, DiscreteVar85 = 1, DiscreteVar86 = 1, DiscreteVar87 = 1, DiscreteVar88 = 0, DiscreteVar89 = 0, DiscreteVar90 = 1, DiscreteVar91 = 0, DiscreteVar92 = 0, DiscreteVar93 = 0, DiscreteVar94 = 0, DiscreteVar95 = 0, DiscreteVar96 = 0, DiscreteVar97 = 1, DiscreteVar98 = 1, DiscreteVar99 = 1, GaussianVar0 = -4,551, GaussianVar1 = 14,731, GaussianVar2 = -1,108, GaussianVar3 = -6,564, GaussianVar4 = -2,415, GaussianVar5 = 10,265, GaussianVar6 = 6,058, GaussianVar7 = 6,367, GaussianVar8 = 26,731, GaussianVar9 = 0,807, GaussianVar10 = -19,410, GaussianVar11 = 18,070, GaussianVar12 = -14,177, GaussianVar13 = 7,765, GaussianVar14 = 3,596, GaussianVar15 = -7,757, GaussianVar16 = -1,705, GaussianVar17 = -5,476, GaussianVar18 = -17,932, GaussianVar19 = 22,843, GaussianVar20 = -9,860, GaussianVar21 = 3,844, GaussianVar22 = 8,262, GaussianVar23 = -9,080, GaussianVar24 = 1,750, GaussianVar25 = 11,532, GaussianVar26 = 0,700, GaussianVar27 = 12,206, GaussianVar28 = 8,532, GaussianVar29 = -40,395, GaussianVar30 = 19,981, GaussianVar31 = -30,713, GaussianVar32 = 0,476, GaussianVar33 = -12,406, GaussianVar34 = 4,942, GaussianVar35 = -0,245, GaussianVar36 = -176,861, GaussianVar37 = 8,474, GaussianVar38 = -8,849, GaussianVar39 = -3,844, GaussianVar40 = -8,495, GaussianVar41 = 4,664, GaussianVar42 = -4,730, GaussianVar43 = 4,063, GaussianVar44 = -1,631, GaussianVar45 = -103,340, GaussianVar46 = -1,598, GaussianVar47 = -11,460, GaussianVar48 = 14,123, GaussianVar49 = -0,135, GaussianVar50 = 1,487, GaussianVar51 = -4,859, GaussianVar52 = 0,370, GaussianVar53 = -10,038, GaussianVar54 = 18,145, GaussianVar55 = 225,324, GaussianVar56 = 1,059, GaussianVar57 = -1,170, GaussianVar58 = 83,480, GaussianVar59 = 7,375, GaussianVar60 = 5,091, GaussianVar61 = 61,381, GaussianVar62 = 42,955, GaussianVar63 = -712,533, GaussianVar64 = 21,460, GaussianVar65 = -19,337, GaussianVar66 = 213,903, GaussianVar67 = -10,197, GaussianVar68 = -65,619, GaussianVar69 = 41,045, GaussianVar70 = 133,452, GaussianVar71 = -1,997, GaussianVar72 = 17,485, GaussianVar73 = -40,691, GaussianVar74 = -16,378, GaussianVar75 = -72,550, GaussianVar76 = -1,761, GaussianVar77 = 12,647, GaussianVar78 = -31,531, GaussianVar79 = -41,444, GaussianVar80 = -14,190, GaussianVar81 = 17,387, GaussianVar82 = -12,333, GaussianVar83 = -57,795, GaussianVar84 = -20,386, GaussianVar85 = 49,735, GaussianVar86 = 14,593, GaussianVar87 = -168,778, GaussianVar88 = -6,157, GaussianVar89 = 82,897, GaussianVar90 = -30,018, GaussianVar91 = -2,366, GaussianVar92 = -12,753, GaussianVar93 = -141,490, GaussianVar94 = 17,844, GaussianVar95 = 99,703, GaussianVar96 = -37,859, GaussianVar97 = 123,045, GaussianVar98 = -4,054, GaussianVar99 = 3,024}
    //        with method:2
    //        and log probability: -171.81983739975342

    for (int k = 0; k < repetitions; k++) {

        mpeInference.setSampleSize(parallelSamples);

        /***********************************************
         *        SIMULATED ANNEALING
         ************************************************/

        // MPE INFERENCE WITH SIMULATED ANNEALING, ALL VARIABLES
        //if (Main.VERBOSE) System.out.println();
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SA.All): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_All_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 1;
        }

        // MPE INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (SA.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: "+ Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_Some_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 0;
        }

        /***********************************************
         *        HILL CLIMBING
         ************************************************/

        // MPE INFERENCE WITH HILL CLIMBING, ALL VARIABLES
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (HC.All): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_All_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 3;
        }

        //  MPE INFERENCE WITH HILL CLIMBING, ONE VARIABLE AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (HC.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_Some_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 2;
        }

        /***********************************************
         *        SAMPLING AND DETERMINISTIC
         ************************************************/

        // MPE INFERENCE WITH SIMULATION AND PICKING MAX

        mpeInference.setSampleSize(samplingMethodSize);

        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SAMPLING);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SAMPLING): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        sampling_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        sampling_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = -1;
        }
    }

    double determ_prob = 0;
    double determ_time = 0;

    //        if(bn.getNumberOfVars()<=50) {
    //
    //            // MPE INFERENCE, DETERMINISTIC
    //            timeStart = System.nanoTime();
    //            mpeInference.runInference(-2);
    //
    //            //mpeEstimate = mpeInference.getEstimate();
    //            //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
    //            //if (Main.VERBOSE) System.out.println("MPE estimate (DETERM.): " + mpeEstimate.outputString(modelVariables));
    //            //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
    //            timeStop = System.nanoTime();
    //            execTime = (double) (timeStop - timeStart) / 1000000000.0;
    //            //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
    //            //if (Main.VERBOSE) System.out.println();
    //            determ_prob = mpeInference.getLogProbabilityOfEstimate();
    //            determ_time = execTime;
    //
    //        }
    //        else {
    //            if (Main.VERBOSE) System.out.println("Too many variables for deterministic method");
    //        }

    /***********************************************
     *        DISPLAY OF RESULTS
     ************************************************/

    if (Main.VERBOSE)
        System.out.println("*** RESULTS ***");

    //        if (Main.VERBOSE) System.out.println("SA_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_prob));
    //        if (Main.VERBOSE) System.out.println("SA_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_prob));
    //        if (Main.VERBOSE) System.out.println("HC_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_prob));
    //        if (Main.VERBOSE) System.out.println("HC_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_prob));
    //        if (Main.VERBOSE) System.out.println("Sampling log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_prob));
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic log-probability");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_prob));
    //        }

    if (Main.VERBOSE)
        System.out.println("SA_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(SA_All_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("SA_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(SA_Some_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("HC_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(HC_All_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("HC_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(HC_Some_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("Sampling RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(sampling_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(SA_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(SA_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(HC_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(HC_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(sampling_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println();
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic time");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_time));
    //        }

    if (Main.VERBOSE)
        System.out.println("BEST MPE ESTIMATE FOUND:");
    if (Main.VERBOSE)
        System.out.println(bestMpeEstimate.outputString(Utils.getTopologicalOrder(bn.getDAG())));
    if (Main.VERBOSE)
        System.out.println("with method:" + bestMpeEstimateMethod);
    if (Main.VERBOSE)
        System.out.println("and log probability: " + bestMpeEstimateLogProb);
}

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

/**
 * The class constructor./*from  www .j  a v a 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 { // args: seedNetwork numberGaussians numberDiscrete seedAlgorithms

    int seedNetwork = 234235125;
    int numberOfGaussians = 50;
    int numberOfMultinomials = 50;

    int seed = 125634;

    int parallelSamples = 50;
    int samplingMethodSize = 20000;

    int repetitions = 10;

    int numberOfIterations = 100;

    if (args.length != 8) {
        if (Main.VERBOSE)
            System.out.println("Invalid number of parameters. Using default values");
    } else {
        try {
            seedNetwork = Integer.parseInt(args[0]);
            numberOfGaussians = Integer.parseInt(args[1]);
            numberOfMultinomials = Integer.parseInt(args[2]);

            seed = Integer.parseInt(args[3]);

            parallelSamples = Integer.parseInt(args[4]);
            samplingMethodSize = Integer.parseInt(args[5]);

            repetitions = Integer.parseInt(args[6]);

            numberOfIterations = Integer.parseInt(args[7]);

        } catch (NumberFormatException ex) {
            if (Main.VERBOSE)
                System.out.println(
                        "Invalid parameters. Provide integers: seedNetwork numberGaussians numberDiscrete seedAlgorithms parallelSamples sampleSize repetitions");
            if (Main.VERBOSE)
                System.out.println("Using default parameters");
            if (Main.VERBOSE)
                System.out.println(ex.toString());
            System.exit(20);
        }
    }
    int numberOfLinks = (int) 1.3 * (numberOfGaussians + numberOfMultinomials);

    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks(numberOfLinks);

    String filename = "./networks/simulated/RandomBN_" + Integer.toString(numberOfMultinomials) + "D_"
            + Integer.toString(numberOfGaussians) + "C_" + Integer.toString(seedNetwork) + "_Seed.bn";
    BayesianNetworkGenerator.generateBNtoFile(numberOfMultinomials, 2, numberOfGaussians, numberOfLinks,
            seedNetwork, filename);
    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    //if (Main.VERBOSE) System.out.println(bn.getDAG());
    //if (Main.VERBOSE) System.out.println(bn.toString());

    MAPInference mapInference = new MAPInference();
    mapInference.setModel(bn);
    mapInference.setParallelMode(true);

    // Set also the list of variables of interest (or MAP variables).
    List<Variable> varsInterest = new ArrayList<>();

    Variable var1 = bn.getVariables().getVariableById(3);
    Variable var2 = bn.getVariables().getVariableById(7);
    Variable var3 = bn.getVariables().getVariableById(60);

    varsInterest.add(var1);
    varsInterest.add(var2);
    varsInterest.add(var3);
    mapInference.setMAPVariables(varsInterest);
    if (Main.VERBOSE)
        System.out.println("Variables of Interest: " + var1.getName() + ", " + var2.getName() + ", "
                + var3.getName() + "\n");

    //if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getCausalOrder(mapInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray()));
    //List<Variable> modelVariables = Utils.getCausalOrder(bn.getDAG());
    if (Main.VERBOSE)
        System.out.println();

    // Including evidence:
    //double observedVariablesRate = 0.00;
    //Assignment evidence = randomEvidence(seed, observedVariablesRate, bn);
    //mapInference.setEvidence(evidence);

    mapInference.setNumberOfIterations(numberOfIterations);

    mapInference.setSampleSize(parallelSamples);
    mapInference.setSeed(seed);

    double[] SA_All_prob = new double[repetitions];
    double[] SA_Some_prob = new double[repetitions];
    double[] HC_All_prob = new double[repetitions];
    double[] HC_Some_prob = new double[repetitions];
    double[] sampling_prob = new double[repetitions];

    double[] SA_All_time = new double[repetitions];
    double[] SA_Some_time = new double[repetitions];
    double[] HC_All_time = new double[repetitions];
    double[] HC_Some_time = new double[repetitions];
    double[] sampling_time = new double[repetitions];

    long timeStart;
    long timeStop;
    double execTime;

    Assignment bestMpeEstimate = new HashMapAssignment(bn.getNumberOfVars());
    double bestMpeEstimateLogProb = -100000;
    int bestMpeEstimateMethod = -5;

    mapInference.setParallelMode(true);

    final double bestProbability = -93.40102227041749;
    //        BEST MAP ESTIMATE FOUND:
    //        {DiscreteVar3 = 1, DiscreteVar7 = 1, GaussianVar10 = 0,011}
    //        with method:2
    //        and log probability: -93.40102227041749
    //
    //        BEST MAP ESTIMATE FOUND:
    //        {DiscreteVar3 = 1, DiscreteVar7 = 0, GaussianVar10 = 14,672}
    //        with method:2
    //        and log probability: -93.84634767213683

    for (int k = 0; k < repetitions; k++) {

        mapInference.setSampleSize(parallelSamples);

        /***********************************************
         *        SIMULATED ANNEALING
         ************************************************/

        // MPE INFERENCE WITH SIMULATED ANNEALING, ALL VARIABLES
        //if (Main.VERBOSE) System.out.println();
        timeStart = System.nanoTime();
        mapInference.runInference(MAPInference.SearchAlgorithm.SA_GLOBAL);

        //mpeEstimate = mapInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SA.All): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_All_prob[k] = mapInference.getLogProbabilityOfEstimate();
        SA_All_time[k] = execTime;

        if (mapInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mapInference.getEstimate();
            bestMpeEstimateLogProb = mapInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 1;
        }

        // MPE INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES AT EACH TIME
        timeStart = System.nanoTime();
        mapInference.runInference(MAPInference.SearchAlgorithm.SA_LOCAL);

        //mpeEstimate = mapInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (SA.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: "+ Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_Some_prob[k] = mapInference.getLogProbabilityOfEstimate();
        SA_Some_time[k] = execTime;

        if (mapInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mapInference.getEstimate();
            bestMpeEstimateLogProb = mapInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 0;
        }

        /***********************************************
         *        HILL CLIMBING
         ************************************************/

        // MPE INFERENCE WITH HILL CLIMBING, ALL VARIABLES
        timeStart = System.nanoTime();
        mapInference.runInference(MAPInference.SearchAlgorithm.HC_GLOBAL);

        //mpeEstimate = mapInference.getEstimate();
        //modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (HC.All): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_All_prob[k] = mapInference.getLogProbabilityOfEstimate();
        HC_All_time[k] = execTime;

        if (mapInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mapInference.getEstimate();
            bestMpeEstimateLogProb = mapInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 3;
        }

        //  MPE INFERENCE WITH HILL CLIMBING, ONE VARIABLE AT EACH TIME
        timeStart = System.nanoTime();
        mapInference.runInference(MAPInference.SearchAlgorithm.HC_LOCAL);

        //mpeEstimate = mapInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (HC.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_Some_prob[k] = mapInference.getLogProbabilityOfEstimate();
        HC_Some_time[k] = execTime;

        if (mapInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mapInference.getEstimate();
            bestMpeEstimateLogProb = mapInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 2;
        }

        /***********************************************
         *        SAMPLING AND DETERMINISTIC
         ************************************************/

        // MPE INFERENCE WITH SIMULATION AND PICKING MAX

        mapInference.setSampleSize(samplingMethodSize);

        timeStart = System.nanoTime();
        mapInference.runInference(MAPInference.SearchAlgorithm.SAMPLING);

        //mpeEstimate = mapInference.getEstimate();
        //modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SAMPLING): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        sampling_prob[k] = mapInference.getLogProbabilityOfEstimate();
        sampling_time[k] = execTime;

        if (mapInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mapInference.getEstimate();
            bestMpeEstimateLogProb = mapInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = -1;
        }
    }

    double determ_prob = 0;
    double determ_time = 0;

    //        if(bn.getNumberOfVars()<=50) {
    //
    //            // MPE INFERENCE, DETERMINISTIC
    //            timeStart = System.nanoTime();
    //            mapInference.runInference(-2);
    //
    //            //mpeEstimate = mapInference.getEstimate();
    //            //modelVariables = mapInference.getOriginalModel().getVariables().getListOfVariables();
    //            //if (Main.VERBOSE) System.out.println("MPE estimate (DETERM.): " + mpeEstimate.outputString(modelVariables));
    //            //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mapInference.getLogProbabilityOfEstimate()) + ", logProb: " + mapInference.getLogProbabilityOfEstimate());
    //            timeStop = System.nanoTime();
    //            execTime = (double) (timeStop - timeStart) / 1000000000.0;
    //            //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
    //            //if (Main.VERBOSE) System.out.println();
    //            determ_prob = mapInference.getLogProbabilityOfEstimate();
    //            determ_time = execTime;
    //
    //        }
    //        else {
    //            if (Main.VERBOSE) System.out.println("Too many variables for deterministic method");
    //        }

    /***********************************************
     *        DISPLAY OF RESULTS
     ************************************************/

    if (Main.VERBOSE)
        System.out.println("*** RESULTS ***");

    if (Main.VERBOSE)
        System.out.println("SA_All log-probabilities");
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(SA_All_prob));
    if (Main.VERBOSE)
        System.out.println("SA_Some log-probabilities");
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(SA_Some_prob));
    if (Main.VERBOSE)
        System.out.println("HC_All log-probabilities");
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(HC_All_prob));
    if (Main.VERBOSE)
        System.out.println("HC_Some log-probabilities");
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(HC_Some_prob));
    if (Main.VERBOSE)
        System.out.println("Sampling log-probabilities");
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(sampling_prob));
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic log-probability");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_prob));
    //        }

    if (Main.VERBOSE)
        System.out.println("SA_All RMS probabilities");
    double SA_All_RMS = Math.sqrt(Arrays.stream(SA_All_prob).map(value -> Math.pow(value - bestProbability, 2))
            .average().getAsDouble());
    if (Main.VERBOSE)
        System.out.println(Double.toString(SA_All_RMS));
    if (Main.VERBOSE)
        System.out.println("SA_Some RMS probabilities");
    double SA_Some_RMS = Math.sqrt(Arrays.stream(SA_Some_prob)
            .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble());
    if (Main.VERBOSE)
        System.out.println(Double.toString(SA_Some_RMS));
    if (Main.VERBOSE)
        System.out.println("HC_All RMS probabilities");
    double HC_All_RMS = Math.sqrt(Arrays.stream(HC_All_prob).map(value -> Math.pow(value - bestProbability, 2))
            .average().getAsDouble());
    if (Main.VERBOSE)
        System.out.println(Double.toString(HC_All_RMS));
    if (Main.VERBOSE)
        System.out.println("HC_Some RMS probabilities");
    double HC_Some_RMS = Math.sqrt(Arrays.stream(HC_Some_prob)
            .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble());
    if (Main.VERBOSE)
        System.out.println(Double.toString(HC_Some_RMS));
    if (Main.VERBOSE)
        System.out.println("Sampling RMS probabilities");
    double sampling_RMS = Math.sqrt(Arrays.stream(sampling_prob)
            .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble());
    if (Main.VERBOSE)
        System.out.println(Double.toString(sampling_RMS));
    double[] RMS_means = { SA_All_RMS, SA_Some_RMS, HC_All_RMS, HC_Some_RMS, sampling_RMS };
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(RMS_means));
    if (Main.VERBOSE)
        System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_time));
    double SA_All_times_mean = Arrays.stream(SA_All_time).average().getAsDouble();
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(SA_All_times_mean));
    if (Main.VERBOSE)
        System.out.println("SA_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_time));
    double SA_Some_times_mean = Arrays.stream(SA_Some_time).average().getAsDouble();
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(SA_Some_times_mean));
    if (Main.VERBOSE)
        System.out.println("HC_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_time));
    double HC_All_times_mean = Arrays.stream(HC_All_time).average().getAsDouble();
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(HC_All_times_mean));
    if (Main.VERBOSE)
        System.out.println("HC_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_time));
    double HC_Some_times_mean = Arrays.stream(HC_Some_time).average().getAsDouble();
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(HC_Some_times_mean));
    if (Main.VERBOSE)
        System.out.println("Sampling times");
    double sampling_times_mean = Arrays.stream(sampling_time).average().getAsDouble();
    //if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(sampling_times_mean));
    if (Main.VERBOSE)
        System.out.println("All means:");
    double[] time_means = { SA_All_times_mean, SA_Some_times_mean, HC_All_times_mean, HC_Some_times_mean,
            sampling_times_mean };
    if (Main.VERBOSE)
        System.out.println(Arrays.toString(time_means));
    if (Main.VERBOSE)
        System.out.println();
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic time");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_time));
    //        }

    if (Main.VERBOSE)
        System.out.println("BEST MAP ESTIMATE FOUND:");
    if (Main.VERBOSE)
        System.out.println(bestMpeEstimate.outputString(Utils.getTopologicalOrder(bn.getDAG())));
    if (Main.VERBOSE)
        System.out.println("with method:" + bestMpeEstimateMethod);
    if (Main.VERBOSE)
        System.out.println("and log probability: " + bestMpeEstimateLogProb);
}

From source file:Main.java

public static double roundTwoDecimals(double d) {
    try {//from w ww .j a  v  a2  s  . c o m
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
    } catch (NumberFormatException nfe) {
        Log.d("nfe", nfe.toString());
        try {
            int i = (int) (d * 100);
            d = (i / 100);
            return d;
        } catch (NumberFormatException ne) {
            return d;
        }
    }
}

From source file:net.ontopia.utils.PropertyUtils.java

/**
 * INTERNAL: Returns the property value as an int. If the value is
 * not set or any problems occur the default value is returned.
 *//*  ww  w.  j a v  a2 s .c o  m*/
public static int getInt(String property_value, int default_value) {
    if (property_value == null)
        return default_value;
    else
        try {
            return getInt(property_value);
        } catch (NumberFormatException e) {
            log.warn(e.toString());
            return default_value;
        }
}

From source file:edu.isi.misd.scanner.network.registry.web.controller.BaseController.java

public static Integer validateIntegerParameter(String param, String value) throws BadRequestException {
    try {//from  w w w.  ja  v a  2s .  com
        return Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
        throw new BadRequestException(
                String.format("Invalid format for parameter [%s] %s", param, nfe.toString()));
    }
}

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;/*from   ww w  .ja v  a2  s.c o m*/
    try {
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }
        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }
        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration)
        throws IOException {
    FTPClient ftp = null;/*from  ww  w  .  j  a v  a 2s  . c  o  m*/
    try {
        String username = linkConfiguration.linkConfig.username;
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = linkConfiguration.linkConfig.password;
        }

        String connectString = linkConfiguration.linkConfig.uri;
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }

        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        // The following section to get the system key for FTPClientConfig is just there for testing purposes
        String systemKey = null;
        String systemTypeString = context.getString("spark.mainframe.connector.system.type", "MVS");
        if (systemTypeString.equals("MVS")) {
            systemKey = FTPClientConfig.SYST_MVS;
        } else if (systemTypeString.equals("UNIX")) {
            systemKey = FTPClientConfig.SYST_UNIX;
        } else {
            assert (false);
        }

        FTPClientConfig config = new FTPClientConfig(systemKey);
        ftp.configure(config);

        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}