@vitessce/zarr 4.0.4 → 4.0.6

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 (55) hide show
  1. package/dist/index.js +14588 -18551
  2. package/dist-tsc/AnnDataSource.d.ts +37 -1
  3. package/dist-tsc/AnnDataSource.d.ts.map +1 -1
  4. package/dist-tsc/AnnDataSource.js +108 -22
  5. package/dist-tsc/AnnDataSource.js.map +1 -1
  6. package/dist-tsc/AnnDataSource.test.js +169 -1
  7. package/dist-tsc/AnnDataSource.test.js.map +1 -1
  8. package/dist-tsc/ZarrDataSource.d.ts +27 -8
  9. package/dist-tsc/ZarrDataSource.d.ts.map +1 -1
  10. package/dist-tsc/ZarrDataSource.js +58 -12
  11. package/dist-tsc/ZarrDataSource.js.map +1 -1
  12. package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.d.ts +1 -1
  13. package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.d.ts.map +1 -1
  14. package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.js +6 -2
  15. package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.js.map +1 -1
  16. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.d.ts +81 -22
  17. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.d.ts.map +1 -1
  18. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.js +410 -180
  19. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.js.map +1 -1
  20. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js +289 -1
  21. package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js.map +1 -1
  22. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.d.ts +16 -1
  23. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.d.ts.map +1 -1
  24. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.js +76 -10
  25. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.js.map +1 -1
  26. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.d.ts +2 -0
  27. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.d.ts.map +1 -0
  28. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.js +81 -0
  29. package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.js.map +1 -0
  30. package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.d.ts +5 -1
  31. package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.d.ts.map +1 -1
  32. package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.js +2 -2
  33. package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.js.map +1 -1
  34. package/dist-tsc/anndata-loaders/utils.d.ts +58 -0
  35. package/dist-tsc/anndata-loaders/utils.d.ts.map +1 -1
  36. package/dist-tsc/anndata-loaders/utils.js +149 -0
  37. package/dist-tsc/anndata-loaders/utils.js.map +1 -1
  38. package/dist-tsc/anndata-loaders/utils.test.js +134 -1
  39. package/dist-tsc/anndata-loaders/utils.test.js.map +1 -1
  40. package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.d.ts.map +1 -1
  41. package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js +9 -2
  42. package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js.map +1 -1
  43. package/package.json +12 -12
  44. package/src/AnnDataSource.js +114 -37
  45. package/src/AnnDataSource.test.js +179 -1
  46. package/src/ZarrDataSource.js +60 -13
  47. package/src/anndata-loaders/ObsFeatureColumnsAnndataLoader.js +6 -2
  48. package/src/anndata-loaders/ObsFeatureMatrixAnndataLoader.js +450 -190
  49. package/src/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js +319 -1
  50. package/src/anndata-loaders/ObsSetsAnndataLoader.js +85 -10
  51. package/src/anndata-loaders/ObsSetsAnndataLoader.test.js +91 -0
  52. package/src/anndata-loaders/SampleSetsAnndataLoader.js +2 -2
  53. package/src/anndata-loaders/utils.js +157 -0
  54. package/src/anndata-loaders/utils.test.js +158 -1
  55. package/src/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js +9 -2
@@ -1,6 +1,11 @@
1
1
  /* eslint-disable func-names, camelcase */
2
- import { describe, it, expect } from 'vitest';
2
+ import {
3
+ describe, it, expect, vi, afterEach,
4
+ } from 'vitest';
5
+ import { root as zarrRoot, create as zarrCreate } from 'zarrita';
3
6
  import { createStoreFromMapContents } from '@vitessce/zarr-utils';
7
+ import { log } from '@vitessce/globals';
8
+ import { MatrixTooLargeError } from '@vitessce/error';
4
9
  import ObsFeatureMatrixAnndataLoader from './ObsFeatureMatrixAnndataLoader.js';
5
10
  import AnnDataSource from '../AnnDataSource.js';
6
11
  import MuDataSource from '../MuDataSource.js';
@@ -27,6 +32,7 @@ import mudata_0_2_CsrFixture from '../json-fixtures/mudata-0.2/mudata-csr.json';
27
32
  import mudata_0_2_DenseFixture from '../json-fixtures/mudata-0.2/mudata-dense.json';
