use of org.jfree.data.time.TimeSeries in project ma-core-public by infiniteautomation.
the class ImageChartUtils method writeChart.
public static void writeChart(PointTimeSeriesCollection pointTimeSeriesCollection, boolean showLegend, OutputStream out, int width, int height, long from, long to) throws IOException {
JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, null, showLegend, false, false);
chart.setBackgroundPaint(SystemSettingsDao.getColour(SystemSettingsDao.CHART_BACKGROUND_COLOUR));
XYPlot plot = chart.getXYPlot();
((DateAxis) plot.getDomainAxis()).setTimeZone(pointTimeSeriesCollection.getTimeZone());
plot.setBackgroundPaint(SystemSettingsDao.getColour(SystemSettingsDao.PLOT_BACKGROUND_COLOUR));
Color gridlines = SystemSettingsDao.getColour(SystemSettingsDao.PLOT_GRIDLINE_COLOUR);
plot.setDomainGridlinePaint(gridlines);
plot.setRangeGridlinePaint(gridlines);
((NumberAxis) plot.getRangeAxis()).setAutoRangeStickyZero(false);
double numericMin = 0;
double numericMax = 1;
int numericSeriesCount = pointTimeSeriesCollection.getNumericSeriesCount();
if (pointTimeSeriesCollection.hasNumericData()) {
for (int i = 0; i < numericSeriesCount; i++) {
NumericTimeSeries nts = pointTimeSeriesCollection.getNumericTimeSeries(i);
AbstractXYItemRenderer renderer;
if (nts.getPlotType() == DataPointVO.PlotTypes.STEP)
renderer = new XYStepRenderer();
else if (nts.getPlotType() == DataPointVO.PlotTypes.LINE)
renderer = new XYLineAndShapeRenderer(true, false);
else {
// XYCardinalSplineRenderer spline = new XYCardinalSplineRenderer(.5d, 16);
// XYSmoothLineAndShapeRenderer spline = new XYSmoothLineAndShapeRenderer();
// XYSplineRenderer spline = new XYSplineRenderer();
// spline.setBaseShapesVisible(false);
// renderer = spline;
renderer = new XYLineAndShapeRenderer(true, false);
}
if (nts.getPaint() != null)
renderer.setSeriesPaint(0, nts.getPaint(), false);
if (nts.getStroke() != null)
renderer.setSeriesStroke(0, nts.getStroke(), false);
plot.setDataset(i, new TimeSeriesCollection(nts.getTimeSeries()));
plot.setRenderer(i, renderer);
}
numericMin = plot.getRangeAxis().getLowerBound();
numericMax = plot.getRangeAxis().getUpperBound();
if (!pointTimeSeriesCollection.hasMultiplePoints()) {
// If this chart displays a single point, check if there should be a range description.
TimeSeries timeSeries = pointTimeSeriesCollection.getNumericTimeSeries(0).getTimeSeries();
String desc = timeSeries.getRangeDescription();
if (!StringUtils.isBlank(desc)) {
// Replace any HTML entities with Java equivalents
desc = StripEntities.stripHTMLEntities(desc, ' ');
plot.getRangeAxis().setLabel(desc);
}
}
} else
plot.getRangeAxis().setVisible(false);
if (pointTimeSeriesCollection.getRangeMarkers() != null) {
boolean rangeAdjusted = false;
for (Marker marker : pointTimeSeriesCollection.getRangeMarkers()) {
plot.addRangeMarker(marker);
if (marker instanceof ValueMarker) {
ValueMarker vm = (ValueMarker) marker;
if (numericMin > vm.getValue()) {
numericMin = vm.getValue();
rangeAdjusted = true;
}
if (numericMax < vm.getValue()) {
numericMax = vm.getValue();
rangeAdjusted = true;
}
}
}
if (rangeAdjusted) {
double adj = (numericMax - numericMin);
plot.getRangeAxis().setLowerBound(numericMin - adj * plot.getRangeAxis().getLowerMargin());
plot.getRangeAxis().setUpperBound(numericMax + adj * plot.getRangeAxis().getUpperMargin());
}
}
int discreteValueCount = pointTimeSeriesCollection.getDiscreteValueCount();
double interval = (numericMax - numericMin) / (discreteValueCount + 1);
int intervalIndex = 1;
if (pointTimeSeriesCollection.hasDiscreteData()) {
for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);
XYStepRenderer renderer = new XYStepRenderer();
TimeSeries ts = new TimeSeries(dts.getName(), null, null);
for (IValueTime vt : dts.getValueTimes()) addMillisecond(ts, vt.getTime(), numericMin + (interval * (dts.getValueIndex(vt.getValue()) + intervalIndex)));
if (dts.getPaint() != null)
renderer.setSeriesPaint(0, dts.getPaint(), false);
if (dts.getStroke() != null)
renderer.setSeriesStroke(0, dts.getStroke(), false);
plot.setDataset(numericSeriesCount + i, new TimeSeriesCollection(ts, pointTimeSeriesCollection.getTimeZone()));
plot.setRenderer(numericSeriesCount + i, renderer);
intervalIndex += dts.getDiscreteValueCount();
}
}
if (from > 0)
plot.getDomainAxis().setLowerBound(from);
if (to > 0)
plot.getDomainAxis().setUpperBound(to);
if (pointTimeSeriesCollection.hasDiscreteData()) {
// Add the value annotations.
double annoX = plot.getDomainAxis().getLowerBound();
intervalIndex = 1;
for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);
for (int j = 0; j < dts.getDiscreteValueCount(); j++) {
XYTextAnnotation anno = new XYTextAnnotation(" " + dts.getValueText(j), annoX, numericMin + (interval * (j + intervalIndex)));
if (!pointTimeSeriesCollection.hasNumericData() && intervalIndex + j == discreteValueCount)
// This prevents the top label from getting cut off
anno.setTextAnchor(TextAnchor.TOP_LEFT);
else
anno.setTextAnchor(TextAnchor.BOTTOM_LEFT);
anno.setPaint(((AbstractRenderer) plot.getRenderer(numericSeriesCount + i)).lookupSeriesPaint(0));
plot.addAnnotation(anno);
}
intervalIndex += dts.getDiscreteValueCount();
}
}
// Return the image.
ChartUtilities.writeChartAsPNG(out, chart, width, height);
}
use of org.jfree.data.time.TimeSeries in project ma-core-public by infiniteautomation.
the class ImageChartServlet method getImageData.
private byte[] getImageData(String imageInfo, HttpServletRequest request) throws IOException {
// Hex colour definitions need to be prefixed with '0x' instead of '#'.
try {
// Remove the / and the .png
imageInfo = imageInfo.substring(1, imageInfo.length() - 4);
// Split by underscore.
String[] imageBits = imageInfo.split("_");
// Get the data.
long from, to;
int pointIdStart;
if (imageBits[0].equals("ft")) {
from = Long.parseLong(imageBits[2]);
to = Long.parseLong(imageBits[3]);
pointIdStart = 4;
} else {
from = Common.timer.currentTimeMillis() - Long.parseLong(imageBits[1]);
to = -1;
pointIdStart = 2;
}
int width = getIntRequestParameter(request, "w", 200);
int height = getIntRequestParameter(request, "h", 100);
String useCacheString = request.getParameter("useCache");
boolean useCache = false;
if (useCacheString != null && Boolean.valueOf(useCacheString))
useCache = true;
TimeZone timeZone = Common.getUserTimeZone(Common.getUser(request));
// Create the datasets
DataPointVO markerPoint = null;
int pointCount = 0;
PointTimeSeriesCollection ptsc = new PointTimeSeriesCollection(timeZone);
for (int i = pointIdStart; i < imageBits.length; i++) {
if (imageBits[i].startsWith("w"))
width = NumberUtils.toInt(imageBits[i].substring(1), width);
else if (imageBits[i].startsWith("h"))
height = NumberUtils.toInt(imageBits[i].substring(1), height);
else {
String dataPointStr = imageBits[i];
Color colour = null;
int dataPointId;
int pipe = dataPointStr.indexOf('|');
if (pipe == -1)
dataPointId = Integer.parseInt(dataPointStr);
else {
try {
String colourStr = dataPointStr.substring(pipe + 1);
if (colourStr.startsWith("0x"))
colourStr = "#" + colourStr.substring(2);
colour = ColorUtils.toColor(colourStr);
} catch (InvalidArgumentException e) {
throw new IOException(e);
}
dataPointId = Integer.parseInt(dataPointStr.substring(0, pipe));
}
// Get the data.
DataPointVO dp = DataPointDao.instance.getDataPoint(dataPointId);
if (dp != null && dp.getName() != null) {
pointCount++;
markerPoint = dp;
// Get the Color if there wasn't one provided
if (colour == null) {
try {
if (dp.getChartColour() != null)
colour = ColorUtils.toColor(dp.getChartColour());
} catch (InvalidArgumentException e) {
// Munch it
}
}
PointValueFacade pointValueFacade = new PointValueFacade(dataPointId, useCache);
List<PointValueTime> data;
if (from == -1 && to == -1)
data = pointValueFacade.getPointValuesBetween(0, Common.timer.currentTimeMillis(), true, true);
else if (from == -1)
data = pointValueFacade.getPointValuesBetween(0, to, true, true);
else if (to == -1)
data = pointValueFacade.getPointValuesBetween(from, Common.timer.currentTimeMillis(), true, true);
else
data = pointValueFacade.getPointValuesBetween(from, to, true, true);
if (dp.getPointLocator().getDataTypeId() == DataTypes.NUMERIC) {
TimeSeries ts;
if (dp.isUseRenderedUnit()) {
// This works because we enforce that all Units default to the ONE Unit if not used
UnitConverter converter = null;
if (dp.getRenderedUnit() != dp.getUnit())
converter = dp.getUnit().getConverterTo(dp.getRenderedUnit());
ts = new TimeSeries(dp.getExtendedName(), null, dp.getTextRenderer().getMetaText());
double value;
for (PointValueTime pv : data) {
if (pv.getValue() != null) {
if (converter != null)
value = converter.convert(pv.getDoubleValue());
else
value = pv.getDoubleValue();
ImageChartUtils.addMillisecond(ts, pv.getTime(), value);
}
}
} else {
// No renderer, don't need it
ts = new TimeSeries(dp.getExtendedName(), null, dp.getTextRenderer().getMetaText());
for (PointValueTime pv : data) {
if (pv.getValue() != null)
ImageChartUtils.addMillisecond(ts, pv.getTime(), pv.getValue().numberValue());
}
}
ptsc.addNumericTimeSeries(new NumericTimeSeries(dp.getPlotType(), ts, colour, null));
} else {
DiscreteTimeSeries ts = new DiscreteTimeSeries(dp.getExtendedName(), dp.getTextRenderer(), colour, null);
for (PointValueTime pv : data) if (pv.getValue() != null)
ts.addValueTime(pv);
ptsc.addDiscreteTimeSeries(ts);
}
}
}
}
if (pointCount == 1) {
// Only one point. Check for limits to draw as markers.
UnitConverter uc;
if (markerPoint.getUnit() != null && markerPoint.getRenderedUnit() != null)
uc = markerPoint.getUnit().getConverterTo(markerPoint.getRenderedUnit());
else
uc = Unit.ONE.getConverterTo(Unit.ONE);
for (AbstractPointEventDetectorVO<?> ped : markerPoint.getEventDetectors()) {
if (ped.getDefinition().getEventDetectorTypeName().equals(AnalogLowLimitEventDetectorDefinition.TYPE_NAME))
ptsc.addRangeMarker(new ValueMarker(uc.convert(((AnalogLowLimitDetectorVO) ped).getLimit()), lowLimitPaint, limitStroke));
else if (ped.getDefinition().getEventDetectorTypeName().equals(AnalogHighLimitEventDetectorDefinition.TYPE_NAME))
ptsc.addRangeMarker(new ValueMarker(uc.convert(((AnalogHighLimitDetectorVO) ped).getLimit()), highLimitPaint, limitStroke));
}
}
return ImageChartUtils.getChartData(ptsc, width, height, from, to);
} catch (StringIndexOutOfBoundsException e) {
// no op
} catch (NumberFormatException e) {
// no op
} catch (ArrayIndexOutOfBoundsException e) {
// no op
}
return null;
}
use of org.jfree.data.time.TimeSeries in project GT by Tencent.
the class AbstractRealTimeLineChart method addOneDataset.
/**
* 插入一种数据,返回该数据的编号
* 插入多次数据的时候需要保证每种数据的测试进程都是相同的
* @Title: addOneDataset
* @Description:
* @param pkgNames
* @param dataName
* @return
* int 返回数据编号,失败返回-1
* @throws
*/
public int addOneDataset(String[] objects, String dataName) {
if (objects == null || objects.length == 0 || dataName == null) {
return -1;
}
objectNum = objects.length;
dataNum++;
for (int i = 0; i < objectNum; i++) {
int index = i * dataNum + (dataNum - 1);
chart.getXYPlot().getRenderer().setSeriesStroke(index, new BasicStroke(Constant.LINE_WIDTH));
tsList.add(index, new TimeSeries(objects[i] + "_" + dataName));
tsEnableList.add(index, true);
dataset.addSeries(tsList.get(index));
}
return dataNum - 1;
}
use of org.jfree.data.time.TimeSeries in project logprocessing by cloudian.
the class GeminiChartUtil method createReport.
public void createReport(OutputStream out, List<ChartSeries> chartData, String strTitle, String strDomainAxisLabel) {
strDomainAxisLabel = "Time Interval: " + strDomainAxisLabel;
String strYAxisLabel;
// String strCategoryType = " ";
strYAxisLabel = "Count";
// SimpleDateFormat sdf = new SimpleDateFormat("MMMM-dd hh:mm a");
// build a dataset as needed by JFreeChart
// note: strCategoryType is for a chart with multiple categories.
// i.e. idisplay multiple bars for each time interval.
//
TimeSeriesCollection dataSet = new TimeSeriesCollection();
// For each series of data, create a TimeSeries
for (int i = 0; i < chartData.size(); i++) {
ChartSeries chartSeries = chartData.get(i);
TimeSeries timeSeries = new TimeSeries(chartSeries.getName(), Millisecond.class);
List<ChartValueByTime> data = chartSeries.getData();
// int cumulValue = 0;
for (int j = 0; j < data.size(); j++) {
ChartValueByTime chartVal = data.get(j);
Millisecond ms = new Millisecond(new Date(chartVal.getTime()));
// *NOT* Store the cumulative value . So maintain a running total.
// cumulValue += chartVal.getValue();
// timeSeries.add(ms, cumulValue);
timeSeries.add(ms, chartVal.getValue());
}
dataSet.addSeries(timeSeries);
}
JFreeChart lineChart = ChartFactory.createTimeSeriesChart(// chart title
strTitle, // domain axis label
strDomainAxisLabel, // range axis label
strYAxisLabel, // data
dataSet, // legend
true, // tooltips
false, // urls
false);
try {
ChartUtilities.writeChartAsPNG(out, lineChart, 800, 400);
} catch (IOException e) {
e.printStackTrace();
}
}
use of org.jfree.data.time.TimeSeries in project zm-mailbox by Zimbra.
the class ChartUtil method createJFReeChart.
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);
}
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);
}
Aggregations