@vitessce/sets-utils 4.0.4 → 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
package/src/expr-utils.js CHANGED
@@ -1,217 +1,272 @@
1
1
  /* eslint-disable camelcase */
2
2
  import { InternMap } from 'internmap';
3
3
  import { getValueTransformFunction } from '@vitessce/utils';
4
- import { isEqual } from 'lodash-es';
5
- import { log } from '@vitessce/globals';
6
4
  import {
7
5
  treeToSelectedSetMap,
8
- treeToObsIdsBySetNames,
6
+ treeToSetIndicesArray,
7
+ setIndicesFromCodes,
9
8
  } from './cell-set-utils.js';
10
9
 
10
+ const hasSelection = selection => Array.isArray(selection) && selection.length > 0;
11
+
11
12
  /**
12
- * Input: selections and data.
13
- * Output: expression data in a hierarchy like
14
- * [
15
- * {
16
- * "selectedCellSet1": {
17
- * "selectedSampleSet1": [],
18
- * }
19
- * },
20
- * exprMax
21
- * ]
22
- * @param {*} sampleEdges
23
- * @param {*} sampleSets
24
- * @param {*} sampleSetSelection
25
- * @param {*} expressionData
26
- * @param {*} obsIndex
27
- * @param {*} mergedCellSets
28
- * @param {*} geneSelection
29
- * @param {*} cellSetSelection
30
- * @param {*} cellSetColor
31
- * @param {*} featureValueTransform
32
- * @param {*} featureValueTransformCoefficient
33
- * @returns
13
+ * The smallest unsigned typed array able to hold 1..count plus 0.
14
+ * @param {number} count The number of selected sets.
15
+ * @returns {Uint8ArrayConstructor|Uint16ArrayConstructor|Uint32ArrayConstructor}
16
+ */
17
+ function getSlotArrayType(count) {
18
+ if (count + 1 <= 256) {
19
+ return Uint8Array;
20
+ }
21
+ return count + 1 <= 65536 ? Uint16Array : Uint32Array;
22
+ }
23
+
24
+ /**
25
+ * Resolve the selections to positional "slot" arrays, so that the per-observation
26
+ * work below is a typed-array read rather than a string-keyed map lookup.
27
+ *
28
+ * cellSlot[i] is 1 + the position in cellSetSelection of the selected set
29
+ * containing observation i (0 when in none); null when there is no cell set
30
+ * selection. sampleSlot[i] is the same for sampleSetSelection via sampleEdges
31
+ * (obsId -> sampleId); null when there is no sample set selection.
32
+ *
33
+ * When raw categorical codes are available for this same observation index
34
+ * (checked by reference), the cell set slots come from the codes without
35
+ * walking the tree; otherwise from the tree, resolving each selected set's
36
+ * members once rather than once per observation.
37
+ * @param {object} params
38
+ * @returns {{ cellSlot: ArrayLike<number>|null, sampleSlot: ArrayLike<number>|null }}
39
+ */
40
+ function computeStrata({
41
+ obsIndex, mergedCellSets, cellSetSelection, obsSetsColumns,
42
+ sampleEdges, sampleSets, sampleSetSelection,
43
+ }) {
44
+ const numObs = obsIndex?.length || 0;
45
+ let cellSlot = null;
46
+ if (hasSelection(cellSetSelection)) {
47
+ if (obsSetsColumns && obsSetsColumns.obsIndex === obsIndex) {
48
+ cellSlot = setIndicesFromCodes({
49
+ columns: obsSetsColumns.columns,
50
+ obsIndex,
51
+ selectedNamePaths: cellSetSelection,
52
+ });
53
+ }
54
+ if (cellSlot === null) {
55
+ cellSlot = treeToSetIndicesArray(mergedCellSets, cellSetSelection, obsIndex);
56
+ }
57
+ }
58
+ let sampleSlot = null;
59
+ if (hasSelection(sampleSetSelection)) {
60
+ const SlotArrayType = getSlotArrayType(sampleSetSelection.length);
61
+ sampleSlot = new SlotArrayType(numObs);
62
+ if (sampleSets && sampleEdges) {
63
+ // Sample sets are small: resolve sampleId -> slot once, then one map lookup
64
+ // per observation to find its sample.
65
+ const slotByPath = new InternMap(
66
+ sampleSetSelection.map((path, i) => [path, i + 1]),
67
+ JSON.stringify,
68
+ );
69
+ const sampleIdToSlot = new Map();
70
+ treeToSelectedSetMap(sampleSets, sampleSetSelection).forEach((path, sampleId) => {
71
+ sampleIdToSlot.set(sampleId, slotByPath.get(path) ?? 0);
72
+ });
73
+ for (let i = 0; i < numObs; i += 1) {
74
+ const sampleId = sampleEdges.get(obsIndex[i]);
75
+ if (sampleId !== undefined) {
76
+ sampleSlot[i] = sampleIdToSlot.get(sampleId) ?? 0;
77
+ }
78
+ }
79
+ }
80
+ }
81
+ return { cellSlot, sampleSlot };
82
+ }
83
+
84
+ /**
85
+ * Assign every observation to a (cell set, sample set) group and count the
86
+ * members of each, so that per-group arrays can be allocated at their final size.
87
+ * @param {object} params
88
+ * @param {number} params.numObs
89
+ * @param {ArrayLike<number>|null} params.cellSlot From computeStrata.
90
+ * @param {ArrayLike<number>|null} params.sampleSlot From computeStrata.
91
+ * @param {number} params.numSampleGroups Number of sample set keys.
92
+ * @param {number} params.numCellGroups Number of cell set keys.
93
+ * @returns {{ groupOfObs: Int32Array, counts: Int32Array, numGroups: number }}
94
+ * groupOfObs[i] = cellGroup * numSampleGroups + sampleGroup, or -1 when excluded.
95
+ */
96
+ function assignGroups({
97
+ numObs, cellSlot, sampleSlot, numSampleGroups, numCellGroups,
98
+ }) {
99
+ const numGroups = numCellGroups * numSampleGroups;
100
+ const groupOfObs = new Int32Array(numObs);
101
+ const counts = new Int32Array(numGroups);
102
+ for (let i = 0; i < numObs; i += 1) {
103
+ const cellGroup = cellSlot ? cellSlot[i] - 1 : 0;
104
+ const sampleGroup = sampleSlot ? sampleSlot[i] - 1 : 0;
105
+ if (cellGroup < 0 || sampleGroup < 0) {
106
+ groupOfObs[i] = -1;
107
+ } else {
108
+ const group = cellGroup * numSampleGroups + sampleGroup;
109
+ groupOfObs[i] = group;
110
+ counts[group] += 1;
111
+ }
112
+ }
113
+ return { groupOfObs, counts, numGroups };
114
+ }
115
+
116
+ /**
117
+ * Stratify per-observation arrays (e.g. embedding coordinates) by selected cell
118
+ * set and selected sample set.
119
+ *
120
+ * Output: an InternMap keyed by cell set path (or null) of InternMaps keyed by
121
+ * sample set path (or null), each holding one array per key of arraysToStratify
122
+ * (of the same constructor as the input) plus 'obsIndex', all aligned with one
123
+ * another and in observation-index order.
124
+ * @param {Map<string, string>|null} sampleEdges Mapping from obsId to sampleId.
125
+ * @param {object|null} sampleSets Sample sets tree.
126
+ * @param {array|null} sampleSetSelection Selected sample set paths.
127
+ * @param {string[]} obsIndex The observation index the arrays align to.
128
+ * @param {object|null} mergedCellSets Cell sets tree.
129
+ * @param {array|null} cellSetSelection Selected cell set paths.
130
+ * @param {object} arraysToStratify Arrays aligned with obsIndex. The key
131
+ * 'featureValue' holds an array of per-feature arrays, aggregated per
132
+ * featureAggregationStrategy.
133
+ * @param {string|number} featureAggregationStrategy How to combine several
134
+ * features: 'first', 'last', a feature index, 'sum', or 'mean'.
135
+ * @param {object} [options]
136
+ * @param {object} [options.obsSetsColumns] Raw categorical columns for the
137
+ * observation sets, as loaded alongside the tree, for a code-based fast path.
138
+ * @returns {[InternMap, number]} The stratified arrays and the number of
139
+ * observations placed.
34
140
  */
