Fix lint warnings.
[dygraphs.git] / dygraph-layout.js
... / ...
CommitLineData
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 */
32var DygraphLayout = function(dygraph) {
33 this.dygraph_ = dygraph;
34 this.datasets = [];
35 this.setNames = [];
36 this.annotations = [];
37 this.yAxes_ = null;
38 this.points = null;
39
40 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
41 // yticks are outputs. Clean this up.
42 this.xTicks_ = null;
43 this.yTicks_ = null;
44};
45
46DygraphLayout.prototype.attr_ = function(name) {
47 return this.dygraph_.attr_(name);
48};
49
50DygraphLayout.prototype.addDataset = function(setname, set_xy) {
51 this.datasets.push(set_xy);
52 this.setNames.push(setname);
53};
54
55DygraphLayout.prototype.getPlotArea = function() {
56 return this.area_;
57};
58
59// Compute the box which the chart should be drawn in. This is the canvas's
60// box, less space needed for axis and chart labels.
61// NOTE: This should only be called by Dygraph.predraw_().
62DygraphLayout.prototype.computePlotArea = function() {
63 var area = {
64 // TODO(danvk): per-axis setting.
65 x: 0,
66 y: 0
67 };
68
69 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
70 area.h = this.dygraph_.height_;
71
72 // Let plugins reserve space.
73 var e = {
74 chart_div: this.dygraph_.graphDiv,
75 reserveSpaceLeft: function(px) {
76 var r = {
77 x: area.x,
78 y: area.y,
79 w: px,
80 h: area.h
81 };
82 area.x += px;
83 area.w -= px;
84 return r;
85 },
86 reserveSpaceRight: function(px) {
87 var r = {
88 x: area.x + area.w - px,
89 y: area.y,
90 w: px,
91 h: area.h
92 };
93 area.w -= px;
94 return r;
95 },
96 reserveSpaceTop: function(px) {
97 var r = {
98 x: area.x,
99 y: area.y,
100 w: area.w,
101 h: px
102 };
103 area.y += px;
104 area.h -= px;
105 return r;
106 },
107 reserveSpaceBottom: function(px) {
108 var r = {
109 x: area.x,
110 y: area.y + area.h - px,
111 w: area.w,
112 h: px
113 };
114 area.h -= px;
115 return r;
116 },
117 chartRect: function() {
118 return {x:area.x, y:area.y, w:area.w, h:area.h};
119 }
120 };
121 this.dygraph_.cascadeEvents_('layout', e);
122
123 this.area_ = area;
124};
125
126DygraphLayout.prototype.setAnnotations = function(ann) {
127 // The Dygraph object's annotations aren't parsed. We parse them here and
128 // save a copy. If there is no parser, then the user must be using raw format.
129 this.annotations = [];
130 var parse = this.attr_('xValueParser') || function(x) { return x; };
131 for (var i = 0; i < ann.length; i++) {
132 var a = {};
133 if (!ann[i].xval && !ann[i].x) {
134 this.dygraph_.error("Annotations must have an 'x' property");
135 return;
136 }
137 if (ann[i].icon &&
138 !(ann[i].hasOwnProperty('width') &&
139 ann[i].hasOwnProperty('height'))) {
140 this.dygraph_.error("Must set width and height when setting " +
141 "annotation.icon property");
142 return;
143 }
144 Dygraph.update(a, ann[i]);
145 if (!a.xval) a.xval = parse(a.x);
146 this.annotations.push(a);
147 }
148};
149
150DygraphLayout.prototype.setXTicks = function(xTicks) {
151 this.xTicks_ = xTicks;
152};
153
154// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
155DygraphLayout.prototype.setYAxes = function (yAxes) {
156 this.yAxes_ = yAxes;
157};
158
159DygraphLayout.prototype.setDateWindow = function(dateWindow) {
160 this.dateWindow_ = dateWindow;
161};
162
163DygraphLayout.prototype.evaluate = function() {
164 this._evaluateLimits();
165 this._evaluateLineCharts();
166 this._evaluateLineTicks();
167 this._evaluateAnnotations();
168};
169
170DygraphLayout.prototype._evaluateLimits = function() {
171 this.minxval = this.maxxval = null;
172 if (this.dateWindow_) {
173 this.minxval = this.dateWindow_[0];
174 this.maxxval = this.dateWindow_[1];
175 } else {
176 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
177 var series = this.datasets[setIdx];
178 if (series.length > 1) {
179 var x1 = series[0][0];
180 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
181
182 var x2 = series[series.length - 1][0];
183 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
184 }
185 }
186 }
187 this.xrange = this.maxxval - this.minxval;
188 this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);
189
190 for (var i = 0; i < this.yAxes_.length; i++) {
191 var axis = this.yAxes_[i];
192 axis.minyval = axis.computedValueRange[0];
193 axis.maxyval = axis.computedValueRange[1];
194 axis.yrange = axis.maxyval - axis.minyval;
195 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
196
197 if (axis.g.attr_("logscale")) {
198 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
199 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
200 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
201 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
202 ' can\'t be displayed in log scale for range [' +
203 axis.minyval + ' - ' + axis.maxyval + ']');
204 }
205 }
206 }
207};
208
209DygraphLayout._calcYNormal = function(axis, value, logscale) {
210 if (logscale) {
211 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
212 } else {
213 return 1.0 - ((value - axis.minyval) * axis.yscale);
214 }
215};
216
217DygraphLayout.prototype._evaluateLineCharts = function() {
218 var connectSeparated = this.attr_('connectSeparatedPoints');
219
220 // series index -> point index in series -> |point| structure
221 this.points = new Array(this.datasets.length);
222
223 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
224 // on chrome+linux, they are 6 times more expensive than iterating through the
225 // points and drawing the lines. The brunt of the cost comes from allocating
226 // the |point| structures.
227 for (var setIdx = 0; setIdx < this.datasets.length; setIdx++) {
228 var dataset = this.datasets[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 // Preallocating the size of points reduces reallocations, and therefore,
235 // calls to collect garbage.
236 var seriesPoints = new Array(dataset.length);
237
238 for (var j = 0; j < dataset.length; j++) {
239 var item = dataset[j];
240 var xValue = DygraphLayout.parseFloat_(item[0]);
241 var yValue = DygraphLayout.parseFloat_(item[1]);
242
243 // Range from 0-1 where 0 represents left and 1 represents right.
244 var xNormal = (xValue - this.minxval) * this.xscale;
245 // Range from 0-1 where 0 represents top and 1 represents bottom
246 var yNormal = DygraphLayout._calcYNormal(axis, yValue, logscale);
247
248 // TODO(danvk): drop the point in this case, don't null it.
249 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
250 if (connectSeparated && item[1] === null) {
251 yValue = null;
252 }
253 seriesPoints[j] = {
254 x: xNormal,
255 y: yNormal,
256 xval: xValue,
257 yval: yValue,
258 name: setName // TODO(danvk): is this really necessary?
259 };
260 }
261
262 this.points[setIdx] = seriesPoints;
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 */
270DygraphLayout.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
280DygraphLayout.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
307/**
308 * Behaves the same way as PlotKit.Layout, but also copies the errors
309 * @private
310 */
311DygraphLayout.prototype.evaluateWithError = function() {
312 this.evaluate();
313 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
314
315 // Copy over the error terms
316 var i = 0; // index in this.points
317 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
318 var points = this.points[setIdx];
319 var j = 0;
320 var dataset = this.datasets[setIdx];
321 var setName = this.setNames[setIdx];
322 var axis = this.dygraph_.axisPropertiesForSeries(setName);
323 // TODO (konigsberg): use optionsForAxis instead.
324 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
325
326 for (j = 0; j < dataset.length; j++, i++) {
327 var item = dataset[j];
328 var xv = DygraphLayout.parseFloat_(item[0]);
329 var yv = DygraphLayout.parseFloat_(item[1]);
330
331 if (xv == points[j].xval &&
332 yv == points[j].yval) {
333 var errorMinus = DygraphLayout.parseFloat_(item[2]);
334 var errorPlus = DygraphLayout.parseFloat_(item[3]);
335
336 var yv_minus = yv - errorMinus;
337 var yv_plus = yv + errorPlus;
338 points[j].y_top = DygraphLayout._calcYNormal(axis, yv_minus, logscale);
339 points[j].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus, logscale);
340 }
341 }
342 }
343};
344
345DygraphLayout.prototype._evaluateAnnotations = function() {
346 // Add the annotations to the point to which they belong.
347 // Make a map from (setName, xval) to annotation for quick lookups.
348 var i;
349 var annotations = {};
350 for (i = 0; i < this.annotations.length; i++) {
351 var a = this.annotations[i];
352 annotations[a.xval + "," + a.series] = a;
353 }
354
355 this.annotated_points = [];
356
357 // Exit the function early if there are no annotations.
358 if (!this.annotations || !this.annotations.length) {
359 return;
360 }
361
362 // TODO(antrob): loop through annotations not points.
363 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
364 var points = this.points[setIdx];
365 for (i = 0; i < points.length; i++) {
366 var p = points[i];
367 var k = p.xval + "," + p.name;
368 if (k in annotations) {
369 p.annotation = annotations[k];
370 this.annotated_points.push(p);
371 }
372 }
373 }
374};
375
376/**
377 * Convenience function to remove all the data sets from a graph
378 */
379DygraphLayout.prototype.removeAllDatasets = function() {
380 delete this.datasets;
381 delete this.setNames;
382 delete this.setPointsLengths;
383 delete this.setPointsOffsets;
384 this.datasets = [];
385 this.setNames = [];
386 this.setPointsLengths = [];
387 this.setPointsOffsets = [];
388};
389
390/**
391 * Return a copy of the point at the indicated index, with its yval unstacked.
392 * @param int index of point in layout_.points
393 */
394DygraphLayout.prototype.unstackPointAtIndex = function(setIdx, row) {
395 var point = this.points[setIdx][row];
396 // If the point is missing, no unstacking is necessary
397 if (!point.yval) {
398 return point;
399 }
400
401 // Clone the point since we modify it
402 var unstackedPoint = {};
403 for (var pt in point) {
404 unstackedPoint[pt] = point[pt];
405 }
406
407 if (!this.attr_("stackedGraph")) {
408 return unstackedPoint;
409 }
410
411 // The unstacked yval is equal to the current yval minus the yval of the
412 // next point at the same xval.
413 if (setIdx == this.points.length - 1) {
414 // We're the last series, so no unstacking is necessary.
415 return unstackedPoint;
416 }
417
418 var points = this.points[setIdx + 1];
419 if (points[row].xval == point.xval && // should always be true?
420 points[row].yval) {
421 unstackedPoint.yval -= points[row].yval;
422 }
423
424 return unstackedPoint;
425};