28
33
 
29
34
  const toArray = typedArr => Array.from(typedArr).map(Number);
35
+ const toBigInt = value => BigInt(value); // eslint-disable-line no-undef
30
36
 
31
37
  function createAnndataLoader(url, mapContents, path = 'X') {
32
38
  const store = createStoreFromMapContents(mapContents);
@@ -226,4 +232,316 @@ describe('loaders/ObsFeatureMatrixAnndataLoader', () => {
226
232
  expect(csrMatrix).toEqual(denseMatrix);
227
233
  });
228
234
  });
235
+
236
+ describe('size handling and the CSR column scan', () => {
237
+ const CSR_URL = '@fixtures/zarr/anndata-0.11/anndata-csr.adata.zarr';
238
+ const CSC_URL = '@fixtures/zarr/anndata-0.11/anndata-csc.zarr';
239
+ const DENSE_URL = '@fixtures/zarr/anndata-0.11/anndata-dense.zarr';
240
+
241
+ // The fixtures store X[i, j] = j for 3 cells and 15 genes.
242
+ const NUM_CELLS = 3;
243
+ const NUM_GENES = 15;
244
+ const PATTERN = Array.from(
245
+ { length: NUM_CELLS },
246
+ () => Array.from({ length: NUM_GENES }, (_, j) => j),
247
+ );
248
+
249
+ const decodeJson = (fixture, key) => JSON.parse(atob(new Map(fixture).get(key)));
250
+
251
+ // Replace one metadata document of a fixture, e.g. to fake a shape.
252
+ function withOverride(fixture, key, value) {
253
+ return [...fixture.filter(([k]) => k !== key), [key, btoa(JSON.stringify(value))]];
254
+ }
255
+
256
+ function createLoaderFromStore(store, options = { path: 'X' }) {
257
+ const config = {
258
+ url: '@fixtures/zarr/custom.zarr',
259
+ fileType: 'obsFeatureMatrix.anndata.zarr',
260
+ options,
261
+ };
262
+ const source = new AnnDataSource({ ...config, store });
263
+ return new ObsFeatureMatrixAnndataLoader(source, config);
264
+ }
265
+
266
+ // A fixture store that records every key read, optionally holding reads of
267
+ // matching keys until released.
268
+ function createCountingStore(mapContents, gatePattern = null) {
269
+ const inner = createStoreFromMapContents(mapContents);
270
+ const reads = [];
271
+ let release = () => {};
272
+ const gate = new Promise((resolve) => { release = resolve; });
273
+ const store = {
274
+ async get(key) {
275
+ reads.push(key);
276
+ if (gatePattern && gatePattern.test(key)) {
277
+ await gate;
278
+ }
279
+ return inner.get(key);
280
+ },
281
+ };
282
+ return { store, reads, release: () => release() };
283
+ }
284
+
285
+ // Build a sparse X (zarr v3, written with zarrita) over the obs/var of a
286
+ // fixture, with a chosen chunk size and pointer dtype, so that multi-chunk
287
+ // and int64 code paths can be tested without new fixture files. Optionally
288
+ // adds a uint8 var column usable as a feature filter.
289
+ async function createSparseOverlayStore(baseFixture, {
290
+ encoding, matrix, chunkSize, indexDtype = 'int32', dataDtype = 'float32', varFilter = null,
291
+ }) {
292
+ const numRows = matrix.length;
293
+ const numCols = matrix[0].length;
294
+ const indptr = [0];
295
+ const indices = [];
296
+ const data = [];
297
+ if (encoding === 'csr_matrix') {
298
+ matrix.forEach((rowValues) => {
299
+ rowValues.forEach((value, col) => {
300
+ if (value !== 0) {
301
+ indices.push(col);
302
+ data.push(value);
303
+ }
304
+ });
305
+ indptr.push(indices.length);
306
+ });
307
+ } else {
308
+ for (let col = 0; col < numCols; col += 1) {
309
+ for (let row = 0; row < numRows; row += 1) {
310
+ if (matrix[row][col] !== 0) {
311
+ indices.push(row);
312
+ data.push(matrix[row][col]);
313
+ }
314
+ }
315
+ indptr.push(indices.length);
316
+ }
317
+ }
318
+ const overlay = new Map();
319
+ const root = zarrRoot(overlay);
320
+ await zarrCreate(root.resolve('X'), {
321
+ attributes: { 'encoding-type': encoding, 'encoding-version': '0.1.0', shape: [numRows, numCols] },
322
+ });
323
+ const TYPED = {
324
+ int32: Int32Array,
325
+ int64: BigInt64Array, // eslint-disable-line no-undef
326
+ float32: Float32Array,
327
+ float64: Float64Array,
328
+ uint8: Uint8Array,
329
+ };
330
+ const writeArray = async (path, values, dataType, chunk) => {
331
+ await zarrCreate(root.resolve(path), {
332
+ shape: [values.length],
333
+ chunkShape: [chunk],
334
+ dtype: dataType,
335
+ codecs: [{ name: 'bytes', configuration: { endian: 'little' } }],
336
+ fillValue: 0,
337
+ });
338
+ // Write the chunk bytes directly (the bytes codec is little-endian raw
339
+ // bytes), padding the trailing chunk the way a zarr writer would.
340
+ const Ctor = TYPED[dataType];
341
+ for (let c = 0; c * chunk < values.length; c += 1) {
342
+ const typed = new Ctor(chunk);
343
+ values.slice(c * chunk, (c + 1) * chunk).forEach((value, i) => {
344
+ typed[i] = dataType === 'int64' ? toBigInt(value) : value;
345
+ });
346
+ overlay.set(`/${path}/c/${c}`, new Uint8Array(typed.buffer));
347
+ }
348
+ };
349
+ await writeArray('X/indptr', indptr, indexDtype, indptr.length);
350
+ await writeArray('X/indices', indices, indexDtype, chunkSize);
351
+ await writeArray('X/data', data, dataDtype, chunkSize);
352
+ if (varFilter) {
353
+ await writeArray('var/highly_variable', varFilter.map(v => (v ? 1 : 0)), 'uint8', varFilter.length);
354
+ }
355
+ const base = createStoreFromMapContents(baseFixture);
356
+ return {
357
+ async get(key) {
358
+ return overlay.has(key) ? overlay.get(key) : base.get(key);
359
+ },
360
+ };
361
+ }
362
+
363
+ afterEach(() => {
364
+ vi.restoreAllMocks();
365
+ delete window.performance.memory;
366
+ });
367
+
368
+ it('selects all-zero, repeated, and unknown features consistently across encodings', async () => {
369
+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
370
+ const selection = { selection: ['gene_0', 'gene_14', 'gene_5', 'gene_5', 'not_a_gene'] };
371
+ const [csr, csc, dense] = await Promise.all([
372
+ createAnndataLoader(CSR_URL, anndata_0_11_CsrFixture).loadGeneSelection(selection),
373
+ createAnndataLoader(CSC_URL, anndata_0_11_CscFixture).loadGeneSelection(selection),
374
+ createAnndataLoader(DENSE_URL, anndata_0_11_DenseFixture).loadGeneSelection(selection),
375
+ ]);
376
+ expect(csr.data.map(toArray)).toEqual(dense.data.map(toArray));
377
+ expect(csc.data.map(toArray)).toEqual(dense.data.map(toArray));
378
+ // gene_0 is all zeros in the fixtures; an unknown feature reports zeros too.
379
+ expect(toArray(dense.data[0])).toEqual([0, 0, 0]);
380
+ expect(toArray(dense.data[1])).toEqual([14, 14, 14]);
381
+ expect(toArray(dense.data[4])).toEqual([0, 0, 0]);
382
+ // One warning per loader for the unknown feature.
383
+ expect(warn).toHaveBeenCalledTimes(3);
384
+ expect(warn.mock.calls[0][0]).toContain('not_a_gene');
385
+ });
386
+
387
+ it('coalesces concurrent CSR selections into a single scan', async () => {
388
+ const { store, reads } = createCountingStore(anndata_0_11_CsrFixture);
389
+ const loader = createLoaderFromStore(store);
390
+ const [a, b] = await Promise.all([
391
+ loader.loadGeneSelection({ selection: ['gene_1'] }),
392
+ loader.loadGeneSelection({ selection: ['gene_5', 'gene_1'] }),
393
+ ]);
394
+ expect(toArray(a.data[0])).toEqual([1, 1, 1]);
395
+ expect(b.data.map(toArray)).toEqual([[5, 5, 5], [1, 1, 1]]);
396
+ expect(reads.filter(key => key === '/X/indices/0').length).toEqual(1);
397
+ expect(reads.filter(key => key === '/X/data/0').length).toEqual(1);
398
+ });
399
+
400
+ it('serves columns requested during a scan with one further scan', async () => {
401
+ const { store, reads, release } = createCountingStore(
402
+ anndata_0_11_CsrFixture, /\/X\/indices\/0$/,
403
+ );
404
+ const loader = createLoaderFromStore(store);
405
+ const first = loader.loadGeneSelection({ selection: ['gene_1'] });
406
+ // Wait until the first scan is blocked on its chunk read, then ask for more.
407
+ await vi.waitFor(() => expect(reads).toContain('/X/indices/0'));
408
+ const second = loader.loadGeneSelection({ selection: ['gene_2'] });
409
+ const third = loader.loadGeneSelection({ selection: ['gene_3'] });
410
+ await new Promise((resolve) => { setTimeout(resolve, 10); });
411
+ release();
412
+ const [a, b, c] = await Promise.all([first, second, third]);
413
+ expect(toArray(a.data[0])).toEqual([1, 1, 1]);
414
+ expect(toArray(b.data[0])).toEqual([2, 2, 2]);
415
+ expect(toArray(c.data[0])).toEqual([3, 3, 3]);
416
+ // The two later requests shared the second scan.
417
+ expect(reads.filter(key => key === '/X/indices/0').length).toEqual(2);
418
+ });
419
+
420
+ it('refuses a CSR selection whose scan exceeds the budget, before reading any chunk', async () => {
421
+ const zarray = decodeJson(anndata_0_11_CsrFixture, '/X/indices/.zarray');
422
+ const fixture = withOverride(
423
+ anndata_0_11_CsrFixture, '/X/indices/.zarray', { ...zarray, shape: [3e9] },
424
+ );
425
+ const { store, reads } = createCountingStore(fixture);
426
+ const loader = createLoaderFromStore(store);
427
+ const error = await loader.loadGeneSelection({ selection: ['gene_1'] }).catch(e => e);
428
+ expect(error).toBeInstanceOf(MatrixTooLargeError);
429
+ expect(error.name).toEqual('MatrixTooLargeError');
430
+ expect(error.message).toContain('"X"');
431
+ expect(error.message).toContain('3,000,000,000');
432
+ expect(error.message).toContain('csc_matrix');
433
+ expect(reads.filter(key => /\/X\/(indices|data)\/\d+$/.test(key))).toEqual([]);
434
+ });
435
+
436
+ it('applies the reported heap limit to the scan budget without caching the refusal', async () => {
437
+ Object.defineProperty(window.performance, 'memory', {
438
+ value: { jsHeapSizeLimit: 64 }, configurable: true,
439
+ });
440
+ const loader = createAnndataLoader(CSR_URL, anndata_0_11_CsrFixture);
441
+ await expect(loader.loadGeneSelection({ selection: ['gene_1'] }))
442
+ .rejects.toThrow(MatrixTooLargeError);
443
+ delete window.performance.memory;
444
+ // The same loader answers once the budget allows; nothing stuck in flight.
445
+ const { data } = await loader.loadGeneSelection({ selection: ['gene_1'] });
446
+ expect(toArray(data[0])).toEqual([1, 1, 1]);
447
+ });
448
+
449
+ it('warns, but still loads, a full matrix whose estimate exceeds the budget', async () => {
450
+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
451
+ Object.defineProperty(window.performance, 'memory', {
452
+ value: { jsHeapSizeLimit: 64 }, configurable: true,
453
+ });
454
+ const [csr, csc, dense] = await Promise.all([
455
+ createAnndataLoader(CSR_URL, anndata_0_11_CsrFixture).loadCellXGene(),
456
+ createAnndataLoader(CSC_URL, anndata_0_11_CscFixture).loadCellXGene(),
457
+ createAnndataLoader(DENSE_URL, anndata_0_11_DenseFixture).loadCellXGene(),
458
+ ]);
459
+ expect(csr).toEqual(dense);
460
+ expect(csc).toEqual(dense);
461
+ expect(warn).toHaveBeenCalledTimes(3);
462
+ warn.mock.calls.forEach(([message]) => {
463
+ expect(message).toContain('"X"');
464
+ expect(message).toContain('[3, 15]');
465
+ expect(message).toContain('initialFeatureFilterPath');
466
+ });
467
+ });
468
+
469
+ it('reports a failed full-matrix allocation as a MatrixTooLargeError', async () => {
470
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
471
+ const fixture = withOverride(anndata_0_11_CsrFixture, '/X/.zattrs', {
472
+ 'encoding-type': 'csr_matrix', 'encoding-version': '0.1.0', shape: [2 ** 20, 2 ** 20],
473
+ });
474
+ const { store, reads } = createCountingStore(fixture);
475
+ const loader = createLoaderFromStore(store);
476
+ const error = await loader.loadCellXGene().catch(e => e);
477
+ expect(error).toBeInstanceOf(MatrixTooLargeError);
478
+ expect(error.message).toContain('[1048576, 1048576]');
479
+ expect(error.message).toContain('"X"');
480
+ expect(error.message).toContain('initialFeatureFilterPath');
481
+ // The allocation is attempted before any stored values are downloaded.
482
+ expect(reads.filter(key => /\/X\/(indices|data)\/\d+$/.test(key))).toEqual([]);
483
+ });
484
+
485
+ it('does not cache a failed full-matrix load', async () => {
486
+ const inner = createStoreFromMapContents(anndata_0_11_CsrFixture);
487
+ let failed = false;
488
+ const store = {
489
+ async get(key) {
490
+ if (!failed && key === '/X/data/0') {
491
+ failed = true;
492
+ throw new Error('transient');
493
+ }
494
+ return inner.get(key);
495
+ },
496
+ };
497
+ const loader = createLoaderFromStore(store);
498
+ await expect(loader.loadCellXGene()).rejects.toThrow('transient');
499
+ const dense = await createAnndataLoader(DENSE_URL, anndata_0_11_DenseFixture).loadCellXGene();
500
+ expect(await loader.loadCellXGene()).toEqual(dense);
501
+ });
502
+
503
+ [
504
+ { encoding: 'csr_matrix', chunkSize: 4 },
505
+ { encoding: 'csr_matrix', chunkSize: 5, indexDtype: 'int64', dataDtype: 'float64' },
506
+ { encoding: 'csr_matrix', chunkSize: 1 },
507
+ { encoding: 'csc_matrix', chunkSize: 4, indexDtype: 'int64' },
508
+ ].forEach((variant) => {
509
+ const label = `${variant.encoding} with ${variant.indexDtype || 'int32'} pointers in chunks of ${variant.chunkSize}`;
510
+ it(`matches the dense matrix for ${label}`, async () => {
511
+ const store = await createSparseOverlayStore(anndata_0_12_DenseFixture, {
512
+ ...variant, matrix: PATTERN,
513
+ });
514
+ const loader = createLoaderFromStore(store);
515
+ const dense = createAnndataLoader(
516
+ '@fixtures/zarr/anndata-0.12/anndata-dense.zarr', anndata_0_12_DenseFixture,
517
+ );
518
+ const selection = { selection: ['gene_0', 'gene_1', 'gene_14', 'gene_7'] };
519
+ const [sparseSelection, denseSelection] = await Promise.all([
520
+ loader.loadGeneSelection(selection),
521
+ dense.loadGeneSelection(selection),
522
+ ]);
523
+ expect(sparseSelection.data.map(toArray)).toEqual(denseSelection.data.map(toArray));
524
+ const [sparseMatrix, denseMatrix] = await Promise.all([
525
+ loader.loadCellXGene(),
526
+ dense.loadCellXGene(),
527
+ ]);
528
+ expect(toArray(sparseMatrix.data)).toEqual(toArray(denseMatrix.data));
529
+ });
530
+ });
531
+
532
+ it('loads an initialFeatureFilterPath subset of a CSR matrix without densifying it', async () => {
533
+ const varFilter = Array.from({ length: NUM_GENES }, (_, j) => j % 2 === 0);
534
+ const store = await createSparseOverlayStore(anndata_0_12_DenseFixture, {
535
+ encoding: 'csr_matrix', chunkSize: 4, matrix: PATTERN, varFilter,
536
+ });
537
+ const options = { path: 'X', initialFeatureFilterPath: 'var/highly_variable' };
538
+ const loader = createLoaderFromStore(store, options);
539
+ const result = await loader.load();
540
+ const expectedGenes = varFilter.flatMap((keep, j) => (keep ? [`gene_${j}`] : []));
541
+ expect(result.data.featureIndex).toEqual(expectedGenes);
542
+ // Row-major over the kept columns only.
543
+ const expected = PATTERN.flatMap(rowValues => rowValues.filter((_, j) => varFilter[j]));
544
+ expect(toArray(result.data.obsFeatureMatrix.data)).toEqual(expected);
545
+ });
546
+ });
229
547
  });
