@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
@@ -53,3 +53,160 @@ export const concatenateColumnVectors = (arr) => {
53
53
  }
54
54
  return new TypedArray(view.buffer);
55
55
  };
56
+
57
+ /**
58
+ * Convert a 64-bit integer array to a Float64Array of plain numbers, exact
59
+ * below 2^53. Unlike maybeDowncastInt64 this keeps the high bits, so it is safe
60
+ * for values that can exceed 2^31, such as sparse `indptr` entries (bounded by
61
+ * nnz). Other arrays pass through unchanged.
62
+ * @param {ArrayLike<number|bigint>} data A typed array.
63
+ * @returns {ArrayLike<number>} A number-valued array.
64
+ */
65
+ export function bigInt64ToNumberArray(data) {
66
+ // eslint-disable-next-line no-undef
67
+ if (data instanceof BigInt64Array || data instanceof BigUint64Array) {
68
+ const out = new Float64Array(data.length);
69
+ for (let i = 0; i < data.length; i += 1) {
70
+ out[i] = Number(data[i]);
71
+ }
72
+ return out;
73
+ }
74
+ return data;
75
+ }
76
+
77
+ const BYTES_PER_ELEMENT = {
78
+ bool: 1,
79
+ int8: 1,
80
+ uint8: 1,
81
+ int16: 2,
82
+ uint16: 2,
83
+ int32: 4,
84
+ uint32: 4,
85
+ float32: 4,
86
+ int64: 8,
87
+ uint64: 8,
88
+ float64: 8,
89
+ };
90
+
91
+ /**
92
+ * Bytes per element for a zarrita data type name.
93
+ * @param {string} dtype A dtype such as 'int32' or 'float32'.
94
+ * @returns {number} Bytes per element; 8 (conservative) when unknown.
95
+ */
96
+ export function getBytesPerElement(dtype) {
97
+ return BYTES_PER_ELEMENT[dtype] ?? 8;
98
+ }
99
+
100
+ /**
101
+ * Create a function that runs async tasks with bounded concurrency.
102
+ * @param {number} concurrency Maximum number of tasks in flight.
103
+ * @returns {<T>(task: () => Promise<T>) => Promise<T>} A scheduler.
104
+ */
105
+ export function createLimiter(concurrency) {
106
+ let active = 0;
107
+ const queue = [];
108
+ const next = () => {
109
+ if (active >= concurrency || queue.length === 0) {
110
+ return;
111
+ }
112
+ active += 1;
113
+ const { task, resolve, reject } = queue.shift();
114
+ task().then(resolve, reject).finally(() => {
115
+ active -= 1;
116
+ next();
117
+ });
118
+ };
119
+ return task => new Promise((resolve, reject) => {
120
+ queue.push({ task, resolve, reject });
121
+ next();
122
+ });
123
+ }
124
+
125
+ /**
126
+ * Extract dense columns from a CSR matrix without densifying it.
127
+ *
128
+ * CSR has no per-column index, so the `indices` array is streamed once, chunk by
129
+ * chunk, and every stored value whose column was requested is placed by row.
130
+ * Rows are recovered with a pointer that moves forward over `indptr` as the
131
+ * position in `indices` increases, so the whole pass is O(nnz + numRows). The
132
+ * `data` chunk is fetched only for chunks that contained a hit. Peak memory is a
133
+ * few chunks plus the output columns, independent of nnz.
134
+ *
135
+ * I/O is injected so the traversal can be tested without a store.
136
+ *
137
+ * @param {object} params
138
+ * @param {ArrayLike<number>} params.indptr Row pointers, number-valued, length numRows + 1.
139
+ * @param {number} params.numRows Number of rows (observations).
140
+ * @param {number} params.numCols Number of columns (features).
141
+ * @param {number[]} params.colIndices Requested columns, unique and within [0, numCols).
142
+ * @param {number} params.nnz Number of stored values (length of indices/data).
143
+ * @param {number} params.chunkSize Chunk length of the indices and data arrays.
144
+ * @param {(chunkIndex: number) => Promise<ArrayLike<number|bigint>>} params.getIndicesChunk
145
+ * Reads one chunk of `indices`; may be padded past nnz, as zarr chunks are.
146
+ * @param {(chunkIndex: number) => Promise<ArrayLike<number|bigint>>} params.getDataChunk
147
+ * Reads the corresponding chunk of `data`.
148
+ * @param {number} [params.prefetch=4] How many chunk reads to keep in flight.
149
+ * @returns {Promise<Float32Array[]>} One column per entry of colIndices, length numRows.
150
+ */
151
+ export async function extractCsrColumns({
152
+ indptr, numRows, numCols, colIndices, nnz, chunkSize,
153
+ getIndicesChunk, getDataChunk, prefetch = 4,
154
+ }) {
155
+ const out = colIndices.map(() => new Float32Array(numRows));
156
+ if (colIndices.length === 0 || nnz === 0) {
157
+ return out;
158
+ }
159
+ // Column -> output slot, so membership is a typed-array read per stored value.
160
+ const slotByCol = new Int32Array(numCols).fill(-1);
161
+ colIndices.forEach((col, slot) => {
162
+ slotByCol[col] = slot;
163
+ });
164
+ const numChunks = Math.ceil(nnz / chunkSize);
165
+ const limit = createLimiter(Math.max(1, prefetch));
166
+ const pending = new Map();
167
+ const prefetchChunk = (c) => {
168
+ if (c < numChunks && !pending.has(c)) {
169
+ pending.set(c, limit(() => getIndicesChunk(c)));
170
+ }
171
+ };
172
+ for (let c = 0; c < Math.min(prefetch, numChunks); c += 1) {
173
+ prefetchChunk(c);
174
+ }
175
+ const fills = [];
176
+ let row = 0;
177
+ for (let c = 0; c < numChunks; c += 1) {
178
+ prefetchChunk(c + prefetch);
179
+ // eslint-disable-next-line no-await-in-loop
180
+ const idx = await pending.get(c);
181
+ pending.delete(c);
182
+ const base = c * chunkSize;
183
+ // The trailing chunk is padded with the fill value (typically 0, which is
184
+ // also a valid column index), so only positions below nnz are stored values.
185
+ const validLen = Math.min(chunkSize, nnz - base);
186
+ const hitPos = [];
187
+ const hitRow = [];
188
+ const hitSlot = [];
189
+ for (let j = 0; j < validLen; j += 1) {
190
+ const slot = slotByCol[Number(idx[j])];
191
+ if (slot >= 0) {
192
+ const k = base + j;
193
+ // k only increases, so the row pointer never moves backwards.
194
+ while (indptr[row + 1] <= k) {
195
+ row += 1;
196
+ }
197
+ hitPos.push(j);
198
+ hitRow.push(row);
199
+ hitSlot.push(slot);
200
+ }
201
+ }
202
+ if (hitPos.length > 0) {
203
+ fills.push(limit(() => getDataChunk(c)).then((values) => {
204
+ for (let h = 0; h < hitPos.length; h += 1) {
205
+ out[hitSlot[h]][hitRow[h]] = Number(values[hitPos[h]]);
206
+ }
207
+ }));
208
+ }
209
+ }
210
+ await Promise.all(fills);
211
+ return out;
212
+ }
@@ -1,7 +1,78 @@
1
- import { convertBigInt64ArrayToInt32Array, IncorrectDataTypeError } from './utils.js';
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import {
3
+ convertBigInt64ArrayToInt32Array,
4
+ IncorrectDataTypeError,
5
+ bigInt64ToNumberArray,
6
+ getBytesPerElement,
7
+ extractCsrColumns,
8
+ } from './utils.js';
2
9
 
