@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.
- package/dist/index.js +14588 -18551
- package/dist-tsc/AnnDataSource.d.ts +37 -1
- package/dist-tsc/AnnDataSource.d.ts.map +1 -1
- package/dist-tsc/AnnDataSource.js +108 -22
- package/dist-tsc/AnnDataSource.js.map +1 -1
- package/dist-tsc/AnnDataSource.test.js +169 -1
- package/dist-tsc/AnnDataSource.test.js.map +1 -1
- package/dist-tsc/ZarrDataSource.d.ts +27 -8
- package/dist-tsc/ZarrDataSource.d.ts.map +1 -1
- package/dist-tsc/ZarrDataSource.js +58 -12
- package/dist-tsc/ZarrDataSource.js.map +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.d.ts +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.d.ts.map +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.js +6 -2
- package/dist-tsc/anndata-loaders/ObsFeatureColumnsAnndataLoader.js.map +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.d.ts +81 -22
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.d.ts.map +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.js +410 -180
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.js.map +1 -1
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js +289 -1
- package/dist-tsc/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js.map +1 -1
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.d.ts +16 -1
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.d.ts.map +1 -1
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.js +76 -10
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.js.map +1 -1
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.d.ts +2 -0
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.d.ts.map +1 -0
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.js +81 -0
- package/dist-tsc/anndata-loaders/ObsSetsAnndataLoader.test.js.map +1 -0
- package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.d.ts +5 -1
- package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.d.ts.map +1 -1
- package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.js +2 -2
- package/dist-tsc/anndata-loaders/SampleSetsAnndataLoader.js.map +1 -1
- package/dist-tsc/anndata-loaders/utils.d.ts +58 -0
- package/dist-tsc/anndata-loaders/utils.d.ts.map +1 -1
- package/dist-tsc/anndata-loaders/utils.js +149 -0
- package/dist-tsc/anndata-loaders/utils.js.map +1 -1
- package/dist-tsc/anndata-loaders/utils.test.js +134 -1
- package/dist-tsc/anndata-loaders/utils.test.js.map +1 -1
- package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.d.ts.map +1 -1
- package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js +9 -2
- package/dist-tsc/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js.map +1 -1
- package/package.json +12 -12
- package/src/AnnDataSource.js +114 -37
- package/src/AnnDataSource.test.js +179 -1
- package/src/ZarrDataSource.js +60 -13
- package/src/anndata-loaders/ObsFeatureColumnsAnndataLoader.js +6 -2
- package/src/anndata-loaders/ObsFeatureMatrixAnndataLoader.js +450 -190
- package/src/anndata-loaders/ObsFeatureMatrixAnndataLoader.test.js +319 -1
- package/src/anndata-loaders/ObsSetsAnndataLoader.js +85 -10
- package/src/anndata-loaders/ObsSetsAnndataLoader.test.js +91 -0
- package/src/anndata-loaders/SampleSetsAnndataLoader.js +2 -2
- package/src/anndata-loaders/utils.js +157 -0
- package/src/anndata-loaders/utils.test.js +158 -1
- package/src/matrix-loaders/MatrixZarrAsObsFeatureMatrix.js +9 -2
|
@@ -1,14 +1,86 @@
|
|
|
1
1
|
/* eslint-disable no-underscore-dangle */
|
|
2
2
|
import { open as zarrOpen, get as zarrGet, slice } from 'zarrita';
|
|
3
|
-
import { createZarrArrayAdapter } from '@vitessce/zarr-utils';
|
|
3
|
+
import { createZarrArrayAdapter, UNCACHED_READ } from '@vitessce/zarr-utils';
|
|
4
4
|
import { LoaderResult, AbstractTwoStepLoader } from '@vitessce/abstract';
|
|
5
|
-
import {
|
|
5
|
+
import { MatrixTooLargeError } from '@vitessce/error';
|
|
6
|
+
import { log } from '@vitessce/globals';
|
|
7
|
+
import {
|
|
8
|
+
commaNumber,
|
|
9
|
+
formatBytes,
|
|
10
|
+
exceedsAllocationBudget,
|
|
11
|
+
getAllocationBudgetBytes,
|
|
12
|
+
} from '@vitessce/utils';
|
|
13
|
+
import {
|
|
14
|
+
maybeDowncastInt64,
|
|
15
|
+
concatenateColumnVectors,
|
|
16
|
+
bigInt64ToNumberArray,
|
|
17
|
+
getBytesPerElement,
|
|
18
|
+
extractCsrColumns,
|
|
19
|
+
createLimiter,
|
|
20
|
+
} from './utils.js';
|
|
21
|
+
|
|
22
|
+
const SPARSE_DOCS_URL = 'https://vitessce.io/docs/data-troubleshooting/#anndata-zarr-obsfeaturematrix-with-sparse-matrices';
|
|
23
|
+
const TOO_LARGE_DOCS_URL = 'https://vitessce.io/docs/data-troubleshooting/#my-obsfeaturematrix-is-too-large-to-render-everything';
|
|
24
|
+
|
|
25
|
+
// Above this estimated download, a CSR feature selection logs a warning (once per
|
|
26
|
+
// loader), so that a permitted-but-slow scan is not silent.
|
|
27
|
+
const CSR_SCAN_WARN_BYTES = 256 * (2 ** 20);
|
|
28
|
+
// Chunk reads kept in flight while scanning a CSR matrix.
|
|
29
|
+
const CSR_SCAN_PREFETCH = 4;
|
|
30
|
+
// Concurrent slice reads when selecting many features from a CSC matrix.
|
|
31
|
+
const CSC_READ_CONCURRENCY = 8;
|
|
32
|
+
// A scan visits each chunk once, so its reads bypass the store-level cache rather
|
|
33
|
+
// than pinning the whole array in it.
|
|
34
|
+
const SCAN_READ_OPTS = { [UNCACHED_READ]: true };
|
|
6
35
|
|
|
7
36
|
// Put array of data into an object,
|
|
8
37
|
// to match the expected format of the
|
|
9
38
|
// value returned from the load function.
|
|
10
39
|
const toObject = data => ({ data });
|
|
11
40
|
|
|
41
|
+
const describeShape = shape => `[${shape.join(', ')}]`;
|
|
42
|
+
const describeBytes = bytes => (
|
|
43
|
+
Number.isFinite(bytes) ? formatBytes(bytes) : 'more memory than can be addressed'
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
function fullMatrixMessage({ path, shape, description, bytes }) {
|
|
47
|
+
return `Loading the full observation-by-feature matrix at "${path}" (shape ${describeShape(shape)}, ${description}) needs about ${describeBytes(bytes)} of memory, more than this browser's ~${formatBytes(getAllocationBudgetBytes())} budget. Load a subset of features with the "initialFeatureFilterPath" option (or a smaller subset, if one is already set), or point "path" at a smaller matrix, for example in obsm, together with "featureFilterPath". See ${TOO_LARGE_DOCS_URL}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function csrScanMessage({ path, shape, nnz, bytes }) {
|
|
51
|
+
return `Selecting features from the csr_matrix at "${path}" (shape ${describeShape(shape)}, ${commaNumber(nnz)} stored values) requires scanning about ${describeBytes(bytes)} of "indices" and "data" per selection, more than this browser's ~${formatBytes(getAllocationBudgetBytes())} budget. Store the matrix as csc_matrix (adata.X = scipy.sparse.csc_matrix(adata.X)) so that individual features can be read without scanning the whole matrix. See ${SPARSE_DOCS_URL}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Whether an error is the RangeError thrown for a typed array that is too large
|
|
56
|
+
* or whose buffer could not be allocated. Checked by name as well as by class,
|
|
57
|
+
* since the error may originate in another realm.
|
|
58
|
+
* @param {*} e A caught error.
|
|
59
|
+
* @returns {boolean} True for an allocation failure.
|
|
60
|
+
*/
|
|
61
|
+
function isAllocationFailure(e) {
|
|
62
|
+
return e instanceof RangeError || e?.name === 'RangeError';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Run an allocation, converting an allocation failure into a
|
|
67
|
+
* MatrixTooLargeError that explains which matrix was being loaded and what to
|
|
68
|
+
* do about it.
|
|
69
|
+
* @param {Function} allocate A function performing the allocation.
|
|
70
|
+
* @param {string} message The descriptive message to use on failure.
|
|
71
|
+
* @returns {*} The allocation result.
|
|
72
|
+
*/
|
|
73
|
+
function allocateOrThrow(allocate, message) {
|
|
74
|
+
try {
|
|
75
|
+
return allocate();
|
|
76
|
+
} catch (e) {
|
|
77
|
+
if (isAllocationFailure(e)) {
|
|
78
|
+
throw new MatrixTooLargeError(`${message} (${e.message})`);
|
|
79
|
+
}
|
|
80
|
+
throw e;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
12
84
|
/**
|
|
13
85
|
* Loader for converting zarr into the a cell x gene matrix for use in Genes/Heatmap components.
|
|
14
86
|
*/
|
|
@@ -17,29 +89,55 @@ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader
|
|
|
17
89
|
return this.options;
|
|
18
90
|
}
|
|
19
91
|
|
|
92
|
+
/**
|
|
93
|
+
* Memoize the promise returned by `factory` on this loader under `key`. A
|
|
94
|
+
* rejected promise is dropped again, so that a later call (for example a
|
|
95
|
+
* react-query retry) re-runs the work instead of re-awaiting a dead promise.
|
|
96
|
+
* @param {string} key The property name to store the promise under.
|
|
97
|
+
* @param {() => Promise<any>} factory Creates the promise on first use.
|
|
98
|
+
* @returns {Promise<any>} The memoized promise.
|
|
99
|
+
*/
|
|
100
|
+
_memoized(key, factory) {
|
|
101
|
+
if (!this[key]) {
|
|
102
|
+
this[key] = Promise.resolve().then(factory).catch((err) => {
|
|
103
|
+
delete this[key];
|
|
104
|
+
throw err;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return this[key];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Log a warning at most once per loader for a given topic.
|
|
112
|
+
* @param {string} topic A key identifying the warning.
|
|
113
|
+
* @param {string} message The warning message.
|
|
114
|
+
*/
|
|
115
|
+
_warnOnce(topic, message) {
|
|
116
|
+
if (!this._warned) {
|
|
117
|
+
this._warned = new Set();
|
|
118
|
+
}
|
|
119
|
+
if (!this._warned.has(topic)) {
|
|
120
|
+
this._warned.add(topic);
|
|
121
|
+
log.warn(message);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
20
125
|
/**
|
|
21
126
|
* Class method for loading the genes list from AnnData.var,
|
|
22
127
|
* filtered if a there is a `geneFilterZarr` present in the view config.
|
|
23
128
|
* @returns {Promise} A promise for the zarr array contianing the gene names.
|
|
24
129
|
*/
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
? this.dataSource.loadVarAlias(geneAlias, path)
|
|
37
|
-
: this.dataSource.loadVarIndex(path);
|
|
38
|
-
this.filteredGeneNames = Promise.all([
|
|
39
|
-
geneNamesPromise,
|
|
40
|
-
getFilterFn(),
|
|
41
|
-
]).then(([data, filter]) => filter(data));
|
|
42
|
-
return this.filteredGeneNames;
|
|
130
|
+
loadFilteredGeneNames() {
|
|
131
|
+
return this._memoized('filteredGeneNames', async () => {
|
|
132
|
+
const { path, featureFilterPath: geneFilterZarr, geneAlias } = this.getOptions();
|
|
133
|
+
const [geneNames, geneFilter] = await Promise.all([
|
|
134
|
+
geneAlias
|
|
135
|
+
? this.dataSource.loadVarAlias(geneAlias, path)
|
|
136
|
+
: this.dataSource.loadVarIndex(path),
|
|
137
|
+
geneFilterZarr ? this.dataSource.getFlatArrDecompressed(geneFilterZarr) : null,
|
|
138
|
+
]);
|
|
139
|
+
return geneFilter ? geneNames.filter((_, j) => geneFilter[j]) : geneNames;
|
|
140
|
+
});
|
|
43
141
|
}
|
|
44
142
|
|
|
45
143
|
/**
|
|
@@ -57,7 +155,7 @@ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader
|
|
|
57
155
|
/**
|
|
58
156
|
* Class method for getting the integer indices of a selection of genes within a list.
|
|
59
157
|
* @param {Array} selection A list of gene names.
|
|
60
|
-
* @returns {Array} A list of integer indices.
|
|
158
|
+
* @returns {Array} A list of integer indices (-1 for genes that are not present).
|
|
61
159
|
*/
|
|
62
160
|
async _getGeneIndices(selection) {
|
|
63
161
|
const geneNames = await this.loadFilteredGeneNames();
|
|
@@ -75,60 +173,106 @@ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader
|
|
|
75
173
|
}
|
|
76
174
|
|
|
77
175
|
/**
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* @returns {
|
|
176
|
+
* Load the attributes of the matrix group or array (encoding type, and the
|
|
177
|
+
* shape for sparse encodings).
|
|
178
|
+
* @returns {Promise<object>} The attributes.
|
|
81
179
|
*/
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
180
|
+
_loadMatrixZattrs() {
|
|
181
|
+
return this._memoized('matrixZattrs', () => {
|
|
182
|
+
const { path: matrix } = this.getOptions();
|
|
183
|
+
return this.dataSource.getJson(`${matrix}/.zattrs`);
|
|
184
|
+
});
|
|
85
185
|
}
|
|
86
186
|
|
|
87
187
|
/**
|
|
88
188
|
* Class method for opening the sparse matrix arrays in zarr.
|
|
89
|
-
* @returns {Array}
|
|
189
|
+
* @returns {Promise<Array>} The opened indptr, indices, and data arrays.
|
|
90
190
|
*/
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
191
|
+
_openSparseArrays() {
|
|
192
|
+
return this._memoized('sparseArrays', () => {
|
|
193
|
+
const { path: matrix } = this.getOptions();
|
|
194
|
+
const { storeRoot } = this.dataSource;
|
|
195
|
+
return Promise.all(
|
|
196
|
+
['indptr', 'indices', 'data'].map(name => zarrOpen(
|
|
197
|
+
storeRoot.resolve(`${matrix}/${name}`), { kind: 'array' },
|
|
198
|
+
)),
|
|
199
|
+
);
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Open the dense matrix array in zarr.
|
|
205
|
+
* @returns {Promise<object>} The opened zarr array.
|
|
206
|
+
*/
|
|
207
|
+
_openDenseArray() {
|
|
208
|
+
return this._memoized('denseArray', () => {
|
|
209
|
+
const { path: matrix } = this.getOptions();
|
|
210
|
+
const { storeRoot } = this.dataSource;
|
|
211
|
+
return zarrOpen(storeRoot.resolve(matrix), { kind: 'array' });
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Load the sparse `indptr` array once, as plain numbers. Its values are
|
|
217
|
+
* bounded by nnz and can exceed 2^31, so int64 is converted without truncation.
|
|
218
|
+
* @returns {Promise<ArrayLike<number>>} The row (CSR) or column (CSC) pointers.
|
|
219
|
+
*/
|
|
220
|
+
_loadIndptr() {
|
|
221
|
+
return this._memoized('indptr', async () => {
|
|
222
|
+
const [indptrArr] = await this._openSparseArrays();
|
|
223
|
+
const { data } = await zarrGet(indptrArr);
|
|
224
|
+
return bigInt64ToNumberArray(data);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The column to report for a feature that is not in the matrix: zeros, with
|
|
230
|
+
* a warning. This matches what the CSC route always did, and keeps a feature
|
|
231
|
+
* selection shared across datasets from failing in the ones that lack a gene.
|
|
232
|
+
* @param {string} name The feature name.
|
|
233
|
+
* @param {number} numRows The number of observations.
|
|
234
|
+
* @returns {Float32Array} An all-zero column.
|
|
235
|
+
*/
|
|
236
|
+
_missingFeatureColumn(name, numRows) {
|
|
237
|
+
const { path } = this.getOptions();
|
|
238
|
+
log.warn(`Feature "${name}" was not found in the observation-by-feature matrix at "${path}"; its values are reported as zeros.`);
|
|
239
|
+
return new Float32Array(numRows);
|
|
101
240
|
}
|
|
102
241
|
|
|
103
242
|
/**
|
|
104
243
|
* Class method for loading a gene selection from a CSC matrix.
|
|
105
244
|
* @param {Array} selection A list of gene names whose data should be fetched.
|
|
106
|
-
* @returns {Promise} A Promise.all array of promises containing
|
|
245
|
+
* @returns {Promise} A Promise.all array of promises containing Float32Arrays, one per selection.
|
|
107
246
|
*/
|
|
108
247
|
async _loadCSCGeneSelection(selection) {
|
|
109
248
|
const indices = await this._getGeneIndices(selection);
|
|
110
|
-
const [
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
249
|
+
const [, indexArr, dataArr] = await this._openSparseArrays();
|
|
250
|
+
const [indptr, { shape }] = await Promise.all([
|
|
251
|
+
this._loadIndptr(),
|
|
252
|
+
this._loadMatrixZattrs(),
|
|
253
|
+
]);
|
|
254
|
+
const numRows = shape[0];
|
|
255
|
+
const limit = createLimiter(CSC_READ_CONCURRENCY);
|
|
114
256
|
return Promise.all(
|
|
115
|
-
indices.map(async (index) => {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
|
|
257
|
+
indices.map(async (index, i) => {
|
|
258
|
+
if (index < 0) {
|
|
259
|
+
return this._missingFeatureColumn(selection[i], numRows);
|
|
260
|
+
}
|
|
261
|
+
const start = indptr[index];
|
|
262
|
+
const end = indptr[index + 1];
|
|
263
|
+
const geneData = new Float32Array(numRows);
|
|
264
|
+
// If there is no change in the column pointer, then the column is all zeros.
|
|
265
|
+
if (start === end) {
|
|
121
266
|
return geneData;
|
|
122
267
|
}
|
|
123
|
-
const { data: rowIndices } = await
|
|
124
|
-
slice(
|
|
268
|
+
const [{ data: rowIndices }, { data: values }] = await Promise.all([
|
|
269
|
+
limit(() => zarrGet(indexArr, [slice(start, end)])),
|
|
270
|
+
limit(() => zarrGet(dataArr, [slice(start, end)])),
|
|
125
271
|
]);
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
for (let rowIndex = 0; rowIndex < rowIndices.length; rowIndex += 1) {
|
|
131
|
-
geneData[rowIndices[rowIndex]] = cellXGeneData[rowIndex];
|
|
272
|
+
const rows = bigInt64ToNumberArray(rowIndices);
|
|
273
|
+
const vals = bigInt64ToNumberArray(values);
|
|
274
|
+
for (let r = 0; r < rows.length; r += 1) {
|
|
275
|
+
geneData[rows[r]] = vals[r];
|
|
132
276
|
}
|
|
133
277
|
return geneData;
|
|
134
278
|
}),
|
|
@@ -137,152 +281,269 @@ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader
|
|
|
137
281
|
|
|
138
282
|
/**
|
|
139
283
|
* Class method for loading a gene selection from a CSR matrix.
|
|
284
|
+
*
|
|
285
|
+
* CSR has no per-column slice, so the requested columns are gathered by one
|
|
286
|
+
* chunk-wise scan of `indices`/`data` (see extractCsrColumns); the matrix is
|
|
287
|
+
* never densified. Concurrent selections on this loader share a single scan.
|
|
140
288
|
* @param {Array} selection A list of gene names whose data should be fetched.
|
|
141
|
-
* @returns {Promise} A Promise.all array of promises containing
|
|
289
|
+
* @returns {Promise} A Promise.all array of promises containing Float32Arrays, one per selection.
|
|
142
290
|
*/
|
|
143
291
|
async _loadCSRGeneSelection(selection) {
|
|
144
292
|
const indices = await this._getGeneIndices(selection);
|
|
145
|
-
const
|
|
146
|
-
const
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
293
|
+
const [, indexArr, dataArr] = await this._openSparseArrays();
|
|
294
|
+
const { shape } = await this._loadMatrixZattrs();
|
|
295
|
+
const { path } = this.getOptions();
|
|
296
|
+
const nnz = indexArr.shape[0];
|
|
297
|
+
const bytesPerEntry = getBytesPerElement(indexArr.dtype) + getBytesPerElement(dataArr.dtype);
|
|
298
|
+
// Every selection reads all of `indices` and most of `data`; refuse when that
|
|
299
|
+
// is beyond what a browser can reasonably move, before reading any chunk.
|
|
300
|
+
const scanBytes = nnz * bytesPerEntry;
|
|
301
|
+
if (exceedsAllocationBudget(scanBytes)) {
|
|
302
|
+
throw new MatrixTooLargeError(csrScanMessage({
|
|
303
|
+
path, shape, nnz, bytes: scanBytes,
|
|
304
|
+
}));
|
|
305
|
+
}
|
|
306
|
+
const numRows = shape[0];
|
|
307
|
+
const numRequested = new Set(indices.filter(index => index >= 0)).size;
|
|
308
|
+
// Memory held during the scan: chunks in flight, the pointers, and the outputs.
|
|
309
|
+
const workingSetBytes = CSR_SCAN_PREFETCH * indexArr.chunks[0] * bytesPerEntry
|
|
310
|
+
+ (numRows + 1) * 8
|
|
311
|
+
+ numRows * 4 * numRequested;
|
|
312
|
+
if (exceedsAllocationBudget(workingSetBytes)) {
|
|
313
|
+
throw new MatrixTooLargeError(csrScanMessage({
|
|
314
|
+
path, shape, nnz, bytes: workingSetBytes,
|
|
315
|
+
}));
|
|
316
|
+
}
|
|
317
|
+
if (scanBytes > CSR_SCAN_WARN_BYTES) {
|
|
318
|
+
this._warnOnce('csrScan', `Selecting features from the csr_matrix at "${path}" scans about ${formatBytes(scanBytes)} of "indices" and "data" per selection. Store the matrix as csc_matrix so that individual features can be read directly. See ${SPARSE_DOCS_URL}`);
|
|
319
|
+
}
|
|
320
|
+
return Promise.all(
|
|
321
|
+
indices.map((index, i) => (
|
|
322
|
+
index < 0
|
|
323
|
+
? this._missingFeatureColumn(selection[i], numRows)
|
|
324
|
+
: this._requestCsrColumn(index)
|
|
325
|
+
)),
|
|
326
|
+
);
|
|
155
327
|
}
|
|
156
328
|
|
|
157
329
|
/**
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
330
|
+
* Request one CSR column. Requests are collected and served by a single scan
|
|
331
|
+
* per batch, so that the one-query-per-feature pattern of the data hooks does
|
|
332
|
+
* not scan the matrix once per feature.
|
|
333
|
+
* @param {number} col The column index.
|
|
334
|
+
* @returns {Promise<Float32Array>} The column.
|
|
161
335
|
*/
|
|
162
|
-
|
|
163
|
-
if (this.
|
|
164
|
-
|
|
336
|
+
_requestCsrColumn(col) {
|
|
337
|
+
if (!this._csrInflight) {
|
|
338
|
+
this._csrInflight = new Map();
|
|
339
|
+
this._csrPending = new Set();
|
|
165
340
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const { data } = await createZarrArrayAdapter(arr).getRaw(null);
|
|
173
|
-
return data;
|
|
174
|
-
}),
|
|
175
|
-
);
|
|
176
|
-
cellXGene = maybeDowncastInt64(cellXGene);
|
|
177
|
-
const cellXGeneMatrix = new Float32Array(shape[0] * shape[1]).fill(0);
|
|
178
|
-
let row = 0;
|
|
179
|
-
rows.forEach((_, index) => {
|
|
180
|
-
const rowStart = rows[index];
|
|
181
|
-
const rowEnd = rows[index + 1];
|
|
182
|
-
for (let i = rowStart; i < rowEnd; i += 1) {
|
|
183
|
-
const val = cellXGene[i];
|
|
184
|
-
const col = cols[i];
|
|
185
|
-
cellXGeneMatrix[row * shape[1] + col] = val;
|
|
186
|
-
}
|
|
187
|
-
row += 1;
|
|
341
|
+
let entry = this._csrInflight.get(col);
|
|
342
|
+
if (!entry) {
|
|
343
|
+
entry = {};
|
|
344
|
+
entry.promise = new Promise((resolve, reject) => {
|
|
345
|
+
entry.resolve = resolve;
|
|
346
|
+
entry.reject = reject;
|
|
188
347
|
});
|
|
189
|
-
|
|
348
|
+
this._csrInflight.set(col, entry);
|
|
349
|
+
this._csrPending.add(col);
|
|
350
|
+
this._scheduleCsrFlush();
|
|
351
|
+
}
|
|
352
|
+
return entry.promise;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
_scheduleCsrFlush() {
|
|
356
|
+
if (this._csrFlushScheduled || this._csrScanning) {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
this._csrFlushScheduled = true;
|
|
360
|
+
// A macrotask, so that every caller in the same burst has enqueued its columns
|
|
361
|
+
// regardless of how many awaits it went through to get here.
|
|
362
|
+
setTimeout(() => {
|
|
363
|
+
this._csrFlushScheduled = false;
|
|
364
|
+
this._flushCsrScan();
|
|
365
|
+
}, 0);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async _flushCsrScan() {
|
|
369
|
+
if (this._csrScanning || this._csrPending.size === 0) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const cols = Array.from(this._csrPending);
|
|
373
|
+
this._csrPending.clear();
|
|
374
|
+
this._csrScanning = true;
|
|
375
|
+
try {
|
|
376
|
+
const columns = await this._scanCsrColumns(cols);
|
|
377
|
+
cols.forEach((col, i) => this._csrInflight.get(col).resolve(columns[i]));
|
|
378
|
+
} catch (err) {
|
|
379
|
+
cols.forEach(col => this._csrInflight.get(col).reject(err));
|
|
380
|
+
} finally {
|
|
381
|
+
cols.forEach(col => this._csrInflight.delete(col));
|
|
382
|
+
this._csrScanning = false;
|
|
383
|
+
if (this._csrPending.size > 0) {
|
|
384
|
+
// Columns requested while this scan ran form the next one.
|
|
385
|
+
this._scheduleCsrFlush();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Scan the CSR `indices`/`data` arrays once for the given columns.
|
|
392
|
+
* @param {number[]} cols Unique column indices.
|
|
393
|
+
* @returns {Promise<Float32Array[]>} One column per entry of cols.
|
|
394
|
+
*/
|
|
395
|
+
async _scanCsrColumns(cols) {
|
|
396
|
+
const [, indexArr, dataArr] = await this._openSparseArrays();
|
|
397
|
+
const [indptr, { shape }] = await Promise.all([
|
|
398
|
+
this._loadIndptr(),
|
|
399
|
+
this._loadMatrixZattrs(),
|
|
400
|
+
]);
|
|
401
|
+
const nnz = indexArr.shape[0];
|
|
402
|
+
const chunkSize = indexArr.chunks[0];
|
|
403
|
+
const getIndicesChunk = c => indexArr.getChunk([c], SCAN_READ_OPTS).then(chunk => chunk.data);
|
|
404
|
+
// AnnData writes `data` with the same chunks as `indices`; if a store does not,
|
|
405
|
+
// read the matching element range instead of a chunk.
|
|
406
|
+
const getDataChunk = dataArr.chunks[0] === chunkSize
|
|
407
|
+
? c => dataArr.getChunk([c], SCAN_READ_OPTS).then(chunk => chunk.data)
|
|
408
|
+
: c => zarrGet(
|
|
409
|
+
dataArr,
|
|
410
|
+
[slice(c * chunkSize, Math.min(nnz, (c + 1) * chunkSize))],
|
|
411
|
+
{ opts: SCAN_READ_OPTS },
|
|
412
|
+
).then(chunk => chunk.data);
|
|
413
|
+
return extractCsrColumns({
|
|
414
|
+
indptr,
|
|
415
|
+
numRows: shape[0],
|
|
416
|
+
numCols: shape[1],
|
|
417
|
+
colIndices: cols,
|
|
418
|
+
nnz,
|
|
419
|
+
chunkSize,
|
|
420
|
+
getIndicesChunk,
|
|
421
|
+
getDataChunk,
|
|
422
|
+
prefetch: CSR_SCAN_PREFETCH,
|
|
190
423
|
});
|
|
191
|
-
return this._sparseMatrix;
|
|
192
424
|
}
|
|
193
425
|
|
|
194
426
|
/**
|
|
195
|
-
* Class method for loading
|
|
196
|
-
*
|
|
427
|
+
* Class method for loading a full sparse (CSR or CSC) matrix from zarr into a
|
|
428
|
+
* dense row-major Float32Array.
|
|
429
|
+
* @param {string} encodingType Either 'csr_matrix' or 'csc_matrix'.
|
|
430
|
+
* @returns {Promise<Float32Array>} The dense matrix.
|
|
197
431
|
*/
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
);
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
432
|
+
_loadSparseCellXGene(encodingType) {
|
|
433
|
+
return this._memoized('sparseMatrix', async () => {
|
|
434
|
+
const { path } = this.getOptions();
|
|
435
|
+
const [[indptrArr, indexArr, dataArr], { shape }] = await Promise.all([
|
|
436
|
+
this._openSparseArrays(),
|
|
437
|
+
this._loadMatrixZattrs(),
|
|
438
|
+
]);
|
|
439
|
+
const nnz = indexArr.shape[0];
|
|
440
|
+
const bytes = 4 * shape[0] * shape[1]
|
|
441
|
+
+ nnz * (getBytesPerElement(indexArr.dtype) + getBytesPerElement(dataArr.dtype))
|
|
442
|
+
+ indptrArr.shape[0] * getBytesPerElement(indptrArr.dtype);
|
|
443
|
+
const message = fullMatrixMessage({
|
|
444
|
+
path, shape, description: encodingType, bytes,
|
|
445
|
+
});
|
|
446
|
+
if (exceedsAllocationBudget(bytes)) {
|
|
447
|
+
// Attempt anyway: the budget is a heuristic, and a failed allocation is
|
|
448
|
+
// reported descriptively below.
|
|
449
|
+
this._warnOnce('fullMatrix', message);
|
|
450
|
+
}
|
|
451
|
+
const numCols = shape[1];
|
|
452
|
+
// Allocate before downloading, so that a matrix too large to hold fails
|
|
453
|
+
// right away instead of after fetching every stored value.
|
|
454
|
+
const matrix = allocateOrThrow(() => new Float32Array(shape[0] * numCols), message);
|
|
455
|
+
const [indptr, indices, values] = await Promise.all([
|
|
456
|
+
this._loadIndptr(),
|
|
457
|
+
zarrGet(indexArr).then(({ data }) => bigInt64ToNumberArray(data)),
|
|
458
|
+
zarrGet(dataArr).then(({ data }) => bigInt64ToNumberArray(data)),
|
|
459
|
+
]);
|
|
460
|
+
const numPointers = indptr.length - 1;
|
|
461
|
+
if (encodingType === 'csr_matrix') {
|
|
462
|
+
const numRows = Math.min(shape[0], numPointers);
|
|
463
|
+
for (let row = 0; row < numRows; row += 1) {
|
|
464
|
+
for (let k = indptr[row]; k < indptr[row + 1]; k += 1) {
|
|
465
|
+
matrix[row * numCols + indices[k]] = values[k];
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
} else {
|
|
469
|
+
const numStoredCols = Math.min(numCols, numPointers);
|
|
470
|
+
for (let col = 0; col < numStoredCols; col += 1) {
|
|
471
|
+
for (let k = indptr[col]; k < indptr[col + 1]; k += 1) {
|
|
472
|
+
matrix[indices[k] * numCols + col] = values[k];
|
|
473
|
+
}
|
|
222
474
|
}
|
|
223
|
-
|
|
475
|
+
}
|
|
476
|
+
return matrix;
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Class method for loading a full dense matrix from zarr.
|
|
482
|
+
* @returns {Promise<TypedArray>} The matrix, in the array's own dtype
|
|
483
|
+
* (int64 downcast to int32).
|
|
484
|
+
*/
|
|
485
|
+
_loadDenseCellXGene() {
|
|
486
|
+
return this._memoized('denseMatrix', async () => {
|
|
487
|
+
const { path } = this.getOptions();
|
|
488
|
+
const z = await this._openDenseArray();
|
|
489
|
+
const bytes = getBytesPerElement(z.dtype) * z.shape[0] * z.shape[1];
|
|
490
|
+
const message = fullMatrixMessage({
|
|
491
|
+
path, shape: z.shape, description: `dense ${z.dtype}`, bytes,
|
|
224
492
|
});
|
|
225
|
-
|
|
493
|
+
if (exceedsAllocationBudget(bytes)) {
|
|
494
|
+
this._warnOnce('fullMatrix', message);
|
|
495
|
+
}
|
|
496
|
+
let data;
|
|
497
|
+
try {
|
|
498
|
+
// zarrita allocates the whole selection up front.
|
|
499
|
+
({ data } = await createZarrArrayAdapter(z).getRaw(null));
|
|
500
|
+
} catch (e) {
|
|
501
|
+
if (isAllocationFailure(e)) {
|
|
502
|
+
throw new MatrixTooLargeError(`${message} (${e.message})`);
|
|
503
|
+
}
|
|
504
|
+
throw e;
|
|
505
|
+
}
|
|
506
|
+
return maybeDowncastInt64(data);
|
|
226
507
|
});
|
|
227
|
-
return this._sparseMatrix;
|
|
228
508
|
}
|
|
229
509
|
|
|
230
510
|
/**
|
|
231
511
|
* Class method for loading the cell x gene matrix.
|
|
232
512
|
* @returns {Promise} A promise for the zarr array contianing the cell x gene data.
|
|
233
513
|
*/
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
this._matrixZattrs = await this.dataSource.getJson(`${matrix}/.zattrs`);
|
|
245
|
-
}
|
|
246
|
-
const encodingType = this._matrixZattrs['encoding-type'];
|
|
247
|
-
if (!matrixGeneFilter) {
|
|
248
|
-
if (encodingType === 'csr_matrix') {
|
|
249
|
-
this.cellXGene = this._loadCSRSparseCellXGene().then(data => toObject(data));
|
|
250
|
-
} else if (encodingType === 'csc_matrix') {
|
|
251
|
-
this.cellXGene = this._loadCSCSparseCellXGene().then(data => toObject(data));
|
|
252
|
-
} else {
|
|
253
|
-
if (!this.arr) {
|
|
254
|
-
this.arr = zarrOpen(storeRoot.resolve(matrix), { kind: 'array' });
|
|
255
|
-
}
|
|
256
|
-
this.cellXGene = this.arr
|
|
257
|
-
.then(z => createZarrArrayAdapter(z).getRaw(null))
|
|
258
|
-
.then(({ data }) => toObject(maybeDowncastInt64(data)));
|
|
259
|
-
}
|
|
260
|
-
} else if (encodingType === 'csr_matrix') {
|
|
261
|
-
this.cellXGene = this._loadCSRSparseCellXGene().then(
|
|
262
|
-
async (cellXGene) => {
|
|
263
|
-
const filteredGenes = await this._getFilteredGenes(matrixGeneFilter);
|
|
264
|
-
const numGenesFiltered = filteredGenes.length;
|
|
265
|
-
const geneNames = await this.loadFilteredGeneNames();
|
|
266
|
-
const numGenes = geneNames.length;
|
|
267
|
-
const numCells = await this._getNumCells();
|
|
268
|
-
const cellXGeneMatrixFiltered = new Float32Array(
|
|
269
|
-
numCells * numGenesFiltered,
|
|
270
|
-
).fill(0);
|
|
271
|
-
for (let i = 0; i < numGenesFiltered; i += 1) {
|
|
272
|
-
const index = geneNames.indexOf(filteredGenes[i]);
|
|
273
|
-
for (let j = 0; j < numCells; j += 1) {
|
|
274
|
-
cellXGeneMatrixFiltered[j * numGenesFiltered + i] = cellXGene[j * numGenes + index];
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
return toObject(cellXGeneMatrixFiltered);
|
|
278
|
-
},
|
|
279
|
-
);
|
|
280
|
-
} else {
|
|
514
|
+
loadCellXGene() {
|
|
515
|
+
return this._memoized('cellXGene', () => this._loadCellXGeneUncached());
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async _loadCellXGeneUncached() {
|
|
519
|
+
const { path, initialFeatureFilterPath: matrixGeneFilter } = this.getOptions();
|
|
520
|
+
const { 'encoding-type': encodingType } = await this._loadMatrixZattrs();
|
|
521
|
+
if (matrixGeneFilter) {
|
|
522
|
+
// Only the filtered features are needed, so read them as columns whatever
|
|
523
|
+
// the encoding; this never densifies the full matrix.
|
|
281
524
|
const genes = await this._getFilteredGenes(matrixGeneFilter);
|
|
282
|
-
|
|
283
|
-
|
|
525
|
+
if (genes.length === 0) {
|
|
526
|
+
return toObject(new Float32Array(0));
|
|
527
|
+
}
|
|
528
|
+
const numRows = await this._getNumCells();
|
|
529
|
+
// The per-feature columns plus their interleaved copy.
|
|
530
|
+
const bytes = 2 * 4 * numRows * genes.length;
|
|
531
|
+
const message = fullMatrixMessage({
|
|
532
|
+
path,
|
|
533
|
+
shape: [numRows, genes.length],
|
|
534
|
+
description: `${encodingType || 'dense'}, ${genes.length} filtered features`,
|
|
535
|
+
bytes,
|
|
536
|
+
});
|
|
537
|
+
if (exceedsAllocationBudget(bytes)) {
|
|
538
|
+
this._warnOnce('fullMatrix', message);
|
|
539
|
+
}
|
|
540
|
+
const { data } = await this.loadGeneSelection({ selection: genes });
|
|
541
|
+
return toObject(allocateOrThrow(() => concatenateColumnVectors(data), message));
|
|
284
542
|
}
|
|
285
|
-
|
|
543
|
+
if (encodingType === 'csr_matrix' || encodingType === 'csc_matrix') {
|
|
544
|
+
return toObject(await this._loadSparseCellXGene(encodingType));
|
|
545
|
+
}
|
|
546
|
+
return toObject(await this._loadDenseCellXGene());
|
|
286
547
|
}
|
|
287
548
|
|
|
288
549
|
/**
|
|
@@ -292,27 +553,26 @@ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader
|
|
|
292
553
|
* @returns {Object} { data } containing an array of gene expression data.
|
|
293
554
|
*/
|
|
294
555
|
async loadGeneSelection({ selection }) {
|
|
295
|
-
const {
|
|
296
|
-
const { storeRoot } = this.dataSource;
|
|
297
|
-
if (!this._matrixZattrs) {
|
|
298
|
-
this._matrixZattrs = await this.dataSource.getJson(`${matrix}/.zattrs`);
|
|
299
|
-
}
|
|
300
|
-
const encodingType = this._matrixZattrs['encoding-type'];
|
|
556
|
+
const { 'encoding-type': encodingType } = await this._loadMatrixZattrs();
|
|
301
557
|
let genes;
|
|
302
558
|
if (encodingType === 'csc_matrix') {
|
|
303
559
|
genes = await this._loadCSCGeneSelection(selection);
|
|
304
560
|
} else if (encodingType === 'csr_matrix') {
|
|
305
561
|
genes = await this._loadCSRGeneSelection(selection);
|
|
306
562
|
} else {
|
|
307
|
-
|
|
308
|
-
this.
|
|
309
|
-
|
|
310
|
-
|
|
563
|
+
const [z, indices] = await Promise.all([
|
|
564
|
+
this._openDenseArray(),
|
|
565
|
+
this._getGeneIndices(selection),
|
|
566
|
+
]);
|
|
311
567
|
// We can index directly into a normal dense array zarr store via `get`.
|
|
312
568
|
genes = await Promise.all(
|
|
313
|
-
indices.map(index =>
|
|
314
|
-
|
|
315
|
-
|
|
569
|
+
indices.map(async (index, i) => {
|
|
570
|
+
if (index < 0) {
|
|
571
|
+
return this._missingFeatureColumn(selection[i], z.shape[0]);
|
|
572
|
+
}
|
|
573
|
+
const { data } = await zarrGet(z, [null, index]);
|
|
574
|
+
return maybeDowncastInt64(data);
|
|
575
|
+
}),
|
|
316
576
|
);
|
|
317
577
|
}
|
|
318
578
|
return { data: genes, url: null };
|