List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:org.finra.dm.core.ArgumentParserTest.java
@Test public void testGetIntegerValue() throws ParseException { final Integer testDefaultValue = 500; final Integer testMinValue = 0; final Integer testMaxValue = 1000; ArgumentParser argParser = new ArgumentParser(""); Option intOpt = argParser.addArgument("i", "int", true, "Some integer parameter", false); Integer inputValue;/*from w w w . j av a 2 s . com*/ Integer resultValue; final String shortIntOpt = String.format("-%s", intOpt.getOpt()); final String longIntOpt = String.format("--%s", intOpt.getLongOpt()); argParser.parseArguments(new String[] {}); assertNull(argParser.getIntegerValue(intOpt)); assertEquals(testDefaultValue, argParser.getIntegerValue(intOpt, testDefaultValue)); inputValue = 123; argParser.parseArguments(new String[] { shortIntOpt, inputValue.toString() }); resultValue = argParser.getIntegerValue(intOpt); assertNotNull(resultValue); assertEquals(inputValue, resultValue); inputValue = 456; argParser.parseArguments(new String[] { shortIntOpt, inputValue.toString() }); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue); assertNotNull(resultValue); assertEquals(inputValue, resultValue); inputValue = 789; argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() }); resultValue = argParser.getIntegerValue(intOpt); assertNotNull(resultValue); assertEquals(inputValue, resultValue); // The "happy path" test case for the minimum and maximum allowed values. inputValue = 234; argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() }); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); assertNotNull(resultValue); assertEquals(inputValue, resultValue); // The default value test case the minimum and maximum allowed values. argParser.parseArguments(new String[] {}); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); assertNotNull(resultValue); assertEquals(testDefaultValue, resultValue); // The edge test case for the minimum allowed value. argParser.parseArguments(new String[] { longIntOpt, testMinValue.toString() }); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); assertNotNull(resultValue); assertEquals(testMinValue, resultValue); // The edge test case for the maximum allowed value. argParser.parseArguments(new String[] { longIntOpt, testMaxValue.toString() }); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); assertNotNull(resultValue); assertEquals(testMaxValue, resultValue); // The edge test case for the minimum and maximum allowed values. argParser.parseArguments(new String[] { longIntOpt, testDefaultValue.toString() }); resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testDefaultValue, testDefaultValue); assertNotNull(resultValue); assertEquals(testDefaultValue, resultValue); // Try to get an option value what is less than the minimum allowed value. inputValue = testMinValue - 1; argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() }); try { argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); fail("Suppose to throw an IllegalArgumentException when option value is less than the minimum allowed value."); } catch (IllegalArgumentException e) { assertEquals(String.format("The %s option value %d is less than the minimum allowed value of %d.", intOpt.getLongOpt(), inputValue, testMinValue), e.getMessage()); } // Try to get an option value what is greater than the maximum allowed value. inputValue = testMaxValue + 1; argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() }); try { argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue); fail("Suppose to throw an IllegalArgumentException when option value is greater than the maximum allowed value."); } catch (IllegalArgumentException e) { assertEquals(String.format("The %s option value %d is bigger than maximum allowed value of %d.", intOpt.getLongOpt(), inputValue, testMaxValue), e.getMessage()); } }
From source file:org.finra.dm.core.ArgumentParserTest.java
@Test public void testGetFileValue() throws ParseException { File testDefaultValue = new File("default_file_name"); ArgumentParser argParser = new ArgumentParser(""); Option fileOpt = argParser.addArgument("f", "file", true, "Source file name", false); File inputValue;/*from ww w . j ava2 s. co m*/ File resultValue; final String shortFileOpt = String.format("-%s", fileOpt.getOpt()); final String longFileOpt = String.format("--%s", fileOpt.getLongOpt()); argParser.parseArguments(new String[] { "" }); assertNull(argParser.getFileValue(fileOpt)); assertEquals(testDefaultValue, argParser.getFileValue(fileOpt, testDefaultValue)); inputValue = new File("folder/file_name_1"); argParser.parseArguments(new String[] { shortFileOpt, inputValue.toString() }); resultValue = argParser.getFileValue(fileOpt); assertNotNull(resultValue); assertEquals(inputValue, resultValue); inputValue = new File("folder/file_name_2"); argParser.parseArguments(new String[] { shortFileOpt, inputValue.toString() }); resultValue = argParser.getFileValue(fileOpt, testDefaultValue); assertNotNull(resultValue); assertEquals(inputValue, resultValue); inputValue = new File("file_name_3"); argParser.parseArguments(new String[] { longFileOpt, inputValue.toString() }); resultValue = argParser.getFileValue(fileOpt); assertNotNull(resultValue); assertEquals(inputValue, resultValue); }
From source file:org.finra.dm.core.ArgumentParserTest.java
/** * Dump state of the Option object instance, suitable for debugging and comparing Options as Strings. * * @param option the Option object instance to dump the state of * * @return Stringified form of this Option object instance */// w ww . jav a 2s.co m private String optionToString(Option option) { StringBuilder buf = new StringBuilder(); buf.append("[ option: "); buf.append(option.getOpt()); if (option.getLongOpt() != null) { buf.append(" ").append(option.getLongOpt()); } buf.append(" "); if (option.hasArg()) { buf.append(" [ARG]"); } buf.append(" :: ").append(option.getDescription()); if (option.isRequired()) { buf.append(" [REQUIRED]"); } buf.append(" ]"); return buf.toString(); }
From source file:org.finra.herd.core.ArgumentParserTest.java
@Test public void testGetUsageInformation() { List<Option> optionsIn = new ArrayList<>(); optionsIn.add(new Option("a", "some_flag", false, "Some flag parameter")); optionsIn.add(new Option("b", "some_parameter", true, "Some parameter with an argument")); ArgumentParser argParser = new ArgumentParser("TestApp"); argParser.addArgument(optionsIn.get(0), false); argParser.addArgument(optionsIn.get(1), true); String usage = argParser.getUsageInformation(); assertNotNull(usage);/*www . j av a 2s . co m*/ assertTrue(usage.contains(String.format("usage: %s", argParser.getApplicationName()))); for (Option option : optionsIn) { assertTrue(usage.contains(String.format("-%s,", option.getOpt()))); assertTrue(usage.contains(String.format("--%s", option.getLongOpt()))); assertTrue(usage.contains(option.getDescription())); assertTrue(!option.hasArg() || usage.contains("<arg>")); } }
From source file:org.g_node.srv.CliOptionServiceTest.java
/** * Main assertions of all option arguments. * @param opt The actual {@link Option}. * @param shortOpt Short commandline argument of the current option. * @param longOpt Long commandline argument of the current option. * @param desc Description text of the current option. * @param isRequired Whether the current option is a required commandline argument. * @param hasArguments Whether the current option requires an additional argument. *//*from ww w. j a v a 2 s. c o m*/ private void assertOption(final Option opt, final String shortOpt, final String longOpt, final String desc, final Boolean isRequired, final Boolean hasArgument, final Boolean hasArguments) { assertThat(opt.getOpt()).isEqualToIgnoringCase(shortOpt); assertThat(opt.getLongOpt()).isEqualToIgnoringCase(longOpt); assertThat(opt.getDescription()).contains(desc); assertThat(opt.isRequired()).isEqualTo(isRequired); assertThat(opt.hasArg()).isEqualTo(hasArgument); assertThat(opt.hasArgs()).isEqualTo(hasArguments); }
From source file:org.jax.bioinfdata.genocall.ConvertAlchemyCallsToHDF5Main.java
/** * the main entry point/*from w w w. j a v a 2 s . com*/ * @param args command line args * @throws IOException * @throws IllegalFormatException */ public static void main(String[] args) throws IllegalFormatException, IOException { // Deal with the options. CommandLineParser parser = new GnuParser(); Options options = new Options(); CommandLine commandLine = null; final Option helpOption; { helpOption = new Option("help", "Print this help and exit"); helpOption.setRequired(false); options.addOption(helpOption); } final Option genoFileOption; { genoFileOption = new Option("alchemygenos", "the genotype calls output from alchemy"); genoFileOption.setRequired(true); genoFileOption.setArgs(1); genoFileOption.setArgName("file name"); options.addOption(genoFileOption); } final Option outputFileOption; { outputFileOption = new Option("hdf5out", "the file to write HDF5 output to"); outputFileOption.setRequired(true); outputFileOption.setArgs(1); outputFileOption.setArgName("file name"); options.addOption(outputFileOption); } try { commandLine = parser.parse(options, args); // See if we just need to print the help options. if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("alchtohdf5", options); } else { final String genoFileName = commandLine.getOptionValue(genoFileOption.getOpt()); final String outFileName = commandLine.getOptionValue(outputFileOption.getOpt()); final FlatFileReader genoFFR = new FlatFileReader(new FileReader(genoFileName), CommonFlatFileFormat.TAB_DELIMITED_UNIX); GenotypeCallMatrix genoMat = GenotypesFlatFile.readAlchemyGenoCalls(genoFFR); genoFFR.close(); IHDF5Factory hdf5Fac = HDF5FactoryProvider.get(); File hdf5File = new File(outFileName); if (hdf5File.exists()) { if (!hdf5File.delete()) { throw new IOException("failed to overwrite \"" + outFileName + "\""); } } IHDF5Writer hdf5Writer = hdf5Fac.open(hdf5File); HDF5GenotypeCallMatrix hdf5GenoMat = new HDF5GenotypeCallMatrix(hdf5Writer); AbstractGenotypeCallMatrix.copyGenoMatrix(genoMat, hdf5GenoMat); hdf5Writer.close(); } } catch (ParseException ex) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("fftohdf5", options); System.exit(-1); } }
From source file:org.jax.bioinfdata.genocall.ConvertGenotypeFlatFileToHDF5Main.java
/** * the main entry point/* www.jav a2 s .c o m*/ * @param args command line args * @throws IOException * @throws IllegalFormatException */ public static void main(String[] args) throws IllegalFormatException, IOException { // Deal with the options. CommandLineParser parser = new GnuParser(); Options options = new Options(); CommandLine commandLine = null; final Option helpOption; { helpOption = new Option("help", "Print this help and exit"); helpOption.setRequired(false); options.addOption(helpOption); } final Option genoFileOption; { genoFileOption = new Option("genoinfiles", "the genotype input flat file"); genoFileOption.setRequired(true); genoFileOption.setArgs(Integer.MAX_VALUE); genoFileOption.setArgName("file name"); options.addOption(genoFileOption); } final Option genoInFormatOption; { genoInFormatOption = new Option("genoinformat", "[optional] the format of the genotype file (must be \"csv\"" + " or \"tab\". \"csv\" is the default)"); genoInFormatOption.setRequired(false); genoInFormatOption.setArgs(1); genoInFormatOption.setArgName("csv or tab"); options.addOption(genoInFormatOption); } final Option aAlleleOption; { aAlleleOption = new Option("aallelecol", "[optional] the A allele column # (one-based index). If " + "no A allele column is given then allele codes must be " + "used in place of nucleotide values where 1 = A allele, " + "2 = B allele, 3 = Heterozygous, -1 = No Call"); aAlleleOption.setRequired(false); aAlleleOption.setArgs(1); aAlleleOption.setArgName("column #"); options.addOption(aAlleleOption); } final Option bAlleleOption; { bAlleleOption = new Option("ballelecol", "[optional] the B allele column # (one-based index). If " + "no B allele column is given then allele codes must be " + "used in place of nucleotide values where 1 = A allele, " + "2 = B allele, 3 = Heterozygous, -1 = No Call"); bAlleleOption.setRequired(false); bAlleleOption.setArgs(1); bAlleleOption.setArgName("column #"); options.addOption(bAlleleOption); } final Option snpIdColumnOption; { snpIdColumnOption = new Option("snpcol", "[optional] the SNP ID column # (one-based index)"); snpIdColumnOption.setRequired(false); snpIdColumnOption.setArgs(1); snpIdColumnOption.setArgName("column #"); options.addOption(snpIdColumnOption); } final Option chromosomeColumnOption; { chromosomeColumnOption = new Option("chrcol", "[optional] the chromosome ID column # (one-based index)"); chromosomeColumnOption.setRequired(false); chromosomeColumnOption.setArgs(1); chromosomeColumnOption.setArgName("column #"); options.addOption(chromosomeColumnOption); } final Option bpPositionColumnOption; { bpPositionColumnOption = new Option("poscol", "[optional] base-pair position column # (one-based index)"); bpPositionColumnOption.setRequired(false); bpPositionColumnOption.setArgs(1); bpPositionColumnOption.setArgName("column #"); options.addOption(bpPositionColumnOption); } final Option bpBuildIDOption; { bpBuildIDOption = new Option("bpbuild", "[optional] BP position build identifier (Eg: \"NCBI Build 37\")"); bpBuildIDOption.setRequired(false); bpBuildIDOption.setArgs(1); bpBuildIDOption.setArgName("build identifier"); options.addOption(bpBuildIDOption); } final Option firstGenoColumnOption; { firstGenoColumnOption = new Option("firstgenocol", "the first genotype column # (one-based index)"); firstGenoColumnOption.setRequired(true); firstGenoColumnOption.setArgs(1); firstGenoColumnOption.setArgName("column #"); options.addOption(firstGenoColumnOption); } final Option lastGenoColumnOption; { lastGenoColumnOption = new Option("lastgenocol", "[optional] the last genotype column # (one-based index). " + "The default behavior is to assume that all columns after " + "the first genotype column are genotype columns."); lastGenoColumnOption.setRequired(false); lastGenoColumnOption.setArgs(1); lastGenoColumnOption.setArgName("column #"); options.addOption(lastGenoColumnOption); } final Option outputFileOption; { outputFileOption = new Option("hdf5out", "the file to write HDF5 output to"); outputFileOption.setRequired(true); outputFileOption.setArgs(1); outputFileOption.setArgName("file name"); options.addOption(outputFileOption); } final Option sortOption; { sortOption = new Option("sort", "Sort the matrix by genomic position"); sortOption.setRequired(false); options.addOption(sortOption); } try { commandLine = parser.parse(options, args); // See if we just need to print the help options. if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("fftohdf5", options); } else { final String[] genoFileNames = commandLine.getOptionValues(genoFileOption.getOpt()); final String genoInFmtStr = commandLine.getOptionValue(genoInFormatOption.getOpt()); final String aColStr = commandLine.getOptionValue(aAlleleOption.getOpt()); final String bColStr = commandLine.getOptionValue(bAlleleOption.getOpt()); final String snpColStr = commandLine.getOptionValue(snpIdColumnOption.getOpt()); final String chrColStr = commandLine.getOptionValue(chromosomeColumnOption.getOpt()); final String bpPosStr = commandLine.getOptionValue(bpPositionColumnOption.getOpt()); final String bpBuildIDStr = commandLine.getOptionValue(bpBuildIDOption.getOpt()); final String fstGenoColStr = commandLine.getOptionValue(firstGenoColumnOption.getOpt()); final String lstGenoColStr = commandLine.getOptionValue(lastGenoColumnOption.getOpt()); final String outFileName = commandLine.getOptionValue(outputFileOption.getOpt()); final FlatFileFormat ffFormat; if (genoInFmtStr == null || genoInFmtStr.trim().toLowerCase().equals("csv")) { ffFormat = CommonFlatFileFormat.CSV_UNIX; } else if (genoInFmtStr.trim().toLowerCase().equals("tab")) { ffFormat = CommonFlatFileFormat.TAB_DELIMITED_UNIX; } else { throw new ParseException("geno file input format must be \"tab\" or \"csv\""); } final FlatFileReader[] genoFFRs = new FlatFileReader[genoFileNames.length]; for (int i = 0; i < genoFFRs.length; i++) { genoFFRs[i] = new FlatFileReader(new FileReader(genoFileNames[i]), ffFormat); } LOG.info("reading genotype flat files"); GenotypeCallMatrix genoMat = GenotypesFlatFile.readGenoCallMatrix(genoFFRs, argToIntMinus1(aColStr), argToIntMinus1(bColStr), argToIntMinus1(snpColStr), argToIntMinus1(chrColStr), argToIntMinus1(bpPosStr), bpBuildIDStr, argToIntMinus1(fstGenoColStr), argToInt(lstGenoColStr)); for (int i = 0; i < genoFFRs.length; i++) { genoFFRs[i].close(); } if (commandLine.hasOption(sortOption.getOpt())) { if (!genoMat.isSortedByPosition()) { LOG.info("sorting genotypes by position"); CallMatrixSorter.sortCallMatrix(genoMat); } } LOG.info("writing call matrix to " + outFileName); IHDF5Factory hdf5Fac = HDF5FactoryProvider.get(); File hdf5File = new File(outFileName); if (hdf5File.exists()) { if (!hdf5File.delete()) { throw new IOException("failed to overwrite \"" + outFileName + "\""); } } IHDF5Writer hdf5Writer = hdf5Fac.open(hdf5File); HDF5GenotypeCallMatrix hdf5GenoMat = new HDF5GenotypeCallMatrix(hdf5Writer); AbstractGenotypeCallMatrix.copyGenoMatrix(genoMat, hdf5GenoMat); hdf5Writer.close(); } } catch (ParseException ex) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("fftohdf5", options); System.exit(-1); } }
From source file:org.jax.bioinfdata.genocall.ConvertGenotypeHDF5ToFlatFileMain.java
/** * the main entry point/*from ww w . j a v a 2 s . co m*/ * @param args command line args * @throws IOException * @throws IllegalFormatException */ public static void main(String[] args) throws IllegalFormatException, IOException { // Deal with the options. CommandLineParser parser = new GnuParser(); Options options = new Options(); CommandLine commandLine = null; final Option helpOption; { helpOption = new Option("help", "Print this help and exit"); helpOption.setRequired(false); options.addOption(helpOption); } final Option genoFileOption; { genoFileOption = new Option("genooutfile", "the genotype output flat file"); genoFileOption.setRequired(true); genoFileOption.setArgs(1); genoFileOption.setArgName("file name"); options.addOption(genoFileOption); } final Option genoOutFormatOption; { genoOutFormatOption = new Option("genooutformat", "[optional] the format of the genotype file (must be \"csv\" or \"tab\")"); genoOutFormatOption.setRequired(false); genoOutFormatOption.setArgs(1); genoOutFormatOption.setArgName("csv or tab"); options.addOption(genoOutFormatOption); } final Option hdf5InputFileOption; { hdf5InputFileOption = new Option("hdf5in", "the file to read HDF5 input from"); hdf5InputFileOption.setRequired(true); hdf5InputFileOption.setArgs(1); hdf5InputFileOption.setArgName("file name"); options.addOption(hdf5InputFileOption); } try { commandLine = parser.parse(options, args); // See if we just need to print the help options. if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("hdf5toff", options); } else { final String genoFileName = commandLine.getOptionValue(genoFileOption.getOpt()); final String genoOutFmtStr = commandLine.getOptionValue(genoOutFormatOption.getOpt()); final String hdf5InFileName = commandLine.getOptionValue(hdf5InputFileOption.getOpt()); IHDF5Factory hdf5Fac = HDF5FactoryProvider.get(); IHDF5Reader hdf5Reader = hdf5Fac.openForReading(new File(hdf5InFileName)); HDF5GenotypeCallMatrix hdf5GenoMatrix = new HDF5GenotypeCallMatrix(hdf5Reader); final FlatFileWriter genoFFW; if (genoOutFmtStr == null || genoOutFmtStr.trim().toLowerCase().equals("csv")) { genoFFW = new FlatFileWriter(new FileWriter(genoFileName), CommonFlatFileFormat.CSV_UNIX); } else if (genoOutFmtStr.trim().toLowerCase().equals("tab")) { genoFFW = new FlatFileWriter(new FileWriter(genoFileName), CommonFlatFileFormat.TAB_DELIMITED_UNIX); } else { throw new ParseException("geno file input format must be \"tab\" or \"csv\""); } GenotypesFlatFile.writeGenoCallMatrix(hdf5GenoMatrix, genoFFW); hdf5Reader.close(); genoFFW.close(); } } catch (ParseException ex) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("hdf5toff", options); System.exit(-1); } }
From source file:org.jax.bioinfdata.phylogeny.MaxKPhylogenyMain.java
/** * The main entry point//www. j a v a 2 s . c o m * @param args function arguments * @throws IOException if we have a problem reading/writing data * @throws NoValidPhylogenyException */ public static void main(String[] args) throws IOException, NoValidPhylogenyException { // Deal with the options. CommandLineParser parser = new GnuParser(); Options options = new Options(); CommandLine commandLine = null; final Option helpOption; { helpOption = new Option("help", "Print this help and exit"); helpOption.setRequired(false); options.addOption(helpOption); } final Option hdf5InputFileOption; { hdf5InputFileOption = new Option("hdf5in", "the HDF5 input file containing the genotype matrix"); hdf5InputFileOption.setRequired(true); hdf5InputFileOption.setArgs(1); hdf5InputFileOption.setArgName("file name"); options.addOption(hdf5InputFileOption); } final Option csvOutputFileOption; { csvOutputFileOption = new Option("csvout", "the CSV output file with max-k intervals and their " + "corresponding perfect phylogenies in newick format"); csvOutputFileOption.setRequired(true); csvOutputFileOption.setArgs(1); csvOutputFileOption.setArgName("file name"); options.addOption(csvOutputFileOption); } try { commandLine = parser.parse(options, args); // See if we just need to print the help options. if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("maxkphylo", options); } else { final String hdf5InFileName = commandLine.getOptionValue(hdf5InputFileOption.getOpt()); final String csvOutFileName = commandLine.getOptionValue(csvOutputFileOption.getOpt()); IHDF5Factory hdf5Fac = HDF5FactoryProvider.get(); IHDF5Reader hdf5Reader = hdf5Fac.openForReading(new File(hdf5InFileName)); HDF5GenotypeCallMatrix hdf5GenoMatrix = new HDF5GenotypeCallMatrix(hdf5Reader); // write the header row FlatFileWriter ffw = new FlatFileWriter( //new OutputStreamWriter(System.out), new FileWriter(csvOutFileName), CommonFlatFileFormat.CSV_UNIX); ffw.writeRow( new String[] { "chrID", "bpStartPosition", "bpEndPosition", "newickPerfectPhylogeny" }); // scan the chromosomes in order for (AbstractGenotypeCallMatrix currChrView : hdf5GenoMatrix.getChromosomeViews()) { List<IndexedSnpInterval> maxKScanResult = IntervalScanner.maxKScan(currChrView); List<PhylogenyTreeNode> phyloScanResult = PhylogenyScanner.inferPerfectPhylogenies(currChrView, maxKScanResult); assert maxKScanResult.size() == phyloScanResult.size(); String[] chrIDArray = currChrView.getChrIDs(); long[] posArray = currChrView.getBpPositions(); for (int i = 0; i < maxKScanResult.size(); i++) { IndexedSnpInterval isi = maxKScanResult.get(i); PhylogenyTreeNode phylo = phyloScanResult.get(i); ffw.writeRow(new String[] { chrIDArray[isi.getStartIndex()], Long.toString(posArray[isi.getStartIndex()]), Long.toString(posArray[isi.getEndIndex()]), phylo.toNewickFormat() }); } } ffw.flush(); ffw.close(); } } catch (ParseException ex) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("maxkphylo", options); System.exit(-1); } }
From source file:org.jax.bioinfdata.phylogeny.PhylogenySdpMain.java
/** * Main entry point for reading in newick trees at specified intervals and * turning them into SDPs//from w ww . j a va 2 s . c om * @param args * @throws IOException * @throws IllegalFormatException */ public static void main(String[] args) throws IOException, IllegalFormatException { // Deal with the options. CommandLineParser parser = new GnuParser(); Options options = new Options(); CommandLine commandLine = null; final Option helpOption; { helpOption = new Option("help", "Print this help and exit"); helpOption.setRequired(false); options.addOption(helpOption); } final Option inputFileOption; { inputFileOption = new Option("phylocsvin", "This is the input " + "CSV file which must have a header row allong with " + "the following four columns in order: chromosome ID, " + "interval start in base pairs, interval end in base pairs, " + "newick formatted phylogeny tree"); inputFileOption.setRequired(true); inputFileOption.setArgs(1); inputFileOption.setArgName("file name"); options.addOption(inputFileOption); } final Option minMinorStrainCountOption; { minMinorStrainCountOption = new Option("minorallelecountthreshold", "this option specifies the minimum minor allele count that " + "an SDP must have. All SDPs that fall below this threshold " + "will be filtered from the output."); minMinorStrainCountOption.setRequired(true); minMinorStrainCountOption.setArgs(1); minMinorStrainCountOption.setArgName("min SDP count"); options.addOption(minMinorStrainCountOption); } final Option outputFileOption; { outputFileOption = new Option("sdpcsvout", "the output CSV file"); outputFileOption.setRequired(true); outputFileOption.setArgs(1); outputFileOption.setArgName("file name"); options.addOption(outputFileOption); } try { commandLine = parser.parse(options, args); // See if we just need to print the help options. if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("phylosdp", options); } else { final String inFileName = commandLine.getOptionValue(inputFileOption.getOpt()); final String outFileName = commandLine.getOptionValue(outputFileOption.getOpt()); final String minMinorStrainCountStr = commandLine .getOptionValue(minMinorStrainCountOption.getOpt()); final int minMinorStrainCount = Integer.parseInt(minMinorStrainCountStr); FlatFileReader ffr = new FlatFileReader(new FileReader(inFileName), CommonFlatFileFormat.CSV_UNIX); String[] inHeader = ffr.readRow(); if (inHeader == null) { throw new IOException("the input file is empty"); } else if (inHeader.length != 4) { throw new IllegalFormatException( "expected the input to have 4 columns but found " + inHeader.length + " columns"); } else { Map<BitSet, List<GenomeInterval>> sdpMap = new HashMap<BitSet, List<GenomeInterval>>(); ArrayList<String> strainNames = null; String[] outHeader = null; String[] currInRow = null; while ((currInRow = ffr.readRow()) != null) { GenomeInterval genoInt = new GenomeInterval(currInRow[0], Long.parseLong(currInRow[1]), Long.parseLong(currInRow[2])); PhylogenyTreeNode phylo = PhylogenyTreeNode.fromNewickFormat(currInRow[3]); if (strainNames == null) { strainNames = new ArrayList<String>(phylo.getAllStrains()); Collections.sort(strainNames); outHeader = new String[strainNames.size() + 1]; for (int i = 0; i < strainNames.size(); i++) { outHeader[i] = strainNames.get(i); } outHeader[outHeader.length - 1] = "genomicIntervals"; } Set<BitSet> phyloSdps = phylo.sdps(strainNames, minMinorStrainCount); for (BitSet sdp : phyloSdps) { List<GenomeInterval> sdpIntervals = sdpMap.get(sdp); if (sdpIntervals == null) { sdpIntervals = new ArrayList<GenomeInterval>(); sdpMap.put(sdp, sdpIntervals); } sdpIntervals.add(genoInt); } } if (strainNames == null) { System.out.println("The input file " + inFileName + " appears empty"); System.exit(-1); } else { // write the header row FlatFileWriter ffw = new FlatFileWriter( //new OutputStreamWriter(System.out), new FileWriter(outFileName), CommonFlatFileFormat.CSV_UNIX); ffw.writeRow(outHeader); int strainCount = strainNames.size(); String[] currOutRow = new String[strainNames.size() + 1]; for (Map.Entry<BitSet, List<GenomeInterval>> entry : sdpMap.entrySet()) { BitSet currSDP = entry.getKey(); for (int i = 0; i < strainCount; i++) { currOutRow[i] = currSDP.get(i) ? "1" : "0"; } StringBuilder sb = new StringBuilder(); List<GenomeInterval> intervals = entry.getValue(); int intervalCount = intervals.size(); for (int i = 0; i < intervalCount; i++) { GenomeInterval interval = intervals.get(i); sb.append(interval.getChrId()); sb.append(';'); sb.append(interval.getStartPositionBp()); sb.append(';'); sb.append(interval.getEndPositionBp()); if (i < intervalCount - 1) { sb.append('|'); } } currOutRow[strainCount] = sb.toString(); ffw.writeRow(currOutRow); } ffw.flush(); } } } } catch (ParseException ex) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("phylosdp", options); System.exit(-1); } }