Example usage for org.jfree.data.xy XYIntervalSeries add

List of usage examples for org.jfree.data.xy XYIntervalSeries add

Introduction

In this page you can find the example usage for org.jfree.data.xy XYIntervalSeries add.

Prototype

public void add(double x, double xLow, double xHigh, double y, double yLow, double yHigh) 

Source Link

Document

Adds a data item to the series and sends a SeriesChangeEvent to all registered listeners.

Usage

From source file:com.att.aro.ui.view.diagnostictab.plot.BluetoothPlot.java

@Override
public void populate(XYPlot plot, AROTraceData analysis) {
    if (analysis != null) {
        bluetoothData.removeAllSeries();
        XYIntervalSeries bluetoothConnected = new XYIntervalSeries(BluetoothState.BLUETOOTH_CONNECTED);
        XYIntervalSeries bluetoothDisconnected = new XYIntervalSeries(BluetoothState.BLUETOOTH_DISCONNECTED);
        XYIntervalSeries bluetoothOff = new XYIntervalSeries(BluetoothState.BLUETOOTH_TURNED_OFF);
        XYIntervalSeries bluetoothOn = new XYIntervalSeries(BluetoothState.BLUETOOTH_TURNED_ON);
        XYIntervalSeries bluetoothUnknown = new XYIntervalSeries(BluetoothState.BLUETOOTH_UNKNOWN);

        bluetoothData.addSeries(bluetoothConnected);
        bluetoothData.addSeries(bluetoothDisconnected);
        bluetoothData.addSeries(bluetoothOff);
        bluetoothData.addSeries(bluetoothOn);
        bluetoothData.addSeries(bluetoothUnknown);

        // Populate the data set
        Iterator<BluetoothInfo> iter = analysis.getAnalyzerResult().getTraceresult().getBluetoothInfos()
                .iterator();/*from www .j a va2s  . co  m*/
        XYIntervalSeries series;
        if (iter.hasNext()) {
            while (iter.hasNext()) {
                BluetoothInfo btEvent = iter.next();
                if (btEvent.getBluetoothState() == null) {
                    series = bluetoothUnknown;
                } else {
                    switch (btEvent.getBluetoothState()) {
                    case BLUETOOTH_CONNECTED:
                        series = bluetoothConnected;
                        break;
                    case BLUETOOTH_DISCONNECTED:
                        series = bluetoothDisconnected;
                        break;
                    case BLUETOOTH_TURNED_ON:
                        series = bluetoothOn;
                        break;
                    case BLUETOOTH_TURNED_OFF:
                        series = bluetoothOff;
                        break;
                    default:
                        series = bluetoothUnknown;
                        break;
                    }
                }
                series.add(btEvent.getBeginTimeStamp(), btEvent.getBeginTimeStamp(), btEvent.getEndTimeStamp(),
                        0.5, 0, 1);
            }

        }

        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(bluetoothData.indexOf(BluetoothState.BLUETOOTH_CONNECTED),
                new Color(34, 177, 76));
        renderer.setSeriesPaint(bluetoothData.indexOf(BluetoothState.BLUETOOTH_DISCONNECTED), Color.YELLOW);
        renderer.setSeriesPaint(bluetoothData.indexOf(BluetoothState.BLUETOOTH_TURNED_OFF),
                new Color(216, 132, 138));
        renderer.setSeriesPaint(bluetoothData.indexOf(BluetoothState.BLUETOOTH_TURNED_ON),
                new Color(162, 226, 98));
        renderer.setSeriesPaint(bluetoothData.indexOf(BluetoothState.BLUETOOTH_UNKNOWN),
                new Color(154, 154, 154));

        // Assign ToolTip to renderer
        renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
                BluetoothState eventType = (BluetoothState) bluetoothData.getSeries(series).getKey();
                return MessageFormat.format(ResourceBundleHelper.getMessageString("bluetooth.tooltip"),
                        dataset.getX(series, item), ResourceBundleHelper.getEnumString(eventType));
            }
        });

    }
    plot.setDataset(bluetoothData);
    //         return plot;
}

