API.md

March 14, 2026 · View on GitHub

Modules

render/event-emitter

Event emitter mixin for phylotree TreeRender Provides on/off/emit pattern for tree events

render/selection-sets

Multi-set selection management for phylotree

Classes

Phylotree

An instance of a phylotree. Sets event listeners, parses tags, and creates links that represent branches.

Functions

getBranchLengths()Array

Returns branch lengths

setBranchLength(attr)Object

Get or set branch length accessor.

normalize()Phylotree

Normalizes branch lengths to range [0,1]

scale(scale_by)Phylotree

Scales branch lengths using a custom transformation function

branchName(attr)

Get or set branch name accessor.

clusterPicker(tree, bootstrap_thresold, diameter_threshold, root_node, missing_bootstrap_value)

Implements a linear time / space version of the Cluster picker algorithm

newickParser(nwk_str)Object

Parses a Newick string into an equivalent JSON representation that is suitable for consumption by hierarchy.

Optionally accepts bootstrap values. Currently supports Newick strings with or without branch lengths, as well as tagged trees such as (a,(b{TAG},(c{TAG},d{ANOTHERTAG})))

getNewick(annotator, node)String

Return Newick string representation of a phylotree.

getTaggedNewick(options)string

Generate Newick string with selection tags.

loadAnnotations(tree, NEXUS)Object

Loads annotations from a nexus-formatted buffer and annotates existing tree nodes appropriately.

mrca()

Return most recent common ancestor of a pair of nodes.

computeMidpoint(tree)Object

Compute midpoint of a phylogenetic tree

deleteANode(The)

Delete a given node.

getTips()Array

Get the tips of the tree

getInternals()Array

Get the internal nodes of the tree

getRootNode()

Get the root node.

getNodes()Array

Get an array of all nodes.

getNodeByName(name)Node

Get a node by name.

assignAttributes(attributes)

Add attributes to nodes. New attributes will be placed in the annotations key of any nodes that are matched.

isLeafNode(A)Bool

Determine if a given node is a leaf node.

updateKeyName(old_key, new_key)

Update a given key name in each node.

selectAllDescendants(node, terminal, internal)Array

Select all descendents of a given node, with options for selecting terminal/internal nodes.

toggleCollapse(node)Phylotree

Toggle collapsed view of a given node. Either collapses a clade into a smaller blob for viewing large trees, or expands a node that was previously collapsed.

modifySelection(node_selecter, attr, place, skip_refresh, mode)

Modify the current selection, via functional programming.

getSelection()Array

Get nodes which are currently selected.

selectAllDescendants(node, terminal, internal)Array

Select all descendents of a given node, with options for selecting terminal/internal nodes.

selectionCallback(callback)

Getter/setter for the selection callback. This function is called every time the current selection is modified, and its argument is an array of nodes that make up the current selection.

selectNodes(names)this

Select nodes by their names.

deselectNodes(names)this

Deselect nodes by their names.

clearSelection()this

Clear all current selection.

nodeSpan(attr)

Get or set the current node span. If setting, the argument should be a function of a node which returns a number, so that node spans can be determined dynamically. Alternatively, the argument can be the string "equal", to give all nodes an equal span.

nodeLabel(attr)

Get or set nodeLabel accessor.

nodeBubbleSize(A)Float

Return the bubble size of the current node.

selectionLabel(attr)

Getter/setter for the selection label. Useful when allowing users to make multiple selections.

nodeSpan(attr)

Get or set the current node span. If setting, the argument should be a function of a node which returns a number, so that node spans can be determined dynamically. Alternatively, the argument can be the string "equal", to give all nodes an equal span.

selectionCallback(callback)

Getter/setter for the selection callback. This function is called every time the current selection is modified, and its argument is an array of nodes that make up the current selection.

countLeaves(node)Number

Count the number of leaf nodes in a subtree.

computeUnrootedLayout(root, scales, width, height, labelPad)

Compute unrooted (equal-angle) layout coordinates for all nodes.

The algorithm allocates 2π of angular space at the root, then recursively assigns each child subtree angular space proportional to its leaf count. Each node is placed at parent_position + branch_length * (cos(angle), sin(angle)).

