@vitessce/zarr 2.0.0-beta.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,245 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import { openArray } from 'zarr';
3
+ import range from 'lodash/range';
4
+ import ZarrDataSource from './ZarrDataSource';
5
+ const readFloat32FromUint8 = (bytes) => {
6
+ if (bytes.length !== 4) {
7
+ throw new Error('readFloat32 only takes in length 4 byte buffers');
8
+ }
9
+ return new Int32Array(bytes.buffer)[0];
10
+ };
11
+ const HEADER_LENGTH = 4;
12
+ function dirname(path) {
13
+ const arr = path.split('/');
14
+ arr.pop();
15
+ return arr.join('/');
16
+ }
17
+ /**
18
+ * Method for decoding text arrays from zarr.
19
+ * Largerly a port of https://github.com/zarr-developers/numcodecs/blob/2c1aff98e965c3c4747d9881d8b8d4aad91adb3a/numcodecs/vlen.pyx#L135-L178
20
+ * @returns {string[]} An array of strings.
21
+ */
22
+ function parseVlenUtf8(buffer) {
23
+ const decoder = new TextDecoder();
24
+ let data = 0;
25
+ const dataEnd = data + buffer.length;
26
+ const length = readFloat32FromUint8(buffer.slice(data, HEADER_LENGTH));
27
+ if (buffer.length < HEADER_LENGTH) {
28
+ throw new Error('corrupt buffer, missing or truncated header');
29
+ }
30
+ data += HEADER_LENGTH;
31
+ const output = new Array(length);
32
+ for (let i = 0; i < length; i += 1) {
33
+ if (data + 4 > dataEnd) {
34
+ throw new Error('corrupt buffer, data seem truncated');
35
+ }
36
+ const l = readFloat32FromUint8(buffer.slice(data, data + 4));
37
+ data += 4;
38
+ if (data + l > dataEnd) {
39
+ throw new Error('corrupt buffer, data seem truncated');
40
+ }
41
+ output[i] = decoder.decode(buffer.slice(data, data + l));
42
+ data += l;
43
+ }
44
+ return output;
45
+ }
46
+ /**
47
+ * A base AnnData loader which has all shared methods for more comlpex laoders,
48
+ * like loading cell names and ids. It inherits from AbstractLoader.
49
+ */
50
+ export default class AnnDataSource extends ZarrDataSource {
51
+ constructor(...args) {
52
+ super(...args);
53
+ /** @type {Map<string, Promise<string[]>} */
54
+ this.promises = new Map();
55
+ }
56
+ loadObsColumns(paths) {
57
+ return this._loadColumns(paths);
58
+ }
59
+ loadVarColumns(paths) {
60
+ return this._loadColumns(paths);
61
+ }
62
+ /**
63
+ * Class method for loading obs variables.
64
+ * Takes the location as an argument because this is shared across objects,
65
+ * which have different ways of specifying location.
66
+ * @param {string[]} paths An array of strings like "obs/leiden" or "obs/bulk_labels."
67
+ * @returns {Promise} A promise for an array of ids with one per cell.
68
+ */
69
+ _loadColumns(paths) {
70
+ const promises = paths.map((path) => {
71
+ const getCol = (col) => {
72
+ if (!this.promises.has(col)) {
73
+ const obsPromise = this._loadColumn(col).catch((err) => {
74
+ // clear from cache if promise rejects
75
+ this.promises.delete(col);
76
+ // propagate error
77
+ throw err;
78
+ });
79
+ this.promises.set(col, obsPromise);
80
+ }
81
+ return this.promises.get(col);
82
+ };
83
+ if (!path) {
84
+ return Promise.resolve(undefined);
85
+ }
86
+ if (Array.isArray(path)) {
87
+ return Promise.resolve(Promise.all(path.map(getCol)));
88
+ }
89
+ return getCol(path);
90
+ });
91
+ return Promise.all(promises);
92
+ }
93
+ async _loadColumn(path) {
94
+ const { store } = this;
95
+ const prefix = dirname(path);
96
+ const { categories, 'encoding-type': encodingType } = await this.getJson(`${path}/.zattrs`);
97
+ let categoriesValues;
98
+ let codes;
99
+ if (categories) {
100
+ const { dtype } = await this.getJson(`/${prefix}/${categories}/.zarray`);
101
+ if (dtype === '|O') {
102
+ categoriesValues = await this.getFlatArrDecompressed(`/${prefix}/${categories}`);
103
+ }
104
+ }
105
+ else if (encodingType === 'categorical') {
106
+ const { dtype } = await this.getJson(`/${path}/categories/.zarray`);
107
+ if (dtype === '|O') {
108
+ categoriesValues = await this.getFlatArrDecompressed(`/${path}/categories`);
109
+ }
110
+ codes = `/${path}/codes`;
111
+ }
112
+ else {
113
+ const { dtype } = await this.getJson(`/${path}/.zarray`);
114
+ if (dtype === '|O') {
115
+ return this.getFlatArrDecompressed(path);
116
+ }
117
+ }
118
+ const arr = await openArray({ store, path: codes || path, mode: 'r' });
119
+ const values = await arr.get();
120
+ const { data } = values;
121
+ const mappedValues = Array.from(data).map(i => (!categoriesValues ? String(i) : categoriesValues[i]));
122
+ return mappedValues;
123
+ }
124
+ /**
125
+ * Class method for loading general numeric arrays.
126
+ * @param {string} path A string like obsm.X_pca.
127
+ * @returns {Promise} A promise for a zarr array containing the data.
128
+ */
129
+ loadNumeric(path) {
130
+ const { store } = this;
131
+ return openArray({
132
+ store,
133
+ path,
134
+ mode: 'r',
135
+ }).then(arr => arr.get());
136
+ }
137
+ /**
138
+ * Class method for loading specific columns of numeric arrays.
139
+ * @param {string} path A string like obsm.X_pca.
140
+ * @param {number[]} dims The column indices to load.
141
+ * @returns {Promise} A promise for a zarr array containing the data.
142
+ */
143
+ loadNumericForDims(path, dims) {
144
+ const { store } = this;
145
+ const arr = openArray({
146
+ store,
147
+ path,
148
+ mode: 'r',
149
+ });
150
+ return Promise.all(dims.map(dim => arr.then(loadedArr => loadedArr.get([null, dim])))).then(cols => ({
151
+ data: cols.map(col => col.data),
152
+ shape: [dims.length, cols[0].shape[0]],
153
+ }));
154
+ }
155
+ /**
156
+ * A common method for loading flattened data
157
+ * i.e that which has shape [n] where n is a natural number.
158
+ * @param {string} path A path to a flat array location, like obs/_index
159
+ * @returns {Array} The data from the zarr array.
160
+ */
161
+ getFlatArrDecompressed(path) {
162
+ const { store } = this;
163
+ return openArray({
164
+ store,
165
+ path,
166
+ mode: 'r',
167
+ }).then(async (z) => {
168
+ let data;
169
+ const parseAndMergeTextBytes = (dbytes) => {
170
+ const text = parseVlenUtf8(dbytes);
171
+ if (!data) {
172
+ data = text;
173
+ }
174
+ else {
175
+ data = data.concat(text);
176
+ }
177
+ };
178
+ const mergeBytes = (dbytes) => {
179
+ if (!data) {
180
+ data = dbytes;
181
+ }
182
+ else {
183
+ const tmp = new Uint8Array(dbytes.buffer.byteLength + data.buffer.byteLength);
184
+ tmp.set(new Uint8Array(data.buffer), 0);
185
+ tmp.set(dbytes, data.buffer.byteLength);
186
+ data = tmp;
187
+ }
188
+ };
189
+ const numRequests = Math.ceil(z.meta.shape[0] / z.meta.chunks[0]);
190
+ const requests = range(numRequests).map(async (item) => store
191
+ .getItem(`${z.keyPrefix}${String(item)}`)
192
+ .then(buf => z.compressor.then(compressor => compressor.decode(buf))));
193
+ const dbytesArr = await Promise.all(requests);
194
+ dbytesArr.forEach((dbytes) => {
195
+ // Use vlenutf-8 decoding if necessary and merge `data` as a normal array.
196
+ if (Array.isArray(z.meta.filters)
197
+ && z.meta.filters[0].id === 'vlen-utf8') {
198
+ parseAndMergeTextBytes(dbytes);
199
+ // Otherwise just merge the bytes as a typed array.
200
+ }
201
+ else {
202
+ mergeBytes(dbytes);
203
+ }
204
+ });
205
+ const { meta: { shape: [length], }, } = z;
206
+ // truncate the filled in values
207
+ return data.slice(0, length);
208
+ });
209
+ }
210
+ /**
211
+ * Class method for loading the obs index.
212
+ * @returns {Promise} An promise for a zarr array containing the indices.
213
+ */
214
+ loadObsIndex() {
215
+ if (this.obsIndex) {
216
+ return this.obsIndex;
217
+ }
218
+ this.obsIndex = this.getJson('obs/.zattrs').then(({ _index }) => this.getFlatArrDecompressed(`/obs/${_index}`));
219
+ return this.obsIndex;
220
+ }
221
+ /**
222
+ * Class method for loading the var index.
223
+ * @returns {Promise} An promise for a zarr array containing the indices.
224
+ */
225
+ loadVarIndex() {
226
+ if (this.varIndex) {
227
+ return this.varIndex;
228
+ }
229
+ this.varIndex = this.getJson('var/.zattrs').then(({ _index }) => this.getFlatArrDecompressed(`/var/${_index}`));
230
+ return this.varIndex;
231
+ }
232
+ /**
233
+ * Class method for loading the var alias.
234
+ * @returns {Promise} An promise for a zarr array containing the aliased names.
235
+ */
236
+ async loadVarAlias(varPath) {
237
+ if (this.varAlias) {
238
+ return this.varAlias;
239
+ }
240
+ [this.varAlias] = await this.loadVarColumns([varPath]);
241
+ const index = await this.loadVarIndex();
242
+ this.varAlias = this.varAlias.map((val, ind) => (val ? val.concat(` (${index[ind]})`) : index[ind]));
243
+ return this.varAlias;
244
+ }
245
+ }
@@ -0,0 +1,49 @@
1
+ import AnnDataSource from './AnnDataSource';
2
+ describe('sources/AnnDataSource', () => {
3
+ describe('AnnData v0.7', () => {
4
+ it('getJson returns json', async () => {
5
+ const dataSource = new AnnDataSource({
6
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr',
7
+ });
8
+ const zGroup = await dataSource.getJson('.zgroup');
9
+ expect(zGroup.zarr_format).toEqual(2);
10
+ });
11
+ it('loadObsColumns returns ids for location in store', async () => {
12
+ const dataSource = new AnnDataSource({
13
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr',
14
+ });
15
+ const ids = await dataSource.loadObsColumns(['obs/leiden']);
16
+ expect(ids).toEqual([['1', '1', '2']]);
17
+ });
18
+ it('loadObsIndex returns names', async () => {
19
+ const dataSource = new AnnDataSource({
20
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr',
21
+ });
22
+ const names = await dataSource.loadObsIndex();
23
+ expect(names).toEqual(['CTG', 'GCA', 'CTG']);
24
+ });
25
+ });
26
+ describe('AnnData v0.8', () => {
27
+ it('getJson returns json', async () => {
28
+ const dataSource = new AnnDataSource({
29
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr',
30
+ });
31
+ const zGroup = await dataSource.getJson('.zgroup');
32
+ expect(zGroup.zarr_format).toEqual(2);
33
+ });
34
+ it('loadObsColumns returns ids for location in store', async () => {
35
+ const dataSource = new AnnDataSource({
36
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr',
37
+ });
38
+ const ids = await dataSource.loadObsColumns(['obs/leiden']);
39
+ expect(ids).toEqual([['1', '1', '2']]);
40
+ });
41
+ it('loadObsIndex returns names', async () => {
42
+ const dataSource = new AnnDataSource({
43
+ url: 'http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr',
44
+ });
45
+ const names = await dataSource.loadObsIndex();
46
+ expect(names).toEqual(['CTG', 'GCA', 'CTG']);
47
+ });
48
+ });
49
+ });
@@ -0,0 +1,35 @@
1
+ import { HTTPStore, KeyError } from 'zarr';
2
+ /**
3
+ * A loader ancestor class containing a default constructor
4
+ * and a stub for the required load() method.
5
+ */
6
+ export default class ZarrDataSource {
7
+ constructor({ url, requestInit }) {
8
+ // TODO: We should probably add a way of allowing HEAD requests as well:
9
+ // https://github.com/gzuidhof/zarr.js/blob/375ce0c299469a970da6bb5653513564e25806bb/docs/getting-started/remote-data.md#stores
10
+ const supportedMethods = ['GET'];
11
+ this.store = new HTTPStore(url, {
12
+ supportedMethods, fetchOptions: requestInit,
13
+ });
14
+ }
15
+ /**
16
+ * Class method for decoding json from the store.
17
+ * @param {string} key A path to the item.
18
+ * @returns {Promise} This async function returns a promise
19
+ * that resolves to the parsed JSON if successful.
20
+ * @throws This may throw an error.
21
+ */
22
+ async getJson(key) {
23
+ try {
24
+ const buf = await this.store.getItem(key);
25
+ const text = new TextDecoder('utf-8').decode(buf);
26
+ return JSON.parse(text);
27
+ }
28
+ catch (err) {
29
+ if (err instanceof KeyError) {
30
+ return {};
31
+ }
32
+ throw err;
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,52 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError } from '@vitessce/vit-s';
2
+ const optionsSchema = {
3
+ $schema: 'http://json-schema.org/draft-07/schema#',
4
+ $id: 'https://github.com/vitessce/vitessce/#cells',
5
+ title: 'obsEmbedding.anndata.zarr options',
6
+ type: 'object',
7
+ additionalProperties: false,
8
+ required: ['path'],
9
+ properties: {
10
+ path: { type: 'string' },
11
+ },
12
+ };
13
+ /**
14
+ * Loader for string arrays located in anndata.zarr stores.
15
+ */
16
+ export default class FeatureLabelsAnndataLoader extends AbstractTwoStepLoader {
17
+ constructor(dataSource, params) {
18
+ super(dataSource, params);
19
+ this.optionsSchema = optionsSchema;
20
+ }
21
+ /**
22
+ * Class method for loading feature string labels.
23
+ * @returns {Promise} A promise for the array.
24
+ */
25
+ async loadLabels() {
26
+ const { path } = this.options;
27
+ if (this.labels) {
28
+ return this.labels;
29
+ }
30
+ if (!this.labels) {
31
+ // eslint-disable-next-line no-underscore-dangle
32
+ this.labels = await this.dataSource._loadColumn(path);
33
+ return this.labels;
34
+ }
35
+ this.labels = Promise.resolve(null);
36
+ return this.labels;
37
+ }
38
+ async load() {
39
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
40
+ if (superResult instanceof AbstractLoaderError) {
41
+ return Promise.reject(superResult);
42
+ }
43
+ return Promise.all([
44
+ this.dataSource.loadVarIndex(),
45
+ this.loadLabels(),
46
+ ]).then(([featureIndex, featureLabels]) => Promise.resolve(new LoaderResult({
47
+ featureIndex,
48
+ featureLabels,
49
+ featureLabelsMap: new Map(featureIndex.map((key, i) => ([key, featureLabels[i]]))),
50
+ }, null)));
51
+ }
52
+ }
@@ -0,0 +1,36 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsEmbeddingAnndataSchema, } from '@vitessce/vit-s';
2
+ /**
3
+ * Loader for embedding arrays located in anndata.zarr stores.
4
+ */
5
+ export default class ObsEmbeddingAnndataLoader extends AbstractTwoStepLoader {
6
+ constructor(dataSource, params) {
7
+ super(dataSource, params);
8
+ this.optionsSchema = obsEmbeddingAnndataSchema;
9
+ }
10
+ /**
11
+ * Class method for loading embedding coordinates, such as those from UMAP or t-SNE.
12
+ * @returns {Promise} A promise for an array of columns.
13
+ */
14
+ async loadEmbedding() {
15
+ const { path, dims = [0, 1] } = this.options;
16
+ if (this.embedding) {
17
+ return this.embedding;
18
+ }
19
+ if (!this.embedding) {
20
+ this.embedding = await this.dataSource.loadNumericForDims(path, dims);
21
+ return this.embedding;
22
+ }
23
+ this.embedding = Promise.resolve(null);
24
+ return this.embedding;
25
+ }
26
+ async load() {
27
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
28
+ if (superResult instanceof AbstractLoaderError) {
29
+ return Promise.reject(superResult);
30
+ }
31
+ return Promise.all([
32
+ this.dataSource.loadObsIndex(),
33
+ this.loadEmbedding(),
34
+ ]).then(([obsIndex, obsEmbedding]) => Promise.resolve(new LoaderResult({ obsIndex, obsEmbedding }, null)));
35
+ }
36
+ }
@@ -0,0 +1,31 @@
1
+ /* eslint-disable func-names */
2
+ import { LoaderResult } from '@vitessce/vit-s';
3
+ import ObsEmbeddingAnndataLoader from './ObsEmbeddingAnndataLoader';
4
+ import AnnDataSource from '../AnnDataSource';
5
+ const createMatrixLoader = (url) => {
6
+ const config = {
7
+ url,
8
+ fileType: 'obsEmbedding.anndata.zarr',
9
+ options: {
10
+ path: 'obsm/X_umap',
11
+ },
12
+ coordinationValues: {
13
+ embeddingType: 'UMAP',
14
+ },
15
+ };
16
+ const source = new AnnDataSource(config);
17
+ return new ObsEmbeddingAnndataLoader(source, config);
18
+ };
19
+ describe('loaders/ObsEmbeddingAnndataLoader', () => {
20
+ it('load returns obsIndex and obsEmbedding', async () => {
21
+ const loader = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr');
22
+ const result = await loader.load();
23
+ expect(result).toBeInstanceOf(LoaderResult);
24
+ const payload = result.data;
25
+ expect(Object.keys(payload)).toEqual(['obsIndex', 'obsEmbedding']);
26
+ expect(payload.obsIndex).toEqual(['CTG', 'GCA', 'CTG']);
27
+ expect(payload.obsEmbedding.shape).toEqual([2, 3]);
28
+ expect(Array.from(payload.obsEmbedding.data[0])).toEqual([-1, 0, 1]);
29
+ expect(Array.from(payload.obsEmbedding.data[1])).toEqual([-1, 0, 1]);
30
+ });
31
+ });
@@ -0,0 +1,363 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import { openArray, slice } from 'zarr';
3
+ import { extent } from 'd3-array';
4
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsFeatureMatrixAnndataSchema, } from '@vitessce/vit-s';
5
+ const normalize = (arr) => {
6
+ const [min, max] = extent(arr);
7
+ const ratio = 255 / (max - min);
8
+ const data = new Uint8Array(arr.map(i => Math.floor((i - min) * ratio)));
9
+ return { data };
10
+ };
11
+ const concatenateColumnVectors = (arr) => {
12
+ const numCols = arr.length;
13
+ const numRows = arr[0].length;
14
+ const { BYTES_PER_ELEMENT } = arr[0];
15
+ const view = new DataView(new ArrayBuffer(numCols * numRows * BYTES_PER_ELEMENT));
16
+ const TypedArray = arr[0].constructor;
17
+ const dtype = TypedArray.name.replace('Array', '');
18
+ for (let i = 0; i < numCols; i += 1) {
19
+ for (let j = 0; j < numRows; j += 1) {
20
+ view[`set${dtype}`](BYTES_PER_ELEMENT * (j * numCols + i), arr[i][j], true);
21
+ }
22
+ }
23
+ return new TypedArray(view.buffer);
24
+ };
25
+ /**
26
+ * Loader for converting zarr into the a cell x gene matrix for use in Genes/Heatmap components.
27
+ */
28
+ export default class ObsFeatureMatrixAnndataLoader extends AbstractTwoStepLoader {
29
+ constructor(dataSource, params) {
30
+ super(dataSource, params);
31
+ this.optionsSchema = obsFeatureMatrixAnndataSchema;
32
+ }
33
+ getOptions() {
34
+ return this.options;
35
+ }
36
+ /**
37
+ * Class method for loading the genes list from AnnData.var,
38
+ * filtered if a there is a `geneFilterZarr` present in the view config.
39
+ * @returns {Promise} A promise for the zarr array contianing the gene names.
40
+ */
41
+ async loadFilteredGeneNames() {
42
+ if (this.filteredGeneNames) {
43
+ return this.filteredGeneNames;
44
+ }
45
+ const { featureFilterPath: geneFilterZarr, geneAlias } = this.getOptions();
46
+ const getFilterFn = async () => {
47
+ if (!geneFilterZarr)
48
+ return data => data;
49
+ const geneFilter = await this.dataSource.getFlatArrDecompressed(geneFilterZarr);
50
+ return data => data.filter((_, j) => geneFilter[j]);
51
+ };
52
+ const geneNamesPromise = geneAlias
53
+ ? this.dataSource.loadVarAlias(geneAlias)
54
+ : this.dataSource.loadVarIndex();
55
+ this.filteredGeneNames = Promise.all([
56
+ geneNamesPromise,
57
+ getFilterFn(),
58
+ ]).then(([data, filter]) => filter(data));
59
+ return this.filteredGeneNames;
60
+ }
61
+ /**
62
+ * Class method for loading a filtered subset of the genes list
63
+ * @param {String} filterZarr A location in the zarr store to fetch a boolean array from.
64
+ * @returns {Array} A list of filtered genes.
65
+ */
66
+ async _getFilteredGenes(filterZarr) {
67
+ const filter = await this.dataSource.getFlatArrDecompressed(filterZarr);
68
+ const geneNames = await this.loadFilteredGeneNames();
69
+ const genes = geneNames.filter((_, i) => filter[i]);
70
+ return genes;
71
+ }
72
+ /**
73
+ * Class method for getting the integer indices of a selection of genes within a list.
74
+ * @param {Array} selection A list of gene names.
75
+ * @returns {Array} A list of integer indices.
76
+ */
77
+ async _getGeneIndices(selection) {
78
+ const geneNames = await this.loadFilteredGeneNames();
79
+ return selection.map(gene => geneNames.indexOf(gene));
80
+ }
81
+ /**
82
+ * Class method for getting the number of cells i.e entries in `obs`.
83
+ * @returns {Number} The number of cells.
84
+ */
85
+ async _getNumCells() {
86
+ const cells = await this.dataSource.loadObsIndex();
87
+ return cells.length;
88
+ }
89
+ /**
90
+ * Class method for getting the number of genes i.e entries in `var`,
91
+ * potentially filtered by `genesFilter`.
92
+ * @returns {Number} The number of genes.
93
+ */
94
+ async _getNumGenes() {
95
+ const genes = await this.loadFilteredGeneNames();
96
+ return genes.length;
97
+ }
98
+ /**
99
+ * Class method for opening the sparse matrix arrays in zarr.
100
+ * @returns {Array} A list of promises pointing to the indptr, indices, and data of the matrix.
101
+ */
102
+ async _openSparseArrays() {
103
+ const { path: matrix } = this.getOptions();
104
+ const { store } = this.dataSource;
105
+ if (this.sparseArrays) {
106
+ return this.sparseArrays;
107
+ }
108
+ this.sparseArrays = Promise.all(['indptr', 'indices', 'data'].map(name => openArray({ store, path: `${matrix}/${name}`, mode: 'r' })));
109
+ return this.sparseArrays;
110
+ }
111
+ /**
112
+ * Class method for loading a gene selection from a CSC matrix.
113
+ * @param {Array} selection A list of gene names whose data should be fetched.
114
+ * @returns {Promise} A Promise.all array of promises containing Uint8Arrays, one per selection.
115
+ */
116
+ async _loadCSCGeneSelection(selection) {
117
+ const indices = await this._getGeneIndices(selection);
118
+ const [indptrArr, indexArr, cellXGeneArr] = await this._openSparseArrays();
119
+ const numCells = await this._getNumCells();
120
+ const { data: cols } = await indptrArr.getRaw(null);
121
+ // If there is not change in the column indexer, then the data is all zeros
122
+ return Promise.all(indices.map(async (index) => {
123
+ const startRowIndex = cols[index];
124
+ const endRowIndex = cols[index + 1];
125
+ const isColumnAllZeros = startRowIndex === endRowIndex;
126
+ const geneData = new Float32Array(numCells).fill(0);
127
+ if (isColumnAllZeros) {
128
+ return geneData;
129
+ }
130
+ const { data: rowIndices } = await indexArr.get([
131
+ slice(startRowIndex, endRowIndex),
132
+ ]);
133
+ const { data: cellXGeneData } = await cellXGeneArr.get([
134
+ slice(startRowIndex, endRowIndex),
135
+ ]);
136
+ for (let rowIndex = 0; rowIndex < rowIndices.length; rowIndex += 1) {
137
+ geneData[rowIndices[rowIndex]] = cellXGeneData[rowIndex];
138
+ }
139
+ return geneData;
140
+ }));
141
+ }
142
+ /**
143
+ * Class method for loading a gene selection from a CSR matrix.
144
+ * @param {Array} selection A list of gene names whose data should be fetched.
145
+ * @returns {Promise} A Promise.all array of promises containing Uint8Arrays, one per selection.
146
+ */
147
+ async _loadCSRGeneSelection(selection) {
148
+ const indices = await this._getGeneIndices(selection);
149
+ const numGenes = await this._getNumGenes();
150
+ const numCells = await this._getNumCells();
151
+ const cellXGene = await this._loadCSRSparseCellXGene();
152
+ return indices.map((index) => {
153
+ const geneData = new Float32Array(numCells).fill(0);
154
+ for (let i = 0; i < numCells; i += 1) {
155
+ geneData[i] = cellXGene[i * numGenes + index];
156
+ }
157
+ return geneData;
158
+ });
159
+ }
160
+ /**
161
+ * Class method for loading row oriented (CSR) sparse data from zarr.
162
+ *
163
+ * @returns {Object} A { data: Float32Array } contianing the CellXGene matrix.
164
+ */
165
+ async _loadCSRSparseCellXGene() {
166
+ if (this._sparseMatrix) {
167
+ return this._sparseMatrix;
168
+ }
169
+ this._sparseMatrix = this._openSparseArrays().then(async (sparseArrays) => {
170
+ const { path: matrix } = this.getOptions();
171
+ const { shape } = await this.dataSource.getJson(`${matrix}/.zattrs`);
172
+ const [rows, cols, cellXGene] = await Promise.all(sparseArrays.map(async (arr) => {
173
+ const { data } = await arr.getRaw(null);
174
+ return data;
175
+ }));
176
+ const cellXGeneMatrix = new Float32Array(shape[0] * shape[1]).fill(0);
177
+ let row = 0;
178
+ rows.forEach((_, index) => {
179
+ const rowStart = rows[index];
180
+ const rowEnd = rows[index + 1];
181
+ for (let i = rowStart; i < rowEnd; i += 1) {
182
+ const val = cellXGene[i];
183
+ const col = cols[i];
184
+ cellXGeneMatrix[row * shape[1] + col] = val;
185
+ }
186
+ row += 1;
187
+ });
188
+ return cellXGeneMatrix;
189
+ });
190
+ return this._sparseMatrix;
191
+ }
192
+ /**
193
+ * Class method for loading column oriented (CSC) sparse data from zarr.
194
+ * @returns {Object} A { data: Float32Array } contianing the CellXGene matrix.
195
+ */
196
+ async _loadCSCSparseCellXGene() {
197
+ if (this._sparseMatrix) {
198
+ return this._sparseMatrix;
199
+ }
200
+ this._sparseMatrix = this._openSparseArrays().then(async (sparseArrays) => {
201
+ const { path: matrix } = this.getOptions();
202
+ const { shape } = await this.dataSource.getJson(`${matrix}/.zattrs`);
203
+ const [cols, rows, cellXGene] = await Promise.all(sparseArrays.map(async (arr) => {
204
+ const { data } = await arr.getRaw(null);
205
+ return data;
206
+ }));
207
+ const cellXGeneMatrix = new Float32Array(shape[0] * shape[1]).fill(0);
208
+ let col = 0;
209
+ cols.forEach((_, index) => {
210
+ const colStart = cols[index];
211
+ const colEnd = cols[index + 1];
212
+ for (let i = colStart; i < colEnd; i += 1) {
213
+ const val = cellXGene[i];
214
+ const row = rows[i];
215
+ cellXGeneMatrix[row * shape[1] + col] = val;
216
+ }
217
+ col += 1;
218
+ });
219
+ return cellXGeneMatrix;
220
+ });
221
+ return this._sparseMatrix;
222
+ }
223
+ /**
224
+ * Class method for loading the cell x gene matrix.
225
+ * @returns {Promise} A promise for the zarr array contianing the cell x gene data.
226
+ */
227
+ async loadCellXGene() {
228
+ const { store } = this.dataSource;
229
+ if (this.cellXGene) {
230
+ return this.cellXGene;
231
+ }
232
+ const { path: matrix, initialFeatureFilterPath: matrixGeneFilter, } = this.getOptions();
233
+ if (!this._matrixZattrs) {
234
+ this._matrixZattrs = await this.dataSource.getJson(`${matrix}/.zattrs`);
235
+ }
236
+ const encodingType = this._matrixZattrs['encoding-type'];
237
+ if (!matrixGeneFilter) {
238
+ if (encodingType === 'csr_matrix') {
239
+ this.cellXGene = this._loadCSRSparseCellXGene().then(data => normalize(data));
240
+ }
241
+ else if (encodingType === 'csc_matrix') {
242
+ this.cellXGene = this._loadCSCSparseCellXGene().then(data => normalize(data));
243
+ }
244
+ else {
245
+ if (!this.arr) {
246
+ this.arr = openArray({ store, path: matrix, mode: 'r' });
247
+ }
248
+ this.cellXGene = this.arr.then(z => z.getRaw(null).then(({ data }) => normalize(data)));
249
+ }
250
+ }
251
+ else if (encodingType === 'csr_matrix') {
252
+ this.cellXGene = this._loadCSRSparseCellXGene().then(async (cellXGene) => {
253
+ const filteredGenes = await this._getFilteredGenes(matrixGeneFilter);
254
+ const numGenesFiltered = filteredGenes.length;
255
+ const geneNames = await this.loadFilteredGeneNames();
256
+ const numGenes = geneNames.length;
257
+ const numCells = await this._getNumCells();
258
+ const cellXGeneMatrixFiltered = new Float32Array(numCells * numGenesFiltered).fill(0);
259
+ for (let i = 0; i < numGenesFiltered; i += 1) {
260
+ const index = geneNames.indexOf(filteredGenes[i]);
261
+ for (let j = 0; j < numCells; j += 1) {
262
+ cellXGeneMatrixFiltered[j * numGenesFiltered + i] = cellXGene[j * numGenes + index];
263
+ }
264
+ }
265
+ return normalize(cellXGeneMatrixFiltered);
266
+ });
267
+ }
268
+ else {
269
+ const genes = await this._getFilteredGenes(matrixGeneFilter);
270
+ this.cellXGene = this.loadGeneSelection({ selection: genes, shouldNormalize: false })
271
+ .then(({ data }) => (normalize(concatenateColumnVectors(data))));
272
+ }
273
+ return this.cellXGene;
274
+ }
275
+ /**
276
+ * Class method for loading a gene selection.
277
+ * @param {Object} args
278
+ * @param {Array} args.selection A list of gene names whose data should be fetched.
279
+ * @param {Boolean} args.shouldNormalize A list of gene names whose data should be fetched.
280
+ * @returns {Object} { data } containing an array of gene expression data.
281
+ */
282
+ async loadGeneSelection({ selection, shouldNormalize = true }) {
283
+ const { path: matrix } = this.getOptions();
284
+ const { store } = this.dataSource;
285
+ if (!this._matrixZattrs) {
286
+ this._matrixZattrs = await this.dataSource.getJson(`${matrix}/.zattrs`);
287
+ }
288
+ const encodingType = this._matrixZattrs['encoding-type'];
289
+ let genes;
290
+ if (encodingType === 'csc_matrix') {
291
+ genes = await this._loadCSCGeneSelection(selection);
292
+ }
293
+ else if (encodingType === 'csr_matrix') {
294
+ genes = await this._loadCSRGeneSelection(selection);
295
+ }
296
+ else {
297
+ if (!this.arr) {
298
+ this.arr = openArray({ store, path: matrix, mode: 'r' });
299
+ }
300
+ const indices = await this._getGeneIndices(selection);
301
+ // We can index directly into a normal dense array zarr store via `get`.
302
+ genes = await Promise.all(indices.map(index => this.arr.then(z => z.get([null, index])).then(({ data }) => data)));
303
+ }
304
+ return { data: genes.map(i => (shouldNormalize ? normalize(i).data : i)), url: null };
305
+ }
306
+ /**
307
+ * Class method for loading only attributes i.e rows and columns
308
+ * @param {Array} selection A list of gene names whose data should be fetched.
309
+ * @returns {Object} { data: { rows, cols }, url } containing row and col labels for the matrix.
310
+ */
311
+ loadAttrs() {
312
+ return Promise.all([this.dataSource.loadObsIndex(), this.loadFilteredGeneNames()])
313
+ .then((d) => {
314
+ const [cellNames, geneNames] = d;
315
+ const attrs = { rows: cellNames, cols: geneNames };
316
+ return {
317
+ data: attrs,
318
+ url: null,
319
+ };
320
+ });
321
+ }
322
+ async loadInitialFilteredGeneNames() {
323
+ const filteredGeneNames = await this.loadFilteredGeneNames();
324
+ const { initialFeatureFilterPath: matrixGeneFilterZarr, } = this.getOptions();
325
+ // In order to return the correct gene list with the heatmap data,
326
+ // we need to filter the columns of attrs so it matches the cellXGene data.
327
+ if (matrixGeneFilterZarr) {
328
+ const matrixGeneFilter = await this.dataSource.getFlatArrDecompressed(matrixGeneFilterZarr);
329
+ return filteredGeneNames.filter((_, i) => matrixGeneFilter[i]);
330
+ }
331
+ return filteredGeneNames;
332
+ }
333
+ /* load() {
334
+ return Promise.all([this.loadAttrs(), this.loadCellXGene()]).then(
335
+ async (d) => {
336
+ const [{ data: attrs }, cellXGene] = d;
337
+ const {
338
+ initialFeatureFilterPath: matrixGeneFilterZarr,
339
+ } = this.getOptions();
340
+ // In order to return the correct gene list with the heatmap data,
341
+ // we need to filter the columns of attrs so it matches the cellXGene data.
342
+ if (matrixGeneFilterZarr) {
343
+ const matrixGeneFilter = await this.dataSource.getFlatArrDecompressed(
344
+ matrixGeneFilterZarr,
345
+ );
346
+ attrs.cols = attrs.cols.filter((_, i) => matrixGeneFilter[i]);
347
+ }
348
+ return Promise.resolve(new LoaderResult([attrs, cellXGene], null));
349
+ },
350
+ );
351
+ } */
352
+ async load() {
353
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
354
+ if (superResult instanceof AbstractLoaderError) {
355
+ return Promise.reject(superResult);
356
+ }
357
+ return Promise.all([
358
+ this.dataSource.loadObsIndex(),
359
+ this.loadInitialFilteredGeneNames(),
360
+ this.loadCellXGene(),
361
+ ]).then(([obsIndex, featureIndex, obsFeatureMatrix]) => Promise.resolve(new LoaderResult({ obsIndex, featureIndex, obsFeatureMatrix }, null)));
362
+ }
363
+ }
@@ -0,0 +1,72 @@
1
+ /* eslint-disable func-names */
2
+ import ObsFeatureMatrixAnndataLoader from './ObsFeatureMatrixAnndataLoader';
3
+ import AnnDataSource from '../AnnDataSource';
4
+ const createMatrixLoader = (url) => {
5
+ const config = {
6
+ url,
7
+ fileType: 'obsFeatureMatrix.anndata.zarr',
8
+ options: {
9
+ path: 'X',
10
+ },
11
+ };
12
+ const source = new AnnDataSource(config);
13
+ return new ObsFeatureMatrixAnndataLoader(source, config);
14
+ };
15
+ describe('loaders/ObsFeatureMatrixAnndataLoader', () => {
16
+ describe('AnnData v0.7', () => {
17
+ it('loadFilteredGeneNames returns gene names', async () => {
18
+ const loader = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr');
19
+ const names = await loader.loadFilteredGeneNames();
20
+ expect(names).toEqual(Array.from({ length: 15 }).map((_, i) => `gene_${i}`));
21
+ });
22
+ it('loadGeneSelection matches across storage methods', async () => {
23
+ const selection = { selection: ['gene_1', 'gene_5'] };
24
+ const loaderCsr = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-csr.zarr');
25
+ const csrSelection = await loaderCsr.loadGeneSelection(selection);
26
+ const loaderDense = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr');
27
+ const denseSelection = await loaderDense.loadGeneSelection(selection);
28
+ const loaderCsc = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-csc.zarr');
29
+ const cscSelection = await loaderCsc.loadGeneSelection(selection);
30
+ expect(cscSelection).toEqual(denseSelection);
31
+ expect(csrSelection).toEqual(denseSelection);
32
+ });
33
+ it('loadCellXGene matches across storage methods', async () => {
34
+ const loaderCsr = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-csr.zarr');
35
+ const csrMatrix = await loaderCsr.loadCellXGene();
36
+ const loaderDense = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-dense.zarr');
37
+ const denseMatrix = await loaderDense.loadCellXGene();
38
+ const loaderCsc = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.7/anndata-csc.zarr');
39
+ const cscMatrix = await loaderCsc.loadCellXGene();
40
+ expect(cscMatrix).toEqual(denseMatrix);
41
+ expect(csrMatrix).toEqual(denseMatrix);
42
+ });
43
+ });
44
+ describe('AnnData v0.8', () => {
45
+ it('loadFilteredGeneNames returns gene names', async () => {
46
+ const loader = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr');
47
+ const names = await loader.loadFilteredGeneNames();
48
+ expect(names).toEqual(Array.from({ length: 15 }).map((_, i) => `gene_${i}`));
49
+ });
50
+ it('loadGeneSelection matches across storage methods', async () => {
51
+ const selection = { selection: ['gene_1', 'gene_5'] };
52
+ const loaderCsr = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-csr.zarr');
53
+ const csrSelection = await loaderCsr.loadGeneSelection(selection);
54
+ const loaderDense = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr');
55
+ const denseSelection = await loaderDense.loadGeneSelection(selection);
56
+ const loaderCsc = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-csc.zarr');
57
+ const cscSelection = await loaderCsc.loadGeneSelection(selection);
58
+ expect(cscSelection).toEqual(denseSelection);
59
+ expect(csrSelection).toEqual(denseSelection);
60
+ });
61
+ it('loadCellXGene matches across storage methods', async () => {
62
+ const loaderCsr = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-csr.zarr');
63
+ const csrMatrix = await loaderCsr.loadCellXGene();
64
+ const loaderDense = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-dense.zarr');
65
+ const denseMatrix = await loaderDense.loadCellXGene();
66
+ const loaderCsc = createMatrixLoader('http://localhost:51204/@fixtures/zarr/anndata-0.8/anndata-csc.zarr');
67
+ const cscMatrix = await loaderCsc.loadCellXGene();
68
+ expect(cscMatrix).toEqual(denseMatrix);
69
+ expect(csrMatrix).toEqual(denseMatrix);
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,37 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsLabelsAnndataSchema, } from '@vitessce/vit-s';
2
+ /**
3
+ * Loader for string arrays located in anndata.zarr stores.
4
+ */
5
+ export default class ObsLabelsAnndataLoader extends AbstractTwoStepLoader {
6
+ constructor(dataSource, params) {
7
+ super(dataSource, params);
8
+ this.optionsSchema = obsLabelsAnndataSchema;
9
+ }
10
+ /**
11
+ * Class method for loading observation string labels.
12
+ * @returns {Promise} A promise for the array.
13
+ */
14
+ async loadLabels() {
15
+ const { path } = this.options;
16
+ if (this.labels) {
17
+ return this.labels;
18
+ }
19
+ if (!this.labels) {
20
+ // eslint-disable-next-line no-underscore-dangle
21
+ this.labels = await this.dataSource._loadColumn(path);
22
+ return this.labels;
23
+ }
24
+ this.labels = Promise.resolve(null);
25
+ return this.labels;
26
+ }
27
+ async load() {
28
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
29
+ if (superResult instanceof AbstractLoaderError) {
30
+ return Promise.reject(superResult);
31
+ }
32
+ return Promise.all([
33
+ this.dataSource.loadObsIndex(),
34
+ this.loadLabels(),
35
+ ]).then(([obsIndex, obsLabels]) => Promise.resolve(new LoaderResult({ obsIndex, obsLabels }, null)));
36
+ }
37
+ }
@@ -0,0 +1,36 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsLocationsAnndataSchema, } from '@vitessce/vit-s';
2
+ /**
3
+ * Loader for embedding arrays located in anndata.zarr stores.
4
+ */
5
+ export default class ObsLocationsAnndataLoader extends AbstractTwoStepLoader {
6
+ constructor(dataSource, params) {
7
+ super(dataSource, params);
8
+ this.optionsSchema = obsLocationsAnndataSchema;
9
+ }
10
+ /**
11
+ * Class method for loading embedding coordinates, such as those from UMAP or t-SNE.
12
+ * @returns {Promise} A promise for an array of columns.
13
+ */
14
+ async loadLocations() {
15
+ const { path, dims = [0, 1] } = this.options;
16
+ if (this.locations) {
17
+ return this.locations;
18
+ }
19
+ if (!this.locations) {
20
+ this.locations = await this.dataSource.loadNumericForDims(path, dims);
21
+ return this.locations;
22
+ }
23
+ this.locations = Promise.resolve(null);
24
+ return this.locations;
25
+ }
26
+ async load() {
27
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
28
+ if (superResult instanceof AbstractLoaderError) {
29
+ return Promise.reject(superResult);
30
+ }
31
+ return Promise.all([
32
+ this.dataSource.loadObsIndex(),
33
+ this.loadLocations(),
34
+ ]).then(([obsIndex, obsLocations]) => Promise.resolve(new LoaderResult({ obsIndex, obsLocations }, null)));
35
+ }
36
+ }
@@ -0,0 +1,44 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsSegmentationsAnndataSchema, } from '@vitessce/vit-s';
2
+ import { DEFAULT_CELLS_LAYER } from '@vitessce/gl';
3
+ /**
4
+ * Loader for embedding arrays located in anndata.zarr stores.
5
+ */
6
+ export default class ObsSegmentationsAnndataLoader extends AbstractTwoStepLoader {
7
+ constructor(dataSource, params) {
8
+ super(dataSource, params);
9
+ this.optionsSchema = obsSegmentationsAnndataSchema;
10
+ }
11
+ /**
12
+ * Class method for loading embedding coordinates, such as those from UMAP or t-SNE.
13
+ * @returns {Promise} A promise for an array of columns.
14
+ */
15
+ async loadSegmentations() {
16
+ const { path } = this.options;
17
+ if (this.segmentations) {
18
+ return this.segmentations;
19
+ }
20
+ if (!this.segmentations) {
21
+ this.segmentations = await this.dataSource.loadNumeric(path);
22
+ return this.segmentations;
23
+ }
24
+ this.segmentations = Promise.resolve(null);
25
+ return this.segmentations;
26
+ }
27
+ async load() {
28
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
29
+ if (superResult instanceof AbstractLoaderError) {
30
+ return Promise.reject(superResult);
31
+ }
32
+ const coordinationValues = {
33
+ spatialSegmentationLayer: DEFAULT_CELLS_LAYER,
34
+ };
35
+ return Promise.all([
36
+ this.dataSource.loadObsIndex(),
37
+ this.loadSegmentations(),
38
+ ]).then(([obsIndex, obsSegmentations]) => Promise.resolve(new LoaderResult({
39
+ obsIndex,
40
+ obsSegmentations,
41
+ obsSegmentationsType: 'polygon',
42
+ }, coordinationValues)));
43
+ }
44
+ }
@@ -0,0 +1,50 @@
1
+ import { LoaderResult, AbstractTwoStepLoader, AbstractLoaderError, obsSetsAnndataSchema, } from '@vitessce/vit-s';
2
+ import { initializeCellSetColor, treeToMembershipMap, dataToCellSetsTree, } from '@vitessce/sets';
3
+ /**
4
+ * Loader for converting zarr into the cell sets json schema.
5
+ */
6
+ export default class ObsSetsAnndataLoader extends AbstractTwoStepLoader {
7
+ constructor(dataSource, params) {
8
+ super(dataSource, params);
9
+ this.optionsSchema = obsSetsAnndataSchema;
10
+ }
11
+ loadCellSetIds() {
12
+ const { options } = this;
13
+ const cellSetZarrLocation = options.map(({ path }) => path);
14
+ return this.dataSource.loadObsColumns(cellSetZarrLocation);
15
+ }
16
+ loadCellSetScores() {
17
+ const { options } = this;
18
+ const cellSetScoreZarrLocation = options.map(option => option.scorePath || undefined);
19
+ return this.dataSource.loadObsColumns(cellSetScoreZarrLocation);
20
+ }
21
+ async load() {
22
+ const superResult = await super.load().catch(reason => Promise.resolve(reason));
23
+ if (superResult instanceof AbstractLoaderError) {
24
+ return Promise.reject(superResult);
25
+ }
26
+ if (!this.cachedResult) {
27
+ const { options } = this;
28
+ this.cachedResult = Promise.all([
29
+ this.dataSource.loadObsIndex(),
30
+ this.loadCellSetIds(),
31
+ this.loadCellSetScores(),
32
+ ]).then(data => [data[0], dataToCellSetsTree(data, options)]);
33
+ }
34
+ const [obsIndex, obsSets] = await this.cachedResult;
35
+ const obsSetsMembership = treeToMembershipMap(obsSets);
36
+ const coordinationValues = {};
37
+ const { tree } = obsSets;
38
+ const newAutoSetSelectionParentName = tree[0].name;
39
+ // Create a list of set paths to initally select.
40
+ const newAutoSetSelections = tree[0].children.map(node => [
41
+ newAutoSetSelectionParentName,
42
+ node.name,
43
+ ]);
44
+ // Create a list of cell set objects with color mappings.
45
+ const newAutoSetColors = initializeCellSetColor(obsSets, []);
46
+ coordinationValues.obsSetSelection = newAutoSetSelections;
47
+ coordinationValues.obsSetColor = newAutoSetColors;
48
+ return Promise.resolve(new LoaderResult({ obsIndex, obsSets, obsSetsMembership }, null, coordinationValues));
49
+ }
50
+ }
@@ -0,0 +1,7 @@
1
+ export { default as ObsFeatureMatrixAnndataLoader } from './ObsFeatureMatrixAnndataLoader';
2
+ export { default as ObsEmbeddingAnndataLoader } from './ObsEmbeddingAnndataLoader';
3
+ export { default as ObsLocationsAnndataLoader } from './ObsLocationsAnndataLoader';
4
+ export { default as ObsSegmentationsAnndataLoader } from './ObsSegmentationsAnndataLoader';
5
+ export { default as ObsSetsAnndataLoader } from './ObsSetsAnndataLoader';
6
+ export { default as ObsLabelsAnndataLoader } from './ObsLabelsAnndataLoader';
7
+ export { default as FeatureLabelsAnndataLoader } from './FeatureLabelsAnndataLoader';
@@ -0,0 +1,15 @@
1
+ import { AbstractTwoStepLoader, LoaderResult } from '@vitessce/vit-s';
2
+ export default class GenomicProfilesZarrLoader extends AbstractTwoStepLoader {
3
+ loadAttrs() {
4
+ if (this.attrs) {
5
+ return this.attrs;
6
+ }
7
+ this.attrs = this.dataSource.getJson('.zattrs');
8
+ return this.attrs;
9
+ }
10
+ load() {
11
+ const { url } = this;
12
+ return this.loadAttrs()
13
+ .then(attrs => Promise.resolve(new LoaderResult(attrs, url)));
14
+ }
15
+ }
@@ -0,0 +1 @@
1
+ export { default as GenomicProfilesZarrLoader } from './GenomicProfilesZarrLoader';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { default as AnnDataSource } from './AnnDataSource';
2
+ export { default as ZarrDataSource } from './ZarrDataSource';
3
+ export * from './matrix-loaders/index';
4
+ export * from './anndata-loaders/index';
5
+ export * from './ome-loaders/index';
6
+ export * from './genomic-loaders/index';
@@ -0,0 +1,30 @@
1
+ import { openArray } from 'zarr';
2
+ import { AbstractTwoStepLoader, LoaderResult } from '@vitessce/vit-s';
3
+ export default class MatrixZarrAsObsFeatureMatrixLoader extends AbstractTwoStepLoader {
4
+ async loadAttrs() {
5
+ if (this.attrs) {
6
+ return this.attrs;
7
+ }
8
+ this.attrs = {
9
+ data: await this.dataSource.getJson('.zattrs'),
10
+ url: null,
11
+ };
12
+ return this.attrs;
13
+ }
14
+ loadArr() {
15
+ const { store } = this.dataSource;
16
+ if (this.arr) {
17
+ return this.arr;
18
+ }
19
+ this.arr = openArray({ store, path: '/', mode: 'r' }).then(z => new Promise((resolve) => {
20
+ z.getRaw([null, null])
21
+ .then(resolve);
22
+ }));
23
+ return this.arr;
24
+ }
25
+ load() {
26
+ return Promise
27
+ .all([this.loadAttrs(), this.loadArr()])
28
+ .then(([attrs, arr]) => Promise.resolve(new LoaderResult({ obsIndex: attrs.data.rows, featureIndex: attrs.data.cols, obsFeatureMatrix: arr }, null)));
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export { default as MatrixZarrAsObsFeatureMatrixLoader } from './MatrixZarrAsObsFeatureMatrix';
@@ -0,0 +1,61 @@
1
+ import { viv, initializeRasterLayersAndChannels } from '@vitessce/gl';
2
+ import { AbstractLoaderError, LoaderResult, AbstractTwoStepLoader } from '@vitessce/vit-s';
3
+ function hexToRgb(hex) {
4
+ const result = /^#?([A-F\d]{2})([A-F\d]{2})([A-F\d]{2})$/i.exec(hex);
5
+ return [
6
+ parseInt(result[1].toLowerCase(), 16),
7
+ parseInt(result[2].toLowerCase(), 16),
8
+ parseInt(result[3].toLowerCase(), 16),
9
+ ];
10
+ }
11
+ export default class OmeZarrLoader extends AbstractTwoStepLoader {
12
+ async load() {
13
+ const payload = await this.dataSource.getJson('.zattrs').catch(reason => Promise.resolve(reason));
14
+ if (payload instanceof AbstractLoaderError) {
15
+ return Promise.reject(payload);
16
+ }
17
+ const loader = await viv.loadOmeZarr(this.url, { fetchOptions: this.requestInit, type: 'multiscales' });
18
+ const { metadata, data } = loader;
19
+ const { omero } = metadata;
20
+ if (!omero) {
21
+ console.error('Path for image not valid');
22
+ return Promise.reject(payload);
23
+ }
24
+ const { rdefs, channels } = omero;
25
+ const t = rdefs.defaultT ?? 0;
26
+ const z = rdefs.defaultZ ?? 0;
27
+ const filterSelection = (sel) => {
28
+ // Remove selection keys for which there is no dimension.
29
+ if (data.length > 0) {
30
+ const nextSel = {};
31
+ // eslint-disable-next-line prefer-destructuring
32
+ const labels = data[0].labels;
33
+ Object.keys(sel).forEach((key) => {
34
+ if (labels.includes(key)) {
35
+ nextSel[key] = sel[key];
36
+ }
37
+ });
38
+ return nextSel;
39
+ }
40
+ return sel;
41
+ };
42
+ const imagesWithLoaderCreators = [
43
+ {
44
+ name: omero.name || 'Image',
45
+ channels: channels.map((channel, i) => ({
46
+ selection: filterSelection({ z, t, c: i }),
47
+ slider: [channel.window.start, channel.window.end],
48
+ color: hexToRgb(channel.color),
49
+ })),
50
+ loaderCreator: async () => ({ ...loader, channels: channels.map(c => c.label) }),
51
+ },
52
+ ];
53
+ // TODO: use options for initial selection of channels
54
+ // which omit domain/slider ranges.
55
+ const [autoImageLayers, imageLayerLoaders, imageLayerMeta,] = await initializeRasterLayersAndChannels(imagesWithLoaderCreators, undefined);
56
+ const coordinationValues = {
57
+ spatialImageLayer: autoImageLayers,
58
+ };
59
+ return Promise.resolve(new LoaderResult({ image: { loaders: imageLayerLoaders, meta: imageLayerMeta } }, [], coordinationValues));
60
+ }
61
+ }
@@ -0,0 +1 @@
1
+ export { default as OmeZarrLoader } from './OmeZarrLoader';
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@vitessce/zarr",
3
+ "version": "2.0.0-beta.0",
4
+ "author": "Gehlenborg Lab",
5
+ "homepage": "http://vitessce.io",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vitessce/vitessce.git"
9
+ },
10
+ "license": "MIT",
11
+ "main": "dist/index.js",
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "dependencies": {
16
+ "@vitessce/constants-internal": "2.0.0-beta.0",
17
+ "@vitessce/gl": "2.0.0-beta.0",
18
+ "@vitessce/sets": "2.0.0-beta.0",
19
+ "@vitessce/utils": "2.0.0-beta.0",
20
+ "@vitessce/vit-s": "2.0.0-beta.0",
21
+ "d3-array": "^2.4.0",
22
+ "lodash": "^4.17.21",
23
+ "zarr": "0.5.1"
24
+ },
25
+ "scripts": {
26
+ "start": "tsc --watch",
27
+ "build": "tsc",
28
+ "test": "pnpm exec vitest --run -r ../../../ --dir ."
29
+ }
30
+ }