@vitessce/sets-utils 2.0.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{index.mjs → index.js} +9301 -7998
  2. package/dist-tsc/CellSetsZarrLoader.d.ts +2 -0
  3. package/dist-tsc/CellSetsZarrLoader.d.ts.map +1 -0
  4. package/dist-tsc/CellSetsZarrLoader.js +91 -0
  5. package/dist-tsc/CellSetsZarrLoader.test.d.ts +2 -0
  6. package/dist-tsc/CellSetsZarrLoader.test.d.ts.map +1 -0
  7. package/dist-tsc/CellSetsZarrLoader.test.js +154 -0
  8. package/dist-tsc/cell-set-utils.d.ts +204 -0
  9. package/dist-tsc/cell-set-utils.d.ts.map +1 -0
  10. package/dist-tsc/cell-set-utils.js +630 -0
  11. package/dist-tsc/cell-set-utils.test.d.ts +2 -0
  12. package/dist-tsc/cell-set-utils.test.d.ts.map +1 -0
  13. package/dist-tsc/cell-set-utils.test.fixtures.d.ts +47 -0
  14. package/dist-tsc/cell-set-utils.test.fixtures.d.ts.map +1 -0
  15. package/dist-tsc/cell-set-utils.test.fixtures.js +68 -0
  16. package/dist-tsc/cell-set-utils.test.js +185 -0
  17. package/dist-tsc/constants.d.ts +17 -0
  18. package/dist-tsc/constants.d.ts.map +1 -0
  19. package/dist-tsc/constants.js +17 -0
  20. package/dist-tsc/index.d.ts +7 -0
  21. package/dist-tsc/index.d.ts.map +1 -0
  22. package/dist-tsc/index.js +6 -5
  23. package/dist-tsc/io.d.ts +47 -0
  24. package/dist-tsc/io.d.ts.map +1 -0
  25. package/dist-tsc/io.js +159 -0
  26. package/dist-tsc/io.test.d.ts +2 -0
  27. package/dist-tsc/io.test.d.ts.map +1 -0
  28. package/dist-tsc/io.test.js +124 -0
  29. package/dist-tsc/set-path-utils.d.ts +28 -0
  30. package/dist-tsc/set-path-utils.d.ts.map +1 -0
  31. package/dist-tsc/set-path-utils.js +133 -0
  32. package/dist-tsc/set-path-utils.test.d.ts +2 -0
  33. package/dist-tsc/set-path-utils.test.d.ts.map +1 -0
  34. package/dist-tsc/set-path-utils.test.js +210 -0
  35. package/dist-tsc/utils.d.ts +45 -0
  36. package/dist-tsc/utils.d.ts.map +1 -0
  37. package/dist-tsc/utils.js +139 -0
  38. package/dist-tsc/utils.test.d.ts +2 -0
  39. package/dist-tsc/utils.test.d.ts.map +1 -0
  40. package/dist-tsc/utils.test.js +39 -0
  41. package/package.json +16 -8
  42. package/src/CellSetsZarrLoader.js +2 -2
  43. package/src/CellSetsZarrLoader.test.js +1 -1
  44. package/src/cell-set-utils.js +33 -16
  45. package/src/cell-set-utils.test.js +105 -4
  46. package/src/constants.js +4 -15
  47. package/src/index.js +11 -5
  48. package/src/io.js +25 -35
  49. package/src/io.test.js +1 -4
  50. package/src/set-path-utils.js +155 -0
  51. package/src/set-path-utils.test.js +257 -0
  52. package/src/utils.js +20 -9
  53. package/src/utils.test.js +48 -0
