Mercurial > repos > peterjc > align_back_trans
annotate tools/align_back_trans/align_back_trans.py @ 6:b27388e5a0bb draft
v0.0.10 removed unused reference to muscle format
author | peterjc |
---|---|
date | Mon, 21 Aug 2017 06:26:14 -0400 |
parents | 2c32e8a8990f |
children | 883842b81796 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/env python |
2 """Back-translate a protein alignment to nucleotides | |
3 | |
4 This tool is a short Python script (using Biopython library functions) to | |
5 load a protein alignment, and matching nucleotide FASTA file of unaligned | |
6 sequences, in order to produce a codon aware nucleotide alignment - which | |
7 can be viewed as a back translation. | |
8 | |
9 The development repository for this tool is here: | |
10 | |
3 | 11 * https://github.com/peterjc/pico_galaxy/tree/master/tools/align_back_trans |
0 | 12 |
13 This tool is available with a Galaxy wrapper from the Galaxy Tool Shed at: | |
14 | |
15 * http://toolshed.g2.bx.psu.edu/view/peterjc/align_back_trans | |
16 | |
17 See accompanying text file for licence details (MIT licence). | |
18 """ | |
19 | |
5 | 20 from __future__ import print_function |
21 | |
0 | 22 import sys |
4
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
23 |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
24 from Bio import AlignIO |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
25 from Bio import SeqIO |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
26 |
0 | 27 from Bio.Align import MultipleSeqAlignment |
4
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
28 from Bio.Alphabet import generic_protein |
0 | 29 from Bio.Data.CodonTable import ambiguous_generic_by_id |
4
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
30 from Bio.Seq import Seq |
0 | 31 |
32 if "-v" in sys.argv or "--version" in sys.argv: | |
5 | 33 print("v0.0.9") |
0 | 34 sys.exit(0) |
35 | |
36 | |
37 def check_trans(identifier, nuc, prot, table): | |
38 """Returns nucleotide sequence if works (can remove trailing stop)""" | |
39 if len(nuc) % 3: | |
3 | 40 sys.exit("Nucleotide sequence for %s is length %i (not a multiple of three)" |
1 | 41 % (identifier, len(nuc))) |
0 | 42 |
43 p = str(prot).upper().replace("*", "X") | |
44 t = str(nuc.translate(table)).upper().replace("*", "X") | |
45 if len(t) == len(p) + 1: | |
46 if str(nuc)[-3:].upper() in ambiguous_generic_by_id[table].stop_codons: | |
3 | 47 # Allow this... |
0 | 48 t = t[:-1] |
3 | 49 nuc = nuc[:-3] # edit return value |
0 | 50 if len(t) != len(p): |
2
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
51 err = ("Inconsistent lengths for %s, ungapped protein %i, " |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
52 "tripled %i vs ungapped nucleotide %i." % |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
53 (identifier, len(p), len(p) * 3, len(nuc))) |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
54 if t.endswith(p): |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
55 err += "\nThere are %i extra nucleotides at the start." % (len(t) - len(p)) |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
56 elif t.startswith(p): |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
57 err += "\nThere are %i extra nucleotides at the end." % (len(t) - len(p)) |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
58 elif p in t: |
3 | 59 # TODO - Calculate and report the number to trim at start and end? |
2
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
60 err += "\nHowever, protein sequence found within translated nucleotides." |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
61 elif p[1:] in t: |
9fbf29a8c12b
v0.0.6 use format_source; v0.0.5 more explicit error msg, citation info
peterjc
parents:
1
diff
changeset
|
62 err += "\nHowever, ignoring first amino acid, protein sequence found within translated nucleotides." |
3 | 63 sys.exit(err) |
0 | 64 |
65 if t == p: | |
66 return nuc | |
67 elif p.startswith("M") and "M" + t[1:] == p: | |
3 | 68 # Close, was there a start codon? |
0 | 69 if str(nuc[0:3]).upper() in ambiguous_generic_by_id[table].start_codons: |
70 return nuc | |
71 else: | |
3 | 72 sys.exit("Translation check failed for %s\n" |
0 | 73 "Would match if %s was a start codon (check correct table used)\n" |
74 % (identifier, nuc[0:3].upper())) | |
75 else: | |
3 | 76 # Allow * vs X here? e.g. internal stop codons |
77 m = "".join("." if x == y else "!" for (x, y) in zip(p, t)) | |
0 | 78 if len(prot) < 70: |
79 sys.stderr.write("Protein: %s\n" % p) | |
80 sys.stderr.write(" %s\n" % m) | |
81 sys.stderr.write("Translation: %s\n" % t) | |
82 else: | |
83 for offset in range(0, len(p), 60): | |
3 | 84 sys.stderr.write("Protein: %s\n" % p[offset:offset + 60]) |
85 sys.stderr.write(" %s\n" % m[offset:offset + 60]) | |
86 sys.stderr.write("Translation: %s\n\n" % t[offset:offset + 60]) | |
87 sys.exit("Translation check failed for %s\n" % identifier) | |
88 | |
0 | 89 |
90 def sequence_back_translate(aligned_protein_record, unaligned_nucleotide_record, gap, table=0): | |
6 | 91 """Back-translate a sequence.""" |
3 | 92 # TODO - Separate arguments for protein gap and nucleotide gap? |
0 | 93 if not gap or len(gap) != 1: |
94 raise ValueError("Please supply a single gap character") | |
95 | |
96 alpha = unaligned_nucleotide_record.seq.alphabet | |
97 if hasattr(alpha, "gap_char"): | |
98 gap_codon = alpha.gap_char * 3 | |
99 assert len(gap_codon) == 3 | |
100 else: | |
101 from Bio.Alphabet import Gapped | |
102 alpha = Gapped(alpha, gap) | |
3 | 103 gap_codon = gap * 3 |
0 | 104 |
105 ungapped_protein = aligned_protein_record.seq.ungap(gap) | |
106 ungapped_nucleotide = unaligned_nucleotide_record.seq | |
107 if table: | |
108 ungapped_nucleotide = check_trans(aligned_protein_record.id, ungapped_nucleotide, ungapped_protein, table) | |
109 elif len(ungapped_protein) * 3 != len(ungapped_nucleotide): | |
3 | 110 sys.exit("Inconsistent lengths for %s, ungapped protein %i, " |
0 | 111 "tripled %i vs ungapped nucleotide %i" % |
112 (aligned_protein_record.id, | |
113 len(ungapped_protein), | |
114 len(ungapped_protein) * 3, | |
115 len(ungapped_nucleotide))) | |
116 | |
117 seq = [] | |
118 nuc = str(ungapped_nucleotide) | |
119 for amino_acid in aligned_protein_record.seq: | |
120 if amino_acid == gap: | |
121 seq.append(gap_codon) | |
122 else: | |
123 seq.append(nuc[:3]) | |
124 nuc = nuc[3:] | |
125 assert not nuc, "Nucleotide sequence for %r longer than protein %r" \ | |
126 % (unaligned_nucleotide_record.id, aligned_protein_record.id) | |
127 | |
3 | 128 aligned_nuc = unaligned_nucleotide_record[:] # copy for most annotation |
129 aligned_nuc.letter_annotation = {} # clear this | |
130 aligned_nuc.seq = Seq("".join(seq), alpha) # replace this | |
0 | 131 assert len(aligned_protein_record.seq) * 3 == len(aligned_nuc) |
132 return aligned_nuc | |
133 | |
3 | 134 |
0 | 135 def alignment_back_translate(protein_alignment, nucleotide_records, key_function=None, gap=None, table=0): |
136 """Thread nucleotide sequences onto a protein alignment.""" | |
3 | 137 # TODO - Separate arguments for protein and nucleotide gap characters? |
0 | 138 if gap is None: |
139 gap = "-" | |
140 | |
141 aligned = [] | |
4
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
142 try: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
143 if key_function is None: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
144 for protein in protein_alignment: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
145 nucleotide = nucleotide_records[protein.id] |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
146 aligned.append(sequence_back_translate(protein, nucleotide, gap, table)) |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
147 else: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
148 for protein in protein_alignment: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
149 nucleotide = nucleotide_records[key_function(protein.id)] |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
150 aligned.append(sequence_back_translate(protein, nucleotide, gap, table)) |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
151 except KeyError: |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
152 raise ValueError("Could not find nucleotide sequence for protein %r" |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
153 % protein.id) |
c8469274d136
v0.0.8 Using Biopython 1.67 from Tool Shed or Conda package
peterjc
parents:
3
diff
changeset
|
154 |
0 | 155 return MultipleSeqAlignment(aligned) |
156 | |
157 | |
158 if len(sys.argv) == 4: | |
159 align_format, prot_align_file, nuc_fasta_file = sys.argv[1:] | |
160 nuc_align_file = sys.stdout | |
161 table = 0 | |
162 elif len(sys.argv) == 5: | |
163 align_format, prot_align_file, nuc_fasta_file, nuc_align_file = sys.argv[1:] | |
164 table = 0 | |
165 elif len(sys.argv) == 6: | |
166 align_format, prot_align_file, nuc_fasta_file, nuc_align_file, table = sys.argv[1:] | |
167 else: | |
3 | 168 sys.exit("""This is a Python script for 'back-translating' a protein alignment, |
0 | 169 |
170 It requires three, four or five arguments: | |
171 - alignment format (e.g. fasta, clustal), | |
172 - aligned protein file (in specified format), | |
173 - unaligned nucleotide file (in fasta format). | |
174 - aligned nucleotiode output file (in same format), optional. | |
175 - NCBI translation table (0 for none), optional | |
176 | |
177 The nucleotide alignment is printed to stdout if no output filename is given. | |
178 | |
179 Example usage: | |
180 | |
181 $ python align_back_trans.py fasta demo_prot_align.fasta demo_nucs.fasta demo_nuc_align.fasta | |
182 | |
183 Warning: If the output file already exists, it will be overwritten. | |
184 | |
185 This script is available with sample data and a Galaxy wrapper here: | |
186 https://github.com/peterjc/pico_galaxy/tree/master/tools/align_back_trans | |
187 http://toolshed.g2.bx.psu.edu/view/peterjc/align_back_trans | |
188 """) | |
189 | |
190 try: | |
191 table = int(table) | |
3 | 192 except ValueError: |
193 sys.exit("Bad table argument %r" % table) | |
0 | 194 |
195 prot_align = AlignIO.read(prot_align_file, align_format, alphabet=generic_protein) | |
196 nuc_dict = SeqIO.index(nuc_fasta_file, "fasta") | |
197 nuc_align = alignment_back_translate(prot_align, nuc_dict, gap="-", table=table) | |
198 AlignIO.write(nuc_align, nuc_align_file, align_format) |