@vitessce/sets-utils 3.5.10 → 3.5.11

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/index.js CHANGED
@@ -9592,6 +9592,7 @@ const CoordinationType$1 = {
9592
9592
  FEATURE_VALUE_COLORMAP: "featureValueColormap",
9593
9593
  FEATURE_VALUE_TRANSFORM: "featureValueTransform",
9594
9594
  FEATURE_VALUE_COLORMAP_RANGE: "featureValueColormapRange",
9595
+ FEATURE_AGGREGATION_STRATEGY: "featureAggregationStrategy",
9595
9596
  OBS_COLOR_ENCODING: "obsColorEncoding",
9596
9597
  SPATIAL_IMAGE_LAYER: "spatialImageLayer",
9597
9598
  SPATIAL_SEGMENTATION_LAYER: "spatialSegmentationLayer",
@@ -9945,6 +9946,7 @@ z.object({
9945
9946
  termColumn: z.string().optional(),
9946
9947
  pValueColumn: z.string(),
9947
9948
  pValueAdjusted: z.boolean().optional(),
9949
+ featureSetLibrary: z.string().optional().describe("Optionally, provide a feature set library name. By default, Reactome_2022."),
9948
9950
  analysisType: z.string().optional().describe("Optionally, provide an analysis_type name. By default, pertpy_hypergeometric.")
9949
9951
  });
9950
9952
  z.object({
@@ -9955,7 +9957,6 @@ z.object({
9955
9957
  foldChangeColumn: z.string().describe("The log-fold change is then calculated between this expected sample and the expected sample with no active covariates from the intercept section."),
9956
9958
  foldChangeTransformation: z.enum(["log2"]).optional(),
9957
9959
  isCredibleEffectColumn: z.string().describe("Column which annotates effects as being credible or not (boolean)."),
9958
- covariateColumn: z.string().describe("Column which defines the covariate used in the analysis."),
9959
9960
  analysisType: z.string().optional().describe("Optionally, provide an analysis_type name. By default, sccoda_df.")
9960
9961
  });
9961
9962
  const annDataObsLabels = annDataObs;
@@ -17773,7 +17774,7 @@ function getCellColors(params) {
17773
17774
  }
17774
17775
  return /* @__PURE__ */ new Map();
17775
17776
  }
17776
- function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify) {
17777
+ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify, featureAggregationStrategy) {
17777
17778
  const result = new InternMap([], JSON.stringify);
17778
17779
  const hasSampleSetSelection = Array.isArray(sampleSetSelection) && sampleSetSelection.length > 0;
17779
17780
  const hasCellSetSelection = Array.isArray(cellSetSelection) && cellSetSelection.length > 0;
@@ -17783,9 +17784,13 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17783
17784
  if (arrKeys.includes("obsIndex") || arrKeys.includes("i")) {
17784
17785
  throw new Error('The keys "obsIndex" and "i" are reserved for internal use.');
17785
17786
  }
17786
- if (Object.values(arraysToStratify).some((arr) => arr.length !== obsIndex.length)) {
17787
- throw new Error("All arrays must have the same length as the obsIndex.");
17788
- }
17787
+ if (Object.entries(arraysToStratify).some(([arrKey, arr]) => {
17788
+ if (arrKey === "featureValue") {
17789
+ return arr.some((a) => a.length !== obsIndex.length);
17790
+ }
17791
+ return arr.length !== obsIndex.length;
17792
+ }))
17793
+ ;
17789
17794
  const sampleSetInfo = sampleSets && sampleSetSelection ? treeToObsIdsBySetNames(sampleSets, sampleSetSelection) : null;
17790
17795
  const cellSetInfo = mergedCellSets && cellSetSelection ? treeToObsIdsBySetNames(mergedCellSets, cellSetSelection) : null;
17791
17796
  cellSetKeys.forEach((cellSetKey) => {
@@ -17817,6 +17822,7 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17817
17822
  });
17818
17823
  const sampleIdToSetMap = sampleSets && sampleSetSelection ? treeToSelectedSetMap(sampleSets, sampleSetSelection) : null;
17819
17824
  const cellIdToSetMap = mergedCellSets && cellSetSelection ? treeToSelectedSetMap(mergedCellSets, cellSetSelection) : null;
17825
+ let cellCount = 0;
17820
17826
  for (let i = 0; i < obsIndex.length; i += 1) {
17821
17827
  const obsId = obsIndex[i];
17822
17828
  const cellSet = (cellIdToSetMap == null ? void 0 : cellIdToSetMap.get(obsId)) || null;
@@ -17827,10 +17833,28 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17827
17833
  }
17828
17834
  const insertionIndex = result.get(cellSet).get(sampleSet).get("i");
17829
17835
  arrKeys.forEach((arrKey) => {
17830
- const value = arraysToStratify[arrKey][i];
17836
+ let value;
17837
+ if (arrKey === "featureValue") {
17838
+ if (featureAggregationStrategy === "first") {
17839
+ value = arraysToStratify[arrKey][0][i];
17840
+ } else if (featureAggregationStrategy === "last") {
17841
+ value = arraysToStratify[arrKey].at(-1)[i];
17842
+ } else if (typeof featureAggregationStrategy === "number") {
17843
+ const j = featureAggregationStrategy;
17844
+ value = arraysToStratify[arrKey][j][i];
17845
+ } else if (featureAggregationStrategy === "sum" || featureAggregationStrategy === "mean") {
17846
+ value = arraysToStratify[arrKey].reduce((a, h) => a + h[i], 0);
17847
+ if (featureAggregationStrategy === "mean") {
17848
+ value /= arraysToStratify[arrKey].length;
17849
+ }
17850
+ }
17851
+ } else {
17852
+ value = arraysToStratify[arrKey][i];
17853
+ }
17831
17854
  result.get(cellSet).get(sampleSet).get(arrKey)[insertionIndex] = value;
17832
17855
  });
17833
17856
  result.get(cellSet).get(sampleSet).set("i", insertionIndex + 1);
17857
+ cellCount += 1;
17834
17858
  }
17835
17859
  cellSetKeys.forEach((cellSetKey) => {
17836
17860
  sampleSetKeys.forEach((sampleSetKey) => {
@@ -17841,7 +17865,7 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17841
17865
  result.get(cellSetKey).get(sampleSetKey).delete("i");
17842
17866
  });
17843
17867
  });
17844
- return result;
17868
+ return [result, cellCount];
17845
17869
  }
