phylotree 1.0.20 → 1.2.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 (40) hide show
  1. package/bin/phylotree-neighbor-join.js +28 -0
  2. package/bin/phylotree-validate.js +33 -0
  3. package/bin/phylotree.js +1 -0
  4. package/dist/phylotree.js +268 -22
  5. package/dist/phylotree.min.js +1 -1
  6. package/package.json +4 -3
  7. package/src/branches.js +0 -156
  8. package/src/clustering/cluster-picker.js +0 -115
  9. package/src/clustering/phylopart.js +0 -238
  10. package/src/export.js +0 -25
  11. package/src/extract-dates.js +0 -69
  12. package/src/formats/beast.js +0 -29
  13. package/src/formats/newick.js +0 -271
  14. package/src/formats/nexml.js +0 -42
  15. package/src/formats/nexus.js +0 -96
  16. package/src/formats/phyloxml.js +0 -80
  17. package/src/formats/registry.js +0 -20
  18. package/src/index.js +0 -22
  19. package/src/main.js +0 -311
  20. package/src/max-parsimony.js +0 -81
  21. package/src/metrics/center-of-tree.js +0 -138
  22. package/src/metrics/compute-midpoint.js +0 -81
  23. package/src/metrics/pairwise-distances.js +0 -119
  24. package/src/metrics/root-to-tip.js +0 -220
  25. package/src/metrics/sackins.js +0 -21
  26. package/src/nodes.js +0 -215
  27. package/src/render/cartesian.js +0 -23
  28. package/src/render/clades.js +0 -116
  29. package/src/render/coordinates.js +0 -7
  30. package/src/render/draw.js +0 -1365
  31. package/src/render/edges.js +0 -134
  32. package/src/render/events.js +0 -166
  33. package/src/render/helpers.js +0 -7
  34. package/src/render/menus.js +0 -452
  35. package/src/render/nodes.js +0 -355
  36. package/src/render/options.js +0 -141
  37. package/src/render/radial.js +0 -79
  38. package/src/rooting.js +0 -183
  39. package/src/transformations.js +0 -20
  40. package/src/traversal.js +0 -114
