Example usage for java.util ArrayList add

List of usage examples for java.util ArrayList add

Introduction

In this page you can find the example usage for java.util ArrayList add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:ISMAGS.CommandLineInterface.java

public static void main(String[] args) throws IOException {
    String folder = null, files = null, motifspec = null, output = null;

    Options opts = new Options();
    opts.addOption("folder", true, "Folder name");
    opts.addOption("linkfiles", true,
            "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)");
    opts.addOption("motif", true, "Motif description by two strings (format: linktypes)");
    opts.addOption("output", true, "Output file name");

    CommandLineParser parser = new PosixParser();
    try {/*from w  ww . j  av a  2s .  c  o  m*/
        CommandLine cmd = parser.parse(opts, args);
        if (cmd.hasOption("folder")) {
            folder = cmd.getOptionValue("folder");
        }
        if (cmd.hasOption("linkfiles")) {
            files = cmd.getOptionValue("linkfiles");
        }
        if (cmd.hasOption("motif")) {
            motifspec = cmd.getOptionValue("motif");
        }
        if (cmd.hasOption("output")) {
            output = cmd.getOptionValue("output");
        }
    } catch (ParseException e) {
        Die("Error: Parsing error");
    }

    if (print) {
        printBanner(folder, files, motifspec, output);
    }

    if (folder == null || files == null || motifspec == null || output == null) {
        Die("Error: not all options are provided");
    } else {
        ArrayList<String> linkfiles = new ArrayList<String>();
        ArrayList<String> linkTypes = new ArrayList<String>();
        ArrayList<String> sourcenetworks = new ArrayList<String>();
        ArrayList<String> destinationnetworks = new ArrayList<String>();
        ArrayList<Boolean> directed = new ArrayList<Boolean>();
        StringTokenizer st = new StringTokenizer(files, " ");
        while (st.hasMoreTokens()) {
            linkTypes.add(st.nextToken());
            directed.add(st.nextToken().equals("d"));
            sourcenetworks.add(st.nextToken());
            destinationnetworks.add(st.nextToken());
            linkfiles.add(folder + st.nextToken());
        }
        ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>();
        HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>();
        for (int i = 0; i < linkTypes.size(); i++) {
            String n = linkTypes.get(i);
            char nn = n.charAt(0);
            LinkType t = typeTranslation.get(nn);
            if (t == null) {
                t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i));
            }
            allLinkTypes.add(t);
            typeTranslation.put(nn, t);
        }
        if (print) {
            System.out.println("Reading network..");
        }
        Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes);

        Motif motif = getMotif(motifspec, typeTranslation);

        if (print) {
            System.out.println("Starting the search..");
        }
        MotifFinder mf = new MotifFinder(network);
        long tijd = System.nanoTime();
        Set<MotifInstance> motifs = mf.findMotif(motif, false);
        tijd = System.nanoTime() - tijd;
        if (print) {
            System.out.println("Completed search in " + tijd / 1000000 + " milliseconds");
        }
        if (print) {
            System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif");
        }
        if (print) {
            System.out.println("Writing instances to file: " + output);
        }
        printMotifs(motifs, output);
        if (print) {
            System.out.println("Done.");
        }
        //            Set<MotifInstance> motifs=null;
        //            MotifFinder mf=null;
        //            System.out.println("Starting the search..");
        //            long tstart = System.nanoTime();
        //            for (int i = 0; i < it; i++) {
        //
        //                mf = new MotifFinder(network, allLinkTypes, true);
        //                motifs = mf.findMotif(motif);
        //            }
        //
        //            long tend = System.nanoTime();
        //            double time_in_ms = (tend - tstart) / 1000000.0;
        //            System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms");
        ////        System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes");
        ////        System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms");
        //            printMotifs(motifs, output);

    }

}

From source file:metaTile.Main.java

