@vitessce/zarr 3.4.12 → 3.5.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.
Files changed (49) hide show
  1. package/dist/{deflate-0a2495db.js → deflate-e0025ccc.js} +1 -1
  2. package/dist/{index-b9ca46db.js → index-a1019708.js} +16311 -758
  3. package/dist/index.js +1 -1
  4. package/dist/{jpeg-7300e0c0.js → jpeg-54659e84.js} +1 -1
  5. package/dist/{lerc-98ac4137.js → lerc-4e84f820.js} +1 -1
  6. package/dist/{lzw-7e525855.js → lzw-40048bd4.js} +1 -1
  7. package/dist/{packbits-7dbd57b5.js → packbits-bf37d3f7.js} +1 -1
  8. package/dist/{raw-269a3143.js → raw-f9274a13.js} +1 -1
  9. package/dist/{webimage-8f0f4c44.js → webimage-88b1773f.js} +1 -1
  10. package/dist-tsc/AnnDataSource.test.js +1 -1
  11. package/dist-tsc/SpatialDataShapesSource.d.ts +25 -0
  12. package/dist-tsc/SpatialDataShapesSource.d.ts.map +1 -1
  13. package/dist-tsc/SpatialDataShapesSource.js +148 -0
  14. package/dist-tsc/anndata-loaders/ObsEmbeddingAnndataLoader.test.js +1 -1
  15. package/dist-tsc/json-fixtures/anndata-0.10/anndata-csc.json +1 -1
  16. package/dist-tsc/json-fixtures/anndata-0.10/anndata-csr.adata.json +1 -1
  17. package/dist-tsc/json-fixtures/anndata-0.10/anndata-dense.json +1 -1
  18. package/dist-tsc/json-fixtures/anndata-0.7/anndata-csc.json +1 -1
  19. package/dist-tsc/json-fixtures/anndata-0.7/anndata-csr.json +1 -1
  20. package/dist-tsc/json-fixtures/anndata-0.7/anndata-dense.json +1 -1
  21. package/dist-tsc/json-fixtures/anndata-0.8/anndata-csc.json +1 -1
  22. package/dist-tsc/json-fixtures/anndata-0.8/anndata-csr.adata.json +1 -1
  23. package/dist-tsc/json-fixtures/anndata-0.8/anndata-dense.json +1 -1
  24. package/dist-tsc/json-fixtures/anndata-0.9/anndata-csc.json +1 -1
  25. package/dist-tsc/json-fixtures/anndata-0.9/anndata-csr.adata.json +1 -1
  26. package/dist-tsc/json-fixtures/anndata-0.9/anndata-dense.json +1 -1
  27. package/dist-tsc/ome-loaders/OmeZarrLoader.js +3 -3
  28. package/dist-tsc/spatialdata-loaders/SpatialDataObsSpotsLoader.d.ts +3 -0
  29. package/dist-tsc/spatialdata-loaders/SpatialDataObsSpotsLoader.d.ts.map +1 -1
  30. package/dist-tsc/spatialdata-loaders/SpatialDataObsSpotsLoader.js +114 -2
  31. package/package.json +15 -12
  32. package/src/AnnDataSource.test.js +1 -1
  33. package/src/SpatialDataShapesSource.js +158 -2
  34. package/src/anndata-loaders/ObsEmbeddingAnndataLoader.test.js +1 -1
  35. package/src/json-fixtures/anndata-0.10/anndata-csc.json +1 -1
  36. package/src/json-fixtures/anndata-0.10/anndata-csr.adata.json +1 -1
  37. package/src/json-fixtures/anndata-0.10/anndata-dense.json +1 -1
  38. package/src/json-fixtures/anndata-0.7/anndata-csc.json +1 -1
  39. package/src/json-fixtures/anndata-0.7/anndata-csr.json +1 -1
  40. package/src/json-fixtures/anndata-0.7/anndata-dense.json +1 -1
  41. package/src/json-fixtures/anndata-0.8/anndata-csc.json +1 -1
  42. package/src/json-fixtures/anndata-0.8/anndata-csr.adata.json +1 -1
  43. package/src/json-fixtures/anndata-0.8/anndata-dense.json +1 -1
  44. package/src/json-fixtures/anndata-0.9/anndata-csc.json +1 -1
  45. package/src/json-fixtures/anndata-0.9/anndata-csr.adata.json +1 -1
  46. package/src/json-fixtures/anndata-0.9/anndata-dense.json +1 -1
  47. package/src/missing-types.d.ts +1 -0
  48. package/src/ome-loaders/OmeZarrLoader.js +3 -3
  49. package/src/spatialdata-loaders/SpatialDataObsSpotsLoader.js +143 -2
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitessce/zarr",
3
- "version": "3.4.12",
4
- "author": "Gehlenborg Lab",
3
+ "version": "3.5.0",
4
+ "author": "HIDIVE Lab at HMS",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
7
7
  "type": "git",
