List of usage examples for org.jfree.data.time TimeSeriesDataItem getPeriod
public RegularTimePeriod getPeriod()
From source file:org.jfree.data.time.MovingAverage.java
/** * Creates a new {@link TimeSeries} containing moving average values for * the given series, calculated by number of points (irrespective of the * 'age' of those points). If the series is empty (contains zero items), * the result is an empty series.//www . j av a 2 s . c o m * <p> * Developed by Benoit Xhenseval (www.ObjectLab.co.uk). * * @param source the source series. * @param name the name of the new series. * @param pointCount the number of POINTS used in the average calculation * (not periods!) * * @return The moving average series. */ public static TimeSeries createPointMovingAverage(TimeSeries source, String name, int pointCount) { ParamChecks.nullNotPermitted(source, "source"); if (pointCount < 2) { throw new IllegalArgumentException("periodCount must be greater " + "than or equal to 2."); } TimeSeries result = new TimeSeries(name); double rollingSumForPeriod = 0.0; for (int i = 0; i < source.getItemCount(); i++) { // get the current data item... TimeSeriesDataItem current = source.getRawDataItem(i); RegularTimePeriod period = current.getPeriod(); // FIXME: what if value is null on next line? rollingSumForPeriod += current.getValue().doubleValue(); if (i > pointCount - 1) { // remove the point i-periodCount out of the rolling sum. TimeSeriesDataItem startOfMovingAvg = source.getRawDataItem(i - pointCount); rollingSumForPeriod -= startOfMovingAvg.getValue().doubleValue(); result.add(period, rollingSumForPeriod / pointCount); } else if (i == pointCount - 1) { result.add(period, rollingSumForPeriod / pointCount); } } return result; }
From source file:org.jfree.data.time.MovingAverage.java
/** * Creates a new {@link TimeSeries} containing moving average values for * the given series. If the series is empty (contains zero items), the * result is an empty series.//from ww w. j a v a2 s. c om * * @param source the source series. * @param name the name of the new series. * @param periodCount the number of periods used in the average * calculation. * @param skip the number of initial periods to skip. * * @return The moving average series. */ public static TimeSeries createMovingAverage(TimeSeries source, String name, int periodCount, int skip) { ParamChecks.nullNotPermitted(source, "source"); if (periodCount < 1) { throw new IllegalArgumentException("periodCount must be greater " + "than or equal to 1."); } TimeSeries result = new TimeSeries(name); if (source.getItemCount() > 0) { // if the initial averaging period is to be excluded, then // calculate the index of the // first data item to have an average calculated... long firstSerial = source.getTimePeriod(0).getSerialIndex() + skip; for (int i = source.getItemCount() - 1; i >= 0; i--) { // get the current data item... RegularTimePeriod period = source.getTimePeriod(i); long serial = period.getSerialIndex(); if (serial >= firstSerial) { // work out the average for the earlier values... int n = 0; double sum = 0.0; long serialLimit = period.getSerialIndex() - periodCount; int offset = 0; boolean finished = false; while ((offset < periodCount) && (!finished)) { if ((i - offset) >= 0) { TimeSeriesDataItem item = source.getRawDataItem(i - offset); RegularTimePeriod p = item.getPeriod(); Number v = item.getValue(); long currentIndex = p.getSerialIndex(); if (currentIndex > serialLimit) { if (v != null) { sum = sum + v.doubleValue(); n = n + 1; } } else { finished = true; } } offset = offset + 1; } if (n > 0) { result.add(period, sum / n); } else { result.add(period, null); } } } } return result; }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
public static int scaleRange(TimeSeriesCollection mtds, Double miny, Double maxy) { int exp = PluginSupport.getExp(miny, maxy); double scale = Math.pow(10, exp); for (Iterator it = mtds.getSeries().iterator(); it.hasNext();) { TimeSeries ds = (TimeSeries) it.next(); for (int item = 0; item < ds.getItemCount(); item++) { TimeSeriesDataItem dataItem = ds.getDataItem(item); RegularTimePeriod period = dataItem.getPeriod(); double y = dataItem.getValue().doubleValue(); y *= scale;// w w w. j ava 2s . c o m ds.update(period, y); } } return exp; }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
public static void getRangeLimits(TimeSeriesCollection mtds, Double rng[]) { Double minx, miny, maxx, maxy; minx = miny = Double.MAX_VALUE; maxx = maxy = -Double.MAX_VALUE; for (Iterator it = mtds.getSeries().iterator(); it.hasNext();) { TimeSeries ds = (TimeSeries) it.next(); for (int item = 1; item < ds.getItemCount() - 1; item++) { TimeSeriesDataItem dataItem = ds.getDataItem(item); RegularTimePeriod period = dataItem.getPeriod(); double y = dataItem.getValue().doubleValue(); double x = period.getFirstMillisecond(); minx = Math.min(minx, x); miny = Math.min(miny, y); maxx = Math.max(maxx, x); maxy = Math.max(maxy, y); }/* www. j a v a 2s . c om*/ } rng[0] = minx; rng[1] = miny; rng[2] = maxx; rng[3] = maxy; }
From source file:de.xirp.chart.ChartUtil.java
/** * Exports the given dataset as CSV./*from w ww .j a va 2s . c o m*/ * * @param dataset * The dataset to export. * @param robotName * The robot name for which the dataset is exported. * @see org.jfree.data.time.TimeSeriesCollection */ private static void exportCSV(TimeSeriesCollection dataset, String robotName) { for (Object obj : dataset.getSeries()) { List<Observed> obs = new ArrayList<Observed>(); TimeSeries ts = (TimeSeries) obj; String observedKey = (String) ts.getKey(); for (Object obj2 : ts.getItems()) { TimeSeriesDataItem tsdi = (TimeSeriesDataItem) obj2; Observed o = new Observed(); o.setObservedKey(observedKey); o.setTimestamp(tsdi.getPeriod().getStart().getTime()); o.setValue(tsdi.getValue().doubleValue()); obs.add(o); } exportCSV(obs, robotName); } }
From source file:org.jstockchart.time.SegmentedTimeSeries.java
/** * Adds a <code>TimeSeriesDataItem</code> instance to the series. * /* w w w . java 2 s . c o m*/ * @param item * the <code>TimeSeriesDataItem</code> instance. */ public void addItem(TimeSeriesDataItem item) { if (lastItem != null) { long lastStart = lastItem.getPeriod().getFirstMillisecond(); long thisStart = item.getPeriod().getFirstMillisecond(); long thisEnd = item.getPeriod().getLastMillisecond(); int diff = 0; if (step > 0) { diff = (int) ((thisStart - lastStart) / (thisEnd - thisStart) - 1) / step; } RegularTimePeriod bufPeriod = lastItem.getPeriod().next(); Number bufValue = lastItem.getValue(); for (int i = 0; i < diff; i++) { TimeSeriesDataItem bufItem = new TimeSeriesDataItem(bufPeriod, bufValue); if (timeline != null) { if (timeline.containsDomainValue(bufPeriod.getLastMillisecond())) { timeseries.addOrUpdate(bufItem); size++; } } else { timeseries.add(bufItem); size++; } bufPeriod = bufItem.getPeriod().next(); } } timeseries.addOrUpdate(item); //timeseries.add(item); size++; lastItem = item; }
From source file:org.jfree.data.time.TimeSeriesDataItem.java
/** * Returns an integer indicating the order of this data pair object * relative to another object.//from www .ja v a 2 s.co m * <P> * For the order we consider only the timing: * negative == before, zero == same, positive == after. * * @param o1 The object being compared to. * * @return An integer indicating the order of the data item object * relative to another object. */ @Override public int compareTo(Object o1) { int result; // CASE 1 : Comparing to another TimeSeriesDataItem object // ------------------------------------------------------- if (o1 instanceof TimeSeriesDataItem) { TimeSeriesDataItem datapair = (TimeSeriesDataItem) o1; result = getPeriod().compareTo(datapair.getPeriod()); } // CASE 2 : Comparing to a general object // --------------------------------------------- else { // consider time periods to be ordered after general objects result = 1; } return result; }
From source file:net.sourceforge.subsonic.controller.StatusChartController.java
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); int index = Integer.parseInt(request.getParameter("index")); List<TransferStatus> statuses = Collections.emptyList(); if ("stream".equals(type)) { statuses = statusService.getAllStreamStatuses(); } else if ("download".equals(type)) { statuses = statusService.getAllDownloadStatuses(); } else if ("upload".equals(type)) { statuses = statusService.getAllUploadStatuses(); }/*from ww w. j av a 2s . c o m*/ if (index < 0 || index >= statuses.size()) { return null; } TransferStatus status = statuses.get(index); TimeSeries series = new TimeSeries("Kbps", Millisecond.class); TransferStatus.SampleHistory history = status.getHistory(); long to = System.currentTimeMillis(); long from = to - status.getHistoryLengthMillis(); Range range = new DateRange(from, to); if (!history.isEmpty()) { TransferStatus.Sample previous = history.get(0); for (int i = 1; i < history.size(); i++) { TransferStatus.Sample sample = history.get(i); long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp(); long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered()); double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0); series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps); previous = sample; } } // Compute moving average. series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000); // Find min and max values. double min = 100; double max = 250; for (Object obj : series.getItems()) { TimeSeriesDataItem item = (TimeSeriesDataItem) obj; double value = item.getValue().doubleValue(); if (item.getPeriod().getFirstMillisecond() > from) { min = Math.min(min, value); max = Math.max(max, value); } } // Add 10% to max value. max *= 1.1D; // Subtract 10% from min value. min *= 0.9D; TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white); plot.setBackgroundPaint(background); XYItemRenderer renderer = plot.getRendererForDataset(dataset); renderer.setSeriesPaint(0, Color.blue.darker()); renderer.setSeriesStroke(0, new BasicStroke(2f)); // Set theme-specific colors. Color bgColor = getBackground(request); Color fgColor = getForeground(request); chart.setBackgroundPaint(bgColor); ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setRange(range); domainAxis.setTickLabelPaint(fgColor); domainAxis.setTickMarkPaint(fgColor); domainAxis.setAxisLinePaint(fgColor); ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setRange(new Range(min, max)); rangeAxis.setTickLabelPaint(fgColor); rangeAxis.setTickMarkPaint(fgColor); rangeAxis.setAxisLinePaint(fgColor); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT); return null; }
From source file:org.madsonic.controller.StatusChartController.java
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); int index = Integer.parseInt(request.getParameter("index")); List<TransferStatus> statuses = Collections.emptyList(); if ("stream".equals(type)) { statuses = statusService.getAllStreamStatuses(); } else if ("download".equals(type)) { statuses = statusService.getAllDownloadStatuses(); } else if ("upload".equals(type)) { statuses = statusService.getAllUploadStatuses(); }/*from w ww . j av a2 s. c o m*/ if (index < 0 || index >= statuses.size()) { return null; } TransferStatus status = statuses.get(index); TimeSeries series = new TimeSeries("Kbps", Millisecond.class); TransferStatus.SampleHistory history = status.getHistory(); long to = System.currentTimeMillis(); long from = to - status.getHistoryLengthMillis(); Range range = new DateRange(from, to); if (!history.isEmpty()) { TransferStatus.Sample previous = history.get(0); for (int i = 1; i < history.size(); i++) { TransferStatus.Sample sample = history.get(i); long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp(); long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered()); double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0); series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps); previous = sample; } } // Compute moving average. series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000); // Find min and max values. double min = 100; double max = 250; for (Object obj : series.getItems()) { TimeSeriesDataItem item = (TimeSeriesDataItem) obj; double value = item.getValue().doubleValue(); if (item.getPeriod().getFirstMillisecond() > from) { min = Math.min(min, value); max = Math.max(max, value); } } // Add 10% to max value. max *= 1.1D; // Subtract 10% from min value. min *= 0.9D; TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white); plot.setBackgroundPaint(background); XYItemRenderer renderer = plot.getRendererForDataset(dataset); renderer.setSeriesPaint(0, Color.gray.darker()); renderer.setSeriesStroke(0, new BasicStroke(2f)); // Set theme-specific colors. Color bgColor = getBackground(request); Color fgColor = getForeground(request); chart.setBackgroundPaint(bgColor); ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setRange(range); domainAxis.setTickLabelPaint(fgColor); domainAxis.setTickMarkPaint(fgColor); domainAxis.setAxisLinePaint(fgColor); ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setRange(new Range(min, max)); rangeAxis.setTickLabelPaint(fgColor); rangeAxis.setTickMarkPaint(fgColor); rangeAxis.setAxisLinePaint(fgColor); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT); return null; }
From source file:org.adempiere.webui.editor.WChartEditor.java
private void render(JFreeChart chart) { ChartRenderingInfo info = new ChartRenderingInfo(); int width = 400; int height = chartModel.getWinHeight(); BufferedImage bi = chart.createBufferedImage(width, height, BufferedImage.TRANSLUCENT, info); try {// w w w . j a v a 2 s .c o m byte[] bytes = EncoderUtil.encode(bi, ImageFormat.PNG, true); AImage image = new AImage("", bytes); Imagemap myImage = new Imagemap(); Panel panel = getComponent(); myImage.setContent(image); if (panel.getPanelchildren() != null) { panel.getPanelchildren().getChildren().clear(); panel.getPanelchildren().appendChild(myImage); } else { Panelchildren pc = new Panelchildren(); panel.appendChild(pc); pc.appendChild(myImage); } int count = 0; for (Iterator<?> it = info.getEntityCollection().getEntities().iterator(); it.hasNext();) { ChartEntity entity = (ChartEntity) it.next(); String key = null; String seriesName = null; if (entity instanceof CategoryItemEntity) { CategoryItemEntity item = ((CategoryItemEntity) entity); Comparable<?> colKey = item.getColumnKey(); Comparable<?> rowKey = item.getRowKey(); if (colKey != null && rowKey != null) { key = colKey.toString(); seriesName = rowKey.toString(); } } else if (entity instanceof PieSectionEntity) { Comparable<?> sectionKey = ((PieSectionEntity) entity).getSectionKey(); if (sectionKey != null) { key = sectionKey.toString(); } } if (entity instanceof XYItemEntity) { XYItemEntity item = ((XYItemEntity) entity); if (item.getDataset() instanceof TimeSeriesCollection) { TimeSeriesCollection data = (TimeSeriesCollection) item.getDataset(); TimeSeries series = data.getSeries(item.getSeriesIndex()); TimeSeriesDataItem dataitem = series.getDataItem(item.getItem()); seriesName = series.getKey().toString(); key = dataitem.getPeriod().toString(); } } if (key == null) continue; Area area = new Area(); myImage.appendChild(area); area.setCoords(entity.getShapeCoords()); area.setShape(entity.getShapeType()); area.setTooltiptext(entity.getToolTipText()); area.setId(count + "_WG__" + seriesName + "__" + key); count++; } myImage.addEventListener(Events.ON_CLICK, new EventListener() { public void onEvent(Event event) throws Exception { MouseEvent me = (MouseEvent) event; String areaId = me.getArea(); if (areaId != null) { String[] strs = areaId.split("__"); if (strs.length == 3) { chartMouseClicked(strs[2], strs[1]); } } } }); } catch (Exception e) { log.log(Level.SEVERE, "", e); } }