negative test
[dygraphs.git] / dygraph.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
5 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
6 * string. Dygraph can handle multiple series with or without error bars. The
7 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
8 * <canvas> tag, so it only works in FF1.5+.
9 * @author danvdk@gmail.com (Dan Vanderkam)
10
11 Usage:
12 <div id="graphdiv" style="width:800px; height:500px;"></div>
13 <script type="text/javascript">
285a6bda
DV
14 new Dygraph(document.getElementById("graphdiv"),
15 "datafile.csv", // CSV file with headers
16 { }); // options
6a1aa64f
DV
17 </script>
18
19 The CSV file is of the form
20
285a6bda 21 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
22 YYYYMMDD,A1,B1,C1
23 YYYYMMDD,A2,B2,C2
24
6a1aa64f
DV
25 If the 'errorBars' option is set in the constructor, the input should be of
26 the form
27
285a6bda 28 Date,SeriesA,SeriesB,...
6a1aa64f
DV
29 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
30 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
31
32 If the 'fractions' option is set, the input should be of the form:
33
285a6bda 34 Date,SeriesA,SeriesB,...
6a1aa64f
DV
35 YYYYMMDD,A1/B1,A2/B2,...
36 YYYYMMDD,A1/B1,A2/B2,...
37
38 And error bars will be calculated automatically using a binomial distribution.
39
285a6bda 40 For further documentation and examples, see http://www.danvk.org/dygraphs
6a1aa64f
DV
41
42 */
43
44/**
45 * An interactive, zoomable graph
46 * @param {String | Function} file A file containing CSV data or a function that
47 * returns this data. The expected format for each line is
48 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
49 * YYYYMMDD,val1,stddev1,val2,stddev2,...
6a1aa64f
DV
50 * @param {Object} attrs Various other attributes, e.g. errorBars determines
51 * whether the input data contains error ranges.
52 */
285a6bda
DV
53Dygraph = function(div, data, opts) {
54 if (arguments.length > 0) {
55 if (arguments.length == 4) {
56 // Old versions of dygraphs took in the series labels as a constructor
57 // parameter. This doesn't make sense anymore, but it's easy to continue
58 // to support this usage.
59 this.warn("Using deprecated four-argument dygraph constructor");
60 this.__old_init__(div, data, arguments[2], arguments[3]);
61 } else {
62 this.__init__(div, data, opts);
63 }
64 }
6a1aa64f
DV
65};
66
285a6bda
DV
67Dygraph.NAME = "Dygraph";
68Dygraph.VERSION = "1.2";
69Dygraph.__repr__ = function() {
6a1aa64f
DV
70 return "[" + this.NAME + " " + this.VERSION + "]";
71};
285a6bda 72Dygraph.toString = function() {
6a1aa64f
DV
73 return this.__repr__();
74};
75
76// Various default values
285a6bda
DV
77Dygraph.DEFAULT_ROLL_PERIOD = 1;
78Dygraph.DEFAULT_WIDTH = 480;
79Dygraph.DEFAULT_HEIGHT = 320;
80Dygraph.AXIS_LINE_WIDTH = 0.3;
6a1aa64f 81
8e4a6af3 82// Default attribute values.
285a6bda 83Dygraph.DEFAULT_ATTRS = {
a9fc39ab 84 highlightCircleSize: 3,
8e4a6af3 85 pixelsPerXLabel: 60,
c6336f04 86 pixelsPerYLabel: 30,
285a6bda 87
8e4a6af3
DV
88 labelsDivWidth: 250,
89 labelsDivStyles: {
90 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
91 },
92 labelsSeparateLines: false,
93 labelsKMB: false,
94
95 strokeWidth: 1.0,
8e4a6af3 96
8846615a
DV
97 axisTickSize: 3,
98 axisLabelFontSize: 14,
99 xAxisLabelWidth: 50,
100 yAxisLabelWidth: 50,
101 rightGap: 5,
285a6bda
DV
102
103 showRoller: false,
104 xValueFormatter: Dygraph.dateString_,
105 xValueParser: Dygraph.dateParser,
106 xTicker: Dygraph.dateTicker,
107
108 sigma: 2.0,
109 errorBars: false,
110 fractions: false,
111 wilsonInterval: true, // only relevant if fractions is true
112 customBars: false
113};
114
115// Various logging levels.
116Dygraph.DEBUG = 1;
117Dygraph.INFO = 2;
118Dygraph.WARNING = 3;
119Dygraph.ERROR = 3;
120
121Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
122 // Labels is no longer a constructor parameter, since it's typically set
123 // directly from the data source. It also conains a name for the x-axis,
124 // which the previous constructor form did not.
125 if (labels != null) {
126 var new_labels = ["Date"];
127 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
128 MochiKit.Base.update(attrs, { 'labels': new_labels });
129 }
130 this.__init__(div, file, attrs);
8e4a6af3
DV
131};
132
6a1aa64f 133/**
285a6bda 134 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
6a1aa64f
DV
135 * and interaction &lt;canvas&gt; inside of it. See the constructor for details
136 * on the parameters.
137 * @param {String | Function} file Source data
138 * @param {Array.<String>} labels Names of the data series
139 * @param {Object} attrs Miscellaneous other options
140 * @private
141 */
285a6bda
DV
142Dygraph.prototype.__init__ = function(div, file, attrs) {
143 // Support two-argument constructor
144 if (attrs == null) { attrs = {}; }
145
6a1aa64f 146 // Copy the important bits into the object
32988383 147 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 148 this.maindiv_ = div;
6a1aa64f 149 this.file_ = file;
285a6bda 150 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 151 this.previousVerticalX_ = -1;
6a1aa64f 152 this.fractions_ = attrs.fractions || false;
6a1aa64f
DV
153 this.dateWindow_ = attrs.dateWindow || null;
154 this.valueRange_ = attrs.valueRange || null;
6a1aa64f
DV
155 this.wilsonInterval_ = attrs.wilsonInterval || true;
156 this.customBars_ = attrs.customBars || false;
8e4a6af3 157
f7d6278e
DV
158 // Clear the div. This ensure that, if multiple dygraphs are passed the same
159 // div, then only one will be drawn.
160 div.innerHTML = "";
161
285a6bda
DV
162 // If the div isn't already sized then give it a default size.
163 if (div.style.width == '') {
164 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
165 }
166 if (div.style.height == '') {
167 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
32988383 168 }
285a6bda
DV
169 this.width_ = parseInt(div.style.width, 10);
170 this.height_ = parseInt(div.style.height, 10);
32988383 171
285a6bda
DV
172 // Dygraphs has many options, some of which interact with one another.
173 // To keep track of everything, we maintain two sets of options:
174 //
175 // this.user_attrs_ only options explicitly set by the user.
176 // this.attrs_ defaults, options derived from user_attrs_, data.
177 //
178 // Options are then accessed this.attr_('attr'), which first looks at
179 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
180 // defaults without overriding behavior that the user specifically asks for.
181 this.user_attrs_ = {};
182 MochiKit.Base.update(this.user_attrs_, attrs);
6a1aa64f 183
285a6bda
DV
184 this.attrs_ = {};
185 MochiKit.Base.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 186
285a6bda
DV
187 // Make a note of whether labels will be pulled from the CSV file.
188 this.labelsFromCSV_ = (this.attr_("labels") == null);
6a1aa64f
DV
189
190 // Create the containing DIV and other interactive elements
191 this.createInterface_();
192
193 // Create the PlotKit grapher
285a6bda
DV
194 // TODO(danvk): why does the Layout need its own set of options?
195 this.layoutOptions_ = { 'errorBars': (this.attr_("errorBars") ||
196 this.customBars_),
6a1aa64f 197 'xOriginIsZero': false };
285a6bda
DV
198 MochiKit.Base.update(this.layoutOptions_, this.attrs_);
199 MochiKit.Base.update(this.layoutOptions_, this.user_attrs_);
6a1aa64f 200
285a6bda 201 this.layout_ = new DygraphLayout(this.layoutOptions_);
6a1aa64f 202
285a6bda 203 // TODO(danvk): why does the Renderer need its own set of options?
6a1aa64f
DV
204 this.renderOptions_ = { colorScheme: this.colors_,
205 strokeColor: null,
285a6bda
DV
206 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
207 MochiKit.Base.update(this.renderOptions_, this.attrs_);
208 MochiKit.Base.update(this.renderOptions_, this.user_attrs_);
209 this.plotter_ = new DygraphCanvasRenderer(this.hidden_, this.layout_,
210 this.renderOptions_);
6a1aa64f
DV
211
212 this.createStatusMessage_();
213 this.createRollInterface_();
214 this.createDragInterface_();
215
738fc797
DV
216 // connect(window, 'onload', this, function(e) { this.start_(); });
217 this.start_();
6a1aa64f
DV
218};
219
285a6bda
DV
220Dygraph.prototype.attr_ = function(name) {
221 if (typeof(this.user_attrs_[name]) != 'undefined') {
222 return this.user_attrs_[name];
223 } else if (typeof(this.attrs_[name]) != 'undefined') {
224 return this.attrs_[name];
225 } else {
226 return null;
227 }
228};
229
230// TODO(danvk): any way I can get the line numbers to be this.warn call?
231Dygraph.prototype.log = function(severity, message) {
232 if (typeof(console) != 'undefined') {
233 switch (severity) {
234 case Dygraph.DEBUG:
235 console.debug('dygraphs: ' + message);
236 break;
237 case Dygraph.INFO:
238 console.info('dygraphs: ' + message);
239 break;
240 case Dygraph.WARNING:
241 console.warn('dygraphs: ' + message);
242 break;
243 case Dygraph.ERROR:
244 console.error('dygraphs: ' + message);
245 break;
246 }
247 }
248}
249Dygraph.prototype.info = function(message) {
250 this.log(Dygraph.INFO, message);
251}
252Dygraph.prototype.warn = function(message) {
253 this.log(Dygraph.WARNING, message);
254}
255Dygraph.prototype.error = function(message) {
256 this.log(Dygraph.ERROR, message);
257}
258
6a1aa64f
DV
259/**
260 * Returns the current rolling period, as set by the user or an option.
261 * @return {Number} The number of days in the rolling window
262 */
285a6bda 263Dygraph.prototype.rollPeriod = function() {
6a1aa64f
DV
264 return this.rollPeriod_;
265}
266
267/**
285a6bda 268 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f
DV
269 * display the current point, and a textbox to adjust the rolling average
270 * period.
271 * @private
272 */
285a6bda 273Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
274 // Create the all-enclosing graph div
275 var enclosing = this.maindiv_;
276
277 this.graphDiv = MochiKit.DOM.DIV( { style: { 'width': this.width_ + "px",
278 'height': this.height_ + "px"
279 }});
280 appendChildNodes(enclosing, this.graphDiv);
281
282 // Create the canvas to store
8846615a
DV
283 // We need to subtract out some space for the x- and y-axis labels.
284 // For the x-axis:
285 // - remove from height: (axisTickSize + height of tick label)
286 // height of tick label == axisLabelFontSize?
287 // - remove from width: axisLabelWidth / 2 (maybe on both ends)
288 // For the y-axis:
289 // - remove axisLabelFontSize from the top
290 // - remove axisTickSize from the left
291
6a1aa64f
DV
292 var canvas = MochiKit.DOM.CANVAS;
293 this.canvas_ = canvas( { style: { 'position': 'absolute' },
294 width: this.width_,
8846615a
DV
295 height: this.height_
296 });
6a1aa64f
DV
297 appendChildNodes(this.graphDiv, this.canvas_);
298
299 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
300 connect(this.hidden_, 'onmousemove', this, function(e) { this.mouseMove_(e) });
301 connect(this.hidden_, 'onmouseout', this, function(e) { this.mouseOut_(e) });
302}
303
304/**
305 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
285a6bda 306 * this particular canvas. All Dygraph work is done on this.canvas_.
8846615a 307 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
308 * @return {Object} The newly-created canvas
309 * @private
310 */
285a6bda 311Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
6a1aa64f
DV
312 var h = document.createElement("canvas");
313 h.style.position = "absolute";
314 h.style.top = canvas.style.top;
315 h.style.left = canvas.style.left;
316 h.width = this.width_;
317 h.height = this.height_;
318 MochiKit.DOM.appendChildNodes(this.graphDiv, h);
319 return h;
320};
321
322/**
323 * Generate a set of distinct colors for the data series. This is done with a
324 * color wheel. Saturation/Value are customizable, and the hue is
325 * equally-spaced around the color wheel. If a custom set of colors is
326 * specified, that is used instead.
6a1aa64f
DV
327 * @private
328 */
285a6bda
DV
329Dygraph.prototype.setColors_ = function() {
330 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
331 // away with this.renderOptions_.
332 var num = this.attr_("labels").length - 1;
6a1aa64f 333 this.colors_ = [];
285a6bda
DV
334 var colors = this.attr_('colors');
335 if (!colors) {
336 var sat = this.attr_('colorSaturation') || 1.0;
337 var val = this.attr_('colorValue') || 0.5;
6a1aa64f
DV
338 for (var i = 1; i <= num; i++) {
339 var hue = (1.0*i/(1+num));
340 this.colors_.push( MochiKit.Color.Color.fromHSV(hue, sat, val) );
341 }
342 } else {
343 for (var i = 0; i < num; i++) {
285a6bda 344 var colorStr = colors[i % colors.length];
6a1aa64f
DV
345 this.colors_.push( MochiKit.Color.Color.fromString(colorStr) );
346 }
347 }
285a6bda
DV
348
349 // TODO(danvk): update this w/r/t/ the new options system.
350 this.renderOptions_.colorScheme = this.colors_;
351 MochiKit.Base.update(this.plotter_.options, this.renderOptions_);
352 MochiKit.Base.update(this.layoutOptions_, this.user_attrs_);
353 MochiKit.Base.update(this.layoutOptions_, this.attrs_);
6a1aa64f
DV
354}
355
356/**
357 * Create the div that contains information on the selected point(s)
358 * This goes in the top right of the canvas, unless an external div has already
359 * been specified.
360 * @private
361 */
285a6bda
DV
362Dygraph.prototype.createStatusMessage_ = function(){
363 if (!this.attr_("labelsDiv")) {
364 var divWidth = this.attr_('labelsDivWidth');
6a1aa64f
DV
365 var messagestyle = { "style": {
366 "position": "absolute",
367 "fontSize": "14px",
368 "zIndex": 10,
369 "width": divWidth + "px",
370 "top": "0px",
8846615a 371 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
372 "background": "white",
373 "textAlign": "left",
374 "overflow": "hidden"}};
285a6bda
DV
375 MochiKit.Base.update(messagestyle["style"], this.attr_('labelsDivStyles'));
376 var div = MochiKit.DOM.DIV(messagestyle);
377 MochiKit.DOM.appendChildNodes(this.graphDiv, div);
378 this.attrs_.labelsDiv = div;
6a1aa64f
DV
379 }
380};
381
382/**
383 * Create the text box to adjust the averaging period
384 * @return {Object} The newly-created text box
385 * @private
386 */
285a6bda 387Dygraph.prototype.createRollInterface_ = function() {
285a6bda 388 var display = this.attr_('showRoller') ? "block" : "none";
6a1aa64f
DV
389 var textAttr = { "type": "text",
390 "size": "2",
391 "value": this.rollPeriod_,
392 "style": { "position": "absolute",
393 "zIndex": 10,
8846615a
DV
394 "top": (this.plotter_.area.h - 25) + "px",
395 "left": (this.plotter_.area.x + 1) + "px",
738fc797 396 "display": display }
6a1aa64f
DV
397 };
398 var roller = MochiKit.DOM.INPUT(textAttr);
399 var pa = this.graphDiv;
400 MochiKit.DOM.appendChildNodes(pa, roller);
401 connect(roller, 'onchange', this,
402 function() { this.adjustRoll(roller.value); });
403 return roller;
404}
405
406/**
407 * Set up all the mouse handlers needed to capture dragging behavior for zoom
408 * events. Uses MochiKit.Signal to attach all the event handlers.
409 * @private
410 */
285a6bda 411Dygraph.prototype.createDragInterface_ = function() {
6a1aa64f
DV
412 var self = this;
413
414 // Tracks whether the mouse is down right now
415 var mouseDown = false;
416 var dragStartX = null;
417 var dragStartY = null;
418 var dragEndX = null;
419 var dragEndY = null;
420 var prevEndX = null;
421
422 // Utility function to convert page-wide coordinates to canvas coords
67e650dc
DV
423 var px = 0;
424 var py = 0;
6a1aa64f
DV
425 var getX = function(e) { return e.mouse().page.x - px };
426 var getY = function(e) { return e.mouse().page.y - py };
427
428 // Draw zoom rectangles when the mouse is down and the user moves around
429 connect(this.hidden_, 'onmousemove', function(event) {
430 if (mouseDown) {
431 dragEndX = getX(event);
432 dragEndY = getY(event);
433
434 self.drawZoomRect_(dragStartX, dragEndX, prevEndX);
435 prevEndX = dragEndX;
436 }
437 });
438
439 // Track the beginning of drag events
440 connect(this.hidden_, 'onmousedown', function(event) {
441 mouseDown = true;
67e650dc
DV
442 px = PlotKit.Base.findPosX(self.canvas_);
443 py = PlotKit.Base.findPosY(self.canvas_);
6a1aa64f
DV
444 dragStartX = getX(event);
445 dragStartY = getY(event);
446 });
447
448 // If the user releases the mouse button during a drag, but not over the
449 // canvas, then it doesn't count as a zooming action.
450 connect(document, 'onmouseup', this, function(event) {
451 if (mouseDown) {
452 mouseDown = false;
453 dragStartX = null;
454 dragStartY = null;
455 }
456 });
457
458 // Temporarily cancel the dragging event when the mouse leaves the graph
459 connect(this.hidden_, 'onmouseout', this, function(event) {
460 if (mouseDown) {
461 dragEndX = null;
462 dragEndY = null;
463 }
464 });
465
466 // If the mouse is released on the canvas during a drag event, then it's a
467 // zoom. Only do the zoom if it's over a large enough area (>= 10 pixels)
468 connect(this.hidden_, 'onmouseup', this, function(event) {
469 if (mouseDown) {
470 mouseDown = false;
471 dragEndX = getX(event);
472 dragEndY = getY(event);
473 var regionWidth = Math.abs(dragEndX - dragStartX);
474 var regionHeight = Math.abs(dragEndY - dragStartY);
475
476 if (regionWidth < 2 && regionHeight < 2 &&
285a6bda 477 self.attr_('clickCallback') != null &&
6a1aa64f 478 self.lastx_ != undefined) {
285a6bda
DV
479 // TODO(danvk): pass along more info about the point.
480 self.attr_('clickCallback')(event, new Date(self.lastx_));
6a1aa64f
DV
481 }
482
483 if (regionWidth >= 10) {
484 self.doZoom_(Math.min(dragStartX, dragEndX),
485 Math.max(dragStartX, dragEndX));
486 } else {
487 self.canvas_.getContext("2d").clearRect(0, 0,
488 self.canvas_.width,
489 self.canvas_.height);
490 }
491
492 dragStartX = null;
493 dragStartY = null;
494 }
495 });
496
497 // Double-clicking zooms back out
498 connect(this.hidden_, 'ondblclick', this, function(event) {
499 self.dateWindow_ = null;
500 self.drawGraph_(self.rawData_);
501 var minDate = self.rawData_[0][0];
502 var maxDate = self.rawData_[self.rawData_.length - 1][0];
285a6bda
DV
503 if (self.attr_("zoomCallback")) {
504 self.attr_("zoomCallback")(minDate, maxDate);
67e650dc 505 }
6a1aa64f
DV
506 });
507};
508
509/**
510 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
511 * up any previous zoom rectangles that were drawn. This could be optimized to
512 * avoid extra redrawing, but it's tricky to avoid interactions with the status
513 * dots.
514 * @param {Number} startX The X position where the drag started, in canvas
515 * coordinates.
516 * @param {Number} endX The current X position of the drag, in canvas coords.
517 * @param {Number} prevEndX The value of endX on the previous call to this
518 * function. Used to avoid excess redrawing
519 * @private
520 */
285a6bda 521Dygraph.prototype.drawZoomRect_ = function(startX, endX, prevEndX) {
6a1aa64f
DV
522 var ctx = this.canvas_.getContext("2d");
523
524 // Clean up from the previous rect if necessary
525 if (prevEndX) {
526 ctx.clearRect(Math.min(startX, prevEndX), 0,
527 Math.abs(startX - prevEndX), this.height_);
528 }
529
530 // Draw a light-grey rectangle to show the new viewing area
531 if (endX && startX) {
532 ctx.fillStyle = "rgba(128,128,128,0.33)";
533 ctx.fillRect(Math.min(startX, endX), 0,
534 Math.abs(endX - startX), this.height_);
535 }
536};
537
538/**
539 * Zoom to something containing [lowX, highX]. These are pixel coordinates
540 * in the canvas. The exact zoom window may be slightly larger if there are no
541 * data points near lowX or highX. This function redraws the graph.
542 * @param {Number} lowX The leftmost pixel value that should be visible.
543 * @param {Number} highX The rightmost pixel value that should be visible.
544 * @private
545 */
285a6bda 546Dygraph.prototype.doZoom_ = function(lowX, highX) {
6a1aa64f
DV
547 // Find the earliest and latest dates contained in this canvasx range.
548 var points = this.layout_.points;
549 var minDate = null;
550 var maxDate = null;
551 // Find the nearest [minDate, maxDate] that contains [lowX, highX]
552 for (var i = 0; i < points.length; i++) {
553 var cx = points[i].canvasx;
554 var x = points[i].xval;
555 if (cx < lowX && (minDate == null || x > minDate)) minDate = x;
556 if (cx > highX && (maxDate == null || x < maxDate)) maxDate = x;
557 }
558 // Use the extremes if either is missing
559 if (minDate == null) minDate = points[0].xval;
560 if (maxDate == null) maxDate = points[points.length-1].xval;
561
562 this.dateWindow_ = [minDate, maxDate];
563 this.drawGraph_(this.rawData_);
285a6bda
DV
564 if (this.attr_("zoomCallback")) {
565 this.attr_("zoomCallback")(minDate, maxDate);
67e650dc 566 }
6a1aa64f
DV
567};
568
569/**
570 * When the mouse moves in the canvas, display information about a nearby data
571 * point and draw dots over those points in the data series. This function
572 * takes care of cleanup of previously-drawn dots.
573 * @param {Object} event The mousemove event from the browser.
574 * @private
575 */
285a6bda 576Dygraph.prototype.mouseMove_ = function(event) {
6a1aa64f
DV
577 var canvasx = event.mouse().page.x - PlotKit.Base.findPosX(this.hidden_);
578 var points = this.layout_.points;
579
580 var lastx = -1;
581 var lasty = -1;
582
583 // Loop through all the points and find the date nearest to our current
584 // location.
585 var minDist = 1e+100;
586 var idx = -1;
587 for (var i = 0; i < points.length; i++) {
588 var dist = Math.abs(points[i].canvasx - canvasx);
589 if (dist > minDist) break;
590 minDist = dist;
591 idx = i;
592 }
593 if (idx >= 0) lastx = points[idx].xval;
594 // Check that you can really highlight the last day's data
595 if (canvasx > points[points.length-1].canvasx)
596 lastx = points[points.length-1].xval;
597
598 // Extract the points we've selected
599 var selPoints = [];
600 for (var i = 0; i < points.length; i++) {
601 if (points[i].xval == lastx) {
602 selPoints.push(points[i]);
603 }
604 }
605
606 // Clear the previously drawn vertical, if there is one
285a6bda 607 var circleSize = this.attr_('highlightCircleSize');
6a1aa64f
DV
608 var ctx = this.canvas_.getContext("2d");
609 if (this.previousVerticalX_ >= 0) {
610 var px = this.previousVerticalX_;
611 ctx.clearRect(px - circleSize - 1, 0, 2 * circleSize + 2, this.height_);
612 }
613
614 if (selPoints.length > 0) {
615 var canvasx = selPoints[0].canvasx;
616
617 // Set the status message to indicate the selected point(s)
285a6bda 618 var replace = this.attr_('xValueFormatter')(lastx, this) + ":";
6a1aa64f
DV
619 var clen = this.colors_.length;
620 for (var i = 0; i < selPoints.length; i++) {
285a6bda 621 if (this.attr_("labelsSeparateLines")) {
6a1aa64f
DV
622 replace += "<br/>";
623 }
624 var point = selPoints[i];
625 replace += " <b><font color='" + this.colors_[i%clen].toHexString() + "'>"
626 + point.name + "</font></b>:"
627 + this.round_(point.yval, 2);
628 }
285a6bda 629 this.attr_("labelsDiv").innerHTML = replace;
6a1aa64f
DV
630
631 // Save last x position for callbacks.
632 this.lastx_ = lastx;
633
634 // Draw colored circles over the center of each selected point
635 ctx.save()
636 for (var i = 0; i < selPoints.length; i++) {
637 ctx.beginPath();
638 ctx.fillStyle = this.colors_[i%clen].toRGBString();
639 ctx.arc(canvasx, selPoints[i%clen].canvasy, circleSize, 0, 360, false);
640 ctx.fill();
641 }
642 ctx.restore();
643
644 this.previousVerticalX_ = canvasx;
645 }
646};
647
648/**
649 * The mouse has left the canvas. Clear out whatever artifacts remain
650 * @param {Object} event the mouseout event from the browser.
651 * @private
652 */
285a6bda 653Dygraph.prototype.mouseOut_ = function(event) {
6a1aa64f
DV
654 // Get rid of the overlay data
655 var ctx = this.canvas_.getContext("2d");
656 ctx.clearRect(0, 0, this.width_, this.height_);
285a6bda 657 this.attr_("labelsDiv").innerHTML = "";
6a1aa64f
DV
658};
659
285a6bda 660Dygraph.zeropad = function(x) {
32988383
DV
661 if (x < 10) return "0" + x; else return "" + x;
662}
663
6a1aa64f 664/**
6b8e33dd
DV
665 * Return a string version of the hours, minutes and seconds portion of a date.
666 * @param {Number} date The JavaScript date (ms since epoch)
667 * @return {String} A time of the form "HH:MM:SS"
668 * @private
669 */
285a6bda
DV
670Dygraph.prototype.hmsString_ = function(date) {
671 var zeropad = Dygraph.zeropad;
6b8e33dd
DV
672 var d = new Date(date);
673 if (d.getSeconds()) {
674 return zeropad(d.getHours()) + ":" +
675 zeropad(d.getMinutes()) + ":" +
676 zeropad(d.getSeconds());
677 } else if (d.getMinutes()) {
678 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
679 } else {
680 return zeropad(d.getHours());
681 }
682}
683
684/**
6a1aa64f
DV
685 * Convert a JS date (millis since epoch) to YYYY/MM/DD
686 * @param {Number} date The JavaScript date (ms since epoch)
687 * @return {String} A date of the form "YYYY/MM/DD"
688 * @private
285a6bda 689 * TODO(danvk): why is this part of the prototype?
6a1aa64f 690 */
285a6bda
DV
691Dygraph.dateString_ = function(date, self) {
692 var zeropad = Dygraph.zeropad;
6a1aa64f
DV
693 var d = new Date(date);
694
695 // Get the year:
696 var year = "" + d.getFullYear();
697 // Get a 0 padded month string
6b8e33dd 698 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
6a1aa64f 699 // Get a 0 padded day string
6b8e33dd 700 var day = zeropad(d.getDate());
6a1aa64f 701
6b8e33dd
DV
702 var ret = "";
703 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
285a6bda 704 if (frac) ret = " " + self.hmsString_(date);
6b8e33dd
DV
705
706 return year + "/" + month + "/" + day + ret;
6a1aa64f
DV
707};
708
709/**
710 * Round a number to the specified number of digits past the decimal point.
711 * @param {Number} num The number to round
712 * @param {Number} places The number of decimals to which to round
713 * @return {Number} The rounded number
714 * @private
715 */
285a6bda 716Dygraph.prototype.round_ = function(num, places) {
6a1aa64f
DV
717 var shift = Math.pow(10, places);
718 return Math.round(num * shift)/shift;
719};
720
721/**
722 * Fires when there's data available to be graphed.
723 * @param {String} data Raw CSV data to be plotted
724 * @private
725 */
285a6bda 726Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f
DV
727 this.rawData_ = this.parseCSV_(data);
728 this.drawGraph_(this.rawData_);
729};
730
285a6bda 731Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 732 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 733Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
734
735/**
736 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
737 * @private
738 */
285a6bda 739Dygraph.prototype.addXTicks_ = function() {
6a1aa64f
DV
740 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
741 var startDate, endDate;
742 if (this.dateWindow_) {
743 startDate = this.dateWindow_[0];
744 endDate = this.dateWindow_[1];
745 } else {
746 startDate = this.rawData_[0][0];
747 endDate = this.rawData_[this.rawData_.length - 1][0];
748 }
749
285a6bda 750 var xTicks = this.attr_('xTicker')(startDate, endDate, this);
6a1aa64f 751 this.layout_.updateOptions({xTicks: xTicks});
32988383
DV
752};
753
754// Time granularity enumeration
285a6bda
DV
755Dygraph.SECONDLY = 0;
756Dygraph.TEN_SECONDLY = 1;
757Dygraph.THIRTY_SECONDLY = 2;
758Dygraph.MINUTELY = 3;
759Dygraph.TEN_MINUTELY = 4;
760Dygraph.THIRTY_MINUTELY = 5;
761Dygraph.HOURLY = 6;
762Dygraph.SIX_HOURLY = 7;
763Dygraph.DAILY = 8;
764Dygraph.WEEKLY = 9;
765Dygraph.MONTHLY = 10;
766Dygraph.QUARTERLY = 11;
767Dygraph.BIANNUAL = 12;
768Dygraph.ANNUAL = 13;
769Dygraph.DECADAL = 14;
770Dygraph.NUM_GRANULARITIES = 15;
771
772Dygraph.SHORT_SPACINGS = [];
773Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
774Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
775Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
776Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
777Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
778Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
779Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
780Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600 * 6;
781Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
782Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383
DV
783
784// NumXTicks()
785//
786// If we used this time granularity, how many ticks would there be?
787// This is only an approximation, but it's generally good enough.
788//
285a6bda
DV
789Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
790 if (granularity < Dygraph.MONTHLY) {
32988383 791 // Generate one tick mark for every fixed interval of time.
285a6bda 792 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
793 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
794 } else {
795 var year_mod = 1; // e.g. to only print one point every 10 years.
796 var num_months = 12;
285a6bda
DV
797 if (granularity == Dygraph.QUARTERLY) num_months = 3;
798 if (granularity == Dygraph.BIANNUAL) num_months = 2;
799 if (granularity == Dygraph.ANNUAL) num_months = 1;
800 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
32988383
DV
801
802 var msInYear = 365.2524 * 24 * 3600 * 1000;
803 var num_years = 1.0 * (end_time - start_time) / msInYear;
804 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
805 }
806};
807
808// GetXAxis()
809//
810// Construct an x-axis of nicely-formatted times on meaningful boundaries
811// (e.g. 'Jan 09' rather than 'Jan 22, 2009').
812//
813// Returns an array containing {v: millis, label: label} dictionaries.
814//
285a6bda 815Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
32988383 816 var ticks = [];
285a6bda 817 if (granularity < Dygraph.MONTHLY) {
32988383 818 // Generate one tick mark for every fixed interval of time.
285a6bda 819 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383 820 var format = '%d%b'; // e.g. "1 Jan"
328bb812 821 // TODO(danvk): be smarter about making sure this really hits a "nice" time.
285a6bda 822 if (granularity < Dygraph.HOURLY) {
328bb812
DV
823 start_time = spacing * Math.floor(0.5 + start_time / spacing);
824 }
32988383
DV
825 for (var t = start_time; t <= end_time; t += spacing) {
826 var d = new Date(t);
827 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
285a6bda 828 if (frac == 0 || granularity >= Dygraph.DAILY) {
32988383
DV
829 // the extra hour covers DST problems.
830 ticks.push({ v:t, label: new Date(t + 3600*1000).strftime(format) });
831 } else {
832 ticks.push({ v:t, label: this.hmsString_(t) });
833 }
834 }
835 } else {
836 // Display a tick mark on the first of a set of months of each year.
837 // Years get a tick mark iff y % year_mod == 0. This is useful for
838 // displaying a tick mark once every 10 years, say, on long time scales.
839 var months;
840 var year_mod = 1; // e.g. to only print one point every 10 years.
841
285a6bda 842 if (granularity == Dygraph.MONTHLY) {
32988383 843 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 844 } else if (granularity == Dygraph.QUARTERLY) {
32988383 845 months = [ 0, 3, 6, 9 ];
285a6bda 846 } else if (granularity == Dygraph.BIANNUAL) {
32988383 847 months = [ 0, 6 ];
285a6bda 848 } else if (granularity == Dygraph.ANNUAL) {
32988383 849 months = [ 0 ];
285a6bda 850 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
851 months = [ 0 ];
852 year_mod = 10;
853 }
854
855 var start_year = new Date(start_time).getFullYear();
856 var end_year = new Date(end_time).getFullYear();
285a6bda 857 var zeropad = Dygraph.zeropad;
32988383
DV
858 for (var i = start_year; i <= end_year; i++) {
859 if (i % year_mod != 0) continue;
860 for (var j = 0; j < months.length; j++) {
861 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
862 var t = Date.parse(date_str);
863 if (t < start_time || t > end_time) continue;
864 ticks.push({ v:t, label: new Date(t).strftime('%b %y') });
865 }
866 }
867 }
868
869 return ticks;
870};
871
6a1aa64f
DV
872
873/**
874 * Add ticks to the x-axis based on a date range.
875 * @param {Number} startDate Start of the date window (millis since epoch)
876 * @param {Number} endDate End of the date window (millis since epoch)
877 * @return {Array.<Object>} Array of {label, value} tuples.
878 * @public
879 */
285a6bda 880Dygraph.dateTicker = function(startDate, endDate, self) {
32988383 881 var chosen = -1;
285a6bda
DV
882 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
883 var num_ticks = self.NumXTicks(startDate, endDate, i);
884 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
885 chosen = i;
886 break;
2769de62 887 }
6a1aa64f
DV
888 }
889
32988383 890 if (chosen >= 0) {
285a6bda 891 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 892 } else {
32988383 893 // TODO(danvk): signal error.
6a1aa64f 894 }
6a1aa64f
DV
895};
896
897/**
898 * Add ticks when the x axis has numbers on it (instead of dates)
899 * @param {Number} startDate Start of the date window (millis since epoch)
900 * @param {Number} endDate End of the date window (millis since epoch)
901 * @return {Array.<Object>} Array of {label, value} tuples.
902 * @public
903 */
285a6bda 904Dygraph.numericTicks = function(minV, maxV, self) {
c6336f04
DV
905 // Basic idea:
906 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
907 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
285a6bda 908 // The first spacing greater than pixelsPerYLabel is what we use.
c6336f04
DV
909 var mults = [1, 2, 5];
910 var scale, low_val, high_val, nTicks;
285a6bda
DV
911 // TODO(danvk): make it possible to set this for x- and y-axes independently.
912 var pixelsPerTick = self.attr_('pixelsPerYLabel');
c6336f04
DV
913 for (var i = -10; i < 50; i++) {
914 var base_scale = Math.pow(10, i);
915 for (var j = 0; j < mults.length; j++) {
916 scale = base_scale * mults[j];
c6336f04
DV
917 low_val = Math.floor(minV / scale) * scale;
918 high_val = Math.ceil(maxV / scale) * scale;
919 nTicks = (high_val - low_val) / scale;
285a6bda 920 var spacing = self.height_ / nTicks;
c6336f04 921 // wish I could break out of both loops at once...
285a6bda 922 if (spacing > pixelsPerTick) break;
c6336f04 923 }
285a6bda 924 if (spacing > pixelsPerTick) break;
6a1aa64f
DV
925 }
926
927 // Construct labels for the ticks
928 var ticks = [];
c6336f04
DV
929 for (var i = 0; i < nTicks; i++) {
930 var tickV = low_val + i * scale;
285a6bda
DV
931 var label = self.round_(tickV, 2);
932 if (self.attr_("labelsKMB")) {
6a1aa64f
DV
933 var k = 1000;
934 if (tickV >= k*k*k) {
285a6bda 935 label = self.round_(tickV/(k*k*k), 1) + "B";
6a1aa64f 936 } else if (tickV >= k*k) {
285a6bda 937 label = self.round_(tickV/(k*k), 1) + "M";
6a1aa64f 938 } else if (tickV >= k) {
285a6bda 939 label = self.round_(tickV/k, 1) + "K";
6a1aa64f
DV
940 }
941 }
942 ticks.push( {label: label, v: tickV} );
943 }
944 return ticks;
945};
946
947/**
948 * Adds appropriate ticks on the y-axis
949 * @param {Number} minY The minimum Y value in the data set
950 * @param {Number} maxY The maximum Y value in the data set
951 * @private
952 */
285a6bda 953Dygraph.prototype.addYTicks_ = function(minY, maxY) {
6a1aa64f 954 // Set the number of ticks so that the labels are human-friendly.
285a6bda
DV
955 // TODO(danvk): make this an attribute as well.
956 var ticks = Dygraph.numericTicks(minY, maxY, this);
6a1aa64f
DV
957 this.layout_.updateOptions( { yAxis: [minY, maxY],
958 yTicks: ticks } );
959};
960
961/**
962 * Update the graph with new data. Data is in the format
963 * [ [date1, val1, val2, ...], [date2, val1, val2, ...] if errorBars=false
964 * or, if errorBars=true,
965 * [ [date1, [val1,stddev1], [val2,stddev2], ...], [date2, ...], ...]
966 * @param {Array.<Object>} data The data (see above)
967 * @private
968 */
285a6bda 969Dygraph.prototype.drawGraph_ = function(data) {
6a1aa64f
DV
970 var maxY = null;
971 this.layout_.removeAllDatasets();
285a6bda
DV
972 this.setColors_();
973
6a1aa64f
DV
974 // Loop over all fields in the dataset
975 for (var i = 1; i < data[0].length; i++) {
976 var series = [];
977 for (var j = 0; j < data.length; j++) {
978 var date = data[j][0];
979 series[j] = [date, data[j][i]];
980 }
981 series = this.rollingAverage(series, this.rollPeriod_);
982
983 // Prune down to the desired range, if necessary (for zooming)
285a6bda 984 var bars = this.attr_("errorBars") || this.customBars_;
6a1aa64f
DV
985 if (this.dateWindow_) {
986 var low = this.dateWindow_[0];
987 var high= this.dateWindow_[1];
988 var pruned = [];
989 for (var k = 0; k < series.length; k++) {
990 if (series[k][0] >= low && series[k][0] <= high) {
991 pruned.push(series[k]);
992 var y = bars ? series[k][1][0] : series[k][1];
993 if (maxY == null || y > maxY) maxY = y;
994 }
995 }
996 series = pruned;
997 } else {
285a6bda
DV
998 if (!this.customBars_) {
999 for (var j = 0; j < series.length; j++) {
1000 var y = bars ? series[j][1][0] : series[j][1];
1001 if (maxY == null || y > maxY) {
1002 maxY = bars ? y + series[j][1][1] : y;
1003 }
1004 }
1005 } else {
1006 // With custom bars, maxY is the max of the high values.
1007 for (var j = 0; j < series.length; j++) {
1008 var y = series[j][1][0];
1009 var high = series[j][1][2];
1010 if (high > y) y = high;
1011 if (maxY == null || y > maxY) {
1012 maxY = y;
1013 }
6a1aa64f
DV
1014 }
1015 }
1016 }
1017
1018 if (bars) {
1019 var vals = [];
1020 for (var j=0; j<series.length; j++)
1021 vals[j] = [series[j][0],
1022 series[j][1][0], series[j][1][1], series[j][1][2]];
285a6bda 1023 this.layout_.addDataset(this.attr_("labels")[i], vals);
6a1aa64f 1024 } else {
285a6bda 1025 this.layout_.addDataset(this.attr_("labels")[i], series);
6a1aa64f
DV
1026 }
1027 }
1028
1029 // Use some heuristics to come up with a good maxY value, unless it's been
1030 // set explicitly by the user.
1031 if (this.valueRange_ != null) {
1032 this.addYTicks_(this.valueRange_[0], this.valueRange_[1]);
1033 } else {
1034 // Add some padding and round up to an integer to be human-friendly.
1035 maxY *= 1.1;
1036 if (maxY <= 0.0) maxY = 1.0;
6a1aa64f
DV
1037 this.addYTicks_(0, maxY);
1038 }
1039
1040 this.addXTicks_();
1041
1042 // Tell PlotKit to use this new data and render itself
1043 this.layout_.evaluateWithError();
1044 this.plotter_.clear();
1045 this.plotter_.render();
1046 this.canvas_.getContext('2d').clearRect(0, 0,
1047 this.canvas_.width, this.canvas_.height);
1048};
1049
1050/**
1051 * Calculates the rolling average of a data set.
1052 * If originalData is [label, val], rolls the average of those.
1053 * If originalData is [label, [, it's interpreted as [value, stddev]
1054 * and the roll is returned in the same form, with appropriately reduced
1055 * stddev for each value.
1056 * Note that this is where fractional input (i.e. '5/10') is converted into
1057 * decimal values.
1058 * @param {Array} originalData The data in the appropriate format (see above)
1059 * @param {Number} rollPeriod The number of days over which to average the data
1060 */
285a6bda 1061Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
1062 if (originalData.length < 2)
1063 return originalData;
1064 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
1065 var rollingData = [];
285a6bda 1066 var sigma = this.attr_("sigma");
6a1aa64f
DV
1067
1068 if (this.fractions_) {
1069 var num = 0;
1070 var den = 0; // numerator/denominator
1071 var mult = 100.0;
1072 for (var i = 0; i < originalData.length; i++) {
1073 num += originalData[i][1][0];
1074 den += originalData[i][1][1];
1075 if (i - rollPeriod >= 0) {
1076 num -= originalData[i - rollPeriod][1][0];
1077 den -= originalData[i - rollPeriod][1][1];
1078 }
1079
1080 var date = originalData[i][0];
1081 var value = den ? num / den : 0.0;
285a6bda 1082 if (this.attr_("errorBars")) {
6a1aa64f
DV
1083 if (this.wilsonInterval_) {
1084 // For more details on this confidence interval, see:
1085 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
1086 if (den) {
1087 var p = value < 0 ? 0 : value, n = den;
1088 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
1089 var denom = 1 + sigma * sigma / den;
1090 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
1091 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
1092 rollingData[i] = [date,
1093 [p * mult, (p - low) * mult, (high - p) * mult]];
1094 } else {
1095 rollingData[i] = [date, [0, 0, 0]];
1096 }
1097 } else {
1098 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
1099 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
1100 }
1101 } else {
1102 rollingData[i] = [date, mult * value];
1103 }
1104 }
1105 } else if (this.customBars_) {
f6885d6a
DV
1106 var low = 0;
1107 var mid = 0;
1108 var high = 0;
1109 var count = 0;
6a1aa64f
DV
1110 for (var i = 0; i < originalData.length; i++) {
1111 var data = originalData[i][1];
1112 var y = data[1];
1113 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a
DV
1114
1115 low += data[0];
1116 mid += y;
1117 high += data[2];
1118 count += 1;
1119 if (i - rollPeriod >= 0) {
1120 var prev = originalData[i - rollPeriod];
1121 low -= prev[1][0];
1122 mid -= prev[1][1];
1123 high -= prev[1][2];
1124 count -= 1;
1125 }
1126 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
1127 1.0 * (mid - low) / count,
1128 1.0 * (high - mid) / count ]];
2769de62 1129 }
6a1aa64f
DV
1130 } else {
1131 // Calculate the rolling average for the first rollPeriod - 1 points where
1132 // there is not enough data to roll over the full number of days
1133 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 1134 if (!this.attr_("errorBars")){
6a1aa64f
DV
1135 for (var i = 0; i < num_init_points; i++) {
1136 var sum = 0;
1137 for (var j = 0; j < i + 1; j++)
1138 sum += originalData[j][1];
1139 rollingData[i] = [originalData[i][0], sum / (i + 1)];
1140 }
1141 // Calculate the rolling average for the remaining points
1142 for (var i = Math.min(rollPeriod - 1, originalData.length - 2);
1143 i < originalData.length;
1144 i++) {
1145 var sum = 0;
1146 for (var j = i - rollPeriod + 1; j < i + 1; j++)
1147 sum += originalData[j][1];
1148 rollingData[i] = [originalData[i][0], sum / rollPeriod];
1149 }
1150 } else {
1151 for (var i = 0; i < num_init_points; i++) {
1152 var sum = 0;
1153 var variance = 0;
1154 for (var j = 0; j < i + 1; j++) {
1155 sum += originalData[j][1][0];
1156 variance += Math.pow(originalData[j][1][1], 2);
1157 }
1158 var stddev = Math.sqrt(variance)/(i+1);
1159 rollingData[i] = [originalData[i][0],
1160 [sum/(i+1), sigma * stddev, sigma * stddev]];
1161 }
1162 // Calculate the rolling average for the remaining points
1163 for (var i = Math.min(rollPeriod - 1, originalData.length - 2);
1164 i < originalData.length;
1165 i++) {
1166 var sum = 0;
1167 var variance = 0;
1168 for (var j = i - rollPeriod + 1; j < i + 1; j++) {
1169 sum += originalData[j][1][0];
1170 variance += Math.pow(originalData[j][1][1], 2);
1171 }
1172 var stddev = Math.sqrt(variance) / rollPeriod;
1173 rollingData[i] = [originalData[i][0],
1174 [sum / rollPeriod, sigma * stddev, sigma * stddev]];
1175 }
1176 }
1177 }
1178
1179 return rollingData;
1180};
1181
1182/**
1183 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
1184 * passed in as an xValueParser in the Dygraph constructor.
1185 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
1186 * @param {String} A date in YYYYMMDD format.
1187 * @return {Number} Milliseconds since epoch.
1188 * @public
1189 */
285a6bda 1190Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 1191 var dateStrSlashed;
285a6bda 1192 var d;
2769de62 1193 if (dateStr.length == 10 && dateStr.search("-") != -1) { // e.g. '2009-07-12'
6a1aa64f 1194 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
1195 while (dateStrSlashed.search("-") != -1) {
1196 dateStrSlashed = dateStrSlashed.replace("-", "/");
1197 }
285a6bda 1198 d = Date.parse(dateStrSlashed);
2769de62 1199 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 1200 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
1201 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
1202 + "/" + dateStr.substr(6,2);
285a6bda 1203 d = Date.parse(dateStrSlashed);
2769de62
DV
1204 } else {
1205 // Any format that Date.parse will accept, e.g. "2009/07/12" or
1206 // "2009/07/12 12:34:56"
285a6bda
DV
1207 d = Date.parse(dateStr);
1208 }
1209
1210 if (!d || isNaN(d)) {
1211 self.error("Couldn't parse " + dateStr + " as a date");
1212 }
1213 return d;
1214};
1215
1216/**
1217 * Detects the type of the str (date or numeric) and sets the various
1218 * formatting attributes in this.attrs_ based on this type.
1219 * @param {String} str An x value.
1220 * @private
1221 */
1222Dygraph.prototype.detectTypeFromString_ = function(str) {
1223 var isDate = false;
1224 if (str.indexOf('-') >= 0 ||
1225 str.indexOf('/') >= 0 ||
1226 isNaN(parseFloat(str))) {
1227 isDate = true;
1228 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
1229 // TODO(danvk): remove support for this format.
1230 isDate = true;
1231 }
1232
1233 if (isDate) {
1234 this.attrs_.xValueFormatter = Dygraph.dateString_;
1235 this.attrs_.xValueParser = Dygraph.dateParser;
1236 this.attrs_.xTicker = Dygraph.dateTicker;
1237 } else {
1238 this.attrs_.xValueFormatter = function(x) { return x; };
1239 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1240 this.attrs_.xTicker = Dygraph.numericTicks;
6a1aa64f 1241 }
6a1aa64f
DV
1242};
1243
1244/**
1245 * Parses a string in a special csv format. We expect a csv file where each
1246 * line is a date point, and the first field in each line is the date string.
1247 * We also expect that all remaining fields represent series.
285a6bda 1248 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f
DV
1249 * date, series1, stddev1, series2, stddev2, ...
1250 * @param {Array.<Object>} data See above.
1251 * @private
285a6bda
DV
1252 *
1253 * @return Array.<Object> An array with one entry for each row. These entries
1254 * are an array of cells in that row. The first entry is the parsed x-value for
1255 * the row. The second, third, etc. are the y-values. These can take on one of
1256 * three forms, depending on the CSV and constructor parameters:
1257 * 1. numeric value
1258 * 2. [ value, stddev ]
1259 * 3. [ low value, center value, high value ]
6a1aa64f 1260 */
285a6bda 1261Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
1262 var ret = [];
1263 var lines = data.split("\n");
285a6bda 1264 var start = 0;
6a1aa64f 1265 if (this.labelsFromCSV_) {
285a6bda
DV
1266 start = 1;
1267 this.attrs_.labels = lines[0].split(",");
6a1aa64f
DV
1268 }
1269
285a6bda
DV
1270 var xParser;
1271 var defaultParserSet = false; // attempt to auto-detect x value type
1272 var expectedCols = this.attr_("labels").length;
6a1aa64f
DV
1273 for (var i = start; i < lines.length; i++) {
1274 var line = lines[i];
1275 if (line.length == 0) continue; // skip blank lines
1276 var inFields = line.split(',');
285a6bda 1277 if (inFields.length < 2) continue;
6a1aa64f
DV
1278
1279 var fields = [];
285a6bda
DV
1280 if (!defaultParserSet) {
1281 this.detectTypeFromString_(inFields[0]);
1282 xParser = this.attr_("xValueParser");
1283 defaultParserSet = true;
1284 }
1285 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
1286
1287 // If fractions are expected, parse the numbers as "A/B"
1288 if (this.fractions_) {
1289 for (var j = 1; j < inFields.length; j++) {
1290 // TODO(danvk): figure out an appropriate way to flag parse errors.
1291 var vals = inFields[j].split("/");
1292 fields[j] = [parseFloat(vals[0]), parseFloat(vals[1])];
1293 }
285a6bda 1294 } else if (this.attr_("errorBars")) {
6a1aa64f
DV
1295 // If there are error bars, values are (value, stddev) pairs
1296 for (var j = 1; j < inFields.length; j += 2)
1297 fields[(j + 1) / 2] = [parseFloat(inFields[j]),
1298 parseFloat(inFields[j + 1])];
1299 } else if (this.customBars_) {
1300 // Bars are a low;center;high tuple
1301 for (var j = 1; j < inFields.length; j++) {
1302 var vals = inFields[j].split(";");
1303 fields[j] = [ parseFloat(vals[0]),
1304 parseFloat(vals[1]),
1305 parseFloat(vals[2]) ];
1306 }
1307 } else {
1308 // Values are just numbers
285a6bda 1309 for (var j = 1; j < inFields.length; j++) {
6a1aa64f 1310 fields[j] = parseFloat(inFields[j]);
285a6bda 1311 }
6a1aa64f
DV
1312 }
1313 ret.push(fields);
285a6bda
DV
1314
1315 if (fields.length != expectedCols) {
1316 this.error("Number of columns in line " + i + " (" + fields.length +
1317 ") does not agree with number of labels (" + expectedCols +
1318 ") " + line);
1319 }
6a1aa64f
DV
1320 }
1321 return ret;
1322};
1323
1324/**
285a6bda
DV
1325 * The user has provided their data as a pre-packaged JS array. If the x values
1326 * are numeric, this is the same as dygraphs' internal format. If the x values
1327 * are dates, we need to convert them from Date objects to ms since epoch.
1328 * @param {Array.<Object>} data
1329 * @return {Array.<Object>} data with numeric x values.
1330 */
1331Dygraph.prototype.parseArray_ = function(data) {
1332 // Peek at the first x value to see if it's numeric.
1333 if (data.length == 0) {
1334 this.error("Can't plot empty data set");
1335 return null;
1336 }
1337 if (data[0].length == 0) {
1338 this.error("Data set cannot contain an empty row");
1339 return null;
1340 }
1341
1342 if (this.attr_("labels") == null) {
1343 this.warn("Using default labels. Set labels explicitly via 'labels' " +
1344 "in the options parameter");
1345 this.attrs_.labels = [ "X" ];
1346 for (var i = 1; i < data[0].length; i++) {
1347 this.attrs_.labels.push("Y" + i);
1348 }
1349 }
1350
1351 if (MochiKit.Base.isDateLike(data[0][0])) {
1352 // Some intelligent defaults for a date x-axis.
1353 this.attrs_.xValueFormatter = Dygraph.dateString_;
1354 this.attrs_.xTicker = Dygraph.dateTicker;
1355
1356 // Assume they're all dates.
1357 var parsedData = MochiKit.Base.clone(data);
1358 for (var i = 0; i < data.length; i++) {
1359 if (parsedData[i].length == 0) {
1360 this.error("Row " << (1 + i) << " of data is empty");
1361 return null;
1362 }
1363 if (parsedData[i][0] == null
1364 || typeof(parsedData[i][0].getTime) != 'function') {
1365 this.error("x value in row " << (1 + i) << " is not a Date");
1366 return null;
1367 }
1368 parsedData[i][0] = parsedData[i][0].getTime();
1369 }
1370 return parsedData;
1371 } else {
1372 // Some intelligent defaults for a numeric x-axis.
1373 this.attrs_.xValueFormatter = function(x) { return x; };
1374 this.attrs_.xTicker = Dygraph.numericTicks;
1375 return data;
1376 }
1377};
1378
1379/**
79420a1e
DV
1380 * Parses a DataTable object from gviz.
1381 * The data is expected to have a first column that is either a date or a
1382 * number. All subsequent columns must be numbers. If there is a clear mismatch
1383 * between this.xValueParser_ and the type of the first column, it will be
1384 * fixed. Returned value is in the same format as return value of parseCSV_.
1385 * @param {Array.<Object>} data See above.
1386 * @private
1387 */
285a6bda 1388Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
1389 var cols = data.getNumberOfColumns();
1390 var rows = data.getNumberOfRows();
1391
1392 // Read column labels
1393 var labels = [];
1394 for (var i = 0; i < cols; i++) {
1395 labels.push(data.getColumnLabel(i));
1396 }
285a6bda 1397 this.attrs_.labels = labels;
79420a1e 1398
d955e223 1399 var indepType = data.getColumnType(0);
285a6bda
DV
1400 if (indepType == 'date') {
1401 this.attrs_.xValueFormatter = Dygraph.dateString_;
1402 this.attrs_.xValueParser = Dygraph.dateParser;
1403 this.attrs_.xTicker = Dygraph.dateTicker;
33127159 1404 } else if (indepType == 'number') {
285a6bda
DV
1405 this.attrs_.xValueFormatter = function(x) { return x; };
1406 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1407 this.attrs_.xTicker = Dygraph.numericTicks;
1408 } else {
33127159 1409 this.error("only 'date' and 'number' types are supported for column 1 " +
285a6bda 1410 "of DataTable input (Got '" + indepType + "')");
79420a1e
DV
1411 return null;
1412 }
1413
1414 var ret = [];
1415 for (var i = 0; i < rows; i++) {
1416 var row = [];
b3b20e24 1417 if (!data.getValue(i, 0)) continue;
d955e223
DV
1418 if (indepType == 'date') {
1419 row.push(data.getValue(i, 0).getTime());
1420 } else {
1421 row.push(data.getValue(i, 0));
1422 }
b3b20e24 1423 var any_data = false;
79420a1e
DV
1424 for (var j = 1; j < cols; j++) {
1425 row.push(data.getValue(i, j));
b3b20e24 1426 if (data.getValue(i, j)) any_data = true;
79420a1e 1427 }
b3b20e24 1428 if (any_data) ret.push(row);
79420a1e
DV
1429 }
1430 return ret;
1431}
1432
1433/**
6a1aa64f
DV
1434 * Get the CSV data. If it's in a function, call that function. If it's in a
1435 * file, do an XMLHttpRequest to get it.
1436 * @private
1437 */
285a6bda 1438Dygraph.prototype.start_ = function() {
6a1aa64f 1439 if (typeof this.file_ == 'function') {
285a6bda 1440 // CSV string. Pretend we got it via XHR.
6a1aa64f 1441 this.loadedEvent_(this.file_());
285a6bda
DV
1442 } else if (MochiKit.Base.isArrayLike(this.file_)) {
1443 this.rawData_ = this.parseArray_(this.file_);
1444 this.drawGraph_(this.rawData_);
79420a1e
DV
1445 } else if (typeof this.file_ == 'object' &&
1446 typeof this.file_.getColumnRange == 'function') {
1447 // must be a DataTable from gviz.
1448 this.rawData_ = this.parseDataTable_(this.file_);
1449 this.drawGraph_(this.rawData_);
285a6bda
DV
1450 } else if (typeof this.file_ == 'string') {
1451 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
1452 if (this.file_.indexOf('\n') >= 0) {
1453 this.loadedEvent_(this.file_);
1454 } else {
1455 var req = new XMLHttpRequest();
1456 var caller = this;
1457 req.onreadystatechange = function () {
1458 if (req.readyState == 4) {
1459 if (req.status == 200) {
1460 caller.loadedEvent_(req.responseText);
1461 }
6a1aa64f 1462 }
285a6bda 1463 };
6a1aa64f 1464
285a6bda
DV
1465 req.open("GET", this.file_, true);
1466 req.send(null);
1467 }
1468 } else {
1469 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
1470 }
1471};
1472
1473/**
1474 * Changes various properties of the graph. These can include:
1475 * <ul>
1476 * <li>file: changes the source data for the graph</li>
1477 * <li>errorBars: changes whether the data contains stddev</li>
1478 * </ul>
1479 * @param {Object} attrs The new properties and values
1480 */
285a6bda
DV
1481Dygraph.prototype.updateOptions = function(attrs) {
1482 // TODO(danvk): this is a mess. Rethink this function.
6a1aa64f
DV
1483 if (attrs.customBars) {
1484 this.customBars_ = attrs.customBars;
1485 }
6a1aa64f
DV
1486 if (attrs.rollPeriod) {
1487 this.rollPeriod_ = attrs.rollPeriod;
1488 }
1489 if (attrs.dateWindow) {
1490 this.dateWindow_ = attrs.dateWindow;
1491 }
1492 if (attrs.valueRange) {
1493 this.valueRange_ = attrs.valueRange;
1494 }
285a6bda
DV
1495 MochiKit.Base.update(this.user_attrs_, attrs);
1496
1497 this.labelsFromCSV_ = (this.attr_("labels") == null);
1498
1499 // TODO(danvk): this doesn't match the constructor logic
1500 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
6a1aa64f
DV
1501 if (attrs['file'] && attrs['file'] != this.file_) {
1502 this.file_ = attrs['file'];
1503 this.start_();
1504 } else {
1505 this.drawGraph_(this.rawData_);
1506 }
1507};
1508
1509/**
1510 * Adjusts the number of days in the rolling average. Updates the graph to
1511 * reflect the new averaging period.
1512 * @param {Number} length Number of days over which to average the data.
1513 */
285a6bda 1514Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f
DV
1515 this.rollPeriod_ = length;
1516 this.drawGraph_(this.rawData_);
1517};
540d00f1
DV
1518
1519
1520/**
285a6bda 1521 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
1522 * @param {Object} container The DOM object the visualization should live in.
1523 */
285a6bda 1524Dygraph.GVizChart = function(container) {
540d00f1
DV
1525 this.container = container;
1526}
1527
285a6bda 1528Dygraph.GVizChart.prototype.draw = function(data, options) {
540d00f1 1529 this.container.innerHTML = '';
285a6bda 1530 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 1531}
285a6bda
DV
1532
1533// Older pages may still use this name.
1534DateGraph = Dygraph;