@@ -19,21 +19,24 @@
19
19
  "d3-array": "^2.4.0",
20
20
  "lodash-es": "^4.17.21",
21
21
  "zarrita": "0.4.0-next.16",
22
- "@vitessce/constants-internal": "3.4.12",
23
- "@vitessce/gl": "3.4.12",
24
- "@vitessce/sets-utils": "3.4.12",
25
- "@vitessce/spatial-utils": "3.4.12",
26
- "@vitessce/image-utils": "3.4.12",
27
- "@vitessce/utils": "3.4.12",
28
- "@vitessce/vit-s": "3.4.12",
29
- "@vitessce/zarr-utils": "3.4.12",
30
- "@vitessce/config": "3.4.12"
22
+ "apache-arrow": "^17.0.0",
23
+ "parquet-wasm": "^0.6.1",
24
+ "ol": "^10.2.1",
25
+ "@vitessce/constants-internal": "3.5.0",
26
+ "@vitessce/gl": "3.5.0",
27
+ "@vitessce/sets-utils": "3.5.0",
28
+ "@vitessce/spatial-utils": "3.5.0",
29
+ "@vitessce/image-utils": "3.5.0",
30
+ "@vitessce/utils": "3.5.0",
31
+ "@vitessce/vit-s": "3.5.0",
32
+ "@vitessce/zarr-utils": "3.5.0",
33
+ "@vitessce/config": "3.5.0"
31
34
  },
32
35
  "devDependencies": {
33
36
  "@zarrita/core": "0.1.0-next.14",
34
37
  "@zarrita/storage": "0.1.0-next.6",
35
38
  "@zarrita/typedarray": "0.1.0-next.3",
36
- "@vitessce/types": "3.4.12"
39
+ "@vitessce/types": "3.5.0"
37
40
  },
38
41
  "scripts": {
39
42
  "bundle": "pnpm exec vite build -c ../../../scripts/vite.config.js",
@@ -40,7 +40,7 @@ describe('sources/AnnDataSource', () => {
40
40
  store: createStoreFromMapContents(fixture),
41
41
  });
42
42
  const names = await dataSource.loadObsIndex();
43
- expect(names).toEqual(['CTG', 'GCA', 'CTG']);
43
+ expect(names).toEqual(['CTG', 'GCA', 'ACG']);
44
44
  });
45
45
  });
46
46
  });
@@ -1,8 +1,40 @@
1
1
  // @ts-check
2
2
  /* eslint-disable no-underscore-dangle */
3
+ /* eslint-disable import/no-unresolved */
4
+ /* eslint-disable no-undef */
5
+ import { tableFromIPC } from 'apache-arrow';
6
+ import WKB from 'ol/format/WKB.js';
3
7
  import AnnDataSource from './AnnDataSource.js';
8
+ import { basename } from './utils.js';
4
9
 