17846
17870
  function stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, expressionData, obsIndex, mergedCellSets, geneSelection, cellSetSelection, cellSetColor, featureValueTransform, featureValueTransformCoefficient) {
17847
17871
  const result = new InternMap([], JSON.stringify);
@@ -17888,12 +17912,38 @@ function stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, exp
17888
17912
  }
17889
17913
  return [null, null];
17890
17914
  }
17891
- function aggregateStratifiedExpressionData(stratifiedResult, geneSelection) {
17915
+ function aggregateStratifiedExpressionData(stratifiedResult, geneSelection, featureAggregationStrategy) {
17892
17916
  const result = new InternMap([], JSON.stringify);
17893
17917
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
17894
17918
  result.set(cellSetKey, new InternMap([], JSON.stringify));
17895
17919
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
17896
- const values = secondLevelInternMap.get(geneSelection[0]);
17920
+ let values;
17921
+ if (featureAggregationStrategy === "first") {
17922
+ values = secondLevelInternMap.get(geneSelection[0]);
17923
+ } else if (featureAggregationStrategy === "last") {
17924
+ values = secondLevelInternMap.get(geneSelection.at(-1));
17925
+ } else if (typeof featureAggregationStrategy === "number") {
17926
+ const i = featureAggregationStrategy;
17927
+ if (i >= 0 && i < geneSelection.length) {
17928
+ values = secondLevelInternMap.get(geneSelection[i]);
17929
+ } else {
17930
+ throw new Error("Feature index used for featureAggregationStrategy is invalid.");
17931
+ }
17932
+ } else if (featureAggregationStrategy === "sum" || featureAggregationStrategy === "mean") {
17933
+ const subarrays = geneSelection.map((geneId) => secondLevelInternMap.get(geneId));
17934
+ values = subarrays.reduce((acc, curr) => acc.map((val, idx) => val + curr[idx]));
17935
+ if (featureAggregationStrategy === "mean") {
17936
+ const N = geneSelection.length;
17937
+ values = values.map((val) => val / N);
17938
+ }
17939
+ } else if (featureAggregationStrategy === "difference") {
17940
+ if (geneSelection.length === 2) {
17941
+ const subarrays = geneSelection.map((geneId) => secondLevelInternMap.get(geneId));
17942
+ values = subarrays.reduce((acc, curr) => acc.map((val, idx) => val - curr[idx]));
17943
+ } else {
17944
+ throw new Error("Expected exactly two selected features when featureAggregationStrategy is difference.");
17945
+ }
17946
+ }
17897
17947
  result.get(cellSetKey).set(sampleSetKey, values);
17898
17948
  });
