Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:org.neuroph.netbeans.main.easyneurons.NeuralGraphRenderer.java

/**
 * Generates a mixed-mode random graph, runs VoltageRanker on it, and
 * returns the resultant graph.//  ww  w  .j av a2  s .c  om
 */
public Graph createGraph() {

    Graph<Neuron, Connection> g = new DirectedSparseGraph<Neuron, Connection>();

    //      Iterator<Layer> li = this.neuralNet.getLayersIterator();
    //      while (li.hasNext()) {
    for (Layer layer : this.neuralNet.getLayers()) {
        //         Layer layer = li.next();
        //         Iterator<Neuron> ni = layer.getNeuronsIterator();
        //         while (ni.hasNext()) {
        //            Neuron neuron = ni.next();
        for (Neuron neuron : layer.getNeurons()) {
            g.addVertex(neuron);

            //            Iterator<Connection> ci = neuron.getInputConnections().iterator();
            //            while (ci.hasNext()) {
            //               Connection connection = ci.next();
            for (Connection connection : neuron.getInputConnections()) {
                Neuron fromNeuron = connection.getFromNeuron(); // .getConnectedNeuron();
                g.addEdge(connection, fromNeuron, neuron);

                // used for highlighting weights
                edge_weight.put(connection, connection.getWeight().getValue());
            }
        }
    }

    voltages = new Transformer<Neuron, Double>() {
        @Override
        public Double transform(Neuron n) {
            return n.getOutput();
        }
    };

    vs = new Transformer<Neuron, String>() {
        @Override
        public String transform(Neuron n) {
            NumberFormat numberFormat = DecimalFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(4);

            return numberFormat.format(n.getOutput());
        }
    };

    es = new Transformer<Connection, String>() {
        @Override
        public String transform(Connection c) {
            NumberFormat numberFormat = DecimalFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(5);

            return numberFormat.format(c.getWeight().getValue());
        }
    };

    return g;
}

From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java