From source file:userinterface.graph.Histogram.java

/**
 * Add a point to the specified graph series.
 * @param seriesKey Key of series to update.
 * @param dataItem XYDataItem object to insert into this series.
 *//*from ww w.  ja va 2 s  .co  m*/
public void addPointToSeries(SeriesKey seriesKey, XYIntervalDataItem dataItem) {

    synchronized (seriesCollection) {

        XYIntervalSeries series = keyToSeries.get(seriesKey);
        series.add(dataItem.getX(), dataItem.getXLowValue(), dataItem.getXHighValue(), dataItem.getYValue(),
                dataItem.getYLowValue(), dataItem.getYHighValue());

    }
}

From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java

private XYIntervalSeries computeRegressionData(double xStart, double xEnd) {
    if (scatterpointsDataset.getItemCount(0) > 1) {
        final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0);
        final Function2D curve = new LineFunction2D(coefficients[0], coefficients[1]);
        final XYSeries regressionData = DatasetUtilities.sampleFunction2DToSeries(curve, xStart, xEnd, 100,
                "regression line");
        final XYIntervalSeries xyIntervalRegression = new XYIntervalSeries(regressionData.getKey());
        for (int i = 0; i < regressionData.getItemCount(); i++) {
            XYDataItem item = regressionData.getDataItem(i);
            final double x = item.getXValue();
            final double y = item.getYValue();
            xyIntervalRegression.add(x, x, x, y, y, y);
        }// www .j  av  a 2 s.c  o  m
        return xyIntervalRegression;
    } else {
        JOptionPane.showMessageDialog(this, "Unable to compute regression line.\n"
                + "At least 2 values are needed to compute regression coefficients.");
        return null;
    }
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private XYIntervalSeries computeRegressionData(double xStart, double xEnd) {
    if (scatterpointsDataset.getItemCount(0) > 1) {
        final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0);
        final Function2D curve = new LineFunction2D(coefficients[0], coefficients[1]);
        final XYSeries regressionData = DatasetUtilities.sampleFunction2DToSeries(curve, xStart, xEnd, 100,
                "regression line");
        final XYIntervalSeries xyIntervalRegression = new XYIntervalSeries(regressionData.getKey());
        final List<XYDataItem> regressionDataItems = regressionData.getItems();
        for (XYDataItem item : regressionDataItems) {
            final double x = item.getXValue();
            final double y = item.getYValue();
            xyIntervalRegression.add(x, x, x, y, y, y);
        }/*w  w  w. j  av  a  2 s  .  c o  m*/
        return xyIntervalRegression;
    } else {
        JOptionPane.showMessageDialog(this, "Unable to compute regression line.\n"
                + "At least 2 values are needed to compute regression coefficients.");
        return null;
    }
}

From source file:jboost.visualization.HistogramFrame.java