17899
17949
  });
@@ -22,7 +22,7 @@
22
22
  * @param {*} featureValueTransformCoefficient
23
23
  * @returns
24
24
  */
25
- export function stratifyArrays(sampleEdges: any, sampleIdToObsIdsMap: any, sampleSets: any, sampleSetSelection: any, obsIndex: any, mergedCellSets: any, cellSetSelection: any, arraysToStratify: any): any;
25
+ export function stratifyArrays(sampleEdges: any, sampleIdToObsIdsMap: any, sampleSets: any, sampleSetSelection: any, obsIndex: any, mergedCellSets: any, cellSetSelection: any, arraysToStratify: any, featureAggregationStrategy: any): any[];
26
26
  /**
27
27
  * Input: selections and data.
28
28
  * Output: expression data in a hierarchy like
@@ -57,7 +57,8 @@ export function stratifyExpressionData(sampleEdges: any, sampleSets: any, sample
57
57
  * I.e., aggregate along the gene axis.
58
58
  * @param {*} stratifiedResult
59
59
  * @param {*} geneSelection
60
+ * @param {number|string} featureAggregationStrategy
60
61
  * @returns
61
62
  */
62
- export function aggregateStratifiedExpressionData(stratifiedResult: any, geneSelection: any): any;
63
+ export function aggregateStratifiedExpressionData(stratifiedResult: any, geneSelection: any, featureAggregationStrategy: number | string): any;
63
64
  //# sourceMappingURL=expr-utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"expr-utils.d.ts","sourceRoot":"","sources":["../src/expr-utils.js"],"names":[],"mappings":"AAUA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,4CAbW,GAAC,wCACD,GAAC,sBACD,GAAC,YAED,GAAC,kBACD,GAAC,oBAED,GAAC,8BAoIX;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,oDAbW,GAAC,cACD,GAAC,sBACD,GAAC,kBACD,GAAC,YACD,GAAC,kBACD,GAAC,iBACD,GAAC,oBACD,GAAC,gBACD,GAAC,yBACD,GAAC,oCACD,GAAC,SAmFX;AAED;;;;;;;;;;GAUG;AACH,oEAJW,GAAC,iBACD,GAAC,OAiBX"}
1
+ {"version":3,"file":"expr-utils.d.ts","sourceRoot":"","sources":["../src/expr-utils.js"],"names":[],"mappings":"AAUA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,4CAbW,GAAC,wCACD,GAAC,sBACD,GAAC,YAED,GAAC,kBACD,GAAC,oBAED,GAAC,iEAiKX;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,oDAbW,GAAC,cACD,GAAC,sBACD,GAAC,kBACD,GAAC,YACD,GAAC,kBACD,GAAC,iBACD,GAAC,oBACD,GAAC,gBACD,GAAC,yBACD,GAAC,oCACD,GAAC,SAmFX;AAED;;;;;;;;;;;GAWG;AACH,oEALW,GAAC,iBACD,GAAC,8BACD,MAAM,GAAC,MAAM,OAiDvB"}
@@ -28,7 +28,8 @@ import { treeToSelectedSetMap, treeToObsIdsBySetNames, } from './cell-set-utils.
28
28
  * @param {*} featureValueTransformCoefficient
