-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathplot.js
443 lines (382 loc) · 13.3 KB
/
plot.js
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var tinycolor = require('tinycolor2');
var Registry = require('../../registry');
var Lib = require('../../lib');
var Colorscale = require('../../components/colorscale');
var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
var maxRowLength = require('./max_row_length');
module.exports = function(gd, plotinfo, cdheatmaps) {
for(var i = 0; i < cdheatmaps.length; i++) {
plotOne(gd, plotinfo, cdheatmaps[i]);
}
};
function plotOne(gd, plotinfo, cd) {
var cd0 = cd[0];
var trace = cd0.trace;
var uid = trace.uid;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var id = 'hm' + uid;
// in case this used to be a contour map
fullLayout._paper.selectAll('.contour' + uid).remove();
fullLayout._infolayer.selectAll('g.rangeslider-container')
.selectAll('.contour' + uid).remove();
if(trace.visible !== true) {
fullLayout._paper.selectAll('.' + id).remove();
fullLayout._infolayer.selectAll('.cb' + uid).remove();
return;
}
var z = cd0.z;
var x = cd0.x;
var y = cd0.y;
var xc = cd0.xCenter;
var yc = cd0.yCenter;
var isContour = Registry.traceIs(trace, 'contour');
var zsmooth = isContour ? 'best' : trace.zsmooth;
// get z dims
var m = z.length;
var n = maxRowLength(z);
var xrev = false;
var yrev = false;
var left, right, temp, top, bottom, i;
// TODO: if there are multiple overlapping categorical heatmaps,
// or if we allow category sorting, then the categories may not be
// sequential... may need to reorder and/or expand z
// Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
// figure out if either axis is reversed (y is usually reversed, in pixel coords)
// also clip the image to maximum 50% outside the visible plot area
// bigger image lets you pan more naturally, but slows performance.
// TODO: use low-resolution images outside the visible plot for panning
// these while loops find the first and last brick bounds that are defined
// (in case of log of a negative)
i = 0;
while(left === undefined && i < x.length - 1) {
left = xa.c2p(x[i]);
i++;
}
i = x.length - 1;
while(right === undefined && i > 0) {
right = xa.c2p(x[i]);
i--;
}
if(right < left) {
temp = right;
right = left;
left = temp;
xrev = true;
}
i = 0;
while(top === undefined && i < y.length - 1) {
top = ya.c2p(y[i]);
i++;
}
i = y.length - 1;
while(bottom === undefined && i > 0) {
bottom = ya.c2p(y[i]);
i--;
}
if(bottom < top) {
temp = top;
top = bottom;
bottom = temp;
yrev = true;
}
// for contours with heatmap fill, we generate the boundaries based on
// brick centers but then use the brick edges for drawing the bricks
if(isContour) {
xc = x;
yc = y;
x = cd0.xfill;
y = cd0.yfill;
}
// make an image that goes at most half a screen off either side, to keep
// time reasonable when you zoom in. if zsmooth is true/fast, don't worry
// about this, because zooming doesn't increase number of pixels
// if zsmooth is best, don't include anything off screen because it takes too long
if(zsmooth !== 'fast') {
var extra = zsmooth === 'best' ? 0 : 0.5;
left = Math.max(-extra * xa._length, left);
right = Math.min((1 + extra) * xa._length, right);
top = Math.max(-extra * ya._length, top);
bottom = Math.min((1 + extra) * ya._length, bottom);
}
var imageWidth = Math.round(right - left),
imageHeight = Math.round(bottom - top);
// setup image nodes
// if image is entirely off-screen, don't even draw it
var isOffScreen = (imageWidth <= 0 || imageHeight <= 0);
var plotgroup = plotinfo.plot.select('.imagelayer')
.selectAll('g.hm.' + id)
.data(isOffScreen ? [] : [0]);
plotgroup.enter().append('g')
.classed('hm', true)
.classed(id, true);
plotgroup.exit().remove();
if(isOffScreen) return;
// generate image data
var canvasW, canvasH;
if(zsmooth === 'fast') {
canvasW = n;
canvasH = m;
} else {
canvasW = imageWidth;
canvasH = imageHeight;
}
var canvas = document.createElement('canvas');
canvas.width = canvasW;
canvas.height = canvasH;
var context = canvas.getContext('2d');
var sclFunc = Colorscale.makeColorScaleFunc(
Colorscale.extractScale(
trace.colorscale,
trace.zmin,
trace.zmax
),
{ noNumericCheck: true, returnArray: true }
);
// map brick boundaries to image pixels
var xpx,
ypx;
if(zsmooth === 'fast') {
xpx = xrev ?
function(index) { return n - 1 - index; } :
Lib.identity;
ypx = yrev ?
function(index) { return m - 1 - index; } :
Lib.identity;
}
else {
xpx = function(index) {
return Lib.constrain(Math.round(xa.c2p(x[index]) - left),
0, imageWidth);
};
ypx = function(index) {
return Lib.constrain(Math.round(ya.c2p(y[index]) - top),
0, imageHeight);
};
}
// build the pixel map brick-by-brick
// cruise through z-matrix row-by-row
// build a brick at each z-matrix value
var yi = ypx(0);
var yb = [yi, yi];
var xbi = xrev ? 0 : 1;
var ybi = yrev ? 0 : 1;
// for collecting an average luminosity of the heatmap
var pixcount = 0;
var rcount = 0;
var gcount = 0;
var bcount = 0;
var xb, j, xi, v, row, c;
function setColor(v, pixsize) {
if(v !== undefined) {
var c = sclFunc(v);
c[0] = Math.round(c[0]);
c[1] = Math.round(c[1]);
c[2] = Math.round(c[2]);
pixcount += pixsize;
rcount += c[0] * pixsize;
gcount += c[1] * pixsize;
bcount += c[2] * pixsize;
return c;
}
return [0, 0, 0, 0];
}
function interpColor(r0, r1, xinterp, yinterp) {
var z00 = r0[xinterp.bin0];
if(z00 === undefined) return setColor(undefined, 1);
var z01 = r0[xinterp.bin1],
z10 = r1[xinterp.bin0],
z11 = r1[xinterp.bin1],
dx = (z01 - z00) || 0,
dy = (z10 - z00) || 0,
dxy;
// the bilinear interpolation term needs different calculations
// for all the different permutations of missing data
// among the neighbors of the main point, to ensure
// continuity across brick boundaries.
if(z01 === undefined) {
if(z11 === undefined) dxy = 0;
else if(z10 === undefined) dxy = 2 * (z11 - z00);
else dxy = (2 * z11 - z10 - z00) * 2 / 3;
}
else if(z11 === undefined) {
if(z10 === undefined) dxy = 0;
else dxy = (2 * z00 - z01 - z10) * 2 / 3;
}
else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3;
else dxy = (z11 + z00 - z01 - z10);
return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
}
if(zsmooth) { // best or fast, works fastest with imageData
var pxIndex = 0,
pixels;
try {
pixels = new Uint8Array(imageWidth * imageHeight * 4);
}
catch(e) {
pixels = new Array(imageWidth * imageHeight * 4);
}
if(zsmooth === 'best') {
var xForPx = xc || x;
var yForPx = yc || y;
var xPixArray = new Array(xForPx.length);
var yPixArray = new Array(yForPx.length);
var xinterpArray = new Array(imageWidth);
var findInterpX = xc ? findInterpFromCenters : findInterp;
var findInterpY = yc ? findInterpFromCenters : findInterp;
var yinterp, r0, r1;
// first make arrays of x and y pixel locations of brick boundaries
for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);
// then make arrays of interpolations
// (bin0=closest, bin1=next, frac=fractional dist.)
for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);
// now do the interpolations and fill the png
for(j = 0; j < imageHeight; j++) {
yinterp = findInterpY(j, yPixArray);
r0 = z[yinterp.bin0];
r1 = z[yinterp.bin1];
for(i = 0; i < imageWidth; i++, pxIndex += 4) {
c = interpColor(r0, r1, xinterpArray[i], yinterp);
putColor(pixels, pxIndex, c);
}
}
}
else { // zsmooth = fast
for(j = 0; j < m; j++) {
row = z[j];
yb = ypx(j);
for(i = 0; i < imageWidth; i++) {
c = setColor(row[i], 1);
pxIndex = (yb * imageWidth + xpx(i)) * 4;
putColor(pixels, pxIndex, c);
}
}
}
var imageData = context.createImageData(imageWidth, imageHeight);
try {
imageData.data.set(pixels);
}
catch(e) {
var pxArray = imageData.data,
dlen = pxArray.length;
for(j = 0; j < dlen; j ++) {
pxArray[j] = pixels[j];
}
}
context.putImageData(imageData, 0, 0);
} else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect
// gaps do not need to be exact integers, but if they *are* we will get
// cleaner edges by rounding at least one edge
var xGap = trace.xgap;
var yGap = trace.ygap;
var xGapLeft = Math.floor(xGap / 2);
var yGapTop = Math.floor(yGap / 2);
for(j = 0; j < m; j++) {
row = z[j];
yb.reverse();
yb[ybi] = ypx(j + 1);
if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
continue;
}
xi = xpx(0);
xb = [xi, xi];
for(i = 0; i < n; i++) {
// build one color brick!
xb.reverse();
xb[xbi] = xpx(i + 1);
if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
continue;
}
v = row[i];
c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
context.fillStyle = 'rgba(' + c.join(',') + ')';
context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop,
xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
}
}
}
rcount = Math.round(rcount / pixcount);
gcount = Math.round(gcount / pixcount);
bcount = Math.round(bcount / pixcount);
var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');
gd._hmpixcount = (gd._hmpixcount||0) + pixcount;
gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance();
var image3 = plotgroup.selectAll('image')
.data(cd);
image3.enter().append('svg:image').attr({
xmlns: xmlnsNamespaces.svg,
preserveAspectRatio: 'none'
});
image3.attr({
height: imageHeight,
width: imageWidth,
x: left,
y: top,
'xlink:href': canvas.toDataURL('image/png')
});
image3.exit().remove();
}
// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
function findInterp(pixel, pixArray) {
var maxBin = pixArray.length - 2;
var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
var pix0 = pixArray[bin];
var pix1 = pixArray[bin + 1];
var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
var bin0 = Math.round(interp);
var frac = Math.abs(interp - bin0);
if(!interp || interp === maxBin || !frac) {
return {
bin0: bin0,
bin1: bin0,
frac: 0
};
}
return {
bin0: bin0,
frac: frac,
bin1: Math.round(bin0 + frac / (interp - bin0))
};
}
function findInterpFromCenters(pixel, centerPixArray) {
var maxBin = centerPixArray.length - 1;
var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
var pix0 = centerPixArray[bin];
var pix1 = centerPixArray[bin + 1];
var frac = ((pixel - pix0) / (pix1 - pix0)) || 0;
if(frac <= 0) {
return {
bin0: bin,
bin1: bin,
frac: 0
};
}
if(frac < 0.5) {
return {
bin0: bin,
bin1: bin + 1,
frac: frac
};
}
return {
bin0: bin + 1,
bin1: bin,
frac: 1 - frac
};
}
function putColor(pixels, pxIndex, c) {
pixels[pxIndex] = c[0];
pixels[pxIndex + 1] = c[1];
pixels[pxIndex + 2] = c[2];
pixels[pxIndex + 3] = Math.round(c[3] * 255);
}