List of usage examples for java.util List addAll
boolean addAll(Collection<? extends E> c);
From source file:AmazonKinesisCreate.java
public static void main(String[] args) throws Exception { init();//from w ww .ja v a 2s . c o m final String myStreamName = "philsteststream"; final Integer myStreamSize = 1; // Create a stream. The number of shards determines the provisioned throughput. CreateStreamRequest createStreamRequest = new CreateStreamRequest(); createStreamRequest.setStreamName(myStreamName); createStreamRequest.setShardCount(myStreamSize); // pt kinesisClient.createStream(createStreamRequest); // The stream is now being created. LOG.info("Creating Stream : " + myStreamName); waitForStreamToBecomeAvailable(myStreamName); // list all of my streams ListStreamsRequest listStreamsRequest = new ListStreamsRequest(); listStreamsRequest.setLimit(10); ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest); List<String> streamNames = listStreamsResult.getStreamNames(); while (listStreamsResult.isHasMoreStreams()) { if (streamNames.size() > 0) { listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1)); } listStreamsResult = kinesisClient.listStreams(listStreamsRequest); streamNames.addAll(listStreamsResult.getStreamNames()); } LOG.info("Printing my list of streams : "); // print all of my streams. if (!streamNames.isEmpty()) { System.out.println("List of my streams: "); } for (int i = 0; i < streamNames.size(); i++) { System.out.println(streamNames.get(i)); } LOG.info("Putting records in stream : " + myStreamName); // Write 10 records to the stream for (int j = 0; j < 10; j++) { try { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(myStreamName); putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes())); putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j)); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } // Delete the stream. /* LOG.info("Deleting stream : " + myStreamName); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); deleteStreamRequest.setStreamName(myStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + myStreamName); LOG.info("Streaming completed" + myStreamName); */ }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step3HITCreator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];//from w w w .j a v a 2s .c o m File outputDir = new File(args[1]); // sandbox or real MTurk? final boolean useSandbox = false; // required only for pilot // final int randomArgumentPairsCount = 50; // pseudo-random generator final Random random = new Random(1); for (Map.Entry<String, SortedSet<String>> entry : BATCHES.entrySet()) { Step3HITCreator hitCreator = new Step3HITCreator(useSandbox); hitCreator.outputPath = new File(outputDir, entry.getKey()); hitCreator.initialize(); // we will process only a subset first List<ArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); System.out.println(files); // read all files for the given batch for (File file : files) { if (entry.getValue().contains(file.getName())) { allArgumentPairs.addAll((List<ArgumentPair>) XStreamTools.getXStream().fromXML(file)); } } // we have to shuffle them Collections.shuffle(allArgumentPairs, random); // only for pilot // List<ArgumentPair> selectedArgumentPairs = allArgumentPairs // .subList(0, randomArgumentPairsCount); // for (ArgumentPair argumentPair : selectedArgumentPairs) { for (ArgumentPair argumentPair : allArgumentPairs) { hitCreator.process(argumentPair); } hitCreator.collectionProcessComplete(); } }
From source file:AmazonKinesisDelete.java
public static void main(String[] args) throws Exception { init();//w w w . jav a 2s . c om //final String myStreamName = "anotestBstream"; //final Integer myStreamSize = 1; // Create a stream. The number of shards determines the provisioned throughput. // CreateStreamRequest createStreamRequest = new CreateStreamRequest(); // createStreamRequest.setStreamName(myStreamName); // createStreamRequest.setShardCount(myStreamSize); // pt // kinesisClient.createStream(createStreamRequest); // The stream is now being created. // LOG.info("Creating Stream : " + myStreamName); // waitForStreamToBecomeAvailable(myStreamName); // list all of my streams ListStreamsRequest listStreamsRequest = new ListStreamsRequest(); listStreamsRequest.setLimit(10); ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest); List<String> streamNames = listStreamsResult.getStreamNames(); while (listStreamsResult.isHasMoreStreams()) { if (streamNames.size() > 0) { listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1)); } listStreamsResult = kinesisClient.listStreams(listStreamsRequest); streamNames.addAll(listStreamsResult.getStreamNames()); } LOG.info("Printing my list of streams : "); // print all of my streams. if (!streamNames.isEmpty()) { System.out.println("List of my streams: "); } for (int i = 0; i < streamNames.size(); i++) { System.out.println(streamNames.get(i)); String actStreamName = streamNames.get(i); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); //deleteStreamRequest.setStreamName(myStreamName); deleteStreamRequest.setStreamName(actStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + actStreamName); } /* LOG.info("Putting records in stream : " + myStreamName); // Write 10 records to the stream for (int j = 0; j < 10; j++) { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(myStreamName); putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes())); putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j)); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); } */ // Delete the stream. /* LOG.info("Deleting stream : " + myStreamName); DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest(); deleteStreamRequest.setStreamName(myStreamName); kinesisClient.deleteStream(deleteStreamRequest); // The stream is now being deleted. LOG.info("Stream is now being deleted : " + myStreamName); LOG.info("Streaming completed" + myStreamName); */ }
From source file:TestDumpRecord.java
public static void main(String[] args) throws NITFException { List<String> argList = Arrays.asList(args); List<File> files = new LinkedList<File>(); for (String arg : argList) { File f = new File(arg); if (f.isDirectory()) { File[] dirFiles = f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { String ext = FilenameUtils.getExtension(name).toLowerCase(); return ext.matches("nitf|nsf|ntf"); }//from w w w . j a v a2 s . c om }); files.addAll(Arrays.asList(dirFiles)); } else files.add(f); } Reader reader = new Reader(); for (File file : files) { PrintStream out = System.out; out.println("=== " + file.getAbsolutePath() + " ==="); IOHandle handle = new IOHandle(file.getAbsolutePath()); Record record = reader.read(handle); dumpRecord(record, reader, out); handle.close(); record.destruct(); // tells the memory manager to decrement the ref // count } }
From source file:AmazonKinesisGet.java
public static void main(String[] args) throws Exception { init();/*w w w .j a v a2 s .c o m*/ final String myStreamName = "philsteststream"; final Integer myStreamSize = 1; // list all of my streams ListStreamsRequest listStreamsRequest = new ListStreamsRequest(); listStreamsRequest.setLimit(10); ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest); List<String> streamNames = listStreamsResult.getStreamNames(); while (listStreamsResult.isHasMoreStreams()) { if (streamNames.size() > 0) { listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1)); } listStreamsResult = kinesisClient.listStreams(listStreamsRequest); streamNames.addAll(listStreamsResult.getStreamNames()); } LOG.info("Printing my list of streams : "); // print all of my streams. if (!streamNames.isEmpty()) { System.out.println("List of my streams: "); } for (int i = 0; i < streamNames.size(); i++) { System.out.println(streamNames.get(i)); } //System.out.println(streamNames.get(0)); String myownstream = streamNames.get(0); // Retrieve the Shards from a Stream DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest(); describeStreamRequest.setStreamName(myownstream); DescribeStreamResult describeStreamResult; List<Shard> shards = new ArrayList<>(); String lastShardId = null; do { describeStreamRequest.setExclusiveStartShardId(lastShardId); describeStreamResult = kinesisClient.describeStream(describeStreamRequest); shards.addAll(describeStreamResult.getStreamDescription().getShards()); if (shards.size() > 0) { lastShardId = shards.get(shards.size() - 1).getShardId(); } } while (describeStreamResult.getStreamDescription().getHasMoreShards()); // Get Data from the Shards in a Stream // Hard-coded to use only 1 shard String shardIterator; GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest(); getShardIteratorRequest.setStreamName(myownstream); //get(0) shows hardcoded to 1 stream getShardIteratorRequest.setShardId(shards.get(0).getShardId()); // using TRIM_HORIZON but could use alternatives getShardIteratorRequest.setShardIteratorType("TRIM_HORIZON"); GetShardIteratorResult getShardIteratorResult = kinesisClient.getShardIterator(getShardIteratorRequest); shardIterator = getShardIteratorResult.getShardIterator(); // Continuously read data records from shard. List<Record> records; while (true) { // Create new GetRecordsRequest with existing shardIterator. // Set maximum records to return to 1000. GetRecordsRequest getRecordsRequest = new GetRecordsRequest(); getRecordsRequest.setShardIterator(shardIterator); getRecordsRequest.setLimit(1000); GetRecordsResult result = kinesisClient.getRecords(getRecordsRequest); // Put result into record list. Result may be empty. records = result.getRecords(); // Print records for (Record record : records) { ByteBuffer byteBuffer = record.getData(); System.out.println(String.format("Seq No: %s - %s", record.getSequenceNumber(), new String(byteBuffer.array()))); } try { Thread.sleep(1000); } catch (InterruptedException exception) { throw new RuntimeException(exception); } shardIterator = result.getNextShardIterator(); } }
From source file:com.act.lcms.MassCalculator2.java
public static void main(String[] args) throws Exception { CommandLine cl = CLI_UTIL.parseCommandLine(args); if (cl.hasOption(OPTION_LICENSE_FILE)) { LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE)); LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); }//from www .j a v a 2s .c om List<String> inchis = new ArrayList<>(); if (cl.hasOption(OPTION_INPUT_FILE)) { try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) { String line; while ((line = reader.readLine()) != null) { inchis.add(line); } } } if (cl.getArgList().size() > 0) { LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size()); inchis.addAll(cl.getArgList()); } try (PrintWriter writer = new PrintWriter( cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)) : new OutputStreamWriter(System.out))) { writer.format("InChI\tMass\tCharge\n"); for (String inchi : inchis) { try { Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi); writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight()); } catch (MolFormatException e) { LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage()); } } } }
From source file:ca.on.oicr.pde.deciders.GenomicAlignmentNovoalignDecider.java
public static void main(String args[]) { List<String> params = new ArrayList<String>(); params.add("--plugin"); params.add(GenomicAlignmentNovoalignDecider.class.getCanonicalName()); params.add("--"); params.addAll(Arrays.asList(args)); System.out.println("Parameters: " + Arrays.deepToString(params.toArray())); net.sourceforge.seqware.pipeline.runner.PluginRunner.main(params.toArray(new String[params.size()])); }
From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java
public static void main(String[] args) throws IOException { CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file") .desc("bazel extra action protobuf file").build()); options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file") .desc("Executable cpplint file to invoke").build()); try {/*from w ww . j av a2 s.c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); String extraActionFile = line.getOptionValue("f"); String cpplintFile = line.getOptionValue("c"); Collection<String> sourceFiles = getSourceFiles(extraActionFile); if (sourceFiles.size() == 0) { LOG.fine("No cpp files found by checkstyle"); return; } LOG.fine(sourceFiles.size() + " cpp files found by checkstyle"); // Create and run the command List<String> commandBuilder = new ArrayList<>(); commandBuilder.add(cpplintFile); commandBuilder.add("--linelength=100"); // TODO: https://github.com/twitter/heron/issues/466, // Remove "runtime/references" when we fix all non-const references in our codebase. // TODO: https://github.com/twitter/heron/issues/467, // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn"); commandBuilder.addAll(sourceFiles); runLinter(commandBuilder); } catch (ParseException exp) { LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + CLASSNAME, options); } }
From source file:diffhunter.DiffHunter.java
/** * @param args the command line arguments * @throws org.apache.commons.cli.ParseException * @throws java.io.IOException//from ww w . j a v a 2 s. co m */ public static void main(String[] args) throws ParseException, IOException { //String test_ = Paths.get("J:\\VishalData\\additional\\", "Sasan" + "_BDB").toAbsolutePath().toString(); // TODO code application logic here /*args = new String[] { "-i", "-b", "J:\\VishalData\\additional\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted.bed", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-o", "J:\\VishalData" };*/ /*args = new String[] { "-c", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-1", "J:\\VishalData\\Ptbp2_Adult_testis_CLIP_mm9_plus_strand_sorted_BDB", "-2", "J:\\VishalData\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted_BDB", "-w", "200", "-s", "50", "-o", "J:\\VishalData" };*/ Options options = new Options(); // add t option options.addOption("i", "index", false, "Indexing BED files."); options.addOption("b", "bed", true, "bed file to be indexed"); options.addOption("o", "output", true, "Folder that the index/comparison file will be created."); options.addOption("r", "reference", true, "Reference annotation file to be used for indexing"); options.addOption("c", "compare", false, "Finding differences between two conditions"); options.addOption("1", "first", true, "First sample index location"); options.addOption("2", "second", true, "Second sample index location"); options.addOption("w", "window", true, "Length of window for identifying differences"); options.addOption("s", "sliding", true, "Length of sliding"); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); boolean indexing = false; boolean comparing = false; //Indexing! if (cmd.hasOption("i")) { //if(cmd.hasOption("1")) //System.err.println("sasan"); //System.out.println("sasa"); indexing = true; } else if (cmd.hasOption("c")) { //System.err.println(""); comparing = true; } else { //System.err.println("Option is not deteced."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } //Indexing is selected // if (indexing == true) { //Since indexing is true. //User have to provide file for indexing. if (!(cmd.hasOption("o") || cmd.hasOption("r") || cmd.hasOption("b"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } String bedfile_ = cmd.getOptionValue("b"); String reference_file = cmd.getOptionValue("r"); String folder_loc = cmd.getOptionValue("o"); String sample_name = FilenameUtils.getBaseName(bedfile_); try (Database B2 = BerkeleyDB_Box.Get_BerkeleyDB( Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString(), true, sample_name)) { Indexer indexing_ = new Indexer(reference_file); indexing_.Make_Index(B2, bedfile_, Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString()); B2.close(); } } else if (comparing == true) { if (!(cmd.hasOption("o") || cmd.hasOption("w") || cmd.hasOption("s") || cmd.hasOption("1") || cmd.hasOption("2"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } String folder_loc = cmd.getOptionValue("o"); int window_ = Integer.parseInt(cmd.getOptionValue("w")); //int window_=600; int slide_ = Integer.parseInt(cmd.getOptionValue("s")); String first = cmd.getOptionValue("1").replace("_BDB", ""); String second = cmd.getOptionValue("2").replace("_BDB", ""); String reference_file = cmd.getOptionValue("r"); //String folder_loc=cmd.getOptionValue("o"); String sample_name_first = FilenameUtils.getBaseName(first); String sample_name_second = FilenameUtils.getBaseName(second); Database B1 = BerkeleyDB_Box.Get_BerkeleyDB(first + "_BDB", false, sample_name_first); Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(second + "_BDB", false, sample_name_second); List<String> first_condition_genes = Files .lines(Paths.get(first + "_BDB", sample_name_first + ".txt").toAbsolutePath()) .collect(Collectors.toList()); List<String> second_condition_genes = Files .lines(Paths.get(second + "_BDB", sample_name_second + ".txt").toAbsolutePath()) .collect(Collectors.toList()); System.out.println("First and second condition are loaded!!! "); List<String> intersection_ = new ArrayList<>(first_condition_genes); intersection_.retainAll(second_condition_genes); BufferedWriter output = new BufferedWriter( new FileWriter(Paths.get(folder_loc, "differences_" + window_ + "_s" + slide_ + "_c" + ".txt") .toAbsolutePath().toString(), false)); List<Result_Window> final_results = Collections.synchronizedList(new ArrayList<>()); Worker_New worker_class = new Worker_New(); worker_class.Read_Reference(reference_file); while (!intersection_.isEmpty()) { List<String> selected_genes = new ArrayList<>(); //if (intersection_.size()<=10000){selected_genes.addAll(intersection_.subList(0, intersection_.size()));} //else selected_genes.addAll(intersection_.subList(0, 10000)); if (intersection_.size() <= intersection_.size()) { selected_genes.addAll(intersection_.subList(0, intersection_.size())); } else { selected_genes.addAll(intersection_.subList(0, intersection_.size())); } intersection_.removeAll(selected_genes); //System.out.println("Intersection count is:"+intersection_.size()); //final List<Result_Window> resultssss_=new ArrayList<>(); IntStream.range(0, selected_genes.size()).parallel().forEach(i -> { System.out.println(selected_genes.get(i) + "\tprocessing......"); String gene_of_interest = selected_genes.get(i);//"ENSG00000142657|PGD";//intersection_.get(6);////"ENSG00000163395|IGFN1";//"ENSG00000270066|SCARNA2"; int start = worker_class.dic_genes.get(gene_of_interest).start_loc; int end = worker_class.dic_genes.get(gene_of_interest).end_loc; Map<Integer, Integer> first_ = Collections.EMPTY_MAP; try { first_ = BerkeleyDB_Box.Get_Coord_Read(B1, gene_of_interest); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex); } Map<Integer, Integer> second_ = Collections.EMPTY_MAP; try { second_ = BerkeleyDB_Box.Get_Coord_Read(B2, gene_of_interest); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex); } List<Window> top_windows_first = worker_class.Get_Top_Windows(window_, first_, slide_); List<Window> top_windows_second = worker_class.Get_Top_Windows(window_, second_, slide_); //System.out.println("passed for window peak call for gene \t"+selected_genes.get(i)); // System.out.println("top_window_first_Count\t"+top_windows_first.size()); // System.out.println("top_window_second_Count\t"+top_windows_second.size()); if (top_windows_first.isEmpty() && top_windows_second.isEmpty()) { return; } List<Result_Window> res_temp = new Worker_New().Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, sample_name_first, sample_name_second, 0.01); if (!res_temp.isEmpty()) { final_results.addAll(res_temp);//final_results.addAll(worker_class.Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, first_condition, second_condition, 0.01)); } //System.out.println(selected_genes.get(i)+"\tprocessed."); }); /*selected_genes.parallelStream().forEach(i -> { });*/ List<Double> pvals = new ArrayList<>(); for (int i = 0; i < final_results.size(); i++) { pvals.add(final_results.get(i).p_value); } List<Double> qvals = MultipleTestCorrection.benjaminiHochberg(pvals); System.out.println("Writing to file..."); output.append("Gene_Symbol\tContributing_Sample\tStart\tEnd\tOddsRatio\tp_Value\tFDR"); output.newLine(); for (int i = 0; i < final_results.size(); i++) { Result_Window item = final_results.get(i); output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value + "\t" + qvals.get(i)); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non); output.newLine(); } /* for (Result_Window item : final_results) { output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non); output.newLine(); } */ final_results.clear(); } output.close(); } System.out.println("Done."); }
From source file:com.act.analysis.similarity.SimilarityAnalysis.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 w w . ja v a 2 s. c om } 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; } LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); if (cl.hasOption(OPTION_TARGET_INCHI) && cl.hasOption(OPTION_TARGET_FILE)) { System.err.format("Specify only one of -%s or -%s\n", OPTION_TARGET_INCHI, OPTION_TARGET_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<SimilarityOperator> querySimilarityOperators = new ArrayList<>(); List<String> header = new ArrayList<>(); header.add("name"); header.add("id"); header.add("inchi"); if (cl.hasOption(OPTION_QUERY_INCHI) && !cl.hasOption(OPTION_QUERY_FILE)) { SimilarityOperator so = makeSimilarityOperators("from inchi", cl.getOptionValue(OPTION_QUERY_INCHI)); so.init(); querySimilarityOperators.add(so); header.addAll(so.getResultFields()); } else if (cl.hasOption(OPTION_QUERY_FILE) && !cl.hasOption(OPTION_QUERY_INCHI)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_QUERY_FILE))); for (Map<String, String> row : parser.getResults()) { System.out.format("Compiling query for %s, %s\n", row.get("name"), row.get("inchi")); SimilarityOperator so = makeSimilarityOperators(row.get("name"), row.get("inchi")); so.init(); querySimilarityOperators.add(so); header.addAll(so.getResultFields()); } } else { System.err.format("Specify exactly one of -%s or -%s\n", OPTION_QUERY_INCHI, OPTION_QUERY_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<Map<String, String>> targetChemicals = null; if (cl.hasOption(OPTION_TARGET_INCHI) && !cl.hasOption(OPTION_TARGET_FILE)) { String inchi = cl.getOptionValue(OPTION_TARGET_INCHI); targetChemicals = Collections.singletonList(new HashMap<String, String>() { { put("name", "direct-input"); put("id", null); put("inchi", inchi); } }); } else if (cl.hasOption(OPTION_TARGET_FILE) && !cl.hasOption(OPTION_TARGET_INCHI)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_TARGET_FILE))); targetChemicals = parser.getResults(); } else { System.err.format("Specify exactly one of -%s or -%s\n", OPTION_TARGET_INCHI, OPTION_TARGET_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } AlignmentMoleculeFactory alignmentMoleculeFactory = new AlignmentMoleculeFactory(); // TODO: add symmetric computations for target as query and each query as target. TSVWriter<String, String> writer = new TSVWriter<>(header); writer.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE))); try { for (Map<String, String> row : targetChemicals) { Molecule targetMol = MolImporter.importMol(row.get("inchi")); Cleaner.clean(targetMol, 3); // This will assign 3D atom coordinates to the MolAtoms in targetMol. Molecule targetFragment = findLargestFragment(targetMol.convertToFrags()); AlignmentMolecule am = alignmentMoleculeFactory.create(targetFragment, AlignmentProperties.DegreeOfFreedomType.TRANSLATE_ROTATE_FLEXIBLE); Map<String, String> outputRow = new HashMap<>(row); System.out.format("Processing target %s\n", row.get("name")); for (SimilarityOperator so : querySimilarityOperators) { System.out.format(" running query %s\n", so.getName()); Map<String, Double> results = so.calculateSimilarity(am); outputRow.putAll(doubleMapToStringMap(results)); } writer.append(outputRow); writer.flush(); } } finally { if (writer != null) { writer.close(); } } System.out.format("Done\n"); }