-
-
Notifications
You must be signed in to change notification settings - Fork 216
/
ete_diff.py
1222 lines (958 loc) · 49.7 KB
/
ete_diff.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import json
import numpy as np
import numpy.linalg as LA
from scipy.cluster import hierarchy as hcluster
import random
import itertools
import multiprocessing as mp
from ..coretype.tree import Tree
from ..utils import print_table, color
from lap import lapjv
import textwrap
import argparse
import logging
log = logging.Logger("main")
DESC = ""
### Distances ###
def SINGLECELL(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the precomputed distances obtained from the formula:
1 - Pearson correlation between reference node and target node
The final distance is calculated as the percentile 50 of all leave distances between the compared nodes.
Parameters:
a: (reference node as tree object, Pearson correlation from both trees as dictionary), as tuple
b: (target node as tree object, Pearson correlation from both trees as dictionary), as tuple
support: flag indicating the use of support values, as boolean (this argument has no effect in this function)
attr1: observed attribute from reference node, as string (this argument has no effect in this function)
attr2: observed attribute from target node, as string (this argument has no effect in this function)
Returns:
float: distance value between the two nodes
'''
dist = []
# Extract and parse pearson dict from first element (could be anyother)
for p in a[1]:
pearson = json.loads(p)
break
len_axb = 0
for leaf_a in a[0].leaves():
for leaf_b in b[0].leaves():
len_axb += 1
dist.append(pearson[leaf_a.name][leaf_b.name])
dist = np.percentile(dist,50)/(1 - 1 / (len([i for i in b[0].leaves()])))
return dist
def EUCL_DIST(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the formula:
1 - (Shared attributes / maximum length of the two nodes)
Parameters:
a: (reference node as tree object, observed attributes as set), as tuple
b: (target node as tree object, observed attributes as set), as tuple
support: flag indicating the use of support values, as boolean (this argument has no effect in this function)
attr1: observed attribute from reference node, as string (this argument has no effect in this function)
attr2: observed attribute from target node, as string (this argument has no effect in this function)
Returns:
float: distance value between the two nodes
'''
return 1 - (float(len(a[1] & b[1])) / max(len(b[1]), len(a[1])))
def EUCL_DIST_B(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the formula:
1 - (Shared attributes / maximum length of the two nodes) + absoulte value of the distance difference between shared leaves from both nodes to their parents
Parameters:
a: (reference node as tree object, observed attributes as set), as tuple
b: (target node as tree object, observed attributes as set), as tuple
support: flag indicating the use of support values, as boolean (this argument has no effect in this function)
attr1: observed attribute from reference node, as string
attr2: observed attribute from target node, as string
Returns:
float: distance value between the two nodes
'''
dist_a = sum([descendant.dist for descendant in a[0].leaves() if descendant.props[attr1] in(a[1] - b[1])]) / len([i for i in a[0].leaves()])
dist_b = sum([descendant.dist for descendant in b[0].leaves() if descendant.props[attr2] in(b[1] - a[1])]) / len([i for i in b[0].leaves()])
return 1 - ((float(len(a[1] & b[1])) / max(len(a[1]), len(b[1]))) + abs(dist_a - dist_b)) / 2
def EUCL_DIST_B_ALL(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the formula:
1 - (Shared attributes / maximum length of the two nodes) + absoulte value of the distance difference between all leaves from both nodes to their parents
Parameters:
a: (reference node as tree object, observed attributes as set), as tuple
b: (target node as tree object, observed attributes as set), as tuple
support: flag indicating the use of support values, as boolean (this argument has no effect in this function)
attr1: observed attribute from reference node, as string (this argument has no effect in this function)
attr2: observed attribute from target node, as string (this argument has no effect in this function)
Returns:
float: distance value between the two nodes
'''
dist_a = sum([descendant.dist for descendant in a[0].leaves()]) / len([i for i in a[0].leaves()])
dist_b = sum([descendant.dist for descendant in b[0].leaves()]) / len([i for i in b[0].leaves()])
return 1 - ((float(len(a[1] & b[1])) / max(len(a[1]), len(b[1]))) + abs(dist_a - dist_b)) / 2
def EUCL_DIST_B_FULL(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the formula:
1 - (Shared attributes / maximum length of the two nodes) + absoulte value of the distance difference between shared leaves from both nodes to their parents
Branch distances are calculated as the entire path leave to root
Parameters:
a: (reference node as tree object, observed attributes as set), as tuple
b: (target node as tree object, observed attributes as set) as tuple
support: flag indicating the use of support values, as boolean
attr1: observed attribute from reference tree, as string
attr2: observed attribute from target tree, as string
Returns:
float: distance value between the two nodes
'''
def _get_leaves_paths(t,attr,support):
leaves = list(t.leaves())
leave_branches = set()
for n in leaves:
if n.is_root:
continue
movingnode = n
length = 0
nodes = 0
while not movingnode.is_root:
nodes += 1
if support:
length += movingnode.dist * movingnode.support
else:
length += movingnode.dist
movingnode = movingnode.up
leave_branches.add((n.props[attr],length/nodes))
return leave_branches
dist_a = sum([descendant[1] for descendant in _get_leaves_paths(a[0],attr1,support) if descendant[0] in(a[1] - b[1])]) / len([i for i in a[0].leaves()])
dist_b = sum([descendant[1] for descendant in _get_leaves_paths(b[0],attr2,support) if descendant[0] in(b[1] - a[1])]) / len([i for i in b[0].leaves()])
return 1 - ((float(len(a[1] & b[1])) / max(len(a[1]), len(b[1]))) + abs(dist_a - dist_b)) / 2
def RF_DIST(a,b,support,attr1,attr2):
'''
Calculates the distance between two nodes using the formula:
Robinson-Foulds distance / Maximum possible Robinson-Foulds distance
Parameters:
a: (reference node as tree object, observed attributes as set), as tuple
b: (target node as tree object, observed attributes as set), as tuple
support: flag indicating the use of support values, as boolean (this argument has no effect in this function)
attr1: observed attribute from reference tree, as string (this argument has no effect in this function)
attr2: observed attribute from target tree as, string (this argument has no effect in this function)
Returns:
float: distance value between the two nodes
'''
if len(a[1] & b[1]) < 1:
return 1.0
(a, b) = (b, a) if len(b[1]) > len(a[1]) else (a,b)
rf, rfmax, names, side1, side2, d1, d2 = a[0].robinson_foulds(b[0])
return (rf/rfmax if rfmax else 0.0)
### Functions ###
def load_matrix(file,separator):
'''
Digests files containing a expression matrix and translates it to a dictionary
Parameters:
file: expression matrix filename, as string
separator: Column separator, as string
Returns:
dictionary with key values:
idx: values are row indexes, as integers
headers: values are column names, as strings
dict: values are dictionary of columns as key values and their expression values, as lists
'''
idx = []
with open(file, "r") as f:
headers = f.readline().rstrip().split(separator)[1:] # exclude empty space at the begining
col2v = { h :[] for h in headers}
for line in f:
elements = line.strip().split(separator)
idx.append(elements.pop(0))
for i,h in enumerate(headers):
col2v[h].append(float(elements[i]))
treedict = {}
treedict['idx'] = idx
treedict['headers'] = headers
treedict['dict'] = col2v
return treedict
def dict2tree(treedict,jobs=1,parallel=None):
'''
Generates a tree object from a dictionary using UPGMA algorithm and Pearson correlations between observations
Parameters:
treedict: dictionary with key values:
idx: values are row indexes, as integers
headers: values are column names, as strings
dict: values are dictionary of columns as key values and their expression values, as lists
jobs: maximum number of jobs to use when parallel argument is provided, as integer
parallel: parallelization method, as string. Options are:
async for asyncronous parallelization
sync for asyncronous parallelization
Returns:
tree object
'''
log = logging.getLogger()
matrix = np.zeros((len(treedict['headers']), len(treedict['headers'])))
dm = {h : {} for h in treedict['headers']}
if parallel == 'sync':
pool = mp.Pool(jobs)
matrix = [[pool.apply(np.corrcoef,args=(treedict['dict'][col1],treedict['dict'][col2])) for col2 in treedict['headers']] for col1 in treedict['headers']]
pool.close()
if parallel == 'async':
pool = mp.Pool(jobs)
matrix = [[pool.apply_async(np.corrcoef,args=(treedict['dict'][col1],treedict['dict'][col2])) for col2 in treedict['headers']] for col1 in treedict['headers']]
pool.close()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] = matrix[i][j].get()[0][1]
else:
matrix = [[(np.corrcoef(treedict['dict'][col1],treedict['dict'][col2]))[0][1] for col2 in treedict['headers']] for col1 in treedict['headers']]
Z = hcluster.linkage(matrix, "average") #"single" for default, "average" for UPGMA
T = hcluster.to_tree(Z)
root = Tree()
root.dist = 0
root.name = "root"
item2node = {T.get_id(): [T, root]}
to_visit = [T]
while to_visit:
node = to_visit.pop()
cl_dist = node.dist /2.0
for ch_node in [node.left, node.right]:
if ch_node:
ch = Tree()
ch.dist = cl_dist
ch.name = str(ch_node.get_id())
item2node[node.get_id()][1].add_child(ch)
item2node[ch_node.get_id()] = [ch_node, ch]
to_visit.append(ch_node)
# This is your ETE tree structure
tree = root
for leaf in tree:
leaf.name = treedict['headers'][int(leaf.name)]
return tree
def tree_from_matrix(matrix,sep=",",dictionary=False,jobs=1,parallel=None):
'''
Wrapps a tree object recontruction using load_matrix and dict2tree functions
Parameters:
matrix: expression matrix filename, as string
sep: column separator, as string
dictionary: whether to return source dictionary used to generate the tree object, as boolean
jobs: maximum number of jobs to use when parallel argument is provided, as integer
parallel: parallelization method, as string. Options are:
async for asyncronous parallelization
sync for asyncronous parallelization
Returns:
tree object
'''
tree_dict = load_matrix(matrix,sep)
if dictionary == True:
return dict2tree(tree_dict,jobs,parallel), tree_dict
else:
return dict2tree(tree_dict,jobs,parallel)
def pearson_corr(rdict,tdict):
'''
Generates a dictionary of precomputed pearson correlations for all observations of two trees
Parameters:
rdict: dictionary with key values:
idx: values are row indexes as integers
headers: values are column names as strings
dict: values are dictionary of columns as key values and their expression values as lists
tdict: dictionary with key values:
idx: values are row indexes as integers
headers: Values are column names as strings
dict: values are dictionary of columns as key values and their expression values as lists
Returns:
Dictionary of pearson correlations formed by sub dictionaries.
Each value is accessed introducing the reference observation as first key and the target observation as second key
(e.g. dictionary['reference_observation']['target_observation'])
'''
# Select only common genes by gene name y both dictionaries
log = logging.getLogger()
log.info("Getting shared genes...")
rfilter = [i for i,value in enumerate(rdict['idx']) if value in tdict['idx']]
tfilter = [i for i,value in enumerate(tdict['idx']) if value in rdict['idx']]
log.info("Total Genes Shared = " + str(len(rfilter)))
rdict['dict'] = {header : [rdict['dict'][header][element] for element in rfilter] for header in rdict['headers']}
tdict['dict'] = {header : [tdict['dict'][header][element] for element in tfilter] for header in tdict['headers']}
leaves = np.concatenate((rdict['headers'],tdict['headers']))
pearson = {x: {} for x in leaves}
for a in rdict['headers']:
for b in tdict['headers']:
pearson[a][b] = pearson[b][a] = 1 - np.corrcoef(rdict['dict'][a],tdict['dict'][b])[0][1]
return pearson
def be_distance(t1,t2,support, attr1,attr2):
'''
Calculates a Branch-Extended Distance.
This distance is intended as an extension for the main distance used by ETE-diff to link similar nodes without altering the results
Parameters:
t1: reference node, as tree object
t2: target node, as tree object
support: whether to use support values to calculate the distance, as boolean
attr1: observed attribute for the reference node, as string
attr2: observed attribute for the target node, as string
Returns:
float distance value
'''
# Get total distance from leaf to root
def _get_leaves_paths(t,attr,support):
leaves = list(t.leaves())
leave_branches = set()
for n in leaves:
if n.is_root:
continue
movingnode = n
length = 0
while not movingnode.is_root:
if support:
length += movingnode.dist * movingnode.support
else:
length += movingnode.dist
movingnode = movingnode.up
leave_branches.add((n.props[attr],length))
return leave_branches
# Get difference of distances from unique leaves in tree 1 - unique leaves in tree 2
def _get_distances(leaf_distances1,leaf_distances2):
unique_leaves1 = leaf_distances1 - leaf_distances2
unique_leaves2 = leaf_distances2 - leaf_distances1
return abs(sum([leaf[1] for leaf in unique_leaves1]) - sum([leaf[1] for leaf in unique_leaves2]))
return _get_distances(_get_leaves_paths(t1,attr1,support),_get_leaves_paths(t2,attr2,support))
def cc_distance(t1,t2,support,attr1,attr2):
'''
Calculates a Cophenetic-Compared Distance.
This distance is intended as an extension for the main distance used by ETE-diff to link similar nodes without altering the results
Parameters:
t1: reference node, as tree object
t2: target node, as tree object
support: whether to use support values to calculate the distance, as boolean
attr1: observed attribute for the reference node, as string
attr2: observed attribute for the target node, as string
Returns:
float distance value
'''
def cophenetic_compared_matrix(t_source,t_compare,attr1,attr2,support):
leaves = list(t_source.leaves())
paths = {x.props[attr1]: set() for x in leaves}
# get the paths going up the tree
# we get all the nodes up to the last one and store them in a set
for n in leaves:
if n.is_root:
continue
movingnode = n
while not movingnode.is_root:
paths[n.props[attr1]].add(movingnode)
movingnode = movingnode.up
# We set the paths for leaves not in the source tree as empty to indicate they are non-existent
for i in (set(x.props[attr2] for x in t_compare.leaves()) - set(x.props[attr1] for x in t_source.leaves())):
paths[i] = set()
# now we want to get all pairs of nodes using itertools combinations. We need AB AC etc but don't need BA CA
leaf_distances = {x: {} for x in paths.keys()}
for (leaf1, leaf2) in itertools.combinations(paths.keys(), 2):
# figure out the unique nodes in the path
if len(paths[leaf1]) > 0 and len(paths[leaf2]) > 0:
uniquenodes = paths[leaf1] ^ paths[leaf2]
if support:
distance = sum(x.dist * x.support for x in uniquenodes)
else:
distance = sum(x.dist for x in uniquenodes)
else:
distance = 0
leaf_distances[leaf1][leaf2] = leaf_distances[leaf2][leaf1] = distance
allleaves = sorted(leaf_distances.keys()) # the leaves in order that we will return
output = [] # the two dimensional array that we will return
for i, n in enumerate(allleaves):
output.append([])
for m in allleaves:
if m == n:
output[i].append(0) # distance to ourself = 0
else:
output[i].append(leaf_distances[n][m])
return np.asarray(output)
ccm1 = cophenetic_compared_matrix(t1,t2,attr1,attr2,support)
ccm2 = cophenetic_compared_matrix(t2,t1,attr1,attr2,support)
return LA.norm(ccm1-ccm2)
def sepstring(items, sep=", "):
return sep.join(sorted(map(str, items)))
### Treediff ###
def treediff(t1, t2, attr1 = 'name', attr2 = 'name', dist_fn=EUCL_DIST, support=False, reduce_matrix=False,extended=None, jobs=1, parallel=None):
'''
Main function of ETE-diff module.
Compares two trees and returns a list of differences for each node from the reference tree
Parameters:
t1: reference tree, as tree object
t2: target tree, as tree object
attr1: observed attribute for the reference node, as string
attr2: observed attribute for the target node, as string
dist_fn: distance function that will be used to calculate the distances between nodes, as python function
support: whether to use support values for the different calculations, as boolean
reduce_matrix: whether to reduce the distances matrix removing columns and rows where observations equal to 0 (perfect matches) are found, as boolean
extended: whether to use an extension function, as python function
jobs: maximum number of parallel jobs to use if parallel argument is given, as integer
parallel: parallelization method, as string. Options are:
async for asyncronous parallelization
sync for asyncronous parallelization
Returns:
list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
'''
log = logging.getLogger()
log.info("Computing distance matrix...")
for index, n in enumerate(t1.traverse('preorder')):
n.add_prop('_nid', index)
for index, n in enumerate(t2.traverse('preorder')):
n.add_prop('_nid', index)
t1_cached_content = t1.get_cached_content(store_attr=attr1)
t1 = None
t2_cached_content = t2.get_cached_content(store_attr=attr2)
t2 = None
if dist_fn != SINGLECELL:
parts1 = [(k, v) for k, v in t1_cached_content.items()]
t1_cached_content = None
parts2 = [(k, v) for k, v in t2_cached_content.items()]
t2_cached_content = None
else:
parts1 = [(k, v) for k, v in t1_cached_content.items() if k.children]
t1_cached_content = None
parts2 = [(k, v) for k, v in t2_cached_content.items() if k.children]
t2_cached_content = None
parts1 = sorted(parts1, key = lambda x : len(x[1]))
parts2 = sorted(parts2, key = lambda x : len(x[1]))
if parallel == 'sync':
pool = mp.Pool(jobs)
gen = [[pool.apply(dist_fn,args=((n1,x),(n2,y),support,attr1,attr2)) for n2,y in parts2] for n1,x in parts1]
pool.close()
elif parallel == 'async':
pool = mp.Pool(jobs)
gen = [[pool.apply_async(dist_fn,args=((n1,x),(n2,y),support,attr1,attr2)) for n2,y in parts2] for n1,x in parts1]
pool.close()
for i, subgen in enumerate(gen):
for j, element in enumerate(subgen):
gen[i][j] = element.get()
else:
gen = ((dist_fn((n1,x),(n2,y),support,attr1,attr2) for n2,y in parts2) for n1,x in parts1)
matrix = np.empty([len(parts1),len(parts2)],dtype=np.float32)
for i, subgen in enumerate(gen):
for j, element in enumerate(subgen):
matrix[i][j] = element
# Reduce matrix to avoid useless comparisons
if reduce_matrix:
log.info( "Reducing distance matrix...")
cols_to_include = set(range(len(matrix[0])))
rows_to_include = []
for i, row in enumerate(matrix):
try:
cols_to_include.remove(np.where(row == 0.0)[0][0])
except IndexError:
rows_to_include.append(i)
except KeyError:
pass
cols_to_include = sorted(cols_to_include)
parts1 = [parts1[row] for row in rows_to_include]
parts2 = [parts2[col] for col in cols_to_include]
new_matrix = np.empty([len(rows_to_include),len(cols_to_include)],dtype=np.float32)
for i, row in enumerate(rows_to_include):
for j, col in enumerate(cols_to_include):
new_matrix[i][j] = matrix[row][col]
if len(new_matrix) < 1:
return new_matrix
log.info("Distance matrix reduced from %dx%d to %dx%d" %\
(len(matrix), len(matrix[0]), len(new_matrix), len(new_matrix[0])))
matrix = new_matrix
log.info("Comparing trees...")
difftable = []
b_dist = -1
if dist_fn != SINGLECELL:
_, cols , _ = lapjv(matrix,extend_cost=True)
for r in range(len(matrix)):
c = cols[r]
if extended:
b_dist = extended(parts1[r][0], parts2[c][0],support,attr1,attr2)
else:
pass
dist, side1, side2, diff, n1, n2 = (matrix[r][c],
parts1[r][1], parts2[c][1],
parts1[r][1].symmetric_difference(parts2[c][1]),
parts1[r][0], parts2[c][0])
difftable.append([dist, b_dist, side1, side2, diff, n1, n2])
return difftable
# Show only best match
elif dist_fn == SINGLECELL:
for r in range(len(matrix)):
c = np.argmin(matrix[r])
if np.percentile(matrix,5) >= matrix[r][c]:
if extended:
b_dist = extended(parts1[r][0], parts2[c][0],attr1,attr2,support)
else:
pass
dist, side1, side2, diff, n1, n2 = (matrix[r][c],
[l.name for l in parts1[r][0].leaves()], [l.name for l in parts2[r][0].leaves()],
parts1[r][1].symmetric_difference(parts2[c][1]),
parts1[r][0], parts2[c][0])
difftable.append([dist, b_dist, side1, side2, diff, n1, n2])
return difftable
### REPORTS ###
def show_difftable_summary(*args, **kwargs):
print(get_difftable_summary(*args, **kwargs))
def get_difftable_summary(difftable, rf=-1, rf_max=-1, extended=False):
"""Return summary from the treediff and Robinson-Foulds distance of trees.
:param list difftable: Each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
:param float rf: Robinson-Foulds distance for reference and target trees.
:param float rf_max: max Robinson-Foulds distance for reference and target.
:param bool extended: whether to show extended distance in final report.
"""
total_dist = 0
total_bdist = 0
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
total_dist += dist
total_bdist += b_dist
if extended:
return '\n'.join([
'\t'.join(['Distance', 'branchDist', 'Mismatches', 'RF', 'maxRF']),
'%0.6f\t%0.6f\t%10d\t%d\t%d' % (total_dist, total_bdist, len(difftable), rf, rf_max)])
else:
return '\n'.join([
'\t'.join(['Distance', 'Mismatches', 'RF', 'maxRF']) +
'%0.6f\t%10d\t%d\t%d' % (total_dist, len(difftable), rf, rf_max)])
# TODO: Fix the other show_difftable*() functions. As they are, they lie on
# what they do, print instead of returning a string are hard to read.
def show_difftable(difftable, extended=False):
'''
Generates a table report from the result of treediff function
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
extended: whether to show extended distance in final report, as boolean
Returns:
Table report of treediff function, as string
'''
showtable = []
if extended:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
showtable.append([dist, b_dist, len(side1), len(side2), len(diff), sepstring(side1), sepstring(side2), sepstring(diff)])
print_table(showtable, header=["Dist", "branchDist", "Size1", "Size2", "ndiffs", "refTree", "targetTree", "Diff"],
max_col_width=80, wrap_style="wrap", row_line=True)
else:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
showtable.append([dist, len(side1), len(side2), len(diff), sepstring(side1), sepstring(side2), sepstring(diff)])
print_table(showtable, header=["Dist", "Size1", "Size2", "ndiffs", "refTree", "targetTree", "Diff"],
max_col_width=80, wrap_style="wrap", row_line=True)
return showtable
def show_difftable_tab(difftable, extended=None):
'''
Generates a tabulated table report from the result of treediff function
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
extended: whether to show extended distance in final report, as boolean
Returns:
Tabulated table report of treediff function, as string
'''
showtable = []
if extended:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
showtable.append([dist, b_dist, len(side1), len(side2), len(diff),
sepstring(side1, "|"), sepstring(side2, "|"),
sepstring(diff, "|")])
print('#' + '\t'.join(["Dist", "branchDist", "Size1", "Size2", "ndiffs", "refTree", "targetTree", "Diff"]))
else:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
showtable.append([dist, len(side1), len(side2), len(diff),
sepstring(side1, "|"), sepstring(side2, "|"),
sepstring(diff, "|")])
print('#' + '\t'.join(["Dist", "Size1", "Size2", "ndiffs", "refTree", "targetTree", "Diff"]))
print('\n'.join(['\t'.join(map(str, items)) for items in showtable]))
def show_difftable_topo(difftable, attr1, attr2, usecolor=False, extended=None):
'''
Generates a topology table report from the result of treediff function
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
attr1: observed attribute from the reference tree, as string
attr2: observed attribute from the target tree, as string
extended: whether to show extended distance in final report, as boolean
Returns:
Topology table report of treediff function, as string
'''
log = logging.getLogger()
if not difftable:
return
showtable = []
maxcolwidth = 80
total_dist = 0
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True):
total_dist += dist
n1 = Tree(n1.write(props=[attr1]))
n2 = Tree(n2.write(props=[attr2]))
n1.ladderize()
n2.ladderize()
for leaf in n1.leaves():
leaf.name = leaf.props[attr1]
if leaf.name in diff:
leaf.name += " ***"
if usecolor:
leaf.name = color(leaf.name, "red")
for leaf in n2.leaves():
leaf.name = leaf.props[attr2]
if leaf.name in diff:
leaf.name += " ***"
if usecolor:
leaf.name = color(leaf.name, "red")
topo1 = n1.get_ascii(show_internal=False, compact=False)
topo2 = n2.get_ascii(show_internal=False, compact=False)
# This truncates too large topology strings pretending to be
# scrolled to the right margin
topo1_lines = topo1.split("\n")
topowidth1 = max([len(l) for l in topo1_lines])
if topowidth1 > maxcolwidth:
start = topowidth1 - maxcolwidth
topo1 = '\n'.join([line[start+1:] for line in topo1_lines])
topo2_lines = topo2.split("\n")
topowidth2 = max([len(l) for l in topo2_lines])
if topowidth2 > maxcolwidth:
start = topowidth2 - maxcolwidth
topo2 = '\n'.join([line[start+1:] for line in topo2_lines])
if extended:
showtable.append([dist, b_dist, "%d/%d (%d)" %(len(side1), len(side2),len(diff)), topo1, topo2])
else:
showtable.append([dist, "%d/%d (%d)" %(len(side1), len(side2),len(diff)), topo1, topo2])
if extended:
print_table(showtable, header=["Dist", "branchDist", "#Diffs", "refTree", "targetTree"],
max_col_width=maxcolwidth, wrap_style="wrap", row_line=True)
else:
print_table(showtable, header=["Dist", "#Diffs", "refTree", "targetTree"],
max_col_width=maxcolwidth, wrap_style="wrap", row_line=True)
log.info("Total euclidean distance:\t%0.4f\tMismatching nodes:\t%d" %(total_dist, len(difftable)))
### SCA REPORTS ###
def show_difftable_summary_SCA(difftable, rf=-1, rf_max=-1, extended=None):
'''
Generates a summary report variant from the result of treediff function and the Robinson-Foulds distance between two trees for the Single Cell Analysis
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
rf: Robinson-Foulds distance for reference and target tree, as float
rf_max: maximum Robinson-Foulds distance for reference and target tree, as float
extended: whether to show extended distance in final report, as boolean
Returns:
Summary report of treediff function and robinson_foulds method, as string
'''
total_dist = 0
total_bdist = 0
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
total_dist += dist
total_bdist += b_dist
if extended:
print("\n"+"\t".join(["Dist", "branchDist", "Mismatches", "RF", "maxRF"]))
print("%0.6f\t%0.6f\t%10d\t%d\t%d" %(total_dist,total_bdist, len(difftable), rf, rf_max))
else:
print("\n"+"\t".join(["Dist", "Mismatches", "RF", "maxRF"]))
print("%0.6f\t%10d\t%d\t%d" %(total_dist, len(difftable), rf, rf_max))
def show_difftable_SCA(difftable, extended=False):
'''
Generates a table report from the result variant of treediff function for the Single Cell Analysis
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
extended: whether to show extended distance in final report, as boolean
Returns:
Table report of treediff function, as string
'''
showtable = []
if extended:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
showtable.append([dist, b_dist, len(side1), len(side2), sepstring(side1), sepstring(side2)])
print_table(showtable, header=["Dist", "branchDist", "Size1", "Size2","refTree", "targetTree"],
max_col_width=80, wrap_style="wrap", row_line=True)
else:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
showtable.append([dist, len(side1), len(side2), sepstring(side1), sepstring(side2)])
print_table(showtable, header=["Dist", "Size1", "Size2", "refTree", "targetTree"],
max_col_width=80, wrap_style="wrap", row_line=True)
def show_difftable_tab_SCA(difftable, extended=None):
'''
Generates a tabulated table report variant from the result of treediff function for the Single Cell Analysis
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
extended: whether to show extended distance in final report, as boolean
Returns:
Table report of treediff function, as string
'''
showtable = []
if extended:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
showtable.append([dist, b_dist, len(side1), len(side2), sepstring(side1, "|"), sepstring(side2, "|")])
print('#' + '\t'.join(["Dist", "branchDist", "Size1", "Size2", "refTree", "targetTree"]))
else:
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
showtable.append([dist, len(side1), len(side2),
sepstring(side1, "|"), sepstring(side2, "|")])
print('#' + '\t'.join(["Dist", "Size1", "Size2", "refTree", "targetTree"]))
print('\n'.join(['\t'.join(map(str, items)) for items in showtable]))
def show_difftable_topo_SCA(difftable, attr1, attr2, usecolor=False, extended=None):
'''
Generates a topology table report from the result of treediff function for the Single Cell Analysis
Parameters:
difftable: list where each entry contains a list with:
distance, as float
extended distance, as float (-1 if not calculated)
observed attributes on reference node, as set
observed attributes on target node, as set
observed attributes disfferent between both nodes, as set
reference node, as tree object
target node, as tree object
attr1: observed attribute from the reference tree, as string
attr2: observed attribute from the target tree, as string
extended: whether to show extended distance in final report, as boolean
Returns:
Topology table report of treediff function, as string
'''
if not difftable:
return
showtable = []
maxcolwidth = 80
total_dist = 0
for dist, b_dist, side1, side2, diff, n1, n2 in sorted(difftable, reverse=True,key = lambda x : x[0]):
log = logging.getLogger()
total_dist += dist
n1 = Tree(n1.write())
n2 = Tree(n2.write())
n1.ladderize()
n2.ladderize()
topo1 = n1.get_ascii(show_internal=False, compact=False)
topo2 = n2.get_ascii(show_internal=False, compact=False)
# This truncates too large topology strings pretending to be
# scrolled to the right margin
topo1_lines = topo1.split("\n")
topowidth1 = max([len(l) for l in topo1_lines])
if topowidth1 > maxcolwidth:
start = topowidth1 - maxcolwidth
topo1 = '\n'.join([line[start+1:] for line in topo1_lines])
topo2_lines = topo2.split("\n")
topowidth2 = max([len(l) for l in topo2_lines])
if topowidth2 > maxcolwidth:
start = topowidth2 - maxcolwidth
topo2 = '\n'.join([line[start+1:] for line in topo2_lines])
if extended:
showtable.append([dist, b_dist, "%d/%d (%d)" %(len(side1), len(side2),len(diff)), topo1, topo2])
else:
showtable.append([dist, "%d/%d (%d)" %(len(side1), len(side2),len(diff)), topo1, topo2])
if extended:
print_table(showtable, header=["Dist", "branchDist", "#Diffs", "refTree", "targetTree"],
max_col_width=maxcolwidth, wrap_style="wrap", row_line=True)
else:
print_table(showtable, header=["Dist", "#Diffs", "refTree", "targetTree"],
max_col_width=maxcolwidth, wrap_style="wrap", row_line=True)
log.info("Total distance:\t%0.4f\tMismatching nodes:\t%d" %(total_dist, len(difftable)))