Skip to content

Trees

Newick I/O and the quarimo array-layout tree representation.

HifukuTree dataclass

Unrooted binary phylogenetic tree, stored as parallel numpy arrays.

Node indices follow the quarimo layout:

  • Leaves occupy indices 0 to n_leaves - 1.
  • Non-root internal nodes occupy indices n_leaves to n_nodes - 2.
  • The root occupies index n_nodes - 1.

Which leaf holds which index, and which internal node holds which, is not fixed by the layout. Parsing puts the leaves in left-first depth-first order and numbers the internal nodes as it goes. A survey renumbers to one shared order instead, because its trees have to be numbered alike to be compared, stored and continued, and because a walk rewires nodes in place and leaves them wherever its moves put them. See :func:reference_leaf_order and :func:canonical.

Parsing binarizes every multifurcation. Each k-ary node (k > 2) becomes a chain of binary nodes, joined by zero-length edges.

Attributes:

Name Type Description
parent ndarray

int32, shape (n_nodes,). Parent index of each node. The root has -1.

left_child ndarray

int32, shape (n_nodes,). Left child index. Leaf nodes have -1.

right_child ndarray

int32, shape (n_nodes,). Right child index. Leaf nodes have -1.

edge_len ndarray

float64, shape (n_nodes,). Length of the edge from the node to its parent. The root has NaN, because it has no parent edge.

names list[str]

Length n_nodes, one entry per node. Leaf entries hold the taxon label. Internal entries hold the empty string. This length equals n_nodes, not n_leaves. To get the taxon count, use n_leaves, n_taxa, or leaf_labels, not len(names).

n_nodes int

Total number of nodes: leaves, plus internal nodes, plus the root.

n_leaves int

Number of leaf (tip) nodes. This is the taxon count.

root int

Index of the root node. This index always equals n_nodes - 1.

had_multifurcations bool

True if the input Newick string had a polytomy. Parsing binarizes every polytomy, so this flag is the only record that one existed.

global_leaf_indices ndarray or None

int32, shape (n_nodes,). For leaf nodes 0 to n_leaves - 1, the global TaxonTable index of that leaf's taxon. Internal nodes and the root hold -1. read_tree sets this field, and restrict carries it forward. Globally consistent split hashes need this field.

Notes
  • Ref: quarimo (array layout and iterative parser pattern).
  • Minh et al. (2020) : zero-length branch convention for polytomies.
