Example usage for java.text NumberFormat getPercentInstance

List of usage examples for java.text NumberFormat getPercentInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getPercentInstance.

Prototype

public static final NumberFormat getPercentInstance() 

Source Link

Document

Returns a percentage format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.jd.survey.web.pdf.StatisticsPdf.java

private void writeCurrencyMatrixQuestionStatistics(Document document, Question question,
        List<QuestionStatistic> questionStatistics, String minimumLabel, String maximumLabel,
        String averageLabel, String standardDeviationLabel) throws Exception {

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(1);

    Table statsTable;//www.j  a  v a2 s. co m
    Cell cell;

    statsTable = new Table(question.getColumnLabels().size() + 1);
    statsTable.setWidth(94);
    statsTable.setBorder(0);
    statsTable.setOffset(5);
    statsTable.setPadding(2);
    statsTable.setDefaultCellBorder(0);

    //header
    cell = new Cell();
    cell.setBorder(Cell.BOTTOM);
    statsTable.addCell(cell);
    for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
        cell = new Cell(new Paragraph(columnLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.BOTTOM);
        statsTable.addCell(cell);
    }
    int rowIndex = 1;
    for (QuestionRowLabel rowLabel : question.getRowLabels()) {
        cell = new Cell(new Paragraph(rowLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.RIGHT);
        if ((rowIndex % 2) == 1) {
            cell.setBackgroundColor(new Color(244, 244, 244));
        }
        statsTable.addCell(cell);
        for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
            boolean found = false;
            cell = new Cell();
            if ((rowIndex % 2) == 1) {
                cell.setBackgroundColor(new Color(244, 244, 244));
            }
            for (QuestionStatistic questionStatistic : questionStatistics) {
                if (questionStatistic.getRowOrder().equals(rowLabel.getOrder())
                        && questionStatistic.getColumnOrder().equals(columnLabel.getOrder())) {
                    cell.add(new Paragraph(
                            minimumLabel + ": " + CurrencyValidator.getInstance()
                                    .format(questionStatistic.getMin(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(
                            maximumLabel + ": " + CurrencyValidator.getInstance()
                                    .format(questionStatistic.getMax(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(
                            averageLabel + ": " + CurrencyValidator.getInstance()
                                    .format(questionStatistic.getAverage(), LocaleContextHolder.getLocale()),
                            normalFont));
                    cell.add(new Paragraph(standardDeviationLabel + ": "
                            + CurrencyValidator.getInstance().format(
                                    questionStatistic.getSampleStandardDeviation(),
                                    LocaleContextHolder.getLocale()),
                            normalFont));

                    break;
                }
            }
            if (!found) {
            }

            statsTable.addCell(cell);
        }
        rowIndex++;
    }

    document.add(statsTable);

}

From source file:org.jfree.chart.ChartFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The color of each section will be determined by the move from the value
 * for the same key in {@code previousDataset}. ie if value1 &gt; value2
 * then the section will be in green (unless {@code greenForIncrease}
 * is {@code false}, in which case it would be {@code red}).
 * Each section can have a shade of red or green as the difference can be
 * tailored between 0% (black) and percentDiffForMaxScale% (bright
 * red/green).//w  w  w . java 2 s.  c  om
 * <p>
 * For instance if {@code percentDiffForMaxScale} is 10 (10%), a
 * difference of 5% will have a half shade of red/green, a difference of
 * 10% or more will have a maximum shade/brightness of red/green.
 * <P>
 * The chart object returned by this method uses a {@link PiePlot} instance
 * as the plot.
 * <p>
 * Written by <a href="mailto:opensource@objectlab.co.uk">Benoit
 * Xhenseval</a>.
 *
 * @param title  the chart title ({@code null} permitted).
 * @param dataset  the dataset for the chart ({@code null} permitted).
 * @param previousDataset  the dataset for the last run, this will be used
 *                         to compare each key in the dataset
 * @param percentDiffForMaxScale scale goes from bright red/green to black,
 *                               percentDiffForMaxScale indicate the change
 *                               required to reach top scale.
 * @param greenForIncrease  an increase since previousDataset will be
 *                          displayed in green (decrease red) if true.
 * @param subTitle displays a subtitle with color scheme if true
 * @param showDifference  create a new dataset that will show the %
 *                        difference between the two datasets.
 *
 * @return A pie chart.
 */
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    plot.setToolTipGenerator(new StandardPieToolTipGenerator());

    List<Comparable> keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Comparable key : keys) {
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.GREEN);
            } else {
                plot.setSectionPaint(key, Color.RED);
            }
            if (showDifference) {
                assert series != null; // suppresses compiler warning
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                assert series != null; // suppresses compiler warning
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, plot);

    if (subTitle) {
        TextTitle subtitle;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:com.jd.survey.web.pdf.StatisticsPdf.java

private void writeDateMatrixQuestionStatistics(Document document, Question question,
        List<QuestionStatistic> questionStatistics, String minimumLabel, String maximumLabel, String dateFormat)
        throws Exception {

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(1);

    Table statsTable;/* w  w w  . java 2s.  co m*/
    Cell cell;

    statsTable = new Table(question.getColumnLabels().size() + 1);
    statsTable.setWidth(94);
    statsTable.setBorder(0);
    statsTable.setOffset(5);
    statsTable.setPadding(2);
    statsTable.setDefaultCellBorder(0);

    //header
    cell = new Cell();
    cell.setBorder(Cell.BOTTOM);
    statsTable.addCell(cell);
    for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
        cell = new Cell(new Paragraph(columnLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.BOTTOM);
        statsTable.addCell(cell);
    }
    int rowIndex = 1;
    for (QuestionRowLabel rowLabel : question.getRowLabels()) {
        cell = new Cell(new Paragraph(rowLabel.getLabel(), boldedFont));
        cell.setBorder(Cell.RIGHT);
        if ((rowIndex % 2) == 1) {
            cell.setBackgroundColor(new Color(244, 244, 244));
        }
        statsTable.addCell(cell);
        for (QuestionColumnLabel columnLabel : question.getColumnLabels()) {
            boolean found = false;
            cell = new Cell();
            if ((rowIndex % 2) == 1) {
                cell.setBackgroundColor(new Color(244, 244, 244));
            }
            for (QuestionStatistic questionStatistic : questionStatistics) {
                if (questionStatistic.getRowOrder().equals(rowLabel.getOrder())
                        && questionStatistic.getColumnOrder().equals(columnLabel.getOrder())) {
                    cell.add(new Paragraph(minimumLabel + ": "
                            + DateValidator.getInstance().format(questionStatistic.getMinDate(), dateFormat),
                            normalFont));
                    cell.add(new Paragraph(maximumLabel + ": "
                            + DateValidator.getInstance().format(questionStatistic.getMaxDate(), dateFormat),
                            normalFont));
                    break;
                }
            }
            if (!found) {
            }

            statsTable.addCell(cell);
        }
        rowIndex++;
    }

    document.add(statsTable);

}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getChapterPareto(DefaultKeyedValues data, String title, String quantity, String range) {

    JFreeChart chart;//from  w  w w. j  ava  2s.  c o m

    data.sortByValues(SortOrder.DESCENDING);
    KeyedValues cummulative = DataUtilities.getCumulativePercentages(data);
    CategoryDataset dataset = DatasetUtilities.createCategoryDataset(quantity, data);

    // create the chart...
    chart = ChartFactory.createBarChart(title, // chart title
            "Chapter", // domain axis label
            range, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, false);

    CategoryPlot plot = chart.getCategoryPlot();

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();

    CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cummulative", cummulative);
    NumberAxis axis2 = new NumberAxis("Percent");
    axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
    axis2.setUpperBound(1);
    axis2.setLowerBound(0);
    plot.setRangeAxis(1, axis2);
    plot.setDataset(1, dataset2);
    plot.setRenderer(1, renderer2);
    plot.mapDatasetToRangeAxis(1, 1);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    return chart;
}

From source file:org.dllearner.algorithms.qtl.experiments.QTLEvaluation.java

public void run(int maxNrOfProcessedQueries, int maxTreeDepth, int[] exampleInterval, double[] noiseInterval,
        HeuristicType[] measures) throws Exception {
    this.maxTreeDepth = maxTreeDepth;
    queryTreeFactory.setMaxDepth(maxTreeDepth);

    if (exampleInterval != null) {
        nrOfExamplesIntervals = exampleInterval;
    }/*from   w ww.jav  a  2s .  c  o m*/
    if (noiseInterval != null) {
        this.noiseIntervals = noiseInterval;
    }
    if (measures != null) {
        this.measures = measures;
    }

    logger.info("Started QTL evaluation...");
    long t1 = System.currentTimeMillis();

    List<String> queries = dataset.getSparqlQueries().values().stream().map(q -> q.toString())
            .collect(Collectors.toList());
    logger.info("#loaded queries: " + queries.size());

    // filter for debugging purposes
    queries = queries.stream().filter(q -> tokens.stream().noneMatch(t -> !q.contains(t)))
            .collect(Collectors.toList());

    if (maxNrOfProcessedQueries == -1) {
        maxNrOfProcessedQueries = queries.size();
    }

    //      queries = filter(queries, (int) Math.ceil((double) maxNrOfProcessedQueries / maxTreeDepth));
    //      queries = queries.subList(0, Math.min(queries.size(), maxNrOfProcessedQueries));
    logger.info("#queries to process: " + queries.size());

    // generate examples for each query
    logger.info("precomputing pos. and neg. examples...");
    final Map<String, ExampleCandidates> query2Examples = new HashMap<>();
    for (String query : queries) {//if(!(query.contains("Borough_(New_York_City)")))continue;
        query2Examples.put(query, generateExamples(query));
    }
    logger.info("precomputing pos. and neg. examples finished.");

    // check for queries that do not return any result (should not happen, but we never know)
    Set<String> emptyQueries = query2Examples.entrySet().stream()
            .filter(e -> e.getValue().correctPosExampleCandidates.isEmpty()).map(e -> e.getKey())
            .collect(Collectors.toSet());
    logger.info("got {} empty queries.", emptyQueries.size());
    queries.removeAll(emptyQueries);

    // min. pos examples
    Set<String> lowNrOfExamplesQueries = query2Examples.entrySet().stream()
            .filter(e -> e.getValue().correctPosExampleCandidates.size() < 2).map(e -> e.getKey())
            .collect(Collectors.toSet());
    logger.info("got {} queries with < 2 pos. examples.", emptyQueries.size());
    queries.removeAll(lowNrOfExamplesQueries);

    final int totalNrOfQTLRuns = heuristics.length * this.measures.length * nrOfExamplesIntervals.length
            * noiseIntervals.length * queries.size();
    logger.info("#QTL runs: " + totalNrOfQTLRuns);

    final AtomicInteger currentNrOfFinishedRuns = new AtomicInteger(0);

    // loop over heuristics
    for (final QueryTreeHeuristic heuristic : heuristics) {
        final String heuristicName = heuristic.getClass().getAnnotation(ComponentAnn.class).shortName();

        // loop over heuristics measures
        for (HeuristicType measure : this.measures) {
            final String measureName = measure.toString();
            heuristic.setHeuristicType(measure);

            double[][] data = new double[nrOfExamplesIntervals.length][noiseIntervals.length];

            // loop over number of positive examples
            for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
                final int nrOfExamples = nrOfExamplesIntervals[i];

                // loop over noise value
                for (int j = 0; j < noiseIntervals.length; j++) {
                    final double noise = noiseIntervals[j];

                    // check if not already processed
                    File logFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-"
                            + heuristicName + "-" + measureName + ".log");
                    File statsFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-"
                            + heuristicName + "-" + measureName + ".stats");

                    if (!override && logFile.exists() && statsFile.exists()) {
                        logger.info(
                                "Eval config already processed. For re-running please remove corresponding output files.");
                        continue;
                    }

                    FileAppender appender = null;
                    try {
                        appender = new FileAppender(new SimpleLayout(), logFile.getPath(), false);
                        Logger.getRootLogger().addAppender(appender);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    logger.info("#examples: " + nrOfExamples + " noise: " + noise);

                    final DescriptiveStatistics nrOfReturnedSolutionsStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics baselinePrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselinePredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestReturnedSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestReturnedSolutionRuntimeStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestSolutionPositionStats = new SynchronizedDescriptiveStatistics();

                    MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).reset();
                    MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).reset();

                    ExecutorService tp = Executors.newFixedThreadPool(nrOfThreads);

                    // indicates if the execution for some of the queries failed
                    final AtomicBoolean failed = new AtomicBoolean(false);

                    // loop over SPARQL queries
                    for (final String sparqlQuery : queries) {

                        tp.submit(() -> {

                            logger.info("##############################################################");
                            logger.info("Processing query\n" + sparqlQuery);

                            try {
                                ExamplesWrapper examples = query2Examples.get(sparqlQuery).get(nrOfExamples,
                                        nrOfExamples, noise);
                                logger.info(
                                        "pos. examples:\n" + Joiner.on("\n").join(examples.correctPosExamples));
                                logger.info(
                                        "neg. examples:\n" + Joiner.on("\n").join(examples.correctNegExamples));

                                // write examples to disk
                                File dir = new File(benchmarkDirectory, "data/" + hash(sparqlQuery));
                                dir.mkdirs();
                                Files.write(Joiner.on("\n").join(examples.correctPosExamples),
                                        new File(dir, "examples_" + nrOfExamples + "_" + noise + ".tp"),
                                        Charsets.UTF_8);
                                Files.write(Joiner.on("\n").join(examples.correctNegExamples),
                                        new File(dir, "examples_" + nrOfExamples + "_" + noise + ".tn"),
                                        Charsets.UTF_8);
                                Files.write(Joiner.on("\n").join(examples.falsePosExamples),
                                        new File(dir, "examples_" + nrOfExamples + "_" + noise + ".fp"),
                                        Charsets.UTF_8);

                                // compute baseline
                                logger.info("Computing baseline...");
                                RDFResourceTree baselineSolution = applyBaseLine(examples,
                                        Baseline.MOST_INFORMATIVE_EDGE_IN_EXAMPLES);
                                logger.info("Baseline solution:\n" + owlRenderer
                                        .render(QueryTreeUtils.toOWLClassExpression(baselineSolution)));
                                logger.info("Evaluating baseline...");
                                Score baselineScore = computeScore(sparqlQuery, baselineSolution, noise);
                                logger.info("Baseline score:\n" + baselineScore);
                                String baseLineQuery = QueryTreeUtils.toSPARQLQueryString(baselineSolution,
                                        dataset.getBaseIRI(), dataset.getPrefixMapping());
                                baselinePrecisionStats.addValue(baselineScore.precision);
                                baselineRecallStats.addValue(baselineScore.recall);
                                baselineFMeasureStats.addValue(baselineScore.fmeasure);
                                baselinePredAccStats.addValue(baselineScore.predAcc);
                                baselineMathCorrStats.addValue(baselineScore.mathCorr);

                                // run QTL
                                PosNegLPStandard lp = new PosNegLPStandard();
                                lp.setPositiveExamples(examples.posExamplesMapping.keySet());
                                lp.setNegativeExamples(examples.negExamplesMapping.keySet());
                                QTL2Disjunctive la = new QTL2Disjunctive(lp, qef);
                                la.setRenderer(new org.dllearner.utilities.owl.DLSyntaxObjectRenderer());
                                la.setReasoner(dataset.getReasoner());
                                la.setEntailment(Entailment.SIMPLE);
                                la.setTreeFactory(queryTreeFactory);
                                la.setPositiveExampleTrees(examples.posExamplesMapping);
                                la.setNegativeExampleTrees(examples.negExamplesMapping);
                                la.setNoise(noise);
                                la.setHeuristic(heuristic);
                                la.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds);
                                la.setMaxTreeComputationTimeInSeconds(maxExecutionTimeInSeconds);
                                la.init();
                                la.start();
                                List<EvaluatedRDFResourceTree> solutions = new ArrayList<>(la.getSolutions());

                                //                              List<EvaluatedRDFResourceTree> solutions = generateSolutions(examples, noise, heuristic);
                                nrOfReturnedSolutionsStats.addValue(solutions.size());

                                // the best returned solution by QTL
                                EvaluatedRDFResourceTree bestSolution = solutions.get(0);
                                logger.info("Got " + solutions.size() + " query trees.");
                                logger.info("Best computed solution:\n"
                                        + render(bestSolution.asEvaluatedDescription()));
                                logger.info("QTL Score:\n" + bestSolution.getTreeScore());
                                long runtimeBestSolution = la.getTimeBestSolutionFound();
                                bestReturnedSolutionRuntimeStats.addValue(runtimeBestSolution);

                                // convert to SPARQL query
                                RDFResourceTree tree = bestSolution.getTree();
                                //                  filter.filter(tree);
                                String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(tree,
                                        dataset.getBaseIRI(), dataset.getPrefixMapping());

                                // compute score
                                Score score = computeScore(sparqlQuery, tree, noise);
                                bestReturnedSolutionPrecisionStats.addValue(score.precision);
                                bestReturnedSolutionRecallStats.addValue(score.recall);
                                bestReturnedSolutionFMeasureStats.addValue(score.fmeasure);
                                bestReturnedSolutionPredAccStats.addValue(score.predAcc);
                                bestReturnedSolutionMathCorrStats.addValue(score.mathCorr);
                                logger.info(score.toString());

                                // find the extensionally best matching tree in the list
                                Pair<EvaluatedRDFResourceTree, Score> bestMatchingTreeWithScore = findBestMatchingTreeFast(
                                        solutions, sparqlQuery, noise, examples);
                                EvaluatedRDFResourceTree bestMatchingTree = bestMatchingTreeWithScore
                                        .getFirst();
                                Score bestMatchingScore = bestMatchingTreeWithScore.getSecond();

                                // position of best tree in list of solutions
                                int positionBestScore = solutions.indexOf(bestMatchingTree);
                                bestSolutionPositionStats.addValue(positionBestScore);

                                Score bestScore = score;
                                if (positionBestScore > 0) {
                                    logger.info("Position of best covering tree in list: " + positionBestScore);
                                    logger.info("Best covering solution:\n"
                                            + render(bestMatchingTree.asEvaluatedDescription()));
                                    logger.info("Tree score: " + bestMatchingTree.getTreeScore());
                                    bestScore = bestMatchingScore;
                                    logger.info(bestMatchingScore.toString());
                                } else {
                                    logger.info("Best returned solution was also the best covering solution.");
                                }
                                bestSolutionRecallStats.addValue(bestScore.recall);
                                bestSolutionPrecisionStats.addValue(bestScore.precision);
                                bestSolutionFMeasureStats.addValue(bestScore.fmeasure);
                                bestSolutionPredAccStats.addValue(bestScore.predAcc);
                                bestSolutionMathCorrStats.addValue(bestScore.mathCorr);

                                for (RDFResourceTree negTree : examples.negExamplesMapping.values()) {
                                    if (QueryTreeUtils.isSubsumedBy(negTree, bestMatchingTree.getTree())) {
                                        Files.append(sparqlQuery + "\n", new File("/tmp/negCovered.txt"),
                                                Charsets.UTF_8);
                                        break;
                                    }
                                }

                                String bestQuery = QueryFactory.create(QueryTreeUtils.toSPARQLQueryString(
                                        filter.apply(bestMatchingTree.getTree()), dataset.getBaseIRI(),
                                        dataset.getPrefixMapping())).toString();

                                if (write2DB) {
                                    write2DB(sparqlQuery, nrOfExamples, examples, noise, baseLineQuery,
                                            baselineScore, heuristicName, measureName,
                                            QueryFactory.create(learnedSPARQLQuery).toString(), score,
                                            runtimeBestSolution, bestQuery, positionBestScore, bestScore);
                                }

                            } catch (Exception e) {
                                failed.set(true);
                                logger.error("Error occured for query\n" + sparqlQuery, e);
                                try {
                                    StringWriter sw = new StringWriter();
                                    PrintWriter pw = new PrintWriter(sw);
                                    e.printStackTrace(pw);
                                    Files.append(sparqlQuery + "\n" + sw.toString(),
                                            new File(benchmarkDirectory, "failed-" + nrOfExamples + "-" + noise
                                                    + "-" + heuristicName + "-" + measureName + ".txt"),
                                            Charsets.UTF_8);
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            } finally {
                                int cnt = currentNrOfFinishedRuns.incrementAndGet();
                                logger.info("***********Evaluation Progress:"
                                        + NumberFormat.getPercentInstance()
                                                .format((double) cnt / totalNrOfQTLRuns)
                                        + "(" + cnt + "/" + totalNrOfQTLRuns + ")" + "***********");
                            }
                        });

                    }

                    tp.shutdown();
                    tp.awaitTermination(12, TimeUnit.HOURS);

                    Logger.getRootLogger().removeAppender(appender);

                    if (!failed.get()) {
                        String result = "";
                        result += "\nBaseline Precision:\n" + baselinePrecisionStats;
                        result += "\nBaseline Recall:\n" + baselineRecallStats;
                        result += "\nBaseline F-measure:\n" + baselineFMeasureStats;
                        result += "\nBaseline PredAcc:\n" + baselinePredAccStats;
                        result += "\nBaseline MathCorr:\n" + baselineMathCorrStats;

                        result += "#Returned solutions:\n" + nrOfReturnedSolutionsStats;

                        result += "\nOverall Precision:\n" + bestReturnedSolutionPrecisionStats;
                        result += "\nOverall Recall:\n" + bestReturnedSolutionRecallStats;
                        result += "\nOverall F-measure:\n" + bestReturnedSolutionFMeasureStats;
                        result += "\nOverall PredAcc:\n" + bestReturnedSolutionPredAccStats;
                        result += "\nOverall MathCorr:\n" + bestReturnedSolutionMathCorrStats;

                        result += "\nTime until best returned solution found:\n"
                                + bestReturnedSolutionRuntimeStats;

                        result += "\nPositions of best solution:\n"
                                + Arrays.toString(bestSolutionPositionStats.getValues());
                        result += "\nPosition of best solution stats:\n" + bestSolutionPositionStats;
                        result += "\nOverall Precision of best solution:\n" + bestSolutionPrecisionStats;
                        result += "\nOverall Recall of best solution:\n" + bestSolutionRecallStats;
                        result += "\nOverall F-measure of best solution:\n" + bestSolutionFMeasureStats;

                        result += "\nCBD generation time(total):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getTotal()
                                + "\n";
                        result += "CBD generation time(avg):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getAvg()
                                + "\n";
                        result += "Tree generation time(total):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getTotal()
                                + "\n";
                        result += "Tree generation time(avg):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getAvg()
                                + "\n";
                        result += "Tree size(avg):\t" + treeSizeStats.getMean() + "\n";

                        logger.info(result);

                        try {
                            Files.write(result, statsFile, Charsets.UTF_8);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        data[i][j] = bestReturnedSolutionFMeasureStats.getMean();

                        if (write2DB) {
                            write2DB(heuristicName, measureName, nrOfExamples, noise,
                                    bestReturnedSolutionFMeasureStats.getMean(),
                                    bestReturnedSolutionPrecisionStats.getMean(),
                                    bestReturnedSolutionRecallStats.getMean(),
                                    bestReturnedSolutionPredAccStats.getMean(),
                                    bestReturnedSolutionMathCorrStats.getMean(),
                                    bestSolutionPositionStats.getMean(), bestSolutionFMeasureStats.getMean(),
                                    bestSolutionPrecisionStats.getMean(), bestSolutionRecallStats.getMean(),
                                    bestSolutionPredAccStats.getMean(), bestSolutionMathCorrStats.getMean(),
                                    baselineFMeasureStats.getMean(), baselinePrecisionStats.getMean(),
                                    baselineRecallStats.getMean(), baselinePredAccStats.getMean(),
                                    baselineMathCorrStats.getMean(),
                                    bestReturnedSolutionRuntimeStats.getMean());
                        }
                    }
                }
            }

            String content = "###";
            String separator = "\t";
            for (double noiseInterval1 : noiseIntervals) {
                content += separator + noiseInterval1;
            }
            content += "\n";
            for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
                content += nrOfExamplesIntervals[i];
                for (int j = 0; j < noiseIntervals.length; j++) {
                    content += separator + data[i][j];
                }
                content += "\n";
            }

            File examplesVsNoise = new File(benchmarkDirectory,
                    "examplesVsNoise-" + heuristicName + "-" + measureName + ".tsv");
            try {
                Files.write(content, examplesVsNoise, Charsets.UTF_8);
            } catch (IOException e) {
                logger.error("failed to write stats to file", e);
            }
        }
    }

    if (write2DB) {
        conn.close();
    }

    if (useEmailNotification) {
        sendFinishedMail();
    }
    long t2 = System.currentTimeMillis();
    long duration = t2 - t1;
    logger.info("QTL evaluation finished in " + DurationFormatUtils.formatDurationHMS(duration) + "ms.");
}

From source file:org.dllearner.algorithms.qtl.experiments.PRConvergenceExperiment.java

public void run(int maxNrOfProcessedQueries, int maxTreeDepth, int[] exampleInterval, double[] noiseInterval,
        HeuristicType[] measures) throws Exception {
    this.maxTreeDepth = maxTreeDepth;
    queryTreeFactory.setMaxDepth(maxTreeDepth);

    if (exampleInterval != null) {
        nrOfExamplesIntervals = exampleInterval;
    }//from www . jav a  2s  .c  om
    if (noiseInterval != null) {
        this.noiseIntervals = noiseInterval;
    }
    if (measures != null) {
        this.measures = measures;
    }

    boolean noiseEnabled = noiseIntervals.length > 1 || noiseInterval[0] > 0;
    boolean posOnly = noiseEnabled ? false : true;

    logger.info("Started QTL evaluation...");
    long t1 = System.currentTimeMillis();

    List<String> queries = dataset.getSparqlQueries().values().stream().map(q -> q.toString())
            .collect(Collectors.toList());
    logger.info("#loaded queries: " + queries.size());

    // filter for debugging purposes
    queries = queries.stream().filter(q -> queriesToProcessTokens.stream().noneMatch(t -> !q.contains(t)))
            .collect(Collectors.toList());
    queries = queries.stream().filter(q -> queriesToOmitTokens.stream().noneMatch(t -> q.contains(t)))
            .collect(Collectors.toList());

    if (maxNrOfProcessedQueries == -1) {
        maxNrOfProcessedQueries = queries.size();
    }

    //      queries = filter(queries, (int) Math.ceil((double) maxNrOfProcessedQueries / maxTreeDepth));
    //      queries = queries.subList(0, Math.min(queries.size(), maxNrOfProcessedQueries));
    logger.info("#queries to process: " + queries.size());

    // generate examples for each query
    logger.info("precomputing pos. and neg. examples...");
    for (String query : queries) {//if(!(query.contains("Borough_(New_York_City)")))continue;
        query2Examples.put(query, generateExamples(query, posOnly, noiseEnabled));
    }
    logger.info("precomputing pos. and neg. examples finished.");

    // check for queries that do not return any result (should not happen, but we never know)
    Set<String> emptyQueries = query2Examples.entrySet().stream()
            .filter(e -> e.getValue().correctPosExampleCandidates.isEmpty()).map(e -> e.getKey())
            .collect(Collectors.toSet());
    logger.info("got {} empty queries.", emptyQueries.size());
    queries.removeAll(emptyQueries);

    // min. pos examples
    int min = 3;
    Set<String> lowNrOfExamplesQueries = query2Examples.entrySet().stream()
            .filter(e -> e.getValue().correctPosExampleCandidates.size() < min).map(e -> e.getKey())
            .collect(Collectors.toSet());
    logger.info("got {} queries with < {} pos. examples.", emptyQueries.size(), min);
    queries.removeAll(lowNrOfExamplesQueries);
    queries = queries.subList(0, Math.min(80, queries.size()));

    final int totalNrOfQTLRuns = heuristics.length * this.measures.length * nrOfExamplesIntervals.length
            * noiseIntervals.length * queries.size();
    logger.info("#QTL runs: " + totalNrOfQTLRuns);

    final AtomicInteger currentNrOfFinishedRuns = new AtomicInteger(0);

    // loop over heuristics
    for (final QueryTreeHeuristic heuristic : heuristics) {
        final String heuristicName = heuristic.getClass().getAnnotation(ComponentAnn.class).shortName();

        // loop over heuristics measures
        for (HeuristicType measure : this.measures) {
            final String measureName = measure.toString();
            heuristic.setHeuristicType(measure);

            double[][] data = new double[nrOfExamplesIntervals.length][noiseIntervals.length];

            // loop over number of positive examples
            for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
                final int nrOfExamples = nrOfExamplesIntervals[i];

                // loop over noise value
                for (int j = 0; j < noiseIntervals.length; j++) {
                    final double noise = noiseIntervals[j];

                    // check if not already processed
                    File logFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-"
                            + heuristicName + "-" + measureName + ".log");
                    File statsFile = new File(benchmarkDirectory, "qtl2-" + nrOfExamples + "-" + noise + "-"
                            + heuristicName + "-" + measureName + ".stats");

                    if (!override && logFile.exists() && statsFile.exists()) {
                        logger.info(
                                "Eval config already processed. For re-running please remove corresponding output files.");
                        continue;
                    }

                    FileAppender appender = null;
                    try {
                        appender = new FileAppender(new SimpleLayout(), logFile.getPath(), false);
                        Logger.getRootLogger().addAppender(appender);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    logger.info("#examples: " + nrOfExamples + " noise: " + noise);

                    final DescriptiveStatistics nrOfReturnedSolutionsStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics baselinePrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselinePredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics baselineMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestReturnedSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestReturnedSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestReturnedSolutionRuntimeStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestSolutionPrecisionStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionRecallStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionFMeasureStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionPredAccStats = new SynchronizedDescriptiveStatistics();
                    final DescriptiveStatistics bestSolutionMathCorrStats = new SynchronizedDescriptiveStatistics();

                    final DescriptiveStatistics bestSolutionPositionStats = new SynchronizedDescriptiveStatistics();

                    MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).reset();
                    MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).reset();

                    ExecutorService tp = Executors.newFixedThreadPool(nrOfThreads);

                    // indicates if the execution for some of the queries failed
                    final AtomicBoolean failed = new AtomicBoolean(false);

                    Set<String> queriesToProcess = new TreeSet<>(queries);
                    queriesToProcess.retainAll(query2Examples.entrySet().stream()
                            .filter(e -> e.getValue().correctPosExampleCandidates.size() >= nrOfExamples)
                            .map(e -> e.getKey()).collect(Collectors.toSet()));

                    // loop over SPARQL queries
                    for (final String sparqlQuery : queriesToProcess) {
                        CBDStructureTree cbdStructure = cbdStructureTree != null ? cbdStructureTree
                                : QueryUtils.getOptimalCBDStructure(QueryFactory.create(sparqlQuery));

                        tp.submit(() -> {
                            logger.info("CBD tree:" + cbdStructure.toStringVerbose());

                            // update max tree depth
                            this.maxTreeDepth = QueryTreeUtils.getDepth(cbdStructure);
                            logger.info("##############################################################");
                            logger.info("Processing query\n" + sparqlQuery);

                            // we repeat it n times with different permutations of examples
                            int nrOfPermutations = 1;

                            if (nrOfExamples >= query2Examples.get(sparqlQuery).correctPosExampleCandidates
                                    .size()) {
                                nrOfPermutations = 1;
                            }
                            for (int perm = 1; perm <= nrOfPermutations; perm++) {
                                logger.info("Run {}/{}", perm, nrOfPermutations);
                                try {
                                    ExamplesWrapper examples = getExamples(sparqlQuery, nrOfExamples,
                                            nrOfExamples, noise, cbdStructure);
                                    logger.info("pos. examples:\n"
                                            + Joiner.on("\n").join(examples.correctPosExamples));
                                    logger.info("neg. examples:\n"
                                            + Joiner.on("\n").join(examples.correctNegExamples));

                                    // write examples to disk
                                    File dir = new File(benchmarkDirectory, "data/" + hash(sparqlQuery));
                                    dir.mkdirs();
                                    Files.write(Joiner.on("\n").join(examples.correctPosExamples), new File(dir,
                                            "examples" + perm + "_" + nrOfExamples + "_" + noise + ".tp"),
                                            Charsets.UTF_8);
                                    Files.write(Joiner.on("\n").join(examples.correctNegExamples), new File(dir,
                                            "examples" + perm + "_" + nrOfExamples + "_" + noise + ".tn"),
                                            Charsets.UTF_8);
                                    Files.write(Joiner.on("\n").join(examples.falsePosExamples), new File(dir,
                                            "examples" + perm + "_" + nrOfExamples + "_" + noise + ".fp"),
                                            Charsets.UTF_8);

                                    // compute baseline
                                    RDFResourceTree baselineSolution = applyBaseLine(examples,
                                            Baseline.MOST_INFORMATIVE_EDGE_IN_EXAMPLES);
                                    logger.info("Evaluating baseline...");
                                    Score baselineScore = computeScore(sparqlQuery, baselineSolution, noise);
                                    logger.info("Baseline score:\n" + baselineScore);
                                    String baseLineQuery = QueryTreeUtils.toSPARQLQueryString(baselineSolution,
                                            dataset.getBaseIRI(), dataset.getPrefixMapping());
                                    baselinePrecisionStats.addValue(baselineScore.precision);
                                    baselineRecallStats.addValue(baselineScore.recall);
                                    baselineFMeasureStats.addValue(baselineScore.fmeasure);
                                    baselinePredAccStats.addValue(baselineScore.predAcc);
                                    baselineMathCorrStats.addValue(baselineScore.mathCorr);

                                    // run QTL
                                    PosNegLPStandard lp = new PosNegLPStandard();
                                    lp.setPositiveExamples(examples.posExamplesMapping.keySet());
                                    lp.setNegativeExamples(examples.negExamplesMapping.keySet());
                                    //                                 QTL2Disjunctive la = new QTL2Disjunctive(lp, qef);
                                    QTL2DisjunctiveMultiThreaded la = new QTL2DisjunctiveMultiThreaded(lp, qef);
                                    la.setRenderer(new org.dllearner.utilities.owl.DLSyntaxObjectRenderer());
                                    la.setReasoner(dataset.getReasoner());
                                    la.setEntailment(Entailment.SIMPLE);
                                    la.setTreeFactory(queryTreeFactory);
                                    la.setPositiveExampleTrees(examples.posExamplesMapping);
                                    la.setNegativeExampleTrees(examples.negExamplesMapping);
                                    la.setNoise(noise);
                                    la.setHeuristic(heuristic);
                                    la.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds);
                                    la.setMaxTreeComputationTimeInSeconds(maxExecutionTimeInSeconds);
                                    la.init();
                                    la.start();
                                    List<EvaluatedRDFResourceTree> solutions = new ArrayList<>(
                                            la.getSolutions());

                                    //                              List<EvaluatedRDFResourceTree> solutions = generateSolutions(examples, noise, heuristic);
                                    nrOfReturnedSolutionsStats.addValue(solutions.size());

                                    // the best returned solution by QTL
                                    EvaluatedRDFResourceTree bestSolution = solutions.get(0);
                                    logger.info("Got " + solutions.size() + " query trees.");
                                    //                                 logger.info("Best computed solution:\n" + render(bestSolution.asEvaluatedDescription()));
                                    logger.info("QTL Score:\n" + bestSolution.getTreeScore());
                                    long runtimeBestSolution = la.getTimeBestSolutionFound();
                                    bestReturnedSolutionRuntimeStats.addValue(runtimeBestSolution);

                                    // convert to SPARQL query
                                    RDFResourceTree tree = bestSolution.getTree();
                                    tree = filter.apply(tree);
                                    String learnedSPARQLQuery = QueryTreeUtils.toSPARQLQueryString(tree,
                                            dataset.getBaseIRI(), dataset.getPrefixMapping());

                                    // compute score
                                    Score score = computeScore(sparqlQuery, tree, noise);
                                    bestReturnedSolutionPrecisionStats.addValue(score.precision);
                                    bestReturnedSolutionRecallStats.addValue(score.recall);
                                    bestReturnedSolutionFMeasureStats.addValue(score.fmeasure);
                                    bestReturnedSolutionPredAccStats.addValue(score.predAcc);
                                    bestReturnedSolutionMathCorrStats.addValue(score.mathCorr);
                                    logger.info(score.toString());

                                    // find the extensionally best matching tree in the list
                                    Pair<EvaluatedRDFResourceTree, Score> bestMatchingTreeWithScore = findBestMatchingTreeFast(
                                            solutions, sparqlQuery, noise, examples);
                                    EvaluatedRDFResourceTree bestMatchingTree = bestMatchingTreeWithScore
                                            .getFirst();
                                    Score bestMatchingScore = bestMatchingTreeWithScore.getSecond();

                                    // position of best tree in list of solutions
                                    int positionBestScore = solutions.indexOf(bestMatchingTree);
                                    bestSolutionPositionStats.addValue(positionBestScore);

                                    Score bestScore = score;
                                    if (positionBestScore > 0) {
                                        logger.info(
                                                "Position of best covering tree in list: " + positionBestScore);
                                        logger.info("Best covering solution:\n"
                                                + render(bestMatchingTree.asEvaluatedDescription()));
                                        logger.info("Tree score: " + bestMatchingTree.getTreeScore());
                                        bestScore = bestMatchingScore;
                                        logger.info(bestMatchingScore.toString());
                                    } else {
                                        logger.info(
                                                "Best returned solution was also the best covering solution.");
                                    }
                                    bestSolutionRecallStats.addValue(bestScore.recall);
                                    bestSolutionPrecisionStats.addValue(bestScore.precision);
                                    bestSolutionFMeasureStats.addValue(bestScore.fmeasure);
                                    bestSolutionPredAccStats.addValue(bestScore.predAcc);
                                    bestSolutionMathCorrStats.addValue(bestScore.mathCorr);

                                    for (RDFResourceTree negTree : examples.negExamplesMapping.values()) {
                                        if (QueryTreeUtils.isSubsumedBy(negTree, bestMatchingTree.getTree())) {
                                            Files.append(sparqlQuery + "\n", new File("/tmp/negCovered.txt"),
                                                    Charsets.UTF_8);
                                            break;
                                        }
                                    }

                                    String bestQuery = QueryFactory
                                            .create(QueryTreeUtils.toSPARQLQueryString(
                                                    filter.apply(bestMatchingTree.getTree()),
                                                    dataset.getBaseIRI(), dataset.getPrefixMapping()))
                                            .toString();

                                    if (write2DB) {
                                        write2DB(sparqlQuery, nrOfExamples, examples, noise, baseLineQuery,
                                                baselineScore, heuristicName, measureName,
                                                QueryFactory.create(learnedSPARQLQuery).toString(), score,
                                                runtimeBestSolution, bestQuery, positionBestScore, bestScore);
                                    }

                                } catch (Exception e) {
                                    failed.set(true);
                                    logger.error("Error occured for query\n" + sparqlQuery, e);
                                    try {
                                        StringWriter sw = new StringWriter();
                                        PrintWriter pw = new PrintWriter(sw);
                                        e.printStackTrace(pw);
                                        Files.append(sparqlQuery + "\n" + sw.toString(),
                                                new File(benchmarkDirectory,
                                                        "failed-" + nrOfExamples + "-" + noise + "-"
                                                                + heuristicName + "-" + measureName + ".txt"),
                                                Charsets.UTF_8);
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }
                                } finally {
                                    int cnt = currentNrOfFinishedRuns.incrementAndGet();
                                    logger.info("***********Evaluation Progress:"
                                            + NumberFormat.getPercentInstance()
                                                    .format((double) cnt / totalNrOfQTLRuns)
                                            + "(" + cnt + "/" + totalNrOfQTLRuns + ")" + "***********");
                                }
                            }
                        });
                    }

                    tp.shutdown();
                    tp.awaitTermination(12, TimeUnit.HOURS);

                    Logger.getRootLogger().removeAppender(appender);

                    if (!failed.get()) {
                        String result = "";
                        result += "\nBaseline Precision:\n" + baselinePrecisionStats;
                        result += "\nBaseline Recall:\n" + baselineRecallStats;
                        result += "\nBaseline F-measure:\n" + baselineFMeasureStats;
                        result += "\nBaseline PredAcc:\n" + baselinePredAccStats;
                        result += "\nBaseline MathCorr:\n" + baselineMathCorrStats;

                        result += "#Returned solutions:\n" + nrOfReturnedSolutionsStats;

                        result += "\nOverall Precision:\n" + bestReturnedSolutionPrecisionStats;
                        result += "\nOverall Recall:\n" + bestReturnedSolutionRecallStats;
                        result += "\nOverall F-measure:\n" + bestReturnedSolutionFMeasureStats;
                        result += "\nOverall PredAcc:\n" + bestReturnedSolutionPredAccStats;
                        result += "\nOverall MathCorr:\n" + bestReturnedSolutionMathCorrStats;

                        result += "\nTime until best returned solution found:\n"
                                + bestReturnedSolutionRuntimeStats;

                        result += "\nPositions of best solution:\n"
                                + Arrays.toString(bestSolutionPositionStats.getValues());
                        result += "\nPosition of best solution stats:\n" + bestSolutionPositionStats;
                        result += "\nOverall Precision of best solution:\n" + bestSolutionPrecisionStats;
                        result += "\nOverall Recall of best solution:\n" + bestSolutionRecallStats;
                        result += "\nOverall F-measure of best solution:\n" + bestSolutionFMeasureStats;

                        result += "\nCBD generation time(total):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getTotal()
                                + "\n";
                        result += "CBD generation time(avg):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.CBD_RETRIEVAL.name()).getAvg()
                                + "\n";
                        result += "Tree generation time(total):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getTotal()
                                + "\n";
                        result += "Tree generation time(avg):\t"
                                + MonitorFactory.getTimeMonitor(TimeMonitors.TREE_GENERATION.name()).getAvg()
                                + "\n";
                        result += "Tree size(avg):\t" + treeSizeStats.getMean() + "\n";

                        logger.info(result);

                        try {
                            Files.write(result, statsFile, Charsets.UTF_8);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        data[i][j] = bestReturnedSolutionFMeasureStats.getMean();

                        if (write2DB) {
                            write2DB(heuristicName, measureName, nrOfExamples, noise,
                                    bestReturnedSolutionFMeasureStats.getMean(),
                                    bestReturnedSolutionPrecisionStats.getMean(),
                                    bestReturnedSolutionRecallStats.getMean(),
                                    bestReturnedSolutionPredAccStats.getMean(),
                                    bestReturnedSolutionMathCorrStats.getMean(),
                                    bestSolutionPositionStats.getMean(), bestSolutionFMeasureStats.getMean(),
                                    bestSolutionPrecisionStats.getMean(), bestSolutionRecallStats.getMean(),
                                    bestSolutionPredAccStats.getMean(), bestSolutionMathCorrStats.getMean(),
                                    baselineFMeasureStats.getMean(), baselinePrecisionStats.getMean(),
                                    baselineRecallStats.getMean(), baselinePredAccStats.getMean(),
                                    baselineMathCorrStats.getMean(),
                                    bestReturnedSolutionRuntimeStats.getMean());
                        }
                    }
                }
            }

            String content = "###";
            String separator = "\t";
            for (double noiseInterval1 : noiseIntervals) {
                content += separator + noiseInterval1;
            }
            content += "\n";
            for (int i = 0; i < nrOfExamplesIntervals.length; i++) {
                content += nrOfExamplesIntervals[i];
                for (int j = 0; j < noiseIntervals.length; j++) {
                    content += separator + data[i][j];
                }
                content += "\n";
            }

            File examplesVsNoise = new File(benchmarkDirectory,
                    "examplesVsNoise-" + heuristicName + "-" + measureName + ".tsv");
            try {
                Files.write(content, examplesVsNoise, Charsets.UTF_8);
            } catch (IOException e) {
                logger.error("failed to write stats to file", e);
            }
        }
    }

    if (write2DB) {
        conn.close();
    }

    if (useEmailNotification) {
        sendFinishedMail();
    }
    long t2 = System.currentTimeMillis();
    long duration = t2 - t1;
    logger.info("QTL evaluation finished in " + DurationFormatUtils.formatDurationHMS(duration) + "ms.");
}

