@vitessce/sets-utils 3.5.9 → 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
@@ -1154,11 +1154,8 @@ function createRange(fromRight) {
1154
1154
  }
1155
1155
  var range$1 = createRange();
1156
1156
  const range$2 = range$1;
1157
- function feature(geom, properties, options) {
1158
- if (options === void 0) {
1159
- options = {};
1160
- }
1161
- var feat = { type: "Feature" };
1157
+ function feature(geom, properties, options = {}) {
1158
+ const feat = { type: "Feature" };
1162
1159
  if (options.id === 0 || options.id) {
1163
1160
  feat.id = options.id;
1164
1161
  }
@@ -1169,10 +1166,7 @@ function feature(geom, properties, options) {
1169
1166
  feat.geometry = geom;
1170
1167
  return feat;
1171
1168
  }
1172
- function point(coordinates, properties, options) {
1173
- if (options === void 0) {
1174
- options = {};
1175
- }
1169
+ function point(coordinates, properties, options = {}) {
1176
1170
  if (!coordinates) {
1177
1171
  throw new Error("coordinates is required");
1178
1172
  }
@@ -1185,17 +1179,14 @@ function point(coordinates, properties, options) {
1185
1179
  if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {
1186
1180
  throw new Error("coordinates must contain numbers");
1187
1181
  }
1188
- var geom = {
1182
+ const geom = {
1189
1183
  type: "Point",
1190
1184
  coordinates
1191
1185
  };
1192
1186
  return feature(geom, properties, options);
1193
1187
  }
1194
- function featureCollection(features, options) {
1195
- if (options === void 0) {
1196
- options = {};
1197
- }
1198
- var fc = { type: "FeatureCollection" };
1188
+ function featureCollection(features, options = {}) {
1189
+ const fc = { type: "FeatureCollection" };
1199
1190
  if (options.id) {
1200
1191
  fc.id = options.id;
1201
1192
  }
@@ -1311,18 +1302,19 @@ function coordEach(geojson, callback, excludeWrapCoord) {
1311
1302
  }
1312
1303
  }
1313
1304
  }
1314
- function centroid(geojson, options) {
1315
- if (options === void 0) {
1316
- options = {};
1317
- }
1318
- var xSum = 0;
1319
- var ySum = 0;
1320
- var len = 0;
1321
- coordEach(geojson, function(coord) {
1322
- xSum += coord[0];
1323
- ySum += coord[1];
1324
- len++;
1325
- }, true);
1305
+ function centroid(geojson, options = {}) {
1306
+ let xSum = 0;
1307
+ let ySum = 0;
1308
+ let len = 0;
1309
+ coordEach(
1310
+ geojson,
1311
+ function(coord) {
1312
+ xSum += coord[0];
1313
+ ySum += coord[1];
1314
+ len++;
1315
+ },
1316
+ true
1317
+ );
1326
1318
  return point([xSum / len, ySum / len], options.properties);
1327
1319
  }
1328
1320
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
@@ -9380,7 +9372,9 @@ const ViewType$1 = {
9380
9372
  LINK_CONTROLLER: "linkController",
9381
9373
  NEUROGLANCER: "neuroglancer",
9382
9374
  DUAL_SCATTERPLOT: "dualScatterplot",
9383
- TREEMAP: "treemap"
9375
+ TREEMAP: "treemap",
9376
+ SAMPLE_SET_PAIR_MANAGER: "sampleSetPairManager",
9377
+ FEATURE_STATS_TABLE: "featureStatsTable"
9384
9378
  };
9385
9379
  const DataType$1 = {
9386
9380
  OBS_LABELS: "obsLabels",
@@ -9598,6 +9592,7 @@ const CoordinationType$1 = {
9598
9592
  FEATURE_VALUE_COLORMAP: "featureValueColormap",
9599
9593
  FEATURE_VALUE_TRANSFORM: "featureValueTransform",
9600
9594
  FEATURE_VALUE_COLORMAP_RANGE: "featureValueColormapRange",
9595
+ FEATURE_AGGREGATION_STRATEGY: "featureAggregationStrategy",
9601
9596
  OBS_COLOR_ENCODING: "obsColorEncoding",
9602
9597
  SPATIAL_IMAGE_LAYER: "spatialImageLayer",
9603
9598
  SPATIAL_SEGMENTATION_LAYER: "spatialSegmentationLayer",
@@ -9951,6 +9946,7 @@ z.object({
9951
9946
  termColumn: z.string().optional(),
9952
9947
  pValueColumn: z.string(),
9953
9948
  pValueAdjusted: z.boolean().optional(),
9949
+ featureSetLibrary: z.string().optional().describe("Optionally, provide a feature set library name. By default, Reactome_2022."),
9954
9950
  analysisType: z.string().optional().describe("Optionally, provide an analysis_type name. By default, pertpy_hypergeometric.")
9955
9951
  });
9956
9952
  z.object({
@@ -9961,7 +9957,6 @@ z.object({
9961
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."),
9962
9958
  foldChangeTransformation: z.enum(["log2"]).optional(),
9963
9959
  isCredibleEffectColumn: z.string().describe("Column which annotates effects as being credible or not (boolean)."),
9964
- covariateColumn: z.string().describe("Column which defines the covariate used in the analysis."),
9965
9960
  analysisType: z.string().optional().describe("Optionally, provide an analysis_type name. By default, sccoda_df.")
9966
9961
  });
9967
9962
  const annDataObsLabels = annDataObs;
@@ -17779,7 +17774,7 @@ function getCellColors(params) {
17779
17774
  }
17780
17775
  return /* @__PURE__ */ new Map();
17781
17776
  }
17782
- function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify) {
17777
+ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetSelection, obsIndex, mergedCellSets, cellSetSelection, arraysToStratify, featureAggregationStrategy) {
17783
17778
  const result = new InternMap([], JSON.stringify);
17784
17779
  const hasSampleSetSelection = Array.isArray(sampleSetSelection) && sampleSetSelection.length > 0;
17785
17780
  const hasCellSetSelection = Array.isArray(cellSetSelection) && cellSetSelection.length > 0;
@@ -17789,9 +17784,13 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17789
17784
  if (arrKeys.includes("obsIndex") || arrKeys.includes("i")) {
17790
17785
  throw new Error('The keys "obsIndex" and "i" are reserved for internal use.');
17791
17786
  }
17792
- if (Object.values(arraysToStratify).some((arr) => arr.length !== obsIndex.length)) {
17793
- throw new Error("All arrays must have the same length as the obsIndex.");
17794
- }
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
+ ;
17795
17794
  const sampleSetInfo = sampleSets && sampleSetSelection ? treeToObsIdsBySetNames(sampleSets, sampleSetSelection) : null;
17796
17795
  const cellSetInfo = mergedCellSets && cellSetSelection ? treeToObsIdsBySetNames(mergedCellSets, cellSetSelection) : null;
17797
17796
  cellSetKeys.forEach((cellSetKey) => {
@@ -17823,6 +17822,7 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17823
17822
  });
17824
17823
  const sampleIdToSetMap = sampleSets && sampleSetSelection ? treeToSelectedSetMap(sampleSets, sampleSetSelection) : null;
17825
17824
  const cellIdToSetMap = mergedCellSets && cellSetSelection ? treeToSelectedSetMap(mergedCellSets, cellSetSelection) : null;
17825
+ let cellCount = 0;
17826
17826
  for (let i = 0; i < obsIndex.length; i += 1) {
17827
17827
  const obsId = obsIndex[i];
17828
17828
  const cellSet = (cellIdToSetMap == null ? void 0 : cellIdToSetMap.get(obsId)) || null;
@@ -17833,10 +17833,28 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17833
17833
  }
17834
17834
  const insertionIndex = result.get(cellSet).get(sampleSet).get("i");
17835
17835
  arrKeys.forEach((arrKey) => {
17836
- 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
+ }
17837
17854
  result.get(cellSet).get(sampleSet).get(arrKey)[insertionIndex] = value;
17838
17855
  });
17839
17856
  result.get(cellSet).get(sampleSet).set("i", insertionIndex + 1);
17857
+ cellCount += 1;
17840
17858
  }
17841
17859
  cellSetKeys.forEach((cellSetKey) => {
17842
17860
  sampleSetKeys.forEach((sampleSetKey) => {
@@ -17847,7 +17865,7 @@ function stratifyArrays(sampleEdges, sampleIdToObsIdsMap, sampleSets, sampleSetS
17847
17865
  result.get(cellSetKey).get(sampleSetKey).delete("i");
17848
17866
  });
17849
17867
  });
17850
- return result;
17868
+ return [result, cellCount];
17851
17869
  }
17852
17870
  function stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, expressionData, obsIndex, mergedCellSets, geneSelection, cellSetSelection, cellSetColor, featureValueTransform, featureValueTransformCoefficient) {
17853
17871
  const result = new InternMap([], JSON.stringify);
@@ -17874,7 +17892,7 @@ function stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, exp
17874
17892
  const obsId = obsIndex[i];
17875
17893
  const cellSet = cellIdToSetMap == null ? void 0 : cellIdToSetMap.get(obsId);
17876
17894
  const sampleId = sampleEdges == null ? void 0 : sampleEdges.get(obsId);
17877
- const sampleSet = sampleId ? sampleIdToSetMap == null ? void 0 : sampleIdToSetMap.get(sampleId) : null;
17895
+ const sampleSet = sampleId && hasSampleSetSelection ? sampleIdToSetMap == null ? void 0 : sampleIdToSetMap.get(sampleId) : null;
17878
17896
  if (hasSampleSetSelection && !sampleSet) {
17879
17897
  continue;
17880
17898
  }
@@ -17894,12 +17912,38 @@ function stratifyExpressionData(sampleEdges, sampleSets, sampleSetSelection, exp
17894
17912
  }
17895
17913
  return [null, null];
17896
17914
  }
17897
- function aggregateStratifiedExpressionData(stratifiedResult, geneSelection) {
17915
+ function aggregateStratifiedExpressionData(stratifiedResult, geneSelection, featureAggregationStrategy) {
17898
17916
  const result = new InternMap([], JSON.stringify);
17899
17917
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
17900
17918
  result.set(cellSetKey, new InternMap([], JSON.stringify));
17901
17919
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
17902
- 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
+ }
17903
17947
  result.get(cellSetKey).set(sampleSetKey, values);
17904
17948
  });
17905
17949
  });
@@ -2,7 +2,7 @@
2
2
  import { v4 as uuidv4 } from 'uuid';
3
3
  import { isNil, isEqual, range } from 'lodash-es';
4
4
  import { featureCollection as turfFeatureCollection, point as turfPoint } from '@turf/helpers';
5
- import centroid from '@turf/centroid';
5
+ import { centroid } from '@turf/centroid';
6
6
  import concaveman from 'concaveman';
7
7
  import { getDefaultColor, PALETTE } from '@vitessce/utils';
8
8
  import { HIERARCHICAL_SCHEMAS, } from './constants.js';
@@ -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,SAiFX;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.
@@ -190,7 +223,9 @@ featureValueTransform, featureValueTransformCoefficient) {
190
223
  const obsId = obsIndex[i];
191
224
  const cellSet = cellIdToSetMap?.get(obsId);
192
225
  const sampleId = sampleEdges?.get(obsId);
193
- const sampleSet = sampleId ? sampleIdToSetMap?.get(sampleId) : null;
226
+ const sampleSet = sampleId && hasSampleSetSelection
227
+ ? sampleIdToSetMap?.get(sampleId)
228
+ : null;
194
229
  if (hasSampleSetSelection && !sampleSet) {
195
230
  // Skip this sample if it is not in the selected sample set.
196
231
  // eslint-disable-next-line no-continue
@@ -222,16 +257,55 @@ featureValueTransform, featureValueTransformCoefficient) {
222
257
  * I.e., aggregate along the gene axis.
223
258
  * @param {*} stratifiedResult
224
259
  * @param {*} geneSelection
260
+ * @param {number|string} featureAggregationStrategy
225
261
  * @returns
226
262
  */
227
- export function aggregateStratifiedExpressionData(stratifiedResult, geneSelection) {
263
+ export function aggregateStratifiedExpressionData(stratifiedResult, geneSelection, featureAggregationStrategy) {
228
264
  const result = new InternMap([], JSON.stringify);
229
265
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
230
266
  result.set(cellSetKey, new InternMap([], JSON.stringify));
231
267
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
232
268
  // For now, we just take the first gene.
233
269
  // TODO: support multiple genes via signature score method.
234
- 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
+ }
235
309
  result.get(cellSetKey).set(sampleSetKey, values);
236
310
  });
237
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.9",
3
+ "version": "3.5.11",
4
4
  "author": "HIDIVE Lab at HMS",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
@@ -16,8 +16,8 @@
16
16
  "dist-tsc"
17
17
  ],
18
18
  "dependencies": {
19
- "@turf/centroid": "^6.5.0",
20
- "@turf/helpers": "^6.5.0",
19
+ "@turf/centroid": "^7.2.0",
20
+ "@turf/helpers": "^7.2.0",
21
21
  "concaveman": "^1.2.1",
22
22
  "d3-dsv": "^1.1.1",
23
23
  "internmap": "^2.0.3",
@@ -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.9",
29
- "@vitessce/utils": "3.5.9",
30
- "@vitessce/globals": "3.5.9"
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",
@@ -2,7 +2,7 @@
2
2
  import { v4 as uuidv4 } from 'uuid';
3
3
  import { isNil, isEqual, range } from 'lodash-es';
4
4
  import { featureCollection as turfFeatureCollection, point as turfPoint } from '@turf/helpers';
5
- import centroid from '@turf/centroid';
5
+ import { centroid } from '@turf/centroid';
6
6
  import concaveman from 'concaveman';
7
7
  import { getDefaultColor, PALETTE } from '@vitessce/utils';
8
8
  import {
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
  /**
@@ -235,7 +264,9 @@ export function stratifyExpressionData(
235
264
 
236
265
  const cellSet = cellIdToSetMap?.get(obsId);
237
266
  const sampleId = sampleEdges?.get(obsId);
238
- const sampleSet = sampleId ? sampleIdToSetMap?.get(sampleId) : null;
267
+ const sampleSet = sampleId && hasSampleSetSelection
268
+ ? sampleIdToSetMap?.get(sampleId)
269
+ : null;
239
270
 
240
271
  if (hasSampleSetSelection && !sampleSet) {
241
272
  // Skip this sample if it is not in the selected sample set.
@@ -273,10 +304,11 @@ export function stratifyExpressionData(
273
304
  * I.e., aggregate along the gene axis.
274
305
  * @param {*} stratifiedResult
275
306
  * @param {*} geneSelection
307
+ * @param {number|string} featureAggregationStrategy
276
308
  * @returns
277
309
  */
278
310
  export function aggregateStratifiedExpressionData(
279
- stratifiedResult, geneSelection,
311
+ stratifiedResult, geneSelection, featureAggregationStrategy,
280
312
  ) {
281
313
  const result = new InternMap([], JSON.stringify);
282
314
  Array.from(stratifiedResult.entries()).forEach(([cellSetKey, firstLevelInternMap]) => {
@@ -284,7 +316,39 @@ export function aggregateStratifiedExpressionData(
284
316
  Array.from(firstLevelInternMap.entries()).forEach(([sampleSetKey, secondLevelInternMap]) => {
285
317
  // For now, we just take the first gene.
286
318
  // TODO: support multiple genes via signature score method.
287
- 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
+ }
288
352
  result.get(cellSetKey).set(sampleSetKey, values);
289
353
  });
290
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
  });