Source code in src/hifuku/tree_io.py
@dataclass
class HifukuTree:
    """
    Unrooted binary phylogenetic tree, stored as parallel numpy arrays.

    Node indices follow the quarimo layout:

    - Leaves occupy indices ``0`` to ``n_leaves - 1``.
    - Non-root internal nodes occupy indices ``n_leaves`` to ``n_nodes - 2``.
    - The root occupies index ``n_nodes - 1``.

    Which leaf holds which index, and which internal node holds which, is not
    fixed by the layout.  Parsing puts the leaves in left-first depth-first
    order and numbers the internal nodes as it goes.  A survey renumbers to one
    shared order instead, because its trees have to be numbered alike to be
    compared, stored and continued, and because a walk rewires nodes in place
    and leaves them wherever its moves put them.  See
    :func:`reference_leaf_order` and :func:`canonical`.

    Parsing binarizes every multifurcation. Each k-ary node (k > 2) becomes
    a chain of binary nodes, joined by zero-length edges.

    Attributes
    ----------
    parent : np.ndarray
        int32, shape (n_nodes,). Parent index of each node. The root has -1.
    left_child : np.ndarray
        int32, shape (n_nodes,). Left child index. Leaf nodes have -1.
    right_child : np.ndarray
        int32, shape (n_nodes,). Right child index. Leaf nodes have -1.
    edge_len : np.ndarray
        float64, shape (n_nodes,). Length of the edge from the node to its
        parent. The root has NaN, because it has no parent edge.
    names : list[str]
        Length n_nodes, one entry per node. Leaf entries hold the taxon
        label. Internal entries hold the empty string. This length equals
        n_nodes, not n_leaves. To get the taxon count, use n_leaves,
        n_taxa, or leaf_labels, not len(names).
    n_nodes : int
        Total number of nodes: leaves, plus internal nodes, plus the root.
    n_leaves : int
        Number of leaf (tip) nodes. This is the taxon count.
    root : int
        Index of the root node. This index always equals n_nodes - 1.
    had_multifurcations : bool
        True if the input Newick string had a polytomy. Parsing binarizes
        every polytomy, so this flag is the only record that one existed.
    global_leaf_indices : np.ndarray or None
        int32, shape (n_nodes,). For leaf nodes 0 to n_leaves - 1, the
        global TaxonTable index of that leaf's taxon. Internal nodes and
        the root hold -1. ``read_tree`` sets this field, and ``restrict``
        carries it forward. Globally consistent split hashes need this
        field.

    Notes
    -----
    - Ref: quarimo (array layout and iterative parser pattern).
    - Minh et al. (2020) : zero-length branch convention for polytomies.
    """

    parent: np.ndarray
    left_child: np.ndarray
    right_child: np.ndarray
    edge_len: np.ndarray

    names: list[str]
    n_nodes: int
    n_leaves: int
    root: int
    had_multifurcations: bool = False
    global_leaf_indices: Optional[np.ndarray] = None
    node_order: Optional[np.ndarray] = None
    """int32, shape (n_nodes - n_leaves - 1,). Holds the non-root internal
    nodes in DFS post-order, with each child listed before its parent. The
    Felsenstein peeling traversal uses this order."""

    def compute_node_order(self) -> np.ndarray:
        """
        Compute the non-root internal nodes in DFS post-order.

        This method lists each child before its parent. It walks the tree
        using the left_child and right_child pointers, so the result is
        correct for any node index assignment.

        Returns
        -------
        np.ndarray
            int32, shape (n_nodes - n_leaves - 1,). Non-root internal nodes
            in DFS post-order.
        """
        return _post_order(
            np.ascontiguousarray(self.left_child, dtype=np.int32),
            np.ascontiguousarray(self.right_child, dtype=np.int32),
            int(self.root), int(self.n_leaves), int(self.n_nodes))

    @property
    def leaf_labels(self) -> list[str]:
        """Taxon labels for the leaf nodes, in index order 0 to n_leaves - 1."""
        return [self.names[i] for i in range(self.n_leaves)]

    @property
    def n_taxa(self) -> int:
        """Number of taxa in the tree. This equals n_leaves."""
        return self.n_leaves

    # -- split identity ---------------------------------------------------
    #
    # A split is a property of the tree, so the tree reads its own.  Comparing
    # two trees by their splits belongs to the metric; deciding what a split is
    # does not.

    def _require_global_indices(self) -> np.ndarray:
        if self.global_leaf_indices is None:
            raise ValueError(
                "split identity requires global_leaf_indices; use read_tree to "
                "build the tree.")
        return self.global_leaf_indices

    def full_value(self) -> int:
        """The leaf values of the whole taxon set, combined."""
        g = self._require_global_indices()
        out = 0
        for i in range(self.n_leaves):
            out = combine_leaf_values(out, leaf_value(int(g[i])))
        return out

    def clade_value(self, v: int) -> int:
        """The leaf values below node ``v``, combined.

        Collects the subtree, so the cost is the subtree's size.  A caller that
        wants every node's value sweeps the tree once instead, which
        :meth:`split_lengths` does.
        """
        g = self._require_global_indices()
        if v < self.n_leaves:
            return leaf_value(int(g[v]))
        out = 0
        for leaf in _collect_subtree_leaves(v, self.left_child,
                                            self.right_child, self.n_leaves):
            out = combine_leaf_values(out, leaf_value(int(g[leaf])))
        return out

    def split_key(self, v: int, full: Optional[int] = None) -> int:
        """Bipartition key of the edge above node ``v``.

        The same for a clade and its complement, so it does not depend on where
        the tree is rooted.  ``full`` is :meth:`full_value`, which a caller
        keying many edges computes once.
        """
        if full is None:
            full = self.full_value()
        clade = self.clade_value(v)
        other = complement_value(full, clade)
        return clade if clade < other else other

    def masked_leaf_values(self, shared_labels) -> np.ndarray:
        """Per-leaf values, zero for a leaf outside ``shared_labels``.

        Two trees over different taxon sets are compared on the taxa they share,
        and the comparison reads the subtree each induces on that set.  Zero is
        the identity of :func:`combine_leaf_values`, so a leaf given zero adds
        nothing to any clade above it and the value below a node comes out equal
        to the value below the matching node of ``self.restrict(shared_labels)``.

        Returns
        -------
        np.ndarray
            uint64, shape ``(n_leaves,)``, indexed by leaf position.
        """
        keep = set(shared_labels)
        g = self._require_global_indices()
        out = np.zeros(self.n_leaves, dtype=np.uint64)
        for i in range(self.n_leaves):
            if self.names[i] in keep:
                out[i] = np.uint64(leaf_value(int(g[i])))
        return out

    def split_lengths(self) -> dict[int, float]:
        """Map each unrooted split of the tree to its total branch length.

        This is the vector form of a tree under the branch score: a tree is the
        lengths it assigns to its splits, and two trees are compared by
        comparing those lengths split by split.

        The two root-child edges share a key, because they are the two halves of
        one split, so their lengths sum.  Every other split maps to one edge.
        The map therefore holds ``n_nodes - 2`` entries and describes the
        unrooted tree.

        **The keys are in ascending order, and that order is part of the
        contract.**  A consumer adds the values in the order given, without
        sorting them again, and gets a result that does not depend on the
        rooting.  Rooting the same tree on another edge, or writing the children
        of a node the other way round, visits the nodes in another order, and
        floating-point addition is not associative.  Ascending key order holds a
        sum steady to the last bit, which keeps a tree that sits on a niche
        boundary in one niche.

        The keys come from one compiled post-order sweep, which carries each
        clade's value up to its parent.  Asking each edge for the leaf set below
        it instead collects that subtree, so the work summed to the tree's total
        path length: O(n log n) on a balanced tree and O(n squared) on a
        caterpillar, against O(n) here.  The two agree bit for bit, which
        ``tests/test_split_core.py`` holds them to.

        Kuhner & Felsenstein (1994) : the split-length vector a branch score compares.
        """
        keys, lengths = self.split_arrays()
        return dict(zip(keys.tolist(), lengths.tolist()))

    def split_arrays(self):
        """``(keys, lengths)`` of the unrooted splits, sorted by key.

        The array form of :meth:`split_lengths`, holding the same pairs in the
        same order.  A caller comparing two trees matches their keys by
        searching two sorted lists rather than looking each one up in a map.
        """
        from hifuku.split_core import sort_and_group, split_keys_and_lengths

        g = self._require_global_indices()
        # One dtype for each argument, so the sweep compiles once rather than
        # once for every combination a caller happens to hold.
        keys, lengths = split_keys_and_lengths(
            np.ascontiguousarray(self.left_child, dtype=np.int64),
            np.ascontiguousarray(self.right_child, dtype=np.int64),
            np.ascontiguousarray(self.edge_len, dtype=np.float64),
            np.ascontiguousarray(g, dtype=np.int64),
            int(self.n_leaves), int(self.n_nodes))
        keys, lengths, n = sort_and_group(keys, lengths, keys.size)
        return keys[:n], lengths[:n]

    def as_newick(self) -> str:
        """Serialize the tree to a Newick string, with a trailing semicolon."""
        return _arrays_to_newick(self) + ";"

    def write_newick(self, path: Union[str, Path]) -> None:
        """Write the tree to *path* as a UTF-8 Newick file."""
        Path(path).write_text(self.as_newick() + "\n", encoding="utf-8")

    def restrict(self, labels: list[str]) -> "HifukuTree":
        """
        Return a new HifukuTree pruned to the taxa in *labels*.

        Pruning can leave degree-2 internal nodes. This method removes each
        one and adds its edge length to the surviving child's edge.

        Parameters
        ----------
        labels : list[str]
            Taxon labels to keep. Every label must already be a leaf label
            in this tree.

        Returns
        -------
        HifukuTree
            A new, independent tree that contains only the given taxa.

        Raises
        ------
        ValueError
            If a label in *labels* is not a leaf label in this tree.

        Notes
        -----
        - Sukumaran & Holder (2010) : restriction semantics.
        """
        keep = set(labels)
        missing = keep - set(self.leaf_labels)
        if missing:
            raise ValueError(f"Labels not in tree: {sorted(missing)}")
        new_tree = _restrict_to_arrays(self, keep)
        if self.global_leaf_indices is not None:
            label_to_global = {
                self.names[i]: int(self.global_leaf_indices[i])
                for i in range(self.n_leaves)
            }
            glidx = np.full(new_tree.n_nodes, -1, dtype=np.int32)
            for i in range(new_tree.n_leaves):
                glidx[i] = label_to_global[new_tree.names[i]]
            new_tree.global_leaf_indices = glidx
        return new_tree

    def __repr__(self) -> str:
        return f"HifukuTree(n_taxa={self.n_leaves}, n_nodes={self.n_nodes})"

