Debian Codegraph @

cgecore/blaster/blaster.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 from __future__ import division
3 import sys
4 import os
5 import time
6 import random
7 import re
8 import subprocess
9
10 from Bio.Blast import NCBIXML
11 from Bio import SeqIO
12
13 import collections
14
15
16 class Blaster():
17 def __init__(self, inputfile, databases, db_path, out_path='', min_cov=0.6,
18 threshold=0.9, blast='blastn', cut_off=True,
19 max_target_seqs=50000, reuse_results=False,
20 allowed_overlap=0):
21
22 min_cov = 100 * float(min_cov)
23 threshold = 100 * float(threshold)
24
25 # For alignment data storage
26 self.gene_align_query = dict() # Sequence alignment lines
27 self.gene_align_homo = dict() # Sequence alignment homolog string
28 self.gene_align_sbjct = dict() # Sequence alignment allele string
29 self.results = dict() # Results
30
31 # TODO: Add excluded results to this dictionay
32 self.results["excluded"] = dict()
33
34 for db in databases:
35 # Adding the path to the database and output
36 db_file = "%s/%s.fsa" % (db_path, db)
37 tmp_out_path = "%s/tmp" % (out_path)
38 out_file = "%s/out_%s.xml" % (tmp_out_path, db)
39 os.makedirs(tmp_out_path, exist_ok=True)
40 os.chmod(tmp_out_path, 0o775)
41
42 # Running blast
43 if (os.path.isfile(out_file)
44 and os.access(out_file, os.R_OK)
45 and reuse_results):
46 print("Found " + out_file + " skipping DB.")
47 out, err = (b'', b'')
48 else:
49 cmd = ("%s -subject %s -query %s -out %s -outfmt 5"
50 " -perc_identity %s -max_target_seqs %s"
51 " -dust no" % (blast, db_file, inputfile,
52 out_file, threshold, max_target_seqs))
53
54 process = subprocess.Popen(cmd, shell=True,
55 stdout=subprocess.PIPE,
56 stderr=subprocess.PIPE)
57 out, err = process.communicate()
58
59 # Get results file
60 try:
61 # Test if output file exist
62 result_handle = open(out_file, "r")
63 except IOError:
64 sys.exit(("Error: BLAST did not run as expected. "
65 "The expected output file, {}, did not exist.\n"
66 "BLAST finished with the following response:"
67 "\n{}\n{}").format(os.path.abspath(out_file),
68 out.decode("utf-8"),
69 err.decode("utf-8")))
70
71 # Test if blast output is empty
72 if os.stat(out_file).st_size == 0:
73 sys.exit(("Error: BLAST did not run as expected. "
74 "The output file {} was empty.\n"
75 "BLAST finished with the following response:"
76 "\n{}\n{}").format(os.path.abspath(out_file),
77 out.decode("utf-8"),
78 err.decode("utf-8")))
79
80 # Get blast output
81 blast_records = NCBIXML.parse(result_handle)
82
83 # Declaring variables for saving the results
84
85 # results for each gene
86 gene_results = dict()
87
88 # For finding the best hits
89 best_hsp = dict()
90
91 # Keeping track of gene split
92 gene_split = collections.defaultdict(dict)
93
94 # Making the dicts for sequence outputs
95 self.gene_align_query[db] = dict()
96 self.gene_align_homo[db] = dict()
97 self.gene_align_sbjct[db] = dict()
98
99 # Parsing over the hits and only keeping the best
100 for blast_record in blast_records:
101 # OLD CODE TO BE REMOVED
102 # query = blast_record.query
103 # blast_record.alignments.sort(key=lambda align: (
104 # -max((len(hsp.query)
105 # * (int(hsp.identities) / float(len(hsp.query)))
106 # for hsp in align.hsps)))
107 # )
108
109 # Sort BLAST alignments by the hsp in each alignment with the
110 # highest number of identical nucleotides (hsp.identities)
111 blast_record.alignments.sort(
112 key=lambda align: (max((int(hsp.identities)
113 for hsp in align.hsps))),
114 reverse=True)
115 query = blast_record.query
116
117 for alignment in blast_record.alignments:
118 # Setting the e-value as 1 and bit as 0 to get the best
119 # HSP fragment
120 best_e_value = 1
121 best_bit = 0
122 start_hsp = 0
123 end_hsp = 0
124
125 for hsp in alignment.hsps:
126 if hsp.expect < best_e_value or hsp.bits > best_bit:
127 # best_e_value = hsp.expect
128 # best_bit = hsp.bits
129 tmp = alignment.title.split(" ")
130 sbjct_header = tmp[1]
131 # DEBUG
132 print("Found: {}".format(sbjct_header))
133 bit = hsp.bits
134 sbjct_length = alignment.length
135 sbjct_start = hsp.sbjct_start
136 sbjct_end = hsp.sbjct_end
137 gaps = hsp.gaps
138 query_string = str(hsp.query)
139 homo_string = str(hsp.match)
140 sbjct_string = str(hsp.sbjct)
141 contig_name = query.replace(">", "")
142 query_start = hsp.query_start
143 query_end = hsp.query_end
144 HSP_length = len(query_string)
145 perc_ident = (int(hsp.identities)
146 / float(HSP_length) * 100)
147 strand = 0
148 coverage = ((int(HSP_length) - int(gaps))
149 / float(sbjct_length))
150 perc_coverage = (((int(HSP_length) - int(gaps))
151 / float(sbjct_length)) * 100)
152
153 # cal_score is later used to select the best hit
154 cal_score = perc_ident * coverage
155
156 hit_id = "%s:%s..%s:%s:%f" % (
157 contig_name, query_start, query_end,
158 sbjct_header, cal_score)
159 # If the hit is on the other strand
160 if sbjct_start > sbjct_end:
161 tmp = sbjct_start
162 sbjct_start = sbjct_end
163 sbjct_end = tmp
164
165 query_string = self.reversecomplement(
166 query_string)
167 homo_string = homo_string[::-1]
168 sbjct_string = self.reversecomplement(
169 sbjct_string)
170 strand = 1
171
172 # Save hit
173 if((cut_off and perc_coverage > 20)
174 or cut_off is False):
175
176 best_hsp = {'evalue': hsp.expect,
177 'sbjct_header': sbjct_header,
178 'bit': bit,
179 'perc_ident': perc_ident,
180 'sbjct_length': sbjct_length,
181 'sbjct_start': sbjct_start,
182 'sbjct_end': sbjct_end,
183 'gaps': gaps,
184 'query_string': query_string,
185 'homo_string': homo_string,
186 'sbjct_string': sbjct_string,
187 'contig_name': contig_name,
188 'query_start': query_start,
189 'query_end': query_end,
190 'HSP_length': HSP_length,
191 'coverage': coverage,
192 'cal_score': cal_score,
193 'hit_id': hit_id,
194 'strand': strand,
195 'perc_coverage': perc_coverage
196 }
197 else:
198 continue
199
200
201
202 # Saving the result if any
203 if best_hsp:
204 save = 1
205
206 # If there are other gene alignments they are compared
207 if gene_results:
208 tmp_gene_split = gene_split
209 tmp_results = gene_results
210 # Compare the hit results
211 save, gene_split, gene_results = (
212 self.compare_results(save, best_hsp,
213 tmp_results,
214 tmp_gene_split,
215 allowed_overlap)
216 )
217
218 # If the hit is not overlapping with other hit
219 # seqeunces it is kept
220 if save == 1:
221 # DEBUG
222 print("Saving: {}".format(hit_id))
223 gene_results[hit_id] = best_hsp
224
225 result_handle.close()
226
227 # If the hit does not cover the entire database reference the
228 # missing seqence data are extracted
229 keys = list(gene_results.keys())
230
231 for hit_id in keys:
232 hit = gene_results[hit_id]
233
234 # Calculate possible split gene coverage
235 perc_coverage = hit['perc_coverage']
236
237 if(hit['sbjct_header'] in gene_split
238 and len(gene_split[hit['sbjct_header']]) > 1):
239
240 # Calculate new length
241 new_length = self.calculate_new_length(gene_split, gene_results,
242 hit)
243 hit['split_length'] = new_length
244
245 # Calculate new coverage
246 perc_coverage = new_length / float(hit['sbjct_length']) * 100
247
248 # If the hit is above the minimum length threshold it is kept
249 if perc_coverage >= min_cov:
250 if hit['coverage'] == 1:
251 self.gene_align_query[db][hit_id] = hit['query_string']
252 self.gene_align_homo[db][hit_id] = hit['homo_string']
253 self.gene_align_sbjct[db][hit_id] = hit['sbjct_string']
254 elif hit['coverage'] != 1:
255 # Getting the whole database sequence
256 for seq_record in SeqIO.parse(db_file, "fasta"):
257 if seq_record.description.replace(" ", "") == hit['sbjct_header'].replace(" ", ""):
258 start_seq = str(seq_record.seq)[:int(hit["sbjct_start"])-1]
259 end_seq = str(seq_record.seq)[int(hit["sbjct_end"]):]
260 self.gene_align_sbjct[db][hit_id] = start_seq + hit['sbjct_string'] + end_seq
261 #self.gene_align_sbjct[db][hit_id] = str(seq_record.seq)
262 break
263
264 # Getting the whole contig to extract extra query seqeunce
265 contig = ''
266 for seq_record in SeqIO.parse(inputfile, "fasta"):
267 if seq_record.description.replace(" ", "") == hit['contig_name'].replace(" ", ""):
268 contig = str(seq_record.seq)
269 break
270
271 # Extract extra sequence from query
272 query_seq, homo_seq = self.get_query_align(hit, contig)
273
274 # Saving the new alignment sequences
275 self.gene_align_query[db][hit_id] = query_seq
276 self.gene_align_homo[db][hit_id] = homo_seq
277
278 else:
279 del gene_results[hit_id]
280 if hit['sbjct_header'] in gene_split:
281 del gene_split[hit['sbjct_header']]
282
283 # Save the database result
284 if gene_results:
285 self.results[db] = gene_results
286 else:
287 self.results[db] = "No hit found"
288
289 @staticmethod
290 def reversecomplement(seq):
291 # Make reverse complement strand
292 trans = str.maketrans("ATGC", "TACG")
293 return seq.translate(trans)[::-1]
294
295 @staticmethod
296 def compare_results(save, best_hsp, tmp_results, tmp_gene_split,
297 allowed_overlap):
298 """
299 Function for comparing hits and saving only the best hit
300 """
301
302 # Get data for comparison
303 hit_id = best_hsp['hit_id']
304 new_start_query = best_hsp['query_start']
305 new_end_query = best_hsp['query_end']
306 new_start_sbjct = int(best_hsp['sbjct_start'])
307 new_end_sbjct = int(best_hsp['sbjct_end'])
308 new_score = best_hsp['cal_score']
309 new_db_hit = best_hsp['sbjct_header']
310 new_contig = best_hsp['contig_name']
311 new_HSP = best_hsp['HSP_length']
312
313 # See if the best HSP fragment overlap with another allignment
314 # and keep the allignment with the highest score - if the new
315 # fragment is not providing new sequence
316 keys = list(tmp_results.keys())
317 for hit in keys:
318 hit_data = tmp_results[hit]
319 old_start_query = hit_data['query_start']
320 old_end_query = hit_data['query_end']
321 old_start_sbjct = int(hit_data['sbjct_start'])
322 old_end_sbjct = int(hit_data['sbjct_end'])
323 old_score = hit_data['cal_score']
324 old_db_hit = hit_data['sbjct_header']
325 old_contig = hit_data['contig_name']
326 old_HSP = hit_data['HSP_length']
327
328 remove_old = 0
329 # If they align to the same gene in the database they are
330 # compared
331 if new_db_hit == old_db_hit:
332
333 #If the hit comes from different contig
334 if old_contig != new_contig:
335
336 # Save a split if the new hit still creats one
337 if(new_db_hit in tmp_gene_split
338 and hit_id not in tmp_gene_split[new_db_hit]):
339
340 tmp_gene_split[new_db_hit][hit_id] = 1
341
342 # If the hit provides additional sequence it is kept and
343 # the new coverage is saved otherwise the one with the
344 # highest score is kept
345 elif(new_start_sbjct < old_start_sbjct
346 or new_end_sbjct > old_end_sbjct):
347
348 # Save the hits as split
349 tmp_gene_split[old_db_hit][hit_id] = 1
350 if hit not in tmp_gene_split[old_db_hit]:
351 tmp_gene_split[old_db_hit][hit] = 1
352
353
354 # else:
355 # if new_score > old_score:
356 # Set to remove old hit
357 # remove_old = 1
358
359 # Save a split if the new hit still creats one
360 # if(new_db_hit in tmp_gene_split
361 # and hit_id not in tmp_gene_split[new_db_hit]):
362
363 # tmp_gene_split[new_db_hit][hit_id] = 1
364 # else:
365 # save = 0
366
367 # If the old and new hit is not identical the
368 # possible saved gene split for the new hit is
369 # removed
370 # if hit_id != hit:
371 # if(new_db_hit in tmp_gene_split
372 # and hit_id in tmp_gene_split[new_db_hit]):
373
374 # del tmp_gene_split[new_db_hit][hit_id]
375 # break
376
377 # If the hits comes form the same part of the contig
378 # sequnce but match different genes only the best hit is
379 # kept
380 if new_contig == old_contig:
381 print("Same contig: {} == {}".format(new_contig, old_contig))
382 print("\t{} vs {}".format(new_db_hit, old_db_hit))
383 # Check if saved hits overlaps with current hit
384 hit_union_length = (max(old_end_query, new_end_query)
385 - min(old_start_query, new_start_query))
386 hit_lengths_sum = ((old_end_query - old_start_query)
387 + (new_end_query - new_start_query))
388 overlap_len = (hit_lengths_sum - hit_union_length)
389
390 if overlap_len < allowed_overlap:
391 print("\tignore overlap ({}): {}".format(overlap_len, new_db_hit))
392 continue
393 print("\toverlap found ({}): {}".format(overlap_len, new_db_hit))
394
395 # If the two hits cover the exact same place on the
396 # contig only the percentage of identity is compared
397 if(old_start_query == new_start_query
398 and old_end_query == new_end_query):
399
400 if best_hsp['perc_ident'] > hit_data['perc_ident']:
401
402 # Set to remove old hit
403 remove_old = 1
404
405 # Save a split if the new hit still creats one
406 if(new_db_hit in tmp_gene_split
407 and hit_id not in tmp_gene_split[new_db_hit]):
408
409 tmp_gene_split[new_db_hit][hit_id] = 1
410
411 elif best_hsp['perc_ident'] == hit_data['perc_ident']:
412 # Save both
413
414 # Save a split if the new hit still creats one
415 if(new_db_hit in tmp_gene_split
416 and hit_id not in tmp_gene_split[new_db_hit]):
417
418 tmp_gene_split[new_db_hit][hit_id] = 1
419 else:
420 save = 0
421
422 # Remove new gene from gene split if present
423 if(new_db_hit in tmp_gene_split
424 and hit_id in tmp_gene_split[new_db_hit]):
425
426 del tmp_gene_split[new_db_hit][hit_id]
427 break
428
429 # If new hit overlaps with the saved hit
430 elif(hit_union_length <= hit_lengths_sum):
431 print("\t{} <= {}".format(hit_union_length, hit_lengths_sum))
432 print("\t\tScores: {} cmp {}".format(new_score, old_score))
433
434 if new_score > old_score:
435 # Set to remove old gene
436 remove_old = 1
437 # Save a split if the new hit still creats one
438 if(new_db_hit in tmp_gene_split
439 and hit_id not in tmp_gene_split[new_db_hit]):
440
441 tmp_gene_split[new_db_hit][hit_id] = 1
442
443 elif new_score == old_score:
444 # If both genes are of same coverage
445 # and identity is the same implied by new_score == old_score
446 # hit is chosen based on length
447 if((int(best_hsp['perc_coverage']) ==
448 int(hit_data['perc_coverage']))
449 and new_HSP > old_HSP):
450
451 # Set to remove old gene
452 remove_old = 1
453 elif((int(best_hsp['perc_coverage']) ==
454 int(hit_data['perc_coverage']))
455 and old_HSP > new_HSP):
456
457 # Remove current hit
458 save = 0
459 elif((int(best_hsp['perc_coverage']) ==
460 int(hit_data['perc_coverage']))
461 and old_HSP==new_HSP):
462 # Both hits has same coverage, and same identity
463 # and same length, how to choose only one hit?
464 pass
465
466 # TODO
467 # If new_score == old_score but identity and coverages are not the same.
468 # which gene should be chosen?? Now they are both keept.
469
470 # Save a split if the new hit creats one - both
471 # hits are saved
472 if(new_db_hit in tmp_gene_split
473 and hit_id not in tmp_gene_split[new_db_hit]):
474
475 tmp_gene_split[new_db_hit][hit_id] = 1
476 else:
477 # Remove new gene from gene split if present
478 if(new_db_hit in tmp_gene_split
479 and hit_id in tmp_gene_split[new_db_hit]):
480
481 del tmp_gene_split[new_db_hit][hit_id]
482
483 save = 0
484 break
485
486 # Remove old hit if new hit is better
487 if remove_old == 1:
488 del tmp_results[hit]
489
490 # Remove gene from gene split if present
491 if(old_db_hit in tmp_gene_split
492 and hit in tmp_gene_split[old_db_hit]):
493
494 del tmp_gene_split[old_db_hit][hit]
495
496 return save, tmp_gene_split, tmp_results
497
498 @staticmethod
499 def calculate_new_length(gene_split, gene_results, hit):
500 """
501 Function for calcualting new length if the gene is split on
502 several contigs
503 """
504 # Looping over splitted hits and calculate new length
505 first = 1
506 for split in gene_split[hit['sbjct_header']]:
507
508 new_start = int(gene_results[split]['sbjct_start'])
509 new_end = int(gene_results[split]['sbjct_end'])
510
511 # Get the first HSP
512 if first == 1:
513 new_length = int(gene_results[split]['HSP_length'])
514 old_start = new_start
515 old_end = new_end
516 first = 0
517 continue
518 if new_start < old_start:
519 new_length = new_length + (old_start - new_start)
520 old_start = new_start
521
522 if new_end > old_end:
523 new_length = new_length + (new_end - old_end)
524 old_end = new_end
525
526 return(new_length)
527
528 @staticmethod
529 def get_query_align(hit, contig):
530 """
531 Function for extracting extra seqeunce data to the query
532 alignment if the full reference length are not covered
533 """
534
535 # Getting data needed to extract sequences
536 query_seq = hit['query_string']
537 homo_seq = hit['homo_string']
538 sbjct_start = int(hit['sbjct_start'])
539 sbjct_end = int(hit['sbjct_end'])
540 query_start = int(hit['query_start'])
541 query_end = int(hit['query_end'])
542 length = int(hit['sbjct_length'])
543
544 # If the alignment doesn't start at the first position data is
545 # added to the begnning
546 if sbjct_start != 1:
547 missing = sbjct_start - 1
548
549 if(query_start >= missing and hit['strand'] != 1
550 or hit['strand'] == 1 and missing <= (len(contig) - query_end)):
551
552 # Getting the query sequence.
553 # If the the hit is on the other strand the characters
554 # are reversed.
555 if hit['strand'] == 1:
556 start_pos = query_end
557 end_pos = query_end + missing
558 chars = contig[start_pos:end_pos]
559 chars = Blaster.reversecomplement(chars)
560 else:
561 start_pos = query_start - missing - 1
562 end_pos = query_start - 1
563 chars = contig[start_pos:end_pos]
564
565 query_seq = chars + str(query_seq)
566 else:
567 # Getting the query sequence.
568 # If the the hit is on the other strand the characters
569 # are reversed.
570 if hit['strand'] == 1:
571 if query_end == len(contig):
572 query_seq = "-" * missing + str(query_seq)
573 else:
574 start_pos = query_end
575 chars = contig[start_pos:]
576 chars = Blaster.reversecomplement(chars)
577
578 query_seq = ("-" * (missing - len(chars))
579 + chars + str(query_seq))
580 elif query_start < 3:
581 query_seq = "-" * missing + str(query_seq)
582 else:
583 end_pos = query_start - 2
584 chars = contig[0:end_pos]
585
586 query_seq = ("-" * (missing - len(chars))
587 + chars + str(query_seq))
588
589 # Adding to the homo sequence
590 spaces = " " * missing
591 homo_seq = str(spaces) + str(homo_seq)
592
593 # If the alignment dosen't end and the last position data is
594 # added to the end
595 if sbjct_end < length:
596 missing = length - sbjct_end
597
598 if(missing <= (len(contig) - query_end) and hit['strand'] != 1
599 or hit['strand'] == 1 and query_start >= missing):
600
601 # Getting the query sequence.
602 # If the the hit is on the other strand the characters
603 # are reversed.
604 if hit['strand'] == 1:
605 start_pos = query_start - missing - 1
606 end_pos = query_start - 1
607 chars = contig[start_pos:end_pos]
608 chars = Blaster.reversecomplement(chars)
609 else:
610 start_pos = query_end
611 end_pos = query_end + missing
612 chars = contig[start_pos:end_pos]
613
614 query_seq = query_seq + chars
615 else:
616 # If the hit is on the other strand the characters are reversed
617 if hit['strand'] == 1:
618 if query_start < 3:
619 query_seq = query_seq + "-" * missing
620 else:
621 end_pos = query_start - 2
622 chars = contig[0:end_pos]
623 chars = Blaster.reversecomplement(chars)
624
625 query_seq = (query_seq
626 + chars + "-" * (missing - len(chars)))
627 elif query_end == len(contig):
628 query_seq = query_seq + "-" * missing
629 else:
630 start_pos = query_end
631 chars = contig[start_pos:]
632
633 query_seq = query_seq + chars + "-" * (missing - len(chars))
634
635 # Adding to the homo sequence
636 spaces = " " * int(missing)
637 homo_seq = str(homo_seq) + str(spaces)
638
639 return query_seq, homo_seq