/**
 * @param args//ww w  .ja  v a2 s  .c om
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

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

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:asl.seedscan.SeedScan.java

public static void main(String args[]) {
    // Default locations of config and schema files
    File configFile = new File("config.xml");
    File schemaFile = new File("schemas/SeedScanConfig.xsd");
    boolean parseConfig = true;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);

    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The xsd schema file which should be used to verify the config file format. ");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);//from  w  ww  . j a va 2 s  . c  om

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.error("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator<?> iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();
        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        }
    }

    // ==== Configuration Read and Parse Actions ====
    ConfigParser parser = new ConfigParser(schemaFiles);
    ConfigT config = parser.parseConfig(configFile);

    // Print out configuration file contents
    Formatter formatter = new Formatter(new StringBuilder(), Locale.US);

    // ===== CONFIG: LOCK FILE =====
    File lockFile = new File(config.getLockfile());
    logger.info("SeedScan lock file is '" + lockFile + "'");
    LockFile lock = new LockFile(lockFile);
    if (!lock.acquire()) {
        logger.error("Could not acquire lock.");
        System.exit(1);
    }

    // ===== CONFIG: LOGGING =====
    // MTH: This is now done in log4j.properties file

    // ===== CONFIG: DATABASE =====
    MetricDatabase readDB = new MetricDatabase(config.getDatabase());
    MetricDatabase writeDB = new MetricDatabase(config.getDatabase());
    MetricReader reader = new MetricReader(readDB);
    MetricInjector injector = new MetricInjector(writeDB);

    // ===== CONFIG: SCANS =====
    Hashtable<String, Scan> scans = new Hashtable<String, Scan>();
    if (config.getScans().getScan() == null) {
        logger.error("No scans in configuration.");
        System.exit(1);
    } else {
        for (ScanT scanCfg : config.getScans().getScan()) {
            String name = scanCfg.getName();
            if (scans.containsKey(name)) {
                logger.error("Duplicate scan name '" + name + "' encountered.");
                System.exit(1);
            }

            // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd
            if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) {
                logger.error(
                        "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!");
                System.exit(1);
            }

            // Configure this Scan
            Scan scan = new Scan(scanCfg.getName());
            scan.setPathPattern(scanCfg.getPath());
            scan.setDatalessDir(scanCfg.getDatalessDir());
            scan.setEventsDir(scanCfg.getEventsDir());
            scan.setPlotsDir(scanCfg.getPlotsDir());
            scan.setDaysToScan(scanCfg.getDaysToScan().intValue());
            if (scanCfg.getStartDay() != null) {
                scan.setStartDay(scanCfg.getStartDay().intValue());
            }
            if (scanCfg.getStartDate() != null) {
                scan.setStartDate(scanCfg.getStartDate().intValue());
            }

            if (scanCfg.getNetworkSubset() != null) {
                logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset());
                Filter filter = new Filter(false);
                for (String network : scanCfg.getNetworkSubset().split(",")) {
                    logger.debug("Network =[{}]", network);
                    filter.addFilter(network);
                }
                scan.setNetworks(filter);
            }
            if (scanCfg.getStationSubset() != null) {
                logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset());
                Filter filter = new Filter(false);
                for (String station : scanCfg.getStationSubset().split(",")) {
                    logger.debug("Station =[{}]", station);
                    filter.addFilter(station);
                }
                scan.setStations(filter);
            }
            if (scanCfg.getLocationSubset() != null) {
                logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset());
                Filter filter = new Filter(false);
                for (String location : scanCfg.getLocationSubset().split(",")) {
                    logger.debug("Location =[{}]", location);
                    filter.addFilter(location);
                }
                scan.setLocations(filter);
            }
            if (scanCfg.getChannelSubset() != null) {
                logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset());
                Filter filter = new Filter(false);
                for (String channel : scanCfg.getChannelSubset().split(",")) {
                    logger.debug("Channel =[{}]", channel);
                    filter.addFilter(channel);
                }
                scan.setChannels(filter);
            }

            for (MetricT met : scanCfg.getMetrics().getMetric()) {
                try {
                    Class<?> metricClass = Class.forName(met.getClassName());
                    MetricWrapper wrapper = new MetricWrapper(metricClass);
                    for (ArgumentT arg : met.getArgument()) {
                        wrapper.add(arg.getName(), arg.getValue());
                    }
                    scan.addMetric(wrapper);
                } catch (ClassNotFoundException ex) {
                    logger.error("No such metric class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (InstantiationException ex) {
                    logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (IllegalAccessException ex) {
                    logger.error("Illegal access while loading class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (NoSuchFieldException ex) {
                    logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'");
                    System.exit(1);
                }

            }
            scans.put(name, scan);
        }
    }

    // ==== Establish Database Connection ====
    // TODO: State Tracking in the Database
    // - Record scan started in database.
    // - Track our progress as we go so a new process can pick up where
    //   we left off if our process dies.
    // - Mark when each date-station-channel-operation is complete
    //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get

    // For each day ((yesterday - scanDepth) to yesterday)
    // scan for these channel files, only process them if
    // they have not yet been scanned, or if changes have
    // occurred to the file since its last scan. Do this for
    // each scan type. Do not re-scan data for each type,
    // launch processes for each scan and use the same data set
    // for each. If we can pipe the data as it is read, do so.
    // If we need to push all of it at once, do these in sequence
    // in order to preserve overall system memory resources.

    Scan scan = null;

    // ==== Perform Scans ====

    scan = scans.get("daily");

    //MTH: This part could/should be moved up higher except that we need to know datalessDir, which,
    //     at this point, is configured on a per scan basis ... so we need to know what scan we're doing
    MetaServer metaServer = null;
    if (config.getMetaserver() != null) {
        if (config.getMetaserver().getUseRemote().equals("yes")
                || config.getMetaserver().getUseRemote().equals("true")) {
            String remoteServer = config.getMetaserver().getRemoteUri();
            try {
                metaServer = new MetaServer(new URI(remoteServer));
            } catch (Exception e) {
                logger.error("caught URI exception:" + e.getMessage());
            }
        } else {
            metaServer = new MetaServer(scan.getDatalessDir());
        }
    } else { // Use local MetaServer
        metaServer = new MetaServer(scan.getDatalessDir());
    }

    List<Station> stations = null;

    if (config.getStationList() == null) { // get StationList from MetaServer
        logger.info("Get StationList from MetaServer");
        stations = metaServer.getStationList();
    } else { // read StationList from config.xml
        logger.info("Read StationList from config.xml");
        List<String> stationList = config.getStationList().getStation();
        if (stationList.size() > 0) {
            stations = new ArrayList<Station>();
            for (String station : stationList) {
                String[] words = station.split("_");
                if (words.length != 2) {
                    logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip",
                            station));
                } else {
                    stations.add(new Station(words[0], words[1]));
                    logger.info("config.xml: Read station:" + station);
                }
            }
        } else {
            logger.error("Error: No valid stations read from config.xml");
        }
    }

    if (stations == null) {
        logger.error("Found NO stations to scan --> EXITTING SeedScan");
        System.exit(1);
    }

    Thread readerThread = new Thread(reader);
    readerThread.start();
    logger.info("Reader thread started.");

    Thread injectorThread = new Thread(injector);
    injectorThread.start();
    logger.info("Injector thread started.");

    // Loop over scans and hand each one to a ScanManager
    logger.info("Hand scan to ScanManager");
    for (String key : scans.keySet()) {
        scan = scans.get(key);
        logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(),
                scan.getStartDate(), scan.getDaysToScan()));
        ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer);
    }

    logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads");

    try {
        injector.halt();
        logger.info("All stations processed. Waiting for injector thread to finish...");
        synchronized (injectorThread) {
            //injectorThread.wait();
            injectorThread.interrupt();
        }
        logger.info("Injector thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The injector thread was interrupted while attempting to complete requests.");
    }

    try {
        reader.halt();
        logger.info("All stations processed. Waiting for reader thread to finish...");
        synchronized (readerThread) {
            //readerThread.wait();
            readerThread.interrupt();
        }
        logger.info("Reader thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The reader thread was interrupted while attempting to complete requests.");
    }

    try {
        lock.release();
    } catch (IOException e) {
        ;
    } finally {
        logger.info("Release seedscan lock and quit metaServer");
        lock = null;
        metaServer.quit();
    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.InformationTheoreticMetricLearner.java

/**
 * @param args/*  w w w  . j  a va2  s  .  c  o m*/
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int d = 2;
    final double u = 5.0;
    final double ell = 7.0;
    final double gamma = 1.0;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final RealMatrix A0 = MatrixUtils.createRealIdentityMatrix(d);

    for (final int w : new int[] { 0, 5 }) {
        for (final int h : new int[] { 0, 50 }) {
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    X.add(new ArrayRealVector(new double[] { x + w, y + h }));
                }
            }
        }
    }

    final ArrayList<int[]> S = new ArrayList<int[]>();
    S.add(new int[] { 4, 12 }); // Must link diagonally
    S.add(new int[] { 21, 31 });
    final ArrayList<double[]> Sd = new ArrayList<double[]>();
    for (final int[] s : S) {
        final double[] a = X.get(s[0]).subtract(X.get(s[1])).toArray();
        Sd.add(a);
    }

    final ArrayList<int[]> D = new ArrayList<int[]>();
    D.add(new int[] { 5, 23 });
    D.add(new int[] { 13, 32 }); // Cannot link vertically
    final ArrayList<double[]> Dd = new ArrayList<double[]>();
    for (final int[] dd : D) {
        final double[] a = X.get(dd[0]).subtract(X.get(dd[1])).toArray();
        Dd.add(a);
    }

    final InformationTheoreticMetricLearner itml = new InformationTheoreticMetricLearner(Sd, Dd, u, ell, A0,
            gamma, rng);
    itml.run();

    final RealMatrix A = itml.A();

    System.out.println(A0.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }

    System.out.println(A.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }

    //      int i = 0;
    //      for( final int w : new int[] { 0, 5 } ) {
    //         for( final int h : new int[] { 0, 5 } ) {
    //            for( int x = -1; x <= 1; ++x ) {
    //               for( int y = -1; y <= 1; ++y ) {
    //                  System.out.println( itml.A().operate( X.get( i++ ) ) );
    //               }
    //            }
    //         }
    //      }
}

