phylotree 1.0.17 → 1.0.18

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,271 @@
1
+ import { isLeafNode } from "../nodes";
2
+
3
+ /**
4
+ * Parses a Newick string into an equivalent JSON representation that is
5
+ * suitable for consumption by ``hierarchy``.
6
+ *
7
+ * Optionally accepts bootstrap values. Currently supports Newick strings with or without branch lengths,
8
+ * as well as tagged trees such as
9
+ * ``(a,(b{TAG},(c{TAG},d{ANOTHERTAG})))``
10
+ *
11
+ * @param {String} nwk_str - A string representing a phylogenetic tree in Newick format.
12
+ * @param {Object} bootstrap_values.
13
+ * @returns {Object} An object with keys ``json`` and ``error``.
14
+ */
15
+
16
+ function newickParser(nwk_str, options={}) {
17
+
18
+ const bootstrap_values = true,
19
+ int_or_float = /^-?\d+(\.\d+)?$/;
20
+ let left_delimiter = options.left_delimiter || '{',
21
+ right_delimiter = options.right_delimiter || '}';
22
+ let clade_stack = [];
23
+
24
+ function addNewTreeLevel() {
25
+ let new_level = {
26
+ name: null
27
+ };
28
+
29
+ let the_parent = clade_stack[clade_stack.length - 1];
30
+
31
+ if (!("children" in the_parent)) {
32
+ the_parent["children"] = [];
33
+ }
34
+
35
+ clade_stack.push(new_level);
36
+
37
+ the_parent["children"].push(clade_stack[clade_stack.length - 1]);
38
+
39
+ clade_stack[clade_stack.length - 1]["original_child_order"] =
40
+ the_parent["children"].length;
41
+ }
42
+
43
+ function finishNodeDefinition() {
44
+
45
+ let this_node = clade_stack.pop();
46
+
47
+ this_node["name"] = current_node_name;
48
+
49
+ if (bootstrap_values && "children" in this_node) {
50
+ this_node["bootstrap_values"] = current_node_name;
51
+ } else {
52
+ this_node["name"] = current_node_name;
53
+ }
54
+
55
+ this_node["attribute"] = current_node_attribute;
56
+ if(left_delimiter == "[" && current_node_annotation.includes("&&NHX")) {
57
+ current_node_annotation
58
+ .split(':')
59
+ .slice(1)
60
+ .forEach(annotation => {
61
+ const [key, value] = annotation.split('=');
62
+ this_node[key] = int_or_float.test(value) ? +value : value;
63
+ });
64
+ } else {
65
+ this_node["annotation"] = current_node_annotation;
66
+ }
67
+
68
+ current_node_name = "";
69
+ current_node_attribute = "";
70
+ current_node_annotation = "";
71
+ }
72
+
73
+ function generateError(location) {
74
+ return {
75
+ json: null,
76
+ error:
77
+ "Unexpected '" +
78
+ nwk_str[location] +
79
+ "' in '" +
80
+ nwk_str.substring(location - 20, location + 1) +
81
+ "[ERROR HERE]" +
82
+ nwk_str.substring(location + 1, location + 20) +
83
+ "'"
84
+ };
85
+ }
86
+
87
+ let automaton_state = 0;
88
+ let current_node_name = "";
89
+ let current_node_attribute = "";
90
+ let current_node_annotation = "";
91
+ let quote_delimiter = null;
92
+
93
+ let name_quotes = {
94
+ "'": 1,
95
+ '"': 1
96
+ };
97
+
98
+ let tree_json = {
99
+ name: "root"
100
+ };
101
+
102
+ clade_stack.push(tree_json);
103
+
104
+ var space = /\s/;
105
+
106
+ for (var char_index = 0; char_index < nwk_str.length; char_index++) {
107
+ try {
108
+ var current_char = nwk_str[char_index];
109
+ switch (automaton_state) {
110
+ case 0: {
111
+ // look for the first opening parenthesis
112
+ if (current_char == "(") {
113
+ addNewTreeLevel();
114
+ automaton_state = 1; // expecting node name
115
+ }
116
+ break;
117
+ }
118
+ case 1: // name
119
+ case 3: {
120
+ // branch length
121
+ // reading name
122
+ if (current_char == ":") {
123
+ automaton_state = 3;
124
+ } else if (current_char == "," || current_char == ")") {
125
+ try {
126
+ finishNodeDefinition();
127
+ automaton_state = 1;
128
+ if (current_char == ",") {
129
+ addNewTreeLevel();
130
+ }
131
+ } catch (e) {
132
+ return generateError(char_index);
133
+ }
134
+ } else if (current_char == "(") {
135
+ if (current_node_name.length > 0) {
136
+ return generateError(char_index);
137
+ } else {
138
+ addNewTreeLevel();
139
+ }
140
+ } else if (current_char in name_quotes) {
141
+ if (
142
+ automaton_state == 1 &&
143
+ current_node_name.length === 0 &&
144
+ current_node_attribute.length === 0 &&
145
+ current_node_annotation.length === 0
146
+ ) {
147
+ automaton_state = 2;
148
+ quote_delimiter = current_char;
149
+ continue;
150
+ }
151
+ return generateError(char_index);
152
+ } else {
153
+ if (current_char == left_delimiter) {
154
+ if (current_node_annotation.length) {
155
+ return generateError(char_index);
156
+ } else {
157
+ automaton_state = 4;
158
+ }
159
+ } else {
160
+ if (automaton_state == 3) {
161
+ current_node_attribute += current_char;
162
+ } else {
163
+ if (space.test(current_char)) {
164
+ continue;
165
+ }
166
+ if (current_char == ";") {
167
+ // semicolon terminates tree definition
168
+ char_index = nwk_str.length;
169
+ break;
170
+ }
171
+ current_node_name += current_char;
172
+ }
173
+ }
174
+ }
175
+
176
+ break;
177
+ }
178
+ case 2: {
179
+ // inside a quoted expression
180
+ if (current_char == quote_delimiter) {
181
+ if (char_index < nwk_str.length - 1) {
182
+ if (nwk_str[char_index + 1] == quote_delimiter) {
183
+ char_index++;
184
+ current_node_name += quote_delimiter;
185
+ continue;
186
+ }
187
+ }
188
+ quote_delimiter = 0;
189
+ automaton_state = 1;
190
+ continue;
191
+ } else {
192
+ current_node_name += current_char;
193
+ }
194
+ break;
195
+ }
196
+ case 4: {
197
+ // inside a comment / attribute
198
+ if (current_char == right_delimiter) {
199
+ automaton_state = 3;
200
+ } else {
201
+ if (current_char == left_delimiter) {
202
+ return generateError(char_index);
203
+ }
204
+ current_node_annotation += current_char;
205
+ }
206
+ break;
207
+ }
208
+ }
209
+ } catch (e) {
210
+ return generateError(char_index);
211
+ }
212
+ }
213
+
214
+ if (clade_stack.length != 1) {
215
+ return generateError(nwk_str.length - 1);
216
+ }
217
+
218
+ return {
219
+ json: tree_json,
220
+ error: null
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Return Newick string representation of a phylotree.
226
+ *
227
+ * @param {Function} annotator - Function to apply to each node, determining
228
+ * what label is written (optional).
229
+ * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
230
+ */
231
+
232
+ // TODO: break this out into two seperate functions
233
+ export function getNewick(annotator) {
234
+
235
+ let self = this;
236
+
237
+ if (!annotator) annotator = d => '';
238
+
239
+ function nodeDisplay(n) {
240
+ if (!isLeafNode(n)) {
241
+ element_array.push("(");
242
+ n.children.forEach(function(d, i) {
243
+ if (i) {
244
+ element_array.push(",");
245
+ }
246
+ nodeDisplay(d);
247
+ });
248
+ element_array.push(")");
249
+ }
250
+
251
+ if(n.data.name != 'root') {
252
+ element_array.push(n.data.name);
253
+ }
254
+ element_array.push(annotator(n));
255
+
256
+ let bl = self.branch_length_accessor(n);
257
+
258
+ if (bl !== undefined) {
259
+ element_array.push(":" + bl);
260
+ }
261
+ }
262
+
263
+ let element_array = [];
264
+ annotator = annotator || "";
265
+ nodeDisplay(this.nodes);
266
+
267
+ return element_array.join("")+";";
268
+
269
+ }
270
+
271
+ export default newickParser;
@@ -0,0 +1,42 @@
1
+ import * as _ from "underscore";
2
+ //import { parseString } from "xml2js";
3
+
4
+ var nexml_parser = function(xml_string, options) {
5
+ var trees;
6
+ parseString(xml_string, function(error, xml) {
7
+ trees = xml["nex:nexml"].trees[0].tree.map(function(nexml_tree) {
8
+ var node_list = nexml_tree.node.map(d => d.$),
9
+ node_hash = node_list.reduce(function(a, b) {
10
+ b.edges = [];
11
+ b.name = b.id;
12
+ a[b.id] = b;
13
+ return a;
14
+ }, {}),
15
+ roots = node_list.filter(d => d.root),
16
+ root_id = roots > 0 ? roots[0].id : node_list[0].id;
17
+ node_hash[root_id].name = "root";
18
+
19
+ nexml_tree.edge.map(d => d.$).forEach(function(edge) {
20
+ node_hash[edge.source].edges.push(edge);
21
+ });
22
+
23
+ function parseNexml(node, index) {
24
+ if (node.edges) {
25
+ var targets = _.pluck(node.edges, "target");
26
+ node.children = _.values(_.pick(node_hash, targets));
27
+ node.children.forEach(function(child, i) {
28
+ child.attribute = node.edges[i].length || "";
29
+ });
30
+ node.children.forEach(parseNexml);
31
+ node.annotation = "";
32
+ }
33
+ }
34
+
35
+ parseNexml(node_hash[root_id]);
36
+ return node_hash[root_id];
37
+ });
38
+ });
39
+ return trees;
40
+ };
41
+
42
+ export default nexml_parser;
@@ -0,0 +1,96 @@
1
+ import * as _ from "underscore";
2
+ import {default as newickParser} from "./newick";
3
+
4
+ export function parseAnnotations (buf) {
5
+
6
+ let str = buf;
7
+ let index = str.toUpperCase().indexOf('BEGIN DATA;');
8
+ let data = str.slice(index);
9
+
10
+ if(data.length < 2) {
11
+ return '';
12
+ }
13
+
14
+ index = data.toUpperCase().indexOf('END;');
15
+ let data_str = data.slice(0, index);
16
+
17
+ // split on semicolon
18
+ data = _.map(data_str.split(';'), d => { return d.trim() } );
19
+
20
+ // get dimensions
21
+ let dimensions = _.filter(data, d => {return d.toUpperCase().startsWith('DIMENSION')});
22
+ dimensions = dimensions[0].split(' ');
23
+ dimensions = _.object(_.map(_.rest(dimensions), d => { return d.split('=') }));
24
+
25
+ // get formats
26
+ let format = _.filter(data, d => {return d.toUpperCase().startsWith('FORMAT')});
27
+ format = format[0].split(' ');
28
+ format = _.object(_.map(_.rest(format), d => { return d.split('=') }));
29
+ format.symbols = _.reject(format.symbols.split(""), d => d=='"');
30
+
31
+ // get character matrix
32
+ let matrix = _.filter(data, d => {return d.toUpperCase().startsWith('MATRIX')});
33
+ matrix = matrix[0].split('\n')
34
+ matrix = _.object(_.map(_.rest(matrix), d=> { return _.compact(d.split(' ')) }));
35
+
36
+ // create all possible states for matrix
37
+ matrix = _.mapObject(matrix, (v,k) => {
38
+
39
+ if(v == '?') {
40
+ return format.symbols
41
+ }
42
+ else {
43
+ return Array(v)
44
+ }
45
+
46
+ });
47
+
48
+ return { 'dimensions' : dimensions, 'format' : format, 'matrix' : matrix }
49
+
50
+ }
51
+
52
+ /**
53
+ * Loads annotations from a nexus-formatted buffer and annotates existing tree
54
+ * nodes appropriately.
55
+ *
56
+ * @param {Object} tree - Instatiated phylotree
57
+ * @param {String} NEXUS string
58
+ * @returns {Object} Annotations
59
+ */
60
+ export function loadAnnotations(tree, label, annotations) {
61
+
62
+ // if filename, then load from filesystem
63
+ _.each(tree.getTips(), d => { d.data["test"] = annotations.matrix[d.data.name] });
64
+
65
+ // decorate nodes with annotations
66
+
67
+ }
68
+
69
+ export default function loadTree(buf) {
70
+
71
+ // if filename, then load from filesystem
72
+ // Parse first tree from NEXUS file and send to newickParser
73
+
74
+ // Make all upper case
75
+ let str = buf;
76
+
77
+ // Get TREE block
78
+ let index = str.toUpperCase().indexOf('BEGIN TREES;');
79
+ let split = str.slice(index);
80
+
81
+ if(split.length < 2) {
82
+ return '';
83
+ }
84
+
85
+ index = split.toUpperCase().indexOf('END;');
86
+ let tree_str = split.slice(0, index);
87
+
88
+ // Filter lines that start with TREE
89
+ let trees = tree_str.split('\n');
90
+ trees = _.filter(trees, d => { return d.trim().toUpperCase().startsWith('TREE') });
91
+
92
+ // Identify start of newick string
93
+ return newickParser(trees[0]);
94
+
95
+ }
96
+
@@ -0,0 +1,80 @@
1
+ // Changes XML to JSON
2
+ // Modified version from here: http://davidwalsh.name/convert-xml-json
3
+ function xmlToJson(xml) {
4
+
5
+ // Create the return object
6
+ var obj = {};
7
+
8
+ if (xml.nodeType == 1) { // element
9
+ // do attributes
10
+ if (xml.attributes.length > 0) {
11
+ obj["@attributes"] = {};
12
+ for (var j = 0; j < xml.attributes.length; j++) {
13
+ var attribute = xml.attributes.item(j);
14
+ obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
15
+ }
16
+ }
17
+ } else if (xml.nodeType == 3) { // text
18
+ obj = xml.nodeValue;
19
+ }
20
+
21
+ // do children
22
+ // If just one text node inside
23
+ if (xml.hasChildNodes() && xml.childNodes.length === 1 && xml.childNodes[0].nodeType === 3) {
24
+ obj = xml.childNodes[0].nodeValue;
25
+ }
26
+ else if (xml.hasChildNodes()) {
27
+ for(var i = 0; i < xml.childNodes.length; i++) {
28
+ var item = xml.childNodes.item(i);
29
+ var nodeName = item.nodeName;
30
+ if (typeof(obj[nodeName]) == "undefined") {
31
+ obj[nodeName] = xmlToJson(item);
32
+ } else {
33
+ if (typeof(obj[nodeName].push) == "undefined") {
34
+ var old = obj[nodeName];
35
+ obj[nodeName] = [];
36
+ obj[nodeName].push(old);
37
+ }
38
+ obj[nodeName].push(xmlToJson(item));
39
+ }
40
+ }
41
+ }
42
+ return obj;
43
+ }
44
+
45
+ var phyloxml_parser = function(xml, options) {
46
+
47
+ function parsePhyloxml(node, index) {
48
+ if (node.clade) {
49
+ node.clade.forEach(parsePhyloxml);
50
+ node.children = node.clade;
51
+ delete node.clade;
52
+ }
53
+
54
+ node.annotation = 1;
55
+ node.attribute = "0.01";
56
+ if (node.branch_length) {
57
+ node.attribute = node.branch_length;
58
+ }
59
+ if (node.taxonomy) {
60
+ node.name = node.taxonomy.scientific_name;
61
+ }
62
+
63
+ node.annotation = "";
64
+
65
+ }
66
+
67
+ var tree_json;
68
+
69
+ xml = xmlToJson(xml);
70
+ tree_json = xml.phyloxml.phylogeny.clade;
71
+ tree_json.name = "root";
72
+ parsePhyloxml(tree_json, 0);
73
+
74
+ return {
75
+ json: tree_json,
76
+ error: null
77
+ };
78
+ };
79
+
80
+ export default phyloxml_parser;
@@ -0,0 +1,20 @@
1
+ import { default as nexml_parser } from "./nexml";
2
+ import { default as newickParser } from "./newick";
3
+ import { default as nexus_parser } from "./nexus";
4
+ import { default as phyloxml_parser } from "./phyloxml";
5
+ import { default as beast_parser } from "./beast";
6
+
7
+ /*
8
+ * A parser must have two fields, the object and
9
+ * options
10
+ */
11
+ var format_registry = {
12
+ nexml: nexml_parser,
13
+ phyloxml: phyloxml_parser,
14
+ nexus : nexus_parser,
15
+ nwk: newickParser,
16
+ nhx: newickParser,
17
+ beast: beast_parser
18
+ };
19
+
20
+ export default format_registry;
package/src/index.js ADDED
@@ -0,0 +1,22 @@
1
+ export { default as phylotree } from "./main.js";
2
+
3
+ export { default as pairwise_distances } from "./metrics/pairwise-distances";
4
+ export { default as sackin } from "./metrics/sackins";
5
+ export { centerOfTree } from "./metrics/center-of-tree";
6
+ export { computeMidpoint } from "./metrics/compute-midpoint";
7
+ export { default as rootToTip, fitRootToTip } from "./metrics/root-to-tip";
8
+
9
+ export { default as extract_dates } from "./extract-dates";
10
+ export { default as clusterPicker } from "./clustering/cluster-picker";
11
+ export { default as phylopart } from "./clustering/phylopart";
12
+
13
+ export { parseAnnotations, loadAnnotations } from "./formats/nexus";
14
+
15
+ export {
16
+ leftChildRightSibling,
17
+ postOrder,
18
+ preOrder,
19
+ default as inOrder
20
+ } from "./traversal.js";
21
+
22
+