After computing raw positions, coordinates are normalized to fit within the given width × height.

equalAngle(node, startAngle, arcSize)

Recursive equal-angle layout.

drawUnrootedEdge(points)String

Draw a straight line edge between two nodes (for unrooted layout).

unrootedSegmentPlacer(edge, where)Object

Place a label along an unrooted edge via linear interpolation.

reroot(node, if)Phylotree

Reroot the tree on the given node.

leftChildRightSibling(tree)Object

Traverses a tree that represents left-child right-sibling

render/event-emitter

Event emitter mixin for phylotree TreeRender Provides on/off/emit pattern for tree events

render/event-emitter.on(eventName, callback) ⇒ this

Register an event listener

Kind: static method of render/event-emitter
Returns: this - For chaining

ParamTypeDescription
eventNamestringEvent name (nodeClick, branchClick, nodeHover, contextMenu, rendered, selectionChange, collapsed, rerooted)
callbackfunctionHandler function

Example

tree.on('nodeClick', (node, event) => console.log(node.data.name));
tree.on('selectionChange', (selectedNodes) => updatePanel(selectedNodes));

render/event-emitter.off(eventName, callback) ⇒ this

Remove an event listener

Kind: static method of render/event-emitter
Returns: this - For chaining

ParamTypeDescription
eventNamestringEvent name
callbackfunctionHandler to remove (must be same reference)

Example

const handler = (node) => console.log(node);
tree.on('nodeClick', handler);
tree.off('nodeClick', handler);

render/selection-sets

Multi-set selection management for phylotree

render/selection-sets.setActiveSet(name) ⇒ this

Set the active selection set. Clicks will add nodes to this set.

Kind: static method of render/selection-sets
Returns: this - For chaining.

ParamTypeDescription
namestringName of the set to activate.

Example

tree.setActiveSet('foreground');

render/selection-sets.getActiveSet() ⇒ string | null

Get the currently active selection set name.

Kind: static method of render/selection-sets
Returns: string | null - Active set name or null if not in multi-set mode.
Example

const activeSet = tree.getActiveSet(); // 'foreground'

render/selection-sets.getSetMembers(setName) ⇒ Array.<Node>

Get all members (nodes) of a selection set.

Kind: static method of render/selection-sets
Returns: Array.<Node> - Array of nodes in the set.

ParamTypeDescription
setNamestringName of the selection set.

Example

const foregroundNodes = tree.getSetMembers('foreground');

render/selection-sets.addToSet(node, setName) ⇒ this

Add a node to a selection set.

Kind: static method of render/selection-sets
Returns: this - For chaining.

ParamTypeDescription
nodeNode | stringNode object or node name.
setNamestringTarget set name.

Example

tree.addToSet('HUMAN', 'foreground');
tree.addToSet(nodeObject, 'background');

render/selection-sets.removeFromSet(node, setName) ⇒ this

Remove a node from a selection set.

Kind: static method of render/selection-sets
Returns: this - For chaining.

ParamTypeDescription
nodeNode | stringNode object or node name.
setNamestringTarget set name.

Example

tree.removeFromSet('HUMAN', 'foreground');

render/selection-sets.isInSet(node, setName) ⇒ boolean

Check if a node belongs to a specific set.

Kind: static method of render/selection-sets
Returns: boolean - True if node is in the set.

ParamTypeDescription
nodeNodeThe node to check.
setNamestringThe set name to check.

render/selection-sets.getNodeSet(node) ⇒ string | null

Get the set name a node belongs to.

Kind: static method of render/selection-sets
Returns: string | null - The set name or null if not in any set.

ParamTypeDescription
nodeNodeThe node to check.

Phylotree

An instance of a phylotree. Sets event listeners, parses tags, and creates links that represent branches.

Kind: global class

new Phylotree(nwk, options)

Returns: Phylotree - phylotree - itself, following the builder pattern.

ParamTypeDescription
nwkObjectA Newick string, PhyloXML string, or hierarchical JSON representation of a phylogenetic tree.
optionsObject- boostrap_values - type - format type

Example

