@vitessce/sets-utils 2.0.2 → 2.0.3

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/utils.js ADDED
@@ -0,0 +1,149 @@
1
+ import tinycolor from 'tinycolor2';
2
+ import isEqual from 'lodash/isEqual';
3
+ import { PALETTE } from '@vitessce/utils';
4
+ import {
5
+ SETS_DATATYPE_OBS,
6
+ HIERARCHICAL_SCHEMAS,
7
+ } from './constants';
8
+
9
+ /**
10
+ * Execute a callback function based on a keypress event.
11
+ * @param {object} event The event from onKeyPress
12
+ * @param {string} key The key identifier to match.
13
+ * @param {Function} callback The function to execute.
14
+ */
15
+ export function callbackOnKeyPress(event, key, callback) {
16
+ if (event.key === key) {
17
+ event.preventDefault();
18
+ callback();
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Convert an array of [r, g, b] numbers to a hex color.
24
+ * @param {number[]} rgbArray The color [r, g, b] array.
25
+ * @returns {string} The hex color as a string.
26
+ */
27
+ export function colorArrayToString(rgbArray) {
28
+ return tinycolor({ r: rgbArray[0], g: rgbArray[1], b: rgbArray[2] }).toHexString();
29
+ }
30
+
31
+ /**
32
+ * Convert a string color representation to an array of [r,g,b].
33
+ * @param {string} colorString The color as a string.
34
+ * @returns {number[]} The color as an array.
35
+ */
36
+ export function colorStringToArray(colorString) {
37
+ const colorObj = tinycolor(colorString).toRgb();
38
+ return [colorObj.r, colorObj.g, colorObj.b];
39
+ }
40
+
41
+ /**
42
+ * Get a string of help text for coloring a particular hierarchy level.
43
+ * @param {integer} i The level. 1 for cluster, 2 for subcluster, etc.
44
+ * @returns {string} The tooltip text for coloring the level.
45
+ */
46
+ export function getLevelTooltipText(i) {
47
+ if (i === 0) return 'Color by hierarchy';
48
+ if (i <= 2) {
49
+ const subs = j => ('sub'.repeat(j));
50
+ return `Color by ${subs(i - 1)}cluster`;
51
+ }
52
+ return `Color by cluster level ${i}`;
53
+ }
54
+
55
+ export function isEqualOrPrefix(targetPath, testPath) {
56
+ if (targetPath.length <= testPath.length) {
57
+ return isEqual(targetPath, testPath.slice(0, targetPath.length));
58
+ }
59
+ return false;
60
+ }
61
+
62
+ export function tryRenamePath(targetPath, testPath, nextTargetPath) {
63
+ if (isEqualOrPrefix(targetPath, testPath)) {
64
+ return [...nextTargetPath, ...testPath.slice(nextTargetPath.length)];
65
+ }
66
+ return testPath;
67
+ }
68
+
69
+ export const PATH_SEP = '___';
70
+
71
+ export function pathToKey(path) {
72
+ return path.join(PATH_SEP);
73
+ }
74
+
75
+ // Moved from src/components/utils.js
76
+
77
+ export function getNextNumberedNodeName(nodes, prefix) {
78
+ let i = 1;
79
+ if (nodes) {
80
+ // eslint-disable-next-line no-loop-func
81
+ while (nodes.find(n => n.name === `${prefix}${i}`)) {
82
+ // eslint-disable-next-line no-plusplus
83
+ i++;
84
+ }
85
+ }
86
+ return `${prefix}${i}`;
87
+ }
88
+
89
+ /**
90
+ * Create a new selected cell set based on a cell selection.
91
+ * @param {string[]} cellSelection An array of cell IDs.
92
+ * @param {object[]} additionalCellSets The previous array of user-defined cell sets.
93
+ * @param {function} setCellSetSelection The setter function for cell set selections.
94
+ * @param {function} setAdditionalCellSets The setter function for user-defined cell sets.
95
+ */
96
+ export function setObsSelection(cellSelection, additionalCellSets, cellSetColor, setCellSetSelection, setAdditionalCellSets, setCellSetColor, setCellColorEncoding, prefix = 'Selection ') {
97
+ const CELL_SELECTIONS_LEVEL_ZERO_NAME = 'My Selections';
98
+
99
+ const selectionsLevelZeroNode = additionalCellSets?.tree.find(
100
+ n => n.name === CELL_SELECTIONS_LEVEL_ZERO_NAME,
101
+ );
102
+ const nextAdditionalCellSets = {
103
+ version: HIERARCHICAL_SCHEMAS[SETS_DATATYPE_OBS].latestVersion,
104
+ datatype: SETS_DATATYPE_OBS,
105
+ tree: [...(additionalCellSets ? additionalCellSets.tree : [])],
106
+ };
107
+
108
+ const nextName = getNextNumberedNodeName(selectionsLevelZeroNode?.children, prefix);
109
+ let colorIndex = 0;
110
+ if (selectionsLevelZeroNode) {
111
+ colorIndex = selectionsLevelZeroNode.children.length;
112
+ selectionsLevelZeroNode.children.push({
113
+ name: nextName,
114
+ set: cellSelection.map(d => [d, null]),
115
+ });
116
+ } else {
117
+ nextAdditionalCellSets.tree.push({
118
+ name: CELL_SELECTIONS_LEVEL_ZERO_NAME,
119
+ children: [
120
+ {
121
+ name: nextName,
122
+ set: cellSelection.map(d => [d, null]),
123
+ },
124
+ ],
125
+ });
126
+ }
127
+ setAdditionalCellSets(nextAdditionalCellSets);
128
+ const nextPath = ['My Selections', nextName];
129
+ setCellSetColor([
130
+ ...(cellSetColor || []),
131
+ {
132
+ path: nextPath,
133
+ color: PALETTE[colorIndex % PALETTE.length],
134
+ },
135
+ ]);
136
+ setCellSetSelection([nextPath]);
137
+ setCellColorEncoding('cellSetSelection');
138
+ }
139
+
140
+ export function mergeObsSets(cellSets, additionalCellSets) {
141
+ return {
142
+ version: HIERARCHICAL_SCHEMAS[SETS_DATATYPE_OBS].latestVersion,
143
+ datatype: SETS_DATATYPE_OBS,
144
+ tree: [
145
+ ...(cellSets ? cellSets.tree : []),
146
+ ...(additionalCellSets ? additionalCellSets.tree : []),
147
+ ],
148
+ };
149
+ }
@@ -1,87 +0,0 @@
1
- import { InternMap } from 'internmap';
2
- import { treeInitialize, nodeAppendChild, } from './cell-set-utils';
3
- import { SETS_DATATYPE_OBS, } from './constants';
4
- export function dataToCellSetsTree(data, options) {
5
- const [cellNames, cellSets, cellSetScores] = data;
6
- const cellSetsTree = treeInitialize(SETS_DATATYPE_OBS);
7
- cellSets.forEach((cellSetIds, j) => {
8
- const { name } = options[j];
9
- let levelZeroNode = {
10
- name,
11
- children: [],
12
- };
13
- if (cellSetIds.length > 0 && Array.isArray(cellSetIds[0])) {
14
- // Multi-level case.
15
- // TODO: throw a warning if the levels are not in order coarser->finer.
16
- const levelSets = new InternMap([], JSON.stringify);
17
- cellNames.forEach((id, i) => {
18
- const classes = cellSetIds.map(col => col[i]);
19
- if (levelSets.has(classes)) {
20
- levelSets.get(classes).push([id, null]);
21
- }
22
- else {
23
- levelSets.set(classes, [[id, null]]);
24
- }
25
- });
26
- const levels = Array.from(levelSets.keys());
27
- const getNextLevelNames = (levelSuffixes) => {
28
- const nextLevelNames = Array.from(new Set(levelSuffixes.map(l => l[0])));
29
- return nextLevelNames.sort((a, b) => a.localeCompare(b));
30
- };
31
- // Recursive function to create nodes.
32
- const getNode = (parentLevelPrefixes, currLevelName, childLevelSuffixes) => {
33
- const isLeaf = childLevelSuffixes.length === 0;
34
- const resultNode = {
35
- name: currLevelName,
36
- };
37
- if (isLeaf) {
38
- // Base case: this is a leaf node.
39
- resultNode.set = levelSets.get([...parentLevelPrefixes, currLevelName]);
40
- }
41
- else {
42
- // Are the remaining suffices redundant?
43
- // Consider ["Parent", "Child", "Child"]
44
- // where parentLevelPrefixes is ["Parent"] and currLevelName is "Child".
45
- const shouldBeLeaf = (childLevelSuffixes.length === 1
46
- && currLevelName === childLevelSuffixes[0][childLevelSuffixes[0].length - 1]);
47
- if (shouldBeLeaf) {
48
- resultNode.set = levelSets.get([...parentLevelPrefixes, currLevelName, ...childLevelSuffixes[0]]);
49
- }
50
- else {
51
- // Recursion, run getNode() on each of the unique names at the next level.
52
- const nextLevelNames = getNextLevelNames(childLevelSuffixes);
53
- resultNode.children = nextLevelNames
54
- .map(nextLevelName => getNode([...parentLevelPrefixes, currLevelName], nextLevelName, childLevelSuffixes
55
- .filter(l => l[0] === nextLevelName)
56
- .map(l => l.slice(1))
57
- .filter(v => v.length > 0)));
58
- }
59
- }
60
- return resultNode;
61
- };
62
- // Start the recursion.
63
- const levelOneNodes = getNextLevelNames(levels)
64
- .map(levelOneName => getNode([], levelOneName, levels.filter(l => l[0] === levelOneName).map(l => l.slice(1))));
65
- levelZeroNode.children = levelOneNodes;
66
- }
67
- else {
68
- // Single-level case.
69
- // Check for the optional corresponding confidence score column name.
70
- const uniqueCellSetIds = Array.from(new Set(cellSetIds)).sort();
71
- const clusters = {};
72
- // eslint-disable-next-line no-return-assign
73
- uniqueCellSetIds.forEach(id => (clusters[id] = { name: id, set: [] }));
74
- if (cellSetScores[j]) {
75
- cellSetIds.forEach((id, i) => clusters[id].set.push([cellNames[i], cellSetScores[j][i]]));
76
- }
77
- else {
78
- cellSetIds.forEach((id, i) => clusters[id].set.push([cellNames[i], null]));
79
- }
80
- Object.values(clusters).forEach(
81
- // eslint-disable-next-line no-return-assign
82
- cluster => (levelZeroNode = nodeAppendChild(levelZeroNode, cluster)));
83
- }
84
- cellSetsTree.tree.push(levelZeroNode);
85
- });
86
- return cellSetsTree;
87
- }
@@ -1,148 +0,0 @@
1
- import { dataToCellSetsTree } from './CellSetsZarrLoader';
2
- describe('loaders/CellSetsZarrLoader', () => {
3
- it('dataToCellSetsTree constructs a hierarchy from an array of columns', async () => {
4
- const data = [
5
- ['cell_1', 'cell_2', 'cell_3', 'cell_4'],
6
- [
7
- [
8
- ['Immune', 'Immune', 'Immune', 'Neuron'],
9
- ['B cell', 'B cell', 'B cell', 'Excitatory neuron'],
10
- ['CD19+', 'CD19-', 'CD19-', 'Retinal bipolar neuron'],
11
- ],
12
- ],
13
- [undefined],
14
- ];
15
- const options = [
16
- { name: 'Subclass Levels', path: ['obs/L1', 'obs/L2', 'obs/L3'] },
17
- ];
18
- const tree = dataToCellSetsTree(data, options);
19
- expect(tree).toEqual({
20
- version: '0.1.3',
21
- datatype: 'obs',
22
- tree: [
23
- {
24
- name: 'Subclass Levels',
25
- children: [
26
- {
27
- name: 'Immune',
28
- children: [
29
- {
30
- name: 'B cell',
31
- children: [
32
- {
33
- name: 'CD19-',
34
- set: [
35
- ['cell_2', null],
36
- ['cell_3', null],
37
- ],
38
- },
39
- {
40
- name: 'CD19+',
41
- set: [
42
- ['cell_1', null],
43
- ],
44
- },
45
- ],
46
- },
47
- ],
48
- },
49
- {
50
- name: 'Neuron',
51
- children: [
52
- {
53
- name: 'Excitatory neuron',
54
- children: [
55
- {
56
- name: 'Retinal bipolar neuron',
57
- set: [
58
- ['cell_4', null],
59
- ],
60
- },
61
- ],
62
- },
63
- ],
64
- },
65
- ],
66
- },
67
- ],
68
- });
69
- });
70
- it('dataToCellSetsTree creates a flat tree from a single column', async () => {
71
- const data = [
72
- ['cell_1', 'cell_2', 'cell_3', 'cell_4'],
73
- [
74
- ['Immune', 'Immune', 'Immune', 'Neuron'],
75
- ],
76
- [undefined],
77
- ];
78
- const options = [
79
- { name: 'Subclass Level 1', path: 'obs/L1' },
80
- ];
81
- const tree = dataToCellSetsTree(data, options);
82
- expect(tree).toEqual({
83
- version: '0.1.3',
84
- datatype: 'obs',
85
- tree: [
86
- {
87
- name: 'Subclass Level 1',
88
- children: [
89
- {
90
- name: 'Immune',
91
- set: [
92
- ['cell_1', null],
93
- ['cell_2', null],
94
- ['cell_3', null],
95
- ],
96
- },
97
- {
98
- name: 'Neuron',
99
- set: [
100
- ['cell_4', null],
101
- ],
102
- },
103
- ],
104
- },
105
- ],
106
- });
107
- });
108
- it('dataToCellSetsTree creates a flat tree from a single column with scores', async () => {
109
- const data = [
110
- ['cell_1', 'cell_2', 'cell_3', 'cell_4'],
111
- [
112
- ['Immune', 'Immune', 'Immune', 'Neuron'],
113
- ],
114
- [
115
- [0.25, 0.5, 0.6, 0.1],
116
- ],
117
- ];
118
- const options = [
119
- { name: 'Subclass Level 1', path: 'obs/L1' },
120
- ];
121
- const tree = dataToCellSetsTree(data, options);
122
- expect(tree).toEqual({
123
- version: '0.1.3',
124
- datatype: 'obs',
125
- tree: [
126
- {
127
- name: 'Subclass Level 1',
128
- children: [
129
- {
130
- name: 'Immune',
131
- set: [
132
- ['cell_1', 0.25],
133
- ['cell_2', 0.5],
134
- ['cell_3', 0.6],
135
- ],
136
- },
137
- {
138
- name: 'Neuron',
139
- set: [
140
- ['cell_4', 0.1],
141
- ],
142
- },
143
- ],
144
- },
145
- ],
146
- });
147
- });
148
- });