29
29
  * @returns
30
30
  */
31
- export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify) {
31
+ export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify, // Assumed to be sorted with respect to the obsIndex.
32
+ featureAggregationStrategy) {
32
33
  const result = new InternMap([], JSON.stringify);
33
34
  const hasSampleSetSelection = Array.isArray(sampleSetSelection) && sampleSetSelection.length > 0;
34
35
  const hasCellSetSelection = Array.isArray(cellSetSelection) && cellSetSelection.length > 0;
@@ -38,8 +39,16 @@ export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sam
38
39
  if (arrKeys.includes('obsIndex') || arrKeys.includes('i')) {
39
40
  throw new Error('The keys "obsIndex" and "i" are reserved for internal use.');
40
41
  }
41
- if (Object.values(arraysToStratify).some(arr => arr.length !== obsIndex.length)) {
42
- throw new Error('All arrays must have the same length as the obsIndex.');
42
+ if (Object.entries(arraysToStratify).some(([arrKey, arr]) => {
43
+ if (arrKey === 'featureValue') {
44
+ // The featureValue array is an array of arrays, one per feature,
45
+ // so we instead expect each sub-array to have a length
46
+ // equal to the number of observations.
47
+ return arr.some(a => a.length !== obsIndex.length);
48
+ }
49
+ return arr.length !== obsIndex.length;
50
+ })) {
51
+ // throw new Error('All arrays must have the same length as the obsIndex.');
43
52
  }
44
53
  const sampleSetInfo = sampleSets && sampleSetSelection
45
54
  ? treeToObsIdsBySetNames(sampleSets, sampleSetSelection)
@@ -98,6 +107,7 @@ export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sam
98
107
  // Iterate over every observation.
99
108
  // Insert the ID and all corresponding values into
100
109
  // the appropriate arrays within the InternMap.
110
+ let cellCount = 0;
101
111
  for (let i = 0; i < obsIndex.length; i += 1) {
102
112
  const obsId = obsIndex[i];
103
113
  const cellSet = cellIdToSetMap?.get(obsId) || null;
@@ -111,13 +121,36 @@ export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sam
111
121
  const insertionIndex = result.get(cellSet).get(sampleSet).get('i');
112
122
  // eslint-disable-next-line no-loop-func
113
123
  arrKeys.forEach((arrKey) => {
114
- const value = arraysToStratify[arrKey][i];
124
+ let value;
125
+ if (arrKey === 'featureValue') {
126
+ if (featureAggregationStrategy === 'first') {
127
+ value = arraysToStratify[arrKey][0][i];
128
+ }
129
+ else if (featureAggregationStrategy === 'last') {
130
+ value = arraysToStratify[arrKey].at(-1)[i];
131
+ }
132
+ else if (typeof featureAggregationStrategy === 'number') {
133
+ const j = featureAggregationStrategy;
134
+ // TODO: more checks here for array index validity.
135
+ value = arraysToStratify[arrKey][j][i];
136
+ }
137
+ else if (featureAggregationStrategy === 'sum' || featureAggregationStrategy === 'mean') {
138
+ value = arraysToStratify[arrKey].reduce((a, h) => a + h[i], 0);
139
+ if (featureAggregationStrategy === 'mean') {
140
+ value /= arraysToStratify[arrKey].length;
141
+ }
142
+ }
143
+ }
144
+ else {
145
+ value = arraysToStratify[arrKey][i];
146
+ }
115
147
  result
116
148
  .get(cellSet)
117
149
  .get(sampleSet)
118
150
  .get(arrKey)[insertionIndex] = value;
119
151
  });
120
152
  result.get(cellSet).get(sampleSet).set('i', insertionIndex + 1);
153
+ cellCount += 1;
121
154
  }
122
155
  cellSetKeys.forEach((cellSetKey) => {
123
156
  // Second level: sample set
@@ -129,7 +162,7 @@ export function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sam
129
162
  result.get(cellSetKey).get(sampleSetKey).delete('i');
130
163
  });
131
164
  });