// Create a simple phylotree from a Newick string
const newick = "((A:0.1,B:0.2):0.05,C:0.3)";
const tree = new Phylotree(newick);

Example

// Create a phylotree with options
const tree = new Phylotree(newick, {
  bootstrap_values: true,
  type: "newick"
});

Example

// Create from hierarchical JSON
const jsonTree = {
  name: "root",
  children: [
    { name: "A", length: 0.1 },
    { name: "B", length: 0.2 }
  ]
};
const tree = new Phylotree(jsonTree);

phylotree.traverse_and_compute(callback, traversal_type, root_node, backtrack)

Traverse the tree in a prescribed order, and compute a value at each node.

Kind: instance method of Phylotree

ParamTypeDescription
callbackfunctionA function to be called on each node.
traversal_typeStringEither "pre-order" or "post-order" or "in-order".
root_nodeNodestart traversal here, if provided, otherwise start at root
backtrackfunction; if provided, then at each node n, backtrack (n) will be called, and if it returns TRUE, traversal will NOT continue past into this node and its children

Example

// Count all nodes in the tree
let nodeCount = 0;
tree.traverse_and_compute(function(node) {
  nodeCount++;
});
console.log(`Tree has ${nodeCount} nodes`);

Example

// Find maximum depth in post-order traversal
tree.traverse_and_compute(function(node) {
  if (!node.children) {
    node.depth = 0;
  } else {
    node.depth = Math.max(...node.children.map(c => c.depth)) + 1;
  }
}, "post-order");

Example

// Add custom attributes to leaf nodes only
tree.traverse_and_compute(function(node) {
  if (!node.children) {
    node.data.isLeaf = true;
  }
});

phylotree.render(options) ⇒ TreeRender

Render the phylotree to a DOM element. Warning: Requires DOM!

Kind: instance method of Phylotree
Returns: TreeRender - The display object for further customization

ParamTypeDescription
optionsObjectRendering options including container, dimensions, and styling

Example

// Basic rendering to a div element
const tree = new Phylotree(newick);
tree.render({
  container: "#tree-container",
  width: 800,
  height: 600
});

Example

// Render with custom styling options
const display = tree.render({
  container: d3.select("#my-tree"),
  width: 1000,
  height: 800,
  'left-right-spacing': 'fit-to-size',
  'top-bottom-spacing': 'fit-to-size',
  'show-scale': true,
  selectable: true,
  collapsible: true
});

Example

// Render radial tree layout
tree.render({
  container: "#radial-tree",
  layout: "radial",
  width: 600,
  height: 600
});

getBranchLengths() ⇒ Array

Returns branch lengths

Kind: global function
Returns: Array - array of branch lengths

setBranchLength(attr) ⇒ Object

Get or set branch length accessor.

Kind: global function
Returns: Object - The branch length accessor if getting, or the current this if setting.

ParamTypeDescription
attrfunctionEmpty if getting, or new branch length accessor if setting.

Example

// Set a custom branch length accessor
const tree = new Phylotree(newick);
tree.setBranchLength(function(node) {
  // Use a transformed branch length
  return Math.log(node.data.attribute + 1);
});

Example

// Set all branch lengths to 1 (equal branch lengths)
tree.setBranchLength(function(node) {
  return 1;
});

Example

// Get the current branch length accessor
const currentAccessor = tree.setBranchLength();

normalize() ⇒ Phylotree

Normalizes branch lengths to range [0,1]

Kind: global function
Returns: Phylotree - The current phylotree instance
Example

// Normalize all branch lengths to 0-1 range
const tree = new Phylotree(newick);
tree.normalizeBranchLengths();
// Now all branch lengths are between 0 and 1

Example

// Useful for comparing trees with different scales
const tree1 = new Phylotree(newick1).normalizeBranchLengths();
const tree2 = new Phylotree(newick2).normalizeBranchLengths();
// Both trees now have comparable branch length scales

scale(scale_by) ⇒ Phylotree

Scales branch lengths using a custom transformation function

Kind: global function
Returns: Phylotree - The current phylotree instance

ParamTypeDescription
scale_byfunctionFunction that transforms each branch length

Example

