List of usage examples for org.apache.commons.cli GnuParser GnuParser
GnuParser
From source file:com.ibm.watson.app.common.tools.services.classifier.TrainClassifier.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The absolute URL of the NL classifier service to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, "url"); Option usernameOption = createOption(USERNAME_OPTION, USERNAME_OPTION_LONG, true, "The username to use during authentication to the NL classifier service", true, "username"); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password to use during authentication to the NL classifier service", true, "password"); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The filepath to be used as training data", false, "file"); Option deleteOption = createOption(DELETE_OPTION, DELETE_OPTION_LONG, false, "If specified, the classifier instance will be deleted if training is not successful"); final Options options = buildOptions(urlOption, usernameOption, passwordOption, fileOption, deleteOption); CommandLine cmd;//from ww w. j ava2 s . c o m try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWEGA14016E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + TrainClassifier.class.getName(), null, options, null); return; } final String url = cmd.hasOption(URL_OPTION) ? cmd.getOptionValue(URL_OPTION) : DEFAULT_URL; final String username = cmd.getOptionValue(USERNAME_OPTION).trim(); final String password = cmd.getOptionValue(PASSWORD_OPTION).trim(); if (username.isEmpty() || password.isEmpty()) { throw new IllegalArgumentException( MessageKey.AQWEGA14014E_username_and_password_cannot_empty.getMessage().getFormattedMessage()); } final NLClassifierRestClient client = new NLClassifierRestClient(url, username, password); listClassifiers(client); System.out.println(MessageKey.AQWEGA10012I_h_help.getMessage().getFormattedMessage()); String userInput; boolean exit = false; NLClassifier classifier = null; boolean isTraining = false; if (cmd.hasOption(FILE_OPTION)) { // File option was specified, go directly to training classifier = train(client, cmd.getOptionValue(FILE_OPTION)); isTraining = true; } try (final Scanner scanner = new Scanner(System.in)) { while (!exit) { System.out.print("> "); userInput = scanner.nextLine().trim(); if (userInput.equals("q") || userInput.equals("quit") || userInput.equals("exit")) { exit = true; } else if (userInput.equals("h") || userInput.equals("help")) { printHelp(); } else if (userInput.equals("l") || userInput.equals("list")) { listClassifiers(client); } else if (userInput.equals("t") || userInput.equals("train")) { if (!isTraining) { System.out.print("Enter filename: "); String filename = scanner.nextLine().trim(); classifier = train(client, filename); isTraining = true; } else { System.err.println(MessageKey.AQWEGA10013I_t_cannot_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("s") || userInput.equals("status")) { if (isTraining) { exit = getStatus(client, classifier, cmd.hasOption(DELETE_OPTION)); } else { System.err.println(MessageKey.AQWEGA10014I_s_can_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("c") || userInput.equals("classify")) { if (classifier != null && classifier.getStatus().equals(Status.AVAILABLE)) { isTraining = false; System.out.print(MessageKey.AQWEGA10015I_text_classify.getMessage().getFormattedMessage()); String text = scanner.nextLine().trim(); classify(client, classifier, text); } else { System.err.println(MessageKey.AQWEGA10016I_c_can_used_after_training_has_completed .getMessage().getFormattedMessage()); } } else { System.err.println( MessageKey.AQWEGA14017E_unknown_command_1.getMessage(userInput).getFormattedMessage()); } Thread.sleep(100); // Give the out / err consoles time to battle it out before printing the command prompt } } }
From source file:frankhassanabad.com.github.Jasperize.java
/** * Main method to call through Java in order to take a LinkedInProfile on disk and load it. * * @param args command line arguments where the options are stored * @throws FileNotFoundException Thrown if any file its expecting cannot be found. * @throws JRException If there's generic overall Jasper issues. * @throws ParseException If there's command line parsing issues. *//*from w ww .jav a 2 s .c om*/ public static void main(String[] args) throws IOException, JRException, ParseException { Options options = new Options(); options.addOption("h", "help", false, "Shows the help documentation"); options.addOption("v", "version", false, "Shows the help documentation"); options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml"); options.addOption("sig", true, "Picture of your signature to add to the cover letter."); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Version:" + version); System.exit(0); } boolean useCoverLetter = cmd.hasOption("cl"); String signatureLocation = cmd.getOptionValue("sig"); BufferedImage signatureImage = null; if (signatureLocation != null) { signatureImage = ImageIO.read(new File(signatureLocation)); ; } @SuppressWarnings("unchecked") List<String> arguments = cmd.getArgList(); final String jrxmlFile; final String jasperOutput; if (arguments.size() == 2) { jrxmlFile = arguments.get(0); jasperOutput = arguments.get(1); System.out.println("*Detected* the command line arguments of:"); System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } else if (arguments.size() == 3) { jrxmlFile = arguments.get(1); jasperOutput = arguments.get(2); System.out.println("*Detected* the command line arguments of:"); System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } else { System.out.println("Using the default arguments of:"); jrxmlFile = "data/jasperTemplates/resume1.jrxml"; jasperOutput = "data/jasperOutput/linkedInResume.pdf"; System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } final String compiledMasterFile; final String outputType; final String jrPrintFile; //Split the inputFile final String[] inputSplit = jrxmlFile.split("\\."); if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) { //Error System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:"); System.out.println(" data/jasperTemplates/resume1.jrxml"); System.exit(1); } //Split the outputFile final String[] outputSplit = jasperOutput.split("\\."); if (outputSplit.length != 2) { //Error System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:"); System.out.println(" data/jasperOutput/linkedInResume.pdf"); System.exit(1); } File inputFile = new File(inputSplit[0]); String inputFileName = inputFile.getName(); String inputFileParentPath = inputFile.getParent(); File outputFile = new File(outputSplit[0]); String outputFileParentPath = outputFile.getParent(); System.out.println("Compiling report(s)"); compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath); System.out.println("Done compiling report(s)"); compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper"; jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint"; System.out.println("Filling report: " + compiledMasterFile); Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage); System.out.println("Done filling reports"); outputType = outputSplit[1]; System.out.println("Creating output export file of: " + jasperOutput); if (outputType.equalsIgnoreCase("pdf")) { Reporting.pdf(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("pptx")) { Reporting.pptx(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("docx")) { Reporting.docx(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("odt")) { Reporting.odt(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("xhtml")) { Reporting.xhtml(jrPrintFile, jasperOutput); } System.out.println("Done creating output export file of: " + jasperOutput); }
From source file:eu.itesla_project.offline.mpi.Master.java
public static void main(String[] args) throws Exception { try {/*from ww w . j a v a 2 s.co m*/ CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(OPTIONS, args); Mode mode = Mode.valueOf(line.getOptionValue("mode")); String simulationDbName = line.hasOption("simulation-db-name") ? line.getOptionValue("simulation-db-name") : OfflineConfig.DEFAULT_SIMULATION_DB_NAME; String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name") : OfflineConfig.DEFAULT_RULES_DB_NAME; String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name") : OfflineConfig.DEFAULT_METRICS_DB_NAME; Path tmpDir = Paths.get(line.getOptionValue("tmp-dir")); Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class")); Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir")); String statisticsDbName = line.getOptionValue("statistics-db-name"); int coresPerRank = Integer.parseInt(line.getOptionValue("cores")); Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive")) : null; String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null; MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext(); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors .newSizeLimitedThreadPool("OFFLINE_POOL", 100); try { MpiStatisticsFactory statisticsFactory = statisticsFactoryClass .asSubclass(MpiStatisticsFactory.class).newInstance(); try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) { try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics, mpiExecutorContext, coresPerRank, false, stdOutArchive)) { OfflineConfig config = OfflineConfig.load(); try (LocalOfflineApplication application = new LocalOfflineApplication(config, computationManager, simulationDbName, rulesDbName, metricsDbName, scheduledExecutorService, offlineExecutorService)) { switch (mode) { case ui: application.await(); break; case simulations: { if (workflowId == null) { workflowId = application.createWorkflow(null, OfflineWorkflowCreationParameters.load()); } application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load()); } break; case rules: { if (workflowId == null) { throw new RuntimeException("Workflow '" + workflowId + "' not found"); } application.computeSecurityRulesAndWait(workflowId); } break; default: throw new IllegalArgumentException("Invalid mode " + mode); } } } } } finally { mpiExecutorContext.shutdown(); offlineExecutorService.shutdown(); scheduledExecutorService.shutdown(); offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES); scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES); } } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("master", OPTIONS, true); System.exit(-1); } catch (Throwable t) { LOGGER.error(t.toString(), t); System.exit(-1); } }
From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The root URL of the application to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, URL_OPTION_LONG); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The file to be used to populate the answers, can point to the file system or the class path", true, FILE_OPTION_LONG);//from www.j a v a2 s . c om Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true, "The directory containing the html answer files, can point to the file system or the class path", true, DIR_OPTION_LONG); Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API", true, USER_OPTION_LONG); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password for the manage API", true, PASSWORD_OPTION_LONG); final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption); CommandLine cmd; try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null); return; } final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL); final String file = cmd.getOptionValue(FILE_OPTION); final String dir = cmd.getOptionValue(DIR_OPTION); final String user = cmd.getOptionValue(USER_OPTION); final String password = cmd.getOptionValue(PASSWORD_OPTION); System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT) .getFormattedMessage()); try { AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password); // we only want to populate if there is nothing in the database already // start with the assumption that we do want to populate and stop if we find answers in there already boolean doPopulate = true; String answersResult = getAnswers(client); if (answersResult != null && !answersResult.isEmpty()) { Gson gson = new Gson(); Type type = new TypeToken<List<ManagedAnswer>>() { }.getType(); List<ManagedAnswer> answers = gson.fromJson(answersResult, type); if (answers != null && answers.size() > 0) { System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size()) .getFormattedMessage()); doPopulate = false; } } if (doPopulate) { System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2 .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage()); boolean success = populate(client, file, dir); if (!success) { throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage() .getFormattedMessage()); } } else { System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage() .getFormattedMessage()); } System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage()); } catch (IOException e) { System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage()) .getFormattedMessage()); e.printStackTrace(System.err); } }
From source file:io.s4.util.LoadGenerator.java
public static void main(String args[]) { Options options = new Options(); boolean warmUp = false; options.addOption(//from w w w . ja v a 2s. c o m OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r")); options.addOption(OptionBuilder.withArgName("display_rate").hasArg() .withDescription("Display Rate at specified second boundary").create("d")); options.addOption(OptionBuilder.withArgName("start_boundary").hasArg() .withDescription("Start boundary in seconds").create("b")); options.addOption(OptionBuilder.withArgName("run_for").hasArg() .withDescription("Run for a specified number of seconds").create("x")); options.addOption(OptionBuilder.withArgName("cluster_manager").hasArg().withDescription("Cluster manager") .create("z")); options.addOption(OptionBuilder.withArgName("sender_application_name").hasArg() .withDescription("Sender application name").create("a")); options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg() .withDescription("Listener application name").create("g")); options.addOption( OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o")); options.addOption(new Option("w", "Warm-up")); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } int expectedRate = 250; if (line.hasOption("r")) { try { expectedRate = Integer.parseInt(line.getOptionValue("r")); } catch (Exception e) { System.err.println("Bad expected rate specified " + line.getOptionValue("r")); System.exit(1); } } int displayRateIntervalSeconds = 20; if (line.hasOption("d")) { try { displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d")); } catch (Exception e) { System.err.println("Bad display rate value specified " + line.getOptionValue("d")); System.exit(1); } } int startBoundary = 2; if (line.hasOption("b")) { try { startBoundary = Integer.parseInt(line.getOptionValue("b")); } catch (Exception e) { System.err.println("Bad start boundary value specified " + line.getOptionValue("b")); System.exit(1); } } int updateFrequency = 0; if (line.hasOption("f")) { try { updateFrequency = Integer.parseInt(line.getOptionValue("f")); } catch (Exception e) { System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f")); System.exit(1); } System.out.printf("Update frequency is %d\n", updateFrequency); } int runForTime = 0; if (line.hasOption("x")) { try { runForTime = Integer.parseInt(line.getOptionValue("x")); } catch (Exception e) { System.err.println("Bad run for time specified " + line.getOptionValue("x")); System.exit(1); } System.out.printf("Run for time is %d\n", runForTime); } String clusterManagerAddress = null; if (line.hasOption("z")) { clusterManagerAddress = line.getOptionValue("z"); } String senderApplicationName = null; if (line.hasOption("a")) { senderApplicationName = line.getOptionValue("a"); } String listenerApplicationName = null; if (line.hasOption("a")) { listenerApplicationName = line.getOptionValue("g"); } if (listenerApplicationName == null) { listenerApplicationName = senderApplicationName; } long sleepOverheadMicros = -1; if (line.hasOption("o")) { try { sleepOverheadMicros = Long.parseLong(line.getOptionValue("o")); } catch (NumberFormatException e) { System.err.println("Bad sleep overhead specified " + line.getOptionValue("o")); System.exit(1); } System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros); } if (line.hasOption("w")) { warmUp = true; } List loArgs = line.getArgList(); if (loArgs.size() < 1) { System.err.println("No input file specified"); System.exit(1); } String inputFilename = (String) loArgs.get(0); EventEmitter emitter = null; SerializerDeserializer serDeser = new KryoSerDeser(); CommLayerEmitter clEmitter = new CommLayerEmitter(); clEmitter.setAppName(senderApplicationName); clEmitter.setListenerAppName(listenerApplicationName); clEmitter.setClusterManagerAddress(clusterManagerAddress); clEmitter.setSenderId(String.valueOf(System.currentTimeMillis() / 1000)); clEmitter.setSerDeser(serDeser); clEmitter.init(); emitter = clEmitter; long endTime = 0; if (runForTime > 0) { endTime = System.currentTimeMillis() + (runForTime * 1000); } LoadGenerator loadGenerator = new LoadGenerator(); loadGenerator.setInputFilename(inputFilename); loadGenerator.setEventEmitter(clEmitter); loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds); loadGenerator.setExpectedRate(expectedRate); loadGenerator.run(); System.exit(0); }
From source file:com.linkedin.pinot.transport.perf.ScatterGatherPerfServer.java
/** * @param args/*w w w . j a va 2 s.co m*/ */ public static void main(String[] args) throws Exception { CommandLineParser cliParser = new GnuParser(); Options cliOptions = buildCommandLineOptions(); CommandLine cmd = cliParser.parse(cliOptions, args, true); if (!cmd.hasOption(RESPONSE_SIZE_OPT_NAME) || !cmd.hasOption(SERVER_PORT_OPT_NAME)) { System.err.println("Missing required arguments !!"); System.err.println(cliOptions); throw new RuntimeException("Missing required arguments !!"); } int responseSize = Integer.parseInt(cmd.getOptionValue(RESPONSE_SIZE_OPT_NAME)); int serverPort = Integer.parseInt(cmd.getOptionValue(SERVER_PORT_OPT_NAME)); ScatterGatherPerfServer server = new ScatterGatherPerfServer(serverPort, responseSize, 2); // 2ms latency server.run(); }
From source file:ml.shifu.shifu.util.ShifuCLI.java
/** * Main entry for the whole framework./*w w w. ja v a2s . c o m*/ * * @throws IOException */ public static void main(String[] args) { // invalid input and help options if (args.length < 1 || (isHelpOption(args[0]))) { printUsage(); System.exit(args.length < 1 ? -1 : 0); } // process -v and -version conditions manually if (isVersionOption(args[0])) { printVersionString(); System.exit(0); } CommandLineParser parser = new GnuParser(); Options opts = buildModelSetOptions(args); CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (ParseException e) { log.error("Invalid command options. Please check help message."); printUsage(); System.exit(1); } try { if (args[0].equals(NEW) && args.length >= 2 && StringUtils.isNotEmpty(args[1])) { // modelset step String modelName = args[1]; int status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE), cmd.getOptionValue(MODELSET_CMD_M)); if (status == 0) { printModelSetCreatedSuccessfulLog(modelName); } // copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP)); } else { if (args[0].equals(MODELSET_CMD_CP) && args.length >= 3 && StringUtils.isNotEmpty(args[1]) && StringUtils.isNotEmpty(args[2])) { String newModelSetName = args[2]; // modelset step copyModel(new String[] { args[1], newModelSetName }); printModelSetCopiedSuccessfulLog(newModelSetName); } else if (args[0].equals(INIT_CMD)) { // init step if (cmd.getOptions() == null || cmd.getOptions().length == 0) { int status = initializeModel(); if (status == 0) { log.info( "ModelSet initilization is successful. Please continue next step by using 'shifu stats'."); } } else if (cmd.hasOption(INIT_CMD_MODEL)) { initializeModelParam(); } else { log.error("Invalid command, please check help message."); printUsage(); } } else if (args[0].equals(STATS_CMD)) { // stats step calModelStats(); log.info( "Do model set statistics successfully. Please continue next step by using 'shifu varselect'."); } else if (args[0].equals(NORMALIZE_CMD)) { // normalize step normalizeTrainData(); log.info( "Do model set normalization successfully. Please continue next step by using 'shifu train'."); } else if (args[0].equals(VARSELECT_CMD)) { // variable selected step selectModelVar(); log.info( "Do model set variables selection successfully. Please continue next step by using 'shifu normalize'."); } else if (args[0].equals(TRAIN_CMD)) { // train step trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG)); log.info( "Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'."); } else if (args[0].equals(POSTTRAIN_CMD)) { // post train step postTrainModel(); log.info( "Do model set post-training successfully. Please configurate your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set."); } else if (args[0].equals(SAVE)) { String newModelSetName = args.length >= 2 ? args[1] : null; saveCurrentModel(newModelSetName); } else if (args[0].equals(SWITCH)) { String newModelSetName = args[1]; switchCurrentModel(newModelSetName); } else if (args[0].equals(SHOW)) { ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null); p.run(); } else if (args[0].equals(EVAL_CMD)) { // eval step if (args.length == 1) { //run everything runEvalSet(cmd.hasOption(TRAIN_CMD_DRY)); log.info("Run eval performance with all eval sets successfully."); } else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) { //create new eval createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW)); log.info( "Create eval set successfully. You can configurate EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info."); } else if (cmd.hasOption(EVAL_CMD_RUN)) { runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY)); log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN)); } else if (cmd.hasOption(SCORE)) { //run score runEvalScore(cmd.getOptionValue(SCORE)); log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE)); } else if (cmd.hasOption(CONFMAT)) { //run confusion matrix runEvalConfMat(cmd.getOptionValue(CONFMAT)); log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT)); } else if (cmd.hasOption(PERF)) { //run perfermance runEvalPerf(cmd.getOptionValue(PERF)); log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF)); } else if (cmd.hasOption(LIST)) { //list all evaluation sets listEvalSet(); } else if (cmd.hasOption(DELETE)) { // delete some evaluation set deleteEvalSet(cmd.getOptionValue(DELETE)); } else { log.error("Invalid command, please check help message."); printUsage(); } } else { log.error("Invalid command, please check help message."); printUsage(); } } } catch (ShifuException e) { // need define error code in each step. log.error(e.getError().toString(), e.getCause()); exceptionExit(e); } catch (Exception e) { exceptionExit(e); } }
From source file:apps.quantification.QuantifySVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);/* w ww . j a v a2s . c o m*/ OptionBuilder.hasArg(false); 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 files in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.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 != 3) { 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(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:de.prozesskraft.pkraft.Merge.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file/* w ww. j a v a 2 s . com*/ ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] instance you want to merge another instance into.") // .isRequired() .create("instance"); Option oguest = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] this instance will be merged into -instance.") // .isRequired() .create("guest"); Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.") // .isRequired() .create("basedir"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oguest); options.addOption(obasedir); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("merge", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.err.println("option -instance is mandatory"); exiter(); } if (!(commandline.hasOption("guest"))) { System.err.println("at least one option -guest is mandatory"); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ String pathToInstance = commandline.getOptionValue("instance"); java.io.File fileInstance = new java.io.File(pathToInstance); String[] pathToGuest = commandline.getOptionValues("guest"); String baseDir = null; if (commandline.hasOption("basedir")) { java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir")); if (!fileBaseDir.exists()) { System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath()); exiter(); } else if (!fileBaseDir.isDirectory()) { System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath()); exiter(); } baseDir = commandline.getOptionValue("basedir"); } // ueberpruefen ob die process.pmb files vorhanden sind // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } for (String pathGuest : pathToGuest) { java.io.File fileGuest = new java.io.File(pathGuest); // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileGuest.exists()) { System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath()); exiter(); } } // base - instance einlesen Process p1 = new Process(); p1.setInfilebinary(pathToInstance); p1.setOutfilebinary(pathToInstance); Process p2 = p1.readBinary(); // alle guests einlesen ArrayList<Process> alleGuests = new ArrayList<Process>(); for (String actPathGuest : pathToGuest) { Process p30 = new Process(); p30.setInfilebinary(actPathGuest); Process pGuest = p30.readBinary(); // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind if (!p2.getName().equals(pGuest.getName())) { System.err.println("error: instances are not from the same type (-instance=" + p2.getName() + " != -guest=" + pGuest.getName()); exiter(); } // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind if (!p2.getVersion().equals(pGuest.getVersion())) { System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!=" + pGuest.getVersion()); exiter(); } alleGuests.add(pGuest); } // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen Process p3 = new Process(); p3.setInfilebinary(pathToInstance); Process process = p3.readBinary(); // den main-prozess ueber die static function klonen // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind Process clonedProcess = cloneProcess(process, null); // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren for (Step actStep : process.getStep()) { if (actStep.getSubprocess() != null) { Process pDummy = new Process(); pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb"); Process processInSubprocess = pDummy.readBinary(); // System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb"); if (processInSubprocess != null) { Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } } // alle dependent steps der zielinstanz einsammeln // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden Map<Step, String> dependentSteps = new HashMap<Step, String>(); // alle guest prozesse merge durchfuehren for (Process actGuestProcess : alleGuests) { System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary()); // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren for (Step actStep : actGuestProcess.getStep()) { if (actStep.isAFannedMultistep()) { System.err.println("info: merging from guest instance step " + actStep.getName()); Step clonedStepForIntegrationInClonedProcess = actStep.clone(); if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) { System.err.println("info: merging step successfully."); // die downstream steps vom merge-punkt merken for (Step actStepToResetBecauseOfDependency : clonedProcess .getStepDependent(actStep.getName())) { dependentSteps.put(actStepToResetBecauseOfDependency, "dummy"); } // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden // den prozess in pradar anmelden durch aufruf des tools: pradar-attend if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) { String call5 = ini.get("apps", "pradar-attend") + " -instance " + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb"; System.err.println("info: calling: " + call5); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call5); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } else { System.err.println("error: merging step failed."); } } else { System.err.println("debug: because it's not a multistep, ignoring from guest instance step " + actStep.getName()); } } } // alle steps downstream der merge-positionen resetten for (Step actStep : dependentSteps.keySet()) { actStep.resetBecauseOfDependency(); } // speichern der ergebnis instanz clonedProcess.writeBinary(); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } }
From source file:apps.quantification.QuantifySVMLight.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMLight.class.getName() + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//from w w w. ja va 2 s. c o m OptionBuilder.hasArg(false); 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 files in svm_light format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmLightClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmLightClassifierCustomizer(remainingArgs[0]); if (line.hasOption("v")) customizer.printSvmLightOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.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 != 3) { 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(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }