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