@vitessce/sets-utils 4.0.3 → 4.0.5

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.
Files changed (48) hide show
  1. package/dist/index.js +986 -5396
  2. package/dist-tsc/CellSetsZarrLoader.d.ts +23 -0
  3. package/dist-tsc/CellSetsZarrLoader.d.ts.map +1 -1
  4. package/dist-tsc/CellSetsZarrLoader.js +90 -6
  5. package/dist-tsc/CellSetsZarrLoader.js.map +1 -1
  6. package/dist-tsc/CellSetsZarrLoader.test.js +76 -1
  7. package/dist-tsc/CellSetsZarrLoader.test.js.map +1 -1
  8. package/dist-tsc/cell-set-utils.d.ts +78 -1
  9. package/dist-tsc/cell-set-utils.d.ts.map +1 -1
  10. package/dist-tsc/cell-set-utils.js +308 -66
  11. package/dist-tsc/cell-set-utils.js.map +1 -1
  12. package/dist-tsc/cell-set-utils.test.fixtures.d.ts +14 -0
  13. package/dist-tsc/cell-set-utils.test.fixtures.js +18 -0
  14. package/dist-tsc/cell-set-utils.test.fixtures.js.map +1 -1
  15. package/dist-tsc/cell-set-utils.test.js +319 -2
  16. package/dist-tsc/cell-set-utils.test.js.map +1 -1
  17. package/dist-tsc/expr-utils.d.ts +51 -46
  18. package/dist-tsc/expr-utils.d.ts.map +1 -1
  19. package/dist-tsc/expr-utils.js +297 -222
  20. package/dist-tsc/expr-utils.js.map +1 -1
  21. package/dist-tsc/expr-utils.test.js +77 -5
  22. package/dist-tsc/expr-utils.test.js.map +1 -1
  23. package/dist-tsc/index.d.ts +3 -2
  24. package/dist-tsc/index.js +3 -2
  25. package/dist-tsc/index.js.map +1 -1
  26. package/dist-tsc/io.d.ts.map +1 -1
  27. package/dist-tsc/io.js +1 -3
  28. package/dist-tsc/io.js.map +1 -1
  29. package/dist-tsc/membership.d.ts +43 -0
  30. package/dist-tsc/membership.d.ts.map +1 -0
  31. package/dist-tsc/membership.js +212 -0
  32. package/dist-tsc/membership.js.map +1 -0
  33. package/dist-tsc/membership.test.d.ts +2 -0
  34. package/dist-tsc/membership.test.d.ts.map +1 -0
  35. package/dist-tsc/membership.test.js +128 -0
  36. package/dist-tsc/membership.test.js.map +1 -0
  37. package/package.json +6 -5
  38. package/src/CellSetsZarrLoader.js +99 -6
  39. package/src/CellSetsZarrLoader.test.js +88 -1
  40. package/src/cell-set-utils.js +322 -57
  41. package/src/cell-set-utils.test.fixtures.js +19 -0
  42. package/src/cell-set-utils.test.js +392 -0
  43. package/src/expr-utils.js +315 -248
  44. package/src/expr-utils.test.js +121 -5
  45. package/src/index.js +11 -0
  46. package/src/io.js +1 -3
  47. package/src/membership.js +217 -0
  48. package/src/membership.test.js +136 -0
@@ -104,10 +104,6 @@ describe('Utility functions for processing expression data', () => {
104
104
  });
105
105
 