5
10
  /** @import { DataSourceParams } from '@vitessce/types' */
11
+ /** @import { TypedArray as ZarrTypedArray, Chunk } from '@zarrita/core' */
12
+
13
+ async function getReadParquet() {
14
+ // Reference: https://observablehq.com/@kylebarron/geoparquet-on-the-web
15
+ // TODO: host somewhere we control, like cdn.vitessce.io?
16
+ // @ts-ignore
17
+ const module = await import(/* webpackIgnore: true */ 'https://unpkg.com/parquet-wasm@0.6.1/esm/parquet_wasm.js');
18
+ await module.default();
19
+ // We cannot use regulary dynamic import here because it breaks NextJS builds
20
+ // due to pointing to a remote URL.
21
+ // I could not figure out a NextJS webpack configuration to resolve it.
22
+ // The following becomes inlined by Vite in library mode
23
+ // eliminating the benefit of dynamic import.
24
+ // Reference: https://github.com/vitejs/vite/issues/4454
25
+ // const responsePromise = await fetch(
26
+ // new URL('parquet-wasm/esm/parquet_wasm_bg.wasm', import.meta.url).href
27
+ // );
28
+ // const responsePromise = await fetch('https://unpkg.com/parquet-wasm@0.6.1/esm/parquet_wasm_bg.wasm');
29
+ // const wasmBuffer = await responsePromise.arrayBuffer();
30
+ // module.initSync(wasmBuffer);
31
+ // Another issue is that when we import parquet-wasm JS from node_modules,
32
+ // running module.default there is a MIME type issue because the Vite dev
33
+ // server does not serve the .wasm with a MIME type of application/wasm.
34
+ // I can't seem to get a custom Vite plugin that sets the MIME type in
35
+ // request headers to work.
36
+ return module.readParquet;
37
+ }
6
38
 
7
39
  // If the array path starts with table/something/rest
8
40
  // capture table/something.
@@ -41,6 +73,24 @@ export function getVarPath(arrPath) {
41
73
  return `${getShapesPrefix(arrPath)}var`;
42
74
  }
43
75
 
76
+ /**
77
+ *
78
+ * @param {string|undefined} arrPath
79
+ * @returns
80
+ */
81
+ export function getParquetPath(arrPath) {
82
+ return `${getShapesPrefix(arrPath)}shapes.parquet`;
83
+ }
84
+
85
+ /**
86
+ *
87
+ * @param {string|undefined} arrPath
88
+ * @returns
89
+ */
90
+ export function getAttrsPath(arrPath) {
91
+ return `${getShapesPrefix(arrPath)}.zattrs`;
92
+ }
93
+
44
94
 