3
10
  const toArray = typedArr => Array.from(typedArr).map(Number);
11
+ const toBigInt = value => BigInt(value); // eslint-disable-line no-undef
4
12
 
13
+ // Build CSR arrays from a dense row-major matrix, for testing the column scan.
14
+ function denseToCsr(matrix) {
15
+ const indptr = [0];
16
+ const indices = [];
17
+ const data = [];
18
+ matrix.forEach((rowValues) => {
19
+ rowValues.forEach((value, col) => {
20
+ if (value !== 0) {
21
+ indices.push(col);
22
+ data.push(value);
23
+ }
24
+ });
25
+ indptr.push(indices.length);
26
+ });
27
+ return { indptr, indices, data, nnz: indices.length };
28
+ }
29
+
30
+ // A 20 x 15 matrix with an all-zero row (7), all-zero columns (4 and 9), and a
31
+ // value pattern that identifies each (row, col) uniquely.
32
+ const NUM_ROWS = 20;
33
+ const NUM_COLS = 15;
34
+ const DENSE = Array.from({ length: NUM_ROWS }, (_, i) => Array.from(
35
+ { length: NUM_COLS },
36
+ (__, j) => ((i + j) % 3 === 0 && i !== 7 && j !== 4 && j !== 9 ? i * NUM_COLS + j + 1 : 0),
37
+ ));
38
+ const CSR = denseToCsr(DENSE);
39
+
40
+ function makeChunkReaders(csr, chunkSize, { Indices = Int32Array, Data = Float32Array } = {}) {
41
+ // Chunks are padded to chunkSize with zeros, as zarr chunks are.
42
+ const padded = (arr, c) => {
43
+ const slice = arr.slice(c * chunkSize, (c + 1) * chunkSize);
44
+ const chunk = new Array(chunkSize).fill(0);
45
+ slice.forEach((v, i) => { chunk[i] = v; });
46
+ return chunk;
47
+ };
48
+ const asTyped = (Ctor, values) => (
49
+ Ctor === BigInt64Array // eslint-disable-line no-undef
50
+ ? Ctor.from(values.map(toBigInt))
51
+ : Ctor.from(values)
52
+ );
53
+ return {
54
+ getIndicesChunk: vi.fn(async c => asTyped(Indices, padded(csr.indices, c))),
55
+ getDataChunk: vi.fn(async c => asTyped(Data, padded(csr.data, c))),
56
+ };
57
+ }
58
+
59
+ async function extract(colIndices, chunkSize, options = {}) {
60
+ const { getIndicesChunk, getDataChunk } = makeChunkReaders(CSR, chunkSize, options);
61
+ const columns = await extractCsrColumns({
62
+ indptr: CSR.indptr,
63
+ numRows: NUM_ROWS,
64
+ numCols: NUM_COLS,
65
+ colIndices,
66
+ nnz: CSR.nnz,
67
+ chunkSize,
68
+ getIndicesChunk,
69
+ getDataChunk,
70
+ ...(options.prefetch ? { prefetch: options.prefetch } : {}),
71
+ });
72
+ return { columns, getIndicesChunk, getDataChunk };
73
+ }
74
+
75
+ const expectedColumn = j => DENSE.map(rowValues => rowValues[j]);
5
76
 
