Example usage for org.apache.commons.cli CommandLine getArgs

List of usage examples for org.apache.commons.cli CommandLine getArgs

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getArgs.

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;
    try {//from ww w  . j  ava 2s  .c  o m
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

From source file:com.genentech.chemistry.openEye.apps.SdfRMSDSphereExclusion.java

/**
 * @param args/* ww  w  . j  av a2s. co  m*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_REFFILE, true,
            "Reference file of molecules which define pre-existign exclusion spheres.");
    options.addOption(opt);

    opt = new Option(OPT_RADIUS, true, "Radius of exclusion spehre in A2.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_GROUPBY, true,
            "Group by fieldname, run sphere exclusion for consecutive groups of records with same value for this field.");
    options.addOption(opt);

    opt = new Option(OPT_DONotOpt, false,
            "If specified the RMSD is computed without trying to optimize the alignment.");
    options.addOption(opt);

    opt = new Option(OPT_PRINT_All, false, "print all molecule, check includeIdx tag");
    options.addOption(opt);

    opt = new Option(OPT_MIRROR, false, "For non-chiral molecules also try mirror image");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String refFile = cmd.getOptionValue(OPT_REFFILE);
    String groupBy = cmd.getOptionValue(OPT_GROUPBY);
    boolean doOptimize = !cmd.hasOption(OPT_DONotOpt);
    double radius = Double.parseDouble(cmd.getOptionValue(OPT_RADIUS));
    boolean printAll = cmd.hasOption(OPT_PRINT_All);
    boolean doMirror = cmd.hasOption(OPT_MIRROR);

    SdfRMSDSphereExclusion sphereExclusion = new SdfRMSDSphereExclusion(refFile, outFile, radius, printAll,
            doMirror, doOptimize, groupBy);

    sphereExclusion.run(inFile);
    sphereExclusion.close();
}

From source file:apps.quantification.LearnQuantificationSVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnQuantificationSVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_learn> <path to svm_perf_classify> <trainingIndexDirectory> <outputDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("f");
    OptionBuilder.withDescription("Number of folds");
    OptionBuilder.withLongOpt("f");
    OptionBuilder.isRequired(true);//from w  ww.  ja  va  2 s  .com
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_perf (default 0.01)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("l");
    OptionBuilder.withDescription("The loss function to optimize (default 2):\n"
            + "               0  Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n"
            + "               1  F1: 100 minus the F1-score in percent.\n"
            + "               2  Errorrate: Percentage of errors in prediction vector.\n"
            + "               3  Prec/Rec Breakeven: 100 minus PRBEP in percent.\n"
            + "               4  Prec@p: 100 minus precision at p in percent.\n"
            + "               5  Rec@p: 100 minus recall at p in percent.\n"
            + "               10  ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea).");
    OptionBuilder.withLongOpt("l");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("w");
    OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n"
            + "               0: n-slack algorithm described in [2]\n"
            + "               1: n-slack algorithm with shrinking heuristic\n"
            + "               2: 1-slack algorithm (primal) described in [5]\n"
            + "               3: 1-slack algorithm (dual) described in [5]\n"
            + "               4: 1-slack algorithm (dual) with constraint cache [5]\n"
            + "               9: custom algorithm in svm_struct_learn_custom.c");
    OptionBuilder.withLongOpt("w");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("p");
    OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)");
    OptionBuilder.withLongOpt("p");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;
    SvmPerfClassifierCustomizer classificationCustomizer = null;

    int folds = -1;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);
        classificationCustomizer = new SvmPerfClassifierCustomizer(remainingArgs[1]);

        folds = Integer.parseInt(line.getOptionValue("f"));

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("w"))
            classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w")));

        if (line.hasOption("p"))
            classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p")));

        if (line.hasOption("l"))
            classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l")));

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmPerfOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t")) {
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));
            classificationCustomizer.setTempPath(line.getOptionValue("t"));
        }

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    assert (classificationLearnerCustomizer != null);

    if (remainingArgs.length != 4) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[2];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String outputPath = remainingArgs[3];

    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false);
    fssm.open();

    IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers");

    IOperationStatusListener status = new IOperationStatusListener() {

        @Override
        public void operationStatus(double percentage) {
            progressBar.signal((int) percentage);
        }
    };

    QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner,
            classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY,
            new LogisticFunction(), status);

    IQuantifier[] quantifiers = quantificationLearner.learn(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath());
    IDataManager classifierDataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify"));
    String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-"
            + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL();
    if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5)
        description += "_P-" + classificationLearnerCustomizer.getP();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();
    String quantifierPrefix = indexName + "_Quantifier-" + folds + description;

    FileSystemStorageManager fssmo = new FileSystemStorageManager(
            outputPath + File.separatorChar + quantifierPrefix, true);
    fssmo.open();
    QuantificationLearner.write(quantifiers, fssmo, classifierDataManager);
    fssmo.close();

    BufferedWriter bfs = new BufferedWriter(
            new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs();

    ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = training.getCategoryDB().getCategoryName(cat);
        ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t"
                + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t"
                + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n";
        bfs.write(line);
        line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp()
                + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn()
                + "\t" + scaledTPR + "\t" + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:com.genentech.chemistry.openEye.apps.SdfRMSDNNFinder.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);//ww  w.  j  a  va2s. c o m
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_REFFILE, true, "Reference file containing poses from reference docking run. " + "If "
            + OPT_REFFILE + " not specified, program uses the input file " + "(internal NN analysis)");
    options.addOption(opt);

    opt = new Option(OPT_MOLIdTag, true, "Name of the field containing the molecule identifier. "
            + " Assumption: Ref file uses the same field name.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_DONotOpt, false,
            "If specified the RMSD is computed without trying to optimize the alignment.");
    options.addOption(opt);

    opt = new Option(OPT_MIRROR, false, "For non-chiral molecules also try mirror image");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();
    if (args.length != 0) {
        ; //error message
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    String refFile = cmd.getOptionValue(OPT_REFFILE);
    boolean noRefFile = false;
    if (refFile == null) {
        if (inFile.startsWith("."))
            inFile = writeRefMolPosesToTempFile(inFile);
        refFile = inFile;
        noRefFile = true;
    }

    String molIdTag = cmd.getOptionValue(OPT_MOLIdTag);
    boolean doOptimize = !cmd.hasOption(OPT_DONotOpt);
    boolean doMirror = cmd.hasOption(OPT_MIRROR);

    SdfRMSDNNFinder nnFinder = new SdfRMSDNNFinder(refFile, outFile, molIdTag, doMirror, doOptimize, noRefFile);

    nnFinder.run(inFile);
    nnFinder.close();
}

From source file:edu.msu.cme.rdp.kmer.cli.KmerCoverage.java

/**
 * This program maps the kmers from reads to kmers on each contig,
 * writes the mean, median coverage of each contig to a file
 * writes the kmer abundance to a file/*from w  w  w.  j  a v  a2 s  . c  o m*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, InterruptedException {
    int kmerSize = 45;
    final int maxThreads;
    final int maxTasks = 1000;
    final PrintStream match_reads_out;
    try {
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();
        if (args.length < 5) {
            throw new Exception("Unexpected number of arguments");
        }
        kmerSize = Integer.parseInt(args[0]);
        if (kmerSize > Kmer.max_nucl_kmer_size) {
            throw new Exception("kmerSize should be less than " + Kmer.max_nucl_kmer_size);
        }
        if (cmdLine.hasOption("match_reads_out")) {
            match_reads_out = new PrintStream(cmdLine.getOptionValue("match_reads_out"));
        } else {
            match_reads_out = null;
        }
        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
            if (maxThreads >= Runtime.getRuntime().availableProcessors()) {
                System.err.println(" Runtime.getRuntime().availableProcessors() "
                        + Runtime.getRuntime().availableProcessors());
            }

        } else {
            maxThreads = 1;
        }

        final KmerCoverage kmerCoverage = new KmerCoverage(kmerSize, new SequenceReader(new File(args[1])));

        final AtomicInteger outstandingTasks = new AtomicInteger();
        ExecutorService service = Executors.newFixedThreadPool(maxThreads);

        Sequence seq;

        // parse one file at a time
        for (int index = 4; index < args.length; index++) {

            SequenceReader reader = new SequenceReader(new File(args[index]));
            while ((seq = reader.readNextSequence()) != null) {
                if (seq.getSeqString().length() < kmerSize) {
                    continue;
                }
                final Sequence threadSeq = seq;

                Runnable r = new Runnable() {

                    public void run() {
                        try {
                            kmerCoverage.processReads(threadSeq, match_reads_out);
                            outstandingTasks.decrementAndGet();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };

                outstandingTasks.incrementAndGet();
                service.submit(r);

                while (outstandingTasks.get() >= maxTasks)
                    ;

            }
            reader.close();
        }
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

        kmerCoverage.printCovereage(new FileOutputStream(new File(args[2])),
                new FileOutputStream(new File(args[3])));
        if (match_reads_out != null) {
            match_reads_out.close();
        }
    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerCoverage <kmerSize> <query_file> <coverage_out> <abundance_out> <reads_file> <reads_file>...\nmaximum kmerSize "
                        + Kmer.max_nucl_kmer_size,
                options);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.quanticate.opensource.pdftkbox.PDFtkBox.java

public static void main(String[] args) throws Exception {
    // For printing help
    Options optsHelp = new Options();
    optsHelp.addOption(Option.builder("help").required().desc("print this message").build());

    // Normal-style import/export
    Options optsNormal = new Options();
    OptionGroup normal = new OptionGroup();
    Option optExport = Option.builder("export").required().hasArg().desc("export bookmarks from pdf")
            .argName("source-pdf").build();
    normal.addOption(optExport);/*from ww w .  jav a 2 s .c o m*/
    Option optImport = Option.builder("import").required().hasArg().desc("import bookmarks into pdf")
            .argName("source-pdf").build();
    normal.addOption(optImport);
    optsNormal.addOptionGroup(normal);
    Option optBookmarks = Option.builder("bookmarks").hasArg().desc("bookmarks definition file")
            .argName("bookmarks").build();
    optsNormal.addOption(optBookmarks);
    Option optOutput = Option.builder("output").hasArg().desc("output to new pdf").argName("pdf").build();
    optsNormal.addOption(optOutput);

    // PDFtk style options
    Options optsPDFtk = new Options();
    OptionGroup pdftk = new OptionGroup();
    Option optDumpData = Option.builder("dump_data").required().desc("dump bookmarks from pdf").build();
    pdftk.addOption(optDumpData);
    Option optUpdateInfo = Option.builder("update_info").required().hasArg().desc("update bookmarks in pdf")
            .argName("bookmarks").build();
    pdftk.addOption(optUpdateInfo);
    optsPDFtk.addOptionGroup(pdftk);
    optsPDFtk.addOption(optOutput);

    // What are we doing?
    CommandLineParser parser = new DefaultParser();

    // Did they want help?
    try {
        parser.parse(optsHelp, args);

        // If we get here, they asked for help
        doPrintHelp(optsHelp, optsNormal, optsPDFtk);
        return;
    } catch (ParseException pe) {
    }

    // Normal-style import/export?
    try {
        CommandLine line = parser.parse(optsNormal, args);

        // Export
        if (line.hasOption(optExport.getOpt())) {
            doExport(line.getOptionValue(optExport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getArgs());
            return;
        }
        // Import with explicit output filename
        if (line.hasOption(optImport.getOpt()) && line.hasOption(optOutput.getOpt())) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getOptionValue(optOutput.getOpt()), null);
            return;
        }
        // Import with implicit output filename
        if (line.hasOption(optImport.getOpt()) && line.getArgs().length > 0) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), null,
                    line.getArgs());
            return;
        }
    } catch (ParseException pe) {
    }

    // PDFtk-style
    if (args.length > 1) {
        // Nobble things for PDFtk-style options and Commons CLI
        for (int i = 1; i < args.length; i++) {
            for (Option opt : optsPDFtk.getOptions()) {
                if (args[i].equals(opt.getOpt())) {
                    args[i] = "-" + args[i];
                }
            }
        }
        try {
            // Input file comes first, then arguments
            String input = args[0];
            String[] pargs = new String[args.length - 1];
            System.arraycopy(args, 1, pargs, 0, pargs.length);

            // Parse what's left and check
            CommandLine line = parser.parse(optsPDFtk, pargs);

            if (line.hasOption(optDumpData.getOpt())) {
                doExport(input, line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
            if (line.hasOption(optUpdateInfo.getOpt())) {
                doImport(input, line.getOptionValue(optUpdateInfo.getOpt()),
                        line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
        } catch (ParseException pe) {
        }
    }

    // If in doubt, print help
    doPrintHelp(optsHelp, optsNormal, optsPDFtk);
}

From source file:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

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

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {/*www.  j a v  a 2 s  .  co m*/
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:com.atilika.kuromoji.benchmark.Benchmark.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("h", "help", false, "Display this help message and exit");
    options.addOption("t", "tokenizer", true, "Tokenizer class to use");
    options.addOption("u", "user-dictionary", true, "Optional user dictionary filename to use");
    options.addOption("c", "count", true, "Number of documents ot process (Default: 0, which means all");
    //        options.addOption("v", "validation-input", true, "Validation filename");
    options.addOption("o", "output", true,
            "Output filename.  If unset, segmentation is done, but the result is discarded");
    options.addOption("n", "n-best", true, "The number of tokenizations to get per input");
    options.addOption(null, "benchmark-output", true, "Benchmark metrics output filename filename");

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;
    try {/*from w ww . j a  v  a 2s.  c  o m*/
        commandLine = parser.parse(options, args);

        args = commandLine.getArgs();

        if (args.length != 1) {
            throw new ParseException("A single input filename is required");
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
    }

    String inputFilename = args[0];

    String className = commandLine.getOptionValue("t", "com.atilika.kuromoji.ipadic.Tokenizer");

    className += "$Builder";

    String userDictionaryFilename = commandLine.getOptionValue("u");

    TokenizerBase tokenizer = null;
    try {
        Class clazz = Class.forName(className);

        // Make builder
        Object builder = clazz.getDeclaredConstructor(null).newInstance();

        // Set user dictionary
        if (userDictionaryFilename != null) {
            builder.getClass().getMethod("userDictionary", String.class).invoke(builder,
                    userDictionaryFilename);
        }

        // Build tokenizer
        tokenizer = (TokenizerBase) builder.getClass().getMethod("build").invoke(builder);

    } catch (Exception e) {
        System.err.println("Could not create tokenizer. Got " + e);
        e.printStackTrace();
        System.exit(1);
    }

    File outputFile = null;
    String outputFilename = commandLine.getOptionValue("o");

    if (outputFilename != null) {
        outputFile = new File(outputFilename);
    }

    File statisticsFile = null;
    String statisticsFilename = commandLine.getOptionValue("benchmark-output");

    if (statisticsFilename != null) {
        statisticsFile = new File(statisticsFilename);
    }

    long count = Long.parseLong(commandLine.getOptionValue("c", "0"));

    int nbest = Integer.parseInt(commandLine.getOptionValue("n", "1"));

    Benchmark benchmark = new Builder().tokenizer(tokenizer).inputFile(new File(inputFilename))
            .outputFile(outputFile).outputStatisticsFile(statisticsFile).setOutputStatistiscs(true).count(count)
            .nbest(nbest).build();

    benchmark.benchmark();
}

From source file:com.genentech.chemistry.openEye.apps.SDFTorsionScanner.java

/**
 * @param args/*from ww w.  j  a  v a 2s . c  o  m*/
 */
public static void main(String... args) throws IOException {
    // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "Output filename.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_STARTTorsion, true,
            "The torsion in your inMol will be rotated by this value for the first job");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONIncrement, true, "Incremnt each subsequent conformation by this step size");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NSTEPS, true, "Number of conformations to create");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_BONDFILE, true, "The file containing the bond atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MINIMIZE, false,
            "Minimize conformer at each step using MMFFs.  If maxConfsPerStep is > 1, "
                    + "all confs will be mimimized and the lowest E will be output.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_CONSTRIANT, true,
            "One of strong (90), medium (45), weak(20), none or a floating point number"
                    + " to specify the tethered constraint strength for -minimize (def=strong)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MAXCONFS_PER_STEP, true,
            "While holding the torsion fixed, maximum number of conformations of free atoms to generat.  default=1");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_COREFILE, true, "Outputfile to store guessed core.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONS_ATOM_TAG, true,
            "Name of sdf tag which will contain the indices of atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    String bondFile = cmd.getOptionValue(OPT_BONDFILE);
    String coreFilename = cmd.getOptionValue(OPT_COREFILE);
    String torsionAtomsTag = cmd.getOptionValue(OPT_TORSIONS_ATOM_TAG);

    int nSteps = Integer.parseInt(cmd.getOptionValue(OPT_NSTEPS));
    int nStartTor = Integer.parseInt(cmd.getOptionValue(OPT_STARTTorsion));
    int nTorIncr = Integer.parseInt(cmd.getOptionValue(OPT_TORSIONIncrement));

    int nMaxConfsPerStep = 1;
    if (cmd.hasOption(OPT_MAXCONFS_PER_STEP)) {
        nMaxConfsPerStep = Integer.parseInt(cmd.getOptionValue(OPT_MAXCONFS_PER_STEP));
    }

    String constraintStrength = cmd.getOptionValue(OPT_CONSTRIANT);

    boolean doMinimize = cmd.hasOption(OPT_MINIMIZE);

    SDFTorsionScanner torGenerator = new SDFTorsionScanner(bondFile, coreFilename, torsionAtomsTag, nSteps,
            nStartTor, nTorIncr, nMaxConfsPerStep, doMinimize, constraintStrength);

    torGenerator.run(inFile, outFile, coreFilename);
}