45
95
  export default class SpatialDataShapesSource extends AnnDataSource {
46
96
  /**
@@ -66,6 +116,45 @@ export default class SpatialDataShapesSource extends AnnDataSource {
66
116
  return this._loadDict(`${tablePath}/uns/spatialdata_attrs`, ['instance_key', 'region', 'region_key']);
67
117
  }
68
118
 
119
+ /**
120
+ *
121
+ * @param {string} path A path to within shapes.
122
+ * @returns {Promise<"0.1"|"0.2">} The format version.
123
+ */
124
+ async getFormatVersion(path) {
125
+ const zattrs = await this.getJson(getAttrsPath(path));
126
+ const formatVersion = zattrs.spatialdata_attrs.version;
127
+ if (!(formatVersion === '0.1' || formatVersion === '0.2')) {
128
+ throw new Error(
129
+ `Unexpected version for shapes spatialdata_attrs: ${formatVersion}`,
130
+ );
131
+ }
132
+ return formatVersion;
133
+ }
134
+
135
+ /**
136
+ *
137
+ * @param {string} path A path to an array within shapes.
138
+ * @returns
139
+ */
140
+ async loadParquetTable(path) {
141
+ if (this.parquetTable) {
142
+ // Return cached table if present.
143
+ return this.parquetTable;
144
+ }
145
+ const readParquet = await getReadParquet();
146
+ const parquetPath = getParquetPath(path);
147
+ const parquetBytes = await this.storeRoot.store.get(`/${parquetPath}`);
148
+ if (!parquetBytes) {
149
+ throw new Error('Failed to load parquet data from store.');
150
+ }
151
+ const wasmTable = readParquet(parquetBytes);
152
+ // TODO: use streaming?
153
+ const arrowTable = tableFromIPC(wasmTable.intoIPCStream());
154
+ this.parquetTable = arrowTable;
155
+ return this.parquetTable;
156
+ }
157
+
69
158
  /**
70
159
  * Class method for loading the obs index.
71
160
  * @param {string|undefined} path
@@ -82,7 +171,6 @@ export default class SpatialDataShapesSource extends AnnDataSource {
82
171
  const obsPath = `${tablePath}/obs`;
83
172
  const { _index } = await this.getJson(`${obsPath}/.zattrs`);
84
173
  indexPath = `${obsPath}/${_index}`;
85
-
86
174
  const {
87
175
  instance_key: instanceKey,
88
176
  // TODO: filter table index by region and element type.
@@ -90,16 +178,84 @@ export default class SpatialDataShapesSource extends AnnDataSource {
90
178
  // region,
91
179
  } = await this.loadSpatialDataAttrs(tablePath);
92
180
 
93
-
94
181
  indexPath = `${obsPath}/${instanceKey}`;
95
182
  }
96
183
  if (indexPath in this.obsIndices) {
97
184
  return this.obsIndices[indexPath];
98
185
  }
186
+ // TODO: support loading from parquet if no tablePath was provided.
99
187
  this.obsIndices[indexPath] = this._loadColumn(indexPath);
100
188
  return this.obsIndices[indexPath];
101
189
  }
102
190
 
191
+ /**
192
+ * Class method for loading general numeric arrays.
193
+ * @param {string} path A string like obsm.X_pca.
194
+ * @returns {Promise<Chunk<any>>} A promise for a zarr array containing the data.
195
+ */
196
+ async loadNumeric(path) {
197
+ const formatVersion = await this.getFormatVersion(path);
198
+ if (formatVersion === '0.1') {
199
+ return super.loadNumeric(path);
200
+ }
201
+ const arrowTable = await this.loadParquetTable(path);
202
+ const columnArr = arrowTable.getChild(basename(path))?.toArray();
203
+ return {
204
+ shape: [columnArr.length],
205
+ // TODO: support other kinds of TypedArrays via @vitessce/arrow-utils.
206
+ data: new Float32Array(columnArr),
207
+ stride: [1],
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Class method for loading specific columns of numeric arrays.
213
+ * @param {string} path A string like obsm.X_pca.
214
+ * @param {[number, number]} dims The column indices to load.
215
+ * @returns {Promise<{
216
+ * data: [ZarrTypedArray<any>, ZarrTypedArray<any>],
217
+ * shape: [number, number],
218
+ * }>} A promise for a zarr array containing the data.
219
+ */
220
+ async loadNumericForDims(path, dims) {
221
+ const formatVersion = await this.getFormatVersion(path);
222
+ if (formatVersion === '0.1') {
223
+ return super.loadNumericForDims(path, dims);
224
+ }
225
+ let columnName = basename(path);
226
+ if (columnName === 'coords') {
227
+ // The "geometry" column was previously called "coords" in version 0.1.
228
+ columnName = 'geometry';
229
+ }
230
+ const arrowTable = await this.loadParquetTable(path);
231
+ if (columnName === 'geometry' && dims[0] === 0 && dims[1] === 1) {
232
+ const geometryColumn = arrowTable.getChild(columnName);
233
+ if (!geometryColumn) {
234
+ throw new Error(`Column ${columnName} not found in parquet table`);
235
+ }
236
+ if (geometryColumn.type.toString() !== 'Binary') {
237
+ throw new Error(`Expected geometry column to have Binary type (WKB) but got ${geometryColumn.type.toString()}`);
238
+ }
239
+ // From GeoPandas.to_parquet docs:
240
+ // "By default, all geometry columns present are serialized to WKB format in the file"
241
+ // Reference: https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.to_parquet.html
242
+ // TODO: support geoarrow serialization schemes in addition to WKB.
243
+ const wkb = new WKB();
244
+ const points = geometryColumn.toArray()
245
+ // @ts-ignore
246
+ .map((/** @type {Uint8Array} */ geom) => wkb.readGeometry(geom).getFlatCoordinates());
247
+ return {
248
+ shape: [2, points.length],
249
+ data: [
250
+ new Float32Array(points.map((/** @type {[number, number]} */ p) => p[0])),
251
+ new Float32Array(points.map((/** @type {[number, number]} */ p) => p[1])),
252
+ ],
253
+ };
254
+ }
255
+ throw new Error('Unexpected column name for loading 2D array from parquet, currently only geometry is supported');
256
+ }
257
+
258
+
103
259
  /**
104
260
  * Class method for loading the var index.
105
261
  * @param {string|undefined} path
@@ -51,7 +51,7 @@ describe('loaders/ObsEmbeddingAnndataLoader for AnnData', () => {
51
51
  expect(result).toBeInstanceOf(LoaderResult);
52
52
  const payload = result.data;
53
53
  expect(Object.keys(payload)).toEqual(['obsIndex', 'obsEmbedding']);
54
- expect(payload.obsIndex).toEqual(['CTG', 'GCA', 'CTG']);
54
+ expect(payload.obsIndex).toEqual(['CTG', 'GCA', 'ACG']);
55
55
  expect(payload.obsEmbedding.shape).toEqual([2, 3]);
56
56
  expect(Array.from(payload.obsEmbedding.data[0])).toEqual([-1, 0, 1]);
57
57
  expect(Array.from(payload.obsEmbedding.data[1])).toEqual([-1, 0, 1]);
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -81,7 +81,7 @@
81
81
  ],
82
82
  [
83
83
  "/obs/_index/0",
84
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
84
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
85
85
  ],
86
86
  [
87
87
  "/obs/leiden/.zattrs",
@@ -93,7 +93,7 @@
93
93
  ],
94
94
  [
95
95
  "/obs/_index/0",
96
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
96
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
97
97
  ],
98
98
  [
99
99
  "/obs/leiden/.zarray",
@@ -93,7 +93,7 @@
93
93
  ],
94
94
  [
95
95
  "/obs/_index/0",
96
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
96
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
97
97
  ],
98
98
  [
99
99
  "/obs/leiden/.zarray",
@@ -69,7 +69,7 @@
69
69
  ],
70
70
  [
71
71
  "/obs/_index/0",
72
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
72
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
73
73
  ],
74
74
  [
75
75
  "/obs/leiden/.zarray",
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -81,7 +81,7 @@
81
81
  ],
82
82
  [
83
83
  "/obs/_index/0",
84
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
84
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
85
85
  ],
86
86
  [
87
87
  "/obs/leiden/.zattrs",
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -101,7 +101,7 @@
101
101
  ],
102
102
  [
103
103
  "/obs/_index/0",
104
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
104
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
105
105
  ],
106
106
  [
107
107
  "/obs/leiden/.zattrs",
@@ -81,7 +81,7 @@
81
81
  ],
82
82
  [
83
83
  "/obs/_index/0",
84
- "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABDVEc="
84
+ "AgEzARkAAAAZAAAAKQAAAAMAAAADAAAAQ1RHAwAAAEdDQQMAAABBQ0c="
85
85
  ],
86
86
  [
87
87
  "/obs/leiden/.zattrs",
@@ -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);