6
77
  describe('loaders/utils', () => {
7
78
  describe('convertBigInt64ArrayToInt32Array', () => {
@@ -18,4 +89,90 @@ describe('loaders/utils', () => {
18
89
  .toThrow(IncorrectDataTypeError);
19
90
  });
20
91
  });
92
+
93
+ describe('bigInt64ToNumberArray', () => {
94
+ it('keeps values above 2^31, unlike the int32 downcast', () => {
95
+ const big = (2n ** 33n) + 5n;
96
+ // eslint-disable-next-line no-undef
97
+ const converted = bigInt64ToNumberArray(new BigInt64Array([big, 5n, 0n]));
98
+ expect(converted).toBeInstanceOf(Float64Array);
99
+ expect(Array.from(converted)).toEqual([(2 ** 33) + 5, 5, 0]);
100
+ });
101
+
102
+ it('passes non-BigInt arrays through by identity', () => {
103
+ const arr = new Int32Array([1, 2]);
104
+ expect(bigInt64ToNumberArray(arr)).toBe(arr);
105
+ });
106
+ });
107
+
108
+ describe('getBytesPerElement', () => {
109
+ it('maps zarrita dtypes to byte widths, defaulting conservatively', () => {
110
+ expect(getBytesPerElement('float32')).toEqual(4);
111
+ expect(getBytesPerElement('int64')).toEqual(8);
112
+ expect(getBytesPerElement('uint8')).toEqual(1);
113
+ expect(getBytesPerElement('bool')).toEqual(1);
114
+ expect(getBytesPerElement('v2:object')).toEqual(8);
115
+ });
116
+ });
117
+
118
+ describe('extractCsrColumns', () => {
119
+ it('matches the dense columns across chunk sizes', async () => {
120
+ const cols = [1, 14, 4, 0, 7];
121
+ const chunkSizes = [1, 3, 8, CSR.nnz, CSR.nnz + 10];
122
+ // eslint-disable-next-line no-restricted-syntax
123
+ for (const chunkSize of chunkSizes) {
124
+ // eslint-disable-next-line no-await-in-loop
125
+ const { columns, getIndicesChunk } = await extract(cols, chunkSize);
126
+ expect(columns.map(toArray)).toEqual(cols.map(expectedColumn));
127
+ expect(getIndicesChunk).toHaveBeenCalledTimes(Math.ceil(CSR.nnz / chunkSize));
128
+ }
129
+ });
130
+
131
+ it('ignores fill-value padding in the trailing chunk', async () => {
132
+ // Column 0 equals the fill value, so padding read as stored values would
133
+ // wrongly place hits for it. Pick a chunk size that leaves a partial chunk.
134
+ const chunkSize = 7;
135
+ expect(CSR.nnz % chunkSize).not.toEqual(0);
136
+ const { columns } = await extract([0], chunkSize);
137
+ expect(toArray(columns[0])).toEqual(expectedColumn(0));
138
+ });
139
+
140
+ it('fetches data only for chunks that contain a requested column', async () => {
141
+ // Column 14 has a hit in roughly one of every three rows, so several
142
+ // small chunks carry no hit for it.
143
+ const chunkSize = 2;
144
+ const { columns, getIndicesChunk, getDataChunk } = await extract([14], chunkSize);
145
+ expect(toArray(columns[0])).toEqual(expectedColumn(14));
146
+ const chunksWithHits = new Set();
147
+ CSR.indices.forEach((col, k) => {
148
+ if (col === 14) {
149
+ chunksWithHits.add(Math.floor(k / chunkSize));
150
+ }
151
+ });
152
+ expect(getDataChunk).toHaveBeenCalledTimes(chunksWithHits.size);
153
+ expect(getDataChunk.mock.calls.length).toBeLessThan(getIndicesChunk.mock.calls.length);
154
+ });
155
+
156
+ it('returns zero columns without reads when nothing is requested', async () => {
157
+ const { columns, getIndicesChunk } = await extract([], 4);
158
+ expect(columns).toEqual([]);
159
+ expect(getIndicesChunk).not.toHaveBeenCalled();
160
+ });
161
+
162
+ it('is independent of the prefetch depth', async () => {
163
+ const cols = [2, 13];
164
+ const serial = await extract(cols, 5, { prefetch: 1 });
165
+ const parallel = await extract(cols, 5, { prefetch: 6 });
166
+ expect(serial.columns.map(toArray)).toEqual(parallel.columns.map(toArray));
167
+ expect(serial.columns.map(toArray)).toEqual(cols.map(expectedColumn));
168
+ });
169
+
170
+ it('accepts 64-bit integer indices and data', async () => {
171
+ const { columns } = await extract([1, 7], 6, {
172
+ Indices: BigInt64Array, // eslint-disable-line no-undef
173
+ Data: BigInt64Array, // eslint-disable-line no-undef
174
+ });
175
+ expect(columns.map(toArray)).toEqual([1, 7].map(expectedColumn));
176
+ });
177
+ });
21
178
  });
