1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| from typing import *
import numpy as np from rich import progress
def neighbor_joining(_otu: List[str], _dist: List[List[float]]): """ Args: _otu: names of otus _dist: distances dict for otus, (i, j) -> dist, i less than j """
nodes = [{"name": e, "parent": None} for e in _otu] n = len(nodes)
otu_distances: np.ndarray = np.array(_dist, dtype=np.float_) otu_distances = np.concatenate([otu_distances, np.zeros((n - 2, n))], axis=0) otu_distances = np.concatenate([otu_distances, np.zeros((2 * n - 2, n - 2))], axis=1)
branch_lengths = np.zeros_like(otu_distances)
current_otus = list(range(n)) for _ in progress.track(range(n - 3)): n = len(current_otus) otu_dists = otu_distances[current_otus, ...][..., current_otus]
otu_dists_to_others: np.ndarray = np.sum(otu_dists, axis=0) / (n - 2)
graph_branch_length = otu_dists - otu_dists_to_others.reshape(-1, 1) - otu_dists_to_others.reshape(1, -1)
otu1, otu2 = min(((i, j) for i in range(n) for j in range(i + 1, n)), key=lambda x: graph_branch_length[x])
n1, n2, n3 = current_otus[otu1], current_otus[otu2], len(nodes) new_node = {"name": f"#{n3}", "parent": None, "children": (n1, n2)} nodes[n1]["parent"] = n3 nodes[n2]["parent"] = n3
otu_distances[n3, ...] = (otu_distances[n1, ...] + otu_distances[n2, ...]) / 2 otu_distances[..., n3] = (otu_distances[..., n1] + otu_distances[..., n2]) / 2 otu_distances[n3, [n1, n2, n3]] = 0 otu_distances[[n1, n2, n3], n3] = 0
branch_lengths[n1, n3] = branch_lengths[n3, n1] = ( otu_distances[n1, n2] + otu_dists_to_others[otu1] - otu_dists_to_others[otu2] - otu_distances[nodes[n1].get("children", (n1, n1))] ) / 2 branch_lengths[n2, n3] = branch_lengths[n3, n2] = ( otu_distances[n2, n1] + otu_dists_to_others[otu2] - otu_dists_to_others[otu1] - otu_distances[nodes[n2].get("children", (n2, n2))] ) / 2
current_otus.remove(n1) current_otus.remove(n2)
nodes.append(new_node) current_otus.append(n3)
n3 = current_otus.pop() n2 = current_otus.pop() n1 = current_otus.pop()
nr = len(nodes) root_node = {"name": f"#{nr}", "parent": None, "children": (n1, n2, n3)} nodes[n1]["parent"] = nr nodes[n2]["parent"] = nr nodes[n3]["parent"] = nr
branch_lengths[n1, nr] = branch_lengths[nr, n1] = ( otu_distances[n1, n2] + otu_distances[n1, n3] - otu_distances[n2, n3] - otu_distances[nodes[n1].get("children", (n1, n1))] ) / 2 branch_lengths[n2, nr] = branch_lengths[nr, n2] = ( otu_distances[n2, n1] + otu_distances[n2, n3] - otu_distances[n1, n3] - otu_distances[nodes[n2].get("children", (n2, n2))] ) / 2 branch_lengths[n3, nr] = branch_lengths[nr, n3] = ( otu_distances[n3, n1] + otu_distances[n3, n2] - otu_distances[n1, n2] - otu_distances[nodes[n3].get("children", (n3, n3))] ) / 2
nodes.append(root_node)
return nodes, branch_lengths
def draw_njtree(nodes: List[Dict[str, Any]], branch_lengths: np.ndarray): lines = []
stack = [] for i, node in enumerate(nodes): if not node["parent"]: stack.append((0, 0, i, node)) while stack: level, count, idx, top = stack.pop()
if level > 0: level_branchs = [] pre_level = 0 for _level, _, _, _ in stack[:len(stack)-count]: if _level > pre_level: level_branchs.append(" " * (_level - pre_level - 1) + "│ ") pre_level = _level level_branchs.append(" " * (level - pre_level - 1) + ("├──" if count > 0 else "└──")) edge_length = f"({branch_lengths[idx, top['parent']]:.6f})" lines.append("".join((*level_branchs, top["name"], edge_length))) else: lines.append(top["name"])
for i, child in enumerate(top.get("children", [])): stack.append((level + 1, i, child, nodes[child]))
return "\n".join(lines)
if __name__ == "__main__": r = neighbor_joining( list(map(str, range(1, 9))), [[0, 7, 8, 11, 13, 16, 13, 17], [7, 0, 5, 8, 10, 13, 10, 14], [8, 5, 0, 5, 7, 10, 7, 11], [11, 8, 5, 0, 8, 11, 8, 12], [13, 10, 7, 8, 0, 5, 6, 10], [16, 13, 10, 11, 5, 0, 9, 13], [13, 10, 7, 8, 6, 9, 0, 8], [17, 14, 11, 12, 10, 13, 8, 0]] )
tree = draw_njtree(r[0], r[1]) print(tree)
|