35
141
  export function stratifyArrays(
36
- sampleEdges, sampleIdToObsIdsMap,
37
- sampleSets, sampleSetSelection,
142
+ sampleEdges, sampleSets, sampleSetSelection,
38
143
  obsIndex, mergedCellSets, cellSetSelection,
39
144
  arraysToStratify, // Assumed to be sorted with respect to the obsIndex.
40
145
  featureAggregationStrategy,
146
+ options = {},
41
147
  ) {
42
- const result = new InternMap([], JSON.stringify);
43
-
44
- const hasSampleSetSelection = Array.isArray(sampleSetSelection) && sampleSetSelection.length > 0;
45
- const hasCellSetSelection = Array.isArray(cellSetSelection) && cellSetSelection.length > 0;
46
-
47
- const sampleSetKeys = hasSampleSetSelection ? sampleSetSelection : [null];
48
- const cellSetKeys = hasCellSetSelection ? cellSetSelection : [null];
148
+ const { obsSetsColumns = null } = options;
49
149
  const arrKeys = Object.keys(arraysToStratify);
50
-
51
150
  if (arrKeys.includes('obsIndex') || arrKeys.includes('i')) {
52
151
  throw new Error('The keys "obsIndex" and "i" are reserved for internal use.');
53
152
  }
54
- if (Object.entries(arraysToStratify).some(([arrKey, arr]) => {
55
- if (arrKey === 'featureValue') {
56
- // The featureValue array is an array of arrays, one per feature,
57
- // so we instead expect each sub-array to have a length
58
- // equal to the number of observations.
59
- return arr.some(a => a.length !== obsIndex.length);
60
- }
61
- return arr.length !== obsIndex.length;
62
- })) {
63
- // throw new Error('All arrays must have the same length as the obsIndex.');
64
- }
65
-
66
- const sampleSetInfo = sampleSets && sampleSetSelection
67
- ? treeToObsIdsBySetNames(sampleSets, sampleSetSelection)
68
- : null;
69
- const cellSetInfo = mergedCellSets && cellSetSelection
70
- ? treeToObsIdsBySetNames(mergedCellSets, cellSetSelection)
71
- : null;
72
-
73
- // First level: cell set
74
- cellSetKeys.forEach((cellSetKey) => {
75
- result.set(cellSetKey, new InternMap([], JSON.stringify));
76
- // Second level: sample set
77
- sampleSetKeys.forEach((sampleSetKey) => {
78
- result.get(cellSetKey).set(sampleSetKey, new InternMap([], JSON.stringify));
79
- // Third level: array
80
-
81
- // Handle cellSetKey and sampleSetKey being null.
82
- const sampleIdsInSampleSet = (sampleSetInfo && sampleSetKey
83
- ? sampleSetInfo?.find(n => isEqual(n.path, sampleSetKey))
84
- : null
85
- )?.ids;
86
- // The sampleSets contain sampleIds. We need to get the obsIds
87
- // corresponding to each sampleId.
88
- const obsIdsInSampleSet = sampleIdsInSampleSet
89
- ? sampleIdsInSampleSet.flatMap(sampleId => sampleIdToObsIdsMap?.get(sampleId) || [])
90
- : null;
91
- const obsIdsInCellSet = (cellSetInfo && cellSetKey
92
- ? cellSetInfo?.find(n => isEqual(n.path, cellSetKey))
93
- : null
94
- )?.ids;
95
-
96
- // Handle cases where obsIdsInSampleSet and/or obsIdsInCellSet is null.
97
- let subObsIndex = obsIndex;
98
- if (obsIdsInSampleSet && obsIdsInCellSet) {
99
- subObsIndex = Array.from(
100
- (new Set(obsIdsInSampleSet)).intersection(new Set(obsIdsInCellSet)),
101
- );
102
- } else if (obsIdsInSampleSet) {
103
- subObsIndex = obsIdsInSampleSet;
104
- } else if (obsIdsInCellSet) {
105
- subObsIndex = obsIdsInCellSet;
106
- }
107
- const arrLen = subObsIndex.length;
108
-
109
- arrKeys.forEach((arrKey) => {
110
- // Instantiate a new array of the appropriate size.
111
- const newArr = new arraysToStratify[arrKey].constructor(arrLen);
112
- result.get(cellSetKey).get(sampleSetKey).set(arrKey, newArr);
113
- });
114
- result.get(cellSetKey).get(sampleSetKey).set('obsIndex', subObsIndex);
115
- // We initialize an incrementer to keep track of
116
- // the next index to use for insertion into the array.
117
- result.get(cellSetKey).get(sampleSetKey).set('i', 0);
118
- });
153
+ const hasSampleSetSelection = hasSelection(sampleSetSelection);
154
+ const hasCellSetSelection = hasSelection(cellSetSelection);
155
+ const sampleSetKeys = hasSampleSetSelection ? sampleSetSelection : [null];
156
+ const cellSetKeys = hasCellSetSelection ? cellSetSelection : [null];
157
+ const numObs = obsIndex?.length || 0;
158
+
159
+ const { cellSlot, sampleSlot } = computeStrata({
160
+ obsIndex,
161
+ mergedCellSets,
162
+ cellSetSelection,
163
+ obsSetsColumns,
164
+ sampleEdges,
165
+ sampleSets,
166
+ sampleSetSelection,
167
+ });
168
+ const { groupOfObs, counts, numGroups } = assignGroups({
169
+ numObs,
170
+ cellSlot,
171
+ sampleSlot,
172
+ numSampleGroups: sampleSetKeys.length,
173
+ numCellGroups: cellSetKeys.length,
119
174
  });
120
175
 
121
- const sampleIdToSetMap = sampleSets && sampleSetSelection
122
- ? treeToSelectedSetMap(sampleSets, sampleSetSelection)
123
- : null;
124
- const cellIdToSetMap = mergedCellSets && cellSetSelection
125
- ? treeToSelectedSetMap(mergedCellSets, cellSetSelection)
126
- : null;
127
-
128
- // Iterate over every observation.
129
- // Insert the ID and all corresponding values into
130
- // the appropriate arrays within the InternMap.
131
- let cellCount = 0;
132
- for (let i = 0; i < obsIndex.length; i += 1) {
133
- const obsId = obsIndex[i];
134
-
135
- const cellSet = cellIdToSetMap?.get(obsId) || null;
136
- const sampleId = sampleEdges?.get(obsId);
137
- const sampleSet = sampleId ? (sampleIdToSetMap?.get(sampleId) || null) : null;
138
-
139
- if ((hasSampleSetSelection && !sampleSet) || (hasCellSetSelection && !cellSet)) {
140
- // Skip this sample if it is not in the selected sample set.
141
- // eslint-disable-next-line no-continue
142
- continue;
176
+ // One accessor per array, resolved once rather than per observation.
177
+ const getters = arrKeys.map((arrKey) => {
178
+ const arr = arraysToStratify[arrKey];
179
+ if (arrKey !== 'featureValue') {
180
+ return i => arr[i];
143
181
  }
144
-
145
- const insertionIndex = result.get(cellSet).get(sampleSet).get('i');
146
-
147
- // eslint-disable-next-line no-loop-func
148
- arrKeys.forEach((arrKey) => {
149
- let value;
150
- if (arrKey === 'featureValue') {
151
- if (featureAggregationStrategy === 'first') {
152
- value = arraysToStratify[arrKey][0][i];
153
- } else if (featureAggregationStrategy === 'last') {
154
- value = arraysToStratify[arrKey].at(-1)[i];
155
- } else if (typeof featureAggregationStrategy === 'number') {
156
- const j = featureAggregationStrategy;
157
- // TODO: more checks here for array index validity.
158
- value = arraysToStratify[arrKey][j][i];
159
- } else if (featureAggregationStrategy === 'sum' || featureAggregationStrategy === 'mean') {
160
- value = arraysToStratify[arrKey].reduce((a, h) => a + h[i], 0);
161
- if (featureAggregationStrategy === 'mean') {
162
- value /= arraysToStratify[arrKey].length;
163
- }
182
+ if (featureAggregationStrategy === 'first') {
183
+ return i => arr[0][i];
184
+ }
185
+ if (featureAggregationStrategy === 'last') {
186
+ return i => arr[arr.length - 1][i];
187
+ }
188
+ if (typeof featureAggregationStrategy === 'number') {
189
+ // TODO: more checks here for array index validity.
190
+ const j = featureAggregationStrategy;
191
+ return i => arr[j][i];
192
+ }
193
+ if (featureAggregationStrategy === 'sum' || featureAggregationStrategy === 'mean') {
194
+ const divisor = featureAggregationStrategy === 'mean' ? arr.length : 1;
195
+ return (i) => {
196
+ let sum = 0;
197
+ for (let h = 0; h < arr.length; h += 1) {
198
+ sum += arr[h][i];
164
199
  }
165
- } else {
166
- value = arraysToStratify[arrKey][i];
167
- }
200
+ return sum / divisor;
201
+ };
202
+ }
203
+ return () => undefined;
204
+ });
168
205
 
169
- result
170
- .get(cellSet)
171
- .get(sampleSet)
172
- .get(arrKey)[insertionIndex] = value;
173
- });
174
- result.get(cellSet).get(sampleSet).set('i', insertionIndex + 1);
175
- cellCount += 1;
206
+ // Allocate every group's arrays at their final size.
207
+ const groupArrays = new Array(numGroups);
208
+ for (let g = 0; g < numGroups; g += 1) {
209
+ groupArrays[g] = {
210
+ arrays: arrKeys.map(arrKey => new arraysToStratify[arrKey].constructor(counts[g])),
211
+ obsIndex: new Array(counts[g]),
212
+ };
176
213
  }
177
-
178
- cellSetKeys.forEach((cellSetKey) => {
179
- // Second level: sample set
180
- sampleSetKeys.forEach((sampleSetKey) => {
181
- const finalInsertionIndex = result.get(cellSetKey).get(sampleSetKey).get('i');
182
- if (finalInsertionIndex !== result.get(cellSetKey).get(sampleSetKey).get('obsIndex').length) {
183
- log.warn('The final insertion index is lower than expected.');
214
+ const positions = new Int32Array(numGroups);
215
+ let cellCount = 0;
216
+ for (let i = 0; i < numObs; i += 1) {
217
+ const g = groupOfObs[i];
218
+ if (g >= 0) {
219
+ const pos = positions[g];
220
+ positions[g] += 1;
221
+ const target = groupArrays[g];
222
+ for (let a = 0; a < arrKeys.length; a += 1) {
223
+ target.arrays[a][pos] = getters[a](i);
184
224
  }
185
- result.get(cellSetKey).get(sampleSetKey).delete('i');
225
+ target.obsIndex[pos] = obsIndex[i];
226
+ cellCount += 1;
227
+ }
228
+ }
229
+
230
+ const result = new InternMap([], JSON.stringify);
231
+ cellSetKeys.forEach((cellSetKey, c) => {
232
+ const sampleMap = new InternMap([], JSON.stringify);
233
+ result.set(cellSetKey, sampleMap);
234
+ sampleSetKeys.forEach((sampleSetKey, s) => {
235
+ const group = groupArrays[c * sampleSetKeys.length + s];
236
+ const arrayMap = new InternMap([], JSON.stringify);
237
+ arrKeys.forEach((arrKey, a) => {
238
+ arrayMap.set(arrKey, group.arrays[a]);
239
+ });
240
+ arrayMap.set('obsIndex', group.obsIndex);
241
+ sampleMap.set(sampleSetKey, arrayMap);
186
242
  });
187
243
  });
188
-
189
244
  return [result, cellCount];
190
245
  }
191
246
 
192
247
  /**
193
- * Input: selections and data.
194
- * Output: expression data in a hierarchy like
195
- * [
196
- * {
197
- * "selectedCellSet1": {
198
- * "selectedSampleSet1": [],
199
- * }
200
- * },
201
- * exprMax
202
- * ]
203
- * @param {*} sampleEdges
204
- * @param {*} sampleSets
205
- * @param {*} sampleSetSelection
206
- * @param {*} expressionData
207
- * @param {*} obsIndex
208
- * @param {*} mergedCellSets
209
- * @param {*} geneSelection
210
- * @param {*} cellSetSelection
211
- * @param {*} cellSetColor
212
- * @param {*} featureValueTransform
213
- * @param {*} featureValueTransformCoefficient
214
- * @returns
248
+ * Stratify expression values by selected cell set, selected sample set, and gene.
249
+ *
250
+ * Output: an InternMap keyed by cell set path of InternMaps keyed by sample set
251
+ * path (or null) of InternMaps keyed by gene, each holding a plain array of
252
+ * transformed values in observation-index order, plus the maximum transformed
253
+ * value overall.
254
+ * @param {Map<string, string>|null} sampleEdges Mapping from obsId to sampleId.
255
+ * @param {object|null} sampleSets Sample sets tree.
256
+ * @param {array|null} sampleSetSelection Selected sample set paths.
257
+ * @param {ArrayLike<number>[]} expressionData One array per selected gene,
258
+ * aligned with obsIndex.
259
+ * @param {string[]} obsIndex The observation index.
260
+ * @param {object|null} mergedCellSets Cell sets tree.
261
+ * @param {string[]} geneSelection Selected genes.
262
+ * @param {array|null} cellSetSelection Selected cell set paths.
263
+ * @param {object[]} cellSetColor Unused; kept for call compatibility.
264
+ * @param {string|null} featureValueTransform Transform name, e.g. 'log1p'.
265
+ * @param {number} featureValueTransformCoefficient Transform coefficient.
266
+ * @param {object} [options]
267
+ * @param {object} [options.obsSetsColumns] Raw categorical columns for the
268
+ * observation sets, for a code-based fast path.
269
+ * @returns {[InternMap|null, number|null]} The stratified values and the maximum.
215
270
  */
216
271
  export function stratifyExpressionData(
217
272
  sampleEdges, sampleSets, sampleSetSelection,
@@ -219,80 +274,92 @@ export function stratifyExpressionData(
219
274
  geneSelection, cellSetSelection,
220
275
  cellSetColor, // TODO: remove this parameter
221
276
  featureValueTransform, featureValueTransformCoefficient,
277
+ options = {},
222
278
  ) {
223
- const result = new InternMap([], JSON.stringify);
224
-
225
- const hasSampleSetSelection = Array.isArray(sampleSetSelection) && sampleSetSelection.length > 0;
226
- const hasCellSetSelection = Array.isArray(cellSetSelection) && cellSetSelection.length > 0;
227
- const hasGeneSelection = Array.isArray(geneSelection) && geneSelection.length > 0;
228
-
279
+ const { obsSetsColumns = null } = options;
280
+ if (!(mergedCellSets && cellSetSelection
281
+ && geneSelection && geneSelection.length >= 1
282
+ && expressionData
283
+ )) {
284
+ return [null, null];
285
+ }
286
+ const hasSampleSetSelection = hasSelection(sampleSetSelection);
287
+ const hasCellSetSelection = hasSelection(cellSetSelection);
229
288
  const sampleSetKeys = hasSampleSetSelection ? sampleSetSelection : [null];
230
289
  const cellSetKeys = hasCellSetSelection ? cellSetSelection : [null];
231
- const geneKeys = hasGeneSelection ? geneSelection : [null];
232
-
233
- // TODO: return a flat array with { cellSet, sampleSet, gene } objects.
234
- // Then, use d3.group to create nested InternMaps.
235
-
236
-
237
- // First level: cell set
238
- cellSetKeys.forEach((cellSetKey) => {
239
- result.set(cellSetKey, new InternMap([], JSON.stringify));
240
- // Second level: sample set
241
- sampleSetKeys.forEach((sampleSetKey) => {
242
- result.get(cellSetKey).set(sampleSetKey, new InternMap([], JSON.stringify));
243
- // Third level: gene
244
- geneKeys.forEach((geneKey) => {
245
- result.get(cellSetKey).get(sampleSetKey).set(geneKey, []);
246
- });
290
+ const geneKeys = geneSelection;
291
+ const numObs = obsIndex?.length || 0;
292
+ let exprMax = -Infinity;
293
+
294
+ const numGroups = cellSetKeys.length * sampleSetKeys.length;
295
+ // With an empty cell set selection nothing is assigned; the groups stay empty.
296
+ let groupOfObs = null;
297
+ let counts = new Int32Array(numGroups);
298
+ if (hasCellSetSelection) {
299
+ const { cellSlot, sampleSlot } = computeStrata({
300
+ obsIndex,
301
+ mergedCellSets,
302
+ cellSetSelection,
303
+ obsSetsColumns,
304
+ sampleEdges,
305
+ sampleSets,
306
+ sampleSetSelection,
247
307
  });
248
- });
249
-
250
-
251
- if (mergedCellSets && cellSetSelection
252
- && geneSelection && geneSelection.length >= 1
253
- && expressionData
254
- ) {
255
- const sampleIdToSetMap = sampleSets && sampleSetSelection
256
- ? treeToSelectedSetMap(sampleSets, sampleSetSelection)
257
- : null;
258
- const cellIdToSetMap = treeToSelectedSetMap(mergedCellSets, cellSetSelection);
259
-
260
- let exprMax = -Infinity;
261
-
262
- for (let i = 0; i < obsIndex.length; i += 1) {
263
- const obsId = obsIndex[i];
264
-
265
- const cellSet = cellIdToSetMap?.get(obsId);
266
- const sampleId = sampleEdges?.get(obsId);
267
- const sampleSet = sampleId && hasSampleSetSelection
268
- ? sampleIdToSetMap?.get(sampleId)
269
- : null;
308
+ ({ groupOfObs, counts } = assignGroups({
309
+ numObs,
310
+ cellSlot,
311
+ sampleSlot,
312
+ numSampleGroups: sampleSetKeys.length,
313
+ numCellGroups: cellSetKeys.length,
314
+ }));
315
+ }
270
316
 
271
- if (hasSampleSetSelection && !sampleSet) {
272
- // Skip this sample if it is not in the selected sample set.
273
- // eslint-disable-next-line no-continue
274
- continue;
317
+ const transform = getValueTransformFunction(
318
+ featureValueTransform, featureValueTransformCoefficient,
319
+ );
320
+ // leaves[group][geneI] is the plain array of values for that group and gene,
321
+ // allocated at its final size (consumers rely on Array methods such as flat()).
322
+ const leaves = new Array(numGroups);
323
+ for (let g = 0; g < numGroups; g += 1) {
324
+ leaves[g] = geneKeys.map(() => new Array(counts[g]));
325
+ }
326
+ if (groupOfObs) {
327
+ const positions = new Int32Array(numGroups);
328
+ geneKeys.forEach((geneKey, geneI) => {
329
+ const column = expressionData[geneI];
330
+ if (!column) {
331
+ // Not loaded yet; leave this gene's arrays unfilled.
332
+ return;
333
+ }
334
+ positions.fill(0);
335
+ for (let i = 0; i < numObs; i += 1) {
336
+ const g = groupOfObs[i];
337
+ if (g >= 0) {
338
+ const value = transform(column[i]);
339
+ if (value > exprMax) {
340
+ exprMax = value;
341
+ }
342
+ leaves[g][geneI][positions[g]] = value;
343
+ positions[g] += 1;
344
+ }
275
345
  }
346
+ });
347
+ }
276
348
 
277
- // eslint-disable-next-line no-loop-func
349
+ const result = new InternMap([], JSON.stringify);
350
+ cellSetKeys.forEach((cellSetKey, c) => {
351
+ const sampleMap = new InternMap([], JSON.stringify);
352
+ result.set(cellSetKey, sampleMap);
353
+ sampleSetKeys.forEach((sampleSetKey, s) => {
354
+ const geneMap = new InternMap([], JSON.stringify);
355
+ const group = leaves[c * sampleSetKeys.length + s];
278
356
  geneKeys.forEach((geneKey, geneI) => {
279
- const value = expressionData[geneI][i];
280
- const transformFunction = getValueTransformFunction(
281
- featureValueTransform, featureValueTransformCoefficient,
282
- );
283
- const transformedValue = transformFunction(value);
284
- exprMax = Math.max(transformedValue, exprMax);
285
-
286
- result
287
- .get(cellSet)
288
- ?.get(sampleSet)
289
- ?.get(geneKey)
290
- ?.push(transformedValue);
357
+ geneMap.set(geneKey, group[geneI]);
291
358
  });
292
- }
293
- return [result, exprMax];
294
- }
295
- return [null, null];
359
+ sampleMap.set(sampleSetKey, geneMap);
360
+ });
361
+ });
362
+ return [result, exprMax];
296
363
  }
297
364
 
298
365
  /**