Skip to content

Latest commit

 

History

History
1343 lines (1104 loc) · 45.9 KB

API.md

File metadata and controls

1343 lines (1104 loc) · 45.9 KB

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(mrca_nodes) ⇒

Return most recent common ancestor of a set 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.

openNodeMenu(node, event) ⇒

Open the menu for node at the position of event.

Emits contextMenu with (node, event) first; a listener that calls event.preventDefault() replaces the built-in menu with its own. For a right-click, the browser's own context menu is suppressed.

addCustomMenu(node, name, callback, [condition])

Add a custom menu item to a node's menu.

It is easy to add the menu items inside the node-styler function in tree.render(), which gets (element, node) as its two arguments -- that node can be passed to addCustomMenu() as its first argument. You may want to set node.menu_items = [] to avoid adding the same menu item multiple times.

The custom item will be added in addition to the default items: "Collapse Subtree", the "Toggle selection" submenu, "Reroot on this node" and "Hide this subtree". It will be added at the end of the menu after a menu divider.

Available both as a package export and as a method on the rendered tree.

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. A hidden (notshown) subtree has no leaves and a collapsed clade counts as one.

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.

maxDescendantDistance(node, baseY) ⇒ Number

Largest distance from a node to any of its shown descendants.

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

Param Type Description
eventName string Event name (nodeClick, branchClick, nodeHover, contextMenu, rendered, selectionChange, collapsed, rerooted)
callback function Handler 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

Param Type Description
eventName string Event name
callback function Handler 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.

Param Type Description
name string Name 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.

Param Type Description
setName string Name 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.

Param Type Description
node Node | string Node object or node name.
setName string Target 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.

Param Type Description
node Node | string Node object or node name.
setName string Target 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.

Param Type Description
node Node The node to check.
setName string The 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.

Param Type Description
node Node The 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.

Param Type Description
nwk Object A Newick string, PhyloXML string, or hierarchical JSON representation of a phylogenetic tree.
options Object - 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

Param Type Description
callback function A function to be called on each node.
traversal_type String Either "pre-order" or "post-order" or "in-order".
root_node Node start traversal here, if provided, otherwise start at root
backtrack function ; 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

Param Type Description
options Object Rendering 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.

Param Type Description
attr function Empty 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

Param Type Description
scale_by function Function 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.

Param Type Description
attr function (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 }

Param Description
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.

Param Type Description
nwk_str String A 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.

Param Type Description
annotator function Function to apply to each node, determining what label is written (optional).
node Node start 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.

Param Type Default Description
options Object Configuration options.
[options.tag] string "'Foreground'" Tag name for selected nodes (single selection mode).
[options.multiSet] boolean false Use 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

Param Type Description
tree Object Instatiated phylotree
NEXUS String string

mrca(mrca_nodes) ⇒

Return most recent common ancestor of a set of nodes.

Kind: global function
Returns: The deepest node whose descendants include all of the given nodes, or undefined if there is none.

Param Type Description
mrca_nodes Array Node names, or nodes.

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 }

Param Type Description
tree Object - the phylotree.js tree object

deleteANode(The) ⇒

Delete a given node.

Kind: global function
Returns: The current phylotree.

Param Type Description
The Node node 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.

Param Type Description
name String Name 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

Param Type Description
attributes Object An 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.

Param Type Description
A Node node in a tree.

updateKeyName(old_key, new_key) ⇒

Update a given key name in each node.

Kind: global function
Returns: The current this.

Param Type Description
old_key String The old key name.
new_key String The 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.

Param Type Description
node Node The node whose descendents should be selected.
terminal Boolean Whether to include terminal nodes.
internal Boolean Whther 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.

Param Type Description
node Node The node to toggle.

openNodeMenu(node, event) ⇒

Open the menu for node at the position of event.

Emits contextMenu with (node, event) first; a listener that calls event.preventDefault() replaces the built-in menu with its own. For a right-click, the browser's own context menu is suppressed.

Kind: global function
Returns: The current this.

Param Type Description
node Object The node whose menu to open.
event Event The triggering mouse event; its clientX/clientY position the menu.

Example

tree.display.on("contextMenu", (node, event) => {
  event.preventDefault(); // skip the built-in menu
  showMyMenu(node, event.clientX, event.clientY);
});

addCustomMenu(node, name, callback, [condition])

Add a custom menu item to a node's menu.

It is easy to add the menu items inside the node-styler function in tree.render(), which gets (element, node) as its two arguments -- that node can be passed to addCustomMenu() as its first argument. You may want to set node.menu_items = [] to avoid adding the same menu item multiple times.

The custom item will be added in addition to the default items: "Collapse Subtree", the "Toggle selection" submenu, "Reroot on this node" and "Hide this subtree". It will be added at the end of the menu after a menu divider.

Available both as a package export and as a method on the rendered tree.

Kind: global function

Param Type Description
node Object The node to add the custom menu item to.
name function Given a node, returns the name of the menu item.
callback function Called as callback(node, event) when the menu item is clicked.
[condition] function Given a node, returns whether the menu item should be shown. Always shown if omitted.

Example

import { phylotree, addCustomMenu } from "phylotree";

const tree = new phylotree(newick);
tree.render({
  container: "#tree",
  "node-styler": (element, node) => {
    addCustomMenu(
      node,
      n => "Show details for " + n.data.name,
      n => showDetails(n),
      n => !n.children
    );
  }
});

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

Modify the current selection, via functional programming.

Kind: global function
Returns: The current this.

Param Type Description
node_selecter function A 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.
attr String (Optional) The selection attribute to modify.
place Boolean (Optional) Whether or not placenodes should be called.
skip_refresh Boolean (Optional) Whether or not a refresh is called.
mode String (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.

Param Type Description
node Node The node whose descendents should be selected.
terminal Boolean Whether to include terminal nodes.
internal Boolean Whther 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.

Param Type Description
callback function (Optional) The selection callback function.

selectNodes(names) ⇒ this

Select nodes by their names.

Kind: global function
Returns: this - For chaining.

Param Type Description
names Array.<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.

Param Type Description
names Array.<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.

Param Type Description
attr function Optional; 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.

Param Type Description
attr function (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.

Param Type Description
A Node node 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.

Param Type Description
attr String (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.

Param Type Description
attr function Optional; 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.

Param Type Description
callback function (Optional) The selection callback function.

countLeaves(node) ⇒ Number

Count the number of leaf nodes in a subtree. A hidden (notshown) subtree has no leaves and a collapsed clade counts as one.

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

Param Type Description
node Object A 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

Param Type Description
root Object The root node of the D3 hierarchy
scales Array [scale_x, scale_y] from placenodes
width Number Available width in pixels
height Number Available height in pixels
labelPad Number Pixel padding to reserve for labels on all sides

maxDescendantDistance(node, baseY) ⇒ Number

Largest distance from a node to any of its shown descendants.

Kind: global function
Returns: Number - The distance, never negative

Param Type Description
node Object The clade root
baseY Number Cumulative branch length at the clade root

equalAngle(node, startAngle, arcSize)

Recursive equal-angle layout.

Kind: global function

Param Type Description
node Object Current node
startAngle Number Start of the angular arc allocated to this node
arcSize Number Total 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

Param Type Description
points Array Array 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

Param Type Description
edge Object Edge object with source and target
where Number Interpolation factor (0 = target, 1 = source)

reroot(node, if) ⇒ Phylotree

Reroot the tree on the given node.

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

Param Type Description
node Node Node to reroot on.
if fraction specified, 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

Param Type Description
tree Object - the phylotree.js tree object