@vitessce/zarr 3.4.12 → 3.4.14

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.
@@ -1,8 +1,46 @@
1
1
  // @ts-check
2
2
  /* eslint-disable no-underscore-dangle */
3
+ /* eslint-disable import/no-unresolved */
4
+ /* eslint-disable no-undef */
5
+ import dynamicImportPolyfill from 'dynamic-import-polyfill';
6
+ import { tableFromIPC } from 'apache-arrow';
7
+ import WKB from 'ol/format/WKB.js';
3
8
  import AnnDataSource from './AnnDataSource.js';
9
+ import { basename } from './utils.js';
4
10
 
5
11
  /** @import { DataSourceParams } from '@vitessce/types' */
12
+ /** @import { TypedArray as ZarrTypedArray, Chunk } from '@zarrita/core' */
13
+
14
+ // Initialize the dynamic __import__() function.
15
+ if (dynamicImportPolyfill) {
16
+ dynamicImportPolyfill.initialize();
17
+ }
18
+
19
+ async function getReadParquet() {
20
+ // Reference: https://observablehq.com/@kylebarron/geoparquet-on-the-web
21
+ // TODO: host somewhere we control, like cdn.vitessce.io?
22
+ // @ts-ignore
23
+ const module = await __import__('https://unpkg.com/parquet-wasm@0.6.1/esm/parquet_wasm.js');
24
+ await module.default();
25
+ // We cannot use regulary dynamic import here because it breaks NextJS builds
26
+ // due to pointing to a remote URL.
27
+ // I could not figure out a NextJS webpack configuration to resolve it.
28
+ // The following becomes inlined by Vite in library mode
29
+ // eliminating the benefit of dynamic import.
30
+ // Reference: https://github.com/vitejs/vite/issues/4454
31
+ // const responsePromise = await fetch(
32
+ // new URL('parquet-wasm/esm/parquet_wasm_bg.wasm', import.meta.url).href
33
+ // );
34
+ // const responsePromise = await fetch('https://unpkg.com/parquet-wasm@0.6.1/esm/parquet_wasm_bg.wasm');
35
+ // const wasmBuffer = await responsePromise.arrayBuffer();
36
+ // module.initSync(wasmBuffer);
37
+ // Another issue is that when we import parquet-wasm JS from node_modules,
38
+ // running module.default there is a MIME type issue because the Vite dev
39
+ // server does not serve the .wasm with a MIME type of application/wasm.
40
+ // I can't seem to get a custom Vite plugin that sets the MIME type in
41
+ // request headers to work.
42
+ return module.readParquet;
43
+ }
6
44
 
7
45
  // If the array path starts with table/something/rest
8
46
  // capture table/something.
@@ -41,6 +79,24 @@ export function getVarPath(arrPath) {
41
79
  return `${getShapesPrefix(arrPath)}var`;
42
80
  }
43
81
 
82
+ /**
83
+ *
84
+ * @param {string|undefined} arrPath
85
+ * @returns
86
+ */
87
+ export function getParquetPath(arrPath) {
88
+ return `${getShapesPrefix(arrPath)}shapes.parquet`;
89
+ }
90
+
91
+ /**
92
+ *
93
+ * @param {string|undefined} arrPath
94
+ * @returns
95
+ */
96
+ export function getAttrsPath(arrPath) {
97
+ return `${getShapesPrefix(arrPath)}.zattrs`;
98
+ }
99
+
44
100
 
