@vitessce/zarr 4.0.4 → 4.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,8 +1,9 @@
1
1
  /* eslint-disable no-underscore-dangle */
2
- import { open as zarrOpen, get as zarrGet } from 'zarrita';
2
+ import { get as zarrGet, slice as zarrSlice } from 'zarrita';
3
3
  import { log } from '@vitessce/globals';
4
4
  import { dirname } from './utils.js';
5
5
  import ZarrDataSource from './ZarrDataSource.js';
6
+ import { maybeDowncastInt64 } from './anndata-loaders/utils.js';
6
7
  /** @import { DataSourceParams } from '@vitessce/types' */
7
8
  /** @import { TypedArray as ZarrTypedArray, Chunk, ByteStringArray } from 'zarrita' */
8
9
 
@@ -93,32 +94,36 @@ export default class AnnDataSource extends ZarrDataSource {
93
94
  }
94
95
 
95
96
  /**
96
- *
97
+ * Inspect a dataframe column's encoding and resolve where its data lives,
98
+ * without materializing per-observation values. Shared by the string-decoding
99
+ * path (_loadColumn) and the raw-codes path (loadObsColumnCodes).
97
100
  * @param {string} pathOrig
98
- * @returns
101
+ * @returns {Promise<
102
+ * { kind: 'stringArray', valuesPath: string }
103
+ * | { kind: 'codes', codesPath: string, categoriesValues: string[] | undefined }
104
+ * >} For 'codes', categoriesValues is undefined when the column is numeric or
105
+ * when its categories could not be decoded; codes are then stringified directly.
99
106
  */
