Package Bio :: Package Fasta :: Module FastaAlign
[hide private]
[frames] | no frames]

Source Code for Module Bio.Fasta.FastaAlign

 1  """ 
 2  Code to deal with alignments written in Fasta format. 
 3   
 4  This mostly just uses the regular Fasta parsing stuff written by Jeff 
 5  to deal with all of the input and output formats. 
 6   
 7  functions: 
 8  o parse_file() 
 9   
10  classes: 
11  FastaAlignment""" 
12  # standard library 
13  import string 
14  import os 
15   
16  # biopython 
17  from Bio.Align.Generic import Alignment 
18  from Bio import Alphabet 
19  from Bio.Alphabet import IUPAC 
20  from Bio import Fasta 
21   
22 -def parse_file(file_name, type = 'DNA'):
23 """Parse the given file into a FastaAlignment object. 24 25 Arguments: 26 o file_name - The location of the file to parse. 27 o type - The type of information contained in the file. 28 """ 29 if type.upper() == 'DNA': 30 alphabet = IUPAC.ambiguous_dna 31 elif type.upper() == 'RNA': 32 alphabet = IUPAC.ambiguous_rna 33 elif type.upper() == 'PROTEIN': 34 alphabet = IUPAC.protein 35 else: 36 raise ValueError("Invalid type %s passed. Need DNA, RNA or PROTEIN" 37 % type) 38 39 # create a new alignment object 40 fasta_align = FastaAlignment(Alphabet.Gapped(alphabet)) 41 42 # now parse the file and fill up the alignment object 43 align_file = open(file_name, 'r') 44 45 parser = Fasta.RecordParser() 46 iterator = Fasta.Iterator(align_file, parser) 47 48 cur_align = iterator.next() 49 while cur_align: 50 fasta_align.add_sequence(cur_align.title, cur_align.sequence) 51 52 cur_align = iterator.next() 53 54 return fasta_align
55
56 -class FastaAlignment(Alignment):
57 """Work with the Fasta Alignment format. 58 59 The fasta alignment format is basically the same as the regular ol' 60 Fasta format we know and love, except the sequences have gaps 61 (represented by -'s). 62 """
63 - def __init__(self, alphabet = Alphabet.Gapped(IUPAC.ambiguous_dna)):
65
66 - def __str__(self):
67 """Print out a fasta version of the alignment info.""" 68 return_string = '' 69 for item in self._records: 70 new_f_record = Fasta.Record() 71 new_f_record.title = item.description 72 new_f_record.sequence = item.seq.data 73 74 return_string = return_string + str(new_f_record) + os.linesep + os.linesep 75 76 # have a extra newline, so strip two off and add one before returning 77 return string.rstrip(return_string) + os.linesep
78