45
101
  export default class SpatialDataShapesSource extends AnnDataSource {
46
102
  /**
@@ -66,6 +122,45 @@ export default class SpatialDataShapesSource extends AnnDataSource {
66
122
  return this._loadDict(`${tablePath}/uns/spatialdata_attrs`, ['instance_key', 'region', 'region_key']);
67
123
  }
68
124
 
125
+ /**
126
+ *
127
+ * @param {string} path A path to within shapes.
128
+ * @returns {Promise<"0.1"|"0.2">} The format version.
129
+ */
130
+ async getFormatVersion(path) {
131
+ const zattrs = await this.getJson(getAttrsPath(path));
132
+ const formatVersion = zattrs.spatialdata_attrs.version;
133
+ if (!(formatVersion === '0.1' || formatVersion === '0.2')) {
134
+ throw new Error(
135
+ `Unexpected version for shapes spatialdata_attrs: ${formatVersion}`,
136
+ );
137
+ }
138
+ return formatVersion;
139
+ }
140
+
141
+ /**
142
+ *
143
+ * @param {string} path A path to an array within shapes.
144
+ * @returns
145
+ */
146
+ async loadParquetTable(path) {
147
+ if (this.parquetTable) {
148
+ // Return cached table if present.
149
+ return this.parquetTable;
150
+ }
151
+ const readParquet = await getReadParquet();
152
+ const parquetPath = getParquetPath(path);
153
+ const parquetBytes = await this.storeRoot.store.get(`/${parquetPath}`);
154
+ if (!parquetBytes) {
155
+ throw new Error('Failed to load parquet data from store.');
156
+ }
157
+ const wasmTable = readParquet(parquetBytes);
158
+ // TODO: use streaming?
159
+ const arrowTable = tableFromIPC(wasmTable.intoIPCStream());
160
+ this.parquetTable = arrowTable;
161
+ return this.parquetTable;
162
+ }
163
+
69
164
  /**
70
165
  * Class method for loading the obs index.
71
166
  * @param {string|undefined} path
@@ -82,7 +177,6 @@ export default class SpatialDataShapesSource extends AnnDataSource {
82
177
  const obsPath = `${tablePath}/obs`;
83
178
  const { _index } = await this.getJson(`${obsPath}/.zattrs`);
84
179
  indexPath = `${obsPath}/${_index}`;
85
-
86
180
  const {
87
181
  instance_key: instanceKey,
88
182
  // TODO: filter table index by region and element type.
@@ -90,16 +184,84 @@ export default class SpatialDataShapesSource extends AnnDataSource {
90
184
  // region,
91
185
  } = await this.loadSpatialDataAttrs(tablePath);
92
186
 
93
-
94
187
  indexPath = `${obsPath}/${instanceKey}`;
95
188
  }
96
189
  if (indexPath in this.obsIndices) {
97
190
  return this.obsIndices[indexPath];
98
191
  }
192
+ // TODO: support loading from parquet if no tablePath was provided.
99
193
  this.obsIndices[indexPath] = this._loadColumn(indexPath);
100
194
  return this.obsIndices[indexPath];
101
195
  }
102
196
 
197
+ /**
198
+ * Class method for loading general numeric arrays.
199
+ * @param {string} path A string like obsm.X_pca.
200
+ * @returns {Promise<Chunk<any>>} A promise for a zarr array containing the data.
201
+ */
202
+ async loadNumeric(path) {
203
+ const formatVersion = await this.getFormatVersion(path);
204
+ if (formatVersion === '0.1') {
205
+ return super.loadNumeric(path);
206
+ }
207
+ const arrowTable = await this.loadParquetTable(path);
208
+ const columnArr = arrowTable.getChild(basename(path))?.toArray();
209
+ return {
210
+ shape: [columnArr.length],
211
+ // TODO: support other kinds of TypedArrays via @vitessce/arrow-utils.
212
+ data: new Float32Array(columnArr),
213
+ stride: [1],
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Class method for loading specific columns of numeric arrays.
219
+ * @param {string} path A string like obsm.X_pca.
220
+ * @param {[number, number]} dims The column indices to load.
221
+ * @returns {Promise<{
222
+ * data: [ZarrTypedArray<any>, ZarrTypedArray<any>],
223
+ * shape: [number, number],
224
+ * }>} A promise for a zarr array containing the data.
225
+ */
226
+ async loadNumericForDims(path, dims) {
227
+ const formatVersion = await this.getFormatVersion(path);
228
+ if (formatVersion === '0.1') {
229
+ return super.loadNumericForDims(path, dims);
230
+ }
231
+ let columnName = basename(path);
232
+ if (columnName === 'coords') {
233
+ // The "geometry" column was previously called "coords" in version 0.1.
234
+ columnName = 'geometry';
235
+ }
236
+ const arrowTable = await this.loadParquetTable(path);
237
+ if (columnName === 'geometry' && dims[0] === 0 && dims[1] === 1) {
238
+ const geometryColumn = arrowTable.getChild(columnName);
239
+ if (!geometryColumn) {
240
+ throw new Error(`Column ${columnName} not found in parquet table`);
241
+ }
242
+ if (geometryColumn.type.toString() !== 'Binary') {
243
+ throw new Error(`Expected geometry column to have Binary type (WKB) but got ${geometryColumn.type.toString()}`);
244
+ }
245
+ // From GeoPandas.to_parquet docs:
246
+ // "By default, all geometry columns present are serialized to WKB format in the file"
247
+ // Reference: https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.to_parquet.html
248
+ // TODO: support geoarrow serialization schemes in addition to WKB.
249
+ const wkb = new WKB();
250
+ const points = geometryColumn.toArray()
251
+ // @ts-ignore
252
+ .map((/** @type {Uint8Array} */ geom) => wkb.readGeometry(geom).getFlatCoordinates());
253
+ return {
254
+ shape: [2, points.length],
255
+ data: [
256
+ new Float32Array(points.map((/** @type {[number, number]} */ p) => p[0])),
257
+ new Float32Array(points.map((/** @type {[number, number]} */ p) => p[1])),
258
+ ],
259
+ };
260
+ }
261
+ throw new Error('Unexpected column name for loading 2D array from parquet, currently only geometry is supported');
262
+ }
263
+
264
+
103
265
  /**
104
266
  * Class method for loading the var index.
105
267
  * @param {string|undefined} path
@@ -0,0 +1 @@
1
+ declare module 'dynamic-import-polyfill';
@@ -125,7 +125,7 @@ export default class OmeZarrLoader extends AbstractTwoStepLoader {
125
125
  channelLabels = channels.map(c => c.label);
126
126
  }
127
127
  } else {
128
- const { rdefs, channels } = omero;
128
+ const { rdefs = {}, channels } = omero;
129
129
  if (typeof rdefs.defaultT === 'number') {
130
130
  initialTargetT = rdefs.defaultT;
131
131
  }
@@ -134,8 +134,8 @@ export default class OmeZarrLoader extends AbstractTwoStepLoader {
134
134
  }
135
135
  channelObjects = channels.map((channel, i) => ({
136
136
  selection: filterSelection({ z: initialTargetZ, t: initialTargetT, c: i }),
137
- slider: [channel.window.start, channel.window.end],
138
- color: hexToRgb(channel.color),
137
+ slider: channel.window ? ([channel.window.start, channel.window.end]) : [0, 255],
138
+ color: channel.color ? hexToRgb(channel.color) : [255, 255, 255],
139
139
  }));
140
140
  channelLabels = channels.map(c => c.label);
141
141
  }
@@ -2,6 +2,11 @@ import {
2
2
  LoaderResult, AbstractTwoStepLoader, AbstractLoaderError,
3
3
  } from '@vitessce/vit-s';
4
4
  import { CoordinationLevel as CL } from '@vitessce/config';
5
+ import {
6
+ normalizeCoordinateTransformations,
7
+ coordinateTransformationsToMatrix,
8
+ } from '@vitessce/spatial-utils';
9
+ import { math } from '@vitessce/gl';
5
10
 
6
11
  function getCoordsPath(path) {
7
12
  return `${path}/coords`;
@@ -11,21 +16,146 @@ function getRadiusPath(path) {
11
16
  return `${path}/radius`;
12
17
  }
13
18
 
19
+ function getAttrsPath(path) {
20
+ return `${path}/.zattrs`;
21
+ }
22
+
23
+ const DEFAULT_AXES = [
24
+ {
25
+ name: 'x',
26
+ type: 'space',
27
+ unit: 'unit',
28
+ },
29
+ {
30
+ name: 'y',
31
+ type: 'space',
32
+ unit: 'unit',
33
+ },
34
+ ];
35
+ const DEFAULT_COORDINATE_TRANSFORMATIONS = [
36
+ {
37
+ input: {
38
+ axes: [
39
+ {
40
+ name: 'x',
41
+ type: 'space',
42
+ unit: 'unit',
43
+ },
44
+ {
45
+ name: 'y',
46
+ type: 'space',
47
+ unit: 'unit',
48
+ },
49
+ ],
50
+ name: 'xy',
51
+ },
52
+ output: {
53
+ axes: [
54
+ {
55
+ name: 'x',
56
+ type: 'space',
57
+ unit: 'unit',
58
+ },
59
+ {
60
+ name: 'y',
61
+ type: 'space',
62
+ unit: 'unit',
63
+ },
64
+ ],
65
+ name: 'global',
66
+ },
67
+ type: 'identity',
68
+ },
69
+ ];
70
+
71
+
14
72
  /**
15
73
  * Loader for embedding arrays located in anndata.zarr stores.
16
74
  */
17
75
  export default class SpatialDataObsSpotsLoader extends AbstractTwoStepLoader {
76
+ async loadModelMatrix() {
77
+ const { path, coordinateSystem = 'global' } = this.options;
78
+ if (this.modelMatrix) {
79
+ return this.modelMatrix;
80
+ }
81
+ // Load the transformations from the .zattrs for the shapes
82
+ const zattrs = await this.dataSource.getJson(getAttrsPath(path));
83
+
84
+ const {
85
+ 'encoding-type': encodingType,
86
+ spatialdata_attrs: {
87
+ geos = {},
88
+ version: attrsVersion,
89
+ },
90
+ } = zattrs;
91
+ const hasExpectedAttrs = (
92
+ encodingType === 'ngff:shapes'
93
+ && ((geos?.name === 'POINT'
94
+ && geos?.type === 0
95
+ && attrsVersion === '0.1') || attrsVersion === '0.2')
96
+ );
97
+ if (!hasExpectedAttrs) {
98
+ throw new AbstractLoaderError(
99
+ 'Unexpected values for encoding-type or spatialdata_attrs for SpatialData shapes',
100
+ );
101
+ }
102
+ // Convert the coordinate transformations to a modelMatrix.
103
+ // For attrsVersion === "0.1", we can assume that there is always a
104
+ // coordinate system which maps from the input "xy" to the specified
105
+ // output coordinate system.
106
+
107
+ // TODO: In a future version of the shapes transformation on-disk format,
108
+ // the SpatialData team plans to relax this so that it will
109
+ // become necessary to create a full tree
110
+ // of coordinate transformations, and traverse the tree from
111
+ // the node corresponding to the output coordinate system of interest
112
+ // back to the root node, applying each transformation along the way.
113
+ const coordinateTransformationsFromFile = (
114
+ zattrs?.coordinateTransformations || DEFAULT_COORDINATE_TRANSFORMATIONS
115
+ ).filter(({ input: { name: inputName }, output: { name: outputName } }) => (
116
+ inputName === 'xy' && outputName === coordinateSystem
117
+ ));
118
+ const axes = zattrs?.axes || DEFAULT_AXES;
119
+ // This new spec is very flexible,
120
+ // so here we will attempt to convert it back to the old spec.
121
+ // TODO: do the reverse, convert old spec to new spec
122
+ const normCoordinateTransformationsFromFile = normalizeCoordinateTransformations(
123
+ coordinateTransformationsFromFile, null,
124
+ );
125
+ const transformMatrixFromFile = coordinateTransformationsToMatrix(
126
+ normCoordinateTransformationsFromFile, axes,
127
+ );
128
+ this.modelMatrix = transformMatrixFromFile;
129
+ return this.modelMatrix;
130
+ }
131
+
18
132
  /**
19
133
  * Class method for loading embedding coordinates, such as those from UMAP or t-SNE.
20
134
  * @returns {Promise} A promise for an array of columns.
21
135
  */
22
136
  async loadSpots() {
23
- const { path, dims = [0, 1] } = this.options;
137
+ const { path } = this.options;
138
+
24
139
  if (this.locations) {
25
140
  return this.locations;
26
141
  }
27
142
  if (!this.locations) {
28
- this.locations = await this.dataSource.loadNumericForDims(getCoordsPath(path), dims);
143
+ const modelMatrix = await this.loadModelMatrix();
144
+ this.locations = await this.dataSource.loadNumericForDims(getCoordsPath(path), [0, 1]);
145
+
146
+ // Apply transformation matrix to the coordinates
147
+ // TODO: instead of applying here, pass matrix all the way down to WebGL shader
148
+ // (or DeckGL layer)
149
+ for (let i = 0; i < this.locations.shape[1]; i++) {
150
+ const xCoord = this.locations.data[0][i];
151
+ const yCoord = this.locations.data[1][i];
152
+ const transformed = new math.Vector2(xCoord, yCoord)
153
+ .transformAsPoint(modelMatrix);
154
+ // eslint-disable-next-line prefer-destructuring
155
+ this.locations.data[0][i] = transformed[0];
156
+ // eslint-disable-next-line prefer-destructuring
157
+ this.locations.data[1][i] = transformed[1];
158
+ }
29
159
  return this.locations;
30
160
  }
31
161
  this.locations = Promise.resolve(null);
@@ -38,7 +168,18 @@ export default class SpatialDataObsSpotsLoader extends AbstractTwoStepLoader {
38
168
  return this.radius;
39
169
  }
40
170
  if (!this.radius) {
171
+ const modelMatrix = await this.loadModelMatrix();
41
172
  this.radius = await this.dataSource.loadNumeric(getRadiusPath(path));
173
+ const scaleFactors = modelMatrix.getScale();
174
+ const xScaleFactor = scaleFactors[0];
175
+ const yScaleFactor = scaleFactors[1];
176
+ if (xScaleFactor !== yScaleFactor) {
177
+ console.warn('Using x-axis scale factor for transformation of obsSpots, but x and y scale factors are not equal');
178
+ }
179
+ // Apply the scale factor to the radius column
180
+ for (let i = 0; i < this.radius.shape[0]; i++) {
181
+ this.radius.data[i] *= xScaleFactor;
182
+ }
42
183
  return this.radius;
43
184
  }
44
185
  this.radius = Promise.resolve(null);