From source file:net.sf.tweety.cli.plugins.CliMain.java

public static void main(String[] args) {

    // check, if first call parameter is for the helptext
    if (args.length == 0) {
        System.out.println("Welcome to the Tweety command line interface.");
        System.out.println("Obtain help with command --help");
        System.exit(0);/* ww  w . j  a  v a  2  s . co  m*/
    } else if ((args.length == 1 && args[0].equals("--help"))) {
        printHelpText();
        System.exit(0);
    } else if (args.length == 1 && !args[0].contains("--help")) {
        System.out.println("No valid input, call with --help for helptext");
        System.exit(0);
    }

    // create new plugin manager
    PluginManager pm = PluginManagerFactory.createPluginManager();
    // create plugin manager util
    PluginManagerUtil pmu = new PluginManagerUtil(pm);

    // System.out.println(pmu.getPlugins());

    // collected parameter
    ArrayList<ArrayList<String>> collectedparams = new ArrayList<ArrayList<String>>();

    // list of available plugins
    Map<String, String> availablePlugins = new HashMap<String, String>();

    // try to configure CLI
    try {
        availablePlugins = configCLI();
    } catch (ConfigurationException e) {
        System.out.println("Something went wrong with your Configuration: ");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.out.println("No such configuration file: ");
        e.printStackTrace();
    }

    // handle all input parameter
    for (int i = 0; i < args.length; i++) {
        // The called plugin
        if (args[i].equals(ARG__CALLED_PLUGIN) || args[i].equals(ARG__CALLED_PLUGIN_SHORT)) {
            String calledPlugin = "";
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                calledPlugin += args[++i];
            }
            plugin = calledPlugin;
        }

        // the input files
        else if (args[i].equals(ARG__INPUT_FILES) || args[i].equals(ARG__INPUT_FILES_SHORT)) {
            ArrayList<String> inFiles = new ArrayList<String>();
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                inFiles.add(args[++i]);
            }

            String[] files = new String[inFiles.size()];
            inFiles.toArray(files);

            File[] inf = new File[inFiles.size()];

            for (int k = 0; k < inf.length; k++) {
                inf[k] = new File(files[k]).getAbsoluteFile();
            }

            inputFiles = inf;
        }

        // output file
        else if (args[i].equals(ARG__OUTPUT_FILE) || args[i].equals(ARG__OUTPUT_FILE_SHORT)) {
            // outputFile not used!
            outputFile = args[++i];
        }

        // collecting given command parameters
        else if (args[i].startsWith("-")) {
            ArrayList<String> temp = new ArrayList<String>();
            temp.add(args[i]);
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                temp.add(args[++i]);

            }
            collectedparams.add(temp);
        } // else if (args[i].equals(ARG__DEBUG_FLAG)
          // ||args[i].equals(ARG__DEBUG_FLAG_SHORT)){
          // debug = true;
          // }
    }

    // check whether the called plugin is present
    boolean pluginPresent = false;
    for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
        if (tp.getCommand().equalsIgnoreCase(plugin)) {
            pluginPresent = true;
            System.out.println("Called plugin present");
        }
    }
    // TODO: move loading into own method
    // trying to load plugin if not present
    // old method for loading plugins
    if (!pluginPresent) {
        System.out.print("Trying to find plugin...");
        if (availablePlugins.containsKey(plugin)) {
            pm.addPluginsFrom(new File(availablePlugins.get(plugin)).toURI());
            System.out.print("success.\n");
        } else {
            System.out.print("no such plugin available.\n");
        }
    }

    // Test: print all plugins
    // System.out.println("Plugin loaded due to call parameter: " +
    // pm.getPlugin(TweetyPlugin.class, new
    // OptionCapabilities("Tweety Plugin", plugin) ));
    // System.out.println("Print all plugins: " + pmu.getPlugins());
    // System.out.println("Given plugin call parameter: " + plugin);

    // each plugin MUST implement the capabilites "Tweety Plugin" and the
    // variable "call parameter" to select called plugin from plugin pool
    TweetyPlugin tp = pm.getPlugin(TweetyPlugin.class, new OptionCapabilities("Tweety Plugin", plugin));

    // for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
    if (tp.getCommand().equalsIgnoreCase(plugin)) {
        System.out.println("Valid plugin found.");
        // each input parameter is checked against the called plugin
        // whether it is valid
        ArrayList<CommandParameter> ip = new ArrayList<CommandParameter>();

        System.out.print("Trying to instantiate parameters...");
        try {
            ip.addAll(instantiateParameters(tp, collectedparams));
            System.out.print("done.\n");
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        PluginOutput out = new PluginOutput();

        System.out.println("Execute Plugin...");
        out = tp.execute(inputFiles, ip.toArray(new CommandParameter[ip.size()]));

        if (outputFile != null) {

            try {
                FileWriter fw = new FileWriter(outputFile);
                fw.write(out.getOutput());
                fw.close();
                System.out.println("Output written to file: " + outputFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            System.out.println("No output file given, writing to console...");
            System.out.println("Output: \n" + out.getOutput());
        }
    } else {
        System.out.println("Faulty parameters. Please check input.");

    }

}

From source file:edu.oregonstate.eecs.mcplan.ml.KulisLowRankKernelLearner.java

/**
 * @param args/*from  www.j  ava  2  s.  com*/
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int d = 2;
    final double u = 5.0;
    final double ell = 7.0;
    final double gamma = 1.0;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final RealMatrix A0 = MatrixUtils.createRealIdentityMatrix(d);

    for (final int w : new int[] { 0, 5 }) {
        for (final int h : new int[] { 0, 5 }) {
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    X.add(new ArrayRealVector(new double[] { x + w, y + h }));
                }
            }
        }
    }

    final ArrayList<int[]> S = new ArrayList<int[]>();
    S.add(new int[] { 4, 31 }); // Must link diagonally
    final ArrayList<int[]> D = new ArrayList<int[]>();
    D.add(new int[] { 4, 13 });
    D.add(new int[] { 22, 31 });
    D.add(new int[] { 13, 22 }); // Cannot link vertically

    final KulisLowRankKernelLearner itml = new KulisLowRankKernelLearner(X, S, D, u, ell, A0, gamma, rng);
    itml.run();

    final RealMatrix A = itml.A();

    System.out.println(A0.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }

    System.out.println(A.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }

    //      int i = 0;
    //      for( final int w : new int[] { 0, 5 } ) {
    //         for( final int h : new int[] { 0, 5 } ) {
    //            for( int x = -1; x <= 1; ++x ) {
    //               for( int y = -1; y <= 1; ++y ) {
    //                  System.out.println( itml.A().operate( X.get( i++ ) ) );
    //               }
    //            }
    //         }
    //      }
}