@@ -1,8 +1,10 @@
1
1
  import { LoaderResult, AbstractTwoStepLoader } from '@vitessce/abstract';
2
2
  import {
3
3
  initializeCellSetColor,
4
- treeToMembershipMap,
4
+ lazyTreeToMembershipMap,
5
5
  dataToCellSetsTree,
6
+ codesToCellSetsTree,
7
+ membershipFromCodes,
6
8
  } from '@vitessce/sets-utils';
7
9
 
8
10
 
@@ -49,18 +51,84 @@ export default class ObsSetsAnndataLoader extends AbstractTwoStepLoader {
49
51
  return this.dataSource.loadObsColumns(cellSetScoreZarrLocation);
50
52
  }
51
53
 
54
+ /**
55
+ * Try to load every obsSets entry as raw categorical codes rather than
56
+ * per-observation strings. Applicable when this is the plain AnnData/MuData
57
+ * loader (not the SpatialData subclass), every entry is a single categorical
58
+ * column without scores, and all columns share one observation axis.
59
+ * @returns {Promise<object|null>} `{ obsIndex, columns }` where columns hold
60
+ * `{ name, path, codes, categories }` per entry, or null to fall back to the
61
+ * string-based route.
62
+ */
63
+ async loadCodesColumns() {
64
+ const { options } = this;
65
+ const entries = options.obsSets || [];
66
+ const eligible = entries.length > 0
67
+ && this.tablePath === null
68
+ && this.region === null
69
+ && typeof this.dataSource.loadObsColumnCodes === 'function'
70
+ && entries.every(entry => typeof entry.path === 'string' && !entry.scorePath);
71
+ if (!eligible) {
72
+ return null;
73
+ }
74
+ const codesResults = await Promise.all(
75
+ entries.map(entry => this.dataSource.loadObsColumnCodes(entry.path)),
76
+ );
77
+ if (codesResults.some(result => !result)) {
78
+ // At least one column is not categorical.
79
+ return null;
80
+ }
81
+ // The codes are positional along each column's dataframe axis; they can only
82
+ // be interpreted together when every column shares one observation index.
83
+ // loadObsIndex caches per obs path, so reference equality is the right check.
84
+ const columnObsIndices = await Promise.all(
85
+ entries.map(entry => this.dataSource.loadObsIndex(entry.path)),
86
+ );
87
+ const columnObsIndex = columnObsIndices[0];
88
+ if (
89
+ !columnObsIndices.every(obsIndex => obsIndex === columnObsIndex)
90
+ || codesResults.some(result => result.codes.length !== columnObsIndex.length)
91
+ ) {
92
+ return null;
93
+ }
94
+ return {
95
+ obsIndex: columnObsIndex,
96
+ columns: entries.map((entry, j) => ({
97
+ name: entry.name,
98
+ path: [entry.name],
99
+ codes: codesResults[j].codes,
100
+ categories: codesResults[j].categories,
101
+ })),
102
+ };
103
+ }
104
+
52
105
  async load() {
53
106
  if (!this.cachedResult) {
54
107
  const { options } = this;
55
- this.cachedResult = Promise.all([
56
- this.dataSource.loadObsIndex(this.tablePath),
57
- this.loadObsIndices(),
58
- this.loadCellSetIds(),
59
- this.loadCellSetScores(),
60
- ]).then(data => [data[0], dataToCellSetsTree([data[1], data[2], data[3]], options.obsSets)]);
108
+ this.cachedResult = (async () => {
109
+ const obsIndex = await this.dataSource.loadObsIndex(this.tablePath);
110
+ const codesData = await this.loadCodesColumns();
111
+ if (codesData) {
112
+ return [obsIndex, codesToCellSetsTree(codesData, options.obsSets), codesData];
113
+ }
114
+ const [obsIndices, cellSetIds, cellSetScores] = await Promise.all([
115
+ this.loadObsIndices(),
116
+ this.loadCellSetIds(),
117
+ this.loadCellSetScores(),
118
+ ]);
119
+ return [
120
+ obsIndex,
121
+ dataToCellSetsTree([obsIndices, cellSetIds, cellSetScores], options.obsSets),
122
+ null,
123
+ ];
124
+ })();
61
125
  }
62
- const [obsIndex, obsSets] = await this.cachedResult;
63
- const obsSetsMembership = treeToMembershipMap(obsSets);
126
+ const [obsIndex, obsSets, codesData] = await this.cachedResult;
127
+ // With codes available, membership lookups read the codes directly; otherwise
128
+ // the tree-based membership map is built lazily (in a worker when possible).
129
+ const obsSetsMembership = codesData
130
+ ? membershipFromCodes(codesData.obsIndex, codesData.columns)
131
+ : lazyTreeToMembershipMap(obsSets, obsIndex);
64
132
  const coordinationValues = {};
65
133
  const { tree } = obsSets;
66
134
  const newAutoSetSelectionParentName = tree[0].name;
@@ -73,6 +141,13 @@ export default class ObsSetsAnndataLoader extends AbstractTwoStepLoader {
73
141
  const newAutoSetColors = initializeCellSetColor(obsSets, []);
74
142
  coordinationValues.obsSetSelection = newAutoSetSelections;
75
143
  coordinationValues.obsSetColor = newAutoSetColors;
76
- return new LoaderResult({ obsIndex, obsSets, obsSetsMembership }, null, coordinationValues);
144
+ return new LoaderResult({
145
+ obsIndex,
146
+ obsSets,
147
+ obsSetsMembership,
148
+ // The raw columns let views build positional color encodings without
149
+ // walking the tree; consumers must check obsSetsColumns.obsIndex alignment.
150
+ ...(codesData ? { obsSetsColumns: codesData } : {}),
151
+ }, null, coordinationValues);
77
152
  }
78
153
  }