// Scale all branch lengths by a constant factor
const tree = new Phylotree(newick);
tree.scaleBranchLengths(function(length) {
  return length * 2; // Double all branch lengths
});

Example

// Apply logarithmic transformation
tree.scaleBranchLengths(function(length) {
  return Math.log10(length + 1);
});

Example

// Convert to time units (assuming substitutions per site)
const mutationRate = 1e-8;
tree.scaleBranchLengths(function(length) {
  return length / mutationRate; // Convert to years
});

branchName(attr) ⇒

Get or set branch name accessor.

Kind: global function
Returns: The nodeLabel accessor if getting, or the current this if setting.

ParamTypeDescription
attrfunction(Optional) If setting, a function that accesses a branch name from a node.

clusterPicker(tree, bootstrap_thresold, diameter_threshold, root_node, missing_bootstrap_value) ⇒

Implements a linear time / space version of the Cluster picker algorithm

Kind: global function
Returns: an array of clusters, where cluster = { 'root' : [root node of cluster], 'members' : [list of leaf. nodes], 'diameter' : max distance in the cluster, 'bootstrap' : bootstrap support at the root node }

ParamDescription
tree- the tree object
bootstrap_thresold- value in [0,1] that sets the stringency of bootstrap support
diameter_threshold- value >=0 that defines the maximum allowable pairwise distance in a cluster
root_node- if specified, traverse the tree starting here (useful for only looking at parts of the tree), tree root by default
missing_bootstrap_value- if a branch is missing bootstrap support value, use this value instead (1.0 by default)

newickParser(nwk_str) ⇒ Object

Parses a Newick string into an equivalent JSON representation that is suitable for consumption by hierarchy.

Optionally accepts bootstrap values. Currently supports Newick strings with or without branch lengths, as well as tagged trees such as (a,(b{TAG},(c{TAG},d{ANOTHERTAG})))

Kind: global function
Returns: Object - An object with keys json and error.

ParamTypeDescription
nwk_strStringA string representing a phylogenetic tree in Newick format.
bootstrap_values.Object

Example

// Parse a simple Newick tree with branch lengths
const newick = "((A:0.1,B:0.2):0.05,C:0.3);";
const result = newickParser(newick);
if (result.error) {
  console.error("Parse error:", result.error);
} else {
  console.log("Parsed tree:", result.json);
}

Example

// Parse tree with tagged branches
const taggedNewick = "((A:0.1,B{Foreground}:0.2){Foreground}:0.05,C:0.3);";
const result = newickParser(taggedNewick);
// Tagged branches will have annotation properties

Example

// Parse tree with custom delimiters
const nhxNewick = "((A:0.1,B:0.2[&&NHX:S=species1:D=Y]):0.05,C:0.3);";
const result = newickParser(nhxNewick, {
  left_delimiter: '[',
  right_delimiter: ']'
});

getNewick(annotator, node) ⇒ String

Return Newick string representation of a phylotree.

Kind: global function
Returns: String - newick - Phylogenetic tree serialized as a Newick string.

ParamTypeDescription
annotatorfunctionFunction to apply to each node, determining what label is written (optional).
nodeNodestart at this node (default == root)

Example

// Export tree to basic Newick format
const tree = new Phylotree(newick);
const exportedNewick = tree.getNewick();
console.log(exportedNewick); // "((A:0.1,B:0.2):0.05,C:0.3);"

Example

// Export with custom node annotations
const annotatedNewick = tree.getNewick(function(node) {
  if (node.data.selected) {
    return "{SELECTED}";
  }
  return "";
});

Example

// Export a subtree starting from a specific node
const nodeOfInterest = tree.getNodeByName("A");
const subtreeNewick = tree.getNewick(null, nodeOfInterest);

getTaggedNewick(options) ⇒ string

Generate Newick string with selection tags.

Kind: global function
Returns: string - Tagged Newick string.

ParamTypeDefaultDescription
optionsObjectConfiguration options.
[options.tag]string"'Foreground'"Tag name for selected nodes (single selection mode).
[options.multiSet]booleanfalseUse multi-set mode tags (uses set names as tags).

Example

