phylotree 1.0.20 → 1.1.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.
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs"),
4
+ phylotree = require("../dist/phylotree.js"),
5
+ commander = require("commander"),
6
+ _ = require("lodash");
7
+
8
+ commander
9
+ .arguments("<fasta>", "Input fasta file")
10
+ .usage("./test/data/CD2.fas")
11
+ .on("--help", function() {
12
+ console.log("\nConstructs neighbor-joining algorithm");
13
+ })
14
+ .parse(process.argv);
15
+
16
+
17
+ fs.readFile(commander.args[0], ( err, fastaData ) => {
18
+
19
+ let fasta = phylotree.parseFasta(fastaData);
20
+ let nodeList = _.keys(fasta);
21
+ let distanceMatrix = phylotree.getDistanceMatrix(fasta);
22
+ let distanceMatrixArr = _.values(distanceMatrix);
23
+
24
+ let nj = phylotree.neighborJoining(distanceMatrixArr, _.keys(fasta).length, nodeList)
25
+ console.log(nj.getNewick());
26
+
27
+ });
28
+
package/dist/phylotree.js CHANGED
@@ -70,34 +70,36 @@
70
70
 
71
71
  // These methods are part of the Phylotree object
72
72
 
73
- function graftANode(graft_at, new_child, new_parent, lengths) {
73
+ function graftANode(graftAt, newChild, newParent, lengths) {
74
74
 
75
75
  let nodes = this.nodes.descendants();
76
76
 
77
- if (graft_at.parent) {
78
- let node_index = nodes.indexOf(graft_at);
77
+ if (graftAt.parent) {
79
78
 
80
- if (node_index >= 0) {
81
- let parent_index = graft_at.parent.children.indexOf(graft_at);
79
+ let nodeIndex = nodes.indexOf(graftAt);
82
80
 
83
- let new_split = {
84
- name: new_parent,
85
- parent: graft_at.parent,
81
+ if (nodeIndex >= 0) {
82
+
83
+ let parentIndex = graftAt.parent.children.indexOf(graftAt);
84
+
85
+ let newSplit = {
86
+ name: newParent,
87
+ parent: graftAt.parent,
86
88
  attribute: lengths ? lengths[2] : null,
87
- original_child_order: graft_at["original_child_order"]
89
+ original_child_order: graftAt["original_child_order"]
88
90
  },
89
- new_node = {
90
- name: new_child,
91
- parent: new_split,
91
+ newNode = {
92
+ name: newChild,
93
+ parent: newSplit,
92
94
  attribute: lengths ? lengths[1] : null,
93
95
  original_child_order: 2
94
96
  };
95
97
 
96
- new_split["children"] = [graft_at, new_node];
97
- graft_at["parent"].children[parent_index] = new_split;
98
- graft_at.parent = new_split;
99
- graft_at["attribute"] = lengths ? lengths[0] : null;
100
- graft_at["original_child_order"] = 1;
98
+ newSplit["children"] = [graftAt, newNode];
99
+ graftAt["parent"].children[parentIndex] = newSplit;
100
+ graftAt.parent = newSplit;
101
+ graftAt["attribute"] = lengths ? lengths[0] : null;
102
+ graftAt["original_child_order"] = 1;
101
103
  }
102
104
  }
103
105
 
@@ -105,6 +107,30 @@
105
107
 
106
108
  }
107
109
 
110
+ function addChild(parent, child) {
111
+
112
+ if(parent.children) {
113
+ parent.children.push(child);
114
+ } else {
115
+ parent["children"] = [child];
116
+ }
117
+
118
+ return parent;
119
+
120
+ }
121
+
122
+ function createNode(name, lengths) {
123
+
124
+ return {
125
+ data: {
126
+ name: name,
127
+ attribute: lengths ? lengths[1] : null
128
+ },
129
+ parent: '',
130
+ };
131
+
132
+ }
133
+
108
134
  /**
109
135
  * Delete a given node.
110
136
  *
@@ -225,9 +251,9 @@
225
251
  function assignAttributes(attributes) {
226
252
  //return nodes;
227
253
  // add annotations to each matching node
228
- ___namespace.each(this.nodes, function(d) {
229
- if (___namespace.indexOf(___namespace.keys(attributes), d.name) >= 0) {
230
- d["annotations"] = attributes[d.name];
254
+ ___namespace.each(this.nodes.descendants(), function(d) {
255
+ if (d.data && (d.data.name in attributes)) {
256
+ d["annotations"] = attributes[d.data.name];
231
257
  }
232
258
  });
233
259
  }
@@ -283,6 +309,8 @@
283
309
  var node_operations = /*#__PURE__*/Object.freeze({
284
310
  __proto__: null,
285
311
  graftANode: graftANode,
312
+ addChild: addChild,
313
+ createNode: createNode,
286
314
  deleteANode: deleteANode,
287
315
  getTips: getTips,
288
316
  getInternals: getInternals,
@@ -520,11 +548,12 @@
520
548
  *
521
549
  * @param {Function} annotator - Function to apply to each node, determining
522
550
  * what label is written (optional).
551
+ * @param {Node} node - start at this node (default == root)
523
552
  * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
524
553
  */
525
554
 
526
555
  // TODO: break this out into two seperate functions
527
- function getNewick(annotator) {
556
+ function getNewick(annotator, root) {
528
557
 
529
558
  let self = this;
530
559
 
@@ -556,7 +585,7 @@
556
585
 
557
586
  let element_array = [];
558
587
  annotator = annotator || "";
559
- nodeDisplay(this.nodes);
588
+ nodeDisplay(root || this.nodes);
560
589
 
561
590
  return element_array.join("")+";";
562
591
 
@@ -1030,7 +1059,6 @@
1030
1059
  function defBranchLengthAccessor(_node, new_length) {
1031
1060
 
1032
1061
  let _node_data = _node.data;
1033
- //let _node_data = _node;
1034
1062
 
1035
1063
  if (
1036
1064
  "attribute" in _node_data &&
@@ -2586,7 +2614,7 @@
2586
2614
  .append("a")
2587
2615
  .attr("class", "dropdown-item")
2588
2616
  .attr("tabindex", "-1")
2589
- .text(constant(d[0])(node)) // eslint-disable-line
2617
+ .text((d[0])(node)) // eslint-disable-line
2590
2618
  .on("click", ___namespace.partial(d[1], node));
2591
2619
  });
2592
2620
  }
@@ -2848,7 +2876,7 @@
2848
2876
  });
2849
2877
 
2850
2878
  // replacement for d3.functor
2851
- function constant$1(x) {
2879
+ function constant(x) {
2852
2880
  return function() {
2853
2881
  return x;
2854
2882
  };
@@ -2925,7 +2953,7 @@
2925
2953
  "minimum-per-node-spacing": 2,
2926
2954
  "maximum-per-level-spacing": 100,
2927
2955
  "minimum-per-level-spacing": 10,
2928
- node_circle_size: constant$1(3),
2956
+ node_circle_size: constant(3),
2929
2957
  transitions: null,
2930
2958
  brush: true,
2931
2959
  reroot: true,
@@ -4013,7 +4041,7 @@
4013
4041
 
4014
4042
  node_circle_size(attr, attr2) {
4015
4043
  if (!arguments.length) return this.options["node_circle_size"];
4016
- this.options["node_circle_size"] = constant$1(attr === undefined ? 3 : attr);
4044
+ this.options["node_circle_size"] = constant(attr === undefined ? 3 : attr);
4017
4045
  return this;
4018
4046
  }
4019
4047
 
@@ -5397,16 +5425,228 @@
5397
5425
  return clusters;
5398
5426
  }
5399
5427
 
5428
+ function parseFasta(fastaData) {
5429
+
5430
+
5431
+ let sfasta = ___namespace$1.split(fastaData, "\n");
5432
+
5433
+ let seqs = ___namespace$1.chain(sfasta)
5434
+ .map((d, i) => (d.startsWith(">") ? i : -1))
5435
+ .filter((d) => d != -1)
5436
+ .map((d, i, c) => ___namespace$1.slice(sfasta, c[i], c[i + 1]))
5437
+ .keyBy((d) => ___namespace$1.trim(d[0], ">"))
5438
+ .mapValues((d) => ___namespace$1.tail(d).join(""))
5439
+ .value();
5440
+
5441
+ return seqs;
5442
+
5443
+ }
5444
+
5445
+ function remove(i, D) {
5446
+ let dNew = [];
5447
+
5448
+ for (let j of ___namespace$1.range(D.length)) {
5449
+ if (j != i) {
5450
+ let dNewRow = [];
5451
+ for (let k of ___namespace$1.range(D[j].length)) {
5452
+ if (k != i) {
5453
+ dNewRow.push(D[j][k]);
5454
+ }
5455
+ }
5456
+ dNew.push(dNewRow);
5457
+ }
5458
+ }
5459
+
5460
+ return dNew;
5461
+ }
5462
+
5463
+ function getDPrime(distanceMatrix, totalDistances, N) {
5464
+ let DPrime = ___namespace$1.chunk(___namespace$1.fill(Array(N * N), 0), N);
5465
+ for (let i of ___namespace$1.range(N)) {
5466
+ for (let j of ___namespace$1.range(___namespace$1.parseInt(i) + 1, N)) {
5467
+ DPrime[i][j] =
5468
+ (N - 2) * distanceMatrix[i][j] - totalDistances[i] - totalDistances[j];
5469
+ DPrime[j][i] = DPrime[i][j];
5470
+ }
5471
+ }
5472
+ return DPrime;
5473
+ }
5474
+
5475
+ function ijMinDPrime(dPrime, N) {
5476
+ let i = -1;
5477
+ let j = -1;
5478
+ let minD = Infinity;
5479
+ for (let ii of ___namespace$1.range(N)) {
5480
+ for (let jj of ___namespace$1.range(i, N)) {
5481
+ if (dPrime[ii][jj] < minD) {
5482
+ i = ii;
5483
+ j = jj;
5484
+ minD = dPrime[i][j];
5485
+ }
5486
+ }
5487
+ }
5488
+ return [i, j, minD];
5489
+ }
5490
+
5491
+ function createDelta(totalDistances, N) {
5492
+ let deltaMatrix = ___namespace$1.chunk(Array(N * N), N);
5493
+
5494
+ for (let i of ___namespace$1.range(N)) {
5495
+ for (let j of ___namespace$1.range(parseInt(i) + 1, N)) {
5496
+ deltaMatrix[i][j] = (totalDistances[i] - totalDistances[j]) / (N - 2);
5497
+ deltaMatrix[j][i] = deltaMatrix[i][j];
5498
+ }
5499
+ }
5500
+
5501
+ return deltaMatrix;
5502
+ }
5503
+
5504
+ function getDistanceMatrix(seqs) {
5505
+ // Gaps are masked
5506
+
5507
+ let initKey = ___namespace$1.keys(seqs)[0];
5508
+ let seqLength = seqs[initKey].length;
5509
+
5510
+ return ___namespace$1.mapValues(seqs, (seq) =>
5511
+ ___namespace$1.map(seqs, (seq2) =>
5512
+ ___namespace$1.sum(
5513
+ ___namespace$1.map(
5514
+ ___namespace$1.range(seqLength),
5515
+ (i) => seq[i] != seq2[i] && seq[i] != "-" && seq2[i] != "-"
5516
+ )
5517
+ )
5518
+ )
5519
+ );
5520
+ }
5521
+
5522
+ function getTotalDistances(distanceMatrix) {
5523
+ return ___namespace$1.map(distanceMatrix, ___namespace$1.sum);
5524
+ }
5525
+
5526
+ /**
5527
+ * Create a neighbor joining tree from a distance matrix
5528
+ * See test/neighbor-join-test.js for a working example
5529
+ *
5530
+ * @param {Array} distanceMatrixArr The NxN distance matrix.
5531
+ * const D = [
5532
+ * [0, 5, 9, 9, 8],
5533
+ * [5, 0, 10, 10, 9],
5534
+ * [9, 10, 0, 8, 7],
5535
+ * [9, 10, 8, 0, 3],
5536
+ * [8, 9, 7, 3, 0]
5537
+ * ];
5538
+ *
5539
+ * @param {Number} n The dimension of the distanceMatrixArr.
5540
+ * @param {Array} nodeList The names of each row in the distanceMatrix
5541
+ * @returns The neighbor joining new tree.
5542
+ */
5543
+ function neighborJoining(distanceMatrixArr, n, nodeList) {
5544
+ if (n <= 2) {
5545
+ let tree = new Phylotree("");
5546
+
5547
+ //T.link(nodeList[0],nodeList[1],D[0][1])
5548
+
5549
+ let newNode = tree.getNodes();
5550
+ // Get root
5551
+ let distance = distanceMatrixArr[0][1] / 2;
5552
+
5553
+ let nodeA = tree.createNode(nodeList[0], [null, [distance]]);
5554
+ let nodeB = tree.createNode(nodeList[1], [null, [distance]]);
5555
+
5556
+ //// Add the children to the newly created node
5557
+ tree.addChild(newNode, nodeA);
5558
+ tree.addChild(newNode, nodeB);
5559
+
5560
+ return tree;
5561
+ } else {
5562
+ let N = n;
5563
+ let totalDistances = getTotalDistances(distanceMatrixArr);
5564
+ let dPrime = getDPrime(distanceMatrixArr, totalDistances, N);
5565
+ let [i, j, minD] = ijMinDPrime(dPrime, N);
5566
+ let deltaMatrix = createDelta(totalDistances, N);
5567
+ let limbLengthI = (distanceMatrixArr[i][j] + deltaMatrix[i][j]) / 2;
5568
+ let limbLengthJ = (distanceMatrixArr[i][j] - deltaMatrix[i][j]) / 2;
5569
+ let newRow = ___namespace$1.concat(
5570
+ 0,
5571
+ ___namespace$1.filter(
5572
+ ___namespace$1.map(___namespace$1.range(n), (k) => {
5573
+ if (k != i && k != j) {
5574
+ return (
5575
+ 0.5 *
5576
+ (distanceMatrixArr[k][i] +
5577
+ distanceMatrixArr[k][j] -
5578
+ distanceMatrixArr[i][j])
5579
+ );
5580
+ }
5581
+ }),
5582
+ ___namespace$1.isNumber
5583
+ )
5584
+ );
5585
+
5586
+ let nodeI = nodeList[i];
5587
+ let nodeJ = nodeList[j];
5588
+
5589
+ // Get all nodes of type InternalNode{x} and increment number.
5590
+ // If there are none, start with InternalNode0
5591
+ let m = "InternalNode0";
5592
+ let internalNodes = ___namespace$1.filter(nodeList, (x) =>
5593
+ ___namespace$1.includes(x, "InternalNode")
5594
+ );
5595
+
5596
+ if (internalNodes.length) {
5597
+ let highestNum = ___namespace$1.max(
5598
+ ___namespace$1.map(internalNodes, (label) => ___namespace$1.split(label, "InternalNode")[1])
5599
+ );
5600
+ m = "InternalNode" + ++highestNum;
5601
+ }
5602
+
5603
+ nodeList.unshift(m);
5604
+
5605
+ distanceMatrixArr = remove(___namespace$1.max([i, j]), distanceMatrixArr);
5606
+ distanceMatrixArr = remove(___namespace$1.min([i, j]), distanceMatrixArr);
5607
+
5608
+ distanceMatrixArr.unshift(newRow);
5609
+
5610
+ ___namespace$1.each(___namespace$1.range(1, n - 1), (l) => distanceMatrixArr[l].unshift(newRow[l]));
5611
+
5612
+ // Remove from nodeList
5613
+ ___namespace$1.remove(nodeList, (n) => n == nodeI || n == nodeJ);
5614
+ let tree = neighborJoining(distanceMatrixArr, N - 1, nodeList);
5615
+
5616
+ let treeNodeI = tree.createNode(nodeI, [null, [limbLengthI]]);
5617
+ let treeNodeJ = tree.createNode(nodeJ, [null, [limbLengthJ]]);
5618
+
5619
+ // If the node doesn't exist, create. Otherwise, reassign the length
5620
+ if (tree.getNodeByName(m)) {
5621
+ let internalNode = tree.getNodeByName(m);
5622
+ tree.addChild(internalNode, treeNodeI);
5623
+ tree.addChild(internalNode, treeNodeJ);
5624
+ } else {
5625
+ let newNode = tree.createNode(m, [null, [0]]);
5626
+ tree.addChild(tree.getNodes(), newNode);
5627
+ // Add the children to the newly created node
5628
+ tree.addChild(newNode, treeNodeI);
5629
+ tree.addChild(newNode, treeNodeJ);
5630
+ }
5631
+
5632
+ // Set negative to 0 and add distance to other limblength
5633
+ return tree;
5634
+ }
5635
+ }
5636
+
5400
5637
  exports.centerOfTree = centerOfTree;
5401
5638
  exports.clusterPicker = clusterPicker;
5402
5639
  exports.computeMidpoint = computeMidpoint;
5403
5640
  exports.extract_dates = extract_dates;
5404
5641
  exports.fitRootToTip = fitRootToTip;
5642
+ exports.getDistanceMatrix = getDistanceMatrix;
5405
5643
  exports.inOrder = inOrder;
5406
5644
  exports.leftChildRightSibling = leftChildRightSibling;
5407
5645
  exports.loadAnnotations = loadAnnotations;
5646
+ exports.neighborJoining = neighborJoining;
5408
5647
  exports.pairwise_distances = computePairwiseDistances;
5409
5648
  exports.parseAnnotations = parseAnnotations;
5649
+ exports.parseFasta = parseFasta;
5410
5650
  exports.phylopart = phylopart;
5411
5651
  exports.phylotree = Phylotree;
5412
5652
  exports.postOrder = postOrder;
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("d3"),require("underscore"),require("lodash")):"function"==typeof define&&define.amd?define(["exports","d3","underscore","lodash"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).phylotree=t.phylotree||{},t.d3,t._,t._$1)}(this,(function(t,e,n,s){"use strict";function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(n){if("default"!==n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})),e.default=t,Object.freeze(e)}var a=i(e),r=i(n),o=i(s);function l(t){return!r.has(t,"children")}var h=Object.freeze({__proto__:null,graftANode:function(t,e,n,s){let i=this.nodes.descendants();if(t.parent){if(i.indexOf(t)>=0){let i=t.parent.children.indexOf(t),a={name:n,parent:t.parent,attribute:s?s[2]:null,original_child_order:t.original_child_order},r={name:e,parent:a,attribute:s?s[1]:null,original_child_order:2};a.children=[t,r],t.parent.children[i]=a,t.parent=a,t.attribute=s?s[0]:null,t.original_child_order=1}}return this},deleteANode:function(t){let e=this.nodes.descendants();if("number"!=typeof t)return this.deleteANode(e.indexOf(t));if(t>0&&t<e.length){let n=e[t];if(n.parent){let s=n.parent.children.indexOf(n);s>=0&&(e.splice(t,1),n.children&&n.children.forEach((function(t){t.original_child_order=n.parent.children.length,n.parent.children.push(t),t.parent=n.parent})),n.parent.children.length>2?n.parent.children.splice(s,1):n.parent.parent?(n.parent.parent.children[n.parent.parent.children.indexOf(n.parent)]=n.parent.children[1-s],n.parent.children[1-s].parent=n.parent.parent,e.splice(e.indexOf(n.parent),1)):(e.splice(0,1),e.parent=null,delete e.data.attribute,delete e.data.annotation,delete e.data.original_child_order,e.name="root",e.data.name="root"))}}return this},getTips:function(){return r.filter(this.nodes.descendants(),(t=>!r.has(t,"children")))},getInternals:function(){return r.filter(this.nodes.descendants(),(t=>r.has(t,"children")))},getRootNode:function(){return this.nodes},getNodes:function(){return this.nodes},getNodeByName:function(t){return r.filter(this.nodes.descendants(),(e=>e.data.name==t))[0]},assignAttributes:function(t){r.each(this.nodes,(function(e){r.indexOf(r.keys(t),e.name)>=0&&(e.annotations=t[e.name])}))},isLeafNode:l,updateKeyName:function(t,e){return this.nodes.each((function(n){t in n&&(e&&(n[e]=n[t]),delete n[t])})),this},clearInternalNodes:function(t){t||this.nodes.each((t=>{l(t)||(t[this.selection_attribute_name]=!1,t.data.traits||(t.data.traits={}),t.data.traits[this.selection_attribute_name]=t[this.selection_attribute_name])}))}});function d(t,e={}){const n=/^-?\d+(\.\d+)?$/;let s=e.left_delimiter||"{",i=e.right_delimiter||"}",a=[];function r(){let t=a[a.length-1];"children"in t||(t.children=[]),a.push({name:null}),t.children.push(a[a.length-1]),a[a.length-1].original_child_order=t.children.length}function o(){let t=a.pop();t.name=d,"children"in t?t.bootstrap_values=d:t.name=d,t.attribute=c,"["==s&&u.includes("&&NHX")?u.split(":").slice(1).forEach((e=>{const[s,i]=e.split("=");t[s]=n.test(i)?+i:i})):t.annotation=u,d="",c="",u=""}function l(e){return{json:null,error:"Unexpected '"+t[e]+"' in '"+t.substring(e-20,e+1)+"[ERROR HERE]"+t.substring(e+1,e+20)+"'"}}let h=0,d="",c="",u="",p=null,_={"'":1,'"':1},f={name:"root"};a.push(f);for(var g=/\s/,m=0;m<t.length;m++)try{var b=t[m];switch(h){case 0:"("==b&&(r(),h=1);break;case 1:case 3:if(":"==b)h=3;else if(","==b||")"==b)try{o(),h=1,","==b&&r()}catch(t){return l(m)}else if("("==b){if(d.length>0)return l(m);r()}else{if(b in _){if(1==h&&0===d.length&&0===c.length&&0===u.length){h=2,p=b;continue}return l(m)}if(b==s){if(u.length)return l(m);h=4}else if(3==h)c+=b;else{if(g.test(b))continue;if(";"==b){m=t.length;break}d+=b}}break;case 2:if(b==p){if(m<t.length-1&&t[m+1]==p){m++,d+=p;continue}p=0,h=1;continue}d+=b;break;case 4:if(b==i)h=3;else{if(b==s)return l(m);u+=b}}}catch(t){return l(m)}return 1!=a.length?l(t.length-1):{json:f,error:null}}function c(t){let e=t,n=e.toUpperCase().indexOf("BEGIN DATA;"),s=e.slice(n);if(s.length<2)return"";n=s.toUpperCase().indexOf("END;");let i=s.slice(0,n);s=r.map(i.split(";"),(t=>t.trim()));let a=r.filter(s,(t=>t.toUpperCase().startsWith("DIMENSION")));a=a[0].split(" "),a=r.object(r.map(r.rest(a),(t=>t.split("="))));let o=r.filter(s,(t=>t.toUpperCase().startsWith("FORMAT")));o=o[0].split(" "),o=r.object(r.map(r.rest(o),(t=>t.split("=")))),o.symbols=r.reject(o.symbols.split(""),(t=>'"'==t));let l=r.filter(s,(t=>t.toUpperCase().startsWith("MATRIX")));return l=l[0].split("\n"),l=r.object(r.map(r.rest(l),(t=>r.compact(t.split(" "))))),l=r.mapObject(l,((t,e)=>"?"==t?o.symbols:Array(t))),{dimensions:a,format:o,matrix:l}}function u(t,e,n){r.each(t.getTips(),(t=>{t.data.test=n.matrix[t.data.name]}))}function p(t){let e=t,n=e.toUpperCase().indexOf("BEGIN TREES;"),s=e.slice(n);if(s.length<2)return"";n=s.toUpperCase().indexOf("END;");let i=s.slice(0,n).split("\n");return i=r.filter(i,(t=>t.trim().toUpperCase().startsWith("TREE"))),d(i[0])}var _=Object.freeze({__proto__:null,parseAnnotations:c,loadAnnotations:u,default:p});function f(t){var e={};if(1==t.nodeType){if(t.attributes.length>0){e["@attributes"]={};for(var n=0;n<t.attributes.length;n++){var s=t.attributes.item(n);e["@attributes"][s.nodeName]=s.nodeValue}}}else 3==t.nodeType&&(e=t.nodeValue);if(t.hasChildNodes()&&1===t.childNodes.length&&3===t.childNodes[0].nodeType)e=t.childNodes[0].nodeValue;else if(t.hasChildNodes())for(var i=0;i<t.childNodes.length;i++){var a=t.childNodes.item(i),r=a.nodeName;if(void 0===e[r])e[r]=f(a);else{if(void 0===e[r].push){var o=e[r];e[r]=[],e[r].push(o)}e[r].push(f(a))}}return e}var g=function(t,e){var n;return(n=(t=f(t)).phyloxml.phylogeny.clade).name="root",function t(e,n){e.clade&&(e.clade.forEach(t),e.children=e.clade,delete e.clade),e.annotation=1,e.attribute="0.01",e.branch_length&&(e.attribute=e.branch_length),e.taxonomy&&(e.name=e.taxonomy.scientific_name),e.annotation=""}(n),{json:n,error:null}};var m={nexml:function(t,e){var n;return parseString(t,(function(t,e){n=e["nex:nexml"].trees[0].tree.map((function(t){var e=t.node.map((t=>t.$)),n=e.reduce((function(t,e){return e.edges=[],e.name=e.id,t[e.id]=e,t}),{}),s=e.filter((t=>t.root)),i=s>0?s[0].id:e[0].id;return n[i].name="root",t.edge.map((t=>t.$)).forEach((function(t){n[t.source].edges.push(t)})),function t(e,s){if(e.edges){var i=r.pluck(e.edges,"target");e.children=r.values(r.pick(n,i)),e.children.forEach((function(t,n){t.attribute=e.edges[n].length||""})),e.children.forEach(t),e.annotation=""}}(n[i]),n[i]}))})),n},phyloxml:g,nexus:p,nwk:d,nhx:d,beast:function(t,e){e.left_delimiter="[",e.right_delimiter="]";const n=d(t,e);return function t(e){if(e.annotation){e.beast={};const t=e.annotation.split(/=|,|{|}/).filter((t=>t));for(var n=0;n<t.length;n+=2){let s=t[n].replace(/&|%/g,"");/[a-df-zA-DF-Z]+/.test(t[n+2])?e.beast[s]=+t[n+1]:(e.beast[s]=[+t[n+1],+t[n+2]],n++)}}e.annotation=void 0,e.children&&e.children.forEach(t)}(n.json),n}};function b(t,e,n){let s,i,a,r=[t],o=[];for(;t=r.pop();)if((!n||!n(t))&&(o.push(t),s=t.children,s))for(i=0,a=s.length;i<a;++i)r.push(s[i]);for(;t=o.pop();)e(t);return t}function v(t,e,n){let s,i,a=[t];for(;t=a.pop();)if((!n||!n(t))&&(e(t),s=t.children,s))for(i=s.length-1;i>=0;--i)a.push(s[i]);return t}function y(t,e,n){let s,i,a,r,o=[t];do{for(s=o.reverse(),o=[];t=s.pop();)if((!n||!n(t))&&(e(t),i=t.children,i))for(a=0,r=i.length;a<r;++a)o.push(i[a])}while(o.length);return t}function x(t){return b(t,(function(t){t.children&&(t.children[0].data.multiway_parent=t,t.children[1].data.multiway_parent=t.parent)})),o.map(t.descendants(),(t=>{let e=t.data.multiway_parent,n="unknown";return e&&(n=e.data.name),{source:t.data.multiway_parent,target:t,name:n}}))}function w(t,e){let n=t.data;if("attribute"in n&&n.attribute&&n.attribute.length){e>0&&(n.attribute=String(e));let t=parseFloat(n.attribute);if(!isNaN(t))return Math.max(0,t)}if("root"==n.name)return 0;console.warn("Undefined branch length at "+n.name+"!")}var N=Object.freeze({__proto__:null,reroot:function(t,e){if(!(t instanceof a.hierarchy))throw new Error("node needs to be an instance of a d3.hierarchy node!");let n=this.nodes.copy();if(e=void 0!==e?e:.5,t.parent){var s=a.hierarchy({name:"new_root"});s.children=[t.copy()],s.data.__mapped_bl=void 0,n.each((t=>{t.data.__mapped_bl=this.branch_length_accessor(t)})),this.setBranchLength((t=>t.data.__mapped_bl));let o=t,l=t.parent,h=r.noop(),d=void 0===t.data.__mapped_bl?void 0:t.data.__mapped_bl*e;var i;if(h=l.data.__mapped_bl,l.data.__mapped_bl=void 0===t.data.__mapped_bl?void 0:t.data.__mapped_bl-d,t.data.__mapped_bl=d,l.parent){for(s.children.push(l);l.parent;){i=l.children.indexOf(o),l.parent.parent?l.children.splice(i,1,l.parent):l.children.splice(i,1);let t=l.parent.data.__mapped_bl;void 0!==t&&(l.parent.data.__mapped_bl=h,h=t),o=l,l=l.parent}i=l.children.indexOf(o),l.children.splice(i,1)}else i=l.children.indexOf(o),l.children.splice(i,1),h=l.data.__mapped_bl,o=s;if(1==l.children.length)h&&(l.children[0].data.__mapped_bl+=h),o.children=o.children.concat(l.children);else{let e=new a.hierarchy({name:"__reroot_top_clade",__mapped_bl:h});r.extendOwn(s.children[0],t),e.data.__mapped_bl=h,e.children=l.children.map((function(t){return t.parent=e,t})),e.parent=o,o.children.push(e)}}if(this.update(s),this.traverse_and_compute((t=>{r.each(t.children,(e=>{e.parent=t}))}),"pre-order"),!r.isUndefined(this.display)){let t=this.display.options;a.select(this.display.container).select("svg").remove();let e=this.display.selection_attribute_name;delete this.display;let n=this.render(t);n.selectionLabel(e),n.update(),a.select(n.container).node().appendChild(n.show()),a.select(this.display.container).dispatch("reroot")}return this},rootpath:function(t,e){if(t=t||"attribute",e=e||"y_scaled","parent"in this){let n=parseFloat(this[t]);this[e]=this.parent[e]+(isNaN(n)?.1:n)}else this[e]=0;return this[e]},pathToRoot:function(t){let e=[];for(;t;)e.push(t),t=t.parent;return e}});function z(t){return t.y}function k(t){return t.x}function E(t,e,n){return{x:n+t*Math.sin(e),y:n+t*Math.cos(e)}}function S(t,e,n,s,i,a){t.radius=e*(t.radius+n),t.angle=2*Math.PI*t.x*i[0]/a[0];let r=E(t.radius,t.angle,s);return t.x=r.x,t.y=r.y,t}function M(t,e){var n=E(e[0].radius,e[0].angle,t),s=E(e[0].radius,e[1].angle,t);return"M "+z(n)+","+k(n)+" A "+e[0].radius+","+e[0].radius+" 0,0, "+(e[1].angle>e[0].angle?1:0)+" "+z(s)+","+k(s)+" L "+z(e[1])+","+k(e[1])}function L(t,e,n){var s=E(t.target.radius+(t.source.radius-t.target.radius)*e,t.target.angle,n);return{x:z(s),y:k(s)}}var A=a.line().x((function(t){return z(t)})).y((function(t){return k(t)})).curve(a.curveStepBefore);function T(t,e){return{x:z(t.target)+(z(t.source)-z(t.target))*e,y:k(t.target)}}function C(t){return t.tag||!1}function O(t,e){return t[e]||!1}const j={"tree-container":"phylotree-container","tree-scale-bar":"tree-scale-bar",node:"node","internal-node":"internal-node","tagged-node":"node-tagged","selected-node":"node-selected","collapsed-node":"node-collapsed","root-node":"root-node",branch:"branch","selected-branch":"branch-selected","tagged-branch":"branch-tagged","tree-selection-brush":"tree-selection-brush","branch-tracer":"branch-tracer",clade:"clade",node_text:"phylotree-node-text"};function P(t){return arguments.length?(P="string"==typeof t&&"equal"==t?function(t){return 1}:t,this):P}var R={all:t=>!0,none:t=>!1,"all-leaf-nodes":t=>l(t.target),"all-internal-nodes":t=>!l(t.target)};var H=Object.freeze({__proto__:null,css_classes:j,internalNames:function(t){return arguments.length?(this.options["internal-names"]=t,this):this.options["internal-names"]},radial:function(t){return arguments.length?(this.options["is-radial"]=t,this):this.options["is-radial"]},alignTips:function(t){return arguments.length?(this.options["align-tips"]=t,this):this.options["align-tips"]},nodeBubbleSize:function(t){return this.options["draw-size-bubbles"]&&this.options["bubble-styler"]?this.options["bubble-styler"](t):this.options["draw-size-bubbles"]?this.relative_nodeSpan(t)*this.scales[0]*.25:0},shiftTip:function(t){return this.options["is-radial"]?[("end"==t.text_align?-1:1)*(this.radius_pad_for_bubbles-t.radius),0]:(this.options["right-to-left"],[this.right_most_leaf-t.screen_x,0])},layoutHandler:function(t){return arguments.length?(this.layout_listener_handler=t,this):this.layout_listener_handler},selectionLabel:function(t){return arguments.length?(this.selection_attribute_name=t,this.syncEdgeLabels(),this):this.selection_attribute_name},get nodeSpan(){return P},predefined_selecters:R,selectionCallback:function(t){return t?(this.selectionCallback=t,this):this.selectionCallback}});function U(t){return!(t.hidden||t.notshown)}function B(t){return t.notshown}function I(t){return t.hasHiddenNodes||!1}function D(t){return t.collapsed||!1}function q(t){return[t.node,t["internal-node"],t["collapsed-node"],t["tagged-node"],t["root-node"]].reduce((function(t,e,n,s){return t+"g."+e+(n<s.length-1?",":"")}),"")}function V(t){return l(t=t.data)?t.name||"":this.showInternalName(t)?t.name:""}var F=Object.freeze({__proto__:null,shiftTip:function(t){return this.radial()?[("end"==t.text_align?-1:1)*(this.radius_pad_for_bubbles-t.radius),0]:(this.options["right-to-left"],[this.right_most_leaf-t.screen_x,0])},drawNode:function(t,e,n){t=a.select(t);var s=l(e);s&&(t=t.attr("data-node-name",e.data.name));var i=t.selectAll("text").data([e]),r=t.selectAll("line");if(s||this.showInternalName(e)&&!D(e))if(i=i.enter().append("text").classed(this.css_classes.node_text,!0).merge(i).on("click",(t=>{this.handle_node_click(e,t)})).attr("dy",(t=>.33*this.shown_font_size)).text((t=>this.options["show-labels"]?this._nodeLabel(t):"")).style("font-size",(t=>this.ensure_size_is_in_px(this.shown_font_size))),i=this.radial()?i.attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle)+this.d3PhylotreeSvgTranslate(this.alignTips()?this.shiftTip(t):null))).attr("text-anchor",(t=>t.text_align)):i.attr("text-anchor","start").attr("transform",(t=>"right-to-left"==this.options.layout?this.d3PhylotreeSvgTranslate([-20,0]):this.d3PhylotreeSvgTranslate(this.alignTips()?this.shiftTip(t):null))),this.alignTips()?(r=r.data([e]),n?r=r.enter().append("line").classed(this.css_classes["branch-tracer"],!0).merge(r).attr("x1",(t=>("end"==t.text_align?-1:1)*this.nodeBubbleSize(e))).attr("x2",0).attr("y1",0).attr("y2",0).attr("x2",(t=>"right-to-left"==this.options.layout?t.screen_x:this.shiftTip(t)[0])).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle))).attr("x2",(t=>"right-to-left"==this.options.layout?t.screen_x:this.shiftTip(t)[0])).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle))):(r=r.enter().append("line").classed(this.css_classes["branch-tracer"],!0).merge(r).attr("x1",(t=>("end"==t.text_align?-1:1)*this.nodeBubbleSize(e))).attr("y2",0).attr("y1",0).attr("x2",(t=>this.shiftTip(t)[0]))).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle)))):r.remove(),this.options["draw-size-bubbles"]){var o=this.nodeBubbleSize(e);t.selectAll("circle").data([o]).enter().append("circle").attr("r",(function(t){return t})),this.shown_font_size>=5&&(i=i.attr("dx",(t=>("end"==t.text_align?-1:1)*((this.alignTips()?0:o)+.33*this.shown_font_size))))}else this.shown_font_size>=5&&(i=i.attr("dx",(t=>("end"==t.text_align?-1:1)*this.shown_font_size*.33)));if(!s){let n=t.selectAll("circle").data([e]).enter().append("circle"),s=this.node_circle_size()(e);s>0?n.merge(n).attr("r",(t=>Math.min(.75*this.shown_font_size,s))).on("click",(t=>{this.handle_node_click(e,t)})):n.remove()}return this.node_styler&&this.node_styler(t,e),e},updateHasHiddenNodes:function(){let t=this.phylotree.nodes.descendants();for(let e=t.length-1;e>=0;e-=1)l(t[e])?t[e].hasHiddenNodes=t[e].notshown:t[e].hasHiddenNodes=t[e].children.reduce((function(t,e){return e.notshown||t}),!1);return this},showInternalName:function(t){const e=this.internalNames();return!!e&&("function"==typeof e?e(t):e)},nodeSpan:function(t){return arguments.length?(this.nodeSpan="string"==typeof t&&"equal"==t?function(t){return 1}:t,this):this.nodeSpan},reclassNode:function(t){let e=j[l(t)?"node":"internal-node"];return C(t)&&(e+=" "+j["tagged-node"]),O(t,this.selection_attribute_name)&&(e+=" "+j["selected-node"]),t.parent||(e+=" "+j["root-node"]),(D(t)||I(t))&&(e+=" "+j["collapsed-node"]),e},nodeVisible:U,nodeNotshown:B,hasHiddenNodes:I,isNodeCollapsed:D,nodeCssSelectors:q,internalLabel:function(t,e){this.phylotree.clearInternalNodes(e);for(var n=this.phylotree.nodes.descendants().length-1;n>=0;n--){var s=this.phylotree.nodes.descendants()[n];l(s)||O(s,this.selection_attribute_name)||(s[this.selection_attribute_name]=t(s.children))}this.modifySelection(((t,e)=>(l(t.target),t.target[this.selection_attribute_name])))},defNodeLabel:V,nodeLabel:function(t){return arguments.length?(this._nodeLabel=t||V,this.update(),this):this._nodeLabel}});function X(t){return[t.clade].reduce((function(t,e,n,s){return t+"path."+e+(n<s.length-1?",":"")}),"")}var G=Object.freeze({__proto__:null,cladeCssSelectors:X,updateCollapsedClades:function(t){let e=this.svg.selectAll("."+this.css_classes["tree-container"]);var n=0;let s=e.selectAll(X(this.css_classes)).data(this.phylotree.nodes.descendants().filter(D),(function(t){return t.id||(t.id=++n)})),i=function(){},o=r.noop();this.radial()?(i=a.line().curve(a.curveBasis).y((function(t){return t[0]})).x((function(t){return t[1]})),o=function(t,e,n,s,i){return e?[n.screen_y+(t[0]-s)/50,n.screen_x+(t[1]-i)/50]:[n.screen_y,n.screen_x]}):(i=a.line().y((function(t){return t[0]})).x((function(t){return t[1]})).curve(a.curveBasis),o=function(t,e,n,s,i){return e?[n.screen_y+(t[0]-s)/50,n.screen_x+(t[1]-i)/50]:[n.screen_y,n.screen_x]}),s.exit().each((function(t){t.collapsed_clade=null})).remove(),t?s.enter().insert("path",":first-child").attr("class",this.css_classes.clade).merge(s).attr("d",(function(t){if(t.collapsed_clade)return t.collapsed_clade;let e=t.collapsed[0][0],n=t.collapsed[0][1];return i(t.collapsed.map((function(s,i){return o(s,i,t,e,n)})))})).attr("d",(function(t){return t.collapsed_clade=i(t.collapsed)})):s.enter().insert("path",":first-child").attr("class",this.css_classes.clade).merge(s).attr("d",(function(t){return t.collapsed_clade?t.collapsed_clade:t.collapsed_clade=i(t.collapsed)}))}});function W(t){return!(t.target.hidden||t.target.notshown)}function $(t){return[t.branch,t["selected-branch"],t["tagged-branch"]].reduce((function(t,e,n,s){return t+"path."+e+(n<s.length-1?",":"")}),"")}var Y=Object.freeze({__proto__:null,drawEdge:function(t,e,n){t=(t=a.select(t)).attr("class",(t=>this.reclassEdge(t))).on("click",(t=>{this.modifySelection([e.target],this.selection_attribute_name),this.update()}));let s=this.draw_branch([e.source,e.target]);n?(t.datum().existing_path&&(t=t.attr("d",(function(t){return t.existing_path}))),t=t.attr("d",s)):t=t.attr("d",s),e.existing_path=s;var i=this.phylotree.branch_length_accessor(e.target);if(void 0!==i){var r=t.selectAll("title");r.empty()&&(r=t.append("title")),r.text("Length = "+i)}else t.selectAll("title").remove();return this.edge_styler&&this.edge_styler(t,e,n),this.phylotree},reclassEdge:function(t){let e=j.branch;return C(t)&&(e+=" "+j["tagged-branch"]),O(t,this.selection_attribute_name)&&(e+=" "+j["selected-branch"]),e},initializeEdgeLabels:function(){this.links.forEach((t=>{t.target.data.annotation&&(t.target[t.target.data.annotation]=t.target.data.annotation)}))},syncEdgeLabels:function(){if(this.links.forEach((t=>{t[this.selection_attribute_name]=t.target[this.selection_attribute_name]||!1,t.tag=t.target.tag||!1})),this.countHandler()){let t={};t[this.selection_attribute_name]=this.links.reduce(((t,e)=>t+(e[this.selection_attribute_name]?1:0)),0),t.tagged=this.links.reduce((function(t,e){return t+(C(e)?1:0)}),0),this.countUpdate(this,t,this.countHandler())}},edgeVisible:W,edgeCssSelectors:$,placeAlongAnEdge:function(t,e){return this.edge_placer(t,e)}});let J="phylotree.event";function K(t){var e=new CustomEvent(J,{detail:["refresh",t]});document.dispatchEvent(e)}function Z(t,e){var n=new CustomEvent(J,{detail:["countUpdate",e,t.countHandler()]});document.dispatchEvent(n)}function Q(t){switch(t.detail[0]){case"refresh":t.detail[1].refresh();break;case"countUpdate":t.detail[2](t.detail[1]);break;case"layout":t.detail[2](t.detail[1])}return!0}function tt(){document.addEventListener(J,Q,!1)}var et=Object.freeze({__proto__:null,toggleCollapse:function(t){if(t.collapsed){t.collapsed=!1;let e=function(t){l(t)||t.collapsed||t.children.forEach(e),t.hidden=!1};e(t)}else t.collapsed=!0;return this.placenodes(),this},resizeSvg:function(t,e,n){let s=this.size;if(this.radial()){let t=this.pad_width(),n="fit-to-size"!=this.options["top-bottom-spacing"]?this.pad_height():0;s=[s[1]+2*t,s[0]+2*t+n],e&&e.selectAll("."+j["tree-container"]).attr("transform","translate ("+t+","+(t+n)+")")}else s=[s[0]+("fit-to-size"!=this.options["top-bottom-spacing"]?this.pad_height():0),s[1]+("fit-to-size"!=this.options["left-right-spacing"]?this.pad_width():0)];return e&&(n&&(e=e.transition(100)),e.attr("height",s[0]).attr("width",s[1])),this.size=s,s},rescale:function(t,e){(e=e||"y_scaled")in this&&(this[e]*=t)},triggerRefresh:K,countUpdate:Z,d3PhylotreeTriggerLayout:function(t){var e=new CustomEvent(J,{detail:["layout",t,t.layoutHandler()]});document.dispatchEvent(e)},d3PhylotreeEventListener:Q,d3PhylotreeAddEventListener:tt,d3PhylotreeSvgTranslate:function(t){return!t||null===t[0]&&null===t[1]?"":"translate ("+(null!==t[0]?t[0]:0)+","+(null!==t[1]?t[1]:0)+") "},d3PhylotreeSvgRotate:function(t){return null!==t?"rotate ("+t+") ":""}});let nt="d3_layout_phylotree_context_menu";var st=Object.freeze({__proto__:null,nodeDropdownMenu:function(t,e,n,s,i){let o=a.select(e).select("#d3_layout_phylotree_context_menu");if(o.empty()&&(o=a.select(e).append("div").attr("id",nt).attr("class","dropdown-menu").attr("role","menu")),o.selectAll("a").remove(),o.selectAll("h6").remove(),o.selectAll("div").remove(),t){if(!r.some([Boolean(t.menu_items),s.hide,s.selectable,s.collapsible])||!s["show-menu"])return;l(t)||(s.collapsible&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text(D(t)?"Expand Subtree":"Collapse Subtree").on("click",(e=>{o.style("display","none"),this.toggleCollapse(t).update()})),s.selectable&&(o.append("div").attr("class","dropdown-divider"),o.append("h6").attr("class","dropdown-header").text("Toggle selection"))),s.selectable&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All descendant branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!0))})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All terminal branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!1))})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All internal branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!1,!0))})))),t.parent&&(s.selectable&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Incident branch").on("click",(function(e){o.style("display","none"),n.modifySelection([t])})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Path to root").on("click",(e=>{o.style("display","none"),this.modifySelection(this.phylotree.pathToRoot(t))})),(s.reroot||s.hide)&&o.append("div").attr("class","dropdown-divider")),s.reroot&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Reroot on this node").on("click",(e=>{o.style("display","none"),this.phylotree.reroot(t),this.update()})),s.hide&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Hide this "+(l(t)?"node":"subtree")).on("click",(e=>{o.style("display","none"),this.modifySelection([t],"notshown",!0,!0).updateHasHiddenNodes().update()}))),I(t)&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Show all descendant nodes").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!0),"notshown",!0,!0,"false").updateHasHiddenNodes().update()}));var h=[];if("menu_items"in t&&"object"==typeof t.menu_items&&t.menu_items.forEach((function(e){3==e.length&&(e[2]&&!e[2](t)||h.push([e[0],e[1]]))})),h.length){const e=[s.hide,s.selectable,s.collapsible];r.some(e)&&o.append("div").attr("class","dropdown-divider"),h.forEach((function(e){o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text(constant(e[0])(t)).on("click",r.partial(e[1],t))}))}let a=document.querySelector(e).getBoundingClientRect();o.style("position","absolute").style("left",i.clientX-a.x+12+"px").style("top",i.clientY-a.y+"px").style("display","block")}else o.style("display","none")},addCustomMenu:function(t,e,n,s){"menu_items"in t||(t.menu_items=[]),t.menu_items.some((function(t){return t[0]==e&&t[1]==n&&t[2]==s}))||t.menu_items.push([e,n,s])},modifySelection:function(t,e,n,s,i){if(e=e||this.selection_attribute_name,i=i||"toggle",this.options["restricted-selectable"].length){if(!r.contains(r.keys(R),t))return;t=R[t]}if(!this.options["restricted-selectable"]&&!this.options.selectable||this.options["binary-selectable"])this.options["binary-selectable"]&&("function"==typeof t?this.links.forEach((function(n){var s=t(n);n[e]=n[e]||!1,n[e]!=s&&(n[e]=s,o=!0,n.target[e]=s),this.options["attribute-list"].forEach((function(t){t!=e&&!0===n[e]&&(n[t]=!1,n.target[t]=!1)}))})):(t.forEach((function(t){var n;n=!t[e],t[e]!=n&&(t[e]=n,o=!0)})),this.links.forEach((function(t){t[e]=t.target[e],this.options["attribute-list"].forEach((function(n){n!=e&&!0!==t[e]&&(t[n]=!1,t.target[n]=!1)}))}))),o&&(s||K(this),this.countHandler()&&((a={})[e]=this.links.reduce((function(t,n){return t+(n[e]?1:0)}),0),this.countUpdate(this,a,this.countHandler())),n&&this.placenodes()));else{var a,o=!1;"function"==typeof t?this.links.forEach((function(n){let s=t(n);n[e]=n[e]||!1,n[e]!=s&&(n[e]=s,o=!0,n.target[e]=s)})):(t.forEach((function(t){var n;switch(i){case"true":n=!0;break;case"false":n=!1;break;default:n=!t[e]}t[e]!=n&&(t[e]=n,o=!0)})),this.links.forEach((function(t){t[e]=t.target[e]}))),o&&(s||K(this),this.countHandler&&((a={})[e]=this.links.reduce((function(t,n){return t+(n[e]?1:0)}),0),Z(this,a,this.countHandler)),n&&this.placenodes())}return this.selectionCallback&&"tag"!=e&&this.selectionCallback(this.getSelection()),this.refresh(),this.update(),this},getSelection:function(){return this.nodes.filter((t=>t[this.selection_attribute_name]))},selectAllDescendants:function(t,e,n){let s=[];return function i(a){l(a)?e&&a!=t&&s.push(a):(n&&a!=t&&s.push(a),a.children.forEach(i))}(t),s},selectionCallback:function(t){return t?(this.selectionCallback=t,this):this.selectionCallback}});function it(t){return function(){return t}}class at{constructor(t,e={}){this.css_classes=j,this.phylotree=t,this.container=e.container,this.separation=function(t,e){return 0},this._nodeLabel=this.defNodeLabel,this.svg=null,this.selectionCallback=null,this.scales=[1,1],this.size=[1,1],this.fixed_width=[14,30],this.font_size=12,this.scale_bar_font_size=12,this.offsets=[0,this.font_size/2],this.draw_branch=A,this.draw_scale_bar=null,this.edge_placer=T,this.count_listener_handler=function(){},this.layout_listener_handler=function(){},this.node_styler=void 0,this.edge_styler=void 0,this.shown_font_size=this.font_size,this.selection_attribute_name="selected",this.right_most_leaf=0,this.label_width=0,this.radial_center=0,this.radius=1,this.radius_pad_for_bubbles=0,this.rescale_nodeSpan=1,this.relative_nodeSpan=function(t){return this.nodeSpan(t)/this.rescale_nodeSpan};let n={layout:"left-to-right",logger:console,branches:"step",scaling:!0,bootstrap:!1,"color-fill":!0,"internal-names":!1,selectable:!0,"restricted-selectable":!1,collapsible:!0,"left-right-spacing":"fixed-step","top-bottom-spacing":"fixed-step","left-offset":0,"show-scale":"top","draw-size-bubbles":!1,"bubble-styler":this.radius_pad_for_bubbles,"binary-selectable":!1,"is-radial":!1,"attribute-list":[],"max-radius":768,"annular-limit":.38196601125010515,compression:.2,"align-tips":!1,"maximum-per-node-spacing":100,"minimum-per-node-spacing":2,"maximum-per-level-spacing":100,"minimum-per-level-spacing":10,node_circle_size:it(3),transitions:null,brush:!0,reroot:!0,hide:!0,"label-nodes-with-name":!1,zoom:!1,"show-menu":!0,"show-labels":!0,"node-styler":null,"edge-styler":null,"node-span":null};this.ensure_size_is_in_px=function(t){return"number"==typeof t?t+"px":t},this.options=r.defaults(e,n),this.width=this.options.width||800,this.height=this.options.height||600,this.node_styler=this.options["node-styler"],this.edge_styler=this.options["edge-styler"],this.nodeSpan=this.options["node-span"],this.nodeSpan||(this.nodeSpan=function(t){return 1}),this.rescale_nodeSpan=this.phylotree.nodes.children.map((t=>{if(l(t)||this.showInternalName(t))return this.nodeSpan(t)})).reduce((function(t,e){return Math.min(e,t||1e200)}),null)||1,this.initialize_svg(this.container),this.links=this.phylotree.nodes.links(),this.initializeEdgeLabels(),this.update(),tt()}pad_height(){return this.draw_scale_bar?this.scale_bar_font_size+25:0}pad_width(){this.label_width=this._label_width(this.shown_font_size);const t=this.options["show-labels"]?this.label_width:0;return this.offsets[1]+this.options["left-offset"]+t}collapse_node(t){D(t)||(t.collapsed=!0)}set_size(t){if(!arguments.length)return this.size;let e=t;return"fixed-step"!=this.options["top-bottom-spacing"]&&(this.size[0]=e[0]),"fixed-step"!=this.options["left-right-spacing"]&&(this.size[1]=e[1]),this}initialize_svg(t){return this.svg!==t&&(a.select(t).select("svg").remove(),this.svg=a.create("svg").attr("width",this.width).attr("height",this.height),this.set_size([this.height,this.width]),"phylotree-container"==this.css_classes["tree-container"]&&(this.svg.selectAll("*").remove(),this.svg.append("defs")),a.select(this.container).on("click",(t=>{this.handle_node_click(null)}),!0)),this}update_layout(t,e){e&&(this.nodes=a.hierarchy(t),this.nodes.each((function(t){t.id=null}))),this.update(),this.syncEdgeLabels()}update(t){var e=this;this.placenodes(),t=this.transitions(t);let n=0,s=this.svg.selectAll("."+j["tree-container"]).data([0]);if(s=s.enter().append("g").attr("class",j["tree-container"]).merge(s).attr("transform",(t=>this.d3PhylotreeSvgTranslate([this.offsets[1]+this.options["left-offset"],this.pad_height()]))),this.draw_scale_bar){let t=this.svg.selectAll("."+j["tree-scale-bar"]).data([0]);t.enter().append("g").attr("class",j["tree-scale-bar"]).style("font-size",this.ensure_size_is_in_px(this.scale_bar_font_size)).merge(t).attr("transform",(t=>this.d3PhylotreeSvgTranslate([this.offsets[1]+this.options["left-offset"],this.pad_height()-10]))).call(this.draw_scale_bar),t.selectAll("text").style("text-anchor","end")}else this.svg.selectAll("."+j["tree-scale-bar"]).remove();s=this.svg.selectAll("."+j["tree-container"]).data([0]),this.updateCollapsedClades(t);let i=s.selectAll($(j)).data(this.links.filter(W),(t=>t.target.id||(t.target.id=++n)));i.exit().remove(),i=i.enter().insert("path",":first-child").merge(i).each((function(n){e.drawEdge(this,n,t)}));let o=s.selectAll(q(j)).data(this.phylotree.nodes.descendants().filter(U),(t=>t.id||(t.id=++n)));if(o.exit().remove(),o=o.enter().append("g").attr("class",this.reclassNode).merge(o).attr("transform",(t=>{const e="right-to-left"==this.options.layout&&l(t);return t.screen_x=z(t),t.screen_y=k(t),this.d3PhylotreeSvgTranslate([e?0:t.screen_x,t.screen_y])})).each((function(n){e.drawNode(this,n,t)})).attr("transform",(t=>{if(!r.isUndefined(t.screen_x)&&!r.isUndefined(t.screen_y))return"translate("+t.screen_x+","+t.screen_y+")"})),this.options["label-nodes-with-name"]&&(o=o.attr("id",(t=>"node-"+t.name))),this.resizeSvg(this.phylotree,this.svg,t),this.options.brush){var h=s.selectAll("."+j["tree-selection-brush"]).data([0]).enter().insert("g",":first-child").attr("class",j["tree-selection-brush"]),d=a.brush().on("brush",((t,e)=>{var n=t.selection,s=this.links.filter(W).filter(((t,e)=>t.source.screen_x>=n[0][0]&&t.source.screen_x<=n[1][0]&&t.source.screen_y>=n[0][1]&&t.source.screen_y<=n[1][1]&&t.target.screen_x>=n[0][0]&&t.target.screen_x<=n[1][0]&&t.target.screen_y>=n[0][1]&&t.target.screen_y<=n[1][1])).map((t=>t.target));this.modifySelection(this.phylotree.links.map((t=>t.target)),"tag",!1,s.length>0,"false"),this.modifySelection(s,"tag",!1,!1,"true")})).on("end",(()=>{}));h.call(d)}if(this.syncEdgeLabels(),this.options.zoom){let t=a.zoom().scaleExtent([.1,10]).on("zoom",(t=>{a.select("."+j["tree-container"]).attr("transform",(e=>t.transform)),a.select("."+j["tree-scale-bar"]).attr("transform",(e=>{let n=t.transform;return n.y-=10,n}))}));this.svg.call(t)}return this}_handle_single_node_layout(t){let e=this.nodeSpan(t)/this.rescale_nodeSpan;this.x=t.x=this.x+this.separation(this.last_node,t)+.5*(this.last_span+e),this._extents[1][1]=Math.max(this._extents[1][1],t.y),this._extents[1][0]=Math.min(this._extents[1][0],t.y-.5*e),this.is_under_collapsed_parent?this._extents[0][1]=Math.max(this._extents[0][1],this.save_x+(t.x-this.save_x)*this.options.compression+this.save_span+(.5*e+this.separation(this.last_node,t))*this.options.compression):this._extents[0][1]=Math.max(this._extents[0][1],this.x+.5*e+this.separation(this.last_node,t)),this.last_node=t,this.last_span=e}tree_layout(t){if(B(t))return;let e=l(t);t.text_angle=null,t.text_align=null,t.radius=null,t.angle=null;let n=!1;if(t.parent)if(this.do_scaling){if(n)return 0;if(t.y=this.phylotree.branch_length_accessor(t),void 0===t.y)return n=!0,0;t.y+=t.parent.y}else t.y=e?this.max_depth:t.depth;else this.x=0,t.y=0,this.last_node=null,this.last_span=0,this._extents=[[0,0],[0,0]];if(e&&this._handle_single_node_layout(t),!e)if(D(t)&&!this.is_under_collapsed_parent){if(this.save_x=this.x,this.save_span=.5*this.last_span,this.is_under_collapsed_parent=!0,this.process_internal_node(t),this.is_under_collapsed_parent=!1,"number"==typeof t.x){t.x=this.save_x+(t.x-this.save_x)*this.options.compression+this.save_span,t.collapsed=[[t.x,t.y]];var s=e=>{e.hidden=!0,l(e)?(this.x=e.x=this.save_x+(e.x-this.save_x)*this.options.compression+this.save_span,t.collapsed.push([e.x,e.y])):e.children.map(s)};this.x=this.save_x,s(t),t.collapsed.splice(1,0,[this.save_x,t.y]),t.collapsed.push([this.x,t.y]),t.collapsed.push([t.x,t.y]),t.hidden=!1}}else this.process_internal_node(t);return t.x}process_internal_node(t){let e=0;if(this.showInternalName(t)){let e=t.children.length/2>>0,n=0,s=!1;for(let i=0;i<t.children.length;i++){"number"==typeof this.tree_layout(t.children[i])&&n++,n>=e&&!s&&(this._handle_single_node_layout(t),s=!0)}0==n?(t.notshown=!0,t.x=void 0):s||this._handle_single_node_layout(t)}else t.x=t.children.map(this.tree_layout.bind(this)).reduce(((t,n)=>"number"==typeof n?t+n:(e+=1,t)),0),e==t.children.length?(t.notshown=!0,t.x=void 0):t.x/=t.children.length-e}do_lr(t){if(this.radial()&&t&&(this.offsets[1]=0),"fixed-step"==this.options["left-right-spacing"])this.size[1]=this.max_depth*this.fixed_width[1],this.scales[1]=(this.size[1]-this.offsets[1]-this.options["left-offset"])/this._extents[1][1],this.label_width=this._label_width(this.shown_font_size),this.radial()&&(this.label_width*=2);else{this.label_width=this._label_width(this.shown_font_size),t=!0;let e=this.size[1]-this.offsets[1]-this.options["left-offset"];.5*e<this.label_width&&(this.shown_font_size*=.5*e/this.label_width,this.label_width=.5*e),this.scales[1]=(this.size[1]-this.offsets[1]-this.options["left-offset"]-this.label_width)/this._extents[1][1]}}placenodes(){this._extents=[[0,0],[0,0]],this.x=0,this.last_span=0,this.last_node=null,this.last_span=0,this.save_x=this.x,this.save_span=.5*this.last_span,this.do_scaling=this.options.scaling;this.is_under_collapsed_parent=!1,this.max_depth=1,this.phylotree.nodes.x=this.tree_layout(this.phylotree.nodes,this.do_scaling),this.max_depth=a.max(this.phylotree.nodes.descendants(),(t=>t.depth)),this.do_scaling;let t=!1;if(this.draw_scale_bar=this.options["show-scale"]&&this.do_scaling,this.offsets[1]=Math.max(this.font_size,-this._extents[1][0]*this.fixed_width[0]),"fixed-step"==this.options["top-bottom-spacing"]?(this.size[0]=this._extents[0][1]*this.fixed_width[0],this.scales[0]=this.fixed_width[0]):(this.scales[0]=(this.size[0]-this.pad_height())/this._extents[0][1],t=!0),this.shown_font_size=Math.min(this.font_size,this.scales[0]),this.radial()){this.draw_branch=r.partial(M,this.radial_center),this.edge_placer=L;let e=null,n=null,s=null,i=0,a=this._extents[0][1]*this.scales[0],o=function(t,e,n,s,i){return i=i||0,Math.sqrt((e-t)*(e-t)+2*(t+i)*(e+i)*(1-Math.cos(n-s)))},l=0;this.phylotree.nodes.each((t=>{let e=t.x*this.scales[0];t.angle=2*Math.PI*e/a,t.text_angle=t.angle-Math.PI/2,t.text_angle=t.text_angle>0&&t.text_angle<Math.PI,t.text_align=t.text_angle?"end":"start",t.text_angle=(t.text_angle?180:0)+180*t.angle/Math.PI})),this.do_lr(t),this.phylotree.nodes.each((t=>{t.radius=t.y*this.scales[1]/this.size[1],l=Math.max(t.radius,l)}));let h=0;this.phylotree.nodes.each((t=>{if(!t.children){let a=t.x*this.scales[0];if(null!==e){let r=a-n,d=o(t.radius,s,t.angle,e,h),c=d>0?r/d:10*this.options["max-radius"];if(c>this.options["max-radius"]){let n=r/this.options["max-radius"],a=t.radius+s,o=t.radius*s-(n*n-(s-t.radius)*(s-t.radius))/2/(1-Math.cos(e-t.angle)),d=Math.sqrt(a*a-4*o);h=Math.min(this.options["annular-limit"]*l,(-a+d)/2),i=this.options["max-radius"]}else i=Math.max(i,c)}e=t.angle,n=a,s=t.radius}})),this.radius=Math.min(this.options["max-radius"],Math.max(a/2/Math.PI,i)),t&&(this.radius=Math.min(this.radius,.5*(Math.min(a,this._extents[1][1]*this.scales[1])-this.label_width)-this.radius*h)),this.radial_center=this.radius_pad_for_bubbles=this.radius,this.draw_branch=r.partial(M,this.radial_center);let d=1;h&&(d=l/(l+h),this.radius*=d),this.phylotree.nodes.each((t=>{if(S(t,this.radius,h,this.radial_center,this.scales,this.size),l=Math.max(l,t.radius),this.options["draw-size-bubbles"]?this.radius_pad_for_bubbles=Math.max(this.radius_pad_for_bubbles,t.radius+this.nodeBubbleSize(t)):this.radius_pad_for_bubbles=Math.max(this.radius_pad_for_bubbles,t.radius),t.collapsed){t.collapsed=t.collapsed.map((t=>{let e={};return e.x=t[0],e.y=t[1],e=S(e,this.radius,h,this.radial_center,this.scales,this.size),[e.x,e.y]}));let e=t.collapsed[1];t.collapsed=t.collapsed.filter((function(n,s){return s<3||s>t.collapsed.length-4||Math.sqrt(Math.pow(n[0]-e[0],2)+Math.pow(n[1]-e[1],2))>3&&(e=n,!0)}))}})),this.size[0]=this.radial_center+this.radius/d,this.size[1]=this.radial_center+this.radius/d}else this.do_lr(),this.draw_branch=A,this.edge_placer=T,this.right_most_leaf=0,this.phylotree.nodes.each((t=>{if(t.x*=this.scales[0],t.y*=.8*this.scales[1],"right-to-left"==this.options.layout&&(t.y=this._extents[1][1]*this.scales[1]-t.y),l(t)&&(this.right_most_leaf=Math.max(this.right_most_leaf,t.y+this.nodeBubbleSize(t))),t.collapsed){t.collapsed.forEach((t=>{t[0]*=this.scales[0],t[1]*=.8*this.scales[1]}));let e=t.collapsed[1][0];t.collapsed=t.collapsed.filter((function(n,s){return s<3||s>t.collapsed.length-4||n[0]-e>3&&(e=n[0],!0)}))}}));if(this.draw_scale_bar){let t,e;if(this.radial()){if(e=Math.min(this.radius/5,50),t=Math.pow(10,Math.ceil(Math.log(this._extents[1][1]*e/this.radius)/Math.log(10))),e=t*(this.radius/this._extents[1][1]),e<30){let n=Math.ceil(30/e);e*=n,t*=n}}else t=this._extents[1][1],e=this.size[1]-this.offsets[1]-this.options["left-offset"]-this.shown_font_size;let n=a.scaleLinear().domain([0,t]).range([0,e]),s=a.format(".2f");if(this.draw_scale_bar=a.axisTop().scale(n).tickFormat((function(t){return 0===t?"":s(t)})),this.radial())this.draw_scale_bar.tickValues([t]);else{let t=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)},i=n.ticks();i=i.length>1?i[1]:i[0],this.draw_scale_bar.ticks(Math.min(10,t(e/(this.shown_font_size*s(i).length*2),0)))}}else this.draw_scale_bar=null;return this}spacing_x(t,e){return arguments.length?(this.fixed_width[0]!=t&&t>=this.options["minimum-per-node-spacing"]&&t<=this.options["maximum-per-node-spacing"]&&(this.fixed_width[0]=t,e||this.placenodes()),this):this.fixed_width[0]}spacing_y(t,e){return arguments.length?(this.fixed_width[1]!=t&&t>=this.options["minimum-per-level-spacing"]&&t<=this.options["maximum-per-level-spacing"]&&(this.fixed_width[1]=t,e||this.placenodes()),this):this.fixed_width[1]}_label_width(t){t=t||this.shown_font_size;let e=0;return this.phylotree.nodes.descendants().filter(U).forEach((n=>{let s=12+this._nodeLabel(n).length*t*.8;null!==n.angle&&(s*=Math.max(Math.abs(Math.cos(n.angle)),Math.abs(Math.sin(n.angle)))),e=Math.max(s,e)})),e}font_size(t){return arguments.length?(this.font_size=void 0===t?12:t,this):this.font_size}scale_bar_font_size(t){return arguments.length?(this.scale_bar_font_size=void 0===t?12:t,this):this.scale_bar_font_size}node_circle_size(t,e){return arguments.length?(this.options.node_circle_size=it(void 0===t?3:t),this):this.options.node_circle_size}css(t){if(0===arguments.length)return this.css_classes;if(arguments.length>2){var e={};return e[t[0]]=t[1],this.css(e)}for(var n in j)n in t&&t[n]!=j[n]&&(j[n]=t[n]);return this}transitions(t){return void 0!==t?t:null!==this.options.transitions?this.options.transitions:this.phylotree.nodes.descendants().length<=300}css_classes(t,e){if(!arguments.length)return this.css_classes;let n=!1;for(var s in j)s in t&&t[s]!=this.css_classes[s]&&(n=!0,this.css_classes[s]=t[s]);return e&&n&&this.layout(),this}layout(t){return this.svg?(this.svg.selectAll("."+this.css_classes["tree-container"]+",."+this.css_classes["tree-scale-bar"]+",."+this.css_classes["tree-selection-brush"]),this.d3PhylotreeTriggerLayout(this),this.update()):(this.d3PhylotreeTriggerLayout(this),this)}handle_node_click(t,e){this.nodeDropdownMenu(t,this.container,this,this.options,e)}refresh(){if(this.svg){let t=this.svg.selectAll("."+this.css_classes["tree-container"]).selectAll($(this.css_classes)).attr("class",this.reclassEdge.bind(this));this.edge_styler&&t.each((t=>{this.edge_styler(a.select(this),t)}))}return this}countHandler(t){return arguments.length?(this.count_listener_handler=t,this):this.count_listener_handler}style_nodes(t){return arguments.length?(this.node_styler=t,this):this.node_styler}style_edges(t){return arguments.length?(this.edge_styler=t.bind(this),this):this.edge_styler}itemSelected(t,e){return t[e]||!1}show(){return this.svg.node()}}r.extend(at.prototype,G),r.extend(at.prototype,F),r.extend(at.prototype,Y),r.extend(at.prototype,et),r.extend(at.prototype,st),r.extend(at.prototype,H);let rt=class{constructor(t,e={}){this.newick_string="",this.nodes=[],this.links=[],this.parsed_tags=[],this.partitions=[],this.branch_length_accessor=w,this.branch_length=w,this.logger=e.logger||console,this.selection_attribute_name="selected";var n=e.type||void 0,s=[],i=this;if(r.isString(n))n in m?s=m[n](t,e):i.logger.error("type "+n+" not in registry! Available types are "+r.keys(m));else if(r.isFunction(n))try{s=n(t,e)}catch(t){i.logger.error("Could not parse custom format!")}else"root"==t.name?s={json:t,error:null}:"string"!=typeof t?s=t:"application/xml"==t.contentType?s=g(t):(this.newick_string=t,s=d(t,e));if(s.json){i.nodes=a.hierarchy(s.json);let t={};i.nodes.each((e=>{e.data.annotation&&(t[e.data.annotation]=!0)})),i.parsed_tags=Object.keys(t)}else i.nodes=[];return i.links=i.nodes.links(),this.hasBranchLengths()||(console.warn("Phylotree User Warning : NO BRANCH LENGTHS DETECTED, SETTING ALL LENGTHS TO 1"),this.setBranchLength((t=>1))),i}json(t){var e=0;this.traverse_and_compute((function(t){t.json_export_index=e++}),t);var n=new Array(e);return e=0,this.traverse_and_compute((function(t){let s=r.clone(t);delete s.json_export_index,t.parent&&(s.parent=t.parent.json_export_index),t.children&&(s.children=r.map(t.children,(function(t){return t.json_export_index}))),n[e++]=s}),t),this.traverse_and_compute((function(t){delete t.json_export_index}),t),JSON.stringify(n)}traverse_and_compute(t,e,n,s){return(e="pre-order"==(e=e||"post-order")?function(e){v(e,t,s)}:"in-order"==e?function(e){y(e,t,s)}:function(e){r.isUndefined(e)||b(e,t,s)})(n||this.nodes),this}get_parsed_tags(){return this.parsed_tags}update(t){this.nodes=t}render(t){return this.display=new at(this,t),this.display}};function ot(t){var e=t.branch_length_accessor;if(!e)throw"A non-null branch lengths accessor function is required for this operation";var n=0;function s(t){for(var e=0;e<t.children.length;e++)for(var n=0;n<t.children.length;n++)e!=n&&r.each(t.children[n].cot_path_to_leaves_below,(function(s,i){t.children[e].cot_path_to_leaves_above&&(t.children[e].cot_path_to_leaves_above[i]=s+t.children[n].cot_computed_length)}))}return t.traverse_and_compute((function(s){if(s.cot_computed_length=e(s),s.parent&&r.isUndefined(s.cot_computed_length))throw"Non-null branch lengths are required for this operation: missing branch length at node "+s.data.name;t.isLeafNode(s)?(s.cot_leaf_index=n++,s.cot_path_to_leaves_below={},s.cot_path_to_leaves_below[s.cot_leaf_index]=0,s.cot_path_to_leaves_above={}):(s.cot_path_to_leaves_below={},s.cot_path_to_leaves_above={})})),t.traverse_and_compute((function(t){t.parent&&r.each(t.cot_path_to_leaves_below,(function(e,n){t.parent.cot_path_to_leaves_below[n]=e+t.cot_computed_length}))})),s(t.getRootNode()),t.traverse_and_compute((function(e){e.parent&&(r.each(e.parent.cot_path_to_leaves_above,(function(t,n){e.cot_path_to_leaves_above[n]=t+e.parent.cot_computed_length})),t.isLeafNode(e)||s(e))}),"pre-order"),n}function lt(t,e,n,s,i){var a=t.branch_length(e),r=!1;if(n||(s=e.data.rootToTip,i=0,r=!0),e.children)for(var o=0;o<e.children.length;o++)e.children[o]!=n?lt(t,e.children[o],e,s,i):r=!0;e.data.rtta=e.data.rootToTip-s+i,r&&(s-=a,i+=a),e.parent&&r&&lt(t,e.parent,e,s,i)}function ht(t){var e=t.reduce((function(t,e){return e[2]+t}),0),n=t.reduce((function(t,e){return e[2]*e[0]+t}),0),s=t.reduce((function(t,e){return e[2]*e[1]+t}),0),i=n/e,a=s/e,r=0,o=0,l=0;t.forEach((function(t){var e=t[0]-i;o+=t[2]*e*e,r+=t[2]*e*t[1],l+=t[2]*(t[1]-a)*(t[1]-a)}));var h=(s-n*(r/=o))/e,d=0;return t.forEach((function(t){var e=t[1]-h-r*t[0];d+=t[2]*e*e})),{intercept:h,slope:r,r2:1-d/l,"var (intercept)":Math.sqrt((1+n*n/(e*o))/e),"var (slope)":Math.sqrt(1/o)}}function dt(t){var e=t.branch_length_accessor,n=0;t.traverse_and_compute((s=>{if(s.parent&&(s.data._computed_length=e(s),!r.isNumber(s.data._computed_length)))throw"rootToTip cannot be run on trees with missing branch lengths";t.isLeafNode(s)&&(s.data.leaf_index=n++),"r2t"in s.data&&delete s.data.r2t})),t.traverse_and_compute((e=>{e.parent&&("r2t"in e.parent.data||(e.parent.data.r2t={}),t.isLeafNode(e)?e.parent.data.r2t[e.data.leaf_index]=e.data._computed_length:(r.each(e.data.r2t,(function(t,n){e.parent.data.r2t[n]=t+e.data._computed_length})),delete e.data.r2t),delete e.data._computed_length)}));var s=t.getRootNode().data.r2t;return t.traverse_and_compute((e=>{t.isLeafNode(e)&&(e.data.rootToTip=s[e.data.leaf_index]||0,delete e.data.leaf_index)})),delete t.getRootNode().data.r2t,t}rt.prototype.isLeafNode=l,rt.prototype.mrca=function(){var t,e;return t=(t=1==arguments.length?arguments[0]:Array.from(arguments)).map((function(t){return"string"==typeof t?t:t.name})),this.traverse_and_compute((function(n){n.children?n.parent?(n.mrca=r.union(...n.descendants().map((t=>t.mrca))),e||n.mrca.length!=t.length||(e=n)):e||(e=n):n.mrca=r.intersection([n.name],t)})),e},rt.prototype.hasBranchLengths=function(){let t=this.branch_length;return!!t&&r.every(this.nodes.descendants(),(function(e){return!e.parent||!r.isUndefined(t(e))}))},rt.prototype.getBranchLengths=function(){let t=this.branch_length;return r.map(this.nodes.descendants(),(e=>t(e)))},rt.prototype.branchName=function(t){return arguments.length?(this.nodeLabel=t,this):this.nodeLabel},rt.prototype.normalizeBranchLengths=function(t){let e=this.branch_length,n=r.map(this.nodes.descendants(),(function(t){return e(t)?e(t):null}));const s=r.max(n),i=r.min(n);return r.each(this.nodes.descendants(),(t=>{let n=e(t);n&&e(t,(n-i)/(s-i))})),this},rt.prototype.scaleBranchLengths=function(t){let e=this.branch_length;return r.each(this.nodes.descendants(),(n=>{let s=e(n);s&&e(n,t(s))})),this},rt.prototype.getNewick=function(t){let e=this;t||(t=t=>"");let n=[];return t=t||"",function s(i){l(i)||(n.push("("),i.children.forEach((function(t,e){e&&n.push(","),s(t)})),n.push(")")),"root"!=i.data.name&&n.push(i.data.name),n.push(t(i));let a=e.branch_length_accessor(i);void 0!==a&&n.push(":"+a)}(this.nodes),n.join("")+";"},rt.prototype.resortChildren=function(t,e,n){return this.nodes.sum((function(t){return t.value})).sort(t),this.display&&(this.display.update_layout(this.nodes),this.display.update()),this},rt.prototype.setBranchLength=function(t){return arguments.length?(this.branch_length_accessor=t||w,this):this.branch_length_accessor},rt.prototype.maxParsimony=function(t,e){const n=r.partial((function(t,e){if(e.mp=[[0,0],[!1,!1]],l(e))e.mp[1][0]=e.mp[1][1]=e[t]||!1,e.mp[0][0]=e.mp[1][0]?1:0,e.mp[0][1]=1-e.mp[0][0];else{e.children.forEach(n);var s=e.children.reduce((function(t,e){return e.mp[0][0]+t}),0),i=e.children.reduce((function(t,e){return e.mp[0][1]+t}),0);e[t]?(e.mp[0][0]=i+1,e.mp[1][0]=!0,e.mp[0][1]=i,e.mp[1][1]=!0):(s<i+1?(e.mp[0][0]=s,e.mp[1][0]=!1):(e.mp[0][0]=i+1,e.mp[1][0]=!0),i<s+1?(e.mp[0][1]=i,e.mp[1][1]=!0):(e.mp[0][1]=s+1,e.mp[1][1]=!1))}}),e);n(this.nodes),this.nodes.each((t=>{t.parent?t.mp=t.mp[1][t.parent.mp?1:0]:t.mp=t.mp[1][t.mp[0][0]<t.mp[0][1]?0:1]})),this.display.modifySelection(((t,n)=>l(t.target)?t.target[e]:t.target.mp))},rt.prototype.getTipLengths=function(){let t=this.getTips(),e=r.map(t,(t=>({name:t.data.name,length:parseFloat(t.data.attribute)})));return e=r.sortBy(e,(t=>-t.length)),e},rt.prototype.leftChildRightSibling=x,r.extend(rt.prototype,h),r.extend(rt.prototype,N),r.extend(rt.prototype,_);const ct=a.timeParse("%Y%m%d"),ut=/([0-9]{4}).?([0-9]{2}).?([0-9]{2})$/g,pt=function(t){if(l(t)&&"name"in t){let e=ut.exec(t.name);if(e)return e[1]+e[2]+e[3]}return null};t.centerOfTree=function(t,e){e=e||2;var n=ot(t),s=Number.MAX_VALUE,i=0,a=null;return 2==e?t.traverse_and_compute((function(t){if(t.parent){var e=0,o=0,l=0,h=0,d=0;r.each(t.cot_path_to_leaves_below,(function(t){e+=t,o+=t*t,d++})),r.each(t.cot_path_to_leaves_above,(function(t){l+=t,h+=t*t}));var c=n-d,u=(l-e+t.cot_computed_length*c)/n;u<0?u=0:u>t.cot_computed_length&&(u=t.cot_computed_length);var p=h+o+2*(l*(t.cot_computed_length-u)+e*u)+d*u*u+(t.cot_computed_length-u)*(t.cot_computed_length-u)*c;p<s&&(a=t,i=u/t.cot_computed_length,s=p),delete t.cot_computed_length,delete t.cot_path_to_leaves_below,delete t.cot_path_to_leaves_above,delete t.cot_leaf_index}})):t.traverse_and_compute((function(t){if(t.parent)for(var n=t.cot_computed_length>0?.05*t.cot_computed_length:.1,o=0;o<t.cot_computed_length;){var l=0;r.each(t.cot_path_to_leaves_below,(function(t){l+=Math.pow(t+o,e)})),r.each(t.cot_path_to_leaves_above,(function(n){l+=Math.pow(n+(t.cot_computed_length-o),e)})),l<s&&(a=t,i=o/t.cot_computed_length,s=l),o+=n}})),{location:a,breakpoint:i,distance:s}},t.clusterPicker=function(t,e,n,s,i){s=s||t.getRootNode(),i=r.isNumber(i)?i:1;let a=t.branch_length;t.traverse_and_compute((function(t){if(t.parent){if(t._computed_length=a(t),!r.isNumber(t._computed_length))throw"clusterPicker cannot be run on trees with missing branch lengths";t.max_path_length=0}})),t.traverse_and_compute((function(t){t.parent&&(t.parent.max_path_length=Math.max(t.parent.max_path_length,t.max_path_length+t._computed_length))}));var o=[];return t.traverse_and_compute(r.noop,"pre-order",s,(function(s){if(!t.isLeafNode(s)){var a=r.isString(s.data.bootstrap_values)?+s.data.bootstrap_values:i;if(a>=e){var l=r.reduce(s.children,(function(t,e){return e.max_path_length+e._computed_length+t}),0);if(l<=n)return o.push({root:s,diameter:l,bootstrap:a}),!0}}return!1})),t.traverse_and_compute((function(t){t.parent&&(delete t._computed_length,delete t.max_path_length)}),"post-order",s),r.each(o,(function(e){e.members=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&e.members.push(n)}),"post-order",e.root)})),o},t.computeMidpoint=function(t){if(!t.hasBranchLengths())throw"Center of tree calculation cannot be performed on trees that do not have fully specified branch lengths";var e=t.branch_length;t.traverse_and_compute((function(n){if(n.parent){var s,i=e(n);t.isLeafNode(n)?(s=n,n.max_path=0,n.max_path_terminus=n):(i+=n.max_path,s=n.max_path_terminus),(!n.parent.max_path||n.parent.max_path<i)&&(n.parent.max_path=i,n.parent.max_path_terminus=s)}}));var n=t.getRootNode(),s=0;if(n.children.forEach((function(t){if(t.max_path_terminus!==n.max_path_terminus){var i=t.max_path+e(t);i>=s&&(s=i)}})),n.max_path>s){s=.5*(s+n.max_path);for(var i=n.max_path_terminus;;){var a=e(i);if(!(a<=s))return{location:i,breakpoint:s/a};s-=a,i=i.parent}}return{location:n,breakpoint:0}},t.extract_dates=function(t,e,n=ct){return e=e||pt,t.traverse_and_compute((function(t){var s=e(t);if(s)try{t.data.date_value=n(s);var i=t.data.date_value.getFullYear(),a=new Date(i,0,1),r=new Date(i+1,0,1);return void(t.data.decimal_date_value=i+(t.data.date_value-a)/(r-a))}catch(t){}t.data.date_value=null,t.data.decimal_date_value=null})),t},t.fitRootToTip=function(t){var e=[],n=0,s=0;!function(t){t.traverse_and_compute((function(e){t.isLeafNode(e)&&(e.data.copy_number=1)}))}(t),dt(t),t.traverse_and_compute((function(n){t.isLeafNode(n)&&!r.isNull(n.data.decimal_date_value)&&e.push([n.data.decimal_date_value,n.data.rtta,n.data.copy_number])}));let i=ht(e);return t.traverse_and_compute((function(a){if(t.isLeafNode(a)&&!r.isNull(a.data.decimal_date_value)){lt(t,a,null,0,0),e=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&!r.isNull(n.data.decimal_date_value)&&e.push([n.data.decimal_date_value,n.data.rtta,n.data.copy_number])}));var o=ht(e),l=o.r2;l>n&&(n=l,s=a,i=o)}})),{root:s,fit:i}},t.inOrder=y,t.leftChildRightSibling=x,t.loadAnnotations=u,t.pairwise_distances=ot,t.parseAnnotations=c,t.phylopart=function(t,e,n,s,i){s=r.isNumber(s)?s:1;var a=ot(t),o=t.getRootNode().children[0],l=Number.MAX_VALUE,h=Number.MAX_VALUE;if(!(n>0&&n<1))throw"Invalid percentile threshold in perform_phylopart";t.traverse_and_compute((function(e){t.isLeafNode(e)&&(e.cot_computed_length<l?(l<h&&(h=l),l=e.cot_computed_length):e.cot_computed_length<h&&(h=e.cot_computed_length))})),l+=h;var d=r.reduce(o.cot_path_to_leaves_below,(function(t,e){return e>t?e:t}),0)+r.reduce(o.cot_path_to_leaves_above,(function(t,e){return e>t?e:t}),0)+o.cot_computed_length-l;r.isUndefined(i)&&(i=Math.min(.001,d/100));var c=1+(d/i>>0);c>500&&(i=d/(c=500));var u=t.getRootNode();u.paths_to_leaves=new Array(a),r.each(u.children,(function(t){r.each(u.cot_path_to_leaves_below,(function(e,n){u.paths_to_leaves[n]=e+t.cot_computed_length}))})),t.traverse_and_compute((function(e){if(!t.isLeafNode(e)){e.histogram=new Array(c);for(var n=0;n<c;n++)e.histogram[n]=0;if(e.parent){var s=0;e.paths_to_leaves=[],r.each(e.cot_path_to_leaves_below,(function(t,n){e.paths_to_leaves[s++]=t}))}}delete e.cot_path_to_leaves_above,delete e.cot_path_to_leaves_below})),t.traverse_and_compute((function(e){if(!t.isLeafNode(e)){for(var n=0;n<e.paths_to_leaves.length;n++)for(var s=n+1;s<e.paths_to_leaves.length;s++){var a=e.paths_to_leaves[n]+e.paths_to_leaves[s];e.histogram[(a-l)/i>>0]++}e.leaf_count=e.paths_to_leaves.length,delete e.paths_to_leaves}}));for(var p=(a-1)*a/2*n,_=0;_<c-1&&p>u.histogram[_];_++)p-=u.histogram[_];var f=l+(_+(u.histogram[_]-p)/u.histogram[_])*i,g=[];return t.traverse_and_compute(r.noop,"pre-order",null,(function(n){if(!t.isLeafNode(n)){var a=r.isString(n.data.bootstrap_values)?+n.data.bootstrap_values:s;if(a>=e){for(var o=n.leaf_count*(n.leaf_count-1)*.25,h=0;h<c-1&&o>n.histogram[h];h++)o-=n.histogram[h];var d=l+(h+(n.histogram[h]-o)/n.histogram[h])*i;if(d<=f)return g.push({root:n,median:d,bootstrap:a}),!0}}return!1})),t.traverse_and_compute((function(e){t.isLeafNode(e)||"histogram"in e&&(delete e.histogram,delete e.leaf_count)})),r.each(g,(function(e){e.members=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&e.members.push(n)}),"post-order",e.root)})),g},t.phylotree=rt,t.postOrder=b,t.preOrder=v,t.rootToTip=dt,t.sackin=function(t){let e=t.getTips(),n=r.map(e,(t=>t.depth));return r.reduce(n,(function(t,e){return t+e}),0)},Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("d3"),require("underscore"),require("lodash")):"function"==typeof define&&define.amd?define(["exports","d3","underscore","lodash"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).phylotree=t.phylotree||{},t.d3,t._,t._$1)}(this,(function(t,e,n,s){"use strict";function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(n){if("default"!==n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})),e.default=t,Object.freeze(e)}var a=i(e),r=i(n),o=i(s);function l(t){return!r.has(t,"children")}var h=Object.freeze({__proto__:null,graftANode:function(t,e,n,s){let i=this.nodes.descendants();if(t.parent){if(i.indexOf(t)>=0){let i=t.parent.children.indexOf(t),a={name:n,parent:t.parent,attribute:s?s[2]:null,original_child_order:t.original_child_order},r={name:e,parent:a,attribute:s?s[1]:null,original_child_order:2};a.children=[t,r],t.parent.children[i]=a,t.parent=a,t.attribute=s?s[0]:null,t.original_child_order=1}}return this},addChild:function(t,e){return t.children?t.children.push(e):t.children=[e],t},createNode:function(t,e){return{data:{name:t,attribute:e?e[1]:null},parent:""}},deleteANode:function(t){let e=this.nodes.descendants();if("number"!=typeof t)return this.deleteANode(e.indexOf(t));if(t>0&&t<e.length){let n=e[t];if(n.parent){let s=n.parent.children.indexOf(n);s>=0&&(e.splice(t,1),n.children&&n.children.forEach((function(t){t.original_child_order=n.parent.children.length,n.parent.children.push(t),t.parent=n.parent})),n.parent.children.length>2?n.parent.children.splice(s,1):n.parent.parent?(n.parent.parent.children[n.parent.parent.children.indexOf(n.parent)]=n.parent.children[1-s],n.parent.children[1-s].parent=n.parent.parent,e.splice(e.indexOf(n.parent),1)):(e.splice(0,1),e.parent=null,delete e.data.attribute,delete e.data.annotation,delete e.data.original_child_order,e.name="root",e.data.name="root"))}}return this},getTips:function(){return r.filter(this.nodes.descendants(),(t=>!r.has(t,"children")))},getInternals:function(){return r.filter(this.nodes.descendants(),(t=>r.has(t,"children")))},getRootNode:function(){return this.nodes},getNodes:function(){return this.nodes},getNodeByName:function(t){return r.filter(this.nodes.descendants(),(e=>e.data.name==t))[0]},assignAttributes:function(t){r.each(this.nodes.descendants(),(function(e){e.data&&e.data.name in t&&(e.annotations=t[e.data.name])}))},isLeafNode:l,updateKeyName:function(t,e){return this.nodes.each((function(n){t in n&&(e&&(n[e]=n[t]),delete n[t])})),this},clearInternalNodes:function(t){t||this.nodes.each((t=>{l(t)||(t[this.selection_attribute_name]=!1,t.data.traits||(t.data.traits={}),t.data.traits[this.selection_attribute_name]=t[this.selection_attribute_name])}))}});function d(t,e={}){const n=/^-?\d+(\.\d+)?$/;let s=e.left_delimiter||"{",i=e.right_delimiter||"}",a=[];function r(){let t=a[a.length-1];"children"in t||(t.children=[]),a.push({name:null}),t.children.push(a[a.length-1]),a[a.length-1].original_child_order=t.children.length}function o(){let t=a.pop();t.name=d,"children"in t?t.bootstrap_values=d:t.name=d,t.attribute=c,"["==s&&u.includes("&&NHX")?u.split(":").slice(1).forEach((e=>{const[s,i]=e.split("=");t[s]=n.test(i)?+i:i})):t.annotation=u,d="",c="",u=""}function l(e){return{json:null,error:"Unexpected '"+t[e]+"' in '"+t.substring(e-20,e+1)+"[ERROR HERE]"+t.substring(e+1,e+20)+"'"}}let h=0,d="",c="",u="",p=null,_={"'":1,'"':1},f={name:"root"};a.push(f);for(var g=/\s/,m=0;m<t.length;m++)try{var b=t[m];switch(h){case 0:"("==b&&(r(),h=1);break;case 1:case 3:if(":"==b)h=3;else if(","==b||")"==b)try{o(),h=1,","==b&&r()}catch(t){return l(m)}else if("("==b){if(d.length>0)return l(m);r()}else{if(b in _){if(1==h&&0===d.length&&0===c.length&&0===u.length){h=2,p=b;continue}return l(m)}if(b==s){if(u.length)return l(m);h=4}else if(3==h)c+=b;else{if(g.test(b))continue;if(";"==b){m=t.length;break}d+=b}}break;case 2:if(b==p){if(m<t.length-1&&t[m+1]==p){m++,d+=p;continue}p=0,h=1;continue}d+=b;break;case 4:if(b==i)h=3;else{if(b==s)return l(m);u+=b}}}catch(t){return l(m)}return 1!=a.length?l(t.length-1):{json:f,error:null}}function c(t){let e=t,n=e.toUpperCase().indexOf("BEGIN DATA;"),s=e.slice(n);if(s.length<2)return"";n=s.toUpperCase().indexOf("END;");let i=s.slice(0,n);s=r.map(i.split(";"),(t=>t.trim()));let a=r.filter(s,(t=>t.toUpperCase().startsWith("DIMENSION")));a=a[0].split(" "),a=r.object(r.map(r.rest(a),(t=>t.split("="))));let o=r.filter(s,(t=>t.toUpperCase().startsWith("FORMAT")));o=o[0].split(" "),o=r.object(r.map(r.rest(o),(t=>t.split("=")))),o.symbols=r.reject(o.symbols.split(""),(t=>'"'==t));let l=r.filter(s,(t=>t.toUpperCase().startsWith("MATRIX")));return l=l[0].split("\n"),l=r.object(r.map(r.rest(l),(t=>r.compact(t.split(" "))))),l=r.mapObject(l,((t,e)=>"?"==t?o.symbols:Array(t))),{dimensions:a,format:o,matrix:l}}function u(t,e,n){r.each(t.getTips(),(t=>{t.data.test=n.matrix[t.data.name]}))}function p(t){let e=t,n=e.toUpperCase().indexOf("BEGIN TREES;"),s=e.slice(n);if(s.length<2)return"";n=s.toUpperCase().indexOf("END;");let i=s.slice(0,n).split("\n");return i=r.filter(i,(t=>t.trim().toUpperCase().startsWith("TREE"))),d(i[0])}var _=Object.freeze({__proto__:null,parseAnnotations:c,loadAnnotations:u,default:p});function f(t){var e={};if(1==t.nodeType){if(t.attributes.length>0){e["@attributes"]={};for(var n=0;n<t.attributes.length;n++){var s=t.attributes.item(n);e["@attributes"][s.nodeName]=s.nodeValue}}}else 3==t.nodeType&&(e=t.nodeValue);if(t.hasChildNodes()&&1===t.childNodes.length&&3===t.childNodes[0].nodeType)e=t.childNodes[0].nodeValue;else if(t.hasChildNodes())for(var i=0;i<t.childNodes.length;i++){var a=t.childNodes.item(i),r=a.nodeName;if(void 0===e[r])e[r]=f(a);else{if(void 0===e[r].push){var o=e[r];e[r]=[],e[r].push(o)}e[r].push(f(a))}}return e}var g=function(t,e){var n;return(n=(t=f(t)).phyloxml.phylogeny.clade).name="root",function t(e,n){e.clade&&(e.clade.forEach(t),e.children=e.clade,delete e.clade),e.annotation=1,e.attribute="0.01",e.branch_length&&(e.attribute=e.branch_length),e.taxonomy&&(e.name=e.taxonomy.scientific_name),e.annotation=""}(n),{json:n,error:null}};var m={nexml:function(t,e){var n;return parseString(t,(function(t,e){n=e["nex:nexml"].trees[0].tree.map((function(t){var e=t.node.map((t=>t.$)),n=e.reduce((function(t,e){return e.edges=[],e.name=e.id,t[e.id]=e,t}),{}),s=e.filter((t=>t.root)),i=s>0?s[0].id:e[0].id;return n[i].name="root",t.edge.map((t=>t.$)).forEach((function(t){n[t.source].edges.push(t)})),function t(e,s){if(e.edges){var i=r.pluck(e.edges,"target");e.children=r.values(r.pick(n,i)),e.children.forEach((function(t,n){t.attribute=e.edges[n].length||""})),e.children.forEach(t),e.annotation=""}}(n[i]),n[i]}))})),n},phyloxml:g,nexus:p,nwk:d,nhx:d,beast:function(t,e){e.left_delimiter="[",e.right_delimiter="]";const n=d(t,e);return function t(e){if(e.annotation){e.beast={};const t=e.annotation.split(/=|,|{|}/).filter((t=>t));for(var n=0;n<t.length;n+=2){let s=t[n].replace(/&|%/g,"");/[a-df-zA-DF-Z]+/.test(t[n+2])?e.beast[s]=+t[n+1]:(e.beast[s]=[+t[n+1],+t[n+2]],n++)}}e.annotation=void 0,e.children&&e.children.forEach(t)}(n.json),n}};function b(t,e,n){let s,i,a,r=[t],o=[];for(;t=r.pop();)if((!n||!n(t))&&(o.push(t),s=t.children,s))for(i=0,a=s.length;i<a;++i)r.push(s[i]);for(;t=o.pop();)e(t);return t}function v(t,e,n){let s,i,a=[t];for(;t=a.pop();)if((!n||!n(t))&&(e(t),s=t.children,s))for(i=s.length-1;i>=0;--i)a.push(s[i]);return t}function y(t,e,n){let s,i,a,r,o=[t];do{for(s=o.reverse(),o=[];t=s.pop();)if((!n||!n(t))&&(e(t),i=t.children,i))for(a=0,r=i.length;a<r;++a)o.push(i[a])}while(o.length);return t}function x(t){return b(t,(function(t){t.children&&(t.children[0].data.multiway_parent=t,t.children[1].data.multiway_parent=t.parent)})),o.map(t.descendants(),(t=>{let e=t.data.multiway_parent,n="unknown";return e&&(n=e.data.name),{source:t.data.multiway_parent,target:t,name:n}}))}function w(t,e){let n=t.data;if("attribute"in n&&n.attribute&&n.attribute.length){e>0&&(n.attribute=String(e));let t=parseFloat(n.attribute);if(!isNaN(t))return Math.max(0,t)}if("root"==n.name)return 0;console.warn("Undefined branch length at "+n.name+"!")}var N=Object.freeze({__proto__:null,reroot:function(t,e){if(!(t instanceof a.hierarchy))throw new Error("node needs to be an instance of a d3.hierarchy node!");let n=this.nodes.copy();if(e=void 0!==e?e:.5,t.parent){var s=a.hierarchy({name:"new_root"});s.children=[t.copy()],s.data.__mapped_bl=void 0,n.each((t=>{t.data.__mapped_bl=this.branch_length_accessor(t)})),this.setBranchLength((t=>t.data.__mapped_bl));let o=t,l=t.parent,h=r.noop(),d=void 0===t.data.__mapped_bl?void 0:t.data.__mapped_bl*e;var i;if(h=l.data.__mapped_bl,l.data.__mapped_bl=void 0===t.data.__mapped_bl?void 0:t.data.__mapped_bl-d,t.data.__mapped_bl=d,l.parent){for(s.children.push(l);l.parent;){i=l.children.indexOf(o),l.parent.parent?l.children.splice(i,1,l.parent):l.children.splice(i,1);let t=l.parent.data.__mapped_bl;void 0!==t&&(l.parent.data.__mapped_bl=h,h=t),o=l,l=l.parent}i=l.children.indexOf(o),l.children.splice(i,1)}else i=l.children.indexOf(o),l.children.splice(i,1),h=l.data.__mapped_bl,o=s;if(1==l.children.length)h&&(l.children[0].data.__mapped_bl+=h),o.children=o.children.concat(l.children);else{let e=new a.hierarchy({name:"__reroot_top_clade",__mapped_bl:h});r.extendOwn(s.children[0],t),e.data.__mapped_bl=h,e.children=l.children.map((function(t){return t.parent=e,t})),e.parent=o,o.children.push(e)}}if(this.update(s),this.traverse_and_compute((t=>{r.each(t.children,(e=>{e.parent=t}))}),"pre-order"),!r.isUndefined(this.display)){let t=this.display.options;a.select(this.display.container).select("svg").remove();let e=this.display.selection_attribute_name;delete this.display;let n=this.render(t);n.selectionLabel(e),n.update(),a.select(n.container).node().appendChild(n.show()),a.select(this.display.container).dispatch("reroot")}return this},rootpath:function(t,e){if(t=t||"attribute",e=e||"y_scaled","parent"in this){let n=parseFloat(this[t]);this[e]=this.parent[e]+(isNaN(n)?.1:n)}else this[e]=0;return this[e]},pathToRoot:function(t){let e=[];for(;t;)e.push(t),t=t.parent;return e}});function z(t){return t.y}function k(t){return t.x}function E(t,e,n){return{x:n+t*Math.sin(e),y:n+t*Math.cos(e)}}function S(t,e,n,s,i,a){t.radius=e*(t.radius+n),t.angle=2*Math.PI*t.x*i[0]/a[0];let r=E(t.radius,t.angle,s);return t.x=r.x,t.y=r.y,t}function M(t,e){var n=E(e[0].radius,e[0].angle,t),s=E(e[0].radius,e[1].angle,t);return"M "+z(n)+","+k(n)+" A "+e[0].radius+","+e[0].radius+" 0,0, "+(e[1].angle>e[0].angle?1:0)+" "+z(s)+","+k(s)+" L "+z(e[1])+","+k(e[1])}function A(t,e,n){var s=E(t.target.radius+(t.source.radius-t.target.radius)*e,t.target.angle,n);return{x:z(s),y:k(s)}}var L=a.line().x((function(t){return z(t)})).y((function(t){return k(t)})).curve(a.curveStepBefore);function T(t,e){return{x:z(t.target)+(z(t.source)-z(t.target))*e,y:k(t.target)}}function C(t){return t.tag||!1}function O(t,e){return t[e]||!1}const j={"tree-container":"phylotree-container","tree-scale-bar":"tree-scale-bar",node:"node","internal-node":"internal-node","tagged-node":"node-tagged","selected-node":"node-selected","collapsed-node":"node-collapsed","root-node":"root-node",branch:"branch","selected-branch":"branch-selected","tagged-branch":"branch-tagged","tree-selection-brush":"tree-selection-brush","branch-tracer":"branch-tracer",clade:"clade",node_text:"phylotree-node-text"};function P(t){return arguments.length?(P="string"==typeof t&&"equal"==t?function(t){return 1}:t,this):P}var R={all:t=>!0,none:t=>!1,"all-leaf-nodes":t=>l(t.target),"all-internal-nodes":t=>!l(t.target)};var B=Object.freeze({__proto__:null,css_classes:j,internalNames:function(t){return arguments.length?(this.options["internal-names"]=t,this):this.options["internal-names"]},radial:function(t){return arguments.length?(this.options["is-radial"]=t,this):this.options["is-radial"]},alignTips:function(t){return arguments.length?(this.options["align-tips"]=t,this):this.options["align-tips"]},nodeBubbleSize:function(t){return this.options["draw-size-bubbles"]&&this.options["bubble-styler"]?this.options["bubble-styler"](t):this.options["draw-size-bubbles"]?this.relative_nodeSpan(t)*this.scales[0]*.25:0},shiftTip:function(t){return this.options["is-radial"]?[("end"==t.text_align?-1:1)*(this.radius_pad_for_bubbles-t.radius),0]:(this.options["right-to-left"],[this.right_most_leaf-t.screen_x,0])},layoutHandler:function(t){return arguments.length?(this.layout_listener_handler=t,this):this.layout_listener_handler},selectionLabel:function(t){return arguments.length?(this.selection_attribute_name=t,this.syncEdgeLabels(),this):this.selection_attribute_name},get nodeSpan(){return P},predefined_selecters:R,selectionCallback:function(t){return t?(this.selectionCallback=t,this):this.selectionCallback}});function I(t){return!(t.hidden||t.notshown)}function H(t){return t.notshown}function U(t){return t.hasHiddenNodes||!1}function D(t){return t.collapsed||!1}function q(t){return[t.node,t["internal-node"],t["collapsed-node"],t["tagged-node"],t["root-node"]].reduce((function(t,e,n,s){return t+"g."+e+(n<s.length-1?",":"")}),"")}function V(t){return l(t=t.data)?t.name||"":this.showInternalName(t)?t.name:""}var F=Object.freeze({__proto__:null,shiftTip:function(t){return this.radial()?[("end"==t.text_align?-1:1)*(this.radius_pad_for_bubbles-t.radius),0]:(this.options["right-to-left"],[this.right_most_leaf-t.screen_x,0])},drawNode:function(t,e,n){t=a.select(t);var s=l(e);s&&(t=t.attr("data-node-name",e.data.name));var i=t.selectAll("text").data([e]),r=t.selectAll("line");if(s||this.showInternalName(e)&&!D(e))if(i=i.enter().append("text").classed(this.css_classes.node_text,!0).merge(i).on("click",(t=>{this.handle_node_click(e,t)})).attr("dy",(t=>.33*this.shown_font_size)).text((t=>this.options["show-labels"]?this._nodeLabel(t):"")).style("font-size",(t=>this.ensure_size_is_in_px(this.shown_font_size))),i=this.radial()?i.attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle)+this.d3PhylotreeSvgTranslate(this.alignTips()?this.shiftTip(t):null))).attr("text-anchor",(t=>t.text_align)):i.attr("text-anchor","start").attr("transform",(t=>"right-to-left"==this.options.layout?this.d3PhylotreeSvgTranslate([-20,0]):this.d3PhylotreeSvgTranslate(this.alignTips()?this.shiftTip(t):null))),this.alignTips()?(r=r.data([e]),n?r=r.enter().append("line").classed(this.css_classes["branch-tracer"],!0).merge(r).attr("x1",(t=>("end"==t.text_align?-1:1)*this.nodeBubbleSize(e))).attr("x2",0).attr("y1",0).attr("y2",0).attr("x2",(t=>"right-to-left"==this.options.layout?t.screen_x:this.shiftTip(t)[0])).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle))).attr("x2",(t=>"right-to-left"==this.options.layout?t.screen_x:this.shiftTip(t)[0])).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle))):(r=r.enter().append("line").classed(this.css_classes["branch-tracer"],!0).merge(r).attr("x1",(t=>("end"==t.text_align?-1:1)*this.nodeBubbleSize(e))).attr("y2",0).attr("y1",0).attr("x2",(t=>this.shiftTip(t)[0]))).attr("transform",(t=>this.d3PhylotreeSvgRotate(t.text_angle)))):r.remove(),this.options["draw-size-bubbles"]){var o=this.nodeBubbleSize(e);t.selectAll("circle").data([o]).enter().append("circle").attr("r",(function(t){return t})),this.shown_font_size>=5&&(i=i.attr("dx",(t=>("end"==t.text_align?-1:1)*((this.alignTips()?0:o)+.33*this.shown_font_size))))}else this.shown_font_size>=5&&(i=i.attr("dx",(t=>("end"==t.text_align?-1:1)*this.shown_font_size*.33)));if(!s){let n=t.selectAll("circle").data([e]).enter().append("circle"),s=this.node_circle_size()(e);s>0?n.merge(n).attr("r",(t=>Math.min(.75*this.shown_font_size,s))).on("click",(t=>{this.handle_node_click(e,t)})):n.remove()}return this.node_styler&&this.node_styler(t,e),e},updateHasHiddenNodes:function(){let t=this.phylotree.nodes.descendants();for(let e=t.length-1;e>=0;e-=1)l(t[e])?t[e].hasHiddenNodes=t[e].notshown:t[e].hasHiddenNodes=t[e].children.reduce((function(t,e){return e.notshown||t}),!1);return this},showInternalName:function(t){const e=this.internalNames();return!!e&&("function"==typeof e?e(t):e)},nodeSpan:function(t){return arguments.length?(this.nodeSpan="string"==typeof t&&"equal"==t?function(t){return 1}:t,this):this.nodeSpan},reclassNode:function(t){let e=j[l(t)?"node":"internal-node"];return C(t)&&(e+=" "+j["tagged-node"]),O(t,this.selection_attribute_name)&&(e+=" "+j["selected-node"]),t.parent||(e+=" "+j["root-node"]),(D(t)||U(t))&&(e+=" "+j["collapsed-node"]),e},nodeVisible:I,nodeNotshown:H,hasHiddenNodes:U,isNodeCollapsed:D,nodeCssSelectors:q,internalLabel:function(t,e){this.phylotree.clearInternalNodes(e);for(var n=this.phylotree.nodes.descendants().length-1;n>=0;n--){var s=this.phylotree.nodes.descendants()[n];l(s)||O(s,this.selection_attribute_name)||(s[this.selection_attribute_name]=t(s.children))}this.modifySelection(((t,e)=>(l(t.target),t.target[this.selection_attribute_name])))},defNodeLabel:V,nodeLabel:function(t){return arguments.length?(this._nodeLabel=t||V,this.update(),this):this._nodeLabel}});function W(t){return[t.clade].reduce((function(t,e,n,s){return t+"path."+e+(n<s.length-1?",":"")}),"")}var X=Object.freeze({__proto__:null,cladeCssSelectors:W,updateCollapsedClades:function(t){let e=this.svg.selectAll("."+this.css_classes["tree-container"]);var n=0;let s=e.selectAll(W(this.css_classes)).data(this.phylotree.nodes.descendants().filter(D),(function(t){return t.id||(t.id=++n)})),i=function(){},o=r.noop();this.radial()?(i=a.line().curve(a.curveBasis).y((function(t){return t[0]})).x((function(t){return t[1]})),o=function(t,e,n,s,i){return e?[n.screen_y+(t[0]-s)/50,n.screen_x+(t[1]-i)/50]:[n.screen_y,n.screen_x]}):(i=a.line().y((function(t){return t[0]})).x((function(t){return t[1]})).curve(a.curveBasis),o=function(t,e,n,s,i){return e?[n.screen_y+(t[0]-s)/50,n.screen_x+(t[1]-i)/50]:[n.screen_y,n.screen_x]}),s.exit().each((function(t){t.collapsed_clade=null})).remove(),t?s.enter().insert("path",":first-child").attr("class",this.css_classes.clade).merge(s).attr("d",(function(t){if(t.collapsed_clade)return t.collapsed_clade;let e=t.collapsed[0][0],n=t.collapsed[0][1];return i(t.collapsed.map((function(s,i){return o(s,i,t,e,n)})))})).attr("d",(function(t){return t.collapsed_clade=i(t.collapsed)})):s.enter().insert("path",":first-child").attr("class",this.css_classes.clade).merge(s).attr("d",(function(t){return t.collapsed_clade?t.collapsed_clade:t.collapsed_clade=i(t.collapsed)}))}});function G(t){return!(t.target.hidden||t.target.notshown)}function $(t){return[t.branch,t["selected-branch"],t["tagged-branch"]].reduce((function(t,e,n,s){return t+"path."+e+(n<s.length-1?",":"")}),"")}var Y=Object.freeze({__proto__:null,drawEdge:function(t,e,n){t=(t=a.select(t)).attr("class",(t=>this.reclassEdge(t))).on("click",(t=>{this.modifySelection([e.target],this.selection_attribute_name),this.update()}));let s=this.draw_branch([e.source,e.target]);n?(t.datum().existing_path&&(t=t.attr("d",(function(t){return t.existing_path}))),t=t.attr("d",s)):t=t.attr("d",s),e.existing_path=s;var i=this.phylotree.branch_length_accessor(e.target);if(void 0!==i){var r=t.selectAll("title");r.empty()&&(r=t.append("title")),r.text("Length = "+i)}else t.selectAll("title").remove();return this.edge_styler&&this.edge_styler(t,e,n),this.phylotree},reclassEdge:function(t){let e=j.branch;return C(t)&&(e+=" "+j["tagged-branch"]),O(t,this.selection_attribute_name)&&(e+=" "+j["selected-branch"]),e},initializeEdgeLabels:function(){this.links.forEach((t=>{t.target.data.annotation&&(t.target[t.target.data.annotation]=t.target.data.annotation)}))},syncEdgeLabels:function(){if(this.links.forEach((t=>{t[this.selection_attribute_name]=t.target[this.selection_attribute_name]||!1,t.tag=t.target.tag||!1})),this.countHandler()){let t={};t[this.selection_attribute_name]=this.links.reduce(((t,e)=>t+(e[this.selection_attribute_name]?1:0)),0),t.tagged=this.links.reduce((function(t,e){return t+(C(e)?1:0)}),0),this.countUpdate(this,t,this.countHandler())}},edgeVisible:G,edgeCssSelectors:$,placeAlongAnEdge:function(t,e){return this.edge_placer(t,e)}});let J="phylotree.event";function K(t){var e=new CustomEvent(J,{detail:["refresh",t]});document.dispatchEvent(e)}function Z(t,e){var n=new CustomEvent(J,{detail:["countUpdate",e,t.countHandler()]});document.dispatchEvent(n)}function Q(t){switch(t.detail[0]){case"refresh":t.detail[1].refresh();break;case"countUpdate":t.detail[2](t.detail[1]);break;case"layout":t.detail[2](t.detail[1])}return!0}function tt(){document.addEventListener(J,Q,!1)}var et=Object.freeze({__proto__:null,toggleCollapse:function(t){if(t.collapsed){t.collapsed=!1;let e=function(t){l(t)||t.collapsed||t.children.forEach(e),t.hidden=!1};e(t)}else t.collapsed=!0;return this.placenodes(),this},resizeSvg:function(t,e,n){let s=this.size;if(this.radial()){let t=this.pad_width(),n="fit-to-size"!=this.options["top-bottom-spacing"]?this.pad_height():0;s=[s[1]+2*t,s[0]+2*t+n],e&&e.selectAll("."+j["tree-container"]).attr("transform","translate ("+t+","+(t+n)+")")}else s=[s[0]+("fit-to-size"!=this.options["top-bottom-spacing"]?this.pad_height():0),s[1]+("fit-to-size"!=this.options["left-right-spacing"]?this.pad_width():0)];return e&&(n&&(e=e.transition(100)),e.attr("height",s[0]).attr("width",s[1])),this.size=s,s},rescale:function(t,e){(e=e||"y_scaled")in this&&(this[e]*=t)},triggerRefresh:K,countUpdate:Z,d3PhylotreeTriggerLayout:function(t){var e=new CustomEvent(J,{detail:["layout",t,t.layoutHandler()]});document.dispatchEvent(e)},d3PhylotreeEventListener:Q,d3PhylotreeAddEventListener:tt,d3PhylotreeSvgTranslate:function(t){return!t||null===t[0]&&null===t[1]?"":"translate ("+(null!==t[0]?t[0]:0)+","+(null!==t[1]?t[1]:0)+") "},d3PhylotreeSvgRotate:function(t){return null!==t?"rotate ("+t+") ":""}});let nt="d3_layout_phylotree_context_menu";var st=Object.freeze({__proto__:null,nodeDropdownMenu:function(t,e,n,s,i){let o=a.select(e).select("#d3_layout_phylotree_context_menu");if(o.empty()&&(o=a.select(e).append("div").attr("id",nt).attr("class","dropdown-menu").attr("role","menu")),o.selectAll("a").remove(),o.selectAll("h6").remove(),o.selectAll("div").remove(),t){if(!r.some([Boolean(t.menu_items),s.hide,s.selectable,s.collapsible])||!s["show-menu"])return;l(t)||(s.collapsible&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text(D(t)?"Expand Subtree":"Collapse Subtree").on("click",(e=>{o.style("display","none"),this.toggleCollapse(t).update()})),s.selectable&&(o.append("div").attr("class","dropdown-divider"),o.append("h6").attr("class","dropdown-header").text("Toggle selection"))),s.selectable&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All descendant branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!0))})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All terminal branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!1))})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("All internal branches").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!1,!0))})))),t.parent&&(s.selectable&&(o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Incident branch").on("click",(function(e){o.style("display","none"),n.modifySelection([t])})),o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Path to root").on("click",(e=>{o.style("display","none"),this.modifySelection(this.phylotree.pathToRoot(t))})),(s.reroot||s.hide)&&o.append("div").attr("class","dropdown-divider")),s.reroot&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Reroot on this node").on("click",(e=>{o.style("display","none"),this.phylotree.reroot(t),this.update()})),s.hide&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Hide this "+(l(t)?"node":"subtree")).on("click",(e=>{o.style("display","none"),this.modifySelection([t],"notshown",!0,!0).updateHasHiddenNodes().update()}))),U(t)&&o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text("Show all descendant nodes").on("click",(function(e){o.style("display","none"),n.modifySelection(n.selectAllDescendants(t,!0,!0),"notshown",!0,!0,"false").updateHasHiddenNodes().update()}));var h=[];if("menu_items"in t&&"object"==typeof t.menu_items&&t.menu_items.forEach((function(e){3==e.length&&(e[2]&&!e[2](t)||h.push([e[0],e[1]]))})),h.length){const e=[s.hide,s.selectable,s.collapsible];r.some(e)&&o.append("div").attr("class","dropdown-divider"),h.forEach((function(e){o.append("a").attr("class","dropdown-item").attr("tabindex","-1").text(e[0](t)).on("click",r.partial(e[1],t))}))}let a=document.querySelector(e).getBoundingClientRect();o.style("position","absolute").style("left",i.clientX-a.x+12+"px").style("top",i.clientY-a.y+"px").style("display","block")}else o.style("display","none")},addCustomMenu:function(t,e,n,s){"menu_items"in t||(t.menu_items=[]),t.menu_items.some((function(t){return t[0]==e&&t[1]==n&&t[2]==s}))||t.menu_items.push([e,n,s])},modifySelection:function(t,e,n,s,i){if(e=e||this.selection_attribute_name,i=i||"toggle",this.options["restricted-selectable"].length){if(!r.contains(r.keys(R),t))return;t=R[t]}if(!this.options["restricted-selectable"]&&!this.options.selectable||this.options["binary-selectable"])this.options["binary-selectable"]&&("function"==typeof t?this.links.forEach((function(n){var s=t(n);n[e]=n[e]||!1,n[e]!=s&&(n[e]=s,o=!0,n.target[e]=s),this.options["attribute-list"].forEach((function(t){t!=e&&!0===n[e]&&(n[t]=!1,n.target[t]=!1)}))})):(t.forEach((function(t){var n;n=!t[e],t[e]!=n&&(t[e]=n,o=!0)})),this.links.forEach((function(t){t[e]=t.target[e],this.options["attribute-list"].forEach((function(n){n!=e&&!0!==t[e]&&(t[n]=!1,t.target[n]=!1)}))}))),o&&(s||K(this),this.countHandler()&&((a={})[e]=this.links.reduce((function(t,n){return t+(n[e]?1:0)}),0),this.countUpdate(this,a,this.countHandler())),n&&this.placenodes()));else{var a,o=!1;"function"==typeof t?this.links.forEach((function(n){let s=t(n);n[e]=n[e]||!1,n[e]!=s&&(n[e]=s,o=!0,n.target[e]=s)})):(t.forEach((function(t){var n;switch(i){case"true":n=!0;break;case"false":n=!1;break;default:n=!t[e]}t[e]!=n&&(t[e]=n,o=!0)})),this.links.forEach((function(t){t[e]=t.target[e]}))),o&&(s||K(this),this.countHandler&&((a={})[e]=this.links.reduce((function(t,n){return t+(n[e]?1:0)}),0),Z(this,a,this.countHandler)),n&&this.placenodes())}return this.selectionCallback&&"tag"!=e&&this.selectionCallback(this.getSelection()),this.refresh(),this.update(),this},getSelection:function(){return this.nodes.filter((t=>t[this.selection_attribute_name]))},selectAllDescendants:function(t,e,n){let s=[];return function i(a){l(a)?e&&a!=t&&s.push(a):(n&&a!=t&&s.push(a),a.children.forEach(i))}(t),s},selectionCallback:function(t){return t?(this.selectionCallback=t,this):this.selectionCallback}});function it(t){return function(){return t}}class at{constructor(t,e={}){this.css_classes=j,this.phylotree=t,this.container=e.container,this.separation=function(t,e){return 0},this._nodeLabel=this.defNodeLabel,this.svg=null,this.selectionCallback=null,this.scales=[1,1],this.size=[1,1],this.fixed_width=[14,30],this.font_size=12,this.scale_bar_font_size=12,this.offsets=[0,this.font_size/2],this.draw_branch=L,this.draw_scale_bar=null,this.edge_placer=T,this.count_listener_handler=function(){},this.layout_listener_handler=function(){},this.node_styler=void 0,this.edge_styler=void 0,this.shown_font_size=this.font_size,this.selection_attribute_name="selected",this.right_most_leaf=0,this.label_width=0,this.radial_center=0,this.radius=1,this.radius_pad_for_bubbles=0,this.rescale_nodeSpan=1,this.relative_nodeSpan=function(t){return this.nodeSpan(t)/this.rescale_nodeSpan};let n={layout:"left-to-right",logger:console,branches:"step",scaling:!0,bootstrap:!1,"color-fill":!0,"internal-names":!1,selectable:!0,"restricted-selectable":!1,collapsible:!0,"left-right-spacing":"fixed-step","top-bottom-spacing":"fixed-step","left-offset":0,"show-scale":"top","draw-size-bubbles":!1,"bubble-styler":this.radius_pad_for_bubbles,"binary-selectable":!1,"is-radial":!1,"attribute-list":[],"max-radius":768,"annular-limit":.38196601125010515,compression:.2,"align-tips":!1,"maximum-per-node-spacing":100,"minimum-per-node-spacing":2,"maximum-per-level-spacing":100,"minimum-per-level-spacing":10,node_circle_size:it(3),transitions:null,brush:!0,reroot:!0,hide:!0,"label-nodes-with-name":!1,zoom:!1,"show-menu":!0,"show-labels":!0,"node-styler":null,"edge-styler":null,"node-span":null};this.ensure_size_is_in_px=function(t){return"number"==typeof t?t+"px":t},this.options=r.defaults(e,n),this.width=this.options.width||800,this.height=this.options.height||600,this.node_styler=this.options["node-styler"],this.edge_styler=this.options["edge-styler"],this.nodeSpan=this.options["node-span"],this.nodeSpan||(this.nodeSpan=function(t){return 1}),this.rescale_nodeSpan=this.phylotree.nodes.children.map((t=>{if(l(t)||this.showInternalName(t))return this.nodeSpan(t)})).reduce((function(t,e){return Math.min(e,t||1e200)}),null)||1,this.initialize_svg(this.container),this.links=this.phylotree.nodes.links(),this.initializeEdgeLabels(),this.update(),tt()}pad_height(){return this.draw_scale_bar?this.scale_bar_font_size+25:0}pad_width(){this.label_width=this._label_width(this.shown_font_size);const t=this.options["show-labels"]?this.label_width:0;return this.offsets[1]+this.options["left-offset"]+t}collapse_node(t){D(t)||(t.collapsed=!0)}set_size(t){if(!arguments.length)return this.size;let e=t;return"fixed-step"!=this.options["top-bottom-spacing"]&&(this.size[0]=e[0]),"fixed-step"!=this.options["left-right-spacing"]&&(this.size[1]=e[1]),this}initialize_svg(t){return this.svg!==t&&(a.select(t).select("svg").remove(),this.svg=a.create("svg").attr("width",this.width).attr("height",this.height),this.set_size([this.height,this.width]),"phylotree-container"==this.css_classes["tree-container"]&&(this.svg.selectAll("*").remove(),this.svg.append("defs")),a.select(this.container).on("click",(t=>{this.handle_node_click(null)}),!0)),this}update_layout(t,e){e&&(this.nodes=a.hierarchy(t),this.nodes.each((function(t){t.id=null}))),this.update(),this.syncEdgeLabels()}update(t){var e=this;this.placenodes(),t=this.transitions(t);let n=0,s=this.svg.selectAll("."+j["tree-container"]).data([0]);if(s=s.enter().append("g").attr("class",j["tree-container"]).merge(s).attr("transform",(t=>this.d3PhylotreeSvgTranslate([this.offsets[1]+this.options["left-offset"],this.pad_height()]))),this.draw_scale_bar){let t=this.svg.selectAll("."+j["tree-scale-bar"]).data([0]);t.enter().append("g").attr("class",j["tree-scale-bar"]).style("font-size",this.ensure_size_is_in_px(this.scale_bar_font_size)).merge(t).attr("transform",(t=>this.d3PhylotreeSvgTranslate([this.offsets[1]+this.options["left-offset"],this.pad_height()-10]))).call(this.draw_scale_bar),t.selectAll("text").style("text-anchor","end")}else this.svg.selectAll("."+j["tree-scale-bar"]).remove();s=this.svg.selectAll("."+j["tree-container"]).data([0]),this.updateCollapsedClades(t);let i=s.selectAll($(j)).data(this.links.filter(G),(t=>t.target.id||(t.target.id=++n)));i.exit().remove(),i=i.enter().insert("path",":first-child").merge(i).each((function(n){e.drawEdge(this,n,t)}));let o=s.selectAll(q(j)).data(this.phylotree.nodes.descendants().filter(I),(t=>t.id||(t.id=++n)));if(o.exit().remove(),o=o.enter().append("g").attr("class",this.reclassNode).merge(o).attr("transform",(t=>{const e="right-to-left"==this.options.layout&&l(t);return t.screen_x=z(t),t.screen_y=k(t),this.d3PhylotreeSvgTranslate([e?0:t.screen_x,t.screen_y])})).each((function(n){e.drawNode(this,n,t)})).attr("transform",(t=>{if(!r.isUndefined(t.screen_x)&&!r.isUndefined(t.screen_y))return"translate("+t.screen_x+","+t.screen_y+")"})),this.options["label-nodes-with-name"]&&(o=o.attr("id",(t=>"node-"+t.name))),this.resizeSvg(this.phylotree,this.svg,t),this.options.brush){var h=s.selectAll("."+j["tree-selection-brush"]).data([0]).enter().insert("g",":first-child").attr("class",j["tree-selection-brush"]),d=a.brush().on("brush",((t,e)=>{var n=t.selection,s=this.links.filter(G).filter(((t,e)=>t.source.screen_x>=n[0][0]&&t.source.screen_x<=n[1][0]&&t.source.screen_y>=n[0][1]&&t.source.screen_y<=n[1][1]&&t.target.screen_x>=n[0][0]&&t.target.screen_x<=n[1][0]&&t.target.screen_y>=n[0][1]&&t.target.screen_y<=n[1][1])).map((t=>t.target));this.modifySelection(this.phylotree.links.map((t=>t.target)),"tag",!1,s.length>0,"false"),this.modifySelection(s,"tag",!1,!1,"true")})).on("end",(()=>{}));h.call(d)}if(this.syncEdgeLabels(),this.options.zoom){let t=a.zoom().scaleExtent([.1,10]).on("zoom",(t=>{a.select("."+j["tree-container"]).attr("transform",(e=>t.transform)),a.select("."+j["tree-scale-bar"]).attr("transform",(e=>{let n=t.transform;return n.y-=10,n}))}));this.svg.call(t)}return this}_handle_single_node_layout(t){let e=this.nodeSpan(t)/this.rescale_nodeSpan;this.x=t.x=this.x+this.separation(this.last_node,t)+.5*(this.last_span+e),this._extents[1][1]=Math.max(this._extents[1][1],t.y),this._extents[1][0]=Math.min(this._extents[1][0],t.y-.5*e),this.is_under_collapsed_parent?this._extents[0][1]=Math.max(this._extents[0][1],this.save_x+(t.x-this.save_x)*this.options.compression+this.save_span+(.5*e+this.separation(this.last_node,t))*this.options.compression):this._extents[0][1]=Math.max(this._extents[0][1],this.x+.5*e+this.separation(this.last_node,t)),this.last_node=t,this.last_span=e}tree_layout(t){if(H(t))return;let e=l(t);t.text_angle=null,t.text_align=null,t.radius=null,t.angle=null;let n=!1;if(t.parent)if(this.do_scaling){if(n)return 0;if(t.y=this.phylotree.branch_length_accessor(t),void 0===t.y)return n=!0,0;t.y+=t.parent.y}else t.y=e?this.max_depth:t.depth;else this.x=0,t.y=0,this.last_node=null,this.last_span=0,this._extents=[[0,0],[0,0]];if(e&&this._handle_single_node_layout(t),!e)if(D(t)&&!this.is_under_collapsed_parent){if(this.save_x=this.x,this.save_span=.5*this.last_span,this.is_under_collapsed_parent=!0,this.process_internal_node(t),this.is_under_collapsed_parent=!1,"number"==typeof t.x){t.x=this.save_x+(t.x-this.save_x)*this.options.compression+this.save_span,t.collapsed=[[t.x,t.y]];var s=e=>{e.hidden=!0,l(e)?(this.x=e.x=this.save_x+(e.x-this.save_x)*this.options.compression+this.save_span,t.collapsed.push([e.x,e.y])):e.children.map(s)};this.x=this.save_x,s(t),t.collapsed.splice(1,0,[this.save_x,t.y]),t.collapsed.push([this.x,t.y]),t.collapsed.push([t.x,t.y]),t.hidden=!1}}else this.process_internal_node(t);return t.x}process_internal_node(t){let e=0;if(this.showInternalName(t)){let e=t.children.length/2>>0,n=0,s=!1;for(let i=0;i<t.children.length;i++){"number"==typeof this.tree_layout(t.children[i])&&n++,n>=e&&!s&&(this._handle_single_node_layout(t),s=!0)}0==n?(t.notshown=!0,t.x=void 0):s||this._handle_single_node_layout(t)}else t.x=t.children.map(this.tree_layout.bind(this)).reduce(((t,n)=>"number"==typeof n?t+n:(e+=1,t)),0),e==t.children.length?(t.notshown=!0,t.x=void 0):t.x/=t.children.length-e}do_lr(t){if(this.radial()&&t&&(this.offsets[1]=0),"fixed-step"==this.options["left-right-spacing"])this.size[1]=this.max_depth*this.fixed_width[1],this.scales[1]=(this.size[1]-this.offsets[1]-this.options["left-offset"])/this._extents[1][1],this.label_width=this._label_width(this.shown_font_size),this.radial()&&(this.label_width*=2);else{this.label_width=this._label_width(this.shown_font_size),t=!0;let e=this.size[1]-this.offsets[1]-this.options["left-offset"];.5*e<this.label_width&&(this.shown_font_size*=.5*e/this.label_width,this.label_width=.5*e),this.scales[1]=(this.size[1]-this.offsets[1]-this.options["left-offset"]-this.label_width)/this._extents[1][1]}}placenodes(){this._extents=[[0,0],[0,0]],this.x=0,this.last_span=0,this.last_node=null,this.last_span=0,this.save_x=this.x,this.save_span=.5*this.last_span,this.do_scaling=this.options.scaling;this.is_under_collapsed_parent=!1,this.max_depth=1,this.phylotree.nodes.x=this.tree_layout(this.phylotree.nodes,this.do_scaling),this.max_depth=a.max(this.phylotree.nodes.descendants(),(t=>t.depth)),this.do_scaling;let t=!1;if(this.draw_scale_bar=this.options["show-scale"]&&this.do_scaling,this.offsets[1]=Math.max(this.font_size,-this._extents[1][0]*this.fixed_width[0]),"fixed-step"==this.options["top-bottom-spacing"]?(this.size[0]=this._extents[0][1]*this.fixed_width[0],this.scales[0]=this.fixed_width[0]):(this.scales[0]=(this.size[0]-this.pad_height())/this._extents[0][1],t=!0),this.shown_font_size=Math.min(this.font_size,this.scales[0]),this.radial()){this.draw_branch=r.partial(M,this.radial_center),this.edge_placer=A;let e=null,n=null,s=null,i=0,a=this._extents[0][1]*this.scales[0],o=function(t,e,n,s,i){return i=i||0,Math.sqrt((e-t)*(e-t)+2*(t+i)*(e+i)*(1-Math.cos(n-s)))},l=0;this.phylotree.nodes.each((t=>{let e=t.x*this.scales[0];t.angle=2*Math.PI*e/a,t.text_angle=t.angle-Math.PI/2,t.text_angle=t.text_angle>0&&t.text_angle<Math.PI,t.text_align=t.text_angle?"end":"start",t.text_angle=(t.text_angle?180:0)+180*t.angle/Math.PI})),this.do_lr(t),this.phylotree.nodes.each((t=>{t.radius=t.y*this.scales[1]/this.size[1],l=Math.max(t.radius,l)}));let h=0;this.phylotree.nodes.each((t=>{if(!t.children){let a=t.x*this.scales[0];if(null!==e){let r=a-n,d=o(t.radius,s,t.angle,e,h),c=d>0?r/d:10*this.options["max-radius"];if(c>this.options["max-radius"]){let n=r/this.options["max-radius"],a=t.radius+s,o=t.radius*s-(n*n-(s-t.radius)*(s-t.radius))/2/(1-Math.cos(e-t.angle)),d=Math.sqrt(a*a-4*o);h=Math.min(this.options["annular-limit"]*l,(-a+d)/2),i=this.options["max-radius"]}else i=Math.max(i,c)}e=t.angle,n=a,s=t.radius}})),this.radius=Math.min(this.options["max-radius"],Math.max(a/2/Math.PI,i)),t&&(this.radius=Math.min(this.radius,.5*(Math.min(a,this._extents[1][1]*this.scales[1])-this.label_width)-this.radius*h)),this.radial_center=this.radius_pad_for_bubbles=this.radius,this.draw_branch=r.partial(M,this.radial_center);let d=1;h&&(d=l/(l+h),this.radius*=d),this.phylotree.nodes.each((t=>{if(S(t,this.radius,h,this.radial_center,this.scales,this.size),l=Math.max(l,t.radius),this.options["draw-size-bubbles"]?this.radius_pad_for_bubbles=Math.max(this.radius_pad_for_bubbles,t.radius+this.nodeBubbleSize(t)):this.radius_pad_for_bubbles=Math.max(this.radius_pad_for_bubbles,t.radius),t.collapsed){t.collapsed=t.collapsed.map((t=>{let e={};return e.x=t[0],e.y=t[1],e=S(e,this.radius,h,this.radial_center,this.scales,this.size),[e.x,e.y]}));let e=t.collapsed[1];t.collapsed=t.collapsed.filter((function(n,s){return s<3||s>t.collapsed.length-4||Math.sqrt(Math.pow(n[0]-e[0],2)+Math.pow(n[1]-e[1],2))>3&&(e=n,!0)}))}})),this.size[0]=this.radial_center+this.radius/d,this.size[1]=this.radial_center+this.radius/d}else this.do_lr(),this.draw_branch=L,this.edge_placer=T,this.right_most_leaf=0,this.phylotree.nodes.each((t=>{if(t.x*=this.scales[0],t.y*=.8*this.scales[1],"right-to-left"==this.options.layout&&(t.y=this._extents[1][1]*this.scales[1]-t.y),l(t)&&(this.right_most_leaf=Math.max(this.right_most_leaf,t.y+this.nodeBubbleSize(t))),t.collapsed){t.collapsed.forEach((t=>{t[0]*=this.scales[0],t[1]*=.8*this.scales[1]}));let e=t.collapsed[1][0];t.collapsed=t.collapsed.filter((function(n,s){return s<3||s>t.collapsed.length-4||n[0]-e>3&&(e=n[0],!0)}))}}));if(this.draw_scale_bar){let t,e;if(this.radial()){if(e=Math.min(this.radius/5,50),t=Math.pow(10,Math.ceil(Math.log(this._extents[1][1]*e/this.radius)/Math.log(10))),e=t*(this.radius/this._extents[1][1]),e<30){let n=Math.ceil(30/e);e*=n,t*=n}}else t=this._extents[1][1],e=this.size[1]-this.offsets[1]-this.options["left-offset"]-this.shown_font_size;let n=a.scaleLinear().domain([0,t]).range([0,e]),s=a.format(".2f");if(this.draw_scale_bar=a.axisTop().scale(n).tickFormat((function(t){return 0===t?"":s(t)})),this.radial())this.draw_scale_bar.tickValues([t]);else{let t=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)},i=n.ticks();i=i.length>1?i[1]:i[0],this.draw_scale_bar.ticks(Math.min(10,t(e/(this.shown_font_size*s(i).length*2),0)))}}else this.draw_scale_bar=null;return this}spacing_x(t,e){return arguments.length?(this.fixed_width[0]!=t&&t>=this.options["minimum-per-node-spacing"]&&t<=this.options["maximum-per-node-spacing"]&&(this.fixed_width[0]=t,e||this.placenodes()),this):this.fixed_width[0]}spacing_y(t,e){return arguments.length?(this.fixed_width[1]!=t&&t>=this.options["minimum-per-level-spacing"]&&t<=this.options["maximum-per-level-spacing"]&&(this.fixed_width[1]=t,e||this.placenodes()),this):this.fixed_width[1]}_label_width(t){t=t||this.shown_font_size;let e=0;return this.phylotree.nodes.descendants().filter(I).forEach((n=>{let s=12+this._nodeLabel(n).length*t*.8;null!==n.angle&&(s*=Math.max(Math.abs(Math.cos(n.angle)),Math.abs(Math.sin(n.angle)))),e=Math.max(s,e)})),e}font_size(t){return arguments.length?(this.font_size=void 0===t?12:t,this):this.font_size}scale_bar_font_size(t){return arguments.length?(this.scale_bar_font_size=void 0===t?12:t,this):this.scale_bar_font_size}node_circle_size(t,e){return arguments.length?(this.options.node_circle_size=it(void 0===t?3:t),this):this.options.node_circle_size}css(t){if(0===arguments.length)return this.css_classes;if(arguments.length>2){var e={};return e[t[0]]=t[1],this.css(e)}for(var n in j)n in t&&t[n]!=j[n]&&(j[n]=t[n]);return this}transitions(t){return void 0!==t?t:null!==this.options.transitions?this.options.transitions:this.phylotree.nodes.descendants().length<=300}css_classes(t,e){if(!arguments.length)return this.css_classes;let n=!1;for(var s in j)s in t&&t[s]!=this.css_classes[s]&&(n=!0,this.css_classes[s]=t[s]);return e&&n&&this.layout(),this}layout(t){return this.svg?(this.svg.selectAll("."+this.css_classes["tree-container"]+",."+this.css_classes["tree-scale-bar"]+",."+this.css_classes["tree-selection-brush"]),this.d3PhylotreeTriggerLayout(this),this.update()):(this.d3PhylotreeTriggerLayout(this),this)}handle_node_click(t,e){this.nodeDropdownMenu(t,this.container,this,this.options,e)}refresh(){if(this.svg){let t=this.svg.selectAll("."+this.css_classes["tree-container"]).selectAll($(this.css_classes)).attr("class",this.reclassEdge.bind(this));this.edge_styler&&t.each((t=>{this.edge_styler(a.select(this),t)}))}return this}countHandler(t){return arguments.length?(this.count_listener_handler=t,this):this.count_listener_handler}style_nodes(t){return arguments.length?(this.node_styler=t,this):this.node_styler}style_edges(t){return arguments.length?(this.edge_styler=t.bind(this),this):this.edge_styler}itemSelected(t,e){return t[e]||!1}show(){return this.svg.node()}}r.extend(at.prototype,X),r.extend(at.prototype,F),r.extend(at.prototype,Y),r.extend(at.prototype,et),r.extend(at.prototype,st),r.extend(at.prototype,B);let rt=class{constructor(t,e={}){this.newick_string="",this.nodes=[],this.links=[],this.parsed_tags=[],this.partitions=[],this.branch_length_accessor=w,this.branch_length=w,this.logger=e.logger||console,this.selection_attribute_name="selected";var n=e.type||void 0,s=[],i=this;if(r.isString(n))n in m?s=m[n](t,e):i.logger.error("type "+n+" not in registry! Available types are "+r.keys(m));else if(r.isFunction(n))try{s=n(t,e)}catch(t){i.logger.error("Could not parse custom format!")}else"root"==t.name?s={json:t,error:null}:"string"!=typeof t?s=t:"application/xml"==t.contentType?s=g(t):(this.newick_string=t,s=d(t,e));if(s.json){i.nodes=a.hierarchy(s.json);let t={};i.nodes.each((e=>{e.data.annotation&&(t[e.data.annotation]=!0)})),i.parsed_tags=Object.keys(t)}else i.nodes=[];return i.links=i.nodes.links(),this.hasBranchLengths()||(console.warn("Phylotree User Warning : NO BRANCH LENGTHS DETECTED, SETTING ALL LENGTHS TO 1"),this.setBranchLength((t=>1))),i}json(t){var e=0;this.traverse_and_compute((function(t){t.json_export_index=e++}),t);var n=new Array(e);return e=0,this.traverse_and_compute((function(t){let s=r.clone(t);delete s.json_export_index,t.parent&&(s.parent=t.parent.json_export_index),t.children&&(s.children=r.map(t.children,(function(t){return t.json_export_index}))),n[e++]=s}),t),this.traverse_and_compute((function(t){delete t.json_export_index}),t),JSON.stringify(n)}traverse_and_compute(t,e,n,s){return(e="pre-order"==(e=e||"post-order")?function(e){v(e,t,s)}:"in-order"==e?function(e){y(e,t,s)}:function(e){r.isUndefined(e)||b(e,t,s)})(n||this.nodes),this}get_parsed_tags(){return this.parsed_tags}update(t){this.nodes=t}render(t){return this.display=new at(this,t),this.display}};function ot(t){var e=t.branch_length_accessor;if(!e)throw"A non-null branch lengths accessor function is required for this operation";var n=0;function s(t){for(var e=0;e<t.children.length;e++)for(var n=0;n<t.children.length;n++)e!=n&&r.each(t.children[n].cot_path_to_leaves_below,(function(s,i){t.children[e].cot_path_to_leaves_above&&(t.children[e].cot_path_to_leaves_above[i]=s+t.children[n].cot_computed_length)}))}return t.traverse_and_compute((function(s){if(s.cot_computed_length=e(s),s.parent&&r.isUndefined(s.cot_computed_length))throw"Non-null branch lengths are required for this operation: missing branch length at node "+s.data.name;t.isLeafNode(s)?(s.cot_leaf_index=n++,s.cot_path_to_leaves_below={},s.cot_path_to_leaves_below[s.cot_leaf_index]=0,s.cot_path_to_leaves_above={}):(s.cot_path_to_leaves_below={},s.cot_path_to_leaves_above={})})),t.traverse_and_compute((function(t){t.parent&&r.each(t.cot_path_to_leaves_below,(function(e,n){t.parent.cot_path_to_leaves_below[n]=e+t.cot_computed_length}))})),s(t.getRootNode()),t.traverse_and_compute((function(e){e.parent&&(r.each(e.parent.cot_path_to_leaves_above,(function(t,n){e.cot_path_to_leaves_above[n]=t+e.parent.cot_computed_length})),t.isLeafNode(e)||s(e))}),"pre-order"),n}function lt(t,e,n,s,i){var a=t.branch_length(e),r=!1;if(n||(s=e.data.rootToTip,i=0,r=!0),e.children)for(var o=0;o<e.children.length;o++)e.children[o]!=n?lt(t,e.children[o],e,s,i):r=!0;e.data.rtta=e.data.rootToTip-s+i,r&&(s-=a,i+=a),e.parent&&r&&lt(t,e.parent,e,s,i)}function ht(t){var e=t.reduce((function(t,e){return e[2]+t}),0),n=t.reduce((function(t,e){return e[2]*e[0]+t}),0),s=t.reduce((function(t,e){return e[2]*e[1]+t}),0),i=n/e,a=s/e,r=0,o=0,l=0;t.forEach((function(t){var e=t[0]-i;o+=t[2]*e*e,r+=t[2]*e*t[1],l+=t[2]*(t[1]-a)*(t[1]-a)}));var h=(s-n*(r/=o))/e,d=0;return t.forEach((function(t){var e=t[1]-h-r*t[0];d+=t[2]*e*e})),{intercept:h,slope:r,r2:1-d/l,"var (intercept)":Math.sqrt((1+n*n/(e*o))/e),"var (slope)":Math.sqrt(1/o)}}function dt(t){var e=t.branch_length_accessor,n=0;t.traverse_and_compute((s=>{if(s.parent&&(s.data._computed_length=e(s),!r.isNumber(s.data._computed_length)))throw"rootToTip cannot be run on trees with missing branch lengths";t.isLeafNode(s)&&(s.data.leaf_index=n++),"r2t"in s.data&&delete s.data.r2t})),t.traverse_and_compute((e=>{e.parent&&("r2t"in e.parent.data||(e.parent.data.r2t={}),t.isLeafNode(e)?e.parent.data.r2t[e.data.leaf_index]=e.data._computed_length:(r.each(e.data.r2t,(function(t,n){e.parent.data.r2t[n]=t+e.data._computed_length})),delete e.data.r2t),delete e.data._computed_length)}));var s=t.getRootNode().data.r2t;return t.traverse_and_compute((e=>{t.isLeafNode(e)&&(e.data.rootToTip=s[e.data.leaf_index]||0,delete e.data.leaf_index)})),delete t.getRootNode().data.r2t,t}rt.prototype.isLeafNode=l,rt.prototype.mrca=function(){var t,e;return t=(t=1==arguments.length?arguments[0]:Array.from(arguments)).map((function(t){return"string"==typeof t?t:t.name})),this.traverse_and_compute((function(n){n.children?n.parent?(n.mrca=r.union(...n.descendants().map((t=>t.mrca))),e||n.mrca.length!=t.length||(e=n)):e||(e=n):n.mrca=r.intersection([n.name],t)})),e},rt.prototype.hasBranchLengths=function(){let t=this.branch_length;return!!t&&r.every(this.nodes.descendants(),(function(e){return!e.parent||!r.isUndefined(t(e))}))},rt.prototype.getBranchLengths=function(){let t=this.branch_length;return r.map(this.nodes.descendants(),(e=>t(e)))},rt.prototype.branchName=function(t){return arguments.length?(this.nodeLabel=t,this):this.nodeLabel},rt.prototype.normalizeBranchLengths=function(t){let e=this.branch_length,n=r.map(this.nodes.descendants(),(function(t){return e(t)?e(t):null}));const s=r.max(n),i=r.min(n);return r.each(this.nodes.descendants(),(t=>{let n=e(t);n&&e(t,(n-i)/(s-i))})),this},rt.prototype.scaleBranchLengths=function(t){let e=this.branch_length;return r.each(this.nodes.descendants(),(n=>{let s=e(n);s&&e(n,t(s))})),this},rt.prototype.getNewick=function(t,e){let n=this;t||(t=t=>"");let s=[];return t=t||"",function e(i){l(i)||(s.push("("),i.children.forEach((function(t,n){n&&s.push(","),e(t)})),s.push(")")),"root"!=i.data.name&&s.push(i.data.name),s.push(t(i));let a=n.branch_length_accessor(i);void 0!==a&&s.push(":"+a)}(e||this.nodes),s.join("")+";"},rt.prototype.resortChildren=function(t,e,n){return this.nodes.sum((function(t){return t.value})).sort(t),this.display&&(this.display.update_layout(this.nodes),this.display.update()),this},rt.prototype.setBranchLength=function(t){return arguments.length?(this.branch_length_accessor=t||w,this):this.branch_length_accessor},rt.prototype.maxParsimony=function(t,e){const n=r.partial((function(t,e){if(e.mp=[[0,0],[!1,!1]],l(e))e.mp[1][0]=e.mp[1][1]=e[t]||!1,e.mp[0][0]=e.mp[1][0]?1:0,e.mp[0][1]=1-e.mp[0][0];else{e.children.forEach(n);var s=e.children.reduce((function(t,e){return e.mp[0][0]+t}),0),i=e.children.reduce((function(t,e){return e.mp[0][1]+t}),0);e[t]?(e.mp[0][0]=i+1,e.mp[1][0]=!0,e.mp[0][1]=i,e.mp[1][1]=!0):(s<i+1?(e.mp[0][0]=s,e.mp[1][0]=!1):(e.mp[0][0]=i+1,e.mp[1][0]=!0),i<s+1?(e.mp[0][1]=i,e.mp[1][1]=!0):(e.mp[0][1]=s+1,e.mp[1][1]=!1))}}),e);n(this.nodes),this.nodes.each((t=>{t.parent?t.mp=t.mp[1][t.parent.mp?1:0]:t.mp=t.mp[1][t.mp[0][0]<t.mp[0][1]?0:1]})),this.display.modifySelection(((t,n)=>l(t.target)?t.target[e]:t.target.mp))},rt.prototype.getTipLengths=function(){let t=this.getTips(),e=r.map(t,(t=>({name:t.data.name,length:parseFloat(t.data.attribute)})));return e=r.sortBy(e,(t=>-t.length)),e},rt.prototype.leftChildRightSibling=x,r.extend(rt.prototype,h),r.extend(rt.prototype,N),r.extend(rt.prototype,_);const ct=a.timeParse("%Y%m%d"),ut=/([0-9]{4}).?([0-9]{2}).?([0-9]{2})$/g,pt=function(t){if(l(t)&&"name"in t){let e=ut.exec(t.name);if(e)return e[1]+e[2]+e[3]}return null};function _t(t,e){let n=[];for(let s of o.range(e.length))if(s!=t){let i=[];for(let n of o.range(e[s].length))n!=t&&i.push(e[s][n]);n.push(i)}return n}t.centerOfTree=function(t,e){e=e||2;var n=ot(t),s=Number.MAX_VALUE,i=0,a=null;return 2==e?t.traverse_and_compute((function(t){if(t.parent){var e=0,o=0,l=0,h=0,d=0;r.each(t.cot_path_to_leaves_below,(function(t){e+=t,o+=t*t,d++})),r.each(t.cot_path_to_leaves_above,(function(t){l+=t,h+=t*t}));var c=n-d,u=(l-e+t.cot_computed_length*c)/n;u<0?u=0:u>t.cot_computed_length&&(u=t.cot_computed_length);var p=h+o+2*(l*(t.cot_computed_length-u)+e*u)+d*u*u+(t.cot_computed_length-u)*(t.cot_computed_length-u)*c;p<s&&(a=t,i=u/t.cot_computed_length,s=p),delete t.cot_computed_length,delete t.cot_path_to_leaves_below,delete t.cot_path_to_leaves_above,delete t.cot_leaf_index}})):t.traverse_and_compute((function(t){if(t.parent)for(var n=t.cot_computed_length>0?.05*t.cot_computed_length:.1,o=0;o<t.cot_computed_length;){var l=0;r.each(t.cot_path_to_leaves_below,(function(t){l+=Math.pow(t+o,e)})),r.each(t.cot_path_to_leaves_above,(function(n){l+=Math.pow(n+(t.cot_computed_length-o),e)})),l<s&&(a=t,i=o/t.cot_computed_length,s=l),o+=n}})),{location:a,breakpoint:i,distance:s}},t.clusterPicker=function(t,e,n,s,i){s=s||t.getRootNode(),i=r.isNumber(i)?i:1;let a=t.branch_length;t.traverse_and_compute((function(t){if(t.parent){if(t._computed_length=a(t),!r.isNumber(t._computed_length))throw"clusterPicker cannot be run on trees with missing branch lengths";t.max_path_length=0}})),t.traverse_and_compute((function(t){t.parent&&(t.parent.max_path_length=Math.max(t.parent.max_path_length,t.max_path_length+t._computed_length))}));var o=[];return t.traverse_and_compute(r.noop,"pre-order",s,(function(s){if(!t.isLeafNode(s)){var a=r.isString(s.data.bootstrap_values)?+s.data.bootstrap_values:i;if(a>=e){var l=r.reduce(s.children,(function(t,e){return e.max_path_length+e._computed_length+t}),0);if(l<=n)return o.push({root:s,diameter:l,bootstrap:a}),!0}}return!1})),t.traverse_and_compute((function(t){t.parent&&(delete t._computed_length,delete t.max_path_length)}),"post-order",s),r.each(o,(function(e){e.members=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&e.members.push(n)}),"post-order",e.root)})),o},t.computeMidpoint=function(t){if(!t.hasBranchLengths())throw"Center of tree calculation cannot be performed on trees that do not have fully specified branch lengths";var e=t.branch_length;t.traverse_and_compute((function(n){if(n.parent){var s,i=e(n);t.isLeafNode(n)?(s=n,n.max_path=0,n.max_path_terminus=n):(i+=n.max_path,s=n.max_path_terminus),(!n.parent.max_path||n.parent.max_path<i)&&(n.parent.max_path=i,n.parent.max_path_terminus=s)}}));var n=t.getRootNode(),s=0;if(n.children.forEach((function(t){if(t.max_path_terminus!==n.max_path_terminus){var i=t.max_path+e(t);i>=s&&(s=i)}})),n.max_path>s){s=.5*(s+n.max_path);for(var i=n.max_path_terminus;;){var a=e(i);if(!(a<=s))return{location:i,breakpoint:s/a};s-=a,i=i.parent}}return{location:n,breakpoint:0}},t.extract_dates=function(t,e,n=ct){return e=e||pt,t.traverse_and_compute((function(t){var s=e(t);if(s)try{t.data.date_value=n(s);var i=t.data.date_value.getFullYear(),a=new Date(i,0,1),r=new Date(i+1,0,1);return void(t.data.decimal_date_value=i+(t.data.date_value-a)/(r-a))}catch(t){}t.data.date_value=null,t.data.decimal_date_value=null})),t},t.fitRootToTip=function(t){var e=[],n=0,s=0;!function(t){t.traverse_and_compute((function(e){t.isLeafNode(e)&&(e.data.copy_number=1)}))}(t),dt(t),t.traverse_and_compute((function(n){t.isLeafNode(n)&&!r.isNull(n.data.decimal_date_value)&&e.push([n.data.decimal_date_value,n.data.rtta,n.data.copy_number])}));let i=ht(e);return t.traverse_and_compute((function(a){if(t.isLeafNode(a)&&!r.isNull(a.data.decimal_date_value)){lt(t,a,null,0,0),e=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&!r.isNull(n.data.decimal_date_value)&&e.push([n.data.decimal_date_value,n.data.rtta,n.data.copy_number])}));var o=ht(e),l=o.r2;l>n&&(n=l,s=a,i=o)}})),{root:s,fit:i}},t.getDistanceMatrix=function(t){let e=o.keys(t)[0],n=t[e].length;return o.mapValues(t,(e=>o.map(t,(t=>o.sum(o.map(o.range(n),(n=>e[n]!=t[n]&&"-"!=e[n]&&"-"!=t[n])))))))},t.inOrder=y,t.leftChildRightSibling=x,t.loadAnnotations=u,t.neighborJoining=function t(e,n,s){if(n<=2){let t=new rt(""),n=t.getNodes(),i=e[0][1]/2,a=t.createNode(s[0],[null,[i]]),r=t.createNode(s[1],[null,[i]]);return t.addChild(n,a),t.addChild(n,r),t}{let a=n,r=(i=e,o.map(i,o.sum)),l=function(t,e,n){let s=o.chunk(o.fill(Array(n*n),0),n);for(let i of o.range(n))for(let a of o.range(o.parseInt(i)+1,n))s[i][a]=(n-2)*t[i][a]-e[i]-e[a],s[a][i]=s[i][a];return s}(e,r,a),[h,d,c]=function(t,e){let n=-1,s=-1,i=1/0;for(let a of o.range(e))for(let r of o.range(n,e))t[a][r]<i&&(n=a,s=r,i=t[n][s]);return[n,s,i]}(l,a),u=function(t,e){let n=o.chunk(Array(e*e),e);for(let s of o.range(e))for(let i of o.range(parseInt(s)+1,e))n[s][i]=(t[s]-t[i])/(e-2),n[i][s]=n[s][i];return n}(r,a),p=(e[h][d]+u[h][d])/2,_=(e[h][d]-u[h][d])/2,f=o.concat(0,o.filter(o.map(o.range(n),(t=>{if(t!=h&&t!=d)return.5*(e[t][h]+e[t][d]-e[h][d])})),o.isNumber)),g=s[h],m=s[d],b="InternalNode0",v=o.filter(s,(t=>o.includes(t,"InternalNode")));if(v.length){let t=o.max(o.map(v,(t=>o.split(t,"InternalNode")[1])));b="InternalNode"+ ++t}s.unshift(b),e=_t(o.max([h,d]),e),(e=_t(o.min([h,d]),e)).unshift(f),o.each(o.range(1,n-1),(t=>e[t].unshift(f[t]))),o.remove(s,(t=>t==g||t==m));let y=t(e,a-1,s),x=y.createNode(g,[null,[p]]),w=y.createNode(m,[null,[_]]);if(y.getNodeByName(b)){let t=y.getNodeByName(b);y.addChild(t,x),y.addChild(t,w)}else{let t=y.createNode(b,[null,[0]]);y.addChild(y.getNodes(),t),y.addChild(t,x),y.addChild(t,w)}return y}var i},t.pairwise_distances=ot,t.parseAnnotations=c,t.parseFasta=function(t){let e=o.split(t,"\n");return o.chain(e).map(((t,e)=>t.startsWith(">")?e:-1)).filter((t=>-1!=t)).map(((t,n,s)=>o.slice(e,s[n],s[n+1]))).keyBy((t=>o.trim(t[0],">"))).mapValues((t=>o.tail(t).join(""))).value()},t.phylopart=function(t,e,n,s,i){s=r.isNumber(s)?s:1;var a=ot(t),o=t.getRootNode().children[0],l=Number.MAX_VALUE,h=Number.MAX_VALUE;if(!(n>0&&n<1))throw"Invalid percentile threshold in perform_phylopart";t.traverse_and_compute((function(e){t.isLeafNode(e)&&(e.cot_computed_length<l?(l<h&&(h=l),l=e.cot_computed_length):e.cot_computed_length<h&&(h=e.cot_computed_length))})),l+=h;var d=r.reduce(o.cot_path_to_leaves_below,(function(t,e){return e>t?e:t}),0)+r.reduce(o.cot_path_to_leaves_above,(function(t,e){return e>t?e:t}),0)+o.cot_computed_length-l;r.isUndefined(i)&&(i=Math.min(.001,d/100));var c=1+(d/i>>0);c>500&&(i=d/(c=500));var u=t.getRootNode();u.paths_to_leaves=new Array(a),r.each(u.children,(function(t){r.each(u.cot_path_to_leaves_below,(function(e,n){u.paths_to_leaves[n]=e+t.cot_computed_length}))})),t.traverse_and_compute((function(e){if(!t.isLeafNode(e)){e.histogram=new Array(c);for(var n=0;n<c;n++)e.histogram[n]=0;if(e.parent){var s=0;e.paths_to_leaves=[],r.each(e.cot_path_to_leaves_below,(function(t,n){e.paths_to_leaves[s++]=t}))}}delete e.cot_path_to_leaves_above,delete e.cot_path_to_leaves_below})),t.traverse_and_compute((function(e){if(!t.isLeafNode(e)){for(var n=0;n<e.paths_to_leaves.length;n++)for(var s=n+1;s<e.paths_to_leaves.length;s++){var a=e.paths_to_leaves[n]+e.paths_to_leaves[s];e.histogram[(a-l)/i>>0]++}e.leaf_count=e.paths_to_leaves.length,delete e.paths_to_leaves}}));for(var p=(a-1)*a/2*n,_=0;_<c-1&&p>u.histogram[_];_++)p-=u.histogram[_];var f=l+(_+(u.histogram[_]-p)/u.histogram[_])*i,g=[];return t.traverse_and_compute(r.noop,"pre-order",null,(function(n){if(!t.isLeafNode(n)){var a=r.isString(n.data.bootstrap_values)?+n.data.bootstrap_values:s;if(a>=e){for(var o=n.leaf_count*(n.leaf_count-1)*.25,h=0;h<c-1&&o>n.histogram[h];h++)o-=n.histogram[h];var d=l+(h+(n.histogram[h]-o)/n.histogram[h])*i;if(d<=f)return g.push({root:n,median:d,bootstrap:a}),!0}}return!1})),t.traverse_and_compute((function(e){t.isLeafNode(e)||"histogram"in e&&(delete e.histogram,delete e.leaf_count)})),r.each(g,(function(e){e.members=[],t.traverse_and_compute((function(n){t.isLeafNode(n)&&e.members.push(n)}),"post-order",e.root)})),g},t.phylotree=rt,t.postOrder=b,t.preOrder=v,t.rootToTip=dt,t.sackin=function(t){let e=t.getTips(),n=r.map(e,(t=>t.depth));return r.reduce(n,(function(t,e){return t+e}),0)},Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=phylotree.min.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "phylotree",
3
- "version": "1.0.20",
3
+ "version": "1.1.0",
4
4
  "main": "dist/phylotree.js",
5
5
  "unpkg": "dist/phylotree.js",
6
6
  "jsdelivr": "dist/phylotree.js",
@@ -26,7 +26,7 @@
26
26
  "d3": "6",
27
27
  "jquery": "3",
28
28
  "lodash": "^4.17.11",
29
- "moment": "^2.29.2",
29
+ "moment": "^2.29.4",
30
30
  "pretty-data": "^0.40.0",
31
31
  "rollup-plugin-node-resolve": "^5.2.0",
32
32
  "underscore": "1.x",
@@ -41,6 +41,7 @@
41
41
  "prettier": "^2.3.2",
42
42
  "rollup": "^2.50.6",
43
43
  "rollup-plugin-copy": "^3.3.0",
44
+ "rollup-plugin-execute": "^1.1.1",
44
45
  "rollup-plugin-terser": "^7.0.2",
45
46
  "rollup-watch": "^4.3.1",
46
47
  "tape": "5.2.2",
package/src/branches.js CHANGED
@@ -45,7 +45,6 @@ export function getBranchLengths() {
45
45
  export function defBranchLengthAccessor(_node, new_length) {
46
46
 
47
47
  let _node_data = _node.data;
48
- //let _node_data = _node;
49
48
 
50
49
  if (
51
50
  "attribute" in _node_data &&
@@ -226,11 +226,12 @@ function newickParser(nwk_str, options={}) {
226
226
  *
227
227
  * @param {Function} annotator - Function to apply to each node, determining
228
228
  * what label is written (optional).
229
+ * @param {Node} node - start at this node (default == root)
229
230
  * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
230
231
  */
231
232
 
232
233
  // TODO: break this out into two seperate functions
233
- export function getNewick(annotator) {
234
+ export function getNewick(annotator, root) {
234
235
 
235
236
  let self = this;
236
237
 
@@ -262,7 +263,7 @@ export function getNewick(annotator) {
262
263
 
263
264
  let element_array = [];
264
265
  annotator = annotator || "";
265
- nodeDisplay(this.nodes);
266
+ nodeDisplay(root || this.nodes);
266
267
 
267
268
  return element_array.join("")+";";
268
269
 
package/src/index.js CHANGED
@@ -10,6 +10,8 @@ export { default as extract_dates } from "./extract-dates";
10
10
  export { default as clusterPicker } from "./clustering/cluster-picker";
11
11
  export { default as phylopart } from "./clustering/phylopart";
12
12
 
13
+ export { default as parseFasta } from "./msa-parsers/fasta";
14
+ export { default as neighborJoining, getDistanceMatrix } from "./neighbor-join";
13
15
  export { parseAnnotations, loadAnnotations } from "./formats/nexus";
14
16
 
15
17
  export {
@@ -0,0 +1,18 @@
1
+ import * as _ from "lodash";
2
+
3
+ export default function parseFasta(fastaData) {
4
+
5
+
6
+ let sfasta = _.split(fastaData, "\n");
7
+
8
+ let seqs = _.chain(sfasta)
9
+ .map((d, i) => (d.startsWith(">") ? i : -1))
10
+ .filter((d) => d != -1)
11
+ .map((d, i, c) => _.slice(sfasta, c[i], c[i + 1]))
12
+ .keyBy((d) => _.trim(d[0], ">"))
13
+ .mapValues((d) => _.tail(d).join(""))
14
+ .value();
15
+
16
+ return seqs;
17
+
18
+ }
@@ -0,0 +1,196 @@
1
+ import * as _ from "lodash";
2
+ import { default as phylotree } from "./main";
3
+
4
+ function remove(i, D) {
5
+ let dNew = [];
6
+
7
+ for (let j of _.range(D.length)) {
8
+ if (j != i) {
9
+ let dNewRow = [];
10
+ for (let k of _.range(D[j].length)) {
11
+ if (k != i) {
12
+ dNewRow.push(D[j][k]);
13
+ }
14
+ }
15
+ dNew.push(dNewRow);
16
+ }
17
+ }
18
+
19
+ return dNew;
20
+ }
21
+
22
+ function getDPrime(distanceMatrix, totalDistances, N) {
23
+ let DPrime = _.chunk(_.fill(Array(N * N), 0), N);
24
+ for (let i of _.range(N)) {
25
+ for (let j of _.range(_.parseInt(i) + 1, N)) {
26
+ DPrime[i][j] =
27
+ (N - 2) * distanceMatrix[i][j] - totalDistances[i] - totalDistances[j];
28
+ DPrime[j][i] = DPrime[i][j];
29
+ }
30
+ }
31
+ return DPrime;
32
+ }
33
+
34
+ function ijMinDPrime(dPrime, N) {
35
+ let i = -1;
36
+ let j = -1;
37
+ let minD = Infinity;
38
+ for (let ii of _.range(N)) {
39
+ for (let jj of _.range(i, N)) {
40
+ if (dPrime[ii][jj] < minD) {
41
+ i = ii;
42
+ j = jj;
43
+ minD = dPrime[i][j];
44
+ }
45
+ }
46
+ }
47
+ return [i, j, minD];
48
+ }
49
+
50
+ function createDelta(totalDistances, N) {
51
+ let deltaMatrix = _.chunk(Array(N * N), N);
52
+
53
+ for (let i of _.range(N)) {
54
+ for (let j of _.range(parseInt(i) + 1, N)) {
55
+ deltaMatrix[i][j] = (totalDistances[i] - totalDistances[j]) / (N - 2);
56
+ deltaMatrix[j][i] = deltaMatrix[i][j];
57
+ }
58
+ }
59
+
60
+ return deltaMatrix;
61
+ }
62
+
63
+ export function getDistanceMatrix(seqs) {
64
+ // Gaps are masked
65
+
66
+ let initKey = _.keys(seqs)[0];
67
+ let seqLength = seqs[initKey].length;
68
+
69
+ return _.mapValues(seqs, (seq) =>
70
+ _.map(seqs, (seq2) =>
71
+ _.sum(
72
+ _.map(
73
+ _.range(seqLength),
74
+ (i) => seq[i] != seq2[i] && seq[i] != "-" && seq2[i] != "-"
75
+ )
76
+ )
77
+ )
78
+ );
79
+ }
80
+
81
+ function getTotalDistances(distanceMatrix) {
82
+ return _.map(distanceMatrix, _.sum);
83
+ }
84
+
85
+ /**
86
+ * Create a neighbor joining tree from a distance matrix
87
+ * See test/neighbor-join-test.js for a working example
88
+ *
89
+ * @param {Array} distanceMatrixArr The NxN distance matrix.
90
+ * const D = [
91
+ * [0, 5, 9, 9, 8],
92
+ * [5, 0, 10, 10, 9],
93
+ * [9, 10, 0, 8, 7],
94
+ * [9, 10, 8, 0, 3],
95
+ * [8, 9, 7, 3, 0]
96
+ * ];
97
+ *
98
+ * @param {Number} n The dimension of the distanceMatrixArr.
99
+ * @param {Array} nodeList The names of each row in the distanceMatrix
100
+ * @returns The neighbor joining new tree.
101
+ */
102
+ export default function neighborJoining(distanceMatrixArr, n, nodeList) {
103
+ if (n <= 2) {
104
+ let tree = new phylotree("");
105
+
106
+ //T.link(nodeList[0],nodeList[1],D[0][1])
107
+
108
+ let newNode = tree.getNodes();
109
+ // Get root
110
+ let distance = distanceMatrixArr[0][1] / 2;
111
+
112
+ let nodeA = tree.createNode(nodeList[0], [null, [distance]]);
113
+ let nodeB = tree.createNode(nodeList[1], [null, [distance]]);
114
+
115
+ //// Add the children to the newly created node
116
+ tree.addChild(newNode, nodeA);
117
+ tree.addChild(newNode, nodeB);
118
+
119
+ return tree;
120
+ } else {
121
+ let N = n;
122
+ let totalDistances = getTotalDistances(distanceMatrixArr);
123
+ let dPrime = getDPrime(distanceMatrixArr, totalDistances, N);
124
+ let [i, j, minD] = ijMinDPrime(dPrime, N);
125
+ let deltaMatrix = createDelta(totalDistances, N);
126
+ let limbLengthI = (distanceMatrixArr[i][j] + deltaMatrix[i][j]) / 2;
127
+ let limbLengthJ = (distanceMatrixArr[i][j] - deltaMatrix[i][j]) / 2;
128
+ let newRow = _.concat(
129
+ 0,
130
+ _.filter(
131
+ _.map(_.range(n), (k) => {
132
+ if (k != i && k != j) {
133
+ return (
134
+ 0.5 *
135
+ (distanceMatrixArr[k][i] +
136
+ distanceMatrixArr[k][j] -
137
+ distanceMatrixArr[i][j])
138
+ );
139
+ }
140
+ }),
141
+ _.isNumber
142
+ )
143
+ );
144
+
145
+ let nodeI = nodeList[i];
146
+ let nodeJ = nodeList[j];
147
+
148
+ // Get all nodes of type InternalNode{x} and increment number.
149
+ // If there are none, start with InternalNode0
150
+ let m = "InternalNode0";
151
+ let internalNodes = _.filter(nodeList, (x) =>
152
+ _.includes(x, "InternalNode")
153
+ );
154
+
155
+ if (internalNodes.length) {
156
+ let highestNum = _.max(
157
+ _.map(internalNodes, (label) => _.split(label, "InternalNode")[1])
158
+ );
159
+ m = "InternalNode" + ++highestNum;
160
+ }
161
+
162
+ nodeList.unshift(m);
163
+
164
+ distanceMatrixArr = remove(_.max([i, j]), distanceMatrixArr);
165
+ distanceMatrixArr = remove(_.min([i, j]), distanceMatrixArr);
166
+
167
+ distanceMatrixArr.unshift(newRow);
168
+
169
+ _.each(_.range(1, n - 1), (l) => distanceMatrixArr[l].unshift(newRow[l]));
170
+
171
+ // Remove from nodeList
172
+ _.remove(nodeList, (n) => n == nodeI || n == nodeJ);
173
+ let tree = neighborJoining(distanceMatrixArr, N - 1, nodeList);
174
+
175
+ let treeNodeI = tree.createNode(nodeI, [null, [limbLengthI]]);
176
+ let treeNodeJ = tree.createNode(nodeJ, [null, [limbLengthJ]]);
177
+
178
+ // If the node doesn't exist, create. Otherwise, reassign the length
179
+ if (tree.getNodeByName(m)) {
180
+ let internalNode = tree.getNodeByName(m);
181
+ tree.addChild(internalNode, treeNodeI);
182
+ tree.addChild(internalNode, treeNodeJ);
183
+ } else {
184
+ let newNode = tree.createNode(m, [null, [0]]);
185
+ tree.addChild(tree.getNodes(), newNode);
186
+ // Add the children to the newly created node
187
+ tree.addChild(newNode, treeNodeI);
188
+ tree.addChild(newNode, treeNodeJ);
189
+ }
190
+
191
+ // Set negative to 0 and add distance to other limblength
192
+ return tree;
193
+ }
194
+
195
+ return null;
196
+ }
package/src/nodes.js CHANGED
@@ -2,34 +2,36 @@ import * as _ from "underscore";
2
2
 
3
3
  // These methods are part of the Phylotree object
4
4
 
5
- export function graftANode(graft_at, new_child, new_parent, lengths) {
5
+ export function graftANode(graftAt, newChild, newParent, lengths) {
6
6
 
7
7
  let nodes = this.nodes.descendants();
8
8
 
9
- if (graft_at.parent) {
10
- let node_index = nodes.indexOf(graft_at);
9
+ if (graftAt.parent) {
11
10
 
12
- if (node_index >= 0) {
13
- let parent_index = graft_at.parent.children.indexOf(graft_at);
11
+ let nodeIndex = nodes.indexOf(graftAt);
14
12
 
15
- let new_split = {
16
- name: new_parent,
17
- parent: graft_at.parent,
13
+ if (nodeIndex >= 0) {
14
+
15
+ let parentIndex = graftAt.parent.children.indexOf(graftAt);
16
+
17
+ let newSplit = {
18
+ name: newParent,
19
+ parent: graftAt.parent,
18
20
  attribute: lengths ? lengths[2] : null,
19
- original_child_order: graft_at["original_child_order"]
21
+ original_child_order: graftAt["original_child_order"]
20
22
  },
21
- new_node = {
22
- name: new_child,
23
- parent: new_split,
23
+ newNode = {
24
+ name: newChild,
25
+ parent: newSplit,
24
26
  attribute: lengths ? lengths[1] : null,
25
27
  original_child_order: 2
26
28
  };
27
29
 
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;
30
+ newSplit["children"] = [graftAt, newNode];
31
+ graftAt["parent"].children[parentIndex] = newSplit;
32
+ graftAt.parent = newSplit;
33
+ graftAt["attribute"] = lengths ? lengths[0] : null;
34
+ graftAt["original_child_order"] = 1;
33
35
  }
34
36
  }
35
37
 
@@ -37,6 +39,30 @@ export function graftANode(graft_at, new_child, new_parent, lengths) {
37
39
 
38
40
  }
39
41
 
42
+ export function addChild(parent, child) {
43
+
44
+ if(parent.children) {
45
+ parent.children.push(child);
46
+ } else {
47
+ parent["children"] = [child];
48
+ }
49
+
50
+ return parent;
51
+
52
+ }
53
+
54
+ export function createNode(name, lengths) {
55
+
56
+ return {
57
+ data: {
58
+ name: name,
59
+ attribute: lengths ? lengths[1] : null
60
+ },
61
+ parent: '',
62
+ };
63
+
64
+ }
65
+
40
66
  /**
41
67
  * Delete a given node.
42
68
  *
@@ -157,9 +183,9 @@ export function getNodeByName(name) {
157
183
  export function assignAttributes(attributes) {
158
184
  //return nodes;
159
185
  // 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];
186
+ _.each(this.nodes.descendants(), function(d) {
187
+ if (d.data && (d.data.name in attributes)) {
188
+ d["annotations"] = attributes[d.data.name];
163
189
  }
164
190
  });
165
191
  }
@@ -200,7 +200,7 @@ export function nodeDropdownMenu(node, container, phylotree, options, event) {
200
200
  .append("a")
201
201
  .attr("class", "dropdown-item")
202
202
  .attr("tabindex", "-1")
203
- .text(constant(d[0])(node)) // eslint-disable-line
203
+ .text((d[0])(node)) // eslint-disable-line
204
204
  .on("click", _.partial(d[1], node));
205
205
  });
206
206
  }