@vitessce/scatterplot-gating 2.0.3-beta.0 → 3.0.0

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.
@@ -0,0 +1,452 @@
1
+ import React, {
2
+ useState, useEffect, useCallback, useMemo,
3
+ } from 'react';
4
+ import plur from 'plur';
5
+ import { extent } from 'd3-array';
6
+ import { isEqual } from 'lodash-es';
7
+ import {
8
+ capitalize, commaNumber,
9
+ getCellColors,
10
+ getValueTransformFunction, VALUE_TRANSFORM_OPTIONS,
11
+ } from '@vitessce/utils';
12
+ import {
13
+ TitleInfo,
14
+ useDeckCanvasSize, useReady, useUrls,
15
+ useUint8FeatureSelection,
16
+ useExpressionValueGetter,
17
+ useObsSetsData,
18
+ useFeatureSelection,
19
+ useObsFeatureMatrixIndices,
20
+ useCoordination,
21
+ useLoaders,
22
+ useSetComponentHover,
23
+ useSetComponentViewInfo,
24
+ } from '@vitessce/vit-s';
25
+ import { getCellSetPolygons, mergeObsSets, setObsSelection } from '@vitessce/sets-utils';
26
+ import {
27
+ Scatterplot, ScatterplotTooltipSubscriber, ScatterplotOptions,
28
+ getPointSizeDevicePixels,
29
+ getPointOpacity,
30
+ EmptyMessage,
31
+ } from '@vitessce/scatterplot';
32
+ import { ViewType, COMPONENT_COORDINATION_TYPES } from '@vitessce/constants-internal';
33
+ import GatingScatterplotOptions from './GatingScatterplotOptions.js';
34
+
35
+ /**
36
+ * A subscriber component for the gating scatterplot.
37
+ * @param {object} props
38
+ * @param {number} props.uuid The unique identifier for this component.
39
+ * @param {string} props.theme The current theme name.
40
+ * @param {object} props.coordinationScopes The mapping from coordination types to coordination
41
+ * scopes.
42
+ * @param {boolean} props.disableTooltip Should the tooltip be disabled?
43
+ * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,
44
+ * to call when the component has been removed from the grid.
45
+ * @param {number} props.averageFillDensity Override the average fill density calculation
46
+ * when using dynamic opacity mode.
47
+ */
48
+ export function GatingSubscriber(props) {
49
+ const {
50
+ uuid,
51
+ coordinationScopes,
52
+ removeGridComponent,
53
+ theme,
54
+ disableTooltip = false,
55
+ title: titleOverride,
56
+ // Average fill density for dynamic opacity calculation.
57
+ averageFillDensity,
58
+ } = props;
59
+
60
+ const loaders = useLoaders();
61
+ const setComponentHover = useSetComponentHover();
62
+ const setComponentViewInfo = useSetComponentViewInfo(uuid);
63
+
64
+ // Get "props" from the coordination space.
65
+ const [{
66
+ dataset,
67
+ obsType,
68
+ featureType,
69
+ featureValueType,
70
+ embeddingZoom: zoom,
71
+ embeddingTargetX: targetX,
72
+ embeddingTargetY: targetY,
73
+ embeddingTargetZ: targetZ,
74
+ obsFilter: cellFilter,
75
+ obsHighlight: cellHighlight,
76
+ obsSetSelection: cellSetSelection,
77
+ obsSetColor: cellSetColor,
78
+ obsColorEncoding: cellColorEncoding,
79
+ additionalObsSets: additionalCellSets,
80
+ embeddingObsSetPolygonsVisible: cellSetPolygonsVisible,
81
+ embeddingObsSetLabelsVisible: cellSetLabelsVisible,
82
+ embeddingObsSetLabelSize: cellSetLabelSize,
83
+ embeddingObsRadius: cellRadiusFixed,
84
+ embeddingObsRadiusMode: cellRadiusMode,
85
+ embeddingObsOpacity: cellOpacityFixed,
86
+ embeddingObsOpacityMode: cellOpacityMode,
87
+ featureValueColormap: geneExpressionColormap,
88
+ featureValueColormapRange: geneExpressionColormapRange,
89
+ featureSelection: gatingFeatureSelectionColor,
90
+ featureValueTransform,
91
+ featureValueTransformCoefficient,
92
+ gatingFeatureSelectionX,
93
+ gatingFeatureSelectionY,
94
+ }, {
95
+ setEmbeddingZoom: setZoom,
96
+ setEmbeddingTargetX: setTargetX,
97
+ setEmbeddingTargetY: setTargetY,
98
+ setEmbeddingTargetZ: setTargetZ,
99
+ setObsFilter: setCellFilter,
100
+ setObsSetSelection: setCellSetSelection,
101
+ setObsHighlight: setCellHighlight,
102
+ setObsSetColor: setCellSetColor,
103
+ setObsColorEncoding: setCellColorEncoding,
104
+ setAdditionalObsSets: setAdditionalCellSets,
105
+ setEmbeddingObsSetPolygonsVisible: setCellSetPolygonsVisible,
106
+ setEmbeddingObsSetLabelsVisible: setCellSetLabelsVisible,
107
+ setEmbeddingObsSetLabelSize: setCellSetLabelSize,
108
+ setEmbeddingObsRadius: setCellRadiusFixed,
109
+ setEmbeddingObsRadiusMode: setCellRadiusMode,
110
+ setEmbeddingObsOpacity: setCellOpacityFixed,
111
+ setEmbeddingObsOpacityMode: setCellOpacityMode,
112
+ setFeatureValueColormap: setGeneExpressionColormap,
113
+ setFeatureValueColormapRange: setGeneExpressionColormapRange,
114
+ setFeatureValueTransform,
115
+ setFeatureValueTransformCoefficient,
116
+ setGatingFeatureSelectionX,
117
+ setGatingFeatureSelectionY,
118
+ }] = useCoordination(
119
+ COMPONENT_COORDINATION_TYPES[ViewType.GATING],
120
+ coordinationScopes,
121
+ );
122
+
123
+ const [urls, addUrl] = useUrls(loaders, dataset);
124
+ const [width, height, deckRef] = useDeckCanvasSize();
125
+
126
+ const title = useMemo(() => {
127
+ if (titleOverride) {
128
+ return titleOverride;
129
+ }
130
+ if (!(gatingFeatureSelectionX && gatingFeatureSelectionY)) {
131
+ return 'Gating';
132
+ }
133
+ return `Gating (${gatingFeatureSelectionX} vs ${gatingFeatureSelectionY})`;
134
+ }, [titleOverride, gatingFeatureSelectionX, gatingFeatureSelectionY]);
135
+
136
+ const featureSelectionX = useMemo(() => (
137
+ gatingFeatureSelectionX ? [gatingFeatureSelectionX] : null
138
+ ), [gatingFeatureSelectionX]);
139
+ const featureSelectionY = useMemo(() => (
140
+ gatingFeatureSelectionY ? [gatingFeatureSelectionY] : null
141
+ ), [gatingFeatureSelectionY]);
142
+
143
+ // Get data from loaders using the data hooks.
144
+ const [{ obsSets: cellSets }, obsSetsStatus] = useObsSetsData(
145
+ loaders, dataset, addUrl, false,
146
+ { setObsSetSelection: setCellSetSelection, setObsSetColor: setCellSetColor },
147
+ { obsSetSelection: cellSetSelection, obsSetColor: cellSetColor },
148
+ { obsType },
149
+ );
150
+ // eslint-disable-next-line no-unused-vars
151
+ const [expressionDataColor, loadedColor, featureSelectionColorStatus] = useFeatureSelection(
152
+ loaders, dataset, false, gatingFeatureSelectionColor,
153
+ { obsType, featureType, featureValueType },
154
+ );
155
+ // eslint-disable-next-line no-unused-vars
156
+ const [expressionDataX, loadedX, featureSelectionXStatus] = useFeatureSelection(
157
+ loaders, dataset, false, featureSelectionX,
158
+ { obsType, featureType, featureValueType },
159
+ );
160
+ // eslint-disable-next-line no-unused-vars
161
+ const [expressionDataY, loadedY, featureSelectionYStatus] = useFeatureSelection(
162
+ loaders, dataset, false, featureSelectionY,
163
+ { obsType, featureType, featureValueType },
164
+ );
165
+ const [{ obsIndex, featureIndex }, matrixIndicesStatus] = useObsFeatureMatrixIndices(
166
+ loaders, dataset, addUrl, false,
167
+ { obsType, featureType, featureValueType },
168
+ );
169
+ const cellsCount = obsIndex?.length || 0;
170
+
171
+ const isReady = useReady([
172
+ obsSetsStatus,
173
+ featureSelectionColorStatus,
174
+ featureSelectionXStatus,
175
+ featureSelectionYStatus,
176
+ matrixIndicesStatus,
177
+ ]);
178
+
179
+ // Generate a new cells object with a mapping added for the user selected genes.
180
+ const obsXY = useMemo(() => {
181
+ if (!(cellsCount && expressionDataX?.[0] && expressionDataY?.[0]
182
+ && featureSelectionX && featureSelectionY
183
+ )) {
184
+ return null;
185
+ }
186
+
187
+ // Get transform coefficient for log and arcsinh
188
+ let coefficient = 1;
189
+ const parsedTransformCoefficient = Number(featureValueTransformCoefficient);
190
+ if (!Number.isNaN(parsedTransformCoefficient) && parsedTransformCoefficient > 0) {
191
+ coefficient = parsedTransformCoefficient;
192
+ }
193
+
194
+ // Set transform function
195
+ const transformFunction = getValueTransformFunction(
196
+ featureValueTransform,
197
+ coefficient,
198
+ );
199
+
200
+ const obsX = new Float32Array(cellsCount);
201
+ const obsY = new Float32Array(cellsCount);
202
+ for (let i = 0; i < cellsCount; i += 1) {
203
+ obsX[i] = transformFunction(expressionDataX[0][i]);
204
+ obsY[i] = transformFunction(expressionDataY[0][i]);
205
+ }
206
+ return {
207
+ data: [obsX, obsY],
208
+ shape: [2, cellsCount],
209
+ };
210
+ }, [cellsCount, expressionDataX, expressionDataY,
211
+ featureValueTransform, featureValueTransformCoefficient,
212
+ featureSelectionX, featureSelectionY,
213
+ ]);
214
+
215
+ const [dynamicCellRadius, setDynamicCellRadius] = useState(cellRadiusFixed);
216
+ const [dynamicCellOpacity, setDynamicCellOpacity] = useState(cellOpacityFixed);
217
+
218
+ const mergedCellSets = useMemo(() => mergeObsSets(
219
+ cellSets, additionalCellSets,
220
+ ), [cellSets, additionalCellSets]);
221
+
222
+ const setCellSelectionProp = useCallback((v) => {
223
+ setObsSelection(
224
+ v, additionalCellSets, cellSetColor,
225
+ setCellSetSelection, setAdditionalCellSets, setCellSetColor,
226
+ setCellColorEncoding,
227
+ );
228
+ }, [additionalCellSets, cellSetColor, setCellColorEncoding,
229
+ setAdditionalCellSets, setCellSetColor, setCellSetSelection]);
230
+
231
+ const cellColors = useMemo(() => getCellColors({
232
+ cellSets: mergedCellSets,
233
+ cellSetSelection,
234
+ cellSetColor,
235
+ obsIndex,
236
+ theme,
237
+ }), [mergedCellSets, theme,
238
+ cellSetSelection, cellSetColor, obsIndex]);
239
+
240
+ // cellSetPolygonCache is an array of tuples like [(key0, val0), (key1, val1), ...],
241
+ // where the keys are cellSetSelection arrays.
242
+ const [cellSetPolygonCache, setCellSetPolygonCache] = useState([]);
243
+ const cacheHas = (cache, key) => cache.findIndex(el => isEqual(el[0], key)) !== -1;
244
+ const cacheGet = (cache, key) => cache.find(el => isEqual(el[0], key))?.[1];
245
+ const cellSetPolygons = useMemo(() => {
246
+ if ((cellSetLabelsVisible || cellSetPolygonsVisible)
247
+ && !cacheHas(cellSetPolygonCache, cellSetSelection)
248
+ && mergedCellSets?.tree?.length
249
+ && obsXY
250
+ && obsIndex
251
+ && cellSetColor?.length) {
252
+ const newCellSetPolygons = getCellSetPolygons({
253
+ obsIndex,
254
+ obsEmbedding: obsXY,
255
+ cellSets: mergedCellSets,
256
+ cellSetSelection,
257
+ cellSetColor,
258
+ theme,
259
+ });
260
+ setCellSetPolygonCache(cache => [...cache, [cellSetSelection, newCellSetPolygons]]);
261
+ return newCellSetPolygons;
262
+ }
263
+ return cacheGet(cellSetPolygonCache, cellSetSelection) || [];
264
+ }, [cellSetPolygonsVisible, cellSetPolygonCache, cellSetLabelsVisible, theme,
265
+ obsIndex, obsXY, mergedCellSets, cellSetSelection, cellSetColor]);
266
+
267
+
268
+ const cellSelection = useMemo(() => Array.from(cellColors.keys()), [cellColors]);
269
+
270
+ const [xRange, yRange, xExtent, yExtent, numCells] = useMemo(() => {
271
+ if (obsXY && obsXY.data && obsXY.shape) {
272
+ const cellCount = obsXY.shape[1];
273
+ const xE = extent(obsXY.data[0]);
274
+ const yE = extent(obsXY.data[1]);
275
+ const xR = xE[1] - xE[0];
276
+ const yR = yE[1] - yE[0];
277
+ return [xR, yR, xE, yE, cellCount];
278
+ }
279
+ return [null, null, null, null, null];
280
+ }, [obsXY]);
281
+
282
+ // After cells have loaded or changed,
283
+ // compute the cell radius scale based on the
284
+ // extents of the cell coordinates on the x/y axes.
285
+ useEffect(() => {
286
+ if (xRange && yRange) {
287
+ const pointSizeDevicePixels = getPointSizeDevicePixels(
288
+ window.devicePixelRatio, zoom, xRange, yRange, width, height,
289
+ );
290
+ setDynamicCellRadius(pointSizeDevicePixels);
291
+
292
+ const nextCellOpacityScale = getPointOpacity(
293
+ zoom, xRange, yRange, width, height, numCells, averageFillDensity,
294
+ );
295
+ setDynamicCellOpacity(nextCellOpacityScale);
296
+
297
+ if (typeof targetX !== 'number' || typeof targetY !== 'number') {
298
+ const newTargetX = xExtent[0] + xRange / 2;
299
+ const newTargetY = yExtent[0] + yRange / 2;
300
+ const newZoom = Math.log2(Math.min(width / xRange, height / yRange));
301
+ setTargetX(newTargetX);
302
+ // Graphics rendering has the y-axis going south so we need to multiply by negative one.
303
+ setTargetY(-newTargetY);
304
+ setZoom(newZoom);
305
+ }
306
+ }
307
+ // eslint-disable-next-line react-hooks/exhaustive-deps
308
+ }, [xRange, yRange, xExtent, yExtent, numCells,
309
+ width, height, zoom, averageFillDensity]);
310
+
311
+ const cellSelectionSet = useMemo(() => new Set(cellSelection), [cellSelection]);
312
+ const getCellIsSelected = useCallback((object, { index }) => (
313
+ (cellSelectionSet || new Set([])).has(obsIndex[index]) ? 1.0 : 0.0
314
+ ), [cellSelectionSet, obsIndex]);
315
+
316
+ const cellRadius = (cellRadiusMode === 'manual' ? cellRadiusFixed : dynamicCellRadius);
317
+ const cellOpacity = (cellOpacityMode === 'manual' ? cellOpacityFixed : dynamicCellOpacity);
318
+
319
+ const [uint8ExpressionData] = useUint8FeatureSelection(expressionDataColor);
320
+
321
+ // Set up a getter function for gene expression values, to be used
322
+ // by the DeckGL layer to obtain values for instanced attributes.
323
+ const getExpressionValue = useExpressionValueGetter({
324
+ instanceObsIndex: obsIndex,
325
+ matrixObsIndex: obsIndex,
326
+ expressionData: uint8ExpressionData,
327
+ });
328
+
329
+ // Puts the mapping values in the cell info tooltip.
330
+ const getObsInfo = useCallback((obsId) => {
331
+ const selectedTransformName = VALUE_TRANSFORM_OPTIONS.find(
332
+ o => o.value === featureValueTransform,
333
+ )?.name;
334
+ const genePrefix = featureValueTransform ? `${selectedTransformName} ` : '';
335
+ const obsIdx = obsIndex?.indexOf(obsId);
336
+ const obsInfo = { [`${capitalize(obsType)} ID`]: obsId };
337
+ if (gatingFeatureSelectionX && gatingFeatureSelectionY) {
338
+ obsInfo[genePrefix + gatingFeatureSelectionX] = obsXY.data[0][obsIdx];
339
+ obsInfo[genePrefix + gatingFeatureSelectionY] = obsXY.data[1][obsIdx];
340
+ }
341
+ return obsInfo;
342
+ }, [obsXY, obsIndex, featureValueTransform,
343
+ gatingFeatureSelectionX, gatingFeatureSelectionY, obsType,
344
+ ]);
345
+
346
+ return (
347
+ <TitleInfo
348
+ title={title}
349
+ info={`${commaNumber(cellsCount)} ${plur(obsType, cellsCount)}`}
350
+ removeGridComponent={removeGridComponent}
351
+ urls={urls}
352
+ theme={theme}
353
+ isReady={isReady}
354
+ options={(
355
+ <ScatterplotOptions
356
+ observationsLabel={obsType}
357
+ cellRadius={cellRadiusFixed}
358
+ setCellRadius={setCellRadiusFixed}
359
+ cellRadiusMode={cellRadiusMode}
360
+ setCellRadiusMode={setCellRadiusMode}
361
+ cellOpacity={cellOpacityFixed}
362
+ setCellOpacity={setCellOpacityFixed}
363
+ cellOpacityMode={cellOpacityMode}
364
+ setCellOpacityMode={setCellOpacityMode}
365
+ cellSetLabelsVisible={cellSetLabelsVisible}
366
+ setCellSetLabelsVisible={setCellSetLabelsVisible}
367
+ cellSetLabelSize={cellSetLabelSize}
368
+ setCellSetLabelSize={setCellSetLabelSize}
369
+ cellSetPolygonsVisible={cellSetPolygonsVisible}
370
+ setCellSetPolygonsVisible={setCellSetPolygonsVisible}
371
+ cellColorEncoding={cellColorEncoding}
372
+ setCellColorEncoding={setCellColorEncoding}
373
+ geneExpressionColormap={geneExpressionColormap}
374
+ setGeneExpressionColormap={setGeneExpressionColormap}
375
+ geneExpressionColormapRange={geneExpressionColormapRange}
376
+ setGeneExpressionColormapRange={setGeneExpressionColormapRange}
377
+ >
378
+ <GatingScatterplotOptions
379
+ featureType={featureType}
380
+ gatingFeatureSelectionX={gatingFeatureSelectionX}
381
+ setGatingFeatureSelectionX={setGatingFeatureSelectionX}
382
+ gatingFeatureSelectionY={gatingFeatureSelectionY}
383
+ setGatingFeatureSelectionY={setGatingFeatureSelectionY}
384
+ gatingFeatureValueTransform={featureValueTransform}
385
+ setGatingFeatureValueTransform={(newValue) => {
386
+ setFeatureValueTransform(newValue);
387
+ setTargetX(null);
388
+ setTargetY(null);
389
+ setZoom(null);
390
+ }}
391
+ gatingFeatureValueTransformCoefficient={featureValueTransformCoefficient}
392
+ setGatingFeatureValueTransformCoefficient={setFeatureValueTransformCoefficient}
393
+ geneSelectOptions={featureIndex}
394
+ transformOptions={VALUE_TRANSFORM_OPTIONS}
395
+ />
396
+ </ScatterplotOptions>
397
+ )}
398
+ >
399
+ <EmptyMessage
400
+ visible={!(gatingFeatureSelectionX && gatingFeatureSelectionY)}
401
+ message={`Select two ${plur(featureType, 2)} in the plot settings.`}
402
+ />
403
+ <Scatterplot
404
+ ref={deckRef}
405
+ uuid={uuid}
406
+ theme={theme}
407
+ hideTools={!(gatingFeatureSelectionX && gatingFeatureSelectionY)}
408
+ viewState={{ zoom, target: [targetX, targetY, targetZ] }}
409
+ setViewState={({ zoom: newZoom, target }) => {
410
+ setZoom(newZoom);
411
+ setTargetX(target[0]);
412
+ setTargetY(target[1]);
413
+ setTargetZ(target[2] || 0);
414
+ }}
415
+ obsEmbeddingIndex={obsIndex}
416
+ obsEmbedding={obsXY}
417
+ cellFilter={cellFilter}
418
+ cellSelection={cellSelection}
419
+ cellHighlight={cellHighlight}
420
+ cellColors={cellColors}
421
+ cellSetPolygons={cellSetPolygons}
422
+ cellSetLabelSize={cellSetLabelSize}
423
+ cellSetLabelsVisible={cellSetLabelsVisible}
424
+ cellSetPolygonsVisible={cellSetPolygonsVisible}
425
+ setCellFilter={setCellFilter}
426
+ setCellSelection={setCellSelectionProp}
427
+ setCellHighlight={setCellHighlight}
428
+ cellRadius={cellRadius}
429
+ cellOpacity={cellOpacity}
430
+ cellColorEncoding={cellColorEncoding}
431
+ geneExpressionColormap={geneExpressionColormap}
432
+ geneExpressionColormapRange={geneExpressionColormapRange}
433
+ setComponentHover={() => {
434
+ setComponentHover(uuid);
435
+ }}
436
+ updateViewInfo={setComponentViewInfo}
437
+ getExpressionValue={getExpressionValue}
438
+ getCellIsSelected={getCellIsSelected}
439
+
440
+ />
441
+ {!disableTooltip && (
442
+ <ScatterplotTooltipSubscriber
443
+ parentUuid={uuid}
444
+ obsHighlight={cellHighlight}
445
+ width={width}
446
+ height={height}
447
+ getObsInfo={getObsInfo}
448
+ />
449
+ )}
450
+ </TitleInfo>
451
+ );
452
+ }
package/src/index.js ADDED
@@ -0,0 +1 @@
1
+ export { GatingSubscriber } from './GatingSubscriber.js';