node_order class-attribute instance-attribute

node_order: Optional[ndarray] = None

int32, shape (n_nodes - n_leaves - 1,). Holds the non-root internal nodes in DFS post-order, with each child listed before its parent. The Felsenstein peeling traversal uses this order.

leaf_labels property

leaf_labels: list[str]

Taxon labels for the leaf nodes, in index order 0 to n_leaves - 1.

n_taxa property

n_taxa: int

Number of taxa in the tree. This equals n_leaves.

compute_node_order

compute_node_order() -> np.ndarray

Compute the non-root internal nodes in DFS post-order.

This method lists each child before its parent. It walks the tree using the left_child and right_child pointers, so the result is correct for any node index assignment.

Returns:

Type Description
ndarray

int32, shape (n_nodes - n_leaves - 1,). Non-root internal nodes in DFS post-order.

Source code in src/hifuku/tree_io.py
def compute_node_order(self) -> np.ndarray:
    """
    Compute the non-root internal nodes in DFS post-order.

    This method lists each child before its parent. It walks the tree
    using the left_child and right_child pointers, so the result is
    correct for any node index assignment.

    Returns
    -------
    np.ndarray
        int32, shape (n_nodes - n_leaves - 1,). Non-root internal nodes
        in DFS post-order.
    """
    return _post_order(
        np.ascontiguousarray(self.left_child, dtype=np.int32),
        np.ascontiguousarray(self.right_child, dtype=np.int32),
        int(self.root), int(self.n_leaves), int(self.n_nodes))

