Debian Codegraph @

cgecore/blaster/run_blaster.py

raw symbols SCIP
1 #!/usr/bin/env python
2 import sys
3 import os
4 import time
5 import random
6 import re
7 import subprocess
8
9 from argparse import ArgumentParser
10 from blaster import Blaster
11
12 ##########################################################################
13 # PARSE COMMAND LINE OPTIONS
14 ##########################################################################
15
16 parser = ArgumentParser()
17 parser.add_argument('-i', '--input',
18 help="Input file")
19 parser.add_argument('-l', '--input_list',
20 help="File with list of files to analyse")
21 parser.add_argument('-d', '--databases',
22 help="Comma seperated list of databases to blast against")
23 parser.add_argument('-o', '--out_path',
24 help="output directory")
25 parser.add_argument("-b", "--blastPath", dest="blast_path",
26 help="Path to blast",
27 default='blastn')
28 parser.add_argument("-p", "--databasePath", dest="db_path",
29 help="Path to the databases",
30 default='')
31 parser.add_argument("-c", "--min_cov", dest="min_cov",
32 help="Minimum coverage",
33 type=float,
34 default=0.60)
35 parser.add_argument("-t", "--threshold", dest="threshold",
36 help="Blast threshold for identity",
37 type=float,
38 default=0.90)
39 parser.add_argument("--overlap",
40 help=("Allow hits/genes to overlap with this number of "
41 "nucleotides. Default: 30."),
42 type=int,
43 default=30)
44
45 args = parser.parse_args()
46
47 ##########################################################################
48 # MAIN
49 ##########################################################################
50
51 min_cov = args.min_cov
52 threshold = args.threshold
53
54 # Check if valid input file is provided
55 input_list = []
56 if args.input is not None and args.input_list is not None:
57 sys.exit("Input Error: Please only provide file list or single input "
58 "file\n")
59
60 elif args.input is None and args.input_list is None:
61 sys.exit("Input Error: No Input were provided!\n")
62
63 elif args.input is not None and not os.path.exists(args.input):
64 sys.exit("Input Error: Input file does not exist!\n")
65
66 elif args.input is not None:
67 inputfile = args.input
68 input_list.append(inputfile)
69
70 elif args.input_list is not None and not os.path.exists(args.input_list):
71 sys.exit("Input Error: No Input were provided!\n")
72
73 elif args.input_list is not None:
74 inputfile = args.input_list
75 with open(inputfile, "r") as f:
76 for line in f:
77 line = line.rstrip()
78 input_list.append(line)
79
80 # Check if valid output directory is provided
81 if not os.path.exists(args.out_path):
82 os.makedirs(args.out_path, exist_ok=True)
83 out_path = args.out_path
84 else:
85 out_path = args.out_path
86
87 # Check if valid file with genes is provided
88 if args.databases is None:
89 sys.exit("Input Error: No databases sepcified!\n")
90 else:
91 databases = args.databases.split(",")
92
93
94 # Check if valid path to BLAST is provided
95 blast = args.blast_path
96 db_path = args.db_path
97
98 for inp_file in input_list:
99 # Calling blast and parsing output
100 blast_run = Blaster(inputfile=inp_file, databases=databases,
101 db_path=db_path, out_path=out_path, min_cov=min_cov,
102 threshold=threshold, blast=blast,
103 allowed_overlap=args.overlap)
104
105 results = blast_run.results
106 query_align = blast_run.gene_align_query
107 homo_align = blast_run.gene_align_homo
108 sbjct_align = blast_run.gene_align_sbjct
109
110 file_name = inp_file.split("/")[-1].split(".")[0]
111 out_name = "%s/%s_hit_alignments.txt" % (out_path, file_name)
112 txt_file_seq_text = dict()
113 pos_result = list()
114
115 # Make result file
116 tab_file = "%s/%s_results.txt" % (out_path, file_name)
117 tab = open(tab_file, "w")
118
119 for db in results:
120
121 if results[db] == "No hit found":
122 tab.write("%s\n%s\n\n" % (db, results[db]))
123 else:
124 pos_result.append(db)
125 tab.write("%s\n" % (db))
126 tab.write("Hit\tIdentity\tAlignment Length/Gene Length\tPosition in "
127 "reference\tContig\tPosition in contig\n")
128
129 txt_file_seq_text[db] = list()
130
131 for hit in results[db]:
132 header = results[db][hit]["sbjct_header"]
133 ID = results[db][hit]["perc_ident"]
134 sbjt_length = results[db][hit]["sbjct_length"]
135 HSP = results[db][hit]["HSP_length"]
136 positions_contig = "%s..%s" % (results[db][hit]["query_start"],
137 results[db][hit]["query_end"])
138 positions_ref = "%s..%s" % (results[db][hit]["sbjct_start"],
139 results[db][hit]["sbjct_end"])
140 contig_name = results[db][hit]["contig_name"]
141
142 # Write tabels
143 tab.write("%s\t%.2f\t%s/%s\t%s\t%s\t%s\n" % (header, ID, HSP,
144 sbjt_length,
145 positions_ref,
146 contig_name,
147 positions_contig))
148 # Writing subjet/ref sequence
149 ref_seq = sbjct_align[db][hit]
150 hit_seq = query_align[db][hit]
151
152 # Getting the header and text for the txt file output
153 sbjct_start = results[db][hit]["sbjct_start"]
154 sbjct_end = results[db][hit]["sbjct_end"]
155 text = ("%s, ID: %.2f %%, Alignment Length/Gene Length: %s/%s, "
156 "Positions in reference: %s..%s, Contig name: %s, "
157 "Position: %s" % (header, ID, HSP, sbjt_length,
158 sbjct_start, sbjct_end, contig_name,
159 positions_contig)
160 )
161
162 # Saving the output to print the txt result file allignemts
163 txt_file_seq_text[db].append((text, ref_seq, homo_align[db][hit],
164 hit_seq))
165
166 tab.close()
167 txt_file = open(out_name, "w")
168
169 for db in pos_result:
170 # Txt file alignments
171 txt_file.write("##################### %s #####################\n" % (db))
172
173 for text in txt_file_seq_text[db]:
174 txt_file.write("%s\n\n" % (text[0]))
175
176 for i in range(0, len(text[1]), 60):
177 txt_file.write("%s\n" % (text[1][i:i + 60]))
178 txt_file.write("%s\n" % (text[2][i:i + 60]))
179 txt_file.write("%s\n\n" % (text[3][i:i + 60]))
180
181 txt_file.write("\n")
182
183 txt_file.close()