private void updateHistogramDatasets() {

    if (histogramDataset.getSeriesCount() > 0) {
        histogramDataset.removeAllSeries();
        fluctDataset.removeAllSeries();//www .j a  va 2  s .c o  m
        weightDataset.removeAllSeries();
        potentialDataset.removeAllSeries();
    }

    XYIntervalSeries posSeries = new XYIntervalSeries("positive");
    XYIntervalSeries negSeries = new XYIntervalSeries("negative");

    double[] posHist = rawData.computeHistogram(1, noOfBins);
    double[] negHist = rawData.computeHistogram(-1, noOfBins);

    double min = rawData.getMin(iter);
    double max = rawData.getMax(iter);

    double x = min;
    double step = (max - min) / noOfBins;
    double height = 1.0;
    for (int i = 0; i < noOfBins; i++) {
        posSeries.add(x, x, x + (step / 2), posHist[i], 0, posHist[i]);
        negSeries.add(x + (step / 2), x + (step / 2), x + step, negHist[i], 0, negHist[i]);
        x = x + step;
        if (posHist[i] > height)
            height = posHist[i];
        if (negHist[i] > height)
            height = negHist[i];
    }

    histogramDataset.addSeries(posSeries);
    histogramDataset.addSeries(negSeries);
    fluctDataset.addSeries(rawData.getFluctBins());
    fluctDataset.addSeries(rawData.getFluctRanges());

    if (histogramChart != null) {
        ValueAxis axis = new NumberAxis();
        axis.setRange(rawData.getMinRange(iter), rawData.getMaxRange(iter));
        histogramChart.getXYPlot().setDomainAxis(axis);
    }

    if (infoParser.isRobustBoost) {
        double t = infoParser.averageTime[iter];
        double rho = infoParser.rho;
        @SuppressWarnings("unused")
        boolean confRated = infoParser.confRated;
        double sigma_f = infoParser.sigma_f;
        double epsilon = infoParser.epsilon;
        double theta = infoParser.theta;

        rho = RobustBoostHelper.calculateRho(sigma_f, epsilon, theta);

        if (showWeight) {
            weightDataset.addSeries(RobustBoostHelper.getPosWeightPlot(sigma_f, epsilon, theta, rho, t, height,
                    min, max, step / 2));
            weightDataset.addSeries(RobustBoostHelper.getNegWeightPlot(sigma_f, epsilon, theta, rho, t, height,
                    min, max, step / 2));
        }

        if (showPotential) {
            potentialDataset.addSeries(RobustBoostHelper.getPosPotentialPlot(sigma_f, epsilon, theta, rho, t,
                    height, min, max, step / 2));
            potentialDataset.addSeries(RobustBoostHelper.getNegPotentialPlot(sigma_f, epsilon, theta, rho, t,
                    height, min, max, step / 2));
        }
    } else if (infoParser.isAdaBoost) {
        if (showWeight) {
            weightDataset.addSeries(AdaBoostHelper.getPosWeightPlot(height, min, max, step / 2));
            weightDataset.addSeries(AdaBoostHelper.getNegWeightPlot(height, min, max, step / 2));
        }

        if (showPotential) {
            potentialDataset.addSeries(AdaBoostHelper.getPosPotentialPlot(height, min, max, step / 2));
            potentialDataset.addSeries(AdaBoostHelper.getNegPotentialPlot(height, min, max, step / 2));
        }
    } else if (infoParser.isLogLossBoost) {
        if (showWeight) {
            weightDataset.addSeries(LogLossBoostHelper.getPosWeightPlot(height, min, max, step / 2));
            weightDataset.addSeries(LogLossBoostHelper.getNegWeightPlot(height, min, max, step / 2));
        }

        if (showPotential) {
            potentialDataset.addSeries(LogLossBoostHelper.getPosPotentialPlot(height, min, max, step / 2));
            potentialDataset.addSeries(LogLossBoostHelper.getNegPotentialPlot(height, min, max, step / 2));
        }
    }
}

