Example usage for org.jfree.data.time TimeSeries getDataItem

List of usage examples for org.jfree.data.time TimeSeries getDataItem

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeries getDataItem.

Prototype

public TimeSeriesDataItem getDataItem(RegularTimePeriod period) 

Source Link

Document

Returns the data item for a specific period.

Usage

From source file:org.jmxtrans.embedded.samples.graphite.GraphiteDataInjector.java

public void exportMetrics(TimeSeries timeSeries) throws IOException {
    System.out.println("Export '" + timeSeries.getKey() + "' to " + graphiteHost + " with prefix '"
            + graphiteMetricPrefix + "'");
    Socket socket = new Socket(graphiteHost, graphitePort);
    OutputStream outputStream = socket.getOutputStream();

    if (generateDataPointsFile) {
        JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount",
                new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false);
        // chart.getXYPlot().setRenderer(new XYSplineRenderer(60));

        File file = new File("/tmp/" + timeSeries.getKey() + ".png");
        ChartUtilities.saveChartAsPNG(file, chart, 1200, 800);
        System.out.println("Exported " + file.getAbsolutePath());

        String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle";
        System.out.println("Generate " + pickleFileName);
        outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName));
    }//from w w  w .j  av  a 2s  . co  m

    PyList list = new PyList();

    for (int i = 0; i < timeSeries.getItemCount(); i++) {
        if (debug)
            System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t"
                    + timeSeries.getDataItem(i).getValue().intValue());
        String metricName = graphiteMetricPrefix + timeSeries.getKey().toString();
        int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(),
                TimeUnit.MILLISECONDS);
        int value = timeSeries.getDataItem(i).getValue().intValue();

        list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value))));

        if (list.size() >= batchSize) {
            System.out.print("-");
            rateLimiter.acquire(list.size());
            sendDataPoints(outputStream, list);
        }
    }

    // send last data points
    if (!list.isEmpty()) {
        rateLimiter.acquire(list.size());
        sendDataPoints(outputStream, list);
    }

    Flushables.flushQuietly(outputStream);
    Closeables.close(outputStream, true);
    try {
        socket.close();
    } catch (Exception e) {
        // swallow exception
        e.printStackTrace();
    }

    System.out.println();
    System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items");
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Test the setMaximumItemCount() method to ensure that it removes items
 * from the series if necessary./*from www. j  a  v  a2  s  .c o  m*/
 */
@Test
public void testSetMaximumItemCount() {
    TimeSeries s1 = new TimeSeries("S1", Year.class);
    s1.add(new Year(2000), 13.75);
    s1.add(new Year(2001), 11.90);
    s1.add(new Year(2002), null);
    s1.add(new Year(2005), 19.32);
    s1.add(new Year(2007), 16.89);
    assertTrue(s1.getItemCount() == 5);

    s1.setMaximumItemCount(3);
    assertTrue(s1.getItemCount() == 3);
    TimeSeriesDataItem item = s1.getDataItem(0);
    assertTrue(item.getPeriod().equals(new Year(2002)));
    assertEquals(16.89, s1.getMinY(), EPSILON);
    assertEquals(19.32, s1.getMaxY(), EPSILON);
}

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