// Basic tagged output (uses selection state)
const tagged = tree.getTaggedNewick();
// Returns: "((A{Foreground}:0.1,B:0.2):0.05,C{Foreground}:0.3);"

Example

// Custom tag name
const tagged = tree.getTaggedNewick({ tag: 'TEST' });
// Returns: "((A{TEST}:0.1,B:0.2):0.05,C{TEST}:0.3);"

Example

// Multi-set mode (uses set names as tags)
const tagged = tree.getTaggedNewick({ multiSet: true });
// Returns: "((A{TEST}:0.1,B{REFERENCE}):0.2,C{TEST}:0.3);"

loadAnnotations(tree, NEXUS) ⇒ Object

Loads annotations from a nexus-formatted buffer and annotates existing tree nodes appropriately.

Kind: global function
Returns: Object - Annotations

ParamTypeDescription
treeObjectInstatiated phylotree
NEXUSStringstring

mrca() ⇒

Return most recent common ancestor of a pair of nodes.

Kind: global function
Returns: An array of strings, comprising each tag that was read.

computeMidpoint(tree) ⇒ Object

Compute midpoint of a phylogenetic tree

Kind: global function
Returns: Object - the calculated midpoint to root on { location: root_node, breakpoint: 0 }

ParamTypeDescription
treeObject- the phylotree.js tree object

deleteANode(The) ⇒

Delete a given node.

Kind: global function
Returns: The current phylotree.

ParamTypeDescription
TheNodenode to be deleted, or the index of such a node.

getTips() ⇒ Array

Get the tips of the tree

Kind: global function
Returns: Array - Nodes in the current phylotree.
Example

// Get all leaf nodes from a tree
const tree = new Phylotree("((A:0.1,B:0.2):0.05,C:0.3);");
const tips = tree.getTips();
console.log(tips.map(tip => tip.data.name)); // ["A", "B", "C"]

Example

// Count the number of taxa in the tree
const numTaxa = tree.getTips().length;
console.log(`Tree has ${numTaxa} taxa`);

getInternals() ⇒ Array

Get the internal nodes of the tree

Kind: global function
Returns: Array - Nodes in the current phylotree.

getRootNode() ⇒

Get the root node.

Kind: global function
Returns: the current root node of the phylotree.

getNodes() ⇒ Array

Get an array of all nodes.

Kind: global function
Returns: Array - Nodes in the current phylotree.

getNodeByName(name) ⇒ Node

Get a node by name.

Kind: global function
Returns: Node - Desired node.

ParamTypeDescription
nameStringName of the desired node.

Example

// Find a specific node by name
const tree = new Phylotree("((A:0.1,B:0.2):0.05,C:0.3);");
const nodeA = tree.getNodeByName("A");
console.log(nodeA.data.name); // "A"

Example

// Check if a node exists and get its branch length
const nodeB = tree.getNodeByName("B");
if (nodeB) {
  console.log(`Node B has branch length: ${nodeB.data.attribute}`);
}

assignAttributes(attributes)

Add attributes to nodes. New attributes will be placed in the annotations key of any nodes that are matched.

Kind: global function

ParamTypeDescription
attributesObjectAn object whose keys are the names of nodes to modify, and whose values are the new attributes to add.

Example

// Add species information to nodes
const tree = new Phylotree(newick);
tree.assignAttributes({
  "Human": { species: "Homo sapiens", host: "human" },
  "Chimp": { species: "Pan troglodytes", host: "chimpanzee" }
});

Example

// Add selection categories for visualization
tree.assignAttributes({
  "foreground_1": { category: "foreground", color: "red" },
  "foreground_2": { category: "foreground", color: "red" },
  "background_1": { category: "background", color: "blue" }
});

isLeafNode(A) ⇒ Bool

Determine if a given node is a leaf node.

Kind: global function
Returns: Bool - Whether or not the node is a leaf node.

ParamTypeDescription
ANodenode in a tree.

updateKeyName(old_key, new_key) ⇒

Update a given key name in each node.

Kind: global function
Returns: The current this.

ParamTypeDescription
old_keyStringThe old key name.
new_keyStringThe new key name.

