lint
[dygraphs.git] / datahandler / bars-error.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 error bars option.
9 * @author David Eberlein (david.eberlein@ch.sauter-bc.com)
10 */
11
12 (function() {
13
14 /*global Dygraph:false */
15 "use strict";
16
17 Dygraph.DataHandlers.ErrorBarsHandler = Dygraph.DataHandler();
18 var ErrorBarsHandler = Dygraph.DataHandlers.ErrorBarsHandler;
19 ErrorBarsHandler.prototype = new Dygraph.DataHandlers.BarsHandler();
20
21 // errorBars
22 ErrorBarsHandler.prototype.extractSeries = function(rawData, i, options) {
23 // TODO(danvk): pre-allocate series here.
24 var series = [];
25 var x, y, variance, point;
26 var sigma = options.get("sigma");
27 var logScale = options.get('logscale');
28 for ( var j = 0; j < rawData.length; j++) {
29 x = rawData[j][0];
30 point = rawData[j][i];
31 if (logScale && point !== null) {
32 // On the log scale, points less than zero do not exist.
33 // This will create a gap in the chart.
34 if (point[0] <= 0 || point[0] - sigma * point[1] <= 0) {
35 point = null;
36 }
37 }
38 // Extract to the unified data format.
39 if (point !== null) {
40 y = point[0];
41 if (y !== null && !isNaN(y)) {
42 variance = sigma * point[1];
43 // preserve original error value in extras for further
44 // filtering
45 series.push([ x, y, [ y - variance, y + variance, point[1] ] ]);
46 } else {
47 series.push([ x, y, [ y, y, y ] ]);
48 }
49 } else {
50 series.push([ x, null, [ null, null, null ] ]);
51 }
52 }
53 return series;
54 };
55
56 ErrorBarsHandler.prototype.rollingAverage = function(originalData, rollPeriod,
57 options) {
58 rollPeriod = Math.min(rollPeriod, originalData.length);
59 var rollingData = [];
60 var sigma = options.get("sigma");
61
62 var i, j, y, v, sum, num_ok, stddev, variance, value;
63
64 // Calculate the rolling average for the first rollPeriod - 1 points
65 // where there is not enough data to roll over the full number of points
66 for (i = 0; i < originalData.length; i++) {
67 sum = 0;
68 variance = 0;
69 num_ok = 0;
70 for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
71 y = originalData[j][1];
72 if (y === null || isNaN(y))
73 continue;
74 num_ok++;
75 sum += y;
76 variance += Math.pow(originalData[j][2][2], 2);
77 }
78 if (num_ok) {
79 stddev = Math.sqrt(variance) / num_ok;
80 value = sum / num_ok;
81 rollingData[i] = [ originalData[i][0], value,
82 [value - sigma * stddev, value + sigma * stddev] ];
83 } else {
84 // This explicitly preserves NaNs to aid with "independent
85 // series".
86 // See testRollingAveragePreservesNaNs.
87 v = (rollPeriod == 1) ? originalData[i][1] : null;
88 rollingData[i] = [ originalData[i][0], v, [ v, v ] ];
89 }
90 }
91
92 return rollingData;
93 };
94
95 })();