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 ADDED
@@ -0,0 +1,7 @@
1
+ """multree: reticulate trees (MUL-trees and phylogenetic networks) and measures to compare them.
2
+
3
+ from multree.reticulate_tree import ReticulateTree
4
+ from multree import compare_reticulations
5
+ """
6
+
7
+ __version__ = "1.0.0"
@@ -0,0 +1,514 @@
1
+ import warnings
2
+ import numpy as np
3
+ import pandas as pd
4
+ import seaborn as sns
5
+ import matplotlib.pyplot as plt
6
+ from pathlib import Path
7
+ from scipy.optimize import linear_sum_assignment
8
+ try: # as a package (multree)
9
+ from .reticulate_tree import ReticulateTree
10
+ except ImportError: # as a flat folder on sys.path
11
+ from reticulate_tree import ReticulateTree
12
+
13
+ # Methods that can only infer a single reticulation by design.
14
+ # Exported so downstream scripts can check method membership.
15
+ # For these methods, Jaccard metrics use best-match-only (no penalty for
16
+ # unmatched reticulations in the reference network).
17
+ SINGLE_RETICULATION_METHODS = {'grampa'}
18
+
19
+ '''
20
+ Edit distance: fixed in ReticulateTree.get_edit_distance (it took the first,
21
+ loose upper bound of nx.optimize_graph_edit_distance instead of the minimum).
22
+ Still to check: the GED inside Polyphest's mul2net folding (polyphest_multree_to_dag).
23
+ '''
24
+
25
+ def compare_num_rets(ret_count_A, ret_count_B):
26
+ """
27
+ Return signed difference: ret_count_B - ret_count_A (predicted - truth).
28
+ Positive = over-estimation, Negative = under-estimation.
29
+ Also returns absolute difference for backward compatibility.
30
+ """
31
+ signed_diff = ret_count_B - ret_count_A
32
+ abs_diff = abs(signed_diff)
33
+ return {'signed': signed_diff, 'abs': abs_diff}
34
+
35
+ def j_dist(intersect, union):
36
+ return 0.0 if union == 0 else 1.0 - (intersect / union)
37
+
38
+ def compare_ploidy_diff(leaf_counts_A, leaf_counts_B):
39
+ '''
40
+ Distance (1 - matches) over leaf ploidy counts beyond diploid.
41
+ Also returns TP/FP/FN counts of extra copies.
42
+ Example:
43
+ A: {a:2,b:3,c:2,rest:1...}, B: {a:2,b:2,c:3,rest:1...}
44
+ -> extras are: a: 1, b: 2 or 1, c: 1 or 2
45
+ -> they differ by 2 out of 5 extras -> dist = 2/5 = 1 - 3/5 (=matches) = 0.4
46
+ -> 3 correct, 1 false positive, 1 false negative
47
+ '''
48
+ taxa = set(leaf_counts_A) | set(leaf_counts_B)
49
+ intersect = 0
50
+ union = 0
51
+ TP = FP = FN = 0
52
+
53
+ for t in taxa:
54
+ c1 = leaf_counts_A.get(t, 0) - 1 # truth copies beyond diploid
55
+ c2 = leaf_counts_B.get(t, 0) - 1 # predicted copies
56
+ if c1 == 0 and c2 == 0:
57
+ continue
58
+ common = min(c1, c2)
59
+ TP += common
60
+ FP += max(0, c2 - c1)
61
+ FN += max(0, c1 - c2)
62
+ intersect += common
63
+ union += max(c1, c2)
64
+
65
+ return {'dist': j_dist(intersect, union), 'FP': FP, 'FN': FN, 'TP': TP}
66
+
67
+ def compare_polyploid_species(leaf_counts_A, leaf_counts_B):
68
+ '''
69
+ Jaccard distance on the sets of polyploid species (species with >1 copy).
70
+ Binary metric: only cares about WHICH species are polyploid, not copy counts.
71
+ Returns float distance in [0, 1]. 0 = same polyploid species, 1 = completely different.
72
+ '''
73
+ polyploids_A = {sp for sp, count in leaf_counts_A.items() if count > 1}
74
+ polyploids_B = {sp for sp, count in leaf_counts_B.items() if count > 1}
75
+
76
+ if len(polyploids_A) == 0 and len(polyploids_B) == 0:
77
+ return 0.0 # Both diploid-only — perfect agreement
78
+
79
+ intersection = len(polyploids_A & polyploids_B)
80
+ union = len(polyploids_A | polyploids_B)
81
+ return 1.0 - (intersection / union) if union > 0 else 1.0
82
+
83
+
84
+ def jaccard(a, b):
85
+ '''Jaccard similarity between two sets; 1.0 if both empty.'''
86
+ a, b = set(a), set(b)
87
+ if not a and not b:
88
+ return 1.0
89
+ return len(a & b) / len(a | b)
90
+
91
+ def hungarian_match(list1, list2, sim_fn):
92
+ '''
93
+ Match two lists of items using the Hungarian algorithm to maximize similarity.
94
+ sim_fn(x, y) should return a similarity score (higher = better).
95
+ Returns (row_ind, col_ind) arrays of matched indices. Possibly empty arrays.
96
+ '''
97
+ if not list1 or not list2:
98
+ return np.array([], int), np.array([], int)
99
+ sim_matrix = np.array([[sim_fn(x, y) for y in list2] for x in list1], dtype=float)
100
+ # maximize by minimizing negative similarity
101
+ row_ind, col_ind = linear_sum_assignment(-sim_matrix)
102
+ #total_score = sim_matrix[row_ind, col_ind].sum()
103
+ return row_ind, col_ind
104
+
105
+ def run_hungarian_on_groups(groups1, groups2):
106
+ '''
107
+ Prepare sets for groups1 and groups2 and compute optimal Hungarian matching
108
+ using Jaccard similarity. Returns (sets1, sets2, row_ind, col_ind).
109
+ sets1/sets2 are lists of set objects in the same order as the input iterables.
110
+ '''
111
+ sets1 = [set(v) for v in groups1]
112
+ sets2 = [set(v) for v in groups2]
113
+ row_ind, col_ind = hungarian_match(sets1, sets2, jaccard)
114
+ max_len = max(len(sets1), len(sets2))
115
+ return sets1, sets2, row_ind, col_ind, max_len
116
+
117
+ def populate_dict(keys, values):
118
+ '''
119
+ Create a dict from keys and values lists.
120
+ '''
121
+ return {k: v for k, v in zip(keys, values)}
122
+
123
+ ALL_STATS_KEYS = ['dist', 'FP', 'FN', 'TP']
124
+ def handle_empty_cases(max_len, len1, len2):
125
+ '''
126
+ Handle cases where one or both input sets are empty.
127
+ Returns: (dist, FP, FN, TP)
128
+ '''
129
+ if not max_len:
130
+ return populate_dict(ALL_STATS_KEYS, (0.0, 0.0, 0.0, 0.0))
131
+ if not len1: # only set2 non-empty
132
+ return populate_dict(ALL_STATS_KEYS, (1.0, 1.0, 0.0, 0.0))
133
+ if not len2: # only set1 non-empty
134
+ return populate_dict(ALL_STATS_KEYS, (1.0, 0.0, 1.0, 0.0))
135
+ return None # both non-empty
136
+
137
+ def compute_leaves_stats(sets1, sets2, row_ind, col_ind, debug=False):
138
+
139
+ # compute stats for each matched pair: (intersection, lenA, lenB)
140
+ stats = [
141
+ (len(sets1[i] & sets2[j]), len(sets1[i]), len(sets2[j]))
142
+ for i, j in zip(row_ind, col_ind)
143
+ ]
144
+ # sum up totals
145
+ totals = {}
146
+ totals['dist'] = sum(j_dist(inter, lenA + lenB - inter) for inter, lenA, lenB in stats)
147
+ # Handle zero-division when networks have no reticulations/polyploids
148
+ totals['FP'] = sum((lenB - inter) / lenB if lenB > 0 else 0.0 for inter, _, lenB in stats)
149
+ totals['FN'] = sum((lenA - inter) / lenA if lenA > 0 else 0.0 for inter, lenA, _ in stats)
150
+
151
+ if debug:
152
+ print('dists:', [j_dist(inter, lenA + lenB - inter) for inter, lenA, lenB in stats])
153
+ print('FPs:', [(lenB - inter) / lenB if lenB > 0 else 0.0 for inter, _, lenB in stats])
154
+ print('FNs:', [(lenA - inter) / lenA if lenA > 0 else 0.0 for inter, lenA, _ in stats])
155
+
156
+ return totals
157
+
158
+ def compute_sisters_stats(sisters1, sisters2, keys1, keys2, row_ind, col_ind, debug=False):
159
+
160
+ totals = {}
161
+ t_dist, t_FP, t_FN = 0.0, 0.0, 0.0
162
+ get1, get2 = sisters1.get, sisters2.get # localize lookups (small perf gain)
163
+ for i, j in zip(row_ind, col_ind):
164
+
165
+ if debug:
166
+ print(f'Computing reticulation pair: {i}, {j}')
167
+
168
+ # map matched indices back to keys
169
+ k1, k2 = keys1[i], keys2[j]
170
+ precomputed = run_hungarian_on_groups(get1(k1, []), get2(k2, []))
171
+ curr = match_and_compare(None, None, precomputed_match=precomputed, debug=debug)
172
+ t_dist += curr['dist']
173
+ t_FP += curr['FP']
174
+ t_FN += curr['FN']
175
+ totals['dist'], totals['FP'], totals['FN'] = t_dist, t_FP, t_FN
176
+
177
+ return totals
178
+
179
+ def correct_and_normalize_stats(totals, max_len, intersect_len, len1, len2, debug=False, partial_match=False):
180
+ '''
181
+ Normalize total_dist, total_FP, total_FN by max_len and account for unmatched groups.
182
+ Modifies the `totals` dict in place.
183
+ Assumes that at most one input set is empty (i.e., max_len > 0).
184
+ totals = {'dist': float, 'FP': float, 'FN': float}
185
+
186
+ If partial_match=True, normalize by the number of matched pairs (intersect_len)
187
+ instead of max_len and skip the unmatched penalty. This is fair for methods
188
+ that can only infer a limited number of reticulations (e.g. GRAMPA).
189
+ '''
190
+ if partial_match and intersect_len > 0:
191
+ # No penalty for unmatched groups; normalize by matched pairs only
192
+ totals['dist'] /= intersect_len
193
+ totals['FP'] /= intersect_len
194
+ totals['FN'] /= intersect_len
195
+ else:
196
+ # Standard: account for unmatched groups
197
+ totals['dist'] += (max_len - intersect_len) # unmatched groups count as full distance
198
+ totals['FP'] += max(0, max_len - len1) # unmatched groups in set2 count as full FP
199
+ totals['FN'] += max(0, max_len - len2) # unmatched groups in set1 count as full FN
200
+
201
+ # normalize by max number of groups
202
+ totals['dist'] /= max_len
203
+ totals['FP'] /= max_len
204
+ totals['FN'] /= max_len
205
+
206
+ if debug:
207
+ mode = 'partial' if partial_match else 'standard'
208
+ print(f'Corrections ({mode}): dist +{(max_len - intersect_len) if not partial_match else 0}, '
209
+ f'FP +{max(0, max_len - len1) if not partial_match else 0}, '
210
+ f'FN +{max(0, max_len - len2) if not partial_match else 0}')
211
+ print(f'Corrected norm. stats: dist={totals["dist"]:.4f}, FP={totals["FP"]:.4f}, FN={totals["FN"]:.4f}')
212
+
213
+ def match_and_compare(leaves1, leaves2, sisters1=None, sisters2=None, precomputed_match=None, debug=False, partial_match=False):
214
+ '''
215
+ Leaves mode:
216
+ (1 - Total Jaccard) over matched reticulation leaf sets.
217
+ Sisters mode:
218
+ (1 - Total Nested Jaccard) over matched reticulation leaf sets and their sister groups:
219
+ - First match reticulations by their leaf-sets
220
+ - Then for each matched reticulation pair, compute matching stats across their sister groups
221
+ Then, compute the average the stats across all matched reticulation pairs and correct for unmatched reticulations
222
+ leaves1 and leaves2 are dict-like mapping reticulation-id -> iterable of leaf labels.
223
+ sisters1 and sisters2 are dict-like mapping reticulation-id -> list of iterables of leaf labels (sister groups).
224
+ Returns: dict of stats with keys: dist, FP, FN, TP
225
+ '''
226
+ mode = 'leaves' if sisters1 is None and sisters2 is None else 'sisters'
227
+ if (sisters1 is None or sisters2 is None) and mode == 'sisters':
228
+ raise ValueError('Both or neither of sisters1 and sisters2 must be provided.')
229
+
230
+ if precomputed_match is not None:
231
+ sets1, sets2, row_ind, col_ind, max_len = precomputed_match
232
+ else: # leaves must be dict-like like in this case!
233
+ sets1, sets2, row_ind, col_ind, max_len = run_hungarian_on_groups(leaves1.values(), leaves2.values())
234
+
235
+ if debug:
236
+ print(f'Hungarian {mode} matching: {row_ind}, {col_ind}, {max_len}\n\tfor sets: {sets1}, {sets2}')
237
+
238
+ empty_case = handle_empty_cases(max_len, len(sets1), len(sets2))
239
+ if empty_case is not None:
240
+ return empty_case
241
+
242
+ if mode == 'leaves':
243
+ totals = compute_leaves_stats(sets1, sets2, row_ind, col_ind, debug=debug)
244
+ elif mode == 'sisters':
245
+ # preserve keys order in lists to index into sets1/sets2
246
+ keys1, keys2 = list(leaves1), list(leaves2)
247
+ totals = compute_sisters_stats(sisters1, sisters2, keys1, keys2, row_ind, col_ind, debug=debug)
248
+ else:
249
+ raise ValueError(f'Unknown mode: {mode}')
250
+
251
+ correct_and_normalize_stats(totals, max_len, len(row_ind), len(sets1), len(sets2), debug=debug, partial_match=partial_match)
252
+
253
+ # NOTE: true positives (TP) can't be derived as 1 - tot_dist in this case, because
254
+ # the denominator is different in each case (unmatched groups count as full distance/FP/FN).
255
+ # One would need to define a TP_precise and TP_recall separately if needed.
256
+ # eg:
257
+ # tot_TP_prec = sum(inter / a_len if a_len else 0.0 for inter, a_len, _ in stats)
258
+ # tot_TP_rec = sum(inter / b_len if b_len else 0.0 for inter, _, b_len in stats)
259
+
260
+ '''
261
+ Clustering A: A1={1,2,3} (size 3), A2={4} (size 1) — 2 clusters
262
+ Clustering B: B1={1,2} (size 2), B2={6,4,5} (size 3) — 2 clusters
263
+
264
+ stats = [
265
+ 2/3 # A1 matched to B1: intersection = 2, |A1|=3, |B1|=2
266
+ 1/3 # A2 matched to B2: intersection = 1, |A2|=1, |B2|=3
267
+ ]
268
+ -> 2/3 + 1/3 = 1.0 -> 1 - 1.0/2 (= 0.5 TP) = 0.5 dist
269
+
270
+ But:
271
+ TP_prec = 2/3 + 1/1 = 1.666 -> 1.666/2 = 0.8333
272
+ TP_rec = 2/2 + 1/3 = 1.333 -> 1.333/2 = 0.6666
273
+
274
+ Pres = TP / (TP + FP) = (2, 1) / (2, 1 + 0, 2) = 1 + 1/3 = 4/3 -> /2 = 0.6667
275
+ Rec = TP / (TP + FN) = (2, 1) / (2, 1 + 1, 0) = 2/3 + 1 = 5/3 -> /2 = 0.8333
276
+ '''
277
+
278
+ totals['TP'] = 1.0 - totals['dist'] # approximate TP as 1 - dist for simplicity
279
+
280
+ return totals
281
+
282
+ # Distinct mu precondition failures already reported, so a run warns once per
283
+ # reason instead of thousands of times for the same cause.
284
+ _MU_REPORTED = set()
285
+
286
+
287
+ def compare_mu(obj1, obj2):
288
+ '''
289
+ mu-distance columns for one pair.
290
+
291
+ Only the normalized distance is reported, since that is the one comparable
292
+ across networks of different sizes. The published unnormalized count stays
293
+ available as get_mu_distance(normalize=False); reporting both doubled the
294
+ cost because each call rebuilds both representations.
295
+
296
+ A pair on mismatched taxa, or whose networks fall outside the semi-binary
297
+ stack-free class of Theorem 1, cannot be scored. Raising would discard the
298
+ other metrics for that pair, which are still valid, so instead the distance
299
+ is NaN and mu_scored is 0.0.
300
+
301
+ Every value returned here must be numeric. Metrics land in a long-format
302
+ 'value' column that aggregate_replicates runs mean/std/min/max over, and a
303
+ string there raises TypeError and takes the whole summary down. That is why
304
+ the reason is emitted as a warning rather than returned as a column.
305
+
306
+ mu_scored exists so the loss is countable: its mean over a group is the
307
+ fraction of pairs that could be scored, which appears in every summary
308
+ table. Without it a mean over mu_distance would quietly skip the failures
309
+ and only n_valid would record them.
310
+
311
+ Precondition failures are caught, and so is a missing phylonetwork (it cannot be
312
+ pip-installed on Python >= 3.12): then mu_distance is NaN and mu_scored 0.0 for every pair,
313
+ with one warning. Anything else propagates.
314
+ '''
315
+ try:
316
+ return {
317
+ 'mu_distance': obj1.get_mu_distance(obj2, normalize=True),
318
+ 'mu_scored': 1.0,
319
+ }
320
+ except (ValueError, ImportError) as exc:
321
+ reason = str(exc)
322
+ key = 'phylonetwork missing' if isinstance(exc, ImportError) else reason.split('.')[0]
323
+ if key not in _MU_REPORTED:
324
+ _MU_REPORTED.add(key)
325
+ warnings.warn(f'mu-distance not computed for at least one pair: {reason}',
326
+ RuntimeWarning, stacklevel=2)
327
+ return {
328
+ 'mu_distance': float('nan'),
329
+ 'mu_scored': 0.0,
330
+ }
331
+
332
+
333
+ def pairwise_compare(obj1, obj2, df=None, partial_match=False, edit_distance=True):
334
+ '''
335
+ Compare two ReticulateTree objects (or their cached rows in df).
336
+ If df is provided, obj1/obj2 are treated as row labels (names).
337
+
338
+ edit_distance=True (default, as in the original version) includes the
339
+ graph edit distance of the folded networks, exact (ReticulateTree.
340
+ get_edit_distance). It is NP-hard and can run for very long on large
341
+ networks: pass edit_distance=False to skip it (the benchmark scripts
342
+ disabled it), or compute it separately with a timeout.
343
+
344
+ If partial_match=True, Jaccard metrics (ret_leaf_jaccard, ret_sisters_jaccard)
345
+ normalize by matched pairs only, with no penalty for unmatched reticulations.
346
+ This is used for methods that can only infer a limited number of reticulations.
347
+ '''
348
+ if df is not None:
349
+ row1, row2 = df.loc[obj1], df.loc[obj2]
350
+ precomputed = run_hungarian_on_groups(row1['reticulation_leaves'].values(),
351
+ row2['reticulation_leaves'].values())
352
+
353
+ # Get reticulation count comparison (returns dict with 'signed' and 'abs')
354
+ num_rets_comparison = compare_num_rets(row1['reticulation_count'], row2['reticulation_count'])
355
+
356
+ return {
357
+ **({'edit_distance': row1['object'] - row2['object']} if edit_distance else {}),
358
+ # Superseded by mu_distance below. The mu-representation is a metric on
359
+ # semi-binary stack-free orchard networks, is exact rather than an
360
+ # approximation, and cannot depend on Newick child order. Kept here,
361
+ # and in ReticulateTree, so it can be switched back on for comparison.
362
+ # 'edit_distance_multree': row1['object'].get_edit_distance_multree(row2['object']), # on MUL-trees
363
+ 'num_rets_diff': num_rets_comparison['abs'], # Absolute difference (backward compatible)
364
+ 'num_rets_bias': num_rets_comparison['signed'], # NEW: Signed difference (bias)
365
+ 'ploidy_diff': compare_ploidy_diff(row1['leaf_counts'], row2['leaf_counts']),
366
+ 'polyploid_species_jaccard': compare_polyploid_species(row1['leaf_counts'], row2['leaf_counts']),
367
+ 'ret_leaf_jaccard': match_and_compare(row1['reticulation_leaves'], row2['reticulation_leaves'],
368
+ precomputed_match = precomputed, partial_match=partial_match),
369
+ 'ret_sisters_jaccard': match_and_compare(row1['reticulation_leaves'], row2['reticulation_leaves'],
370
+ row1['reticulation_sisters'], row2['reticulation_sisters'], precomputed,
371
+ partial_match=partial_match),
372
+ # *_matched normalise over matched pairs only, so a reticulation the
373
+ # method never found costs nothing. They answer "were the ones it found
374
+ # right", where the penalised columns answer "did it find them". These
375
+ # use partial_match=True for every method, so unlike the columns above
376
+ # they mean the same thing in every row and compare across methods.
377
+ 'ret_leaf_jaccard_matched': match_and_compare(row1['reticulation_leaves'], row2['reticulation_leaves'],
378
+ precomputed_match=precomputed, partial_match=True),
379
+ 'ret_sisters_jaccard_matched': match_and_compare(row1['reticulation_leaves'], row2['reticulation_leaves'],
380
+ row1['reticulation_sisters'], row2['reticulation_sisters'], precomputed,
381
+ partial_match=True),
382
+ **compare_mu(row1['object'], row2['object']),
383
+ }
384
+ # object-based comparison
385
+ precomputed = run_hungarian_on_groups(obj1.get_reticulation_leaves().values(), obj2.get_reticulation_leaves().values())
386
+
387
+ # Get reticulation count comparison (returns dict with 'signed' and 'abs')
388
+ num_rets_comparison = compare_num_rets(obj1.get_reticulation_count(), obj2.get_reticulation_count())
389
+
390
+ return {
391
+ **({'edit_distance': obj1 - obj2} if edit_distance else {}),
392
+ # (edit_distance: NP-hard, can hang on large trees; see edit_distance above)
393
+ # Superseded by mu_distance below. The mu-representation is a metric on
394
+ # semi-binary stack-free orchard networks, is exact rather than an
395
+ # approximation, and cannot depend on Newick child order. Kept here,
396
+ # and in ReticulateTree, so it can be switched back on for comparison.
397
+ # 'edit_distance_multree': obj1.get_edit_distance_multree(obj2), # edit distance on MUL-trees
398
+ 'num_rets_diff': num_rets_comparison['abs'], # Absolute difference (backward compatible)
399
+ 'num_rets_bias': num_rets_comparison['signed'], # NEW: Signed difference (bias)
400
+ 'ploidy_diff': compare_ploidy_diff(obj1.get_leaf_counts(), obj2.get_leaf_counts()),
401
+ 'polyploid_species_jaccard': compare_polyploid_species(obj1.get_leaf_counts(), obj2.get_leaf_counts()),
402
+ 'ret_leaf_jaccard': match_and_compare(obj1.get_reticulation_leaves(), obj2.get_reticulation_leaves(),
403
+ precomputed_match = precomputed, partial_match=partial_match),
404
+ 'ret_sisters_jaccard': match_and_compare(obj1.get_reticulation_leaves(), obj2.get_reticulation_leaves(),
405
+ obj1.get_reticulation_sisters(), obj2.get_reticulation_sisters(), precomputed,
406
+ partial_match=partial_match),
407
+ # *_matched normalise over matched pairs only, so a reticulation the
408
+ # method never found costs nothing. They answer "were the ones it found
409
+ # right", where the penalised columns answer "did it find them". These
410
+ # use partial_match=True for every method, so unlike the columns above
411
+ # they mean the same thing in every row and compare across methods.
412
+ 'ret_leaf_jaccard_matched': match_and_compare(obj1.get_reticulation_leaves(), obj2.get_reticulation_leaves(),
413
+ precomputed_match=precomputed, partial_match=True),
414
+ 'ret_sisters_jaccard_matched': match_and_compare(obj1.get_reticulation_leaves(), obj2.get_reticulation_leaves(),
415
+ obj1.get_reticulation_sisters(), obj2.get_reticulation_sisters(), precomputed,
416
+ partial_match=True),
417
+ **compare_mu(obj1, obj2),
418
+ }
419
+
420
+ def are_identical(obj1, obj2):
421
+ '''
422
+ Check if two ReticulateTree objects are identical by comparing the measurements.
423
+ '''
424
+ # Compare all measurements
425
+ comp = pairwise_compare(obj1, obj2)
426
+ print(f'Comparison vector: {comp.values()}')
427
+ # Edit distancd is bugged probably due to internal nodes being unmatched...
428
+ # num_rets_diff now returns absolute difference, num_rets_bias returns signed difference
429
+ return (#comp['edit_distance'] == 0 and
430
+ comp['num_rets_diff'] == 0 and
431
+ comp['num_rets_bias'] == 0 and
432
+ comp['ploidy_diff']['dist'] == 0.0 and
433
+ comp['ret_leaf_jaccard']['dist'] == 0.0 and
434
+ comp['ret_sisters_jaccard']['dist'] == 0.0)
435
+
436
+ def pairwise_comparison(df, debug=False):
437
+ ''' Create pairwise comparison matrix for each measurement. '''
438
+ names = df.index
439
+ n = len(names)
440
+
441
+ metrics = {
442
+ 'edit_distance': np.zeros((n, n)),
443
+ 'num_rets_diff': np.zeros((n, n)),
444
+ 'ploidy_diff': np.zeros((n, n)),
445
+ 'ret_leaf_jaccard': np.zeros((n, n)),
446
+ 'ret_sisters_jaccard': np.zeros((n, n)),
447
+ }
448
+
449
+ print(f'Comparing {n} trees...')
450
+
451
+ for i in range(n):
452
+ for j in range(i + 1):
453
+ name1, name2 = names[i], names[j]
454
+ if debug:
455
+ print(f'Comparing {name1} vs {name2}')
456
+ results = pairwise_compare(name1, name2, df)
457
+ for k in metrics:
458
+ res = results[k]
459
+ if debug:
460
+ print(f' {k}: {res}')
461
+ if isinstance(res, dict):
462
+ res = res['dist'] # take only the score, not the dict
463
+ metrics[k][i, j] = res
464
+ # Symmetric fill
465
+ if i != j:
466
+ metrics[k][j, i] = res
467
+
468
+ dfs = {}
469
+ for k, mat in metrics.items():
470
+ dfs[k] = pd.DataFrame(mat, index=names, columns=names)
471
+
472
+ return dfs
473
+
474
+ def one_stop_compare(phylo_trees: dict, printout: bool = True, visualize: bool = False):
475
+
476
+ results = []
477
+ logs = []
478
+
479
+ for name, value in phylo_trees.items():
480
+ try:
481
+ tree = ReticulateTree(value)
482
+ measurements = tree.measure(printout=printout)
483
+ results.append({'name': name, 'object': tree, **measurements})
484
+ if visualize:
485
+ tree.visualize()
486
+ if printout:
487
+ logs.append(f'Finished {name}\n')
488
+ except Exception as e:
489
+ logs.append(f'Error processing {name}: {e}')
490
+
491
+ try:
492
+ df = pd.DataFrame(results).set_index('name')
493
+ comparison = pairwise_comparison(df, debug=printout)
494
+ except Exception as e:
495
+ logs.append(f'Error processing DataFrame: {e}')
496
+ return {'data': None, 'comparisons': None, 'logs': logs}
497
+
498
+ return {'data': df, 'comparisons': comparison, 'logs': logs}
499
+
500
+ def plot_comparison_heatmaps(comparison_matrices, phylo_df, save_path=None):
501
+ # Plot each as heatmap
502
+ for metric, matrix in comparison_matrices.items():
503
+ plt.figure(figsize=(8, 6))
504
+ sns.heatmap(matrix, annot=True, fmt=".2f", cmap='coolwarm', square=True,
505
+ xticklabels=phylo_df.index, yticklabels=phylo_df.index)
506
+ plt.title(f'{metric.upper()} Heatmap')
507
+ plt.tight_layout()
508
+ if save_path:
509
+ plt.savefig(save_path / f'{metric}_heatmap.png', dpi=600)
510
+ plt.show()
511
+
512
+ if __name__ == '__main__':
513
+
514
+ main_path = Path(__file__).parent