Skip to content

Neighbor-Joining Anchors

Anchor trees are neighbor-joining trees built from the gene alignments, with corrected pairwise distances (JC69 for DNA, Kimura 1983 for protein).

nj_tree

nj_tree(alignment: 'Alignment', taxon_table: TaxonTable, label: str = '', min_occupancy: float = MIN_TAXON_OCCUPANCY) -> HifukuTree

Compute a neighbor-joining anchor tree from a compressed alignment.

The NJ algorithm runs on all of the alignment's local taxa. The returned HifukuTree is restricted to the taxa currently in taxon_table, so the caller controls the effective namespace by pre-populating taxon_table.

Negative branch lengths produced by the NJ algorithm (a known artifact on non-tree-metric distance matrices) are clamped to zero.

Parameters:

Name Type Description Default
alignment 'Alignment'

Compressed alignment (DNA or AA) produced by load_alignment.

required
taxon_table TaxonTable

Shared global TaxonTable. Leaf taxa from the NJ tree that are in this table are kept; the rest are pruned. Any kept taxa not already in the table are registered via require.

required
label str

The gene this alignment holds, named in the warning the distance correction may raise. A caller building several trees at once passes it so that a reader can tell which gene the warning is about.

''
min_occupancy float

The fraction of the alignment's sites a taxon must carry to be placed. A taxon carrying nothing is dropped whatever this says. Raise it for a fragmentary alignment, where taxa that carry a little of the gene leave pairs the correction cannot read; see tree_distances for what the trade costs and MIN_TAXON_OCCUPANCY for the default.

MIN_TAXON_OCCUPANCY

Returns:

Type Description
HifukuTree

NJ tree restricted to taxon_table, with global_leaf_indices set.

Notes

Distance model (per seq_type):

Saturated pairs are capped at a large finite distance; see _SATURATED_DIST.

Neighbor-joining: Saitou & Nei (1987).

Source code in src/hifuku/nj.py
def nj_tree(alignment: "Alignment", taxon_table: TaxonTable,
            label: str = "",
            min_occupancy: float = MIN_TAXON_OCCUPANCY) -> HifukuTree:
    """
    Compute a neighbor-joining anchor tree from a compressed alignment.

    The NJ algorithm runs on all of the alignment's local taxa. The returned
    HifukuTree is restricted to the taxa currently in *taxon_table*, so the
    caller controls the effective namespace by pre-populating *taxon_table*.

    Negative branch lengths produced by the NJ algorithm (a known artifact
    on non-tree-metric distance matrices) are clamped to zero.

    Parameters
    ----------
    alignment :
        Compressed alignment (DNA or AA) produced by ``load_alignment``.
    taxon_table :
        Shared global TaxonTable.  Leaf taxa from the NJ tree that are in
        this table are kept; the rest are pruned.  Any kept taxa not already
        in the table are registered via ``require``.
    label :
        The gene this alignment holds, named in the warning the distance
        correction may raise.  A caller building several trees at once passes
        it so that a reader can tell which gene the warning is about.
    min_occupancy :
        The fraction of the alignment's sites a taxon must carry to be placed.
        A taxon carrying nothing is dropped whatever this says.  Raise it for a
        fragmentary alignment, where taxa that carry a little of the gene leave
        pairs the correction cannot read; see ``tree_distances`` for what the
        trade costs and ``MIN_TAXON_OCCUPANCY`` for the default.

    Returns
    -------
    HifukuTree
        NJ tree restricted to *taxon_table*, with ``global_leaf_indices`` set.

    Notes
    -----
    Distance model (per seq_type):

    - ``'DNA'``: Jukes-Cantor 1969 correction, d = -(3/4) ln(1-(4/3)p).
      Jukes & Cantor (1969).
    - ``'AA'``: Kimura 1983 correction, d = -ln(1-p-0.2p^2).
      Kimura (1983).

    Saturated pairs are capped at a large finite distance; see _SATURATED_DIST.

    Neighbor-joining: Saitou & Nei (1987).
    """
    # The matrix, and the taxa it covers.  A taxon carrying no residue is left
    # out: nothing in it can be compared, so every distance from it would be
    # capped and it would enter the tree wherever the cap put it.
    d_corr, labels, stats = tree_distances(alignment,
                                           min_occupancy=min_occupancy)
    if len(labels) < 3:
        n_all = len(alignment.index.labels)
        raise ValueError(
            f"Alignment has {n_all} taxa, of which {len(labels)} carry enough "
            f"of the gene to be placed; NJ requires at least 3."
        )

    if stats.saturated_fraction > SATURATED_PAIR_WARN_FRAC:
        if math.isnan(stats.d_median):
            against = "and no pair was near enough for it to invert at all"
        else:
            against = (f"against a median of {stats.d_median:.2f} over the "
                       f"pairs it could invert")
        who = f"{label}: " if label else ""
        # Point at the lever.  A capped pair usually means the two sequences
        # overlap on too little of the alignment rather than that they are
        # genuinely that far apart, and asking for more of the gene removes
        # those pairs by removing the taxa that cannot supply them.
        held = (f"at min_occupancy {min_occupancy:g}"
                if min_occupancy > 0.0 else
                "with only the taxa carrying nothing left out")
        warnings.warn(
            f"{who}{stats.model}: {stats.n_saturated} of {stats.n_pairs} pairs "
            f"({stats.saturated_fraction:.1%}) are too divergent for the "
            f"correction to invert and are capped at {stats.cap}, {against}. "
            f"About {stats.quartets_with_two_caps:.0%} of quartets then hold "
            f"two capped pairs, which carry the same value, so the four-point "
            f"condition neighbor joining relies on is met by that value rather "
            f"than by the sequences. Read this tree as one whose topology is "
            f"not supported by the data on that fraction of its quartets. "
            f"This tree keeps {stats.n_taxa} taxa {held} and leaves out "
            f"{stats.n_taxa_dropped}. A pair is usually capped for overlapping "
            f"on too little of the alignment rather than for being that far "
            f"apart, so raising min_occupancy, which asks each taxon to carry "
            f"more of the gene, is what removes these pairs; it trades taxa for "
            f"that, and how many depends on the alignment.",
            SaturatedDistanceWarning,
            stacklevel=2,
        )

    # Run neighbor joining and parse the newick into a temporary local
    # TaxonTable, so that pruned taxa never reach the global namespace.
    newick = _neighbor_join(list(labels), d_corr)
    local_tt = TaxonTable()
    tree = read_tree(newick, local_tt, from_string=True)

    # Clamp negative branch lengths (NJ artifact on non-tree-metric input).
    neg_mask = tree.edge_len < 0.0
    if np.any(neg_mask):
        tree.edge_len[neg_mask] = 0.0

    # Restrict to the labels currently in the caller's taxon_table (the
    # shared global namespace).  Using a local_tt above avoids accidentally
    # registering pruned taxa into the global namespace.
    ns_set = set(taxon_table.labels)
    keep = [lbl for lbl in tree.leaf_labels if lbl in ns_set]
    if len(keep) < 3:
        raise ValueError(
            f"Fewer than 3 NJ tree taxa are in the global namespace "
            f"({len(keep)} kept from {tree.n_leaves} in the tree)."
        )
    result = tree if len(keep) == tree.n_leaves else tree.restrict(keep)

    # Register kept taxa into the global namespace and set global_leaf_indices.
    for lbl in result.leaf_labels:
        taxon_table.require(lbl)
    glidx = np.full(result.n_nodes, -1, dtype=np.int32)
    for i in range(result.n_leaves):
        glidx[i] = taxon_table.index_of(result.names[i])
    result.global_leaf_indices = glidx

    return result