List of usage examples for org.apache.commons.cli OptionBuilder hasArg
public static OptionBuilder hasArg()
From source file:apps.classification.LearnSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf> <trainingIndexDirectory>"; Options options = new Options(); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false);/* w ww . j av a 2 s . c om*/ 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; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); 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")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 2) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); // LEARNING SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); IIndex training = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); IClassifier classifier = classificationLearner.build(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); SvmPerfDataManager dataManager = 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(); storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); dataManager.write(storageManager, indexName + description, classifier); storageManager.close(); }
From source file:name.wagners.bpp.Bpp.java
public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations") .withDescription("Number of generations [default: 50]").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate") .withDescription("Mutation rate [default: 1]").create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop") .withDescription("Mutation propability [default: 0.5]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg") .withDescription("Recombination algorithm [default: a]").create()); // options.addOption(OptionBuilder // .hasArg()/*from w w w . j ava2 s. c om*/ // .withArgName("int") // .withLongOpt("recombrate") // .withDescription("Recombination rate [default: 1]") // .create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop") .withDescription("Recombination propability [default: 0.8]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg") .withDescription("Selection algorithm [default: a]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").create()); options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism") .withDescription("Enable Elitism [default: 1]").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("filename") // .isRequired() .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]") .create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(0); } if (line.hasOption("version")) { log.info("Bpp 0.1 (c) 2007 by Daniel Wagner"); } if (line.hasOption("datafile")) { fname = line.getOptionValue("datafile"); } if (line.hasOption("elitism")) { elitism = Boolean.parseBoolean(line.getOptionValue("elitism")); } if (line.hasOption("generations")) { gen = Integer.parseInt(line.getOptionValue("generations")); } if (line.hasOption("mutprop")) { mp = Double.parseDouble(line.getOptionValue("mutprop")); } if (line.hasOption("mutrate")) { mr = Integer.parseInt(line.getOptionValue("mutrate")); } if (line.hasOption("populationsize")) { ps = Integer.parseInt(line.getOptionValue("populationsize")); } if (line.hasOption("recombalg")) { sel = line.getOptionValue("recombalg").charAt(0); } if (line.hasOption("recombprop")) { rp = Double.parseDouble(line.getOptionValue("recombprop")); } if (line.hasOption("selalg")) { selalg = line.getOptionValue("selalg").charAt(0); } if (line.hasOption("selectionpressure")) { sp = Integer.parseInt(line.getOptionValue("selectionpressure")); } } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); log.info(" Datafile: " + fname); log.info(" Generations: " + gen); log.info(" Population size: " + ps); log.info(" Elitism: " + elitism); log.info(" Mutation propapility: " + mp); log.info(" Mutation rate: " + mr); log.info(" Recombination algorithm " + (char) sel); log.info(" Recombination propapility: " + rp); log.info(" Selection pressure: " + sp); // Daten laden instance = new Instance(); instance.load(fname); Evolutionizer e = new Evolutionizer(instance); e.run(); }
From source file:edu.harvard.med.screensaver.io.Spammer.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { CommandLineApplication app = new CommandLineApplication(args); String[] option = MAIL_RECIPIENT_LIST_OPTION; app.addCommandLineOption(OptionBuilder.withType(Integer.class).hasArg().isRequired() .withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = MAIL_CC_LIST_OPTION;/*from w w w . j a v a 2s. co m*/ app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_REPLYTO_LIST_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_MESSAGE_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_FILE_ATTACHMENT; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_SUBJECT_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_SERVER_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USERNAME_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USER_PASSWORD_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_FROM_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USE_SMTPS; app.addCommandLineOption( OptionBuilder.withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); app.processOptions(true, true); String message = app.getCommandLineOptionValue(MAIL_MESSAGE_OPTION[SHORT_OPTION_INDEX]); File attachedFile = null; if (app.isCommandLineFlagSet(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX])) { attachedFile = new File(app.getCommandLineOptionValue(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX])); if (!attachedFile.exists()) { log.error("Specified file does not exist: " + attachedFile.getCanonicalPath()); System.exit(1); } } String subject = app.getCommandLineOptionValue(MAIL_SUBJECT_OPTION[SHORT_OPTION_INDEX]); String recipientlist = app.getCommandLineOptionValue(MAIL_RECIPIENT_LIST_OPTION[SHORT_OPTION_INDEX]); String[] recipients = recipientlist.split(DELIMITER); String[] ccrecipients = null; if (app.isCommandLineFlagSet(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX])) { String cclist = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]); ccrecipients = cclist.split(DELIMITER); } String replytos = null; if (app.isCommandLineFlagSet(MAIL_REPLYTO_LIST_OPTION[SHORT_OPTION_INDEX])) { replytos = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]); } String mailHost = app.getCommandLineOptionValue(MAIL_SERVER_OPTION[SHORT_OPTION_INDEX]); String username = app.getCommandLineOptionValue(MAIL_USERNAME_OPTION[SHORT_OPTION_INDEX]); String password = app.getCommandLineOptionValue(MAIL_USER_PASSWORD_OPTION[SHORT_OPTION_INDEX]); boolean useSmtps = app.isCommandLineFlagSet(MAIL_USE_SMTPS[SHORT_OPTION_INDEX]); String mailFrom = username; if (app.isCommandLineFlagSet(MAIL_FROM_OPTION[SHORT_OPTION_INDEX])) { mailFrom = app.getCommandLineOptionValue(MAIL_FROM_OPTION[SHORT_OPTION_INDEX]); } SmtpEmailService service = new SmtpEmailService(mailHost, username, replytos, password, useSmtps); service.send(subject, message, mailFrom, recipients, ccrecipients, attachedFile); }
From source file:edu.harvard.med.screensaver.io.screenresults.ScreenResultImporter.java
@SuppressWarnings("static-access") public static void main(String[] args) { ScreenResultImporter app = new ScreenResultImporter(args); app.addCommandLineOption(OptionBuilder.hasArg().withArgName("screen facility ID").isRequired() .withDescription(//from w w w . jav a 2 s . c o m "the facility-assigned ID of the screen for which the screen result is being parsed") .withLongOpt(SCREEN_OPTION[LONG_OPTION]).create(SCREEN_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName("file").isRequired() .withDescription("the file location of the Excel workbook file holding the Screen Result metadata") .withLongOpt(INPUT_FILE_OPTION[LONG_OPTION]).create(INPUT_FILE_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName("comments").isRequired(false) .withDescription("comments to associate with the data loading activity") .withLongOpt(COMMENTS[LONG_OPTION]).create(COMMENTS[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.withDescription("The first plate number to parse/import").hasArg() .withArgName("#").withLongOpt(PLATE_NUMBER_START_OPTION[LONG_OPTION]) .create(PLATE_NUMBER_START_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.withDescription("The last plate number to parse/import").hasArg() .withArgName("#").withLongOpt(PLATE_NUMBER_END_OPTION[LONG_OPTION]) .create(PLATE_NUMBER_END_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder .withDescription("Import screen result into database if parsing is successful. " + "(By default, the parser only validates the input and then exits.)") .withLongOpt(IMPORT_OPTION[LONG_OPTION]).create(IMPORT_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.withDescription("Ignore any subsequent duplicates of a well") .isRequired(false).withLongOpt(IGNORE_DUPLICATE_ERRORS_OPTION[LONG_OPTION]) .create(IGNORE_DUPLICATE_ERRORS_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.withDescription( "Set the incremental flushing option; this is necessary for conserving memory in large imports (default=\"true\")") .isRequired(false).withArgName("value").withLongOpt(INCREMENTAL_FLUSH_OPTION[LONG_OPTION]) .create(INCREMENTAL_FLUSH_OPTION[SHORT_OPTION])); app.addCommandLineOption(OptionBuilder.withDescription(DELETE_EXISTING[2]).hasArg(false) .withLongOpt(DELETE_EXISTING[LONG_OPTION]).create(DELETE_EXISTING[SHORT_OPTION])); app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true); try { execute(app); } catch (ParseErrorsException e) { if (!e.getErrors().isEmpty()) { for (ParseError pe : e.getErrors()) { log.error("" + pe); } log.error("" + e.getErrors().size() + " errors found."); } System.exit(1); } catch (Exception e) { log.error("Failed to create the screen result", e); System.exit(1); } }
From source file:apps.quantification.LearnQuantificationSVMLight.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnQuantificationSVMLight.class.getName() + " [OPTIONS] <path to svm_light_learn> <path to svm_light_classify> <trainingIndexDirectory> <outputDirectory>"; Options options = new Options(); OptionBuilder.withArgName("f"); OptionBuilder.withDescription("Number of folds"); OptionBuilder.withLongOpt("f"); OptionBuilder.isRequired(true);//w ww. j ava 2 s . co m OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_light (default 1)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("k"); OptionBuilder.withDescription("Kernel type (default 0: linear, 1: polynomial, 2: RBF, 3: sigmoid)"); OptionBuilder.withLongOpt("k"); 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("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_light format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmLightLearnerCustomizer classificationLearnerCustomizer = null; SvmLightClassifierCustomizer classificationCustomizer = null; int folds = -1; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmLightLearnerCustomizer(remainingArgs[0]); classificationCustomizer = new SvmLightClassifierCustomizer(remainingArgs[1]); folds = Integer.parseInt(line.getOptionValue("f")); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("k")) { System.out.println("Kernel type: " + line.getOptionValue("k")); classificationLearnerCustomizer.setKernelType(Integer.parseInt(line.getOptionValue("k"))); } if (line.hasOption("v")) classificationLearnerCustomizer.printSvmLightOutput(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]; SvmLightLearner classificationLearner = new SvmLightLearner(); 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.getSvmLightLearnPath()); IDataManager classifierDataManager = new SvmLightDataManager(new SvmLightClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_light_classify")); String description = "_SVMLight_C-" + classificationLearnerCustomizer.getC() + "_K-" + classificationLearnerCustomizer.getKernelType(); 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: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);/* w w w .j ava 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:edu.harvard.med.iccbl.screensaver.io.users.UserAgreementExpirationUpdater.java
@SuppressWarnings("static-access") public static void main(String[] args) { final UserAgreementExpirationUpdater app = new UserAgreementExpirationUpdater(args); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(SCREEN_TYPE_OPTION[ARG_INDEX]) .withDescription(SCREEN_TYPE_OPTION[DESCRIPTION_INDEX]) .withLongOpt(SCREEN_TYPE_OPTION[LONG_OPTION_INDEX]).create(SCREEN_TYPE_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(NOTIFY_DAYS_AHEAD_OPTION[ARG_INDEX]) .withDescription(NOTIFY_DAYS_AHEAD_OPTION[DESCRIPTION_INDEX]) .withLongOpt(NOTIFY_DAYS_AHEAD_OPTION[LONG_OPTION_INDEX]) .create(NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(EXPIRATION_TIME_OPTION[ARG_INDEX]) .withDescription(EXPIRATION_TIME_OPTION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRATION_TIME_OPTION[LONG_OPTION_INDEX]) .create(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(EXPIRE_OPTION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRE_OPTION[LONG_OPTION_INDEX]).create(EXPIRE_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(EXPIRATION_EMAIL_MESSAGE_LOCATION[ARG_INDEX]) .withDescription(EXPIRATION_EMAIL_MESSAGE_LOCATION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRATION_EMAIL_MESSAGE_LOCATION[LONG_OPTION_INDEX]) .create(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(TEST_ONLY[DESCRIPTION_INDEX]) .withLongOpt(TEST_ONLY[LONG_OPTION_INDEX]).create(TEST_ONLY[SHORT_OPTION_INDEX])); app.processOptions(true, true);// ww w .ja v a 2 s . c om log.info("==== Running UserAgreementExpirationUpdater: " + app.toString() + "======"); final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao"); app.init(); dao.doInTransaction(new DAOTransaction() { public void runTransaction() { app.setScreenType(app.getCommandLineOptionEnumValue(SCREEN_TYPE_OPTION[SHORT_OPTION_INDEX], ScreenType.class)); int timeToExpireDays = DEFAULT_EXPIRATION_TIME_DAYS; if (app.isCommandLineFlagSet(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX])) { timeToExpireDays = app.getCommandLineOptionValue(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX], Integer.class); } try { try { if (app.isCommandLineFlagSet(NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX])) { Integer daysAheadToNotify = app.getCommandLineOptionValue( NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX], Integer.class); app.notifyAhead(daysAheadToNotify, timeToExpireDays); } else if (app.isCommandLineFlagSet(EXPIRE_OPTION[SHORT_OPTION_INDEX])) { app.expire(timeToExpireDays); } else { app.showHelpAndExit("Must specify either the \"" + NOTIFY_DAYS_AHEAD_OPTION[LONG_OPTION_INDEX] + "\" option or the \"" + EXPIRE_OPTION[LONG_OPTION_INDEX] + "\" option"); } } catch (OperationRestrictedException e) { app.sendErrorMail("OperationRestrictedException: Could not complete expiration service", app.toString(), e); throw new DAOTransactionRollbackException(e); } } catch (MessagingException e) { String msg = "Admin email operation not completed due to MessagingException"; log.error(msg + ":\nApp: " + app.toString(), e); throw new DAOTransactionRollbackException(msg, e); } if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { throw new DAOTransactionRollbackException("Rollback, testing only"); } } }); log.info("==== finished UserAgreementExpirationUpdater ======"); }
From source file:edu.harvard.med.iccbl.screensaver.io.screens.ConfirmedPositivesStudyCreator.java
@SuppressWarnings("static-access") public static void main(String[] args) { final ConfirmedPositivesStudyCreator app = new ConfirmedPositivesStudyCreator(args); String[] option = OPTION_STUDY_TITLE; app.addCommandLineOption(//from w w w.j a v a2 s .com OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_NUMBER; app.addCommandLineOption(OptionBuilder.hasArg().withType(Integer.class).withArgName(option[ARG_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_SUMMARY; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_REPLACE; app.addCommandLineOption(OptionBuilder.withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(TEST_ONLY[DESCRIPTION_INDEX]) .withLongOpt(TEST_ONLY[LONG_OPTION_INDEX]).create(TEST_ONLY[SHORT_OPTION_INDEX])); app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true); log.info("==== Running ConfirmedPositivesStudyCreator: " + app.toString() + "======"); final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao"); final ScreenResultReporter report = (ScreenResultReporter) app.getSpringBean("screenResultReporter"); final ScreenResultsDAO screenResultsDao = (ScreenResultsDAO) app.getSpringBean("screenResultsDao"); final ScreenDAO screenDao = (ScreenDAO) app.getSpringBean("screenDao"); dao.doInTransaction(new DAOTransaction() { public void runTransaction() { try { AdministratorUser admin = app.findAdministratorUser(); boolean replaceStudyIfExists = app.isCommandLineFlagSet(OPTION_REPLACE[SHORT_OPTION_INDEX]); String title = null; String summary = null; String studyFacilityId = ScreensaverConstants.DEFAULT_BATCH_STUDY_ID_CONFIRMATION_SUMMARY; if (app.isCommandLineFlagSet(OPTION_STUDY_NUMBER[SHORT_OPTION_INDEX])) { studyFacilityId = app.getCommandLineOptionValue(OPTION_STUDY_NUMBER[SHORT_OPTION_INDEX], String.class); } title = DEFAULT_STUDY_TITLE; summary = DEFAULT_STUDY_SUMMARY; if (app.isCommandLineFlagSet(OPTION_STUDY_TITLE[SHORT_OPTION_INDEX])) { title = app.getCommandLineOptionValue(OPTION_STUDY_TITLE[SHORT_OPTION_INDEX]); } if (app.isCommandLineFlagSet(OPTION_STUDY_SUMMARY[SHORT_OPTION_INDEX])) { summary = app.getCommandLineOptionValue(OPTION_STUDY_SUMMARY[SHORT_OPTION_INDEX]); } //TODO: refactor this code that checks for the exisiting study Screen study = dao.findEntityByProperty(Screen.class, Screen.facilityId.getPropertyName(), studyFacilityId); if (study != null) { // first check if the study is out of date ScreenResult latestScreenResult = screenResultsDao.getLatestScreenResult(); if (latestScreenResult == null) { log.info("No screen results found in the database"); System.exit(0); } else if (study.getDateCreated().compareTo(latestScreenResult.getDateCreated()) < 1) { screenDao.deleteStudy(study); } else if (replaceStudyIfExists) { screenDao.deleteStudy(study); } else { String msg = "study " + studyFacilityId + " already exists and is up-to-date (as determined by the date of the latest uploaded screen result). " + "Use the --" + OPTION_REPLACE[LONG_OPTION_INDEX] + " flag to delete the existing study first."; log.info(msg); System.exit(0); } } int count = app.createStudy(admin, studyFacilityId, title, summary, dao, report); study = dao.findEntityByProperty(Screen.class, Screen.facilityId.getPropertyName(), studyFacilityId); String subject = "Study created: \"" + study.getTitle() + "\""; //app.getMessages().getMessage("Study generated"); if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { subject = "[TEST ONLY, no commits] " + subject; } String msg = "Study: " + study.getFacilityId() + "\n\"" + study.getTitle() + "\"\n" + study.getSummary() + "\n\nTotal count of Confirmed Positives considered in the study: " + count; app.sendAdminEmails(subject, msg); } catch (MessagingException e) { throw new DAOTransactionRollbackException(e); } if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { throw new DAOTransactionRollbackException("Rollback, testing only"); } } }); log.info("==== finished ConfirmedPositivesStudyCreator ======"); }
From source file:edu.harvard.med.iccbl.screensaver.soaputils.PubchemChembankQueryUtility.java
@SuppressWarnings("static-access") public static void main(String[] args) throws IOException, InterruptedException { final PubchemChembankQueryUtility app = new PubchemChembankQueryUtility(args); String[] option = LIBRARY_NAME; app.addCommandLineOption(//from w w w. j a v a 2 s. c o m OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = QUERY_ALL_LIBRARIES; app.addCommandLineOption( OptionBuilder.withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OUTPUT_FILE; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = TRY_LIMIT; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = INTERVAL_BETWEEN_TRIES; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = QUERY_PUBCHEM; app.addCommandLineOption( OptionBuilder.withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = QUERY_CHEMBANK; app.addCommandLineOption( OptionBuilder.withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); try { if (!app.processOptions(/* acceptDatabaseOptions= */true, /* showHelpOnError= */true)) { return; } final boolean queryPubchem = app.isCommandLineFlagSet(QUERY_PUBCHEM[SHORT_OPTION_INDEX]); final boolean queryChembank = app.isCommandLineFlagSet(QUERY_CHEMBANK[SHORT_OPTION_INDEX]); if (!(queryPubchem || queryChembank)) { log.error("Must specify either " + QUERY_PUBCHEM[LONG_OPTION_INDEX] + " or " + QUERY_CHEMBANK[LONG_OPTION_INDEX]); app.showHelp(); return; } if (!app.isCommandLineFlagSet(LIBRARY_NAME[SHORT_OPTION_INDEX]) && !app.isCommandLineFlagSet(QUERY_ALL_LIBRARIES[SHORT_OPTION_INDEX])) { log.error("Must specify either " + LIBRARY_NAME[LONG_OPTION_INDEX] + " or " + QUERY_ALL_LIBRARIES[LONG_OPTION_INDEX]); app.showHelp(); return; } if (app.isCommandLineFlagSet(LIBRARY_NAME[SHORT_OPTION_INDEX]) && app.isCommandLineFlagSet(QUERY_ALL_LIBRARIES[SHORT_OPTION_INDEX])) { log.error("Must specify either " + LIBRARY_NAME[LONG_OPTION_INDEX] + " or " + QUERY_ALL_LIBRARIES[LONG_OPTION_INDEX]); app.showHelp(); return; } if (app.isCommandLineFlagSet(QUERY_ALL_LIBRARIES[SHORT_OPTION_INDEX]) && app.isCommandLineFlagSet(OUTPUT_FILE[SHORT_OPTION_INDEX])) { log.error("option \"" + OUTPUT_FILE[LONG_OPTION_INDEX] + "\" not allowed with \"" + QUERY_ALL_LIBRARIES[LONG_OPTION_INDEX] + "\" option."); app.showHelp(); return; } // if(app.isCommandLineFlagSet(LIBRARY_NAME[SHORT_OPTION_INDEX]) // && !app.isCommandLineFlagSet(OUTPUT_FILE[SHORT_OPTION_INDEX])) { // log.error("option \"" + OUTPUT_FILE[LONG_OPTION_INDEX] + "\" must be specified with \"" + LIBRARY_NAME[LONG_OPTION_INDEX] + "\" option."); // app.showHelp(); // return; // } final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao"); dao.doInTransaction(new DAOTransaction() { public void runTransaction() { PrintWriter writer = null; PrintWriter errorWriter = null; try { int intervalMs = PugSoapUtil.INTERVAL_BETWEEN_TRIES_MS; if (app.isCommandLineFlagSet(INTERVAL_BETWEEN_TRIES[SHORT_OPTION_INDEX])) { intervalMs = app.getCommandLineOptionValue(INTERVAL_BETWEEN_TRIES[SHORT_OPTION_INDEX], Integer.class); } int numberOfTries = PugSoapUtil.TRY_LIMIT; if (app.isCommandLineFlagSet(TRY_LIMIT[SHORT_OPTION_INDEX])) { numberOfTries = app.getCommandLineOptionValue(TRY_LIMIT[SHORT_OPTION_INDEX], Integer.class); } List<Library> libraries = Lists.newArrayList(); if (app.isCommandLineFlagSet(LIBRARY_NAME[SHORT_OPTION_INDEX])) { String temp = app.getCommandLineOptionValue(LIBRARY_NAME[SHORT_OPTION_INDEX]); for (String libraryName : temp.split(",")) { Library library = dao.findEntityByProperty(Library.class, "shortName", libraryName.trim()); if (library == null) { throw new IllegalArgumentException( "no library with short name: " + libraryName); } libraries.add(library); } // if there is only one library to query, then set these values from the command line option if (libraries.size() == 1) { String outputFilename = app .getCommandLineOptionValue(OUTPUT_FILE[SHORT_OPTION_INDEX]); writer = app.getOutputFile(outputFilename); errorWriter = app.getOutputFile(outputFilename + ".errors"); } } else if (app.isCommandLineFlagSet(QUERY_ALL_LIBRARIES[SHORT_OPTION_INDEX])) { libraries = dao.findEntitiesByProperty(Library.class, "screenType", ScreenType.SMALL_MOLECULE); for (Iterator<Library> iter = libraries.iterator(); iter.hasNext();) { Library library = iter.next(); if (library.getLibraryType() == LibraryType.ANNOTATION || library.getLibraryType() == LibraryType.NATURAL_PRODUCTS) { iter.remove(); } } } Collections.sort(libraries, new NullSafeComparator<Library>() { @Override protected int doCompare(Library o1, Library o2) { return o1.getShortName().compareTo(o2.getShortName()); } }); List<String> libraryNames = Lists.transform(libraries, new Function<Library, String>() { @Override public String apply(Library from) { return from.getShortName(); } }); log.info("libraries to process:\n" + libraryNames); int i = 0; for (Library library : libraries) { if (writer == null || i > 0) { writer = app.getOutputFile(library.getShortName()); } if (errorWriter == null || i > 0) { errorWriter = app.getOutputFile(library.getShortName() + ".errors"); } log.info("\nProcessing the library: " + library.getShortName() + "\nlong name: " + library.getLibraryName() + "\noutput file: " + library.getShortName() + ".csv"); app.query(library, queryPubchem, queryChembank, dao, intervalMs, numberOfTries, writer, errorWriter); i++; } } catch (Exception e) { throw new DAOTransactionRollbackException(e); } finally { if (writer != null) writer.close(); if (errorWriter != null) errorWriter.close(); } } }); System.exit(0); } catch (ParseException e) { log.error("error parsing command line options: " + e.getMessage()); } }
From source file:edu.harvard.med.iccbl.screensaver.io.screens.ScreenPositivesCountStudyCreator.java
@SuppressWarnings("static-access") public static void main(String[] args) throws MessagingException { final ScreenPositivesCountStudyCreator app = new ScreenPositivesCountStudyCreator(args); String[] option = OPTION_STUDY_TITLE; app.addCommandLineOption(/*from www. j a va 2s. c o m*/ OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_NUMBER; app.addCommandLineOption(OptionBuilder.hasArg().withType(Integer.class).withArgName(option[ARG_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_SUMMARY; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_SCREEN_TYPE_SM; app.addCommandLineOption(OptionBuilder.withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_SCREEN_TYPE_RNAI; app.addCommandLineOption(OptionBuilder.withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_REPLACE; app.addCommandLineOption(OptionBuilder.withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(TEST_ONLY[DESCRIPTION_INDEX]) .withLongOpt(TEST_ONLY[LONG_OPTION_INDEX]).create(TEST_ONLY[SHORT_OPTION_INDEX])); app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true); log.info("==== Running ScreenPositivesCountStudyCreator: " + app.toString() + "======"); try { app.execute(); } catch (Exception e) { String subject = "Execution failure for " + app.getClass().getName(); String msg = subject + "\n" + app.toString(); app.sendErrorMail(subject, msg, e); System.exit(1); } }