From source file:com.tonygalati.sprites.SpriteGenerator.java

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

    //        if (args.length != 3)
    //        {//from  w w w . j  a  v a 2s  .c o  m
    //           System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n");
    //           System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n");
    //           System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n");
    //           System.out.print("most browsers.\n\n");
    //           return;
    //        }

    //        Integer margin = Integer.parseInt(args[1]);
    Integer margin = Integer.parseInt("1");
    String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png";
    SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator();

    ClassLoader classLoader = SpriteGenerator.class.getClassLoader();
    URL folderPath = classLoader.getResource(NAIC_SMALL_ICON);
    if (folderPath != null) {
        File imageFolder = new File(folderPath.getPath());

        // Read images
        ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
        Integer yCoordinate = null;

        for (File f : imageFolder.listFiles()) {
            if (f.isFile()) {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

                if (ext.equals("png")) {
                    System.out.println("adding file " + fileName);
                    BufferedImage image = ImageIO.read(f);
                    imageList.add(image);

                    if (yCoordinate == null) {
                        yCoordinate = 0;
                    } else {
                        yCoordinate += (image.getHeight() + margin);
                    }

                    // add to cssGenerator
                    cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate);
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList) {
            totalHeight += image.getHeight() + margin;

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(),
                totalHeight, maxWidth);

        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList) {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight() + margin;
        }

        System.out.format("Writing sprite: %s%n", spriteFile);
        ImageIO.write(sprite, "png", new File(spriteFile));
        File cssFile = cssGenerator.getFile(spriteFile);
        System.out.println(cssFile.getAbsolutePath() + " created");
    } else {
        System.err.println("Could not find folder: " + NAIC_SMALL_ICON);

    }

}

