@vitessce/spatial-utils 2.0.3-beta.0 → 3.0.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/src/spatial.js ADDED
@@ -0,0 +1,418 @@
1
+ import { isEqual } from 'lodash-es';
2
+ import { Matrix4 } from 'math.gl';
3
+ import { divide, compare, unit } from 'mathjs';
4
+ import { VIEWER_PALETTE } from '@vitessce/utils';
5
+ import { viv } from '@vitessce/gl';
6
+ import { getMultiSelectionStats } from './layer-controller.js';
7
+
8
+ export function square(x, y, r) {
9
+ return [[x, y + r], [x + r, y], [x, y - r], [x - r, y]];
10
+ }
11
+
12
+ export const GLOBAL_LABELS = ['z', 't'];
13
+
14
+ export const DEFAULT_RASTER_DOMAIN_TYPE = 'Min/Max';
15
+
16
+ export const DEFAULT_RASTER_LAYER_PROPS = {
17
+ visible: true,
18
+ colormap: null,
19
+ opacity: 1,
20
+ domainType: DEFAULT_RASTER_DOMAIN_TYPE,
21
+ transparentColor: [0, 0, 0],
22
+ renderingMode: viv.RENDERING_MODES.ADDITIVE,
23
+ use3d: false,
24
+ };
25
+
26
+ export const DEFAULT_MOLECULES_LAYER = {
27
+ opacity: 1, radius: 20, visible: true,
28
+ };
29
+ export const DEFAULT_CELLS_LAYER = {
30
+ opacity: 1, radius: 50, visible: true, stroked: false,
31
+ };
32
+ export const DEFAULT_NEIGHBORHOODS_LAYER = {
33
+ visible: false,
34
+ };
35
+
36
+ export const DEFAULT_LAYER_TYPE_ORDERING = [
37
+ 'molecules',
38
+ 'cells',
39
+ 'neighborhoods',
40
+ 'raster',
41
+ ];
42
+
43
+ /**
44
+ * Get a representative PixelSource from a loader object returned from
45
+ * the Vitessce imaging loaders
46
+ * @param {object} loader { data: (PixelSource[]|PixelSource), metadata, channels } object
47
+ * @param {number=} level Level of the multiscale loader from which to get a PixelSource
48
+ * @returns {object} PixelSource object
49
+ */
50
+ export function getSourceFromLoader(loader, level) {
51
+ const { data } = loader;
52
+ const source = Array.isArray(data) ? data[(level || data.length - 1)] : data;
53
+ return source;
54
+ }
55
+
56
+ /**
57
+ * Helper method to determine whether pixel data is interleaved and rgb or not.
58
+ * @param {object} loader
59
+ * @param {array|null} channels
60
+ */
61
+ export function isRgb(loader, channels) {
62
+ const source = getSourceFromLoader(loader);
63
+ const { shape, dtype, labels } = source;
64
+ const channelSize = shape[(labels.includes('channel') ? labels.indexOf('channel') : labels.indexOf('c'))];
65
+ if (channelSize === 3 && dtype === 'Uint8') {
66
+ return true;
67
+ }
68
+ if (channels && channels.length === 3
69
+ && isEqual(channels[0].color, [255, 0, 0])
70
+ && isEqual(channels[1].color, [0, 255, 0])
71
+ && isEqual(channels[2].color, [0, 0, 255])
72
+ ) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ // From spatial/utils.js
79
+
80
+ function getMetaWithTransformMatrices(imageMeta, imageLoaders) {
81
+ // Do not fill in transformation matrices if any of the layers specify one.
82
+ const sources = imageLoaders.map(loader => getSourceFromLoader(loader));
83
+ if (
84
+ imageMeta.map(meta => meta?.metadata?.transform?.matrix
85
+ || meta?.metadata?.transform?.scale
86
+ || meta?.metadata?.transform?.translate).some(Boolean)
87
+ || sources.every(
88
+ source => !source.meta?.physicalSizes?.x || !source.meta?.physicalSizes?.y,
89
+ )
90
+ ) {
91
+ return imageMeta;
92
+ }
93
+ // Get the minimum physical among all the current images.
94
+ const minPhysicalSize = sources.reduce((acc, source) => {
95
+ const hasZPhyscialSize = source.meta?.physicalSizes?.z?.size;
96
+ const sizes = [
97
+ unit(`${source.meta?.physicalSizes.x.size} ${source.meta?.physicalSizes.x.unit}`.replace('µ', 'u')),
98
+ unit(`${source.meta?.physicalSizes.y.size} ${source.meta?.physicalSizes.y.unit}`.replace('µ', 'u')),
99
+ ];
100
+ if (hasZPhyscialSize) {
101
+ sizes.push(unit(`${source.meta?.physicalSizes.z.size} ${source.meta?.physicalSizes.z.unit}`.replace('µ', 'u')));
102
+ }
103
+ acc[0] = (acc[0] === undefined || compare(sizes[0], acc[0]) === -1) ? sizes[0] : acc[0];
104
+ acc[1] = (acc[1] === undefined || compare(sizes[1], acc[1]) === -1) ? sizes[1] : acc[1];
105
+ acc[2] = (acc[2] === undefined || compare(sizes[2], acc[2]) === -1) ? sizes[2] : acc[2];
106
+ return acc;
107
+ }, []);
108
+ const imageMetaWithTransform = imageMeta.map((meta, j) => {
109
+ const source = sources[j];
110
+ const hasZPhyscialSize = source.meta?.physicalSizes?.z?.size;
111
+ const sizes = [
112
+ unit(`${source.meta?.physicalSizes.x.size} ${source.meta?.physicalSizes.x.unit}`.replace('µ', 'u')),
113
+ unit(`${source.meta?.physicalSizes.y.size} ${source.meta?.physicalSizes.y.unit}`.replace('µ', 'u')),
114
+ ];
115
+ if (hasZPhyscialSize) {
116
+ sizes.push(unit(`${source.meta?.physicalSizes.z.size} ${source.meta?.physicalSizes.z.unit}`.replace('µ', 'u')));
117
+ }
118
+ // Find the ratio of the sizes to get the scaling factor.
119
+ const scale = sizes.map((i, k) => divide(i, minPhysicalSize[k]));
120
+ // sizes are special objects with own equals method - see `unit` in declaration
121
+ if (!sizes[0].equals(sizes[1])) {
122
+ // Handle scaling in the Y direction for non-square pixels
123
+ scale[1] = divide(sizes[1], sizes[0]);
124
+ }
125
+ // Add in z dimension needed for Matrix4 scale API.
126
+ if (!scale[2]) {
127
+ scale[2] = 1;
128
+ }
129
+ // no need to store/use identity scaling
130
+ if (isEqual(scale, [1, 1, 1])) {
131
+ return meta;
132
+ }
133
+ // Make sure to scale the z direction by one.
134
+ const matrix = new Matrix4().scale([...scale]);
135
+ const newMeta = { ...meta };
136
+ newMeta.metadata = {
137
+ ...newMeta.metadata,
138
+ // We don't want to store matrix objects in the view config.
139
+ transform: { matrix: matrix.toArray() },
140
+ };
141
+ return newMeta;
142
+ });
143
+ return imageMetaWithTransform;
144
+ }
145
+
146
+ /**
147
+ * Return the midpoint of the global dimensions.
148
+ * @param {object} source PixelSource object from Viv
149
+ * @returns {object} The selection.
150
+ */
151
+ function getDefaultGlobalSelection(source) {
152
+ const globalIndices = source.labels
153
+ .filter(dim => GLOBAL_LABELS.includes(dim));
154
+ const selection = {};
155
+ globalIndices.forEach((dim) => {
156
+ selection[dim] = Math.floor(
157
+ (source.shape[source.labels.indexOf(dim)] || 0) / 2,
158
+ );
159
+ });
160
+ return selection;
161
+ }
162
+
163
+
164
+ /**
165
+ * Create a default selection using the midpoint of the available global dimensions,
166
+ * and then the first four available selections from the first selectable channel.
167
+ * @param {object} source PixelSource object from Viv
168
+ * @returns {object} The selection.
169
+ */
170
+ function buildDefaultSelection(source) {
171
+ const selection = [];
172
+ const globalSelection = getDefaultGlobalSelection(source);
173
+ // First non-global dimension with some sort of selectable values
174
+ const firstNonGlobalDimension = source.labels.filter(
175
+ dim => !GLOBAL_LABELS.includes(dim)
176
+ && source.shape[source.labels.indexOf(dim)],
177
+ )[0];
178
+ for (let i = 0; i < Math.min(4, source.shape[
179
+ source.labels.indexOf(firstNonGlobalDimension)
180
+ ]); i += 1) {
181
+ selection.push(
182
+ {
183
+ [firstNonGlobalDimension]: i,
184
+ ...globalSelection,
185
+ },
186
+ );
187
+ }
188
+ return selection;
189
+ }
190
+
191
+ /**
192
+ * @param {Array.<number>} shape loader shape
193
+ */
194
+ export function isInterleaved(shape) {
195
+ const lastDimSize = shape[shape.length - 1];
196
+ return lastDimSize === 3 || lastDimSize === 4;
197
+ }
198
+
199
+ /**
200
+ * Initialize the channel selections for an individual layer.
201
+ * @param {object} loader A viv loader instance with channel names appended by Vitessce loaders
202
+ * of the form { data: (PixelSource[]|PixelSource), metadata: Object, channels }
203
+ * @returns {object[]} An array of selected channels with default
204
+ * domain/slider settings.
205
+ */
206
+ export async function initializeLayerChannels(loader, use3d) {
207
+ const result = [];
208
+ const source = getSourceFromLoader(loader);
209
+ // Add channel automatically as the first avaialable value for each dimension.
210
+ let defaultSelection = buildDefaultSelection(source);
211
+ defaultSelection = isInterleaved(source.shape)
212
+ ? [{ ...defaultSelection[0], c: 0 }] : defaultSelection;
213
+ const stats = await getMultiSelectionStats({
214
+ loader: loader.data, selections: defaultSelection, use3d,
215
+ });
216
+
217
+ const domains = isRgb(loader, null)
218
+ ? [[0, 255], [0, 255], [0, 255]]
219
+ : stats.domains;
220
+ const colors = isRgb(loader, null)
221
+ ? [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
222
+ : null;
223
+ const sliders = isRgb(loader, null)
224
+ ? [[0, 255], [0, 255], [0, 255]]
225
+ : stats.sliders;
226
+
227
+ defaultSelection.forEach((selection, i) => {
228
+ const domain = domains[i];
229
+ const slider = sliders[i];
230
+ const channel = {
231
+ selection,
232
+ // eslint-disable-next-line no-nested-ternary
233
+ color: colors ? colors[i]
234
+ : defaultSelection.length !== 1
235
+ ? VIEWER_PALETTE[i] : [255, 255, 255],
236
+ visible: true,
237
+ slider: slider || domain,
238
+ };
239
+ result.push(channel);
240
+ });
241
+ return result;
242
+ }
243
+
244
+ /**
245
+ * Given a set of image layer loader creator functions,
246
+ * create loader objects for an initial layer or set of layers,
247
+ * which will be selected based on default values predefined in
248
+ * the image data file or otherwise by a heuristic
249
+ * (the midpoint of the layers array).
250
+ * @param {object[]} rasterLayers A list of layer metadata objects with
251
+ * shape { name, type, url, createLoader }.
252
+ * @param {(string[]|null)} rasterRenderLayers A list of default raster layers. Optional.
253
+ */
254
+ export async function initializeRasterLayersAndChannels(
255
+ rasterLayers,
256
+ rasterRenderLayers,
257
+ usePhysicalSizeScaling,
258
+ ) {
259
+ const nextImageLoaders = [];
260
+ let nextImageMetaAndLayers = [];
261
+ const autoImageLayerDefPromises = [];
262
+
263
+ // Start all loader creators immediately.
264
+ // Reference: https://eslint.org/docs/rules/no-await-in-loop
265
+ const loaders = await Promise.all(rasterLayers.map(layer => layer.loaderCreator()));
266
+
267
+ for (let i = 0; i < rasterLayers.length; i++) {
268
+ const layer = rasterLayers[i];
269
+ const loader = loaders[i];
270
+ nextImageLoaders[i] = loader;
271
+ nextImageMetaAndLayers[i] = layer;
272
+ }
273
+ if (usePhysicalSizeScaling) {
274
+ nextImageMetaAndLayers = getMetaWithTransformMatrices(nextImageMetaAndLayers, nextImageLoaders);
275
+ }
276
+ // No layers were pre-defined so set up the default image layers.
277
+ if (!rasterRenderLayers) {
278
+ // Midpoint of images list as default image to show.
279
+ const layerIndex = Math.floor(rasterLayers.length / 2);
280
+ const loader = nextImageLoaders[layerIndex];
281
+ const autoImageLayerDefPromise = initializeLayerChannels(loader)
282
+ .then(channels => Promise.resolve({
283
+ type: nextImageMetaAndLayers[layerIndex]?.metadata?.isBitmask ? 'bitmask' : 'raster',
284
+ index: layerIndex,
285
+ ...DEFAULT_RASTER_LAYER_PROPS,
286
+ channels: channels.map((channel, j) => ({
287
+ ...channel,
288
+ ...(nextImageMetaAndLayers[layerIndex].channels
289
+ ? nextImageMetaAndLayers[layerIndex].channels[j] : []),
290
+ })),
291
+ modelMatrix: nextImageMetaAndLayers[layerIndex]?.metadata?.transform?.matrix,
292
+ transparentColor: layerIndex > 0 ? [0, 0, 0] : null,
293
+ }));
294
+ autoImageLayerDefPromises.push(autoImageLayerDefPromise);
295
+ } else {
296
+ // The renderLayers parameter is a list of layer names to show by default.
297
+ const globalIndicesOfRenderLayers = rasterRenderLayers
298
+ .map(imageName => rasterLayers.findIndex(image => image.name === imageName));
299
+ for (let i = 0; i < globalIndicesOfRenderLayers.length; i++) {
300
+ const layerIndex = globalIndicesOfRenderLayers[i];
301
+ const loader = nextImageLoaders[layerIndex];
302
+ const autoImageLayerDefPromise = initializeLayerChannels(loader)
303
+ // eslint-disable-next-line no-loop-func
304
+ .then(channels => Promise.resolve({
305
+ type: nextImageMetaAndLayers[layerIndex]?.metadata?.isBitmask ? 'bitmask' : 'raster',
306
+ index: layerIndex,
307
+ ...DEFAULT_RASTER_LAYER_PROPS,
308
+ channels: channels.map((channel, j) => ({
309
+ ...channel,
310
+ ...(nextImageMetaAndLayers[layerIndex].channels
311
+ ? nextImageMetaAndLayers[layerIndex].channels[j] : []),
312
+ })),
313
+ domainType: 'Min/Max',
314
+ modelMatrix: nextImageMetaAndLayers[layerIndex]?.metadata?.transform?.matrix,
315
+ transparentColor: i > 0 ? [0, 0, 0] : null,
316
+ }));
317
+ autoImageLayerDefPromises.push(autoImageLayerDefPromise);
318
+ }
319
+ }
320
+
321
+ const autoImageLayerDefs = await Promise.all(autoImageLayerDefPromises);
322
+ return [autoImageLayerDefs, nextImageLoaders, nextImageMetaAndLayers];
323
+ }
324
+
325
+ function getDefaultAxisType(name) {
326
+ if (name === 't') return 'time';
327
+ if (name === 'c') return 'channel';
328
+ return 'space';
329
+ }
330
+
331
+ // Reference: https://github.com/hms-dbmi/vizarr/blob/ade9d5d71bbedc8c20357c5310557ff9a0c59ac5/src/utils.ts#LL114-L142C2
332
+ export function getNgffAxes(firstMultiscalesAxes) {
333
+ // Returns axes in the latest v0.4+ format.
334
+ // defaults for v0.1 & v0.2
335
+ const defaultAxes = [
336
+ { type: 'time', name: 't' },
337
+ { type: 'channel', name: 'c' },
338
+ { type: 'space', name: 'z' },
339
+ { type: 'space', name: 'y' },
340
+ { type: 'space', name: 'x' },
341
+ ];
342
+ let axes = defaultAxes;
343
+ // v0.3 & v0.4+
344
+ if (firstMultiscalesAxes) {
345
+ axes = firstMultiscalesAxes.map((axis) => {
346
+ // axis may be string 'x' (v0.3) or object
347
+ if (typeof axis === 'string') {
348
+ return { name: axis, type: getDefaultAxisType(axis) };
349
+ }
350
+ const { name, type } = axis;
351
+ return { name, type: type ?? getDefaultAxisType(name) };
352
+ });
353
+ }
354
+ return axes;
355
+ }
356
+
357
+ export function getNgffAxesForTiff(dimOrder) {
358
+ return dimOrder
359
+ .toLowerCase()
360
+ .split('')
361
+ .map(name => ({
362
+ name,
363
+ type: getDefaultAxisType(name),
364
+ }));
365
+ }
366
+
367
+ /**
368
+ * Convert an array of coordinateTransformations objects to a 16-element
369
+ * plain JS array using Matrix4 linear algebra transformation functions.
370
+ * @param {object[]} coordinateTransformations List of objects matching the
371
+ * OME-NGFF v0.4 coordinateTransformations spec.
372
+ * @param {object[]} axes Axes in OME-NGFF v0.4 format, objects
373
+ * with { type, name }.
374
+ * @returns {Array<number>} Array of 16 numbers representing the Matrix4.
375
+ */
376
+ export function coordinateTransformationsToMatrix(coordinateTransformations, axes) {
377
+ let mat = (new Matrix4()).identity();
378
+ if (coordinateTransformations && axes) {
379
+ // Get the indices of the objects corresponding to X, Y, and Z from `axes`.
380
+ const xyzIndices = ['x', 'y', 'z'].map(name => axes.findIndex(axisObj => axisObj.type === 'space' && axisObj.name === name));
381
+ // Apply each transformation sequentially and in order according to the OME-NGFF v0.4 spec.
382
+ // Reference: https://ngff.openmicroscopy.org/0.4/#trafo-md
383
+ coordinateTransformations.forEach((transform) => {
384
+ if (transform.type === 'translation') {
385
+ const { translation: axisOrderedTranslation } = transform;
386
+ if (axisOrderedTranslation.length !== axes.length) {
387
+ throw new Error('Length of translation array was expected to match length of axes.');
388
+ }
389
+ const defaultValue = 0;
390
+ // Get the translation values for [x, y, z].
391
+ const xyzTranslation = xyzIndices.map(axisIndex => (
392
+ axisIndex >= 0
393
+ ? axisOrderedTranslation[axisIndex]
394
+ : defaultValue
395
+ ));
396
+ const nextMat = (new Matrix4()).translate(xyzTranslation);
397
+ mat = mat.multiplyLeft(nextMat);
398
+ }
399
+ if (transform.type === 'scale') {
400
+ const { scale: axisOrderedScale } = transform;
401
+ // Add in z dimension needed for Matrix4 scale API.
402
+ if (axisOrderedScale.length !== axes.length) {
403
+ throw new Error('Length of scale array was expected to match length of axes.');
404
+ }
405
+ const defaultValue = 1;
406
+ // Get the scale values for [x, y, z].
407
+ const xyzScale = xyzIndices.map(axisIndex => (
408
+ axisIndex >= 0
409
+ ? axisOrderedScale[axisIndex]
410
+ : defaultValue
411
+ ));
412
+ const nextMat = (new Matrix4()).scale(xyzScale);
413
+ mat = mat.multiplyLeft(nextMat);
414
+ }
415
+ });
416
+ }
417
+ return mat;
418
+ }
@@ -0,0 +1,45 @@
1
+ import { square, coordinateTransformationsToMatrix } from './spatial.js';
2
+
3
+ const defaultAxes = [
4
+ { type: 'time', name: 't' },
5
+ { type: 'channel', name: 'c' },
6
+ { type: 'space', name: 'z' },
7
+ { type: 'space', name: 'y' },
8
+ { type: 'space', name: 'x' },
9
+ ];
10
+
11
+ describe('Spatial.js', () => {
12
+ describe('square()', () => {
13
+ it('gives the right coordinates', () => {
14
+ expect(square(0, 0, 50)).toEqual([[0, 50], [50, 0], [0, -50], [-50, 0]]);
15
+ });
16
+ });
17
+ describe('coordinateTransformationsToMatrix', () => {
18
+ it('returns an Array instance', () => {
19
+ const transformations = [
20
+ {
21
+ type: 'translation',
22
+ translation: [0, 0, 0, 1, 1],
23
+ },
24
+ {
25
+ type: 'scale',
26
+ scale: [1, 1, 0.5, 0.5, 0.5],
27
+ },
28
+ ];
29
+ expect(coordinateTransformationsToMatrix(transformations, defaultAxes)).toEqual([
30
+ 0.5, 0, 0, 0,
31
+ 0, 0.5, 0, 0,
32
+ 0, 0, 0.5, 0,
33
+ 0.5, 0.5, 0, 1,
34
+ ]);
35
+ });
36
+ it('returns Identity matrix when coordinateTransformations is null', () => {
37
+ expect(coordinateTransformationsToMatrix(null, defaultAxes)).toEqual([
38
+ 1, 0, 0, 0,
39
+ 0, 1, 0, 0,
40
+ 0, 0, 1, 0,
41
+ 0, 0, 0, 1,
42
+ ]);
43
+ });
44
+ });
45
+ });
@@ -1,8 +0,0 @@
1
- import { square } from './spatial';
2
- describe('Spatial.js', () => {
3
- describe('square()', () => {
4
- it('gives the right coordinates', () => {
5
- expect(square(0, 0, 50)).toEqual([[0, 50], [50, 0], [0, -50], [-50, 0]]);
6
- });
7
- });
8
- });
File without changes