List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:goal.tools.Run.java
public static void main(String[] args) { try {// w w w . java 2 s. co m run(args); } catch (ParseException e) { System.out.println(e.getMessage()); showHelp(); } catch (Exception e) { // run throws generic Exceptions... System.out.println("Exception during execution: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.xtructure.xnet.demos.art.TwoNodeSimulation.java
/** * The main method.//from w ww . j a v a 2 s. c om * * @param args * the arguments */ public static void main(String[] args) { Options options = new Options(); options.addOption("n", "networkFile", true, // "the xml file from which the network is loaded"); options.addOption("i", "inputFile", true, // "the xml file from which the input is loaded"); options.addOption("test", false, "run integration test (non-gui, ignores networkFile and inputFile options)"); BasicParser bp = new BasicParser(); try { CommandLine cl = bp.parse(options, args); if (cl.hasOption("test")) { new TwoNodeSimulation(); } else { File networkFile = new File(RESOURCE_DIR, "default.network.xml"); File inputFile = new File(RESOURCE_DIR, "default.input.xml"); loadConfigFiles(RESOURCE_DIR, inputFile, networkFile); if (cl.hasOption("n")) { networkFile = new File(cl.getOptionValue("n")).getAbsoluteFile(); } if (cl.hasOption("i")) { inputFile = new File(cl.getOptionValue("i")).getAbsoluteFile(); } new TwoNodeSimulation(networkFile, inputFile); } } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter hf = new HelpFormatter(); hf.printHelp("Usage:", options); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
public static void main(String[] args) { Options options = new Options(); options.addOption(O_CERT, true, "file path of the certificate"); options.addOption(O_DUMP, false, "dump the certificate (print toString() value of the certificate)"); options.addOption(O_GET, true, "get a field in the certificate, valid fields:" + KnownCertField.names() + "|" + SubjectCertField.names()); options.addOption(O_HELP, false, "print usage"); options.addOption(O_PRINT, false, "print the certificate(print each parsed certificate fields)"); CommandLine cl = null;/*from www . j a v a 2s . c o m*/ try { CommandLineParser parser = new GnuParser(); cl = parser.parse(options, args); if (cl == null) { throw new ParseException(""); } } catch (ParseException e) { usage(options); e.printStackTrace(); System.exit(EXIT_CODE_BAD); } if (cl.hasOption(O_HELP)) { usage(options); System.exit(EXIT_CODE_GOOD); } String certFilePath = null; if (cl.hasOption(O_CERT)) { certFilePath = cl.getOptionValue(O_CERT); } else { usage(options, "missing cert path"); System.exit(EXIT_CODE_BAD); } try { CertUtil certUtil = new CertUtil(); certUtil.loadCert(certFilePath); if (cl.hasOption(O_DUMP)) { certUtil.dumpCert((String) null); } else if (cl.hasOption(O_PRINT)) { certUtil.printCert((String) null); } else if (cl.hasOption(O_GET)) { String field = cl.getOptionValue(O_GET); CertField certField = ClientCertPrincipalMap.parseCertField(field); String value = certUtil.getCertField(certField); System.out.println(field + ": " + value); } } catch (Exception e) { e.printStackTrace(); System.exit(EXIT_CODE_BAD); } }
From source file:edu.umass.cs.gnsserver.installer.EC2Runner.java
/** * The main routine.//from w ww . java 2s . co m * * @param args */ public static void main(String[] args) { try { CommandLine parser = initializeOptions(args); if (parser.hasOption("help")) { printUsage(); System.exit(1); } String createRunsetName = parser.getOptionValue("create"); String terminateRunsetName = parser.getOptionValue("terminate"); String runsetDescribe = parser.getOptionValue("describe"); String runSetWriteConfig = parser.getOptionValue("writeConfig"); String dataStoreName = parser.getOptionValue("datastore"); if (dataStoreName != null) { try { dataStoreType = DataStoreType.valueOf(dataStoreName); } catch (IllegalArgumentException e) { System.out.println("Unknown data store type " + dataStoreName + "; exiting."); System.exit(1); } } configName = createRunsetName != null ? createRunsetName : terminateRunsetName != null ? terminateRunsetName : runsetDescribe != null ? runsetDescribe : runSetWriteConfig != null ? runSetWriteConfig : null; System.out.println("Config name: " + configName); if (configName != null) { loadConfig(configName); } if (createRunsetName != null) { createRunSetMulti(createRunsetName); } else if (terminateRunsetName != null) { terminateRunSet(terminateRunsetName); } else if (runsetDescribe != null) { describeRunSet(runsetDescribe); } else if (runSetWriteConfig != null) { writeGNSINstallerConfForRunSet(runSetWriteConfig); } else { printUsage(); System.exit(1); } } catch (ParseException e1) { e1.printStackTrace(); printUsage(); System.exit(1); } System.exit(0); }
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event.//from www. j a v a 2 s. co m * * @param args */ @SuppressWarnings("static-access") public static void main(String[] args) { BasicConfigurator.configure(); log.debug("System initializing"); try { Logger.getRootLogger().addAppender( new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log")); } catch (IOException e1) { log.error("Unable to open the log file..?"); } /* * Initialize the configuration engine. */ XMLConfiguration config = new XMLConfiguration(); config.setListDelimiter('|'); /* * Initialize the Command-Line parsing engine. */ CommandLineParser parser = new PosixParser(); Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg() .withDescription("The configuration file to load").withArgName("config.xml").create("c")); opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use") .withArgName("Default").create("p")); opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with") .withArgName("password").create("P")); opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d')); opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v')); File configurationFile = new File("config.xml"); try { // Parse the command-line options CommandLine cmds = parser.parse(opts, args); if (!cmds.hasOption('p')) { Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR)); } Logger.getRootLogger().setLevel(Level.ERROR); if (cmds.hasOption('v')) { Logger.getRootLogger().setLevel(Level.INFO); } if (cmds.hasOption('d')) { Logger.getRootLogger().setLevel(Level.DEBUG); } log.debug("Enabling configuration file parsing"); // The user has given us a file to parse. if (cmds.hasOption("c")) { configurationFile = new File(cmds.getOptionValue("c")); } log.debug("Config file: " + configurationFile); // Load the configuration file if (configurationFile.exists()) { config.load(configurationFile); } else { log.error("Cannot find config file"); } /* * Convert the profiles into memory */ Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>(); List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile"); for (Object p : profList) { SubnodeConfiguration profile = (SubnodeConfiguration) p; String name = profile.getString("[@name]"); String auth = profile.getString("LdapAuthString"); String server = profile.getString("LdapServerString"); String group = profile.getString("LdapGroupsLocation"); ConnectionProfile prof = new ConnectionProfile(name, server, auth, group); profs.add(prof); } ConnectionProfile prof = null; if (!cmds.hasOption('p')) { /* * Deploy the profile selector, to select a profile */ ProfileSelector profSel = new ProfileSelector(profs); prof = profSel.getSelection(); if (prof == null) { return; } /* * Empty the profiles and load a clean copy - then save it back * to the file */ config.clearTree("Profiles"); for (ConnectionProfile p : profSel.getProfiles()) { config.addProperty("Profiles.Profile(-1)[@name]", p.getName()); config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString()); config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString()); config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString()); } config.save(configurationFile); } else { for (ConnectionProfile p : profs) { if (p.getName().equals(cmds.getOptionValue('p'))) { prof = p; break; } } } log.info("User selected " + prof); String password = ""; if (cmds.hasOption('P')) { password = cmds.getOptionValue('P'); } else { password = PasswordPrompter.promptForPassword("Password?"); } if (password.equals("")) { return; } LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(), prof.getLdapGroupsString(), password); /* * Gather options information from the configuration engine for the * specified report. */ Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>(); List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report"); for (Object p : repConfig) { SubnodeConfiguration repNode = (SubnodeConfiguration) p; // TODO Do something with the report profile. // Allowing the user to deploy "profiles" is a nice feature // String profile = repNode.getString("[@profile]"); String reportName = repNode.getString("[@report]"); Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>(); reportDataStructure.put(reportName, reportOptions); // Loop through the options and add each to the table. for (Object o : repNode.configurationsAt("option")) { SubnodeConfiguration option = (SubnodeConfiguration) o; String name = option.getString("[@name]"); String type = option.getString("[@type]"); String value = option.getString("[@value]"); ReportOption ro = new ReportOption(); ro.setName(name); if (type.toLowerCase().equals("boolean")) { ro.setBoolValue(Boolean.parseBoolean(value)); } else if (type.toLowerCase().equals("integer")) { ro.setIntValue(Integer.valueOf(value)); } else { // Assume a string type here then. ro.setStrValue(value); } reportOptions.put(name, ro); log.debug(ro); } } System.out.println(reportDataStructure); /* * At this point, we now need to deploy the reports window to have * the user pick a report and select some happy options to allow * that report to work. Let's go. */ /* * Deploy the Reports selector, to select a report */ Reports.getInstance().setLdapConnection(ldap); ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure); Report report = reports.getSelection(); if (report == null) { return; } /* * Empty the profiles and load a clean copy - then save it back to * the file */ config.clearTree("Reports"); for (Report r : Reports.getInstance().getAllReports()) { config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName()); config.addProperty("Reports.Report[@name]", "Standard"); for (ReportOption ro : r.getOptions().values()) { config.addProperty("Reports.Report.option(-1)[@name]", ro.getName()); config.addProperty("Reports.Report.option[@type]", ro.getType()); config.addProperty("Reports.Report.option[@value]", ro.getStrValue()); } } config.save(configurationFile); ProgressBar bar = new ProgressBar(); bar.start(); report.execute(); ASCIIFormatter format = new ASCIIFormatter(); ReportResult res = report.getResult(); format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt")); bar.stop(); JOptionPane.showMessageDialog(null, "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FAST Ldap Searcher", opts); } catch (ConfigurationException e) { e.printStackTrace(); log.fatal("OH EM GEES! Configuration errors."); } catch (Exception e) { e.printStackTrace(); } }
From source file:eu.skqs.bertie.standalone.BertieStandalone.java
public static void main(String[] args) { // Options/*from ww w.ja v a2s .c o m*/ Option file = OptionBuilder.withArgName("file").withLongOpt("file").hasArg() .withDescription("File to annotate").create("f"); Option directory = OptionBuilder.withArgName("directory").withLongOpt("directory").hasArg() .withDescription("Directory to annotate").create("d"); Option owl = OptionBuilder.withArgName("owl").withLongOpt("owl").hasArg() .withDescription("OWL file to use in annotation").create("o"); Option plain = OptionBuilder.withLongOpt("plain").withDescription("Plain text file format").create("p"); Option tei = OptionBuilder.withLongOpt("tei").withDescription("TEI file format").create("t"); Option mode = OptionBuilder.withArgName("extract|minimal|maximal|prosody").withLongOpt("mode").hasArg() .withDescription("Mode to operate in").create("m"); Option clean = OptionBuilder.withArgName("T0,T1,T3").withLongOpt("clean").hasArg() .withDescription("Remove gives types, MUST START UPPERCASE").create("c"); Options options = new Options(); options.addOption(file); options.addOption(directory); options.addOption(owl); options.addOption(plain); options.addOption(tei); options.addOption(mode); options.addOption(clean); CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmdline = null; try { cmdline = parser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); System.exit(-1); } BertieStandalone standalone = new BertieStandalone(); String documentPath = null; // Check for custom OWL if (cmdline.hasOption("owl")) { owlPath = cmdline.getOptionValue("owl"); } // Check for clean if (cmdline.hasOption("clean")) { typesToRemove = cmdline.getOptionValue("clean"); } // Check for mode if (cmdline.hasOption("mode")) { String currentMode = cmdline.getOptionValue("mode"); if (currentMode.equals("extract")) { extractMode = true; } else if (currentMode.equals("poetry")) { poetryMode = true; } analysisMode = currentMode; } // Check for directory option if (cmdline.hasOption("directory")) { // We support TEI directorys only if (!cmdline.hasOption("tei")) { logger.log(Level.WARNING, "TEI file format must be selected with directory argument"); System.exit(-1); } String directoryPath = cmdline.getOptionValue("directory"); if (extractMode) { try { standalone.extractWithCollectionReader(directoryPath); } catch (Exception e) { } System.exit(0); } try { standalone.processWithCollectionReader(directoryPath); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } // Check for file option if (cmdline.hasOption("file")) { // TODO: clean this up documentPath = cmdline.getOptionValue("file"); filePath = cmdline.getOptionValue("file"); // TEI if (cmdline.hasOption("tei")) { try { processWithFile(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } // Check for plain option if (!cmdline.hasOption("plain")) { logger.log(Level.WARNING, "Plain text format must be selected with file argument"); System.exit(-1); } } else { logger.log(Level.WARNING, "No file argument given. Quitting."); formatter.printHelp("bertie", options); System.exit(-1); } // Make sure we have a document path if (documentPath == null) { logger.log(Level.WARNING, "Document path is empty. Quitting."); System.exit(-1); } // Read the document try { String encodingType = "UTF-8"; BufferedReader fileReader = new BufferedReader( new InputStreamReader(new FileInputStream(documentPath), encodingType)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = fileReader.readLine()) != null) { sb.append(line + newLine); } String input = sb.toString(); fileReader.close(); String output = standalone.process(input); if (output == null) { logger.log(Level.WARNING, "Empty processing result."); System.exit(-1); } PrintWriter fileWriter = new PrintWriter(documentPath, encodingType); fileWriter.write(output); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:discovery.compression.kdd2011.ratio.RatioCompressionReport.java
public static void main(String[] args) throws GraphReadingException, IOException, java.text.ParseException { opts.addOption("r", true, "Goal compression ratio"); // opts.addOption( "a", // true, // "Algorithm used for compression. The default and only currently available option is \"greedy\""); //opts.addOption("cost-output",true,"Output file for costs, default is costs.txt"); //opts.addOption("cost-format",true,"Output format for "); opts.addOption("ctype", true, "Connectivity type: global or local, default is global."); opts.addOption("connectivity", false, "enables output for connectivity. Connectivity info will be written to connectivity.txt"); opts.addOption("output_bmg", true, "Write bmg file with groups to given file."); opts.addOption("algorithm", true, "Algorithm to use, one of: greedy random1 random2 bruteforce slowgreedy"); opts.addOption("hop2", false, "Only try to merge nodes that have common neighbors"); opts.addOption("kmedoids", false, "Enables output for kmedoids clustering"); opts.addOption("kmedoids_k", true, "Number of clusters to be used in kmedoids. Default is 3"); opts.addOption("kmedoids_output", true, "Output file for kmedoid clusters. Default is clusters.txt. This file will be overwritten."); opts.addOption("norefresh", false, "Use old style merging: all connectivities are not refreshed when merging"); opts.addOption("edge_attribute", true, "Attribute from bmgraph used as edge weight"); opts.addOption("only_times", false, "Only write times.txt"); //opts.addOption("no_metrics",false,"Exit after compression, don't calculate any metrics or produce output bmg for the compression."); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;// w ww .j a va2 s . c o m try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } boolean connectivity = false; double ratio = 0; boolean hop2 = cmd.hasOption("hop2"); RatioCompression compression = new GreedyRatioCompression(hop2); if (cmd.hasOption("connectivity")) connectivity = true; ConnectivityType ctype = ConnectivityType.GLOBAL; CompressionMergeModel mergeModel = new PathAverageMergeModel(); if (cmd.hasOption("ctype")) { String ctypeStr = cmd.getOptionValue("ctype"); if (ctypeStr.equals("local")) { ctype = ConnectivityType.LOCAL; mergeModel = new EdgeAverageMergeModel(); } else if (ctypeStr.equals("global")) { ctype = ConnectivityType.GLOBAL; mergeModel = new PathAverageMergeModel(); } else { System.out.println(PROGRAM_NAME + ": unknown connectivity type " + ctypeStr); printHelp(); } } if (cmd.hasOption("norefresh")) mergeModel = new PathAverageMergeModelNorefresh(); if (cmd.hasOption("algorithm")) { String alg = cmd.getOptionValue("algorithm"); if (alg.equals("greedy")) { compression = new GreedyRatioCompression(hop2); } else if (alg.equals("random1")) { compression = new RandomRatioCompression(hop2); } else if (alg.equals("random2")) { compression = new SmartRandomRatioCompression(hop2); } else if (alg.equals("bruteforce")) { compression = new BruteForceCompression(hop2, ctype == ConnectivityType.LOCAL); } else if (alg.equals("slowgreedy")) { compression = new SlowGreedyRatioCompression(hop2); } else { System.out.println("algorithm must be one of: greedy random1 random2 bruteforce slowgreedy"); printHelp(); } } compression.setMergeModel(mergeModel); if (cmd.hasOption("r")) { ratio = Double.parseDouble(cmd.getOptionValue("r")); } else { System.out.println(PROGRAM_NAME + ": compression ratio not defined"); printHelp(); } if (cmd.hasOption("help")) { printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } boolean kmedoids = false; int kmedoidsK = 3; String kmedoidsOutput = "clusters.txt"; if (cmd.hasOption("kmedoids")) kmedoids = true; if (cmd.hasOption("kmedoids_k")) kmedoidsK = Integer.parseInt(cmd.getOptionValue("kmedoids_k")); if (cmd.hasOption("kmedoids_output")) kmedoidsOutput = cmd.getOptionValue("kmedoids_output"); String edgeAttrib = "goodness"; if (cmd.hasOption("edge_attribute")) edgeAttrib = cmd.getOptionValue("edge_attribute"); // This program should directly use bmgraph-java to read and // DefaultGraph should have a constructor that takes a BMGraph as an // argument. //VisualGraph vg = new VisualGraph(infile, edgeAttrib, false); //System.out.println("vg read"); //SimpleVisualGraph origSG = new SimpleVisualGraph(vg); BMGraph bmg = BMGraphUtils.readBMGraph(infile); int origN = bmg.getNodes().size(); //for(int i=0;i<origN;i++) //System.out.println(i+"="+origSG.getVisualNode(i)); System.out.println("bmgraph read"); BMNode[] i2n = new BMNode[origN]; HashMap<BMNode, Integer> n2i = new HashMap<BMNode, Integer>(); { int pi = 0; for (BMNode nod : bmg.getNodes()) { n2i.put(nod, pi); i2n[pi++] = nod; } } DefaultGraph dg = new DefaultGraph(); for (BMEdge e : bmg.getEdges()) { dg.addEdge(n2i.get(e.getSource()), n2i.get(e.getTarget()), Double.parseDouble(e.get(edgeAttrib))); } DefaultGraph origDG = dg.copy(); System.out.println("inputs read"); RatioCompression nopCompressor = new RatioCompression.DefaultRatioCompression(); ResultGraph nopResult = nopCompressor.compressGraph(dg, 1); long start = System.currentTimeMillis(); ResultGraph result = compression.compressGraph(dg, ratio); long timeSpent = System.currentTimeMillis() - start; double seconds = timeSpent * 0.001; BufferedWriter timesWriter = new BufferedWriter(new FileWriter("times.txt", true)); timesWriter.append("" + seconds + "\n"); timesWriter.close(); if (cmd.hasOption("only_times")) { System.out.println("Compression done, exiting."); System.exit(0); } BufferedWriter costsWriter = new BufferedWriter(new FileWriter("costs.txt", true)); costsWriter.append("" + nopResult.getCompressorCosts() + " " + result.getCompressorCosts() + "\n"); costsWriter.close(); double[][] origProb; double[][] compProb; int[] group = new int[origN]; for (int i = 0; i < result.partition.size(); i++) for (int x : result.partition.get(i)) group[x] = i; if (ctype == ConnectivityType.LOCAL) { origProb = new double[origN][origN]; compProb = new double[origN][origN]; DefaultGraph g = result.uncompressedGraph(); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { origProb[i][j] = dg.getEdgeWeight(i, j); compProb[i][j] = g.getEdgeWeight(i, j); } } System.out.println("Writing edge-dissimilarity"); } else { origProb = ProbDijkstra.getProbMatrix(origDG); compProb = new double[origN][origN]; System.out.println("nodeCount = " + result.graph.getNodeCount()); double[][] ccProb = ProbDijkstra.getProbMatrix(result.graph); System.out.println("ccProb.length = " + ccProb.length); System.out.println("ccProb[0].length = " + ccProb[0].length); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { if (group[i] == group[j]) compProb[i][j] = result.graph.getEdgeWeight(group[i], group[j]); else { int gj = group[j]; int gi = group[i]; compProb[i][j] = ccProb[group[i]][group[j]]; } } } System.out.println("Writing best-path-dissimilarity"); //compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } { BufferedWriter connWr = null;// if (connectivity) { connWr = new BufferedWriter(new FileWriter("connectivity.txt", true)); } double totalDiff = 0; for (int i = 0; i < origN; i++) { for (int j = i + 1; j < origN; j++) { double diff = Math.abs(origProb[i][j] - compProb[i][j]); //VisualNode ni = origSG.getVisualNode(i); //VisualNode nj = origSG.getVisualNode(j); BMNode ni = i2n[i]; BMNode nj = i2n[j]; if (connectivity) connWr.append(ni + "\t" + nj + "\t" + origProb[i][j] + "\t" + compProb[i][j] + "\t" + diff + "\n"); totalDiff += diff * diff; } } if (connectivity) { connWr.append("\n"); connWr.close(); } totalDiff = Math.sqrt(totalDiff); BufferedWriter dissWr = new BufferedWriter(new FileWriter("dissimilarity.txt", true)); dissWr.append("" + totalDiff + "\n"); dissWr.close(); } if (cmd.hasOption("output_bmg")) { BMGraph outgraph = new BMGraph(); String outputfile = cmd.getOptionValue("output_bmg"); HashMap<Integer, BMNode> nodes = new HashMap<Integer, BMNode>(); for (int i = 0; i < result.partition.size(); i++) { ArrayList<Integer> g = result.partition.get(i); if (g.size() == 0) continue; BMNode node = new BMNode("Supernode_" + i); HashMap<String, String> attributes = new HashMap<String, String>(); StringBuffer contents = new StringBuffer(); for (int x : g) contents.append(i2n[x] + ","); contents.delete(contents.length() - 1, contents.length()); attributes.put("nodes", contents.toString()); attributes.put("self-edge", "" + result.graph.getEdgeWeight(i, i)); node.setAttributes(attributes); nodes.put(i, node); outgraph.ensureHasNode(node); } for (int i = 0; i < result.partition.size(); i++) { if (result.partition.get(i).size() == 0) continue; for (int x : result.graph.getNeighbors(i)) { if (x < i) continue; BMNode from = nodes.get(i); BMNode to = nodes.get(x); if (from == null || to == null) { System.out.println(from + "->" + to); System.out.println(i + "->" + x); System.out.println(""); } BMEdge e = new BMEdge(nodes.get(i), nodes.get(x), "notype"); e.setAttributes(new HashMap<String, String>()); e.put("goodness", "" + result.graph.getEdgeWeight(i, x)); outgraph.ensureHasEdge(e); } } BMGraphUtils.writeBMGraph(outgraph, outputfile); } // k medoids! if (kmedoids) { //KMedoidsResult clustersOrig=KMedoids.runKMedoids(origProb,kmedoidsK); if (ctype == ConnectivityType.LOCAL) { compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } //KMedoidsResult compClusters = KMedoids.runKMedoids(ProbDijkstra.getProbMatrix(result.graph),kmedoidsK); KMedoidsResult clustersComp = KMedoids.runKMedoids(compProb, kmedoidsK); BufferedWriter bw = new BufferedWriter(new FileWriter(kmedoidsOutput)); for (int i = 0; i < origN; i++) { int g = group[i]; //bw.append(origSG.getVisualNode(i).getBMNode()+" "+compClusters.clusters[g]+"\n"); bw.append(i2n[i] + " " + clustersComp.clusters[i] + "\n"); } bw.close(); } System.exit(0); }
From source file:com.yhfudev.SimulatorForSelfStabilizing.java
public static void main(String[] args) { // command line lib: apache CLI http://commons.apache.org/proper/commons-cli/ // command line arguments: // -- input file // -- output line to a csv file // -- algorithm: Ding's linear or randomized // single thread parsing ... Options options = new Options(); options.addOption("h", false, "print this message"); //heuristic/*from w w w .j a va 2 s . c o m*/ options.addOption("u", false, "(rand) heuristic on"); options.addOption("y", true, "show the graph with specified delay (ms)"); options.addOption("i", true, "the input file name"); options.addOption("o", true, "the results is save to a attachable output cvs file"); options.addOption("l", true, "the graph activities trace log file name"); options.addOption("s", true, "save the graph to a file"); options.addOption("a", true, "the algorithm name, ding or rand"); // options specified to generator options.addOption("g", true, "the graph generator algorithm name: fan1l, fan2l, rand, doro, flower, watt, lobster"); options.addOption("n", true, "the number of nodes"); options.addOption("d", true, "(rand) the node degree (max)"); options.addOption("f", false, "(rand) if the degree value is fix or not"); options.addOption("p", true, "(watt) the probability of beta"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); return; } if (cmd.hasOption("h")) { showHelp(options); return; } int delay_time = 0; if (cmd.hasOption("y")) { delay_time = Integer.parseInt(cmd.getOptionValue("y")); } String sFileName = null; sFileName = null; FileWriter writer = null; if (cmd.hasOption("o")) { sFileName = cmd.getOptionValue("o"); } if ((null != sFileName) && (!"".equals(sFileName))) { try { writer = new FileWriter(sFileName, true); // true: append } catch (IOException e) { e.printStackTrace(); System.out.println("Error: unable to open the output file " + sFileName); return; } } FileWriter wrGraph = null; sFileName = null; if (cmd.hasOption("s")) { sFileName = cmd.getOptionValue("s"); } if ((null != sFileName) && (!"".equals(sFileName))) { try { wrGraph = new FileWriter(sFileName, true); // true: append } catch (IOException e) { e.printStackTrace(); System.out.println("Error: unable to open the saveGraph file " + sFileName); return; } } sFileName = null; if (cmd.hasOption("i")) { sFileName = cmd.getOptionValue("i"); } String genname = null; if (cmd.hasOption("g")) { genname = cmd.getOptionValue("g"); } if ((null == genname) && (null == sFileName)) { System.out.println("Error: not specify the input file or graph generator"); showHelp(options); return; } if ((null != genname) && (null != sFileName)) { System.out.println("Error: do not specify the input file and graph generator at the same time"); showHelp(options); return; } if (delay_time > 0) { // create and display a graph System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer"); } Graph graph = new SingleGraph("test"); //graph.setNullAttributesAreErrors(true); // to throw an exception instead of returning null (in getAttribute()). if (delay_time > 0) { graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); graph.addAttribute("ui.stylesheet", "url(data/selfstab-mwcds.css);"); graph.display(); } // save the trace to file FileSinkDGS dgs = null; if (cmd.hasOption("l")) { dgs = new FileSinkDGS(); graph.addSink(dgs); try { dgs.begin(cmd.getOptionValue("l")); } catch (IOException e) { e.printStackTrace(); } } Generator generator = null; if (null != sFileName) { System.out.println("DEBUG: the input file=" + sFileName); FileSource source = new FileSourceDGS(); source.addSink(graph); int count_edge_error = 0; try { //source.begin("data/selfstab-mwcds.dgs"); // Ding's paper example //source.begin("data/selfstab-ds.dgs"); // DS example //source.begin("data/selfstab-doro-1002.dgs"); // DorogovtsevMendes //source.begin("data/selfstab-rand-p10-10002.dgs"); // random connected graph with degree = 10% nodes //source.begin("data/selfstab-rand-f5-34.dgs"); // random connected graph with degree = 5 source.begin(sFileName); while (true) { try { if (false == source.nextEvents()) { break; } } catch (EdgeRejectedException e) { // ignore count_edge_error++; System.out.println("DEBUG: adding edge error: " + e.toString()); } if (delay_time > 0) { delay(delay_time); } } source.end(); //} catch (InterruptedException e) { // e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("DEBUG: END read from source. # of edges ignored=" + count_edge_error); } else { // assert (genname != null); // graph generator //generator = new ChvatalGenerator(); // fix size //generator = new FullGenerator(); // full connected, 2 steps,1 node in dominate set //generator = new GridGenerator(); // only one result //generator = new HypercubeGenerator(); // one result //generator = new IncompleteGridGenerator(); // error //generator = new PetersenGraphGenerator(); // fix size //generator = new PointsOfInterestGenerator(); // error //generator = new RandomEuclideanGenerator(); // linear algo endless loop //generator = new RandomFixedDegreeDynamicGraphGenerator(); // //generator = new RandomGenerator(); // //generator = new URLGenerator("http://www.cnbeta.com"); // //generator = new WikipediaGenerator("Antarctica"); // no end //generator = new DorogovtsevMendesGenerator(); // ok //generator = new FlowerSnarkGenerator(); // ok //generator = new WattsStrogatzGenerator(maxSteps, 30, 0.5); // small world, ok //generator = new LobsterGenerator(); // tree like, ok int i; int n = 12; // the number of nodes if (cmd.hasOption("n")) { n = Integer.parseInt(cmd.getOptionValue("n")); } int d = 3; // the degree of nodes if (cmd.hasOption("d")) { d = Integer.parseInt(cmd.getOptionValue("d")); } boolean isFix = false; if (cmd.hasOption("f")) { isFix = true; } if ("".equals(genname)) { System.out.println("Error: not set generator name"); return; } else if ("fan1l".equals(genname)) { generator = new FanGenerator(); } else if ("fan2l".equals(genname)) { generator = new Fan2lGenerator(graph, d); } else if ("doro".equals(genname)) { generator = new DorogovtsevMendesGenerator(); } else if ("flower".equals(genname)) { generator = new FlowerSnarkGenerator(); } else if ("lobster".equals(genname)) { generator = new LobsterGenerator(); } else if ("rand".equals(genname)) { generator = new ConnectionGenerator(graph, d, false, isFix); } else if ("watt".equals(genname)) { // WattsStrogatzGenerator(n,k,beta) // a ring of n nodes // each node is connected to its k nearest neighbours, k must be even // n >> k >> log(n) >> 1 // beta being a probability it must be between 0 and 1. int k; double beta = 0.5; if (cmd.hasOption("p")) { beta = Double.parseDouble(cmd.getOptionValue("p")); } k = (n / 20) * 2; if (k < 2) { k = 2; } if (n < 2 * 6) { n = 2 * 6; } generator = new WattsStrogatzGenerator(n, k, beta); } /*int listf5[][] = { {12, 5}, {34, 5}, {102, 5}, {318, 5}, {1002, 5}, {3164, 5}, {10002, 5}, }; int listp3[][] = { {12, 2}, {34, 2}, {102, 3}, {318, 9}, {1002, 30}, {3164, 90}, {10002, 300}, }; int listp10[][] = { {12, 2}, {34, 3}, {102, 10}, {318, 32}, {1002, 100}, {3164, 316}, {10002, 1000}, }; i = 6; maxSteps = listf5[i][0]; int degree = listf5[i][1]; generator = new ConnectionGenerator(graph, degree, false, true); */ generator.addSink(graph); generator.begin(); for (i = 1; i < n; i++) { generator.nextEvents(); } generator.end(); delay(500); } if (cmd.hasOption("a")) { SinkAlgorithm algorithm = null; String algo = "rand"; algo = cmd.getOptionValue("a"); if ("ding".equals(algo)) { algorithm = new SelfStabilizingMWCDSLinear(); } else if ("ds".equals(algo)) { algorithm = new SelfStabilizingDSLinear(); } else { algorithm = new SelfStabilizingMWCDSRandom(); } algorithm.init(graph); algorithm.setSource("0"); if (delay_time > 0) { algorithm.setAnimationDelay(delay_time); } if (cmd.hasOption("u")) { algorithm.heuristicOn(true); } else { algorithm.heuristicOn(false); } algorithm.compute(); GraphVerificator verificator = new MWCDSGraphVerificator(); if (verificator.verify(graph)) { System.out.println("DEBUG: PASS MWCDSGraphVerificator verficiation."); } else { System.out.println("DEBUG: FAILED MWCDSGraphVerificator verficiation!"); } if (null != writer) { AlgorithmResult result = algorithm.getResult(); result.SaveTo(writer); try { writer.flush(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } algorithm.terminate(); } if (null != generator) { generator.removeSink(graph); } if (dgs != null) { graph.removeSink(dgs); try { dgs.end(); } catch (IOException e) { e.printStackTrace(); } } if (null != wrGraph) { try { saveGraph(graph, wrGraph); wrGraph.flush(); wrGraph.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:biomine.nodeimportancecompression.ImportanceCompressionReport.java
public static void main(String[] args) throws IOException, java.text.ParseException { opts.addOption("algorithm", true, "Used algorithm for compression. Possible values are 'brute-force', " + "'brute-force-edges','brute-force-merges','randomized','randomized-merges'," + "'randomized-edges'," + "'fast-brute-force'," + "'fast-brute-force-merges','fast-brute-force-merge-edges'. Default is 'brute-force'."); opts.addOption("query", true, "Query nodes ids, separated by comma."); opts.addOption("queryfile", true, "Read query nodes from file."); opts.addOption("ratio", true, "Goal ratio"); opts.addOption("importancefile", true, "Read importances straight from file"); opts.addOption("keepedges", false, "Don't remove edges during merges"); opts.addOption("connectivity", false, "Compute and output connectivities in edge oriented case"); opts.addOption("paths", false, "Do path oriented compression"); opts.addOption("edges", false, "Do edge oriented compression"); // opts.addOption( "a", double sigma = 1.0; CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*from w w w. ja v a 2s . c om*/ try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } String queryStr = cmd.getOptionValue("query"); String[] queryNodeIDs = {}; double[] queryNodeIMP = {}; if (queryStr != null) { queryNodeIDs = queryStr.split(","); queryNodeIMP = new double[queryNodeIDs.length]; for (int i = 0; i < queryNodeIDs.length; i++) { String s = queryNodeIDs[i]; String[] es = s.split("="); queryNodeIMP[i] = 1; if (es.length == 2) { queryNodeIDs[i] = es[0]; queryNodeIMP[i] = Double.parseDouble(es[1]); } else if (es.length > 2) { System.out.println("Too many '=' in querynode specification: " + s); } } } String queryFile = cmd.getOptionValue("queryfile"); Map<String, Double> queryNodes = Collections.EMPTY_MAP; if (queryFile != null) { File in = new File(queryFile); BufferedReader read = new BufferedReader(new FileReader(in)); queryNodes = readMap(read); read.close(); } String impfile = cmd.getOptionValue("importancefile"); Map<String, Double> importances = null; if (impfile != null) { File in = new File(impfile); BufferedReader read = new BufferedReader(new FileReader(in)); importances = readMap(read); read.close(); } String algoStr = cmd.getOptionValue("algorithm"); CompressionAlgorithm algo = null; if (algoStr == null || algoStr.equals("brute-force")) { algo = new BruteForceCompression(); } else if (algoStr.equals("brute-force-edges")) { algo = new BruteForceCompressionOnlyEdges(); } else if (algoStr.equals("brute-force-merges")) { algo = new BruteForceCompressionOnlyMerges(); } else if (algoStr.equals("fast-brute-force-merges")) { //algo = new FastBruteForceCompressionOnlyMerges(); algo = new FastBruteForceCompression(true, false); } else if (algoStr.equals("fast-brute-force-edges")) { algo = new FastBruteForceCompression(false, true); //algo = new FastBruteForceCompressionOnlyEdges(); } else if (algoStr.equals("fast-brute-force")) { algo = new FastBruteForceCompression(true, true); } else if (algoStr.equals("randomized-edges")) { algo = new RandomizedCompressionOnlyEdges(); //modified } else if (algoStr.equals("randomized")) { algo = new RandomizedCompression(); } else if (algoStr.equals("randomized-merges")) { algo = new RandomizedCompressionOnlyMerges(); } else { System.out.println("Unsupported algorithm: " + algoStr); printHelp(); } String ratioStr = cmd.getOptionValue("ratio"); double ratio = 0; if (ratioStr != null) { ratio = Double.parseDouble(ratioStr); } else { System.out.println("Goal ratio not specified"); printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } BMGraph bmg = BMGraphUtils.readBMGraph(new File(infile)); HashMap<BMNode, Double> queryBMNodes = new HashMap<BMNode, Double>(); for (String id : queryNodes.keySet()) { queryBMNodes.put(bmg.getNode(id), queryNodes.get(id)); } long startMillis = System.currentTimeMillis(); ImportanceGraphWrapper wrap = QueryImportance.queryImportanceGraph(bmg, queryBMNodes); if (importances != null) { for (String id : importances.keySet()) { wrap.setImportance(bmg.getNode(id), importances.get(id)); } } ImportanceMerger merger = null; if (cmd.hasOption("edges")) { merger = new ImportanceMergerEdges(wrap.getImportanceGraph()); } else if (cmd.hasOption("paths")) { merger = new ImportanceMergerPaths(wrap.getImportanceGraph()); } else { System.out.println("Specify either 'paths' or 'edges'."); System.exit(1); } if (cmd.hasOption("keepedges")) { merger.setKeepEdges(true); } algo.compress(merger, ratio); long endMillis = System.currentTimeMillis(); // write importance { BufferedWriter wr = new BufferedWriter(new FileWriter("importance.txt", false)); for (BMNode nod : bmg.getNodes()) { wr.write(nod + " " + wrap.getImportance(nod) + "\n"); } wr.close(); } // write sum of all pairs of node importance added by Fang /* { BufferedWriter wr = new BufferedWriter(new FileWriter("sum_of_all_pairs_importance.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); double sum = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { for (int j = i+1; j <= orig.getMaxNodeId(); j++) { sum = sum+ wrap.getImportance(i)* wrap.getImportance(j); } } wr.write(""+sum); wr.write("\n"); wr.close(); } */ // write uncompressed edges { BufferedWriter wr = new BufferedWriter(new FileWriter("edges.txt", false)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); for (int i = 0; i <= orig.getMaxNodeId(); i++) { String iname = wrap.intToNode(i).toString(); HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i < j) continue; String jname = wrap.intToNode(j).toString(); double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); wr.write(iname + " " + jname + " " + a + " " + b + " " + Math.abs(a - b)); wr.write("\n"); } } wr.close(); } // write distance { // BufferedWriter wr = new BufferedWriter(new // FileWriter("distance.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("distance.txt", true)); //modified by Fang ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double error = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i <= j) continue; double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); error += (a - b) * (a - b) * wrap.getImportance(i) * wrap.getImportance(j); // modify by Fang: multiply imp(u)imp(v) } } error = Math.sqrt(error); //////////error = Math.sqrt(error / 2); // modified by Fang: the error of each // edge is counted twice wr.write("" + error); wr.write("\n"); wr.close(); } // write sizes { ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph comp = merger.getCurrentGraph(); // BufferedWriter wr = new BufferedWriter(new // FileWriter("sizes.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("sizes.txt", true)); //modified by Fang wr.write(orig.getNodeCount() + " " + orig.getEdgeCount() + " " + comp.getNodeCount() + " " + comp.getEdgeCount()); wr.write("\n"); wr.close(); } //write time { System.out.println("writing time"); BufferedWriter wr = new BufferedWriter(new FileWriter("time.txt", true)); //modified by Fang double secs = (endMillis - startMillis) * 0.001; wr.write("" + secs + "\n"); wr.close(); } //write change of connectivity for edge-oriented case // added by Fang { if (cmd.hasOption("connectivity")) { BufferedWriter wr = new BufferedWriter(new FileWriter("connectivity.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double diff = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { ProbDijkstra pdori = new ProbDijkstra(orig, i); ProbDijkstra pducom = new ProbDijkstra(ucom, i); for (int j = i + 1; j <= orig.getMaxNodeId(); j++) { double oriconn = pdori.getProbTo(j); double ucomconn = pducom.getProbTo(j); diff = diff + (oriconn - ucomconn) * (oriconn - ucomconn) * wrap.getImportance(i) * wrap.getImportance(j); } } diff = Math.sqrt(diff); wr.write("" + diff); wr.write("\n"); wr.close(); } } //write output graph { BMGraph output = bmg;//new BMGraph(bmg); int no = 0; BMNode[] nodes = new BMNode[merger.getGroups().size()]; for (ArrayList<Integer> gr : merger.getGroups()) { BMNode bmgroup = new BMNode("Group", "" + (no + 1)); bmgroup.setAttributes(new HashMap<String, String>()); bmgroup.put("autoedges", "0"); nodes[no] = bmgroup; no++; if (gr.size() == 0) continue; for (int x : gr) { BMNode nod = output.getNode(wrap.intToNode(x).toString()); BMEdge belongs = new BMEdge(nod, bmgroup, "belongs_to"); output.ensureHasEdge(belongs); } output.ensureHasNode(bmgroup); } for (int i = 0; i < nodes.length; i++) { for (int x : merger.getCurrentGraph().getNeighbors(i)) { if (x == i) { nodes[x].put("selfedge", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); //ge.put("goodness", ""+merger.getCurrentGraph().getEdgeWeight(i, x)); continue; } BMEdge ge = new BMEdge(nodes[x], nodes[i], "groupedge"); ge.setAttributes(new HashMap<String, String>()); ge.put("goodness", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); output.ensureHasEdge(ge); } } System.out.println(output.getGroupNodes()); BMGraphUtils.writeBMGraph(output, "output.bmg"); } }
From source file:com.hortonworks.atlas.cli.AtlasCLI.java
/** * //from ww w.j a va2s .co m * @param args */ public static void main(String[] args) { try { @SuppressWarnings("unused") AtlasCLI cli = new AtlasCLI(args); } catch (ParseException e) { e.printStackTrace(); } }