From source file:LineageSimulator.java

public static void main(String[] args) {
    Options options = new Options();
    // commands//from w  w  w  . j  av a  2s .  c  om
    //options.addOption("simulate", false, "Simulate lineage trees");
    //options.addOption("sample", false, "Sample from the simulated trees");
    //options.addOption("evaluate", false, "Evaluate trees");

    // tree simulation
    options.addOption("t", "nTrees", true, "Number of trees to simulate (default: 100)");
    options.addOption("i", "nIter", true, "Number of tree growth iterations (default: 50)");
    options.addOption("snv", "probSNV", true,
            "Per node probablity of generating a descendant cell population with an acquired SNV during a tree growth iteration (default: 0.15)");
    options.addOption("cnv", "probCNV", true,
            "Per node probablity of generating a descendant cell population with an acquired CNV during a tree growth iteration (default: 0.02)");
    options.addOption("probDeath", true,
            "Probablity of a cell population death in each tree growth iteration (default: 0.06)");
    options.addOption("maxPopulationSize", true, "Max size of a cell population (default: 1000000)");
    options.addOption("minNodes", true,
            "Minimum number of undead cell population nodes in a valid tree, tree growth will continue beyond the defined number of iterations until this value is reached (default: 10)");
    options.addOption("maxNodes", true,
            "Maximum number of undead cell population nodes in a tree, tree growth will stop after the iteration in which this value is reached/first surpassed (default: 1000)");

    // sampling
    Option samplesOption = new Option("s", "nSamples", true,
            "Number of samples to collect, accepts multiple values, e.g. 5 10 15 (default: 5)");
    samplesOption.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(samplesOption);
    Option covOption = new Option("c", "coverage", true,
            "Simulated coverage to generate the VAFs, accepts multiple values, e.g. 500 1000 (default: 1000)");
    covOption.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(covOption);
    options.addOption("maxSubclones", true, "Max number of subclones per sample (default: 5)");
    options.addOption("sampleSize", true, "Number of cells per sample (default: 100000)");
    options.addOption("e", true, "Sequencing error (default: 0.001)");
    options.addOption("minNC", true,
            "Minimum percentage of normal contamination per sample; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 0)");
    options.addOption("maxNC", true,
            "Maximum percentage of normal contamination per sample; if maxNC < minNC, maxNC will be automatically set to minNC; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 20)");
    //options.addOption("localized", false, "Enable localized sampling (default: random sampling)");
    //options.addOption("mixSubclone", false, "With localized sampling, add an additional subclone from a different subtree to each sample; by default, the sample is localized to a single disjoint subtree");

    // input/output/display
    options.addOption("dir", "outputDir", true,
            "Directory where the output files should be created [required]");
    options.addOption("dot", false, "Produce DOT files for the simulated trees");
    options.addOption("sdot", "sampledDot", false,
            "Produce DOT files for the simulated trees with indicated samples");
    options.addOption("sampleProfile", false,
            "Output VAF file includes an additional column with the binary sample profile for each SNV");

    // other
    options.addOption("v", "verbose", false, "Verbose mode");
    options.addOption("h", "help", false, "Print usage");

    // display order
    ArrayList<Option> optionsList = new ArrayList<Option>();
    optionsList.add(options.getOption("dir"));
    optionsList.add(options.getOption("t"));
    optionsList.add(options.getOption("i"));
    optionsList.add(options.getOption("snv"));
    optionsList.add(options.getOption("cnv"));
    optionsList.add(options.getOption("probDeath"));
    optionsList.add(options.getOption("maxPopulationSize"));
    optionsList.add(options.getOption("minNodes"));
    optionsList.add(options.getOption("maxNodes"));
    optionsList.add(options.getOption("s"));
    optionsList.add(options.getOption("c"));
    optionsList.add(options.getOption("maxSubclones"));
    optionsList.add(options.getOption("sampleSize"));
    optionsList.add(options.getOption("e"));
    optionsList.add(options.getOption("minNC"));
    optionsList.add(options.getOption("maxNC"));
    optionsList.add(options.getOption("dot"));
    optionsList.add(options.getOption("sdot"));
    optionsList.add(options.getOption("sampleProfile"));
    optionsList.add(options.getOption("v"));
    optionsList.add(options.getOption("h"));

    CommandLineParser parser = new BasicParser();
    CommandLine cmdLine = null;
    HelpFormatter hf = new HelpFormatter();
    hf.setOptionComparator(new OptionComarator<Option>(optionsList));
    try {
        cmdLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        hf.printHelp(PROG_NAME, options);
        System.exit(-1);
    }
    Args params = new Args();
    if (cmdLine.hasOption("dir")) {
        params.simPath = cmdLine.getOptionValue("dir") + "/" + SIMULATION_DATA_DIR;
    } else {
        System.err.println("Required parameter: output directory path [-dir]");
        hf.printHelp(PROG_NAME, options);
        System.exit(-1);
    }
    if (cmdLine.hasOption("t")) {
        Parameters.NUM_TREES = Integer.parseInt(cmdLine.getOptionValue("t"));
    }
    if (cmdLine.hasOption("i")) {
        Parameters.NUM_ITERATIONS = Integer.parseInt(cmdLine.getOptionValue("i"));
    }
    if (cmdLine.hasOption("snv")) {
        Parameters.PROB_SNV = Double.parseDouble(cmdLine.getOptionValue("snv"));
    }
    if (cmdLine.hasOption("cnv")) {
        Parameters.PROB_CNV = Double.parseDouble(cmdLine.getOptionValue("cnv"));
    }
    if (cmdLine.hasOption("probDeath")) {
        Parameters.PROB_DEATH = Double.parseDouble(cmdLine.getOptionValue("probDeath"));
    }
    if (cmdLine.hasOption("maxPopulationSize")) {
        Parameters.MAX_POPULATION_SIZE = Integer.parseInt(cmdLine.getOptionValue("maxPopulationSize"));
    }
    if (cmdLine.hasOption("minNodes")) {
        Parameters.MIN_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("minNodes"));
        if (Parameters.MIN_NUM_NODES < 1) {
            System.err.println("Minimum number of nodes [-minNodes] must be at least 1");
            System.exit(-1);
        }
    }
    if (cmdLine.hasOption("maxNodes")) {
        Parameters.MAX_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("maxNodes"));
        if (Parameters.MAX_NUM_NODES < 1 || Parameters.MAX_NUM_NODES < Parameters.MIN_NUM_NODES) {
            System.err.println(
                    "Maximum number of nodes [-maxNodes] must be at least 1 and not less than [-minNodes]");
            System.exit(-1);
        }
    }
    if (cmdLine.hasOption("s")) {
        String[] samples = cmdLine.getOptionValues("s");
        Parameters.NUM_SAMPLES_ARRAY = new int[samples.length];
        for (int i = 0; i < samples.length; i++) {
            Parameters.NUM_SAMPLES_ARRAY[i] = Integer.parseInt(samples[i]);
        }
    }
    if (cmdLine.hasOption("c")) {
        String[] cov = cmdLine.getOptionValues("c");
        Parameters.COVERAGE_ARRAY = new int[cov.length];
        for (int i = 0; i < cov.length; i++) {
            Parameters.COVERAGE_ARRAY[i] = Integer.parseInt(cov[i]);
        }
    }
    if (cmdLine.hasOption("maxSubclones")) {
        Parameters.MAX_NUM_SUBCLONES = Integer.parseInt(cmdLine.getOptionValue("maxSubclones"));
    }
    if (cmdLine.hasOption("sampleSize")) {
        Parameters.NUM_CELLS_PER_SAMPLE = Integer.parseInt(cmdLine.getOptionValue("sampleSize"));
    }
    if (cmdLine.hasOption("e")) {
        Parameters.SEQUENCING_ERROR = Double.parseDouble(cmdLine.getOptionValue("e"));
    }
    if (cmdLine.hasOption("minNC")) {
        Parameters.MIN_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("minNC"));
    }
    if (cmdLine.hasOption("maxNC")) {
        Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("maxNC"));
    }
    if (Parameters.MAX_PERCENT_NORMAL_CONTAMINATION < Parameters.MIN_PERCENT_NORMAL_CONTAMINATION) {
        Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Parameters.MIN_PERCENT_NORMAL_CONTAMINATION;
    }

    /*if(cmdLine.hasOption("localized")) {
       Parameters.LOCALIZED_SAMPLING = true;
    }
    if(cmdLine.hasOption("mixSubclone")) {
       Parameters.MIX_NBR_SUBTREE_SUBCLONE = true;
    }*/

    if (cmdLine.hasOption("dot")) {
        params.generateDOT = true;
    }
    if (cmdLine.hasOption("sampledDot")) {
        params.generateSampledDOT = true;
    }
    if (cmdLine.hasOption("sampleProfile")) {
        params.outputSampleProfile = true;
    }
    if (cmdLine.hasOption("h")) {
        new HelpFormatter().printHelp(" ", options);
    }
    // logger
    ConsoleHandler h = new ConsoleHandler();
    h.setFormatter(new LogFormatter());
    h.setLevel(Level.INFO);
    logger.setLevel(Level.INFO);
    if (cmdLine.hasOption("v")) {
        h.setLevel(Level.FINEST);
        logger.setLevel(Level.FINEST);
    }
    logger.addHandler(h);
    logger.setUseParentHandlers(false);

    // validate settings
    if (Parameters.PROB_SNV + Parameters.PROB_CNV + Parameters.PROB_DEATH > 1) {
        System.err.println("The sum of SSNV, CNV, and cell death probabilities cannot exceed 1");
        hf.printHelp(PROG_NAME, options);
        System.exit(-1);
    }
    simulateLineageTrees(params);
}