@@ -1,238 +0,0 @@
1
- import * as _ from "underscore";
2
-
3
- /*
4
- *Implements a linear time / space version of the Phylopart algorithm
5
- *Nature Communications volume 2, Article number: 321 (2011)
6
- *
7
- *@param tree -- the tree object
8
- *
9
- *@param bootstrap_thresold -- value in [0,1] that sets the stringency of bootstrap support
10
- *
11
- *@param percentile threshold -- a value in 0-1, which is used to delineate how clusters
12
- * are defined; the actual criterion used is
13
- * [approximate] median pairwise distance in a cluster <= %-le of tree-wide distribution
14
- *
15
- *@param missing_bootstrap_value -- if a branch is missing bootstrap support value, use this value instead
16
- * (1.0 by default)
17
- *
18
- *@param resolution -- the width of the bin for the histogram; by default is set to be the
19
- * minimum of 0.001, branch length range / 100,
20
- * however, the maximum number of histogram bins is capped at 500 for
21
- * performance reasons
22
- *
23
- *@return an array of clusters, where cluster =
24
- *{
25
- * 'root' : [root node of cluster]
26
- * 'members' : [list of leaf. nodes]
27
- * 'median' : approximate median cluster distance,
28
- * 'bootstrap' : bootstrap support at the root node
29
- *}
30
- */
31
-
32
- import { default as pairwise_distances } from "../metrics/pairwise-distances";
33
-
34
- function phylopart(
35
- tree,
36
- bootstrap_threshold,
37
- percentile_threshold,
38
- missing_bootstrap_value,
39
- resolution
40
- ) {
41
- /** TODO SLKP 20180817 : this implementation does not compute pairwise distances correctly at the moment;
42
- instead it computes root-to-tip distances */
43
- missing_bootstrap_value = _.isNumber(missing_bootstrap_value)
44
- ? missing_bootstrap_value
45
- : 1;
46
-
47
- var leaf_count = pairwise_distances(tree);
48
-
49
- /** first, decide on the domain of branch lengths **/
50
-
51
- var core_node = tree.getRootNode().children[0];
52
-
53
- var min_bl = Number.MAX_VALUE,
54
- min_bl2 = Number.MAX_VALUE;
55
-
56
- if (!(percentile_threshold > 0 && percentile_threshold < 1)) {
57
- throw "Invalid percentile threshold in perform_phylopart";
58
- }
59
-
60
- tree.traverse_and_compute(function(n) {
61
- if (tree.isLeafNode(n)) {
62
- if (n.cot_computed_length < min_bl) {
63
- if (min_bl < min_bl2) {
64
- min_bl2 = min_bl;
65
- }
66
- min_bl = n.cot_computed_length;
67
- } else {
68
- if (n.cot_computed_length < min_bl2) {
69
- min_bl2 = n.cot_computed_length;
70
- }
71
- }
72
- }
73
- });
74
-
75
- min_bl += min_bl2;
76
-
77
- // pairwise distances are bounded below by the sum of two shortest terminal branches
78
-
79
- // compute the upper bound
80
- var max_path_length =
81
- _.reduce(
82
- core_node.cot_path_to_leaves_below,
83
- function(c, n) {
84
- return n > c ? n : c;
85
- },
86
- 0
87
- ) +
88
- _.reduce(
89
- core_node.cot_path_to_leaves_above,
90
- function(c, n) {
91
- return n > c ? n : c;
92
- },
93
- 0
94
- ) +
95
- core_node.cot_computed_length;
96
-
97
- var domain = max_path_length - min_bl;
98
-
99
- if (_.isUndefined(resolution)) {
100
- resolution = Math.min(1e-3, domain / 100);
101
- }
102
-
103
- var number_of_bins = ((domain / resolution) >> 0) + 1;
104
- if (number_of_bins > 500) {
105
- number_of_bins = 500;
106
- resolution = domain / number_of_bins;
107
- }
108
-
109
- var root_node = tree.getRootNode();
110
-
111
- root_node.paths_to_leaves = new Array(leaf_count);
112
-
113
- _.each(root_node.children, function(cn) {
114
- _.each(root_node.cot_path_to_leaves_below, function(v, i) {
115
- root_node.paths_to_leaves[i] = v + cn.cot_computed_length;
116
- });
117
- });
118
-
119
- tree.traverse_and_compute(function(n) {
120
- if (!tree.isLeafNode(n)) {
121
- n.histogram = new Array(number_of_bins);
122
- for (var i = 0; i < number_of_bins; i++) {
123
- n.histogram[i] = 0;
124
- }
125
- if (n.parent) {
126
- var index = 0;
127
- n.paths_to_leaves = [];
128
- _.each(n.cot_path_to_leaves_below, function(v, i) {
129
- n.paths_to_leaves[index++] = v;
130
- });
131
- }
132
- }
133
- delete n.cot_path_to_leaves_above;
134
- delete n.cot_path_to_leaves_below;
135
- });
136
-
137
- /**
138
- for each internal node, produce a histogram of pairwise distances on sequences that are defined
139
- by the subtree at that node
140
-
141
- this could be approximated (I think), by merging histograms of children
142
- */
143
-
144
- tree.traverse_and_compute(function(n) {
145
- if (!tree.isLeafNode(n)) {
146
- for (var n1 = 0; n1 < n.paths_to_leaves.length; n1++) {
147
- for (var n2 = n1 + 1; n2 < n.paths_to_leaves.length; n2++) {
148
- var sum = n.paths_to_leaves[n1] + n.paths_to_leaves[n2];
149
- n.histogram[((sum - min_bl) / resolution) >> 0]++;
150
- }
151
- }
152
- n.leaf_count = n.paths_to_leaves.length;
153
-
154
- delete n.paths_to_leaves;
155
- }
156
- });
157
-
158
- // compute the percentile distance cutoff
159
-
160
- var total_comparisons =
161
- (leaf_count - 1) * leaf_count / 2 * percentile_threshold;
162
- var bin_i = 0;
163
- for (
164
- ;
165
- bin_i < number_of_bins - 1 &&
166
- total_comparisons > root_node.histogram[bin_i];
167
- bin_i++
168
- ) {
169
- total_comparisons -= root_node.histogram[bin_i];
170
- }
171
-
172
- var median_threshold =
173
- min_bl +
174
- (bin_i +
175
- (root_node.histogram[bin_i] - total_comparisons) /
176
- root_node.histogram[bin_i]) *
177
- resolution;
178
-
179
- var clusters = [];
180
-
181
- tree.traverse_and_compute(_.noop, "pre-order", null, function(n) {
182
- if (!tree.isLeafNode(n)) {
183
- var bs = _.isString(n.data.bootstrap_values)
184
- ? +n.data.bootstrap_values
185
- : missing_bootstrap_value;
186
- if (bs >= bootstrap_threshold) {
187
- var total_comparisons = n.leaf_count * (n.leaf_count - 1) * 0.25;
188
-
189
- var bin_i = 0;
190
- for (
191
- ;
192
- bin_i < number_of_bins - 1 && total_comparisons > n.histogram[bin_i];
193
- bin_i++
194
- ) {
195
- total_comparisons -= n.histogram[bin_i];
196
- }
197
-
198
- var my_median =
199
- min_bl +
200
- (bin_i +
201
- (n.histogram[bin_i] - total_comparisons) / n.histogram[bin_i]) *
202
- resolution;
203
-
204
- if (my_median <= median_threshold) {
205
- clusters.push({ root: n, median: my_median, bootstrap: bs });
206
- return true;
207
- }
208
- }
209
- }
210
- return false;
211
- });
212
-
213
- tree.traverse_and_compute(function(n) {
214
- if (!tree.isLeafNode(n)) {
215
- if ("histogram" in n) {
216
- delete n.histogram;
217
- delete n.leaf_count;
218
- }
219
- }
220
- });
221
-
222
- _.each(clusters, function(cluster) {
223
- cluster["members"] = [];
224
- tree.traverse_and_compute(
225
- function(n) {
226
- if (tree.isLeafNode(n)) {
227
- cluster["members"].push(n);
228
- }
229
- },
230
- "post-order",
231
- cluster["root"]
232
- );
233
- });
234
-
235
- return clusters;
236
- }
237
-
238
- export default phylopart;
package/src/export.js DELETED
@@ -1,25 +0,0 @@
1
- import * as _ from "underscore";
2
-
3
- /**
4
- * Return CSV of nodes sorted by longest branches.
5
- *
6
- * @returns {Array} An array of all tips and associated lengths of the form :
7
- * [{
8
- * name : <tip_name>,
9
- * length: <tip_length>
10
- * }, ...]
11
- */
12
-
13
- export default function getTipLengths() {
14
-
15
- // Get nodes and branch lengths
16
- let self = this;
17
- let tips = self.getTips();
18
-
19
- // Transform to name, attribute key-pair and sort by attribute length, descending
20
- let toExport = _.map(tips, d => { return {'name' : d.data.name, 'length' : parseFloat(d.data.attribute) } });
21
- toExport = _.sortBy(toExport, d=> -d.length)
22
- return toExport;
23
-
24
-
25
- }
@@ -1,69 +0,0 @@
1
- import * as d3 from "d3";
2
- import { isLeafNode } from "./nodes";
3
-
4
- const default_date_converter = d3.timeParse("%Y%m%d");
5
-
6
- const default_regexp = /([0-9]{4}).?([0-9]{2}).?([0-9]{2})$/g;
7
-
8
- const default_date_getter = function(node) {
9
- if (isLeafNode(node)) {
10
- if ("name" in node) {
11
- let location = default_regexp.exec(node.name);
12
- if (location) {
13
- return location[1] + location[2] + location[3];
14
- }
15
- }
16
- }
17
- return null;
18
- };
19
-
20
- /*
21
- * Extracts dates from nodes using a provided callback (defaults supplied),
22
- * and also converts them to decimal dates; missing dates are allowed; if desired, missing dates
23
- * can throw exceptions
24
- *
25
- * @param tree : the tree object
26
- *
27
- * @param date_getter : a function that extracts date strings from nodes (e.g. by parsing the name),
28
- * default is to extract from the end of the node name, using [YYYY] optional sep [MM] optional sep [DD] format;
29
- * default is implemented in phylotree_extensions.extract_dates.date_getter ()
30
- *
31
- * @param date_converter : if provided, will be used to parse the date string; default is %Y%m%d implemented in
32
- * phylotree_extensions.extract_dates.date_converter
33
- *
34
- *
35
- * @return tree with date-annotated nodes, i.e. each node will have
36
- *
37
- * n.date_value (date object, e.g. 2018-08-17); null for missing
38
- * n.decimal_date_value (decimal object, e.g. 2018.72)
39
- *
40
- */
41
- const extract_dates = function(tree, date_getter, date_converter=default_date_converter) {
42
-
43
- date_getter = date_getter || default_date_getter;
44
-
45
- tree.traverse_and_compute(function(n) {
46
- var d_string = date_getter(n);
47
- if (d_string) {
48
- try {
49
- n.data.date_value = date_converter(d_string);
50
- var full_year = n.data.date_value.getFullYear();
51
- var year_start = new Date(full_year, 0, 1),
52
- year_start_p1 = new Date(full_year + 1, 0, 1);
53
-
54
- n.data.decimal_date_value =
55
- full_year +
56
- (n.data.date_value - year_start) / (year_start_p1 - year_start);
57
- return;
58
- } catch (e) {
59
- // for conversion failures
60
- }
61
- }
62
- n.data.date_value = null;
63
- n.data.decimal_date_value = null;
64
- });
65
-
66
- return tree;
67
- };
68
-
69
- export default extract_dates;
@@ -1,29 +0,0 @@
1
- import newickParser from "./newick";
2
-
3
- export default function(newick, options) {
4
- options.left_delimiter = '[';
5
- options.right_delimiter = ']';
6
- const parsed_newick = newickParser(newick, options);
7
- function parseBeastNode(node) {
8
- if(node.annotation) {
9
- node.beast = {};
10
- const tokens = node.annotation.split(/=|,|{|}/)
11
- .filter(token => token);
12
- for(var i = 0; i < tokens.length; i+=2) {
13
- let key = tokens[i].replace(/&|%/g, '');
14
- if(/[a-df-zA-DF-Z]+/.test(tokens[i+2])) {
15
- node.beast[key] = +tokens[i+1];
16
- } else {
17
- node.beast[key] = [+tokens[i+1], +tokens[i+2]];
18
- i++;
19
- }
20
- }
21
- }
22
- node.annotation = undefined;
23
- if(node.children) {
24
- node.children.forEach(parseBeastNode);
25
- }
26
- }
27
- parseBeastNode(parsed_newick.json);
28
- return parsed_newick;
29
- }
@@ -1,271 +0,0 @@
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;
@@ -1,42 +0,0 @@
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;