@@ -0,0 +1,68 @@
1
+ export const levelTwoNodeLeaf = {
2
+ name: 'Pericytes',
3
+ set: [['cell_1', null], ['cell_2', null], ['cell_3', null]],
4
+ };
5
+ export const levelOneNode = {
6
+ name: 'Vasculature',
7
+ children: [
8
+ {
9
+ name: 'Pericytes',
10
+ set: [['cell_1', null], ['cell_2', null], ['cell_3', null]],
11
+ },
12
+ {
13
+ name: 'Endothelial',
14
+ set: [['cell_4', null], ['cell_5', null], ['cell_6', null]],
15
+ },
16
+ ],
17
+ };
18
+ export const levelZeroNode = {
19
+ name: 'Cell Type Annotations',
20
+ children: [
21
+ {
22
+ name: 'Vasculature',
23
+ children: [
24
+ {
25
+ name: 'Pericytes',
26
+ set: [['cell_1', null], ['cell_2', null], ['cell_3', null]],
27
+ },
28
+ {
29
+ name: 'Endothelial',
30
+ set: [['cell_4', null], ['cell_5', null], ['cell_6', null]],
31
+ },
32
+ ],
33
+ },
34
+ ],
35
+ };
36
+ export const tree = {
37
+ version: '0.1.3',
38
+ datatype: 'cell',
39
+ tree: [
40
+ {
41
+ name: 'Cell Type Annotations',
42
+ children: [
43
+ {
44
+ name: 'Vasculature',
45
+ children: [
46
+ {
47
+ name: 'Pericytes',
48
+ set: [['cell_1', null], ['cell_2', null], ['cell_3', null]],
49
+ },
50
+ {
51
+ name: 'Endothelial',
52
+ set: [['cell_3', null], ['cell_4', null], ['cell_5', null]],
53
+ },
54
+ {
55
+ name: 'Epithelial',
56
+ children: [
57
+ {
58
+ name: 'Squamous',
59
+ set: [['cell_5', null], ['cell_6', null], ['cell_7', null]],
60
+ },
61
+ ],
62
+ },
63
+ ],
64
+ },
65
+ ],
66
+ },
67
+ ],
68
+ };
@@ -0,0 +1,185 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import { cloneDeep } from 'lodash-es';
3
+ import { nodeToRenderProps, nodeToSet, nodeToHeight, treeFindNodeByNamePath, nodeTransform, treeToUnion, treeToIntersection, treeToComplement, nodeToLevelDescendantNamePaths, treeExport, filterNode, treeToSetSizesBySetNames, } from './cell-set-utils.js';
4
+ import { levelTwoNodeLeaf, levelZeroNode, tree, } from './cell-set-utils.test.fixtures.js';
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('Generate properties from paths', () => {
72
+ it('treeToSetSizesBySetNames where one bar is selected', () => {
73
+ const setColor = [
74
+ {
75
+ path: ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
76
+ color: [255, 0, 0],
77
+ },
78
+ {
79
+ path: ['Cell Type Annotations', 'Vasculature'],
80
+ color: [68, 119, 170],
81
+ },
82
+ ];
83
+ const setSizes = treeToSetSizesBySetNames(tree, [['Cell Type Annotations', 'Vasculature', 'Endothelial'], ['Cell Type Annotations', 'Vasculature']], [['Cell Type Annotations', 'Vasculature', 'Endothelial']], setColor, 'dark');
84
+ expect(setSizes.length).toEqual(2);
85
+ expect(setSizes[0].name).toEqual('Endothelial');
86
+ expect(setSizes[0].size).toEqual(3);
87
+ expect(setSizes[0].color).toEqual([255, 0, 0]);
88
+ expect(setSizes[0].isGrayedOut).toEqual(false);
89
+ expect(setSizes[0].setNamePath).toEqual(['Cell Type Annotations', 'Vasculature', 'Endothelial']);
90
+ expect(setSizes[1].name).toEqual('Vasculature');
91
+ expect(setSizes[1].size).toEqual(9);
92
+ expect(setSizes[1].color).toEqual([68, 119, 170]);
93
+ expect(setSizes[1].isGrayedOut).toEqual(true);
94
+ });
95
+ it('treeToSetSizesBySetNames where nothing is selected', () => {
96
+ const setColor = [
97
+ {
98
+ path: ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
99
+ color: [255, 0, 0],
100
+ },
101
+ {
102
+ path: ['Cell Type Annotations', 'Vasculature'],
103
+ color: [68, 119, 170],
104
+ },
105
+ ];
106
+ const setSizes = treeToSetSizesBySetNames(tree, [['Cell Type Annotations', 'Vasculature', 'Endothelial'], ['Cell Type Annotations', 'Vasculature']], [], setColor, 'dark');
107
+ expect(setSizes.length).toEqual(2);
108
+ expect(setSizes[0].name).toEqual('Endothelial');
109
+ expect(setSizes[0].size).toEqual(3);
110
+ expect(setSizes[0].color).toEqual([255, 0, 0]);
111
+ expect(setSizes[0].isGrayedOut).toEqual(true);
112
+ expect(setSizes[0].setNamePath).toEqual(['Cell Type Annotations', 'Vasculature', 'Endothelial']);
113
+ expect(setSizes[1].name).toEqual('Vasculature');
114
+ expect(setSizes[1].size).toEqual(9);
115
+ expect(setSizes[1].color).toEqual([68, 119, 170]);
116
+ expect(setSizes[1].isGrayedOut).toEqual(true);
117
+ expect(setSizes[1].setNamePath).toEqual(['Cell Type Annotations', 'Vasculature']);
118
+ });
119
+ it('treeToSetSizesBySetNames where selected paths are not part of all paths', () => {
120
+ const setColor = [
121
+ {
122
+ path: ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
123
+ color: [255, 0, 0],
124
+ },
125
+ {
126
+ path: ['Cell Type Annotations', 'Vasculature'],
127
+ color: [68, 119, 170],
128
+ },
129
+ ];
130
+ const setSizes = treeToSetSizesBySetNames(tree, [['Cell Type Annotations', 'Vasculature', 'Endothelial'], ['Cell Type Annotations', 'Vasculature']], [['Louvain Clusters', '0'], ['Louvain Clusters', '1']], setColor, 'dark');
131
+ expect(setSizes.length).toEqual(2);
132
+ expect(setSizes[0].name).toEqual('Endothelial');
133
+ expect(setSizes[0].size).toEqual(3);
134
+ expect(setSizes[0].color).toEqual([255, 0, 0]);
135
+ expect(setSizes[0].isGrayedOut).toEqual(true);
136
+ expect(setSizes[0].setNamePath).toEqual(['Cell Type Annotations', 'Vasculature', 'Endothelial']);
137
+ expect(setSizes[1].name).toEqual('Vasculature');
138
+ expect(setSizes[1].size).toEqual(9);
139
+ expect(setSizes[1].color).toEqual([68, 119, 170]);
140
+ expect(setSizes[1].isGrayedOut).toEqual(true);
141
+ expect(setSizes[1].setNamePath).toEqual(['Cell Type Annotations', 'Vasculature']);
142
+ });
143
+ });
144
+ describe('Get from tree', () => {
145
+ it('Tree Union', () => {
146
+ const union = treeToUnion(tree, [
147
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
148
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
149
+ ]);
150
+ expect(union).toEqual(['cell_3', 'cell_4', 'cell_5', 'cell_6', 'cell_7']);
151
+ });
152
+ it('Tree Intersection', () => {
153
+ const union = treeToIntersection(tree, [
154
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
155
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
156
+ ]);
157
+ expect(union).toEqual(['cell_5']);
158
+ });
159
+ it('Tree Union Complement', () => {
160
+ const complement = treeToComplement(tree, [
161
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
162
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial', 'Squamous'],
163
+ ], ['cell_6', 'cell_7', 'cell_8']);
164
+ expect(complement).toEqual(['cell_8']);
165
+ });
166
+ it('Node Descendants by Level', () => {
167
+ const descendants = nodeToLevelDescendantNamePaths(tree.tree[0], 2, []);
168
+ expect(descendants).toEqual([['Cell Type Annotations', 'Vasculature', 'Epithelial']]);
169
+ const descendantsStopEarly = nodeToLevelDescendantNamePaths(tree.tree[0], 2, [], true);
170
+ expect(descendantsStopEarly).toEqual([['Cell Type Annotations', 'Vasculature', 'Pericytes'],
171
+ ['Cell Type Annotations', 'Vasculature', 'Endothelial'],
172
+ ['Cell Type Annotations', 'Vasculature', 'Epithelial']]);
173
+ });
174
+ it('Tree export', () => {
175
+ const exportedTree = treeExport(tree, 'cell');
176
+ // Clears state going deeply
177
+ expect(exportedTree.tree[0].children[0]._state).toEqual(undefined);
178
+ expect(exportedTree.tree[0].children[0].children[0]._state).toEqual(undefined);
179
+ // Tree still has same names for nodes
180
+ expect(exportedTree.tree[0].children[0].name).toEqual(tree.tree[0].children[0].name);
181
+ expect(exportedTree.tree[0].children[0].children[0].name)
182
+ .toEqual(tree.tree[0].children[0].children[0].name);
183
+ });
184
+ });
185
+ });
@@ -0,0 +1,17 @@
1
+ export const FILE_EXTENSION_JSON: "json";
2
+ export const MIME_TYPE_JSON: "application/json";
3
+ export const FILE_EXTENSION_TABULAR: "csv";
4
+ export const MIME_TYPE_TABULAR: "text/csv";
5
+ export const SEPARATOR_TABULAR: ",";
6
+ export const NA_VALUE_TABULAR: "NA";
7
+ export const SETS_DATATYPE_OBS: "obs";
8
+ export namespace HIERARCHICAL_SCHEMAS {
9
+ export const latestVersion: string;
10
+ export { obsSetsSchema as schema };
11
+ }
12
+ export namespace TABULAR_SCHEMAS {
13
+ export { obsSetsTabularSchema as schema };
14
+ }
15
+ import { obsSetsSchema } from "@vitessce/schemas";
16
+ import { obsSetsTabularSchema } from "@vitessce/schemas";
17
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.js"],"names":[],"mappings":"AAEA,yCAA0C;AAC1C,gDAAiD;AAEjD,2CAA4C;AAC5C,2CAA4C;AAC5C,oCAAqC;AAGrC,oCAAqC;AAErC,sCAAuC"}
@@ -0,0 +1,17 @@
1
+ import { obsSetsSchema, obsSetsTabularSchema } from '@vitessce/schemas';
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
+ latestVersion: '0.1.3',
13
+ schema: obsSetsSchema,
14
+ };
15
+ export const TABULAR_SCHEMAS = {
16
+ schema: obsSetsTabularSchema,
17
+ };
@@ -0,0 +1,7 @@
1
+ export { dataToCellSetsTree } from "./CellSetsZarrLoader.js";
2
+ 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.js";
3
+ export { findLongestCommonPath, filterPathsByExpansionAndSelection, findChangedHierarchy } from "./set-path-utils.js";
4
+ export { isEqualOrPrefix, tryRenamePath, PATH_SEP, setObsSelection, mergeObsSets, getNextNumberedNodeName, colorArrayToString, callbackOnKeyPress, getLevelTooltipText, pathToKey, getObsInfoFromDataWithinRange } from "./utils.js";
5
+ export { downloadForUser, handleExportJSON, handleExportTabular, tryUpgradeTreeToLatestSchema, handleImportJSON, handleImportTabular } from "./io.js";
6
+ export { FILE_EXTENSION_JSON, FILE_EXTENSION_TABULAR, SETS_DATATYPE_OBS, MIME_TYPE_JSON, MIME_TYPE_TABULAR } from "./constants.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":""}
package/dist-tsc/index.js CHANGED
@@ -1,5 +1,6 @@
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';
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.js';
2
+ export { findLongestCommonPath, filterPathsByExpansionAndSelection, findChangedHierarchy, } from './set-path-utils.js';
3
+ export { isEqualOrPrefix, tryRenamePath, PATH_SEP, setObsSelection, mergeObsSets, getNextNumberedNodeName, colorArrayToString, callbackOnKeyPress, getLevelTooltipText, pathToKey, getObsInfoFromDataWithinRange, } from './utils.js';
4
+ export { downloadForUser, handleExportJSON, handleExportTabular, tryUpgradeTreeToLatestSchema, handleImportJSON, handleImportTabular, } from './io.js';
5
+ export { FILE_EXTENSION_JSON, FILE_EXTENSION_TABULAR, SETS_DATATYPE_OBS, MIME_TYPE_JSON, MIME_TYPE_TABULAR, } from './constants.js';
6
+ export { dataToCellSetsTree, } from './CellSetsZarrLoader.js';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Check if an imported tree has an old schema version that we know how to
3
+ * "upgrade" to the latest schema version. Validate against the schema.
4
+ * @param {object} currTree A hierarchical tree object with a .version property,
5
+ * which has already passed schema validation, but may not have the latest schema version.
6
+ * @param {string} datatype The data type of the items in the schema.
7
+ * @returns {[object, boolean]} The upgraded tree object and a boolean indicating
8
+ * whether the tree was upgraded.
9
+ */
10
+ export function tryUpgradeTreeToLatestSchema(currTree: object, datatype: string): [object, boolean];
11
+ /**
12
+ * Handler for JSON imports. Validates and upgrades against the hierarchical sets schema.
13
+ * @param {string} result The data passed from the FileReader as a string.
14
+ * @param {string} datatype The data type to validate against.
15
+ * @param {string} theme "light" or "dark" for the vitessce theme
16
+ * @returns {object} The imported tree object.
17
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
18
+ */
19
+ export function handleImportJSON(result: string, datatype: string, theme: string): object;
20
+ /**
21
+ * Handler for tabular imports. Validates against the tabular sets schema.
22
+ * @param {string} result The data passed from the FileReader as a string.
23
+ * @param {string} datatype The data type to validate against.
24
+ * @param {string} theme "light" or "dark" for the vitessce theme
25
+ * @returns {object} The imported tree object.
26
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
27
+ */
28
+ export function handleImportTabular(result: string, datatype: string, theme: string): object;
29
+ /**
30
+ * Convert a tree object to a JSON representation.
31
+ * @param {object} result The object to export.
32
+ * @returns {string} The data in a string representation.
33
+ */
34
+ export function handleExportJSON(result: object): string;
35
+ /**
36
+ * Convert a tree object with one level (height === 1) to a tabular representation.
37
+ * @param {object} result The object to export.
38
+ * @returns {string} The data in a string representation.
39
+ */
40
+ export function handleExportTabular(result: object): string;
41
+ /**
42
+ * Download a file. Appends and removes an anchor node in the DOM.
43
+ * @param {string} dataString The function that converts the data to a string.
44
+ * @param {string} fileName The name of the file to be downloaded.
45
+ */
46
+ export function downloadForUser(dataString: string, fileName: string): void;
47
+ //# sourceMappingURL=io.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.d.ts","sourceRoot":"","sources":["../src/io.js"],"names":[],"mappings":"AAaA;;;;;;;;GAQG;AAEH,uDAPW,MAAM,YAEN,MAAM,GACJ,CAAC,MAAM,EAAE,OAAO,CAAC,CAiB7B;AAED;;;;;;;GAOG;AAEH,yCAPW,MAAM,YACN,MAAM,SACN,MAAM,GACJ,MAAM,CASlB;AAED;;;;;;;GAOG;AACH,4CANW,MAAM,YACN,MAAM,SACN,MAAM,GACJ,MAAM,CAuDlB;AAED;;;;GAIG;AACH,yCAHW,MAAM,GACJ,MAAM,CAMlB;AAED;;;;GAIG;AACH,4CAHW,MAAM,GACJ,MAAM,CA2BlB;AAED;;;;GAIG;AACH,4CAHW,MAAM,YACN,MAAM,QAShB"}
package/dist-tsc/io.js ADDED
@@ -0,0 +1,159 @@
1
+ import { isNil } from 'lodash-es';
2
+ import { dsvFormat } from 'd3-dsv';
3
+ // TODO(monorepo): try to find a different package for this.
4
+ // Reference: https://github.com/zemirco/json2csv/issues/539
5
+ import { Parser } from 'json2csv/dist/json2csv.umd.js';
6
+ import { getDefaultColor } from '@vitessce/utils';
7
+ import { colorArrayToString, colorStringToArray } from './utils.js';
8
+ import { HIERARCHICAL_SCHEMAS, TABULAR_SCHEMAS, MIME_TYPE_JSON, MIME_TYPE_TABULAR, SEPARATOR_TABULAR, NA_VALUE_TABULAR, } from './constants.js';
9
+ /**
10
+ * Check if an imported tree has an old schema version that we know how to
11
+ * "upgrade" to the latest schema version. Validate against the schema.
12
+ * @param {object} currTree A hierarchical tree object with a .version property,
13
+ * which has already passed schema validation, but may not have the latest schema version.
14
+ * @param {string} datatype The data type of the items in the schema.
15
+ * @returns {[object, boolean]} The upgraded tree object and a boolean indicating
16
+ * whether the tree was upgraded.
17
+ */
18
+ // eslint-disable-next-line no-unused-vars
19
+ export function tryUpgradeTreeToLatestSchema(currTree, datatype) {
20
+ const zodSchema = HIERARCHICAL_SCHEMAS.schema;
21
+ const latestSchemaVersion = HIERARCHICAL_SCHEMAS.latestVersion;
22
+ const parseResult = zodSchema.safeParse(currTree);
23
+ const valid = parseResult.success;
24
+ if (!valid) {
25
+ const failureReason = JSON.stringify(parseResult.error.message, null, 2);
26
+ throw new Error(`Tree validation failed: ${failureReason}`);
27
+ }
28
+ // Zod will not only validate, but also will upgrade from v0.1.2 to v0.1.3 via transform.
29
+ // We also want to return a boolean indicating whether the tree was upgraded.
30
+ const didUpgrade = (currTree.version !== latestSchemaVersion);
31
+ return [parseResult.data, didUpgrade];
32
+ }
33
+ /**
34
+ * Handler for JSON imports. Validates and upgrades against the hierarchical sets schema.
35
+ * @param {string} result The data passed from the FileReader as a string.
36
+ * @param {string} datatype The data type to validate against.
37
+ * @param {string} theme "light" or "dark" for the vitessce theme
38
+ * @returns {object} The imported tree object.
39
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
40
+ */
41
+ // eslint-disable-next-line no-unused-vars
42
+ export function handleImportJSON(result, datatype, theme) {
43
+ let importData = JSON.parse(result);
44
+ // Validate the imported file.
45
+ [importData] = tryUpgradeTreeToLatestSchema(importData, datatype);
46
+ return importData;
47
+ }
48
+ /**
49
+ * Handler for tabular imports. Validates against the tabular sets schema.
50
+ * @param {string} result The data passed from the FileReader as a string.
51
+ * @param {string} datatype The data type to validate against.
52
+ * @param {string} theme "light" or "dark" for the vitessce theme
53
+ * @returns {object} The imported tree object.
54
+ * @throws {Error} Throws error if validation fails or if the datatype does not match.
55
+ */
56
+ export function handleImportTabular(result, datatype, theme) {
57
+ const dsvParser = dsvFormat(SEPARATOR_TABULAR);
58
+ const importData = dsvParser.parse(result, row => ({
59
+ groupName: row.groupName,
60
+ setName: row.setName,
61
+ setColor: (row.setColor ? colorStringToArray(row.setColor) : getDefaultColor(theme)),
62
+ obsId: row.obsId,
63
+ predictionScore: ((isNil(row.predictionScore)
64
+ || row.predictionScore === NA_VALUE_TABULAR)
65
+ ? null
66
+ : +row.predictionScore),
67
+ }));
68
+ // Validate the imported file.
69
+ const zodSchema = TABULAR_SCHEMAS.schema;
70
+ const parseResult = zodSchema.safeParse(importData);
71
+ const valid = parseResult.success;
72
+ if (!valid) {
73
+ const failureReason = JSON.stringify(parseResult.error.message, null, 2);
74
+ throw new Error(`Import validation failed: ${failureReason}`);
75
+ }
76
+ else {
77
+ const parsedData = parseResult.data;
78
+ // Convert the validated array to a tree representation.
79
+ const treeToImport = {
80
+ version: HIERARCHICAL_SCHEMAS.latestVersion,
81
+ tree: [],
82
+ };
83
+ const uniqueGroupNames = Array.from(new Set(parsedData.map(d => d.groupName)));
84
+ uniqueGroupNames.forEach((groupName) => {
85
+ const levelZeroNode = {
86
+ name: groupName,
87
+ children: [],
88
+ };
89
+ const groupRows = parsedData.filter(d => d.groupName === groupName);
90
+ const uniqueSetNames = Array.from(new Set(groupRows.map(d => d.setName)));
91
+ uniqueSetNames.forEach((setName) => {
92
+ const setRows = groupRows.filter(d => d.setName === setName);
93
+ const { setColor } = setRows[0];
94
+ const levelOneNode = {
95
+ name: setName,
96
+ color: setColor,
97
+ set: setRows.map(d => ([d.obsId, d.predictionScore])),
98
+ };
99
+ levelZeroNode.children.push(levelOneNode);
100
+ });
101
+ treeToImport.tree.push(levelZeroNode);
102
+ });
103
+ return treeToImport;
104
+ }
105
+ }
106
+ /**
107
+ * Convert a tree object to a JSON representation.
108
+ * @param {object} result The object to export.
109
+ * @returns {string} The data in a string representation.
110
+ */
111
+ export function handleExportJSON(result) {
112
+ const jsonString = JSON.stringify(result);
113
+ const dataString = `data:${MIME_TYPE_JSON};charset=utf-8,${encodeURIComponent(jsonString)}`;
114
+ return dataString;
115
+ }
116
+ /**
117
+ * Convert a tree object with one level (height === 1) to a tabular representation.
118
+ * @param {object} result The object to export.
119
+ * @returns {string} The data in a string representation.
120
+ */
121
+ export function handleExportTabular(result) {
122
+ // Convert a tree object to an array of JSON objects.
123
+ const exportData = [];
124
+ result.tree.forEach((levelZeroNode) => {
125
+ levelZeroNode.children.forEach((levelOneNode) => {
126
+ if (levelOneNode.set) {
127
+ levelOneNode.set.forEach(([obsId, prob]) => {
128
+ exportData.push({
129
+ groupName: levelZeroNode.name,
130
+ setName: levelOneNode.name,
131
+ setColor: colorArrayToString(levelOneNode.color),
132
+ obsId,
133
+ predictionScore: isNil(prob) ? NA_VALUE_TABULAR : prob,
134
+ });
135
+ });
136
+ }
137
+ });
138
+ });
139
+ const parser = new Parser({
140
+ fields: ['groupName', 'setName', 'setColor', 'obsId', 'predictionScore'],
141
+ delimiter: SEPARATOR_TABULAR,
142
+ });
143
+ const csvString = parser.parse(exportData);
144
+ const dataString = `data:${MIME_TYPE_TABULAR};charset=utf-8,${encodeURIComponent(csvString)}`;
145
+ return dataString;
146
+ }
147
+ /**
148
+ * Download a file. Appends and removes an anchor node in the DOM.
149
+ * @param {string} dataString The function that converts the data to a string.
150
+ * @param {string} fileName The name of the file to be downloaded.
151
+ */
152
+ export function downloadForUser(dataString, fileName) {
153
+ const downloadAnchorNode = document.createElement('a');
154
+ downloadAnchorNode.setAttribute('href', dataString);
155
+ downloadAnchorNode.setAttribute('download', fileName);
156
+ document.body.appendChild(downloadAnchorNode); // required for firefox
157
+ downloadAnchorNode.click();
158
+ downloadAnchorNode.remove();
159
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=io.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.test.d.ts","sourceRoot":"","sources":["../src/io.test.js"],"names":[],"mappings":""}