@vitessce/heatmap 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Heatmap.js DELETED
@@ -1,689 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- /* eslint-disable react/display-name */
3
- import React, { useRef, useState, useCallback, useMemo, useEffect, useReducer, forwardRef, } from 'react';
4
- import uuidv4 from 'uuid/v4';
5
- import { deck, luma, HeatmapCompositeTextLayer, PixelatedBitmapLayer, PaddedExpressionHeatmapBitmapLayer, HeatmapBitmapLayer, TILE_SIZE, MAX_ROW_AGG, MIN_ROW_AGG, COLOR_BAR_SIZE, AXIS_MARGIN, DATA_TEXTURE_SIZE, PIXELATED_TEXTURE_PARAMETERS, } from '@vitessce/gl';
6
- import range from 'lodash/range';
7
- import clamp from 'lodash/clamp';
8
- import isEqual from 'lodash/isEqual';
9
- import { getLongestString, DEFAULT_GL_OPTIONS, createDefaultUpdateCellsHover, createDefaultUpdateGenesHover, createDefaultUpdateTracksHover, createDefaultUpdateViewInfo, copyUint8Array, getDefaultColor, } from '@vitessce/utils';
10
- import { layerFilter, getAxisSizes, mouseToHeatmapPosition, heatmapToMousePosition, mouseToCellColorPosition, } from './utils';
11
- import HeatmapWorkerPool from './HeatmapWorkerPool';
12
- // Only allocate the memory once for the container
13
- const paddedExpressionContainer = new Uint8Array(DATA_TEXTURE_SIZE * DATA_TEXTURE_SIZE);
14
- /**
15
- * Should the "padded" implementation
16
- * be used? Only works if the number of heatmap values is
17
- * <= 4096^2 = ~16 million.
18
- * @param {number|null} dataLength The number of heatmap values.
19
- * @returns {boolean} Whether the more efficient implementation should be used.
20
- */
21
- function shouldUsePaddedImplementation(dataLength) {
22
- return dataLength <= DATA_TEXTURE_SIZE ** 2;
23
- }
24
- /**
25
- * A heatmap component for cell x gene matrices.
26
- * @param {object} props
27
- * @param {string} props.uuid The uuid of this component,
28
- * used by tooltips to determine whether to render a tooltip or
29
- * a crosshair.
30
- * @param {string} props.theme The current theme name.
31
- * @param {object} props.viewState The viewState for
32
- * DeckGL.
33
- * @param {function} props.setViewState The viewState setter
34
- * for DeckGL.
35
- * @param {number} props.width The width of the canvas.
36
- * @param {number} props.height The height of the canvas.
37
- * @param {object} props.expressionMatrix An object { rows, cols, matrix },
38
- * where matrix is a flat Uint8Array, rows is a list of cell ID strings,
39
- * and cols is a list of gene ID strings.
40
- * @param {Map} props.cellColors Map of cell ID to color. Optional.
41
- * If defined, the key ordering is used to order the cell axis of the heatmap.
42
- * @param {array} props.cellColorLabels array of labels to place beside cell color
43
- * tracks. Only works for transpose=true.
44
- * @param {function} props.clearPleaseWait The clear please wait callback,
45
- * called when the expression matrix has loaded (is not null).
46
- * @param {function} props.setCellHighlight Callback function called on
47
- * hover with the cell ID. Optional.
48
- * @param {function} props.setGeneHighlight Callback function called on
49
- * hover with the gene ID. Optional.
50
- * @param {function} props.updateViewInfo Callback function that gets called with an
51
- * object { uuid, project() } where project is a function that maps (cellId, geneId)
52
- * to canvas (x,y) coordinates. Used to show tooltips. Optional.
53
- * @param {boolean} props.transpose By default, false.
54
- * @param {string} props.variablesTitle By default, 'Genes'.
55
- * @param {string} props.observationsTitle By default, 'Cells'.
56
- * @param {number} props.useDevicePixels By default, 1. Higher values
57
- * e.g. 2 increase text sharpness.
58
- * @param {boolean} props.hideObservationLabels By default false.
59
- * @param {boolean} props.hideVariableLabels By default false.
60
- * @param {string} props.colormap The name of the colormap function to use.
61
- * @param {array} props.colormapRange A tuple [lower, upper] to adjust the color scale.
62
- * @param {function} props.setColormapRange The setter function for colormapRange.
63
- */
64
- const Heatmap = forwardRef((props, deckRef) => {
65
- const { uuid, theme, viewState: rawViewState, setViewState, width: viewWidth, height: viewHeight, expressionMatrix: expression, cellColors, cellColorLabels = [''], colormap, colormapRange, clearPleaseWait, setComponentHover, setCellHighlight = createDefaultUpdateCellsHover('Heatmap'), setGeneHighlight = createDefaultUpdateGenesHover('Heatmap'), setTrackHighlight = createDefaultUpdateTracksHover('Heatmap'), updateViewInfo = createDefaultUpdateViewInfo('Heatmap'), setIsRendering = () => { }, transpose = false, variablesTitle = 'Genes', observationsTitle = 'Cells', variablesDashes = true, observationsDashes = true, useDevicePixels = 1, hideObservationLabels = false, hideVariableLabels = false, } = props;
66
- const viewState = {
67
- ...rawViewState,
68
- target: (transpose ? [rawViewState.target[1], rawViewState.target[0]] : rawViewState.target),
69
- minZoom: 0,
70
- };
71
- const axisLeftTitle = (transpose ? variablesTitle : observationsTitle);
72
- const axisTopTitle = (transpose ? observationsTitle : variablesTitle);
73
- const workerPool = useMemo(() => new HeatmapWorkerPool(), []);
74
- useEffect(() => {
75
- if (clearPleaseWait && expression) {
76
- clearPleaseWait('expression-matrix');
77
- }
78
- }, [clearPleaseWait, expression]);
79
- const tilesRef = useRef();
80
- const dataRef = useRef();
81
- const [axisLeftLabels, setAxisLeftLabels] = useState([]);
82
- const [axisTopLabels, setAxisTopLabels] = useState([]);
83
- const [numCellColorTracks, setNumCellColorTracks] = useState([]);
84
- // Since we are storing the tile data in a ref,
85
- // and updating it asynchronously when the worker finishes,
86
- // we need to tie it to a piece of state through this iteration value.
87
- const [tileIteration, incTileIteration] = useReducer(i => i + 1, 0);
88
- // We need to keep a backlog of the tasks for the worker thread,
89
- // since the array buffer can only be held by one thread at a time.
90
- const [backlog, setBacklog] = useState([]);
91
- // Store a reference to the matrix Uint8Array in the dataRef,
92
- // since we need to access its array buffer to transfer
93
- // it back and forth from the worker thread.
94
- useEffect(() => {
95
- // Store the expression matrix Uint8Array in the dataRef.
96
- if (expression && expression.matrix
97
- && !shouldUsePaddedImplementation(expression.matrix.length)) {
98
- dataRef.current = copyUint8Array(expression.matrix);
99
- }
100
- }, [dataRef, expression]);
101
- // Check if the ordering of axis labels needs to be changed,
102
- // for example if the cells "selected" (technically just colored)
103
- // have changed.
104
- useEffect(() => {
105
- if (!expression) {
106
- return;
107
- }
108
- const newCellOrdering = (!cellColors || cellColors.size === 0
109
- ? expression.rows
110
- : Array.from(cellColors.keys()));
111
- const oldCellOrdering = (transpose ? axisTopLabels : axisLeftLabels);
112
- if (!isEqual(oldCellOrdering, newCellOrdering)) {
113
- if (transpose) {
114
- setAxisTopLabels(newCellOrdering);
115
- }
116
- else {
117
- setAxisLeftLabels(newCellOrdering);
118
- }
119
- }
120
- }, [expression, cellColors, axisTopLabels, axisLeftLabels, transpose]);
121
- // Set the genes ordering.
122
- useEffect(() => {
123
- if (!expression) {
124
- return;
125
- }
126
- if (transpose) {
127
- setAxisLeftLabels(expression.cols);
128
- }
129
- else {
130
- setAxisTopLabels(expression.cols);
131
- }
132
- }, [expression, transpose]);
133
- const [longestCellLabel, longestGeneLabel] = useMemo(() => {
134
- if (!expression) {
135
- return ['', ''];
136
- }
137
- return [
138
- getLongestString(expression.rows),
139
- getLongestString([...expression.cols, ...cellColorLabels]),
140
- ];
141
- }, [expression, cellColorLabels]);
142
- // Creating a look up dictionary once is faster than calling indexOf many times
143
- // i.e when cell ordering changes.
144
- const expressionRowLookUp = useMemo(() => {
145
- const lookUp = new Map();
146
- if (expression?.rows) {
147
- // eslint-disable-next-line no-return-assign
148
- expression.rows.forEach((cell, j) => (lookUp.set(cell, j)));
149
- }
150
- return lookUp;
151
- }, [expression]);
152
- const width = axisTopLabels.length;
153
- const height = axisLeftLabels.length;
154
- const [axisOffsetLeft, axisOffsetTop] = getAxisSizes(transpose, longestGeneLabel, longestCellLabel, hideObservationLabels, hideVariableLabels);
155
- const [gl, setGlContext] = useState(null);
156
- const offsetTop = axisOffsetTop + COLOR_BAR_SIZE * (transpose ? numCellColorTracks : 0);
157
- const offsetLeft = axisOffsetLeft + COLOR_BAR_SIZE * (transpose ? 0 : numCellColorTracks);
158
- const matrixWidth = viewWidth - offsetLeft;
159
- const matrixHeight = viewHeight - offsetTop;
160
- const matrixLeft = -matrixWidth / 2;
161
- const matrixRight = matrixWidth / 2;
162
- const matrixTop = -matrixHeight / 2;
163
- const matrixBottom = matrixHeight / 2;
164
- const xTiles = Math.ceil(width / TILE_SIZE);
165
- const yTiles = Math.ceil(height / TILE_SIZE);
166
- const widthRatio = 1 - (TILE_SIZE - (width % TILE_SIZE)) / (xTiles * TILE_SIZE);
167
- const heightRatio = 1 - (TILE_SIZE - (height % TILE_SIZE)) / (yTiles * TILE_SIZE);
168
- const tileWidth = (matrixWidth / widthRatio) / (xTiles);
169
- const tileHeight = (matrixHeight / heightRatio) / (yTiles);
170
- const scaleFactor = 2 ** viewState.zoom;
171
- const cellHeight = (matrixHeight * scaleFactor) / height;
172
- const cellWidth = (matrixWidth * scaleFactor) / width;
173
- // Get power of 2 between 1 and 16,
174
- // for number of cells to aggregate together in each direction.
175
- const aggSizeX = clamp(2 ** Math.ceil(Math.log2(1 / cellWidth)), MIN_ROW_AGG, MAX_ROW_AGG);
176
- const aggSizeY = clamp(2 ** Math.ceil(Math.log2(1 / cellHeight)), MIN_ROW_AGG, MAX_ROW_AGG);
177
- const [targetX, targetY] = viewState.target;
178
- // Emit the viewInfo object on viewState updates
179
- // (used by tooltips / crosshair elements).
180
- useEffect(() => {
181
- updateViewInfo({
182
- uuid,
183
- project: (cellId, geneId) => {
184
- const colI = transpose ? axisTopLabels.indexOf(cellId) : axisTopLabels.indexOf(geneId);
185
- const rowI = transpose ? axisLeftLabels.indexOf(geneId) : axisLeftLabels.indexOf(cellId);
186
- return heatmapToMousePosition(colI, rowI, {
187
- offsetLeft,
188
- offsetTop,
189
- targetX: viewState.target[0],
190
- targetY: viewState.target[1],
191
- scaleFactor,
192
- matrixWidth,
193
- matrixHeight,
194
- numRows: height,
195
- numCols: width,
196
- });
197
- },
198
- });
199
- }, [uuid, updateViewInfo, transpose, axisTopLabels, axisLeftLabels, offsetLeft,
200
- offsetTop, viewState, scaleFactor, matrixWidth, matrixHeight, height, width]);
201
- // Listen for viewState changes.
202
- // Do not allow the user to zoom and pan outside of the initial window.
203
- const onViewStateChange = useCallback(({ viewState: nextViewState }) => {
204
- const { zoom: nextZoom } = nextViewState;
205
- const nextScaleFactor = 2 ** nextZoom;
206
- const minTargetX = nextZoom === 0 ? 0 : -(matrixRight - (matrixRight / nextScaleFactor));
207
- const maxTargetX = -1 * minTargetX;
208
- const minTargetY = nextZoom === 0 ? 0 : -(matrixBottom - (matrixBottom / nextScaleFactor));
209
- const maxTargetY = -1 * minTargetY;
210
- // Manipulate view state if necessary to keep the user in the window.
211
- const nextTarget = [
212
- clamp(nextViewState.target[0], minTargetX, maxTargetX),
213
- clamp(nextViewState.target[1], minTargetY, maxTargetY),
214
- ];
215
- setViewState({
216
- zoom: nextZoom,
217
- target: (transpose ? [nextTarget[1], nextTarget[0]] : nextTarget),
218
- });
219
- }, [matrixRight, matrixBottom, transpose, setViewState]);
220
- // If `expression` or `cellOrdering` have changed,
221
- // then new tiles need to be generated,
222
- // so add a new task to the backlog.
223
- useEffect(() => {
224
- if (!expression || !expression.matrix || expression.matrix.length < DATA_TEXTURE_SIZE ** 2) {
225
- return;
226
- }
227
- // Use a uuid to give the task a unique ID,
228
- // to help identify where in the list it is located
229
- // after the worker thread asynchronously sends the data back
230
- // to this thread.
231
- if (axisTopLabels && axisLeftLabels && xTiles && yTiles) {
232
- setBacklog(prev => [...prev, uuidv4()]);
233
- }
234
- }, [dataRef, expression, axisTopLabels, axisLeftLabels, xTiles, yTiles]);
235
- // When the backlog has updated, a new worker job can be submitted if:
236
- // - the backlog has length >= 1 (at least one job is waiting), and
237
- // - buffer.byteLength is not zero, so the worker does not currently "own" the buffer.
238
- useEffect(() => {
239
- if (backlog.length < 1 || shouldUsePaddedImplementation(dataRef.current.length)) {
240
- return;
241
- }
242
- const curr = backlog[backlog.length - 1];
243
- if (dataRef.current
244
- && dataRef.current.buffer.byteLength && expressionRowLookUp.size > 0
245
- && !shouldUsePaddedImplementation(dataRef.current.length)) {
246
- const { cols, matrix } = expression;
247
- const promises = range(yTiles).map(i => range(xTiles).map(async (j) => workerPool.process({
248
- curr,
249
- tileI: i,
250
- tileJ: j,
251
- tileSize: TILE_SIZE,
252
- cellOrdering: transpose ? axisTopLabels : axisLeftLabels,
253
- cols,
254
- transpose,
255
- data: matrix.buffer.slice(),
256
- expressionRowLookUp,
257
- })));
258
- const process = async () => {
259
- const tiles = await Promise.all(promises.flat());
260
- tilesRef.current = tiles.map(i => i.tile);
261
- incTileIteration();
262
- dataRef.current = new Uint8Array(tiles[0].buffer);
263
- const { curr: currWork } = tiles[0];
264
- setBacklog((prev) => {
265
- const currIndex = prev.indexOf(currWork);
266
- return prev.slice(currIndex + 1, prev.length);
267
- });
268
- };
269
- process();
270
- }
271
- }, [axisLeftLabels, axisTopLabels, backlog, expression, transpose,
272
- xTiles, yTiles, workerPool, expressionRowLookUp]);
273
- useEffect(() => {
274
- setIsRendering(backlog.length > 0);
275
- }, [backlog, setIsRendering]);
276
- // Create the padded expression matrix for holding data which can then be bound to the GPU.
277
- const paddedExpressions = useMemo(() => {
278
- const cellOrdering = transpose ? axisTopLabels : axisLeftLabels;
279
- if (expression?.matrix && cellOrdering.length
280
- && gl && shouldUsePaddedImplementation(expression.matrix.length)) {
281
- let newIndex = 0;
282
- for (let cellOrderingIndex = 0; cellOrderingIndex < cellOrdering.length; cellOrderingIndex += 1) {
283
- const cell = cellOrdering[cellOrderingIndex];
284
- newIndex = transpose ? cellOrderingIndex : newIndex;
285
- const cellIndex = expressionRowLookUp.get(cell);
286
- for (let geneIndex = 0; geneIndex < expression.cols.length; geneIndex += 1) {
287
- const index = cellIndex * expression.cols.length + geneIndex;
288
- paddedExpressionContainer[newIndex % (DATA_TEXTURE_SIZE * DATA_TEXTURE_SIZE)] = expression.matrix[index];
289
- newIndex = transpose ? newIndex + cellOrdering.length : newIndex + 1;
290
- }
291
- }
292
- }
293
- return gl ? new luma.Texture2D(gl, {
294
- data: paddedExpressionContainer,
295
- mipmaps: false,
296
- parameters: PIXELATED_TEXTURE_PARAMETERS,
297
- // Each color contains a single luminance value.
298
- // When sampled, rgb are all set to this luminance, alpha is 1.0.
299
- // Reference: https://luma.gl/docs/api-reference/webgl/texture#texture-formats
300
- format: luma.GL.LUMINANCE,
301
- dataFormat: luma.GL.LUMINANCE,
302
- type: luma.GL.UNSIGNED_BYTE,
303
- width: DATA_TEXTURE_SIZE,
304
- height: DATA_TEXTURE_SIZE,
305
- }) : paddedExpressionContainer;
306
- }, [
307
- transpose,
308
- axisTopLabels,
309
- axisLeftLabels,
310
- expression,
311
- expressionRowLookUp,
312
- gl,
313
- ]);
314
- // Update the heatmap tiles if:
315
- // - new tiles are available (`tileIteration` has changed), or
316
- // - the matrix bounds have changed, or
317
- // - the `aggSizeX` or `aggSizeY` have changed, or
318
- // - the cell ordering has changed.
319
- const heatmapLayers = useMemo(() => {
320
- const usePaddedExpressions = expression?.matrix
321
- && shouldUsePaddedImplementation(expression?.matrix.length);
322
- if ((!tilesRef.current || backlog.length) && !usePaddedExpressions) {
323
- return [];
324
- }
325
- if (usePaddedExpressions) {
326
- const cellOrdering = transpose ? axisTopLabels : axisLeftLabels;
327
- // eslint-disable-next-line no-inner-declarations, no-shadow
328
- function getLayer(i, j) {
329
- const { cols } = expression;
330
- return new PaddedExpressionHeatmapBitmapLayer({
331
- id: `heatmapLayer-${i}-${j}`,
332
- image: paddedExpressions,
333
- bounds: [
334
- matrixLeft + j * tileWidth,
335
- matrixTop + i * tileHeight,
336
- matrixLeft + (j + 1) * tileWidth,
337
- matrixTop + (i + 1) * tileHeight,
338
- ],
339
- tileI: i,
340
- tileJ: j,
341
- numXTiles: xTiles,
342
- numYTiles: yTiles,
343
- origDataSize: transpose
344
- ? [cols.length, cellOrdering.length]
345
- : [cellOrdering.length, cols.length],
346
- aggSizeX,
347
- aggSizeY,
348
- colormap,
349
- colorScaleLo: colormapRange[0],
350
- colorScaleHi: colormapRange[1],
351
- updateTriggers: {
352
- image: [axisLeftLabels, axisTopLabels],
353
- bounds: [tileHeight, tileWidth],
354
- },
355
- });
356
- }
357
- const layers = range(yTiles * xTiles).map(index => getLayer(Math.floor(index / xTiles), index % xTiles));
358
- return layers;
359
- }
360
- function getLayer(i, j, tile) {
361
- return new HeatmapBitmapLayer({
362
- id: `heatmapLayer-${tileIteration}-${i}-${j}`,
363
- image: tile,
364
- bounds: [
365
- matrixLeft + j * tileWidth,
366
- matrixTop + i * tileHeight,
367
- matrixLeft + (j + 1) * tileWidth,
368
- matrixTop + (i + 1) * tileHeight,
369
- ],
370
- aggSizeX,
371
- aggSizeY,
372
- colormap,
373
- colorScaleLo: colormapRange[0],
374
- colorScaleHi: colormapRange[1],
375
- updateTriggers: {
376
- image: [axisLeftLabels, axisTopLabels],
377
- bounds: [tileHeight, tileWidth],
378
- },
379
- });
380
- }
381
- const layers = tilesRef.current.map((tile, index) => getLayer(Math.floor(index / xTiles), index % xTiles, tile));
382
- return layers;
383
- }, [expression, backlog.length, transpose, axisTopLabels, axisLeftLabels, yTiles, xTiles,
384
- paddedExpressions, matrixLeft, tileWidth, matrixTop, tileHeight,
385
- aggSizeX, aggSizeY, colormap, colormapRange, tileIteration]);
386
- const axisLeftDashes = (transpose ? variablesDashes : observationsDashes);
387
- const axisTopDashes = (transpose ? observationsDashes : variablesDashes);
388
- // Map cell and gene names to arrays with indices,
389
- // to prepare to render the names in TextLayers.
390
- const axisTopLabelData = useMemo(() => axisTopLabels.map((d, i) => [i, (axisTopDashes ? `- ${d}` : d)]), [axisTopLabels, axisTopDashes]);
391
- const axisLeftLabelData = useMemo(() => axisLeftLabels.map((d, i) => [i, (axisLeftDashes ? `${d} -` : d)]), [axisLeftLabels, axisLeftDashes]);
392
- const cellColorLabelsData = useMemo(() => cellColorLabels.map((d, i) => [i, d && (transpose ? `${d} -` : `- ${d}`)]), [cellColorLabels, transpose]);
393
- const hideTopLabels = (transpose ? hideObservationLabels : hideVariableLabels);
394
- const hideLeftLabels = (transpose ? hideVariableLabels : hideObservationLabels);
395
- // Generate the axis label, axis title, and loading indicator text layers.
396
- const textLayers = [
397
- new HeatmapCompositeTextLayer({
398
- axis: 'left',
399
- id: 'axisLeftCompositeTextLayer',
400
- targetX,
401
- targetY,
402
- scaleFactor,
403
- axisLeftLabelData,
404
- matrixTop,
405
- height,
406
- matrixHeight,
407
- cellHeight,
408
- cellWidth,
409
- axisTopLabelData,
410
- matrixLeft,
411
- width,
412
- matrixWidth,
413
- viewHeight,
414
- viewWidth,
415
- theme,
416
- axisLeftTitle,
417
- axisTopTitle,
418
- axisOffsetLeft,
419
- axisOffsetTop,
420
- hideTopLabels,
421
- hideLeftLabels,
422
- transpose,
423
- }),
424
- new HeatmapCompositeTextLayer({
425
- axis: 'top',
426
- id: 'axisTopCompositeTextLayer',
427
- targetX,
428
- targetY,
429
- scaleFactor,
430
- axisLeftLabelData,
431
- matrixTop,
432
- height,
433
- matrixHeight,
434
- cellHeight,
435
- cellWidth,
436
- axisTopLabelData,
437
- matrixLeft,
438
- width,
439
- matrixWidth,
440
- viewHeight,
441
- viewWidth,
442
- theme,
443
- axisLeftTitle,
444
- axisTopTitle,
445
- axisOffsetLeft,
446
- axisOffsetTop,
447
- cellColorLabelsData,
448
- hideTopLabels,
449
- hideLeftLabels,
450
- transpose,
451
- }),
452
- new HeatmapCompositeTextLayer({
453
- axis: 'corner',
454
- id: 'cellColorLabelCompositeTextLayer',
455
- targetX,
456
- targetY,
457
- scaleFactor,
458
- axisLeftLabelData,
459
- matrixTop,
460
- height,
461
- matrixHeight,
462
- cellHeight,
463
- cellWidth,
464
- axisTopLabelData,
465
- matrixLeft,
466
- width,
467
- matrixWidth,
468
- viewHeight,
469
- viewWidth,
470
- theme,
471
- axisLeftTitle,
472
- axisTopTitle,
473
- axisOffsetLeft,
474
- axisOffsetTop,
475
- cellColorLabelsData,
476
- hideTopLabels,
477
- hideLeftLabels,
478
- transpose,
479
- }),
480
- ];
481
- useEffect(() => {
482
- setNumCellColorTracks(cellColorLabels.length);
483
- }, [cellColorLabels]);
484
- // Create the left color bar with a BitmapLayer.
485
- // TODO: find a way to do aggregation for this as well.
486
- const cellColorsTilesList = useMemo(() => {
487
- if (!cellColors) {
488
- return null;
489
- }
490
- let cellId;
491
- let offset;
492
- let color;
493
- let rowI;
494
- const cellOrdering = (transpose ? axisTopLabels : axisLeftLabels);
495
- const colorBarTileWidthPx = (transpose ? TILE_SIZE : 1);
496
- const colorBarTileHeightPx = (transpose ? 1 : TILE_SIZE);
497
- const result = range(numCellColorTracks).map((track) => {
498
- const trackResult = range((transpose ? xTiles : yTiles)).map((i) => {
499
- const tileData = new Uint8ClampedArray(TILE_SIZE * 1 * 4);
500
- range(TILE_SIZE).forEach((tileY) => {
501
- rowI = (i * TILE_SIZE) + tileY; // the row / cell index
502
- if (rowI < cellOrdering.length) {
503
- cellId = cellOrdering[rowI];
504
- color = cellColors.get(cellId);
505
- offset = (transpose ? tileY : (TILE_SIZE - tileY - 1)) * 4;
506
- if (color) {
507
- // allows color to be [R, G, B] or array of arrays of [R, G, B]
508
- if (typeof color[0] !== 'number')
509
- color = color[track] ?? getDefaultColor(theme);
510
- const [rValue, gValue, bValue] = color;
511
- tileData[offset + 0] = rValue;
512
- tileData[offset + 1] = gValue;
513
- tileData[offset + 2] = bValue;
514
- tileData[offset + 3] = 255;
515
- }
516
- }
517
- });
518
- return new ImageData(tileData, colorBarTileWidthPx, colorBarTileHeightPx);
519
- });
520
- return trackResult;
521
- });
522
- return result;
523
- }, [cellColors, transpose, axisTopLabels, axisLeftLabels,
524
- numCellColorTracks, xTiles, yTiles, theme]);
525
- const cellColorsLayersList = useMemo(() => {
526
- if (!cellColorsTilesList) {
527
- return [];
528
- }
529
- const result = cellColorsTilesList.map((cellColorsTiles, track) => (cellColorsTiles
530
- ? cellColorsTiles.map((tile, i) => new PixelatedBitmapLayer({
531
- id: `${(transpose ? 'colorsTopLayer' : 'colorsLeftLayer')}-${track}-${i}-${uuidv4()}`,
532
- image: tile,
533
- bounds: (transpose ? [
534
- matrixLeft + i * tileWidth,
535
- -matrixHeight / 2,
536
- matrixLeft + (i + 1) * tileWidth,
537
- matrixHeight / 2,
538
- ] : [
539
- -matrixWidth / 2,
540
- matrixTop + i * tileHeight,
541
- matrixWidth / 2,
542
- matrixTop + (i + 1) * tileHeight,
543
- ]),
544
- }))
545
- : []));
546
- return (result);
547
- }, [cellColorsTilesList, matrixTop, matrixLeft, matrixHeight,
548
- matrixWidth, tileWidth, tileHeight, transpose]);
549
- const layers = heatmapLayers
550
- .concat(textLayers)
551
- .concat(...cellColorsLayersList);
552
- // Set up the onHover function.
553
- function onHover(info, event) {
554
- if (!expression) {
555
- return;
556
- }
557
- const { x: mouseX, y: mouseY } = event.offsetCenter;
558
- const [trackColI, trackI] = mouseToCellColorPosition(mouseX, mouseY, {
559
- axisOffsetTop,
560
- axisOffsetLeft,
561
- offsetTop,
562
- offsetLeft,
563
- colorBarSize: COLOR_BAR_SIZE,
564
- numCellColorTracks,
565
- transpose,
566
- targetX,
567
- targetY,
568
- scaleFactor,
569
- matrixWidth,
570
- matrixHeight,
571
- numRows: height,
572
- numCols: width,
573
- });
574
- if (trackI === null || trackColI === null) {
575
- setTrackHighlight(null);
576
- }
577
- else {
578
- const obsI = expression.rows.indexOf(axisTopLabels[trackColI]);
579
- const cellIndex = expression.rows[obsI];
580
- setTrackHighlight([cellIndex, trackI, mouseX, mouseY]);
581
- }
582
- const [colI, rowI] = mouseToHeatmapPosition(mouseX, mouseY, {
583
- offsetLeft,
584
- offsetTop,
585
- targetX,
586
- targetY,
587
- scaleFactor,
588
- matrixWidth,
589
- matrixHeight,
590
- numRows: height,
591
- numCols: width,
592
- });
593
- if (colI === null) {
594
- if (transpose) {
595
- setCellHighlight(null);
596
- }
597
- else {
598
- setGeneHighlight(null);
599
- }
600
- }
601
- if (rowI === null) {
602
- if (transpose) {
603
- setGeneHighlight(null);
604
- }
605
- else {
606
- setCellHighlight(null);
607
- }
608
- }
609
- const obsI = expression.rows.indexOf(transpose
610
- ? axisTopLabels[colI]
611
- : axisLeftLabels[rowI]);
612
- const varI = expression.cols.indexOf(transpose
613
- ? axisLeftLabels[rowI]
614
- : axisTopLabels[colI]);
615
- const obsId = expression.rows[obsI];
616
- const varId = expression.cols[varI];
617
- if (setComponentHover) {
618
- setComponentHover();
619
- }
620
- setCellHighlight(obsId || null);
621
- setGeneHighlight(varId || null);
622
- }
623
- const cellColorsViews = useMemo(() => {
624
- const result = range(numCellColorTracks).map((track) => {
625
- let view;
626
- if (transpose) {
627
- view = new deck.OrthographicView({
628
- id: `colorsTop-${track}`,
629
- controller: true,
630
- x: offsetLeft,
631
- y: axisOffsetTop + track * COLOR_BAR_SIZE,
632
- width: matrixWidth,
633
- height: COLOR_BAR_SIZE - AXIS_MARGIN,
634
- });
635
- }
636
- else {
637
- view = new deck.OrthographicView({
638
- id: `colorsLeft-${track}`,
639
- controller: true,
640
- x: axisOffsetLeft + track * COLOR_BAR_SIZE,
641
- y: offsetTop,
642
- width: COLOR_BAR_SIZE - AXIS_MARGIN,
643
- height: matrixHeight,
644
- });
645
- }
646
- return view;
647
- });
648
- return result;
649
- }, [numCellColorTracks, transpose, offsetLeft, axisOffsetTop,
650
- matrixWidth, axisOffsetLeft, offsetTop, matrixHeight]);
651
- return (_jsx(deck.DeckGL, { id: `deckgl-overlay-${uuid}`, ref: deckRef, onWebGLInitialized: setGlContext, views: [
652
- // Note that there are multiple views here,
653
- // but only one viewState.
654
- new deck.OrthographicView({
655
- id: 'heatmap',
656
- controller: true,
657
- x: offsetLeft,
658
- y: offsetTop,
659
- width: matrixWidth,
660
- height: matrixHeight,
661
- }),
662
- new deck.OrthographicView({
663
- id: 'axisLeft',
664
- controller: false,
665
- x: 0,
666
- y: offsetTop,
667
- width: axisOffsetLeft,
668
- height: matrixHeight,
669
- }),
670
- new deck.OrthographicView({
671
- id: 'axisTop',
672
- controller: false,
673
- x: offsetLeft,
674
- y: 0,
675
- width: matrixWidth,
676
- height: axisOffsetTop,
677
- }),
678
- new deck.OrthographicView({
679
- id: 'cellColorLabel',
680
- controller: false,
681
- x: (transpose ? 0 : axisOffsetLeft),
682
- y: (transpose ? axisOffsetTop : 0),
683
- width: (transpose ? axisOffsetLeft : COLOR_BAR_SIZE * numCellColorTracks),
684
- height: (transpose ? COLOR_BAR_SIZE * numCellColorTracks : axisOffsetTop),
685
- }),
686
- ...cellColorsViews,
687
- ], layers: layers, layerFilter: layerFilter, getCursor: interactionState => (interactionState.isDragging ? 'grabbing' : 'default'), glOptions: DEFAULT_GL_OPTIONS, onViewStateChange: onViewStateChange, viewState: viewState, onHover: onHover, useDevicePixels: useDevicePixels }));
688
- });
689
- export default Heatmap;