From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

    final AttributeDescriptor dataField = scatterPlotModel.dataField;
    if (raster == null || dataField == null) {
        return;/*from   w  ww .  j av  a2  s  .  c o  m*/
    }

    SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() {

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            SystemUtils.LOG.finest("start computing scatter plot data");

            final List<ComputedData> computedDataList = new ArrayList<>();

            final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource
                    .getFeatureCollection();
            final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]);

            final int boxSize = scatterPlotModel.boxSize;

            final Rectangle sceneRect = new Rectangle(raster.getRasterWidth(), raster.getRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = Product.findImageToModelTransform(geoCoding);
            for (SimpleFeature feature : features) {
                final Point point = (Point) feature.getDefaultGeometryProperty().getValue();
                Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY());
                final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null);

                if (!sceneRect.contains(imagePos)) {
                    continue;
                }
                final float imagePosX = (float) imagePos.getX();
                final float imagePosY = (float) imagePos.getY();
                final Rectangle imageRect = sceneRect.intersection(new Rectangle(
                        ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize));
                if (imageRect.isEmpty()) {
                    continue;
                }
                final double[] rasterValues = new double[imageRect.width * imageRect.height];
                raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues);

                final int[] maskBuffer = new int[imageRect.width * imageRect.height];
                Arrays.fill(maskBuffer, 1);
                if (selectedMask != null) {
                    selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height,
                            maskBuffer);
                }

                final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2);
                if (maskBuffer[centerIndex] == 0) {
                    continue;
                }

                double sum = 0;
                double sumSqr = 0;
                int n = 0;
                boolean valid = false;

                for (int y = 0; y < imageRect.height; y++) {
                    for (int x = 0; x < imageRect.width; x++) {
                        final int index = y * imageRect.height + x;
                        if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) {
                            final double rasterValue = rasterValues[index];
                            sum += rasterValue;
                            sumSqr += rasterValue * rasterValue;
                            n++;
                            valid = true;
                        }
                    }
                }

                if (!valid) {
                    continue;
                }

                double rasterMean = sum / n;
                double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0;

                String localName = dataField.getLocalName();
                Number attribute = (Number) feature.getAttribute(localName);

                final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties();

                final float correlativeData = attribute.floatValue();
                final GeoPos geoPos = new GeoPos();
                if (geoCoding.canGetGeoPos()) {
                    final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY);
                    geoCoding.getGeoPos(pixelPos, geoPos);
                } else {
                    geoPos.setInvalid();
                }
                computedDataList.add(
                        new ComputedData(imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(),
                                (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties));
            }

            return computedDataList.toArray(new ComputedData[computedDataList.size()]);
        }

        @Override
        public void done() {
            try {
                final ValueAxis xAxis = getPlot().getDomainAxis();
                final ValueAxis yAxis = getPlot().getRangeAxis();

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                scatterpointsDataset.removeAllSeries();
                acceptableDeviationDataset.removeAllSeries();
                regressionDataset.removeAllSeries();
                getPlot().removeAnnotation(r2Annotation);
                computedDatas = null;

                final ComputedData[] data = get();
                if (data.length == 0) {
                    return;
                }

                computedDatas = data;

                final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName());
                for (ComputedData computedData : computedDatas) {
                    final float rasterMean = computedData.rasterMean;
                    final float rasterSigma = computedData.rasterSigma;
                    final float correlativeData = computedData.correlativeData;
                    scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean,
                            rasterMean - rasterSigma, rasterMean + rasterSigma);
                }

                computingData = true;
                scatterpointsDataset.addSeries(scatterValues);

                xAxis.setAutoRange(true);
                yAxis.setAutoRange(true);

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound());
                yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound());

                if (xAxisRangeControl.isAutoMinMax()) {
                    xAxisRangeControl.adjustComponents(xAxis, 3);
                } else {
                    xAxisRangeControl.adjustAxis(xAxis, 3);
                }
                if (yAxisRangeControl.isAutoMinMax()) {
                    yAxisRangeControl.adjustComponents(yAxis, 3);
                } else {
                    yAxisRangeControl.adjustAxis(yAxis, 3);
                }

                computeRegressionAndAcceptableDeviationData();
                computingData = false;
            } catch (InterruptedException | CancellationException e) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE,
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        JOptionPane.ERROR_MESSAGE, null);
            } catch (ExecutionException e) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n"
                        + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null);
            }
        }
    };
    swingWorker.execute();
}

From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java