From source file:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/addProjectStatus/{prismId}/{applicationId}", method = RequestMethod.POST)
public String addProjectStatus(@PathVariable("prismId") String prismId,
        @PathVariable("applicationId") String applicationId,
        @Valid @ModelAttribute("projectStatusViewModel") ProjectStatusViewModel projectStatusViewModel,
        HttpServletRequest request, BindingResult result) {
    String sessionUser = (String) request.getSession().getAttribute("loginUser");
    if (sessionUser == null || sessionUser.isEmpty() || "Not Logged In".equalsIgnoreCase(sessionUser)) {
        request.getSession().setAttribute("loginUser", "Not Logged In");
        logger.error("[Merce]: user not logged in.. redirecting to logout page");
        return "redirect:/logout";
    }//from   w  w w .j a  v  a 2 s  .  c  o m

    NumberFormat defaultFormat = NumberFormat.getPercentInstance();
    defaultFormat.setMinimumFractionDigits(0);
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    int appId = Integer.parseInt(applicationId);
    String appName = DataService.getApplicationNameByPrismIdApplicationId(appId, prismId);
    int impactTypeId = DataService.getImpactTypeIdByPrismIdAndApplicationName(prismId, appName);

    if (result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        for (ObjectError r : result.getAllErrors()) {
            sb.append(r.getDefaultMessage());
        }
        logger.error(msgHeader + " addProjectStatus errors: " + sb.toString());
    }

    // refresh cahce?
    if (artifactHistory != null) {
        artifactHistory = null;
    }
    DataService.initializeProjectAppOwnerByPrismId(prismId);

    // TO
    if (impactTypeId != 3 && impactTypeId != 4) {
        // prefix. Agile
        if (projectStatusViewModel.getAgilePercentageComplete() == null
                || projectStatusViewModel.getAgilePercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus Agile is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus Agile is set, updateing ..");

            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.AGILE);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getAgilePercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getAgilePercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getAgilePercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getAgilePercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getAgileDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getAgileDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAgileDateCreatedT());
                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getAgileDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAgileDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.AGILE, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getAgilePercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getAgilePercentageComplete())))) {
                    logger.error("Agile has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 1. BR
        if (projectStatusViewModel.getBRPercentageComplete() == null
                || projectStatusViewModel.getBRPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus BR is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus BR is set, updateing ..");

            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.BR);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getBRPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getBRPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getBRPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getBRPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getBRDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getBRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getBRDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getBRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getBRDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.BR, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getBRPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getBRPercentageComplete())))) {
                    logger.error("BR has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 2. SR
        if (projectStatusViewModel.getSRPercentageComplete() == null
                || projectStatusViewModel.getSRPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus SR is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus SR is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.SR);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getSRPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getSRPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getSRPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getSRPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getSRDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getSRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getSRDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getSRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getSRDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.SR, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getSRPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getSRPercentageComplete())))) {
                    logger.error("SR has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }

            }
        }

        // 3. HLD
        if (projectStatusViewModel.getHLDPercentageComplete() == null
                || projectStatusViewModel.getHLDPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus HLD is not set, so keep record in database as is.");
        } else {
            logger.error(
                    msgHeader + " addProjectStatus HLD is set, updateing .. " + prismId + ", " + applicationId);
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.HLD);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getHLDPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getHLDPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getHLDPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getHLDPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getHLDDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getHLDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getHLDDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getHLDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getHLDDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.HLD, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getHLDPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getHLDPercentageComplete())))) {
                    logger.error("HLD has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 4. AID
        if (projectStatusViewModel.getAIDPercentageComplete() == null
                || projectStatusViewModel.getAIDPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus AID is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus AID is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.AID);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getAIDPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getAIDPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getAIDPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getAIDPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getAIDDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getAIDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAIDDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getAIDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAIDDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.AID, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getAIDPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getAIDPercentageComplete())))) {
                    logger.error("AID has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 5. DES
        if (projectStatusViewModel.getDESPercentageComplete() == null
                || projectStatusViewModel.getDESPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus DES is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus DES is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.DES);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getDESPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getDESPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getDESPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getDESPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getDESDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getDESDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDESDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getDESDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDESDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.DES, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getDESPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getDESPercentageComplete())))) {
                    logger.error("DES has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 6. DEV
        if (projectStatusViewModel.getDEVPercentageComplete() == null
                || projectStatusViewModel.getDEVPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus DEV is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus DEV is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.DEV);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getDEVPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getDEVPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getDEVPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getDEVPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getDEVDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getDEVDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDEVDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getDEVDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDEVDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.DEV, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getDEVPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getDEVPercentageComplete())))) {
                    logger.error("DEV has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

    } // end not impacttypeid = 3, to and tso 4

    // 7. IST
    if (projectStatusViewModel.getISTPercentageComplete() == null
            || projectStatusViewModel.getISTPercentageComplete().isEmpty()) {
        logger.error(msgHeader + " addProjectStatus IST is not set, so keep record in database as is.");
    } else {
        logger.error(msgHeader + " addProjectStatus IST is set, updateing ..");
        ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                prismId, Integer.valueOf(applicationId), PiratesConstants.IST);
        if (mod != null && !mod.getPercentageComplete()
                .equalsIgnoreCase(defaultFormat.format(
                        Double.parseDouble(projectStatusViewModel.getISTPercentageComplete() == null ? "0"
                                : projectStatusViewModel.getISTPercentageComplete())))) {
            ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
            // now change the percentage completed to user input value
            mod.setPercentageComplete(projectStatusViewModel.getISTPercentageComplete());

            // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
            try {
                if (projectStatusViewModel.getISTPercentageComplete().equalsIgnoreCase("1.00")
                        && !sdf.format(sdf.parse(projectStatusViewModel.getISTDateCreatedT()))
                                .equals(sdf.format(new Date()))) {
                    logger.error(
                            "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                    + projectStatusViewModel.getISTDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTDateCreatedT());

                } else {
                    logger.error("User chooses to use today as datecreated, using it .. "
                            + projectStatusViewModel.getISTDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTDateCreatedT());
                }
            } catch (ParseException ex) {
                logger.error(msgHeader + ex.getMessage());
            }

            DataService.processProjectStatusForArtifact(mod, PiratesConstants.IST, sessionUser, p);
        } else {
            if (mod != null && mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getISTPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getISTPercentageComplete())))) {
                logger.error("IST has same value as in the DB, ignoring..");
            } else {
                logger.error(
                        "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
            }
        }
    }

    // 8. ISTExec
    if (projectStatusViewModel.getISTExecPercentageComplete() == null
            || projectStatusViewModel.getISTExecPercentageComplete().isEmpty()) {
        logger.error(msgHeader + " addProjectStatus ISTExec is not set, so keep record in database as is.");
    } else {
        logger.error(msgHeader + " addProjectStatus ISTExec is set, updateing ..");
        ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                prismId, Integer.valueOf(applicationId), PiratesConstants.ISTExec);
        if (mod != null && !mod.getPercentageComplete()
                .equalsIgnoreCase(defaultFormat.format(
                        Double.parseDouble(projectStatusViewModel.getISTExecPercentageComplete() == null ? "0"
                                : projectStatusViewModel.getISTExecPercentageComplete())))) {
            ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
            // now change the percentage completed to user input value
            mod.setPercentageComplete(projectStatusViewModel.getISTExecPercentageComplete());

            // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
            try {
                if (projectStatusViewModel.getISTExecPercentageComplete().equalsIgnoreCase("1.00")
                        && !sdf.format(sdf.parse(projectStatusViewModel.getISTExecDateCreatedT()))
                                .equals(sdf.format(new Date()))) {
                    logger.error(
                            "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                    + projectStatusViewModel.getISTExecDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTExecDateCreatedT());

                } else {
                    logger.error("User chooses to use today as datecreated, using it .. "
                            + projectStatusViewModel.getISTExecDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTExecDateCreatedT());
                }
            } catch (ParseException ex) {
                logger.error(msgHeader + ex.getMessage());
            }

            DataService.processProjectStatusForArtifact(mod, PiratesConstants.ISTExec, sessionUser, p);
        } else {
            if (mod != null && mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(Double
                            .parseDouble(projectStatusViewModel.getISTExecPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getISTExecPercentageComplete())))) {
                logger.error("ISTExec has same value as in the DB, ignoring..");
            } else {
                logger.error(
                        "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
            }
        }
    }

    if (impactTypeId != 3 && impactTypeId != 4) {
        // 8. CloseOut
        if (projectStatusViewModel.getCloseOutPercentageComplete() == null
                || projectStatusViewModel.getCloseOutPercentageComplete().isEmpty()) {
            logger.error(
                    msgHeader + " addProjectStatus Closeout is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus Closeout is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.CLOSEOUT);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(Double
                            .parseDouble(projectStatusViewModel.getCloseOutPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getCloseOutPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getCloseOutPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getCloseOutPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getCODateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getCODateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getCODateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getCODateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getCODateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.CLOSEOUT, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double.parseDouble(
                                projectStatusViewModel.getCloseOutPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getCloseOutPercentageComplete())))) {
                    logger.error("CloseOut has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }
    } // end  && impactTypeId != 4 (TSO) &&  && impactTypeId != 3 (TO)

    // prismId will be considered while expanding the placeholders
    // return "redirect:/impact_pirates/projects/index/{prismId}";
    if (artifactHistory != null) {
        artifactHistory = null;
    }
    DataService.initializeProjectAppOwnerByPrismId(prismId);
    return "redirect:/projects/index/{prismId}";
}

From source file:org.evosuite.utils.ReportGenerator.java

/**
 * Write some overall stats/*from   w  w  w .  j av a2s  .c o m*/
 * 
 * @param buffer
 *            a {@link java.lang.StringBuffer} object.
 * @param entry
 *            a {@link org.evosuite.utils.ReportGenerator.StatisticEntry}
 *            object.
 */
protected void writeResultTable(StringBuffer buffer, StatisticEntry entry) {

    //buffer.append("<h2>Statistics</h2>\n");
    buffer.append("<ul>\n");

    buffer.append("<li>");
    buffer.append(entry.result_fitness_evaluations);
    buffer.append(" fitness evaluations, ");
    buffer.append(entry.age);
    buffer.append(" generations, ");
    buffer.append(entry.result_statements_executed);
    buffer.append(" statements, ");
    buffer.append(entry.result_tests_executed);
    buffer.append(" tests.\n");

    long duration_GA = (entry.end_time - entry.start_time) / 1000;
    long duration_MI = (entry.minimized_time - entry.end_time) / 1000;
    long duration_TO = (entry.minimized_time - entry.start_time) / 1000;

    buffer.append("<li>Time: "
            + String.format("%d:%02d:%02d", duration_TO / 3600, (duration_TO % 3600) / 60, (duration_TO % 60)));

    buffer.append("(Search: "
            + String.format("%d:%02d:%02d", duration_GA / 3600, (duration_GA % 3600) / 60, (duration_GA % 60))
            + ", ");
    buffer.append("minimization: "
            + String.format("%d:%02d:%02d", duration_MI / 3600, (duration_MI % 3600) / 60, (duration_MI % 60))
            + ")\n");

    buffer.append("<li>Coverage: " + entry.covered_branches + "/" + (2 * entry.total_branches) + " branches, ");
    buffer.append(entry.covered_methods + "/" + entry.total_methods + " methods, ");
    buffer.append(entry.covered_goals + "/" + entry.total_goals + " total goals\n");
    buffer.append(
            "<li>Mutation score: " + NumberFormat.getPercentInstance().format(entry.mutationScore) + "\n");

    buffer.append("</ul>\n");
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private JFreeChart renderPieChart(cfSession _Session, cfCHARTInternalData chartData,
        List<cfCHARTSERIESData> series, String tipStyle, String drillDownUrl) throws cfmRunTimeException {
    // Retrieve the attributes of the chart
    String backgroundColorStr = getDynamic(_Session, "BACKGROUNDCOLOR").toString();
    Color backgroundColor = convertStringToColor(backgroundColorStr);

    String foregroundColorStr = getDynamic(_Session, "FOREGROUNDCOLOR").toString();
    Color foregroundColor = convertStringToColor(foregroundColorStr);

    String labelFormat = getDynamic(_Session, "LABELFORMAT").toString().toLowerCase();
    if (!labelFormat.equals("number") && !labelFormat.equals("currency") && !labelFormat.equals("percent"))
        throw newRunTimeException(
                "The labelFormat value '" + labelFormat + "' is not supported with pie charts");

    String pieSliceStyle = getDynamic(_Session, "PIESLICESTYLE").toString().toLowerCase();

    String title = null;//from w ww.ja v  a 2  s  .c  o m
    if (containsAttribute("TITLE"))
        title = getDynamic(_Session, "TITLE").toString();

    Font font = getFont(_Session);

    cfCHARTSERIESData seriesData = series.get(0);

    boolean bShow3D = getDynamic(_Session, "SHOW3D").getBoolean();
    if (bShow3D && !seriesData.getType().equals("pie"))
        throw newRunTimeException("Only bar, line, horizontal bar and pie charts can be displayed in 3D");

    boolean bShowBorder = getDynamic(_Session, "SHOWBORDER").getBoolean();

    boolean bShowLegend = true; // default to true for pie charts
    if (containsAttribute("SHOWLEGEND"))
        bShowLegend = getDynamic(_Session, "SHOWLEGEND").getBoolean();

    // Get the plot for the chart and configure it
    PiePlot plot = getPiePlot(series, pieSliceStyle, bShow3D);
    setBackgroundImage(_Session, plot, chartData.getImageData());
    plot.setBackgroundPaint(backgroundColor);
    plot.setLabelBackgroundPaint(backgroundColor);
    plot.setLabelShadowPaint(backgroundColor);

    // Set the labels color
    plot.setLabelPaint(convertStringToColor(seriesData.getDataLabelColor()));

    // Set the labels font
    plot.setLabelFont(getFont(seriesData.getDataLabelFont(), seriesData.getDataLabelFontBold(),
            seriesData.getDataLabelFontItalic(), seriesData.getDataLabelFontSize()));

    String dataLabelStyle = seriesData.getDataLabelStyle();

    NumberFormat percentInstance = NumberFormat.getPercentInstance();
    percentInstance.setMaximumFractionDigits(3);

    NumberFormat numberFormat = null;
    if (labelFormat.equals("number")) {
        // Only display the value in the Label as a number
        numberFormat = NumberFormat.getInstance();
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}"));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0} {1} ({2} of {3})"));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern));
        }
    } else if (labelFormat.equals("currency")) {
        // Only display the value in the Label as a currency
        numberFormat = NumberFormat.getCurrencyInstance();
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}",
                    NumberFormat.getCurrencyInstance(), percentInstance));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(
                    "{0} {1} ({2} of {3})", NumberFormat.getCurrencyInstance(), percentInstance));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern,
                    NumberFormat.getCurrencyInstance(), percentInstance));
        }
    } else if (labelFormat.equals("percent")) {
        // Only display the value in the Label as a percent
        numberFormat = percentInstance;
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}",
                    percentInstance, percentInstance));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(
                    "{0} {1} ({2} of {3})", percentInstance, percentInstance));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern,
                    percentInstance, percentInstance));
        }
    }

    if (!tipStyle.equals("none")) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator(
                StandardPieToolTipGenerator.DEFAULT_SECTION_LABEL_FORMAT, numberFormat, numberFormat));
    }

    if (drillDownUrl != null) {
        plot.setURLGenerator(new com.newatlanta.bluedragon.PieURLGenerator(drillDownUrl, numberFormat));
    }

    // Get the chart and configure it
    JFreeChart chart = new JFreeChart(null, null, plot, false);
    chart.setBorderVisible(bShowBorder);
    chart.setBackgroundPaint(backgroundColor);
    setTitle(chart, title, font, foregroundColor, chartData.getTitles());
    setLegend(chart, bShowLegend, font, foregroundColor, backgroundColor, chartData.getLegendData());

    return chart;
}

From source file:org.exist.storage.dom.DOMFile.java

public void printStatistics() {
    super.printStatistics();
    final NumberFormat nf1 = NumberFormat.getPercentInstance();
    final NumberFormat nf2 = NumberFormat.getInstance();
    final StringBuilder buf = new StringBuilder();
    buf.append(getFile().getName()).append(" DATA ");
    buf.append("Buffers occupation : ");
    if (dataCache.getBuffers() == 0 && dataCache.getUsedBuffers() == 0) {
        buf.append("N/A");
    } else {/*from   w ww.  j a  v a  2 s  . c  o  m*/
        buf.append(nf1.format(dataCache.getUsedBuffers() / (float) dataCache.getBuffers()));
    }
    buf.append(" (" + nf2.format(dataCache.getUsedBuffers()) + " out of " + nf2.format(dataCache.getBuffers())
            + ")");
    buf.append(" Cache efficiency : ");
    if (dataCache.getHits() == 0 && dataCache.getFails() == 0) {
        buf.append("N/A");
    } else {
        buf.append(nf1.format(dataCache.getHits() / (float) (dataCache.getFails() + dataCache.getHits())));
    }
    LOGSTATS.info(buf.toString());
}