List of usage examples for org.jfree.data.time TimeSeries getItemCount
@Override public int getItemCount()
From source file:org.jfree.data.time.TimeSeries.java
/** * Tests the series for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean./* w ww. j a v a 2 s . c o m*/ */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TimeSeries)) { return false; } TimeSeries that = (TimeSeries) obj; if (!ObjectUtilities.equal(getDomainDescription(), that.getDomainDescription())) { return false; } if (!ObjectUtilities.equal(getRangeDescription(), that.getRangeDescription())) { return false; } if (!ObjectUtilities.equal(this.timePeriodClass, that.timePeriodClass)) { return false; } if (getMaximumItemAge() != that.getMaximumItemAge()) { return false; } if (getMaximumItemCount() != that.getMaximumItemCount()) { return false; } int count = getItemCount(); if (count != that.getItemCount()) { return false; } if (!ObjectUtilities.equal(this.data, that.data)) { return false; } return super.equals(obj); }
From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java
private boolean updateMainTraceInfo(Point2D point) { if (point == null) { return false; }/* w ww .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.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java
/*********************************************************************************************** * Preserve, Truncate or Decimate an XYDataset to try to achieve the requested display limit. * Decimation requested overrides all other modes. * Transform the dataset in accordance with the ChannelSelection Modes. * TRUNCATE is not currently used.// w w w . ja v a 2 s . co m * * ChartUpdate isdecimated Outcome * * PRESERVE N Always PRESERVE, don't use displaylimit * Y ditto * * DECIMATE N Do same as PRESERVE * Y Skip enough to leave displaylimit * * TRUNCATE N Use only displaylimit, ignore isdecimated * Y ditto * * * @param dataset * @param timezone * @param chartupdatetype * @param displaylimit * @param isdecimated * @param selectionmodes * * @return XYDataset */ private static XYDataset copyTransformedXYDataset(final XYDataset dataset, final TimeZone timezone, final DataUpdateType chartupdatetype, final int displaylimit, final boolean isdecimated, final List<ChannelSelectionMode> selectionmodes) { final String SOURCE = "ChartHelper.copyTransformedXYDataset() "; final DataUpdateType updateTypeToTransform; final XYDataset xyResult; // If decimation is NOT requested by the user for a DECIMATE chart then just do PRESERVE // Otherwise do exactly as the Chart configuration requests if ((DataUpdateType.DECIMATE.equals(chartupdatetype)) && (!isdecimated)) { updateTypeToTransform = DataUpdateType.PRESERVE; } else { updateTypeToTransform = chartupdatetype; } // System.out.println(SOURCE + "displaylimit=" + displaylimit // + " isdecimated=" + isdecimated // + " chartupdatetype=" + chartupdatetype.getName() // + " updateTypeToTransform=" + updateTypeToTransform.getName()); //----------------------------------------------------------------------------------------- // Use the whole dataset immediately if requested if (DataUpdateType.PRESERVE.equals(updateTypeToTransform)) { //System.out.println(SOURCE + "Preserve whole dataset"); xyResult = dataset; return (xyResult); } //----------------------------------------------------------------------------------------- // Now do the transformation: TRUNCATE or DECIMATE if (dataset instanceof TimeSeriesCollection) { xyResult = new TimeSeriesCollection(timezone); // Process each Series in turn for (int intSeriesIndex = 0; intSeriesIndex < dataset.getSeriesCount(); intSeriesIndex++) { final TimeSeries timeSeriesInput; final TimeSeries timeSeriesOutput; timeSeriesInput = ((TimeSeriesCollection) dataset).getSeries(intSeriesIndex); // Make a TimeSeries based on Seconds... // whose name is the ChannelName timeSeriesOutput = new TimeSeries(timeSeriesInput.getKey(), timeSeriesInput.getTimePeriodClass()); switch (updateTypeToTransform) { case TRUNCATE: { final int intStart; //System.out.println("truncate time series"); if (timeSeriesInput.getItemCount() > displaylimit) { intStart = timeSeriesInput.getItemCount() - displaylimit; } else { intStart = 0; } // Modify each Series in exactly the same way! // timeSeriesOutput = timeSeriesInput.createCopy(intStart, timeSeriesInput.getItemCount()-1); for (int item = intStart; item < timeSeriesInput.getItemCount(); item++) { timeSeriesOutput.add(timeSeriesInput.getDataItem(item)); } break; } case DECIMATE: { final int intSkipCount; //System.out.println("decimate time series index=" + intSeriesIndex); if (timeSeriesInput.getItemCount() > displaylimit) { intSkipCount = (timeSeriesInput.getItemCount() / displaylimit) - 1; } else { // Show all of the data items, i.e. insufficient data to decimate intSkipCount = 0; } for (int item = 0; item < timeSeriesInput.getItemCount(); item = item + intSkipCount + 1) { timeSeriesOutput.add(timeSeriesInput.getDataItem(item)); } break; } default: { LOGGER.error(SOURCE + MSG_UNSUPPORTED_UPDATE_TYPE); } } // Accumulate each Series in the output ((TimeSeriesCollection) xyResult).addSeries(timeSeriesOutput); } } else if (dataset instanceof XYSeriesCollection) { xyResult = new XYSeriesCollection(); //System.out.println(SOURCE + "XYSeriesCollection for " + displaylimit + " samples"); // Process each Series in turn for (int intSeriesIndex = 0; intSeriesIndex < dataset.getSeriesCount(); intSeriesIndex++) { final XYSeries xySeriesInput; final XYSeries xySeriesOutput; xySeriesInput = ((XYSeriesCollection) dataset).getSeries(intSeriesIndex); xySeriesOutput = new XYSeries(dataset.getSeriesKey(intSeriesIndex)); switch (updateTypeToTransform) { case TRUNCATE: { final int intStart; //System.out.println("truncate xy"); if (xySeriesInput.getItemCount() > displaylimit) { intStart = xySeriesInput.getItemCount() - displaylimit; } else { intStart = 0; } // Modify each Series in exactly the same way! // xySeriesOutput = xySeriesInput.createCopy(intStart, xySeriesInput.getItemCount()-1); for (int item = intStart; item < xySeriesInput.getItemCount(); item++) { xySeriesOutput.add(xySeriesInput.getDataItem(item)); } break; } case DECIMATE: { final int intSkipCount; //System.out.println("decimate xy series index=" + intSeriesIndex); if (xySeriesInput.getItemCount() > displaylimit) { intSkipCount = (xySeriesInput.getItemCount() / displaylimit) - 1; } else { // Show all of the data items, i.e. insufficient data to decimate intSkipCount = 0; } for (int item = 0; item < xySeriesInput.getItemCount(); item = item + intSkipCount + 1) { xySeriesOutput.add(xySeriesInput.getDataItem(item)); } break; } default: { LOGGER.error(SOURCE + MSG_UNSUPPORTED_UPDATE_TYPE); } } // Accumulate each Series in the output ((XYSeriesCollection) xyResult).addSeries(xySeriesOutput); } } else { LOGGER.error(SOURCE + "Unsupported XYDataset type"); xyResult = new XYSeriesCollection(); } return (xyResult); }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private boolean updateROIPoint(Point2D _ROIPoint) { if (_ROIPoint == null) { return false; }/*from www. java2s . 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; }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private boolean updateInvestPoint(Point2D _investPoint) { if (_investPoint == null) { return false; }// w ww. java2 s . com 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:com.zimbra.perf.chart.ChartUtil.java
private List<JFreeChart> createJFReeChart(ChartSettings cs) { double minValue = Double.MAX_VALUE; double maxValue = Double.MIN_VALUE; double d = 0; double count = 0; double total = 0; TimeSeriesCollection data = new TimeSeriesCollection(); ArrayList<ChartSettings> syntheticSettings = new ArrayList<ChartSettings>(); for (GroupPlotSettings gps : cs.getGroupPlots()) { String groupBy = gps.getGroupBy(); DataColumn dc = new DataColumn(gps.getInfile(), groupBy); StringSeries groupBySeries = mStringSeries.get(dc); dc = new DataColumn(gps.getInfile(), gps.getDataColumn()); DataSeries ds = mDataSeries.get(dc); int idx = 0; Map<String, List<Integer>> groups = new HashMap<String, List<Integer>>(); for (StringEntry e : groupBySeries.dataCollection) { String g = e.getVal(); List<Integer> indices = groups.get(g); if (indices == null) { indices = new ArrayList<Integer>(); groups.put(g, indices);//from www . j av a2 s.co m } indices.add(idx); idx++; } for (Map.Entry<String, List<Integer>> g : groups.entrySet()) { String groupByValue = g.getKey(); if (gps.getIgnoreSet().contains(groupByValue)) continue; List<Integer> indices = g.getValue(); DataSeries syntheticDS = new DataSeries(); DataColumn c = new DataColumn(gps.getInfile(), GROUP_PLOT_SYNTHETIC + groupByValue + ":" + gps.getDataColumn()); for (int i : indices) { Entry e = ds.get(i); syntheticDS.AddEntry(e.getTimestamp(), e.getVal()); } mDataSeries.put(c, syntheticDS); PlotSettings syntheticPlot = new PlotSettings(groupByValue, c.getInfile(), c.getColumn(), gps.getShowRaw(), gps.getShowMovingAvg(), gps.getMovingAvgPoints(), gps.getMultiplier(), gps.getDivisor(), gps.getNonNegative(), gps.getPercentTime(), gps.getDataFunction(), gps.getAggregateFunction(), gps.getOptional(), null, null); cs.addPlot(syntheticPlot); if (cs.getOutDocument() != null) { ChartSettings s = new ChartSettings(String.format(cs.getTitle(), groupByValue), cs.getCategory(), String.format(cs.getOutfile(), groupByValue), cs.getXAxis(), cs.getYAxis(), cs.getAllowLogScale(), cs.getPlotZero(), cs.getWidth(), cs.getHeight(), null, cs.getTopPlots(), cs.getTopPlotsType()); s.addPlot(syntheticPlot); syntheticSettings.add(s); } } } if (cs.getOutDocument() != null && cs.getGroupPlots().size() != 0) { ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>(); for (ChartSettings c : syntheticSettings) { charts.addAll(createJFReeChart(c)); c.setOutDocument(cs.getOutDocument()); } mSyntheticChartSettings.addAll(syntheticSettings); return charts; } List<PlotSettings> plots = cs.getPlots(); if (cs.getTopPlots() > 0 && plots.size() > cs.getTopPlots()) { String aggregateFunction = cs.getTopPlotsType().name().toLowerCase(); System.out.println(String.format("Reducing %d to %d plots for chart '%s'", plots.size(), cs.getTopPlots(), cs.getTitle())); ArrayList<PlotAggregatePair> aggregates = new ArrayList<PlotAggregatePair>(); for (PlotSettings ps : plots) { DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn()); String key = ps.getInfile() + ":" + ps.getDataColumn() + ":" + ps.getAggregateFunction(); PlotDataIterator pdIter = new PlotDataIterator(ps, mDataSeries.get(dc)); double aggregate = mAggregator.compute(pdIter, aggregateFunction, mAggregateStartAt, mAggregateEndAt, key); aggregates.add(new PlotAggregatePair(ps, aggregate)); } Collections.sort(aggregates); while (aggregates.size() > cs.getTopPlots()) { PlotAggregatePair pair = aggregates.remove(0); plots.remove(pair.ps); } } for (PlotSettings ps : plots) { String columnName = ps.getDataColumn(); if (columnName == null) { columnName = RATIO_PLOT_SYNTHETIC + ps.getRatioTop() + "/" + ps.getRatioBottom(); String infile = ps.getInfile(); String[] top = ps.getRatioTop().split("\\+"); String[] bottom = ps.getRatioBottom().split("\\+"); DataColumn[] ratioTop = new DataColumn[top.length]; DataColumn[] ratioBottom = new DataColumn[bottom.length]; for (int i = 0, j = top.length; i < j; i++) ratioTop[i] = new DataColumn(infile, top[i]); for (int i = 0, j = bottom.length; i < j; i++) ratioBottom[i] = new DataColumn(infile, bottom[i]); DataSeries[] topData = new DataSeries[ratioTop.length]; DataSeries[] bottomData = new DataSeries[ratioBottom.length]; for (int i = 0, j = ratioTop.length; i < j; i++) topData[i] = mDataSeries.get(ratioTop[i]); for (int i = 0, j = ratioBottom.length; i < j; i++) bottomData[i] = mDataSeries.get(ratioBottom[i]); DataSeries ds = new DataSeries(); for (int i = 0, j = topData[0].size(); i < j; i++) { double topValue = 0.0; double bottomValue = 0.0; double ratio = 0.0; Entry lastEntry = null; for (int m = 0, n = topData.length; m < n; m++) { Entry e = topData[m].get(i); topValue += e.getVal(); } for (int m = 0, n = bottomData.length; m < n; m++) { Entry e = bottomData[m].get(i); bottomValue += e.getVal(); lastEntry = e; } if (bottomValue != 0.0) { ratio = topValue / bottomValue; } // should never be null assert lastEntry != null; ds.AddEntry(lastEntry.getTimestamp(), ratio); } mDataSeries.put(new DataColumn(infile, columnName), ds); ps.setDataColumn(columnName); } DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn()); DataSeries ds = mDataSeries.get(dc); TimeSeries ts = new TimeSeries(ps.getLegend(), FixedMillisecond.class); int numSamples = 0; for (PlotDataIterator pdIter = new PlotDataIterator(ps, ds); pdIter.hasNext(); numSamples++) { Pair<Date, Double> entry = pdIter.next(); Date tstamp = entry.getFirst(); double val = entry.getSecond().doubleValue(); if (val != 0 || cs.getPlotZero()) { if (d < minValue) minValue = val; if (d > maxValue) maxValue = val; count++; total += val; try { ts.addOrUpdate(new FixedMillisecond(tstamp), val); } catch (SeriesException e) { e.printStackTrace(System.out); } } } if (numSamples == 0 && ps.getOptional()) { System.out.format("Skipping optional plot %s (no data sample found)\n\n", ps.getLegend()); continue; } System.out.format("Adding %d %s points to %s.\n\n", ds.size(), ps.getLegend(), cs.getOutfile()); if (ps.getShowRaw()) { data.addSeries(ts); } if (ps.getShowMovingAvg()) { int numPoints = ps.getMovingAvgPoints(); if (numPoints == PlotSettings.DEFAULT_PLOT_MOVING_AVG_POINTS) { // Display 200 points for moving average. // Divide the total number of points by 200 to // determine the number of samples to average // for each point. numPoints = ts.getItemCount() / 200; } if (numPoints >= 2) { TimeSeries ma = MovingAverage.createPointMovingAverage(ts, ps.getLegend() + " (moving avg)", numPoints); data.addSeries(ma); } else { System.out.println("Not enough data to display moving average for " + ps.getLegend()); data.addSeries(ts); } } } // Create chart boolean legend = (data.getSeriesCount() > 1); JFreeChart chart = ChartFactory.createTimeSeriesChart(null, cs.getXAxis(), cs.getYAxis(), data, legend, false, false); // Make Y-axis logarithmic if a spike was detected if (cs.getAllowLogScale() && (minValue > 0) && (maxValue > 0) && (maxValue > 20 * (total / count))) { if (maxValue / minValue > 100) { XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis oldAxis = plot.getRangeAxis(); LogarithmicAxis newAxis = new LogarithmicAxis(oldAxis.getLabel()); plot.setRangeAxis(newAxis); } } mChartMap.put(cs, chart); return Arrays.asList(chart); }
From source file:org.mwc.debrief.track_shift.views.StackedDotHelper.java
/** * ok, our track has been dragged, calculate the new series of offsets * /*from ww w. j av a 2 s . c om*/ * @param linePlot * @param dotPlot * @param onlyVis * @param holder * @param logger * * @param currentOffset * how far the current track has been dragged */ public void updateFrequencyData(final XYPlot dotPlot, final XYPlot linePlot, final TrackDataProvider tracks, final boolean onlyVis, final Composite holder, final ErrorLogger logger, final boolean updateDoublets) { // do we have anything? if (_primaryTrack == null) return; // ok, find the track wrappers if (_secondaryTrack == null) initialise(tracks, false, onlyVis, holder, logger, "Frequency", false, true); // ok - the tracks have moved. better update the doublets if (updateDoublets) updateDoublets(onlyVis, false, true); // aah - but what if we've ditched our doublets? // aah - but what if we've ditched our doublets? if ((_primaryDoublets == null) || (_primaryDoublets.size() == 0)) { // better clear the plot dotPlot.setDataset(null); linePlot.setDataset(null); return; } // create the collection of series final TimeSeriesCollection errorSeries = new TimeSeriesCollection(); final TimeSeriesCollection actualSeries = new TimeSeriesCollection(); // produce a dataset for each track final TimeSeries errorValues = new TimeSeries(_primaryTrack.getName()); final TimeSeries measuredValues = new TimeSeries("Measured"); final TimeSeries correctedValues = new TimeSeries("Corrected"); final TimeSeries predictedValues = new TimeSeries("Predicted"); final TimeSeries baseValues = new TimeSeries("Base"); // ok, run through the points on the primary track final Iterator<Doublet> iter = _primaryDoublets.iterator(); while (iter.hasNext()) { final Doublet thisD = iter.next(); try { final Color thisColor = thisD.getColor(); final double measuredFreq = thisD.getMeasuredFrequency(); final HiResDate currentTime = thisD.getDTG(); final FixedMillisecond thisMilli = new FixedMillisecond(currentTime.getDate().getTime()); final ColouredDataItem mFreq = new ColouredDataItem(thisMilli, measuredFreq, thisColor, false, null); // final ColouredDataItem corrFreq = new ColouredDataItem( // new FixedMillisecond(currentTime.getDate().getTime()), // correctedFreq, thisColor, false, null); measuredValues.add(mFreq); // do we have target data? if (thisD.getTarget() != null) { final double correctedFreq = thisD.getCorrectedFrequency(); final double baseFreq = thisD.getBaseFrequency(); final Color calcColor = thisD.getTarget().getColor(); final ColouredDataItem corrFreq = new ColouredDataItem(thisMilli, correctedFreq, thisColor, true, null); // did we get a base frequency? We may have a track // with a section of data that doesn't have frequency, you see. if (baseFreq != Doublet.INVALID_BASE_FREQUENCY) { final double predictedFreq = thisD.getPredictedFrequency(); final double thisError = thisD.calculateFreqError(measuredFreq, predictedFreq); final ColouredDataItem bFreq = new ColouredDataItem(thisMilli, baseFreq, thisColor, true, null); final ColouredDataItem pFreq = new ColouredDataItem(thisMilli, predictedFreq, calcColor, false, null); final ColouredDataItem eFreq = new ColouredDataItem(thisMilli, thisError, thisColor, false, null); baseValues.add(bFreq); predictedValues.add(pFreq); errorValues.add(eFreq); } correctedValues.add(corrFreq); } } catch (final SeriesException e) { CorePlugin.logError(Status.INFO, "some kind of trip whilst updating frequency plot", e); } } // ok, add these new series if (errorValues.getItemCount() > 0) errorSeries.addSeries(errorValues); actualSeries.addSeries(measuredValues); actualSeries.addSeries(correctedValues); if (predictedValues.getItemCount() > 0) actualSeries.addSeries(predictedValues); if (baseValues.getItemCount() > 0) actualSeries.addSeries(baseValues); dotPlot.setDataset(errorSeries); linePlot.setDataset(actualSeries); }
From source file:LineChart.java
private static JFreeChart createDataset(JTable table) { TimeZone tz = TimeZone.getTimeZone("GMT"); XYDataset ds = null;/*w ww. ja v a 2s .c o m*/ if (table.getColumnCount() > 0) { Class klass = table.getColumnClass(0); if ((klass == Date.class) || (klass == Time.class) || (klass == c.Month.class) || (klass == c.Minute.class) || (klass == c.Second.class) || (klass == Timestamp.class)) { TimeSeriesCollection tsc = new TimeSeriesCollection(); for (int col = 1; col < table.getColumnCount(); col++) { TimeSeries series = null; try { if (klass == Date.class) { series = new TimeSeries(table.getColumnName(col), Day.class); for (int row = 0; row < table.getRowCount(); row++) { Date date = (Date) table.getValueAt(row, 0); Day day = new Day(date, tz); Object o = table.getValueAt(row, col); if (o instanceof Number) { ((TimeSeries) series).addOrUpdate(day, (Number) table.getValueAt(row, col)); } } } else if (klass == Time.class) { series = new TimeSeries(table.getColumnName(col), Millisecond.class); for (int row = 0; row < table.getRowCount(); row++) { Time time = (Time) table.getValueAt(row, 0); Millisecond ms = new Millisecond(time, tz); // Millisecond ms = new Millisecond(time); Object o = table.getValueAt(row, col); if (o instanceof Number) { series.addOrUpdate(ms, (Number) table.getValueAt(row, col)); } } } else if (klass == Timestamp.class) { series = new TimeSeries(table.getColumnName(col), Millisecond.class); for (int row = 0; row < table.getRowCount(); row++) { Timestamp time = (Timestamp) table.getValueAt(row, 0); Millisecond ms = new Millisecond(time, tz); Object o = table.getValueAt(row, col); if (o instanceof Number) { series.addOrUpdate(ms, (Number) table.getValueAt(row, col)); } } } else if (klass == c.Month.class) { series = new TimeSeries(table.getColumnName(col), Month.class); for (int row = 0; row < table.getRowCount(); row++) { c.Month time = (c.Month) table.getValueAt(row, 0); int m = time.i + 24000; int y = m / 12; m = 1 + m % 12; Month month = new Month(m, y); Object o = table.getValueAt(row, col); if (o instanceof Number) { series.addOrUpdate(month, (Number) table.getValueAt(row, col)); } } } else if (klass == c.Second.class) { series = new TimeSeries(table.getColumnName(col), Second.class); for (int row = 0; row < table.getRowCount(); row++) { c.Second time = (c.Second) table.getValueAt(row, 0); Second second = new Second(time.i % 60, time.i / 60, 0, 1, 1, 2001); Object o = table.getValueAt(row, col); if (o instanceof Number) { series.addOrUpdate(second, (Number) table.getValueAt(row, col)); } } } else if (klass == c.Minute.class) { series = new TimeSeries(table.getColumnName(col), Minute.class); for (int row = 0; row < table.getRowCount(); row++) { c.Minute time = (c.Minute) table.getValueAt(row, 0); Minute minute = new Minute(time.i % 60, time.i / 60, 1, 1, 2001); Object o = table.getValueAt(row, col); if (o instanceof Number) { series.addOrUpdate(minute, (Number) table.getValueAt(row, col)); } } } } catch (SeriesException e) { System.err.println("Error adding to series"); } if (series.getItemCount() > 0) tsc.addSeries(series); } ds = tsc; } else if ((klass == double.class) || (klass == int.class) || (klass == short.class) || (klass == long.class) || (klass == Time.class)) { XYSeriesCollection xysc = new XYSeriesCollection(); for (int col = 1; col < table.getColumnCount(); col++) { XYSeries series = null; try { series = new XYSeries(table.getColumnName(col)); for (int row = 0; row < table.getRowCount(); row++) { Number x = (Number) table.getValueAt(row, 0); Object y = table.getValueAt(row, col); if (y instanceof Number) { series.add(x, (Number) y); } } } catch (SeriesException e) { System.err.println("Error adding to series"); } if (series.getItemCount() > 0) xysc.addSeries(series); } ds = xysc; } } if (ds != null) { boolean legend = false; if (ds.getSeriesCount() > 1) { legend = true; } if (ds instanceof XYSeriesCollection) { return ChartFactory.createXYLineChart("", "", "", ds, PlotOrientation.VERTICAL, legend, true, true); } else if (ds instanceof TimeSeriesCollection) return ChartFactory.createTimeSeriesChart("", "", "", ds, legend, true, true); } return null; }
From source file:org.mwc.debrief.track_shift.views.StackedDotHelper.java
/** * ok, our track has been dragged, calculate the new series of offsets * //from w w w. java2 s . c o m * @param linePlot * @param dotPlot * @param onlyVis * @param showCourse * @param b * @param holder * @param logger * * @param currentOffset * how far the current track has been dragged */ public void updateBearingData(final XYPlot dotPlot, final XYPlot linePlot, final TrackDataProvider tracks, final boolean onlyVis, final boolean showCourse, final boolean flipAxes, final Composite holder, final ErrorLogger logger, final boolean updateDoublets) { // do we even have a primary track if (_primaryTrack == null) return; // ok, find the track wrappers if (_secondaryTrack == null) initialise(tracks, false, onlyVis, holder, logger, "Bearing", true, false); // did it work? // if (_secondaryTrack == null) // return; // ok - the tracks have moved. better update the doublets if (updateDoublets) updateDoublets(onlyVis, true, false); // aah - but what if we've ditched our doublets? if ((_primaryDoublets == null) || (_primaryDoublets.size() == 0)) { // better clear the plot dotPlot.setDataset(null); linePlot.setDataset(null); return; } // create the collection of series final TimeSeriesCollection errorSeries = new TimeSeriesCollection(); final TimeSeriesCollection actualSeries = new TimeSeriesCollection(); // produce a dataset for each track final TimeSeries errorValues = new TimeSeries(_primaryTrack.getName()); final TimeSeries measuredValues = new TimeSeries("Measured"); final TimeSeries ambigValues = new TimeSeries("Ambiguous Bearing"); final TimeSeries calculatedValues = new TimeSeries("Calculated"); final TimeSeries osCourseValues = new TimeSeries("Course"); // ok, run through the points on the primary track final Iterator<Doublet> iter = _primaryDoublets.iterator(); while (iter.hasNext()) { final Doublet thisD = iter.next(); try { // obvious stuff first (stuff that doesn't need the tgt data) final Color thisColor = thisD.getColor(); double measuredBearing = thisD.getMeasuredBearing(); double ambigBearing = thisD.getAmbiguousMeasuredBearing(); final HiResDate currentTime = thisD.getDTG(); final FixedMillisecond thisMilli = new FixedMillisecond(currentTime.getDate().getTime()); // put the measured bearing back in the positive domain if (measuredBearing < 0) measuredBearing += 360d; // stop, stop, stop - do we wish to plot bearings in the +/- 180 domain? if (flipAxes) if (measuredBearing > 180) measuredBearing -= 360; final ColouredDataItem mBearing = new ColouredDataItem(thisMilli, measuredBearing, thisColor, false, null); // and add them to the series measuredValues.add(mBearing); if (ambigBearing != Doublet.INVALID_BASE_FREQUENCY) { if (flipAxes) if (ambigBearing > 180) ambigBearing -= 360; final ColouredDataItem amBearing = new ColouredDataItem(thisMilli, ambigBearing, thisColor, false, null); ambigValues.add(amBearing); } // do we have target data? if (thisD.getTarget() != null) { double calculatedBearing = thisD.getCalculatedBearing(null, null); final Color calcColor = thisD.getTarget().getColor(); final double thisError = thisD.calculateBearingError(measuredBearing, calculatedBearing); final ColouredDataItem newError = new ColouredDataItem(thisMilli, thisError, thisColor, false, null); if (flipAxes) if (calculatedBearing > 180) calculatedBearing -= 360; final ColouredDataItem cBearing = new ColouredDataItem(thisMilli, calculatedBearing, calcColor, true, null); errorValues.add(newError); calculatedValues.add(cBearing); } } catch (final SeriesException e) { CorePlugin.logError(Status.INFO, "some kind of trip whilst updating bearing plot", e); } } // right, we do course in a special way, since it isn't dependent on the // target track. Do course here. HiResDate startDTG, endDTG; // just double-check we've still got our primary doublets if (_primaryDoublets == null) { CorePlugin.logError(Status.WARNING, "FOR SOME REASON PRIMARY DOUBLETS IS NULL - INVESTIGATE", null); return; } if (_primaryDoublets.size() == 0) { CorePlugin.logError(Status.WARNING, "FOR SOME REASON PRIMARY DOUBLETS IS ZERO LENGTH - INVESTIGATE", null); return; } startDTG = _primaryDoublets.first().getDTG(); endDTG = _primaryDoublets.last().getDTG(); if (startDTG.greaterThan(endDTG)) { System.err.println("in the wrong order, start:" + startDTG + " end:" + endDTG); return; } final Collection<Editable> hostFixes = _primaryTrack.getItemsBetween(startDTG, endDTG); // loop through th items for (final Iterator<Editable> iterator = hostFixes.iterator(); iterator.hasNext();) { final Editable editable = (Editable) iterator.next(); final FixWrapper fw = (FixWrapper) editable; final FixedMillisecond thisMilli = new FixedMillisecond(fw.getDateTimeGroup().getDate().getTime()); double ownshipCourse = MWC.Algorithms.Conversions.Rads2Degs(fw.getCourse()); // stop, stop, stop - do we wish to plot bearings in the +/- 180 domain? if (flipAxes) if (ownshipCourse > 180) ownshipCourse -= 360; final ColouredDataItem crseBearing = new ColouredDataItem(thisMilli, ownshipCourse, fw.getColor(), true, null); osCourseValues.add(crseBearing); } // ok, add these new series if (showCourse) { actualSeries.addSeries(osCourseValues); } if (errorValues.getItemCount() > 0) errorSeries.addSeries(errorValues); actualSeries.addSeries(measuredValues); if (ambigValues.getItemCount() > 0) actualSeries.addSeries(ambigValues); if (calculatedValues.getItemCount() > 0) actualSeries.addSeries(calculatedValues); dotPlot.setDataset(errorSeries); linePlot.setDataset(actualSeries); }
From source file:studio.ui.LineChart.java
public static JFreeChart createDataset(KTableModel table) { TimeZone tz = TimeZone.getTimeZone("GMT"); XYDataset ds = null;// w w w . java2 s. co m if (table.getColumnCount() > 0) { Class klass = table.getColumnClass(0); if ((klass == K.KTimestampVector.class) || (klass == K.KTimespanVector.class) || (klass == K.KDateVector.class) || (klass == K.KTimeVector.class) || (klass == K.KMonthVector.class) || (klass == K.KMinuteVector.class) || (klass == K.KSecondVector.class) || (klass == K.KDatetimeVector.class)) { TimeSeriesCollection tsc = new TimeSeriesCollection(tz); for (int col = 1; col < table.getColumnCount(); col++) { TimeSeries series = null; try { if (klass == K.KDateVector.class) { series = new TimeSeries(table.getColumnName(col), Day.class); K.KDateVector dates = (K.KDateVector) table.getColumn(0); for (int row = 0; row < dates.getLength(); row++) { K.KDate date = (K.KDate) dates.at(row); Day day = new Day(date.toDate(), tz); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(day, ((ToDouble) o).toDouble()); } } else if (klass == K.KTimeVector.class) { series = new TimeSeries(table.getColumnName(col), Millisecond.class); K.KTimeVector times = (K.KTimeVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.KTime time = (K.KTime) times.at(row); Millisecond ms = new Millisecond(time.toTime(), tz); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(ms, ((ToDouble) o).toDouble()); } } else if (klass == K.KTimestampVector.class) { series = new TimeSeries(table.getColumnName(col), Day.class); K.KTimestampVector dates = (K.KTimestampVector) table.getColumn(0); for (int row = 0; row < dates.getLength(); row++) { K.KTimestamp date = (K.KTimestamp) dates.at(row); Day day = new Day(new java.util.Date(date.toTimestamp().getTime()), tz); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(day, ((ToDouble) o).toDouble()); } } else if (klass == K.KTimespanVector.class) { series = new TimeSeries(table.getColumnName(col), Millisecond.class); K.KTimespanVector times = (K.KTimespanVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.KTimespan time = (K.KTimespan) times.at(row); Millisecond ms = new Millisecond(time.toTime(), tz); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(ms, ((ToDouble) o).toDouble()); } } else if (klass == K.KDatetimeVector.class) { series = new TimeSeries(table.getColumnName(col), Millisecond.class); K.KDatetimeVector times = (K.KDatetimeVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.KDatetime time = (K.KDatetime) times.at(row); Millisecond ms = new Millisecond(time.toTimestamp(), tz); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(ms, ((ToDouble) o).toDouble()); } } else if (klass == K.KMonthVector.class) { series = new TimeSeries(table.getColumnName(col), Month.class); K.KMonthVector times = (K.KMonthVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.Month time = (K.Month) times.at(row); int m = time.i + 24000; int y = m / 12; m = 1 + m % 12; Month month = new Month(m, y); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(month, ((ToDouble) o).toDouble()); } } else if (klass == K.KSecondVector.class) { series = new TimeSeries(table.getColumnName(col), Second.class); K.KSecondVector times = (K.KSecondVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.Second time = (K.Second) times.at(row); Second second = new Second(time.i % 60, time.i / 60, 0, 1, 1, 2001); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(second, ((ToDouble) o).toDouble()); } } else if (klass == K.KMinuteVector.class) { series = new TimeSeries(table.getColumnName(col), Minute.class); K.KMinuteVector times = (K.KMinuteVector) table.getColumn(0); for (int row = 0; row < table.getRowCount(); row++) { K.Minute time = (K.Minute) times.at(row); Minute minute = new Minute(time.i % 60, time.i / 60, 1, 1, 2001); Object o = table.getValueAt(row, col); if (o instanceof K.KBase) if (!((K.KBase) o).isNull()) if (o instanceof ToDouble) series.addOrUpdate(minute, ((ToDouble) o).toDouble()); } } } catch (SeriesException e) { System.err.println("Error adding to series"); } if (series.getItemCount() > 0) tsc.addSeries(series); } ds = tsc; } else if ((klass == K.KDoubleVector.class) || (klass == K.KFloatVector.class) || (klass == K.KShortVector.class) || (klass == K.KIntVector.class) || (klass == K.KLongVector.class)) { XYSeriesCollection xysc = new XYSeriesCollection(); for (int col = 1; col < table.getColumnCount(); col++) { XYSeries series = null; try { series = new XYSeries(table.getColumnName(col)); for (int row = 0; row < table.getRowCount(); row++) { double x = ((ToDouble) table.getValueAt(row, 0)).toDouble(); double y = ((ToDouble) table.getValueAt(row, col)).toDouble(); series.add(x, y); } } catch (SeriesException e) { System.err.println("Error adding to series"); } if (series.getItemCount() > 0) xysc.addSeries(series); } ds = xysc; } } if (ds != null) { boolean legend = false; if (ds.getSeriesCount() > 1) legend = true; if (ds instanceof XYSeriesCollection) return ChartFactory.createXYLineChart("", "", "", ds, PlotOrientation.VERTICAL, legend, true, true); else if (ds instanceof TimeSeriesCollection) return ChartFactory.createTimeSeriesChart("", "", "", ds, legend, true, true); } return null; }