phylotree.js

repository·master·Indexed 42 days ago

https://github.com/veg/phylotree.js

A JavaScript library built on D3.js for creating interactive phylogenetic tree visualizations. Version 2.6.0 supports Newick and HyPhy formats, providing tools for tree rendering, analytical utilities like Sackin's index and root-to-tip regression, clustering algorithms (Cluster Picker, PhyloPart), and tree construction from sequences via neighbor-joining.

Tokens
20.4K
Snippets
87
Records
108
Agent score
3%

What's inside phylotree.js

  1. Supported Tree Formats

    master
    The library supports the standard Newick format. It also supports an extension used by HyPhy, which allows assigning categories to branches using curly braces directly after identifiers (e.g., NodeName{Category}:Distance).
  2. Manage multi-set selections with selection-sets

    master

    The render/selection-sets module allows you to manage multiple named groups of nodes (e.g., 'foreground' and 'background'). This is useful for highlighting specific subsets of a tree. You can set an active set so that subsequent user clicks automatically add nodes to that specific set.

    // Activate a set so clicks add nodes to it
    tree.setActiveSet('foreground');
    
    // Manually add/remove nodes
    tree.addToSet('HUMAN', 'foreground');
    tree.removeFromSet(nodeObject, 'background');
    
    // Query sets
    const members = tree.getSetMembers('foreground');
    const isInSet = tree.isInSet(node, 'foreground');
    const setName = tree.getNodeSet(node); // returns string or null
  3. Manage multiple selection sets in phylotree

    master

    When selection-mode is set to 'multi-set', phylotree allows you to define multiple named selection sets, each with its own color. Nodes can be assigned to these sets, which applies specific CSS styles to the node circles and branches.

    Key behaviors:

    • Mutual Exclusivity: A node can only belong to one selection set at a time. Adding a node to a new set automatically removes it from any previous sets.
    • Styling: Selection sets inject dynamic CSS. The class names follow the pattern .phylotree-set-{safe_name} for nodes and .phylotree-set-branch-{safe_name} for branches.
    • Interactivity: In multi-set mode, clicking a node will toggle its membership in the currently active set.
  4. Use the tip-date-extractor CLI to extract dates from Newick files

    master

    The tip-date-extractor command parses a Newick tree file and extracts date information from the tip (leaf) labels. This is typically used to prepare data for root-to-tip distance calculations. The tool supports two mutually exclusive methods for finding dates: using a regular expression or splitting the tip name by a delimiter.

    Note: You cannot use the -r/--regex and -s/--split-on-char options at the same time.

    # Example 1: Using a delimiter (e.g., underscore) to find a date
    tip-date-extractor -n test/data/MERS.txt -s "_" -f YYYY-MM-DD
    
    # Example 2: Using a regular expression to find a date
    tip-date-extractor -n test/data/MERS.txt -r "[0-9]{4}-[0-9]{2}-[0-9]{2}" -f YYYY-MM-DD
  5. Basic Usage: Parse and render a phylogenetic tree

    master

    To use phylotree, import the phylotree class, instantiate it with a Newick string, and then call .render() to generate an SVG in a specified container.

    Common render options include:

    • container: The CSS selector for the SVG container.
    • width: The width of the tree.
    • height: The height of the tree.
    • align-tips: Boolean to align tip names.
    • zoom: Boolean to enable zooming.
    import { phylotree } from "phylotree";
    
    // Parse a Newick string
    const newick = "((A:0.1,B:0.2):0.3,(C:0.4,D:0.5):0.6);";
    const tree = new phylotree(newick);
    
    // Render to an SVG container
    const renderer = tree.render({
      container: "#tree-container",
      width: 800,
      height: 600,
      "align-tips": true,
      zoom: true
    });
  6. Compute unrooted (equal-angle) layouts

    master

    For unrooted tree visualizations, use the following functions to calculate coordinates and draw edges.

    computeUnrootedLayout

    Calculates unrooted (equal-angle) layout coordinates for all nodes. It allocates angular space at the root and recursively assigns child subtree space proportional to leaf counts. Coordinates are normalized to fit the provided dimensions.

    Parameters:

    • root: The root node of the D3 hierarchy.
    • scales: An array [scale_x, scale_y] from placenodes.
    • width: Available width in pixels.
    • height: Available height in pixels.
    • labelPad: Pixel padding to reserve for labels on all sides.

    drawUnrootedEdge

    Draws a straight line edge between two nodes for unrooted layouts. Returns an SVG path string.

    Parameters:

    • points: An array of [source, target] node objects.

    unrootedSegmentPlacer

    Places a label along an unrooted edge using linear interpolation.

    Parameters:

    • edge: Edge object containing source and target.
    • where: Interpolation factor (0 = target, 1 = source). Returns {x, y} screen coordinates.
  7. Find a node by name with getNodeByName()

    master

    The getNodeByName method searches the tree for a node with the specified name and returns it.

    // 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");
    
    // 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}`);
    }
  8. Initialize a Phylotree instance

    master

    Create a new Phylotree instance using a Newick string, PhyloXML string, or a hierarchical JSON object. The constructor follows a builder pattern.

    // From Newick string
    const tree = new Phylotree("((A:0.1,B:0.2):0.05,C:0.3)");
    
    // With options
    const tree = new Phylotree(newick, {
      bootstrap_values: true,
      type: "newick"
    });
    
    // From hierarchical JSON
    const jsonTree = {
      name: "root",
      children: [{ name: "A", length: 0.1 }, { name: "B", length: 0.2 }]
    };
    const tree = new Phylotree(jsonTree);
  9. Retrieve tree tips with getTips()

    master

    The getTips method returns an array of all leaf nodes (tips) in the current phylotree.

    // 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"]
    
    // Count the number of taxa in the tree
    const numTaxa = tree.getTips().length;
  10. Use Tree Metric utility functions

    master

    The library exports several utilities for calculating phylogenetic metrics:

    • pairwiseDistances: Compute pairwise distances between nodes.
    • sackin: Sackin's index (tree balance measure).
    • centerOfTree: Find the center node of the tree.
    • computeMidpoint: Compute midpoint for rooting.
    • rootToTip: Root-to-tip distance regression.
    • fitRootToTip: Find optimal root by R² maximization.
    import {
      pairwiseDistances,
      sackin,
      centerOfTree,
      computeMidpoint,
      rootToTip,
      fitRootToTip
    } from "phylotree";