From source file:IndexService.Indexer.java

public static void main(String[] args) throws IOException {
    System.out.println("input cmd:   indexdir  idx  type  startvalue  endvalue");
    String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
    StringTokenizer st = new StringTokenizer(str);
    String indexdir = st.nextToken();
    int idx = Integer.parseInt(st.nextToken());
    String type = st.nextToken();
    String startvalue = st.nextToken();
    String endvalue = null;//from  w ww. j  ava2  s . c  o  m
    if (st.hasMoreTokens())
        endvalue = st.nextToken();
    else
        endvalue = startvalue;
    ArrayList<IRecord.IFValue> values = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values.add(new IRecord.IFValue(Byte.parseByte(startvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values.add(new IRecord.IFValue(Short.parseShort(startvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values.add(new IRecord.IFValue(Integer.parseInt(startvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values.add(new IRecord.IFValue(Long.parseLong(startvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values.add(new IRecord.IFValue(Float.parseFloat(startvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values.add(new IRecord.IFValue(Double.parseDouble(startvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values.add(new IRecord.IFValue(startvalue, idx));
    ArrayList<IRecord.IFValue> values1 = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values1.add(new IRecord.IFValue(Byte.parseByte(endvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values1.add(new IRecord.IFValue(Short.parseShort(endvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values1.add(new IRecord.IFValue(Integer.parseInt(endvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values1.add(new IRecord.IFValue(Long.parseLong(endvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values1.add(new IRecord.IFValue(Float.parseFloat(endvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values1.add(new IRecord.IFValue(Double.parseDouble(endvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values1.add(new IRecord.IFValue(endvalue, idx));
    Indexer indexer = new Indexer();
    List<IRecord> recs = indexer.getRange(indexdir, null, values, values1, 100, null, -1);
    for (IRecord rec : recs) {
        rec.show();
    }

}

From source file:edu.oregonstate.eecs.mcplan.ml.ConstrainedKMeans.java

/**
 * @param args/*from  w w  w  .  j a v  a  2s  . c  om*/
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int K = 2;
    final int d = 2;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final double u = 2.0;
    final double ell = 8.0;
    final double gamma = 10.0;

    for (final int s : new int[] { 0, 5, 10 }) {
        for (int x = -1; x <= 1; ++x) {
            for (int y = -1; y <= 1; ++y) {
                X.add(new ArrayRealVector(new double[] { x + s, y }));
            }
        }
    }

    final TIntObjectMap<Pair<int[], double[]>> M = new TIntObjectHashMap<Pair<int[], double[]>>();
    M.put(16, Pair.makePair(new int[] { 20 }, new double[] { 1.0 }));
    M.put(0, Pair.makePair(new int[] { 8 }, new double[] { 1.0 }));

    final TIntObjectMap<Pair<int[], double[]>> C = new TIntObjectHashMap<Pair<int[], double[]>>();
    C.put(13, Pair.makePair(new int[] { 20 }, new double[] { 1.0 }));
    C.put(10, Pair.makePair(new int[] { 16 }, new double[] { 1.0 }));

    final ArrayList<double[]> S = new ArrayList<double[]>();
    M.forEachKey(new TIntProcedure() {
        @Override
        public boolean execute(final int i) {
            final Pair<int[], double[]> p = M.get(i);
            if (p != null) {
                for (final int j : p.first) {
                    S.add(new double[] { i, j });
                }
            }
            return true;
        }
    });

    final ArrayList<double[]> D = new ArrayList<double[]>();
    C.forEachKey(new TIntProcedure() {
        @Override
        public boolean execute(final int i) {
            final Pair<int[], double[]> p = C.get(i);
            if (p != null) {
                for (final int j : p.first) {
                    D.add(new double[] { i, j });
                }
            }
            return true;
        }
    });

    final ConstrainedKMeans kmeans = new ConstrainedKMeans(K, d, X, M, C, rng) {
        RealMatrix A_ = MatrixUtils.createRealIdentityMatrix(d);
        double Dmax_ = 1.0;

        @Override
        public double distance(final RealVector x1, final RealVector x2) {
            final RealVector diff = x1.subtract(x2);
            return Math.sqrt(HilbertSpace.inner_prod(diff, A_, diff));
        }

        @Override
        public double distanceMax() {
            return Dmax_;
        }

        @Override
        protected void initializeDistanceFunction() {
            double max_distance = 0.0;
            for (int i = 0; i < X.size(); ++i) {
                for (int j = i + 1; j < X.size(); ++j) {
                    final double d = distance(X.get(i), X.get(j));
                    if (d > max_distance) {
                        max_distance = d;
                    }
                }
            }
            Dmax_ = max_distance;
        }

        @Override
        protected boolean updateDistanceFunction() {
            final InformationTheoreticMetricLearner itml = new InformationTheoreticMetricLearner(S, D, u, ell,
                    A_, gamma, rng_);
            itml.run();
            final double delta = A_.subtract(itml.A()).getFrobeniusNorm();
            A_ = itml.A();
            initializeDistanceFunction();
            return delta > convergence_tolerance_;
        }
    };

    kmeans.run();
    for (int i = 0; i < kmeans.mu().length; ++i) {
        System.out.println("Mu " + i + ": " + kmeans.mu()[i]);
        for (int j = 0; j < kmeans.assignments().length; ++j) {
            if (kmeans.assignments()[j] == i) {
                System.out.println("\tPoint " + X.get(j));
            }
        }
    }

}