private void addDataset(String pId, XYDataset pDataset) {
    if (chart == null) {
        setupChart(pId, pDataset);/*from  w  ww .  j av a2 s. co  m*/
    } else {
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDataset(plot.getDatasetCount(), pDataset);
        NumberAxis axis = new NumberAxis(pId);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(0);
        axis.setNumberFormatOverride(nf);
        plot.setRangeAxis(plot.getDatasetCount() - 1, axis);
        plot.setRangeAxisLocation(plot.getDatasetCount() - 1, AxisLocation.TOP_OR_LEFT);
        plot.mapDatasetToRangeAxis(plot.getDatasetCount() - 1, plot.getDatasetCount() - 1);
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(0, jShowDataPoints.isSelected());
        plot.setRenderer(plot.getDatasetCount() - 1, renderer);
        renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
        renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
        renderer.setDefaultToolTipGenerator(
                new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                        new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
        axis.setAxisLinePaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickMarkPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java

private void setupChart(String pInitialId, XYDataset pInitialDataset) {
    chart = ChartFactory.createTimeSeriesChart("Spielerstatistiken", // title
            "Zeiten", // x-axis label
            pInitialId, // y-axis label
            pInitialDataset, // data
            jShowLegend.isSelected(), // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );//w  ww .j a  v  a  2 s .  com

    chart.setBackgroundPaint(Constants.DS_BACK);
    XYPlot plot = (XYPlot) chart.getPlot();
    setupPlotDrawing(plot);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    for (int i = 0; i < plot.getSeriesCount(); i++) {
        renderer.setSeriesLinesVisible(i, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(i, jShowDataPoints.isSelected());
        plot.setRenderer(i, renderer);
    }

    renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
    renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
    renderer.setDefaultToolTipGenerator(
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
    int lastDataset = plot.getDatasetCount() - 1;
    if (lastDataset > 0) {
        plot.getRangeAxis().setAxisLinePaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setTickLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setTickMarkPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
    }
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    NumberAxis na = ((NumberAxis) plot.getRangeAxis());
    if (na != null) {
        na.setNumberFormatOverride(nf);
    }
}

From source file:org.yccheok.jstock.gui.NewBuyTransactionJDialog.java

private JFormattedTextField getCurrencyJFormattedTextField() {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(4);
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setMinimum(0.0);/*from  w  ww.  j  a  va  2  s.  c o  m*/
    formatter.setValueClass(Double.class);
    JFormattedTextField formattedTextField = new JFormattedTextField(formatter);
    formattedTextField.addMouseListener(getJFormattedTextFieldMouseListener());
    return formattedTextField;
}

From source file:de.tor.tribes.ui.views.DSWorkbenchReportFrame.java

private void fireRebuildStatsEvent() {
    List selection = jList1.getSelectedValuesList();
    if (selection == null || selection.isEmpty()) {
        jOverallStatsArea.setText("<html>Kein Stamm ausgewhlt</html>");
        jAllyStatsArea.setText("<html>Kein Stamm ausgewhlt</html>");
        jTribeStatsArea.setText("<html>Kein Stamm ausgewhlt</html>");
        return;/*from w ww. j  av  a  2s . c o  m*/
    }
    int overallDefAllies = lastStats.getDefendingAllies().length;
    int overallDefTribes = lastStats.getDefendingTribes().length;

    NumberFormat f = NumberFormat.getInstance();
    f.setMinimumFractionDigits(0);
    f.setMaximumFractionDigits(0);

    StringBuilder allyBuffer = new StringBuilder();
    StringBuilder tribeBuffer = new StringBuilder();
    HashMap<Ally, AllyStatResult> allyResults = new HashMap<>();
    OverallStatResult overallResult = new OverallStatResult();
    for (Object o : selection) {
        Ally a = (Ally) o;
        AllyStatResult result = new AllyStatResult();
        allyResults.put(a, result);
        for (Tribe t : lastStats.getAttackingTribes(a)) {
            TribeStatResult tribeResult = new TribeStatResult();
            SingleAttackerStat stats = lastStats.getStatsForTribe(t);
            tribeResult.setTribeStats(stats, jGuessUnknownLosses.isSelected());
            result.addTribeStatResult(tribeResult);
        }
        overallResult.addAllyStatsResult(result);
    }
    overallResult.setStartDate(lastStats.getStartDate());
    overallResult.setEndDate(lastStats.getEndDate());
    overallResult.setReportCount(lastStats.getReportCount());
    overallResult.setAttackerAllies(selection.size());
    overallResult.setDefenders(overallDefTribes);
    overallResult.setDefenderAllies(overallDefAllies);

    for (Ally a : allyResults.keySet()) {
        AllyStatResult res = allyResults.get(a);
        res.setAlly(a);
        res.setOverallKills(overallResult.getKills());
        res.setOverallLosses(overallResult.getLosses());

        for (TribeStatResult tRes : res.getTribeStats()) {
            tRes.setOverallKills(res.getOverallKills());
            tRes.setOverallLosses(res.getOverallLosses());
            tRes.setAllyKills(res.getKills());
            tRes.setAllyLosses(res.getLosses());
        }
    }

    try {
        List<OverallStatResult> list = Arrays.asList(overallResult);
        overallResultCodes = new OverallReportStatsFormatter().formatElements(list, true);
        jOverallStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>"
                + BBCodeFormatter.toHtml(overallResultCodes) + "</body></html>");
    } catch (Exception e) {
        overallResultCodes = null;
        jOverallStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>");
        logger.error("Failed to render overall BB representation", e);
    }
    try {
        List<AllyStatResult> list = new LinkedList<>();
        CollectionUtils.addAll(list, allyResults.values());
        allyResultCodes = new AllyReportStatsFormatter().formatElements(list, true);
        jAllyStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>"
                + BBCodeFormatter.toHtml(allyResultCodes) + "</body></html>");
    } catch (Exception e) {
        allyResultCodes = null;
        jAllyStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>");
        logger.error("Failed to render BB representation for allies", e);
    }

    try {
        List<TribeStatResult> list = new LinkedList<>();
        for (AllyStatResult allyStat : allyResults.values()) {
            Collections.addAll(list,
                    allyStat.getTribeStats().toArray(new TribeStatResult[allyStat.getTribeStats().size()]));
        }
        tribeResultCodes = new TribeReportStatsFormatter().formatElements(list, true);
        jTribeStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>"
                + BBCodeFormatter.toHtml(tribeResultCodes) + "</body></html>");
    } catch (Exception e) {
        tribeResultCodes = null;
        jTribeStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>");
        logger.error("Failed to render BB representation for tribes", e);
    }
    jResultTabbedPane.setSelectedIndex(0);
}

From source file:com.vip.saturn.job.console.service.impl.JobDimensionServiceImpl.java

public String geJobRunningInfo(final String jobName) {
    String serverNodePath = JobNodePath.getServerNodePath(jobName);
    CuratorRepository.CuratorFrameworkOp curatorFrameworkOp = curatorRepository.inSessionClient();
    if (!curatorFrameworkOp.checkExists(serverNodePath)) {
        return "";
    }//from  w  ww. ja va 2  s . c om
    List<String> servers = curatorFrameworkOp.getChildren(serverNodePath);
    // serverServer?Crashed
    if (servers == null || servers.size() == 0) {
        return "";
    }

    int processSuccessCount = 0;
    int processFailureCount = 0;

    for (String each : servers) {
        String processSuccessCountStr = curatorFrameworkOp
                .getData(JobNodePath.getServerNodePath(jobName, each, "processSuccessCount"));
        if (!Strings.isNullOrEmpty(processSuccessCountStr)) {
            processSuccessCount += Integer.parseInt(processSuccessCountStr);
        }

        String processFailureCountStr = curatorFrameworkOp
                .getData(JobNodePath.getServerNodePath(jobName, each, "processFailureCount"));
        if (!Strings.isNullOrEmpty(processFailureCountStr)) {
            processFailureCount += Integer.parseInt(processFailureCountStr);
        }
    }

    int count = processSuccessCount;
    int total = processSuccessCount + processFailureCount;
    if (total == 0) {
        return "";
    }
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setMaximumFractionDigits(2);
    String result = numberFormat.format((double) count / (double) total * 100);
    return result + "%";
}

From source file:org.prom5.framework.log.filter.LogEventLogFilterEnh.java

/**
 * Returns a Panel for the setting of parameters. When a LogFilter can be
 * added to a list in the framework. This panel is shown, and parameters can
 * be set. When the dialog is closed, a new instance of a LogFilter is
 * created by the framework by calling the <code>getNewLogFilter</code> method
 * of the dialog.// w  ww  .  ja va 2 s.co m
 *
 * @param summary A LogSummary to be used for setting parameters.
 * @return JPanel
 */
public LogFilterParameterDialog getParameterDialog(LogSummary summary) {
    return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) {

        LogEventCheckBoxEnh[] checks;
        JSpinner percTaskSpinner;
        JSpinner percPiSpinner;
        JComboBox choiceBox;

        /**
         * Keep the statistics for all the tasks
         */
        SummaryStatistics taskStatistics = null;

        /**
         * Keep the statistics for the occurrence of tasks in process instances
         */
        SummaryStatistics piStatistics = null;

        public LogFilter getNewLogFilter() {
            LogEvents e = new LogEvents();
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    e.add(checks[i].getLogEvent());
                }
            }
            return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()),
                    getDoubleValueFromSpinner(percPiSpinner.getValue()),
                    choiceBox.getSelectedItem().toString());
        }

        protected JPanel getPanel() {
            // add message to the test log for this plugin
            Message.add("<EnhEvtLogFilter>", Message.TEST);
            // statistics
            taskStatistics = SummaryStatistics.newInstance();
            piStatistics = SummaryStatistics.newInstance();
            // Set up an percentformatter
            NumberFormat percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMinimumFractionDigits(2);
            percentFormatter.setMaximumFractionDigits(2);
            // Instantiate the spinners
            percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            // generate the buttons that are needed
            JButton jButtonCalculate = new JButton("Calculate");
            JButton jButtonInvert = new JButton("Invert selection");
            // set up a choicebox to indicate whether the relationship between the two
            // percentages is AND or OR.

            percTaskSpinner.setValue(new Double(percentageTask));
            percPiSpinner.setValue(new Double(percentagePI));

            choiceBox = new JComboBox();
            choiceBox.addItem("AND");
            choiceBox.addItem("OR");
            choiceBox.setSelectedItem(selectedItemComboBox);

            // Some values that are needed for the sequel.
            int size = summary.getLogEvents().size();
            // For the new log reader sumATEs should be calculated in another way
            int sumATEs = 0;
            if (summary instanceof ExtendedLogSummary) {
                sumATEs = summary.getNumberOfAuditTrailEntries();
            } else if (summary instanceof LightweightLogSummary) {
                HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>();
                Iterator logEvents = summary.getLogEvents().iterator();
                while (logEvents.hasNext()) {
                    LogEvent evt = (LogEvent) logEvents.next();
                    pis.addAll(summary.getInstancesForEvent(evt));
                }
                Iterator pis2 = pis.iterator();
                while (pis2.hasNext()) {
                    ProcessInstance pi = (ProcessInstance) pis2.next();
                    int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
                    int numberATEs = pi.getAuditTrailEntryList().size();
                    sumATEs += simPis * numberATEs;
                    pi.isEmpty();
                }
            } else {

            }
            // calculate the number of process Instances, taking into account
            // the number of similar instances
            int sumPIs = 0;
            if (summary instanceof LightweightLogSummary) {
                sumPIs = calculateSumPIs(summary);
            }
            checks = new LogEventCheckBoxEnh[size];

            // create panels and labels
            JPanel global = new JPanel(new BorderLayout());
            JPanel sub2 = new JPanel(new BorderLayout());
            sub2.setBackground(Color.white);
            JLabel labelPercTask = new JLabel("percentage task");
            JLabel labelPercPI = new JLabel("percentage PI");

            // create panel sub1 to put the checkboxes on
            JPanel sub1 = new JPanel(new SpringLayout());
            sub1.setBackground(Color.lightGray);

            // Get percentage of task in the log and percentage of in how many
            // different PIs it appears.
            Iterator it = summary.getLogEvents().iterator();
            int i = 0;
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                double percent = 0.0;
                if (summary instanceof ExtendedLogSummary) {
                    percent = ((double) evt.getOccurrenceCount() / (double) sumATEs);
                } else if (summary instanceof LightweightLogSummary) {
                    Set instances = summary.getInstancesForEvent(evt);
                    // getFrequencyTasks(evt, instances)
                    percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs;
                } else {

                }
                //String percString = percentFormatter.format(percent);
                LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt);
                check.setPercentageTask(percent * 100);
                // add percentage to the statistics for the tasks
                taskStatistics.addValue(percent);
                // Get percentage of in how many different PIs a task appears,
                // taking into account whether the new or old logreader is used
                if (summary instanceof LightweightLogSummary) {
                    Set<ProcessInstance> pis = summary.getInstancesForEvent(evt);
                    int numberInstancesTask = 0;
                    Iterator it2 = pis.iterator();
                    while (it2.hasNext()) {
                        ProcessInstance pi = (ProcessInstance) it2.next();
                        numberInstancesTask += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                    double fPI = (double) numberInstancesTask / (double) sumPIs;

                    check.setPercentagePI(fPI * 100);
                    // add percentage to the statistics for the PIs
                    piStatistics.addValue(fPI);
                } else if (summary instanceof ExtendedLogSummary) {
                    double percPIcheck = getPercentagePI(evt);
                    check.setPercentagePI(percPIcheck);
                    piStatistics.addValue(percPIcheck / 100);
                } else {
                    // raise exception, unknown logreader
                }
                // add to the checks array
                checks[i++] = check;
            }
            // fill sub1 with statistics information
            sub1.add(new JLabel(" Statistics    ( #tasks = " + taskStatistics.getN() + " )"));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" Arithmetic Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean())));
            sub1.add(new JLabel(" Geometric Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean())));
            sub1.add(new JLabel(" Standard Deviation "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation())));
            sub1.add(new JLabel(" Min "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin())));
            sub1.add(new JLabel(" Max "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax())));
            sub1.add(new JLabel(" ------------------ "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" Tasks "));
            sub1.add(new JLabel(" percentage task "));
            sub1.add(new JLabel(" percentage PI "));
            // generate messages for the test case for this plugin
            Message.add("number tasks: " + taskStatistics.getN(), Message.TEST);
            Message.add("<percentage task>", Message.TEST);
            Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + taskStatistics.getMin(), Message.TEST);
            Message.add("max: " + taskStatistics.getMax(), Message.TEST);
            Message.add("<percentage task/>", Message.TEST);
            Message.add("<percentage PI>", Message.TEST);
            Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + piStatistics.getMin(), Message.TEST);
            Message.add("max: " + piStatistics.getMax(), Message.TEST);
            Message.add("<percentage PI/>", Message.TEST);
            // add the checkboxes to the GUI.
            Arrays.sort(checks);
            for (i = 0; i < checks.length; i++) {
                sub1.add(checks[i]);
                if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) {
                    checks[i].setSelected(false);
                }
                // put the percentages on the GUI
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100)));
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100)));
            }
            //
            SpringUtilities util = new SpringUtilities();
            util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3);
            // put the contents on the respective panels
            global.add(sub2, java.awt.BorderLayout.CENTER);
            global.add(sub1, java.awt.BorderLayout.SOUTH);
            //
            JPanel sub21 = new JPanel(new SpringLayout());
            //sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS));
            sub2.setBackground(Color.red);
            JPanel textPanel = new JPanel(new BorderLayout());
            textPanel.setBackground(Color.yellow);
            JPanel sub221 = new JPanel(new FlowLayout());
            sub221.setBackground(Color.yellow);
            JPanel sub222 = new JPanel(new FlowLayout());
            sub222.setBackground(Color.yellow);
            // two different panels to be places on sub21
            //JPanel sub21First = new JPanel();
            //sub21First.setLayout(new BoxLayout(sub21First, BoxLayout.LINE_AXIS));
            //sub21First.setMaximumSize(new Dimension(1000, 25));
            //sub21First.add(Box.createHorizontalGlue());
            //sub21First.add(labelPercTask);
            //sub21First.add(percTaskSpinner, null);
            //percTaskSpinner.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(jButtonCalculate);
            //jButtonCalculate.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(labelPercPI);
            //sub21First.add(percPiSpinner, null);
            //percPiSpinner.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(choiceBox);
            //choiceBox.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(Box.createHorizontalGlue());
            //JPanel sub21Second = new JPanel();
            //sub21Second.setLayout(new BoxLayout(sub21Second, BoxLayout.LINE_AXIS));
            //sub21Second.setMaximumSize(new Dimension(1000, 25));
            //sub21Second.add(Box.createHorizontalGlue());
            //sub21Second.add(jButtonInvert);
            //sub21Second.add(Box.createHorizontalGlue());
            //
            //sub21.add(sub21First);
            //sub21.add(sub21Second);

            sub21.add(labelPercTask);
            sub21.add(percTaskSpinner, null);
            sub21.add(jButtonCalculate);
            sub21.add(labelPercPI);
            sub21.add(percPiSpinner, null);
            sub21.add(choiceBox);
            // add the invert button
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(jButtonInvert);
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.setMaximumSize(sub21.getPreferredSize());
            sub2.add(sub21, java.awt.BorderLayout.CENTER);
            sub2.add(textPanel, java.awt.BorderLayout.SOUTH);
            textPanel.add(new JLabel(
                    "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"),
                    java.awt.BorderLayout.CENTER);
            textPanel.add(
                    new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"),
                    java.awt.BorderLayout.SOUTH);
            util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3);
            //

            // specify button action for the button ButtonPreview
            jButtonCalculate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // The preview button is clicked
                    buttonClicked();
                    // end for
                }
            });

            // specify button action for the button Invert
            jButtonInvert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    invertButtonClicked();
                }
            });

            return global;

        }

        /**
         * When the preview button is clicked
         */
        public void buttonClicked() {
            for (int k = 0; k < checks.length; k++) {
                boolean firstCheck = false;
                boolean secondCheck = false;
                LogEventCheckBoxEnh c = checks[k];
                // check for the task in c whether its percentage is higher than
                // perc
                firstCheck = checkTask(c, percTaskSpinner.getValue());

                // Also check whether the task occurs in more than percTr
                // percent of the traces
                secondCheck = checkPI(c, percPiSpinner.getValue());

                // Check whether for choiceBox OR or AND is selected
                boolean logicalResult = true;
                if (((String) choiceBox.getSelectedItem()).equals("AND")) {
                    logicalResult = firstCheck && secondCheck;
                } else if (((String) choiceBox.getSelectedItem()).equals("OR")) {
                    logicalResult = firstCheck || secondCheck;
                }
                // set the checkbox selected or not
                if (logicalResult == true) {
                    c.setSelected(true);
                } else {
                    c.setSelected(false);
                }
            }
            // add messages to the test log for this case
            int numberCheckedBoxes = 0;
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    numberCheckedBoxes++;
                }
            }
            Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST);
            Message.add("<EnhEvtLogFilter/>", Message.TEST);
        }

        /**
         *
         */
        public void invertButtonClicked() {
            for (int i = 0; i < checks.length; i++) {
                checks[i].setSelected(!checks[i].isSelected());
            }
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in the log
         * than the percentage given by percTask.
         * @param c LogEventCheckBoxEnh the checkbox that contains the task.
         * @param percTask Object the percentage
         * @return boolean True if the percentage of which the task in c occurs
         * in the log is greater or equal than percTaks, false otherwise.
         */
        private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) {
            boolean returnBoolean = false;
            double percT = 0.0;
            percT = getDoubleValueFromSpinner(percTask);
            // check whether its percentage is higher than percT
            if (c.getPercentageTask() >= percT) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in different
         * process instances than the percentage given by percTrace.
         * @param c LogEventCheckBoxEnh the checkbox that contains the task.
         * @param percTrace Object the percentage.
         * @return boolean True, if the percentage of which the task in different
         * process instances occurs in the log is greater or equal than percTrace,
         * false otherwise.
         */
        private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) {
            boolean returnBoolean = false;
            double percPI = 0.0;

            percPI = getDoubleValueFromSpinner(percPIobj);
            // check whether its percentage is higher than percPI
            if (c.getPercentagePI() >= percPI) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Get the percentage of that this task occurs in different PIs
         * @param evt LogEvent the logEvent in which the task can be found
         * @return double the percentage of which this task in the log occurs
         */
        private double getPercentagePI(LogEvent evt) {
            double returnPercent = 0.0;
            HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs();
            int numberPI = summary.getNumberOfProcessInstances();

            // Get the frequency of PI in which the task occurs
            Object value = null;
            Iterator it = mapping.keySet().iterator();
            while (it.hasNext()) {
                Object keyObj = it.next();
                String key = (String) keyObj;
                if (key.equals(
                        evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) {
                    value = mapping.get(keyObj);
                    break;
                }
            }

            if (value != null) {
                // calculate frequency
                returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100;
            }

            return returnPercent;
        }

        private int getFrequencyTasks(LogEvent evt, Set instances) {
            int returnFrequency = 0;
            Iterator instIterator = instances.iterator();
            while (instIterator.hasNext()) {
                ProcessInstance pi = (ProcessInstance) instIterator.next();
                Iterator ates = pi.getAuditTrailEntryList().iterator();
                while (ates.hasNext()) {
                    AuditTrailEntry ate = (AuditTrailEntry) ates.next();
                    if (ate.getElement().trim().equals(evt.getModelElementName().trim())
                            && ate.getType().equals(evt.getEventType())) {
                        returnFrequency += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                }
            }
            return returnFrequency;
        }

        /**
         * Gets the double value of an object, provided that value is a
         * Double or Long object
         * @param value Object
         * @return double the double value
         */
        private double getDoubleValueFromSpinner(Object value) {
            double returnDouble = 0.0;

            if (value instanceof Long) {
                returnDouble = (((Long) value).doubleValue());
            } else if (value instanceof Double) {
                returnDouble = (((Double) value).doubleValue());
            }

            return returnDouble;
        }

        /**
         * Returns the number of process instances, taking into account the
         * number of similar instances
         * @param summary LogSummary the log summary
         * @return int the number of process instances
         */
        private int calculateSumPIs(LogSummary summary) {
            int returnSum = 0;
            HashSet pis = new HashSet<ProcessInstance>();
            Iterator it = summary.getLogEvents().iterator();
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                pis.addAll(summary.getInstancesForEvent(evt));
            }
            // for each process instance in pis, get the number of similar instances
            Iterator it2 = pis.iterator();
            while (it2.hasNext()) {
                ProcessInstance pi = (ProcessInstance) it2.next();
                returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
            }
            return returnSum;
        }

        protected boolean getAllParametersSet() {
            // calculate values
            //buttonClicked();
            return true;
        }

    };
}

