summaryrefslogtreecommitdiff
path: root/timings/js/plotter.js
blob: 86fb230492ec507cf154e6d02696572095388a72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
  Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
  Use of this source code is governed by a BSD-style license that can be
  found in the LICENSE file.
*/

// Collection of classes used to plot data in a <canvas>.  Create a Plotter()
// to generate a plot.

// vertical marker for columns
function Marker(color) {
  var m = document.createElement("DIV");
  m.setAttribute("class", "plot-cursor");
  m.style.backgroundColor = color;
  m.style.opacity = "0.3";
  m.style.position = "absolute";
  m.style.left = "-2px";
  m.style.top = "-2px";
  m.style.width = "0px";
  m.style.height = "0px";
  return m;
}

/**
 * HorizontalMarker class
 * Create a horizontal marker at the indicated mouse location.
 * @constructor
 *
 * @param canvasRect {Object} The canvas bounds (in client coords).
 * @param clientY {Number} The vertical mouse click location that spawned
 *    the marker, in the client coordinate space.
 * @param yValue {Number} The plotted value corresponding to the clientY
 *     click location.
 */
function HorizontalMarker(canvasRect, clientY, yValue) {
  // Add a horizontal line to the graph.
  var m = document.createElement("DIV");
  m.setAttribute("class", "plot-baseline");
  m.style.backgroundColor = HorizontalMarker.COLOR;
  m.style.opacity = "0.3";
  m.style.position = "absolute";
  m.style.left = canvasRect.offsetLeft;
  var h = HorizontalMarker.HEIGHT;
  m.style.top = (clientY - h/2).toFixed(0) + "px";
  m.style.width = canvasRect.width + "px";
  m.style.height = h + "px";
  this.markerDiv_ = m;

  this.value = yValue;
}

HorizontalMarker.HEIGHT = 5;
HorizontalMarker.COLOR = "rgb(0,100,100)";

// Remove the horizontal line from the graph.
HorizontalMarker.prototype.remove_ = function() {
  this.markerDiv_.parentNode.removeChild(this.markerDiv_);
}

/**
 * Plotter class
 * @constructor
 *
 * Draws a chart using CANVAS element. Takes array of lines to draw with
 * deviations values for each data sample.
 *
 * @param {Array} clNumbers list of clNumbers for each data sample.
 * @param {Array} plotData list of arrays that represent individual lines.
 *                         The line itself is an Array of value and stdd.
 * @param {Array} dataDescription list of data description for each line
 *                         in plotData.
 * @units {string} units name of measurement used to describe plotted data.
 *
 * Example of the plotData:
 *  [
 *    [line 1 data],
 *    [line 2 data]
 *  ].
 *  Line data looks like  [[point one], [point two]].
 *  And individual points are [value, deviation value]
 */
function Plotter(clNumbers, plotData, dataDescription, units, resultNode) {
  this.clNumbers_ = clNumbers;
  this.plotData_ = plotData;
  this.dataDescription_ = dataDescription;
  this.resultNode_ = resultNode;
  this.units_ = units;
  this.coordinates = new Coordinates(plotData);

  // A color palette that's unambigous for normal and color-deficient viewers.
  // Values are (red, green, blue) on a scale of 255.
  // Taken from http://jfly.iam.u-tokyo.ac.jp/html/manuals/pdf/color_blind.pdf
  this.colors = [[0, 114, 178],   // blue
                 [230, 159, 0],   // orange
                 [0, 158, 115],   // green
                 [204, 121, 167], // purplish pink
                 [86, 180, 233],  // sky blue
                 [213, 94, 0],    // dark orange
                 [0, 0, 0],       // black
                 [240, 228, 66]   // yellow
                ];
}

/**
 * Does the actual plotting.
 */