full_value

full_value() -> int

The leaf values of the whole taxon set, combined.

Source code in src/hifuku/tree_io.py
def full_value(self) -> int:
    """The leaf values of the whole taxon set, combined."""
    g = self._require_global_indices()
    out = 0
    for i in range(self.n_leaves):
        out = combine_leaf_values(out, leaf_value(int(g[i])))
    return out

clade_value

clade_value(v: int) -> int

The leaf values below node v, combined.

Collects the subtree, so the cost is the subtree's size. A caller that wants every node's value sweeps the tree once instead, which :meth:split_lengths does.

Source code in src/hifuku/tree_io.py
def clade_value(self, v: int) -> int:
    """The leaf values below node ``v``, combined.

    Collects the subtree, so the cost is the subtree's size.  A caller that
    wants every node's value sweeps the tree once instead, which
    :meth:`split_lengths` does.
    """
    g = self._require_global_indices()
    if v < self.n_leaves:
        return leaf_value(int(g[v]))
    out = 0
    for leaf in _collect_subtree_leaves(v, self.left_child,
                                        self.right_child, self.n_leaves):
        out = combine_leaf_values(out, leaf_value(int(g[leaf])))
    return out

split_key

split_key(v: int, full: Optional[int] = None) -> int

Bipartition key of the edge above node v.

The same for a clade and its complement, so it does not depend on where the tree is rooted. full is :meth:full_value, which a caller keying many edges computes once.

Source code in src/hifuku/tree_io.py
def split_key(self, v: int, full: Optional[int] = None) -> int:
    """Bipartition key of the edge above node ``v``.

    The same for a clade and its complement, so it does not depend on where
    the tree is rooted.  ``full`` is :meth:`full_value`, which a caller
    keying many edges computes once.
    """
    if full is None:
        full = self.full_value()
    clade = self.clade_value(v)
    other = complement_value(full, clade)
    return clade if clade < other else other

masked_leaf_values

masked_leaf_values(shared_labels) -> np.ndarray

Per-leaf values, zero for a leaf outside shared_labels.

Two trees over different taxon sets are compared on the taxa they share, and the comparison reads the subtree each induces on that set. Zero is the identity of :func:combine_leaf_values, so a leaf given zero adds nothing to any clade above it and the value below a node comes out equal to the value below the matching node of self.restrict(shared_labels).

Returns:

Type Description
ndarray

uint64, shape (n_leaves,), indexed by leaf position.

