Back to index

python-biopython  1.60
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
Bio.AlignIO.StockholmIO.StockholmIterator Class Reference
Inheritance diagram for Bio.AlignIO.StockholmIO.StockholmIterator:
Inheritance graph
[legend]
Collaboration diagram for Bio.AlignIO.StockholmIO.StockholmIterator:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def next

Public Attributes

 ids
 sequences
 seq_annotation
 seq_col_annotation

Static Public Attributes

dictionary pfam_gr_mapping
dictionary pfam_gs_mapping

Private Member Functions

def _identifier_split
def _get_meta_data
def _populate_meta_data

Private Attributes

 _header

Detailed Description

Loads a Stockholm file from PFAM into MultipleSeqAlignment objects.

The file may contain multiple concatenated alignments, which are loaded
and returned incrementally.

This parser will detect if the Stockholm file follows the PFAM
conventions for sequence specific meta-data (lines starting #=GS
and #=GR) and populates the SeqRecord fields accordingly.

Any annotation which does not follow the PFAM conventions is currently
ignored.

If an accession is provided for an entry in the meta data, IT WILL NOT
be used as the record.id (it will be recorded in the record's
annotations).  This is because some files have (sub) sequences from
different parts of the same accession (differentiated by different
start-end positions).

Wrap-around alignments are not supported - each sequences must be on
a single line.  However, interlaced sequences should work.

For more information on the file format, please see:
http://www.bioperl.org/wiki/Stockholm_multiple_alignment_format
http://www.cgb.ki.se/cgb/groups/sonnhammer/Stockholm.html

For consistency with BioPerl and EMBOSS we call this the "stockholm"
format.

Definition at line 267 of file StockholmIO.py.


Member Function Documentation

def Bio.AlignIO.StockholmIO.StockholmIterator._get_meta_data (   self,
  identifier,
  meta_dict 
) [private]
Takes an itentifier and returns dict of all meta-data matching it.

For example, given "Q9PN73_CAMJE/149-220" will return all matches to
this or "Q9PN73_CAMJE" which the identifier without its /start-end
suffix.

In the example below, the suffix is required to match the AC, but must
be removed to match the OS and OC meta-data::

    # STOCKHOLM 1.0
    #=GS Q9PN73_CAMJE/149-220  AC Q9PN73
    ...
    Q9PN73_CAMJE/149-220               NKA...
    ...
    #=GS Q9PN73_CAMJE OS Campylobacter jejuni
    #=GS Q9PN73_CAMJE OC Bacteria 

This function will return an empty dictionary if no data is found.

Definition at line 470 of file StockholmIO.py.

00470 
00471     def _get_meta_data(self, identifier, meta_dict):
00472         """Takes an itentifier and returns dict of all meta-data matching it.
00473 
00474         For example, given "Q9PN73_CAMJE/149-220" will return all matches to
00475         this or "Q9PN73_CAMJE" which the identifier without its /start-end
00476         suffix.
00477 
00478         In the example below, the suffix is required to match the AC, but must
00479         be removed to match the OS and OC meta-data::
00480 
00481             # STOCKHOLM 1.0
00482             #=GS Q9PN73_CAMJE/149-220  AC Q9PN73
00483             ...
00484             Q9PN73_CAMJE/149-220               NKA...
00485             ...
00486             #=GS Q9PN73_CAMJE OS Campylobacter jejuni
00487             #=GS Q9PN73_CAMJE OC Bacteria 
00488 
00489         This function will return an empty dictionary if no data is found."""
00490         name, start, end = self._identifier_split(identifier)
00491         if name==identifier:
00492             identifier_keys = [identifier]
00493         else:
00494             identifier_keys = [identifier, name]
00495         answer = {}
00496         for identifier_key in identifier_keys:
00497             try:
00498                 for feature_key in meta_dict[identifier_key]:
00499                     answer[feature_key] = meta_dict[identifier_key][feature_key]
00500             except KeyError:
00501                 pass
00502         return answer

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.AlignIO.StockholmIO.StockholmIterator._identifier_split (   self,
  identifier 
) [private]
Returns (name,start,end) string tuple from an identier.

Definition at line 457 of file StockholmIO.py.

00457 
00458     def _identifier_split(self, identifier):
00459         """Returns (name,start,end) string tuple from an identier."""
00460         if identifier.find("/")!=-1:
00461             name, start_end = identifier.rsplit("/",1)
00462             if start_end.count("-")==1:
00463                 try:
00464                     start, end = map(int, start_end.split("-"))
00465                     return (name, start, end)
00466                 except ValueError:
00467                     # Non-integers after final '/' - fall through
00468                     pass
00469         return (identifier, None, None)
    

Here is the caller graph for this function:

def Bio.AlignIO.StockholmIO.StockholmIterator._populate_meta_data (   self,
  identifier,
  record 
) [private]
Adds meta-date to a SecRecord's annotations dictionary.

This function applies the PFAM conventions.

Definition at line 503 of file StockholmIO.py.

00503 
00504     def _populate_meta_data(self, identifier, record):
00505         """Adds meta-date to a SecRecord's annotations dictionary.
00506 
00507         This function applies the PFAM conventions."""
00508 
00509         seq_data = self._get_meta_data(identifier, self.seq_annotation)
00510         for feature in seq_data:
00511             #Note this dictionary contains lists!
00512             if feature=="AC" : #ACcession number
00513                 assert len(seq_data[feature])==1
00514                 record.annotations["accession"]=seq_data[feature][0]
00515             elif feature=="DE" : #DEscription
00516                 record.description = "\n".join(seq_data[feature])
00517             elif feature=="DR" : #Database Reference
00518                 #Should we try and parse the strings?
00519                 record.dbxrefs = seq_data[feature]
00520             elif feature in self.pfam_gs_mapping:
00521                 record.annotations[self.pfam_gs_mapping[feature]] = ", ".join(seq_data[feature])
00522             else:
00523                 #Ignore it?
00524                 record.annotations["GS:" + feature] = ", ".join(seq_data[feature])
00525 
00526         #Now record the per-letter-annotations
00527         seq_col_data = self._get_meta_data(identifier, self.seq_col_annotation)
00528         for feature in seq_col_data:
00529             #Note this dictionary contains strings!
00530             if feature in self.pfam_gr_mapping:
00531                 record.letter_annotations[self.pfam_gr_mapping[feature]] = seq_col_data[feature]
00532             else:
00533                 #Ignore it?
                record.letter_annotations["GR:" + feature] = seq_col_data[feature]

Here is the call graph for this function:

Definition at line 311 of file StockholmIO.py.

00311 
00312     def next(self):
00313         try:
00314             line = self._header
00315             del self._header
00316         except AttributeError:
00317             line = self.handle.readline()
00318         if not line:
00319             #Empty file - just give up.
00320             raise StopIteration
00321         if not line.strip() == '# STOCKHOLM 1.0':
00322             raise ValueError("Did not find STOCKHOLM header")
00323             #import sys
00324             #print >> sys.stderr, 'Warning file does not start with STOCKHOLM 1.0'
00325 
00326         # Note: If this file follows the PFAM conventions, there should be
00327         # a line containing the number of sequences, e.g. "#=GF SQ 67"
00328         # We do not check for this - perhaps we should, and verify that
00329         # if present it agrees with our parsing.
00330 
00331         seqs = {}
00332         ids = []
00333         gs = {}
00334         gr = {}
00335         gf = {}
00336         passed_end_alignment = False
00337         while 1:
00338             line = self.handle.readline()
00339             if not line: break #end of file
00340             line = line.strip() #remove trailing \n
00341             if line == '# STOCKHOLM 1.0':
00342                 self._header = line
00343                 break
00344             elif line == "//":
00345                 #The "//" line indicates the end of the alignment.
00346                 #There may still be more meta-data
00347                 passed_end_alignment = True
00348             elif line == "":
00349                 #blank line, ignore
00350                 pass
00351             elif line[0] != "#":
00352                 #Sequence
00353                 #Format: "<seqname> <sequence>"
00354                 assert not passed_end_alignment
00355                 parts = [x.strip() for x in line.split(" ",1)]
00356                 if len(parts) != 2:
00357                     #This might be someone attempting to store a zero length sequence?
00358                     raise ValueError("Could not split line into identifier " \
00359                                       + "and sequence:\n" + line)
00360                 id, seq = parts
00361                 if id not in ids:
00362                     ids.append(id)
00363                 seqs.setdefault(id, '')
00364                 seqs[id] += seq.replace(".","-")
00365             elif len(line) >= 5:
00366                 #Comment line or meta-data
00367                 if line[:5] == "#=GF ":
00368                     #Generic per-File annotation, free text
00369                     #Format: #=GF <feature> <free text>
00370                     feature, text = line[5:].strip().split(None,1)
00371                     #Each feature key could be used more than once,
00372                     #so store the entries as a list of strings.
00373                     if feature not in gf:
00374                         gf[feature] = [text]
00375                     else:
00376                         gf[feature].append(text)
00377                 elif line[:5] == '#=GC ':
00378                     #Generic per-Column annotation, exactly 1 char per column
00379                     #Format: "#=GC <feature> <exactly 1 char per column>"
00380                     pass
00381                 elif line[:5] == '#=GS ':
00382                     #Generic per-Sequence annotation, free text
00383                     #Format: "#=GS <seqname> <feature> <free text>"
00384                     id, feature, text = line[5:].strip().split(None,2)
00385                     #if id not in ids:
00386                     #    ids.append(id)
00387                     if id not in gs:
00388                         gs[id] = {}
00389                     if feature not in gs[id]:
00390                         gs[id][feature] = [text]
00391                     else:
00392                         gs[id][feature].append(text)
00393                 elif line[:5] == "#=GR ":
00394                     #Generic per-Sequence AND per-Column markup
00395                     #Format: "#=GR <seqname> <feature> <exactly 1 char per column>"
00396                     id, feature, text = line[5:].strip().split(None,2)
00397                     #if id not in ids:
00398                     #    ids.append(id)
00399                     if id not in gr:
00400                         gr[id] = {}
00401                     if feature not in gr[id]:
00402                         gr[id][feature] = ""
00403                     gr[id][feature] += text.strip() # append to any previous entry
00404                     #TODO - Should we check the length matches the alignment length?
00405                     #       For iterlaced sequences the GR data can be split over
00406                     #       multiple lines
00407             #Next line...            
00408 
00409 
00410         assert len(seqs) <= len(ids)
00411         #assert len(gs)   <= len(ids)
00412         #assert len(gr)   <= len(ids)
00413 
00414         self.ids = ids
00415         self.sequences = seqs
00416         self.seq_annotation = gs
00417         self.seq_col_annotation = gr
00418 
00419         if ids and seqs:
00420 
00421             if self.records_per_alignment is not None \
00422             and self.records_per_alignment != len(ids):
00423                 raise ValueError("Found %i records in this alignment, told to expect %i" \
00424                                  % (len(ids), self.records_per_alignment))
00425 
00426             alignment_length = len(seqs.values()[0])
00427             records = [] #Alignment obj will put them all in a list anyway
00428             for id in ids:
00429                 seq = seqs[id]
00430                 if alignment_length != len(seq):
00431                     raise ValueError("Sequences have different lengths, or repeated identifier")
00432                 name, start, end = self._identifier_split(id)
00433                 record = SeqRecord(Seq(seq, self.alphabet),
00434                                    id = id, name = name, description = id,
00435                                    annotations = {"accession":name})
00436                 #Accession will be overridden by _populate_meta_data if an explicit
00437                 #accession is provided:
00438                 record.annotations["accession"]=name
00439 
00440                 if start is not None:
00441                     record.annotations["start"] = start
00442                 if end is not None:
00443                     record.annotations["end"] = end
00444 
00445                 self._populate_meta_data(id, record)
00446                 records.append(record)
00447             alignment = MultipleSeqAlignment(records, self.alphabet)
00448 
00449             #TODO - Introduce an annotated alignment class?
00450             #For now, store the annotation a new private property:
00451             alignment._annotations = gr
00452 
00453             return alignment
00454         else:
00455             raise StopIteration
00456 

Here is the caller graph for this function:


Member Data Documentation

Definition at line 341 of file StockholmIO.py.

Definition at line 413 of file StockholmIO.py.

Initial value:
{"SS" : "secondary_structure",
                       "SA" : "surface_accessibility",
                       "TM" : "transmembrane",
                       "PP" : "posterior_probability",
                       "LI" : "ligand_binding",
                       "AS" : "active_site",
                       "IN" : "intron"}

Definition at line 299 of file StockholmIO.py.

Initial value:
{"OS" : "organism",
                       "OC" : "organism_classification",
                       "LO" : "look"}

Definition at line 307 of file StockholmIO.py.

Definition at line 415 of file StockholmIO.py.

Definition at line 416 of file StockholmIO.py.

Definition at line 414 of file StockholmIO.py.


The documentation for this class was generated from the following file: