Debian Codegraph @

cgecore/cgefinder.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 import subprocess
3 import re
4 import os.path
5 import sys
6
7 # TODO import blaster and make blaster function in CGEFinder
8 # from cge.blaster.blaster import Blaster
9
10
11 def eprint(*args, **kwargs):
12 print(*args, file=sys.stderr, **kwargs)
13
14
15 class FinderResult():
16 def __init__(self, results, align_sbjct=None, align_query=None,
17 align_homo=None):
18 self.results = results # Results
19 self.gene_align_query = align_query # Sequence alignment lines
20 self.gene_align_homo = align_homo # Sequence alignment homolog string
21 self.gene_align_sbjct = align_sbjct # Sequence alignment allele string
22
23
24 class CGEFinder():
25
26 # Variables used by methods to distinguish results created by different
27 # methods.
28 TYPE_BLAST = "blast"
29 TYPE_KMA = "kma"
30
31 @staticmethod
32 def kma(inputfile_1, out_path, databases, db_path_kma, min_cov=0.6,
33 threshold=0.9, kma_path="cge/kma/kma", sample_name="",
34 inputfile_2=None, kma_mrs=None, kma_gapopen=None,
35 kma_gapextend=None, kma_penalty=None, kma_reward=None,
36 kma_apm=None, kma_memmode=False, kma_nanopore=False, debug=False,
37 kma_add_args=None, kma_cge=False, kma_1t1=False):
38 """
39 TODO: Result storage - Too complex. Not effective.
40 Before changing code: Check downstream dependencies of results
41 dicts.
42 Currently the code stores results in four different dicts. This can
43 be reduced to just one.
44 The main dict that stores all results currently stores one result pr
45 hit, and distiguishes hits to the same gene by adding an increasing
46 integer (obtained by getting the length of the internal gene dict).
47 The main dict also stores an internal dict for each 'gene'
48 containing an empty dict for each hit.
49 Solution: Create a main<dict> -> gene<list> -> hit<dict> design, and
50 remove all the references main -> hit. This reduces redundancy and
51 the need for manipulating gene names with an incremental integer.
52
53 TODO: Method too many responsibilities
54 Solution: Create KMA class, create additional functions.
55
56 Original comment:
57 "I expect that there will only be one hit pr gene, but if there are
58 more, I assume that the sequence of the hits are the same in the res
59 file and the aln file."
60 Not sure if this holds for the current code.
61 """
62 threshold = threshold * 100
63 min_cov = min_cov * 100
64
65 kma_results = dict()
66 kma_results["excluded"] = dict()
67
68 if(sample_name):
69 sample_name = "_" + sample_name
70
71 # Initiate output dicts.
72 gene_align_sbjct = {}
73 gene_align_query = {}
74 gene_align_homo = {}
75
76 for db in databases:
77 kma_db = db_path_kma + "/" + db
78 kma_outfile = out_path + "/kma_" + db + sample_name
79 kma_cmd = ("%s -t_db %s -o %s -e 1.0" % (kma_path,
80 kma_db, kma_outfile))
81 if(inputfile_2 is not None):
82 kma_cmd += " -ipe " + inputfile_1 + " " + inputfile_2
83 else:
84 kma_cmd += " -i " + inputfile_1
85 if(kma_mrs is not None):
86 kma_cmd += " -mrs " + str(kma_mrs)
87 if(kma_gapopen is not None):
88 kma_cmd += " -gapopen " + str(kma_gapopen)
89 if(kma_gapextend is not None):
90 kma_cmd += " -gapextend " + str(kma_gapextend)
91 if(kma_penalty is not None):
92 kma_cmd += " -penalty " + str(kma_penalty)
93 if(kma_reward is not None):
94 kma_cmd += " -reward " + str(kma_reward)
95 if(kma_apm is not None):
96 kma_cmd += " -apm " + kma_apm
97 if(kma_cge):
98 kma_cmd += " -cge "
99 if(kma_1t1):
100 kma_cmd += " -1t1 "
101 if (kma_memmode):
102 kma_cmd += " -mem_mode "
103 if (kma_nanopore):
104 kma_cmd += " -bcNano "
105 kma_cmd += " -mp 20 "
106 if (kma_add_args is not None):
107 kma_cmd += " " + kma_add_args + " "
108
109 # kma output files
110 align_filename = kma_outfile + ".aln"
111 res_filename = kma_outfile + ".res"
112
113 # If .res file exists then skip mapping
114 if(os.path.isfile(res_filename)
115 and os.access(res_filename, os.R_OK)):
116 eprint("Found " + res_filename + " skipping DB.")
117 else:
118 # Call KMA
119 if(debug):
120 eprint("KMA cmd: " + kma_cmd)
121
122 process = subprocess.Popen(kma_cmd, shell=True,
123 stdout=subprocess.PIPE,
124 stderr=subprocess.PIPE)
125 out, err = process.communicate()
126
127 kma_results[db] = 'No hit found'
128
129 # Open res file
130 try:
131 res_file = open(res_filename, "r")
132 header = res_file.readline()
133 except IOError as error:
134 sys.exit("Error: KMA did not run as expected.\n"
135 "KMA finished with the following response:"
136 "\n{}\n{}".format(out.decode("utf-8"),
137 err.decode("utf-8")))
138
139 gene_res_count = {}
140
141 for line in res_file:
142
143 if kma_results[db] == 'No hit found':
144 kma_results[db] = dict()
145
146 data = [data.strip() for data in line.split("\t")]
147 gene = data[0]
148
149 gene_count = gene_res_count.get(gene, 0)
150 gene_count = gene_count + 1
151 gene_res_count[gene] = gene_count
152 if(gene_count == 1):
153 hit = gene
154 else:
155 hit = "{}_{}".format(gene, gene_count)
156
157 sbjct_len = int(data[3])
158 sbjct_ident = float(data[4])
159 coverage = float(data[5])
160 depth = float(data[-3])
161 q_value = float(data[-2])
162 p_value = float(data[-1])
163
164 exclude_reasons = []
165
166 if(coverage < min_cov or sbjct_ident < threshold):
167 exclude_reasons.append(coverage)
168 exclude_reasons.append(sbjct_ident)
169
170 if(exclude_reasons):
171 kma_results["excluded"][hit] = exclude_reasons
172
173 kma_results[db][hit] = dict()
174 kma_results[db][hit]['sbjct_length'] = sbjct_len
175 kma_results[db][hit]["perc_coverage"] = coverage
176 kma_results[db][hit]["sbjct_string"] = []
177 kma_results[db][hit]["query_string"] = []
178 kma_results[db][hit]["homo_string"] = []
179 kma_results[db][hit]["sbjct_header"] = gene
180 kma_results[db][hit]["perc_ident"] = sbjct_ident
181 kma_results[db][hit]["query_start"] = "NA"
182 kma_results[db][hit]["query_end"] = "NA"
183 kma_results[db][hit]["contig_name"] = "NA"
184 kma_results[db][hit]["HSP_length"] = ""
185 kma_results[db][hit]["cal_score"] = q_value
186 kma_results[db][hit]["depth"] = depth
187 kma_results[db][hit]["p_value"] = p_value
188 res_file.close()
189
190 if kma_results[db] == 'No hit found':
191 continue
192
193 # Open align file
194 with open(align_filename, "r") as align_file:
195 gene_aln_count = {}
196 gene = ""
197 # Parse through alignments
198 for line in align_file:
199 # Skip empty lines
200 if(not line.strip()):
201 continue
202
203 # Check when a new gene alignment start
204 if line.startswith("#"):
205 gene = line[1:].strip()
206
207 gene_count = gene_aln_count.get(gene, 0)
208 gene_aln_count[gene] = gene_count + 1
209 else:
210 if(gene_aln_count[gene] == 1):
211 hit = gene
212 else:
213 hit = "{}_{}".format(gene, gene_aln_count[gene])
214
215 if hit in kma_results[db]:
216 line_data = line.split("\t")[-1].strip()
217 if line.startswith("template"):
218 kma_results[db][hit]["sbjct_string"] += (
219 [line_data])
220 elif line.startswith("query"):
221 kma_results[db][hit]["query_string"] += (
222 [line_data])
223 else:
224 kma_results[db][hit]["homo_string"] += (
225 [line_data])
226 else:
227 print(hit + " not in results: ", kma_results)
228
229 # concatinate all sequence lists and find subject start
230 # and subject end
231
232 gene_align_sbjct[db] = {}
233 gene_align_query[db] = {}
234 gene_align_homo[db] = {}
235
236 for hit in kma_results[db]:
237 align_sbjct = "".join(kma_results[db][hit]['sbjct_string'])
238 align_query = "".join(kma_results[db][hit]['query_string'])
239 align_homo = "".join(kma_results[db][hit]['homo_string'])
240
241 # Extract only aligned sequences
242 start = re.search("^-*(\w+)", align_query).start(1)
243 end = re.search("\w+(-*)$", align_query).start(1)
244
245 kma_results[db][hit]['sbjct_string'] = align_sbjct[start:end]
246 kma_results[db][hit]['query_string'] = align_query[start:end]
247 kma_results[db][hit]['homo_string'] = align_homo[start:end]
248
249 # Save align start and stop positions relative to
250 # subject sequence
251 kma_results[db][hit]['sbjct_start'] = start + 1
252 kma_results[db][hit]["sbjct_end"] = end + 1
253 kma_results[db][hit]["HSP_length"] = end - start
254
255 # Count gaps in the alignment
256 kma_results[db][hit]["gaps"] = (
257 kma_results[db][hit]['sbjct_string'].count("-")
258 + kma_results[db][hit]['query_string'].count("-"))
259
260 # Save sequences covering the entire subject sequence
261 # in seperate variables
262 gene_align_sbjct[db][hit] = align_sbjct
263 gene_align_query[db][hit] = align_query
264 gene_align_homo[db][hit] = align_homo
265
266 return FinderResult(kma_results, gene_align_sbjct, gene_align_query,
267 gene_align_homo)