-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMCHelper.py
More file actions
3410 lines (3043 loc) · 178 KB
/
MCHelper.py
File metadata and controls
3410 lines (3043 loc) · 178 KB
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
"""
Manual Curation Helper Version 1.7.1
Novelties:
* Added recovery mode for the BEE step
* Corrected bug when fail opening the TE+Aid plot in manual inspection module
"""
import sys
import os
import io
import re
import argparse
import pandas as pd
import multiprocessing
from pdf2image import convert_from_path
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import subprocess
import cv2
from matplotlib import pyplot as plt
# import matplotlib
# matplotlib.use('WebAgg')
import psutil
import glob
import shutil
import time
import numpy as np
import math
from sklearn.cluster import DBSCAN
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
dicc_orders = {2: "LTR", 3: "COPIA", 4: "GYPSY", 5: "BELPAO", 6: "ERV", 7: "TRIM", 8: "LARD", 9: "LINE", 10: "SINE",
11: "R2", 12: "RTE", 13: "JOCKEY", 14: "L1", 15: "I", 16: "R1", 17: "CR1", 18: "LOA", 19: "L2",
20: "PLE",
21: "DIRS", 22: "NGARO", 23: "VIPER", 24: "TIR", 25: "MITE", 26: "TC1MARINER", 27: "HAT", 28: "MUTATOR",
29: "MERLIN", 30: "TRANSIB", 31: "P", 32: "PIGGYBAC", 33: "PIFHARBINGER", 34: "CACTA", 35: "MULE",
36: "CMC", 37: "HELITRON", 38: "MAVERICK", 39: "CRYPTON", 40: "UNCLASSIFIED", 41: "CLASSI",
42: "CLASSII"}
orders_superfamilies = [x for x in dicc_orders.values()]
def write_sequences_file(sequences, filename):
try:
SeqIO.write(sequences, filename, "fasta")
except FileNotFoundError:
print("FATAL ERROR: I couldn't find the file, please check: '" + filename + "'. Path not found")
sys.exit(0)
except PermissionError:
print("FATAL ERROR: I couldn't access the files, please check: '" + filename + "'. I don't have permissions.")
sys.exit(0)
except Exception as exp:
print("FATAL ERROR: There is a unknown problem writing sequences in : '" + filename + "'.")
print(exp)
sys.exit(0)
def create_output_folders(folder_path):
try:
if not os.path.exists(folder_path):
os.mkdir(folder_path)
except FileNotFoundError:
print("FATAL ERROR: I couldn't create the folder " + folder_path + ". Path not found")
sys.exit(0)
except PermissionError:
print("FATAL ERROR: I couldn't create the folder " + folder_path + ". I don't have permissions.")
sys.exit(0)
def delete_files(file_path):
if os.path.exists(file_path):
try:
os.remove(file_path)
except PermissionError:
print("WARNING: The file " + file_path + " couldn't be removed because I don't have permissions.")
def filter_flf(ref_tes, flf_file, minFullLenFragments, outputdir):
flf_lines = open(flf_file, 'r').readlines()[1:]
seqsID_with_flf = [s.split("\t")[0] for s in flf_lines]
seqs_with_flf = []
numCopies = {}
for te in SeqIO.parse(ref_tes, "fasta"):
seq_name = str(te.id).split("#")[0]
if seq_name in seqsID_with_flf:
numfullCopies = int([s.split("\t")[6] for s in flf_lines if s.split("\t")[0] == seq_name][0])
numfullFrags = int([s.split("\t")[4] for s in flf_lines if s.split("\t")[0] == seq_name][0])
if numfullFrags >= minFullLenFragments: # number of copies greater or equal than threshold?
seqs_with_flf.append(te)
numCopies[seq_name] = [numfullFrags, numfullCopies]
write_sequences_file(seqs_with_flf, outputdir + "/cons_flf.fa")
return outputdir + "/cons_flf.fa", numCopies
def processing_gff(seqname, gff_files, pre):
posBlan = []
postBlax = []
posBlax = []
posTR = []
gff_blastn = open(gff_files + '/' + pre + '_TE_BLRn.gff3', 'r').readlines()
for anno in gff_blastn:
columns = anno.split('\t')
# if columns[0] == seqname and columns[2] == 'TE_BLRn':
if columns[0] == seqname and columns[2] == 'exon':
posBlan.append((int(columns[3]), int(columns[4]) - int(columns[3])))
gff_tblastx = open(gff_files + '/' + pre + '_TE_BLRtx.gff3', 'r').readlines()
for anno in gff_tblastx:
columns = anno.split('\t')
# if columns[0] == seqname and columns[2] == 'TE_BLRtx':
if columns[0] == seqname and columns[2] == 'exon':
postBlax.append((int(columns[3]), int(columns[4]) - int(columns[3])))
gff_blastx = open(gff_files + '/' + pre + '_TE_BLRx.gff3', 'r').readlines()
for anno in gff_blastx:
columns = anno.split('\t')
# if columns[0] == seqname and columns[2] == 'TE_BLRx':
if columns[0] == seqname and columns[2] == 'exon':
posBlax.append((int(columns[3]), int(columns[4]) - int(columns[3])))
gff_tr = open(gff_files + '/' + pre + '_TR.gff3', 'r').readlines()
for anno in gff_tr:
columns = anno.split('\t')
if columns[0] == seqname and columns[2] == 'exon':
posTR.append((int(columns[3]), int(columns[4]) - int(columns[3])))
return posBlan, postBlax, posBlax, posTR
def count_flf_fasta(ref_tes, genome, cores, outputdir):
if not os.path.exists(outputdir + "/fullLengthFrag.txt"):
create_output_folders(outputdir)
flf_df = pd.DataFrame(columns=['TE', 'length', 'covg', 'frags', 'fullLgthFrags', 'copies', 'fullLgthCopies'])
if not os.path.exists(genome + ".nhr"):
output = subprocess.run(
['makeblastdb', '-in', genome, '-dbtype', 'nucl'], stdout=subprocess.PIPE, text=True)
output = subprocess.run(
['blastn', '-query', ref_tes, '-db', genome, '-out', outputdir + "/TEs_vs_genome.blast", '-num_threads',
str(cores), "-outfmt", "6 qseqid length", "-evalue", "10e-8"], stdout=subprocess.PIPE, text=True)
blastresult = pd.read_table(outputdir + "/TEs_vs_genome.blast", sep='\t', names=['qseqid', 'length'])
for te in SeqIO.parse(ref_tes, "fasta"):
seq_name = str(te.id).split("#")[0]
te_hits = blastresult[blastresult.qseqid == str(te.id)].reset_index()
count_frag = 0
count_flf = 0
te_len = len(str(te.seq))
for i in range(te_hits.shape[0]):
len_hit = te_hits.loc[i, 'length']
if len_hit >= (te_len * 0.94): # it's a full-length fragment
count_flf += 1
else:
count_frag += 1
flf_df = pd.concat([flf_df, pd.DataFrame(
{'TE': seq_name, 'length': [te_len], 'covg': [0], 'frags': [count_frag], 'fullLgthFrags': [count_flf],
'copies': [count_frag], 'fullLgthCopies': [count_flf]})], ignore_index=True)
flf_df.to_csv(outputdir + "/fullLengthFrag.txt", header=True, sep='\t', index=False)
delete_files(outputdir + "/TEs_vs_genome.blast")
else:
print("MESSAGE: Full-length file was already created, please verify or change the output directory")
return outputdir + "/fullLengthFrag.txt"
def checkChrNames(genome_file):
Ids = [x.id.isdigit() for x in SeqIO.parse(genome_file, "fasta")]
if True in Ids:
return False
else:
return True
def check_classification_Userlibrary(user_library, outputdir):
ids_no_contained = []
reasons = []
fine_tes = []
for te in SeqIO.parse(user_library, "fasta"):
if "#" not in str(te.id): # it doesn't have the correct format
ids_no_contained.append(te.id)
reasons.append(
"The sequence ID doesn't have the character '#' needed to separate the ID to the classification")
elif len(str(te.id).split("#")[1].split("/")) > 3:
ids_no_contained.append(te.id)
reasons.append(
"The sequence ID has more than 3 levels of classification. I can work with the following formats:\n 1) Class/Order/Superfamily\n 2) Order/Superfamily\n Class/Order\n 3) order or superfamily")
else:
classification = str(te.id).split("#")[1].upper().replace("-", "")
if len(classification.split("/")) == 3:
# The most complete case Class / order / superfamily
order_given = classification.split("/")[1]
superfamily = classification.split("/")[2]
elif len(classification.split("/")) == 2:
# The most common case: Class / Order or order / superfamily
order_given = classification.split("/")[0]
superfamily = classification.split("/")[1]
elif len(classification.split("/")) == 1:
# the most incomplete but still fine to work with: only the order or superfamily is provided
order_given = classification
superfamily = "NA"
if superfamily not in orders_superfamilies and order_given not in orders_superfamilies:
# Maybe is it Repbase/Dfam taxonomy?
if "UNKNOWN" in classification:
te.id = te.id.split("#")[0] + "#Unclassified"
te.description = ""
fine_tes.append(te)
elif "DNA" in classification:
classification = classification.replace("DNA", "TIR")
te.id = te.id.split("#")[0] + "#" + classification
te.description = ""
fine_tes.append(te)
else:
ids_no_contained.append(te.id)
reasons.append(
"The classification wasn't find in my classification system. Remember that I use the Wicker nomenclature.")
else:
fine_tes.append(te)
# Checking that there is no duplicated sequences
duplicates = False
if len(fine_tes) != len(list(set([x.id for x in fine_tes]))):
freq = {}
for TE in fine_tes:
freq[TE.id] = freq.get(TE.id, 0) + 1
if freq[TE.id] > 1:
ids_no_contained.append(TE.id)
reasons.append("Duplicated sequence ID")
duplicates = True
write_sequences_file(fine_tes, outputdir + "/candidate_tes.fa")
if len(ids_no_contained) == 0: # Congrats!! everything looks great!
return 0
else:
output_file = open(outputdir + "/sequences_with_problems.txt", "w")
output_file.write("Sequence ID\tProblem\n")
for i in range(len(ids_no_contained)):
output_file.write(ids_no_contained[i] + "\t" + reasons[i] + "\n")
if duplicates:
return -2
return -1
def check_repet_input_folder(repet_input_dir, proj_name):
ref_tes = repet_input_dir + "/" + proj_name + "_refTEs.fa"
# flf_file = repet_input_dir + "/TEannot/" + proj_name + "_chr_allTEs_nr_noSSR_join_path.annotStatsPerTE_FullLengthFrag.txt"
features_table = repet_input_dir + "/" + proj_name + "_denovoLibTEs_PC.classif"
plots_dir = repet_input_dir + "/plotCoverage"
gff_files = repet_input_dir + "/gff_reversed"
if not os.path.exists(repet_input_dir):
valid = False
reason = "FATAL ERROR: " + repet_input_dir + " does not exist. Please check the path and re-run the software"
elif not os.path.exists(ref_tes):
valid = False
reason = "FATAL ERROR: " + ref_tes + " does not exist. Please check the path and re-run the software"
elif os.path.getsize(ref_tes) == 0:
valid = False
reason = "FATAL ERROR: " + ref_tes + " is empty. Please check the file and re-run the software"
# elif not os.path.exists(flf_file):
# valid = False
# reason = "FATAL ERROR: "+flf_file+" does not exist. Please check the path and re-run the software"
# elif os.path.getsize(flf_file) == 0:
# valid = False
# reason = "FATAL ERROR: "+flf_file+" is empty. Please check the file and re-run the software"
elif not os.path.exists(features_table):
valid = False
reason = "FATAL ERROR: " + features_table + " does not exist. Please check the path and re-run the software"
elif os.path.getsize(features_table) == 0:
valid = False
reason = "FATAL ERROR: " + features_table + " is empty. Please check the file and re-run the software"
elif not os.path.exists(plots_dir):
valid = False
reason = "FATAL ERROR: " + plots_dir + " does not exist. Please check the path and re-run the software"
elif not os.path.exists(gff_files):
valid = False
reason = "FATAL ERROR: " + gff_files + " does not exist. Please check the path and re-run the software"
else:
# In this case, everything is ok to run the curation process !!
valid = True
reason = ""
return valid, reason
def find_TRs2(te, outputdir, minLTR, minTIR, minpolyA, cores):
lenLTR = 0
lenTIR = 0
lenPolyA = 0
mismatches = minpolyA // 8
if te.seq[:minpolyA + mismatches].upper().count("A") >= minpolyA:
lenPolyA = max(lenPolyA, te.seq[:minpolyA + mismatches].upper().count("A") + len(
re.match("(.*?)[^A]", str(te.seq)[minpolyA:]).group()) - 2)
if te.seq[:minpolyA + mismatches].upper().count("T") >= minpolyA:
lenPolyA = max(lenPolyA, te.seq[:minpolyA + mismatches].upper().count("T") + len(
re.match("(.*?)[^T]", str(te.seq)[minpolyA:]).group()) - 2)
if te.seq[-(minpolyA + mismatches):].upper().count("A") >= minpolyA:
lenPolyA = max(lenPolyA, te.seq[-(minpolyA + mismatches):].upper().count("A") + len(
re.match("(.*?)[^A]", str(te.seq)[:len(te.seq) - minpolyA][::-1]).group()) - 2)
if te.seq[-(minpolyA + mismatches):].upper().count("T") >= minpolyA:
lenPolyA = max(lenPolyA, te.seq[-(minpolyA + mismatches):].upper().count("T") + len(
re.match("(.*?)[^T]", str(te.seq)[:len(te.seq) - minpolyA][::-1]).group()) - 2)
seq_name = str(te.id).split("#")[0]
write_sequences_file(te, outputdir + "/temp/" + seq_name + ".fa")
output = subprocess.run(['makeblastdb', '-in', outputdir + "/temp/" + seq_name + ".fa", '-dbtype', 'nucl'],
stdout=subprocess.PIPE, text=True)
output = subprocess.run([
"blastn -query " + outputdir + "/temp/" + seq_name + ".fa -db " + outputdir + "/temp/" + seq_name + ".fa -num_threads " + str(
cores) + " -outfmt \"6 qseqid qstart qend sstart send\" -word_size 11 -gapopen 5 -gapextend 2 -reward 2 -penalty -3 | sed 's/#/-/g' > " + outputdir + "/temp/" + str(
seq_name) + ".blast"], shell=True)
blastresult = pd.read_table(outputdir + "/temp/" + str(seq_name) + ".blast", sep='\t',
names=['qseqid', 'qstart', 'qend', 'sstart', 'send'],
dtype={'qseqid': str, 'qstart': int, 'qend': int, 'sstart': int, 'send': int})
blastHits = blastresult.shape[0]
if blastresult.shape[0] > 1:
blastresult = blastresult[1:]
blastresult["len"] = abs(blastresult["qend"] - blastresult["qstart"])
ltr_check = blastresult[
(((blastresult.qend - blastresult.qstart) * (blastresult.send - blastresult.sstart)) > 0)
& (blastresult[['qstart', 'qend', 'sstart', 'send']].min(axis=1) < len(te) * 0.1)
& (blastresult[['qstart', 'qend', 'sstart', 'send']].max(axis=1) > len(te) * 0.9)]
try:
lenLTR = max(ltr_check[ltr_check.len >= minLTR].len)
except:
lenLTR = 0
tir_check = blastresult[
(((blastresult.qend - blastresult.qstart) * (blastresult.send - blastresult.sstart)) < 0)
& (blastresult[['qstart', 'qend', 'sstart', 'send']].min(axis=1) < len(te) * 0.1)
& (blastresult[['qstart', 'qend', 'sstart', 'send']].max(axis=1) > len(te) * 0.9)]
try:
lenTIR = max(tir_check[tir_check.len >= minTIR].len)
except:
lenTIR = 0
return lenLTR, lenTIR, lenPolyA, blastHits
def find_profiles(te, outputdir, ref_profiles):
# domains: LTR retrotransposons/LINE DIRS/Crypton
domains_dict = {'_GAG_': 0, '_AP_': 0, '_INT_': 0, '_RT_': 0, '_RNaseH_': 0, '_ENV_': 0, '_PhageINT_': 0,
# PLE TIRs Helitron
'_EN_': 0, '_Tase_': 0, '_HEL_': 0, '_RPA_': 0, '_REP_': 0, '_OTU_': 0, '_SET_': 0,
# Maverick
'_Prp': 0, '_ATPase_': 0}
seq_name = str(te.id).split("#")[0]
write_sequences_file(te, outputdir + "/" + seq_name + "_putative_te.fa")
output = subprocess.run(
['getorf', '-sequence', outputdir + "/" + seq_name + "_putative_te.fa", '-minsize', '300', '-outseq',
outputdir + "/" + seq_name + "_putative_te_orf.fa"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
output = subprocess.run(
['hmmscan', '--tblout', outputdir + "/" + seq_name + "_profiles_found.hmm", '-E', '10', '--noali', '--cpu',
'1', ref_profiles, outputdir + "/" + seq_name + "_putative_te_orf.fa"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
result = ""
struc_domains = ""
if os.path.exists(outputdir + "/" + seq_name + "_profiles_found.hmm"):
command = 'grep -v "^#" ' + outputdir + '/' + seq_name + '_profiles_found.hmm | wc -l'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
hits = int(process.stdout.read())
if hits > 0:
command = 'grep -v "^#" ' + outputdir + '/' + seq_name + '_profiles_found.hmm | sed "s/_RVT_/_RT_/g" | awk \'{print $1"\t"$2"\t"$3"\t"$4"\t"$5"\t"$6"\t"$7"\t"$8"\t"$9"\t"$10}\' > ' + outputdir + "/" + seq_name + "_profiles_found.hmm_formatted"
process = subprocess.Popen(command, shell=True)
process.communicate()
hmm_results = pd.read_table(outputdir + "/" + seq_name + "_profiles_found.hmm_formatted", sep='\t',
names=['domain', 'acc', 'orf', 'acc_orf', 'evalue', 'score', 'A', 'B', 'C',
'D'])
hasDomains = False
for domain in domains_dict.keys():
best_hit = hmm_results[hmm_results.domain.str.contains(domain)].reset_index()
if best_hit.shape[0] > 0:
hasDomains = True
domains_dict[domain] = best_hit.loc[0, 'evalue']
result += best_hit.loc[0, 'domain'] + ": " + str(best_hit.loc[0, 'evalue']) + ", "
struc_domains += domain.replace("_", "") + " "
if hasDomains:
result = "profiles: " + result[:-2]
delete_files(outputdir + "/" + seq_name + "_profiles_found.hmm_formatted")
delete_files(outputdir + "/" + seq_name + "_profiles_found.hmm")
delete_files(outputdir + "/" + seq_name + "_putative_te_orf.fa")
delete_files(outputdir + "/" + seq_name + "_putative_te.fa")
return result, struc_domains
def find_blast_hits(te, outputdir, blastx_db, blastn_db):
seq_name = str(te.id).split("#")[0]
write_sequences_file(te, outputdir + "/" + seq_name + "_putative_te.fa")
output = subprocess.run(
['blastx', '-query', outputdir + "/" + seq_name + "_putative_te.fa", '-db', blastx_db, '-out',
outputdir + "/" + seq_name + "_putative_te.fa.blastx", '-num_threads', '1', "-outfmt",
"6 sseqid pident evalue bitscore"],
stdout=subprocess.PIPE, text=True)
blastresult = pd.read_table(outputdir + "/" + seq_name + "_putative_te.fa.blastx", sep='\t',
names=['sseqid', 'pident', 'evalue', 'bitscore'])
blastx_result = ""
i = 0
if blastresult.shape[0] > 0:
blastx_result = "TE_BLRx: "
while i < 3 and i < blastresult.shape[0]:
blastx_result += blastresult.loc[0, "sseqid"] + ": " + str(blastresult.loc[0, "pident"]) + "%, "
i += 1
blastx_result = blastx_result[:-2]
output = subprocess.run(
['tblastx', '-query', outputdir + "/" + seq_name + "_putative_te.fa", '-db', blastn_db, '-out',
outputdir + "/" + seq_name + "_putative_te.fa.tblastx", '-num_threads', '1', "-outfmt",
"6 sseqid pident evalue bitscore"],
stdout=subprocess.PIPE, text=True)
blastresult = pd.read_table(outputdir + "/" + seq_name + "_putative_te.fa.tblastx", sep='\t',
names=['sseqid', 'pident', 'evalue', 'bitscore'])
blasttx_result = ""
i = 0
if blastresult.shape[0] > 0:
blasttx_result = "TE_BLRtx: "
while i < 3 and i < blastresult.shape[0]:
blasttx_result += blastresult.loc[0, "sseqid"] + ": " + str(blastresult.loc[0, "pident"]) + "%, "
i += 1
blasttx_result = blasttx_result[:-2]
delete_files(outputdir + "/" + seq_name + "_putative_te.fa")
delete_files(outputdir + "/" + seq_name + "_putative_te.fa.tblastx")
delete_files(outputdir + "/" + seq_name + "_putative_te.fa.blastx")
return blastx_result, blasttx_result
def build_class_table_parallel(ref_tes, cores, outputdir, blastn_db, blastx_db, ref_profiles, do_blast):
if not os.path.exists(outputdir + "/denovoLibTEs_PC.classif"):
tes = [te for te in SeqIO.parse(ref_tes, "fasta")]
n = len(tes)
seqs_per_procs = int(n / cores)
remain = n % cores
ini_per_thread = []
end_per_thread = []
# indexing the Pfam database if needed
if not os.path.exists(ref_profiles + ".h3m"):
output = subprocess.run(['hmmpress', ref_profiles],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
for p in range(cores):
if p < remain:
init = p * (seqs_per_procs + 1)
end = n if init + seqs_per_procs + 1 > n else init + seqs_per_procs + 1
else:
init = p * seqs_per_procs + remain
end = n if init + seqs_per_procs > n else init + seqs_per_procs
ini_per_thread.append(init)
end_per_thread.append(end)
# Run in parallel the checking
pool = multiprocessing.Pool(processes=cores)
create_output_folders(outputdir + "/temp")
localresults = [pool.apply_async(build_class_table,
args=[tes[ini_per_thread[x]:end_per_thread[x]], ref_profiles, outputdir,
blastn_db,
blastx_db, do_blast, cores]) for x in range(cores)]
local_dfs = [p.get() for p in localresults]
class_df = pd.DataFrame(
columns=['Seq_name', 'length', 'strand', 'confused', 'class', 'order', 'Wcode', 'sFamily', 'CI', 'coding',
'struct', 'other'])
for i in range(len(local_dfs)):
class_df = pd.concat([class_df, local_dfs[i]], ignore_index=True)
pool.close()
class_df.to_csv(outputdir + "/denovoLibTEs_PC.classif", header=True, sep='\t', index=False)
new_tes_user = []
for te in SeqIO.parse(ref_tes, "fasta"):
te.id = str(te.id).split("#")[0]
te.description = ""
new_tes_user.append(te)
os.system("rm -r " + outputdir + "/temp")
write_sequences_file(new_tes_user, outputdir + "/new_user_lib.fa")
else:
print("MESSAGE: TE Feature table was already created, please verify or change the output directory")
def build_class_table(ref_tes, ref_profiles, outputdir, blastn_db, blastx_db, do_blast, cores):
class_df = pd.DataFrame(
columns=['Seq_name', 'length', 'strand', 'confused', 'class', 'order', 'Wcode', 'sFamily', 'CI', 'coding',
'struct', 'other'])
orders = ['LTR', 'TRIM', 'LARD', 'LINE', 'SINE', 'PLE', 'DIRS', 'TIR', 'MITE', 'HELITRON', 'MAVERICK', 'CRYPTON']
superfamilies = ["COPIA", "GYPSY", "BELPAO", "ERV", "PLE", "DIRS", "NGARO", "VIPER", "R2", "RTE", "JOCKEY", "L1",
"I", "R1", "CR1", "LOA", "L2", "SINE", "TC1MARINER", "HAT", "MUTATOR", "MERLIN", "TRANSIB", "P",
"PIGGYBAC", "PIFHARBINGER", "CACTA", "MULE", "CMC", "MITE", "HELITRON", "MAVERICK", "CRYPTON"]
classes = ["CLASSI", "CLASSII", "RETROTRANSPOSON", "TRANSPOSON"]
for te in ref_tes:
seq_name = str(te.id).split("#")[0]
classification = str(te.id).split("#")[1].upper().replace("-", "")
length = len(str(te.seq))
class_given = ""
if len(classification.split("/")) == 3:
# The most complete case Class / order / superfamily
class_given = classification.split("/")[0]
order_given = classification.split("/")[1]
superfamily = classification.split("/")[2]
elif len(classification.split("/")) == 2:
# The most common case Class / Order or order / superfamily
order_given = classification.split("/")[0]
superfamily = classification.split("/")[1]
if superfamily in orders and order_given in classes: # it's the form Class / order
class_given = order_given
order_given = superfamily
superfamily = "NA"
elif len(classification.split("/")) == 1:
# the most incomplete but still fine to work with
order_given = classification
if order_given in superfamilies: # it's a superfamily
superfamily = order_given
elif order_given in classes: # it's a class
class_given = order_given
order_given = "NA"
superfamily = "NA"
else: # it's actually an order
superfamily = "NA"
if superfamily in superfamilies:
# superfamily found !!!
sFamily = superfamily
order = ""
sFamily_index = superfamilies.index(superfamily)
if sFamily_index <= 3:
order = "LTR"
elif sFamily_index == 4:
order = "PLE"
elif sFamily_index >= 5 and sFamily_index <= 7:
order = "DIRS"
elif sFamily_index >= 8 and sFamily_index <= 16:
order = "LINE"
elif sFamily_index == 17:
order = "SINE"
elif sFamily_index >= 18 and sFamily_index <= 28:
order = "TIR"
elif sFamily_index == 29:
order = "MITE"
elif sFamily_index == 30:
order = "Helitron"
elif sFamily_index == 31:
order = "Maverick"
elif sFamily_index == 32:
order = "Crypton"
if sFamily_index <= 17:
classTE = "CLASSI"
else:
classTE = "CLASSII"
elif order_given in orders:
# Well, superfamily didn't find, but I found the order
sFamily = "NA"
order = order_given
orden_index = orders.index(order)
if orden_index <= 6:
classTE = "CLASSI"
else:
classTE = "CLASSII"
elif class_given != "":
classTE = class_given
order = "NA"
sFamily = "NA"
else:
# print("WARNING: I didn't find the superfamily, neither the order: "+order_given+"/"+superfamily)
classTE = "Unclassified"
order = "Unclassified"
sFamily = "Unclassified"
lenLTR, lenTIR, lenPolyA, blastHits = find_TRs2(te, outputdir, 10, 10, 10, cores)
profiles, struc_dom = find_profiles(te, outputdir, ref_profiles)
if do_blast:
blastx, blasttx = find_blast_hits(te, outputdir, blastx_db, blastn_db)
else:
blastx, blasttx = "", ""
terminals = ''
terminals_list = []
if lenLTR > 0:
terminals_list.append("termLTR: " + str(lenLTR))
if lenTIR > 0:
terminals_list.append("termTIR: " + str(lenTIR))
if lenPolyA > 0:
terminals_list.append("polyAtail: " + str(lenPolyA))
if len(terminals_list) > 0:
terminals = 'TermRepeats: ' + ' '.join(terminals_list) + ';'
final_coding_string = ""
if blasttx != "":
final_coding_string = blasttx + "; "
if blastx != '':
final_coding_string += blastx + ";"
if profiles != "":
final_coding_string += profiles
if blastx == "" and blasttx == "" and profiles == "":
final_coding_string = "NA"
### Heuristcs to purge simple repeats and chimeric elements
other = 'other=NA'
if blastHits > 40: ### MAGIC NUMBER; INCLUDE AS OPTIONAL PARAMETHER
other = 'other=Satellites/Simple Repeats found'
elif lenLTR > length * 0.35: ### MAGIC NUMBER; INCLUDE AS OPTIONAL PARAMETHER
other = 'other=Chimeric evidence found'
class_df = pd.concat([class_df, pd.DataFrame(
{'Seq_name': seq_name, 'length': [length], 'strand': '+', 'confused': 'False', 'class': classTE,
'order': order, 'Wcode': 'NA', 'sFamily': sFamily, 'CI': [0],
'coding': 'coding=(' + final_coding_string + ')',
'struct': 'struct=(TElength: ' + str(length) + 'bps; ' + terminals + ' ' + struc_dom + ')',
'other': other})], ignore_index=True)
return class_df
def count_domains_by_order(profiles, order):
right_doms = 0
other_doms = 0
if order == "LINE":
right_doms = len(
[x for x in profiles.split(",") if '_RT_' in x or '_EN_' in x or '_RNaseH_' in x or '_GAG_' in x])
other_doms = len([x for x in profiles.split(",") if '_AP_' in x or '_INT_' in x or '_ENV_' in x or '_Tase_' in x
or '_HEL_' in x or '_RPA_' in x or '_REP_' in x or '_OTU_' in x or '_SET_' in x or '_Prp' in x
or '_ATPase_' in x or '_PhageINT_' in x])
elif order == "LTR":
right_doms = len([x for x in profiles.split(",") if
'_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x or '_RNaseH_' in x or '_ENV_' in x])
other_doms = len([x for x in profiles.split(",") if '_EN_' in x or '_Tase_' in x or '_HEL_' in x or '_RPA_' in x
or '_REP_' in x or '_OTU_' in x or '_SET_' in x or '_Prp' in x or '_ATPase_' in x or '_PhageINT_' in x])
elif order == "DIRS":
right_doms = len([x for x in profiles.split(",") if
'_GAG_' in x or '_RT_' in x or '_RNaseH_' in x or '_PhageINT_' in x])
other_doms = len([x for x in profiles.split(",") if '_AP_' in x or '_INT_' in x or '_ENV_' in x or '_EN_' in x
or '_Tase_' in x or '_HEL_' in x or '_RPA_' in x or '_REP_' in x or '_OTU_' in x or '_SET_'
in x or '_Prp' in x or '_ATPase_' in x])
elif order == "TIR":
right_doms = len([x for x in profiles.split(",") if '_Tase_' in x])
other_doms = len([x for x in profiles.split(",") if '_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x
or '_RNaseH_' in x or '_ENV_' in x or '_EN_' in x or '_HEL_' in x or '_RPA_' in x or '_REP_'
in x or '_OTU_' in x or '_SET_' in x or '_Prp' in x or '_ATPase_' in x or '_PhageINT_' in x])
elif order == "HELITRON":
right_doms = len([x for x in profiles.split(",") if '_HEL_' in x or '_EN_' in x or '_RPA_' in x or '_REP_' in x
or '_OTU_' in x or '_SET_' in x])
other_doms = len([x for x in profiles.split(",") if
'_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x or '_RNaseH_' in x or '_ENV_' in x
or '_Tase_' in x or '_Prp' in x or '_ATPase_' in x or '_PhageINT_' in x])
elif order == "MAVERICK":
right_doms = len(
[x for x in profiles.split(",") if '_Prp' in x or '_ATPase_' in x or '_INT_' in x or '_AP_' in x])
other_doms = len([x for x in profiles.split(",") if
'_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x or '_RNaseH_' in x or '_ENV_' in x
or '_EN_' in x or '_Tase_' in x or '_HEL_' in x or '_RPA_' in x or '_REP_' in x or '_OTU_' in x
or '_SET_' in x or '_PhageINT_' in x])
elif order == "CRYPTON":
right_doms = len([x for x in profiles.split(",") if '_PhageINT_' in x])
other_doms = len([x for x in profiles.split(",") if '_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x
or '_RNaseH_' in x or '_ENV_' in x or '_EN_' in x or '_HEL_' in x or '_RPA_' in x or '_REP_'
in x or '_OTU_' in x or '_SET_' in x or '_Prp' in x or '_ATPase_' in x or '_Tase_' in x])
return right_doms, other_doms
def inferring_domains(input_profiles):
inferred = False
new_class = 0
if len(input_profiles) > 0:
profiles = input_profiles[0]
# Class I or II ?
class2_doms = len(
[x for x in profiles.split(",") if '_Tase_' in x or '_HEL_' in x or '_RPA_' in x or '_REP_' in x or '_OTU_'
in x or '_SET_' in x or '_Prp' in x or '_ATPase_' in x or '_PhageINT_' in x])
class1_doms = len(
[x for x in profiles.split(",") if '_GAG_' in x or '_AP_' in x or '_INT_' in x or '_RT_' in x or
'_RNaseH_' in x or '_ENV_' in x or '_EN_' in x])
if class1_doms > 0 and class2_doms == 0:
# Retrotransposon !
inferred = True
new_class = orders_superfamilies.index("CLASSI") + 2
# which order?
count_orders = 0
for ord in ['LTR', 'LINE', 'DIRS']:
good_doms, other_doms = count_domains_by_order(profiles, ord)
if good_doms > 0 and other_doms == 0:
new_class = orders_superfamilies.index(ord) + 2
count_orders += 1
if count_orders > 1: # It wasn't possible to distinguish between Class I's orders
new_class = orders_superfamilies.index("CLASSI") + 2
elif class1_doms == 0 and class2_doms > 0:
# Transposon !
inferred = True
new_class = orders_superfamilies.index("CLASSII") + 2
# which order?
count_orders = 0
for ord in ['TIR', 'HELITRON', 'MAVERICK', 'CRYPTON']:
good_doms, other_doms = count_domains_by_order(profiles, ord)
if good_doms > 0 and other_doms == 0:
new_class = orders_superfamilies.index(ord) + 2
count_orders += 1
if count_orders > 1: # It wasn't possible to distinguish between Class II's orders
new_class = orders_superfamilies.index("CLASSII") + 2
return inferred, new_class
def decision_tree_rules(struc_table, profiles, i, keep_seqs, minDomLTR, num_copies, orders, minFLNA, kept_seqs_record,
ref_tes, automatic):
status = -1 # 0 = delete, 1 = keep, -1 = Manual Inspection classified module, -3 = unclassified module
reason = ""
superFamily = str(struc_table.at[i, "sFamily"])
#### Class 1 Retrotransposons
if str(struc_table.at[i, "order"]).upper() == 'LINE' or str(struc_table.at[i, "order"]).upper() == 'SINE':
if len(profiles) > 0 and len(profiles[0].split(",")) >= 1:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "LINE")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
if superFamily in orders_superfamilies:
orders.append(orders_superfamilies.index(superFamily) + 2)
else:
orders.append(orders_superfamilies.index("LINE") + 2)
reason = "It's a LINE !!! Kept for having at least one domain !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection because having non-LINE domains !"
else:
reason = "Marked as incomplete TE for having non-LINE domains"
elif len(profiles) == 0 and "polyAtail" in struc_table.at[i, "struct"] and (
num_copies[struc_table.at[i, "Seq_name"]][0] >= minFLNA or num_copies[struc_table.at[i, "Seq_name"]][1]
>= minFLNA):
keep_seqs.append(struc_table.at[i, "Seq_name"])
orders.append(orders_superfamilies.index("SINE") + 2)
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
reason = "It's a SINE !!! Kept for having polyA tail, no domains and at least " + str(
minFLNA) + " full-length fragments or copies !"
status = 1
else:
if automatic != 'F':
reason = "Sent to manual inspection for don't having any domains or PolyA"
else:
reason = "Marked as incomplete TE for don't having any domains or PolyA"
status = -1
elif str(struc_table.at[i, "order"]).upper() == 'LTR' or str(struc_table.at[i, "order"]).upper() == 'LARD' or \
str(struc_table.at[i, "order"]).upper() == 'TRIM':
status_ltr = False
if "termLTR: " in struc_table.at[i, "struct"]:
if len(profiles) > 0 and len(profiles[0].split(",")) >= minDomLTR:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "LTR")
if rigth_doms > minDomLTR and other_doms == 0:
reason = "It's a LTR-RT !!! Kept for having at least " + str(minDomLTR) + " domains and LTRs !"
status_ltr = True
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for having non-LTR-RTs domains !"
else:
reason = "Marked as incomplete TE for having non-LTR-RTs domains !"
elif len(profiles) > 0 and len(profiles[0].split(",")) > 0 and struc_table.at[i, "order"] == 'LTR':
rigth_doms, other_doms = count_domains_by_order(profiles[0], "LTR")
if rigth_doms > 0 and other_doms == 0:
reason = "It's a truncated LTR-RT !!! Kept for having " + str(
len(profiles[0].split(","))) + " domains and LTRs !"
status_ltr = True
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having non-LTR-RTs domains !"
else:
reason = "Marked as incomplete TE for don't having non-LTR-RTs domains !"
elif len(profiles) == 0 and (num_copies[struc_table.at[i, "Seq_name"]][0] >= minFLNA or
num_copies[struc_table.at[i, "Seq_name"]][1] >= minFLNA):
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
if int(struc_table.at[i, "length"]) <= 2500:
name = "TRIM"
else:
name = "LARD"
orders.append(orders_superfamilies.index(name) + 2)
reason = "It's a " + name + " !!! Kept for having LTRs, no domains and at least " + str(
minFLNA) + " full-length fragments or copies !"
status = 1
else:
# no profiles and no LTRs
if len(profiles) == 0:
if automatic != 'F':
reason = "Sent to manual inspection for don't having any domains neither LTRs!"
else:
reason = "Marked as incomplete TE for don't having any domains neither LTRs!"
else:
if automatic != 'F':
reason = "Sent to manual inspection for don't having at least " + str(
minDomLTR) + " domains and LTRs!"
else:
reason = "Marked as incomplete TE for don't having at least " + str(
minDomLTR) + " domains and LTRs!"
status = -1
if status_ltr:
if superFamily.upper().replace("-", "") in orders_superfamilies:
orders.append(orders_superfamilies.index(superFamily.upper().replace("-", "")) + 2)
else:
orders.append(orders_superfamilies.index("LTR") + 2)
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
elif str(struc_table.at[i, "order"]).upper() == 'DIRS':
# manual inspection in classified module
if len(profiles) > 0 and len(profiles[0].split(",")) >= 1:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "DIRS")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("DIRS") + 2)
reason = "It's a DIRS !!! Kept for having at least one domain !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for having non-DIRS domains !"
else:
reason = "Marked as incomplete TE for having non-DIRS domains !"
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having domains !"
else:
reason = "Marked as incomplete TE for don't having domains !"
elif str(struc_table.at[i, "order"]).upper() == 'PLE':
# manual inspection in classified module
if automatic != 'F':
reason = "Sent to manual inspection"
else:
reason = "Marked as incomplete TE"
status = -1
#### Class 2 DNA Transposons
elif str(struc_table.at[i, "order"]).upper() == 'TIR' or str(struc_table.at[i, "order"]).upper() == 'MITE':
if "termTIR: " in struc_table.at[i, "struct"]:
if len(profiles) > 0 and len(profiles[0].split(",")) > 0:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "TIR")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
if superFamily.upper().replace("-", "") in orders_superfamilies:
orders.append(orders_superfamilies.index(superFamily.upper().replace("-", "")) + 2)
else:
orders.append(orders_superfamilies.index("TIR") + 2)
reason = "It's a TIR !!! Kept for having at least one domain !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection because having non-TIR domains !"
else:
reason = "Marked as incomplete TE because having non-TIR domains !"
else:
if num_copies[struc_table.at[i, "Seq_name"]][0] >= minFLNA or num_copies[struc_table.at[i, "Seq_name"]][
1] >= minFLNA:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("MITE") + 2)
reason = "It's a MITE !!! Kept for having TIRs, no domains and at least " + str(
minFLNA) + " full-length fragments or copies !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection because having TIRs, no domains but less than " + str(
minFLNA) + " full-length fragments or copies !"
else:
reason = "Marked as incomplete TE because having TIRs, no domains but less than " + str(
minFLNA) + " full-length fragments or copies !"
else:
# no profiles and no TIRs
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having TIRs neither domains !"
else:
reason = "Marked as incomplete TE for don't having TIRs neither domains !"
elif str(struc_table.at[i, "order"]).upper() == 'CRYPTON':
if len(profiles) > 0 and len(profiles[0].split(",")) >= 1:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "CRYPTON")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("CRYPTON") + 2)
reason = "It's a CRYPTON !!! Kept for having at least one domain !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for having non-CRYPTON domains !"
else:
reason = "Marked as incomplete TE for having non-CRYPTON domains !"
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having domains !"
else:
reason = "Marked as incomplete TE for don't having domains !"
elif str(struc_table.at[i, "order"]).upper() == 'HELITRON':
if len(profiles) > 0:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "HELITRON")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("HELITRON") + 2)
reason = "It's a Helitron !!! Kept for having Helicase !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for having non-Helitron domains"
else:
reason = "Marked as incomplete TE for having non-Helitron domains"
elif "helitronExtremities: " in struc_table.at[i, "struct"]:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("HELITRON") + 2)
reason = "It's a Helitron !!! Kept for having helitron Extremities !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having Helitron Extremities neither helicase !"
else:
reason = "Marked as incomplete TE for don't having Helitron Extremities neither helicase !"
elif str(struc_table.at[i, "order"]).upper() == 'MAVERICK':
if len(profiles) > 0 and len(profiles[0].split(",")) >= 1:
rigth_doms, other_doms = count_domains_by_order(profiles[0], "MAVERICK")
if rigth_doms > 0 and other_doms == 0:
keep_seqs.append(struc_table.at[i, "Seq_name"])
kept_seqs_record.append([x for x in SeqIO.parse(ref_tes, "fasta") if
str(x.id).split("#")[0] == struc_table.at[i, "Seq_name"]][0])
orders.append(orders_superfamilies.index("MAVERICK") + 2)
reason = "It's a Maverick !!! Kept for having at least one domain !"
status = 1
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for having non-Maverick domains !"
else:
reason = "Marked as incomplete TE for having non-Maverick domains !"
else:
status = -1
if automatic != 'F':
reason = "Sent to manual inspection for don't having domains !"
else:
reason = "Marked as incomplete TE for don't having domains !"
else:
status = -3