132
- return result;
165
+ return [result, cellCount];
133
166
  }
134
167
  /**
135
168
  * Input: selections and data.
@@ -224,16 +257,55 @@ featureValueTransform, featureValueTransformCoefficient) {
224
257
  * I.e., aggregate along the gene axis.
225
258
  * @param {*} stratifiedResult
226
259
  * @param {*} geneSelection
260
+ * @param {number|string} featureAggregationStrategy
227
261
  * @returns
228
262
  */
229
- export function aggregateStratifiedExpressionData(stratifiedResult, geneSelection) {
263
+ export function aggregateStratifiedExpressionData(stratifiedResult, geneSelection, featureAggregationStrategy) {
230
264
  const result = new InternMap([], JSON.stringify);
231
265
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
232
266
  result.set(cellSetKey, new InternMap([], JSON.stringify));
233
267
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
234
268
  // For now, we just take the first gene.
235
269
  // TODO: support multiple genes via signature score method.
236
- const values = secondLevelInternMap.get(geneSelection[0]);
270
+ let values;
271
+ if (featureAggregationStrategy === 'first') {
272
+ values = secondLevelInternMap.get(geneSelection[0]);
273
+ }
274
+ else if (featureAggregationStrategy === 'last') {
275
+ values = secondLevelInternMap.get(geneSelection.at(-1));
276
+ }
277
+ else if (typeof featureAggregationStrategy === 'number') {
278
+ const i = featureAggregationStrategy;
279
+ if (i >= 0 && i < geneSelection.length) {
280
+ values = secondLevelInternMap.get(geneSelection[i]);
281
+ }
282
+ else {
283
+ throw new Error('Feature index used for featureAggregationStrategy is invalid.');
284
+ }
285
+ }
286
+ else if (featureAggregationStrategy === 'sum' || featureAggregationStrategy === 'mean') {
287
+ // Array of per-gene arrays.
288
+ const subarrays = geneSelection
289
+ .map(geneId => secondLevelInternMap.get(geneId));
290
+ // Use reduce+map to sum the arrays element-wise.
291
+ values = subarrays
292
+ .reduce((acc, curr) => acc.map((val, idx) => val + curr[idx]));
293
+ if (featureAggregationStrategy === 'mean') {
294
+ const N = geneSelection.length;
295
+ values = values.map(val => val / N);
296
+ }
297
+ }
298
+ else if (featureAggregationStrategy === 'difference') {
299
+ if (geneSelection.length === 2) {
300
+ const subarrays = geneSelection
301
+ .map(geneId => secondLevelInternMap.get(geneId));
302
+ values = subarrays
303
+ .reduce((acc, curr) => acc.map((val, idx) => val - curr[idx]));
304
+ }
305
+ else {
306
+ throw new Error('Expected exactly two selected features when featureAggregationStrategy is difference.');
307
+ }
308
+ }
237
309
  result.get(cellSetKey).set(sampleSetKey, values);
238
310
  });
239
311
  });