private XYIntervalSeries computeAcceptableDeviationData(double lowerBound, double upperBound) {
    final XYSeries identity = DatasetUtilities.sampleFunction2DToSeries(x -> x, lowerBound, upperBound, 100,
            "1:1 line");
    final XYIntervalSeries xyIntervalSeries = new XYIntervalSeries(identity.getKey());
    for (int i = 0; i < identity.getItemCount(); i++) {
        XYDataItem item = identity.getDataItem(i);
        final double x = item.getXValue();
        final double y = item.getYValue();
        if (scatterPlotModel.showAcceptableDeviation) {
            final double acceptableDeviation = scatterPlotModel.acceptableDeviationInterval;
            final double xOff = acceptableDeviation * x / 100;
            final double yOff = acceptableDeviation * y / 100;
            xyIntervalSeries.add(x, x - xOff, x + xOff, y, y - yOff, y + yOff);
        } else {/*w  w  w . ja v  a2 s  .co  m*/
            xyIntervalSeries.add(x, x, x, y, y, y);
        }
    }
    return xyIntervalSeries;
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

    final AttributeDescriptor dataField = scatterPlotModel.dataField;
    if (raster == null || dataField == null) {
        return;/*from   w  w w .j a  v  a 2s  .  c  o  m*/
    }

    SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() {

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            BeamLogManager.getSystemLogger().finest("start computing scatter plot data");

            final List<ComputedData> computedDataList = new ArrayList<>();

            final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource
                    .getFeatureCollection();
            final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]);

            final int boxSize = scatterPlotModel.boxSize;

            final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(),
                    raster.getSceneRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding);
            for (SimpleFeature feature : features) {
                final Point point = (Point) feature.getDefaultGeometryProperty().getValue();
                Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY());
                final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null);

                if (!sceneRect.contains(imagePos)) {
                    continue;
                }
                final float imagePosX = (float) imagePos.getX();
                final float imagePosY = (float) imagePos.getY();
                final Rectangle imageRect = sceneRect.intersection(new Rectangle(
                        ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize));
                if (imageRect.isEmpty()) {
                    continue;
                }
                final double[] rasterValues = new double[imageRect.width * imageRect.height];
                raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues);

                final int[] maskBuffer = new int[imageRect.width * imageRect.height];
                Arrays.fill(maskBuffer, 1);
                if (selectedMask != null) {
                    selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height,
                            maskBuffer);
                }

                final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2);
                if (maskBuffer[centerIndex] == 0) {
                    continue;
                }

                double sum = 0;
                double sumSqr = 0;
                int n = 0;
                boolean valid = false;

                for (int y = 0; y < imageRect.height; y++) {
                    for (int x = 0; x < imageRect.width; x++) {
                        final int index = y * imageRect.height + x;
                        if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) {
                            final double rasterValue = rasterValues[index];
                            sum += rasterValue;
                            sumSqr += rasterValue * rasterValue;
                            n++;
                            valid = true;
                        }
                    }
                }

                if (!valid) {
                    continue;
                }

                double rasterMean = sum / n;
                double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0;

                String localName = dataField.getLocalName();
                Number attribute = (Number) feature.getAttribute(localName);

                final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties();

                final float correlativeData = attribute.floatValue();
                final GeoPos geoPos = new GeoPos();
                if (geoCoding.canGetGeoPos()) {
                    final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY);
                    geoCoding.getGeoPos(pixelPos, geoPos);
                } else {
                    geoPos.setInvalid();
                }
                computedDataList.add(new ComputedData(imagePosX, imagePosY, geoPos.getLat(), geoPos.getLon(),
                        (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties));
            }

            return computedDataList.toArray(new ComputedData[computedDataList.size()]);
        }

        @Override
        public void done() {
            try {
                final ValueAxis xAxis = getPlot().getDomainAxis();
                final ValueAxis yAxis = getPlot().getRangeAxis();

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                scatterpointsDataset.removeAllSeries();
                acceptableDeviationDataset.removeAllSeries();
                regressionDataset.removeAllSeries();
                getPlot().removeAnnotation(r2Annotation);
                computedDatas = null;

                final ComputedData[] data = get();
                if (data.length == 0) {
                    return;
                }

                computedDatas = data;

                final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName());
                for (ComputedData computedData : computedDatas) {
                    final float rasterMean = computedData.rasterMean;
                    final float rasterSigma = computedData.rasterSigma;
                    final float correlativeData = computedData.correlativeData;
                    scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean,
                            rasterMean - rasterSigma, rasterMean + rasterSigma);
                }

                computingData = true;
                scatterpointsDataset.addSeries(scatterValues);

                xAxis.setAutoRange(true);
                yAxis.setAutoRange(true);

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound());
                yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound());

                if (xAxisRangeControl.isAutoMinMax()) {
                    xAxisRangeControl.adjustComponents(xAxis, 3);
                } else {
                    xAxisRangeControl.adjustAxis(xAxis, 3);
                }
                if (yAxisRangeControl.isAutoMinMax()) {
                    yAxisRangeControl.adjustComponents(yAxis, 3);
                } else {
                    yAxisRangeControl.adjustAxis(yAxis, 3);
                }

                computeRegressionAndAcceptableDeviationData();
                computingData = false;
            } catch (InterruptedException | CancellationException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        /*I18N*/
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            } catch (ExecutionException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "An error occurred:\n"
                                + e.getCause().getMessage(),
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    };
    swingWorker.execute();
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private XYIntervalSeries computeAcceptableDeviationData(double lowerBound, double upperBound) {
    final Function2D identityFunction = new Function2D() {
        @Override/*from w ww  .  j  a v a2 s  .c  om*/
        public double getValue(double x) {
            return x;
        }
    };

    final XYSeries identity = DatasetUtilities.sampleFunction2DToSeries(identityFunction, lowerBound,
            upperBound, 100, "1:1 line");
    final XYIntervalSeries xyIntervalSeries = new XYIntervalSeries(identity.getKey());
    final List<XYDataItem> items = identity.getItems();
    for (XYDataItem item : items) {
        final double x = item.getXValue();
        final double y = item.getYValue();
        if (scatterPlotModel.showAcceptableDeviation) {
            final double acceptableDeviation = scatterPlotModel.acceptableDeviationInterval;
            final double xOff = acceptableDeviation * x / 100;
            final double yOff = acceptableDeviation * y / 100;
            xyIntervalSeries.add(x, x - xOff, x + xOff, y, y - yOff, y + yOff);
        } else {
            xyIntervalSeries.add(x, x, x, y, y, y);
        }
    }
    return xyIntervalSeries;
}

