Skip to content

nj_tree

piqtree.nj_tree(pairwise_distances, *, allow_negative=False)

Construct a neighbour joining tree from a pairwise distance matrix.

PARAMETER DESCRIPTION
pairwise_distances

Pairwise distances to construct neighbour joining tree from.

TYPE: DistanceMatrix

allow_negative

Whether to allow negative branch lengths in the output. Coerces to 0 if not allowed, by default False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
PhyloNode

The neighbour joining tree.

See Also

jc_distances : construction of pairwise JC distance matrix from alignment.

Source code in src/piqtree/iqtree/_tree.py
def nj_tree(
    pairwise_distances: DistanceMatrix,
    *,
    allow_negative: bool = False,
) -> PhyloNode:
    """Construct a neighbour joining tree from a pairwise distance matrix.

    Parameters
    ----------
    pairwise_distances : DistanceMatrix
        Pairwise distances to construct neighbour joining tree from.
    allow_negative : bool, optional
        Whether to allow negative branch lengths in the output.
        Coerces to 0 if not allowed, by default False.

    Returns
    -------
    PhyloNode
        The neighbour joining tree.

    See Also
    --------
    jc_distances : construction of pairwise JC distance matrix from alignment.

    """
    if np.isnan(pairwise_distances.array).any():
        msg = "The pairwise distance matrix cannot contain NaN values."
        raise ValueError(msg)

    newick_tree = iq_nj_tree(
        pairwise_distances.keys(),
        np.array(pairwise_distances).flatten(),
    )

    tree = make_tree(newick_tree)

    if not allow_negative:
        for node in tree.preorder(include_self=False):
            node.length = max(cast("float", node.length), 0)

    return tree

Usage

For usage, see "Construct a rapid neighbour-joining tree from a distance matrix".