@@ -68,6 +68,7 @@ describe('Utility functions for processing expression data', () => {
68
68
  ];
69
69
  const featureValueTransform = null;
70
70
  const featureValueTransformCoefficient = 1;
71
+ const featureAggregationStrategy = 'first';
71
72
  it('stratifyExpressionData: stratify by cell set, then sample set', () => {
72
73
  const [result, exprMax] = stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, expressionData, obsIndex, mergedCellSets, geneSelection, cellSetSelection, cellSetColor, featureValueTransform, featureValueTransformCoefficient);
73
74
  expect(Array.from(result.keys())).toEqual([['Cell type', 'T cell'], ['Cell type', 'B cell']]);
@@ -75,7 +76,7 @@ describe('Utility functions for processing expression data', () => {
75
76
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('Gene 1').length).toBe(2);
76
77
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('Gene 1')).toEqual([10, 30]);
77
78
  expect(exprMax).toEqual(41);
78
- const aggregateData = aggregateStratifiedExpressionData(result, geneSelection);
79
+ const aggregateData = aggregateStratifiedExpressionData(result, geneSelection, featureAggregationStrategy);
79
80
  expect(Array.from(aggregateData.keys())).toEqual([['Cell type', 'T cell'], ['Cell type', 'B cell']]);
80
81
  expect(Array.from(aggregateData.get(['Cell type', 'T cell']).keys())).toEqual([['Clinical groups', 'AKI'], ['Clinical groups', 'CKD']]);
81
82
  expect(aggregateData.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).length).toBe(2);
@@ -97,19 +98,19 @@ describe('Utility functions for processing expression data', () => {
97
98
  const uint8ExpressionData = [
98
99
  new Uint8Array([10, 20, 30, 40, 11, 21, 31, 41]),
99
100
  ];
100
- const result = stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, alignedEmbeddingIndex, mergedCellSets, cellSetSelection, {
101
+ const [result, cellCount] = stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, alignedEmbeddingIndex, mergedCellSets, cellSetSelection, {
101
102
  obsEmbeddingX: alignedEmbeddingData.data[0],
102
103
  obsEmbeddingY: alignedEmbeddingData.data[1],
103
- // TODO: aggregate and transform expression data if needed prior to passing here
104
- ...(uint8ExpressionData?.[0] ? { featureValue: uint8ExpressionData?.[0] } : {}),
105
- });
104
+ ...(uint8ExpressionData?.[0] ? { featureValue: uint8ExpressionData } : {}),
105
+ }, featureAggregationStrategy);
106
106
  expect(Array.from(result.keys())).toEqual([['Cell type', 'T cell'], ['Cell type', 'B cell']]);
107
107
  expect(Array.from(result.get(['Cell type', 'T cell']).keys())).toEqual([['Clinical groups', 'AKI'], ['Clinical groups', 'CKD']]);
108
108
  expect(Array.from(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).keys())).toEqual(['obsEmbeddingX', 'obsEmbeddingY', 'featureValue', 'obsIndex']);
109
109
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue').length).toBe(2);
110
- expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue')).toEqual(new Uint8Array([10, 30]));
110
+ expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue')).toEqual([10, 30]);
111
111
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingX').length).toBe(2);
112
112
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingY').length).toBe(2);
113
+ expect(cellCount).toBe(8);
113
114
  });
114
115
  });
115
116
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitessce/sets-utils",
3
- "version": "3.5.10",
3
+ "version": "3.5.11",
4
4
  "author": "HIDIVE Lab at HMS",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
@@ -25,9 +25,9 @@
25
25
  "lodash-es": "^4.17.21",
26
26
  "tinycolor2": "^1.4.1",
27
27
  "uuid": "^9.0.0",
28
- "@vitessce/schemas": "3.5.10",
29
- "@vitessce/utils": "3.5.10",
30
- "@vitessce/globals": "3.5.10"
28
+ "@vitessce/schemas": "3.5.11",
29
+ "@vitessce/utils": "3.5.11",
30
+ "@vitessce/globals": "3.5.11"
31
31
  },