@@ -0,0 +1,91 @@
1
+ /* eslint-disable func-names, camelcase */
2
+ import { describe, it, expect } from 'vitest';
3
+ import { LoaderResult } from '@vitessce/abstract';
4
+ import { createStoreFromMapContents } from '@vitessce/zarr-utils';
5
+ import ObsSetsAnndataLoader from './ObsSetsAnndataLoader.js';
6
+ import AnnDataSource from '../AnnDataSource.js';
7
+ import anndata_0_7_DenseFixture from '../json-fixtures/anndata-0.7/anndata-dense.json';
8
+ import anndata_0_8_DenseFixture from '../json-fixtures/anndata-0.8/anndata-dense.json';
9
+ import anndata_0_12_DenseFixture from '../json-fixtures/anndata-0.12/anndata-dense.json';
10
+
11
+ const createLoader = (version, fixture, obsSets) => {
12
+ const store = createStoreFromMapContents(fixture);
13
+ const config = {
14
+ url: `@fixtures/zarr/anndata-${version}/anndata-dense.zarr`,
15
+ fileType: 'obsSets.anndata.zarr',
16
+ options: { obsSets },
17
+ };
18
+ const source = new AnnDataSource({ ...config, store });
19
+ return { loader: new ObsSetsAnndataLoader(source, config), source };
20
+ };
21
+
22
+ const LEIDEN_OPTIONS = [{ name: 'Leiden', path: 'obs/leiden' }];
23
+
24
+ describe('loaders/ObsSetsAnndataLoader', () => {
25
+ Object.entries({
26
+ 0.7: anndata_0_7_DenseFixture,
27
+ 0.8: anndata_0_8_DenseFixture,
28
+ 0.12: anndata_0_12_DenseFixture,
29
+ }).forEach(([version, fixture]) => {
30
+ describe(`AnnData v${version}`, () => {
31
+ it('codes route produces the same tree and membership as the string route', async () => {
32
+ const { loader: codesLoader } = createLoader(version, fixture, LEIDEN_OPTIONS);
33
+ const { loader: stringLoader, source: stringSource } = createLoader(
34
+ version, fixture, LEIDEN_OPTIONS,
35
+ );
36
+ // Force the reference loader onto the string-based route.
37
+ stringSource.loadObsColumnCodes = null;
38
+
39
+ const codesResult = await codesLoader.load();
40
+ const stringResult = await stringLoader.load();
41
+ expect(codesResult).toBeInstanceOf(LoaderResult);
42
+
43
+ // The tree must be byte-identical between routes.
44
+ expect(codesResult.data.obsSets).toEqual(stringResult.data.obsSets);
45
+ expect(codesResult.data.obsIndex).toEqual(stringResult.data.obsIndex);
46
+ // Membership answers must agree for every observation.
47
+ codesResult.data.obsIndex.forEach((obsId) => {
48
+ expect(codesResult.data.obsSetsMembership.get(obsId))
49
+ .toEqual(stringResult.data.obsSetsMembership.get(obsId));
50
+ });
51
+ // Initial coordination values (auto selections/colors) must agree.
52
+ expect(codesResult.coordinationValues).toEqual(stringResult.coordinationValues);
53
+
54
+ // Only the codes route carries raw columns for the view fast path.
55
+ expect(codesResult.data.obsSetsColumns).toBeDefined();
56
+ expect(stringResult.data.obsSetsColumns).toEqual(undefined);
57
+ const { obsIndex, columns } = codesResult.data.obsSetsColumns;
58
+ expect(columns.length).toEqual(1);
59
+ expect(columns[0].path).toEqual(['Leiden']);
60
+ expect(Array.from(columns[0].codes).length).toEqual(obsIndex.length);
61
+ });
62
+ });
63
+ });
64
+
65
+ it('falls back to the string route when a scorePath is present', async () => {
66
+ const { loader } = createLoader('0.8', anndata_0_8_DenseFixture, [
67
+ { name: 'Leiden', path: 'obs/leiden', scorePath: 'obs/leiden' },
68
+ ]);
69
+ const result = await loader.load();
70
+ expect(result.data.obsSetsColumns).toEqual(undefined);
71
+ expect(result.data.obsSets.tree.length).toEqual(1);
72
+ });
73
+
74
+ it('falls back to the string route for multi-level path arrays', async () => {
75
+ const { loader } = createLoader('0.8', anndata_0_8_DenseFixture, [
76
+ { name: 'Leiden', path: ['obs/leiden'] },
77
+ ]);
78
+ const result = await loader.load();
79
+ expect(result.data.obsSetsColumns).toEqual(undefined);
80
+ expect(result.data.obsSets.tree.length).toEqual(1);
81
+ });
82
+
83
+ it('falls back to the string route for non-categorical columns', async () => {
84
+ const { loader } = createLoader('0.8', anndata_0_8_DenseFixture, [
85
+ { name: 'Index', path: 'obs/_index' },
86
+ ]);
87
+ const result = await loader.load();
88
+ expect(result.data.obsSetsColumns).toEqual(undefined);
89
+ expect(result.data.obsSets.tree.length).toEqual(1);
90
+ });
91
+ });
@@ -1,7 +1,7 @@
1
1
  import { LoaderResult, AbstractTwoStepLoader } from '@vitessce/abstract';
2
2
  import {
3
3
  initializeCellSetColor,
4
- treeToMembershipMap,
4
+ lazyTreeToMembershipMap,
5
5
  dataToCellSetsTree,
6
6
  } from '@vitessce/sets-utils';
7
7
 
@@ -57,7 +57,7 @@ export default class SampleSetsAnndataLoader extends AbstractTwoStepLoader {
57
57
  ]));
58
58
  }
59
59
  const [obsIndex, obsSets] = await this.cachedResult;
60
- const obsSetsMembership = treeToMembershipMap(obsSets);
60
+ const obsSetsMembership = lazyTreeToMembershipMap(obsSets, obsIndex);
61
61
  const coordinationValues = {};
62
62
  const { tree } = obsSets;
63
63
  const newAutoSetSelectionParentName = tree[0].name;