@@ -1,6 +1,7 @@
1
1
  import { open as zarrOpen } from 'zarrita';
2
2
  import { createZarrArrayAdapter } from '@vitessce/zarr-utils';
3
- import { AbstractTwoStepLoader, LoaderResult } from '@vitessce/abstract';
3
+ import { AbstractTwoStepLoader, LoaderResult, allocateDenseMatrix } from '@vitessce/abstract';
4
+ import { getBytesPerElement } from '../anndata-loaders/utils.js';
4
5
 
5
6
  export default class MatrixZarrAsObsFeatureMatrixLoader extends AbstractTwoStepLoader {
6
7
  async loadAttrs() {
@@ -20,7 +21,13 @@ export default class MatrixZarrAsObsFeatureMatrixLoader extends AbstractTwoStepL
20
21
  return this.arr;
21
22
  }
22
23
  const z = await zarrOpen(storeRoot, { kind: 'array' });
23
- this.arr = await createZarrArrayAdapter(z).getRaw([null, null]);
24
+ this.arr = await allocateDenseMatrix({
25
+ source: `"${this.url?.split('?')[0]}"`,
26
+ shape: z.shape,
27
+ bytesPerElement: getBytesPerElement(z.dtype),
28
+ // zarrita allocates the whole selection up front.
29
+ allocate: () => createZarrArrayAdapter(z).getRaw([null, null]),
30
+ });
24
31
  return this.arr;
25
32
  }
26
33