Source code in src/hifuku/tree_io.py
def masked_leaf_values(self, shared_labels) -> np.ndarray:
    """Per-leaf values, zero for a leaf outside ``shared_labels``.

    Two trees over different taxon sets are compared on the taxa they share,
    and the comparison reads the subtree each induces on that set.  Zero is
    the identity of :func:`combine_leaf_values`, so a leaf given zero adds
    nothing to any clade above it and the value below a node comes out equal
    to the value below the matching node of ``self.restrict(shared_labels)``.

    Returns
    -------
    np.ndarray
        uint64, shape ``(n_leaves,)``, indexed by leaf position.
    """
    keep = set(shared_labels)
    g = self._require_global_indices()
    out = np.zeros(self.n_leaves, dtype=np.uint64)
    for i in range(self.n_leaves):
        if self.names[i] in keep:
            out[i] = np.uint64(leaf_value(int(g[i])))
    return out

split_lengths

split_lengths() -> dict[int, float]

Map each unrooted split of the tree to its total branch length.

This is the vector form of a tree under the branch score: a tree is the lengths it assigns to its splits, and two trees are compared by comparing those lengths split by split.

The two root-child edges share a key, because they are the two halves of one split, so their lengths sum. Every other split maps to one edge. The map therefore holds n_nodes - 2 entries and describes the unrooted tree.

The keys are in ascending order, and that order is part of the contract. A consumer adds the values in the order given, without sorting them again, and gets a result that does not depend on the rooting. Rooting the same tree on another edge, or writing the children of a node the other way round, visits the nodes in another order, and floating-point addition is not associative. Ascending key order holds a sum steady to the last bit, which keeps a tree that sits on a niche boundary in one niche.

The keys come from one compiled post-order sweep, which carries each clade's value up to its parent. Asking each edge for the leaf set below it instead collects that subtree, so the work summed to the tree's total path length: O(n log n) on a balanced tree and O(n squared) on a caterpillar, against O(n) here. The two agree bit for bit, which tests/test_split_core.py holds them to.

Kuhner & Felsenstein (1994) : the split-length vector a branch score compares.

Source code in src/hifuku/tree_io.py
def split_lengths(self) -> dict[int, float]:
    """Map each unrooted split of the tree to its total branch length.

    This is the vector form of a tree under the branch score: a tree is the
    lengths it assigns to its splits, and two trees are compared by
    comparing those lengths split by split.

    The two root-child edges share a key, because they are the two halves of
    one split, so their lengths sum.  Every other split maps to one edge.
    The map therefore holds ``n_nodes - 2`` entries and describes the
    unrooted tree.

    **The keys are in ascending order, and that order is part of the
    contract.**  A consumer adds the values in the order given, without
    sorting them again, and gets a result that does not depend on the
    rooting.  Rooting the same tree on another edge, or writing the children
    of a node the other way round, visits the nodes in another order, and
    floating-point addition is not associative.  Ascending key order holds a
    sum steady to the last bit, which keeps a tree that sits on a niche
    boundary in one niche.

    The keys come from one compiled post-order sweep, which carries each
    clade's value up to its parent.  Asking each edge for the leaf set below
    it instead collects that subtree, so the work summed to the tree's total
    path length: O(n log n) on a balanced tree and O(n squared) on a
    caterpillar, against O(n) here.  The two agree bit for bit, which
    ``tests/test_split_core.py`` holds them to.

    Kuhner & Felsenstein (1994) : the split-length vector a branch score compares.
    """
    keys, lengths = self.split_arrays()
    return dict(zip(keys.tolist(), lengths.tolist()))

split_arrays

split_arrays()

(keys, lengths) of the unrooted splits, sorted by key.

The array form of :meth:split_lengths, holding the same pairs in the same order. A caller comparing two trees matches their keys by searching two sorted lists rather than looking each one up in a map.

Source code in src/hifuku/tree_io.py
def split_arrays(self):
    """``(keys, lengths)`` of the unrooted splits, sorted by key.

    The array form of :meth:`split_lengths`, holding the same pairs in the
    same order.  A caller comparing two trees matches their keys by
    searching two sorted lists rather than looking each one up in a map.
    """
    from hifuku.split_core import sort_and_group, split_keys_and_lengths

    g = self._require_global_indices()
    # One dtype for each argument, so the sweep compiles once rather than
    # once for every combination a caller happens to hold.
    keys, lengths = split_keys_and_lengths(
        np.ascontiguousarray(self.left_child, dtype=np.int64),
        np.ascontiguousarray(self.right_child, dtype=np.int64),
        np.ascontiguousarray(self.edge_len, dtype=np.float64),
        np.ascontiguousarray(g, dtype=np.int64),
        int(self.n_leaves), int(self.n_nodes))
    keys, lengths, n = sort_and_group(keys, lengths, keys.size)
    return keys[:n], lengths[:n]

