@vitessce/sets-utils 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.
@@ -0,0 +1,112 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import { cloneDeep } from 'lodash';
3
+ import { nodeToRenderProps, nodeToSet, nodeToHeight, treeFindNodeByNamePath, nodeTransform, treeToUnion, treeToIntersection, treeToComplement, nodeToLevelDescendantNamePaths, treeExport, filterNode, } from './cell-set-utils';
4
+ import { levelTwoNodeLeaf, levelZeroNode, tree, } from './cell-set-utils.test.fixtures';
5
+ describe('Hierarchical sets cell-set-utils', () => {
6
+ describe('Node rendering', () => {
7
+ it('can get render properties for a node', () => {
8
+ const levelTwoRenderProps = nodeToRenderProps(levelTwoNodeLeaf, ['Cell Type Annotations', 'Vasculature', 'Pericytes'], [{
9
+ path: ['Cell Type Annotations', 'Vasculature', 'Pericytes'],
10
+ color: [255, 0, 0],
11
+ }]);
12
+ expect(levelTwoRenderProps.title).toEqual('Pericytes');
13
+ expect(levelTwoRenderProps.size).toEqual(3);
14
+ expect(levelTwoRenderProps.color).toEqual([255, 0, 0]);
15
+ expect(levelTwoRenderProps.level).toEqual(2);
16
+ expect(levelTwoRenderProps.isLeaf).toEqual(true);
17
+ expect(levelTwoRenderProps.height).toEqual(0);
18
+ const levelZeroRenderProps = nodeToRenderProps(levelZeroNode, ['Cell Type Annotations'], []);
19
+ expect(levelZeroRenderProps.title).toEqual('Cell Type Annotations');
20
+ expect(levelZeroRenderProps.size).toEqual(6);
21
+ expect(levelZeroRenderProps.color).toEqual(undefined);
22
+ expect(levelZeroRenderProps.level).toEqual(0);
23
+ expect(levelZeroRenderProps.isLeaf).toEqual(false);
24
+ expect(levelZeroRenderProps.height).toEqual(2);
25
+ });
26
+ });
27
+ describe('Get derived Node properties', () => {
28
+ it('Get children set for Node', () => {
29
+ const nodeSet = nodeToSet(levelZeroNode);
30
+ expect(nodeSet).toEqual([['cell_1', null], ['cell_2', null], ['cell_3', null], ['cell_4', null], ['cell_5', null], ['cell_6', null]]);
31
+ });
32
+ it('Get height for Node', () => {
33
+ const nodeHeight = nodeToHeight(levelZeroNode);
34
+ expect(nodeHeight).toEqual(2);
35
+ const nodeHeightZero = nodeToHeight(levelTwoNodeLeaf);
36
+ expect(nodeHeightZero).toEqual(0);
37
+ });
38
+ it('Get Node by Path', () => {
39
+ const node = treeFindNodeByNamePath(tree, ['Cell Type Annotations', 'Vasculature', 'Pericytes']);
40
+ expect(node.name).toEqual('Pericytes');
41
+ const noNode = treeFindNodeByNamePath(tree, ['Cell Type Annotations', 'Foo', 'Bar']);
42
+ expect(noNode).toEqual(null);
43
+ });
44
+ it('Filter node by path', () => {
45
+ const node = tree.tree[0];
46
+ const newNodeFiltered = filterNode(node, [], ['Cell Type Annotations', 'Vasculature', 'Pericytes']);
47
+ // eslint-disable-next-line no-return-assign
48
+ expect(newNodeFiltered.children[0].children.findIndex(i => i.name === 'Pericytes')).toEqual(-1);
49
+ const vasculatureNode = tree.tree[0].children.find(i => i.name === 'Vasculature');
50
+ const newNodeFilteredFromLevel1 = filterNode(vasculatureNode, ['Cell Type Annotations'], ['Cell Type Annotations', 'Vasculature', 'Pericytes']);
51
+ expect(newNodeFilteredFromLevel1.children.findIndex(i => i.name === 'Pericytes')).toEqual(-1);
52
+ });
53
+ });
54
+ describe('Alter Node properties', () => {
55
+ it('Node Transform', () => {
56
+ const nodeTransformedWithPredicate = nodeTransform(cloneDeep(levelZeroNode), node => node.name === 'Pericytes',
57
+ // eslint-disable-next-line no-param-reassign
58
+ (node) => { node.name = 'New name'; return node; }, [], ['Cell Type Annotations']);
59
+ // Node matching predicate is transformed but none others
60
+ expect(nodeTransformedWithPredicate.name).toEqual('Cell Type Annotations');
61
+ expect(nodeTransformedWithPredicate.children[0].children[0].name).toEqual('New name');
62
+ // eslint-disable-next-line no-param-reassign
63
+ const nodeTransformedWithoutPredicate = nodeTransform(cloneDeep(levelZeroNode), () => false,
64
+ // eslint-disable-next-line no-param-reassign
65
+ (node) => { node.name = 'New name'; return node; }, [], ['Cell Type Annotations']);
66
+ // No nodes transformed for fals-y predicate.
67
+ expect(nodeTransformedWithoutPredicate.name).toEqual('Cell Type Annotations');
68
+ expect(nodeTransformedWithoutPredicate.children[0].children[0].name).toEqual('Pericytes');
69
+ });
70
+ });
71
+ describe('Get from tree', () => {
72
+ it('Tree Union', () => {
73
+ const union = treeToUnion(tree, [
74
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
75
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
76
+ ]);
77
+ expect(union).toEqual(['cell_3', 'cell_4', 'cell_5', 'cell_6', 'cell_7']);
78
+ });
79
+ it('Tree Intersection', () => {
80
+ const union = treeToIntersection(tree, [
81
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
82
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
83
+ ]);
84
+ expect(union).toEqual(['cell_5']);
85
+ });
86
+ it('Tree Union Complement', () => {
87
+ const complement = treeToComplement(tree, [
88
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
89
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
90
+ ], ['cell_6', 'cell_7', 'cell_8']);
91
+ expect(complement).toEqual(['cell_8']);
92
+ });
93
+ it('Node Descendants by Level', () => {
94
+ const descendants = nodeToLevelDescendantNamePaths(tree.tree[0], 2, []);
95
+ expect(descendants).toEqual([['Cell Type Annotations', 'Vasculature', 'Epithelial']]);
96
+ const descendantsStopEarly = nodeToLevelDescendantNamePaths(tree.tree[0], 2, [], true);
97
+ expect(descendantsStopEarly).toEqual([['Cell Type Annotations', 'Vasculature', 'Pericytes'],
98
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
99
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial']]);
100
+ });
101
+ it('Tree export', () => {
102
+ const exportedTree = treeExport(tree, 'cell');
103
+ // Clears state going deeply
104
+ expect(exportedTree.tree[0].children[0]._state).toEqual(undefined);
105
+ expect(exportedTree.tree[0].children[0].children[0]._state).toEqual(undefined);
106
+ // Tree still has same names for nodes
107
+ expect(exportedTree.tree[0].children[0].name).toEqual(tree.tree[0].children[0].name);
108
+ expect(exportedTree.tree[0].children[0].children[0].name)
109
+ .toEqual(tree.tree[0].children[0].children[0].name);
110
+ });
111
+ });
112
+ });
@@ -0,0 +1,28 @@
1
+ import { obsSetsSchema, obsSetsTabularSchema } from '@vitessce/vit-s';
2
+ export const FILE_EXTENSION_JSON = 'json';
3
+ export const MIME_TYPE_JSON = 'application/json';
4
+ export const FILE_EXTENSION_TABULAR = 'csv';
5
+ export const MIME_TYPE_TABULAR = 'text/csv';
6
+ export const SEPARATOR_TABULAR = ',';
7
+ // The NA value below corresponds to the allowed string enum
8
+ // value "NA" in the cell-sets-tabular JSON schema.
9
+ export const NA_VALUE_TABULAR = 'NA';
10
+ export const SETS_DATATYPE_OBS = 'obs';
11
+ export const HIERARCHICAL_SCHEMAS = {
12
+ cell: {
13
+ latestVersion: '0.1.3',
14
+ schema: obsSetsSchema,
15
+ },
16
+ obs: {
17
+ latestVersion: '0.1.3',
18
+ schema: obsSetsSchema,
19
+ },
20
+ };
21
+ export const TABULAR_SCHEMAS = {
22
+ cell: {
23
+ schema: obsSetsTabularSchema,
24
+ },
25
+ obs: {
26
+ schema: obsSetsTabularSchema,
27
+ },
28
+ };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { treeToCellColorsBySetNames, treeToSetSizesBySetNames, treeToObjectsBySetNames, treeExportLevelZeroNode, treeExportSet, treeToExpectedCheckedLevel, nodeToLevelDescendantNamePaths, treeToIntersection, treeToUnion, treeToComplement, treeFindNodeByNamePath, treesConflict, nodeTransform, nodeAppendChild, nodePrependChild, nodeInsertChild, filterNode, treeInitialize, initializeCellSetColor, nodeToRenderProps, getCellSetPolygons, treeToMembershipMap, nodeToSet, } from './cell-set-utils';
2
+ export { isEqualOrPrefix, tryRenamePath, PATH_SEP, setObsSelection, mergeObsSets, getNextNumberedNodeName, colorArrayToString, callbackOnKeyPress, getLevelTooltipText, pathToKey, } from './utils';
3
+ export { downloadForUser, handleExportJSON, handleExportTabular, tryUpgradeTreeToLatestSchema, handleImportJSON, handleImportTabular, } from './io';
4
+ export { FILE_EXTENSION_JSON, FILE_EXTENSION_TABULAR, SETS_DATATYPE_OBS, MIME_TYPE_JSON, MIME_TYPE_TABULAR, } from './constants';
5
+ export { dataToCellSetsTree, } from './CellSetsZarrLoader';
package/dist/io.js ADDED
@@ -0,0 +1,164 @@
1
+ import Ajv from 'ajv';
2
+ import isNil from 'lodash/isNil';
3
+ import { dsvFormat } from 'd3-dsv';
4
+ // TODO(monorepo): try to find a different package for this.
5
+ // Reference: https://github.com/zemirco/json2csv/issues/539
6
+ import { Parser } from 'json2csv/dist/json2csv.umd';
7
+ import { getDefaultColor } from '@vitessce/utils';
8
+ import { colorArrayToString, colorStringToArray } from './utils';
9
+ import { nodeTransform } from './cell-set-utils';
10
+ import { HIERARCHICAL_SCHEMAS, TABULAR_SCHEMAS, MIME_TYPE_JSON, MIME_TYPE_TABULAR, SEPARATOR_TABULAR, NA_VALUE_TABULAR, } from './constants';
11
+ /**
12
+ * Check if an imported tree has an old schema version that we know how to
13
+ * "upgrade" to the latest schema version. Validate against the schema.
14
+ * @param {object} currTree A hierarchical tree object with a .version property,
15
+ * which has already passed schema validation, but may not have the latest schema version.
16
+ * @param {string} datatype The data type of the items in the schema.
17
+ */
18
+ export function tryUpgradeTreeToLatestSchema(currTree, datatype) {
19
+ const validate = new Ajv().compile(HIERARCHICAL_SCHEMAS[datatype].schema);
20
+ const valid = validate(currTree);
21
+ if (!valid) {
22
+ const failureReason = JSON.stringify(validate.errors, null, 2);
23
+ throw new Error(`Tree validation failed: ${failureReason}`);
24
+ }
25
+ else if (currTree.datatype !== datatype) {
26
+ throw new Error(`The data type does not match the expected data type of '${datatype}'.`);
27
+ }
28
+ if (currTree.version === '0.1.2') {
29
+ // To upgrade from cell-sets schema 0.1.2 to 0.1.3,
30
+ // add a confidence value of null for each cell ID.
31
+ return {
32
+ ...currTree,
33
+ version: HIERARCHICAL_SCHEMAS[datatype].latestVersion,
34
+ tree: currTree.tree.map(levelZeroNode => nodeTransform(levelZeroNode, n => !n.children && Array.isArray(n.set), n => ({ ...n, set: n.set.map(itemId => ([itemId, null])) }), [])),
35
+ };
36
+ }
37
+ return currTree;
38
+ }
39
+ /**
40
+ * Handler for JSON imports. Validates and upgrades against the hierarchical sets schema.
41
+ * @param {string} result The data passed from the FileReader as a string.
42
+ * @param {string} datatype The data type to validate against.
43
+ * @param {string} theme "light" or "dark" for the vitessce theme
44
+ * @returns {object} The imported tree object.
45
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
46
+ */
47
+ // eslint-disable-next-line no-unused-vars
48
+ export function handleImportJSON(result, datatype, theme) {
49
+ let importData = JSON.parse(result);
50
+ // Validate the imported file.
51
+ importData = tryUpgradeTreeToLatestSchema(importData, datatype);
52
+ return importData;
53
+ }
54
+ /**
55
+ * Handler for tabular imports. Validates against the tabular sets schema.
56
+ * @param {string} result The data passed from the FileReader as a string.
57
+ * @param {string} datatype The data type to validate against.
58
+ * @param {string} theme "light" or "dark" for the vitessce theme
59
+ * @returns {object} The imported tree object.
60
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
61
+ */
62
+ export function handleImportTabular(result, datatype, theme) {
63
+ const dsvParser = dsvFormat(SEPARATOR_TABULAR);
64
+ const importData = dsvParser.parse(result, row => ({
65
+ groupName: row.groupName,
66
+ setName: row.setName,
67
+ setColor: (row.setColor ? colorStringToArray(row.setColor) : getDefaultColor(theme)),
68
+ obsId: row.obsId,
69
+ predictionScore: ((isNil(row.predictionScore)
70
+ || row.predictionScore === NA_VALUE_TABULAR)
71
+ ? null
72
+ : +row.predictionScore),
73
+ }));
74
+ // Validate the imported file.
75
+ const validate = new Ajv().compile(TABULAR_SCHEMAS[datatype].schema);
76
+ const valid = validate(importData);
77
+ if (!valid) {
78
+ const failureReason = JSON.stringify(validate.errors, null, 2);
79
+ throw new Error(`Import validation failed: ${failureReason}`);
80
+ }
81
+ else {
82
+ // Convert the validated array to a tree representation.
83
+ const treeToImport = {
84
+ version: HIERARCHICAL_SCHEMAS[datatype].latestVersion,
85
+ datatype,
86
+ tree: [],
87
+ };
88
+ const uniqueGroupNames = Array.from(new Set(importData.map(d => d.groupName)));
89
+ uniqueGroupNames.forEach((groupName) => {
90
+ const levelZeroNode = {
91
+ name: groupName,
92
+ children: [],
93
+ };
94
+ const groupRows = importData.filter(d => d.groupName === groupName);
95
+ const uniqueSetNames = Array.from(new Set(groupRows.map(d => d.setName)));
96
+ uniqueSetNames.forEach((setName) => {
97
+ const setRows = groupRows.filter(d => d.setName === setName);
98
+ const { setColor } = setRows[0];
99
+ const levelOneNode = {
100
+ name: setName,
101
+ color: setColor,
102
+ set: setRows.map(d => ([d.obsId, d.predictionScore])),
103
+ };
104
+ levelZeroNode.children.push(levelOneNode);
105
+ });
106
+ treeToImport.tree.push(levelZeroNode);
107
+ });
108
+ return treeToImport;
109
+ }
110
+ }
111
+ /**
112
+ * Convert a tree object to a JSON representation.
113
+ * @param {object} result The object to export.
114
+ * @returns {string} The data in a string representation.
115
+ */
116
+ export function handleExportJSON(result) {
117
+ const jsonString = JSON.stringify(result);
118
+ const dataString = `data:${MIME_TYPE_JSON};charset=utf-8,${encodeURIComponent(jsonString)}`;
119
+ return dataString;
120
+ }
121
+ /**
122
+ * Convert a tree object with one level (height === 1) to a tabular representation.
123
+ * @param {object} result The object to export.
124
+ * @returns {string} The data in a string representation.
125
+ */
126
+ export function handleExportTabular(result) {
127
+ // Convert a tree object to an array of JSON objects.
128
+ const exportData = [];
129
+ result.tree.forEach((levelZeroNode) => {
130
+ levelZeroNode.children.forEach((levelOneNode) => {
131
+ if (levelOneNode.set) {
132
+ levelOneNode.set.forEach(([obsId, prob]) => {
133
+ exportData.push({
134
+ groupName: levelZeroNode.name,
135
+ setName: levelOneNode.name,
136
+ setColor: colorArrayToString(levelOneNode.color),
137
+ obsId,
138
+ predictionScore: isNil(prob) ? NA_VALUE_TABULAR : prob,
139
+ });
140
+ });
141
+ }
142
+ });
143
+ });
144
+ const parser = new Parser({
145
+ fields: ['groupName', 'setName', 'setColor', 'obsId', 'predictionScore'],
146
+ delimiter: SEPARATOR_TABULAR,
147
+ });
148
+ const csvString = parser.parse(exportData);
149
+ const dataString = `data:${MIME_TYPE_TABULAR};charset=utf-8,${encodeURIComponent(csvString)}`;
150
+ return dataString;
151
+ }
152
+ /**
153
+ * Download a file. Appends and removes an anchor node in the DOM.
154
+ * @param {string} dataString The function that converts the data to a string.
155
+ * @param {string} fileName The name of the file to be downloaded.
156
+ */
157
+ export function downloadForUser(dataString, fileName) {
158
+ const downloadAnchorNode = document.createElement('a');
159
+ downloadAnchorNode.setAttribute('href', dataString);
160
+ downloadAnchorNode.setAttribute('download', fileName);
161
+ document.body.appendChild(downloadAnchorNode); // required for firefox
162
+ downloadAnchorNode.click();
163
+ downloadAnchorNode.remove();
164
+ }
@@ -0,0 +1,127 @@
1
+ import { handleImportJSON, handleExportJSON, handleImportTabular, handleExportTabular, } from './io';
2
+ const treeV012 = {
3
+ version: '0.1.2',
4
+ datatype: 'cell',
5
+ tree: [
6
+ {
7
+ name: 'Clustering Algorithm',
8
+ children: [
9
+ {
10
+ name: 'Cluster A',
11
+ color: [255, 0, 0],
12
+ set: ['cell_243', 'cell_271', 'cell_247', 'cell_248'],
13
+ },
14
+ ],
15
+ },
16
+ ],
17
+ };
18
+ const treeV013 = {
19
+ version: '0.1.3',
20
+ datatype: 'cell',
21
+ tree: [
22
+ {
23
+ name: 'Clustering Algorithm',
24
+ children: [
25
+ {
26
+ name: 'Cluster A',
27
+ color: [255, 0, 0],
28
+ set: [
29
+ ['cell_243', null],
30
+ ['cell_271', null],
31
+ ['cell_247', null],
32
+ ['cell_248', null],
33
+ ],
34
+ },
35
+ ],
36
+ },
37
+ ],
38
+ };
39
+ const treeV013WithPredictionScores = {
40
+ version: '0.1.3',
41
+ datatype: 'cell',
42
+ tree: [
43
+ {
44
+ name: 'Clustering Algorithm',
45
+ children: [
46
+ {
47
+ name: 'Cluster A',
48
+ color: [255, 0, 0],
49
+ set: [
50
+ ['cell_243', 0.5],
51
+ ['cell_271', 0.6],
52
+ ['cell_247', 0.12345],
53
+ ['cell_248', 0],
54
+ ],
55
+ },
56
+ ],
57
+ },
58
+ ],
59
+ };
60
+ const treeV012AsJson = JSON.stringify(treeV012);
61
+ const treeV013AsJson = JSON.stringify(treeV013);
62
+ const treeV013WithPredictionScoresAsJson = JSON.stringify(treeV013WithPredictionScores);
63
+ const expectedExportedJson = `data:application/json;charset=utf-8,${encodeURIComponent(treeV013AsJson)}`;
64
+ const expectedExportedJsonWithPredictionScores = `data:application/json;charset=utf-8,${encodeURIComponent(treeV013WithPredictionScoresAsJson)}`;
65
+ const treeV012AsCsv = `"groupName","setName","setColor","obsId"
66
+ "Clustering Algorithm","Cluster A","#ff0000","cell_243"
67
+ "Clustering Algorithm","Cluster A","#ff0000","cell_271"
68
+ "Clustering Algorithm","Cluster A","#ff0000","cell_247"
69
+ "Clustering Algorithm","Cluster A","#ff0000","cell_248"`;
70
+ const treeV013AsCsv = `"groupName","setName","setColor","obsId","predictionScore"
71
+ "Clustering Algorithm","Cluster A","#ff0000","cell_243","NA"
72
+ "Clustering Algorithm","Cluster A","#ff0000","cell_271","NA"
73
+ "Clustering Algorithm","Cluster A","#ff0000","cell_247","NA"
74
+ "Clustering Algorithm","Cluster A","#ff0000","cell_248","NA"`;
75
+ const expectedExportedTabular = `data:text/csv;charset=utf-8,${encodeURIComponent(treeV013AsCsv)}`;
76
+ const treeV013WithPredictionScoresAsCsv = `"groupName","setName","setColor","obsId","predictionScore"
77
+ "Clustering Algorithm","Cluster A","#ff0000","cell_243",0.5
78
+ "Clustering Algorithm","Cluster A","#ff0000","cell_271",0.6
79
+ "Clustering Algorithm","Cluster A","#ff0000","cell_247",0.12345
80
+ "Clustering Algorithm","Cluster A","#ff0000","cell_248",0`;
81
+ const expectedExportedTabularWithPredictionScores = `data:text/csv;charset=utf-8,${encodeURIComponent(treeV013WithPredictionScoresAsCsv)}`;
82
+ describe('io.js', () => {
83
+ describe('importing sets', () => {
84
+ it('can import cell sets from a JSON file v0.1.2', () => {
85
+ const importedTree = handleImportJSON(treeV012AsJson, 'cell');
86
+ expect(importedTree).toEqual(treeV013);
87
+ });
88
+ it('can import cell sets from a JSON file v0.1.3', () => {
89
+ const importedTree = handleImportJSON(treeV013AsJson, 'cell');
90
+ expect(importedTree).toEqual(treeV013);
91
+ });
92
+ it('can import cell sets from a JSON file v0.1.3 with prediction scores', () => {
93
+ const importedTree = handleImportJSON(treeV013WithPredictionScoresAsJson, 'cell');
94
+ expect(importedTree).toEqual(treeV013WithPredictionScores);
95
+ });
96
+ it('can import cell sets from a CSV file v0.1.2', () => {
97
+ const importedTree = handleImportTabular(treeV012AsCsv, 'cell');
98
+ expect(importedTree).toEqual(treeV013);
99
+ });
100
+ it('can import cell sets from a CSV file v0.1.3', () => {
101
+ const importedTree = handleImportTabular(treeV013AsCsv, 'cell');
102
+ expect(importedTree).toEqual(treeV013);
103
+ });
104
+ it('can import cell sets from a CSV file v0.1.3 with prediction scores', () => {
105
+ const importedTree = handleImportTabular(treeV013WithPredictionScoresAsCsv, 'cell');
106
+ expect(importedTree).toEqual(treeV013WithPredictionScores);
107
+ });
108
+ });
109
+ describe('exporting sets', () => {
110
+ it('can export sets to a JSON file v0.1.3', () => {
111
+ const dataString = handleExportJSON(treeV013);
112
+ expect(dataString).toEqual(expectedExportedJson);
113
+ });
114
+ it('can export sets to a JSON file v0.1.3 with prediction scores', () => {
115
+ const dataString = handleExportJSON(treeV013WithPredictionScores);
116
+ expect(dataString).toEqual(expectedExportedJsonWithPredictionScores);
117
+ });
118
+ it('can export sets to a CSV file v0.1.3', () => {
119
+ const dataString = handleExportTabular(treeV013);
120
+ expect(dataString).toEqual(expectedExportedTabular);
121
+ });
122
+ it('can export sets to a CSV file v0.1.3 with prediction scores', () => {
123
+ const dataString = handleExportTabular(treeV013WithPredictionScores);
124
+ expect(dataString).toEqual(expectedExportedTabularWithPredictionScores);
125
+ });
126
+ });
127
+ });
package/dist/utils.js ADDED
@@ -0,0 +1,132 @@
1
+ import tinycolor from 'tinycolor2';
2
+ import isEqual from 'lodash/isEqual';
3
+ import { PALETTE } from '@vitessce/utils';
4
+ import { SETS_DATATYPE_OBS, HIERARCHICAL_SCHEMAS, } from './constants';
5
+ /**
6
+ * Execute a callback function based on a keypress event.
7
+ * @param {object} event The event from onKeyPress
8
+ * @param {string} key The key identifier to match.
9
+ * @param {Function} callback The function to execute.
10
+ */
11
+ export function callbackOnKeyPress(event, key, callback) {
12
+ if (event.key === key) {
13
+ event.preventDefault();
14
+ callback();
15
+ }
16
+ }
17
+ /**
18
+ * Convert an array of [r, g, b] numbers to a hex color.
19
+ * @param {number[]} rgbArray The color [r, g, b] array.
20
+ * @returns {string} The hex color as a string.
21
+ */
22
+ export function colorArrayToString(rgbArray) {
23
+ return tinycolor({ r: rgbArray[0], g: rgbArray[1], b: rgbArray[2] }).toHexString();
24
+ }
25
+ /**
26
+ * Convert a string color representation to an array of [r,g,b].
27
+ * @param {string} colorString The color as a string.
28
+ * @returns {number[]} The color as an array.
29
+ */
30
+ export function colorStringToArray(colorString) {
31
+ const colorObj = tinycolor(colorString).toRgb();
32
+ return [colorObj.r, colorObj.g, colorObj.b];
33
+ }
34
+ /**
35
+ * Get a string of help text for coloring a particular hierarchy level.
36
+ * @param {integer} i The level. 1 for cluster, 2 for subcluster, etc.
37
+ * @returns {string} The tooltip text for coloring the level.
38
+ */
39
+ export function getLevelTooltipText(i) {
40
+ if (i === 0)
41
+ return 'Color by hierarchy';
42
+ if (i <= 2) {
43
+ const subs = j => ('sub'.repeat(j));
44
+ return `Color by ${subs(i - 1)}cluster`;
45
+ }
46
+ return `Color by cluster level ${i}`;
47
+ }
48
+ export function isEqualOrPrefix(targetPath, testPath) {
49
+ if (targetPath.length <= testPath.length) {
50
+ return isEqual(targetPath, testPath.slice(0, targetPath.length));
51
+ }
52
+ return false;
53
+ }
54
+ export function tryRenamePath(targetPath, testPath, nextTargetPath) {
55
+ if (isEqualOrPrefix(targetPath, testPath)) {
56
+ return [...nextTargetPath, ...testPath.slice(nextTargetPath.length)];
57
+ }
58
+ return testPath;
59
+ }
60
+ export const PATH_SEP = '___';
61
+ export function pathToKey(path) {
62
+ return path.join(PATH_SEP);
63
+ }
64
+ // Moved from src/components/utils.js
65
+ export function getNextNumberedNodeName(nodes, prefix) {
66
+ let i = 1;
67
+ if (nodes) {
68
+ // eslint-disable-next-line no-loop-func
69
+ while (nodes.find(n => n.name === `${prefix}${i}`)) {
70
+ // eslint-disable-next-line no-plusplus
71
+ i++;
72
+ }
73
+ }
74
+ return `${prefix}${i}`;
75
+ }
76
+ /**
77
+ * Create a new selected cell set based on a cell selection.
78
+ * @param {string[]} cellSelection An array of cell IDs.
79
+ * @param {object[]} additionalCellSets The previous array of user-defined cell sets.
80
+ * @param {function} setCellSetSelection The setter function for cell set selections.
81
+ * @param {function} setAdditionalCellSets The setter function for user-defined cell sets.
82
+ */
83
+ export function setObsSelection(cellSelection, additionalCellSets, cellSetColor, setCellSetSelection, setAdditionalCellSets, setCellSetColor, setCellColorEncoding, prefix = 'Selection ') {
84
+ const CELL_SELECTIONS_LEVEL_ZERO_NAME = 'My Selections';
85
+ const selectionsLevelZeroNode = additionalCellSets?.tree.find(n => n.name === CELL_SELECTIONS_LEVEL_ZERO_NAME);
86
+ const nextAdditionalCellSets = {
87
+ version: HIERARCHICAL_SCHEMAS[SETS_DATATYPE_OBS].latestVersion,
88
+ datatype: SETS_DATATYPE_OBS,
89
+ tree: [...(additionalCellSets ? additionalCellSets.tree : [])],
90
+ };
91
+ const nextName = getNextNumberedNodeName(selectionsLevelZeroNode?.children, prefix);
92
+ let colorIndex = 0;
93
+ if (selectionsLevelZeroNode) {
94
+ colorIndex = selectionsLevelZeroNode.children.length;
95
+ selectionsLevelZeroNode.children.push({
96
+ name: nextName,
97
+ set: cellSelection.map(d => [d, null]),
98
+ });
99
+ }
100
+ else {
101
+ nextAdditionalCellSets.tree.push({
102
+ name: CELL_SELECTIONS_LEVEL_ZERO_NAME,
103
+ children: [
104
+ {
105
+ name: nextName,
106
+ set: cellSelection.map(d => [d, null]),
107
+ },
108
+ ],
109
+ });
110
+ }
111
+ setAdditionalCellSets(nextAdditionalCellSets);
112
+ const nextPath = ['My Selections', nextName];
113
+ setCellSetColor([
114
+ ...(cellSetColor || []),
115
+ {
116
+ path: nextPath,
117
+ color: PALETTE[colorIndex % PALETTE.length],
118
+ },
119
+ ]);
120
+ setCellSetSelection([nextPath]);
121
+ setCellColorEncoding('cellSetSelection');
122
+ }
123
+ export function mergeObsSets(cellSets, additionalCellSets) {
124
+ return {
125
+ version: HIERARCHICAL_SCHEMAS[SETS_DATATYPE_OBS].latestVersion,
126
+ datatype: SETS_DATATYPE_OBS,
127
+ tree: [
128
+ ...(cellSets ? cellSets.tree : []),
129
+ ...(additionalCellSets ? additionalCellSets.tree : []),
130
+ ],
131
+ };
132
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@vitessce/sets-utils",
3
+ "version": "2.0.1",
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
+ "@turf/centroid": "^6.5.0",
17
+ "@turf/helpers": "^6.5.0",
18
+ "ajv": "^6.10.0",
19
+ "concaveman": "^1.2.1",
20
+ "d3-dsv": "^1.1.1",
21
+ "internmap": "^2.0.3",
22
+ "json2csv": "^5.0.0",
23
+ "lodash": "^4.17.21",
24
+ "tinycolor2": "^1.4.1",
25
+ "uuid": "^3.3.2",
26
+ "@vitessce/utils": "2.0.1",
27
+ "@vitessce/vit-s": "2.0.1"
28
+ },
29
+ "scripts": {
30
+ "start": "tsc --watch",
31
+ "build": "tsc",
32
+ "test": "pnpm exec vitest --run -r ../../../ --dir ."
33
+ }
34
+ }