UNPKG

phylotree

Version:

A JavaScript library for developing applications and interactive visualizations involving [phylogenetic trees](https://en.wikipedia.org/wiki/Phylogenetic_tree), written as an extension of the [D3](http://d3js.org) [hierarchy layout](https://github.com/d3/

1 lines 59.2 kB
!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")}function h(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}var d=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])}))},selectAllDescendants:h});function c(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 u(t,e){let n=this;t||(t=t=>"");let s=[];return t=t||"",function e(i){if(i.notshown)return;if(l(i)||(s.push("("),i.children.forEach((function(t,n){n&&s.push(","),e(t)})),s.push(")")),"root"!==i.data.name){const t=i.data.name.replaceAll("'","''");/\W/.test(t)?s.push("'"+t+"'"):s.push(t)}s.push(t(i));let a=n.branch_length_accessor(i);void 0!==a&&s.push(":"+a)}(e||this.nodes),s.join("")+";"}function p(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 _(t,e,n){r.each(t.getTips(),(t=>{t.data.test=n.matrix[t.data.name]}))}function f(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"))),c(i[0])}var g=Object.freeze({__proto__:null,parseAnnotations:p,loadAnnotations:_,default:f});function m(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]=m(a);else{if(void 0===e[r].push){var o=e[r];e[r]=[],e[r].push(o)}e[r].push(m(a))}}return e}var b=function(t,e){var n;return(n=(t=m(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 v={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:b,nexus:f,nwk:c,nhx:c,beast:function(t,e){e.left_delimiter="[",e.right_delimiter="]";const n=c(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 y(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 x(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 w(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 N(t){return y(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 z(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 k=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 E(t){return t.y}function S(t){return t.x}function M(t,e,n){return{x:n+t*Math.sin(e),y:n+t*Math.cos(e)}}function A(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=M(t.radius,t.angle,s);return t.x=r.x,t.y=r.y,t}function L(t,e){var n=M(e[0].radius,e[0].angle,t),s=M(e[0].radius,e[1].angle,t);return"M "+E(n)+","+S(n)+" A "+e[0].radius+","+e[0].radius+" 0,0, "+(e[1].angle>e[0].angle?1:0)+" "+E(s)+","+S(s)+" L "+E(e[1])+","+S(e[1])}function T(t,e,n){var s=M(t.target.radius+(t.source.radius-t.target.radius)*e,t.target.angle,n);return{x:E(s),y:S(s)}}var C=a.line().x((function(t){return E(t)})).y((function(t){return S(t)})).curve(a.curveStepBefore);function O(t,e){return{x:E(t.target)+(E(t.source)-E(t.target))*e,y:S(t.target)}}function j(t){return t.tag||!1}function P(t,e){return t[e]||!1}const R={"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 B(t){return arguments.length?(B="string"==typeof t&&"equal"==t?function(t){return 1}:t,this):B}var I={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:R,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 B},predefined_selecters:I,selectionCallback:function(t){return t?(this.selectionCallback=t,this):this.selectionCallback}});function U(t){return!(t.hidden||t.notshown)}function D(t){return t.notshown}function q(t){return t.hasHiddenNodes||!1}function V(t){return t.collapsed||!1}function F(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 W(t){return l(t=t.data)?t.name||"":this.showInternalName(t)?t.name:""}var X=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)&&!V(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=R[l(t)?"node":"internal-node"];return j(t)&&(e+=" "+R["tagged-node"]),P(t,this.selection_attribute_name)&&(e+=" "+R["selected-node"]),t.parent||(e+=" "+R["root-node"]),(V(t)||q(t))&&(e+=" "+R["collapsed-node"]),e},nodeVisible:U,nodeNotshown:D,hasHiddenNodes:q,isNodeCollapsed:V,nodeCssSelectors:F,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)||P(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:W,nodeLabel:function(t){return arguments.length?(this._nodeLabel=t||W,this.update(),this):this._nodeLabel}});function G(t){return[t.clade].reduce((function(t,e,n,s){return t+"path."+e+(n<s.length-1?",":"")}),"")}var $=Object.freeze({__proto__:null,cladeCssSelectors:G,updateCollapsedClades:function(t){let e=this.svg.selectAll("."+this.css_classes["tree-container"]);var n=0;let s=e.selectAll(G(this.css_classes)).data(this.phylotree.nodes.descendants().filter(V),(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 Y(t){return!(t.target.hidden||t.target.notshown)}function J(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 K=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=R.branch;return j(t)&&(e+=" "+R["tagged-branch"]),P(t,this.selection_attribute_name)&&(e+=" "+R["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+(j(e)?1:0)}),0),this.countUpdate(this,t,this.countHandler())}},edgeVisible:Y,edgeCssSelectors:J,placeAlongAnEdge:function(t,e){return this.edge_placer(t,e)}});let Z="phylotree.event";function Q(t){var e=new CustomEvent(Z,{detail:["refresh",t]});document.dispatchEvent(e)}function tt(t,e){var n=new CustomEvent(Z,{detail:["countUpdate",e,t.countHandler()]});document.dispatchEvent(n)}function et(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 nt(){document.addEventListener(Z,et,!1)}var st=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("."+R["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:Q,countUpdate:tt,d3PhylotreeTriggerLayout:function(t){var e=new CustomEvent(Z,{detail:["layout",t,t.layoutHandler()]});document.dispatchEvent(e)},d3PhylotreeEventListener:et,d3PhylotreeAddEventListener:nt,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 it="d3_layout_phylotree_context_menu";var at=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",it).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(V(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()}))),q(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(I),t))return;t=I[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||Q(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||Q(this),this.countHandler&&((a={})[e]=this.links.reduce((function(t,n){return t+(n[e]?1:0)}),0),tt(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 rt(t){return function(){return t}}class ot{constructor(t,e={}){this.css_classes=R,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.scale_bar_font_size=12,this.draw_branch=C,this.draw_scale_bar=null,this.edge_placer=O,this.count_listener_handler=function(){},this.layout_listener_handler=function(){},this.node_styler=void 0,this.edge_styler=void 0,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,"font-size":14,"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:rt(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.font_size=this.options["font-size"],this.offsets=[0,this.font_size/2],this.shown_font_size=this.font_size,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(),nt()}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){V(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("."+R["tree-container"]).data([0]);if(s=s.enter().append("g").attr("class",R["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("."+R["tree-scale-bar"]).data([0]);t.enter().append("g").attr("class",R["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("."+R["tree-scale-bar"]).remove();s=this.svg.selectAll("."+R["tree-container"]).data([0]),this.updateCollapsedClades(t);let i=s.selectAll(J(R)).data(this.links.filter(Y),(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(F(R)).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=E(t),t.screen_y=S(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("."+R["tree-selection-brush"]).data([0]).enter().insert("g",":first-child").attr("class",R["tree-selection-brush"]),d=a.brush().on("brush",((t,e)=>{var n=t.selection,s=this.links.filter(Y).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("."+R["tree-container"]).attr("transform",(e=>t.transform)),a.select("."+R["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(D(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(V(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(L,this.radial_center),this.edge_placer=T;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(L,this.radial_center);let d=1;h&&(d=l/(l+h),this.radius*=d),this.phylotree.nodes.each((t=>{if(A(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=A(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=C,this.edge_placer=O,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=rt(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 R)n in t&&t[n]!=R[n]&&(R[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 R)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(J(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(ot.prototype,$),r.extend(ot.prototype,X),r.extend(ot.prototype,K),r.extend(ot.prototype,st),r.extend(ot.prototype,at),r.extend(ot.prototype,H);let lt=class{constructor(t,e={}){this.newick_string="",this.nodes=[],this.links=[],this.parsed_tags=[],this.partitions=[],this.branch_length_accessor=z,this.branch_length=z,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 v?s=v[n](t,e):i.logger.error("type "+n+" not in registry! Available types are "+r.keys(v));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=b(t):(this.newick_string=t,s=c(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){x(e,t,s)}:"in-order"==e?function(e){w(e,t,s)}:function(e){r.isUndefined(e)||y(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 ot(this,t),this.display}};function ht(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 dt(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?dt(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&&dt(t,e.parent,e,s,i)}function ct(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 ut(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}lt.prototype.isLeafNode=l,lt.prototype.selectAllDescendants=h,lt.prototype.mrca=function(t){var e;return t=t.map((function(t){return"string"==typeof t?t:t.data.name})),this.traverse_and_compute((function(n){n.children?n.parent?(n.data.mrca=r.union(...n.descendants().map((t=>t.data.mrca))),e||n.data.mrca.length!=t.length||(e=n)):e||(e=n):n.data.mrca=r.intersection([n.data.name],t)})),e},lt.prototype.hasBranchLengths=function(){let t=this.branch_length;return!!t&&r.every(this.nodes.descendants(),(function(e){return!e.parent||!r.isUndefined(t(e))}))},lt.prototype.getBranchLengths=function(){let t=this.branch_length;return r.map(this.nodes.descendants(),(e=>t(e)))},lt.prototype.branchName=function(t){return arguments.length?(this.nodeLabel=t,this):this.nodeLabel},lt.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},lt.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},lt.prototype.getNewick=u,lt.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},lt.prototype.setBranchLength=function(t){return arguments.length?(this.branch_length_accessor=t||z,this):this.branch_length_accessor},lt.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]=