From source file:org.processmining.framework.log.filter.LogEventLogFilterEnh.java

/**
 * Returns a Panel for the setting of parameters. When a LogFilter can be
 * added to a list in the framework. This panel is shown, and parameters can
 * be set. When the dialog is closed, a new instance of a LogFilter is
 * created by the framework by calling the <code>getNewLogFilter</code>
 * method of the dialog.//from   ww w  . j a v a2 s  .  co  m
 * 
 * @param summary
 *            A LogSummary to be used for setting parameters.
 * @return JPanel
 */
public LogFilterParameterDialog getParameterDialog(LogSummary summary) {
    return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) {

        LogEventCheckBoxEnh[] checks;
        JSpinner percTaskSpinner;
        JSpinner percPiSpinner;
        JComboBox choiceBox;

        /**
         * Keep the statistics for all the tasks
         */
        SummaryStatistics taskStatistics = null;

        /**
         * Keep the statistics for the occurrence of tasks in process
         * instances
         */
        SummaryStatistics piStatistics = null;

        public LogFilter getNewLogFilter() {
            LogEvents e = new LogEvents();
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    e.add(checks[i].getLogEvent());
                }
            }
            return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()),
                    getDoubleValueFromSpinner(percPiSpinner.getValue()),
                    choiceBox.getSelectedItem().toString());
        }

        protected JPanel getPanel() {
            // add message to the test log for this plugin
            Message.add("<EnhEvtLogFilter>", Message.TEST);
            // statistics
            taskStatistics = SummaryStatistics.newInstance();
            piStatistics = SummaryStatistics.newInstance();
            // Set up an percentformatter
            NumberFormat percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMinimumFractionDigits(2);
            percentFormatter.setMaximumFractionDigits(2);
            // Instantiate the spinners
            percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            // generate the buttons that are needed
            JButton jButtonCalculate = new JButton("Calculate");
            JButton jButtonInvert = new JButton("Invert selection");
            // set up a choicebox to indicate whether the relationship
            // between the two
            // percentages is AND or OR.

            percTaskSpinner.setValue(new Double(percentageTask));
            percPiSpinner.setValue(new Double(percentagePI));

            choiceBox = new JComboBox();
            choiceBox.addItem("AND");
            choiceBox.addItem("OR");
            choiceBox.setSelectedItem(selectedItemComboBox);

            // Some values that are needed for the sequel.
            int size = summary.getLogEvents().size();
            // For the new log reader sumATEs should be calculated in
            // another way
            int sumATEs = 0;
            if (summary instanceof ExtendedLogSummary) {
                sumATEs = summary.getNumberOfAuditTrailEntries();
            } else if (summary instanceof LightweightLogSummary) {
                HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>();
                Iterator logEvents = summary.getLogEvents().iterator();
                while (logEvents.hasNext()) {
                    LogEvent evt = (LogEvent) logEvents.next();
                    pis.addAll(summary.getInstancesForEvent(evt));
                }
                Iterator pis2 = pis.iterator();
                while (pis2.hasNext()) {
                    ProcessInstance pi = (ProcessInstance) pis2.next();
                    int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
                    int numberATEs = pi.getAuditTrailEntryList().size();
                    sumATEs += simPis * numberATEs;
                    pi.isEmpty();
                }
            } else {

            }
            // calculate the number of process Instances, taking into
            // account
            // the number of similar instances
            int sumPIs = 0;
            if (summary instanceof LightweightLogSummary) {
                sumPIs = calculateSumPIs(summary);
            }
            checks = new LogEventCheckBoxEnh[size];

            // create panels and labels
            JPanel global = new JPanel(new BorderLayout());
            JPanel sub2 = new JPanel(new BorderLayout());
            sub2.setBackground(Color.white);
            JLabel labelPercTask = new JLabel("percentage task");
            JLabel labelPercPI = new JLabel("percentage PI");

            // create panel sub1 to put the checkboxes on
            JPanel sub1 = new JPanel(new SpringLayout());
            sub1.setBackground(Color.lightGray);

            // Get percentage of task in the log and percentage of in how
            // many
            // different PIs it appears.
            Iterator it = summary.getLogEvents().iterator();
            int i = 0;
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                double percent = 0.0;
                if (summary instanceof ExtendedLogSummary) {
                    percent = ((double) evt.getOccurrenceCount() / (double) sumATEs);
                } else if (summary instanceof LightweightLogSummary) {
                    Set instances = summary.getInstancesForEvent(evt);
                    // getFrequencyTasks(evt, instances)
                    percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs;
                } else {

                }
                // String percString = percentFormatter.format(percent);
                LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt);
                check.setPercentageTask(percent * 100);
                // add percentage to the statistics for the tasks
                taskStatistics.addValue(percent);
                // Get percentage of in how many different PIs a task
                // appears,
                // taking into account whether the new or old logreader is
                // used
                if (summary instanceof LightweightLogSummary) {
                    Set<ProcessInstance> pis = summary.getInstancesForEvent(evt);
                    int numberInstancesTask = 0;
                    Iterator it2 = pis.iterator();
                    while (it2.hasNext()) {
                        ProcessInstance pi = (ProcessInstance) it2.next();
                        numberInstancesTask += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                    double fPI = (double) numberInstancesTask / (double) sumPIs;

                    check.setPercentagePI(fPI * 100);
                    // add percentage to the statistics for the PIs
                    piStatistics.addValue(fPI);
                } else if (summary instanceof ExtendedLogSummary) {
                    double percPIcheck = getPercentagePI(evt);
                    check.setPercentagePI(percPIcheck);
                    piStatistics.addValue(percPIcheck / 100);
                } else {
                    // raise exception, unknown logreader
                }
                // add to the checks array
                checks[i++] = check;
            }
            // fill sub1 with statistics information
            sub1.add(new JLabel(" Statistics    ( #tasks = " + taskStatistics.getN() + " )"));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" Arithmetic Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean())));
            sub1.add(new JLabel(" Geometric Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean())));
            sub1.add(new JLabel(" Standard Deviation "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation())));
            sub1.add(new JLabel(" Min "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin())));
            sub1.add(new JLabel(" Max "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax())));
            sub1.add(new JLabel(" ------------------ "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" Tasks "));
            sub1.add(new JLabel(" percentage task "));
            sub1.add(new JLabel(" percentage PI "));
            // generate messages for the test case for this plugin
            Message.add("number tasks: " + taskStatistics.getN(), Message.TEST);
            Message.add("<percentage task>", Message.TEST);
            Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + taskStatistics.getMin(), Message.TEST);
            Message.add("max: " + taskStatistics.getMax(), Message.TEST);
            Message.add("<percentage task/>", Message.TEST);
            Message.add("<percentage PI>", Message.TEST);
            Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + piStatistics.getMin(), Message.TEST);
            Message.add("max: " + piStatistics.getMax(), Message.TEST);
            Message.add("<percentage PI/>", Message.TEST);
            // add the checkboxes to the GUI.
            Arrays.sort(checks);
            for (i = 0; i < checks.length; i++) {
                sub1.add(checks[i]);
                if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) {
                    checks[i].setSelected(false);
                }
                // put the percentages on the GUI
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100)));
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100)));
            }
            //
            SpringUtilities util = new SpringUtilities();
            util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3);
            // put the contents on the respective panels
            global.add(sub2, java.awt.BorderLayout.CENTER);
            global.add(sub1, java.awt.BorderLayout.SOUTH);
            //
            JPanel sub21 = new JPanel(new SpringLayout());
            // sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS));
            sub2.setBackground(Color.red);
            JPanel textPanel = new JPanel(new BorderLayout());
            textPanel.setBackground(Color.yellow);
            JPanel sub221 = new JPanel(new FlowLayout());
            sub221.setBackground(Color.yellow);
            JPanel sub222 = new JPanel(new FlowLayout());
            sub222.setBackground(Color.yellow);
            // two different panels to be places on sub21
            // JPanel sub21First = new JPanel();
            // sub21First.setLayout(new BoxLayout(sub21First,
            // BoxLayout.LINE_AXIS));
            // sub21First.setMaximumSize(new Dimension(1000, 25));
            // sub21First.add(Box.createHorizontalGlue());
            // sub21First.add(labelPercTask);
            // sub21First.add(percTaskSpinner, null);
            // percTaskSpinner.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(jButtonCalculate);
            // jButtonCalculate.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(labelPercPI);
            // sub21First.add(percPiSpinner, null);
            // percPiSpinner.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(choiceBox);
            // choiceBox.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(Box.createHorizontalGlue());
            // JPanel sub21Second = new JPanel();
            // sub21Second.setLayout(new BoxLayout(sub21Second,
            // BoxLayout.LINE_AXIS));
            // sub21Second.setMaximumSize(new Dimension(1000, 25));
            // sub21Second.add(Box.createHorizontalGlue());
            // sub21Second.add(jButtonInvert);
            // sub21Second.add(Box.createHorizontalGlue());
            //
            // sub21.add(sub21First);
            // sub21.add(sub21Second);

            sub21.add(labelPercTask);
            sub21.add(percTaskSpinner, null);
            sub21.add(jButtonCalculate);
            sub21.add(labelPercPI);
            sub21.add(percPiSpinner, null);
            sub21.add(choiceBox);
            // add the invert button
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(jButtonInvert);
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.setMaximumSize(sub21.getPreferredSize());
            sub2.add(sub21, java.awt.BorderLayout.CENTER);
            sub2.add(textPanel, java.awt.BorderLayout.SOUTH);
            textPanel.add(new JLabel(
                    "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"),
                    java.awt.BorderLayout.CENTER);
            textPanel.add(
                    new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"),
                    java.awt.BorderLayout.SOUTH);
            util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3);
            //

            // specify button action for the button ButtonPreview
            jButtonCalculate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // The preview button is clicked
                    buttonClicked();
                    // end for
                }
            });

            // specify button action for the button Invert
            jButtonInvert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    invertButtonClicked();
                }
            });

            return global;

        }

        /**
         * When the preview button is clicked
         */
        public void buttonClicked() {
            for (int k = 0; k < checks.length; k++) {
                boolean firstCheck = false;
                boolean secondCheck = false;
                LogEventCheckBoxEnh c = checks[k];
                // check for the task in c whether its percentage is higher
                // than
                // perc
                firstCheck = checkTask(c, percTaskSpinner.getValue());

                // Also check whether the task occurs in more than percTr
                // percent of the traces
                secondCheck = checkPI(c, percPiSpinner.getValue());

                // Check whether for choiceBox OR or AND is selected
                boolean logicalResult = true;
                if (((String) choiceBox.getSelectedItem()).equals("AND")) {
                    logicalResult = firstCheck && secondCheck;
                } else if (((String) choiceBox.getSelectedItem()).equals("OR")) {
                    logicalResult = firstCheck || secondCheck;
                }
                // set the checkbox selected or not
                if (logicalResult == true) {
                    c.setSelected(true);
                } else {
                    c.setSelected(false);
                }
            }
            // add messages to the test log for this case
            int numberCheckedBoxes = 0;
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    numberCheckedBoxes++;
                }
            }
            Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST);
            Message.add("<EnhEvtLogFilter/>", Message.TEST);
        }

        /**
         *
         */
        public void invertButtonClicked() {
            for (int i = 0; i < checks.length; i++) {
                checks[i].setSelected(!checks[i].isSelected());
            }
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in
         * the log than the percentage given by percTask.
         * 
         * @param c
         *            LogEventCheckBoxEnh the checkbox that contains the
         *            task.
         * @param percTask
         *            Object the percentage
         * @return boolean True if the percentage of which the task in c
         *         occurs in the log is greater or equal than percTaks,
         *         false otherwise.
         */
        private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) {
            boolean returnBoolean = false;
            double percT = 0.0;
            percT = getDoubleValueFromSpinner(percTask);
            // check whether its percentage is higher than percT
            if (c.getPercentageTask() >= percT) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in
         * different process instances than the percentage given by
         * percTrace.
         * 
         * @param c
         *            LogEventCheckBoxEnh the checkbox that contains the
         *            task.
         * @param percTrace
         *            Object the percentage.
         * @return boolean True, if the percentage of which the task in
         *         different process instances occurs in the log is greater
         *         or equal than percTrace, false otherwise.
         */
        private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) {
            boolean returnBoolean = false;
            double percPI = 0.0;

            percPI = getDoubleValueFromSpinner(percPIobj);
            // check whether its percentage is higher than percPI
            if (c.getPercentagePI() >= percPI) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Get the percentage of that this task occurs in different PIs
         * 
         * @param evt
         *            LogEvent the logEvent in which the task can be found
         * @return double the percentage of which this task in the log
         *         occurs
         */
        private double getPercentagePI(LogEvent evt) {
            double returnPercent = 0.0;
            HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs();
            int numberPI = summary.getNumberOfProcessInstances();

            // Get the frequency of PI in which the task occurs
            Object value = null;
            Iterator it = mapping.keySet().iterator();
            while (it.hasNext()) {
                Object keyObj = it.next();
                String key = (String) keyObj;
                if (key.equals(
                        evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) {
                    value = mapping.get(keyObj);
                    break;
                }
            }

            if (value != null) {
                // calculate frequency
                returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100;
            }

            return returnPercent;
        }

        private int getFrequencyTasks(LogEvent evt, Set instances) {
            int returnFrequency = 0;
            Iterator instIterator = instances.iterator();
            while (instIterator.hasNext()) {
                ProcessInstance pi = (ProcessInstance) instIterator.next();
                Iterator ates = pi.getAuditTrailEntryList().iterator();
                while (ates.hasNext()) {
                    AuditTrailEntry ate = (AuditTrailEntry) ates.next();
                    if (ate.getElement().trim().equals(evt.getModelElementName().trim())
                            && ate.getType().equals(evt.getEventType())) {
                        returnFrequency += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                }
            }
            return returnFrequency;
        }

        /**
         * Gets the double value of an object, provided that value is a
         * Double or Long object
         * 
         * @param value
         *            Object
         * @return double the double value
         */
        private double getDoubleValueFromSpinner(Object value) {
            double returnDouble = 0.0;

            if (value instanceof Long) {
                returnDouble = (((Long) value).doubleValue());
            } else if (value instanceof Double) {
                returnDouble = (((Double) value).doubleValue());
            }

            return returnDouble;
        }

        /**
         * Returns the number of process instances, taking into account the
         * number of similar instances
         * 
         * @param summary
         *            LogSummary the log summary
         * @return int the number of process instances
         */
        private int calculateSumPIs(LogSummary summary) {
            int returnSum = 0;
            HashSet pis = new HashSet<ProcessInstance>();
            Iterator it = summary.getLogEvents().iterator();
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                pis.addAll(summary.getInstancesForEvent(evt));
            }
            // for each process instance in pis, get the number of similar
            // instances
            Iterator it2 = pis.iterator();
            while (it2.hasNext()) {
                ProcessInstance pi = (ProcessInstance) it2.next();
                returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
            }
            return returnSum;
        }

        protected boolean getAllParametersSet() {
            // calculate values
            // buttonClicked();
            return true;
        }

    };
}