From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java

protected JFreeChart getFutureForecastChart(TSForecaster forecaster, List<List<NumericPrediction>> preds,
        List<String> targetNames, Instances history) {

    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) {

            // fill in any missing time stamps only
            history = new Instances(history);
            history = weka.classifiers.timeseries.core.Utils.replaceMissing(history, null,
                    lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
        }/*from   www. j  a  v  a  2s.c o  m*/
    }

    // set up a collection of series
    XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();

    if (history != null) {
        // add actual historical data values
        for (String targetName : targetNames) {
            XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false);
            xyDataset.addSeries(targetSeries);
        }
    }

    // add predicted series
    for (String targetName : targetNames) {
        XYIntervalSeries targetSeries = new XYIntervalSeries(targetName + "-predicted", false, false);
        xyDataset.addSeries(targetSeries);
    }

    ValueAxis timeAxis = null;
    NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false);
    int timeIndex = -1;
    boolean timeAxisIsDate = false;
    double artificialTimeStart = 0;
    double lastRealTimeValue = Utils.missingValue();
    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) {
            String timeName = lagMaker.getTimeStampField();
            if (history.attribute(timeName).isDate()) {
                timeAxis = new DateAxis("");
                timeAxisIsDate = true;
                timeIndex = history.attribute(timeName).index();
            }
        } else {
            try {
                artificialTimeStart = (history != null) ? 1 : lagMaker.getArtificialTimeStartValue() + 1;
            } catch (Exception ex) {
            }
        }
    }

    if (timeAxis == null) {
        timeAxis = new NumberAxis("");
        ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
    }

    boolean hasConfidenceIntervals = false;

    // now populate the series
    if (history != null) {

        // do the actuals first
        for (int i = 0; i < history.numInstances(); i++) {
            Instance current = history.instance(i);

            for (String targetName : targetNames) {
                int dataIndex = history.attribute(targetName.trim()).index();

                if (dataIndex >= 0) {
                    XYIntervalSeries actualSeries = null;
                    int actualIndex = xyDataset.indexOf(targetName);
                    actualSeries = xyDataset.getSeries(actualIndex);
                    double x = Utils.missingValue();

                    if (timeAxisIsDate) {
                        x = current.value(timeIndex);
                        if (!Utils.isMissingValue(x)) {
                            lastRealTimeValue = x;
                        }
                    } else {
                        x = artificialTimeStart;
                    }

                    double y = Utils.missingValue();
                    y = current.value(dataIndex);

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        if (actualSeries != null) {
                            actualSeries.add(x, x, x, y, y, y);
                        }
                    }
                }
            }

            if (!timeAxisIsDate) {
                artificialTimeStart++;
            }
        }
    }

    // now do the futures
    List<String> forecasterTargets = AbstractForecaster.stringToList(forecaster.getFieldsToForecast());

    // loop over the steps
    for (int j = 0; j < preds.size(); j++) {
        List<NumericPrediction> predsForStepJ = preds.get(j);

        // advance the real time index (if appropriate)
        if (timeAxisIsDate) {
            lastRealTimeValue = ((TSLagUser) forecaster).getTSLagMaker()
                    .advanceSuppliedTimeValue(lastRealTimeValue);
        }
        for (String targetName : targetNames) {

            // look up this requested target in the list that the forecaster
            // has predicted
            int predIndex = forecasterTargets.indexOf(targetName.trim());
            if (predIndex >= 0) {
                NumericPrediction predsForTargetAtStepJ = predsForStepJ.get(predIndex);
                XYIntervalSeries predSeries = null;
                int datasetIndex = xyDataset.indexOf(targetName + "-predicted");
                predSeries = xyDataset.getSeries(datasetIndex);

                if (predSeries != null) {
                    double y = predsForTargetAtStepJ.predicted();
                    double x = Utils.missingValue();
                    double yHigh = y;
                    double yLow = y;
                    double[][] conf = predsForTargetAtStepJ.predictionIntervals();
                    if (conf.length > 0) {
                        yLow = conf[0][0];
                        yHigh = conf[0][1];
                        hasConfidenceIntervals = true;
                    }

                    if (!timeAxisIsDate) {
                        x = artificialTimeStart;
                    } else {
                        x = lastRealTimeValue;
                    }

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        predSeries.add(x, x, x, y, yLow, yHigh);
                    }
                }
            }
        }

        // advance the artificial time index (if appropriate)
        if (!timeAxisIsDate) {
            artificialTimeStart++;
        }
    }

    String title = "Future forecast for: ";
    for (String s : targetNames) {
        title += s + ",";
    }
    title = title.substring(0, title.lastIndexOf(","));

    /*
     * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
     * + ")";
     */

    if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
        double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
        title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
    }

    XYErrorRenderer renderer = new XYErrorRenderer();

    // renderer.setShapesFilled(true);
    XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
    // renderer = (XYErrorRenderer)plot.getRenderer();
    if (history != null) {
        for (String targetName : targetNames) {
            XYIntervalSeries predSeries = null;
            int predIndex = xyDataset.indexOf(targetName + "-predicted");
            predSeries = xyDataset.getSeries(predIndex);

            XYIntervalSeries actualSeries = null;
            int actualIndex = xyDataset.indexOf(targetName);
            actualSeries = xyDataset.getSeries(actualIndex);

            if (actualSeries != null && predSeries != null) {
                // match the color of the actual series
                java.awt.Paint actualPaint = renderer.lookupSeriesPaint(actualIndex);
                renderer.setSeriesPaint(predIndex, actualPaint);

                // now set the line style to dashed
                BasicStroke dashed = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                        new float[] { 5.0f }, 0.0f);

                renderer.setSeriesStroke(predIndex, dashed);
            }
        }
    }

    renderer.setBaseLinesVisible(true);
    renderer.setDrawXError(false);
    renderer.setDrawYError(true);

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(java.awt.Color.white);
    TextTitle chartTitle = chart.getTitle();
    String fontName = chartTitle.getFont().getFontName();
    java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
    chartTitle.setFont(newFont);

    return chart;
}