From source file:com.genentech.chemistry.tool.align.SDFAlign.java

public static void main(String... args) {
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);//from   w ww.  ja  v a 2s  . c o m
    options.addOption(opt);

    opt = new Option("out", true, "output file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("method", true, "fss|sss|MCS|clique (default mcs).");
    options.addOption(opt);

    opt = new Option("ref", true,
            "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported");
    options.addOption(opt);

    opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image.");
    options.addOption(opt);

    opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output.");
    options.addOption(opt);

    opt = new Option("atomMatch", true,
            "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n"
                    + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n"
                    + "Queryfeatures are considered only if default is used.");
    options.addOption(opt);

    opt = new Option("bondMatch", true,
            "Sequence of none|default specifing how bonds are matched cf. oe document.");
    options.addOption(opt);

    opt = new Option("keepCoreHydrogens", false,
            "If not specified the hydrigen atoms are removed from the core.");
    options.addOption(opt);

    opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd.");
    options.addOption(opt);

    opt = new Option("doNotOptimize", false,
            "If specified the RMSD is computed without moving optimizing the overlay.");
    options.addOption(opt);

    opt = new Option("quiet", false, "Reduced warining messages");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }

    if (cmd.getArgs().length > 0)
        exitWithHelp("To many arguments", options);

    // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms
    int atomExpr = OEExprOpts.DefaultAtoms;
    int bondExpr = OEExprOpts.DefaultBonds;

    String atomMatch = cmd.getOptionValue("atomMatch");
    if (atomMatch == null)
        atomMatch = "";
    atomMatch = '|' + atomMatch.toLowerCase() + '|';

    String bondMatch = cmd.getOptionValue("bondMatch");
    if (bondMatch == null)
        bondMatch = "";
    bondMatch = '|' + bondMatch.toLowerCase() + '|';

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");
    String method = cmd.getOptionValue("method");
    String rmsdTag = cmd.getOptionValue("rmsdTag");
    String oMol = cmd.getOptionValue("outputMol");
    boolean doMirror = cmd.hasOption("mirror");
    boolean doOptimize = !cmd.hasOption("doNotOptimize");
    boolean quiet = cmd.hasOption("quiet");

    OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase());

    if (atomMatch.startsWith("|none"))
        atomExpr = 0;
    if (atomMatch.contains("|hcount|"))
        atomExpr |= OEExprOpts.HCount;
    if (atomMatch.contains("|noAromatic|"))
        atomExpr &= (~OEExprOpts.Aromaticity);

    if (bondMatch.startsWith("|none"))
        bondExpr = 0;

    ArrayList<OEMol> refmols = new ArrayList<OEMol>();
    if (refFile != null) {
        oemolistream reffs = new oemolistream(refFile);
        if (!is3DFormat(reffs.GetFormat()))
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        reffs.SetFormat(OEFormat.MDL);

        int aromodel = OEIFlavor.Generic.OEAroModelOpenEye;
        int qflavor = reffs.GetFlavor(reffs.GetFormat());
        reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel));

        OEMol rmol = new OEMol();
        while (oechem.OEReadMDLQueryFile(reffs, rmol)) {
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);
            refmols.add(rmol);
            rmol = new OEMol();
        }
        rmol.delete();

        if (refmols.size() == 0)
            throw new Error("reference file had no entries");

        reffs.close();
    }

    oemolistream fitfs = new oemolistream(inFile);
    if (!is3DFormat(fitfs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");

    oemolostream ofs = new oemolostream(outFile);
    if (!is3DFormat(ofs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");

    AlignInterface aligner = null;
    OEGraphMol fitmol = new OEGraphMol();

    if (oechem.OEReadMolecule(fitfs, fitmol)) {
        if (refmols.size() == 0) {
            OEMol rmol = new OEMol(fitmol);
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);

            refmols.add(rmol);
        }

        if ("sss".equalsIgnoreCase(method)) {
            aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("clique".equalsIgnoreCase(method)) {
            aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("fss".equalsIgnoreCase(method)) {
            if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch"))
                exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options);
            aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror);

        } else {
            aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);
        }

        do {
            aligner.align(fitmol);
            oechem.OEWriteMolecule(ofs, fitmol);
        } while (oechem.OEReadMolecule(fitfs, fitmol));

    }

    fitmol.delete();
    if (aligner != null)
        aligner.close();
    for (OEMolBase mol : refmols)
        mol.delete();
    fitfs.close();
    ofs.close();
}