as_newick

as_newick() -> str

Serialize the tree to a Newick string, with a trailing semicolon.

Source code in src/hifuku/tree_io.py
def as_newick(self) -> str:
    """Serialize the tree to a Newick string, with a trailing semicolon."""
    return _arrays_to_newick(self) + ";"

write_newick

write_newick(path: Union[str, Path]) -> None

Write the tree to path as a UTF-8 Newick file.

Source code in src/hifuku/tree_io.py
def write_newick(self, path: Union[str, Path]) -> None:
    """Write the tree to *path* as a UTF-8 Newick file."""
    Path(path).write_text(self.as_newick() + "\n", encoding="utf-8")

restrict

restrict(labels: list[str]) -> 'HifukuTree'

Return a new HifukuTree pruned to the taxa in labels.

Pruning can leave degree-2 internal nodes. This method removes each one and adds its edge length to the surviving child's edge.

Parameters:

Name Type Description Default
labels list[str]

Taxon labels to keep. Every label must already be a leaf label in this tree.

required

Returns:

Type Description
HifukuTree

A new, independent tree that contains only the given taxa.

Raises:

Type Description
ValueError

If a label in labels is not a leaf label in this tree.

Notes
Source code in src/hifuku/tree_io.py
def restrict(self, labels: list[str]) -> "HifukuTree":
    """
    Return a new HifukuTree pruned to the taxa in *labels*.

    Pruning can leave degree-2 internal nodes. This method removes each
    one and adds its edge length to the surviving child's edge.

    Parameters
    ----------
    labels : list[str]
        Taxon labels to keep. Every label must already be a leaf label
        in this tree.

    Returns
    -------
    HifukuTree
        A new, independent tree that contains only the given taxa.

    Raises
    ------
    ValueError
        If a label in *labels* is not a leaf label in this tree.

    Notes
    -----
    - Sukumaran & Holder (2010) : restriction semantics.
    """
    keep = set(labels)
    missing = keep - set(self.leaf_labels)
    if missing:
        raise ValueError(f"Labels not in tree: {sorted(missing)}")
    new_tree = _restrict_to_arrays(self, keep)
    if self.global_leaf_indices is not None:
        label_to_global = {
            self.names[i]: int(self.global_leaf_indices[i])
            for i in range(self.n_leaves)
        }
        glidx = np.full(new_tree.n_nodes, -1, dtype=np.int32)
        for i in range(new_tree.n_leaves):
            glidx[i] = label_to_global[new_tree.names[i]]
        new_tree.global_leaf_indices = glidx
    return new_tree

read_tree

read_tree(source: Union[str, Path], taxon_table: TaxonTable, *, from_string: bool = False) -> HifukuTree

Parse a Newick tree and register its leaf taxa into taxon_table.

Parameters:

Name Type Description Default
source str or Path

Path to a Newick file, or a Newick string when from_string is True.

required
taxon_table TaxonTable

Shared global TaxonTable; leaf taxa are registered (added if absent).

required
from_string bool

If True, treat source as a Newick string rather than a file path.

False

Returns:

Type Description
HifukuTree

Parsed tree with node_order set in DFS post-order.

Source code in src/hifuku/tree_io.py
def read_tree(
    source: Union[str, Path],
    taxon_table: TaxonTable,
    *,
    from_string: bool = False,
) -> HifukuTree:
    """
    Parse a Newick tree and register its leaf taxa into *taxon_table*.

    Parameters
    ----------
    source : str or Path
        Path to a Newick file, or a Newick string when *from_string* is True.
    taxon_table : TaxonTable
        Shared global TaxonTable; leaf taxa are registered (added if absent).
    from_string : bool
        If True, treat *source* as a Newick string rather than a file path.

    Returns
    -------
    HifukuTree
        Parsed tree with node_order set in DFS post-order.
    """
    if from_string:
        newick = str(source).strip().rstrip(";")
    else:
        newick = Path(source).read_text(encoding="utf-8").strip().rstrip(";")

    tree = _parse_newick(newick)
    for lbl in tree.leaf_labels:
        taxon_table.require(lbl)
    glidx = np.full(tree.n_nodes, -1, dtype=np.int32)
    for i in range(tree.n_leaves):
        glidx[i] = taxon_table.index_of(tree.names[i])
    tree.global_leaf_indices = glidx
    return tree