multree 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
multree/holm_python.py ADDED
@@ -0,0 +1,295 @@
1
+ from ete3 import Tree
2
+ import networkx as nx
3
+ from collections import Counter
4
+ try: # as a package (multree)
5
+ from .reticulate_tree import ReticulateTree
6
+ except ImportError: # as a flat folder on sys.path
7
+ from reticulate_tree import ReticulateTree
8
+
9
+
10
+ class Multiset:
11
+ def __init__(self):
12
+ self.counter = Counter()
13
+ self.concatenated = ""
14
+
15
+ def add(self, item):
16
+ if isinstance(item, Multiset):
17
+ self.counter.update(item.counter)
18
+ else:
19
+ self.counter[item] += 1
20
+
21
+ def addSorted(self, item):
22
+ self.add(item)
23
+
24
+ def setConcatenatedElements(self, label=None):
25
+ if label is not None:
26
+ self.concatenated = label
27
+ else:
28
+ flat = sorted(self.counter.elements())
29
+ self.concatenated = "|".join(flat)
30
+
31
+ def __repr__(self):
32
+ return f"{dict(self.counter)}"
33
+
34
+ def __eq__(self, other):
35
+ if not isinstance(other, Multiset):
36
+ return False
37
+ return self.counter == other.counter and self.concatenated == other.concatenated
38
+
39
+ def __hash__(self):
40
+ return hash((frozenset(self.counter.items()), self.concatenated))
41
+
42
+
43
+ class HeightList:
44
+ def __init__(self):
45
+ self.entries = [] # list of tuples: (node, multiset)
46
+
47
+ def addSorted(self, node, multiset):
48
+ self.entries.append((node, multiset))
49
+ self.entries.sort(key=lambda x: repr(x[1])) # Sort by multiset string
50
+
51
+ def remove(self, node):
52
+ self.entries = [(n, m) for n, m in self.entries if n != node]
53
+
54
+ def __getitem__(self, idx):
55
+ return self.entries[idx][0]
56
+
57
+ def __len__(self):
58
+ return len(self.entries)
59
+
60
+ def isEmpty(self):
61
+ return len(self.entries) == 0
62
+
63
+ def size(self):
64
+ return len(self.entries)
65
+
66
+
67
+ class MultilabeledTree:
68
+ def __init__(self, newick=None):
69
+ self.tree = Tree(newick, format=1) if newick else Tree()
70
+ self.all_multisets = {}
71
+ self.all_node_heights = {}
72
+ self.all_multisets = self.collect_all_multisets()
73
+ self.all_node_heights = self.collect_all_node_heights()
74
+
75
+ def get_multisets(self, node):
76
+ cluster_set = []
77
+ self._get_multisets_rec(node, cluster_set)
78
+ return cluster_set
79
+
80
+ def _get_multisets_rec(self, node, cluster_set):
81
+ if node.is_leaf():
82
+ cluster = Multiset()
83
+ cluster.setConcatenatedElements(node.name)
84
+ cluster.add(node.name)
85
+ cluster_set.append(cluster)
86
+ return cluster
87
+
88
+ if len(node.children) == 1 and (node.up and len(node.up.children) > 1):
89
+ return self._get_multisets_rec(node.children[0], cluster_set)
90
+
91
+ cluster = Multiset()
92
+ for child in node.children:
93
+ cluster.addSorted(self._get_multisets_rec(child, cluster_set))
94
+ cluster.setConcatenatedElements()
95
+ cluster_set.append(cluster)
96
+ return cluster
97
+
98
+ def collect_all_multisets(self):
99
+ multisets = {}
100
+ self._collect_all_multisets_rec(self.tree, multisets)
101
+ return multisets
102
+
103
+ def _collect_all_multisets_rec(self, node, multisets):
104
+ if node.is_leaf():
105
+ cluster = Multiset()
106
+ cluster.setConcatenatedElements(node.name)
107
+ cluster.add(node.name)
108
+ multisets[id(node)] = cluster
109
+ return cluster
110
+
111
+ cluster = Multiset()
112
+ for child in node.children:
113
+ cluster.addSorted(self._collect_all_multisets_rec(child, multisets))
114
+ cluster.setConcatenatedElements()
115
+ multisets[id(node)] = cluster
116
+ return cluster
117
+
118
+ def collect_all_node_heights(self):
119
+ heights = {}
120
+ self._collect_node_heights_rec(self.tree, heights)
121
+ return heights
122
+
123
+ def _collect_node_heights_rec(self, node, heights):
124
+ if node.is_leaf():
125
+ heights[id(node)] = 0
126
+ return 0
127
+ max_height = 0
128
+ for child in node.children:
129
+ h = 1 + self._collect_node_heights_rec(child, heights)
130
+ max_height = max(max_height, h)
131
+ heights[id(node)] = max_height
132
+ return max_height
133
+
134
+ def get_multiset(self, node):
135
+ return self.all_multisets.get(id(node))
136
+
137
+ def get_height(self, node):
138
+ return self.all_node_heights.get(id(node), 0)
139
+
140
+ def get_all_taxa(self):
141
+ return {leaf.name for leaf in self.tree.iter_leaves()}
142
+
143
+ def get_descending_nodes(self, node):
144
+ return [node] + list(node.iter_descendants())
145
+
146
+ def get_ascending_nodes(self, node):
147
+ asc = []
148
+ while node.up:
149
+ asc.append(node.up)
150
+ node = node.up
151
+ return asc
152
+
153
+ def compute_all_canonical_forms(self, root):
154
+ self._canonical_map = {}
155
+
156
+ def recurse(node):
157
+ """
158
+ Recursively compute a canonical string representation of a subtree rooted at `node`,
159
+ such that isomorphic subtrees (with possibly duplicated leaves) get the same string.
160
+ """
161
+ if node.is_leaf():
162
+ canon = node.name
163
+ else:
164
+ child_encodings = sorted([recurse(c) for c in node.children])
165
+ canon = '(' + ','.join(child_encodings) + ')'
166
+ self._canonical_map[node] = canon
167
+ return canon
168
+
169
+ recurse(root)
170
+
171
+ def are_strictly_isomorphic(self, node1, node2):
172
+ """
173
+ Strict topological isomorphism, allowing for duplicated taxa.
174
+ """
175
+ #print(node1.get_ascii(show_internal=True))
176
+ #print(node2.get_ascii(show_internal=True))
177
+ return self._canonical_map[node1] == self._canonical_map[node2]
178
+
179
+ def apply_exact_network(self, strict=True):
180
+ t = MultilabeledTree(self.tree.write(format=1)) # fresh copy
181
+ root = t.tree
182
+ h_max = {}
183
+ rootHeight = t.get_height(root)
184
+ h = HeightList()
185
+ h.addSorted(root, t.get_multiset(root))
186
+ h_max[rootHeight] = h
187
+
188
+ if strict:
189
+ t.compute_all_canonical_forms(root)
190
+ iso_cond = lambda a, b: t.are_strictly_isomorphic(a, b)
191
+ else:
192
+ iso_cond = lambda a, b: t.get_multiset(a) == t.get_multiset(b)
193
+
194
+ for i in range(rootHeight, -1, -1):
195
+ l_h = h_max.get(i)
196
+ if not l_h:
197
+ continue
198
+ while not l_h.isEmpty():
199
+ t_max = l_h[0]
200
+ for child in t_max.children:
201
+ h_j = t.get_height(child)
202
+ h_list = h_max.get(h_j)
203
+ if h_list is None:
204
+ h_list = HeightList()
205
+ h_max[h_j] = h_list
206
+ h_list.addSorted(child, t.get_multiset(child))
207
+
208
+ isomorphs = []
209
+ for j in range(1, l_h.size()):
210
+ w = l_h[j]
211
+ if iso_cond(t_max, w):
212
+ isomorphs.append(w)
213
+ else:
214
+ break
215
+
216
+ if isomorphs:
217
+ if not t_max.up:
218
+ continue # Skip if root
219
+
220
+ parent = t_max.up
221
+ u = parent.add_child(name=None)
222
+ parent.remove_child(t_max)
223
+ u.add_child(t_max)
224
+ t.set_reticulate_edge(parent, u)
225
+ t.set_edge_weight(parent, u, 0)
226
+
227
+ for w in isomorphs:
228
+ if not w.up:
229
+ continue
230
+ w_parent = w.up
231
+ w.detach()
232
+ w_parent.add_child(u)
233
+ t.set_reticulate_edge(w_parent, u)
234
+ t.set_edge_weight(w_parent, u, 0)
235
+
236
+ for iso in isomorphs:
237
+ l_h.remove(iso)
238
+ l_h.remove(t_max)
239
+
240
+ print("number of reticulations:", t.get_number_reticulate_edges() // 2)
241
+ return t
242
+
243
+ def set_reticulate_edge(self, parent, child):
244
+ if not hasattr(self, "_reticulate_edges"):
245
+ self._reticulate_edges = set()
246
+ self._reticulate_edges.add((id(parent), id(child)))
247
+
248
+ def set_edge_weight(self, parent, child, weight):
249
+ if not hasattr(self, "_edge_weights"):
250
+ self._edge_weights = {}
251
+ self._edge_weights[(id(parent), id(child))] = weight
252
+
253
+ def is_reticulate_edge(self, parent, child):
254
+ return (id(parent), id(child)) in getattr(self, "_reticulate_edges", set())
255
+
256
+ def get_number_reticulate_edges(self):
257
+ return len(getattr(self, "_reticulate_edges", []))
258
+
259
+ def to_networkx(self):
260
+ G = nx.DiGraph()
261
+
262
+ # mapping ete3 node id to display name
263
+ def get_node_label(node):
264
+ return node.name if node.name else str(id(node))
265
+
266
+ # add nodes
267
+ for node in self.tree.traverse("preorder"):
268
+ G.add_node(id(node), label=get_node_label(node))
269
+
270
+ # add edges
271
+ for node in self.tree.traverse("preorder"):
272
+ for child in node.children:
273
+ G.add_edge(id(node), id(child), reticulate=self.is_reticulate_edge(node, child))
274
+
275
+ return G
276
+
277
+ if __name__ == "__main__":
278
+ newick = "((((c,w),d),(x,((z,y),w))),((a,(x,((y,z),w))),b));"
279
+ mlt = MultilabeledTree(newick)
280
+
281
+ print("All Taxa:", mlt.get_all_taxa())
282
+ print("Special Nodes:", mlt.get_number_of_special_nodes())
283
+
284
+ for node in mlt.tree.traverse():
285
+ print(f"Node: {node.name or 'internal'}, Height: {mlt.get_height(node)}, Multiset: {mlt.get_multiset(node)}")
286
+
287
+ exact_net = mlt.apply_exact_network()
288
+
289
+ print(mlt.get_multisets(mlt.tree.get_tree_root()))
290
+ print(mlt.get_height(mlt.tree.get_tree_root()))
291
+
292
+ dag = exact_net.to_networkx()
293
+
294
+ new_obj = ReticulateTree(dag)
295
+ new_obj.visualize()