-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcompleasm.py
executable file
·2749 lines (2564 loc) · 154 KB
/
compleasm.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Neng Huang
Email: neng@ds.dfci.harvard.edu
Date: 2023 Apr 11
"""
import os
import argparse
import hashlib
import sys
import tarfile
import urllib.request
import subprocess
from multiprocessing import Pool
import shlex
import shutil
import re
import json
from enum import Enum
from collections import defaultdict
import pandas as pd
import time
from _version import __version__
### utils
class Error(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
### DownloadLineage.py
class URLError(OSError):
def __init__(self, reason, filename=None):
self.args = reason,
self.reason = reason
if filename is not None:
self.filename = filename
def __str__(self):
return '<urlopen error %s>' % self.reason
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
class Downloader2:
def __init__(self, download_dir=None, download_lineage=True, download_placement=True):
pass
def download_single_file(self):
pass
def download_file_version_document(self):
pass
def download_placement(self):
pass
class Downloader:
def __init__(self, download_dir=None, download_lineage=True, download_placement=True):
self.base_url = "https://busco-data.ezlab.org/v5/data/"
self.default_lineage = ["eukaryota_odb10"]
if download_dir is None:
self.download_dir = "mb_downloads"
else:
self.download_dir = download_dir
self.placement_dir = os.path.join(self.download_dir, "placement_files")
if not os.path.exists(self.download_dir):
os.mkdir(self.download_dir)
self.lineage_description, self.placement_description = self.download_file_version_document()
if download_placement:
if not os.path.exists(self.placement_dir):
os.mkdir(self.placement_dir)
if not os.path.exists(self.placement_dir + ".done"):
self.download_placement() # download placement files
if download_lineage:
for lineage in self.default_lineage:
self.download_lineage(lineage)
def download_single_file(self, remote_filepath, local_filepath, expected_hash):
try:
urllib.request.urlretrieve(remote_filepath, local_filepath)
observed_hash = md5(local_filepath)
if observed_hash != expected_hash:
print("md5 hash is incorrect: {} while {} expected".format(str(observed_hash), str(expected_hash)))
print("deleting corrupted file {}".format(local_filepath))
# os.remove(local_filepath)
print("Unable to download necessary files")
raise Error("Unable to download necessary files")
else:
print("Success download from {}".format(remote_filepath))
except URLError:
print("Cannot reach {}".format(remote_filepath))
return False
return True
def download_file_version_document(self):
file_version_url = self.base_url + "file_versions.tsv"
file_version_download_path = os.path.join(self.download_dir, "file_versions.tsv")
hash_url = self.base_url + "file_versions.tsv.hash"
hash_download_path = os.path.join(self.download_dir, "file_versions.tsv.hash")
if os.path.exists(file_version_download_path + ".tmp"):
sys.exit("file_versions.tsv.tmp exists, another process is downloading, please run again later.")
if not os.path.exists(file_version_download_path + ".done"):
open(file_version_download_path + ".tmp", 'w').close()
# download hash file
try:
urllib.request.urlretrieve(hash_url, hash_download_path)
except URLError:
print("Cannot reach {}".format(hash_url))
os.remove(file_version_download_path + ".tmp")
raise Error("Unable to download necessary file {}".format("file_versions.tsv.hash"))
with open(hash_download_path, 'r') as fin:
expected_file_version_hash = fin.readline().strip().split()[0]
download_success = self.download_single_file(file_version_url,
file_version_download_path,
expected_file_version_hash)
if not download_success:
os.remove(file_version_download_path + ".tmp")
raise Error("Unable to download necessary file {}".format("file_versions.tsv"))
else:
open(file_version_download_path + ".done", 'w').close()
os.remove(file_version_download_path + ".tmp")
lineages_description_dict = {}
placement_description_dict = {}
with open(file_version_download_path, 'r') as fin:
for line in fin:
strain, date, hash_value, category, info = line.strip().split()
if info == "lineages":
lineages_description_dict[strain] = [date, hash_value, category]
elif info == "placement_files":
placement_description_dict[strain] = [date, hash_value, category]
return lineages_description_dict, placement_description_dict
def download_lineage(self, lineage):
if not lineage.endswith("_odb10"):
lineage = lineage + "_odb10"
if os.path.exists(os.path.join(self.download_dir, lineage) + ".tmp"):
sys.exit("{}.tmp exists, another process is downloading, please run again later.".format(lineage))
if not os.path.exists(os.path.join(self.download_dir, lineage) + ".done"):
open(os.path.join(self.download_dir, lineage) + ".tmp", 'w').close()
try:
date, expected_hash = self.lineage_description[lineage][0:2] # [date, hash_value, category]
except KeyError:
os.remove(os.path.join(self.download_dir, lineage) + ".tmp")
raise Error("invalid lineage name: {}".format(lineage))
remote_url = self.base_url + "lineages/{}.{}.tar.gz".format(lineage, date)
download_path = os.path.join(self.download_dir, "{}.{}.tar.gz".format(lineage, date))
download_success = self.download_single_file(remote_url, download_path, expected_hash)
if not download_success:
os.remove(os.path.join(self.download_dir, lineage) + ".tmp")
raise Error("Unable to download necessary file {}".format("{}.{}.tar.gz".format(lineage, date)))
if download_success:
tar = tarfile.open(download_path)
# tar.extractall(self.download_dir)
try:
tar.extractall(self.download_dir, members=[tar.getmember('{}/refseq_db.faa.gz'.format(lineage)),
tar.getmember('{}/links_to_ODB10.txt'.format(lineage)),
tar.getmember('{}/hmms'.format(lineage)),
tar.getmember('{}/scores_cutoff'.format(lineage)),
tar.getmember('{}/lengths_cutoff'.format(lineage))])
hmm_files = [u for u in tar.getnames() if ".hmm" in u]
tar.extractall(self.download_dir, members=[tar.getmember(u) for u in hmm_files])
except KeyError:
if "{}/refseq_db.faa.gz".format(lineage) not in tar.getnames():
os.remove(os.path.join(self.download_dir, lineage) + ".tmp")
os.remove(download_path)
sys.exit(
"No refseq_db.faa.gz in lineage {}, this lineage cannot be used in compleasm! Lineage file has been deleted.".format(
lineage))
tar.extractall(self.download_dir, members=[tar.getmember('{}/refseq_db.faa.gz'.format(lineage)),
tar.getmember('{}/hmms'.format(lineage)),
tar.getmember('{}/scores_cutoff'.format(lineage)),
tar.getmember('{}/lengths_cutoff'.format(lineage))])
hmm_files = [u for u in tar.getnames() if ".hmm" in u]
tar.extractall(self.download_dir, members=[tar.getmember(u) for u in hmm_files])
except:
os.remove(os.path.join(self.download_dir, lineage) + ".tmp")
os.remove(download_path)
raise Error("Unable to extract file: {} or {} from {}".format("refseq_db.faa.gz",
"links_to_ODB10.txt",
download_path))
tar.close()
print("Lineage file extraction path: {}/{}".format(self.download_dir, lineage))
local_lineage_dir = os.path.join(self.download_dir, lineage)
self.lineage_description[lineage].append(local_lineage_dir)
open(os.path.join(self.download_dir, lineage) + ".done", 'w').close()
os.remove(os.path.join(self.download_dir, lineage) + ".tmp")
else:
if lineage not in self.lineage_description.keys():
## for modified lineage file by user
self.lineage_description[lineage] = [lineage, "Unknown", "Unknown", os.path.join(self.download_dir, lineage)]
else:
self.lineage_description[lineage].append(os.path.join(self.download_dir, lineage))
def download_placement(self):
if os.path.exists(self.placement_dir + ".tmp"):
sys.exit("placement_files.tmp exists, another process is downloading, please run again later.")
if not os.path.exists(self.placement_dir + ".done"):
open(self.placement_dir + ".tmp", 'w').close()
for strain in self.placement_description.keys():
date, expected_hash, category = self.placement_description[strain]
if strain.startswith("supermatrix"):
prefix, aln, version, sufix = strain.split(".")
download_file_name = "{}.{}.{}.{}.{}.tar.gz".format(prefix, aln, version, date, sufix)
else:
prefix, version, sufix = strain.split(".")
download_file_name = "{}.{}.{}.{}.tar.gz".format(prefix, version, date, sufix)
if "eukaryota" not in download_file_name:
continue
remote_url = self.base_url + "placement_files/{}".format(download_file_name)
download_path = os.path.join(self.placement_dir, download_file_name)
download_success = self.download_single_file(remote_url, download_path, expected_hash)
if not download_success:
os.remove(self.placement_dir + ".tmp")
raise Error("Unable to download necessary file {}".format(download_file_name))
if download_success:
tar = tarfile.open(download_path)
tar.extractall(self.placement_dir)
tar.close()
print("Placement file extraction path: {}/{}".format(self.placement_dir,
download_file_name.replace(".tar.gz", "")))
self.placement_description[strain].append(
os.path.join(self.placement_dir, download_file_name.replace(".tar.gz", "")))
open(self.placement_dir + ".done", 'w').close()
os.remove(self.placement_dir + ".tmp")
else:
for strain in self.placement_description.keys():
date, expected_hash, category = self.placement_description[strain]
if strain.startswith("supermatrix"):
prefix, aln, version, sufix = strain.split(".")
download_file_name = "{}.{}.{}.{}.{}.tar.gz".format(prefix, aln, version, date, sufix)
else:
prefix, version, sufix = strain.split(".")
download_file_name = "{}.{}.{}.{}.tar.gz".format(prefix, version, date, sufix)
if "eukaryota" not in download_file_name:
continue
self.placement_description[strain].append(
os.path.join(self.placement_dir, download_file_name.replace(".tar.gz", "")))
### miniprot ###
def listfiles(folder):
for root, folders, files in os.walk(folder):
for filename in folders + files:
yield os.path.join(root, filename)
class MiniprotRunner:
def __init__(self, miniprot_execute_command, outs, nthreads=1):
if miniprot_execute_command is None:
miniprot_execute_command = self.search_miniprot()
print("miniprot execute command:\n {}".format(miniprot_execute_command))
self.miniprot_execute_command = miniprot_execute_command
self.threads = nthreads
self.outs = outs
def run_miniprot(self, assembly_filepath, lineage_filepath, alignment_outdir):
if not os.path.exists(alignment_outdir):
os.mkdir(alignment_outdir)
output_filepath = os.path.join(alignment_outdir, "miniprot_output.gff")
fout = open(output_filepath, "w")
miniprot_process = subprocess.Popen(shlex.split(
"{} --trans -u -I --outs={} -t {} --gff {} {}".format(self.miniprot_execute_command, self.outs,
self.threads, assembly_filepath, lineage_filepath,
output_filepath)), stdout=fout,
bufsize=8388608)
exitcode = miniprot_process.wait()
fout.close()
if exitcode != 0:
raise Exception("miniprot exited with non-zero exit code: {}".format(exitcode))
else:
tag_file = os.path.join(alignment_outdir, "miniprot.done")
open(tag_file, 'w').close()
return output_filepath
### auto lineage ###
class AutoLineager:
def __init__(self, sepp_output_directory, sepp_tmp_directory, library_path, threads, sepp_execute_command=None):
self.sepp_output_folder = sepp_output_directory
self.sepp_tmp_folder = sepp_tmp_directory
self.threads = threads
self.downloader = Downloader(library_path)
self.lineage_description = self.downloader.lineage_description
self.placement_description = self.downloader.placement_description
self.library_folder = self.downloader.download_dir
self.placement_file_folder = self.downloader.placement_dir
self.sepp_execute_command = sepp_execute_command
def run_sepp(self, marker_genes_filapath):
# select the best one in ["archaea_odb10", "bacteria_odb10", "eukaryota_odb10"] as search_lineage to run repp
search_lineage = "eukaryota_odb10"
sepp_output_folder = self.sepp_output_folder
tmp_file_folder = self.sepp_tmp_folder
tree_nwk_path = self.placement_description["tree.{}.nwk".format(search_lineage)][3]
tree_metadata_path = self.placement_description["tree_metadata.{}.txt".format(search_lineage)][3]
supermaxtix_path = self.placement_description["supermatrix.aln.{}.faa".format(search_lineage)][3]
print("tree_nwk_path: {}".format(tree_nwk_path))
print("tree_metadata_path: {}".format(tree_metadata_path))
print("supermaxtix_path: {}".format(supermaxtix_path))
if os.path.exists(sepp_output_folder):
shutil.rmtree(sepp_output_folder)
if os.path.exists(tmp_file_folder):
shutil.rmtree(tmp_file_folder)
sepp_process = "{} --cpu {} --outdir {} -t {} -r {} -a {} -f {} -F 15 -m amino -p {}".format(
self.sepp_execute_command, self.threads, sepp_output_folder, tree_nwk_path, tree_metadata_path,
supermaxtix_path, marker_genes_filapath, tmp_file_folder)
os.system(sepp_process)
# sepp = subprocess.Popen(sepp_process)
# sepp.wait()
return search_lineage
# Code from https://gitlab.com/ezlab/busco
def pick_dataset(self, search_lineage):
# run_folder = self.run_folder
# load busco dataset name by id in a dict {taxid:name}
datasets_mapping = {}
taxid_busco_file_name = "mapping_taxids-busco_dataset_name.{}.txt".format(search_lineage)
taxid_busco_file_path = self.placement_description[taxid_busco_file_name][3]
with open(taxid_busco_file_path) as f:
for line in f:
parts = line.strip().split("\t")
tax_id = parts[0]
dataset = parts[1].split(",")[0]
datasets_mapping.update({tax_id: dataset})
# load the lineage for each taxid in a dict {taxid:reversed_lineage}
# lineage is 1:2:3:4:5:6 => {6:[6,5,4,3,2,1]}
lineages = set()
parents = {}
taxid_dataset = {}
for t in datasets_mapping:
taxid_dataset.update({t: t})
taxid_lineage_name = "mapping_taxid-lineage.{}.txt".format(search_lineage)
taxid_lineage_file_path = self.placement_description[taxid_lineage_name][3]
with open(taxid_lineage_file_path) as f:
for line in f:
if line.startswith("#"):
continue
lineage = line.strip().split("\t")[4]
lineages.add(lineage)
# for each line, e.g. 6\t1:2:3:4:5:6, create/update the lineage for each level
# 6:[1,2,3,4,5,6], 5:[1,2,3,4,5], 4:[1,2,3,4], etc.
levels = lineage.split(",")
for i, t in enumerate(levels):
parents.update({t: levels[0: i + 1][::-1]})
for t in parents:
for p in parents[t]: # get the deepest parent, not the root one
if p in datasets_mapping:
taxid_dataset.update({t: p})
break
# load json
# load "tree" in a string
# load placements
# obtain a dict of taxid num of markers
# figure out which taxid to use by using the highest number of markers and some extra rules
try:
with open(os.path.join(self.sepp_output_folder, "output_placement.json")) as json_file:
data = json.load(json_file)
tree = data["tree"]
placements = data["placements"]
except FileNotFoundError:
raise Error("Placements failed. Try to rerun increasing the memory or select a lineage manually.")
node_weight = {}
n_p = 0
for placement in placements:
n_p += 1
for individual_placement in placement["p"]:
# find the taxid in tree
node = individual_placement[0]
match = re.findall( # deal with weird character in the json file, see the output yourself.
# if this pattern is inconsistant with pplacer version, it may break buscoplacer.
"[^0-9][0-9]*:[0-9]*[^0-9]{0,1}[0-9]*[^0-9]{0,2}[0-9]*\[%s\]"
% node,
tree,
)
# extract taxid:
try:
if re.match("^[A-Za-z]", match[0]):
taxid = match[0][7:].split(":")[0]
else:
taxid = match[0][1:].split(":")[0]
except IndexError as e:
raise e
if taxid_dataset[taxid] in node_weight:
node_weight[taxid_dataset[taxid]] += 1
else:
node_weight[taxid_dataset[taxid]] = 1
break # Break here to keep only the best match. In my experience, keeping all does not change much.
# from here, define which placement can be trusted
max_markers = 0
choice = []
# taxid for which no threshold or minimal amount of placement should be considered.
# If it is the best, go for it.
no_rules = ["204428"]
ratio = 2.5
if search_lineage.split("_")[-2] == "archaea":
ratio = 1.2
min_markers = 12
node_with_max_markers = None
for n in node_weight:
if node_weight[n] > max_markers:
max_markers = node_weight[n]
node_with_max_markers = n
if node_with_max_markers in no_rules:
choice = [node_with_max_markers]
else:
for n in node_weight:
# if the ration between the best and the current one is not enough, keep both
if node_weight[n] * ratio >= max_markers:
choice.append(n)
if len(choice) > 1:
# more than one taxid should be considered, pick the common ancestor
choice = self._get_common_ancestor(choice, parents)
elif len(choice) == 0:
if search_lineage.split("_")[-2] == "bacteria":
choice.append("2")
elif search_lineage.split("_")[-2] == "archaea":
choice.append("2157")
elif search_lineage.split("_")[-2] == "eukaryota":
choice.append("2759")
if max_markers < min_markers and not (choice[0] in no_rules):
if search_lineage.split("_")[-2] == "bacteria":
key_taxid = "2"
elif search_lineage.split("_")[-2] == "archaea":
key_taxid = "2157"
elif search_lineage.split("_")[-2] == "eukaryota":
key_taxid = "2759"
else:
key_taxid = None # unexpected. Should throw an exception or use assert.
lineage = datasets_mapping[taxid_dataset[key_taxid]]
else:
lineage = datasets_mapping[taxid_dataset[choice[0]]]
lineage = "{}_{}".format(lineage, "odb10")
placed_markers = sum(node_weight.values())
return [lineage, max_markers, placed_markers]
@staticmethod
def _get_common_ancestor(choice, parents):
# starts with the parents of the first choice
all_ancestors = set(parents[choice[0]])
# order will be lost with sets, so keep in a list the lineage of one entry to later pick the deepest ancestor
ordered_lineage = []
for c in choice:
if len(parents[c]) > len(ordered_lineage):
# probably useless. Init with parents[choice[0] should work
ordered_lineage = parents[c]
# keep in set only entries that are in the currently explored lineage
all_ancestors = all_ancestors.intersection(parents[c])
# go through the ordered list of the deepest linage until you found a common ancestor.
for parent in ordered_lineage:
if parent in all_ancestors:
return [parent]
def Run(self, marker_gene_filepath):
search_lineage = self.run_sepp(marker_gene_filepath)
lineage, max_markers, placed_markers = self.pick_dataset(search_lineage)
return lineage
### hmmsearch ###
def run_hmmsearch(hmmsearch_execute_command, output_file, hmm_profile, protein_seqs):
hmmer_process = subprocess.Popen(shlex.split(
"{} --domtblout {} --cpu 1 {} -".format(hmmsearch_execute_command, output_file, hmm_profile)),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, error = hmmer_process.communicate(input=protein_seqs.encode())
output.decode()
exitcode = hmmer_process.returncode
return exitcode
def run_hmmsearch2(hmmsearch_execute_command, output_file, hmm_profile, protein_file):
hmmer_process = subprocess.Popen(shlex.split(
"{} --domtblout {} --cpu 1 {} {}".format(hmmsearch_execute_command, output_file, hmm_profile, protein_file)),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, error = hmmer_process.communicate()
output.decode()
exitcode = hmmer_process.returncode
return exitcode
class Hmmersearch:
def __init__(self, hmmsearch_execute_command, hmm_profiles, threads, output_folder):
if hmmsearch_execute_command is None:
hmmsearch_execute_command = self.search_hmmsearch()
print("hmmsearch execute command:\n {}".format(hmmsearch_execute_command))
self.hmmsearch_execute_command = hmmsearch_execute_command
self.hmm_profiles = hmm_profiles
self.threads = threads
self.output_folder = output_folder
def Run(self, translated_proteins):
pool = Pool(self.threads)
results = []
for profile in os.listdir(self.hmm_profiles):
outfile = profile.replace(".hmm", ".out")
target_specie = profile.replace(".hmm", "")
protein_seqs = translated_proteins[target_specie]
if len(protein_seqs) == 0:
continue
absolute_path_outfile = os.path.join(self.output_folder, outfile)
absolute_path_profile = os.path.join(self.hmm_profiles, profile)
results.append(pool.apply_async(run_hmmsearch, args=(self.hmmsearch_execute_command, absolute_path_outfile,
absolute_path_profile, protein_seqs)))
pool.close()
pool.join()
for res in results:
exitcode = res.get()
if exitcode != 0:
raise Exception("hmmsearch exited with non-zero exit code: {}".format(exitcode))
done_file = os.path.join(os.path.dirname(self.output_folder), "hmmsearch.done")
open(done_file, "w").close()
### Analysis miniprot alignment ###
AminoAcid = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I",
"L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
class GeneLabel(Enum):
Single = 1
Duplicated = 2
Fragmented = 3
Interspaced = 4
Missing = 5
class MiniprotGffItems:
def __init__(self):
self.atn_seq = ""
self.ata_seq = ""
self.target_id = ""
self.contig_id = ""
self.protein_length = 0
self.protein_start = 0
self.protein_end = 0
self.contig_start = 0
self.contig_end = 0
self.strand = ""
self.score = 0
self.rank = 0
self.identity = 0
self.positive = 0
self.codons = []
self.frameshift_events = 0
self.frameshift_lengths = 0
self.frame_shifts = []
def show(self):
return [self.atn_seq,
self.ata_seq,
self.target_id,
self.contig_id,
self.protein_length,
self.protein_start,
self.protein_end,
self.contig_start,
self.contig_end,
self.strand,
self.score,
self.rank,
self.identity,
self.positive,
"|".join(self.codons),
self.frameshift_events,
self.frameshift_lengths,
self.frame_shifts]
def get_region_clusters(regions):
sorted_regions = sorted(regions, key=lambda x: x[0], reverse=False)
clusters = []
for (start, stop) in sorted_regions:
if not clusters:
clusters.append([start, stop])
else:
last_cluster = clusters[-1]
if last_cluster[0] <= start <= last_cluster[1]:
# has overlap
clusters[-1][0] = min(last_cluster[0], start)
clusters[-1][1] = max(last_cluster[1], stop)
else:
clusters.append([start, stop])
return clusters
class OutputFormat:
def __init__(self):
self.gene_label = None
self.data_record = None
def find_frameshifts(cs_seq):
frameshifts = []
frameshift_events = 0
frameshift_lengths = 0
pt = r"[0-9]+[MIDFGNUV]"
it = re.finditer(pt, cs_seq)
for m in it:
if m.group(0).endswith("F") or m.group(0).endswith("G"):
frameshifts.append(m.group(0))
frameshift_events += 1
frameshift_lengths += int(m.group(0)[:-1])
return frameshifts, frameshift_events, frameshift_lengths
def find_frameshifts2(cs_seq):
frameshifts = []
frameshift_events = 0
frameshift_lengths = 0
pt = r"[0-9]+[MIDFGNUV]"
it = re.finditer(pt, cs_seq)
pattern_lst = []
for m in it:
l, type = int(m.group(0)[:-1]), m.group(0)[-1]
pattern_lst.append((l, type))
for i in range(len(pattern_lst)):
if pattern_lst[i][1] == "F" or pattern_lst[i][1] == "G":
## left search
j = i - 1
left_match_cnt = 0
while j >= 0:
if pattern_lst[j][1] == "M":
left_match_cnt += pattern_lst[j][0]
elif pattern_lst[j][1] == "N" or pattern_lst[j][1] == "U" or pattern_lst[j][1] == "V":
break
j -= 1
## right search
j = i + 1
right_match_cnt = 0
while j < len(pattern_lst):
if pattern_lst[j][1] == "M":
right_match_cnt += pattern_lst[j][0]
elif pattern_lst[j][1] == "N" or pattern_lst[j][1] == "U" or pattern_lst[j][1] == "V":
break
j += 1
if left_match_cnt >= 20 and right_match_cnt >= 20:
frameshifts.append(str(pattern_lst[i][0]) + pattern_lst[i][1])
frameshift_events += 1
frameshift_lengths += int(pattern_lst[i][0])
return frameshifts, frameshift_events, frameshift_lengths
def load_dbinfo(dbinfo_file):
dbinfo = {}
with open(dbinfo_file, "r") as f:
for line in f:
gene_id, db, link = line.strip().split("\t")
dbinfo[gene_id] = [link, db]
return dbinfo
def load_score_cutoff(scores_cutoff_file):
cutoff_dict = {}
try:
with open(scores_cutoff_file, "r") as f:
for line in f:
line = line.strip().split()
try:
taxid = line[0]
score = float(line[1])
cutoff_dict[taxid] = score
except IndexError:
raise Error("Error parsing the scores_cutoff file.")
except IOError:
raise Error("Impossible to read the scores in {}".format(scores_cutoff_file))
return cutoff_dict
def load_length_cutoff(lengths_cutoff_file):
cutoff_dict = {}
try:
with open(lengths_cutoff_file, "r") as f:
for line in f:
line = line.strip().split()
try:
taxid = line[0]
sigma = float(line[2])
length = float(line[3])
if sigma == 0.0:
sigma = 1
cutoff_dict[taxid] = {}
cutoff_dict[taxid]["sigma"] = sigma
cutoff_dict[taxid]["length"] = length
except IndexError:
raise Error("Error parsing the lengths_cutoff file.")
except IOError:
raise Error("Impossible to read the lengths in {}".format(lengths_cutoff_file))
return cutoff_dict
def load_hmmsearch_output(hmmsearch_output_folder, cutoff_dict):
reliable_mappings = {}
hmm_length_dict = {}
for outfile in os.listdir(hmmsearch_output_folder):
outfile = os.path.join(hmmsearch_output_folder, outfile)
with open(outfile, 'r') as fin:
best_one_candidate = None
coords_dict = defaultdict(list)
for line in fin:
if line.startswith('#'):
continue
line = line.strip().split()
target_name = line[0]
query_name = line[3]
hmm_score = float(line[7])
hmm_from = int(line[15])
hmm_to = int(line[16])
assert hmm_to >= hmm_from
## query name must match the target name
if target_name.split("|", maxsplit=1)[0].split("_")[0] != query_name:
continue
## save records of the best candidate only (maybe duplicated)
if best_one_candidate is not None and best_one_candidate != target_name.split("|", maxsplit=1)[0]:
continue
if hmm_score >= cutoff_dict[query_name]:
reliable_mappings[target_name] = hmm_score
location = target_name.split("|", maxsplit=1)[1]
coords_dict[location].append((hmm_from, hmm_to))
best_one_candidate = target_name.split("|", maxsplit=1)[0]
for location in coords_dict.keys():
coords = coords_dict[location]
keyname = "{}|{}".format(best_one_candidate, location)
interval = []
coords = sorted(coords, key=lambda x: x[0])
for i in range(len(coords)):
hmm_from, hmm_to = coords[i]
if i == 0:
interval.extend([hmm_from, hmm_to, hmm_to - hmm_from])
else:
try:
assert hmm_from >= interval[0]
except:
raise Error("Error parsing the hmmsearch output file {}.".format(outfile))
if hmm_from >= interval[1]:
interval[1] = hmm_to
interval[2] += hmm_to - hmm_from
elif hmm_from < interval[1] and hmm_to >= interval[1]:
interval[2] += hmm_to - interval[1]
interval[1] = hmm_to
elif hmm_to < interval[1]:
continue
else:
raise Error("Error parsing the hmmsearch output file {}.".format(outfile))
hmm_length_dict[keyname] = interval[2]
reliable_mappings = list(reliable_mappings.keys())
if len(reliable_mappings) == 0:
print("Warning: no reliable mappings found. All candidates do not pass the cutoff of BUSCO gene.")
return reliable_mappings, hmm_length_dict
class MiniprotAlignmentParser:
def __init__(self, run_folder, gff_file, lineage, min_length_percent, min_diff, min_identity, min_complete,
min_rise, specified_contigs, autolineage, hmmsearch_execute_command, nthreads, library_path, mode):
self.autolineage = autolineage
self.run_folder = run_folder
if not os.path.exists(run_folder):
os.makedirs(run_folder)
if lineage is None:
self.completeness_output_file = os.path.join(self.run_folder, "summary.txt")
self.full_table_output_file = os.path.join(self.run_folder, "full_table.tsv")
self.full_table_busco_format_output_file = os.path.join(self.run_folder, "full_table_busco_format.tsv")
else:
if not lineage.endswith("_odb10"):
lineage = lineage + "_odb10"
self.run_folder = os.path.join(run_folder, lineage)
if not os.path.exists(self.run_folder):
os.makedirs(self.run_folder)
self.completeness_output_file = os.path.join(run_folder, "summary.txt")
self.full_table_output_file = os.path.join(self.run_folder, "full_table.tsv")
self.full_table_busco_format_output_file = os.path.join(self.run_folder, "full_table_busco_format.tsv")
self.library_path = library_path
self.gff_file = gff_file
self.lineage = lineage
self.min_length_percent = min_length_percent
self.min_diff = min_diff
self.min_identity = min_identity
self.min_complete = min_complete
self.min_rise = min_rise
self.specified_contigs = specified_contigs
self.marker_gene_path = os.path.join(self.run_folder, "gene_marker.fasta")
self.translated_protein_path = os.path.join(self.run_folder, "translated_protein.fasta")
self.hmm_profiles = os.path.join(self.library_path, lineage, "hmms")
self.hmmsearch_execute_command = hmmsearch_execute_command
self.hmm_output_folder = os.path.join(self.run_folder, "hmmer_output")
self.nthreads = nthreads
self.mode = mode
assert mode in ["lite", "busco"]
if not os.path.exists(self.hmm_output_folder):
os.makedirs(self.hmm_output_folder)
@staticmethod
def parse_miniprot_records(gff_file):
items = MiniprotGffItems()
with open(gff_file, "r") as gff:
while True:
line = gff.readline()
if not line:
if items.target_id != "":
yield items
return
if line.startswith("##gff-version"):
continue
if line.startswith("##PAF"):
if items.target_id != "":
yield items
items.__init__()
fields = line.strip().split("\t")[1:]
items.target_id = fields[0]
items.protein_length = int(fields[1])
items.protein_start = int(fields[2])
items.protein_end = int(fields[3])
items.strand = fields[4]
items.contig_id = fields[5]
items.contig_start = int(fields[7])
items.contig_end = int(fields[8])
if fields[5] == "*":
## Unmapped protein
items.score = 0
items.frameshift_events = 0
items.frameshift_lengths = 0
items.frame_shifts = []
continue
additional_fields = fields[12:]
additional_fields_dict = {}
for sub_f in additional_fields:
additional_fields_dict[sub_f.split(":")[0]] = sub_f
items.score = int(additional_fields_dict["ms"].strip().split(":")[2])
cg = additional_fields_dict["cg"].replace("cg:Z:", "")
frame_shifts, frameshift_events, frameshift_lengths = find_frameshifts2(cg)
items.frameshift_events = frameshift_events
items.frameshift_lengths = frameshift_lengths
items.frame_shifts = frame_shifts
sta_line = gff.readline()
sta_seq = sta_line.strip().split("\t")[1]
new_sta = []
for i in range(len(sta_seq)):
if sta_seq[i].upper() not in AminoAcid:
continue
else:
new_sta.append(sta_seq[i])
items.ata_seq = "".join(new_sta)
else:
fields = line.strip().split("\t")
if fields[2] == "mRNA":
info_dict = dict(v.split("=") for v in fields[8].split()[0].split(";"))
items.rank = int(info_dict["Rank"])
items.identity = float(info_dict["Identity"])
items.positive = float(info_dict["Positive"])
if fields[2] == "CDS":
seq_id = fields[0]
codon_start = int(fields[3]) # 1-based
codon_end = int(fields[4]) # 1-based
codon_strand = fields[6]
info_dict = dict(x.split("=") for x in fields[8].split()[0].split(";"))
target_id = info_dict["Target"]
assert target_id == items.target_id and seq_id == items.contig_id
items.codons.append("{}_{}_{}".format(codon_start, codon_end, codon_strand))
@staticmethod
def record_1st_gene_label(dataframe, min_identity, min_complete, by_length=False):
# check records with same tid of the best record
output = OutputFormat()
gene_id = dataframe.iloc[0]["Target_id"]
# dataframe = dataframe[dataframe["Identity"] >= min_identity]
if dataframe.shape[0] == 0:
output.gene_label = GeneLabel.Missing
return output
elif dataframe.shape[0] == 1:
if by_length:
if dataframe.iloc[0]["Protein_mapped_length"] >= min_complete:
output.gene_label = GeneLabel.Single
output.data_record = dataframe.iloc[0]
return output
else:
output.gene_label = GeneLabel.Fragmented
output.data_record = dataframe.iloc[0]
return output
else:
if dataframe.iloc[0]["Protein_mapped_rate"] >= min_complete:
output.gene_label = GeneLabel.Single
output.data_record = dataframe.iloc[0]
return output
else:
output.gene_label = GeneLabel.Fragmented
output.data_record = dataframe.iloc[0]
return output
else:
complete_regions = []
fragmented_regions = []
for i in range(dataframe.shape[0]):
if by_length:
if dataframe.iloc[i]["Protein_mapped_length"] >= min_complete:
complete_regions.append(
(dataframe.iloc[i]["Contig_id"], dataframe.iloc[i]["Start"], dataframe.iloc[i]["Stop"]))
else:
fragmented_regions.append(
(dataframe.iloc[i]["Contig_id"], dataframe.iloc[i]["Start"], dataframe.iloc[i]["Stop"]))
else:
if dataframe.iloc[i]["Protein_mapped_rate"] >= min_complete:
complete_regions.append(
(dataframe.iloc[i]["Contig_id"], dataframe.iloc[i]["Start"], dataframe.iloc[i]["Stop"]))
else:
fragmented_regions.append(
(dataframe.iloc[i]["Contig_id"], dataframe.iloc[i]["Start"], dataframe.iloc[i]["Stop"]))
if len(complete_regions) == 0:
output.gene_label = GeneLabel.Fragmented
output.data_record = dataframe.iloc[0]
return output
elif len(complete_regions) == 1:
output.gene_label = GeneLabel.Single
output.data_record = dataframe.iloc[0]
return output
else:
ctgs = [x[0] for x in complete_regions]
if len(set(ctgs)) > 1:
output.gene_label = GeneLabel.Duplicated
output.data_record = dataframe
return output
regions = [(x[1], x[2]) for x in complete_regions]
clusters = get_region_clusters(regions)
if len(clusters) == 1:
output.gene_label = GeneLabel.Single
output.data_record = dataframe.iloc[0]
return output
else:
output.gene_label = GeneLabel.Duplicated
output.data_record = dataframe
return output
@staticmethod
def record_1st_2nd_gene_label(dataframe_1st, dataframe_2nd, min_identity, min_complete, min_rise, by_length=False):
# check top 1st and 2nd records whether they are the same gene
output = OutputFormat()
# dataframe_1st = dataframe_1st[dataframe_1st["Identity"] >= min_identity]
# dataframe_2nd = dataframe_2nd[dataframe_2nd["Identity"] >= min_identity]
if dataframe_1st.shape[0] >= 1 and dataframe_2nd.shape[0] == 0:
out = MiniprotAlignmentParser.record_1st_gene_label(dataframe_1st, min_identity, min_complete, by_length)
return out
if dataframe_1st.shape[0] == 0 and dataframe_2nd.shape[0] >= 1:
out = MiniprotAlignmentParser.record_1st_gene_label(dataframe_2nd, min_identity, min_complete, by_length)