32
32
  "scripts": {
33
33
  "bundle": "pnpm exec vite build -c ../../../scripts/vite.config.js",
package/src/expr-utils.js CHANGED
@@ -37,6 +37,7 @@ export function stratifyArrays(
37
37
  sampleSets, sampleSetSelection,
38
38
  obsIndex, mergedCellSets, cellSetSelection,
39
39
  arraysToStratify, // Assumed to be sorted with respect to the obsIndex.
40
+ featureAggregationStrategy,
40
41
  ) {
41
42
  const result = new InternMap([], JSON.stringify);
42
43
 
@@ -50,8 +51,16 @@ export function stratifyArrays(
50
51
  if (arrKeys.includes('obsIndex') || arrKeys.includes('i')) {
51
52
  throw new Error('The keys "obsIndex" and "i" are reserved for internal use.');
52
53
  }
53
- if (Object.values(arraysToStratify).some(arr => arr.length !== obsIndex.length)) {
54
- throw new Error('All arrays must have the same length as the obsIndex.');
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.');
55
64
  }
56
65
 
57
66
  const sampleSetInfo = sampleSets && sampleSetSelection
@@ -119,6 +128,7 @@ export function stratifyArrays(
119
128
  // Iterate over every observation.
120
129
  // Insert the ID and all corresponding values into
121
130
  // the appropriate arrays within the InternMap.
131
+ let cellCount = 0;
122
132
  for (let i = 0; i < obsIndex.length; i += 1) {
123
133
  const obsId = obsIndex[i];
124
134
 
@@ -136,7 +146,25 @@ export function stratifyArrays(
136
146
 
137
147
  // eslint-disable-next-line no-loop-func
138
148
  arrKeys.forEach((arrKey) => {
139
- const value = arraysToStratify[arrKey][i];
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
+ }
164
+ }
165
+ } else {
166
+ value = arraysToStratify[arrKey][i];
167
+ }
140
168
 
141
169
  result
142
170
  .get(cellSet)
@@ -144,6 +172,7 @@ export function stratifyArrays(
144
172
  .get(arrKey)[insertionIndex] = value;
145
173
  });
146
174
  result.get(cellSet).get(sampleSet).set('i', insertionIndex + 1);
175
+ cellCount += 1;
147
176
  }
148
177
 
149
178
  cellSetKeys.forEach((cellSetKey) => {
@@ -157,7 +186,7 @@ export function stratifyArrays(
157
186
  });
158
187
  });
159
188
 
160
- return result;
189
+ return [result, cellCount];
161
190
  }
162
191
 
163
192
  /**
@@ -275,10 +304,11 @@ export function stratifyExpressionData(
275
304
  * I.e., aggregate along the gene axis.
276
305
  * @param {*} stratifiedResult
277
306
  * @param {*} geneSelection
307
+ * @param {number|string} featureAggregationStrategy
278
308
  * @returns
279
309
  */
280
310
  export function aggregateStratifiedExpressionData(
281
- stratifiedResult, geneSelection,
311
+ stratifiedResult, geneSelection, featureAggregationStrategy,
282
312
  ) {
283
313
  const result = new InternMap([], JSON.stringify);
284
314
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
@@ -286,7 +316,39 @@ export function aggregateStratifiedExpressionData(
286
316
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
287
317
  // For now, we just take the first gene.
288
318
  // TODO: support multiple genes via signature score method.
289
- const values = secondLevelInternMap.get(geneSelection[0]);
319
+ let values;
320
+ if (featureAggregationStrategy === 'first') {
321
+ values = secondLevelInternMap.get(geneSelection[0]);
322
+ } else if (featureAggregationStrategy === 'last') {
323
+ values = secondLevelInternMap.get(geneSelection.at(-1));
324
+ } else if (typeof featureAggregationStrategy === 'number') {
325
+ const i = featureAggregationStrategy;
326
+ if (i >= 0 && i < geneSelection.length) {
327
+ values = secondLevelInternMap.get(geneSelection[i]);
328
+ } else {
329
+ throw new Error('Feature index used for featureAggregationStrategy is invalid.');
330
+ }
331
+ } else if (featureAggregationStrategy === 'sum' || featureAggregationStrategy === 'mean') {
332
+ // Array of per-gene arrays.
333
+ const subarrays = geneSelection
334
+ .map(geneId => secondLevelInternMap.get(geneId));
335
+ // Use reduce+map to sum the arrays element-wise.
336
+ values = subarrays
337
+ .reduce((acc, curr) => acc.map((val, idx) => val + curr[idx]));
338
+ if (featureAggregationStrategy === 'mean') {
339
+ const N = geneSelection.length;
340
+ values = values.map(val => val / N);
341
+ }
342
+ } else if (featureAggregationStrategy === 'difference') {
343
+ if (geneSelection.length === 2) {
344
+ const subarrays = geneSelection
345
+ .map(geneId => secondLevelInternMap.get(geneId));
346
+ values = subarrays
347
+ .reduce((acc, curr) => acc.map((val, idx) => val - curr[idx]));
348
+ } else {
349
+ throw new Error('Expected exactly two selected features when featureAggregationStrategy is difference.');
350
+ }
351
+ }
290
352
  result.get(cellSetKey).set(sampleSetKey, values);
291
353
  });
292
354
  });