selectAllDescendants(node, terminal, internal) ⇒ Array

Select all descendents of a given node, with options for selecting terminal/internal nodes.

Kind: global function
Returns: Array - An array of selected nodes.

ParamTypeDescription
nodeNodeThe node whose descendents should be selected.
terminalBooleanWhether to include terminal nodes.
internalBooleanWhther to include internal nodes.

Example

// Select all descendants of an internal node
const tree = new Phylotree("(((A,B)AB,(C,D)CD)ABCD,E);");
const internalNode = tree.getNodeByName("ABCD");
const allDescendants = tree.selectAllDescendants(internalNode, true, true);
console.log(allDescendants.map(n => n.data.name)); // ["AB", "A", "B", "CD", "C", "D"]

Example

// Select only terminal descendants (tips in a clade)
const cladeTips = tree.selectAllDescendants(internalNode, true, false);
console.log(cladeTips.map(n => n.data.name)); // ["A", "B", "C", "D"]

Example

// Select only internal descendants
const cladeInternals = tree.selectAllDescendants(internalNode, false, true);
console.log(cladeInternals.map(n => n.data.name)); // ["AB", "CD"]

toggleCollapse(node) ⇒ Phylotree

Toggle collapsed view of a given node. Either collapses a clade into a smaller blob for viewing large trees, or expands a node that was previously collapsed.

Kind: global function
Returns: Phylotree - The current phylotree.

ParamTypeDescription
nodeNodeThe node to toggle.

modifySelection(node_selecter, attr, place, skip_refresh, mode) ⇒

Modify the current selection, via functional programming.

Kind: global function
Returns: The current this.

ParamTypeDescription
node_selecterfunctionA function to apply to each node, which determines whether they become part of the current selection. Alternatively, if restricted-selectable mode is enabled, a string describing one of the pre-defined restricted-selectable options.
attrString(Optional) The selection attribute to modify.
placeBoolean(Optional) Whether or not placenodes should be called.
skip_refreshBoolean(Optional) Whether or not a refresh is called.
modeString(Optional) Can be "toggle", "true", or "false".

getSelection() ⇒ Array

Get nodes which are currently selected.

Kind: global function
Returns: Array - An array of nodes that match the current selection.

selectAllDescendants(node, terminal, internal) ⇒ Array

Select all descendents of a given node, with options for selecting terminal/internal nodes.

Kind: global function
Returns: Array - An array of selected nodes.

ParamTypeDescription
nodeNodeThe node whose descendents should be selected.
terminalBooleanWhether to include terminal nodes.
internalBooleanWhther to include internal nodes.

selectionCallback(callback) ⇒

Getter/setter for the selection callback. This function is called every time the current selection is modified, and its argument is an array of nodes that make up the current selection.

Kind: global function
Returns: The current _selectionCallback if getting, or the current this if setting.

ParamTypeDescription
callbackfunction(Optional) The selection callback function.

selectNodes(names) ⇒ this

Select nodes by their names.

Kind: global function
Returns: this - For chaining.

ParamTypeDescription
namesArray.<string>Array of node names to select.

Example

tree.selectNodes(['HUMAN', 'CHIMP', 'GORILLA']);

deselectNodes(names) ⇒ this

Deselect nodes by their names.

Kind: global function
Returns: this - For chaining.

ParamTypeDescription
namesArray.<string>Array of node names to deselect.

Example

tree.deselectNodes(['HUMAN']);

clearSelection() ⇒ this

Clear all current selection.

Kind: global function
Returns: this - For chaining.
Example

tree.clearSelection();

nodeSpan(attr) ⇒

Get or set the current node span. If setting, the argument should be a function of a node which returns a number, so that node spans can be determined dynamically. Alternatively, the argument can be the string "equal", to give all nodes an equal span.

Kind: global function
Returns: The nodeSpan if getting, or the current phylotree if setting.

ParamTypeDescription
attrfunctionOptional; if setting, the nodeSpan function.

nodeLabel(attr) ⇒

Get or set nodeLabel accessor.

Kind: global function
Returns: The nodeLabel accessor if getting, or the current this if setting.