From source file:au.org.theark.lims.web.component.subjectlims.lims.biospecimen.form.BiospecimenModalDetailForm.java

public void initialiseDetailForm() {
    idTxtFld = new TextField<String>("biospecimen.id");
    biospecimenUidTxtFld = new TextField<String>("biospecimen.biospecimenUid");
    biospecimenUidTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = 1L;

        @Override/*from  w w  w  . j  a  v  a2s.  c o m*/
        protected void onUpdate(AjaxRequestTarget target) {
            // Check BiospecimenUID is unique
            String biospecimenUid = (getComponent().getDefaultModelObject().toString() != null
                    ? getComponent().getDefaultModelObject().toString()
                    : new String());
            Biospecimen biospecimen = iLimsService.getBiospecimenByUid(biospecimenUid,
                    cpModel.getObject().getBiospecimen().getStudy());
            if (biospecimen != null && biospecimen.getId() != null) {
                error("Biospecimen UID must be unique. Please try again.");
                target.focusComponent(getComponent());
            }
            target.add(feedbackPanel);
        }
    });

    parentUidTxtFld = new TextField<String>("biospecimen.parentUid");
    commentsTxtAreaFld = new TextArea<String>("biospecimen.comments");
    sampleDateTxtFld = new DateTextField("biospecimen.sampleDate", au.org.theark.core.Constants.DD_MM_YYYY);
    useCollectionDate = new AjaxLink<Date>("useCollectionDate") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            BioCollection selectedBioCollection = cpModel.getObject().getBioCollection();
            cpModel.getObject().getBiospecimen().setSampleDate(selectedBioCollection.getCollectionDate());
            target.add(sampleDateTxtFld);
        }
    };

    sampleTimeTxtFld = new TimeField("biospecimen.sampleTime") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onBeforeRender() {
            this.getDateTextField().setVisibilityAllowed(false);
            super.onBeforeRender();
        }

        @Override
        protected void convertInput() {
            // Slight change to not default to today's date
            Date modelObject = (Date) getDefaultModelObject();
            getDateTextField().setConvertedInput(modelObject != null ? modelObject : null);
            super.convertInput();
        }
    };

    processedDateTxtFld = new DateTextField("biospecimen.processedDate",
            au.org.theark.core.Constants.DD_MM_YYYY);
    processedTimeTxtFld = new TimeField("biospecimen.processedTime") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onBeforeRender() {
            this.getDateTextField().setVisibilityAllowed(false);
            super.onBeforeRender();
        }

        @Override
        protected void convertInput() {
            // Slight change to not default to today's date
            Date modelObject = (Date) getDefaultModelObject();
            getDateTextField().setConvertedInput(modelObject != null ? modelObject : null);
            super.convertInput();
        }
    };

    ArkDatePicker sampleDatePicker = new ArkDatePicker();
    sampleDatePicker.bind(sampleDateTxtFld);
    sampleDateTxtFld.add(sampleDatePicker);

    ArkDatePicker processedDatePicker = new ArkDatePicker();
    processedDatePicker.bind(processedDateTxtFld);
    processedDateTxtFld.add(processedDatePicker);

    quantityTxtFld = new TextField<Double>("biospecimen.quantity") {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        @Override
        public <C> IConverter<C> getConverter(Class<C> type) {
            DoubleConverter doubleConverter = new DoubleConverter();
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMinimumFractionDigits(1);
            numberFormat.setMaximumFractionDigits(10);
            doubleConverter.setNumberFormat(getLocale(), numberFormat);
            return (IConverter<C>) doubleConverter;
        }
    };
    parentQuantityTxtFld = new TextField<Double>("parentBiospecimen.quantity") {
        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        @Override
        public <C> IConverter<C> getConverter(Class<C> type) {
            DoubleConverter doubleConverter = new DoubleConverter();
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMinimumFractionDigits(1);
            numberFormat.setMaximumFractionDigits(10);
            doubleConverter.setNumberFormat(getLocale(), numberFormat);
            return (IConverter<C>) doubleConverter;
        }
    };
    parentQuantityTxtFld.setVisible(cpModel.getObject().getBiospecimenProcessing()
            .equalsIgnoreCase(au.org.theark.lims.web.Constants.BIOSPECIMEN_PROCESSING_PROCESSING));
    parentQuantityTxtFld.setOutputMarkupId(true);

    quantityTxtFld.setEnabled(false);
    bioTransactionQuantityTxtFld = new TextField<Double>("bioTransaction.quantity") {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        @Override
        public <C> IConverter<C> getConverter(Class<C> type) {
            DoubleConverter doubleConverter = new DoubleConverter();
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMinimumFractionDigits(1);
            numberFormat.setMaximumFractionDigits(10);
            doubleConverter.setNumberFormat(getLocale(), numberFormat);
            return (IConverter<C>) doubleConverter;
        }
    };
    bioTransactionQuantityTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(amountLbl);
        }
    });

    concentrationTxtFld = new TextField<Number>("biospecimen.concentration");
    concentrationTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(amountLbl);
        }
    });
    amountLbl = new Label("biospecimen.amount", new Model<Number>() {
        private static final long serialVersionUID = 1L;

        @Override
        public Number getObject() {
            Number concentration = ((concentrationTxtFld.getModelObject() == null) ? 0
                    : concentrationTxtFld.getModelObject());
            Number quantity = null;
            if (bioTransactionQuantityTxtFld.isVisible()) {
                quantity = ((bioTransactionQuantityTxtFld.getModelObject() == null) ? 0
                        : bioTransactionQuantityTxtFld.getModelObject());
            } else {
                quantity = ((quantityTxtFld.getModelObject() == null) ? 0 : quantityTxtFld.getModelObject());
            }
            Number amount = (concentration.doubleValue() * quantity.doubleValue());
            return amount;
        }
    });
    amountLbl.setOutputMarkupPlaceholderTag(true);

    setQuantityLabel();
    initSampleTypeDdc();
    initBioCollectionDdc();
    initUnitDdc();
    initTreatmentTypeDdc();
    initGradeDdc();
    initStoredInDdc();
    initAnticoagDdc();
    initStatusDdc();
    initQualityDdc();
    initBiospecimenProtocol();
    purity = new TextField<Number>("biospecimen.purity");

    barcodedChkBox = new CheckBox("biospecimen.barcoded");
    barcodedChkBox.setVisible(true);
    barcodedChkBox.setEnabled(false);

    initialiseBarcodeImage();

    initialiseBiospecimenCFDataEntry();
    initialiseBioTransactionListPanel();
    initialiseBiospecimenLocationPanel();
    initialiseBiospecimenButtonsPanel();
    initDeleteModelWindow();

    attachValidators();
    addComponents();

    // Focus on Sample Type
    sampleTypeDdc.add(new ArkDefaultFormFocusBehavior());
}

From source file:io.hummer.util.test.GenericTestResult.java

public String getPlottableAverages3D(List<Integer> levels, String[] keyTemplates, ResultType type,
        String... additionalCommands) {
    StringBuilder b = new StringBuilder();
    NumberFormat f = NumberFormat.getInstance(Locale.US);
    f.setMinimumFractionDigits(3);//from www .ja  v  a  2  s  . co m
    f.setMaximumFractionDigits(3);
    f.setGroupingUsed(false);
    for (int l : levels) {
        for (String t : keyTemplates) {
            String key = t.replaceAll("<level>", "" + l);
            Double val = 0.0;
            if (type == ResultType.THROUGHPUT)
                val = getThroughput(key);
            else if (type == ResultType.MEAN)
                val = getMean(key);
            if (val.isNaN())
                val = 0.0;
            b.append(f.format(val));
            b.append("\n");
        }
        b.append("\n");
    }
    return b.toString();
}