Example usage for java.util Arrays toString

List of usage examples for java.util Arrays toString

Introduction

In this page you can find the example usage for java.util Arrays toString.

Prototype

public static String toString(Object[] a) 

Source Link

Document

Returns a string representation of the contents of the specified array.

Usage

From source file:microbiosima.SelectiveMicrobiosima.java

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

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

    Options options = new Options();

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

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

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

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

    formatter.setWidth(80);

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

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

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

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

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

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

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

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

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

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryClassDeclarationAttributes.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from   w  w w  . jav  a 2  s . co  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryClassDeclarationAttributes.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            HashMap<String, EList<NamedElement>> list = JavaQueries.getClassDeclarationAttributes(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO,
                    MessageFormat.format("Query result contains {0} elements", list.entrySet().size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapTraverser.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/* w w  w  .  ja  v  a  2  s . c  o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        resource.getContents().get(0);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

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

/**
 * The class constructor./*from  ww  w  .j av a2  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 {

    int seedNetwork = 61236719 + 123;

    int numberOfGaussians = 20;

    int numberOfMultinomials = numberOfGaussians;
    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks((int) 1.3 * (numberOfGaussians + numberOfMultinomials));

    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    int seed = seedNetwork + 231591;

    //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.getTopologicalOrder(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);

    int parallelSamples = 100;
    int samplingMethodSize = 10000;

    mpeInference.setSampleSize(parallelSamples);

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

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

    Assignment 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());
    long timeStop = System.nanoTime();
    double 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();

    // 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();

    /***********************************************
     *        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();

    //  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();

    /***********************************************
     *        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();

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

        // MPE INFERENCE, DETERMINISTIC
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.EXHAUSTIVE);

        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();

    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaTraverser.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);// ww w.ja  v  a 2  s  .c  o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI uri = URI.createURI("morsa://" + commandLine.getOptionValue(IN));

        Class<?> inClazz = MorsaTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        loadOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        loadOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_POLICY, FIFOEObjectCachePolicy.class.getName());
        //         loadOpts.put(IMorsaResource.OPTION_MAX_CACHE_SIZE, 30000);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_FLUSH_FACTOR, 0.3f);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD_STRATEGY, IMorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, true);

        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.music.tools.ScaleTester.java

public static void main(String[] args) {
    System.out.println(// w ww.  j a  v a  2s  .  co  m
            "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>");
    final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true);
    try {
        fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class);
        int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class);

        List<Double> harmonicFrequencies = new ArrayList<>();
        List<String> ratios = new ArrayList<>();
        Set<Double> frequencies = new HashSet<Double>();
        frequencies.add(fundamentalFreq);
        int octaveMultiplier = 2;
        for (int i = 2; i < 100; i++) {
            // Exclude the 7th harmonic TODO exclude the 11th as well?
            // http://www.phy.mtu.edu/~suits/badnote.html
            if (i % 7 == 0) {
                continue;
            }
            double actualFreq = fundamentalFreq * i;
            double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier);
            if (closestTonicRatio < 1 || closestTonicRatio > 2) {
                octaveMultiplier *= 2;
            }
            double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier);
            double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic);

            harmonicFrequencies.add(actualFreq);
            frequencies.add(normalizedFreq);
            if (frequencies.size() == pitchesInChromaticScale) {
                break;
            }
        }

        System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies);
        System.out.println("Transposed harmonic frequencies: " + frequencies);

        List<Double> chromaticScale = new ArrayList<>(frequencies);
        Collections.sort(chromaticScale);

        // find the "perfect" interval (e.g. perfect fifth)
        int perfectIntervalIndex = 0;
        int idx = 0;
        for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) {
            Double noteFreq = it.next();
            long[] fraction = findCommonFraction(noteFreq / fundamentalFreq);
            fractionCache.put(noteFreq, fraction);
            if (fraction[0] == 3 && fraction[1] == 2) {
                perfectIntervalIndex = idx;
                System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex);
            }
            idx++;
            ratios.add(Arrays.toString(fraction));
        }
        System.out.println("Ratios to fundemental frequency: " + ratios);

        if (getBooleanArgument(args, 4, USE_ET)) {
            chromaticScale = temper(chromaticScale);
        }

        System.out.println();
        System.out.println("Chromatic scale: " + chromaticScale);

        Set<Double> scaleSet = new HashSet<Double>();
        scaleSet.add(chromaticScale.get(0));
        idx = 0;
        List<Double> orderedInCircle = new ArrayList<>();
        // now go around the circle of perfect intervals and put the notes
        // in order
        while (orderedInCircle.size() < chromaticScale.size()) {
            orderedInCircle.add(chromaticScale.get(idx));
            idx += perfectIntervalIndex;
            idx = idx % chromaticScale.size();
        }
        System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle);

        List<Double> scale = new ArrayList<Double>(scaleSet);
        int currentIdxInCircle = orderedInCircle.size() - 1; // start with
                                                             // the last
                                                             // note in the
                                                             // circle
        int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class);
        while (scale.size() < scaleSize) {
            double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size());
            if (!scale.contains(pitch)) {
                scale.add(pitch);
            }
            currentIdxInCircle++;
        }
        Collections.sort(scale);

        System.out.println("Scale: " + scale);

        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af);
        line.start();

        Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]);

        // first play the whole scale
        WaveMelodyGenerator.playScale(line, scaleFrequencies);
        // then generate a random melody in the scale
        WaveMelodyGenerator.playMelody(line, scaleFrequencies);

        line.drain();
        line.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.Migrator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from  w  w  w  . j  ava  2s .  c  om*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option outClassOpt = OptionBuilder.create(OUT_EPACKAGE_CLASS);
    outClassOpt.setArgName("CLASS");
    outClassOpt.setDescription("FQN of output EPackage implementation class");
    outClassOpt.setArgs(1);
    outClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(outClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createFileURI(commandLine.getOptionValue(OUT));
        Class<?> inClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        Class<?> outClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(OUT_EPACKAGE_CLASS));

        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);
        EPackage outEPackage = (EPackage) outClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);
        Resource targetResource = resourceSet.createResource(targetUri);

        targetResource.getContents().clear();
        LOG.log(Level.INFO, "Start migration");
        targetResource.getContents()
                .add(MigratorUtil.migrate(sourceResource.getContents().get(0), outEPackage));
        LOG.log(Level.INFO, "Migration finished");

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        saveOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saving done");
    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ReferencesCounter.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from  w  w  w .  j av a  2 s.c o m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option labelOpt = OptionBuilder.create(LABEL);
    labelOpt.setArgName("LABEL");
    labelOpt.setDescription("Label for the data set");
    labelOpt.setArgs(1);
    labelOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(labelOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        Class<?> inClazz = ReferencesCounter.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);

        FileWriter writer = new FileWriter(new File(commandLine.getOptionValue(OUT)));
        try {
            writer.write(commandLine.getOptionValue(LABEL));
            writer.write("\n");

            for (Iterator<EObject> iterator = sourceResource.getAllContents(); iterator.hasNext();) {
                EObject eObject = iterator.next();
                for (EStructuralFeature feature : eObject.eClass().getEAllStructuralFeatures()) {
                    if (feature.isMany() && eObject.eIsSet(feature)) {
                        EList<?> value = (EList<?>) eObject.eGet(feature);
                        //                     if (value.size() > 10) 
                        writer.write(String.format("%d\n", value.size()));
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(writer);
        }

    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQuery.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//from   w  w  w  .  j a  v a  2  s .  c o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQuery.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result (list) contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result (loops) contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.ikanow.aleph2.data_import_manager.harvest.modules.LocalHarvestTestModule.java

/** Entry point
 * @param args - config_file source_key harvest_tech_id
 * @throws Exception //from w ww .  ja v  a  2  s  .  co  m
 */
public static void main(final String[] args) {
    try {
        if (args.length < 3) {
            System.out.println("CLI: config_file source_key harvest_tech_jar_path");
            System.exit(-1);
        }
        System.out.println("Running with command line: " + Arrays.toString(args));
        Config config = ConfigFactory.parseFile(new File(args[0]));

        LocalHarvestTestModule app = ModuleUtils.initializeApplication(Arrays.asList(), Optional.of(config),
                Either.left(LocalHarvestTestModule.class));
        app.start(args[1], args[2], Arrays.copyOfRange(args, 3, args.length));
    } catch (Exception e) {
        try {
            System.out.println("Got all the way to main");
            e.printStackTrace();
        } catch (Exception e2) { // the exception failed!
            System.out.println(ErrorUtils.getLongForm("Got all the way to main: {0}", e));
        }
    }
}