106
106
  it('stratifyArrays: stratifiy by cell set, then sample set', () => {
107
- const sampleIdToObsIdsMap = new Map([
108
- ['donor1', ['cell1-1', 'cell1-2', 'cell1-3', 'cell1-4']],
109
- ['donor2', ['cell2-1', 'cell2-2', 'cell2-3', 'cell2-4']],
110
- ]);
111
107
  const alignedEmbeddingIndex = ['cell1-1', 'cell1-2', 'cell1-3', 'cell1-4', 'cell2-1', 'cell2-2', 'cell2-3', 'cell2-4'];
112
108
  const alignedEmbeddingData = {
113
109
  data: [
@@ -120,7 +116,7 @@ describe('Utility functions for processing expression data', () => {
120
116
  ];
121
117
 
122
118
  const [result, cellCount] = stratifyArrays(
123
- sampleEdges, sampleIdToObsIdsMap,
119
+ sampleEdges,
124
120
  sampleSets, sampleSetSelection,
125
121
  alignedEmbeddingIndex, mergedCellSets, cellSetSelection, {
126
122
  obsEmbeddingX: alignedEmbeddingData.data[0],
@@ -137,7 +133,127 @@ describe('Utility functions for processing expression data', () => {
137
133
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue')).toEqual([10, 30]);
138
134
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingX').length).toBe(2);
139
135
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingY').length).toBe(2);
136
+ // The per-group arrays are aligned with one another, in observation order.
137
+ expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsIndex')).toEqual(['cell1-1', 'cell1-3']);
138
+ expect(Array.from(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingX'))).toEqual([0, 2]);
139
+ expect(result.get(['Cell type', 'B cell']).get(['Clinical groups', 'CKD']).get('obsIndex')).toEqual(['cell2-2', 'cell2-4']);
140
140
  expect(cellCount).toBe(8);
141
141
  });
142
+
143
+ // Raw categorical codes describing the same sets as mergedCellSets.
144
+ const obsSetsColumns = {
145
+ obsIndex,
146
+ columns: [{
147
+ name: 'Cell type',
148
+ path: ['Cell type'],
149
+ codes: Int8Array.from([0, 1, 0, 1, 0, 1, 0, 1]),
150
+ categories: ['T cell', 'B cell'],
151
+ }],
152
+ };
153
+ const toPlain = stratified => Array.from(stratified.entries()).map(([cellKey, sampleMap]) => [
154
+ cellKey,
155
+ Array.from(sampleMap.entries()).map(([sampleKey, leafMap]) => [
156
+ sampleKey,
157
+ Array.from(leafMap.entries()).map(([leafKey, values]) => [leafKey, Array.from(values)]),
158
+ ]),
159
+ ]);
160
+
161
+ it('stratifyExpressionData: the code-based strata match the tree-based strata', () => {
162
+ const args = [
163
+ sampleEdges, sampleSets, sampleSetSelection,
164
+ expressionData, obsIndex, mergedCellSets,
165
+ geneSelection, cellSetSelection, cellSetColor,
166
+ featureValueTransform, featureValueTransformCoefficient,
167
+ ];
168
+ const [fromTree, maxFromTree] = stratifyExpressionData(...args);
169
+ const [fromCodes, maxFromCodes] = stratifyExpressionData(...args, { obsSetsColumns });
170
+ expect(toPlain(fromCodes)).toEqual(toPlain(fromTree));
171
+ expect(maxFromCodes).toEqual(maxFromTree);
172
+ // With a tree that lacks the selected sets, only the codes can place cells.
173
+ const [fromCodesOnly] = stratifyExpressionData(
174
+ sampleEdges, sampleSets, sampleSetSelection,
175
+ expressionData, obsIndex, { tree: [] },
176
+ geneSelection, cellSetSelection, cellSetColor,
177
+ featureValueTransform, featureValueTransformCoefficient,
178
+ { obsSetsColumns },
179
+ );
180
+ expect(toPlain(fromCodesOnly)).toEqual(toPlain(fromTree));
181
+ // Codes for a different observation index are not used.
182
+ const [fromOtherCodes] = stratifyExpressionData(
183
+ sampleEdges, sampleSets, sampleSetSelection,
184
+ expressionData, obsIndex, { tree: [] },
185
+ geneSelection, cellSetSelection, cellSetColor,
186
+ featureValueTransform, featureValueTransformCoefficient,
187
+ { obsSetsColumns: { ...obsSetsColumns, obsIndex: [...obsIndex] } },
188
+ );
189
+ expect(fromOtherCodes.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('Gene 1')).toEqual([]);
190
+ });
191
+
192
+ it('stratifyExpressionData: applies the value transform and excludes unselected samples', () => {
193
+ const [result, exprMax] = stratifyExpressionData(
194
+ sampleEdges, sampleSets, [['Clinical groups', 'AKI']],
195
+ expressionData, obsIndex, mergedCellSets,
196
+ geneSelection, cellSetSelection, cellSetColor,
197
+ 'log1p', 1,
198
+ );
199
+ expect(Array.from(result.get(['Cell type', 'T cell']).keys())).toEqual([['Clinical groups', 'AKI']]);
200
+ expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('Gene 1'))
201
+ .toEqual([Math.log1p(10), Math.log1p(30)]);
202
+ expect(result.get(['Cell type', 'B cell']).get(['Clinical groups', 'AKI']).get('Gene 1'))
203
+ .toEqual([Math.log1p(20), Math.log1p(40)]);
204
+ // The maximum is over the transformed values that were placed.
205
+ expect(exprMax).toEqual(Math.log1p(40));
206
+ });
207
+
208
+ it('stratifyExpressionData: an empty cell set selection assigns nothing', () => {
209
+ const [result, exprMax] = stratifyExpressionData(
210
+ sampleEdges, sampleSets, sampleSetSelection,
211
+ expressionData, obsIndex, mergedCellSets,
212
+ geneSelection, [], cellSetColor,
213
+ featureValueTransform, featureValueTransformCoefficient,
214
+ );
215
+ expect(Array.from(result.keys())).toEqual([null]);
216
+ expect(result.get(null).get(['Clinical groups', 'AKI']).get('Gene 1')).toEqual([]);
217
+ expect(exprMax).toEqual(-Infinity);
218
+ expect(stratifyExpressionData(
219
+ sampleEdges, sampleSets, sampleSetSelection,
220
+ expressionData, obsIndex, mergedCellSets,
221
+ geneSelection, null, cellSetColor,
222
+ featureValueTransform, featureValueTransformCoefficient,
223
+ )).toEqual([null, null]);
224
+ });
225
+
226
+ it('stratifyArrays: without selections every observation lands in one group', () => {
227
+ const [result, cellCount] = stratifyArrays(
228
+ null, null, null,
229
+ obsIndex, mergedCellSets, null,
230
+ { x: new Float32Array([0, 1, 2, 3, 4, 5, 6, 7]) },
231
+ featureAggregationStrategy,
232
+ );
233
+ expect(Array.from(result.keys())).toEqual([null]);
234
+ expect(Array.from(result.get(null).keys())).toEqual([null]);
235
+ expect(Array.from(result.get(null).get(null).get('x'))).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
236
+ expect(result.get(null).get(null).get('obsIndex')).toEqual(obsIndex);
237
+ expect(cellCount).toBe(8);
238
+ });
239
+
240
+ it('stratifyArrays: aggregates several feature arrays per strategy and accepts codes', () => {
241
+ const featureValue = [
242
+ new Uint8Array([10, 20, 30, 40, 11, 21, 31, 41]),
243
+ new Uint8Array([2, 4, 6, 8, 3, 5, 7, 9]),
244
+ ];
245
+ const stratify = strategy => stratifyArrays(
246
+ null, null, null,
247
+ obsIndex, { tree: [] }, cellSetSelection,
248
+ { featureValue },
249
+ strategy,
250
+ { obsSetsColumns },
251
+ )[0].get(['Cell type', 'T cell']).get(null).get('featureValue');
252
+ expect(stratify('first')).toEqual([10, 30, 11, 31]);
253
+ expect(stratify('last')).toEqual([2, 6, 3, 7]);
254
+ expect(stratify(1)).toEqual([2, 6, 3, 7]);
255
+ expect(stratify('sum')).toEqual([12, 36, 14, 38]);
256
+ expect(stratify('mean')).toEqual([6, 18, 7, 19]);
257
+ });
142
258
  });
143
259
  });
package/src/index.js CHANGED
@@ -2,6 +2,11 @@ export {
2
2
  treeToSelectedSetMap,
3
3
  treeToCellColorsBySetNames,
4
4
  treeToCellSetColorIndicesBySetNames,
5
+ treeToColorIndicesArray,
6
+ colorIndicesFromCodes,
7
+ treeToSetIndicesArray,
8
+ setIndicesFromCodes,
9
+ getObsIndexMap,
5
10
  treeToSetSizesBySetNames,
6
11
  treeToObjectsBySetNames,
7
12
  treeToObsIdsBySetNames,
@@ -25,8 +30,13 @@ export {
25
30
  nodeToRenderProps,
26
31
  getCellSetPolygons,
27
32
  treeToMembershipMap,
33
+ treeToLeafSets,
28
34
  nodeToSet,
29
35
  } from './cell-set-utils.js';
36
+ export {
37
+ lazyTreeToMembershipMap,
38
+ membershipFromCodes,
39
+ } from './membership.js';
30
40
  export {
31
41
  findLongestCommonPath,
32
42
  filterPathsByExpansionAndSelection,
@@ -62,6 +72,7 @@ export {
62
72
  } from './constants.js';
63
73
  export {
64
74
  dataToCellSetsTree,
75
+ codesToCellSetsTree,
65
76
  } from './CellSetsZarrLoader.js';
66
77
  export {
67
78
  getCellColors,
package/src/io.js CHANGED
@@ -1,8 +1,6 @@
1
1
  import { isNil } from 'lodash-es';
2
2
  import { dsvFormat } from 'd3-dsv';
3
- // TODO(monorepo): try to find a different package for this.
4
- // Reference: https://github.com/zemirco/json2csv/issues/539
5
- import { Parser } from 'json2csv/dist/json2csv.umd.js';
3
+ import { Parser } from '@json2csv/plainjs';
6
4
  import { getDefaultColor } from '@vitessce/utils';
7
5
  import { colorArrayToString, colorStringToArray } from './utils.js';
8
6
  import {
@@ -0,0 +1,217 @@
1
+ import { ObsSetsWorker, packStrings } from '@vitessce/workers';
2
+ import { MISSING_VALUE_PLACEHOLDER } from '@vitessce/utils';
3
+ import { treeToLeafSets, treeToMembershipMap, getObsIndexMap } from './cell-set-utils.js';
4
+
5
+ // Built membership encodings, keyed weakly by the set tree they came from, so that
6
+ // repeated loader invocations and multiple views over one tree share the result.
7
+ const membershipCache = new WeakMap();
8
+
9
+ /**
10
+ * Run a task on a fresh obs sets worker.
11
+ * @param {object} payload The message payload.
12
+ * @param {Transferable[]} transfers Buffers to transfer rather than copy.
13
+ * @returns {Promise<object>} The worker's reply.
14
+ */
15
+ function runInWorker(payload, transfers) {
16
+ return new Promise((resolve, reject) => {
17
+ let worker;
18
+ try {
19
+ worker = new ObsSetsWorker();
20
+ } catch (e) {
21
+ // No worker support, or the bundle could not construct one.
22
+ reject(e);
23
+ return;
24
+ }
25
+ const settle = (fn, value) => {
26
+ worker.terminate();
27
+ fn(value);
28
+ };
29
+ worker.onmessage = (event) => {
30
+ if (event.data?.error) {
31
+ settle(reject, new Error(event.data.error));
32
+ } else {
33
+ settle(resolve, event.data);
34
+ }
35
+ };
36
+ worker.onerror = e => settle(reject, e);
37
+ worker.postMessage(['buildMembership', payload], transfers);
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Run a callback when the main thread is next idle.
43
+ * @param {Function} callback The callback to run.
44
+ */
45
+ function whenIdle(callback) {
46
+ if (typeof requestIdleCallback === 'function') {
47
+ // The timeout bounds how long a busy page can defer this. The result is only
48
+ // needed once a tooltip is shown, so it does not need to be prompt.
49
+ requestIdleCallback(callback, { timeout: 5000 });
50
+ } else {
51
+ setTimeout(callback, 0);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Get an observation-ID-to-set-paths lookup that avoids blocking the main thread.
57
+ *
58
+ * The encoding is built in a worker and returned as transferable typed arrays, so
59
+ * neither the set tree nor a per-observation Map is ever serialized across the
60
+ * worker boundary. Packing and dispatch are deferred to idle time, and until the
61
+ * worker replies, lookups fall back to building the map synchronously — so this is
62
+ * never less correct than doing the work eagerly, only less costly.
63
+ *
64
+ * @param {object} currTree A tree object.
65
+ * @param {string[]} [obsIndex] The observation index to align the encoding to. When
66
+ * omitted, no worker is used and the map is built lazily on the main thread.
67
+ * @returns {{ get: Function, has: Function, size: number }} A Map-like lookup
68
+ * exposing the subset of the Map interface that consumers use.
69
+ */
70
+ export function lazyTreeToMembershipMap(currTree, obsIndex = undefined) {
71
+ let state = currTree ? membershipCache.get(currTree) : undefined;
72
+ if (!state) {
73
+ state = { csr: null, leafSets: null, syncMap: null, dispatched: false };
74
+ if (currTree) {
75
+ membershipCache.set(currTree, state);
76
+ }
77
+ }
78
+
79
+ function getSyncMap() {
80
+ if (!state.syncMap) {
81
+ state.syncMap = treeToMembershipMap(currTree);
82
+ }
83
+ return state.syncMap;
84
+ }
85
+
86
+ function dispatchToWorker() {
87
+ if (state.dispatched || state.csr || !currTree || !obsIndex?.length) {
88
+ return;
89
+ }
90
+ state.dispatched = true;
91
+ whenIdle(() => {
92
+ if (state.csr || state.syncMap) {
93
+ // Already answered synchronously, so the worker would be wasted effort.
94
+ return;
95
+ }
96
+ let payload;
97
+ let transfers;
98
+ try {
99
+ const leafSets = treeToLeafSets(currTree);
100
+ const setSizes = new Uint32Array(leafSets.length);
101
+ const setObsIds = [];
102
+ leafSets.forEach(({ set }, i) => {
103
+ setSizes[i] = set.length;
104
+ set.forEach(([obsId]) => setObsIds.push(obsId));
105
+ });
106
+ const obsIndexBuffer = packStrings(obsIndex);
107
+ const setObsIdsBuffer = packStrings(setObsIds);
108
+ payload = { obsIndexBuffer, setObsIdsBuffer, setSizes };
109
+ transfers = [obsIndexBuffer.buffer, setObsIdsBuffer.buffer];
110
+ state.leafSets = leafSets;
111
+ } catch (e) {
112
+ // Fall back to the synchronous path on the next lookup.
113
+ return;
114
+ }
115
+ runInWorker(payload, transfers).then(({ offsets, setIds }) => {
116
+ // Observations that are in a set but missing from obsIndex cannot be
117
+ // represented positionally. Rather than answer for them incorrectly, keep
118
+ // using the synchronous map.
119
+ let expected = 0;
120
+ payload.setSizes.forEach((n) => { expected += n; });
121
+ if (setIds.length === expected) {
122
+ state.csr = { offsets, setIds };
123
+ }
124
+ }).catch(() => {
125
+ // Worker unavailable or failed; the synchronous path still answers.
126
+ });
127
+ });
128
+ }
129
+
130
+ dispatchToWorker();
131
+
132
+ function get(obsId) {
133
+ const { csr, leafSets } = state;
134
+ if (csr && leafSets) {
135
+ const obsI = getObsIndexMap(obsIndex).get(obsId);
136
+ if (obsI === undefined) {
137
+ return undefined;
138
+ }
139
+ const start = csr.offsets[obsI];
140
+ const end = csr.offsets[obsI + 1];
141
+ if (start === end) {
142
+ return undefined;
143
+ }
144
+ const paths = new Array(end - start);
145
+ for (let i = start; i < end; i += 1) {
146
+ paths[i - start] = leafSets[csr.setIds[i]].path;
147
+ }
148
+ return paths;
149
+ }
150
+ if (!currTree) {
151
+ return undefined;
152
+ }
153
+ return getSyncMap().get(obsId);
154
+ }
155
+
156
+ return {
157
+ get,
158
+ has: obsId => get(obsId) !== undefined,
159
+ get size() {
160
+ const { csr } = state;
161
+ if (csr) {
162
+ let count = 0;
163
+ for (let i = 0; i < csr.offsets.length - 1; i += 1) {
164
+ if (csr.offsets[i + 1] > csr.offsets[i]) {
165
+ count += 1;
166
+ }
167
+ }
168
+ return count;
169
+ }
170
+ return currTree ? getSyncMap().size : 0;
171
+ },
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Get an observation-ID-to-set-paths lookup backed directly by raw categorical
177
+ * codes, for single-level hierarchies. No per-observation structure is built at
178
+ * all: a lookup is a memoized obsIndexMap position plus one typed-array read per
179
+ * hierarchy. Matches the answers a tree-based membership map would give for the
180
+ * tree that codesToCellSetsTree builds from the same columns, including the
181
+ * placeholder-named set that holds observations with a negative (missing) code.
182
+ * @param {string[]} obsIndex The observation index shared by all columns.
183
+ * @param {{ name: string, codes: ArrayLike<number>, categories: string[] }[]} columns
184
+ * Raw codes and category names per hierarchy, with the hierarchy name.
185
+ * @returns {{ get: Function, has: Function, size: number }} A Map-like lookup
186
+ * exposing the subset of the Map interface that consumers use.
187
+ */
188
+ export function membershipFromCodes(obsIndex, columns) {
189
+ // The only per-observation cost left is the obsId-to-position map, which is
190
+ // shared via getObsIndexMap. Warm it during idle time so the first tooltip
191
+ // hover does not pay for building it.
192
+ whenIdle(() => getObsIndexMap(obsIndex));
193
+ function get(obsId) {
194
+ const obsI = getObsIndexMap(obsIndex).get(obsId);
195
+ if (obsI === undefined) {
196
+ return undefined;
197
+ }
198
+ const paths = new Array(columns.length);
199
+ for (let j = 0; j < columns.length; j += 1) {
200
+ const { name, codes, categories } = columns[j];
201
+ const code = codes[obsI];
202
+ // A negative code is a missing value, which the tree places in the set
203
+ // named by the shared placeholder.
204
+ paths[j] = [name, code >= 0 ? categories[code] : MISSING_VALUE_PLACEHOLDER];
205
+ }
206
+ return paths;
207
+ }
208
+ return {
209
+ get,
210
+ has: obsId => get(obsId) !== undefined,
211
+ get size() {
212
+ // Every observation belongs to one set per hierarchy (possibly the
213
+ // undefined-named one), so membership covers the whole index.
214
+ return columns.length > 0 ? obsIndex.length : 0;
215
+ },
216
+ };
217
+ }
@@ -0,0 +1,136 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { MISSING_VALUE_PLACEHOLDER } from '@vitessce/utils';
3
+ import { cloneDeep } from 'lodash-es';
4
+ import { buildMembershipCsr } from '@vitessce/workers';
5
+ import { treeToLeafSets, treeToMembershipMap } from './cell-set-utils.js';
6
+ import { lazyTreeToMembershipMap, membershipFromCodes } from './membership.js';
7
+ import { codesToCellSetsTree } from './CellSetsZarrLoader.js';
8
+ import { tree } from './cell-set-utils.test.fixtures.js';
9
+
10
+ const PERICYTES = ['Cell Type Annotations', 'Vasculature', 'Pericytes'];
11
+
12
+ // Decode a CSR encoding the way the membership store's lookup does.
13
+ function decode(csr, leafSets, obsIndex, obsId) {
14
+ const obsI = obsIndex.indexOf(obsId);
15
+ if (obsI === -1) return undefined;
16
+ const start = csr.offsets[obsI];
17
+ const end = csr.offsets[obsI + 1];
18
+ if (start === end) return undefined;
19
+ return Array.from(csr.setIds.slice(start, end)).map(id => leafSets[id].path);
20
+ }
21
+
22
+ describe('obs set membership store', () => {
23
+ const obsIndex = ['cell_1', 'cell_2', 'cell_3', 'cell_4', 'cell_5', 'cell_6', 'cell_7'];
24
+
25
+ it('the worker encoding decodes to the same answer as the main-thread map', () => {
26
+ // This is the composition the worker path performs: pack the leaf sets, build
27
+ // the CSR off-thread, then resolve set IDs back to paths on lookup.
28
+ const leafSets = treeToLeafSets(tree);
29
+ const setSizes = new Uint32Array(leafSets.length);
30
+ const setObsIds = [];
31
+ leafSets.forEach(({ set }, i) => {
32
+ setSizes[i] = set.length;
33
+ set.forEach(([obsId]) => setObsIds.push(obsId));
34
+ });
35
+ const csr = buildMembershipCsr(obsIndex, setObsIds, setSizes);
36
+ const expected = treeToMembershipMap(tree);
37
+ obsIndex.forEach((obsId) => {
38
+ expect(decode(csr, leafSets, obsIndex, obsId)).toEqual(expected.get(obsId));
39
+ });
40
+ // Every membership was representable, which is what lets the store accept it.
41
+ expect(csr.setIds.length).toEqual(setObsIds.length);
42
+ });
43
+
44
+ it('answers correctly before any worker result arrives', () => {
45
+ // Worker construction is unavailable under jsdom, so this exercises the
46
+ // synchronous fallback that also covers browsers without worker support.
47
+ const membership = lazyTreeToMembershipMap(tree, obsIndex);
48
+ const expected = treeToMembershipMap(tree);
49
+ obsIndex.forEach((obsId) => {
50
+ expect(membership.get(obsId)).toEqual(expected.get(obsId));
51
+ });
52
+ expect(membership.size).toEqual(expected.size);
53
+ expect(membership.has('cell_1')).toEqual(true);
54
+ expect(membership.has('not_a_cell')).toEqual(false);
55
+ expect(membership.get('not_a_cell')).toEqual(undefined);
56
+ });
57
+
58
+ it('does no work until first lookup', () => {
59
+ // Traversal has to read `tree`, so an untouched getter proves the map was never
60
+ // built. The value is stable because the traversal reads it more than once.
61
+ const treeValue = cloneDeep(tree).tree;
62
+ let reads = 0;
63
+ const spyTree = {
64
+ version: '0.1.3',
65
+ datatype: 'cell',
66
+ get tree() {
67
+ reads += 1;
68
+ return treeValue;
69
+ },
70
+ };
71
+ const membership = lazyTreeToMembershipMap(spyTree);
72
+ expect(reads).toEqual(0);
73
+ expect(membership.get('cell_1')).toEqual([PERICYTES]);
74
+ expect(reads).toBeGreaterThan(0);
75
+ });
76
+
77
+ it('builds once and shares across instances', () => {
78
+ const treeValue = cloneDeep(tree).tree;
79
+ let reads = 0;
80
+ const spyTree = {
81
+ version: '0.1.3',
82
+ datatype: 'cell',
83
+ get tree() {
84
+ reads += 1;
85
+ return treeValue;
86
+ },
87
+ };
88
+ const first = lazyTreeToMembershipMap(spyTree);
89
+ const second = lazyTreeToMembershipMap(spyTree);
90
+ first.get('cell_1');
91
+ const readsAfterFirstBuild = reads;
92
+ first.get('cell_2');
93
+ // Memoized on the tree, so a second store over the same tree — a repeated
94
+ // loader invocation, or another view — reuses the built map.
95
+ second.get('cell_3');
96
+ expect(second.size).toEqual(first.size);
97
+ expect(reads).toEqual(readsAfterFirstBuild);
98
+ });
99
+
100
+ it('tolerates an absent tree and an absent obsIndex', () => {
101
+ expect(lazyTreeToMembershipMap(null, obsIndex).get('cell_1')).toEqual(undefined);
102
+ expect(lazyTreeToMembershipMap(null, obsIndex).size).toEqual(0);
103
+ expect(lazyTreeToMembershipMap(null, obsIndex).has('cell_1')).toEqual(false);
104
+ // Without an obsIndex there is nothing to align to, so it stays on the
105
+ // main-thread path.
106
+ expect(lazyTreeToMembershipMap(tree).get('cell_1')).toEqual([PERICYTES]);
107
+ });
108
+ });
109
+
110
+ describe('membershipFromCodes', () => {
111
+ const obsIndex = ['cell_1', 'cell_2', 'cell_3', 'cell_4'];
112
+ const columns = [
113
+ { name: 'Cell Type', codes: Int8Array.from([0, 1, -1, 0]), categories: ['T cell', 'B cell'] },
114
+ { name: 'Leiden', codes: Int8Array.from([1, 1, 0, -1]), categories: ['0', '1'] },
115
+ ];
116
+
117
+ it('matches the tree-based membership map, including missing codes', () => {
118
+ const options = [{ name: 'Cell Type' }, { name: 'Leiden' }];
119
+ const codesTree = codesToCellSetsTree({ obsIndex, columns }, options);
120
+ const expected = treeToMembershipMap(codesTree);
121
+ const membership = membershipFromCodes(obsIndex, columns);
122
+ obsIndex.forEach((obsId) => {
123
+ expect(membership.get(obsId)).toEqual(expected.get(obsId));
124
+ expect(membership.has(obsId)).toEqual(true);
125
+ });
126
+ expect(membership.size).toEqual(expected.size);
127
+ // A missing code reports the placeholder-named set, as the tree does.
128
+ expect(membership.get('cell_3')).toEqual([['Cell Type', MISSING_VALUE_PLACEHOLDER], ['Leiden', '0']]);
129
+ expect(membership.get('not_a_cell')).toEqual(undefined);
130
+ expect(membership.has('not_a_cell')).toEqual(false);
131
+ });
132
+
133
+ it('reports zero size with no columns', () => {
134
+ expect(membershipFromCodes(obsIndex, []).size).toEqual(0);
135
+ });
136
+ });