@@ -74,6 +74,7 @@ describe('Utility functions for processing expression data', () => {
74
74
  ];
75
75
  const featureValueTransform = null;
76
76
  const featureValueTransformCoefficient = 1;
77
+ const featureAggregationStrategy = 'first';
77
78
 
78
79
 
79
80
  it('stratifyExpressionData: stratify by cell set, then sample set', () => {
@@ -91,7 +92,7 @@ describe('Utility functions for processing expression data', () => {
91
92
  expect(exprMax).toEqual(41);
92
93
 
93
94
  const aggregateData = aggregateStratifiedExpressionData(
94
- result, geneSelection,
95
+ result, geneSelection, featureAggregationStrategy,
95
96
  );
96
97
 
97
98
  expect(Array.from(aggregateData.keys())).toEqual([['Cell type', 'T cell'], ['Cell type', 'B cell']]);
@@ -118,24 +119,25 @@ describe('Utility functions for processing expression data', () => {
118
119
  new Uint8Array([10, 20, 30, 40, 11, 21, 31, 41]),
119
120
  ];
120
121
 
121
- const result = stratifyArrays(
122
+ const [result, cellCount] = stratifyArrays(
122
123
  sampleEdges, sampleIdToObsIdsMap,
123
124
  sampleSets, sampleSetSelection,
124
125
  alignedEmbeddingIndex, mergedCellSets, cellSetSelection, {
125
126
  obsEmbeddingX: alignedEmbeddingData.data[0],
126
127
  obsEmbeddingY: alignedEmbeddingData.data[1],
127
- // TODO: aggregate and transform expression data if needed prior to passing here
128
- ...(uint8ExpressionData?.[0] ? { featureValue: uint8ExpressionData?.[0] } : {}),
128
+ ...(uint8ExpressionData?.[0] ? { featureValue: uint8ExpressionData } : {}),
129
129
  },
130
+ featureAggregationStrategy,
130
131
  );
131
132
 
132
133
  expect(Array.from(result.keys())).toEqual([['Cell type', 'T cell'], ['Cell type', 'B cell']]);
133
134
  expect(Array.from(result.get(['Cell type', 'T cell']).keys())).toEqual([['Clinical groups', 'AKI'], ['Clinical groups', 'CKD']]);
134
135
  expect(Array.from(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).keys())).toEqual(['obsEmbeddingX', 'obsEmbeddingY', 'featureValue', 'obsIndex']);
135
136
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue').length).toBe(2);
136
- expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue')).toEqual(new Uint8Array([10, 30]));
137
+ expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('featureValue')).toEqual([10, 30]);
137
138
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingX').length).toBe(2);
138
139
  expect(result.get(['Cell type', 'T cell']).get(['Clinical groups', 'AKI']).get('obsEmbeddingY').length).toBe(2);
140
+ expect(cellCount).toBe(8);
139
141
  });
140
142
  });
141
143
  });