@vitessce/gl 2.0.0-beta.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14,4 +14,3 @@ export { TILE_SIZE, MAX_ROW_AGG, MIN_ROW_AGG, COLOR_BAR_SIZE, AXIS_MARGIN, DATA_
14
14
  export * as viv from './viv';
15
15
  export * as luma from './luma';
16
16
  export * as deck from './deck';
17
- export { GLOBAL_LABELS, DEFAULT_CELLS_LAYER, DEFAULT_MOLECULES_LAYER, DEFAULT_NEIGHBORHOODS_LAYER, DEFAULT_RASTER_DOMAIN_TYPE, DEFAULT_RASTER_LAYER_PROPS, DEFAULT_LAYER_TYPE_ORDERING, square, initializeLayerChannels, initializeRasterLayersAndChannels, getSourceFromLoader, isRgb, } from './spatial';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitessce/gl",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.1",
4
4
  "author": "Gehlenborg Lab",
5
5
  "homepage": "http://vitessce.io",
6
6
  "repository": {
@@ -42,13 +42,13 @@
42
42
  "@turf/boolean-within": "^6.5.0",
43
43
  "@turf/centroid": "^6.5.0",
44
44
  "@turf/helpers": "^6.5.0",
45
- "@vitessce/utils": "2.0.0-beta.2",
46
45
  "deck.gl": "8.6.7",
47
46
  "glslify": "^7.0.0",
48
47
  "lodash": "^4.17.21",
49
48
  "math.gl": "^3.5.6",
50
49
  "mathjs": "^9.2.0",
51
- "nebula.gl": "0.23.8"
50
+ "nebula.gl": "0.23.8",
51
+ "@vitessce/utils": "2.0.1"
52
52
  },
53
53
  "devDependencies": {
54
54
  "glsl-colormap": "^1.0.1"
@@ -1,109 +0,0 @@
1
- import { Matrix4 } from 'math.gl';
2
- import { getChannelStats } from './viv';
3
- async function getSingleSelectionStats2D({ loader, selection }) {
4
- const data = Array.isArray(loader) ? loader[loader.length - 1] : loader;
5
- const raster = await data.getRaster({ selection });
6
- const selectionStats = getChannelStats(raster.data);
7
- const { domain, contrastLimits: slider } = selectionStats;
8
- return { domain, slider };
9
- }
10
- async function getSingleSelectionStats3D({ loader, selection }) {
11
- const lowResSource = loader[loader.length - 1];
12
- const { shape, labels } = lowResSource;
13
- // eslint-disable-next-line no-bitwise
14
- const sizeZ = shape[labels.indexOf('z')] >> (loader.length - 1);
15
- const raster0 = await lowResSource.getRaster({
16
- selection: { ...selection, z: 0 },
17
- });
18
- const rasterMid = await lowResSource.getRaster({
19
- selection: { ...selection, z: Math.floor(sizeZ / 2) },
20
- });
21
- const rasterTop = await lowResSource.getRaster({
22
- selection: { ...selection, z: Math.max(0, sizeZ - 1) },
23
- });
24
- const stats0 = getChannelStats(raster0.data);
25
- const statsMid = getChannelStats(rasterMid.data);
26
- const statsTop = getChannelStats(rasterTop.data);
27
- return {
28
- domain: [
29
- Math.min(stats0.domain[0], statsMid.domain[0], statsTop.domain[0]),
30
- Math.max(stats0.domain[1], statsMid.domain[1], statsTop.domain[1]),
31
- ],
32
- slider: [
33
- Math.min(stats0.contrastLimits[0], statsMid.contrastLimits[0], statsTop.contrastLimits[0]),
34
- Math.max(stats0.contrastLimits[1], statsMid.contrastLimits[1], statsTop.contrastLimits[1]),
35
- ],
36
- };
37
- }
38
- /**
39
- * Get bounding cube for a given loader i.e [[0, width], [0, height], [0, depth]]
40
- * @param {Object} loader PixelSource|PixelSource[]
41
- * @param {[]} selection Selection for stats.
42
- * @param {boolean} use3d Whether or not to get 3d stats.
43
- * @returns {Object} { domains, sliders }
44
- */
45
- export const getSingleSelectionStats = async ({ loader, selection, use3d }) => {
46
- const getStats = use3d
47
- ? getSingleSelectionStats3D
48
- : getSingleSelectionStats2D;
49
- return getStats({ loader, selection });
50
- };
51
- export const getMultiSelectionStats = async ({ loader, selections, use3d }) => {
52
- const stats = await Promise.all(selections.map(selection => getSingleSelectionStats({ loader, selection, use3d })));
53
- const domains = stats.map(stat => stat.domain);
54
- const sliders = stats.map(stat => stat.slider);
55
- return { domains, sliders };
56
- };
57
- /**
58
- * Get physical size scaling Matrix4
59
- * @param {Object} loader PixelSource
60
- * @returns {Object} matrix
61
- */
62
- export function getPhysicalSizeScalingMatrix(loader) {
63
- const { x, y, z } = loader?.meta?.physicalSizes ?? {};
64
- if (x?.size && y?.size && z?.size) {
65
- const min = Math.min(z.size, x.size, y.size);
66
- const ratio = [x.size / min, y.size / min, z.size / min];
67
- return new Matrix4().scale(ratio);
68
- }
69
- return new Matrix4().identity();
70
- }
71
- /**
72
- * Get bounding cube for a given loader
73
- * @param {Object} loader PixelSource|PixelSource[]
74
- * @returns {Array} [0, width], [0, height], [0, depth]]
75
- */
76
- export function getBoundingCube(loader) {
77
- const source = Array.isArray(loader) ? loader[0] : loader;
78
- const { shape, labels } = source;
79
- const physicalSizeScalingMatrix = getPhysicalSizeScalingMatrix(source);
80
- const xSlice = [0, physicalSizeScalingMatrix[0] * shape[labels.indexOf('x')]];
81
- const ySlice = [0, physicalSizeScalingMatrix[5] * shape[labels.indexOf('y')]];
82
- const zSlice = [
83
- 0,
84
- physicalSizeScalingMatrix[10] * shape[labels.indexOf('z')],
85
- ];
86
- return [xSlice, ySlice, zSlice];
87
- }
88
- export function abbreviateNumber(value) {
89
- // Return an abbreviated representation of value, in 5 characters or less.
90
- const maxLength = 5;
91
- let maxNaiveDigits = maxLength;
92
- /* eslint-disable no-plusplus */
93
- if (!Number.isInteger(value)) {
94
- --maxNaiveDigits;
95
- } // Wasted on "."
96
- if (value < 1) {
97
- --maxNaiveDigits;
98
- } // Wasted on "0."
99
- /* eslint-disable no-plusplus */
100
- const naive = Intl.NumberFormat('en-US', {
101
- maximumSignificantDigits: maxNaiveDigits,
102
- useGrouping: false,
103
- }).format(value);
104
- if (naive.length <= maxLength)
105
- return naive;
106
- // "e+9" consumes 3 characters, so if we even had two significant digits,
107
- // it would take take us to six characters, including the decimal point.
108
- return value.toExponential(0);
109
- }
package/dist/spatial.js DELETED
@@ -1,281 +0,0 @@
1
- import isEqual from 'lodash/isEqual';
2
- import { Matrix4 } from 'math.gl';
3
- import { divide, compare, unit } from 'mathjs';
4
- import { VIEWER_PALETTE } from '@vitessce/utils';
5
- import { getMultiSelectionStats } from './layer-controller';
6
- import { RENDERING_MODES } from './viv';
7
- export function square(x, y, r) {
8
- return [[x, y + r], [x + r, y], [x, y - r], [x - r, y]];
9
- }
10
- export const GLOBAL_LABELS = ['z', 't'];
11
- export const DEFAULT_RASTER_DOMAIN_TYPE = 'Min/Max';
12
- export const DEFAULT_RASTER_LAYER_PROPS = {
13
- visible: true,
14
- colormap: null,
15
- opacity: 1,
16
- domainType: DEFAULT_RASTER_DOMAIN_TYPE,
17
- transparentColor: [0, 0, 0],
18
- renderingMode: RENDERING_MODES.ADDITIVE,
19
- use3d: false,
20
- };
21
- export const DEFAULT_MOLECULES_LAYER = {
22
- opacity: 1, radius: 20, visible: true,
23
- };
24
- export const DEFAULT_CELLS_LAYER = {
25
- opacity: 1, radius: 50, visible: true, stroked: false,
26
- };
27
- export const DEFAULT_NEIGHBORHOODS_LAYER = {
28
- visible: false,
29
- };
30
- export const DEFAULT_LAYER_TYPE_ORDERING = [
31
- 'molecules',
32
- 'cells',
33
- 'neighborhoods',
34
- 'raster',
35
- ];
36
- /**
37
- * Get a representative PixelSource from a loader object returned from
38
- * the Vitessce imaging loaders
39
- * @param {object} loader { data: (PixelSource[]|PixelSource), metadata, channels } object
40
- * @param {number=} level Level of the multiscale loader from which to get a PixelSource
41
- * @returns {object} PixelSource object
42
- */
43
- export function getSourceFromLoader(loader, level) {
44
- const { data } = loader;
45
- const source = Array.isArray(data) ? data[(level || data.length - 1)] : data;
46
- return source;
47
- }
48
- /**
49
- * Helper method to determine whether pixel data is interleaved and rgb or not.
50
- * @param {object} loader
51
- * @param {array|null} channels
52
- */
53
- export function isRgb(loader, channels) {
54
- const source = getSourceFromLoader(loader);
55
- const { shape, dtype, labels } = source;
56
- const channelSize = shape[(labels.includes('channel') ? labels.indexOf('channel') : labels.indexOf('c'))];
57
- if (channelSize === 3 && dtype === 'Uint8') {
58
- return true;
59
- }
60
- if (channels && channels.length === 3
61
- && isEqual(channels[0].color, [255, 0, 0])
62
- && isEqual(channels[1].color, [0, 255, 0])
63
- && isEqual(channels[2].color, [0, 0, 255])) {
64
- return true;
65
- }
66
- return false;
67
- }
68
- // From spatial/utils.js
69
- function getMetaWithTransformMatrices(imageMeta, imageLoaders) {
70
- // Do not fill in transformation matrices if any of the layers specify one.
71
- const sources = imageLoaders.map(loader => getSourceFromLoader(loader));
72
- if (imageMeta.map(meta => meta?.metadata?.transform?.matrix
73
- || meta?.metadata?.transform?.scale
74
- || meta?.metadata?.transform?.translate).some(Boolean)
75
- || sources.every(source => !source.meta?.physicalSizes?.x || !source.meta?.physicalSizes?.y)) {
76
- return imageMeta;
77
- }
78
- // Get the minimum physical among all the current images.
79
- const minPhysicalSize = sources.reduce((acc, source) => {
80
- const hasZPhyscialSize = source.meta?.physicalSizes?.z?.size;
81
- const sizes = [
82
- unit(`${source.meta?.physicalSizes.x.size} ${source.meta?.physicalSizes.x.unit}`.replace('µ', 'u')),
83
- unit(`${source.meta?.physicalSizes.y.size} ${source.meta?.physicalSizes.y.unit}`.replace('µ', 'u')),
84
- ];
85
- if (hasZPhyscialSize) {
86
- sizes.push(unit(`${source.meta?.physicalSizes.z.size} ${source.meta?.physicalSizes.z.unit}`.replace('µ', 'u')));
87
- }
88
- acc[0] = (acc[0] === undefined || compare(sizes[0], acc[0]) === -1) ? sizes[0] : acc[0];
89
- acc[1] = (acc[1] === undefined || compare(sizes[1], acc[1]) === -1) ? sizes[1] : acc[1];
90
- acc[2] = (acc[2] === undefined || compare(sizes[2], acc[2]) === -1) ? sizes[2] : acc[2];
91
- return acc;
92
- }, []);
93
- const imageMetaWithTransform = imageMeta.map((meta, j) => {
94
- const source = sources[j];
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
- // Find the ratio of the sizes to get the scaling factor.
104
- const scale = sizes.map((i, k) => divide(i, minPhysicalSize[k]));
105
- // Add in z dimension needed for Matrix4 scale API.
106
- if (!scale[2]) {
107
- scale[2] = 1;
108
- }
109
- // no need to store/use identity scaling
110
- if (isEqual(scale, [1, 1, 1])) {
111
- return meta;
112
- }
113
- // Make sure to scale the z direction by one.
114
- const matrix = new Matrix4().scale([...scale]);
115
- const newMeta = { ...meta };
116
- newMeta.metadata = {
117
- ...newMeta.metadata,
118
- // We don't want to store matrix objects in the view config.
119
- transform: { matrix: matrix.toArray() },
120
- };
121
- return newMeta;
122
- });
123
- return imageMetaWithTransform;
124
- }
125
- /**
126
- * Return the midpoint of the global dimensions.
127
- * @param {object} source PixelSource object from Viv
128
- * @returns {object} The selection.
129
- */
130
- function getDefaultGlobalSelection(source) {
131
- const globalIndices = source.labels
132
- .filter(dim => GLOBAL_LABELS.includes(dim));
133
- const selection = {};
134
- globalIndices.forEach((dim) => {
135
- selection[dim] = Math.floor((source.shape[source.labels.indexOf(dim)] || 0) / 2);
136
- });
137
- return selection;
138
- }
139
- /**
140
- * Create a default selection using the midpoint of the available global dimensions,
141
- * and then the first four available selections from the first selectable channel.
142
- * @param {object} source PixelSource object from Viv
143
- * @returns {object} The selection.
144
- */
145
- function buildDefaultSelection(source) {
146
- const selection = [];
147
- const globalSelection = getDefaultGlobalSelection(source);
148
- // First non-global dimension with some sort of selectable values
149
- const firstNonGlobalDimension = source.labels.filter(dim => !GLOBAL_LABELS.includes(dim)
150
- && source.shape[source.labels.indexOf(dim)])[0];
151
- for (let i = 0; i < Math.min(4, source.shape[source.labels.indexOf(firstNonGlobalDimension)]); i += 1) {
152
- selection.push({
153
- [firstNonGlobalDimension]: i,
154
- ...globalSelection,
155
- });
156
- }
157
- return selection;
158
- }
159
- /**
160
- * @param {Array.<number>} shape loader shape
161
- */
162
- export function isInterleaved(shape) {
163
- const lastDimSize = shape[shape.length - 1];
164
- return lastDimSize === 3 || lastDimSize === 4;
165
- }
166
- /**
167
- * Initialize the channel selections for an individual layer.
168
- * @param {object} loader A viv loader instance with channel names appended by Vitessce loaders
169
- * of the form { data: (PixelSource[]|PixelSource), metadata: Object, channels }
170
- * @returns {object[]} An array of selected channels with default
171
- * domain/slider settings.
172
- */
173
- export async function initializeLayerChannels(loader, use3d) {
174
- const result = [];
175
- const source = getSourceFromLoader(loader);
176
- // Add channel automatically as the first avaialable value for each dimension.
177
- let defaultSelection = buildDefaultSelection(source);
178
- defaultSelection = isInterleaved(source.shape)
179
- ? [{ ...defaultSelection[0], c: 0 }] : defaultSelection;
180
- const stats = await getMultiSelectionStats({
181
- loader: loader.data, selections: defaultSelection, use3d,
182
- });
183
- const domains = isRgb(loader, null)
184
- ? [[0, 255], [0, 255], [0, 255]]
185
- : stats.domains;
186
- const colors = isRgb(loader, null)
187
- ? [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
188
- : null;
189
- const sliders = isRgb(loader, null)
190
- ? [[0, 255], [0, 255], [0, 255]]
191
- : stats.sliders;
192
- defaultSelection.forEach((selection, i) => {
193
- const domain = domains[i];
194
- const slider = sliders[i];
195
- const channel = {
196
- selection,
197
- // eslint-disable-next-line no-nested-ternary
198
- color: colors ? colors[i]
199
- : defaultSelection.length !== 1
200
- ? VIEWER_PALETTE[i] : [255, 255, 255],
201
- visible: true,
202
- slider: slider || domain,
203
- };
204
- result.push(channel);
205
- });
206
- return result;
207
- }
208
- /**
209
- * Given a set of image layer loader creator functions,
210
- * create loader objects for an initial layer or set of layers,
211
- * which will be selected based on default values predefined in
212
- * the image data file or otherwise by a heuristic
213
- * (the midpoint of the layers array).
214
- * @param {object[]} rasterLayers A list of layer metadata objects with
215
- * shape { name, type, url, createLoader }.
216
- * @param {(string[]|null)} rasterRenderLayers A list of default raster layers. Optional.
217
- */
218
- export async function initializeRasterLayersAndChannels(rasterLayers, rasterRenderLayers, usePhysicalSizeScaling) {
219
- const nextImageLoaders = [];
220
- let nextImageMetaAndLayers = [];
221
- const autoImageLayerDefPromises = [];
222
- // Start all loader creators immediately.
223
- // Reference: https://eslint.org/docs/rules/no-await-in-loop
224
- const loaders = await Promise.all(rasterLayers.map(layer => layer.loaderCreator()));
225
- for (let i = 0; i < rasterLayers.length; i++) {
226
- const layer = rasterLayers[i];
227
- const loader = loaders[i];
228
- nextImageLoaders[i] = loader;
229
- nextImageMetaAndLayers[i] = layer;
230
- }
231
- if (usePhysicalSizeScaling) {
232
- nextImageMetaAndLayers = getMetaWithTransformMatrices(nextImageMetaAndLayers, nextImageLoaders);
233
- }
234
- // No layers were pre-defined so set up the default image layers.
235
- if (!rasterRenderLayers) {
236
- // Midpoint of images list as default image to show.
237
- const layerIndex = Math.floor(rasterLayers.length / 2);
238
- const loader = nextImageLoaders[layerIndex];
239
- const autoImageLayerDefPromise = initializeLayerChannels(loader)
240
- .then(channels => Promise.resolve({
241
- type: nextImageMetaAndLayers[layerIndex]?.metadata?.isBitmask ? 'bitmask' : 'raster',
242
- index: layerIndex,
243
- ...DEFAULT_RASTER_LAYER_PROPS,
244
- channels: channels.map((channel, j) => ({
245
- ...channel,
246
- ...(nextImageMetaAndLayers[layerIndex].channels
247
- ? nextImageMetaAndLayers[layerIndex].channels[j] : []),
248
- })),
249
- modelMatrix: nextImageMetaAndLayers[layerIndex]?.metadata?.transform?.matrix,
250
- transparentColor: layerIndex > 0 ? [0, 0, 0] : null,
251
- }));
252
- autoImageLayerDefPromises.push(autoImageLayerDefPromise);
253
- }
254
- else {
255
- // The renderLayers parameter is a list of layer names to show by default.
256
- const globalIndicesOfRenderLayers = rasterRenderLayers
257
- .map(imageName => rasterLayers.findIndex(image => image.name === imageName));
258
- for (let i = 0; i < globalIndicesOfRenderLayers.length; i++) {
259
- const layerIndex = globalIndicesOfRenderLayers[i];
260
- const loader = nextImageLoaders[layerIndex];
261
- const autoImageLayerDefPromise = initializeLayerChannels(loader)
262
- // eslint-disable-next-line no-loop-func
263
- .then(channels => Promise.resolve({
264
- type: nextImageMetaAndLayers[layerIndex]?.metadata?.isBitmask ? 'bitmask' : 'raster',
265
- index: layerIndex,
266
- ...DEFAULT_RASTER_LAYER_PROPS,
267
- channels: channels.map((channel, j) => ({
268
- ...channel,
269
- ...(nextImageMetaAndLayers[layerIndex].channels
270
- ? nextImageMetaAndLayers[layerIndex].channels[j] : []),
271
- })),
272
- domainType: 'Min/Max',
273
- modelMatrix: nextImageMetaAndLayers[layerIndex]?.metadata?.transform?.matrix,
274
- transparentColor: i > 0 ? [0, 0, 0] : null,
275
- }));
276
- autoImageLayerDefPromises.push(autoImageLayerDefPromise);
277
- }
278
- }
279
- const autoImageLayerDefs = await Promise.all(autoImageLayerDefPromises);
280
- return [autoImageLayerDefs, nextImageLoaders, nextImageMetaAndLayers];
281
- }
@@ -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
- });