@vitessce/utils 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.
package/dist/Pool.js ADDED
@@ -0,0 +1,58 @@
1
+ // https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
2
+ // We need to give a different way of getting this for safari, so 4 is probably a safe bet
3
+ // for parallel processing in the meantime. More can't really hurt since they'll just block
4
+ // each other and not the UI thread, which is the real benefit.
5
+ const defaultPoolSize = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 4 : null;
6
+ /**
7
+ * Pool for workers to decode chunks of the images.
8
+ * This is a line-for-line copy of GeoTIFFs old implementation: https://github.com/geotiffjs/geotiff.js/blob/v1.0.0-beta.6/src/pool.js
9
+ */
10
+ export default class Pool {
11
+ /**
12
+ * @constructor
13
+ * @param {object} Worker The worker class to be used for processing.
14
+ */
15
+ constructor(createWorker) {
16
+ this.workers = [];
17
+ this.idleWorkers = [];
18
+ this.waitQueue = [];
19
+ this.decoder = null;
20
+ // eslint-disable-next-line no-plusplus
21
+ for (let i = 0; i < defaultPoolSize; ++i) {
22
+ const w = createWorker();
23
+ this.workers.push(w);
24
+ this.idleWorkers.push(w);
25
+ }
26
+ }
27
+ // eslint-disable-next-line class-methods-use-this
28
+ async process() {
29
+ throw new Error('Pool needs to implement "process" method');
30
+ }
31
+ async waitForWorker() {
32
+ const idleWorker = this.idleWorkers.pop();
33
+ if (idleWorker) {
34
+ return idleWorker;
35
+ }
36
+ const waiter = {};
37
+ const promise = new Promise((resolve) => {
38
+ waiter.resolve = resolve;
39
+ });
40
+ this.waitQueue.push(waiter);
41
+ return promise;
42
+ }
43
+ async finishTask(currentWorker) {
44
+ const waiter = this.waitQueue.pop();
45
+ if (waiter) {
46
+ waiter.resolve(currentWorker);
47
+ }
48
+ else {
49
+ this.idleWorkers.push(currentWorker);
50
+ }
51
+ }
52
+ destroy() {
53
+ // eslint-disable-next-line no-plusplus
54
+ for (let i = 0; i < this.workers.length; ++i) {
55
+ this.workers[i].terminate();
56
+ }
57
+ }
58
+ }
package/dist/add.js ADDED
@@ -0,0 +1,3 @@
1
+ export function add(a, b, c) {
2
+ return a + b + c;
3
+ }
@@ -0,0 +1,114 @@
1
+ // Originally in src/components/utils.js
2
+ export const DEFAULT_DARK_COLOR = [50, 50, 50];
3
+ export const DEFAULT_LIGHT_COLOR = [200, 200, 200];
4
+ export function getDefaultColor(theme) {
5
+ return theme === 'dark' ? DEFAULT_DARK_COLOR : DEFAULT_LIGHT_COLOR;
6
+ }
7
+ // From https://personal.sron.nl/~pault/#sec:qualitative
8
+ export const PALETTE = [
9
+ [68, 119, 170],
10
+ [136, 204, 238],
11
+ [68, 170, 153],
12
+ [17, 119, 51],
13
+ [153, 153, 51],
14
+ [221, 204, 119],
15
+ [204, 102, 119],
16
+ [136, 34, 85],
17
+ [170, 68, 153],
18
+ ];
19
+ export const VIEWER_PALETTE = [
20
+ [0, 0, 255],
21
+ [0, 255, 0],
22
+ [255, 0, 255],
23
+ [255, 255, 0],
24
+ [0, 255, 255],
25
+ [255, 255, 255],
26
+ [255, 128, 0],
27
+ [255, 0, 0],
28
+ ];
29
+ export const COLORMAP_OPTIONS = [
30
+ 'viridis',
31
+ 'greys',
32
+ 'magma',
33
+ 'jet',
34
+ 'hot',
35
+ 'bone',
36
+ 'copper',
37
+ 'summer',
38
+ 'density',
39
+ 'inferno',
40
+ ];
41
+ export const DEFAULT_GL_OPTIONS = { webgl2: true };
42
+ export function createDefaultUpdateStatus(componentName) {
43
+ return message => console.warn(`${componentName} updateStatus: ${message}`);
44
+ }
45
+ export function createDefaultUpdateCellsSelection(componentName) {
46
+ return cellsSelection => console.warn(`${componentName} updateCellsSelection: ${cellsSelection}`);
47
+ }
48
+ export function createDefaultUpdateCellsHover(componentName) {
49
+ return hoverInfo => console.warn(`${componentName} updateCellsHover: ${hoverInfo.cellId}`);
50
+ }
51
+ export function createDefaultUpdateGenesHover(componentName) {
52
+ return hoverInfo => console.warn(`${componentName} updateGenesHover: ${hoverInfo.geneId}`);
53
+ }
54
+ export function createDefaultUpdateTracksHover(componentName) {
55
+ return hoverInfo => console.warn(`${componentName} updateTracksHover: ${hoverInfo}`);
56
+ }
57
+ export function createDefaultUpdateViewInfo(componentName) {
58
+ return viewInfo => console.warn(`${componentName} updateViewInfo: ${viewInfo}`);
59
+ }
60
+ export function createDefaultClearPleaseWait() {
61
+ return () => { };
62
+ }
63
+ /**
64
+ * Copy a typed array into a new array buffer.
65
+ * @param {Uint8Array} arr The typed array to be copied.
66
+ * @returns {Uint8Array} The copied array.
67
+ */
68
+ export function copyUint8Array(arr) {
69
+ const newBuffer = new ArrayBuffer(arr.buffer.byteLength);
70
+ const newArr = new Uint8Array(newBuffer);
71
+ newArr.set(arr);
72
+ return newArr;
73
+ }
74
+ export function asEsModule(component) {
75
+ return {
76
+ __esModule: true,
77
+ default: component,
78
+ };
79
+ }
80
+ export function formatBytes(bytes, decimals = 2) {
81
+ if (bytes === 0)
82
+ return '0 Bytes';
83
+ const k = 1024;
84
+ const dm = decimals < 0 ? 0 : decimals;
85
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
86
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
87
+ // eslint-disable-next-line no-restricted-properties
88
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
89
+ }
90
+ export const getStatsForResolution = (loader, resolution) => {
91
+ const { shape, labels } = loader[resolution];
92
+ const height = shape[labels.indexOf('y')];
93
+ const width = shape[labels.indexOf('x')];
94
+ const depth = shape[labels.indexOf('z')];
95
+ // eslint-disable-next-line no-bitwise
96
+ const depthDownsampled = Math.max(1, depth >> resolution);
97
+ // Check memory allocation limits for Float32Array (used in XR3DLayer for rendering)
98
+ const totalBytes = 4 * height * width * depthDownsampled;
99
+ return {
100
+ height, width, depthDownsampled, totalBytes,
101
+ };
102
+ };
103
+ export const canLoadResolution = (loader, resolution) => {
104
+ const { totalBytes, height, width, depthDownsampled, } = getStatsForResolution(loader, resolution);
105
+ const maxHeapSize = window.performance?.memory
106
+ && window.performance?.memory?.jsHeapSizeLimit / 2;
107
+ const maxSize = maxHeapSize || (2 ** 31) - 1;
108
+ // 2048 is a normal texture size limit although some browsers go larger.
109
+ return (totalBytes < maxSize
110
+ && height <= 2048
111
+ && depthDownsampled <= 2048
112
+ && width <= 2048
113
+ && depthDownsampled > 1);
114
+ };
@@ -0,0 +1,70 @@
1
+ import Bowser from 'bowser';
2
+ import { compressToEncodedURIComponent, decompressFromEncodedURIComponent } from 'lz-string';
3
+ const CURRENT_VERSION = '0.0.1';
4
+ const VITESSCE_CONF_QUERY_STRING = 'vitessce_conf';
5
+ const VERSION_QUERY_STRING = 'vitessce_conf_version';
6
+ const LENGTH_QUERY_STRING = 'vitessce_conf_length';
7
+ function sniffBrowser() {
8
+ const { browser } = Bowser.parse(window.navigator.userAgent);
9
+ return browser.name;
10
+ }
11
+ // https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
12
+ const MAX_BROWSER_URL_LENGTHS = {
13
+ Chrome: 32779,
14
+ 'Internet Explorer': 2047,
15
+ Edge: 2047,
16
+ Safari: 65000,
17
+ Firefox: 65000,
18
+ };
19
+ export default class CompressedConfLengthError {
20
+ constructor(message) {
21
+ this.message = message;
22
+ }
23
+ }
24
+ /**
25
+ * Encode a configuration as url params with a version and an lz-compressed conf.
26
+ * @param {Object} params
27
+ * @param {Object} params.conf Previous scope names.
28
+ * @param {function} params.onOverMaximumUrlLength Callback for when new url
29
+ * is over max length for your browser - takes two arguments: { message, willWorkOn }
30
+ * for the error message and the browsers for which the url will work (optional).
31
+ * @returns {string} The new params like
32
+ * vitessce_conf_length=10&vitessce_conf_version=0.0.1&vitessce_conf=fksdfasdfjkl
33
+ */
34
+ export function encodeConfInUrl({ conf, onOverMaximumUrlLength = () => { }, }) {
35
+ const compressedConf = compressToEncodedURIComponent(JSON.stringify(conf));
36
+ const newParams = `${LENGTH_QUERY_STRING}=${compressedConf.length}&${VERSION_QUERY_STRING}=${CURRENT_VERSION}&${VITESSCE_CONF_QUERY_STRING}=${compressedConf}`;
37
+ const browser = sniffBrowser();
38
+ const maxLength = MAX_BROWSER_URL_LENGTHS[browser];
39
+ if (newParams.length > maxLength) {
40
+ const willWorkOn = Object.entries(MAX_BROWSER_URL_LENGTHS)
41
+ .filter(entry => entry[1] > newParams.length)
42
+ .map(entry => entry[0]);
43
+ const message = `Configuration is ${compressedConf.length} characters; max URL for ${browser} is ${maxLength}: it will work on ${willWorkOn.join(', ') || 'no browser'}.`;
44
+ console.error(message);
45
+ onOverMaximumUrlLength({ message, willWorkOn });
46
+ }
47
+ return newParams;
48
+ }
49
+ /**
50
+ * Decode URL params to a Vitessce configuration.
51
+ * The URL params must have version and vitessce_conf params,
52
+ * like vitessce_conf_length=10&vitessce_conf_version=0.0.1&vitessce_conf=fksdfasdfjkl.
53
+ * @param {Object} queryString The URL params,
54
+ * like vitessce_conf_length=10&vitessce_conf_version=0.0.1&vitessce_conf=fksdfasdfjkl.
55
+ * @returns {string} A vitessce configuration.
56
+ */
57
+ export function decodeURLParamsToConf(queryString) {
58
+ const params = new URLSearchParams(queryString.replace('#', '&'));
59
+ const compressedConfString = params.get(VITESSCE_CONF_QUERY_STRING);
60
+ const expectedConfLength = Number(params.get(LENGTH_QUERY_STRING));
61
+ if (expectedConfLength !== compressedConfString.length) {
62
+ throw new CompressedConfLengthError(`Compressed conf length (${compressedConfString.length}) != expected (${expectedConfLength}). URL truncated?`);
63
+ }
64
+ const version = params.get(VERSION_QUERY_STRING);
65
+ if (version === CURRENT_VERSION) {
66
+ const conf = JSON.parse(decompressFromEncodedURIComponent(compressedConfString));
67
+ return conf;
68
+ }
69
+ throw new Error('Unrecognized URL Param Version');
70
+ }
@@ -0,0 +1,63 @@
1
+ import { encodeConfInUrl, decodeURLParamsToConf, } from './export-utils';
2
+ const fakeConfig = {
3
+ version: '0.1.0',
4
+ public: false,
5
+ layers: [
6
+ {
7
+ name: 'cells',
8
+ type: 'CELLS',
9
+ fileType: 'cells.json',
10
+ url: 'http://example.com/cells.json',
11
+ },
12
+ ],
13
+ name: 'Just scatterplot',
14
+ staticLayout: [
15
+ {
16
+ component: 'scatterplot',
17
+ props: {
18
+ mapping: 't-SNE',
19
+ view: {
20
+ zoom: 0.75,
21
+ target: [0, 0, 0],
22
+ },
23
+ },
24
+ x: 0,
25
+ y: 0,
26
+ w: 12,
27
+ h: 2,
28
+ },
29
+ ],
30
+ };
31
+ function makeLongString(length) {
32
+ let result = '';
33
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
34
+ const charactersLength = characters.length;
35
+ // eslint-disable-next-line no-plusplus
36
+ for (let i = 0; i < length; i++) {
37
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
38
+ }
39
+ return result;
40
+ }
41
+ describe('src/app/export-utils.js', () => {
42
+ describe('encodeConfInUrl', () => {
43
+ it('encodes a view config for a URL', () => {
44
+ const urlParams1 = encodeConfInUrl({ conf: {} });
45
+ expect(urlParams1).toEqual('vitessce_conf_length=5&vitessce_conf_version=0.0.1&vitessce_conf=N4XyA');
46
+ const urlParams2 = encodeConfInUrl({ conf: fakeConfig });
47
+ expect(urlParams2).toEqual('vitessce_conf_length=327&vitessce_conf_version=0.0.1&vitessce_conf=N4IgbgpgTgzglgewHYgFwgAwDoCMWMgA0IADgK4BGANnAMZoBmAhlTBMVUwJ7QxoDaoJEwC2ENCFoQqrIiAAuXEuPQBhAKIAZTQGU5DOFQgAVJSsnTWWAFYxkcslCoSAFvPklUAei8QAHqIkRli0CCJeUjIwNnYoAL4AusTCYhIAUmQw8gAEMLRM7tBBCPJyWQV0mtwIZKWogpJhJMgQSHUgeQXyRVQlciRQCCR8qKAiTCQkcEgA5hLyALQ6AHLqcmBwEADuaKAAXghhaNgA7ACsxPJMUDMQdfwYhI8YCXFxxH7HxFxfIDuoOAATMQXGhAYk4kA');
48
+ });
49
+ it('Calls onOverMaximumUrlLength for conf too long', () => {
50
+ let browsers;
51
+ // eslint-disable-next-line no-return-assign
52
+ const onOverMaximumUrlLength = ({ willWorkOn }) => browsers = willWorkOn;
53
+ encodeConfInUrl({ conf: { foo: makeLongString(69000) }, onOverMaximumUrlLength });
54
+ expect(browsers).toEqual([]);
55
+ });
56
+ it('decodes a view config for a URL', () => {
57
+ const viewConfig1 = decodeURLParamsToConf('vitessce_conf_length=5&vitessce_conf_version=0.0.1&vitessce_conf=N4XyA');
58
+ expect(viewConfig1).toEqual({});
59
+ const viewConfig2 = decodeURLParamsToConf('vitessce_conf_length=327&vitessce_conf_version=0.0.1&vitessce_conf=N4IgbgpgTgzglgewHYgFwgAwDoCMWMgA0IADgK4BGANnAMZoBmAhlTBMVUwJ7QxoDaoJEwC2ENCFoQqrIiAAuXEuPQBhAKIAZTQGU5DOFQgAVJSsnTWWAFYxkcslCoSAFvPklUAei8QAHqIkRli0CCJeUjIwNnYoAL4AusTCYhIAUmQw8gAEMLRM7tBBCPJyWQV0mtwIZKWogpJhJMgQSHUgeQXyRVQlciRQCCR8qKAiTCQkcEgA5hLyALQ6AHLqcmBwEADuaKAAXghhaNgA7ACsxPJMUDMQdfwYhI8YCXFxxH7HxFxfIDuoOAATMQXGhAYk4kA');
60
+ expect(viewConfig2).toEqual(fakeConfig);
61
+ });
62
+ });
63
+ });
package/dist/gating.js ADDED
@@ -0,0 +1,30 @@
1
+ // Originally in src/components/gating/utils.js
2
+ export const VALUE_TRANSFORM_OPTIONS = [
3
+ { name: 'None', value: null },
4
+ { name: 'Log', value: 'log1p' },
5
+ { name: 'ArcSinh', value: 'arcsinh' },
6
+ ];
7
+ /**
8
+ * Get a feature value transform function such as
9
+ * log1p or arcsinh.
10
+ * @param {string} featureValueTransform The function name.
11
+ * @param {number} coefficient The transform coefficient.
12
+ * @returns {function} The function which takes one number
13
+ * as a parameter and returns the transformed number
14
+ * (or the original number in the identity case).
15
+ */
16
+ export function getValueTransformFunction(featureValueTransform, coefficient) {
17
+ // Set transform function
18
+ let transformFunction;
19
+ switch (featureValueTransform) {
20
+ case 'log1p':
21
+ transformFunction = v => Math.log(1 + v * coefficient);
22
+ break;
23
+ case 'arcsinh':
24
+ transformFunction = v => Math.asinh(v * coefficient);
25
+ break;
26
+ default:
27
+ transformFunction = v => v;
28
+ }
29
+ return transformFunction;
30
+ }
@@ -0,0 +1,56 @@
1
+ import range from 'lodash/range';
2
+ export function getGeneByCellTile(view, { tileSize, tileI, tileJ, numCells, numGenes, cellOrdering, expressionRowLookUp, }) {
3
+ const tileData = new Uint8Array(tileSize * tileSize);
4
+ let offset;
5
+ let value;
6
+ let cellI;
7
+ let geneI;
8
+ let sortedCellI;
9
+ const tileSizeRange = range(tileSize);
10
+ tileSizeRange.forEach((j) => {
11
+ // Need to iterate over cells in the outer loop.
12
+ cellI = (tileJ * tileSize) + j;
13
+ if (cellI < numCells) {
14
+ sortedCellI = expressionRowLookUp.get(cellOrdering[cellI]);
15
+ if (sortedCellI >= -1) {
16
+ tileSizeRange.forEach((i) => {
17
+ geneI = (tileI * tileSize) + i;
18
+ value = view[sortedCellI * numGenes + geneI];
19
+ offset = ((tileSize - i - 1) * tileSize + j);
20
+ tileData[offset] = value;
21
+ });
22
+ }
23
+ }
24
+ });
25
+ return tileData;
26
+ }
27
+ export function getCellByGeneTile(view, { tileSize, tileI, tileJ, numCells, numGenes, cellOrdering, expressionRowLookUp, }) {
28
+ const tileData = new Uint8Array(tileSize * tileSize);
29
+ let offset;
30
+ let value;
31
+ let cellI;
32
+ let geneI;
33
+ let sortedCellI;
34
+ const tileSizeRange = range(tileSize);
35
+ tileSizeRange.forEach((i) => {
36
+ // Need to iterate over cells in the outer loop.
37
+ cellI = (tileI * tileSize) + i;
38
+ if (cellI < numCells) {
39
+ sortedCellI = expressionRowLookUp.get(cellOrdering[cellI]);
40
+ if (sortedCellI >= -1) {
41
+ tileSizeRange.forEach((j) => {
42
+ geneI = (tileJ * tileSize) + j;
43
+ if (geneI < numGenes) {
44
+ value = view[sortedCellI * numGenes + geneI];
45
+ }
46
+ else {
47
+ value = 0;
48
+ }
49
+ offset = ((tileSize - i - 1) * tileSize + j);
50
+ tileData[offset] = value;
51
+ });
52
+ }
53
+ }
54
+ });
55
+ return tileData;
56
+ }
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './root';
2
+ export * from './components';
3
+ export { encodeConfInUrl, decodeURLParamsToConf, } from './export-utils';
4
+ export { getValueTransformFunction, VALUE_TRANSFORM_OPTIONS, } from './gating';
5
+ export { getCellColors, } from './interpolate-colors';
6
+ export { default as Pool } from './Pool';
@@ -0,0 +1,101 @@
1
+ /* eslint-disable no-nested-ternary */
2
+ /* eslint-disable no-param-reassign */
3
+ import { treeToCellColorsBySetNames } from '@vitessce/sets';
4
+ import { getDefaultColor } from './components';
5
+ // The functions defined here have been adapted from d3-interpolate,
6
+ // d3-color, and d3-scale-chromatic.
7
+ // Color string "rgb(r,g,b)" representations are replaced by color array [r, g, b]
8
+ // representations, to allow them to work nicely with deck.gl,
9
+ // without the need to converting back and forth between string and array formats.
10
+ // Reference: https://github.com/d3/d3-scale-chromatic/blob/431d21da776f97c632f53a855bd822edfbbcd56e/src/diverging/RdBu.js
11
+ // eslint-disable-next-line max-len
12
+ const schemeRdBu = [[103, 0, 31], [178, 24, 43], [214, 96, 77], [244, 165, 130], [253, 219, 199], [247, 247, 247], [209, 229, 240], [146, 197, 222], [67, 147, 195], [33, 102, 172], [5, 48, 97]];
13
+ // eslint-disable-next-line max-len
14
+ const schemePlasma = [[13, 8, 135], [16, 7, 136], [19, 7, 137], [22, 7, 138], [25, 6, 140], [27, 6, 141], [29, 6, 142], [32, 6, 143], [34, 6, 144], [36, 6, 145], [38, 5, 145], [40, 5, 146], [42, 5, 147], [44, 5, 148], [46, 5, 149], [47, 5, 150], [49, 5, 151], [51, 5, 151], [53, 4, 152], [55, 4, 153], [56, 4, 154], [58, 4, 154], [60, 4, 155], [62, 4, 156], [63, 4, 156], [65, 4, 157], [67, 3, 158], [68, 3, 158], [70, 3, 159], [72, 3, 159], [73, 3, 160], [75, 3, 161], [76, 2, 161], [78, 2, 162], [80, 2, 162], [81, 2, 163], [83, 2, 163], [85, 2, 164], [86, 1, 164], [88, 1, 164], [89, 1, 165], [91, 1, 165], [92, 1, 166], [94, 1, 166], [96, 1, 166], [97, 0, 167], [99, 0, 167], [100, 0, 167], [102, 0, 167], [103, 0, 168], [105, 0, 168], [106, 0, 168], [108, 0, 168], [110, 0, 168], [111, 0, 168], [113, 0, 168], [114, 1, 168], [116, 1, 168], [117, 1, 168], [119, 1, 168], [120, 1, 168], [122, 2, 168], [123, 2, 168], [125, 3, 168], [126, 3, 168], [128, 4, 168], [129, 4, 167], [131, 5, 167], [132, 5, 167], [134, 6, 166], [135, 7, 166], [136, 8, 166], [138, 9, 165], [139, 10, 165], [141, 11, 165], [142, 12, 164], [143, 13, 164], [145, 14, 163], [146, 15, 163], [148, 16, 162], [149, 17, 161], [150, 19, 161], [152, 20, 160], [153, 21, 159], [154, 22, 159], [156, 23, 158], [157, 24, 157], [158, 25, 157], [160, 26, 156], [161, 27, 155], [162, 29, 154], [163, 30, 154], [165, 31, 153], [166, 32, 152], [167, 33, 151], [168, 34, 150], [170, 35, 149], [171, 36, 148], [172, 38, 148], [173, 39, 147], [174, 40, 146], [176, 41, 145], [177, 42, 144], [178, 43, 143], [179, 44, 142], [180, 46, 141], [181, 47, 140], [182, 48, 139], [183, 49, 138], [184, 50, 137], [186, 51, 136], [187, 52, 136], [188, 53, 135], [189, 55, 134], [190, 56, 133], [191, 57, 132], [192, 58, 131], [193, 59, 130], [194, 60, 129], [195, 61, 128], [196, 62, 127], [197, 64, 126], [198, 65, 125], [199, 66, 124], [200, 67, 123], [201, 68, 122], [202, 69, 122], [203, 70, 121], [204, 71, 120], [204, 73, 119], [205, 74, 118], [206, 75, 117], [207, 76, 116], [208, 77, 115], [209, 78, 114], [210, 79, 113], [211, 81, 113], [212, 82, 112], [213, 83, 111], [213, 84, 110], [214, 85, 109], [215, 86, 108], [216, 87, 107], [217, 88, 106], [218, 90, 106], [218, 91, 105], [219, 92, 104], [220, 93, 103], [221, 94, 102], [222, 95, 101], [222, 97, 100], [223, 98, 99], [224, 99, 99], [225, 100, 98], [226, 101, 97], [226, 102, 96], [227, 104, 95], [228, 105, 94], [229, 106, 93], [229, 107, 93], [230, 108, 92], [231, 110, 91], [231, 111, 90], [232, 112, 89], [233, 113, 88], [233, 114, 87], [234, 116, 87], [235, 117, 86], [235, 118, 85], [236, 119, 84], [237, 121, 83], [237, 122, 82], [238, 123, 81], [239, 124, 81], [239, 126, 80], [240, 127, 79], [240, 128, 78], [241, 129, 77], [241, 131, 76], [242, 132, 75], [243, 133, 75], [243, 135, 74], [244, 136, 73], [244, 137, 72], [245, 139, 71], [245, 140, 70], [246, 141, 69], [246, 143, 68], [247, 144, 68], [247, 145, 67], [247, 147, 66], [248, 148, 65], [248, 149, 64], [249, 151, 63], [249, 152, 62], [249, 154, 62], [250, 155, 61], [250, 156, 60], [250, 158, 59], [251, 159, 58], [251, 161, 57], [251, 162, 56], [252, 163, 56], [252, 165, 55], [252, 166, 54], [252, 168, 53], [252, 169, 52], [253, 171, 51], [253, 172, 51], [253, 174, 50], [253, 175, 49], [253, 177, 48], [253, 178, 47], [253, 180, 47], [253, 181, 46], [254, 183, 45], [254, 184, 44], [254, 186, 44], [254, 187, 43], [254, 189, 42], [254, 190, 42], [254, 192, 41], [253, 194, 41], [253, 195, 40], [253, 197, 39], [253, 198, 39], [253, 200, 39], [253, 202, 38], [253, 203, 38], [252, 205, 37], [252, 206, 37], [252, 208, 37], [252, 210, 37], [251, 211, 36], [251, 213, 36], [251, 215, 36], [250, 216, 36], [250, 218, 36], [249, 220, 36], [249, 221, 37], [248, 223, 37], [248, 225, 37], [247, 226, 37], [247, 228, 37], [246, 230, 38], [246, 232, 38], [245, 233, 38], [245, 235, 39], [244, 237, 39], [243, 238, 39], [243, 240, 39], [242, 242, 39], [241, 244, 38], [241, 245, 37], [240, 247, 36], [240, 249, 33]];
15
+ // Reference: https://github.com/d3/d3-interpolate/blob/96d54051d1c2fec55f240edd0ec5401715b10390/src/rgb.js
16
+ function rgbSpline(spline) {
17
+ return (colors) => {
18
+ const n = colors.length;
19
+ let r = new Array(n);
20
+ let g = new Array(n);
21
+ let b = new Array(n);
22
+ let i;
23
+ let color;
24
+ // eslint-disable-next-line no-plusplus
25
+ for (i = 0; i < n; ++i) {
26
+ color = [colors[i][0], colors[i][1], colors[i][2]];
27
+ r[i] = color[0] || 0;
28
+ g[i] = color[1] || 0;
29
+ b[i] = color[2] || 0;
30
+ }
31
+ r = spline(r);
32
+ g = spline(g);
33
+ b = spline(b);
34
+ return t => [r(t), g(t), b(t)];
35
+ };
36
+ }
37
+ // Reference: https://github.com/d3/d3-interpolate/blob/594a32af1fe1118812b439012c2cb742e907c0c0/src/basis.js
38
+ function basis(values) {
39
+ function innerBasis(t1, v0, v1, v2, v3) {
40
+ const t2 = t1 * t1;
41
+ const t3 = t2 * t1;
42
+ return ((1 - 3 * t1 + 3 * t2 - t3) * v0
43
+ + (4 - 6 * t2 + 3 * t3) * v1
44
+ + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
45
+ + t3 * v3) / 6;
46
+ }
47
+ const n = values.length - 1;
48
+ return (t) => {
49
+ const i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n);
50
+ const v1 = values[i];
51
+ const v2 = values[i + 1];
52
+ const v0 = i > 0 ? values[i - 1] : 2 * v1 - v2;
53
+ const v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
54
+ return innerBasis((t - i / n) * n, v0, v1, v2, v3);
55
+ };
56
+ }
57
+ // Reference: https://github.com/d3/d3-scale-chromatic/blob/ade54c13e8dfdb9807801a794eaec1a37f926b8a/src/ramp.js
58
+ const interpolateRgbBasis = rgbSpline(basis);
59
+ function interpolateSequentialMulti(range) {
60
+ const n = range.length;
61
+ return t => range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
62
+ }
63
+ export const interpolateRdBu = interpolateRgbBasis(schemeRdBu);
64
+ export const interpolatePlasma = interpolateSequentialMulti(schemePlasma);
65
+ /**
66
+ * Get a mapping of cell IDs to cell colors based on
67
+ * gene / cell set selection coordination state.
68
+ * @param {object} params
69
+ * @param {object} params.expressionMatrix { rows, cols, matrix }
70
+ * @param {array} params.geneSelection Array of selected gene IDs.
71
+ * @param {object} params.cellSets The cell sets tree.
72
+ * @param {object} params.cellSetSelection Selected cell sets.
73
+ * @param {string} params.cellColorEncoding Which to use for
74
+ * coloring: gene expression or cell sets?
75
+ * @returns {Map} Mapping from cell IDs to [r, g, b] color arrays.
76
+ */
77
+ export function getCellColors(params) {
78
+ const { cellColorEncoding, expressionData, cellSets, cellSetSelection, cellSetColor, obsIndex, theme, } = params;
79
+ if (cellColorEncoding === 'geneSelection' && expressionData && obsIndex) {
80
+ // TODO: allow other color maps.
81
+ const geneExpColormap = interpolatePlasma;
82
+ const colors = new Map();
83
+ for (let i = 0; i < expressionData.length; i += 1) {
84
+ const value = expressionData[i];
85
+ const cellColor = geneExpColormap(value / 255);
86
+ colors.set(obsIndex[i], cellColor);
87
+ }
88
+ return colors;
89
+ }
90
+ if (cellColorEncoding === 'cellSetSelection' && cellSetSelection && cellSets) {
91
+ // Cell sets can potentially lack set colors since the color property
92
+ // is not a required part of the schema.
93
+ // The `initializeSets` function fills in any empty colors
94
+ // with defaults and returns the processed tree object.
95
+ return treeToCellColorsBySetNames(cellSets, cellSetSelection, cellSetColor, theme);
96
+ }
97
+ if (obsIndex && theme) {
98
+ return new Map(obsIndex.map(o => ([o, getDefaultColor(theme)])));
99
+ }
100
+ return new Map();
101
+ }
@@ -0,0 +1,24 @@
1
+ import { interpolateRdBu, interpolatePlasma } from './interpolate-colors';
2
+ const expectRgb = ([testR, testG, testB], [r, g, b]) => ([
3
+ expect(testR).toBeCloseTo(r),
4
+ expect(testG).toBeCloseTo(g),
5
+ expect(testB).toBeCloseTo(b),
6
+ ]);
7
+ describe('components/interpolate-colors', () => {
8
+ describe('interpolateRdBu()', () => {
9
+ it('maps 0 to a red color', () => {
10
+ expectRgb(interpolateRdBu(0), [103, 0, 31]);
11
+ });
12
+ it('maps 1 to a blue color', () => {
13
+ expectRgb(interpolateRdBu(1), [5, 48, 97]);
14
+ });
15
+ });
16
+ describe('interpolatePlasma()', () => {
17
+ it('maps 0 to dark cool color', () => {
18
+ expectRgb(interpolatePlasma(0), [13, 8, 135]);
19
+ });
20
+ it('maps 1 to bright warm color', () => {
21
+ expectRgb(interpolatePlasma(1), [240, 249, 33]);
22
+ });
23
+ });
24
+ });
@@ -0,0 +1,109 @@
1
+ import { viv } from '@vitessce/gl';
2
+ import { Matrix4 } from 'math.gl';
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 = viv.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 = viv.getChannelStats(raster0.data);
25
+ const statsMid = viv.getChannelStats(rasterMid.data);
26
+ const statsTop = viv.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/root.js ADDED
@@ -0,0 +1,74 @@
1
+ /* eslint-disable no-plusplus */
2
+ // Originally in src/utils.js
3
+ // Adapted from https://github.com/feross/fromentries/blob/29b52a850bb3a47c390937631c2638edf3443942/index.js
4
+ export function fromEntries(iterable) {
5
+ return [...iterable]
6
+ .reduce((obj, { 0: key, 1: val }) => Object.assign(obj, { [key]: val }), {});
7
+ }
8
+ export function commaNumber(n) {
9
+ const nf = new Intl.NumberFormat('en-US');
10
+ return nf.format(n);
11
+ }
12
+ /**
13
+ * Capitalize a the first letter of a string.
14
+ * @param {string} word A string to capitalize.
15
+ * @returns {string} The word parameter with the first letter capitalized.
16
+ */
17
+ export function capitalize(word) {
18
+ return word ? word.charAt(0).toUpperCase() + word.slice(1) : '';
19
+ }
20
+ /**
21
+ * Get the longest string in the array of strings.
22
+ * @param {string[]} strings The array of strings.
23
+ * @returns The longest string.
24
+ */
25
+ export function getLongestString(strings) {
26
+ return strings.reduce((prevLongest, currentValue) => (prevLongest.length > currentValue.length ? prevLongest : currentValue));
27
+ }
28
+ /**
29
+ * Generate a new scope name which does not
30
+ * conflict / overlap with a previous scope name.
31
+ * Really these just need to be unique within the coordination object.
32
+ * So in theory they could be String(Math.random()) or uuidv4() or something.
33
+ * However it may be good to make them more human-readable and memorable
34
+ * since eventually we will want to expose a UI to update the coordination.
35
+ * @param {string[]} prevScopes Previous scope names.
36
+ * @returns {string} The new scope name.
37
+ */
38
+ export function getNextScope(prevScopes) {
39
+ // Keep an ordered list of valid characters.
40
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
41
+ // Store the value of the next character for each position
42
+ // in the new string.
43
+ // For example, [0] -> "A", [1] -> "B", [0, 1] -> "AB"
44
+ const nextCharIndices = [0];
45
+ // Generate a new scope name,
46
+ // potentially conflicting with an existing name.
47
+ // Reference: https://stackoverflow.com/a/12504061
48
+ function next() {
49
+ const r = [];
50
+ nextCharIndices.forEach((charIndex) => {
51
+ r.unshift(chars[charIndex]);
52
+ });
53
+ let increment = true;
54
+ for (let i = 0; i < nextCharIndices.length; i++) {
55
+ const val = ++nextCharIndices[i];
56
+ if (val >= chars.length) {
57
+ nextCharIndices[i] = 0;
58
+ }
59
+ else {
60
+ increment = false;
61
+ break;
62
+ }
63
+ }
64
+ if (increment) {
65
+ nextCharIndices.push(0);
66
+ }
67
+ return r.join('');
68
+ }
69
+ let nextScope;
70
+ do {
71
+ nextScope = next();
72
+ } while (prevScopes.includes(nextScope));
73
+ return nextScope;
74
+ }
@@ -0,0 +1,281 @@
1
+ import isEqual from 'lodash/isEqual';
2
+ import { viv } from '@vitessce/gl';
3
+ import { Matrix4 } from 'math.gl';
4
+ import { divide, compare, unit } from 'mathjs';
5
+ import { getMultiSelectionStats } from './layer-controller';
6
+ import { VIEWER_PALETTE } from './components';
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: viv.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
+ }
@@ -0,0 +1,8 @@
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
+ });
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@vitessce/utils",
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/sets": "2.0.0-beta.0",
17
+ "bowser": "^2.11.0",
18
+ "lodash": "^4.17.21",
19
+ "lz-string": "^1.4.4"
20
+ },
21
+ "scripts": {
22
+ "start": "tsc --watch",
23
+ "build": "tsc",
24
+ "test": "pnpm exec vitest --run -r ../../ --dir ."
25
+ }
26
+ }