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,119 @@
1
+ import * as _ from "underscore";
2
+
3
+ /*
4
+ * given a tree, this function will compute quantities required to work with
5
+ * all v all pairwise distances (like in COT)
6
+ *
7
+ * @param tree the tree object
8
+ * @returns leaf count
9
+ *
10
+ */
11
+ function computePairwiseDistances(tree) {
12
+ /*
13
+ * traverse the tree and populate the following values in each node
14
+ *
15
+ * .cot_computed_length -> for each node (except the root), the current branch length
16
+ * (so as to not compute them each time via a callback)
17
+ * .cot_leaf_index -> post_order traversal order of a leaf (0 to number of leaves - 1)
18
+ *
19
+ * for each node
20
+ *
21
+ * .cot_path_to_leaves_below
22
+ * -> a dictionary that maps a leaf index to the total path length from this node
23
+ * to each of the descendant leaves, EXCLUDING the length of this branch
24
+ *
25
+ * .cot_path_to_leaves_above
26
+ * -> a dictionary that maps a leaf index to the total path length from this node
27
+ * to each of the leaves outside the split defined by this node, EXCLUDING
28
+ * the length of this branch
29
+ */
30
+
31
+ var bl = tree.branch_length_accessor;
32
+
33
+ if (!bl) {
34
+ throw "A non-null branch lengths accessor function is required for this operation";
35
+ }
36
+
37
+ var leaf_count = 0;
38
+
39
+ tree.traverse_and_compute(function(n) {
40
+ n.cot_computed_length = bl(n);
41
+
42
+
43
+ if (n.parent && _.isUndefined(n.cot_computed_length)) {
44
+ throw "Non-null branch lengths are required for this operation: missing branch length at node " + n.data.name;
45
+ }
46
+
47
+ if (tree.isLeafNode(n)) {
48
+ n.cot_leaf_index = leaf_count++;
49
+ n.cot_path_to_leaves_below = {};
50
+ n.cot_path_to_leaves_below[n.cot_leaf_index] = 0;
51
+ n.cot_path_to_leaves_above = {};
52
+ } else {
53
+ n.cot_path_to_leaves_below = {};
54
+ n.cot_path_to_leaves_above = {};
55
+ }
56
+ });
57
+
58
+ // populate all cot_path_to_leaves_below
59
+ tree.traverse_and_compute(function(n) {
60
+ if (n.parent) {
61
+ _.each(n.cot_path_to_leaves_below, function(length_so_far, leaf_index) {
62
+ n.parent.cot_path_to_leaves_below[leaf_index] =
63
+ length_so_far + n.cot_computed_length;
64
+ });
65
+ }
66
+ });
67
+
68
+ // populate all cot_path_to_leaves_above; this is done via a 'pre-order' traversal
69
+ // handle root node first
70
+ var root_node = tree.getRootNode();
71
+
72
+ function CopyFromSiblings(a_node) {
73
+ for (var this_node = 0; this_node < a_node.children.length; this_node++) {
74
+ for (
75
+ var other_node = 0;
76
+ other_node < a_node.children.length;
77
+ other_node++
78
+ ) {
79
+ if (this_node != other_node) {
80
+ _.each(a_node.children[other_node].cot_path_to_leaves_below, function(
81
+ length,
82
+ index
83
+ ) {
84
+ if (a_node.children[this_node].cot_path_to_leaves_above) {
85
+ a_node.children[this_node].cot_path_to_leaves_above[index] =
86
+ length + a_node.children[other_node].cot_computed_length;
87
+ }
88
+ });
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ CopyFromSiblings(root_node);
95
+
96
+ // takes two passes
97
+
98
+ tree.traverse_and_compute(function(n) {
99
+ if (n.parent) {
100
+ // copy parent's 'above' nodes
101
+ _.each(n.parent.cot_path_to_leaves_above, function(
102
+ length_so_far,
103
+ leaf_index
104
+ ) {
105
+ n.cot_path_to_leaves_above[leaf_index] =
106
+ length_so_far + n.parent.cot_computed_length;
107
+ });
108
+
109
+ if (!tree.isLeafNode(n)) {
110
+ CopyFromSiblings(n);
111
+ }
112
+ // copy sibling's 'below' nodes
113
+ }
114
+ }, "pre-order");
115
+
116
+ return leaf_count;
117
+ }
118
+
119
+ export default computePairwiseDistances;
@@ -0,0 +1,220 @@
1
+ import * as _ from "underscore";
2
+
3
+ function annotateCopyNumber(tree) {
4
+ tree.traverse_and_compute(function(node) {
5
+ if (tree.isLeafNode(node)) {
6
+ node.data.copy_number = 1;
7
+ }
8
+ });
9
+ }
10
+
11
+ // internal function used by best root fitting
12
+ function computeRootToTipOtherRoot(
13
+ tree,
14
+ node,
15
+ coming_from,
16
+ shared_distance,
17
+ distance_to_new_root
18
+ ) {
19
+
20
+ var my_bl = tree.branch_length(node);
21
+
22
+ var go_up = false;
23
+
24
+ if (!coming_from) {
25
+ shared_distance = node.data.rootToTip;
26
+ distance_to_new_root = 0;
27
+ go_up = true;
28
+ }
29
+
30
+ if (node.children) {
31
+ for (var c = 0; c < node.children.length; c++) {
32
+ if (node.children[c] != coming_from) {
33
+ computeRootToTipOtherRoot(
34
+ tree,
35
+ node.children[c],
36
+ node,
37
+ shared_distance,
38
+ distance_to_new_root
39
+ );
40
+ } else {
41
+ go_up = true;
42
+ }
43
+ }
44
+ }
45
+
46
+ node.data.rtta = node.data.rootToTip - shared_distance + distance_to_new_root;
47
+
48
+ if (go_up) {
49
+ shared_distance -= my_bl;
50
+ distance_to_new_root += my_bl;
51
+ }
52
+
53
+ if (node.parent && go_up) {
54
+ computeRootToTipOtherRoot(
55
+ tree,
56
+ node.parent,
57
+ node,
58
+ shared_distance,
59
+ distance_to_new_root
60
+ );
61
+ }
62
+ }
63
+
64
+ export function fitRootToTip(tree) {
65
+
66
+ var linear_data = [],
67
+ max_r2 = 0,
68
+ best_node = 0;
69
+
70
+ annotateCopyNumber(tree);
71
+ rootToTip(tree);
72
+
73
+ // To return if best node is the root already
74
+ tree.traverse_and_compute(function(node) {
75
+ if (tree.isLeafNode(node) && !_.isNull(node.data.decimal_date_value)) {
76
+ linear_data.push([node.data.decimal_date_value, node.data.rtta, node.data.copy_number]);
77
+ }
78
+ });
79
+
80
+ let best_fit = linearFit(linear_data);
81
+
82
+ tree.traverse_and_compute(function(node) {
83
+
84
+ if (tree.isLeafNode(node) && !_.isNull(node.data.decimal_date_value)) {
85
+
86
+ computeRootToTipOtherRoot(tree, node, null, 0, 0);
87
+
88
+ linear_data = [];
89
+
90
+ tree.traverse_and_compute(function(node) {
91
+ if (tree.isLeafNode(node) && !_.isNull(node.data.decimal_date_value)) {
92
+ linear_data.push([
93
+ node.data.decimal_date_value,
94
+ node.data.rtta,
95
+ node.data.copy_number
96
+ ]);
97
+ }
98
+ });
99
+
100
+ var fit = linearFit(linear_data),
101
+ r2 = fit["r2"];
102
+
103
+ if (r2 > max_r2) {
104
+ max_r2 = r2;
105
+ best_node = node;
106
+ best_fit = fit;
107
+ }
108
+
109
+ }
110
+ });
111
+
112
+ return { root: best_node, fit: best_fit };
113
+
114
+ }
115
+
116
+ // linear fit of root to tip distances
117
+ function linearFit(data) {
118
+
119
+ var ss = data.reduce(function(p, c) {
120
+ return c[2] + p;
121
+ }, 0), // sample count
122
+ sx = data.reduce(function(p, c) {
123
+ return c[2] * c[0] + p;
124
+ }, 0), // sum X
125
+ sy = data.reduce(function(p, c) {
126
+ return c[2] * c[1] + p;
127
+ }, 0), // sum Y
128
+ sxoss = sx / ss,
129
+ syoss = sy / ss;
130
+
131
+ var fitB = 0,
132
+ st2 = 0,
133
+ vary = 0;
134
+
135
+ data.forEach(function(point) {
136
+ var t = point[0] - sxoss;
137
+ st2 += point[2] * t * t;
138
+ fitB += point[2] * t * point[1];
139
+ vary += point[2] * (point[1] - syoss) * (point[1] - syoss);
140
+ });
141
+
142
+ fitB /= st2;
143
+
144
+ var a = (sy - sx * fitB) / ss;
145
+
146
+ var varres = 0;
147
+
148
+ data.forEach(function(point) {
149
+ var t = point[1] - a - fitB * point[0];
150
+ varres += point[2] * t * t;
151
+ });
152
+
153
+ return {
154
+ intercept: a,
155
+ slope: fitB,
156
+ r2: 1 - varres / vary,
157
+ "var (intercept)": Math.sqrt((1 + sx * sx / (ss * st2)) / ss),
158
+ "var (slope)": Math.sqrt(1 / st2)
159
+ };
160
+ }
161
+
162
+ /**
163
+ * fast and memory efficient root to tip distance calculator
164
+ * for each leaf node stores the current root to tip distance in
165
+ * the node.rootToTip field
166
+ *
167
+ * @param tree
168
+ * @return tree with rootToTip computed
169
+ *
170
+ */
171
+ export default function rootToTip(tree) {
172
+
173
+ var bl = tree.branch_length_accessor,
174
+ index = 0;
175
+
176
+ tree.traverse_and_compute(n => {
177
+ if (n.parent) {
178
+ n.data._computed_length = bl(n);
179
+ if (!_.isNumber(n.data._computed_length)) {
180
+ throw "rootToTip cannot be run on trees with missing branch lengths";
181
+ }
182
+ }
183
+ if (tree.isLeafNode(n)) {
184
+ n.data.leaf_index = index++;
185
+ }
186
+ if ("r2t" in n.data) {
187
+ delete n.data.r2t;
188
+ }
189
+ });
190
+
191
+ tree.traverse_and_compute(n => {
192
+ if (n.parent) {
193
+ if (!("r2t" in n.parent.data)) {
194
+ n.parent.data.r2t = {};
195
+ }
196
+ if (tree.isLeafNode(n)) {
197
+ n.parent.data.r2t[n.data.leaf_index] = n.data._computed_length;
198
+ } else {
199
+ _.each(n.data.r2t, function(v, idx) {
200
+ n.parent.data.r2t[idx] = v + n.data._computed_length;
201
+ });
202
+ delete n.data.r2t;
203
+ }
204
+ delete n.data._computed_length;
205
+ }
206
+ });
207
+
208
+ var r2t = tree.getRootNode().data.r2t;
209
+
210
+ tree.traverse_and_compute(n => {
211
+ if (tree.isLeafNode(n)) {
212
+ n.data.rootToTip = r2t[n.data.leaf_index] || 0;
213
+ delete n.data.leaf_index;
214
+ }
215
+ });
216
+
217
+ delete tree.getRootNode().data.r2t;
218
+
219
+ return tree;
220
+ }
@@ -0,0 +1,21 @@
1
+ import * as _ from "underscore";
2
+
3
+ /*
4
+ * The Sackin's index is computed as the sum of the number of ancestors for each
5
+ * tips of the tree.
6
+ *
7
+ * The less balanced a tree is, the larger its Sackin's index.
8
+ *
9
+ */
10
+
11
+ export default function sackin(tree) {
12
+
13
+ // Get tips of tree
14
+ let tips = tree.getTips();
15
+
16
+ // Count number of ancestors to root for each tree
17
+ let depths = _.map(tips, d => { return d.depth });
18
+
19
+ return _.reduce(depths, function(memo, num){ return memo + num; }, 0);
20
+
21
+ }
package/src/nodes.js ADDED
@@ -0,0 +1,215 @@
1
+ import * as _ from "underscore";
2
+
3
+ // These methods are part of the Phylotree object
4
+
5
+ export function graftANode(graft_at, new_child, new_parent, lengths) {
6
+
7
+ let nodes = this.nodes.descendants();
8
+
9
+ if (graft_at.parent) {
10
+ let node_index = nodes.indexOf(graft_at);
11
+
12
+ if (node_index >= 0) {
13
+ let parent_index = graft_at.parent.children.indexOf(graft_at);
14
+
15
+ let new_split = {
16
+ name: new_parent,
17
+ parent: graft_at.parent,
18
+ attribute: lengths ? lengths[2] : null,
19
+ original_child_order: graft_at["original_child_order"]
20
+ },
21
+ new_node = {
22
+ name: new_child,
23
+ parent: new_split,
24
+ attribute: lengths ? lengths[1] : null,
25
+ original_child_order: 2
26
+ };
27
+
28
+ new_split["children"] = [graft_at, new_node];
29
+ graft_at["parent"].children[parent_index] = new_split;
30
+ graft_at.parent = new_split;
31
+ graft_at["attribute"] = lengths ? lengths[0] : null;
32
+ graft_at["original_child_order"] = 1;
33
+ }
34
+ }
35
+
36
+ return this;
37
+
38
+ }
39
+
40
+ /**
41
+ * Delete a given node.
42
+ *
43
+ * @param {Node} The node to be deleted, or the index of such a node.
44
+ * @returns The current ``phylotree``.
45
+ */
46
+ export function deleteANode(index) {
47
+ let nodes = this.nodes.descendants();
48
+
49
+ if (typeof index != "number") {
50
+ return this.deleteANode(nodes.indexOf(index));
51
+ }
52
+
53
+ if (index > 0 && index < nodes.length) {
54
+ let node = nodes[index];
55
+
56
+ if (node.parent) {
57
+ // can only delete nodes that are not the root
58
+ let delete_me_idx = node.parent.children.indexOf(node);
59
+
60
+ if (delete_me_idx >= 0) {
61
+ nodes.splice(index, 1);
62
+
63
+ if (node.children) {
64
+ node.children.forEach(function(d) {
65
+ d["original_child_order"] = node.parent.children.length;
66
+ node.parent.children.push(d);
67
+ d.parent = node.parent;
68
+ });
69
+ }
70
+
71
+ if (node.parent.children.length > 2) {
72
+ node.parent.children.splice(delete_me_idx, 1);
73
+ } else {
74
+ if (node.parent.parent) {
75
+ node.parent.parent.children[
76
+ node.parent.parent.children.indexOf(node.parent)
77
+ ] =
78
+ node.parent.children[1 - delete_me_idx];
79
+ node.parent.children[1 - delete_me_idx].parent = node.parent.parent;
80
+ nodes.splice(nodes.indexOf(node.parent), 1);
81
+ } else {
82
+ nodes.splice(0, 1);
83
+ nodes.parent = null;
84
+ delete nodes.data["attribute"];
85
+ delete nodes.data["annotation"];
86
+ delete nodes.data["original_child_order"];
87
+ nodes.name = "root";
88
+ nodes.data.name = "root";
89
+ }
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ return this;
96
+ }
97
+
98
+ /**
99
+ * Get the tips of the tree
100
+ * @returns {Array} Nodes in the current ``phylotree``.
101
+ */
102
+ export function getTips() {
103
+ // get all nodes that have no nodes
104
+ return _.filter(this.nodes.descendants(), n => {
105
+ return !_.has(n, "children");
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Get the internal nodes of the tree
111
+ * @returns {Array} Nodes in the current ``phylotree``.
112
+ */
113
+ export function getInternals() {
114
+ // get all nodes that have no nodes
115
+ return _.filter(this.nodes.descendants(), n => {
116
+ return _.has(n, "children");
117
+ });
118
+ }
119
+
120
+
121
+ /**
122
+ * Get the root node.
123
+ *
124
+ * @returns the current root node of the ``phylotree``.
125
+ */
126
+ export function getRootNode() {
127
+ return this.nodes;
128
+ }
129
+
130
+ /**
131
+ * Get an array of all nodes.
132
+ * @returns {Array} Nodes in the current ``phylotree``.
133
+ */
134
+ export function getNodes() {
135
+ return this.nodes;
136
+ }
137
+
138
+ /**
139
+ * Get a node by name.
140
+ *
141
+ * @param {String} name Name of the desired node.
142
+ * @returns {Node} Desired node.
143
+ */
144
+ export function getNodeByName(name) {
145
+ return _.filter(this.nodes.descendants(), d => {
146
+ return d.data.name == name;
147
+ })[0];
148
+ }
149
+
150
+ /**
151
+ * Add attributes to nodes. New attributes will be placed in the
152
+ * ``annotations`` key of any nodes that are matched.
153
+ *
154
+ * @param {Object} attributes An object whose keys are the names of nodes
155
+ * to modify, and whose values are the new attributes to add.
156
+ */
157
+ export function assignAttributes(attributes) {
158
+ //return nodes;
159
+ // add annotations to each matching node
160
+ _.each(this.nodes, function(d) {
161
+ if (_.indexOf(_.keys(attributes), d.name) >= 0) {
162
+ d["annotations"] = attributes[d.name];
163
+ }
164
+ });
165
+ }
166
+
167
+ /**
168
+ * Determine if a given node is a leaf node.
169
+ *
170
+ * @param {Node} A node in a tree.
171
+ * @returns {Bool} Whether or not the node is a leaf node.
172
+ */
173
+ export function isLeafNode(node) {
174
+ return !_.has(node, "children")
175
+ }
176
+
177
+ /**
178
+ * Update a given key name in each node.
179
+ *
180
+ * @param {String} old_key The old key name.
181
+ * @param {String} new_key The new key name.
182
+ * @returns The current ``this``.
183
+ */
184
+ export function updateKeyName(old_key, new_key) {
185
+ this.nodes.each(function(n) {
186
+ if (old_key in n) {
187
+ if (new_key) {
188
+ n[new_key] = n[old_key];
189
+ }
190
+ delete n[old_key];
191
+ }
192
+ });
193
+
194
+ return this;
195
+ }
196
+
197
+ export function clearInternalNodes(respect) {
198
+ if (!respect) {
199
+ this.nodes.each(d => {
200
+ if (!isLeafNode(d)) {
201
+
202
+ // TODO: Move away from storing attribute data as root (BREAKS occasionally with d3>3)
203
+ d[this.selection_attribute_name] = false;
204
+
205
+ if(!d.data.traits) {
206
+ d.data.traits = {};
207
+ }
208
+ d.data.traits[this.selection_attribute_name] = d[this.selection_attribute_name];
209
+
210
+ }
211
+ });
212
+ }
213
+ }
214
+
215
+
@@ -0,0 +1,23 @@
1
+ import * as d3 from "d3";
2
+ import { xCoord, yCoord } from "./coordinates";
3
+
4
+ export var draw_line = d3
5
+ .line()
6
+ .x(function(d) {
7
+ return xCoord(d);
8
+ })
9
+ .y(function(d) {
10
+ return yCoord(d);
11
+ })
12
+ .curve(d3.curveStepBefore);
13
+
14
+ export function lineSegmentPlacer(edge, where) {
15
+ return {
16
+ x:
17
+ xCoord(edge.target) +
18
+ (xCoord(edge.source) - xCoord(edge.target)) * where,
19
+ y: yCoord(edge.target)
20
+ };
21
+ }
22
+
23
+ export default draw_line;
@@ -0,0 +1,116 @@
1
+ import * as d3 from "d3";
2
+ import * as _ from "underscore";
3
+ import { isNodeCollapsed } from "./nodes";
4
+
5
+ export function cladeCssSelectors(css_classes) {
6
+ return [css_classes["clade"]].reduce(function(p, c, i, a) {
7
+ return (p += "path." + c + (i < a.length - 1 ? "," : ""));
8
+ }, "");
9
+ }
10
+
11
+ export function updateCollapsedClades(transitions) {
12
+
13
+ let enclosure = this.svg.selectAll("." + this.css_classes["tree-container"]);
14
+ var node_id = 0;
15
+
16
+ let collapsed_clades = enclosure
17
+ .selectAll(cladeCssSelectors(this.css_classes))
18
+ .data(
19
+ this.phylotree.nodes.descendants().filter(isNodeCollapsed),
20
+ function(d) {
21
+ return d.id || (d.id = ++node_id);
22
+ }
23
+ );
24
+
25
+ let spline = function() {};
26
+ let spline_f = _.noop();
27
+
28
+ // Collapse radial differently
29
+ if (this.radial()) {
30
+ spline = d3
31
+ .line()
32
+ .curve(d3.curveBasis)
33
+ .y(function(d) {
34
+ return d[0];
35
+ })
36
+ .x(function(d) {
37
+ return d[1];
38
+ });
39
+
40
+ spline_f = function(coord, i, d, init_0, init_1) {
41
+ if (i) {
42
+ return [
43
+ d.screen_y + (coord[0] - init_0) / 50,
44
+ d.screen_x + (coord[1] - init_1) / 50
45
+ ];
46
+ } else {
47
+ return [d.screen_y, d.screen_x];
48
+ }
49
+ };
50
+ } else {
51
+ spline = d3
52
+ .line()
53
+ .y(function(d) {
54
+ return d[0];
55
+ })
56
+ .x(function(d) {
57
+ return d[1];
58
+ }).curve(d3.curveBasis);
59
+
60
+ spline_f = function(coord, i, d, init_0, init_1) {
61
+ if (i) {
62
+ return [
63
+ d.screen_y + (coord[0] - init_0) / 50 ,
64
+ d.screen_x + (coord[1] - init_1) / 50,
65
+ ];
66
+ } else {
67
+ return [d.screen_y, d.screen_x];
68
+ }
69
+ };
70
+ }
71
+
72
+ collapsed_clades
73
+ .exit()
74
+ .each(function(d) {
75
+ d.collapsed_clade = null;
76
+ })
77
+ .remove();
78
+
79
+ if (transitions) {
80
+ collapsed_clades
81
+ .enter()
82
+ .insert("path", ":first-child")
83
+ .attr("class", this.css_classes["clade"])
84
+ .merge(collapsed_clades)
85
+ .attr("d", function(d) {
86
+ if (d.collapsed_clade) {
87
+ return d.collapsed_clade;
88
+ }
89
+
90
+ //console.log (d.collapsed);
91
+ let init_0 = d.collapsed[0][0];
92
+ let init_1 = d.collapsed[0][1];
93
+
94
+
95
+
96
+ // #1 return spline(d.collapsed.map(spline_f, d, init_0, init_1));
97
+ return spline(
98
+ d.collapsed.map(function(coord, i) {
99
+ return spline_f(coord, i, d, init_0, init_1);
100
+ })
101
+ );
102
+ })
103
+ .attr("d", function(d) {
104
+ return (d.collapsed_clade = spline(d.collapsed));
105
+ });
106
+ } else {
107
+ collapsed_clades
108
+ .enter()
109
+ .insert("path", ":first-child")
110
+ .attr("class", this.css_classes["clade"])
111
+ .merge(collapsed_clades)
112
+ .attr("d", function(d) {
113
+ return (d.collapsed_clade ? d.collapsed_clade : d.collapsed_clade = spline(d.collapsed));
114
+ });
115
+ }
116
+ }