private Point2D.Double getPoint(int dataIndex, Type type) {
    if (dataIndex < 0) {
        return null;
    }//from  w  w  w .ja v a 2  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:org.mwc.cmap.xyplot.views.XYPlotView.java

@SuppressWarnings("deprecation")
private void fillThePlot(final String title, final String units, final formattingOperation theFormatter,
        final AbstractSeriesDataset dataset) {

    final StepControl _theStepper = null;

    // the working variables we rely on later
    _thePlotArea = null;//from   w w w  . ja v  a2 s  .  c  o m
    ValueAxis xAxis = null;

    XYToolTipGenerator tooltipGenerator = null;

    // the y axis is common to hi & lo res. Format it here
    final NumberAxis yAxis = new NumberAxis(units);
    final Font tickFont = new Font("SansSerif", Font.PLAIN, 14);
    Font labelFont = new Font("SansSerif", Font.PLAIN, 16);
    yAxis.setLabelFont(labelFont);
    yAxis.setTickLabelFont(tickFont);

    // hmm, see if we are in hi-res mode. If we are, don't use a formatted
    // y-axis, just use the plain long microseconds
    // value
    if (HiResDate.inHiResProcessingMode()) {

        // final SimpleDateFormat _secFormat = new SimpleDateFormat("ss");

        // ok, simple enough for us...
        final NumberAxis nAxis = new NumberAxis("time (secs.micros)") {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            // public String getTickLabel(double currentTickValue)
            // {
            // long time = (long) currentTickValue;
            // Date dtg = new HiResDate(0, time).getDate();
            // String res = _secFormat.format(dtg) + "."
            // + DebriefFormatDateTime.formatMicros(new HiResDate(0, time));
            // return res;
            // }
        };
        nAxis.setAutoRangeIncludesZero(false);
        xAxis = nAxis;

        // just show the raw data values
        tooltipGenerator = new StandardXYToolTipGenerator();
    } else {
        // create a date-formatting axis
        final DateAxis dAxis = new RelativeDateAxis();
        dAxis.setStandardTickUnits(DateAxisEditor.createStandardDateTickUnitsAsTickUnits());
        xAxis = dAxis;

        // also create the date-knowledgable tooltip writer
        tooltipGenerator = new DatedToolTipGenerator();
    }

    xAxis.setTickLabelFont(tickFont);
    xAxis.setLabelFont(labelFont);

    // create the special stepper plot
    final ColourStandardXYItemRenderer theRenderer = new ColourStandardXYItemRenderer(tooltipGenerator, null,
            null);
    _thePlot = new StepperXYPlot(null, (RelativeDateAxis) xAxis, yAxis, _theStepper, theRenderer);
    theRenderer.setPlot(_thePlot);
    theRenderer.setStroke(new BasicStroke(3.0f));

    _thePlot.setRangeGridlineStroke(new BasicStroke(1f));
    _thePlot.setDomainGridlineStroke(new BasicStroke(1f));
    _thePlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
    xAxis.setTickMarkStroke(new BasicStroke(1f));
    yAxis.setTickMarkStroke(new BasicStroke(1f));
    _thePlot.setOutlineStroke(new BasicStroke(2f));

    // loop through the datasets, setting the color of each series to the first
    // color in that series
    if (dataset instanceof TimeSeriesCollection) {
        Color seriesCol = null;
        final TimeSeriesCollection tsc = (TimeSeriesCollection) dataset;
        for (int i = 0; i < dataset.getSeriesCount(); i++) {
            final TimeSeries ts = tsc.getSeries(i);
            if (ts.getItemCount() > 0) {
                final TimeSeriesDataItem dataItem = ts.getDataItem(0);
                if (dataItem instanceof ColouredDataItem) {
                    final ColouredDataItem cd = (ColouredDataItem) dataItem;
                    seriesCol = cd.getColor();
                    _thePlot.getRenderer().setSeriesPaint(i, seriesCol);
                }
            }
        }
    }

    // apply any formatting for this choice
    if (theFormatter != null) {
        theFormatter.format(_thePlot);
    }

    boolean createLegend = dataset.getSeriesCount() > 1;
    _thePlotArea = new NewFormattedJFreeChart(title, null, _thePlot, createLegend, _theStepper);

    // set the color of the area surrounding the plot
    // - naah, don't bother. leave it in the application background color.
    _thePlotArea.setBackgroundPaint(Color.white);

    // ////////////////////////////////////////////////
    // put the holder into one of our special items
    // ////////////////////////////////////////////////
    _chartInPanel = new StepperChartPanel(_thePlotArea, true, _theStepper);

    // ok - we need to fire time-changes to the chart
    setupFiringChangesToChart();

    // format the chart
    _chartInPanel.setName(title);
    _chartInPanel.setMouseZoomable(true, true);

    // and insert into the composite
    _plotControl.setChart(_thePlotArea);

    // get the cross hairs ready
    _thePlot.setDomainCrosshairVisible(true);
    _thePlot.setRangeCrosshairVisible(true);
    _thePlot.setDomainCrosshairPaint(Color.GRAY);
    _thePlot.setRangeCrosshairPaint(Color.GRAY);
    _thePlot.setDomainCrosshairStroke(new BasicStroke(2));
    _thePlot.setRangeCrosshairStroke(new BasicStroke(2));

    // and the plot object to display the cross hair value
    _crosshairValueText = new XYTextAnnotation(" ", 0, 0);
    _crosshairValueText.setTextAnchor(TextAnchor.TOP_LEFT);
    _crosshairValueText.setFont(new Font("SansSerif", Font.BOLD, 15));
    _crosshairValueText.setPaint(Color.black);
    _crosshairValueText.setBackgroundPaint(Color.white);
    _thePlot.addAnnotation(_crosshairValueText);

    _thePlotArea.addChangeListener(new ChartChangeListener() {

        @Override
        public void chartChanged(ChartChangeEvent event) {
            if (_showSymbols.isShowSymbols() != _thePlotArea.isShowSymbols()) {
                _showSymbols.updateAction();
            }
        }
    });
    _showSymbols.updateAction();
    _thePlotArea.addProgressListener(new ChartProgressListener() {
        public void chartProgress(final ChartProgressEvent cpe) {
            if (cpe.getType() != ChartProgressEvent.DRAWING_FINISHED)
                return;

            // double-check our label is still in the right place
            final double xVal = _thePlot.getRangeAxis().getUpperBound();
            final double yVal = _thePlot.getDomainAxis().getLowerBound();

            boolean annotChanged = false;
            if (_crosshairValueText.getX() != yVal) {
                _crosshairValueText.setX(yVal);
                annotChanged = true;
            }
            if (_crosshairValueText.getY() != xVal) {
                _crosshairValueText.setY(xVal);
                annotChanged = true;
            }

            // and write the text
            final String numA = MWC.Utilities.TextFormatting.GeneralFormat
                    .formatOneDecimalPlace(_thePlot.getRangeCrosshairValue());
            final Date newDate = new Date((long) _thePlot.getDomainCrosshairValue());
            final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss");
            _df.setTimeZone(TimeZone.getTimeZone("GMT"));
            final String dateVal = _df.format(newDate);
            final String theMessage = " [" + dateVal + "," + numA + "]";
            if (!theMessage.equals(_crosshairValueText.getText())) {
                _crosshairValueText.setText(theMessage);
                annotChanged = true;
            }

            if (annotChanged) {
                _plotControl.getChart().setNotify(true);
            }
        }
    });

    // ////////////////////////////////////////////////////
    // put the time series into the plot
    // ////////////////////////////////////////////////////
    _thePlot.setDataset((XYDataset) dataset);
}

From source file:org.tolven.web.MenuAction.java

/**
  * Creates a dataset from menuData.//  w ww.  j a  v  a  2  s . co  m
  *
  * @return An XY dataset
  */
public XYDataset createDataset3(String path) {
    // Adjust the path to make this work
    MenuStructure msLab = getMenuLocal().findMenuStructure(getAccountId(), path);
    if (msLab == null)
        throw new IllegalArgumentException("Path not valid for this account");
    // Create a new path based on the matching id(s) from the called path
    // for example, if patient were specified in the input nodeValues and the new path has a patient node, then
    // it's pulled.
    MenuPath mdPath = new MenuPath(msLab.getPath(), getTargetMenuPath());
    //        TolvenLogger.info("dataset: Query from " + msLab.getPath() + " for requested path: " + getTargetMenuPath(), MenuAction.class);
    MenuQueryControl ctrl = new MenuQueryControl();
    ctrl.setLimit(5000); // TODO: This is a hard coded hard query limit that should be in a property or something
    ctrl.setMenuStructure(msLab);
    ctrl.setAccountUser(TolvenRequest.getInstance().getAccountUser());
    ctrl.setNow(getNow());
    ctrl.setOffset(0);
    ctrl.setOriginalTargetPath(mdPath);
    ctrl.setRequestedPath(mdPath);
    List<MenuData> menuData = getMenuLocal().findMenuData(ctrl);
    TimeSeries s1 = new TimeSeries("Peak Flow", TolvenHour.class);
    for (MenuData md : menuData) {
        TimeSeries sx;
        //            TolvenLogger.info("MD Item: " + md.getId(), MenuAction.class);
        String result = md.getString01().toLowerCase();
        if ("peak flow".equals(result) || "peakflow".equals(result)) {
            sx = s1;
        } else
            continue;
        Hour d = new TolvenHour(md.getDate01());
        //           TolvenLogger.info( "Graph Data: " + m.getMonth() + "/" + m.getYear() + "=" + md.getPqValue01(), MenuAction.class);
        TimeSeriesDataItem di = sx.getDataItem(d);
        if (di != null)
            TolvenLogger.info(
                    "Date: " + di.getPeriod() + " replacing " + di.getValue() + " with " + md.getPqValue01(),
                    MenuAction.class);
        sx.addOrUpdate(d, md.getPqValue01());
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    //        dataset.setDomainIsPointsInTime(true);
    TolvenLogger.info("Done preparing Dataset", MenuAction.class);

    return dataset;

}

From source file:org.tolven.web.MenuAction.java

/**
  * Creates a dataset from menuData.//from w  ww  .jav  a2 s.co m
  *
  * @return An XY dataset
  */
public XYDataset createDataset2(String path) {
    // Adjust the path to make this work
    MenuStructure msLab = getMenuLocal().findMenuStructure(getAccountId(), path);
    if (msLab == null)
        throw new IllegalArgumentException("Path not valid for this account");
    // Create a new path based on the matching id(s) from the called path
    // for example, if patient were specified in the input nodeValues and the new path has a patient node, then
    // it's pulled.
    MenuPath mdPath = new MenuPath(msLab.getPath(), getTargetMenuPath());
    //        TolvenLogger.info("dataset: Query from " + msLab.getPath() + " for requested path: " + getTargetMenuPath(), MenuAction.class);
    MenuQueryControl ctrl = new MenuQueryControl();
    ctrl.setLimit(5000); // TODO: This is a hard coded hard query limit that should be in a property or something
    ctrl.setMenuStructure(msLab);
    ctrl.setAccountUser(TolvenRequest.getInstance().getAccountUser());
    ctrl.setNow(getNow());
    ctrl.setOffset(0);
    ctrl.setOriginalTargetPath(mdPath);
    ctrl.setRequestedPath(mdPath);
    List<MenuData> menuData = getMenuLocal().findMenuData(ctrl);
    TimeSeries s1 = new TimeSeries("glucose (mg/dL)", TolvenHour.class);
    TimeSeries s2 = new TimeSeries("Weight (lb)", TolvenHour.class);
    for (MenuData md : menuData) {
        TimeSeries sx;
        //            TolvenLogger.info("MD Item: " + md.getId(), MenuAction.class);
        String result = md.getString01();
        if ("Blood Glucose".equals(result)) {
            sx = s1;
        } else if ("Weight".equals(result)) {
            sx = s2;
        } else
            continue;
        Hour d = new TolvenHour(md.getDate01());
        //           TolvenLogger.info( "Graph Data: " + m.getMonth() + "/" + m.getYear() + "=" + md.getPqValue01(), MenuAction.class);
        TimeSeriesDataItem di = sx.getDataItem(d);
        if (di != null)
            TolvenLogger.info(
                    "Date: " + di.getPeriod() + " replacing " + di.getValue() + " with " + md.getPqValue01(),
                    MenuAction.class);
        sx.addOrUpdate(d, md.getPqValue01());
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    dataset.addSeries(s2);
    //        dataset.setDomainIsPointsInTime(true);
    TolvenLogger.info("Done preparing Dataset", MenuAction.class);

    return dataset;

}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Transform a Domain Slider value to an index into the List of specified data items,
 * taking account that the List may not fully occupy the Domain.
 *
 * Series_position   Left   Right/*from   www.j  a  va2s  . co m*/
 *        |
 *        |  xxx     start   -1
 *        |
 *        |xxx       start   start
 *        |
 *       xxx         index   index
 *        |
 *     xxx|          end     end
 *        |
 *   xxx  |          -1      end
 *        |
 *
 * @param domainslidermin
 * @param domainslidermax
 * @param domainslidervalue
 * @param domainsliderindex
 * @param domainlowerbound
 * @param domainupperbound
 * @param datasettype
 * @param calendar
 * @param series
 * @param debug
 *
 * @return int
 */

public static int transformDomainSliderValueToSeriesIndex(final int domainslidermin, final int domainslidermax,
        final int domainslidervalue, final int domainsliderindex, final double domainlowerbound,
        final double domainupperbound, final DatasetType datasettype, final Calendar calendar,
        final Series series, final boolean debug) {
    final String SOURCE = "ChartHelper.transformDomainSliderValueToSeriesIndex() ";
    final int intIndex;

    switch (datasettype) {
    case XY: {
        final XYSeries xySeries;
        final XYDataItem dataItemFirst;
        final XYDataItem dataItemLast;
        final double dblItemFirstX;
        final double dblItemLastX;
        final double dblItemLastFirstX;
        final double dblDomainSliderX;

        xySeries = (XYSeries) series;
        dataItemFirst = xySeries.getDataItem(0);
        dataItemLast = xySeries.getDataItem(xySeries.getItemCount() - 1);

        dblItemFirstX = dataItemFirst.getXValue();
        dblItemLastX = dataItemLast.getXValue();

        // Diagnostic only
        dblItemLastFirstX = dblItemLastX - dblItemFirstX;

        dblDomainSliderX = calculateDomainSliderX(domainslidermin, domainslidermax, domainslidervalue,
                domainlowerbound, domainupperbound);

        LOGGER.debug(debug,
                SOURCE + "\n[domain.slider.min=" + domainslidermin + "]\n[domain.slider.max=" + domainslidermax
                        + "]\n[domain.slider.value=" + domainslidervalue + "]\n[domain.slider.index="
                        + domainsliderindex + "]\n[domain.lowerbound=" + domainlowerbound
                        + "]\n[domain.upperbound=" + domainupperbound + "]\n[domain.slider.x="
                        + dblDomainSliderX + "]\n[lastfirstitem.x=" + dblItemLastFirstX + "]\n[firstitem.x="
                        + dblItemFirstX + "]\n[lastitem.x=" + dblItemLastX + "]\n[dataset.type="
                        + datasettype.getName() + "]\n[series.itemcount=" + series.getItemCount() + "]");

        if (domainsliderindex == INDEX_LEFT) {
            if (dblDomainSliderX <= dblItemFirstX) {
                intIndex = 0;
                //System.out.println("LEFT <=");
            } else if (dblDomainSliderX == dblItemLastX) {
                intIndex = xySeries.getItemCount() - 1;
                //System.out.println("LEFT ==");
            } else if (dblDomainSliderX > dblItemLastX) {
                intIndex = -1;
                //System.out.println("LEFT >");
            } else {
                intIndex = findXYDataItemIndexForX(dblDomainSliderX, xySeries);
                //System.out.println("LEFT index");
            }
        } else if (domainsliderindex == INDEX_RIGHT) {
            if (dblDomainSliderX < dblItemFirstX) {
                intIndex = -1;
                //System.out.println("RIGHT <");
            } else if (dblDomainSliderX == dblItemFirstX) {
                intIndex = 0;
                //System.out.println("RIGHT ==");
            } else if (dblDomainSliderX >= dblItemLastX) {
                intIndex = xySeries.getItemCount() - 1;
                //System.out.println("RIGHT >=");
            } else {
                intIndex = findXYDataItemIndexForX(dblDomainSliderX, xySeries);
                //System.out.println("RIGHT index");
            }
        } else {
            // Do nothing, an Error
            LOGGER.error(SOURCE + "Invalid Domain Slider [index=" + domainsliderindex + "]");
            intIndex = -1;
        }

        break;
    }

    case TIMESTAMPED: {
        final TimeSeries timeSeries;
        final TimeSeriesDataItem dataItemFirst;
        final TimeSeriesDataItem dataItemLast;
        final double dblItemFirstMillis;
        final double dblItemLastMillis;
        final double dblItemLastFirstMillis;
        final double dblDomainSliderMillis;

        timeSeries = (TimeSeries) series;
        dataItemFirst = timeSeries.getDataItem(0);
        dataItemLast = timeSeries.getDataItem(timeSeries.getItemCount() - 1);

        dblItemFirstMillis = dataItemFirst.getPeriod().getFirstMillisecond(calendar);
        dblItemLastMillis = dataItemLast.getPeriod().getLastMillisecond(calendar);

        // Diagnostic only
        dblItemLastFirstMillis = dblItemLastMillis - dblItemFirstMillis;

        dblDomainSliderMillis = calculateDomainSliderMillis(domainslidermin, domainslidermax, domainslidervalue,
                domainlowerbound, domainupperbound, calendar, debug);
        LOGGER.debug(debug,
                SOURCE + "]\n\n[domain.slider.index=" + domainsliderindex + "]\n[domain.slider.value="
                        + domainslidervalue + "]\n[domain.slider.millis=" + (long) dblDomainSliderMillis

                        + "]\n\n[firstitem.millis.calendar=" + (long) dblItemFirstMillis
                        + "]\n[firstitem.millis.period=" + dataItemFirst.getPeriod().getFirstMillisecond()
                        + "]\n[lastitem.millis.calendar=" + (long) dblItemLastMillis
                        + "]\n[lastitem.millis.period=" + dataItemLast.getPeriod().getLastMillisecond()
                        + "]\n[lastfirstitem.millis=" + (long) dblItemLastFirstMillis

                        + "]\n\n[dataset.type=" + datasettype.getName() + "]\n[series.itemcount="
                        + series.getItemCount() + "]");

        if (domainsliderindex == INDEX_LEFT) {
            if (dblDomainSliderMillis <= dblItemFirstMillis) {
                intIndex = 0;
                LOGGER.debug(debug, SOURCE + "LEFT(slider) <= FIRST(calendar)");
            } else if (dblDomainSliderMillis == dblItemLastMillis) {
                intIndex = timeSeries.getItemCount() - 1;
                LOGGER.debug(debug, SOURCE + "LEFT(slider) == LAST(calendar)");
            } else if (dblDomainSliderMillis > dblItemLastMillis) {
                intIndex = -1;
                LOGGER.debug(debug, SOURCE + "LEFT(slider) > LAST(calendar)");
            } else {
                intIndex = findTimeSeriesIndexForMillis(dblDomainSliderMillis, timeSeries, calendar);
                LOGGER.debug(debug, SOURCE + "LEFT ok");
            }
        } else if (domainsliderindex == INDEX_RIGHT) {
            if (dblDomainSliderMillis < dblItemFirstMillis) {
                intIndex = -1;
                LOGGER.debug(debug, SOURCE + "RIGHT(slider) < FIRST(calendar)");
            } else if (dblDomainSliderMillis == dblItemFirstMillis) {
                intIndex = 0;
                LOGGER.debug(debug, SOURCE + "RIGHT(slider) == FIRST(calendar)");
            } else if (dblDomainSliderMillis >= dblItemLastMillis) {
                intIndex = timeSeries.getItemCount() - 1;
                LOGGER.debug(debug, SOURCE + "RIGHT(slider) >= LAST(calendar)");
            } else {
                intIndex = findTimeSeriesIndexForMillis(dblDomainSliderMillis, timeSeries, calendar);
                LOGGER.debug(debug, SOURCE + "RIGHT(slider) ok");
            }
        } else {
            // Do nothing, an Error
            LOGGER.error(SOURCE + "Invalid Domain Slider [domainslider.index=" + domainsliderindex + "]");
            intIndex = -1;
        }

        break;
    }

    default: {
        // Do nothing, an Error
        LOGGER.error(SOURCE + "Invalid DatasetType [type=" + datasettype.getName() + "]");
        intIndex = -1;
    }
    }

    LOGGER.debug(debug,
            SOURCE + "[series.item.index=" + intIndex + "] [series.item.count=" + series.getItemCount() + "]");
    LOGGER.debug(debug, Logger.CONSOLE_SEPARATOR_MINOR);

    return (intIndex);
}

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

private Point2D.Double getPoint(int plotIndex, int seriesIndex, int dataIndex) {
    final TimeSeries timeSeries = this.getTimeSeries(plotIndex, seriesIndex);
    if (timeSeries == null) {
        // Possible this is candlestick?
        final XYPlot plot = this.chartJDialog.getPlot(plotIndex);
        if (plot.getDataset(seriesIndex) instanceof org.jfree.data.xy.DefaultHighLowDataset) {
            return this._getPointForCandlestick(plotIndex, seriesIndex, dataIndex);
        }/* w  ww. j  a  v a 2 s.c o  m*/
        return null;
    }

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

    final ChartPanel chartPanel = this.chartJDialog.getChartPanel();
    final XYPlot plot = this.chartJDialog.getPlot(plotIndex);
    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().getSubplotInfo(plotIndex)
            .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:org.yccheok.jstock.gui.charting.ChartLayerUI.java

private boolean updateMainTraceInfo(Point2D point) {
    if (point == null) {
        return false;
    }/* w w w  . j  a v a 2s  . c  om*/

    final ChartPanel chartPanel = this.chartJDialog.getChartPanel();
    // Top most plot.
    final XYPlot plot = this.chartJDialog.getPlot();

    if (plot.getDataset() instanceof org.jfree.data.xy.DefaultHighLowDataset) {
        return this._updateMainTraceInfoForCandlestick(point);
    }

    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset();
    // 0 are the main chart. 1, 2, 3... are TA.
    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)point);

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

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    // Don't use it. It will cause us to lose precision.
    //final double coordinateX = domainAxis.java2DToValue(p2.getX(), _plotArea,
    //        domainAxisEdge);
    final double coordinateX = domainAxis.java2DToValue(point.getX(), _plotArea, domainAxisEdge);
    //double coordinateY = rangeAxis.java2DToValue(mousePoint2.getY(), plotArea,
    //        rangeAxisEdge);

    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;
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    this.mainDrawArea.setRect(_plotArea);

    if (this.mainDrawArea.contains(tmpPoint)) {
        // 0 indicates main plot.
        this.mainTraceInfo = TraceInfo.newInstance(tmpPoint, 0, 0, tmpIndex);
        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 www  .  ja  v  a  2s  . c om*/

    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;
}