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