List of usage examples for java.util List size
int size();
From source file:gov.nasa.jpl.mudrod.ontology.process.LocalOntology.java
public static void main(String[] args) throws Exception { // boolean options Option helpOpt = new Option("h", "help", false, "show this help message"); // argument options Option ontDirOpt = OptionBuilder.hasArg(true).withArgName(ONT_DIR) .withDescription("A directory containing .owl files.").isRequired(false).create(); // create the options Options options = new Options(); options.addOption(helpOpt);//from w w w . jav a2 s . co m options.addOption(ontDirOpt); String ontDir; CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(ONT_DIR)) { ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/"); } else { ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile(); } if (!ontDir.endsWith("/")) { ontDir += "/"; } } catch (Exception e) { LOG.error("Error whilst processing main method of LocalOntology.", e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true); return; } File fileDir = new File(ontDir); //Fail if the input is not a directory. if (fileDir.isDirectory()) { List<String> owlFiles = new ArrayList<>(); for (File owlFile : fileDir.listFiles()) { owlFiles.add(owlFile.toString()); } MudrodEngine mEngine = new MudrodEngine(); Properties props = mEngine.loadConfig(); Ontology ontology = new OntologyFactory(props).getOntology(); //convert to correct iput for ontology loading. String[] owlArray = new String[owlFiles.size()]; owlArray = owlFiles.toArray(owlArray); ontology.load(owlArray); String[] terms = new String[] { "Glacier ice" }; //Demonstrate that we can do basic ontology heirarchy navigation and log output. for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) { //print Ontology Class Hierarchy OntClass c = i.next(); renderHierarchy(System.out, c, new LinkedList<>(), 0); for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) { OntClass sub = subClass.next(); //This means that the search term is present as an OntClass if (terms[0].equalsIgnoreCase(sub.getLabel(null))) { //Add the search term(s) above to the term cache. for (int j = 0; j < terms.length; j++) { addSearchTerm(terms[j], sub); } //Query the ontology and return subclasses of the search term(s) for (int k = 0; k < terms.length; k++) { Iterator<String> iter = ontology.subclasses(terms[k]); while (iter.hasNext()) { LOG.info("Subclasses >> " + iter.next()); } } //print any synonymic relationships to demonstrate that we can //undertake synonym-based query expansion for (int l = 0; l < terms.length; l++) { Iterator<String> iter = ontology.synonyms(terms[l]); while (iter.hasNext()) { LOG.info("Synonym >> " + iter.next()); } } } } } mEngine.end(); } }
From source file:com.act.lcms.db.analysis.IonDetectionAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww .j a v a 2 s . co m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_LCMS_FILE_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR); // Get include and excluse ions from command line Set<String> includeIons; if (cl.hasOption(OPTION_INCLUDE_IONS)) { includeIons = new HashSet<>(Arrays.asList(cl.getOptionValues(OPTION_INCLUDE_IONS))); LOGGER.info("Including ions in search: %s", StringUtils.join(includeIons, ", ")); } else { includeIons = new HashSet<>(); includeIons.add(DEFAULT_ION); } try (DB db = DB.openDBFromCLI(cl)) { ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); File inputPredictionCorpus = new File(cl.getOptionValue(OPTION_INPUT_PREDICTION_CORPUS)); Map<Double, Set<Pair<String, String>>> massChargeToChemicalAndIon = constructMassChargeToChemicalIonsFromInputFile( inputPredictionCorpus, includeIons, cl.hasOption(OPTION_LIST_OF_INCHIS_INPUT_FILE)); Pair<Set<Pair<String, Double>>, Map<String, Double>> values = constructFakeNameToMassChargeAndSetOfMassChargePairs( massChargeToChemicalAndIon.keySet()); Set<Pair<String, Double>> searchMZs = values.getLeft(); Map<String, Double> chemIDToMassCharge = values.getRight(); LOGGER.info("The number of mass charges are: %d", searchMZs.size()); Map<ScanData.KIND, List<LCMSWell>> wellTypeToLCMSWells = readInputExperimentalSetup(db, new File(cl.getOptionValue(OPTION_INPUT_POSITIVE_AND_NEGATIVE_CONTROL_WELLS_FILE))); // Get experimental setup ie. positive and negative wells from config file List<LCMSWell> positiveWells = wellTypeToLCMSWells.get(ScanData.KIND.POS_SAMPLE); List<LCMSWell> negativeWells = wellTypeToLCMSWells.get(ScanData.KIND.NEG_CONTROL); LOGGER.info("Number of positive wells is: %d", positiveWells.size()); LOGGER.info("Number of negative wells is: %d", negativeWells.size()); HashMap<Integer, Plate> plateCache = new HashMap<>(); String outputPrefix = cl.getOptionValue(OPTION_OUTPUT_PREFIX); IonDetectionAnalysis<LCMSWell> ionDetectionAnalysis = new IonDetectionAnalysis<LCMSWell>(lcmsDir, positiveWells, negativeWells, plottingDirectory, plateCache, searchMZs, db); ionDetectionAnalysis.runLCMSMiningAnalysisAndPlotResults(chemIDToMassCharge, massChargeToChemicalAndIon, outputPrefix, cl.hasOption(OPTION_NON_REPLICATE_ANALYSIS)); } }
From source file:com.microsoft.gittf.client.clc.Main.java
public static void main(String[] args) { // Configure logging, use the standard TFS SDK logging. System.setProperty("teamexplorer.application", ProductInformation.getProductName()); //$NON-NLS-1$ LoggingConfiguration.configure();/*from w w w . ja v a2s. com*/ final Log log = LogFactory.getLog(ProductInformation.getProductName()); try { ArgumentCollection mainArguments = new ArgumentCollection(); try { mainArguments = ArgumentParser.parse(args, ARGUMENTS, ArgumentParserOptions.ALLOW_UNKNOWN_ARGUMENTS); } catch (ArgumentParserException e) { console.getErrorStream().println(e.getLocalizedMessage()); console.getErrorStream().println(getUsage()); System.exit(ExitCode.FAILURE); } if (mainArguments.contains("version")) //$NON-NLS-1$ { console.getOutputStream().println(Messages.formatString("Main.ApplicationVersionFormat", //$NON-NLS-1$ ProductInformation.getProductName(), ProductInformation.getBuildNumber())); return; } /* * Special case "--help command" handling - convert to * "help command" */ if (mainArguments.contains("help") && mainArguments.contains("command")) //$NON-NLS-1$ //$NON-NLS-2$ { HelpCommand helpCommand = new HelpCommand(); helpCommand.setArguments(ArgumentParser.parse(new String[] { ((FreeArgumentCollection) mainArguments.getArgument("command")).getValues()[0] //$NON-NLS-1$ }, helpCommand.getPossibleArguments())); helpCommand.setConsole(console); helpCommand.run(); return; } else if (mainArguments.contains("help") || !mainArguments.contains("command")) //$NON-NLS-1$ //$NON-NLS-2$ { showHelp(); return; } // Set the verbosity of the console from the arguments. if (mainArguments.contains("quiet")) //$NON-NLS-1$ { console.setVerbosity(Verbosity.QUIET); } else if (mainArguments.contains("verbose")) //$NON-NLS-1$ { console.setVerbosity(Verbosity.VERBOSE); } /* * Parse the free arguments into the command name and arguments to * pass to it. Add any unmatched arguments that were specified on * the command line before the argument. (eg, for * "git-tf --bare clone", we parsed the "--bare" as an unmatched * argument to the main command. We instead want to add the "--bare" * as an argument to "clone".) */ String[] fullCommand = ((FreeArgumentCollection) mainArguments.getArgument("command")).getValues(); //$NON-NLS-1$ String[] additionalArguments = mainArguments.getUnknownArguments(); String commandName = fullCommand[0]; String[] commandArgs = new String[additionalArguments.length + (fullCommand.length - 1)]; if (additionalArguments.length > 0) { System.arraycopy(additionalArguments, 0, commandArgs, 0, additionalArguments.length); } if (fullCommand.length > 1) { System.arraycopy(fullCommand, 1, commandArgs, mainArguments.getUnknownArguments().length, fullCommand.length - 1); } // Locate the specified command by name List<CommandDefinition> possibleCommands = new ArrayList<CommandDefinition>(); for (CommandDefinition c : COMMANDS) { if (c.getName().equals(commandName)) { possibleCommands.clear(); possibleCommands.add(c); break; } else if (c.getName().startsWith(commandName)) { possibleCommands.add(c); } } if (possibleCommands.size() == 0) { printError(Messages.formatString("Main.CommandNotFoundFormat", commandName, //$NON-NLS-1$ ProductInformation.getProductName())); System.exit(1); } if (possibleCommands.size() > 1) { printError(Messages.formatString("Main.AmbiguousCommandFormat", commandName, //$NON-NLS-1$ ProductInformation.getProductName())); for (CommandDefinition c : possibleCommands) { printError(Messages.formatString("Main.AmbiguousCommandListFormat", c.getName()), false); //$NON-NLS-1$ } System.exit(1); } // Instantiate the command final CommandDefinition commandDefinition = possibleCommands.get(0); Command command = null; try { command = commandDefinition.getType().newInstance(); } catch (Exception e) { printError(Messages.formatString("Main.CommandCreationFailedFormat", commandName)); //$NON-NLS-1$ System.exit(1); } // Set the console command.setConsole(console); // Parse the arguments ArgumentCollection argumentCollection = null; try { argumentCollection = ArgumentParser.parse(commandArgs, command.getPossibleArguments()); } catch (ArgumentParserException e) { Main.printError(e.getLocalizedMessage()); Main.printError(getUsage(command)); log.error("Could not parse arguments", e); //$NON-NLS-1$ System.exit(1); } // Handle the --help argument directly if (argumentCollection.contains("help")) //$NON-NLS-1$ { command.showHelp(); System.exit(0); } // Set the verbosity of the console from the arguments. if (argumentCollection.contains("quiet")) //$NON-NLS-1$ { console.setVerbosity(Verbosity.QUIET); } else if (argumentCollection.contains("verbose")) //$NON-NLS-1$ { console.setVerbosity(Verbosity.VERBOSE); } command.setArguments(argumentCollection); System.exit(command.run()); } catch (Exception e) { printError(e.getLocalizedMessage()); log.warn(MessageFormat.format("Error executing command: {0}", getCommandLine(args)), e); //$NON-NLS-1$ } }
From source file:net.sf.jsignpdf.verify.SignatureCounter.java
/** * Main program./*from w w w . ja v a 2 s . co m*/ * * @param args */ public static void main(String[] args) { // create the Options final Option optHelp = new Option("h", "help", false, "print this message"); final Option optDebug = new Option("d", "debug", false, "enables debug output"); final Option optNames = new Option("n", "names", false, "print comma separated signature names instead of the count"); final Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optDebug); options.addOption(optNames); options.addOption(optPasswd); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage()); System.exit(Constants.EXIT_CODE_PARSE_ERR); } final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar SignatureCounter.jar [file1.pdf [file2.pdf ...]]", "JSignPdf SignatureCounter is a command line tool which prints count of signatures in given PDF document.", options, null, true); } else { byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } final boolean debug = line.hasOption("d"); final boolean names = line.hasOption("n"); for (String tmpFilePath : tmpArgs) { if (debug) { System.out.print("Counting signatures in " + tmpFilePath + ": "); } final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couldn't read the file. Check the path and permissions: " + tmpFilePath); System.exit(Constants.EXIT_CODE_CANT_READ_FILE); } try { final PdfReader pdfReader = PdfUtils.getPdfReader(tmpFilePath, tmpPasswd); @SuppressWarnings("unchecked") final List<String> sigNames = pdfReader.getAcroFields().getSignatureNames(); if (names) { //print comma-separated names boolean isNotFirst = false; for (String sig : sigNames) { if (isNotFirst) { System.out.println(","); } else { isNotFirst = true; } System.out.println(sig); } } else { //normal processing print only count of signatures System.out.println(sigNames.size()); if (debug) { System.out.println("Signature names: " + sigNames); } } } catch (IOException e) { e.printStackTrace(); System.exit(Constants.EXIT_CODE_COMMON_ERROR); } } } }
From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from ww w. j a v a 2 s .c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCT), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT)); List<Pair<String, Double>> searchMZs = new ArrayList<>(productMasses.size()); List<ChemicalAssociatedWithPathway> pathwayChems = new ArrayList<>(productMasses.size()); for (Pair<ChemicalAssociatedWithPathway, Double> productMass : productMasses) { String chemName = productMass.getLeft().getChemical(); searchMZs.add(Pair.of(chemName, productMass.getRight())); pathwayChems.add(productMass.getLeft()); } System.out.format("Searching for intermediate/side-reaction products:\n"); for (Pair<String, Double> searchMZ : searchMZs) { System.out.format(" %s: %.3f\n", searchMZ.getLeft(), searchMZ.getRight()); } // Look up the standard by name. List<StandardWell> standardWells = new ArrayList<>(); if (cl.hasOption(OPTION_STANDARD_WELLS)) { Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); Map<Integer, StandardWell> pathwayIdToStandardWell = extractStandardWellsFromOptionsList(db, pathwayChems, cl.getOptionValues(OPTION_STANDARD_WELLS), standardPlate); for (ChemicalAssociatedWithPathway c : pathwayChems) { // TODO: we can avoid this loop. StandardWell well = pathwayIdToStandardWell.get(c.getId()); if (well != null) { standardWells.add(well); } } } else { for (ChemicalAssociatedWithPathway c : pathwayChems) { String standardName = c.getChemical(); System.out.format("Searching for well containing standard %s\n", standardName); List<StandardWell> wells = StandardIonAnalysis.getStandardWellsForChemical(db, c.getChemical()); if (wells != null) { standardWells.addAll(wells); } } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. We do not need to specify granular includeIons and excludeIons since * this would not take advantage of our caching strategy which uses a list of metlin ions as an index. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".tsv"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR); List<ScanData<LCMSWell>> posNegWells = new ArrayList<>(); posNegWells.addAll(allPositiveScans.getLeft()); posNegWells.addAll(allNegativeScans.getLeft()); Map<Integer, String> searchIons; if (cl.hasOption(OPTION_PATHWAY_SEARCH_IONS)) { searchIons = extractPathwayStepIons(pathwayChems, cl.getOptionValues(OPTION_PATHWAY_SEARCH_IONS), cl.getOptionValue(OPTION_SEARCH_ION, "M+H")); /* This is pretty lazy, but works with the existing API. Extract all selected ions for all search masses when * performing the scan, then filter down to the desired ions for the plot at the end. * TODO: specify the masses and scans per sample rather than batching everything together. It might be slower, * but it'll be clearer to read. */ } else { // We need to make sure that the standard metlin ion we choose is consistent with the ion modes of // the given positive, negative and standard scan files. For example, we should not pick a negative // metlin ion if all our available positive control scan files are in the positive ion mode. Map<Integer, Pair<Boolean, Boolean>> ionModes = new HashMap<>(); for (ChemicalAssociatedWithPathway chemical : pathwayChems) { boolean isPositiveScanPresent = false; boolean isNegativeScanPresent = false; for (ScanData<StandardWell> scan : allStandardScans.getLeft()) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } for (ScanData<LCMSWell> scan : posNegWells) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } ionModes.put(chemical.getId(), Pair.of(isPositiveScanPresent, isNegativeScanPresent)); } // Sort in descending order of media where MeOH and Water related media are promoted to the top and // anything derived from yeast media are demoted. We do this because we want to first process the water // and meoh media before processing the yeast media since the yeast media depends on the analysis of the former. Collections.sort(standardWells, new Comparator<StandardWell>() { @Override public int compare(StandardWell o1, StandardWell o2) { if (StandardWell.doesMediaContainYeastExtract(o1.getMedia()) && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) { return 1; } else { return 0; } } }); searchIons = extractPathwayStepIonsFromStandardIonAnalysis(pathwayChems, lcmsDir, db, standardWells, plottingDirectory, ionModes); } produceLCMSPathwayHeatmaps(lcmsDir, outData, outImg, outAnalysis, pathwayChems, allStandardScans, allPositiveScans, allNegativeScans, fontScale, cl.hasOption(OPTION_USE_HEATMAP), searchIons); } }
From source file:ws.moor.bt.grapher.Grapher.java
public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Please specify a tab-separated values file"); System.exit(1);// w ww. ja v a 2 s.c om } File file = new File(args[0]); final CSVMapCollector collector = new CSVMapCollector( new CSVSkipFilter(new CSVInputStream(new FileInputStream(file)), 0 * 1000)); JFrame window = new JFrame("Grapher"); window.setSize(1100, 800); window.setLayout(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(null); List<String> possibleNames = collector.getAvailableStreams(); Collections.sort(possibleNames); TreeNode root = convertToTree(possibleNames); final JTree tree = new JTree(root); tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { List<String> names = new ArrayList<String>(); final TreePath[] paths = tree.getSelectionModel().getSelectionPaths(); if (paths == null) { chartPanel.setChart(null); return; } for (TreePath path : paths) { Object lastPath = path.getLastPathComponent(); if (lastPath instanceof DefaultMutableTreeNode) { Object value = ((DefaultMutableTreeNode) lastPath).getUserObject(); if (value instanceof NodeValue) { names.add(value.toString()); } } } chartPanel.setChart(createChart(collector, names.toArray(new String[names.size()]))); } }); Font font = tree.getFont(); tree.setFont(font.deriveFont(10.0f)); JScrollPane scrollPane = new JScrollPane(tree); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(scrollPane); splitPane.setRightComponent(chartPanel); splitPane.setDividerLocation(200); window.setContentPane(splitPane); window.setVisible(true); }
From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException, Exception { String directory;/*ww w . ja v a 2 s . com*/ String gold_standard_lexicon; String output_lexicon; String configFile; Language language; String output; Stopwords stopwords = new Stopwords(); HashMap<String, Double> maxima; maxima = new HashMap<String, Double>(); if (args.length < 3) { System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n"); return; } // Classifier classifier; directory = args[1]; configFile = args[2]; final Config config = new Config(); config.loadFromFile(configFile); gold_standard_lexicon = config.getGoldStandardLexicon(); String model_file = config.getModel(); output_lexicon = config.getOutputLexicon(); output = config.getOutput(); language = config.getLanguage(); LexiconLoader loader = new LexiconLoader(); Lexicon gold = loader.loadFromFile(gold_standard_lexicon); Set<String> uris = new HashSet<>(); // Map<Integer,String> sentence_list = new HashMap<>(); Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>(); //consider only properties for (LexicalEntry entry : gold.getEntries()) { try { for (Sense sense : entry.getSenseBehaviours().keySet()) { String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", ""); if (!Character.isUpperCase(tmp_uri.charAt(0))) { uris.add(sense.getReference().getURI()); } } } catch (Exception e) { } ; } ModelPreprocessor preprocessor = new ModelPreprocessor(language); preprocessor.setCoreferenceResolution(false); Set<String> dep = new HashSet<>(); dep.add("prep"); dep.add("appos"); dep.add("nn"); dep.add("dobj"); dep.add("pobj"); dep.add("num"); preprocessor.setDEP(dep); List<File> list_files = new ArrayList<>(); if (config.getFiles().isEmpty()) { File folder = new File(directory); File[] files = folder.listFiles(); for (File file : files) { if (file.toString().contains(".ttl")) list_files.add(file); } } else { list_files.addAll(config.getFiles()); } System.out.println(list_files.size()); int sentence_counter = 0; Map<String, Set<Integer>> bag_words_uri = new HashMap<>(); Map<String, Integer> mapping_word_id = new HashMap<>(); for (File file : list_files) { Model model = RDFDataMgr.loadModel(file.toString()); for (Model sentence : getSentences(model)) { String reference = getReference(sentence); reference = reference.replace("http://dbpedia/", "http://dbpedia.org/"); if (uris.contains(reference)) { sentence_counter += 1; Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id); //TODO: add sentence preprocessing String obj = getObject(sentence); String subj = getSubject(sentence); preprocessor.preprocess(sentence, subj, obj, language); //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course) String parsed_sentence = getParsedSentence(sentence); try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(sentence_counter + "\t" + parsed_sentence); } catch (IOException e) { e.printStackTrace(); } for (Integer word_id : words_ids) { if (mapping_words_sentences.containsKey(word_id)) { Set<Integer> tmp_set = mapping_words_sentences.get(word_id); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } else { Set<Integer> tmp_set = new HashSet<>(); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } } if (bag_words_uri.containsKey(reference)) { Set<Integer> tmp = bag_words_uri.get(reference); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } else { Set<Integer> tmp = new HashSet<>(); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } } } model.close(); } PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv"); StringBuilder string_builder = new StringBuilder(); for (String r : bag_words_uri.keySet()) { string_builder.append(r); for (Integer i : bag_words_uri.get(r)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv"); string_builder = new StringBuilder(); for (Integer w : mapping_words_sentences.keySet()) { string_builder.append(w); for (int i : mapping_words_sentences.get(w)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); }
From source file:edu.osu.ling.pep.Pep.java
/** * Invokes Pep from the command line.//from w w w.j a va 2s . c o m * <p> * The main work this method does, apart from tokenizing the arguments and * input tokens, is to load and parse the XML grammar file (as specified by * <code>-g</code> or <code>--grammar</code>). If any of the arguments * <code>-g</code>, <code>--grammar</code>, <code>-s</code>, * <code>--seed</code>, <code>-o</code>, <code>--option</code>, occur with * no argument following, this method prints an error notifying the user. * * @param args * The expected arguments are as follows, and can occur in any * particular order: * <ul> * <li><code>-g|--grammar <grammar file></code></li> <li> * <code>-s|--seed <seed category></code></li> <li><code> * -v|--verbose {verbosity level}</code></li> <li><code> * -o|--option <OPTION_NAME=value></code></li> <li><code> * -h|--help (prints usage information)</code></li> <li><code> * <token1 ... token<em>n</em>></code> (or <code>-</code> * for standard input)</li> * </ul> * <code>OPTION_NAME</code> must be the name of one of the * recognized {@link ParserOption options}. If <code>-h</code> or * <code>--help</code> occur anywhere in the arguments, usage * information is printed and no parsing takes place. */ @SuppressWarnings("static-access") public static final void main(final String[] args) { try { final Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("grammar").withDescription("the grammar to use").hasArg() .isRequired().withArgName("grammar file").create('g')); opts.addOption(OptionBuilder.withLongOpt("seed").withDescription("the seed category to parse for") .hasArg().isRequired().withArgName("seed category").create('s')); opts.addOption(OptionBuilder.withLongOpt("verbose").withDescription("0-3").hasOptionalArg() .withArgName("verbosity level").create('v')); opts.addOption(OptionBuilder.withLongOpt("option").withDescription("sets parser options") .withArgName("OPTION=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property").create("o")); opts.addOption(OptionBuilder.withLongOpt("help").withDescription("prints this message").create('h')); final CommandLineParser parser = new GnuParser(); try { final CommandLine line = parser.parse(opts, args); if (line.hasOption('h')) { Pep.printHelp(opts); } else { final int v = Integer.parseInt(line.getOptionValue('v', Integer.toString(Pep.V_PARSE))); if (v < 0) { throw new PepException("verbosity < 0: " + v); } Pep.verbosity = v; final Map<ParserOption, Boolean> options = new EnumMap<ParserOption, Boolean>( ParserOption.class); final Properties props = line.getOptionProperties("o"); for (final Object key : props.keySet()) { try { options.put(ParserOption.valueOf(key.toString()), Boolean.valueOf(props.get(key).toString())); } catch (final IllegalArgumentException iae) { Pep.printError("no option named " + key.toString()); Pep.printHelp(opts); return; } } final Pep pep = new Pep(options); // final Grammar grammar = // new GrammarParser(Pep.findGrammar(line // .getOptionValue('g'))).t.parse(); final List<?> ts = line.getArgList(); List<String> tokens = null; if (ts.isEmpty() || ts.get(0).equals("-")) { tokens = Pep.readTokens(new Scanner(System.in)); } else { tokens = new ArrayList<String>(ts.size()); for (final Object t : ts) { tokens.add(t.toString()); } } pep.lastParseStart = System.currentTimeMillis(); // try { // pep.parse(grammar, tokens, // new Category(line.getOptionValue('s'))); // } catch (final PepException ignore) { // // ignore here, we're listening // } } } catch (final ParseException pe) { Pep.printError("command-line syntax problem: " + pe.getMessage()); Pep.printHelp(opts); } } catch (final PepException pe) { final Throwable cause = pe.getCause(); Pep.printError((cause == null) ? pe : cause); } catch (final RuntimeException re) { Pep.printError(re); } }
From source file:act.installer.pubchem.PubchemSynonymFinder.java
public static void main(String[] args) throws Exception { org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww . ja v a2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!rocksDBFile.isDirectory()) { System.err.format("Index directory does not exist or is not a directory at '%s'", rocksDBFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<String> compoundIds = null; if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) { compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID)); } else if (cl.hasOption(OPTION_IDS_FILE)) { File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE)); if (!idsFile.exists()) { System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } compoundIds = getCIDsFromFile(idsFile); if (compoundIds.size() == 0) { System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } } else { System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.", OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Run a quick check to warn users of malformed ids. compoundIds.forEach(x -> { if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching. LOGGER.warn("Specified compound id does not match expected format: %s", x); } }); LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size()); Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null; Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size()); try { dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile); RocksDB db = dbAndHandles.getLeft(); ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight() .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS); for (String cid : compoundIds) { PubchemSynonyms synonyms = null; byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8)); if (val != null) { ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val)); // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check. synonyms = (PubchemSynonyms) oi.readObject(); } else { LOGGER.warn("No synonyms available for compound id '%s'", cid); } results.put(cid, synonyms); } } finally { if (dbAndHandles != null) { dbAndHandles.getLeft().close(); } } try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT) ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT)) : System.out) { OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results); new OutputStreamWriter(outputStream).append('\n'); } LOGGER.info("Done searching for Pubchem synonyms"); }
From source file:amie.keys.CombinationsExplorationNew.java
public static void main(String[] args) throws IOException { CommandLine cli = parseArguments(args); // We get a map with the properties and their number of subjects propertiesSupport = kb.frequentBindingsOf(ByteString.of("?p"), ByteString.of("?s"), KB.triples(KB.triple("?s", "?p", "?o"))); // Helper object that contains the implementation for the calculation // of confidence and support numberOfInstances = kb.size(Column.Subject); miningHelper = new DefaultMiningAssistant(kb); // The file with the non-keys, one per line List<List<String>> nonKeys = new ArrayList<>(); for (List<String> nonKey : Utilities.parseNonKeysFile(cli.getOptionValue("nk"))) { if (nonKey.size() > 1) { nonKeys.add(nonKey);//from ww w . j a va 2 s .co m } } System.out.println("nonKeys" + nonKeys); // for(List<String> nonKey:nonKeys){ // System.out.println(nonKey); //} long timea = System.currentTimeMillis(); // System.out.println("nonKeys:"+nonKeys); // We map the non-keys to an integer space nonKeysInt = buildDictionaries(nonKeys, propertiesList); // System.out.println(nonKeysInt.size() + " => nonKeysInt:" + nonKeysInt); //System.out.println("prop:"+property2Id); System.out.println("Dictionaries built"); // We discover the conditional keys discoverConditionalKeys(); long timeb = System.currentTimeMillis(); System.out.println("Total time in ms: " + (timeb - timea)); }