-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpipeline.py
1766 lines (1524 loc) · 71.2 KB
/
pipeline.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 asyncio
import itertools
import math
import os
import shutil
import sys
import traceback
from collections import namedtuple
import os.path as osp
from glob import glob
from typing import Union, List, Optional, Tuple, Dict, Iterable
import scipy.stats
from amas import AMAS
from ete3 import PhyloTree
import networkx as nx
import numpy as np
from numpy import array, nan
import gseapy as gp
from scipy.stats import spearmanr
import xlsxwriter
from fasta import read_records, write_records, Record, phylogenetic_sort
from utilities import async_call, safe_phylo_read, safe_delete, _self_path, safe_mkdir, chunks, make_bold_formatting, \
make_p_formatting, make_rho_formatting
ErcResult = namedtuple('ErcResult', ['file1', 'file2', 'rho', 'p', 'raw_rates'])
ErcDataSource = namedtuple('ErcDataSource', ['tree_dir', 'ercs', 'sep', 'is_oneway'])
ErcDataSourceEntry = namedtuple('ErcDataSourceEntry', ['path1', 'path2', 'rho', 'p'])
SegmentedERC = namedtuple("SegmentedERC", ["result", 'is_file1_segmented', 'is_file2_segmented',
'file1_base', 'file2_base', 'file1_range', 'file2_range'])
datasources = []
GAP_CHARS = {'?', '-', '*'}
_10mya_cutoff = """ORNITHORHYNCHUS_ANATINUS
MONODELPHIS_DOMESTICA
PHASCOLARCTOS_CINEREUS
SARCOPHILUS_HARRISII
DASYPUS_NOVEMCINCTUS
LOXODONTA_AFRICANA
TRICHECHUS_MANATUS
ORYCTEROPUS_AFER
ELEPHANTULUS_EDWARDII
CHRYSOCHLORIS_ASIATICA
ECHINOPS_TELFAIRI
OCHOTONA_PRINCEPS
ORYCTOLAGUS_CUNICULUS
FUKOMYS_DAMARENSIS
HETEROCEPHALUS_GLABER
CAVIA_PORCELLUS
CHINCHILLA_LANIGERA
OCTODON_DEGUS
MARMOTA_MARMOTA
CASTOR_CANADENSIS
DIPODOMYS_ORDII
JACULUS_JACULUS
NANNOSPALAX_GALILI
PEROMYSCUS_MANICULATUS
MICROTUS_OCHROGASTER
CRICETULUS_GRISEUS
MESOCRICETUS_AURATUS
MERIONES_UNGUICULATUS
RATTUS_NORVEGICUS
MUS_MUSCULUS
GALEOPTERUS_VARIEGATUS
OTOLEMUR_GARNETTII
MICROCEBUS_MURINUS
PROPITHECUS_COQUERELI
CARLITO_SYRICHTA
AOTUS_NANCYMAAE
CALLITHRIX_JACCHUS
SAIMIRI_BOLIVIENSIS
NOMASCUS_LEUCOGENYS
PONGO_ABELII
HOMO_SAPIENS
GORILLA_GORILLA
RHINOPITHECUS_BIETI
RHINOLOPHUS_ROXELLANA
COLOBUS_ANGOLENSIS
PILIOCOLOBUS_TEPHROSCELES
CHLOROCEBUS_SABAEUS
PAPIO_ANUBIS
MANDRILLUS_LEUCOPHAEUS
MACACA_MULATTA
CONDYLURA_CRISTATA
ERINACEUS_EUROPAEUS
SOREX_ARANEUS
HIPPOSIDEROS_ARMIGER
RHINOLOPHUS_SINICUS
ROUSETTUS_AEGYPTIACUS
PTEROPUS_ALECTO
PTEROPUS_VAMPYRUS
MINIOPTERUS_NATALENSIS
EPTESICUS_FUSCUS
MYOTIS_DAVIDII
MYOTIS_BRANDTII
MYOTIS_LUCIFUGUS
CERATOTHERIUM_SIMUM
EQUUS_CABALLUS
MANIS_JAVANICA
ACINONYX_JUBATUS
FELIS_CATUS
CANIS_LUPUS
AILUROPODA_MELANOLEUCA
URSUS_MARITIMUS
ENHYDRA_LUTRIS
MUSTELA_PUTORIUS
LEPTONYCHOTES_WEDDELLII
ODOBENUS_ROSMARUS
VICUGNA_PACOS
CAMELUS_FERUS
SUS_SCROFA
BALAENOPTERA_ACUTOROSTRATA
PHYSETER_CATODON
LIPOTES_VEXILLIFER
DELPHINAPTERUS_LEUCAS
ORCINUS_ORCA
ODOCOILEUS_VIRGINIANUS
PANTHOLOPS_HODGSONII
CAPRA_HIRCUS
OVIS_ARIES
BUBALUS_BUBALIS
BOS_GRUNNIENS""".splitlines()
_20mya_cutoff = """ORNITHORHYNCHUS_ANATINUS
MONODELPHIS_DOMESTICA
PHASCOLARCTOS_CINEREUS
SARCOPHILUS_HARRISII
DASYPUS_NOVEMCINCTUS
LOXODONTA_AFRICANA
TRICHECHUS_MANATUS
ORYCTEROPUS_AFER
ELEPHANTULUS_EDWARDII
CHRYSOCHLORIS_ASIATICA
ECHINOPS_TELFAIRI
OCHOTONA_PRINCEPS
ORYCTOLAGUS_CUNICULUS
FUKOMYS_DAMARENSIS
HETEROCEPHALUS_GLABER
CAVIA_PORCELLUS
CHINCHILLA_LANIGERA
OCTODON_DEGUS
MARMOTA_MARMOTA
CASTOR_CANADENSIS
DIPODOMYS_ORDII
JACULUS_JACULUS
NANNOSPALAX_GALILI
PEROMYSCUS_MANICULATUS
MICROTUS_OCHROGASTER
CRICETULUS_GRISEUS
MESOCRICETUS_AURATUS
MERIONES_UNGUICULATUS
RATTUS_NORVEGICUS
MUS_MUSCULUS
GALEOPTERUS_VARIEGATUS
OTOLEMUR_GARNETTII
MICROCEBUS_MURINUS
PROPITHECUS_COQUERELI
CARLITO_SYRICHTA
AOTUS_NANCYMAAE
CALLITHRIX_JACCHUS
SAIMIRI_BOLIVIENSIS
NOMASCUS_LEUCOGENYS
HOMO_SAPIENS
RHINOPITHECUS_BIETI
MACACA_MULATTA
CONDYLURA_CRISTATA
ERINACEUS_EUROPAEUS
SOREX_ARANEUS
HIPPOSIDEROS_ARMIGER
RHINOLOPHUS_SINICUS
ROUSETTUS_AEGYPTIACUS
PTEROPUS_VAMPYRUS
MINIOPTERUS_NATALENSIS
EPTESICUS_FUSCUS
MYOTIS_DAVIDII
MYOTIS_LUCIFUGUS
CERATOTHERIUM_SIMUM
EQUUS_CABALLUS
MANIS_JAVANICA
FELIS_CATUS
CANIS_LUPUS
AILUROPODA_MELANOLEUCA
URSUS_MARITIMUS
ENHYDRA_LUTRIS
MUSTELA_PUTORIUS
LEPTONYCHOTES_WEDDELLII
ODOBENUS_ROSMARUS
VICUGNA_PACOS
CAMELUS_FERUS
SUS_SCROFA
BALAENOPTERA_ACUTOROSTRATA
PHYSETER_CATODON
LIPOTES_VEXILLIFER
DELPHINAPTERUS_LEUCAS
ORCINUS_ORCA
ODOCOILEUS_VIRGINIANUS
PANTHOLOPS_HODGSONII
OVIS_ARIES
BOS_GRUNNIENS""".splitlines()
_30mya_cutoff = """ORNITHORHYNCHUS_ANATINUS
MONODELPHIS_DOMESTICA
PHASCOLARCTOS_CINEREUS
SARCOPHILUS_HARRISII
DASYPUS_NOVEMCINCTUS
LOXODONTA_AFRICANA
TRICHECHUS_MANATUS
ORYCTEROPUS_AFER
ELEPHANTULUS_EDWARDII
CHRYSOCHLORIS_ASIATICA
ECHINOPS_TELFAIRI
OCHOTONA_PRINCEPS
ORYCTOLAGUS_CUNICULUS
FUKOMYS_DAMARENSIS
HETEROCEPHALUS_GLABER
CAVIA_PORCELLUS
CHINCHILLA_LANIGERA
OCTODON_DEGUS
MARMOTA_MARMOTA
CASTOR_CANADENSIS
DIPODOMYS_ORDII
JACULUS_JACULUS
NANNOSPALAX_GALILI
PEROMYSCUS_MANICULATUS
MESOCRICETUS_AURATUS
MERIONES_UNGUICULATUS
MUS_MUSCULUS
GALEOPTERUS_VARIEGATUS
OTOLEMUR_GARNETTII
MICROCEBUS_MURINUS
PROPITHECUS_COQUERELI
CARLITO_SYRICHTA
CALLITHRIX_JACCHUS
HOMO_SAPIENS
MACACA_MULATTA
CONDYLURA_CRISTATA
ERINACEUS_EUROPAEUS
SOREX_ARANEUS
HIPPOSIDEROS_ARMIGER
RHINOLOPHUS_SINICUS
ROUSETTUS_AEGYPTIACUS
PTEROPUS_VAMPYRUS
MINIOPTERUS_NATALENSIS
EPTESICUS_FUSCUS
MYOTIS_LUCIFUGUS
CERATOTHERIUM_SIMUM
EQUUS_CABALLUS
MANIS_JAVANICA
FELIS_CATUS
CANIS_LUPUS
AILUROPODA_MELANOLEUCA
MUSTELA_PUTORIUS
ODOBENUS_ROSMARUS
CAMELUS_FERUS
SUS_SCROFA
BALAENOPTERA_ACUTOROSTRATA
PHYSETER_CATODON
ORCINUS_ORCA
ODOCOILEUS_VIRGINIANUS
BOS_GRUNNIENS""".splitlines()
# def read_gene_info_as_l2n(filename: str, as_symbols: bool = False) -> Dict[str, str]:
# """
# Reads a gene info list file to make a label -> name dict.
# :param filename: The file.
# :param as_symbols: Whether to return symbols or full names. If none, both are combined
# :return: The l2n dict.
# """
# l2n = {
# "209332at40674": "APOA1" if as_symbols else ("Apolipoprotein A-I (APOA1)" if as_symbols is None else "Apolipoprotein A-I"),
# "91651at40674": "CETP" if as_symbols else ("Cholesteryl ester transfer protein (CETP)" if as_symbols is None else "Cholesteryl ester transfer protein"),
# "209652at40674": "APOC1" if as_symbols else ("Apolipoprotein C-I (APOC1)" if as_symbols is None else "Apolipoprotein C-I"),
# "158878at40674": "VEGFA" if as_symbols else ("Vascular endothelial growth factor A (VEGFA)" if as_symbols is None else "Vascular endothelial growth factor A"),
# "coag9": "F9" if as_symbols else ("Coagulation Factor 9 (F9)" if as_symbols is None else "Coagulation Factor 9"),
# "coag10": "F10" if as_symbols else ("Coagulation Factor 10 (F10)" if as_symbols is None else "Coagulation Factor 10"),
# "68161at40674": "POLH" if as_symbols else ("DNA polymerase eta (POLH)" if as_symbols is None else "DNA polymerase eta"),
# "71251at40674": "SELE" if as_symbols else ("Selectin E (SELE)" if as_symbols is None else "Selectin E"),
# "147514at40674": "ALKBH4" if as_symbols else ("alkB homolog 4, lysine demethylase (ALKBH4)" if as_symbols is None else "alkB homolog 4, lysine demethylase"),
# "70809at40674": "MARCHF10" if as_symbols else ("Testis secretory sperm-binding protein Li 228n (MARCHF10)" if as_symbols is None else "Testis secretory sperm-binding protein Li 228n")
# } # FIXME: Update the master file to include these builtins
# with open(filename, 'r') as f:
# first = True
# for l in f:
# if first:
# first = False
# continue
# row = l.strip().split("\t")
# if len(row) == 0:
# continue
# offset = 1 if as_symbols else 0
# odb = row[0]
#
# if odb in l2n:
# continue
#
# human = row[3 + offset]
# mouse = row[5 + offset]
# chimp = row[7 + offset]
# bonobo = row[9 + offset]
# generic = row[11]
# entrez = row[12]
# uniprot = row[14]
#
# name = 'NOT FOUND'
#
# if human == 'NOT FOUND':
# if mouse == 'NOT FOUND':
# if chimp == 'NOT FOUND':
# if bonobo == 'NOT FOUND':
# if entrez == 'NOT FOUND' or not as_symbols:
# if uniprot == 'NOT FOUND' or as_symbols:
# name = odb if as_symbols else generic
# else:
# name = uniprot
# else:
# name = entrez
# else:
# name = bonobo
# else:
# name = chimp
# else:
# name = mouse
# else:
# name = human
#
# l2n[odb] = name
#
# if as_symbols is None:
# symbol = "NOT FOUND"
# if row[4] == 'NOT FOUND':
# if row[6] == 'NOT FOUND':
# if row[8] == 'NOT FOUND':
# symbol = row[10]
# else:
# symbol = row[8]
# else:
# symbol = row[6]
# else:
# symbol = row[4]
# l2n[odb] = f"{l2n[odb]} ({symbol})"
#
# return l2n
#
#
# def make_l2n(as_symbols = None) -> Dict[str, str]:
# annotations = osp.join(_self_path(), "data", "full_gene_info.tsv") # Latest matrix
# return read_gene_info_as_l2n(annotations, as_symbols)
def make_l2n(as_symbols: bool = None) -> Dict[str, str]:
if as_symbols is None:
file = "id2name.tsv"
elif as_symbols:
file = "id2symbol.tsv"
else:
file = "id2longname.tsv"
id2name_dict = dict()
with open(osp.join(_self_path(), "data", file), 'r') as f:
first = True
for l in f:
if first:
first = False
continue
split = l.strip().split("\t")
split = [s.strip().strip('"').strip("'") for s in split]
if len(split) < 2:
continue
id2name_dict[split[0].strip()] = split[1].strip()
return id2name_dict
def find_tree(odb: str, return_as_tree: bool = True) -> Union[str, PhyloTree]:
for datasource in datasources:
tree_dir = datasource.tree_dir
if osp.exists(osp.join(tree_dir, odb + '.fa.pred')):
path = osp.join(tree_dir, odb + '.fa.pred')
if return_as_tree:
return safe_phylo_read(path)
else:
return path
raise AssertionError(f"Cant't find {odb}!")
def find_trim_seq(odb: str) -> str:
for datasource in datasources:
tree_dir = datasource.tree_dir
if osp.exists(osp.join(tree_dir, odb + '.fa.pred')):
if tree_dir.endswith("/"):
tree_dir = tree_dir[0:len(tree_dir)-1]
path = tree_dir.split("/")
path = "/".join(path[0:len(path)-1])
if osp.exists(osp.join(path, "trimmed")):
path = osp.join(path, "trimmed", odb + '.fa')
elif not osp.exists(osp.join(path, "trimmed")) and osp.exists(osp.join(path, "trimmed.tar.bz2")):
call('tar -xvf ' + osp.join(path, "trimmed.tar.bz2"), cwd=path)
path = osp.join(path, "trimmed", odb + '.fa')
else:
if osp.exists("/".join([path, path[1:], 'trim'])):
path = "/".join([path, path[1:], 'trim', odb + '.fa'])
else:
call('tar -xvf ' + osp.join(path, "trim.tar.bz2"), cwd=path)
path = "/".join([path, path[1:], 'trim', odb + '.fa'])
if not osp.exists(path):
continue
else:
return path
raise AssertionError(f"Cant't find {odb}!")
def get_rates(timetree: Union[str, PhyloTree], prune: bool = True, taxa: List[str] = None, *trees: Union[str, PhyloTree]) -> Tuple[List[str], List[List[float]]]:
"""
Get rates from time + trees.
:param timetree: The time tree.
:param prune: Whether the prune the tree based on the passed in taxa. Trees are still pruned to match species.
:param taxa: The taxa to consider.
:param trees: The trees to get rates for.
:return: A tuple, first you get a list representing the taxon indices. Second, you get a list of lists. The outer
list represents the tree (note: index 0 = time), the inner list corresponds to taxon rates.
"""
timetree = timetree if not isinstance(timetree, str) else safe_phylo_read(timetree)
trees = [tree if not isinstance(tree, str) else safe_phylo_read(tree) for tree in trees]
shared_taxa = set(timetree.iter_leaf_names())
for tree in trees:
shared_taxa = shared_taxa & set(tree.iter_leaf_names())
if taxa:
taxa = list(shared_taxa & set(taxa))
shared_taxa = list(shared_taxa)
if not taxa:
taxa = shared_taxa
if prune:
timetree = prune_tree(timetree, taxa)
trees = [(prune_tree(tree, taxa)) for tree in trees]
else:
timetree = prune_tree(timetree, shared_taxa)
trees = [(prune_tree(tree, shared_taxa)) for tree in trees]
rates = [[] for _ in trees]
rates.append([])
leaves = []
for leaf in timetree.iter_leaves():
if leaf.name not in taxa:
continue
leaves.append(leaf.name)
time = np.float(leaf.get_distance(leaf.up))
rates[0].append(time)
for i, tree in enumerate(trees):
if time == 0.:
rates[i+1].append(np.float(0.0))
else:
leaf2 = list(tree.get_leaves_by_name(leaf.name))[0]
rates[i+1].append(np.float(leaf2.get_distance(leaf2.up)) / time)
return leaves, rates
async def get_changed_branches(timetree: PhyloTree, tree: PhyloTree, prune_list: List[str]) -> List[str]:
pruned_time_tree = prune_tree(timetree, list(tree.iter_leaf_names()))
branches = {leaf.name: leaf.get_distance(leaf.up) for leaf in pruned_time_tree.iter_leaves()}
pruned = prune_tree(pruned_time_tree, prune_list)
changed = []
for leaf in pruned.iter_leaves():
if branches[leaf.name] < leaf.get_distance(leaf.up):
changed.append(leaf.name)
return changed
# Convert rate object to correlation
def rates_to_correlation(res: Tuple[List[str], List[List[float]]], corr_to_time: bool = False) -> Tuple[np.float, np.float]:
results = spearmanr(np.array(res[1][0 + (not corr_to_time)]), np.array(res[1][1 + (not corr_to_time)]), nan_policy='raise')
return results.correlation, results.pvalue
async def archive_directory(directory: str, archive: str):
"""
Archives a directory.
:param directory: The directory to archive
:param archive: The archive name
"""
if osp.exists(directory) and not osp.exists(archive):
try:
await async_call(f"tar -cjf {archive} {directory}")
shutil.rmtree(directory, True)
except Exception as e:
print(f"WARNING: Unable to tar compress the directory {directory}")
traceback.print_exc()
async def clean_fasta(treefile: str, fastafile: str, clean_out: str = None):
"""
Given a topology, normalizes fasta taxa naming and drops all taxa with paralogs.
:param treefile: The tree topology.
:param fastafile: The input file.
:param clean_out: The output file path.
"""
if not clean_out:
clean_out = fastafile
records = read_records(fastafile)
taxa_names = set(r.title for r in records)
fasta2tree = dict()
for n in safe_phylo_read(treefile).get_leaf_names():
norm_n = n.replace(' ', '_').upper().strip()
for t in taxa_names:
norm_t = t.replace(' ', '_').upper().strip()
if norm_n in norm_t or norm_t in norm_n:
fasta2tree[t] = n
counts = dict()
for r in records:
r.title = fasta2tree.get(r.title, r.title)
if r.title not in counts:
counts[r.title] = 0
counts[r.title] += 1
dupes = {taxon for taxon, count in counts.items() if count > 1}
new_records = []
for r in records:
if r.title not in dupes:
new_records.append(r)
write_records(clean_out, new_records)
def concat(in_files: Iterable[str], partitions_file: str, out_file: str):
alignment = AMAS.MetaAlignment(data_type='aa', in_format='fasta', concat_out=out_file, in_files=in_files,
part_format='raxml', command='concat')
if osp.exists(out_file):
os.remove(out_file)
if osp.exists(partitions_file):
os.remove(partitions_file)
alignment.write_concat("fasta")
alignment.write_partitions(partitions_file, 'raxml')
async def align_fasta(fastafile: str, outputfile: str, threads: int = 5):
"""
Aligns a file.
:param fastafile: The input path
:param outputfile: The output path
"""
assert fastafile and osp.exists(fastafile)
if not outputfile:
outputfile = fastafile
# NOTE: --anysymbol allows the U symbol to be used in protein seqs https://mafft.cbrc.jp/alignment/software/anysymbol.html
await async_call(f"mafft --maxiterate 1000 --localpair --anysymbol --thread {threads} --out {outputfile} {fastafile}")
assert osp.exists(outputfile)
async def trim(inputfile: str, outputfile: str):
"""
Trims an alignment.
:param inputfile: The input alignment.
:param outputfile: The trimmed alignment.
:return:
"""
assert inputfile and osp.exists(inputfile)
await async_call("trimal -in {} -out {} -automated1".format(inputfile, outputfile))
def prune_tree(in_file: Union[str, PhyloTree], retained: List[str], out_group: Optional[str] = None,
out_file: str = None, deroot: bool = False) -> Optional[PhyloTree]:
if isinstance(in_file, str):
assert in_file and osp.exists(in_file)
if out_file and osp.exists(out_file):
os.remove(out_file)
tree = safe_phylo_read(in_file)
else:
tree = in_file.copy()
curr_leaves = [l for l in tree.iter_leaf_names()]
try:
tree.prune([r for r in retained if r in curr_leaves], preserve_branch_length=True)
except Exception as e:
print(in_file)
print(retained)
print(curr_leaves)
print([r for r in retained if r in curr_leaves])
raise e
tree.resolve_polytomy()
if out_group is not None:
tree.set_outgroup(out_group)
if deroot:
tree.unroot("keep")
if out_file:
tree.write(outfile=out_file)
else:
return tree
async def prune(alignment: str, tree: str, treeout: str):
"""
Prunes a tree based on taxa in an alignment.
:param alignment: The alignment.
:param tree: The tree.
:param treeout: The output path.
"""
prune_tree(tree, [r.title for r in read_records(alignment) if '.' not in r.title], out_group=None, out_file=treeout)
async def iqtree2(alignment: str,
consensus_tree: str = None,
model: str = "AUTO", # LG+F+G+I
output: str = None,
bootstraps: int = 1000,
cpus: int = 2,
expect_model_violations: bool = False,
partitions_file: str = None,
site_specific_rates: bool = True,
clean_outputs: bool = True,
ancestral_states: bool = True):
# Outputs: {alignment}.iqtree -> full report
# {alignment}.treefile -> tree
# {alignment}.log -> log file
# {alignment}.model -> selected model if none is specified
# {alignment}.contree -> tree with bootstrap values only
# {alignment}.splits.nex -> support values in percentage for all splits (bipartitions), computed as the occurence frequencies in the bootstrap trees.
# {alignment}.rate -> site specific rates. See http://www.iqtree.org/doc/Advanced-Tutorial
cmd = f"iqtree2 -s {alignment} -B {bootstraps} -T {cpus} -st AA -seed 1234567890"
if model != "AUTO":
cmd += f" -m {model}" # GTR+I+G
if expect_model_violations: # . With this option UFBoot will further optimize each bootstrap tree using a hill-climbing nearest neighbor interchange (NNI) search based directly on the corresponding bootstrap alignment.
cmd += " -bnni"
if partitions_file:
cmd += f" -p {partitions_file}"
if consensus_tree:
cmd += f" -g {consensus_tree}"
if site_specific_rates:
cmd += " --mlrate"
if ancestral_states:
cmd += " -asr"
await async_call(cmd)
if output:
base = partitions_file if partitions_file else alignment
shutil.move(base + ".treefile", output)
if site_specific_rates:
shutil.move(base + ".mlrate", output + ".mlrate")
if ancestral_states:
shutil.move(base + ".state", output + ".state")
if clean_outputs:
safe_delete(base + ".ckp.gz") # Checkpoint info
safe_delete(base + ".log") # Log
safe_delete(base + ".uniqueseq.phy") # Pruned alignment
safe_delete(base + ".contree") # consensus tree
safe_delete(base + ".iqtree") # more logging?
safe_delete(base + ".parstree") # Parsimony tree
safe_delete(base + ".splits.nex") # Split info
async def protein_tree(alignment: str, topology: str, output: str, partition_file: str = None, cores: int = 5):
"""
Generates a tree using iqtree.
:param alignment: The alignment.
:param topology: The topology.
:param output: The output file. Site specific rates: output + ".mlrate" and ancestral states: output + ".state"
"""
try:
if not output or not osp.exists(output):
await iqtree2(alignment, topology, model="LG+F+G+I", output=output, ancestral_states=True, partitions_file=partition_file, cpus=cores)
except Exception as e:
print(f"WARNING: Could not generate tree for {alignment}!", flush=True)
traceback.print_exc()
async def partial_correlation(tree1: PhyloTree, tree2: PhyloTree, to_control: PhyloTree, species: PhyloTree,
method: str = "spearman", correct_control: bool = True,
to_control2: PhyloTree = None, correct_control2: bool = True,
to_control3: PhyloTree = None, correct_control3: bool = True,
to_control4: PhyloTree = None, correct_control4: bool = True,
normalize_controls: bool = False, return_shared_taxa_count: bool = False) -> Union[Tuple[np.float, np.float], Tuple[np.float, np.float, np.int]]:
"""
Bound using https://cran.r-project.org/web/packages/ppcor/ppcor.pdf
Requires R
returns corr, p-val
"""
fingerprint = str(hex((hash(tree1) ^ hash(tree2) ^ hash(species)) + hash(to_control) + hash(method) \
+ hash(to_control2) + hash(to_control3) + hash(to_control4) + hash(correct_control) + hash(correct_control2) \
+ hash(correct_control3) + hash(correct_control4) + hash(normalize_controls)))
if not to_control2:
all_taxa = list(set(tree1.iter_leaf_names()) & set(tree2.iter_leaf_names()) & set(to_control.iter_leaf_names()))
elif not to_control3:
all_taxa = list(set(tree1.iter_leaf_names()) & set(tree2.iter_leaf_names()) & set(to_control2.iter_leaf_names()) & set(to_control.iter_leaf_names()))
elif not to_control4:
all_taxa = list(set(tree1.iter_leaf_names()) & set(tree2.iter_leaf_names()) & set(to_control3.iter_leaf_names()) & set(to_control2.iter_leaf_names()) & set(to_control.iter_leaf_names()))
else:
all_taxa = list(set(tree1.iter_leaf_names()) & set(tree2.iter_leaf_names()) & set(to_control4.iter_leaf_names()) & set(to_control3.iter_leaf_names()) & set(to_control2.iter_leaf_names()) & set(to_control.iter_leaf_names()))
tree1 = tree1.copy()
tree2 = tree2.copy()
to_control = to_control.copy()
to_control2 = to_control2.copy() if to_control2 else None
to_control3 = to_control3.copy() if to_control3 else None
to_control4 = to_control4.copy() if to_control4 else None
species = species.copy()
tree1.prune(all_taxa, preserve_branch_length=True)
tree2.prune(all_taxa, preserve_branch_length=True)
to_control.prune(all_taxa, preserve_branch_length=True)
species.prune(all_taxa, preserve_branch_length=True)
if to_control2:
to_control2.prune(all_taxa, preserve_branch_length=True)
if to_control3:
to_control3.prune(all_taxa, preserve_branch_length=True)
if to_control4:
to_control4.prune(all_taxa, preserve_branch_length=True)
tree1_data = dict()
tree2_data = dict()
control_data = dict()
species_data = dict()
control_data2 = dict()
control_data3 = dict()
control_data4 = dict()
for leaf in tree1.iter_leaves():
if leaf.name not in all_taxa:
continue
tree1_data[leaf.name] = leaf.get_distance(leaf.up)
for leaf in tree2.iter_leaves():
if leaf.name not in all_taxa:
continue
tree2_data[leaf.name] = leaf.get_distance(leaf.up)
for leaf in to_control.iter_leaves():
if leaf.name not in all_taxa:
continue
control_data[leaf.name] = leaf.get_distance(leaf.up)
for leaf in species.iter_leaves():
if leaf.name not in all_taxa:
continue
species_data[leaf.name] = leaf.get_distance(leaf.up)
if to_control2:
for leaf in to_control2.iter_leaves():
if leaf.name not in all_taxa:
continue
control_data2[leaf.name] = leaf.get_distance(leaf.up)
if to_control3:
for leaf in to_control3.iter_leaves():
if leaf.name not in all_taxa:
continue
control_data3[leaf.name] = leaf.get_distance(leaf.up)
if to_control4:
for leaf in to_control4.iter_leaves():
if leaf.name not in all_taxa:
continue
control_data4[leaf.name] = leaf.get_distance(leaf.up)
if normalize_controls:
max_control1 = max(control_data.values())
min_control1 = min(control_data.values())
for k, v in list(control_data.items()):
control_data[k] = (v - min_control1) / (max_control1 - min_control1)
if to_control2:
max_control2 = max(control_data2.values())
min_control2 = min(control_data2.values())
for k, v in list(control_data2.items()):
control_data2[k] = (v - min_control2) / (max_control2 - min_control2)
if to_control3:
max_control3 = max(control_data3.values())
min_control3 = min(control_data3.values())
for k, v in list(control_data3.items()):
control_data3[k] = (v - min_control3) / (max_control3 - min_control3)
if to_control4:
max_control4 = max(control_data4.values())
min_control4 = min(control_data4.values())
for k, v in list(control_data4.items()):
control_data4[k] = (v - min_control4) / (max_control4 - min_control4)
with open(f"temp_{fingerprint}.csv", 'w') as f:
f.write("x,y,")
if to_control4:
f.write("z1,z2,z3,z4\n")
elif to_control3:
f.write("z1,z2,z3\n")
elif to_control2:
f.write("z1,z2\n")
else:
f.write("z\n")
for taxon in all_taxa:
f.write(f"{np.float(tree1_data[taxon]) / np.float(species_data[taxon])},")
f.write(f"{np.float(tree2_data[taxon]) / np.float(species_data[taxon])},")
if correct_control:
f.write(f"{np.float(control_data[taxon]) / np.float(species_data[taxon])}")
else:
f.write(f"{np.float(control_data[taxon])}")
if to_control2:
if correct_control2:
f.write(f",{np.float(control_data2[taxon]) / np.float(species_data[taxon])}")
else:
f.write(f",{np.float(control_data2[taxon])}")
if to_control3:
if correct_control3:
f.write(f",{np.float(control_data3[taxon]) / np.float(species_data[taxon])}")
else:
f.write(f",{np.float(control_data3[taxon])}")
if to_control4:
if correct_control4:
f.write(f",{np.float(control_data4[taxon]) / np.float(species_data[taxon])}")
else:
f.write(f",{np.float(control_data4[taxon])}")
f.write("\n")
if to_control4:
script_name = "specific_partial_correlation4.R"
elif to_control3:
script_name = "specific_partial_correlation3.R"
elif to_control2:
script_name = "specific_partial_correlation2.R"
else:
script_name = "specific_partial_correlation.R"
await async_call(f"Rscript --vanilla {osp.join(_self_path(), 'R', script_name)} temp_{fingerprint}.csv {method} temp_out_{fingerprint}.csv")
nums = []
if not osp.exists(f'temp_out_{fingerprint}.csv'):
nums.append(np.nan)
nums.append(np.nan)
else:
with open(f'temp_out_{fingerprint}.csv', 'r') as f:
first = True
for l in f:
if first:
first = False
continue
if len(l.strip()) == 0:
continue
num_str = l.strip()
if num_str == 'NA':
nums.append(np.nan)
else:
nums.append(np.float(num_str))
os.remove(f"temp_{fingerprint}.csv")
os.remove(f"temp_out_{fingerprint}.csv")
if return_shared_taxa_count:
return nums[0], nums[1], np.int(len(all_taxa))
return nums[0], nums[1]
async def correlate(tree1: Union[str, PhyloTree], tree2: Union[str, PhyloTree], norm_tree: Union[str, PhyloTree],
internal_requirement: float = -1, include_terminal: bool = False,
ignore_species: List[str] = None) -> Tuple[float, float, Dict[str, Tuple[float, float, float]]]:
norm_tree = safe_phylo_read(norm_tree) if isinstance(norm_tree, str) else norm_tree.copy() # We can reasonably assume this won't error
try:
tree1 = safe_phylo_read(tree1) if isinstance(tree1, str) else tree1.copy()
tree2 = safe_phylo_read(tree2) if isinstance(tree2, str) else tree2.copy()
except Exception as e:
print(f"Problem handling trees: {tree1}, {tree2}, {norm_tree}", file=sys.stderr)
return nan, nan, {l: (nan, nan) for l in norm_tree.iter_leaves()}
tree1_rates = list()
tree2_rates = list()
raw_rates = {}
if internal_requirement < 0:
for leaf in tree1.iter_leaves():
if ignore_species and leaf.name in ignore_species:
continue
tree1_rate = leaf.get_distance(leaf.up)
results = tree2.get_leaves_by_name(leaf.name)
if leaf.name not in [x.name for x in results]:
print(f"Skipping {leaf.name}...", flush=True)
continue
tree2_leaf = results[0]
assert tree2_leaf.is_leaf()
tree2_rate = tree2_leaf.get_distance(tree2_leaf.up)
results = norm_tree.get_leaves_by_name(leaf.name)
if leaf.name not in [x.name for x in results]:
print(f"Skipping {leaf.name}...", flush=True)
continue
norm_leaf = results[0]
assert norm_leaf.is_leaf()
norm_factor = norm_leaf.get_distance(norm_leaf.up)
tree1_rates.append(0 if norm_factor == 0. else tree1_rate / norm_factor)
tree2_rates.append(0 if norm_factor == 0. else tree2_rate / norm_factor)
raw_rates[leaf.name] = (tree1_rates[-1], tree2_rates[-1], norm_factor)
# else:
# raise AssertionError("Unexpected norm_mode " + norm_mode)
else:
for node in tree1.traverse():
if node.is_leaf():
if not include_terminal or (ignore_species and node.name in ignore_species):
continue
leaf = node
tree1_rate = leaf.get_distance(leaf.up)
results = tree2.get_leaves_by_name(leaf.name)
if leaf.name not in [x.name for x in results]:
print(f"Skipping {leaf.name}...", flush=True)
continue
tree2_leaf = results[0]
assert tree2_leaf.is_leaf()
tree2_rate = tree2_leaf.get_distance(tree2_leaf.up)
results = norm_tree.get_leaves_by_name(leaf.name)
if leaf.name not in [x.name for x in results]:
print(f"Skipping {leaf.name}...", flush=True)
continue
norm_leaf = results[0]
assert norm_leaf.is_leaf()
norm_factor = norm_leaf.get_distance(norm_leaf.up)
tree1_rates.append(0 if norm_factor == 0. else tree1_rate / norm_factor)
tree2_rates.append(0 if norm_factor == 0. else tree2_rate / norm_factor)
raw_rates[leaf.name] = (tree1_rates[-1], tree2_rates[-1], norm_factor)
# else:
# raise AssertionError("Unexpected norm_mode " + norm_mode)
else:
leaves = set(node.get_leaf_names())
tree2_node = None
for node2 in tree2.traverse():
if leaves == set(node2.get_leaf_names()):
tree2_node = node2
break
if not tree2_node:
print(f"Skipping {node.name}...", flush=True)
continue
norm_node = None
for nnode in norm_tree.traverse():
if leaves == set(nnode.get_leaf_names()):
norm_node = nnode
break
if not norm_node:
print(f"Skipping {node.name}...", flush=True)
continue
if norm_node.up is not None:
if norm_node.get_distance(norm_node.up) < internal_requirement:
continue
norm_factor = norm_node.get_distance(norm_node.up)
tree1_rate = node.get_distance(node.up)
tree2_rate = tree2_node.get_distance(tree2_node.up)
tree1_rates.append(0 if norm_factor == 0. else tree1_rate / norm_factor)
tree2_rates.append(0 if norm_factor == 0. else tree2_rate / norm_factor)
raw_rates["$".join(leaves)] = (tree1_rates[-1], tree2_rates[-1], norm_factor)
results = spearmanr(array(tree1_rates), array(tree2_rates), nan_policy='raise')