Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / static / fusion / raptor / dy3 / js / dygraph-layout.js
1 /**
2  * @license
3  * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4  * MIT-licensed (http://opensource.org/licenses/MIT)
5  */
6
7 /**
8  * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
9  * dygraphs.
10  */
11
12 /*jshint globalstrict: true */
13 /*global Dygraph:false */
14 "use strict";
15
16 /**
17  * Creates a new DygraphLayout object.
18  *
19  * This class contains all the data to be charted.
20  * It uses data coordinates, but also records the chart range (in data
21  * coordinates) and hence is able to calculate percentage positions ('In this
22  * view, Point A lies 25% down the x-axis.')
23  *
24  * Two things that it does not do are:
25  * 1. Record pixel coordinates for anything.
26  * 2. (oddly) determine anything about the layout of chart elements.
27  *
28  * The naming is a vestige of Dygraph's original PlotKit roots.
29  *
30  * @constructor
31  */
32 var DygraphLayout = function(dygraph) {
33   this.dygraph_ = dygraph;
34   /**
35    * Array of points for each series.
36    *
37    * [series index][row index in series] = |Point| structure,
38    * where series index refers to visible series only, and the
39    * point index is for the reduced set of points for the current
40    * zoom region (including one point just outside the window).
41    * All points in the same row index share the same X value.
42    *
43    * @type {Array.<Array.<Dygraph.PointType>>}
44    */
45   this.points = [];
46   this.setNames = [];
47   this.annotations = [];
48   this.yAxes_ = null;
49
50   // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
51   // yticks are outputs. Clean this up.
52   this.xTicks_ = null;
53   this.yTicks_ = null;
54 };
55
56 DygraphLayout.prototype.attr_ = function(name) {
57   return this.dygraph_.attr_(name);
58 };
59
60 /**
61  * Add points for a single series.
62  *
63  * @param {string} setname Name of the series.
64  * @param {Array.<Dygraph.PointType>} set_xy Points for the series.
65  */
66 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
67   this.points.push(set_xy);
68   this.setNames.push(setname);
69 };
70
71 /**
72  * Returns the box which the chart should be drawn in. This is the canvas's
73  * box, less space needed for the axis and chart labels.
74  *
75  * @return {{x: number, y: number, w: number, h: number}}
76  */
77 DygraphLayout.prototype.getPlotArea = function() {
78   return this.area_;
79 };
80
81 // Compute the box which the chart should be drawn in. This is the canvas's
82 // box, less space needed for axis, chart labels, and other plug-ins.
83 // NOTE: This should only be called by Dygraph.predraw_().
84 DygraphLayout.prototype.computePlotArea = function() {
85   var area = {
86     // TODO(danvk): per-axis setting.
87     x: 0,
88     y: 0
89   };
90
91   area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
92   area.h = this.dygraph_.height_;
93
94   // Let plugins reserve space.
95   var e = {
96     chart_div: this.dygraph_.graphDiv,
97     reserveSpaceLeft: function(px) {
98       var r = {
99         x: area.x,
100         y: area.y,
101         w: px,
102         h: area.h
103       };
104       area.x += px;
105       area.w -= px;
106       return r;
107     },
108     reserveSpaceRight: function(px) {
109       var r = {
110         x: area.x + area.w - px,
111         y: area.y,
112         w: px,
113         h: area.h
114       };
115       area.w -= px;
116       return r;
117     },
118     reserveSpaceTop: function(px) {
119       var r = {
120         x: area.x,
121         y: area.y,
122         w: area.w,
123         h: px
124       };
125       area.y += px;
126       area.h -= px;
127       return r;
128     },
129     reserveSpaceBottom: function(px) {
130       var r = {
131         x: area.x,
132         y: area.y + area.h - px,
133         w: area.w,
134         h: px
135       };
136       area.h -= px;
137       return r;
138     },
139     chartRect: function() {
140       return {x:area.x, y:area.y, w:area.w, h:area.h};
141     }
142   };
143   this.dygraph_.cascadeEvents_('layout', e);
144
145   this.area_ = area;
146 };
147
148 DygraphLayout.prototype.setAnnotations = function(ann) {
149   // The Dygraph object's annotations aren't parsed. We parse them here and
150   // save a copy. If there is no parser, then the user must be using raw format.
151   this.annotations = [];
152   var parse = this.attr_('xValueParser') || function(x) { return x; };
153   for (var i = 0; i < ann.length; i++) {
154     var a = {};
155     if (!ann[i].xval && ann[i].x === undefined) {
156       this.dygraph_.error("Annotations must have an 'x' property");
157       return;
158     }
159     if (ann[i].icon &&
160         !(ann[i].hasOwnProperty('width') &&
161           ann[i].hasOwnProperty('height'))) {
162       this.dygraph_.error("Must set width and height when setting " +
163                           "annotation.icon property");
164       return;
165     }
166     Dygraph.update(a, ann[i]);
167     if (!a.xval) a.xval = parse(a.x);
168     this.annotations.push(a);
169   }
170 };
171
172 DygraphLayout.prototype.setXTicks = function(xTicks) {
173   this.xTicks_ = xTicks;
174 };
175
176 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
177 DygraphLayout.prototype.setYAxes = function (yAxes) {
178   this.yAxes_ = yAxes;
179 };
180
181 DygraphLayout.prototype.evaluate = function() {
182   this._evaluateLimits();
183   this._evaluateLineCharts();
184   this._evaluateLineTicks();
185   this._evaluateAnnotations();
186 };
187
188 DygraphLayout.prototype._evaluateLimits = function() {
189   var xlimits = this.dygraph_.xAxisRange();
190   this.minxval = xlimits[0];
191   this.maxxval = xlimits[1];
192   var xrange = xlimits[1] - xlimits[0];
193   this.xscale = (xrange !== 0 ? 1 / xrange : 1.0);
194
195   for (var i = 0; i < this.yAxes_.length; i++) {
196     var axis = this.yAxes_[i];
197     axis.minyval = axis.computedValueRange[0];
198     axis.maxyval = axis.computedValueRange[1];
199     axis.yrange = axis.maxyval - axis.minyval;
200     axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
201
202     if (axis.g.attr_("logscale")) {
203       axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
204       axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
205       if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
206         axis.g.error('axis ' + i + ' of graph at ' + axis.g +
207             ' can\'t be displayed in log scale for range [' +
208             axis.minyval + ' - ' + axis.maxyval + ']');
209       }
210     }
211   }
212 };
213
214 DygraphLayout._calcYNormal = function(axis, value, logscale) {
215   if (logscale) {
216     return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
217   } else {
218     return 1.0 - ((value - axis.minyval) * axis.yscale);
219   }
220 };
221
222 DygraphLayout.prototype._evaluateLineCharts = function() {
223   var connectSeparated = this.attr_('connectSeparatedPoints');
224   var isStacked = this.attr_("stackedGraph");
225   var hasBars = this.attr_('errorBars') || this.attr_('customBars');
226
227   for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
228     var points = this.points[setIdx];
229     var setName = this.setNames[setIdx];
230     var axis = this.dygraph_.axisPropertiesForSeries(setName);
231     // TODO (konigsberg): use optionsForAxis instead.
232     var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
233
234     for (var j = 0; j < points.length; j++) {
235       var point = points[j];
236
237       // Range from 0-1 where 0 represents left and 1 represents right.
238       point.x = (point.xval - this.minxval) * this.xscale;
239       // Range from 0-1 where 0 represents top and 1 represents bottom
240       var yval = point.yval;
241       if (isStacked) {
242         point.y_stacked = DygraphLayout._calcYNormal(
243             axis, point.yval_stacked, logscale);
244         if (yval !== null && !isNaN(yval)) {
245           yval = point.yval_stacked;
246         }
247       }
248       if (yval === null) {
249         yval = NaN;
250         if (!connectSeparated) {
251           point.yval = NaN;
252         }
253       }
254       point.y = DygraphLayout._calcYNormal(axis, yval, logscale);
255
256       if (hasBars) {
257         point.y_top = DygraphLayout._calcYNormal(
258             axis, yval - point.yval_minus, logscale);
259         point.y_bottom = DygraphLayout._calcYNormal(
260             axis, yval + point.yval_plus, logscale);
261       }
262     }
263   }
264 };
265
266 /**
267  * Optimized replacement for parseFloat, which was way too slow when almost
268  * all values were type number, with few edge cases, none of which were strings.
269  */
270 DygraphLayout.parseFloat_ = function(val) {
271   // parseFloat(null) is NaN
272   if (val === null) {
273     return NaN;
274   }
275
276   // Assume it's a number or NaN. If it's something else, I'll be shocked.
277   return val;
278 };
279
280 DygraphLayout.prototype._evaluateLineTicks = function() {
281   var i, tick, label, pos;
282   this.xticks = [];
283   for (i = 0; i < this.xTicks_.length; i++) {
284     tick = this.xTicks_[i];
285     label = tick.label;
286     pos = this.xscale * (tick.v - this.minxval);
287     if ((pos >= 0.0) && (pos <= 1.0)) {
288       this.xticks.push([pos, label]);
289     }
290   }
291
292   this.yticks = [];
293   for (i = 0; i < this.yAxes_.length; i++ ) {
294     var axis = this.yAxes_[i];
295     for (var j = 0; j < axis.ticks.length; j++) {
296       tick = axis.ticks[j];
297       label = tick.label;
298       pos = this.dygraph_.toPercentYCoord(tick.v, i);
299       if ((pos >= 0.0) && (pos <= 1.0)) {
300         this.yticks.push([i, pos, label]);
301       }
302     }
303   }
304 };
305
306 DygraphLayout.prototype._evaluateAnnotations = function() {
307   // Add the annotations to the point to which they belong.
308   // Make a map from (setName, xval) to annotation for quick lookups.
309   var i;
310   var annotations = {};
311   for (i = 0; i < this.annotations.length; i++) {
312     var a = this.annotations[i];
313     annotations[a.xval + "," + a.series] = a;
314   }
315
316   this.annotated_points = [];
317
318   // Exit the function early if there are no annotations.
319   if (!this.annotations || !this.annotations.length) {
320     return;
321   }
322
323   // TODO(antrob): loop through annotations not points.
324   for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
325     var points = this.points[setIdx];
326     for (i = 0; i < points.length; i++) {
327       var p = points[i];
328       var k = p.xval + "," + p.name;
329       if (k in annotations) {
330         p.annotation = annotations[k];
331         this.annotated_points.push(p);
332       }
333     }
334   }
335 };
336
337 /**
338  * Convenience function to remove all the data sets from a graph
339  */
340 DygraphLayout.prototype.removeAllDatasets = function() {
341   delete this.points;
342   delete this.setNames;
343   delete this.setPointsLengths;
344   delete this.setPointsOffsets;
345   this.points = [];
346   this.setNames = [];
347   this.setPointsLengths = [];
348   this.setPointsOffsets = [];
349 };