@vitessce/scatterplot-embedding 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,393 @@
1
+ import React, {
2
+ useState, useEffect, useCallback, useMemo,
3
+ } from 'react';
4
+ import { extent } from 'd3-array';
5
+ import { isEqual } from 'lodash-es';
6
+ import plur from 'plur';
7
+ import {
8
+ TitleInfo,
9
+ useReady, useUrls,
10
+ useDeckCanvasSize,
11
+ useUint8FeatureSelection,
12
+ useExpressionValueGetter,
13
+ useGetObsInfo,
14
+ useObsEmbeddingData,
15
+ useObsSetsData,
16
+ useFeatureSelection,
17
+ useObsFeatureMatrixIndices,
18
+ useFeatureLabelsData,
19
+ useMultiObsLabels,
20
+ useCoordination,
21
+ useLoaders,
22
+ useSetComponentHover,
23
+ useSetComponentViewInfo,
24
+ } from '@vitessce/vit-s';
25
+ import { setObsSelection, mergeObsSets, getCellSetPolygons } from '@vitessce/sets-utils';
26
+ import { getCellColors, commaNumber } from '@vitessce/utils';
27
+ import {
28
+ Scatterplot, ScatterplotTooltipSubscriber, ScatterplotOptions,
29
+ getPointSizeDevicePixels,
30
+ getPointOpacity,
31
+ } from '@vitessce/scatterplot';
32
+ import { Legend } from '@vitessce/legend';
33
+ import { ViewType, COMPONENT_COORDINATION_TYPES } from '@vitessce/constants-internal';
34
+
35
+ /**
36
+ * A subscriber component for the 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 {function} props.removeGridComponent The callback function to pass to TitleInfo,
43
+ * to call when the component has been removed from the grid.
44
+ * @param {string} props.title An override value for the component title.
45
+ * @param {number} props.averageFillDensity Override the average fill density calculation
46
+ * when using dynamic opacity mode.
47
+ */
48
+ export function EmbeddingScatterplotSubscriber(props) {
49
+ const {
50
+ uuid,
51
+ coordinationScopes,
52
+ removeGridComponent,
53
+ theme,
54
+ observationsLabelOverride,
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
+ embeddingType: mapping,
75
+ obsFilter: cellFilter,
76
+ obsHighlight: cellHighlight,
77
+ featureSelection: geneSelection,
78
+ obsSetSelection: cellSetSelection,
79
+ obsSetColor: cellSetColor,
80
+ obsColorEncoding: cellColorEncoding,
81
+ additionalObsSets: additionalCellSets,
82
+ embeddingObsSetPolygonsVisible: cellSetPolygonsVisible,
83
+ embeddingObsSetLabelsVisible: cellSetLabelsVisible,
84
+ embeddingObsSetLabelSize: cellSetLabelSize,
85
+ embeddingObsRadius: cellRadiusFixed,
86
+ embeddingObsRadiusMode: cellRadiusMode,
87
+ embeddingObsOpacity: cellOpacityFixed,
88
+ embeddingObsOpacityMode: cellOpacityMode,
89
+ featureValueColormap: geneExpressionColormap,
90
+ featureValueColormapRange: geneExpressionColormapRange,
91
+ tooltipsVisible,
92
+ }, {
93
+ setEmbeddingZoom: setZoom,
94
+ setEmbeddingTargetX: setTargetX,
95
+ setEmbeddingTargetY: setTargetY,
96
+ setEmbeddingTargetZ: setTargetZ,
97
+ setObsFilter: setCellFilter,
98
+ setObsSetSelection: setCellSetSelection,
99
+ setObsHighlight: setCellHighlight,
100
+ setObsSetColor: setCellSetColor,
101
+ setObsColorEncoding: setCellColorEncoding,
102
+ setAdditionalObsSets: setAdditionalCellSets,
103
+ setEmbeddingObsSetPolygonsVisible: setCellSetPolygonsVisible,
104
+ setEmbeddingObsSetLabelsVisible: setCellSetLabelsVisible,
105
+ setEmbeddingObsSetLabelSize: setCellSetLabelSize,
106
+ setEmbeddingObsRadius: setCellRadiusFixed,
107
+ setEmbeddingObsRadiusMode: setCellRadiusMode,
108
+ setEmbeddingObsOpacity: setCellOpacityFixed,
109
+ setEmbeddingObsOpacityMode: setCellOpacityMode,
110
+ setFeatureValueColormap: setGeneExpressionColormap,
111
+ setFeatureValueColormapRange: setGeneExpressionColormapRange,
112
+ setTooltipsVisible,
113
+ }] = useCoordination(COMPONENT_COORDINATION_TYPES[ViewType.SCATTERPLOT], coordinationScopes);
114
+
115
+ const observationsLabel = observationsLabelOverride || obsType;
116
+
117
+ const [urls, addUrl] = useUrls(loaders, dataset);
118
+ const [width, height, deckRef] = useDeckCanvasSize();
119
+
120
+ const title = titleOverride || `Scatterplot (${mapping})`;
121
+
122
+ const [obsLabelsTypes, obsLabelsData] = useMultiObsLabels(
123
+ coordinationScopes, obsType, loaders, dataset, addUrl,
124
+ );
125
+
126
+ // Get data from loaders using the data hooks.
127
+ const [{ obsIndex: obsEmbeddingIndex, obsEmbedding }, obsEmbeddingStatus] = useObsEmbeddingData(
128
+ loaders, dataset, addUrl, true, {}, {},
129
+ { obsType, embeddingType: mapping },
130
+ );
131
+ const cellsCount = obsEmbeddingIndex?.length || 0;
132
+ const [{ obsSets: cellSets, obsSetsMembership }, obsSetsStatus] = useObsSetsData(
133
+ loaders, dataset, addUrl, false,
134
+ { setObsSetSelection: setCellSetSelection, setObsSetColor: setCellSetColor },
135
+ { obsSetSelection: cellSetSelection, obsSetColor: cellSetColor },
136
+ { obsType },
137
+ );
138
+ // eslint-disable-next-line no-unused-vars
139
+ const [expressionData, loadedFeatureSelection, featureSelectionStatus] = useFeatureSelection(
140
+ loaders, dataset, false, geneSelection,
141
+ { obsType, featureType, featureValueType },
142
+ );
143
+ const [{ obsIndex: matrixObsIndex }, matrixIndicesStatus] = useObsFeatureMatrixIndices(
144
+ loaders, dataset, addUrl, false,
145
+ { obsType, featureType, featureValueType },
146
+ );
147
+ const [{ featureLabelsMap }, featureLabelsStatus] = useFeatureLabelsData(
148
+ loaders, dataset, addUrl, false, {}, {},
149
+ { featureType },
150
+ );
151
+
152
+ const isReady = useReady([
153
+ obsEmbeddingStatus,
154
+ obsSetsStatus,
155
+ featureSelectionStatus,
156
+ featureLabelsStatus,
157
+ matrixIndicesStatus,
158
+ ]);
159
+
160
+ const [dynamicCellRadius, setDynamicCellRadius] = useState(cellRadiusFixed);
161
+ const [dynamicCellOpacity, setDynamicCellOpacity] = useState(cellOpacityFixed);
162
+
163
+ const [originalViewState, setOriginalViewState] = useState(null);
164
+
165
+ const mergedCellSets = useMemo(() => mergeObsSets(
166
+ cellSets, additionalCellSets,
167
+ ), [cellSets, additionalCellSets]);
168
+
169
+ const setCellSelectionProp = useCallback((v) => {
170
+ setObsSelection(
171
+ v, additionalCellSets, cellSetColor,
172
+ setCellSetSelection, setAdditionalCellSets, setCellSetColor,
173
+ setCellColorEncoding,
174
+ );
175
+ }, [additionalCellSets, cellSetColor, setCellColorEncoding,
176
+ setAdditionalCellSets, setCellSetColor, setCellSetSelection]);
177
+
178
+ const cellColors = useMemo(() => getCellColors({
179
+ cellSets: mergedCellSets,
180
+ cellSetSelection,
181
+ cellSetColor,
182
+ obsIndex: matrixObsIndex,
183
+ theme,
184
+ }), [mergedCellSets, theme,
185
+ cellSetSelection, cellSetColor, matrixObsIndex]);
186
+
187
+ // cellSetPolygonCache is an array of tuples like [(key0, val0), (key1, val1), ...],
188
+ // where the keys are cellSetSelection arrays.
189
+ const [cellSetPolygonCache, setCellSetPolygonCache] = useState([]);
190
+ const cacheHas = (cache, key) => cache.findIndex(el => isEqual(el[0], key)) !== -1;
191
+ const cacheGet = (cache, key) => cache.find(el => isEqual(el[0], key))?.[1];
192
+ const cellSetPolygons = useMemo(() => {
193
+ if ((cellSetLabelsVisible || cellSetPolygonsVisible)
194
+ && !cacheHas(cellSetPolygonCache, cellSetSelection)
195
+ && mergedCellSets?.tree?.length
196
+ && obsEmbedding
197
+ && obsEmbeddingIndex
198
+ && cellSetColor?.length) {
199
+ const newCellSetPolygons = getCellSetPolygons({
200
+ obsIndex: obsEmbeddingIndex,
201
+ obsEmbedding,
202
+ cellSets: mergedCellSets,
203
+ cellSetSelection,
204
+ cellSetColor,
205
+ theme,
206
+ });
207
+ setCellSetPolygonCache(cache => [...cache, [cellSetSelection, newCellSetPolygons]]);
208
+ return newCellSetPolygons;
209
+ }
210
+ return cacheGet(cellSetPolygonCache, cellSetSelection) || [];
211
+ }, [cellSetPolygonsVisible, cellSetPolygonCache, cellSetLabelsVisible, theme,
212
+ obsEmbeddingIndex, obsEmbedding, mergedCellSets, cellSetSelection, cellSetColor]);
213
+
214
+
215
+ const cellSelection = useMemo(() => Array.from(cellColors.keys()), [cellColors]);
216
+
217
+ const [xRange, yRange, xExtent, yExtent, numCells] = useMemo(() => {
218
+ if (obsEmbedding && obsEmbedding.data && obsEmbedding.shape) {
219
+ const cellCount = obsEmbedding.shape[1];
220
+ const xE = extent(obsEmbedding.data[0]);
221
+ const yE = extent(obsEmbedding.data[1]);
222
+ const xR = xE[1] - xE[0];
223
+ const yR = yE[1] - yE[0];
224
+ return [xR, yR, xE, yE, cellCount];
225
+ }
226
+ return [null, null, null, null, null];
227
+ }, [obsEmbedding]);
228
+
229
+ // After cells have loaded or changed,
230
+ // compute the cell radius scale based on the
231
+ // extents of the cell coordinates on the x/y axes.
232
+ useEffect(() => {
233
+ // We do not really need isReady here, since the above useMemo that
234
+ // computes xRange and yRange will only run after obsEmbedding has loaded anyway.
235
+ // However, we include it here to ensure this effect waits as long as possible to run;
236
+ // For some reason, otherwise, in some cases this effect will run before the react-grid-layout
237
+ // initialization animation has finished,
238
+ // prior to `height` and `width` reaching their ultimate values, resulting in
239
+ // an initial viewState for that small view size, which looks bad.
240
+ if (xRange && yRange && isReady) {
241
+ const pointSizeDevicePixels = getPointSizeDevicePixels(
242
+ window.devicePixelRatio, zoom, xRange, yRange, width, height,
243
+ );
244
+ setDynamicCellRadius(pointSizeDevicePixels);
245
+
246
+ const nextCellOpacityScale = getPointOpacity(
247
+ zoom, xRange, yRange, width, height, numCells, averageFillDensity,
248
+ );
249
+ setDynamicCellOpacity(nextCellOpacityScale);
250
+
251
+ if (typeof targetX !== 'number' || typeof targetY !== 'number') {
252
+ // The view config did not define an initial viewState so
253
+ // we calculate one based on the data and set it.
254
+ const newTargetX = xExtent[0] + xRange / 2;
255
+ const newTargetY = yExtent[0] + yRange / 2;
256
+ const newZoom = Math.log2(Math.min(width / xRange, height / yRange));
257
+ setTargetX(newTargetX);
258
+ // Graphics rendering has the y-axis going south so we need to multiply by negative one.
259
+ setTargetY(-newTargetY);
260
+ setZoom(newZoom);
261
+ setOriginalViewState({ target: [newTargetX, -newTargetY, 0], zoom: newZoom });
262
+ } else if (!originalViewState) {
263
+ // originalViewState has not yet been set and
264
+ // the view config defined an initial viewState.
265
+ setOriginalViewState({ target: [targetX, targetY, 0], zoom });
266
+ }
267
+ }
268
+ // eslint-disable-next-line react-hooks/exhaustive-deps
269
+ }, [xRange, yRange, isReady, xExtent, yExtent, numCells,
270
+ width, height, zoom, averageFillDensity]);
271
+
272
+ const getObsInfo = useGetObsInfo(
273
+ observationsLabel, obsLabelsTypes, obsLabelsData, obsSetsMembership,
274
+ );
275
+
276
+ const cellSelectionSet = useMemo(() => new Set(cellSelection), [cellSelection]);
277
+ const getCellIsSelected = useCallback((object, { index }) => (
278
+ (cellSelectionSet || new Set([])).has(obsEmbeddingIndex[index]) ? 1.0 : 0.0
279
+ ), [cellSelectionSet, obsEmbeddingIndex]);
280
+
281
+ const cellRadius = (cellRadiusMode === 'manual' ? cellRadiusFixed : dynamicCellRadius);
282
+ const cellOpacity = (cellOpacityMode === 'manual' ? cellOpacityFixed : dynamicCellOpacity);
283
+
284
+ const [uint8ExpressionData, expressionExtents] = useUint8FeatureSelection(expressionData);
285
+
286
+ // Set up a getter function for gene expression values, to be used
287
+ // by the DeckGL layer to obtain values for instanced attributes.
288
+ const getExpressionValue = useExpressionValueGetter({
289
+ instanceObsIndex: obsEmbeddingIndex,
290
+ matrixObsIndex,
291
+ expressionData: uint8ExpressionData,
292
+ });
293
+
294
+ const setViewState = ({ zoom: newZoom, target }) => {
295
+ setZoom(newZoom);
296
+ setTargetX(target[0]);
297
+ setTargetY(target[1]);
298
+ setTargetZ(target[2] || 0);
299
+ };
300
+
301
+ return (
302
+ <TitleInfo
303
+ title={title}
304
+ info={`${commaNumber(cellsCount)} ${plur(observationsLabel, cellsCount)}`}
305
+ removeGridComponent={removeGridComponent}
306
+ urls={urls}
307
+ theme={theme}
308
+ isReady={isReady}
309
+ options={(
310
+ <ScatterplotOptions
311
+ observationsLabel={observationsLabel}
312
+ cellRadius={cellRadiusFixed}
313
+ setCellRadius={setCellRadiusFixed}
314
+ cellRadiusMode={cellRadiusMode}
315
+ setCellRadiusMode={setCellRadiusMode}
316
+ cellOpacity={cellOpacityFixed}
317
+ setCellOpacity={setCellOpacityFixed}
318
+ cellOpacityMode={cellOpacityMode}
319
+ setCellOpacityMode={setCellOpacityMode}
320
+ cellSetLabelsVisible={cellSetLabelsVisible}
321
+ setCellSetLabelsVisible={setCellSetLabelsVisible}
322
+ tooltipsVisible={tooltipsVisible}
323
+ setTooltipsVisible={setTooltipsVisible}
324
+ cellSetLabelSize={cellSetLabelSize}
325
+ setCellSetLabelSize={setCellSetLabelSize}
326
+ cellSetPolygonsVisible={cellSetPolygonsVisible}
327
+ setCellSetPolygonsVisible={setCellSetPolygonsVisible}
328
+ cellColorEncoding={cellColorEncoding}
329
+ setCellColorEncoding={setCellColorEncoding}
330
+ geneExpressionColormap={geneExpressionColormap}
331
+ setGeneExpressionColormap={setGeneExpressionColormap}
332
+ geneExpressionColormapRange={geneExpressionColormapRange}
333
+ setGeneExpressionColormapRange={setGeneExpressionColormapRange}
334
+ />
335
+ )}
336
+ >
337
+ <Scatterplot
338
+ ref={deckRef}
339
+ uuid={uuid}
340
+ theme={theme}
341
+ viewState={{ zoom, target: [targetX, targetY, targetZ] }}
342
+ setViewState={setViewState}
343
+ originalViewState={originalViewState}
344
+ obsEmbeddingIndex={obsEmbeddingIndex}
345
+ obsEmbedding={obsEmbedding}
346
+ cellFilter={cellFilter}
347
+ cellSelection={cellSelection}
348
+ cellHighlight={cellHighlight}
349
+ cellColors={cellColors}
350
+ cellSetPolygons={cellSetPolygons}
351
+ cellSetLabelSize={cellSetLabelSize}
352
+ cellSetLabelsVisible={cellSetLabelsVisible}
353
+ cellSetPolygonsVisible={cellSetPolygonsVisible}
354
+ setCellFilter={setCellFilter}
355
+ setCellSelection={setCellSelectionProp}
356
+ setCellHighlight={setCellHighlight}
357
+ cellRadius={cellRadius}
358
+ cellOpacity={cellOpacity}
359
+ cellColorEncoding={cellColorEncoding}
360
+ geneExpressionColormap={geneExpressionColormap}
361
+ geneExpressionColormapRange={geneExpressionColormapRange}
362
+ setComponentHover={() => {
363
+ setComponentHover(uuid);
364
+ }}
365
+ updateViewInfo={setComponentViewInfo}
366
+ getExpressionValue={getExpressionValue}
367
+ getCellIsSelected={getCellIsSelected}
368
+
369
+ />
370
+ {tooltipsVisible && (
371
+ <ScatterplotTooltipSubscriber
372
+ parentUuid={uuid}
373
+ obsHighlight={cellHighlight}
374
+ width={width}
375
+ height={height}
376
+ getObsInfo={getObsInfo}
377
+ />
378
+ )}
379
+ <Legend
380
+ visible
381
+ theme={theme}
382
+ featureType={featureType}
383
+ featureValueType={featureValueType}
384
+ obsColorEncoding={cellColorEncoding}
385
+ featureSelection={geneSelection}
386
+ featureLabelsMap={featureLabelsMap}
387
+ featureValueColormap={geneExpressionColormap}
388
+ featureValueColormapRange={geneExpressionColormapRange}
389
+ extent={expressionExtents?.[0]}
390
+ />
391
+ </TitleInfo>
392
+ );
393
+ }
package/src/index.js ADDED
@@ -0,0 +1 @@
1
+ export { EmbeddingScatterplotSubscriber } from './EmbeddingScatterplotSubscriber.js';