Datahandler and Unified Data Format
[dygraphs.git] / datahandler / bars-custom.js
1 /**
2 * @license
3 * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview DataHandler implementation for the custom bars option.
9 * @author David Eberlein (david.eberlein@ch.sauter-bc.com)
10 */
11
12 (function() {
13 /*global Dygraph:false */
14 "use strict";
15
16 var CustomBarsHandler = Dygraph.DataHandler();
17 CustomBarsHandler.prototype = Dygraph.DataHandlers.createHandler("bars");
18 Dygraph.DataHandlers.registerHandler("bars-custom", CustomBarsHandler);
19 // customBars
20 CustomBarsHandler.prototype.extractSeries = function(rawData, i, options) {
21 // TODO(danvk): pre-allocate series here.
22 var series = [];
23 var x, y, point;
24 var logScale = options.get('logscale');
25 for ( var j = 0; j < rawData.length; j++) {
26 x = rawData[j][0];
27 point = rawData[j][i];
28 if (logScale && point !== null) {
29 // On the log scale, points less than zero do not exist.
30 // This will create a gap in the chart.
31 if (point[0] <= 0 || point[1] <= 0 || point[2] <= 0) {
32 point = null;
33 }
34 }
35 // Extract to the unified data format.
36 if (point !== null) {
37 y = point[1];
38 if (y !== null && !isNaN(y)) {
39 series.push([ x, y, [ point[0], point[2] ] ]);
40 } else {
41 series.push([ x, y, [ y, y ] ]);
42 }
43 } else {
44 series.push([ x, null, [ null, null ] ]);
45 }
46 }
47 return series;
48 };
49
50 CustomBarsHandler.prototype.rollingAverage = function(originalData, rollPeriod,
51 options) {
52 rollPeriod = Math.min(rollPeriod, originalData.length);
53 var rollingData = [];
54 var y, low, high, mid,count, i, extremes;
55
56 low = 0;
57 mid = 0;
58 high = 0;
59 count = 0;
60 for (i = 0; i < originalData.length; i++) {
61 y = originalData[i][1];
62 extremes = originalData[i][2];
63 rollingData[i] = originalData[i];
64
65 if (y !== null && !isNaN(y)) {
66 low += extremes[0];
67 mid += y;
68 high += extremes[1];
69 count += 1;
70 }
71 if (i - rollPeriod >= 0) {
72 var prev = originalData[i - rollPeriod];
73 if (prev[1] !== null && !isNaN(prev[1])) {
74 low -= prev[2][0];
75 mid -= prev[1];
76 high -= prev[2][1];
77 count -= 1;
78 }
79 }
80 if (count) {
81 rollingData[i] = [
82 originalData[i][0],
83 1.0 * mid / count,
84 [ 1.0 * low / count,
85 1.0 * high / count ] ];
86 } else {
87 rollingData[i] = [ originalData[i][0], null, [ null, null ] ];
88 }
89 }
90
91 return rollingData;
92 };
93 })();