Plotter.prototype.plot = function() {
  var canvas = this.canvas();
  this.coordinates_div_ = this.coordinates_();
  this.ruler_div_ = this.ruler();
  // marker for the result-point that the mouse is currently over
  this.cursor_div_ = new Marker("rgb(100,80,240)");
  // marker for the result-point for which details are shown
  this.marker_div_ = new Marker("rgb(100,100,100)");
  var ctx = canvas.getContext("2d");
  for (var i = 0; i < this.plotData_.length; i++)
    this.plotLine_(ctx, this.nextColor(i), this.plotData_[i]);

  this.resultNode_.appendChild(canvas);
  this.resultNode_.appendChild(this.coordinates_div_);

  this.resultNode_.appendChild(this.ruler_div_);
  this.resultNode_.appendChild(this.cursor_div_);
  this.resultNode_.appendChild(this.marker_div_);
  this.attachEventListeners(canvas);
  this.canvasRectangle = {
    "offsetLeft": canvas.offsetLeft,
    "offsetTop":  canvas.offsetTop,
    "width":      canvas.offsetWidth,
    "height":     canvas.offsetHeight
  };
};

Plotter.prototype.drawDeviationBar_ = function(context, strokeStyles, x, y,
                                                deviationValue) {
  context.strokeStyle = strokeStyles;
  context.lineWidth = 1.0;
  context.beginPath();
  context.moveTo(x, (y + deviationValue));
  context.lineTo(x, (y - deviationValue));
  context.moveTo(x, (y - deviationValue));
  context.closePath();
  context.stroke();
};

Plotter.prototype.plotLine_ = function(ctx, strokeStyles, data) {
  ctx.strokeStyle = strokeStyles;
  ctx.lineWidth = 2.0;
  ctx.beginPath();
  var initial = true;
  var deviationData = [];
  for (var i = 0; i < data.length; i++) {
    var x = this.coordinates.xPoints(i);
    var value = data[i][0];
    var stdd = data[i][1];
    var y = 0.0;
    var err = 0.0;
    if (isNaN(value)) {
      // Re-set 'initial' if we're at a gap in the data.
      initial = true;
    } else {
      y = this.coordinates.yPoints(value);
      // We assume that the stdd will only be NaN (missing) when the value is.
      if (parseFloat(value) != 0.0)
        err = y * parseFloat(stdd) / parseFloat(value);
      if (initial)
        initial = false;
      else
        ctx.lineTo(x, y);
    }

    ctx.moveTo(x, y);
    deviationData.push([x, y, err])
  }
  ctx.closePath();
  ctx.stroke();

  for (var i = 0; i < deviationData.length; i++) {
    this.drawDeviationBar_(ctx, strokeStyles, deviationData[i][0],
                            deviationData[i][1], deviationData[i][2]);
  }
};

Plotter.prototype.attachEventListeners = function(canvas) {
  var self = this;
  canvas.parentNode.addEventListener(
    "mousemove", function(evt) { self.onMouseMove_(evt); }, false);
  this.cursor_div_.addEventListener(
    "click", function(evt) { self.onMouseClick_(evt); }, false);
};

Plotter.prototype.updateRuler_ = function(evt) {
  var r = this.ruler_div_;
  r.style.left = this.canvasRectangle.offsetLeft + "px";

  r.style.top = this.canvasRectangle.offsetTop + "px";
  r.style.width = this.canvasRectangle.width + "px";
  var h = evt.clientY - this.canvasRectangle.offsetTop;
  if (h > this.canvasRectangle.height)
    h = this.canvasRectangle.height;
  r.style.height = h + "px";
};

Plotter.prototype.updateCursor_ = function() {
  var c = this.cursor_div_;
  c.style.top = this.canvasRectangle.offsetTop + "px";
  c.style.height = this.canvasRectangle.height + "px";
  var w = this.canvasRectangle.width / this.clNumbers_.length;
  var x = (this.canvasRectangle.offsetLeft +
            w * this.current_index_).toFixed(0);
  c.style.left = x + "px";
  c.style.width = w + "px";
};