100
- async _loadColumn(pathOrig) {
101
- const { storeRoot } = this;
102
-
107
+ async _getColumnSpec(pathOrig) {
103
108
  const path = prependSlash(pathOrig);
104
109
  const prefixOrig = dirname(path);
105
110
  const prefix = prependSlash(prefixOrig);
106
111
  const { categories, 'encoding-type': encodingType } = await this.getJson(`${path}/.zattrs`);
107
- /** @type {string[]} */
112
+ /** @type {string[] | undefined} */
108
113
  let categoriesValues;
109
114
  /** @type {undefined | string} */
110
115
  let codesPath;
111
116
  if (categories) {
112
- const { dtype } = await zarrOpen(
113
- storeRoot.resolve(`${prefix}/${categories}`),
114
- { kind: 'array' },
115
- );
117
+ // AnnData 0.7-style: the column holds codes, and a sibling array
118
+ // (named by the `categories` attribute) holds the category strings.
119
+ const { dtype } = await this.openArray(`${prefix}/${categories}`);
116
120
  if (dtype === 'v2:object' || dtype === '|O') {
117
121
  categoriesValues = await this.getFlatArrDecompressed(
118
122
  `${prefix}/${categories}`,
119
123
  );
120
124
  }
121
125
  } else if (encodingType === 'categorical') {
126
+ // AnnData 0.8+ style: the column is a group with codes/ and categories/.
122
127
  const categoriesZattrs = await this.getJson(`${path}/categories/.zattrs`);
123
128
  const categoriesEncodingType = categoriesZattrs?.['encoding-type'];
124
129
  if (categoriesEncodingType === 'nullable-string-array') {
@@ -126,32 +131,37 @@ export default class AnnDataSource extends ZarrDataSource {
126
131
  } else if (categoriesEncodingType === 'string-array') {
127
132
  categoriesValues = await this.getFlatArrDecompressed(`${path}/categories`);
128
133
  } else {
129
- const { dtype } = await zarrOpen(
130
- storeRoot.resolve(`${path}/categories`),
131
- { kind: 'array' },
132
- );
134
+ const { dtype } = await this.openArray(`${path}/categories`);
133
135
  if (dtype === 'v2:object' || dtype === '|O') {
134
136
  categoriesValues = await this.getFlatArrDecompressed(`${path}/categories`);
135
137
  }
136
138
  }
137
139
  codesPath = `${path}/codes`;
138
140
  } else if (encodingType === 'nullable-string-array') {
139
- return this.getFlatArrDecompressed(`${path}/values`);
141
+ return { kind: 'stringArray', valuesPath: `${path}/values` };
140
142
  } else if (encodingType === 'string-array') {
141
- return this.getFlatArrDecompressed(path);
143
+ return { kind: 'stringArray', valuesPath: path };
142
144
  } else {
143
- const { dtype } = await zarrOpen(
144
- storeRoot.resolve(path),
145
- { kind: 'array' },
146
- );
145
+ const { dtype } = await this.openArray(path);
147
146
  if (dtype === 'v2:object' || dtype === '|O') {
148
- return this.getFlatArrDecompressed(path);
147
+ return { kind: 'stringArray', valuesPath: path };
149
148
  }
150
149
  }
151
- const arr = await zarrOpen(
152
- storeRoot.resolve(codesPath || path),
153
- { kind: 'array' },
154
- );
150
+ return { kind: 'codes', codesPath: codesPath || path, categoriesValues };
151
+ }
152
+
153
+ /**
154
+ *
155
+ * @param {string} pathOrig
156
+ * @returns
157
+ */
158
+ async _loadColumn(pathOrig) {
159
+ const spec = await this._getColumnSpec(pathOrig);
160
+ if (spec.kind === 'stringArray') {
161
+ return this.getFlatArrDecompressed(spec.valuesPath);
162
+ }
163
+ const { codesPath, categoriesValues } = spec;
164
+ const arr = await this.openArray(codesPath);
155
165
  const values = await zarrGet(arr, [null]);
156
166
  const { data } = values;
157
167
  const mappedValues = Array.from(data).map(
@@ -160,14 +170,50 @@ export default class AnnDataSource extends ZarrDataSource {
160
170
  return mappedValues;
161
171
  }
162
172
 
173
+ /**
174
+ * Load a categorical column as its raw integer codes plus the (small) list of
175
+ * category strings, skipping the per-observation string materialization that
176
+ * _loadColumn performs. Codes are positional along the column's dataframe axis;
177
+ * a negative code means the value is missing.
178
+ * @param {string} path A path to a dataframe column, like "obs/leiden".
179
+ * @returns {Promise<{
180
+ * codes: ZarrTypedArray<any>, categories: string[],
181
+ * } | null>} Null when the column is not categorical (callers should fall back
182
+ * to the string-based path).
183
+ */
184
+ loadObsColumnCodes(path) {
185
+ if (!this.codesPromises) {
186
+ /** @type {Map<string, Promise<any>>} */
187
+ this.codesPromises = new Map();
188
+ }
189
+ if (!this.codesPromises.has(path)) {
190
+ const promise = (async () => {
191
+ const spec = await this._getColumnSpec(path);
192
+ if (spec.kind !== 'codes' || !spec.categoriesValues) {
193
+ return null;
194
+ }
195
+ const arr = await this.openArray(spec.codesPath);
196
+ const { data } = await zarrGet(arr, [null]);
197
+ // Codes index into a small category list, so int64 codes (BigInt64Array)
198
+ // are safely downcast for plain numeric indexing.
199
+ return { codes: maybeDowncastInt64(data), categories: spec.categoriesValues };
200
+ })().catch((err) => {
201
+ // Clear from cache if the promise rejects, then propagate.
202
+ this.codesPromises.delete(path);
203
+ throw err;
204
+ });
205
+ this.codesPromises.set(path, promise);
206
+ }
207
+ return this.codesPromises.get(path);
208
+ }
209
+
163
210
  /**
164
211
  * Class method for loading general numeric arrays.
165
212
  * @param {string} path A string like obsm.X_pca.
166
213
  * @returns {Promise<Chunk<any>>} A promise for a zarr array containing the data.
167
214
  */
168
215
  async loadNumeric(path) {
169
- const { storeRoot } = this;
170
- return zarrOpen(storeRoot.resolve(path), { kind: 'array' })
216
+ return this.openArray(path)
171
217
  .then(arr => zarrGet(arr));
172
218
  }
173
219
 
@@ -181,12 +227,45 @@ export default class AnnDataSource extends ZarrDataSource {
181
227
  * }>} A promise for a zarr array containing the data.
182
228
  */
183
229
  async loadNumericForDims(path, dims) {
184
- const { storeRoot } = this;
185
- const arr = zarrOpen(storeRoot.resolve(path), { kind: 'array' });
230
+ const loadedArr = await this.openArray(path);
231
+ const minDim = Math.min(...dims);
232
+ const maxDim = Math.max(...dims);
233
+ const isContiguous = maxDim - minDim + 1 === dims.length;
234
+ // A sliced read only helps when at least two requested dims live in the
235
+ // same chunk, where per-dim reads would fetch and decompress that chunk
236
+ // once per dim (e.g. chunks like [129578, 4]). When every dim maps to its
237
+ // own chunk column (e.g. chunks like [160497, 1]), per-dim reads fetch the
238
+ // same chunks but skip the sliced read's interleaved 2D assembly and
239
+ // per-column extraction, which cost ~0.5 s at millions of observations.
240
+ const chunkWidth = loadedArr.chunks[1] ?? 1;
241
+ const dimsShareChunks = new Set(
242
+ dims.map(dim => Math.floor(dim / chunkWidth)),
243
+ ).size < dims.length;
244
+ if (isContiguous && dimsShareChunks) {
245
+ // The dims form a contiguous run (the common case, e.g. [0, 1]), so a single
246
+ // sliced read covers all of them without fetching any shared chunk twice.
247
+ const { data, shape, stride } = await zarrGet(
248
+ loadedArr, [null, zarrSlice(minDim, maxDim + 1)],
249
+ );
250
+ const numRows = shape[0];
251
+ const cols = dims.map((dim) => {
252
+ const colIndex = dim - minDim;
253
+ const col = new /** @type {any} */ (data.constructor)(numRows);
254
+ for (let i = 0; i < numRows; i += 1) {
255
+ col[i] = data[i * stride[0] + colIndex * stride[1]];
256
+ }
257
+ return col;
258
+ });
259
+ return {
260
+ data: /** @type {[ZarrTypedArray<any>, ZarrTypedArray<any>]} */ (cols),
261
+ shape: [dims.length, numRows],
262
+ };
263
+ }
264
+ // Per-dim reads: chunk-disjoint dims fetch every chunk exactly once, and
265
+ // for non-contiguous dims the store-level cache still coalesces concurrent
266
+ // reads of any shared chunks.
186
267
  return Promise.all(
187
- dims.map(dim => arr.then(
188
- loadedArr => zarrGet(loadedArr, [null, dim]),
189
- )),
268
+ dims.map(dim => zarrGet(loadedArr, [null, dim])),
190
269
  ).then(cols => ({
191
270
  data: /** @type {[ZarrTypedArray<any>, ZarrTypedArray<any>]} */ (
192
271
  cols.map(col => col.data)
@@ -202,8 +281,7 @@ export default class AnnDataSource extends ZarrDataSource {
202
281
  * @returns {Promise<string[]>} The data from the zarr array.
203
282
  */
204
283
  async getFlatArrDecompressed(path) {
205
- const { storeRoot } = this;
206
- const arr = await zarrOpen(storeRoot.resolve(path), { kind: 'array' });
284
+ const arr = await this.openArray(path);
207
285
  if (arr.shape[0] === 0) {
208
286
  return [];
209
287
  }
@@ -303,7 +381,6 @@ export default class AnnDataSource extends ZarrDataSource {
303
381
  * @returns {Promise<string>}
304
382
  */
305
383
  async _loadString(path) {
306
- const { storeRoot } = this;
307
384
  const zattrs = await this._loadAttrs(path);
308
385
  if ('encoding-type' in zattrs && 'encoding-version' in zattrs) {
309
386
  const {
@@ -312,7 +389,7 @@ export default class AnnDataSource extends ZarrDataSource {
312
389
  } = zattrs;
313
390
 
314
391
  if (encodingType === 'string' && encodingVersion === '0.2.0') {
315
- const arr = await zarrOpen(storeRoot.resolve(path), { kind: 'array' });
392
+ const arr = await this.openArray(path);
316
393
  // TODO: Use zarrGet once it supports zero-dimensional array access.
317
394
  const { data } = /** @type {{ data: ByteStringArray }} */ (await arr.getChunk([]));
318
395
  return data.get(0);
@@ -1,5 +1,6 @@
1
- /* eslint-disable camelcase */
1
+ /* eslint-disable camelcase, no-underscore-dangle */
2
2
  import { describe, it, expect } from 'vitest';
3
+ import { root as zarrRoot, create as zarrCreate, set as zarrSet } from 'zarrita';
3
4
  import { createStoreFromMapContents } from '@vitessce/zarr-utils';
4
5
  import AnnDataSource from './AnnDataSource.js';
5
6
  import anndata_0_7_DenseFixture from './json-fixtures/anndata-0.7/anndata-dense.json';
@@ -47,3 +48,180 @@ describe('sources/AnnDataSource', () => {
47
48
  });
48
49
  });
49
50
  });
51
+
52
+ describe('AnnDataSource.loadNumericForDims', () => {
53
+ // Wrap the fixture store so that every chunk read is counted.
54
+ function createCountingStore(fixture) {
55
+ const inner = createStoreFromMapContents(fixture);
56
+ const calls = [];
57
+ return {
58
+ calls,
59
+ store: {
60
+ get: (key, opts) => {
61
+ calls.push(key);
62
+ return inner.get(key, opts);
63
+ },
64
+ },
65
+ };
66
+ }
67
+
68
+ it('reads each chunk once for contiguous dims', async () => {
69
+ const { store, calls } = createCountingStore(anndata_0_12_DenseFixture);
70
+ const dataSource = new AnnDataSource({
71
+ url: '@fixtures/zarr/anndata-0.12/anndata-dense.zarr',
72
+ store,
73
+ });
74
+ const result = await dataSource.loadNumericForDims('obsm/X_umap', [0, 1]);
75
+ expect(result.shape).toEqual([2, 3]);
76
+ expect(Array.from(result.data[0])).toEqual([-1, 0, 1]);
77
+ expect(Array.from(result.data[1])).toEqual([-1, 0, 1]);
78
+ // Both dims live in the single chunk 0.0; the contiguous-slice path
79
+ // must read it exactly once rather than once per dim.
80
+ const chunkReads = calls.filter(key => /X_umap\/(c\/0\/0|0\.0)$/.test(key));
81
+ expect(chunkReads.length).toEqual(1);
82
+ });
83
+
84
+ it('returns the same data for non-contiguous dims via the per-dim path', async () => {
85
+ const dataSource = new AnnDataSource({
86
+ url: '@fixtures/zarr/anndata-0.12/anndata-dense.zarr',
87
+ store: createStoreFromMapContents(anndata_0_12_DenseFixture),
88
+ });
89
+ // Both umap columns, requested in descending order: still a contiguous run.
90
+ const descending = await dataSource.loadNumericForDims('obsm/X_umap', [1, 0]);
91
+ expect(Array.from(descending.data[0])).toEqual([-1, 0, 1]);
92
+ expect(Array.from(descending.data[1])).toEqual([-1, 0, 1]);
93
+ // A single dim exercises the per-dim path (max - min + 1 === 1 === length,
94
+ // so it takes the slice path; a duplicated dim forces per-dim).
95
+ const duplicated = await dataSource.loadNumericForDims('obsm/X_umap', [1, 1]);
96
+ expect(Array.from(duplicated.data[0])).toEqual([-1, 0, 1]);
97
+ expect(Array.from(duplicated.data[1])).toEqual([-1, 0, 1]);
98
+ });
99
+ });
100
+
101
+ describe('AnnDataSource.loadObsColumnCodes', () => {
102
+ Object.entries({ 0.7: anndata_0_7_DenseFixture, 0.8: anndata_0_8_DenseFixture, 0.9: anndata_0_9_DenseFixture, '0.10': anndata_0_10_DenseFixture, 0.11: anndata_0_11_DenseFixture, 0.12: anndata_0_12_DenseFixture }).forEach(([version, fixture]) => {
103
+ it(`decodes to the same strings as loadObsColumns for AnnData v${version}`, async () => {
104
+ const dataSource = new AnnDataSource({
105
+ url: `@fixtures/zarr/anndata-${version}/anndata-dense.zarr`,
106
+ store: createStoreFromMapContents(fixture),
107
+ });
108
+ const result = await dataSource.loadObsColumnCodes('obs/leiden');
109
+ expect(result).not.toEqual(null);
110
+ const { codes, categories } = result;
111
+ const decoded = Array.from(codes).map(code => categories[code]);
112
+ const [expected] = await dataSource.loadObsColumns(['obs/leiden']);
113
+ expect(decoded).toEqual(expected);
114
+ });
115
+ });
116
+
117
+ it('returns null for a non-categorical column', async () => {
118
+ const dataSource = new AnnDataSource({
119
+ url: '@fixtures/zarr/anndata-0.8/anndata-dense.zarr',
120
+ store: createStoreFromMapContents(anndata_0_8_DenseFixture),
121
+ });
122
+ expect(await dataSource.loadObsColumnCodes('obs/_index')).toEqual(null);
123
+ });
124
+
125
+ it('caches the promise per column path', async () => {
126
+ const dataSource = new AnnDataSource({
127
+ url: '@fixtures/zarr/anndata-0.8/anndata-dense.zarr',
128
+ store: createStoreFromMapContents(anndata_0_8_DenseFixture),
129
+ });
130
+ const first = dataSource.loadObsColumnCodes('obs/leiden');
131
+ const second = dataSource.loadObsColumnCodes('obs/leiden');
132
+ expect(first).toBe(second);
133
+ expect((await first).codes).toBe((await second).codes);
134
+ });
135
+ });
136
+
137
+ describe('AnnDataSource metadata caching', () => {
138
+ // Wrap the fixture store so that every read is counted.
139
+ function createCountingStore(fixture) {
140
+ const inner = createStoreFromMapContents(fixture);
141
+ const calls = [];
142
+ return {
143
+ calls,
144
+ store: {
145
+ get: (key, opts) => {
146
+ calls.push(key);
147
+ return inner.get(key, opts);
148
+ },
149
+ },
150
+ };
151
+ }
152
+ const isMetadataKey = key => /\.z(attrs|array|group)$/.test(key);
153
+
154
+ it('reads each metadata document at most once per data source', async () => {
155
+ const { store, calls } = createCountingStore(anndata_0_11_DenseFixture);
156
+ const dataSource = new AnnDataSource({
157
+ url: '@fixtures/zarr/anndata-0.11/anndata-dense.zarr',
158
+ store,
159
+ });
160
+ // Loading a categorical column both reads attributes and opens arrays on
161
+ // the same nodes; through the per-path node cache each metadata document
162
+ // is still requested only once.
163
+ const column = await dataSource._loadColumn('obs/leiden');
164
+ expect(column).toEqual(['1', '1', '2']);
165
+ const metaAfterFirst = calls.filter(isMetadataKey);
166
+ expect(new Set(metaAfterFirst).size).toEqual(metaAfterFirst.length);
167
+ // Repeating the load, and re-reading attributes directly, adds no reads.
168
+ await dataSource._loadColumn('obs/leiden');
169
+ await dataSource.getJson('obs/leiden/.zattrs');
170
+ expect(calls.filter(isMetadataKey).length).toEqual(metaAfterFirst.length);
171
+ });
172
+
173
+ it('does not cache a failed open, so a retry reaches the store again', async () => {
174
+ const { store, calls } = createCountingStore(anndata_0_11_DenseFixture);
175
+ const dataSource = new AnnDataSource({
176
+ url: '@fixtures/zarr/anndata-0.11/anndata-dense.zarr',
177
+ store,
178
+ });
179
+ await expect(dataSource.getJson('obs/missing/.zattrs')).rejects.toThrow();
180
+ const probesAfterFirst = calls.filter(key => key.includes('missing')).length;
181
+ expect(probesAfterFirst).toBeGreaterThan(0);
182
+ await expect(dataSource.getJson('obs/missing/.zattrs')).rejects.toThrow();
183
+ expect(calls.filter(key => key.includes('missing')).length)
184
+ .toBeGreaterThan(probesAfterFirst);
185
+ });
186
+ });
187
+
188
+ describe('AnnDataSource.loadNumericForDims chunk-layout routing', () => {
189
+ it('reads each chunk once and skips unrequested columns on a column-chunked array', async () => {
190
+ const overlay = new Map();
191
+ const root = zarrRoot(overlay);
192
+ const numRows = 6;
193
+ const values = Float32Array.from({ length: numRows * 3 }, (_, i) => i);
194
+ const arr = await zarrCreate(root.resolve('obsm/X_test'), {
195
+ shape: [numRows, 3],
196
+ // One column per chunk, three row-chunks per column: the layout where
197
+ // the contiguous-slice route only adds 2D assembly overhead.
198
+ chunkShape: [2, 1],
199
+ dtype: 'float32',
200
+ codecs: [{ name: 'bytes', configuration: { endian: 'little' } }],
201
+ fillValue: 0,
202
+ });
203
+ await zarrSet(arr, [null, null], {
204
+ data: values, shape: [numRows, 3], stride: [3, 1],
205
+ });
206
+ const calls = [];
207
+ const store = {
208
+ get: (key) => {
209
+ calls.push(key);
210
+ return overlay.get(key);
211
+ },
212
+ };
213
+ const dataSource = new AnnDataSource({
214
+ url: '@fixtures/zarr/generated/column-chunked.zarr',
215
+ store,
216
+ });
217
+ const result = await dataSource.loadNumericForDims('obsm/X_test', [0, 1]);
218
+ expect(result.shape).toEqual([2, numRows]);
219
+ expect(Array.from(result.data[0])).toEqual([0, 3, 6, 9, 12, 15]);
220
+ expect(Array.from(result.data[1])).toEqual([1, 4, 7, 10, 13, 16]);
221
+ const chunkCalls = calls.filter(key => key.includes('/c/'));
222
+ // Every requested chunk exactly once, and column 2 never touched.
223
+ expect(new Set(chunkCalls).size).toEqual(chunkCalls.length);
224
+ expect(chunkCalls.length).toEqual(6);
225
+ expect(chunkCalls.filter(key => key.endsWith('/2')).length).toEqual(0);
226
+ });
227
+ });
@@ -1,10 +1,10 @@
1
1
  // @ts-check
2
2
  import { log } from '@vitessce/globals';
3
- import { zarrOpenRoot } from '@vitessce/zarr-utils';
4
- import { open as zarrOpen, root as zarrRoot } from 'zarrita';
3
+ import { zarrOpenRoot, applyStoreExtensions } from '@vitessce/zarr-utils';
4
+ import { open as zarrOpen, root as zarrRoot, Array as ZarrArray } from 'zarrita';
5
5
  import { ZarrNodeNotFoundError } from '@vitessce/error';
6
6
 
7
- /** @import { Location as ZarrLocation, Readable } from 'zarrita' */
7
+ /** @import { Location as ZarrLocation, AsyncReadable } from 'zarrita' */
8
8
  /** @import { DataSourceParams } from '@vitessce/types' */
9
9
 
10
10
  /**
@@ -15,48 +15,95 @@ export default class ZarrDataSource {
15
15
  /**
16
16
  * @param {DataSourceParams & { refSpecUrl?: string }} params The parameters object.
17
17
  */
18
- constructor({ url, requestInit, refSpecUrl, store, fileType }) {
18
+ constructor({ url, requestInit, refSpecUrl, store, fileType, queryClient }) {
19
19
  log.info('Using a Zarr-based data source. 403 and 404 HTTP responses for Zarr metadata files (.zattrs, .zarray, .zgroup, zarr.json) are to be expected and do not necessarily indicate errors.');
20
+ this.queryClient = queryClient;
20
21
  if (store) {
21
22
  // TODO: check here that it is a valid Zarrita Readable?
22
- this.storeRoot = zarrRoot(store);
23
+ // @ts-ignore
24
+ const extendedStore = applyStoreExtensions(store, url, queryClient);
25
+ this.storeRoot = zarrRoot(extendedStore);
23
26
  } else if (url) {
24
- this.storeRoot = zarrOpenRoot(url, fileType, { requestInit, refSpecUrl });
27
+ // The queryClient backs the store-level chunk cache, so that concurrent
28
+ // reads of the same chunk share one request. See CachedStore in zarr-utils.
29
+ this.storeRoot = zarrOpenRoot(url, fileType, { requestInit, refSpecUrl, queryClient });
25
30
  } else {
26
31
  throw new Error('Either a store or a URL must be provided to the ZarrDataSource constructor.');
27
32
  }
33
+ // Zarr nodes opened relative to the store root, memoized per path so that a
34
+ // node's metadata documents (.zattrs/.zarray/.zgroup or zarr.json) are read
35
+ // once per data source, however many methods touch the node.
36
+ /** @type {Map<string, Promise<any>>} */
37
+ this.nodeCache = new Map();
38
+ }
39
+
40
+ /**
41
+ * Open the zarr node (array or group) at a path relative to the store root,
42
+ * memoized per path. A rejected open is dropped again, so a later call
43
+ * retries instead of re-awaiting a dead promise.
44
+ * @param {string} path The node path relative to the store root.
45
+ * @returns {Promise<any>} The zarrita Array or Group.
46
+ */
47
+ openNode(path) {
48
+ // Callers pass paths both with and without a leading slash; resolve()
49
+ // treats them the same, so the cache key must too.
50
+ const key = path.startsWith('/') ? path : `/${path}`;
51
+ if (!this.nodeCache.has(key)) {
52
+ // @ts-ignore
53
+ const promise = zarrOpen(this.storeRoot.resolve(path)).catch((err) => {
54
+ this.nodeCache.delete(key);
55
+ throw err;
56
+ });
57
+ this.nodeCache.set(key, promise);
58
+ }
59
+ return /** @type {Promise<any>} */ (this.nodeCache.get(key));
60
+ }
61
+
62
+ /**
63
+ * Open the zarr array at a path relative to the store root, through the same
64
+ * per-path cache as openNode.
65
+ * @param {string} path The array path relative to the store root.
66
+ * @returns {Promise<any>} The zarrita Array.
67
+ * @throws When the node exists but is a group.
68
+ */
69
+ async openArray(path) {
70
+ const node = await this.openNode(path);
71
+ if (!(node instanceof ZarrArray)) {
72
+ throw new Error(`Expected a zarr array at ${path}, but found a group.`);
73
+ }
74
+ return node;
28
75
  }
29
76
 
30
77
  /**
31
78
  *
32
79
  * @param {string} path
33
- * @returns {ZarrLocation<Readable>}
80
+ * @returns {ZarrLocation<AsyncReadable>}
34
81
  */
35
82
  getStoreRoot(path) {
83
+ // @ts-ignore
36
84
  return this.storeRoot.resolve(path);
37
85
  }
38
86
 
39
87
  /**
40
88
  * Method for accessing JSON attributes, relative to the store root.
41
89
  * @param {string} key A path to the item.
42
- * @param {ZarrLocation<Readable>|null} storeRootParam An optional location,
90
+ * @param {ZarrLocation<AsyncReadable>|null} storeRootParam An optional location,
43
91
  * which if provided will override the default store root.
44
92
  * @returns {Promise<any>} This async function returns a promise
45
93
  * that resolves to the parsed JSON if successful.
46
94
  * @throws This may throw an error.
47
95
  */
48
96
  async getJson(key, storeRootParam = null) {
49
- const { storeRoot } = this;
50
- const storeRootToUse = storeRootParam || storeRoot;
51
-
52
97
  let dirKey = key;
53
98
  // TODO: update calls to not include these file names in the first place.
54
99
  if (key.endsWith('.zattrs') || key.endsWith('.zarray') || key.endsWith('.zgroup')) {
55
100
  dirKey = key.substring(0, key.length - 8);
56
101
  }
57
102
  try {
58
- const location = storeRootToUse.resolve(dirKey);
59
- const arrOrGroup = await zarrOpen(location);
103
+ const arrOrGroup = await (storeRootParam
104
+ // A custom location cannot go through the per-path cache.
105
+ ? zarrOpen(storeRootParam.resolve(dirKey))
106
+ : this.openNode(dirKey));
60
107
  return arrOrGroup.attrs;
61
108
  } catch (/** @type {any} */ e) {
62
109
  if (e.name === 'NodeNotFoundError') {
@@ -1,4 +1,4 @@
1
- import { LoaderResult, AbstractTwoStepLoader } from '@vitessce/abstract';
1
+ import { LoaderResult, AbstractTwoStepLoader, allocateDenseMatrix } from '@vitessce/abstract';
2
2
  import { basename } from '../utils.js';
3
3
 
4
4
  /**
@@ -20,7 +20,11 @@ export default class ObsFeatureColumnsAnndataLoader extends AbstractTwoStepLoade
20
20
  const obsIndex = await this.dataSource.loadObsIndex(firstPath);
21
21
  const featureIndex = colPaths.map(colPath => basename(colPath));
22
22
  const shape = [obsIndex.length, featureIndex.length];
23
- const out = new Float32Array(shape[0] * shape[1]);
23
+ const out = allocateDenseMatrix({
24
+ source: `the "obsFeatureColumns" of "${this.url?.split('?')[0]}"`,
25
+ shape,
26
+ allocate: () => new Float32Array(shape[0] * shape[1]),
27
+ });
24
28
 
25
29
  const data = await Promise.all(
26
30
  colPaths.map(colPath => this.dataSource.loadNumeric(colPath)),