Debian Codegraph @

cgecore/alignment.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """ This module contains core functions and classes related to alignment. """
3 ################################################################################
4 # CGE ALIGNMENT MODULE #
5 ################################################################################
6 import os, subprocess, collections
7 from Bio.Blast import NCBIXML
8 from Bio import SeqIO
9
10 # Python2 / Python3 specifik imports
11 try: from string import maketrans
12 except: maketrans = str.maketrans
13
14 def extended_cigar(aligned_template, aligned_query):
15 ''' Convert mutation annotations to extended cigar format
16
17 https://github.com/lh3/minimap2#the-cs-optional-tag
18
19 USAGE:
20 >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
21 >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
22 >>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3'
23 True
24 '''
25 # - Go through each position in the alignment
26 insertion = []
27 deletion = []
28 matches = []
29 cigar = []
30 for r_aa, q_aa in zip(aligned_template.lower(), aligned_query.lower()):
31 gap_ref = r_aa == '-'
32 gap_que = q_aa == '-'
33 match = r_aa == q_aa
34 if matches and not match:
35 # End match block
36 cigar.append(":%s"%len(matches))
37 matches = []
38 if insertion and not gap_ref:
39 # End insertion
40 cigar.append("+%s"%''.join(insertion))
41 insertion = []
42 elif deletion and not gap_que:
43 # End deletion
44 cigar.append("-%s"%''.join(deletion))
45 deletion = []
46 if gap_ref:
47 if insertion:
48 # Extend insertion
49 insertion.append(q_aa)
50 else:
51 # Start insertion
52 insertion = [q_aa]
53 elif gap_que:
54 if deletion:
55 # Extend deletion
56 deletion.append(r_aa)
57 else:
58 # Start deletion
59 deletion = [r_aa]
60 elif match:
61 if matches:
62 # Extend match block
63 matches.append(r_aa)
64 else:
65 # Start match block
66 matches = [r_aa]
67 else:
68 # Add SNP annotation
69 cigar.append("*%s%s"%(r_aa, q_aa))
70
71 if matches:
72 cigar.append(":%s"%len(matches))
73 del matches
74 if insertion:
75 # End insertion
76 cigar.append("+%s"%''.join(insertion))
77 del insertion
78 elif deletion:
79 # End deletion
80 cigar.append("-%s"%''.join(deletion))
81 del deletion
82
83 return ''.join(cigar)
84
85 def cigar2query(template, cigar):
86 ''' Generate query sequence from the template and extended cigar annotation
87
88 USAGE:
89 >>> template = 'CGATCGATAAATAGAGTAGGAATAGCA'
90 >>> cigar = ':6-ata:10+gtc:4*at:3'
91 >>> cigar2query(template, cigar) == 'CGATCGAATAGAGTAGGTCGAATtGCA'.upper()
92 True
93 '''
94 query = []
95 entries = ['+','-','*',':']
96 number = list(map(str,range(10)))
97 cigar_length = len(cigar)
98 num = []
99 entry = None
100 pos = 0
101 i = 0
102 while i < cigar_length:
103 if cigar[i] in entries:
104 # New entry
105 if entry == ':':
106 old_pos = pos
107 pos += int(''.join(num))
108 query.append(template[old_pos:pos])
109 num = []
110 entry = cigar[i]
111 if entry == '*':
112 i += 2
113 query.append(cigar[i])
114 pos += 1
115 elif cigar[i] in number:
116 num.append(cigar[i])
117 elif entry == '-':
118 pos += 1
119 elif entry == '+':
120 query.append(cigar[i])
121 i += 1
122
123 if entry == ':':
124 old_pos = pos
125 pos += int(''.join(num))
126 query.append(template[old_pos:pos])
127
128 return ''.join(query).upper()
129
130 def Blaster(inputfile, databases, db_path, out_path='.', min_cov=0.6,
131 threshold=0.9, blast='blastn', cut_off=True):
132 ''' BLAST wrapper method, that takes a simple input and produces a overview
133 list of the hits to templates, and their alignments
134
135 Usage
136 >>> import os, subprocess, collections
137 >>> from Bio.Blast import NCBIXML
138 >>> from Bio import SeqIO
139 >>> from string import maketrans
140 >>> inputfile = 'test.fsa'
141 >>> databases = ['enterobacteriaceae']
142 >>> db_path = '/path/to/databases/plasmidfinder/'
143 >>> Blaster(inputfile, databases, db_path)
144 '''
145 min_cov = 100 * float(min_cov)
146 threshold = 100 * float(threshold)
147
148 # For alignment
149 gene_align_query = dict() #will contain the sequence alignment lines
150 gene_align_homo = dict() #will contain the sequence alignment homolog string
151 gene_align_sbjct = dict() #will contain the sequence alignment allele string
152 results = dict() #will contain the results
153
154 for db in databases:
155 # Adding the path to the database and output
156 db_file = "%s/%s.fsa"%(db_path, db)
157 os.system("mkdir -p %s/tmp"%(out_path))
158 os.system("chmod 775 %s/tmp"%(out_path))
159 out_file = "%s/tmp/out_%s.xml"%(out_path, db)
160
161 # Running blast
162 cmd = "%s -subject %s -query %s -out %s -outfmt '5' -perc_identity %s -dust 'no'"%(blast, db_file, inputfile, out_file, threshold)
163 process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
164 out, err = process.communicate()
165
166 # Getting the results
167 result_handle = open(out_file)
168 blast_records = NCBIXML.parse(result_handle)
169
170 # Declaring variables for saving the results
171 gene_results = dict() #will contain the results for each gene
172
173 # For finding the best hits
174 best_hsp = dict()
175
176 # Keeping track of gene split
177 gene_split = collections.defaultdict(dict)
178
179 # Making the dicts for sequence outputs
180 gene_align_query[db] = dict()
181 gene_align_homo[db] = dict()
182 gene_align_sbjct[db] = dict()
183
184 # Parsing over the hits and only keeping the best
185 for blast_record in blast_records:
186 query = blast_record.query
187 blast_record.alignments.sort(key = lambda align: -max((len(hsp.query) * (int(hsp.identities)/float(len(hsp.query))) for hsp in align.hsps)))
188 for alignment in blast_record.alignments:
189 # Setting the e-value as 1 and bit as 0 to get the best HSP fragment
190 best_e_value = 1
191 best_bit = 0
192 for hsp in alignment.hsps:
193 if hsp.expect < best_e_value or hsp.bits > best_bit:
194 best_e_value = hsp.expect
195 best_bit = hsp.bits
196 tmp = alignment.title.split(" ")
197 sbjct_header = tmp[1]
198 bit = hsp.bits
199 sbjct_length = alignment.length
200 sbjct_start = hsp.sbjct_start
201 sbjct_end = hsp.sbjct_end
202 gaps = hsp.gaps
203 query_string = str(hsp.query)
204 homo_string = str(hsp.match)
205 sbjct_string = str(hsp.sbjct)
206 contig_name = query.replace(">","")
207 query_start = hsp.query_start
208 query_end = hsp.query_end
209 HSP_length = len(query_string)
210 perc_ident = int(hsp.identities)/float(HSP_length) * 100
211 strand = 0
212 coverage = ((int(HSP_length) - int(gaps))/float(sbjct_length))
213 perc_coverage = ((int(HSP_length) - int(gaps))/float(sbjct_length)) * 100
214 if int(HSP_length) == int(sbjct_length):
215 cal_score = perc_ident * coverage * 100
216 else:
217 cal_score = perc_ident * coverage
218 hit_id = "%s:%s..%s:%s:%f"%(contig_name, query_start, query_end, sbjct_header, cal_score)
219
220 # If the hit is on the other strand
221 if sbjct_start > sbjct_end:
222 tmp = sbjct_start
223 sbjct_start = sbjct_end
224 sbjct_end = tmp
225
226 query_string = reverse_complement(query_string)
227 homo_string = homo_string[::-1]
228 sbjct_string = reverse_complement(sbjct_string)
229 strand = 1
230
231 if cut_off == True:
232 if perc_coverage > 20 :
233 best_hsp = {'evalue': hsp.expect, 'sbjct_header': sbjct_header, 'bit': bit,
234 'perc_ident': perc_ident, 'sbjct_length':sbjct_length,
235 'sbjct_start': sbjct_start, 'sbjct_end': sbjct_end,
236 'gaps': gaps, 'query_string': query_string,
237 'homo_string': homo_string, 'sbjct_string': sbjct_string,
238 'contig_name': contig_name, 'query_start': query_start,
239 'query_end': query_end, 'HSP_length': HSP_length, 'coverage': coverage,
240 'cal_score': cal_score, 'hit_id': hit_id, 'strand': strand,
241 'perc_coverage': perc_coverage
242 }
243 else:
244 best_hsp = {'evalue': hsp.expect, 'sbjct_header': sbjct_header, 'bit': bit,
245 'perc_ident': perc_ident, 'sbjct_length':sbjct_length,
246 'sbjct_start': sbjct_start, 'sbjct_end': sbjct_end,
247 'gaps': gaps, 'query_string': query_string,
248 'homo_string': homo_string, 'sbjct_string': sbjct_string,
249 'contig_name': contig_name, 'query_start': query_start,
250 'query_end': query_end, 'HSP_length': HSP_length, 'coverage': coverage,
251 'cal_score': cal_score, 'hit_id': hit_id, 'strand': strand,
252 'perc_coverage': perc_coverage
253 }
254
255 # Saving the result if any
256 if best_hsp:
257 save = 1
258
259 # If there are other gene alignments they are compared
260 if gene_results:
261 tmp_gene_split = gene_split
262 tmp_results = gene_results
263
264 # Compare the hit results
265 save, gene_split, gene_results = compare_results(save, best_hsp, tmp_results, tmp_gene_split)
266
267 # If the hit is not overlapping with other hit seqeunces it is kept
268 if save == 1:
269 gene_results[hit_id] = best_hsp
270 else:
271 pass
272
273 # If the hit does not cover the entire database reference the missing seqence data are extracted
274 for hit_id in list(gene_results):
275 hit = gene_results[hit_id]
276
277 # Calculate possible split gene coverage
278 perc_coverage = hit['perc_coverage']
279
280 if hit['sbjct_header'] in gene_split and len(gene_split[hit['sbjct_header']]) > 1:
281 # Calculate new length
282 new_length = calculate_new_length(gene_split, gene_results, hit)
283 hit['split_length'] = new_length
284
285 # Calculate new coverage
286 perc_coverage = new_length / float(hit['sbjct_length']) * 100
287
288 # If the hit is above the minimum length threshold it is kept
289 if perc_coverage >= min_cov:
290 if hit['coverage'] == 1:
291 gene_align_query[db][hit_id] = hit['query_string']
292 gene_align_homo[db][hit_id] = hit['homo_string']
293 gene_align_sbjct[db][hit_id] = hit['sbjct_string']
294 elif hit['coverage'] != 1:
295 # Getting the whole database sequence
296 for seq_record in SeqIO.parse(db_file, "fasta"):
297 if seq_record.description == hit['sbjct_header']:
298 gene_align_sbjct[db][hit_id] = str(seq_record.seq)
299 break
300
301 # Getting the whole contig to extract extra query seqeunce
302 contig = ''
303 for seq_record in SeqIO.parse(inputfile, "fasta"):
304 if seq_record.description == hit['contig_name']:
305 contig = str(seq_record.seq)
306 break
307
308 # Extract extra sequence from query
309 query_seq, homo_seq = get_query_align(hit, contig)
310
311 # Saving the new alignment sequences
312 gene_align_query[db][hit_id] = query_seq
313 gene_align_homo[db][hit_id] = homo_seq
314
315 else:
316 del gene_results[hit_id]
317 if hit['sbjct_header'] in gene_split:
318 del gene_split[hit['sbjct_header']]
319
320 # Save the database result
321 if gene_results:
322 results[db] = gene_results
323 else:
324 results[db] = "No hit found"
325 return (results, gene_align_query, gene_align_homo, gene_align_sbjct)
326
327 trans = maketrans("AGCT","TCGA")
328 def reverse_complement(seq):
329 ''' Make reverse complement strand '''
330 return seq.translate(trans)[::-1]
331
332 def compare_results(save, best_hsp, tmp_results, tmp_gene_split):
333 ''' Function for comparing hits and saving only the best hit '''
334 # Get data for comparison
335 hit_id = best_hsp['hit_id']
336 new_start_query = best_hsp['query_start']
337 new_end_query = best_hsp['query_end']
338 new_start_sbjct = int(best_hsp['sbjct_start'])
339 new_end_sbjct = int(best_hsp['sbjct_end'])
340 new_score = best_hsp['cal_score']
341 new_db_hit = best_hsp['sbjct_header']
342 new_contig = best_hsp['contig_name']
343 new_HSP = best_hsp['HSP_length']
344
345 # See if the best HSP fragment overlap with another allignment and keep the
346 # allignment with the highest score - if the new fragment is not providing new seqeunce
347 for hit in list(tmp_results):
348 hit_data = tmp_results[hit]
349 old_start_query = hit_data['query_start']
350 old_end_query = hit_data['query_end']
351 old_start_sbjct = int(hit_data['sbjct_start'])
352 old_end_sbjct = int(hit_data['sbjct_end'])
353 old_score = hit_data['cal_score']
354 old_db_hit = hit_data['sbjct_header']
355 old_contig = hit_data['contig_name']
356 old_HSP = hit_data['HSP_length']
357
358 remove_old = 0
359
360 # If they align to the same gene in the database they are compared
361 if new_db_hit == old_db_hit:
362 # If the hit provids additional sequence it is kept and the new coverage is saved
363 # otherwise the one with the highest score is kept
364 if new_start_sbjct < (old_start_sbjct) or new_end_sbjct > (old_end_sbjct):
365 # Save the hits as splitted
366 tmp_gene_split[old_db_hit][hit_id] = 1
367 if not hit in tmp_gene_split[old_db_hit]:
368 tmp_gene_split[old_db_hit][hit] = 1
369 else:
370 if new_score > old_score:
371 # Set to remove old hit
372 remove_old = 1
373
374 # Save a split if the new hit still creats one
375 if new_db_hit in tmp_gene_split and not hit_id in tmp_gene_split[new_db_hit]:
376 tmp_gene_split[new_db_hit][hit_id] = 1
377 else:
378 save = 0
379
380 # If the old and new hit is not identical the possible saved gene split for the new hit is removed
381 if hit_id != hit:
382 if new_db_hit in tmp_gene_split and hit_id in tmp_gene_split[new_db_hit]:
383 del tmp_gene_split[new_db_hit][hit_id]
384 break
385
386 # If the hits comes form the same part of the contig sequnce but match different genes only the best hit is kept
387 if new_contig == old_contig:
388 # if the two hits cover the exact same place on the contig only
389 # the percentage of identity is compared
390 if old_start_query == new_start_query and old_end_query == new_end_query:
391 if best_hsp['perc_ident'] > hit_data['perc_ident']:
392
393 # Set to remove old hit
394 remove_old = 1
395
396 # Save a split if the new hit still creats one
397 if new_db_hit in tmp_gene_split and not hit_id in tmp_gene_split[new_db_hit]:
398 tmp_gene_split[new_db_hit][hit_id] = 1
399
400 elif best_hsp['perc_ident'] == hit_data['perc_ident']:
401 # Save both
402
403 # Save a split if the new hit still creats one
404 if new_db_hit in tmp_gene_split and not hit_id in tmp_gene_split[new_db_hit]:
405 tmp_gene_split[new_db_hit][hit_id] = 1
406 else:
407 save = 0
408 # Remove new gene from gene split if present
409 if new_db_hit in tmp_gene_split and hit_id in tmp_gene_split[new_db_hit]:
410 del tmp_gene_split[new_db_hit][hit_id]
411 break
412
413 elif (max(old_end_query, new_end_query) - min(old_start_query, new_start_query)) <= ((old_end_query - old_start_query) + (new_end_query - new_start_query)):
414 if new_score > old_score:
415 # Set to remove old gene
416 remove_old = 1
417
418 # Save a split if the new hit still creats one
419 if new_db_hit in tmp_gene_split and not hit_id in tmp_gene_split[new_db_hit]:
420 tmp_gene_split[new_db_hit][hit_id] = 1
421
422 elif new_score == old_score:
423 # If both genes are completly covered the longest hit is chosen
424 if int(best_hsp['perc_coverage']) == 100 and int(hit_data['perc_coverage']) == 100 and new_HSP > old_HSP:
425 # Set to remove old gene
426 remove_old = 1
427
428 # Save a split if the new hit creats one - both hits are saved
429 if new_db_hit in tmp_gene_split and not hit_id in tmp_gene_split[new_db_hit]:
430 tmp_gene_split[new_db_hit][hit_id] = 1
431 else:
432 # Remove new gene from gene split if present
433 if new_db_hit in tmp_gene_split and hit_id in tmp_gene_split[new_db_hit]:
434 del tmp_gene_split[new_db_hit][hit_id]
435
436 save = 0
437 break
438
439 # Remove old hit if new hit is better
440 if remove_old == 1:
441 del tmp_results[hit]
442 # Remove gene from gene split if present
443 if old_db_hit in tmp_gene_split and hit in tmp_gene_split[old_db_hit]:
444 del tmp_gene_split[old_db_hit][hit]
445
446 return save, tmp_gene_split, tmp_results
447
448 def calculate_new_length(gene_split, gene_results, hit):
449 ''' Function for calcualting new length if the gene is split on several
450 contigs
451 '''
452 # Looping over splitted hits and calculate new length
453 first = 1
454 for split in gene_split[hit['sbjct_header']]:
455 new_start = int(gene_results[split]['sbjct_start'])
456 new_end = int(gene_results[split]['sbjct_end'])
457
458 # Get the frist HSP
459 if first == 1:
460 new_length = int(gene_results[split]['HSP_length'])
461 old_start = new_start
462 old_end = new_end
463 first = 0
464 continue
465 if new_start < old_start:
466 new_length = new_length + (old_start - new_start)
467 old_start = new_start
468
469 if new_end > old_end:
470 new_length = new_length + (new_end - old_end)
471 old_end = new_end
472
473 return(new_length)
474
475 def get_query_align(hit, contig):
476 ''' Function for extracting extra seqeunce data to the query alignment if
477 the full reference length are not covered
478 '''
479 # Getting data needed to extract sequences
480 query_seq = hit['query_string']
481 homo_seq = hit['homo_string']
482 sbjct_start = int(hit['sbjct_start'])
483 sbjct_end = int(hit['sbjct_end'])
484 query_start = int(hit['query_start'])
485 query_end = int(hit['query_end'])
486 length = int(hit['sbjct_length'])
487
488 # If the alignment doesn't start at the first position data is added to the begnning
489 if sbjct_start!= 1:
490 missing = sbjct_start - 1
491
492 if query_start >= missing and hit['strand'] != 1 or hit['strand'] == 1 and missing <= (len(contig) - query_end):
493 # Getting the query sequence
494 # If the the hit is on the other strand the characters are reversed
495 if hit['strand'] == 1:
496 start_pos = query_end
497 end_pos = query_end + missing
498 chars = contig[start_pos:end_pos]
499 chars = reverse_complement(chars)
500 else:
501 start_pos = query_start - missing - 1
502 end_pos = query_start - 1
503 chars = contig[start_pos:end_pos]
504
505 query_seq = chars + str(query_seq)
506 else:
507 # Getting the query sequence
508 # If the the hit is on the other strand the characters are reversed
509 if hit['strand'] == 1:
510 if query_end == len(contig):
511 query_seq = "-" * missing + str(query_seq)
512 else:
513 start_pos = query_end
514 chars = contig[start_pos:]
515 chars = reverse_complement(chars)
516
517 query_seq = "-" * (missing - len(chars)) + chars + str(query_seq)
518 elif query_start < 3:
519 query_seq = "-" * missing + str(query_seq)
520 else:
521 end_pos = query_start - 2
522 chars = contig[0:end_pos]
523
524 query_seq = "-" * (missing - len(chars)) + chars + str(query_seq)
525
526 # Adding to the homo sequence
527 spaces = " " * missing
528 homo_seq = str(spaces) + str(homo_seq)
529
530 # If the alignment dosen't end and the last position data is added to the end
531 if sbjct_end < length:
532 missing = length - sbjct_end
533
534 if missing <= (len(contig) - query_end) and hit['strand'] != 1 or hit['strand'] == 1 and query_start >= missing:
535 # Getting the query sequence
536 # If the the hit is on the other strand the characters are reversed
537 if hit['strand'] == 1:
538 start_pos = query_start - missing - 1
539 end_pos = query_start - 1
540 chars = contig[start_pos:end_pos]
541 chars = reverse_complement(chars)
542 else:
543 start_pos = query_end
544 end_pos = query_end + missing
545 chars = contig[start_pos:end_pos]
546
547 query_seq = query_seq + chars
548 else:
549 # If the hit is on the other strand the characters are reversed
550 if hit['strand'] == 1:
551 if query_start < 3:
552 query_seq = query_seq + "-" * missing
553 else:
554 end_pos = query_start - 2
555 chars = contig[0:end_pos]
556 chars = reverse_complement(chars)
557
558 query_seq = query_seq + chars + "-" * (missing - len(chars))
559 elif query_end == len(contig):
560 query_seq = query_seq + "-" * missing
561 else:
562 start_pos = query_end
563 chars = contig[start_pos:]
564
565 query_seq = query_seq + chars + "-" * (missing - len(chars))
566
567 # Adding to the homo sequence
568 spaces = " " * int(missing)
569 homo_seq = str(homo_seq) + str(spaces)
570
571 return query_seq, homo_seq