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/__init__.py +7 -0
- multree/compare_reticulations.py +514 -0
- multree/holm_python.py +295 -0
- multree/reticulate_tree.py +1516 -0
- multree-1.0.0.dist-info/METADATA +144 -0
- multree-1.0.0.dist-info/RECORD +9 -0
- multree-1.0.0.dist-info/WHEEL +5 -0
- multree-1.0.0.dist-info/licenses/LICENSE +21 -0
- multree-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1516 @@
|
|
|
1
|
+
import webbrowser
|
|
2
|
+
import networkx as nx
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from ete3 import Tree, TreeNode
|
|
6
|
+
from pyvis.network import Network
|
|
7
|
+
from collections import defaultdict, Counter
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
# The per-reticulation "malformed inference" warning below floods scoring output
|
|
11
|
+
# (thousands of lines on over-reticulate reconstructions) and is not actionable
|
|
12
|
+
# during benchmarking. Off by default; set RETICULATE_WARN_MALFORMED=1 to re-enable.
|
|
13
|
+
_WARN_MALFORMED_RETIC = os.environ.get("RETICULATE_WARN_MALFORMED") == "1"
|
|
14
|
+
|
|
15
|
+
# Convension for this class:
|
|
16
|
+
# _func() for private methods, may or may not be static
|
|
17
|
+
# func() for public methods, therefore we should try to make them static or classmethods [not to modify the instance state]
|
|
18
|
+
|
|
19
|
+
class ReticulateTree:
|
|
20
|
+
|
|
21
|
+
def __init__(self, input_data, is_multree=False, threshold=None, normalize=None,
|
|
22
|
+
refold=False):
|
|
23
|
+
self.tree = None
|
|
24
|
+
self.tree_str = None
|
|
25
|
+
self.dag = None
|
|
26
|
+
self.retnodes = None
|
|
27
|
+
self.threshold = threshold
|
|
28
|
+
self.normalize = normalize
|
|
29
|
+
self.refold = refold
|
|
30
|
+
|
|
31
|
+
input_type = self._determine_input_type(input_data)
|
|
32
|
+
|
|
33
|
+
if input_type == 'str:newick':
|
|
34
|
+
self.tree_str = input_data
|
|
35
|
+
self.tree = Tree(input_data, format=1)
|
|
36
|
+
self._init_from_tree(is_multree)
|
|
37
|
+
|
|
38
|
+
elif input_type == 'ete3tree':
|
|
39
|
+
self.tree = input_data
|
|
40
|
+
self.tree_str = input_data.write(format=1)
|
|
41
|
+
self._init_from_tree(is_multree)
|
|
42
|
+
|
|
43
|
+
elif input_type == 'str:enewick':
|
|
44
|
+
self._init_from_dag(
|
|
45
|
+
self.__class__.enewick_to_dag(input_data)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
elif input_type.endswith('nexml'):
|
|
49
|
+
raise NotImplementedError('NeXML input is not yet supported for ReticulateTree initialization.')
|
|
50
|
+
#dag = self._parse_nexml_to_dag(input_data, input_type.split(':')[0])
|
|
51
|
+
#self._init_from_dag(dag)
|
|
52
|
+
|
|
53
|
+
elif input_type == 'nxdag':
|
|
54
|
+
self._init_from_dag(input_data)
|
|
55
|
+
|
|
56
|
+
# XOR None check to ensure correct param tracking
|
|
57
|
+
if (self.threshold is None) ^ (self.normalize is None):
|
|
58
|
+
print('Warning: Under the current settings, MUL-tree folding parameters are not used.')
|
|
59
|
+
self.threshold = None
|
|
60
|
+
self.normalize = None
|
|
61
|
+
|
|
62
|
+
self.retnodes = self.get_reticulation_nodes()
|
|
63
|
+
|
|
64
|
+
def _init_from_tree(self, is_multree):
|
|
65
|
+
if is_multree or self.check_duplicated():
|
|
66
|
+
if self.threshold is not None or self.normalize is not None:
|
|
67
|
+
# Polyphest's multree folding defaults
|
|
68
|
+
if self.threshold is None:
|
|
69
|
+
self.threshold = 0.2
|
|
70
|
+
if self.normalize is None:
|
|
71
|
+
self.normalize = True
|
|
72
|
+
print("Note: Polyphest's multree folding does NOT guarantee DAG back-translatability to the original (MUL-)tree!")
|
|
73
|
+
self.dag = self.__class__.polyphest_multree_to_dag(self.tree, threshold=self.threshold, normalize=self.normalize)
|
|
74
|
+
else:
|
|
75
|
+
self.dag = self.__class__.multree_to_dag(self.tree, strict=True)
|
|
76
|
+
else:
|
|
77
|
+
self.dag = self.tree_to_dag(self.tree)
|
|
78
|
+
|
|
79
|
+
def _init_from_dag(self, dag):
|
|
80
|
+
'''
|
|
81
|
+
Take a network that arrives already folded, such as extended Newick.
|
|
82
|
+
|
|
83
|
+
With refold=True the network is unfolded to the MUL-tree it exhibits
|
|
84
|
+
and folded again with Holm, which maps any binary resolution back onto
|
|
85
|
+
the canonical N(T). Huber et al. 2006 prove a minimal binary network
|
|
86
|
+
exhibiting a MUL-tree is a resolution of N(T), so this compares such a
|
|
87
|
+
network at the same resolution level as every method whose output is a
|
|
88
|
+
MUL-tree, instead of penalising it for committing to an event ordering
|
|
89
|
+
that no MUL-tree determines.
|
|
90
|
+
|
|
91
|
+
Off by default. get_modified_mu_representation rebuilds a
|
|
92
|
+
ReticulateTree around a suppressed graph, and refolding there would
|
|
93
|
+
silently change the metric.
|
|
94
|
+
'''
|
|
95
|
+
self.tree = self.__class__.dag_to_multree(dag, match_dag=True)
|
|
96
|
+
self.tree_str = self.tree.write(format=1)
|
|
97
|
+
self.dag = (self.__class__.multree_to_dag(self.tree, strict=True)
|
|
98
|
+
if self.refold else dag)
|
|
99
|
+
|
|
100
|
+
def check_duplicated(self):
|
|
101
|
+
''' Check if the tree has duplicated labels (i.e., multiple leaves with the same name). '''
|
|
102
|
+
return any(v > 1 for v in self.get_leaf_counts().values())
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def _determine_input_type(input_data):
|
|
106
|
+
'''
|
|
107
|
+
Determine the type of input data provided to ReticulateTree.
|
|
108
|
+
Returns a string indicating the type:
|
|
109
|
+
- 'str:newick' for Newick strings
|
|
110
|
+
- 'str:enewick' for enriched Newick strings with #H markers
|
|
111
|
+
- 'str:nexml' for NeXML strings
|
|
112
|
+
- 'ete3tree' for ETE3 Tree objects
|
|
113
|
+
- 'nxdag' for NetworkX directed acyclic graphs (DAGs)
|
|
114
|
+
- 'file:nexml' for file-like objects (assumed to be NeXML)
|
|
115
|
+
'''
|
|
116
|
+
input_type = None
|
|
117
|
+
if isinstance(input_data, str):
|
|
118
|
+
input_str = input_data.strip()
|
|
119
|
+
# Can be Newick, enriched Newick, or NeXML - check format
|
|
120
|
+
if input_str.endswith('nexml>'):
|
|
121
|
+
input_type = 'str:nexml'
|
|
122
|
+
print('Warning: NeXML input is only supported for networks!')
|
|
123
|
+
else:
|
|
124
|
+
if not input_str.endswith(';'):
|
|
125
|
+
raise ValueError('String format unrecognized. Must end with ";" for Newick / enriched Newick, or "nexml>" for NeXML.')
|
|
126
|
+
else:
|
|
127
|
+
if '#' in input_str or '//' in input_str:
|
|
128
|
+
input_type = 'str:enewick'
|
|
129
|
+
else:
|
|
130
|
+
input_type = 'str:newick'
|
|
131
|
+
elif isinstance(input_data, Tree):
|
|
132
|
+
input_type = 'ete3tree'
|
|
133
|
+
elif isinstance(input_data, nx.DiGraph):
|
|
134
|
+
input_type = 'nxdag'
|
|
135
|
+
elif hasattr(input_data, 'read'):
|
|
136
|
+
# Assume file-like object
|
|
137
|
+
input_type = 'file:nexml' # Default to NeXML for file-like objects
|
|
138
|
+
print('Warning: NeXML input is only supported for networks!')
|
|
139
|
+
else:
|
|
140
|
+
raise ValueError(f'Unsupported input type: {type(input_data)}')
|
|
141
|
+
return input_type
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def get_dag_root(G):
|
|
145
|
+
''' Get the root of a directed acyclic graph (DAG). '''
|
|
146
|
+
roots = [n for n, d in G.in_degree() if d == 0]
|
|
147
|
+
if len(roots) != 1:
|
|
148
|
+
raise ValueError('Expected exactly one root.')
|
|
149
|
+
return roots[0]
|
|
150
|
+
|
|
151
|
+
@staticmethod
|
|
152
|
+
def compute_depths(G):
|
|
153
|
+
''' Compute DAG depths to mimic layered layout. '''
|
|
154
|
+
root = ReticulateTree.get_dag_root(G)
|
|
155
|
+
depths = {node: float('-inf') for node in G.nodes}
|
|
156
|
+
depths[root] = 0
|
|
157
|
+
# Topological sort guarantees that all parents are visited before children
|
|
158
|
+
for node in nx.topological_sort(G):
|
|
159
|
+
for child in G.successors(node):
|
|
160
|
+
proposed_depth = depths[node] + 1
|
|
161
|
+
if proposed_depth > depths[child]:
|
|
162
|
+
depths[child] = proposed_depth
|
|
163
|
+
return depths
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def is_reticulation_node(G, node):
|
|
167
|
+
''' Check if a DAG node is a reticulation node (including autopolyploidy nodes). '''
|
|
168
|
+
return G.in_degree(node) > 1 or G.nodes[node].get('autopolyploidy', False)
|
|
169
|
+
|
|
170
|
+
# ───── MODULE: From simple tree to network ─────
|
|
171
|
+
|
|
172
|
+
@staticmethod
|
|
173
|
+
def tree_to_dag(t):
|
|
174
|
+
'''
|
|
175
|
+
Convert ete3 singly-labeled tree to networkx DAG (no reticulations)
|
|
176
|
+
'''
|
|
177
|
+
G = nx.DiGraph()
|
|
178
|
+
for node in t.traverse('postorder'):
|
|
179
|
+
nid = id(node)
|
|
180
|
+
G.add_node(
|
|
181
|
+
nid,
|
|
182
|
+
ete=node, # original ete3 node
|
|
183
|
+
label=node.name, # display label # node.name if node.is_leaf() else str(nid)
|
|
184
|
+
)
|
|
185
|
+
if node.up:
|
|
186
|
+
if hasattr(node, 'dist'):
|
|
187
|
+
G.add_edge(id(node.up), nid, length=node.dist)
|
|
188
|
+
else:
|
|
189
|
+
G.add_edge(id(node.up), nid)
|
|
190
|
+
return G
|
|
191
|
+
|
|
192
|
+
# ───── MODULE: From MUL-tree to network ─────
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _compute_height_map(root):
|
|
196
|
+
height_map = defaultdict(list)
|
|
197
|
+
heights = {} # only used inside this loop to compute parent's height
|
|
198
|
+
|
|
199
|
+
for node in root.traverse('postorder'):
|
|
200
|
+
if node.is_leaf():
|
|
201
|
+
h = 0
|
|
202
|
+
else:
|
|
203
|
+
h = max(heights[child] for child in node.children) + 1
|
|
204
|
+
heights[node] = h
|
|
205
|
+
height_map[h].append(node)
|
|
206
|
+
|
|
207
|
+
return height_map
|
|
208
|
+
|
|
209
|
+
@staticmethod
|
|
210
|
+
def _compute_sorted_multisets(root):
|
|
211
|
+
'''
|
|
212
|
+
Returns a dict: {node: tuple(sorted multiset items)} for each node.
|
|
213
|
+
'''
|
|
214
|
+
sorted_multisets = {}
|
|
215
|
+
multisets = {}
|
|
216
|
+
|
|
217
|
+
for node in root.traverse('postorder'):
|
|
218
|
+
if node.is_leaf():
|
|
219
|
+
mset = Counter([node.name])
|
|
220
|
+
else:
|
|
221
|
+
mset = Counter()
|
|
222
|
+
for child in node.children:
|
|
223
|
+
mset += multisets[child]
|
|
224
|
+
|
|
225
|
+
# Store the Counter for children use, but also store sorted tuple for output
|
|
226
|
+
multisets[node] = mset
|
|
227
|
+
sorted_multisets[node] = tuple(sorted(mset.items()))
|
|
228
|
+
|
|
229
|
+
return sorted_multisets
|
|
230
|
+
|
|
231
|
+
@staticmethod
|
|
232
|
+
def _compute_canonical_forms(root):
|
|
233
|
+
canonical_map = {}
|
|
234
|
+
|
|
235
|
+
def recurse(node):
|
|
236
|
+
'''
|
|
237
|
+
Recursively compute a canonical string representation of a subtree rooted at `node`,
|
|
238
|
+
such that isomorphic subtrees (with possibly duplicated leaves) get the same string.
|
|
239
|
+
'''
|
|
240
|
+
if node.is_leaf():
|
|
241
|
+
canon = node.name
|
|
242
|
+
else:
|
|
243
|
+
child_encodings = sorted([recurse(c) for c in node.children])
|
|
244
|
+
canon = '(' + ','.join(child_encodings) + ')'
|
|
245
|
+
canonical_map[node] = canon
|
|
246
|
+
return canon
|
|
247
|
+
|
|
248
|
+
recurse(root)
|
|
249
|
+
return canonical_map
|
|
250
|
+
|
|
251
|
+
@staticmethod
|
|
252
|
+
def _insert_reticulation(G, src, tgt):
|
|
253
|
+
u = f'retic_{src}_{tgt}'
|
|
254
|
+
G.add_node(u, label='Ret.')
|
|
255
|
+
# Keep the length attribute if present
|
|
256
|
+
old_edge = G[src][tgt]
|
|
257
|
+
G.remove_edge(src, tgt)
|
|
258
|
+
if 'length' in old_edge:
|
|
259
|
+
G.add_edge(src, u, length=old_edge['length'])
|
|
260
|
+
else:
|
|
261
|
+
G.add_edge(src, u)
|
|
262
|
+
G.add_edge(u, tgt)
|
|
263
|
+
return u
|
|
264
|
+
|
|
265
|
+
@staticmethod
|
|
266
|
+
def _simplify_redundant_reticulations(G):
|
|
267
|
+
to_remove = []
|
|
268
|
+
for node in list(G.nodes):
|
|
269
|
+
preds = list(G.predecessors(node))
|
|
270
|
+
succs = list(G.successors(node))
|
|
271
|
+
|
|
272
|
+
# Skip autopolyploidy nodes - they represent WGD events and should be preserved
|
|
273
|
+
if G.nodes[node].get('autopolyploidy', False):
|
|
274
|
+
continue
|
|
275
|
+
|
|
276
|
+
# Here we can't use `is_reticulation_node` because it checks in-degree > 1,
|
|
277
|
+
# which is still not the case for these temporary reticulation nodes (to be removed).
|
|
278
|
+
if 'ete' not in G.nodes[node] and len(preds) == 1 and len(succs) == 1:
|
|
279
|
+
parent, child = preds[0], succs[0]
|
|
280
|
+
if not G.has_edge(parent, child):
|
|
281
|
+
G.add_edge(parent, child)
|
|
282
|
+
to_remove.append(node)
|
|
283
|
+
|
|
284
|
+
G.remove_nodes_from(to_remove)
|
|
285
|
+
|
|
286
|
+
@staticmethod
|
|
287
|
+
def _get_single_child(G, retnode):
|
|
288
|
+
children = list(G.successors(retnode))
|
|
289
|
+
x = len(children)
|
|
290
|
+
if x != 1:
|
|
291
|
+
raise ValueError(f'Reticulation node {retnode} should have exactly one child, found {x}')
|
|
292
|
+
return children[0]
|
|
293
|
+
|
|
294
|
+
@classmethod
|
|
295
|
+
def multree_to_dag(cls, tree, strict=True):
|
|
296
|
+
'''
|
|
297
|
+
An implementation of the HOLM2006 algorithm to convert an ete3 multree to a networkx DAG phylogenetic network.
|
|
298
|
+
This method should NOT modify the original tree.
|
|
299
|
+
|
|
300
|
+
Optimizations:
|
|
301
|
+
- Group nodes at each height by canonical form (or multiset) instead of doing O(k^2) pairwise comparisons.
|
|
302
|
+
- Cache sorted multiset representations used for ordering.
|
|
303
|
+
'''
|
|
304
|
+
# Compute heights and multisets (same as before)
|
|
305
|
+
height_map = cls._compute_height_map(tree)
|
|
306
|
+
|
|
307
|
+
# Create the initial networkx graph
|
|
308
|
+
G = cls.tree_to_dag(tree)
|
|
309
|
+
|
|
310
|
+
# Prepare canonical map or use multisets, depending on strict flag
|
|
311
|
+
if strict:
|
|
312
|
+
# Expect compute_canonical_forms to return a dict: {node: canon_str}
|
|
313
|
+
canonical_map = cls._compute_canonical_forms(tree)
|
|
314
|
+
def key_fn(n):
|
|
315
|
+
return canonical_map[n]
|
|
316
|
+
else:
|
|
317
|
+
# Precompute a stable, hashable representation for each node's multiset
|
|
318
|
+
sorted_multisets = cls._compute_sorted_multisets(tree)
|
|
319
|
+
def key_fn(n):
|
|
320
|
+
return sorted_multisets[n]
|
|
321
|
+
|
|
322
|
+
# Process heights from root down to leaves (same order as before)
|
|
323
|
+
for h in sorted(height_map.keys(), reverse=True):
|
|
324
|
+
nodes_at_height = height_map[h]
|
|
325
|
+
# Sort nodes in a stable way using the same key as original code used for ordering.
|
|
326
|
+
# (Original sorted by sorted(multisets[n].items()); for strict True canonical_map ordering is used implicitly.)
|
|
327
|
+
nodes_at_height = sorted(nodes_at_height, key=lambda n: key_fn(n))
|
|
328
|
+
|
|
329
|
+
# Group nodes by their key (canonical string or sorted multiset tuple)
|
|
330
|
+
groups = defaultdict(list)
|
|
331
|
+
for n in nodes_at_height:
|
|
332
|
+
groups[key_fn(n)].append(n)
|
|
333
|
+
|
|
334
|
+
# For each group with >1 node, pick the first as the retained node and treat the rest as isomorphs
|
|
335
|
+
for group_nodes in groups.values():
|
|
336
|
+
if len(group_nodes) <= 1:
|
|
337
|
+
continue
|
|
338
|
+
|
|
339
|
+
leader = group_nodes[0] # the node we keep and attach the reticulation above
|
|
340
|
+
# If leader has no parent, we cannot insert a reticulation above it (mirrors previous behavior)
|
|
341
|
+
parent_leader = leader.up
|
|
342
|
+
if not parent_leader:
|
|
343
|
+
# This mirrors previous code that only inserts reticulation when parent exists.
|
|
344
|
+
# Skip group if there's no valid parent for leader.
|
|
345
|
+
continue
|
|
346
|
+
|
|
347
|
+
pid = id(parent_leader)
|
|
348
|
+
nid_leader = id(leader)
|
|
349
|
+
|
|
350
|
+
# Count distinct parents among alive nodes for event classification
|
|
351
|
+
alive_parents = [pid] # leader's parent (leader is always alive at this point)
|
|
352
|
+
|
|
353
|
+
# Insert reticulation node above leader in G
|
|
354
|
+
retic_node = cls._insert_reticulation(G, pid, nid_leader)
|
|
355
|
+
|
|
356
|
+
# For every other isomorphic node in the group, reroute its parent's edge(s) to the retic node
|
|
357
|
+
for iso in group_nodes[1:]:
|
|
358
|
+
iso_parent = iso.up
|
|
359
|
+
iso_pid = id(iso_parent) if iso_parent else None
|
|
360
|
+
|
|
361
|
+
# Track parent only if this iso is still alive in the DAG
|
|
362
|
+
if iso_pid and id(iso) in G:
|
|
363
|
+
alive_parents.append(iso_pid)
|
|
364
|
+
|
|
365
|
+
# Detect autopolyploidy: identical subtrees under the same parent
|
|
366
|
+
if iso_pid == pid:
|
|
367
|
+
G.nodes[retic_node]['autopolyploidy'] = True
|
|
368
|
+
|
|
369
|
+
# If the DAG contains the edge we expect, replace it so the parent's edge now goes to the retic node
|
|
370
|
+
if iso_pid and G.has_edge(iso_pid, id(iso)):
|
|
371
|
+
G.remove_edge(iso_pid, id(iso))
|
|
372
|
+
G.add_edge(iso_pid, retic_node)
|
|
373
|
+
|
|
374
|
+
# Remove the isomorphic subtree nodes from the DAG (exactly as before)
|
|
375
|
+
to_delete = [id(n) for n in iso.traverse()]
|
|
376
|
+
G.remove_nodes_from(to_delete)
|
|
377
|
+
|
|
378
|
+
# Store event counts: auto = copies under same parent, allo = connections between parents
|
|
379
|
+
k = len(alive_parents)
|
|
380
|
+
d = len(set(alive_parents))
|
|
381
|
+
G.nodes[retic_node]['auto_events'] = k - d
|
|
382
|
+
G.nodes[retic_node]['allo_events'] = d - 1
|
|
383
|
+
|
|
384
|
+
# Remove reticulation nodes that have exactly one predecessor and one successor
|
|
385
|
+
cls._simplify_redundant_reticulations(G)
|
|
386
|
+
return G
|
|
387
|
+
|
|
388
|
+
@classmethod
|
|
389
|
+
def polyphest_multree_to_dag(cls, tree, threshold=0.2, normalize=True):
|
|
390
|
+
'''
|
|
391
|
+
Polyphest's implementation of the HOLM2006 algorithm:
|
|
392
|
+
|
|
393
|
+
Converts an ETE3 MUL-tree to a DAG by merging near-isomorphic subtrees
|
|
394
|
+
based on graph edit distance <= threshold.
|
|
395
|
+
|
|
396
|
+
This follows the structure of polyphest's folding.convert_multree_to_network(),
|
|
397
|
+
but uses ETE3 + NetworkX instead of PhyNetPy + Polyphest's helper functions.
|
|
398
|
+
'''
|
|
399
|
+
# Height map {height: [nodes at that height]}
|
|
400
|
+
height_map = cls._compute_height_map(tree)
|
|
401
|
+
|
|
402
|
+
# DAG copy of the tree (node IDs are id(ete3_node))
|
|
403
|
+
G = cls.tree_to_dag(tree)
|
|
404
|
+
|
|
405
|
+
# Helper: get set of leaf names under node
|
|
406
|
+
def get_leaf_set(n):
|
|
407
|
+
return frozenset(leaf.name for leaf in n.iter_leaves())
|
|
408
|
+
|
|
409
|
+
# Near-isomorphic check (polyphest-style)
|
|
410
|
+
def is_near_isomorphic(n1, n2):
|
|
411
|
+
# Quick leaf-set filter
|
|
412
|
+
if get_leaf_set(n1) != get_leaf_set(n2):
|
|
413
|
+
return False
|
|
414
|
+
|
|
415
|
+
H1 = cls.tree_to_dag(n1)
|
|
416
|
+
H2 = cls.tree_to_dag(n2)
|
|
417
|
+
dist = nx.graph_edit_distance(
|
|
418
|
+
H1, H2,
|
|
419
|
+
node_match=lambda u, v: u.get('label') == v.get('label')
|
|
420
|
+
)
|
|
421
|
+
if normalize:
|
|
422
|
+
dist /= (H1.number_of_nodes() + H2.number_of_nodes())
|
|
423
|
+
return dist <= threshold
|
|
424
|
+
|
|
425
|
+
# Process from top (root) to bottom (leaves)
|
|
426
|
+
for h in sorted(height_map.keys(), reverse=True):
|
|
427
|
+
nodes_to_check = list(height_map[h])
|
|
428
|
+
while nodes_to_check:
|
|
429
|
+
node = nodes_to_check.pop(0)
|
|
430
|
+
isomorphic_trees = [node]
|
|
431
|
+
remaining = []
|
|
432
|
+
|
|
433
|
+
for other in nodes_to_check:
|
|
434
|
+
if is_near_isomorphic(node, other):
|
|
435
|
+
isomorphic_trees.append(other)
|
|
436
|
+
else:
|
|
437
|
+
remaining.append(other)
|
|
438
|
+
|
|
439
|
+
nodes_to_check = remaining
|
|
440
|
+
|
|
441
|
+
if len(isomorphic_trees) > 1:
|
|
442
|
+
leader = isomorphic_trees[0]
|
|
443
|
+
parent_leader = leader.up
|
|
444
|
+
if not parent_leader:
|
|
445
|
+
continue # Can't insert reticulation above root
|
|
446
|
+
|
|
447
|
+
pid = id(parent_leader)
|
|
448
|
+
nid_leader = id(leader)
|
|
449
|
+
|
|
450
|
+
# Count distinct parents among alive nodes for event classification
|
|
451
|
+
alive_parents = [pid] # leader's parent
|
|
452
|
+
|
|
453
|
+
retic_node = cls._insert_reticulation(G, pid, nid_leader)
|
|
454
|
+
|
|
455
|
+
for iso in isomorphic_trees[1:]:
|
|
456
|
+
iso_parent = iso.up
|
|
457
|
+
iso_pid = id(iso_parent) if iso_parent else None
|
|
458
|
+
|
|
459
|
+
# Track parent only if this iso is still alive in the DAG
|
|
460
|
+
if iso_pid and id(iso) in G:
|
|
461
|
+
alive_parents.append(iso_pid)
|
|
462
|
+
|
|
463
|
+
# Detect autopolyploidy: identical subtrees under the same parent
|
|
464
|
+
if iso_pid == pid:
|
|
465
|
+
G.nodes[retic_node]['autopolyploidy'] = True
|
|
466
|
+
|
|
467
|
+
if iso_parent and G.has_edge(iso_pid, id(iso)):
|
|
468
|
+
G.remove_edge(iso_pid, id(iso))
|
|
469
|
+
G.add_edge(iso_pid, retic_node)
|
|
470
|
+
G.remove_nodes_from([id(n) for n in iso.traverse()])
|
|
471
|
+
|
|
472
|
+
# Store event counts
|
|
473
|
+
k = len(alive_parents)
|
|
474
|
+
d = len(set(alive_parents))
|
|
475
|
+
G.nodes[retic_node]['auto_events'] = k - d
|
|
476
|
+
G.nodes[retic_node]['allo_events'] = d - 1
|
|
477
|
+
|
|
478
|
+
cls._simplify_redundant_reticulations(G)
|
|
479
|
+
return G
|
|
480
|
+
|
|
481
|
+
# ───── MODULE: From exact network to (MUL-)tree ─────
|
|
482
|
+
|
|
483
|
+
@classmethod
|
|
484
|
+
def dag_to_multree(cls, G, match_dag=False):
|
|
485
|
+
'''
|
|
486
|
+
Convert a DAG (from multree or similar) back into an ete3 Tree.
|
|
487
|
+
This handles multi-labeled trees and reticulations.
|
|
488
|
+
'''
|
|
489
|
+
def clone_node(orig_node_data):
|
|
490
|
+
node = TreeNode()
|
|
491
|
+
label = orig_node_data.get('name') or orig_node_data.get('label') or None
|
|
492
|
+
if label:
|
|
493
|
+
node.name = label
|
|
494
|
+
return node
|
|
495
|
+
|
|
496
|
+
# Identify reticulation nodes by having multiple parents
|
|
497
|
+
retic_nodes = {n for n in G.nodes if cls.is_reticulation_node(G, n)}
|
|
498
|
+
|
|
499
|
+
# Identify root (node with in-degree 0)
|
|
500
|
+
root_id = cls.get_dag_root(G)
|
|
501
|
+
# Root must not be a reticulation node
|
|
502
|
+
if root_id in retic_nodes:
|
|
503
|
+
raise ValueError('Root node cannot be a reticulation node.')
|
|
504
|
+
|
|
505
|
+
def build_tree(node_id):
|
|
506
|
+
node_data = G.nodes[node_id]
|
|
507
|
+
|
|
508
|
+
# Skip reticulation nodes and attach their single child directly
|
|
509
|
+
if node_id in retic_nodes:
|
|
510
|
+
return build_tree( ReticulateTree._get_single_child(G, node_id) )
|
|
511
|
+
|
|
512
|
+
# Normal node
|
|
513
|
+
curr_node = clone_node(node_data)
|
|
514
|
+
|
|
515
|
+
# Attach to DAG node if requested
|
|
516
|
+
if match_dag:
|
|
517
|
+
G.nodes[node_id]['ete'] = curr_node
|
|
518
|
+
G.nodes[node_id]['label'] = curr_node.name
|
|
519
|
+
|
|
520
|
+
for child_id in G.successors(node_id):
|
|
521
|
+
child_subtree = build_tree(child_id)
|
|
522
|
+
curr_node.add_child(child_subtree)
|
|
523
|
+
|
|
524
|
+
return curr_node
|
|
525
|
+
|
|
526
|
+
# Post-process: tag reticulation nodes (only if match_dag)
|
|
527
|
+
if match_dag:
|
|
528
|
+
for node in retic_nodes:
|
|
529
|
+
G.nodes[node].pop('ete', None)
|
|
530
|
+
G.nodes[node]['label'] = 'Ret.'
|
|
531
|
+
|
|
532
|
+
return build_tree(root_id)
|
|
533
|
+
|
|
534
|
+
# ───── MODULE: From H-enriched newick to network ─────
|
|
535
|
+
|
|
536
|
+
@staticmethod
|
|
537
|
+
def _find_reticulation_defs(G):
|
|
538
|
+
defs = {}
|
|
539
|
+
for n, data in G.nodes(data=True):
|
|
540
|
+
name = data.get('label', '')
|
|
541
|
+
if name.startswith('#') and G.out_degree(n) > 0:
|
|
542
|
+
hid = name[1:] # strip the '#' prefix
|
|
543
|
+
if hid in defs:
|
|
544
|
+
raise ValueError(f"Duplicate definition for reticulation id '{hid}' found.")
|
|
545
|
+
defs[hid] = n
|
|
546
|
+
return defs
|
|
547
|
+
|
|
548
|
+
@staticmethod
|
|
549
|
+
def _link_and_track_references(G, defs):
|
|
550
|
+
renamed_targets = set()
|
|
551
|
+
for n, data in list(G.nodes(data=True)):
|
|
552
|
+
name = data.get('label', '')
|
|
553
|
+
if name.startswith('#') and G.out_degree(n) == 0: # leaf reference
|
|
554
|
+
hid = name[1:] # strip the '#' prefix
|
|
555
|
+
if hid not in defs:
|
|
556
|
+
continue
|
|
557
|
+
|
|
558
|
+
parent = next(G.predecessors(n), None)
|
|
559
|
+
if parent is None:
|
|
560
|
+
continue
|
|
561
|
+
|
|
562
|
+
edata = dict(G[parent][n]) # preserve edge data (branch length)
|
|
563
|
+
G.remove_node(n) # remove leaf reference
|
|
564
|
+
|
|
565
|
+
target = defs[hid]
|
|
566
|
+
if G.out_degree(target) > 1: # cladistic case
|
|
567
|
+
G.add_edge(parent, target, **edata)
|
|
568
|
+
new_node = hid + '_ref'
|
|
569
|
+
G.add_node(new_node)
|
|
570
|
+
for child in list(G.successors(target)):
|
|
571
|
+
G.add_edge(new_node, child, **G[target][child])
|
|
572
|
+
G.remove_edge(target, child)
|
|
573
|
+
G.add_edge(target, new_node) # structural only
|
|
574
|
+
else: # direct case
|
|
575
|
+
G.add_edge(parent, target, **edata)
|
|
576
|
+
|
|
577
|
+
renamed_targets.add(hid)
|
|
578
|
+
|
|
579
|
+
return renamed_targets
|
|
580
|
+
|
|
581
|
+
@classmethod
|
|
582
|
+
def enewick_to_dag(cls, enewick_str):
|
|
583
|
+
'''
|
|
584
|
+
Convert enriched Newick with #H reticulation markers into a DAG.
|
|
585
|
+
- Branch lengths from #H reference leaves are preserved on the edge to the reticulation node.
|
|
586
|
+
- Reticulation -> new internal node edges have no branch length (structural only).
|
|
587
|
+
'''
|
|
588
|
+
# Step 1: parse as-is into DAG
|
|
589
|
+
tree = Tree(enewick_str, format=1) # format for Newick TBD !!!
|
|
590
|
+
G = cls.tree_to_dag(tree)
|
|
591
|
+
|
|
592
|
+
# Step 2: find definition nodes (internal nodes ending in #H)
|
|
593
|
+
defs = cls._find_reticulation_defs(G)
|
|
594
|
+
|
|
595
|
+
# Step 3: link references and track retnodes
|
|
596
|
+
renamed_targets = cls._link_and_track_references(G, defs)
|
|
597
|
+
|
|
598
|
+
# Step 4: rename all reticulation targets
|
|
599
|
+
for hid in renamed_targets:
|
|
600
|
+
target = defs[hid]
|
|
601
|
+
new_tgt_key = 'retic_' + hid
|
|
602
|
+
nx.relabel_nodes(G, {target: new_tgt_key}, copy=False)
|
|
603
|
+
G.nodes[new_tgt_key]['label'] = 'Ret.' # mark as reticulation
|
|
604
|
+
|
|
605
|
+
return G
|
|
606
|
+
|
|
607
|
+
def to_enewick(self, filename=None):
|
|
608
|
+
G = self.dag
|
|
609
|
+
retnodes = set(self.retnodes) # reticulation nodes (no numbering)
|
|
610
|
+
|
|
611
|
+
# Assign new #H IDs to reticulation nodes
|
|
612
|
+
hid_map = {node: str(i) for i, node in enumerate(sorted(retnodes))}
|
|
613
|
+
|
|
614
|
+
# Find root
|
|
615
|
+
root = self.get_dag_root(G)
|
|
616
|
+
|
|
617
|
+
defined = set() # keep track of reticulations already defined
|
|
618
|
+
|
|
619
|
+
def build(node, parent=None):
|
|
620
|
+
# If reticulation node
|
|
621
|
+
if node in retnodes:
|
|
622
|
+
hid = hid_map[node]
|
|
623
|
+
if node not in defined and (parent is None or parent not in retnodes):
|
|
624
|
+
# First encounter from main parent → definition
|
|
625
|
+
defined.add(node)
|
|
626
|
+
children = list(G.successors(node))
|
|
627
|
+
if not children:
|
|
628
|
+
# Reticulation leaf alone
|
|
629
|
+
return f"#H{hid}"
|
|
630
|
+
inner = ",".join(build(c, node) for c in children)
|
|
631
|
+
return f"({inner})#H{hid}"
|
|
632
|
+
else:
|
|
633
|
+
# Reference form (from other parents)
|
|
634
|
+
return f"#H{hid}"
|
|
635
|
+
|
|
636
|
+
# Non-reticulation node
|
|
637
|
+
children = list(G.successors(node))
|
|
638
|
+
if not children:
|
|
639
|
+
# leaf: output label or node id
|
|
640
|
+
label = G.nodes[node].get("label", str(node))
|
|
641
|
+
return label
|
|
642
|
+
|
|
643
|
+
label = G.nodes[node].get("label", "")
|
|
644
|
+
inner = ",".join(build(c, node) for c in children)
|
|
645
|
+
return f"({inner}){label}"
|
|
646
|
+
|
|
647
|
+
newick_str = build(root) + ";"
|
|
648
|
+
|
|
649
|
+
if filename:
|
|
650
|
+
with open(filename, "w") as f:
|
|
651
|
+
f.write(newick_str)
|
|
652
|
+
return newick_str
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
# ───── MODULE: Visualization ─────
|
|
656
|
+
|
|
657
|
+
def __str__(self):
|
|
658
|
+
return self.tree_str
|
|
659
|
+
|
|
660
|
+
def visualize(self, filename=None, uid_labeled=False, launch=True):
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
G = self.dag
|
|
664
|
+
depths = self.compute_depths(G)
|
|
665
|
+
max_depth = max(depths.values()) if depths else 0
|
|
666
|
+
|
|
667
|
+
# Group nodes by layer
|
|
668
|
+
layers = defaultdict(list)
|
|
669
|
+
for node, d in depths.items():
|
|
670
|
+
layers[d].append(node)
|
|
671
|
+
|
|
672
|
+
# ---------------------------------------------------------
|
|
673
|
+
# BREADTH SORTING (Barycenter Heuristic for Crossing Min.)
|
|
674
|
+
# ---------------------------------------------------------
|
|
675
|
+
# 1. Assign initial arbitrary X coordinates
|
|
676
|
+
x_coords = {}
|
|
677
|
+
for d, nodes in layers.items():
|
|
678
|
+
for i, n in enumerate(nodes):
|
|
679
|
+
x_coords[n] = i
|
|
680
|
+
|
|
681
|
+
# 2. Sweep top-down and bottom-up to untangle edges
|
|
682
|
+
for _ in range(5): # 5 sweeps is usually enough to converge
|
|
683
|
+
# Top-down sweep
|
|
684
|
+
for d in range(1, max_depth + 1):
|
|
685
|
+
if d not in layers: continue
|
|
686
|
+
def parent_avg_x(n):
|
|
687
|
+
preds = list(G.predecessors(n))
|
|
688
|
+
if not preds: return x_coords[n]
|
|
689
|
+
return sum(x_coords[p] for p in preds) / len(preds)
|
|
690
|
+
|
|
691
|
+
layers[d].sort(key=parent_avg_x)
|
|
692
|
+
for i, n in enumerate(layers[d]):
|
|
693
|
+
x_coords[n] = i
|
|
694
|
+
|
|
695
|
+
# Bottom-up sweep
|
|
696
|
+
for d in range(max_depth - 1, -1, -1):
|
|
697
|
+
if d not in layers: continue
|
|
698
|
+
def child_avg_x(n):
|
|
699
|
+
succs = list(G.successors(n))
|
|
700
|
+
if not succs: return x_coords[n]
|
|
701
|
+
return sum(x_coords[c] for c in succs) / len(succs)
|
|
702
|
+
|
|
703
|
+
layers[d].sort(key=child_avg_x)
|
|
704
|
+
for i, n in enumerate(layers[d]):
|
|
705
|
+
x_coords[n] = i
|
|
706
|
+
|
|
707
|
+
# 3. Final Coordinate Assignment (Center the layers)
|
|
708
|
+
pos = {}
|
|
709
|
+
for d, nodes in layers.items():
|
|
710
|
+
width = len(nodes)
|
|
711
|
+
offset = (width - 1) / 2.0
|
|
712
|
+
for i, n in enumerate(nodes):
|
|
713
|
+
# X is centered, Y is inverted so the root (depth 0) is at the top
|
|
714
|
+
pos[n] = (i - offset, -d)
|
|
715
|
+
|
|
716
|
+
# ---------------------------------------------------------
|
|
717
|
+
# DRAWING
|
|
718
|
+
# ---------------------------------------------------------
|
|
719
|
+
node_colors = []
|
|
720
|
+
node_shapes = {}
|
|
721
|
+
for node in G.nodes():
|
|
722
|
+
if self.is_reticulation_node(G, node):
|
|
723
|
+
node_shapes[node] = 'D'
|
|
724
|
+
node_colors.append('orange')
|
|
725
|
+
elif G.out_degree(node) == 0:
|
|
726
|
+
node_shapes[node] = 'o'
|
|
727
|
+
node_colors.append('lightgreen')
|
|
728
|
+
else:
|
|
729
|
+
node_shapes[node] = 'o'
|
|
730
|
+
node_colors.append('lightblue')
|
|
731
|
+
|
|
732
|
+
# Draw Edges FIRST (zorder=1) with a slight curve to avoid node collision
|
|
733
|
+
nx.draw_networkx_edges(
|
|
734
|
+
G, pos,
|
|
735
|
+
arrows=True,
|
|
736
|
+
connectionstyle="arc3,rad=0.1", # Curve edges
|
|
737
|
+
node_size=1000, # Stop arrows exactly at node border
|
|
738
|
+
#zorder=1 # Keep underneath nodes
|
|
739
|
+
)
|
|
740
|
+
|
|
741
|
+
# Draw Nodes SECOND (zorder=2) so they sit perfectly on top
|
|
742
|
+
for shape in set(node_shapes.values()):
|
|
743
|
+
shaped_nodes = [n for n in G.nodes if node_shapes[n] == shape]
|
|
744
|
+
nx.draw_networkx_nodes(
|
|
745
|
+
G, pos, nodelist=shaped_nodes,
|
|
746
|
+
node_shape=shape,
|
|
747
|
+
node_color=[node_colors[list(G.nodes).index(n)] for n in shaped_nodes],
|
|
748
|
+
node_size=1000,
|
|
749
|
+
#zorder=2
|
|
750
|
+
)
|
|
751
|
+
|
|
752
|
+
# Labels
|
|
753
|
+
labels = {}
|
|
754
|
+
for n, d in G.nodes(data=True):
|
|
755
|
+
label = d.get('label', None)
|
|
756
|
+
labels[n] = str(n) if uid_labeled and label == '' else label
|
|
757
|
+
|
|
758
|
+
nx.draw_networkx_labels(G, pos, labels=labels, font_size=10)#, zorder=3)
|
|
759
|
+
|
|
760
|
+
plt.axis('off')
|
|
761
|
+
plt.tight_layout()
|
|
762
|
+
if filename:
|
|
763
|
+
plt.savefig(filename, dpi=690)
|
|
764
|
+
print(f'Graph saved to {filename}')
|
|
765
|
+
if launch:
|
|
766
|
+
plt.show()
|
|
767
|
+
else:
|
|
768
|
+
plt.close()
|
|
769
|
+
|
|
770
|
+
def visualize2(self, filename=None, uid_labeled=False, launch=True):
|
|
771
|
+
G = self.dag
|
|
772
|
+
depths = self.compute_depths(G)
|
|
773
|
+
|
|
774
|
+
# Annotate graph with depth-based 'layer' for multipartite layout
|
|
775
|
+
for node, depth in depths.items():
|
|
776
|
+
G.nodes[node]['layer'] = depth
|
|
777
|
+
|
|
778
|
+
pos = nx.multipartite_layout(G, subset_key='layer')
|
|
779
|
+
|
|
780
|
+
# Color and shape encoding
|
|
781
|
+
node_colors = []
|
|
782
|
+
node_shapes = {}
|
|
783
|
+
for node in G.nodes():
|
|
784
|
+
if self.is_reticulation_node(G, node):
|
|
785
|
+
node_shapes[node] = 'D'
|
|
786
|
+
node_colors.append('orange')
|
|
787
|
+
elif G.out_degree(node) == 0:
|
|
788
|
+
node_shapes[node] = 'o'
|
|
789
|
+
node_colors.append('lightgreen')
|
|
790
|
+
else:
|
|
791
|
+
node_shapes[node] = 'o'
|
|
792
|
+
node_colors.append('lightblue')
|
|
793
|
+
|
|
794
|
+
for shape in set(node_shapes.values()):
|
|
795
|
+
shaped_nodes = [n for n in G.nodes if node_shapes[n] == shape]
|
|
796
|
+
nx.draw_networkx_nodes(
|
|
797
|
+
G, pos, nodelist=shaped_nodes,
|
|
798
|
+
node_shape=shape,
|
|
799
|
+
node_color=[node_colors[list(G.nodes).index(n)] for n in shaped_nodes],
|
|
800
|
+
node_size=1000
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
nx.draw_networkx_edges(G, pos, arrows=True)
|
|
804
|
+
|
|
805
|
+
# Labels (with uid fallback)
|
|
806
|
+
labels = {}
|
|
807
|
+
for n, d in G.nodes(data=True):
|
|
808
|
+
label = d.get('label', None)
|
|
809
|
+
labels[n] = str(n) if uid_labeled and label == '' else label
|
|
810
|
+
nx.draw_networkx_labels(G, pos, labels=labels, font_size=10)
|
|
811
|
+
|
|
812
|
+
plt.axis('off')
|
|
813
|
+
plt.tight_layout()
|
|
814
|
+
if filename:
|
|
815
|
+
plt.savefig(filename, dpi=690)
|
|
816
|
+
print(f'Graph saved to {filename}')
|
|
817
|
+
if launch:
|
|
818
|
+
plt.show()
|
|
819
|
+
else:
|
|
820
|
+
plt.close()
|
|
821
|
+
|
|
822
|
+
def interact(self, filename, uid_labeled=False, launch=True):
|
|
823
|
+
'''
|
|
824
|
+
Interactive DAG visualization using pyvis.
|
|
825
|
+
Emulates the structure and appearance of the matplotlib-based layout.
|
|
826
|
+
'''
|
|
827
|
+
filename = Path(filename)
|
|
828
|
+
net = Network(height='800px', width='100%', directed=True, layout=True)
|
|
829
|
+
net.toggle_physics(False) # Static layout for hierarchy-like appearance
|
|
830
|
+
|
|
831
|
+
G = self.dag
|
|
832
|
+
depths = self.compute_depths(G)
|
|
833
|
+
|
|
834
|
+
# Add nodes
|
|
835
|
+
for node, data in G.nodes(data=True):
|
|
836
|
+
label = data.get('label', '')
|
|
837
|
+
if not uid_labeled and label == '':
|
|
838
|
+
label = ' '
|
|
839
|
+
|
|
840
|
+
node_type = 'internal'
|
|
841
|
+
shape = 'ellipse'
|
|
842
|
+
color = 'lightblue'
|
|
843
|
+
|
|
844
|
+
if self.is_reticulation_node(G, node):
|
|
845
|
+
node_type = 'reticulation'
|
|
846
|
+
shape = 'diamond'
|
|
847
|
+
color = 'orange'
|
|
848
|
+
elif G.out_degree(node) == 0:
|
|
849
|
+
node_type = 'leaf'
|
|
850
|
+
color = 'lightgreen'
|
|
851
|
+
|
|
852
|
+
level = depths.get(node, 0)
|
|
853
|
+
|
|
854
|
+
net.add_node(
|
|
855
|
+
str(node),
|
|
856
|
+
label=label,
|
|
857
|
+
title=f'{node_type} node: {node}',
|
|
858
|
+
level=level,
|
|
859
|
+
shape=shape,
|
|
860
|
+
color=color,
|
|
861
|
+
size=20
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
# Add edges
|
|
865
|
+
for u, v in G.edges():
|
|
866
|
+
net.add_edge(str(u), str(v), width=1)
|
|
867
|
+
|
|
868
|
+
# Save and optionally open
|
|
869
|
+
net.save_graph(str(filename))
|
|
870
|
+
print(f'Interactive graph saved to {filename}.')
|
|
871
|
+
if launch:
|
|
872
|
+
try:
|
|
873
|
+
net.show(str(filename))
|
|
874
|
+
except Exception as e:
|
|
875
|
+
print(f'Failed to display HTML. Reason: {e}\nTrying to open in browser...')
|
|
876
|
+
try:
|
|
877
|
+
webbrowser.open(str(filename))
|
|
878
|
+
# Wait for the user to come back
|
|
879
|
+
input('Press Enter to continue...')
|
|
880
|
+
except:
|
|
881
|
+
print('Failed to open in browser. Please open the file manually.')
|
|
882
|
+
pass
|
|
883
|
+
|
|
884
|
+
# ───── MODULE: Comparative features ─────
|
|
885
|
+
|
|
886
|
+
def get_reticulation_nodes(self):
|
|
887
|
+
'''
|
|
888
|
+
Get all reticulation nodes in the DAG.
|
|
889
|
+
'''
|
|
890
|
+
return [n for n in self.dag.nodes() if self.is_reticulation_node(self.dag, n)]
|
|
891
|
+
|
|
892
|
+
def get_reticulation_count(self):
|
|
893
|
+
'''
|
|
894
|
+
Count total reticulation events (auto + allo).
|
|
895
|
+
Uses event counts stored during folding when available,
|
|
896
|
+
falls back to in_degree - 1 for extended Newick input.
|
|
897
|
+
'''
|
|
898
|
+
count = 0
|
|
899
|
+
for n in self.retnodes:
|
|
900
|
+
if 'auto_events' in self.dag.nodes[n]:
|
|
901
|
+
count += self.dag.nodes[n]['auto_events'] + self.dag.nodes[n]['allo_events']
|
|
902
|
+
else:
|
|
903
|
+
# Extended Newick input: no folding, use in-degree
|
|
904
|
+
count += max(self.dag.in_degree(n) - 1, 1)
|
|
905
|
+
return count
|
|
906
|
+
|
|
907
|
+
def get_auto_event_count(self):
|
|
908
|
+
'''Count autopolyploidization events (copies under same parent).'''
|
|
909
|
+
return sum(self.dag.nodes[n].get('auto_events', 0) for n in self.retnodes)
|
|
910
|
+
|
|
911
|
+
def get_allo_event_count(self):
|
|
912
|
+
'''Count allopolyploidization events (copies under different parents).'''
|
|
913
|
+
count = 0
|
|
914
|
+
for n in self.retnodes:
|
|
915
|
+
if 'allo_events' in self.dag.nodes[n]:
|
|
916
|
+
count += self.dag.nodes[n]['allo_events']
|
|
917
|
+
else:
|
|
918
|
+
# Extended Newick input: all events assumed allo
|
|
919
|
+
count += max(self.dag.in_degree(n) - 1, 1)
|
|
920
|
+
return count
|
|
921
|
+
|
|
922
|
+
def get_reticulation_leaves(self):
|
|
923
|
+
'''
|
|
924
|
+
Get all leaves that are descendants of reticulation nodes.
|
|
925
|
+
'''
|
|
926
|
+
leaves = {}
|
|
927
|
+
for ret in self.retnodes:
|
|
928
|
+
desc = nx.descendants(self.dag, ret)
|
|
929
|
+
leaf_labels = [
|
|
930
|
+
self.dag.nodes[n].get('label', str(n))
|
|
931
|
+
for n in desc
|
|
932
|
+
if self.dag.out_degree(n) == 0
|
|
933
|
+
]
|
|
934
|
+
leaves[ret] = leaf_labels
|
|
935
|
+
return leaves
|
|
936
|
+
|
|
937
|
+
def get_reticulation_sisters(self):
|
|
938
|
+
'''
|
|
939
|
+
For each reticulation node, return its two sister clades (one from each parent).
|
|
940
|
+
Each clade is a list of ete3 TreeNodes (from the 'ete' attribute in the DAG).
|
|
941
|
+
|
|
942
|
+
Returns:
|
|
943
|
+
dict: {ret_node_id: [clade1_nodes, clade2_nodes]}
|
|
944
|
+
'''
|
|
945
|
+
def collect_subtree_nodes(node):
|
|
946
|
+
'''Return node as ete3 TreeNodes under the given DAG node.'''
|
|
947
|
+
data = self.dag.nodes[node]
|
|
948
|
+
# Check if n is a ret node, if so, take its only child
|
|
949
|
+
|
|
950
|
+
if self.is_reticulation_node(self.dag, node):
|
|
951
|
+
data = self.dag.nodes[ self._get_single_child(self.dag, node) ]
|
|
952
|
+
try:
|
|
953
|
+
return data['ete']
|
|
954
|
+
except KeyError:
|
|
955
|
+
raise ValueError(f'No ete3 node found for DAG node {node}')
|
|
956
|
+
|
|
957
|
+
sisters = {}
|
|
958
|
+
for ret in self.retnodes:
|
|
959
|
+
parents = list(self.dag.predecessors(ret))
|
|
960
|
+
if len(parents) != 2:
|
|
961
|
+
if self.dag.nodes[ret].get('autopolyploidy', False):
|
|
962
|
+
# Autopolyploidy node has 1 parent - this is expected
|
|
963
|
+
pass
|
|
964
|
+
else:
|
|
965
|
+
if _WARN_MALFORMED_RETIC:
|
|
966
|
+
print(f'Warning: Reticulation node {ret} does not have exactly two parents: {parents}')
|
|
967
|
+
print('This indicates that a Strict MUL-to-Net mode was used on a malformed inference.')
|
|
968
|
+
|
|
969
|
+
clades = []
|
|
970
|
+
for parent in parents:
|
|
971
|
+
# Identify the specific child of the parent that is the reticulation node
|
|
972
|
+
# We want the 'sibling' subtrees, i.e., other children of the parent
|
|
973
|
+
sibling_children = [child for child in self.dag.successors(parent) if child != ret]
|
|
974
|
+
# Collect all ete3 nodes in the sibling clades
|
|
975
|
+
clade_nodes = []
|
|
976
|
+
for child in sibling_children:
|
|
977
|
+
clade_nodes.extend(collect_subtree_nodes(child))
|
|
978
|
+
clades.append(clade_nodes)
|
|
979
|
+
|
|
980
|
+
sisters[ret] = clades
|
|
981
|
+
|
|
982
|
+
# Convert to a more user-friendly format: list of sets of names
|
|
983
|
+
sisters = { ret:
|
|
984
|
+
[set([n.name for n in side]) for side in sister_pair]
|
|
985
|
+
for ret, sister_pair in sisters.items()
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
return sisters
|
|
989
|
+
|
|
990
|
+
def get_leaf_counts(self):
|
|
991
|
+
return dict(Counter(leaf.name for leaf in self.tree.iter_leaves()))
|
|
992
|
+
|
|
993
|
+
def measure(self, printout=False):
|
|
994
|
+
measurements = {
|
|
995
|
+
'reticulation_count': self.get_reticulation_count(),
|
|
996
|
+
'reticulation_leaves': self.get_reticulation_leaves(),
|
|
997
|
+
'reticulation_sisters': self.get_reticulation_sisters(),
|
|
998
|
+
'leaf_counts': self.get_leaf_counts(),
|
|
999
|
+
}
|
|
1000
|
+
if printout:
|
|
1001
|
+
for key, value in measurements.items():
|
|
1002
|
+
k_str = key.replace('_', ' ').title()
|
|
1003
|
+
print(f'{k_str}: {value}')
|
|
1004
|
+
return measurements
|
|
1005
|
+
|
|
1006
|
+
def get_edit_distance(self, other: 'ReticulateTree', normalize=True, timeout=None) -> float:
|
|
1007
|
+
'''
|
|
1008
|
+
Compute the graph edit distance between two ReticulateTree instances
|
|
1009
|
+
(nodes match when their labels match).
|
|
1010
|
+
Exact by default; with timeout (seconds) the best distance found within
|
|
1011
|
+
that time (an upper bound). Previously this took only the FIRST value
|
|
1012
|
+
of nx.optimize_graph_edit_distance, a loose initial upper bound (e.g. 12
|
|
1013
|
+
for two identical networks whose exact distance is 0), which is what
|
|
1014
|
+
made the score look wrong.
|
|
1015
|
+
'''
|
|
1016
|
+
distance = nx.graph_edit_distance(
|
|
1017
|
+
self.dag, other.dag,
|
|
1018
|
+
node_match=lambda u, v: u.get('label') == v.get('label'),
|
|
1019
|
+
timeout=timeout,
|
|
1020
|
+
)
|
|
1021
|
+
if normalize:
|
|
1022
|
+
normalization = max(
|
|
1023
|
+
len(self.dag.nodes) + len(self.dag.edges),
|
|
1024
|
+
len(other.dag.nodes) + len(other.dag.edges)
|
|
1025
|
+
)
|
|
1026
|
+
distance /= normalization
|
|
1027
|
+
return distance
|
|
1028
|
+
|
|
1029
|
+
def get_edit_distance_multree(self, other: 'ReticulateTree', normalize=True, timeout=300,
|
|
1030
|
+
canonical=True) -> float:
|
|
1031
|
+
'''
|
|
1032
|
+
Compute graph edit distance on MUL-trees (before folding to networks).
|
|
1033
|
+
This compares the tree structures directly without network folding.
|
|
1034
|
+
|
|
1035
|
+
Args:
|
|
1036
|
+
other: Another ReticulateTree instance
|
|
1037
|
+
normalize: If True, normalize by max tree size
|
|
1038
|
+
timeout: Max seconds per comparison (default 300s = 5 min).
|
|
1039
|
+
Returns NaN if exceeded. GED is NP-hard so large trees
|
|
1040
|
+
that don't finish in 5 min won't finish in 24 hours either.
|
|
1041
|
+
canonical: If True (default), children are visited in canonical order so the
|
|
1042
|
+
result cannot depend on the child ordering of the input Newick.
|
|
1043
|
+
Only set False to reproduce pre-2026-08-05 numbers.
|
|
1044
|
+
|
|
1045
|
+
Returns:
|
|
1046
|
+
Edit distance between the two MUL-trees, or NaN if timed out
|
|
1047
|
+
'''
|
|
1048
|
+
import signal
|
|
1049
|
+
|
|
1050
|
+
def _timeout_handler(signum, frame):
|
|
1051
|
+
raise TimeoutError("GED computation timed out")
|
|
1052
|
+
|
|
1053
|
+
# Convert trees to graphs (without folding - just tree structure)
|
|
1054
|
+
def tree_to_simple_graph(tree_obj):
|
|
1055
|
+
"""Convert ete3 tree to NetworkX graph preserving tree structure.
|
|
1056
|
+
|
|
1057
|
+
optimize_graph_edit_distance below returns the FIRST complete edit path its
|
|
1058
|
+
greedy search finds, not the minimum, and that search enumerates candidates
|
|
1059
|
+
in node INSERTION order. So without canonical ordering the score depends on
|
|
1060
|
+
the child order of the input Newick, which is phylogenetically meaningless
|
|
1061
|
+
and differs between the programs that wrote each tree: two identical trees
|
|
1062
|
+
can score up to ~0.6 instead of 0.
|
|
1063
|
+
|
|
1064
|
+
Same idea as _compute_canonical_forms above and _iso_leaf_map in
|
|
1065
|
+
apply_diploidization.py, order both sides canonically so they align.
|
|
1066
|
+
Does not modify the tree.
|
|
1067
|
+
"""
|
|
1068
|
+
G = nx.DiGraph()
|
|
1069
|
+
|
|
1070
|
+
if not canonical:
|
|
1071
|
+
# Kept verbatim so canonical=False reproduces pre-fix numbers exactly
|
|
1072
|
+
# (traverse() defaults to levelorder, not the preorder walk below)
|
|
1073
|
+
for node in tree_obj.tree.traverse():
|
|
1074
|
+
node_id = id(node)
|
|
1075
|
+
# Leaf nodes get their species name as label
|
|
1076
|
+
if node.is_leaf():
|
|
1077
|
+
G.add_node(node_id, label=node.name)
|
|
1078
|
+
else:
|
|
1079
|
+
# Internal nodes don't get labels (or get None)
|
|
1080
|
+
G.add_node(node_id, label=None)
|
|
1081
|
+
|
|
1082
|
+
# Add edge from parent to this node
|
|
1083
|
+
if not node.is_root():
|
|
1084
|
+
parent_id = id(node.up)
|
|
1085
|
+
G.add_edge(parent_id, node_id)
|
|
1086
|
+
|
|
1087
|
+
return G
|
|
1088
|
+
|
|
1089
|
+
canon = {}
|
|
1090
|
+
|
|
1091
|
+
def canonical_form(node):
|
|
1092
|
+
if node.is_leaf():
|
|
1093
|
+
form = node.name
|
|
1094
|
+
else:
|
|
1095
|
+
form = '(' + ','.join(sorted(canonical_form(c) for c in node.children)) + ')'
|
|
1096
|
+
canon[node] = form
|
|
1097
|
+
return form
|
|
1098
|
+
|
|
1099
|
+
canonical_form(tree_obj.tree)
|
|
1100
|
+
|
|
1101
|
+
def add_subtree(node):
|
|
1102
|
+
node_id = id(node)
|
|
1103
|
+
G.add_node(node_id, label=node.name if node.is_leaf() else None)
|
|
1104
|
+
|
|
1105
|
+
if not node.is_root():
|
|
1106
|
+
G.add_edge(id(node.up), node_id)
|
|
1107
|
+
|
|
1108
|
+
# Ties (identical sibling subtrees, i.e. autopolyploidy) keep their input
|
|
1109
|
+
# order, which is harmless because the subtrees are identical
|
|
1110
|
+
for child in sorted(node.children, key=lambda c: canon[c]):
|
|
1111
|
+
add_subtree(child)
|
|
1112
|
+
|
|
1113
|
+
add_subtree(tree_obj.tree)
|
|
1114
|
+
return G
|
|
1115
|
+
|
|
1116
|
+
# Get graphs for both trees
|
|
1117
|
+
graph1 = tree_to_simple_graph(self)
|
|
1118
|
+
graph2 = tree_to_simple_graph(other)
|
|
1119
|
+
|
|
1120
|
+
# GED is NP-hard with exponential memory — skip for very large trees
|
|
1121
|
+
MAX_NODES_FOR_GED = 500
|
|
1122
|
+
n1, n2 = len(graph1.nodes), len(graph2.nodes)
|
|
1123
|
+
if max(n1, n2) > MAX_NODES_FOR_GED:
|
|
1124
|
+
print(f" Skipping MUL-tree GED: trees too large ({n1}, {n2} nodes > {MAX_NODES_FOR_GED} limit)")
|
|
1125
|
+
return float('nan')
|
|
1126
|
+
|
|
1127
|
+
# Compute edit distance with timeout. SIGALRM is POSIX-only, so on Windows
|
|
1128
|
+
# we run without one (fine for the small trees used off-cluster).
|
|
1129
|
+
use_alarm = bool(timeout) and hasattr(signal, 'SIGALRM')
|
|
1130
|
+
if use_alarm:
|
|
1131
|
+
old_handler = signal.signal(signal.SIGALRM, _timeout_handler)
|
|
1132
|
+
signal.alarm(timeout)
|
|
1133
|
+
try:
|
|
1134
|
+
distance = next(nx.optimize_graph_edit_distance(
|
|
1135
|
+
graph1, graph2,
|
|
1136
|
+
node_match=lambda u, v: u.get('label') == v.get('label')
|
|
1137
|
+
))
|
|
1138
|
+
except TimeoutError:
|
|
1139
|
+
n1, n2 = len(graph1.nodes), len(graph2.nodes)
|
|
1140
|
+
print(f" WARNING: MUL-tree GED timed out after {timeout}s "
|
|
1141
|
+
f"(tree sizes: {n1}, {n2} nodes). Returning NaN.")
|
|
1142
|
+
return float('nan')
|
|
1143
|
+
finally:
|
|
1144
|
+
if use_alarm:
|
|
1145
|
+
signal.alarm(0)
|
|
1146
|
+
signal.signal(signal.SIGALRM, old_handler)
|
|
1147
|
+
|
|
1148
|
+
if normalize:
|
|
1149
|
+
normalization = max(
|
|
1150
|
+
len(graph1.nodes) + len(graph1.edges),
|
|
1151
|
+
len(graph2.nodes) + len(graph2.edges)
|
|
1152
|
+
)
|
|
1153
|
+
if normalization > 0:
|
|
1154
|
+
distance /= normalization
|
|
1155
|
+
|
|
1156
|
+
return distance
|
|
1157
|
+
|
|
1158
|
+
def _mu_taxa(self, G=None):
|
|
1159
|
+
'''
|
|
1160
|
+
Sorted taxon labels of the folded network's leaves.
|
|
1161
|
+
|
|
1162
|
+
The mu-representation indexes its vectors by taxon, so the network must
|
|
1163
|
+
carry exactly one leaf per taxon. Folding collapses the MUL-tree copies,
|
|
1164
|
+
so this holds for a correctly folded network and a violation means the
|
|
1165
|
+
network is not a valid comparison target.
|
|
1166
|
+
'''
|
|
1167
|
+
G = self.dag if G is None else G
|
|
1168
|
+
labels = [G.nodes[n].get('label') for n, d in G.out_degree() if d == 0]
|
|
1169
|
+
if any(label is None for label in labels):
|
|
1170
|
+
raise ValueError('Network has an unlabeled leaf; cannot index mu-vectors by taxon.')
|
|
1171
|
+
if len(labels) != len(set(labels)):
|
|
1172
|
+
duplicated = sorted({x for x in labels if labels.count(x) > 1})
|
|
1173
|
+
raise ValueError(
|
|
1174
|
+
f'Network has repeated leaf labels {duplicated}; the mu-representation '
|
|
1175
|
+
'requires one leaf per taxon. Was this folded?'
|
|
1176
|
+
)
|
|
1177
|
+
return sorted(labels)
|
|
1178
|
+
|
|
1179
|
+
@staticmethod
|
|
1180
|
+
def _suppress_elision_nodes(G):
|
|
1181
|
+
'''
|
|
1182
|
+
Drop nodes with in-degree 1 and out-degree 1.
|
|
1183
|
+
|
|
1184
|
+
Folding can leave these behind. They carry no phylogenetic information,
|
|
1185
|
+
and semi-binary requires every internal tree node to have out-degree 2,
|
|
1186
|
+
so they must go before the class preconditions or the representation
|
|
1187
|
+
are evaluated.
|
|
1188
|
+
'''
|
|
1189
|
+
H = G.copy()
|
|
1190
|
+
changed = True
|
|
1191
|
+
while changed:
|
|
1192
|
+
changed = False
|
|
1193
|
+
for node in list(H.nodes()):
|
|
1194
|
+
if H.in_degree(node) == 1 and H.out_degree(node) == 1:
|
|
1195
|
+
parent = next(H.predecessors(node))
|
|
1196
|
+
child = next(H.successors(node))
|
|
1197
|
+
H.remove_node(node)
|
|
1198
|
+
if parent != child:
|
|
1199
|
+
H.add_edge(parent, child)
|
|
1200
|
+
changed = True
|
|
1201
|
+
break
|
|
1202
|
+
return H
|
|
1203
|
+
|
|
1204
|
+
def _mu_network(self):
|
|
1205
|
+
'''The folded network in the form the mu-representation is defined on.'''
|
|
1206
|
+
return self._suppress_elision_nodes(self.dag)
|
|
1207
|
+
|
|
1208
|
+
def _check_mu_preconditions(self, G, label='network'):
|
|
1209
|
+
'''
|
|
1210
|
+
Enforce the hypotheses of Theorem 1 of arXiv:2412.05107.
|
|
1211
|
+
|
|
1212
|
+
Raises rather than returning a number the theorem does not licence. A
|
|
1213
|
+
network outside the class can share its representation with a
|
|
1214
|
+
non-isomorphic one, so a distance of 0 would not mean what it appears
|
|
1215
|
+
to mean.
|
|
1216
|
+
'''
|
|
1217
|
+
reticulations = {u for u, d in G.in_degree() if d >= 2}
|
|
1218
|
+
|
|
1219
|
+
stacked = [(p, c) for p, c in G.edges()
|
|
1220
|
+
if p in reticulations and c in reticulations]
|
|
1221
|
+
if stacked:
|
|
1222
|
+
raise ValueError(
|
|
1223
|
+
f'The {label} is not stack-free: {len(stacked)} reticulation(s) are '
|
|
1224
|
+
'children of reticulations. Theorem 1 of the modified '
|
|
1225
|
+
'mu-representation does not apply, so no distance is reported.'
|
|
1226
|
+
)
|
|
1227
|
+
|
|
1228
|
+
offending = []
|
|
1229
|
+
for node in G.nodes():
|
|
1230
|
+
in_degree, out_degree = G.in_degree(node), G.out_degree(node)
|
|
1231
|
+
if out_degree == 0:
|
|
1232
|
+
if in_degree != 1:
|
|
1233
|
+
offending.append((in_degree, out_degree))
|
|
1234
|
+
elif node in reticulations:
|
|
1235
|
+
if out_degree != 1:
|
|
1236
|
+
offending.append((in_degree, out_degree))
|
|
1237
|
+
elif out_degree != 2:
|
|
1238
|
+
offending.append((in_degree, out_degree))
|
|
1239
|
+
if offending:
|
|
1240
|
+
raise ValueError(
|
|
1241
|
+
f'The {label} is not semi-binary: {len(offending)} node(s) violate the '
|
|
1242
|
+
f'degree constraints, e.g. (in,out) = {offending[:5]}. Tree nodes must '
|
|
1243
|
+
'have out-degree 2 and reticulations out-degree 1.'
|
|
1244
|
+
)
|
|
1245
|
+
|
|
1246
|
+
@staticmethod
|
|
1247
|
+
def _suppress_node(G, node):
|
|
1248
|
+
'''Bypass a node left with one parent and one child, or a stalled root.'''
|
|
1249
|
+
if node not in G:
|
|
1250
|
+
return
|
|
1251
|
+
if G.in_degree(node) == 1 and G.out_degree(node) == 1:
|
|
1252
|
+
parent = next(G.predecessors(node))
|
|
1253
|
+
child = next(G.successors(node))
|
|
1254
|
+
G.remove_node(node)
|
|
1255
|
+
if parent != child:
|
|
1256
|
+
G.add_edge(parent, child)
|
|
1257
|
+
elif G.in_degree(node) == 0 and G.out_degree(node) == 1:
|
|
1258
|
+
G.remove_node(node)
|
|
1259
|
+
|
|
1260
|
+
@classmethod
|
|
1261
|
+
def _pick_reducible_pair(cls, G):
|
|
1262
|
+
'''
|
|
1263
|
+
Pick one cherry or reticulated cherry from G, reducing it in place.
|
|
1264
|
+
|
|
1265
|
+
A cherry is two leaves sharing a parent. A reticulated cherry is a leaf
|
|
1266
|
+
whose parent is a reticulation that is itself a child of the parent of
|
|
1267
|
+
another leaf. Returns the pair of leaf labels, or None if neither
|
|
1268
|
+
exists, in which case the reduction is stuck.
|
|
1269
|
+
'''
|
|
1270
|
+
leaves = [n for n, d in G.out_degree() if d == 0]
|
|
1271
|
+
|
|
1272
|
+
by_parent = defaultdict(list)
|
|
1273
|
+
for leaf in leaves:
|
|
1274
|
+
if G.in_degree(leaf) == 1:
|
|
1275
|
+
by_parent[next(G.predecessors(leaf))].append(leaf)
|
|
1276
|
+
for parent, siblings in by_parent.items():
|
|
1277
|
+
if len(siblings) >= 2:
|
|
1278
|
+
removed, kept = siblings[0], siblings[1]
|
|
1279
|
+
pair = (G.nodes[removed].get('label'), G.nodes[kept].get('label'))
|
|
1280
|
+
G.remove_node(removed)
|
|
1281
|
+
cls._suppress_node(G, parent)
|
|
1282
|
+
return pair
|
|
1283
|
+
|
|
1284
|
+
reticulations = {n for n, d in G.in_degree() if d >= 2}
|
|
1285
|
+
for leaf in leaves:
|
|
1286
|
+
if G.in_degree(leaf) != 1:
|
|
1287
|
+
continue
|
|
1288
|
+
reticulation = next(G.predecessors(leaf))
|
|
1289
|
+
if reticulation not in reticulations:
|
|
1290
|
+
continue
|
|
1291
|
+
for parent in list(G.predecessors(reticulation)):
|
|
1292
|
+
partners = [c for c in G.successors(parent)
|
|
1293
|
+
if c != reticulation and G.out_degree(c) == 0]
|
|
1294
|
+
if not partners:
|
|
1295
|
+
continue
|
|
1296
|
+
pair = (G.nodes[leaf].get('label'), G.nodes[partners[0]].get('label'))
|
|
1297
|
+
G.remove_edge(parent, reticulation)
|
|
1298
|
+
cls._suppress_node(G, reticulation)
|
|
1299
|
+
cls._suppress_node(G, parent)
|
|
1300
|
+
return pair
|
|
1301
|
+
|
|
1302
|
+
return None
|
|
1303
|
+
|
|
1304
|
+
def orchard_certificate(self):
|
|
1305
|
+
'''
|
|
1306
|
+
Try to reduce the network to a single leaf by cherry picking.
|
|
1307
|
+
|
|
1308
|
+
Returns (True, sequence) when it succeeds, where sequence is the list of
|
|
1309
|
+
picked pairs and therefore a certificate that the network is orchard.
|
|
1310
|
+
Returns (False, None) when the reduction gets stuck.
|
|
1311
|
+
|
|
1312
|
+
The search is greedy. A success is a proof because the sequence is
|
|
1313
|
+
exhibited. A failure is only a proof if cherry picking is confluent for
|
|
1314
|
+
this class, so treat (False, None) as "no certificate found" rather than
|
|
1315
|
+
as established non-orchard.
|
|
1316
|
+
'''
|
|
1317
|
+
G = self._mu_network()
|
|
1318
|
+
sequence = []
|
|
1319
|
+
while True:
|
|
1320
|
+
leaves = [n for n, d in G.out_degree() if d == 0]
|
|
1321
|
+
if len(leaves) <= 1:
|
|
1322
|
+
return True, sequence
|
|
1323
|
+
pair = self.__class__._pick_reducible_pair(G)
|
|
1324
|
+
if pair is None:
|
|
1325
|
+
return False, None
|
|
1326
|
+
sequence.append(pair)
|
|
1327
|
+
|
|
1328
|
+
def is_orchard(self):
|
|
1329
|
+
'''True when a cherry picking sequence reducing the network was found.'''
|
|
1330
|
+
return self.orchard_certificate()[0]
|
|
1331
|
+
|
|
1332
|
+
def get_modified_mu_representation(self):
|
|
1333
|
+
'''
|
|
1334
|
+
Modified mu-representation, Definition 1 of arXiv:2412.05107.
|
|
1335
|
+
|
|
1336
|
+
mu-bar(v) = ( in_degree(v), mu_1(v), ..., mu_n(v) )
|
|
1337
|
+
|
|
1338
|
+
where mu_i(v) counts directed paths from v to leaf i. The multiset runs
|
|
1339
|
+
over ALL nodes, reticulations included.
|
|
1340
|
+
|
|
1341
|
+
This is not the extended mu-representation of Cardona et al. 2024. That
|
|
1342
|
+
one prepends the number of paths to a reticulation instead of the
|
|
1343
|
+
in-degree, excludes reticulation nodes, and encodes only BINARY orchard
|
|
1344
|
+
networks. Figure 1 of arXiv:2412.05107 exhibits two non-isomorphic
|
|
1345
|
+
semi-binary stack-free networks sharing an extended mu-representation,
|
|
1346
|
+
and MUL-tree folding produces semi-binary networks, so the extended
|
|
1347
|
+
form is not sound here.
|
|
1348
|
+
|
|
1349
|
+
The mu-vectors themselves come from the authors' `phylonetwork`
|
|
1350
|
+
package, so the path counts are the published implementation. Making
|
|
1351
|
+
them semi-binary ready needs only the in-degree prepended, which the
|
|
1352
|
+
package already exposes. Ours is the suppression of degree-2 nodes that
|
|
1353
|
+
semi-binary requires, the class preconditions, and the distance.
|
|
1354
|
+
'''
|
|
1355
|
+
G = self._mu_network()
|
|
1356
|
+
self._check_mu_preconditions(G)
|
|
1357
|
+
|
|
1358
|
+
try:
|
|
1359
|
+
import phylonetwork
|
|
1360
|
+
except ImportError as exc:
|
|
1361
|
+
raise ImportError(
|
|
1362
|
+
'The mu-vectors are computed by the phylonetwork reference '
|
|
1363
|
+
'implementation (Cardona et al.), which is not installed. '
|
|
1364
|
+
'Install it with: pip install phylonetwork==2.2.2'
|
|
1365
|
+
) from exc
|
|
1366
|
+
|
|
1367
|
+
# phylonetwork indexes mu-vectors by every node LABEL, not only leaves,
|
|
1368
|
+
# so an internal node carrying a name would add a coordinate. Vectors of
|
|
1369
|
+
# two networks would then have different widths, no tuple could compare
|
|
1370
|
+
# equal, and the distance would pin at exactly 1.0 while the taxon guard,
|
|
1371
|
+
# which looks at leaves only, saw nothing wrong. Strip them.
|
|
1372
|
+
stripped = G.copy()
|
|
1373
|
+
for node in stripped.nodes():
|
|
1374
|
+
if stripped.out_degree(node) != 0:
|
|
1375
|
+
stripped.nodes[node].pop('label', None)
|
|
1376
|
+
|
|
1377
|
+
network = phylonetwork.PhylogeneticNetwork(
|
|
1378
|
+
eNewick=self.__class__(stripped).to_enewick()
|
|
1379
|
+
)
|
|
1380
|
+
|
|
1381
|
+
taxa = self._mu_taxa(G)
|
|
1382
|
+
if sorted(network.taxa) != taxa:
|
|
1383
|
+
raise ValueError(
|
|
1384
|
+
'Taxa seen by the reference implementation do not match the leaf '
|
|
1385
|
+
f'labels of the network. Leaves: {taxa}. Reference: '
|
|
1386
|
+
f'{sorted(network.taxa)}. The mu-vectors would be misaligned.'
|
|
1387
|
+
)
|
|
1388
|
+
|
|
1389
|
+
return [tuple([network.in_degree(u)] + [int(x) for x in network.mu_dict[u]])
|
|
1390
|
+
for u in network.nodes()]
|
|
1391
|
+
|
|
1392
|
+
def _mu_path_counts(self, G):
|
|
1393
|
+
'''
|
|
1394
|
+
Standard mu-vector of every node: mu_i(v) counts paths from v to leaf i.
|
|
1395
|
+
|
|
1396
|
+
Nodes are visited in reverse topological order so every child is
|
|
1397
|
+
complete before its parent.
|
|
1398
|
+
'''
|
|
1399
|
+
taxa = self._mu_taxa(G)
|
|
1400
|
+
position = {taxon: i for i, taxon in enumerate(taxa)}
|
|
1401
|
+
|
|
1402
|
+
vectors = {}
|
|
1403
|
+
for node in reversed(list(nx.topological_sort(G))):
|
|
1404
|
+
vector = [0] * len(taxa)
|
|
1405
|
+
for child in G.successors(node):
|
|
1406
|
+
child_vector = vectors[child]
|
|
1407
|
+
for i in range(len(taxa)):
|
|
1408
|
+
vector[i] += child_vector[i]
|
|
1409
|
+
if G.out_degree(node) == 0:
|
|
1410
|
+
vector[position[G.nodes[node]['label']]] += 1
|
|
1411
|
+
vectors[node] = vector
|
|
1412
|
+
|
|
1413
|
+
return vectors, taxa
|
|
1414
|
+
|
|
1415
|
+
def get_mu_root_vector(self):
|
|
1416
|
+
'''
|
|
1417
|
+
Taxa and the root's per-taxon path counts.
|
|
1418
|
+
|
|
1419
|
+
mu_i(root) counts root-to-leaf-i paths, which equals the number of
|
|
1420
|
+
copies of taxon i in the MUL-tree, so this is the copy-number (ploidy)
|
|
1421
|
+
vector of the network.
|
|
1422
|
+
'''
|
|
1423
|
+
G = self._mu_network()
|
|
1424
|
+
vectors, taxa = self._mu_path_counts(G)
|
|
1425
|
+
root = self.__class__.get_dag_root(G)
|
|
1426
|
+
return taxa, tuple(vectors[root])
|
|
1427
|
+
|
|
1428
|
+
def get_mu_distance(self, other: 'ReticulateTree', normalize=True) -> float:
|
|
1429
|
+
'''
|
|
1430
|
+
Extended mu-distance between two folded networks.
|
|
1431
|
+
|
|
1432
|
+
d(N1, N2) = |mu-bar(N1) symmetric-difference mu-bar(N2)|, Theorem 1 of
|
|
1433
|
+
arXiv:2412.05107: for N1 semi-binary stack-free orchard and N2
|
|
1434
|
+
semi-binary stack-free, this is 0 exactly when N1 and N2 are isomorphic.
|
|
1435
|
+
|
|
1436
|
+
Uses the MODIFIED mu-representation, which prepends each node's
|
|
1437
|
+
in-degree to its standard mu-vector and ranges over all nodes. The
|
|
1438
|
+
extended mu-representation of Cardona et al. 2024, which the
|
|
1439
|
+
phylonetwork package implements, encodes only BINARY orchard networks
|
|
1440
|
+
and is not sound on the semi-binary networks MUL-tree folding produces.
|
|
1441
|
+
Our standard mu-vectors are cross-checked against that package.
|
|
1442
|
+
|
|
1443
|
+
Networks outside the semi-binary stack-free class, and pairs on
|
|
1444
|
+
different taxon sets, raise rather than returning a number the theorem
|
|
1445
|
+
does not licence.
|
|
1446
|
+
|
|
1447
|
+
With normalize=True the count is divided by the number of INTERNAL
|
|
1448
|
+
nodes of the two networks, |V1| + |V2| - 2n for n taxa, which is the
|
|
1449
|
+
largest the count can be. That gives a value in [0, 1] on every pair,
|
|
1450
|
+
reaching 1 when the networks share no internal structure, and it is
|
|
1451
|
+
what makes the value comparable across networks of different sizes.
|
|
1452
|
+
See the comment on the normalization below for why the leaves are
|
|
1453
|
+
excluded. normalize=False returns the published raw count.
|
|
1454
|
+
'''
|
|
1455
|
+
network_self = self._mu_network()
|
|
1456
|
+
network_other = other._mu_network()
|
|
1457
|
+
self._check_mu_preconditions(network_self, 'first network')
|
|
1458
|
+
other._check_mu_preconditions(network_other, 'second network')
|
|
1459
|
+
|
|
1460
|
+
taxa_self = self._mu_taxa(network_self)
|
|
1461
|
+
taxa_other = other._mu_taxa(network_other)
|
|
1462
|
+
if taxa_self != taxa_other:
|
|
1463
|
+
only_self = sorted(set(taxa_self) - set(taxa_other))
|
|
1464
|
+
only_other = sorted(set(taxa_other) - set(taxa_self))
|
|
1465
|
+
raise ValueError(
|
|
1466
|
+
'Cannot compute mu-distance between networks on different taxa. '
|
|
1467
|
+
f'Only in first: {only_self}. Only in second: {only_other}.'
|
|
1468
|
+
)
|
|
1469
|
+
|
|
1470
|
+
mu_self = self.get_modified_mu_representation()
|
|
1471
|
+
mu_other = other.get_modified_mu_representation()
|
|
1472
|
+
set_self, set_other = set(mu_self), set(mu_other)
|
|
1473
|
+
distance = float(sum(1 for vector in mu_self + mu_other
|
|
1474
|
+
if vector not in set_self or vector not in set_other))
|
|
1475
|
+
|
|
1476
|
+
if normalize:
|
|
1477
|
+
# Normalize by the INTERNAL nodes of both networks, not every node.
|
|
1478
|
+
#
|
|
1479
|
+
# _check_mu_preconditions requires every leaf to have in-degree 1, so
|
|
1480
|
+
# the modified mu-vector of the leaf labelled x is (1, e_x) in any
|
|
1481
|
+
# network that reaches this point, and both networks are on the same
|
|
1482
|
+
# taxa (checked above). All 2n leaf vectors are therefore shared by
|
|
1483
|
+
# construction and can never enter the symmetric difference. Counting
|
|
1484
|
+
# them in the denominator caps the distance at 1 - 2n/(|V1|+|V2|),
|
|
1485
|
+
# which depends on the leaf-to-node ratio of the pair and runs from
|
|
1486
|
+
# about 0.48 to 0.76 over our 21 reference networks. That defeats the
|
|
1487
|
+
# point of normalizing, since values on networks of different shapes
|
|
1488
|
+
# then sit on different scales and cannot be averaged.
|
|
1489
|
+
#
|
|
1490
|
+
# Dividing by the internal nodes makes the denominator equal to the
|
|
1491
|
+
# largest value the numerator can take, so the range is [0, 1] for
|
|
1492
|
+
# every pair and 1 means the two networks share no internal structure.
|
|
1493
|
+
#
|
|
1494
|
+
# The numerator is untouched. Removing a sub-multiset that is
|
|
1495
|
+
# identical on both sides cannot change whether the representations
|
|
1496
|
+
# are equal, so Theorem 1 still gives 0 exactly for isomorphic
|
|
1497
|
+
# networks. normalize=False remains the published raw count.
|
|
1498
|
+
n_taxa = len(taxa_self) # == len(taxa_other), enforced above
|
|
1499
|
+
normalization = (len(mu_self) - n_taxa) + (len(mu_other) - n_taxa)
|
|
1500
|
+
if normalization <= 0:
|
|
1501
|
+
raise ValueError(
|
|
1502
|
+
'No internal nodes to normalize by: the networks have no node '
|
|
1503
|
+
'above their leaves, so there is no structure to compare.'
|
|
1504
|
+
)
|
|
1505
|
+
distance /= normalization
|
|
1506
|
+
|
|
1507
|
+
return distance
|
|
1508
|
+
|
|
1509
|
+
def __sub__(self, other: 'ReticulateTree') -> float:
|
|
1510
|
+
'''
|
|
1511
|
+
Overriding the minus operator to compute the edit distance between two ReticulateTree instances.
|
|
1512
|
+
'''
|
|
1513
|
+
if not isinstance(other, ReticulateTree):
|
|
1514
|
+
raise TypeError('Subtraction is only supported between ReticulateTree instances.')
|
|
1515
|
+
return self.get_edit_distance(other)
|
|
1516
|
+
|