ParamTypeDescription
attrfunction(Optional) If setting, a function that accesses a branch name from a node.

nodeBubbleSize(A) ⇒ Float

Return the bubble size of the current node.

Kind: global function
Returns: Float - The size of the bubble associated to this node.

ParamTypeDescription
ANodenode in the phylotree.

selectionLabel(attr) ⇒

Getter/setter for the selection label. Useful when allowing users to make multiple selections.

Kind: global function
Returns: The current selection label if getting, or the current phylotree if setting.

ParamTypeDescription
attrString(Optional) If setting, the new selection label.

nodeSpan(attr) ⇒

Get or set the current node span. If setting, the argument should be a function of a node which returns a number, so that node spans can be determined dynamically. Alternatively, the argument can be the string "equal", to give all nodes an equal span.

Kind: global function
Returns: The nodeSpan if getting, or the current phylotree if setting.

ParamTypeDescription
attrfunctionOptional; if setting, the nodeSpan function.

selectionCallback(callback) ⇒

Getter/setter for the selection callback. This function is called every time the current selection is modified, and its argument is an array of nodes that make up the current selection.

Kind: global function
Returns: The current _selectionCallback if getting, or the current this if setting.

ParamTypeDescription
callbackfunction(Optional) The selection callback function.

countLeaves(node) ⇒ Number

Count the number of leaf nodes in a subtree.

Kind: global function
Returns: Number - The number of leaves

ParamTypeDescription
nodeObjectA D3 hierarchy node

computeUnrootedLayout(root, scales, width, height, labelPad)

Compute unrooted (equal-angle) layout coordinates for all nodes.

The algorithm allocates 2π of angular space at the root, then recursively assigns each child subtree angular space proportional to its leaf count. Each node is placed at parent_position + branch_length * (cos(angle), sin(angle)).

After computing raw positions, coordinates are normalized to fit within the given width × height.

Kind: global function

ParamTypeDescription
rootObjectThe root node of the D3 hierarchy
scalesArray[scale_x, scale_y] from placenodes
widthNumberAvailable width in pixels
heightNumberAvailable height in pixels
labelPadNumberPixel padding to reserve for labels on all sides

equalAngle(node, startAngle, arcSize)

Recursive equal-angle layout.

Kind: global function

ParamTypeDescription
nodeObjectCurrent node
startAngleNumberStart of the angular arc allocated to this node
arcSizeNumberTotal angular arc allocated to this node

drawUnrootedEdge(points) ⇒ String

Draw a straight line edge between two nodes (for unrooted layout).

Kind: global function
Returns: String - SVG path string

ParamTypeDescription
pointsArrayArray of [source, target] node objects

unrootedSegmentPlacer(edge, where) ⇒ Object

Place a label along an unrooted edge via linear interpolation.

Kind: global function
Returns: Object - {x, y} screen coordinates

ParamTypeDescription
edgeObjectEdge object with source and target
whereNumberInterpolation factor (0 = target, 1 = source)

reroot(node, if) ⇒ Phylotree

Reroot the tree on the given node.

Kind: global function
Returns: Phylotree - The current phylotree.

ParamTypeDescription
nodeNodeNode to reroot on.
iffractionspecified, partition the branch not into 0.5 : 0.5, but according to the specified fraction

Example

// Reroot tree on a specific node
const tree = new Phylotree("((A:0.1,B:0.2):0.05,(C:0.3,D:0.1):0.08);");
const nodeC = tree.getNodeByName("C");
tree.reroot(nodeC);
// Tree is now rooted on the branch leading to C

Example

// Reroot with custom branch length partitioning
const nodeA = tree.getNodeByName("A");
tree.reroot(nodeA, 0.3); // 30% of branch length goes to new root

Example

// Reroot on midpoint of tree (balance tree)
const tips = tree.getTips();
const midpoint = tree.computeMidpoint();
tree.reroot(midpoint);

leftChildRightSibling(tree) ⇒ Object

Traverses a tree that represents left-child right-sibling

Kind: global function
Returns: Object - An edge list that represents the original multi-way tree

ParamTypeDescription
treeObject- the phylotree.js tree object