Plotter.prototype.onMouseMove_ = function(evt) {
  var canvas = evt.currentTarget.firstChild;
  var positionX = evt.clientX - this.canvasRectangle.offsetLeft;
  var positionY = evt.clientY - this.canvasRectangle.offsetTop;

  this.current_index_ = this.coordinates.dataSampleIndex(positionX);
  var yValue = this.coordinates.yValue(positionY);

  this.coordinates_td_.innerHTML =
      "r" + this.clNumbers_[this.current_index_] + ": " +
      this.plotData_[0][this.current_index_][0].toFixed(2) + " " +
      this.units_ + " +/- " +
      this.plotData_[0][this.current_index_][1].toFixed(2) + " " +
      yValue.toFixed(2) + " " + this.units_;

  // If there is a horizontal marker, also display deltas relative to it.
  if (this.horizontal_marker_) {
    var baseline = this.horizontal_marker_.value;
    var delta = yValue - baseline
    var fraction = delta / baseline; // allow division by 0

    var deltaStr = (delta >= 0 ? "+" : "") + delta.toFixed(0) + " " +
        this.units_;
    var percentStr = (fraction >= 0 ? "+" : "") +
        (fraction * 100).toFixed(3) + "%";

    this.baseline_deltas_td_.innerHTML = deltaStr + ": " + percentStr;
  }

  this.updateRuler_(evt);
  this.updateCursor_();
};

Plotter.prototype.onMouseClick_ = function(evt) {
  // Shift-click controls the horizontal reference line.
  if (evt.shiftKey) {
    if (this.horizontal_marker_) {
      this.horizontal_marker_.remove_();
    }

    var canvasY = evt.clientY - this.canvasRectangle.offsetTop;
    this.horizontal_marker_ = new HorizontalMarker(this.canvasRectangle,
        evt.clientY, this.coordinates.yValue(canvasY));

    // Insert before cursor node, otherwise it catches clicks.
    this.cursor_div_.parentNode.insertBefore(
        this.horizontal_marker_.markerDiv_, this.cursor_div_);
  } else {
    var index = this.current_index_;
    var m = this.marker_div_;
    var c = this.cursor_div_;
    m.style.top = c.style.top;
    m.style.left = c.style.left;
    m.style.width = c.style.width;
    m.style.height = c.style.height;
    if ("onclick" in this) {
      var this_x = this.clNumbers_[index];
      var prev_x = index > 0 ? (parseInt(this.clNumbers_[index-1]) + 1) :
                                this_x;
      this.onclick(prev_x, this_x);
    }
  }
};

Plotter.prototype.canvas = function() {
  var canvas = document.createElement("CANVAS");
  canvas.setAttribute("id", "_canvas");
  canvas.setAttribute("class", "plot");
  canvas.setAttribute("width", this.coordinates.widthMax);
  canvas.setAttribute("height", this.coordinates.heightMax);
  return canvas;
};

Plotter.prototype.ruler = function() {
  ruler = document.createElement("DIV");
  ruler.setAttribute("class", "plot-ruler");
  ruler.style.borderBottom = "1px dotted black";
  ruler.style.position = "absolute";
  ruler.style.left = "-2px";
  ruler.style.top = "-2px";
  ruler.style.width = "0px";
  ruler.style.height = "0px";
  return ruler;
};

Plotter.prototype.coordinates_ = function() {
  var coordinatesDiv = document.createElement("DIV");
  var table_html =
     "<table border=0 width='100%'><tbody><tr>" +
     "<td colspan=2 class='legend'>Legend: ";
  for (var i = 0; i < this.dataDescription_.length; i++) {
    if (i > 0)
      table_html += ", ";
    table_html += "<span class='legend_item' style='color:" +
      this.nextColor(i) + "'>" + this.dataDescription_[i] + "</span>";
  }
  table_html += "</td></tr><tr>" +
     "<td class='plot-coordinates'><i>move mouse over graph</i></td>" +
     "<td align=right style='color: " + HorizontalMarker.COLOR +
     "'><i>Shift-click to place baseline</i></td>" +
     "</tr></tbody></table>";
  coordinatesDiv.innerHTML = table_html;

  var tr = coordinatesDiv.firstChild.firstChild.childNodes[1];
  this.coordinates_td_ = tr.childNodes[0];
  this.baseline_deltas_td_ = tr.childNodes[1];

  return coordinatesDiv;
};

Plotter.prototype.nextColor = function(i) {
  var index = i % this.colors.length;
  return "rgb(" + this.colors[index][0] + "," +
                  this.colors[index][1] + "," +
                  this.colors[index][2] + ")";
};

Plotter.prototype.log = function(val) {
  document.getElementById('log').appendChild(
    document.createTextNode(val + '\n'));
};