Skip to content

Tree Metric

The normalized branch-score metric. Two trees are cut to the m taxa they share, and the squared distance is

d^2 = (1-w) * (1 - B / sqrt(A C)) + w * RF / (2m - 6),

where A and C are the squared lengths of the two split-length vectors, B is their inner product, and RF is the Robinson-Foulds count. Both terms lie in [0, 1], so w weights topology against branch length in the same way on every data set, and no two trees are further apart than 1. The chart owns a metric instance built with its topology weight.

BranchScoreMetric dataclass

Branch-score implementation of the TreeMetric protocol.

Both trees are cut to the taxa they share, and the distance is read from the subtree each induces there:

d^2 = (1 - w) * (1 - B / sqrt(A C)) + w * RF / (2 m - 6)

A and C are the squared lengths of the two split-length vectors, B is their inner product, RF is the count of splits held by one tree and not the other, and m is the shared taxon count. w in [0, 1] weights topology against branch length.

Each term is a ratio of two sums over the same splits, so the taxon count cancels and the distance reads dissimilarity alone. The branch score itself grows with the taxon count, about 15-fold from 32 shared taxa to 1024, which would otherwise make two pairs of different overlap incomparable. Both terms lie in [0, 1], so w means the same thing on every data set.

The branch term is half the squared distance between the two vectors after each is scaled to unit length, so on one taxon set it is squared Euclidean and the plane embedding holds.

A pair sharing fewer than METRIC_MIN_SHARED_TAXA taxa has no distance, and the distance reads NaN. Trees that share no taxa share no topology, so there is nothing for the distance to measure.

quality = B_frac in [0, 1]; the length-overlap fraction. Near 0 = branch- score saturation; near 1 = similar trees.

Kuhner & Felsenstein (1994), robinson1981rf.

Source code in src/hifuku/metric/branch_score.py
@dataclass
class BranchScoreMetric:
    """
    Branch-score implementation of the TreeMetric protocol.

    Both trees are cut to the taxa they share, and the distance is read from the
    subtree each induces there:

        d^2 = (1 - w) * (1 - B / sqrt(A C)) + w * RF / (2 m - 6)

    ``A`` and ``C`` are the squared lengths of the two split-length vectors,
    ``B`` is their inner product, ``RF`` is the count of splits held by one tree
    and not the other, and ``m`` is the shared taxon count.  ``w`` in [0, 1]
    weights topology against branch length.

    Each term is a ratio of two sums over the same splits, so the taxon count
    cancels and the distance reads dissimilarity alone.  The branch score itself
    grows with the taxon count, about 15-fold from 32 shared taxa to 1024, which
    would otherwise make two pairs of different overlap incomparable.  Both terms
    lie in [0, 1], so ``w`` means the same thing on every data set.

    The branch term is half the squared distance between the two vectors after
    each is scaled to unit length, so on one taxon set it is squared Euclidean
    and the plane embedding holds.

    A pair sharing fewer than ``METRIC_MIN_SHARED_TAXA`` taxa has no distance,
    and the distance reads NaN.  Trees that share no taxa share no topology, so
    there is nothing for the distance to measure.

    ``quality`` = B_frac in [0, 1]; the length-overlap fraction.  Near 0 = branch-
    score saturation; near 1 = similar trees.

    Kuhner & Felsenstein (1994), robinson1981rf.
    """

    w: float = METRIC_W
    #: What the second tree of a pair contributes, kept between calls.  A chart
    #: measures every tree against the same three anchors, so the anchor side of
    #: the work repeats and the tree side does not.  Left out of equality and of
    #: the repr: it is a saving, not part of what the metric is.
    _reference_cache: dict = field(default_factory=dict, compare=False,
                                   repr=False)

    def __call__(
        self, t1: HifukuTree, t2: HifukuTree
    ) -> tuple[float, float]:
        return _branch_score_dist_quality(t1, t2, self.w, self._reference_cache)

    @staticmethod
    def shared_taxa(t1: HifukuTree, t2: HifukuTree) -> int:
        """How many taxa the two trees hold in common.

        Selection reads this to reject a pair the metric cannot measure, and the
        weighted embedding reads it to drop that pair from the fit.
        """
        return len(set(t1.leaf_labels) & set(t2.leaf_labels))

shared_taxa staticmethod

shared_taxa(t1: HifukuTree, t2: HifukuTree) -> int

How many taxa the two trees hold in common.

Selection reads this to reject a pair the metric cannot measure, and the weighted embedding reads it to drop that pair from the fit.

Source code in src/hifuku/metric/branch_score.py
@staticmethod
def shared_taxa(t1: HifukuTree, t2: HifukuTree) -> int:
    """How many taxa the two trees hold in common.

    Selection reads this to reject a pair the metric cannot measure, and the
    weighted embedding reads it to drop that pair from the fit.
    """
    return len(set(t1.leaf_labels) & set(t2.leaf_labels))

TreeMetric

Bases: Protocol

Protocol for tree distance metrics used by the 2D CV.

A callable that takes two HifukuTree objects and returns a (distance, quality) pair. The quality score is a reliability / confidence value interpretable as a likelihood-like weight: high quality = the metric distinguishes the two trees well; low quality = metric saturation (the metric has lost resolution; distinct from substitution saturation).

BranchScoreMetric below is the only implementation. Code outside it must not assume its internals.

Source code in src/hifuku/metric/branch_score.py
@runtime_checkable
class TreeMetric(Protocol):
    """
    Protocol for tree distance metrics used by the 2D CV.

    A callable that takes two HifukuTree objects and returns a (distance,
    quality) pair.  The quality score is a reliability / confidence value
    interpretable as a likelihood-like weight: high quality = the metric
    distinguishes the two trees well; low quality = metric saturation (the
    metric has lost resolution; distinct from substitution saturation).

    BranchScoreMetric below is the only implementation.  Code outside it must not
    assume its internals.
    """

    def __call__(
        self, t1: HifukuTree, t2: HifukuTree
    ) -> tuple[float, float]:
        """
        Parameters
        ----------
        t1, t2 : HifukuTree
            Trees with ``global_leaf_indices`` set and restricted to the same
            global taxon namespace.

        Returns
        -------
        (distance, quality) : (float, float)
            ``distance >= 0``.  ``quality`` in [0, 1], where 0 = metric
            saturation and 1 = identical trees.
        """
        ...