-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMGERT.py
executable file
·1745 lines (1533 loc) · 73.4 KB
/
MGERT.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
"""
look at the argparse section
"""
import argparse
from datetime import datetime
import os
import re
import glob
import sys
import json
import csv
import shutil
import tarfile
import multiprocessing
from pathlib import Path
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio.Blast import NCBIXML
from lxml.html import parse
from urllib.request import urlopen
import matplotlib
import pandas as pd
import subprocess as sbp
matplotlib.use("Agg") # Force matplotlib not to use any X-windows backend.
from matplotlib import pyplot as plt
# Settings part: make CDD and configure
def which(program):
"""
:param program: any program you wish to find
:return: a path to executable that are in the PATH variable
"""
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def make_config():
# make a dict to write to a json file (config.json)
# file_units = ["domain"]
file_units = []
soft_units = ["RepeatMasker", "RepeatModeler", "ORFfinder", "rpstblastn", "bedtools", "makeprofiledb"]
config_dict = dict.fromkeys(file_units + soft_units)
# configuring the software paths
for unit in soft_units:
found_path = which(unit)
if found_path is None:
print("%s not found on your computer. Enter a valid path to an executable file (including the file itself)" % unit)
given_path = Path(input("Enter the path > "))
while not given_path.is_file():
print("This path is invalid: file not found!")
given_path = Path(input("Enter the path > "))
config_dict[unit] = str(given_path)
# print("Ok...")
else:
print("%s found here - %s" % (unit, found_path))
config_dict[unit] = found_path
# print("OK...")
# special case - BuildDatabase
bd_dir = config_dict["RepeatModeler"]
bd_path = bd_dir[:-13] + "BuildDatabase"
if os.path.isfile(bd_path):
config_dict["BuildDatabase"] = bd_path
print("BuildDatabase found here - %s" % bd_path)
else:
# try to do which()
bd_path = which("BuildDatabase")
if bd_path is None:
print("%s not found on your computer. Enter a valid path to an executable file (including the file itself)" % unit)
given_path = Path(input("Enter the path > "))
while not given_path.is_file():
print("This path is invalid: file not found!")
given_path = Path(input("Enter the path > "))
config_dict["BuildDatabase"] = str(given_path)
else:
print("BuildDatabase found here - %s" % bd_path)
config_dict["BuildDatabase"] = bd_path
# configure the paths to files which will be used in the pipeline
if len(file_units) > 0:
for unit in file_units:
# separate action for repeat type
# if unit == "RepeatType":
# config_dict[unit] = input("What repeats you're interested in? [LINE, Gypsy, Penelope]... > ")
# print("OK...")
# separate action for Conserved Domain Database
# NB: this settings are valid only for RT domains
if unit == "domain":
domain_name = Path(input("Enter a name for Conserved Domain Database %s... > " % unit))
config_dict[unit] = str(domain_name)
print("OK...")
# separate action for prefix (species name) to added to all other files
elif unit == "prefix":
prefix = input("Enter a prefix for your files (species name) > ")
config_dict[unit] = prefix
print("OK...")
# and anything else
else:
unit_path = Path(input("Enter a path to %s... > " % unit))
if unit_path.is_file() or str(unit_path) == "skip":
config_dict[unit] = str(unit_path)
print("OK...")
else:
print("ERROR. No such file or your path is wrong!\nQuit")
sys.exit()
# add fixed file names and paths to the config
# config_dict["RepeatMasker Output"] = config_dict["genome"][:-3] + ".out"
config_dict["RepeatModeler Output"] = "consensi.fa.classified"
config_dict["GetORF Output"] = "hitdata.xml"
config_dict["ORFinder Input"] = "matches_w_hits.fa"
config_dict["CENSOR Output"] = "Unknown_classified.fa"
config_dict["domain"] = "CD"
# if you do not run makeCDD script, you have to add domain name
config_dict["CDD"] = os.getcwd()+"/LocalCDD/" + config_dict["domain"]
config_str = json.dumps(config_dict)
with open("config.json", 'w') as outfile:
outfile.write(config_str)
print("OK. All files are configured.")
def make_local_cdd(dir_for_cd="LocalCDD"):
"""
:param dir_for_cd: a name for a directory to store local CDD
:return: no
"""
domain_name = read_config("domain")
# find smp files and make list of them, call it "smp_files_list.pn"
workdir = os.getcwd()
files = glob.glob("*.smp")
# check if there is no such files
if len(files) == 0:
print("No smp files found in %s" % workdir)
if os.path.isdir(dir_for_cd):
ans = input("LocalCDD directory is found. Maybe a database already exists? [y/n] > ")
if ans == "y":
print("Ok...")
# add to config
cdd_path_full = os.getcwd() + "/" + dir_for_cd + "/" + domain_name
# os.chdir("../")
add_config("CDD", cdd_path_full)
print("Local Conserved Domain Database is made and added to the config.")
sys.exit(0)
else:
print("ERROR! Put *smp files to current working directory.")
sys.exit(1)
if not os.path.isdir(dir_for_cd):
print("ERROR! Move *smp files to the current working directory.")
sys.exit(1)
# check if dir for CDD exists and make it, if not exists, and move into
if not os.path.isdir(dir_for_cd):
os.mkdir(dir_for_cd)
# check if smp table exists and move it
cd_table = glob.glob("*.[c,t]sv")
if len(cd_table) == 0:
print("No correspondence table is found...")
#print("assume there is only one CD type...")
else:
print("Correspondence table is found and added to the config...")
new_path = workdir + "/" + dir_for_cd +"/" + cd_table[0]
shutil.move(cd_table[0], new_path)
add_config("cd_table", new_path)
# move smp files to new dir
os.system("mv *.smp %s" % dir_for_cd)
os.chdir(dir_for_cd)
with open("smp_files_list.pn", "w") as out:
for f in files:
out.write("%s\n" % f)
print("A list of smp files has been compiled.")
print("Database name - %s" % domain_name)
# make local database
cmd = "makeprofiledb -in smp_files_list.pn -out %s " % domain_name
os.system(cmd)
cdd_path_full = os.getcwd() + "/" + domain_name
# go to level up to write config in right directory
os.chdir("../")
add_config("CDD", cdd_path_full)
print("Local Conserved Domain Database is made and added to the config.")
# GetCons part
def check_types(seq_file=""):
"""
collects types of sequences in a file (if the file exists)
:param seq_file: fasta file with sequences
:return: a sorted list of repeat types in the file
"""
if seq_file == "":
seq_file = read_config("RepeatModeler Output")
try:
with open(seq_file) as f:
repeats = [re.findall(r'#(.*)', rec.id)[0] for rec in SeqIO.parse(f, 'fasta')]
repeats.sort()
for rep in set(repeats):
print("%s" % rep)
except FileNotFoundError:
print("File %s not found!" % seq_file)
sys.exit()
def read_config(unit, home=False):
"""
reads config file and returns a value of a requested key
:param unit: key from config.json
:param home: where is config.json: in 'home' dir or in CWD?
:return: value of this key
"""
# if home:
# config_location = os.getcwd() + "/config.json"
# else:
# config_location = "config.json"
config_location = "config.json"
try:
conf = open(config_location).readline()
jconf = json.loads(conf)
except FileNotFoundError:
try:
# check if config exists one level above (RepeatModeler and MakeCDD case)
conf = open("../"+config_location).readline()
jconf = json.loads(conf)
except FileNotFoundError:
try:
conf = open("../../"+config_location).readline()
jconf = json.loads(conf)
except FileNotFoundError:
print("ERROR! config.json not found!")
sys.exit()
return jconf[unit]
def add_config(unit, val, home=False):
"""
add new item to the config file
:param unit: new key to add
:param val: a value for the key
:param home: where is config.json: in 'home' dir or in CWD?
:return: there is no return
"""
# if home:
# config_location = os.getcwd() + "/config.json"
# else:
# config_location = "config.json"
config_location = "config.json"
try:
conf = open(config_location).readline()
jconf = json.loads(conf)
config_path = config_location
except FileNotFoundError:
try:
# check if config exists one level above (RepeatModeler and MakeCDD case)
conf = open("../"+config_location).readline()
jconf = json.loads(conf)
config_path = "../"+config_location
except FileNotFoundError:
try:
conf = open("../../"+config_location).readline()
jconf = json.loads(conf)
config_path = "../../" + config_location
except FileNotFoundError:
print("ERROR! config.json not found!")
print("config location - %s" % config_location)
sys.exit()
jconf[unit] = val
conf = json.dumps(jconf)
with open(config_path, 'w') as outfile:
outfile.write(conf)
# print("New item was added to the config - %s" % unit)
def repeat_collector(filename, word, merge=False, message=True):
"""
repeat_collector extracts entries containing particular word in their headers (e.g. repeat type)
from any fasta file (e.g. RepeatModeler output file - consensi.fa.classified)
:param filename: name of the fasta file with sequences
:param word: a word in sequence header you are interested in
:param merge: if this run is for subsequent merge, default=False
"""
try:
f = open(filename)
except FileNotFoundError:
print("Error! File %s not found!" % filename)
sys.exit()
extracted_sequences = [record for record in SeqIO.parse(f, 'fasta') if word in record.id]
if len(extracted_sequences) == 0:
# print("No %s sequences found in %s" % (word, filename))
print("No %s sequences found there" % word)
# rename initial file into final one
if merge:
cmd = "mv " + word + "_consensi.fa.classified" + " All_" + word + "_consensi.fa"
os.system(cmd)
print("Your repeat consensuses file was renamed")
# sys.exit()
# else:
# sys.exit()
fileout = word + "_" + filename.split("/")[-1]
with open(fileout, 'w') as output:
SeqIO.write(extracted_sequences, output, 'fasta')
if word == "Unknown":
add_config("Unknown repeats file", fileout)
if message:
print('%s Consensus TEs from RepeatModeler output have been collected' % word)
def censor_parser(url):
"""
censor_parser reads and parses CENSOR html output (either file or URL)
and renames unclassified consensuses from RepeatModeler
arg: unknown sequences file
"""
# file = input("unknown sequences file? > ")
file = read_config("Unknown repeats file")
# insert URL from GIRI Censor output
# 'http://www.girinst.org/cgi-bin/censor/show_results.cgi?id=79886&lib=root'
# url = input("CENSOR output URL > ")
if "html" in url:
# that's a file
parsed = parse(url)
else:
# it's an URL, probably it contains 'girinst.org'
parsed = parse(urlopen(url))
# parsed = parse(urlopen(url))
doc = parsed.getroot()
tables = doc.findall('.//table')
text_tables = [tables[i].text_content().split(' ') for i in range(len(tables))]
# collect consensus name and rep class/family it belongs to in tuples
cons_type = [(item[12], item[-5]) for item in text_tables if len(item) >= 15] # >= 3 is minimal
# make new sequence file
classified = []
for rec in SeqIO.parse(file, 'fasta'):
for item in cons_type:
if rec.id == item[0]:
newid = rec.id[:-7] + item[1] # cut off the word 'Unknown'
newrec = SeqRecord(rec.seq, id=newid, description='')
classified.append(newrec)
with open("Unknown_classified.fa", 'w') as f:
SeqIO.write(classified, f, 'fasta')
print('TEs from CENSOR output have been collected.')
def merger(file_a, file_b, fill):
"""
merge file_a (repeats from repmod output) and file_b (repeats from censor output)
:param file_a: repeats from collector_repmod
:param file_b: repeats from collector_censor
:param fill: a word to insert in out file name (typically - repeat name)
:return: the name of new concatenated file
"""
out = "All_" + fill + "_consensi.fa"
command = "cat " + file_a + " " + file_b + " > " + out
os.system(command)
return out
def get_cons(mge_type='', censor=False, url='', unknown=False, recollect=False, merge=False, b_types=False, n_types=False, a_types=False, standard=False):
"""
Function to collect seqs from a file according to word in seqs' headers.
It is started several times inside the pipeline with different logical args
:param censor: use CENSOR or not
:param url: URL address of CENSOR output
:param unknown: collect unknown sequences
:param recollect: collect your repeats from newly classified sequences
:param merge:
:param b_types:
:param n_types:
:param a_types:
:param standard:
:param mge_type: type of MGE to search. For some actions is unnecessary
:return:
"""
if standard:
filenm = read_config("RepeatModeler Output")
# collect repeats of interest
repeat_collector(filenm, mge_type)
# collect Unknown repeats
# repeat_collector(filenm, "Unknown")
# print("Now you may run CENSOR -> http://www.girinst.org/censor/")
elif censor:
censor_parser(url)
# print("CENSOR output has been parsed and your TEs have been collected")
elif unknown:
filenm = read_config("RepeatModeler Output")
# reptype = "Unknown"
repeat_collector(filenm, "Unknown")
print("Unknown TEs have been collected")
elif recollect:
# reptype = read_config("RepeatType")
fname = read_config("CENSOR Output")
repeat_collector(fname, mge_type, merge=False, message=False)
# print("Collecting %s TEs from %s..." % (mge_type, fname))
file1 = mge_type + "_" + read_config("RepeatModeler Output")
file2 = mge_type + "_" + read_config("CENSOR Output")
merger(file1, file2, fill=mge_type)
# print("%s TEs from newly classified sequences have been collected and merged with previous data set" % mge_type)
elif merge:
# is never called throughout the pipeline
file1 = mge_type + "_" + read_config("RepeatModeler Output")
file2 = mge_type + "_" + read_config("CENSOR Output")
out = merger(file1, file2, fill=read_config("RepeatType"))
print("Two data sets have been merged - see %s" % out)
elif b_types:
file = read_config("RepeatModeler Output")
types = check_types(file)
print("The following types of TEs were found in %s:" % file)
for type in sorted(set(types)):
print(type, types.count(type), sep=" - ")
elif n_types:
file = read_config("CENSOR Output")
types = check_types(file)
print("The following types of TEs were found in %s:" % file)
for type in sorted(set(types)):
print(type, types.count(type), sep=" - ")
elif a_types:
file1 = read_config("RepeatModeler Output")
file2 = read_config("CENSOR Output")
concat = merger(file1, file2, fill="Repeats")
types = check_types(concat)
print("The following types of TEs were found in %s:" % concat)
for type in sorted(set(types)):
print(type, types.count(type), sep=" - ")
else:
print("Nothing to do :-(")
# GetSeq part
def merge_overlap(df, ov=0):
"""
to merge overlapping matches in one data frame record,
runs inside ori_to_csv() function
:param df: a DataFrame object with all the same values in 'strand' column
:param ov: the overlap value; matches closer to each other than this 'ov'
will be considered as overlapping
:return: a pandas data frame object with merged matches
"""
# see c_strand.csv as an example
# df = pd.read_csv("c_strand.csv")
start = df["start"]
skewed_start = start[1:].append(pd.Series(0))
diff = pd.Series(skewed_start.values - start.values, index=start.index)
# df["diff"] = diff
df["overlap"] = df["length"] > diff - ov
# what blocks of overlapping matches we have?
# '1' - means it's the 1st block; '2' - 2nd and so on;
# 'False' in 'overlap' column means end of the block
blocks = []
n = 1
for item in df['overlap']:
if item:
blocks.append(n)
else:
blocks.append(n)
n += 1
df['blocks'] = blocks
# and now merge rows with overlapping matches:
clean_groups = []
for name, group in df.groupby('blocks'):
# find the 'stop' of the last row in this table:
z = int(group.tail(1)['stop'])
# assign new value to the 'stop' of the 1st row of this table:
group.set_value(min(group.index), 'stop', z)
# remove all other rows in this table:
# but first select these rows:
these_rows = list(group.index[1:len(group) + 1])
group = group.drop(these_rows)
clean_groups.append(group)
clean_df = pd.concat(clean_groups)
# we don't need 'blocks' and 'overlaps' anymore:
del clean_df["blocks"]
del clean_df["overlap"]
# update 'length' column:
clean_df["length"] = clean_df["stop"] - clean_df["start"] + 1
return clean_df
def ori_to_csv(rm_file, len_cutoff=0, expansion=0, make_plot=True, bins=200):
"""
to read ori file, compute lengths of matches, drop off matches with
lengths less than is set by 'len_value' parameter, expand coordinates, merge overlapping matches.
Also prompts to print a histogram of lengths
:param rm_file: RepeatMasker *ori.out file (text)
:param len_cutoff: all matches with shorter length will be removed (integer)
:param expansion: bps to expand matches (integer)
:param make_plot: whether to make a density plot (logical)
:param bins: number of bins in histogram
:return: cleaner and shorter table of csv format (writes it to disk)
"""
print("RepeatMasker table cleaning and transformation...")
rm_tab = pd.read_csv(rm_file, delim_whitespace=True, header=None)
# remove THESE columns
rm_tab = rm_tab.drop([0, 1, 2, 3, 7, 9, 10, 11, 12, 13], axis=1)
# headers = ["contig", "start", "stop", "strand"]
length = rm_tab[6] - rm_tab[5] + 1
rm_tab[9] = length
# assign column names
rm_tab.columns = ['contig', 'start', 'stop', 'strand', 'length']
# drop off too short matches
tab_sort = rm_tab[rm_tab['length'] >= len_cutoff]
print("Matches shorter than %i bp have been dropped" % len_cutoff)
# expanding coordinates
tab_sort["start"] = tab_sort["start"] - expansion
tab_sort["stop"] = tab_sort["stop"] + expansion
# split DF by contigs
cleaned_df_lst = []
# number of matches being processed,
# frequency of message printing,
# number of contigs
x = 0
num_con = len(tab_sort['contig'].unique())
step = 500
for name1, contig_group in tab_sort.groupby('contig'):
x += 1
# split unique contig DF by strand
for name2, strand_group in contig_group.groupby('strand'):
# get cleaned version of strand-specific DF
cleaned_result = merge_overlap(strand_group)
cleaned_df_lst.append(cleaned_result)
if x % step == 0:
print("Number of contigs processed: %i/%i" % (x, num_con))
tab_clean = pd.concat(cleaned_df_lst)
tab_clean.to_csv('file.fa.ori.out.cleaned.csv', index=False)
# plot/histogram printing
# ans = input("print a histogram? [y/n] > ")
if make_plot:
plot3 = tab_clean['length'].hist(bins=bins)
# plot = tab_clean['length'].plot(kind='kde')
fig3 = plot3.get_figure()
fig3.savefig(rm_file + "_hist.png")
plt.close(fig3)
def cut_match_dict(genomic_seq, rm_ori_csv, begin=1, end=2, output="excised_matches.fa"):
"""
to cut the matches from genomic sequences according to coordinates in RepMask output file
counts matches per scaffold and rev-complements them if it is necessary
:param genomic_seq: *fa/*fna file with whole genome assembly or with scaffolds where matches have been found
:param rm_ori_csv: a *csv table from ori_to_csv()
:param begin: start of a match
:param end: end of a match
:param output: output file name (default "excised_matches.fa")
:return: writes fasta file with sequences of matches [extended & counted]
"""
print("Excision...")
genome_dict = dict()
# make genomic dictionary scaffold_name:SeqRecord
for rec in SeqIO.parse(genomic_seq, "fasta"):
genome_dict[rec.id] = rec
# open cleaned rm table
match_table = csv.reader(open(rm_ori_csv))
s = int(begin)
e = int(end)
match_list = []
# this is match counter
count = 1
# and name of 'previous' scaffold
previous = ''
# this skips the first row (header) of the CSV file
next(match_table)
#####################################################
# main block of code:
# here it counts matches in a scaffold, excises them
# and rev-complements if it is necessary
#####################################################
for row in match_table:
try:
scaffold = genome_dict[row[0]]
except KeyError:
print("Error: scaffold not found: %s" % str(row[0]))
else:
# here it counts matches per one scaffold
if row[0] == previous:
count += 1
else:
count = 1
previous = row[0]
# and here it makes match's SeqRecord
# define [and adjust] start and end coordinates
start = int(row[s])
if start <= 0:
start = 1
end = int(row[e])
if end > len(scaffold.seq):
end = len(scaffold.seq)
# get sequence of a match
match_seq = scaffold.seq[start - 1:end]
# rev comp it if "C"
if row[3] == "C":
match_seq == match_seq.reverse_complement()
descr = "-_%i_%i-%i" % (count, start, end)
else:
descr = "+_%i_%i-%i" % (count, start, end)
accession = scaffold.id
record = SeqRecord(match_seq, id=accession, description=descr)
match_list.append(record)
# write to a file
with open(output, 'w') as handle:
SeqIO.write(match_list, handle, 'fasta')
genome_dict.clear()
print("RM-matches excised...")
add_config("GetSeq Output", output)
def translate_match(matches_file):
"""
This script makes six translations and writes them into a file
Default translation table = 1 (standard)
:param matches_file: file with counted matches from previous function
:return: file with translations for RPS-Blast
"""
print("Translating...")
trans_list = list()
for seq_record in SeqIO.parse(matches_file, 'fasta'):
accession = seq_record.description
rc_sequence = seq_record.seq.reverse_complement()
# translating by all frames
for frame in range(3):
# for leading strand
orf = seq_record.seq[frame:]
protein = orf.translate()
record = SeqRecord(protein, id=accession, description='+%i' % frame)
trans_list.append(record)
# for reverse complement strand
rc_orf = rc_sequence[frame:]
rc_protein = rc_orf.translate()
rc_record = SeqRecord(rc_protein, id=accession, description='-%i' % frame)
trans_list.append(rc_record)
# write to file
handle = open('translations.faa', 'w')
SeqIO.write(trans_list, handle, 'fasta')
def bed_tools(rm_file, ref_genome, ori=False, expansion=0, output_prefix="excised_matches", bins=200):
"""
invokes bedtools suite to excise repeat matches
:param rm_file: RepeatMasker output file (*ori.out or *out)
:param ref_genome: genome assembly file
:param ori: if the RepeatMasker output is *ori.out or not (default: True)
:param expansion: merge nearby (within x bp) repetitive elements into a single entry.
:param output_prefix: prefix for the output file name (default "excised_matches")
:param bins: number of bins in a histogram
:return: there is no return :)
"""
# every time add MGE's name to any output
mge_name = read_config("RepeatType") + "_"
output_prefix = mge_name + output_prefix
if ori:
rm_file = rm_file[:-4] + ".ori.out"
print("Using *ori.out file with BEDtools")
ori2bed = "sed 's/^\s*//' %s | sed -E 's/\s+/\t/g' | cut -f5-9 | " \
"awk 'BEGIN { OFS=\"\t\" } { print $1, $2-1, $3, $4, $5}' | " \
"sed -E 's/\tC/\t-/g' | sed -E 's/\t\(/\tElement\t\(/g' | " \
"sort -k1,1 -k2,2n > temp.bed; mergeBed -s -d %s -i temp.bed > temp2.bed; mergeBed -i temp2.bed > " % (rm_file, str(expansion)) + "%s; rm temp.bed; rm temp2.bed" % (rm_file + ".bed")
os.system(ori2bed)
# sbp.call(["sh", "ori_to_bed.sh", rm_file, str(expansion)])
sbp.call(["bedtools", "getfasta", "-s", "-fi", ref_genome, "-bed", rm_file + ".bed", "-fo", output_prefix + str(expansion) + ".fa"])
else:
if rm_file[-3:] == "bed":
#print("bed-file detected")
sbp.call(["bedtools", "getfasta", "-s", "-fi", ref_genome, "-bed", rm_file + ".bed", "-fo", output_prefix + str(expansion) + ".fa"])
else:
print("Using RepeatMasker output with headers")
out2bed = "tail -n +4 %s | sed 's/^\s*//' | sed -E 's/\s+/\t/g' | cut -f5-9 | " \
"awk 'BEGIN { OFS=\"\t\" } { print $1, $2-1, $3, $4, $5}' | sed -E 's/\tC/\t-/g' | " \
"sed -E 's/\t\(/\tElement\t\(/g' | sort -k1,1 -k2,2n > " \
"temp.bed; mergeBed -s -d %s -i temp.bed > temp2.bed; mergeBed -i temp2.bed > " % (rm_file, str(expansion)) + "%s; rm temp.bed; rm temp2.bed" % (rm_file + ".bed")
os.system(out2bed)
# sbp.call(["sh", "out_to_bed.sh", rm_file, str(expansion)])
sbp.call(["bedtools", "getfasta", "-s", "-fi", ref_genome, "-bed", rm_file + ".bed", "-fo", output_prefix + str(expansion) + ".fa"])
# add output to the config
add_config("GetSeq Output", output_prefix + str(expansion) + ".fa")
# make plot
df = pd.read_table(rm_file + ".bed", header=None)
length = df[2] - df[1] + 1
plot2 = length.hist(color='g', alpha=0.5, bins=200)
plot2 = plt.xlabel("length, b.p.")
plot2 = plt.ylabel("count")
plot2 = plt.title("Histogram of consensus hits' lengths")
fig2 = plot2.get_figure()
fig2.savefig(output_prefix + str(expansion) + ".png")
plt.close(fig2)
# make some descriptive stats on lengths
des_stat = length.describe()
# write statistics to a file
des_stat.to_csv(output_prefix + str(expansion) + ".stats", header=False, index=True, sep="\t")
# print on the screen
#print("Excised matches:")
print(pd.DataFrame(des_stat))
def get_seq(pandas=False, merge=0, ori=False, rm_tab=""):
"""
this function cuts repeat sequences from a genome according to coords from repeat masker table.
it uses bedtools or pandas (the latter could be very slow).
:param pandas: logical, to use pandas or not. Default False.
:param merge: "merge all repeats within M bp into a single entry"
:param ori: "explicitly set that RepeatMasker output is *ori.out"
:param rm_tab: repeat masker table to use
:return: no
"""
if rm_tab == "":
repmask_out = read_config("RepeatMasker Output")
else:
repmask_out = rm_tab
genome = read_config("genome")
# remove '.gz' suffix
genome = genome[:-3]
#if '.gz' in genome:
# # remove '.gz' suffix
# genome = genome[:-3]
#else:
# print('The genome is not gzipped')
# d = os.getcwd()
if not os.path.isfile(repmask_out):
print("ERROR! File %s not found!" % repmask_out)
sys.exit()
elif not os.path.isfile(genome):
print("ERROR! File %s not found!" % genome)
sys.exit()
if pandas:
print("Using pandas library")
prfx = read_config("prefix")
ori_to_csv(repmask_out, expansion=merge)
cut_match_dict(genome, prfx + ".fa.cleaned.csv")
elif not ori:
bed_tools(repmask_out, genome, expansion=merge, ori=False)
elif ori:
bed_tools(repmask_out, genome, expansion=merge, ori=True)
print("Collecting sequences completed...")
# GetORF part
# def rps_blast(in_file, cdd, e_value=0.01, threads=1, outprefix="matches_w_hits", xml_prefix="hitdata", stat=True, check=False):
# """
# runs rpsblast on sequences from GetSeq; the output set to xml.
# then the script gets all CD hits and writes them to a file. Also plots a histogram of hit's lengths distribution
# :param in_file: input file for RPS-BLAST - fasta file from GetSeq
# :param cdd: path to local Conserved Domain Database (CDD), including index name
# :param e_value: expectation value (E), default 0.01
# :param threads: number of threads to use, default 1
# :param outprefix: prefix of the output file name
# :param xml_prefix: prefix of xml file (rpsblastn output)
# :param stat: make descriptive statistics (only when check=False)
# :param check: make just ORFs checking
# :return: no return
# """
# # add MGE's name to any output
# mge_name = read_config("RepeatType") + "_"
# if not check:
# outprefix = mge_name + outprefix
#
# xml_prefix = mge_name + xml_prefix
#
# print("run RPS-BLAST...")
# # print("CDD location set as %s" % cdd)
# xml_file = xml_prefix + str(e_value)[2:] + ".xml"
#
# # for rpsblast 2.6.0+
# # rpsblast -db RTCDD/RT -query excised_matches.fa -out test.fmt5 -evalue 0.01 -outfmt 5 -num_threads 12
# # sbp.call(["rpsblast", "-i", in_file, "-p", "F", "-d", cdd, "-e", str(e_value), "-m 7", "-l", "log", "-a", str(threads), "-o", xml_file])
#
# sbp.call(["rpstblastn", "-db", cdd, "-query", in_file, "-out", xml_file, "-evalue", str(e_value), "-outfmt", "5", "-num_threads", str(threads)])
# if not check:
# # add to config only if it is not ORF checking
# add_config(unit="GetORF Output", val=xml_file)
#
# try:
# hits_only = [item.query for item in NCBIXML.parse(open(xml_file)) if item.alignments]
# if len(hits_only) == 0:
# print("No sequences with hits found! Exit.")
# sys.exit()
# else:
# print("Found %i sequences with hits." % len(hits_only))
# except FileNotFoundError:
# print("ERROR! File %s not found!" % xml_file)
# sys.exit()
#
# # make dictionary excised_match:SeqRecord
# dna_dict = dict()
# for record in SeqIO.parse(in_file, "fasta"):
# dna_dict[record.description] = record
#
# # collect dna sequences with hits to a new list
# # note that last 3 symbols are cropped
# hits_only_dna = [dna_dict[item] for item in hits_only]
#
# if stat:
# # make some stat and plots (not for check only)
# hits_len = pd.Series([len(item) for item in hits_only_dna])
# plot = hits_len.hist(color='g', alpha=0.5, bins=200)
# fig = plot.get_figure()
# fig.savefig(outprefix + "_e" + str(e_value)[2:] + ".png")
# plt.close(fig)
# des_stat = hits_len.describe()
# # write statistics to a file
# des_stat.to_csv(outprefix + "_e" + str(e_value)[2:] + ".stats", header=False, index=True, sep="\t")
# # print on the screen
# print("Statistics of excised matches' length:")
# print(pd.DataFrame(des_stat))
#
# # make output name
# # if runs as part of check_orfs()
# if not check:
# matches_fname = outprefix + "_e" + str(e_value)[2:] + ".fa"
# # add to config matches with hits, but not checked ORFs!
# add_config("ORFinder Input", matches_fname)
# else:
# matches_fname = outprefix + ".fa"
#
# with open(matches_fname, 'w') as handle:
# SeqIO.write(hits_only_dna, handle, 'fasta')
# # print("Done!")
def rps_blast(in_file, cdd, smp_table='', e_value=0.01, threads=1, outprefix="matches_w_hits", xml_prefix="hitdata", stat=True, check=False):
"""
runs rpsblast on sequences from GetSeq; the output set to xml.
then the script gets all CD hits and writes them to a file. Also plots a histogram of hit's lengths distribution
:param in_file: input file for RPS-BLAST - fasta file from GetSeq
:param cdd: path to local Conserved Domain Database (CDD), including index name
:param smp_table: csv table of SMP files groupings
:param e_value: expectation value (E), default 0.01
:param threads: number of threads to use, default 1
:param outprefix: prefix of the output file name
:param xml_prefix: prefix of xml file (rpsblastn output)
:param stat: make descriptive statistics (only when check=False)
:param check: make just ORFs checking
:return: no return
"""
# add MGE's name to any output
mge_name = read_config("RepeatType") + "_"
if not check:
outprefix = mge_name + outprefix
xml_prefix = mge_name + xml_prefix
print("running RPS-BLAST...")
# print("CDD location set as %s" % cdd)
xml_file = xml_prefix + str(e_value)[2:] + ".xml"
# for rpsblast 2.6.0+
# rpsblast -db RTCDD/RT -query excised_matches.fa -out test.fmt5 -evalue 0.01 -outfmt 5 -num_threads 12
# sbp.call(["rpsblast", "-i", in_file, "-p", "F", "-d", cdd, "-e", str(e_value), "-m 7", "-l", "log", "-a", str(threads), "-o", xml_file])
# read a table of CD groupings (assume it is tab delimited)
# cdgroups = "doms.txt"
def read_and_guess(tabfile):
"""
A function to read CSV file adn to guess the delimiter
:param tabfile: csv file
:return: csv file as a list of rows
"""
with open(tabfile, 'r') as f:
dialect = csv.Sniffer().sniff(f.read(1024), delimiters="\t,")
f.seek(0)
reader = csv.reader(f, dialect)
tab = [r for r in reader]
return tab
if smp_table == '':
try:
group_tab = read_and_guess(read_config('cd_table'))
#reader = csv.reader(open(read_config('cd_table')))
except KeyError:
print("No smp table found in the config file!")
smptable = input("Type a path to smp table > ")
#reader = csv.reader(open(smptable))
group_tab = read_and_guess(read_config('cd_table'))
else:
group_tab = read_and_guess(smp_table)
#reader = csv.reader(open(smp_table))
#group_tab = [row for row in reader]
group_label = set([row[1] for row in group_tab])
group_dict = {}
for l in group_label:
group_dict[l]=[r[0] for r in group_tab if l in r[1]]
print("Command:\n")
print('rpstblastn -db %s -query %s -out %s -evalue %i -outfmt 5 -num_threads %i' %(cdd, in_file, xml_file, e_value, threads))
sbp.call(["rpstblastn", "-db", cdd, "-query", in_file, "-out", xml_file, "-evalue", str(e_value), "-outfmt", "5", "-num_threads", str(threads)])
if not check:
# add to config only if it is not ORF checking
add_config(unit="GetORF Output", val=xml_file)
try:
#hits_only = [item.query for item in NCBIXML.parse(open(xml_file)) if item.alignments]
hits_only = []
for record in NCBIXML.parse(open(xml_file)):
if record.alignments:
hits = []
for align in record.alignments:
hits.append(align.title)
# leave only the name of a CD file that produced a hit
# based on assumption that all 'title' start from 'gnl|CDD|123456 '
hits = [re.findall('^gnl\|CDD\|[0-9]* ([a-z,A-Z]*[0-9]*), ', hit)[0] for hit in hits]
# now I need to check for each CD label if any of its SMP present in 'hits' list
hits_counter = 0
for key in group_dict.keys():
for smp in group_dict[key]:
if smp[:-4] in hits:
hits_counter += 1
break
continue
if hits_counter == len(group_dict.keys()):
# all CDs were found in this record!
hits_only.append(record.query)
if len(hits_only) == 0:
print("No sequences with specified number of hits found!\nTry to search for one CD.\nExit.")
sys.exit()
else:
print("Found %i sequences with %i hits." %(len(hits_only), len(group_label)))
except FileNotFoundError:
print("ERROR! File %s not found!" % xml_file)
sys.exit()
# make dictionary excised_match:SeqRecord