Example usage for org.jfree.chart ChartPanel getChart

List of usage examples for org.jfree.chart ChartPanel getChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartPanel getChart.

Prototype

public JFreeChart getChart() 

Source Link

Document

Returns the chart contained in the panel.

Usage

From source file:net.sf.maltcms.chromaui.annotations.PeakAnnotationRenderer.java

private void drawOutline(Shape entity, Graphics2D g2, Color fill, Color stroke, ChartPanel chartPanel,
        boolean scale, float alpha) {
    if (entity != null) {
        //System.out.println("Drawing entity with bbox: "+entity.getBounds2D());
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        Color c = g2.getColor();//  w ww . ja v  a2 s .  c  om
        Composite comp = g2.getComposite();
        g2.clip(dataArea);
        g2.setColor(fill);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        JFreeChart chart = chartPanel.getChart();
        XYPlot plot = (XYPlot) chart.getPlot();
        ValueAxis xAxis = plot.getDomainAxis();
        ValueAxis yAxis = plot.getRangeAxis();
        RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
        RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
        Rectangle2D entityBounds = entity.getBounds2D();
        double viewX = xAxis.valueToJava2D(entityBounds.getCenterX(), dataArea, xAxisEdge);
        double viewY = yAxis.valueToJava2D(entityBounds.getCenterY(), dataArea, yAxisEdge);
        double viewW = xAxis.lengthToJava2D(entityBounds.getWidth(), dataArea, xAxisEdge);
        double viewH = yAxis.lengthToJava2D(entityBounds.getHeight(), dataArea, yAxisEdge);
        PlotOrientation orientation = plot.getOrientation();

        //transform model to origin (0,0) in model coordinates
        AffineTransform toOrigin = AffineTransform.getTranslateInstance(-entityBounds.getCenterX(),
                -entityBounds.getCenterY());
        //transform from origin (0,0) to model location
        AffineTransform toModelLocation = AffineTransform.getTranslateInstance(entityBounds.getCenterX(),
                entityBounds.getCenterY());
        //transform from model scale to view scale
        double scaleX = viewW / entityBounds.getWidth();
        double scaleY = viewH / entityBounds.getHeight();
        Logger.getLogger(getClass().getName()).log(Level.FINE, "Scale x: {0} Scale y: {1}",
                new Object[] { scaleX, scaleY });
        AffineTransform toViewScale = AffineTransform.getScaleInstance(scaleX, scaleY);
        AffineTransform toViewLocation = AffineTransform.getTranslateInstance(viewX, viewY);
        AffineTransform flipTransform = AffineTransform.getScaleInstance(1.0f, -1.0f);
        AffineTransform modelToView = new AffineTransform(toOrigin);
        modelToView.preConcatenate(flipTransform);
        modelToView.preConcatenate(toViewScale);
        modelToView.preConcatenate(toViewLocation);
        //
        //            if (orientation == PlotOrientation.HORIZONTAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewY,
        //                        viewX);
        //            } else if (orientation == PlotOrientation.VERTICAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewX,
        //                        viewY);
        //            }
        FlatteningPathIterator iter = new FlatteningPathIterator(modelToView.createTransformedShape(entity)
                .getPathIterator(AffineTransform.getTranslateInstance(0, 0)), 5);
        Path2D.Float path = new Path2D.Float();
        path.append(iter, false);

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.fill(path);
        if (stroke != null) {
            g2.setColor(stroke);
            g2.draw(path);
        }
        g2.setComposite(comp);
        g2.setColor(c);
        g2.setClip(savedClip);
    } else {
        Logger.getLogger(getClass().getName()).info("Entity is null!");
    }
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.AngleDirectController.java

/**
 * Initialize the main view./* w  ww  .  j a va2 s . co m*/
 */
private void initAngleDirectPanel() {
    // initialize the main view
    angleDirectPanel = new AngleDirectPanel();
    // initialize the dataTable
    dataTable = new JTable();
    JScrollPane scrollPane = new JScrollPane(dataTable);
    //the table will take all the viewport height available
    dataTable.setFillsViewportHeight(true);
    scrollPane.getViewport().setBackground(Color.white);
    dataTable.getTableHeader().setReorderingAllowed(false);
    //row selection must be false && column selection true to be able to select through columns
    dataTable.setColumnSelectionAllowed(true);
    dataTable.setRowSelectionAllowed(false);
    angleDirectPanel.getDataTablePanel().add(scrollPane);
    //create a ButtonGroup for the radioButtons used for analysis
    ButtonGroup radioButtonGroup = new ButtonGroup();
    //adding buttons to a ButtonGroup automatically deselect one when another one gets selected
    radioButtonGroup.add(angleDirectPanel.getInstTurnAngleRadioButton());
    radioButtonGroup.add(angleDirectPanel.getTrackTurnAngleRadioButton());
    //        radioButtonGroup.add(angleDirectPanel.getDynamicDirectRatioRadioButton());
    //        radioButtonGroup.add(angleDirectPanel.getEndPointDirectRatioRadioButton());

    /**
     * Add action listeners
     */
    // show instantaneous turning angles
    angleDirectPanel.getInstTurnAngleRadioButton().addActionListener((ActionEvent e) -> {
        PlateCondition currentCondition = singleCellPreProcessingController.getCurrentCondition();
        //check that a condition is selected
        if (currentCondition != null) {
            showInstAngleInTable(currentCondition);
            plotHistTA(currentCondition);
            plotPolarTA(currentCondition);
            plotRoseTA(currentCondition);
            plotCompassTA(currentCondition);
        }
    });

    // show and plot averaged-track turning angles
    angleDirectPanel.getTrackTurnAngleRadioButton().addActionListener((ActionEvent e) -> {
        PlateCondition currentCondition = singleCellPreProcessingController.getCurrentCondition();
        //check that a condition is selected
        if (currentCondition != null) {
            showTrackAngleInTable(currentCondition);
            plotHistTrackTA(currentCondition);
            plotPolarTrackTA(currentCondition);
            plotRoseTrackTA(currentCondition);
            plotCompassTrackTA(currentCondition);
        }
    });

    /**
     *
     */
    angleDirectPanel.getSaveChartToPdfButton().addActionListener((ActionEvent e) -> {

        ChartPanel chartPanel = rosePlotChartPanels.get(2);
        JFreeChart chart = chartPanel.getChart();
        if (chart != null) {
            try {
                // create the PDF report file
                createPdf(chart);
            } catch (IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    });

    //        // show dynamic directionality ratios
    //        angleDirectPanel.getDynamicDirectRatioRadioButton().addActionListener((ActionEvent e) -> {
    //            PlateCondition currentCondition = singleCellPreProcessingController.getCurrentCondition();
    //            //check that a condition is selected
    //            if (currentCondition != null) {
    //
    //            }
    //        });
    //
    //        // show end-point directionality ratios
    //        angleDirectPanel.getEndPointDirectRatioRadioButton().addActionListener((ActionEvent e) -> {
    //            PlateCondition currentCondition = singleCellPreProcessingController.getCurrentCondition();
    //            //check that a condition is selected
    //            if (currentCondition != null) {
    //
    //            }
    //        });
    //select as default first button 
    angleDirectPanel.getInstTurnAngleRadioButton().setSelected(true);

    // add view to parent panel
    singleCellPreProcessingController.getSingleCellAnalysisPanel().getAngleDirectParentPanel()
            .add(angleDirectPanel, gridBagConstraints);
    angleDirectPanel.getTurningAngleParentPanel().add(turningAnglePanel, gridBagConstraints);
}

From source file:fr.ign.cogit.simplu3d.rjmcmc.generic.visitor.FilmVisitor.java

/**
 * Permet d'enregistrer une image  partir de l'cran Ne fonctionne qu'avec
 * l'IHM actuel (Offset ncessaire) Ne prends pas compte de l'existance d'un
 * fichier de mme nom//  w w w.  j a v  a 2 s  .c  o m
 * 
 * @param path
 *            le dossier dans lequel l'impr ecran sera supprime
 * @param fileName
 *            le nom du fichier
 * @return indique si la capture s'est effectue avec succs
 */
public boolean screenCapture(String path, String fileName, InterfaceMap3D iMap3D) {

    try {

        ChartPanel v = StatsVisitor.CHARTSINGLETON;

        int xSup = 0;
        int ySup = 0;

        boolean hasStats = (v != null);

        if (hasStats) {

            xSup = v.getSize().width;
            ySup = v.getSize().height;

        }

        int xSize = iMap3D.getSize().width + xSup;
        int ySize = Math.max(iMap3D.getSize().height, ySup);

        BufferedImage bufImage = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);

        Graphics g = bufImage.createGraphics();

        g.setColor(Color.white);

        // g.drawRect(0, 0, xSize, ySize);

        g.fillRect(0, 0, xSize, ySize);

        iMap3D.getCanvas3D().paint(g);

        if (hasStats) {

            g.drawImage(v.getChart().createBufferedImage(xSup, ySup), iMap3D.getSize().width,
                    (ySize - ySup) / 2, null);

        }

        File fichier = new File(path, fileName);
        if (fichier.exists()) {
            System.out.println("Fail");
            return false;
        } else {
            ImageIO.write(bufImage, "jpg", fichier);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:cish.CISH.java

@Override
public String getHTMLReport(String HTMLFolderName) {
    String output = "<html>";
    String lb = "\n";

    if (!tss.isEmpty()) {

        // Save the parameters
        output += "<table><tr>" + lb + "  <td colspan=2><i><u>CISH Parameters</u></i></td>" + lb + " </tr>" + lb
                + " <tr>" + lb + "  <td><b>Point Radius:</b></td>" + lb + "  <td>"
                + getParam_PointSignalRadius() + "</td>" + lb + " </tr>" + lb + " <tr>" + lb
                + "  <td><b>Number of Random Points for Local Ratio:</b></td>" + lb + "  <td>" + getParam_nPts()
                + "</td>" + lb + " </tr>" + lb + " <tr>" + lb + "  <td><b>Polarity:</b></td>" + lb + "  <td>"
                + (getParam_darkpoints() ? "Detect Dark Points" : "Detect Light Points") + "</td>" + lb
                + " </tr>" + lb;
        output += "</table><br>" + lb;

        // Save the CISH Table
        output += "<table>" + lb + "  <tr>" + lb;
        for (int i = 0; i < jXTable1.getColumnCount(); i++) {
            output += "    <th>" + jXTable1.getColumnName(i) + "</th>" + lb;
        }/*from w w  w . j  av a  2 s.c om*/
        output += "  </tr>" + lb;
        for (int i = 0; i < jXTable1.getRowCount(); i++) {
            output += "  <tr>" + lb;
            for (int j = 0; j < jXTable1.getColumnCount(); j++) {
                output += "    <td>" + jXTable1.getStringAt(i, j) + "</td>" + lb;
            }
            output += "  </tr>" + lb;
        }
        output += "</table>" + lb;

        // Save the CISH plot image
        ChartPanel chartpanel = (ChartPanel) jPanel1.getComponent(0);
        if (chartpanel != null) {
            File file_tmp = new File(HTMLFolderName + "CISHPlot.png");
            try {
                ChartUtilities.saveChartAsPNG(file_tmp, chartpanel.getChart(), chartpanel.getWidth(),
                        chartpanel.getHeight());
            } catch (IOException ex) {
                Logger.getLogger(CISH.class.getName()).log(Level.SEVERE, null, ex);
            }
            output += "<br><br>" + lb;
            output += "<img src=\"" + HTMLFolderName
                    + "CISHPlot.png\" alt=\"Global vs. Local Ratio Plot\"><br><br>" + lb;
        }

        // Save the TMA spot images with CISH marks
        for (TMAspot ts : tss) {
            try {
                File file_tmp = new File(HTMLFolderName + ts.getName() + "_CISH.jpg");
                BufferedImage bi = ts.getBufferedImage();
                drawInformationPreNuclei(ts, bi.createGraphics(), 1, 0, 0, bi.getWidth(), bi.getHeight());
                ImageIO.write(bi, "jpg", file_tmp);
                output += "<a href=\"" + HTMLFolderName + ts.getName() + "_CISH.jpg\">" + "<img src=\""
                        + HTMLFolderName + ts.getName() + "_CISH.jpg\" alt=\"" + ts.getName()
                        + " CISH Points\" width=\"100\">" + "</a>&nbsp;&nbsp;&nbsp;" + lb;
            } catch (IOException ex) {
                Logger.getLogger(CISH.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        output += "<br>" + "<font color=\"" + Misc.Color2HTML(COLORS[0]) + "\"><b>centromer</b></font> "
                + "<font color=\"" + Misc.Color2HTML(COLORS[1]) + "\"><b>gene</b></font> " + "<font color=\""
                + Misc.Color2HTML(COLORS[4]) + "\"><b>both</b></font> " + "<br><br>" + lb;
    }

    output += "</html>";

    return output;
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private Point2D.Double getPoint(int dataIndex, Type type) {
    if (dataIndex < 0) {
        return null;
    }//from   www  .j av  a2  s  .  c  o m

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    // Dataset 0 are the invest information. 1 is the ROI information.
    final TimeSeriesCollection timeSeriesCollection;
    if (type == Type.Invest) {
        timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(0);
    } else {
        assert (type == Type.ROI);
        timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(1);
    }
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    if (dataIndex >= timeSeries.getItemCount()) {
        /* Not ready yet. */
        return null;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(dataIndex);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final Rectangle2D plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
    final double xJava2D = domainAxis.valueToJava2D(xValue, plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, plotArea, rangeAxisEdge);
    // Use Double version, to avoid from losing precision.
    return new Point2D.Double(xJava2D, yJava2D);
}

From source file:GUI.GUIModel.java

public void PutPoint(double key, double x, double y, JPanel GraphHerePanel) {
    Component[] a = GraphHerePanel.getComponents();
    ChartPanel chartpanel = (ChartPanel) a[0];
    JFreeChart chart = chartpanel.getChart();

    XYPlot plot = (XYPlot) chart.getPlot();
    XYSeriesCollection data = (XYSeriesCollection) plot.getDataset();
    XYSeries XYseries = data.getSeries(key);
    XYseries.add(x, y);//w  ww . jav  a  2  s.com
    this.revalidate();
    this.repaint();

}

From source file:org.jfree.chart.demo.SuperDemo.java

private void exportToPDF() {
    java.awt.Component component = chartContainer.getComponent(0);
    if (component instanceof ChartPanel) {
        JFileChooser jfilechooser = new JFileChooser();
        jfilechooser.setName("untitled.pdf");
        jfilechooser.setFileFilter(new FileFilter() {

            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".pdf");
            }//from w w  w.ja v  a 2s. c  o  m

            public String getDescription() {
                return "Portable Document Format (PDF)";
            }

        });
        int i = jfilechooser.showSaveDialog(this);
        if (i == 0) {
            ChartPanel chartpanel = (ChartPanel) component;
            try {
                JFreeChart jfreechart = (JFreeChart) chartpanel.getChart().clone();
                PDFExportTask pdfexporttask = new PDFExportTask(jfreechart, chartpanel.getWidth(),
                        chartpanel.getHeight(), jfilechooser.getSelectedFile());
                Thread thread = new Thread(pdfexporttask);
                thread.start();
            } catch (CloneNotSupportedException clonenotsupportedexception) {
                clonenotsupportedexception.printStackTrace();
            }
        }
    } else {
        String s = "Unable to export the selected item.  There is ";
        s = s + "either no chart selected,\nor else the chart is not ";
        s = s + "at the expected location in the component hierarchy\n";
        s = s + "(future versions of the demo may include code to ";
        s = s + "handle these special cases).";
        JOptionPane.showMessageDialog(this, s, "PDF Export", 1);
    }
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private boolean updateInvestPoint(Point2D _investPoint) {
    if (_investPoint == null) {
        return false;
    }//from   w  ww .ja  v a2 s . c o m

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset();
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)_investPoint);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    /* Believe it? When there is another thread keep updateing time series data,
     * and keep calling setDirty, _plotArea can be 0 size sometimes. Ignore it.
     * Just assume we had processed it.
     */
    if (_plotArea.getWidth() == 0.0 && _plotArea.getHeight() == 0.0) {
        /* Cheat the caller. */
        return true;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    final double coordinateX = domainAxis.java2DToValue(_investPoint.getX(), _plotArea, domainAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // Do not perform translation as this will cause precision losing.
    // We might experience unstable point. For example,
    //
    // this.investPoint is 700.9, there are 2 data points which are 700 and
    // 701.
    // During first updateInvestPoint(this.investPoint) call, data point 701
    // will be chosen, and this.investPoint has been truncated to 700.
    // During second updateInvestPoint(this.investPoint) call, data point 700
    // will be chosen. We may observe an unstable point swings between 700
    // and 701.
    //
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    //final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    final Point2D tmpPoint = new Point2D.Double(xJava2D, yJava2D);
    this.drawArea.setRect(_plotArea);

    if (this.drawArea.contains(tmpPoint)) {
        this.investPointIndex = tmpIndex;
        this.investPoint = tmpPoint;
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private boolean updateROIPoint(Point2D _ROIPoint) {
    if (_ROIPoint == null) {
        return false;
    }//from w  w  w  .j a  v a2  s. c o  m

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    // Dataset 0 are the invest information. 1 is the ROI information.
    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(1);
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)_ROIPoint);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    /* Believe it? When there is another thread keep updateing time series data,
     * and keep calling setDirty, _plotArea can be 0 size sometimes. Ignore it.
     * Just assume we had processed it.
     */
    if (_plotArea.getWidth() == 0.0 && _plotArea.getHeight() == 0.0) {
        /* Cheat the caller. */
        return true;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    final double coordinateX = domainAxis.java2DToValue(_ROIPoint.getX(), _plotArea, domainAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // Do not perform translation as this will cause precision losing.
    // We might experience unstable point. For example,
    //
    // this.ROIPoint is 700.9, there are 2 data points which are 700 and
    // 701.
    // During first updateROIPoint(this.ROIPoint) call, data point 701
    // will be chosen, and this.ROIPoint has been truncated to 700.
    // During second updateROIPoint(this.ROIPoint) call, data point 700
    // will be chosen. We may observe an unstable point swings between 700
    // and 701.
    //
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    //final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    final Point2D tmpPoint = new Point2D.Double(xJava2D, yJava2D);
    this.drawArea.setRect(_plotArea);

    if (this.drawArea.contains(tmpPoint)) {
        this.ROIPointIndex = tmpIndex;
        this.ROIPoint = tmpPoint;
        return true;
    }
    return false;
}

From source file:lu.lippmann.cdb.ext.hydviga.ui.GapFillingFrame.java

private GapFillingCase refresh(final Algo algo, final int[] indexesOfUsedSeries, final boolean hideOthers,
        final boolean showError, final boolean zoom, final boolean showEnvelope, final boolean multAxis)
        throws Exception {
    if (!inBatchMode)
        this.centerPanel.removeAll();

    int[] arr = new int[] { attr.index(), dateIdx };
    for (final int iii : indexesOfUsedSeries) {
        arr = ArraysUtil.concat(arr, new int[] { dataSet.attribute(this.attrNames.get(iii)).index() });
    }/* w w w . j av a2  s .  c o  m*/

    Instances filteredDs = WekaDataProcessingUtil.buildFilteredByAttributesDataSet(dataSet, arr);
    //System.out.println(filteredDs.toSummaryString());

    Attribute original = null;
    Instances filteredDsWithOriginal = null;
    if (this.isGapSimulated) {
        original = new Attribute("original");
        filteredDsWithOriginal = new Instances(filteredDs);
        filteredDsWithOriginal.insertAttributeAt(original, filteredDsWithOriginal.numAttributes() - 1);
        final Attribute origAttr = filteredDsWithOriginal.attribute(original.name());
        for (int ii = position - 1; ii < position + gapsize + 1; ii++) {
            filteredDsWithOriginal.instance(ii).setValue(origAttr, this.originalDataBeforeGapSimulation[ii]);
        }
    }

    filteredDs = WekaDataProcessingUtil.buildFilteredDataSet(filteredDs, 0, filteredDs.numAttributes() - 1,
            Math.max(0, this.position - this.valuesBeforeAndAfter),
            Math.min(this.position + this.gapsize + this.valuesBeforeAndAfter, filteredDs.numInstances() - 1));

    this.gapFiller = GapFillerFactory.getGapFiller(algo);

    final Instances completedds = this.gapFiller.fillGaps(filteredDs);
    final Instances diff = WekaTimeSeriesUtil.buildDiff(filteredDs, completedds);

    final int valuesToCheckForError = this.valuesBeforeAndAfter / 4;

    double maeByEnlargingGap = Double.NaN;
    double maeByAddingAGapBefore = Double.NaN;
    double maeByAddingAGapAfter = Double.NaN;
    double maeByComparingWithOriginal = Double.NaN;

    double rmseByEnlargingGap = Double.NaN;
    double rmseByAddingAGapBefore = Double.NaN;
    double rmseByAddingAGapAfter = Double.NaN;
    double rmseByComparingWithOriginal = Double.NaN;

    double rsrByEnlargingGap = Double.NaN;
    double rsrByAddingAGapBefore = Double.NaN;
    double rsrByAddingAGapAfter = Double.NaN;
    double rsrByComparingWithOriginal = Double.NaN;

    double pbiasByEnlargingGap = Double.NaN;
    double pbiasByAddingAGapBefore = Double.NaN;
    double pbiasByAddingAGapAfter = Double.NaN;
    double pbiasByComparingWithOriginal = Double.NaN;

    double nsByEnlargingGap = Double.NaN;
    double nsByAddingAGapBefore = Double.NaN;
    double nsByAddingAGapAfter = Double.NaN;
    double nsByComparingWithOriginal = Double.NaN;

    double indexOfAgreementByEnlargingGap = Double.NaN;
    double indexOfAgreementByAddingAGapBefore = Double.NaN;
    double indexOfAgreementByAddingAGapAfter = Double.NaN;
    double indexOfAgreementByComparingWithOriginal = Double.NaN;

    if (this.isGapSimulated) {
        //System.out.println(attr.index()+" begin="+(this.position)+" end="+(this.position+this.gapsize));

        final Instances correctedDataSet = buildCorrectedDataset(diff);

        final double[] cad = correctedDataSet.attributeToDoubleArray(attr.index());
        maeByComparingWithOriginal = MathsUtil.mae(this.originalDataBeforeGapSimulation, cad, this.position,
                this.position + this.gapsize);
        rmseByComparingWithOriginal = MathsUtil.rmse(this.originalDataBeforeGapSimulation, cad, this.position,
                this.position + this.gapsize);
        rsrByComparingWithOriginal = MathsUtil.rsr(this.originalDataBeforeGapSimulation, cad, this.position,
                this.position + this.gapsize);
        pbiasByComparingWithOriginal = MathsUtil.pbias(this.originalDataBeforeGapSimulation, cad, this.position,
                this.position + this.gapsize);
        nsByComparingWithOriginal = MathsUtil.nashSutcliffe(this.originalDataBeforeGapSimulation, cad,
                this.position, this.position + this.gapsize);
        indexOfAgreementByComparingWithOriginal = MathsUtil.indexOfAgreement(
                this.originalDataBeforeGapSimulation, cad, this.position, this.position + this.gapsize);
    } else {
        maeByEnlargingGap = this.gapFiller.evaluateMAEByEnlargingGap(filteredDs, valuesToCheckForError);
        maeByAddingAGapBefore = this.gapFiller.evaluateMAEByAddingAGapBefore(filteredDs, valuesToCheckForError);
        maeByAddingAGapAfter = this.gapFiller.evaluateMAEByAddingAGapAfter(filteredDs, valuesToCheckForError);

        rmseByEnlargingGap = this.gapFiller.evaluateRMSEByEnlargingGap(filteredDs, valuesToCheckForError);
        rmseByAddingAGapBefore = this.gapFiller.evaluateRMSEByAddingAGapBefore(filteredDs,
                valuesToCheckForError);
        rmseByAddingAGapAfter = this.gapFiller.evaluateRMSEByAddingAGapAfter(filteredDs, valuesToCheckForError);

        nsByEnlargingGap = this.gapFiller.evaluateNSByEnlargingGap(filteredDs, valuesToCheckForError);
        nsByAddingAGapBefore = this.gapFiller.evaluateNSByAddingAGapBefore(filteredDs, valuesToCheckForError);
        nsByAddingAGapAfter = this.gapFiller.evaluateNSByAddingAGapAfter(filteredDs, valuesToCheckForError);
    }

    if (hideOthers) {
        if (this.isGapSimulated) {
            filteredDs = WekaDataProcessingUtil.buildFilteredByAttributesDataSet(filteredDsWithOriginal,
                    new int[] { 0, 1, filteredDsWithOriginal.attribute(original.name()).index() });
            filteredDs = WekaDataProcessingUtil.buildFilteredDataSet(filteredDs, 0,
                    filteredDs.numAttributes() - 1, Math.max(0, this.position - this.valuesBeforeAndAfter),
                    Math.min(this.position + this.gapsize + this.valuesBeforeAndAfter,
                            filteredDs.numInstances() - 1));
        } else {
            filteredDs = WekaDataProcessingUtil.buildFilteredByAttributesDataSet(filteredDs,
                    new int[] { 0, 1 });
        }
    }

    final Instances decomposition = WekaTimeSeriesUtil.buildMergedDataSet(filteredDs, diff);

    final Attribute diffAttribute = decomposition.attribute(attr.name() + "_diff");

    final List<XYAnnotation> aaa = new ArrayList<XYAnnotation>();
    if (showError) {
        showError(this.isGapSimulated ? maeByComparingWithOriginal : maeByEnlargingGap, decomposition,
                diffAttribute, aaa);
    }

    if (showEnvelope) {
        final MainViewLoadingFrame loadingFrame = new MainViewLoadingFrame();
        loadingFrame.setVisible(true);
        loadingFrame.pack();
        loadingFrame.repaint();
        showEnvelope(arr, aaa);
        loadingFrame.setVisible(false);
    }

    if (!inBatchMode) {
        final ChartPanel cp;
        /*if (showError)
        {
           cp=TimeSeriesChartUtil.buildChartPanelForAllAttributesInterval(decomposition,WekaDataStatsUtil.getFirstDateAttributeIdx(decomposition),mae,diffAttribute.index());
        }
        else
        {*/
        cp = TimeSeriesChartUtil.buildChartPanelForAllAttributes(decomposition, multAxis,
                WekaDataStatsUtil.getFirstDateAttributeIdx(decomposition), null, aaa);
        /*}*/

        final Marker gapBeginMarker = new ValueMarker(
                dataSet.instance(Math.max(0, position - 1)).value(dateIdx));
        gapBeginMarker.setPaint(Color.RED);
        gapBeginMarker.setLabel("Gap begin");
        gapBeginMarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
        gapBeginMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        cp.getChart().getXYPlot().addDomainMarker(gapBeginMarker);

        final Marker gapEndMarker = new ValueMarker(
                dataSet.instance(Math.min(dataSet.numInstances() - 1, position + gapsize)).value(dateIdx));
        gapEndMarker.setPaint(Color.RED);
        gapEndMarker.setLabel("Gap end");
        gapEndMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        gapEndMarker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
        cp.getChart().getXYPlot().addDomainMarker(gapEndMarker);

        if (!zoom) {
            final NumberAxis na = (NumberAxis) (cp.getChart().getXYPlot().getRangeAxis());
            na.setRange(0, WekaDataStatsUtil.getMaxValue(dataSet, attrNames));
        }

        String errorInfo;
        if (!this.isGapSimulated) {
            errorInfo = "By enlarging the gap:\t MAE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(maeByEnlargingGap) + "\t RMSE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(rmseByEnlargingGap) + "\t NASH-SUTCLIFFE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(nsByEnlargingGap)
                    + "\nBy adding a gap before:\t MAE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(maeByAddingAGapBefore) + "\t RMSE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(rmseByAddingAGapBefore) + "\t NASH-SUTCLIFFE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(nsByAddingAGapBefore)
                    + "\nBy adding a gap after:\t MAE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(maeByAddingAGapAfter) + "\t RMSE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(rmseByAddingAGapAfter) + "\t NASH-SUTCLIFFE="
                    + FormatterUtil.DECIMAL_FORMAT_4.format(nsByAddingAGapAfter);
        } else {
            errorInfo = "MAE: " + FormatterUtil.DECIMAL_FORMAT_4.format(maeByComparingWithOriginal);
            errorInfo += "\n";
            errorInfo += "RMSE: " + FormatterUtil.DECIMAL_FORMAT_4.format(rmseByComparingWithOriginal);
            errorInfo += "\n";
            errorInfo += "RSR: " + FormatterUtil.DECIMAL_FORMAT_4.format(rsrByComparingWithOriginal);
            errorInfo += "\n";
            errorInfo += "PBIAS: " + FormatterUtil.DECIMAL_FORMAT_4.format(pbiasByComparingWithOriginal);
            errorInfo += "\n";
            errorInfo += "NASH-SUTCLIFFE: " + FormatterUtil.DECIMAL_FORMAT_4.format(nsByComparingWithOriginal);
            errorInfo += "\n";
            errorInfo += "INDEX OF AGREEMENT: "
                    + FormatterUtil.DECIMAL_FORMAT_4.format(indexOfAgreementByComparingWithOriginal);
        }
        cp.setBorder(new TitledBorder(""));
        final JTextArea errorTextArea = new JTextArea(errorInfo);
        errorTextArea.setBorder(new TitledBorder(""));
        this.centerPanel.add(errorTextArea, BorderLayout.NORTH);
        this.centerPanel.add(cp, BorderLayout.CENTER);

        final JXPanel cmdPanel = new JXPanel();
        final JXButton okButton = new JXButton("Ok");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final Instances correctedDataSet = buildCorrectedDataset(diff);

                final DataChange change = new DataChange(correctedDataSet, TabView.DataChangeTypeEnum.Update);
                atv.pushDataChange(change);

                setVisible(false);
            }
        });
        cmdPanel.add(okButton);
        final JXButton cancelButton = new JXButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                setVisible(false);
            }
        });
        cmdPanel.add(cancelButton);
        this.centerPanel.add(cmdPanel, BorderLayout.SOUTH);

        this.centerPanel.updateUI();

        getContentPane().repaint();
    }

    final double globalMAE = (this.isGapSimulated) ? maeByComparingWithOriginal
            : ((maeByEnlargingGap + maeByAddingAGapBefore + maeByAddingAGapAfter) / 3);

    final double globalRMSE = (this.isGapSimulated) ? rmseByComparingWithOriginal
            : ((rmseByEnlargingGap + rmseByAddingAGapBefore + rmseByAddingAGapAfter) / 3);

    final double globalRSR = (this.isGapSimulated) ? rsrByComparingWithOriginal
            : ((rsrByEnlargingGap + rsrByAddingAGapBefore + rsrByAddingAGapAfter) / 3);

    final double globalPBIAS = (this.isGapSimulated) ? pbiasByComparingWithOriginal
            : ((pbiasByEnlargingGap + pbiasByAddingAGapBefore + pbiasByAddingAGapAfter) / 3);

    final double globalNS = (this.isGapSimulated) ? nsByComparingWithOriginal
            : ((nsByEnlargingGap + nsByAddingAGapBefore + nsByAddingAGapAfter) / 3);

    final double globalIndexOfAgreement = (this.isGapSimulated) ? indexOfAgreementByComparingWithOriginal
            : ((indexOfAgreementByEnlargingGap + indexOfAgreementByAddingAGapBefore
                    + indexOfAgreementByAddingAGapAfter) / 3);

    // usage logs for stats      
    final long firstTimestamp = (long) dataSet.instance(position).value(dateIdx);
    final boolean isDuringRising;
    if (nearest == null)
        isDuringRising = GapsUtil.isDuringRising(dataSet, position, gapsize,
                new int[] { dateIdx, attr.index() });
    else
        isDuringRising = GapsUtil.isDuringRising(dataSet, position, gapsize,
                new int[] { dateIdx, attr.index(), dataSet.attribute(nearest).index() });

    return new GapFillingCase(DateUtil.getSeason(firstTimestamp), DateUtil.getYear(firstTimestamp), algo,
            gapsize, position, attr, gcp.getCoordinates(attr.name())[0], gcp.getCoordinates(attr.name())[1],
            gcp.findDownstreamStation(attr.name()) != null, gcp.findUpstreamStation(attr.name()) != null,
            globalMAE, globalRMSE, globalRSR, globalPBIAS, globalNS, globalIndexOfAgreement,
            ArraysUtil.contains(indexesOfUsedSeries, attrNames.indexOf(mostSimilar)),
            ArraysUtil.contains(indexesOfUsedSeries, attrNames.indexOf(nearest)),
            ArraysUtil.contains(indexesOfUsedSeries, attrNames.indexOf(downstream)),
            ArraysUtil.contains(indexesOfUsedSeries, attrNames.indexOf(upstream)), isDuringRising,
            GapsUtil.measureHighMiddleLowInterval(dataSet, attr.index(), position - 1));
}