Back to index

python-biopython  1.60
_Track.py
Go to the documentation of this file.
00001 # Copyright 2003-2008 by Leighton Pritchard.  All rights reserved.
00002 # This code is part of the Biopython distribution and governed by its
00003 # license.  Please see the LICENSE file that should have been included
00004 # as part of this package.
00005 #
00006 # Contact:       Leighton Pritchard, Scottish Crop Research Institute,
00007 #                Invergowrie, Dundee, Scotland, DD2 5DA, UK
00008 #                L.Pritchard@scri.ac.uk
00009 ################################################################################
00010 
00011 """ Track module
00012 
00013     Provides:
00014 
00015     o Track - Container for a single track on the diagram, containing
00016                 FeatureSet and GraphSet objects
00017 
00018     For drawing capabilities, this module uses reportlab to draw and write
00019     the diagram:
00020 
00021     http://www.reportlab.com
00022 
00023     For dealing with biological information, the package expects BioPython
00024     objects:
00025 
00026     http://www.biopython.org
00027 
00028 """
00029 
00030 # ReportLab imports
00031 from reportlab.lib import colors
00032 
00033 # GenomeDiagram imports
00034 from _FeatureSet import FeatureSet
00035 from _GraphSet import GraphSet
00036 
00037 class Track(object):
00038     """ Track
00039 
00040         Provides:
00041 
00042         Methods:
00043 
00044         o __init__(self, name=None, ...) Called on instantiation
00045 
00046         o add_set(self, set)    Add a FeatureSet or GraphSet to the diagram
00047 
00048         o del_set(self, set_id) Delete a FeatureSet or GraphSet from the
00049                                 diagram
00050 
00051         o get_sets(self)    Returns a list of the sets in the track
00052 
00053         o get_ids(self)     Returns a list of the ids for sets in the track
00054 
00055         o range(self)   Returns the base/position range covered by the data in
00056                         the track
00057 
00058         o to_string(self, verbose=0)    Returns a string describing the data in
00059                                         the track
00060 
00061         o __getitem__(self, key)    Returns the set with the passed id
00062 
00063         o __str__(self) Returns a formatted string describing the track
00064 
00065         Attributes:
00066 
00067         o height    Int describing the relative height to other trackscale_fontsizes in the
00068                     diagram
00069 
00070         o name      String describing the track
00071 
00072         o hide      Boolean, 0 if the track is not to be drawn
00073         
00074         o start, end    Integers (or None) specifying start/end to draw just
00075                         a partial track.
00076 
00077         o greytrack     Boolean, 1 if a grey background to the track is to be
00078                         drawn
00079 
00080         o greytrack_labels  Int describing how many track-identifying labels
00081                             should be placed on the track at regular intervals
00082 
00083         o greytrack_font    String describing the font to use for the greytrack
00084                             labels
00085 
00086         o greytrack_fontsize    Int describing the font size to display the
00087                                 labels on the grey track
00088 
00089         o greytrack_font_rotation   Int describing the angle through which to
00090                                     rotate the grey track labels
00091 
00092         o greytrack_font_color     colors.Color describing the color to draw
00093                                     the grey track labels
00094 
00095         o scale     Boolean, 1 if a scale is to be drawn on the track
00096 
00097         o scale_format  String, defaults to None, when scale values are written
00098                         as numerals.  Setting this to 'SInt' invokes SI
00099                         unit-like multiples, such as Mbp, Kbp and so on.
00100 
00101         o scale_color  colors.Color to draw the elemnts of the scale
00102 
00103         o scale_font    String describing the font to use for the scale labels
00104 
00105         o scale_fontsize    Int describing the size of the scale label font
00106 
00107         o scale_fontangle   Int describing the angle at which to draw the scale
00108                             labels (linear only)
00109 
00110         o scale_ticks       Boolean, 1 if ticks should be drawn at all on the
00111                             scale
00112 
00113         o scale_largeticks  Float (0->1) describing the height of large
00114                             scale ticks relative to the track height.
00115 
00116         o scale_smallticks  Float (0->1) describing the height of large
00117                             scale ticks relative to the track height.
00118 
00119         o scale_largetick_interval  Int, describing the number of bases that
00120                                     should separate large ticks
00121 
00122         o scale_smalltick_interval  Int, describing the number of bases that
00123                                     should separate small ticks
00124 
00125         o scale_largetick_labels    Boolean describing whether position labels
00126                                     should be written over large ticks
00127                                     
00128         o scale_smalltick_labels    Boolean describing whether position labels
00129                                     should be written over small ticks
00130 
00131         o axis_labels       Boolean describing whether the value labels should
00132                             be placed on the Y axes
00133     """
00134     def __init__(self, name=None, height=1, hide=0, greytrack=0,
00135                  greytrack_labels=5, greytrack_fontsize=8,
00136                  greytrack_font='Helvetica', greytrack_font_rotation=0,
00137                  greytrack_font_color = colors.Color(0.6, 0.6, 0.6),
00138                  scale=1, scale_format=None, scale_color=colors.black,
00139                  scale_font='Helvetica', scale_fontsize=6,
00140                  scale_fontangle=45, scale_largeticks=0.5, scale_ticks=1,
00141                  scale_smallticks=0.3, scale_largetick_interval=1e6,
00142                  scale_smalltick_interval=1e4, scale_largetick_labels=1,
00143                  scale_smalltick_labels=0, axis_labels=1,
00144                  start=None, end=None,
00145                  greytrack_font_colour = None, scale_colour=None):
00146         """ __init__(self, name=None, ...)
00147 
00148             o height    Int describing the relative height to other tracks in the
00149                         diagram
00150 
00151             o name      String describing the track
00152 
00153             o hide      Boolean, 0 if the track is not to be drawn
00154 
00155             o greytrack     Boolean, 1 if a grey background to the track is to be
00156                             drawn
00157 
00158             o greytrack_labels  Int describing how many track-identifying labels
00159                                 should be placed on the track at regular intervals
00160 
00161             o greytrack_font    String describing the font to use for the greytrack
00162                                 labels
00163 
00164             o greytrack_fontsize    Int describing the font size to display the
00165                                     labels on the grey track
00166 
00167             o greytrack_font_rotation   Int describing the angle through which to
00168                                         rotate the grey track labels
00169 
00170             o greytrack_font_color     colors.Color describing the color to draw
00171                                        the grey track labels (overridden by
00172                                        backwards compatible argument with UK
00173                                        spelling, colour).
00174 
00175             o scale     Boolean, 1 if a scale is to be drawn on the track
00176 
00177             o scale_color  colors.Color to draw the elemnts of the scale
00178                            (overridden by backwards compatible argument with UK
00179                            spelling, colour).
00180 
00181             o scale_font    String describing the font to use for the scale labels
00182 
00183             o scale_fontsize    Int describing the size of the scale label font
00184 
00185             o scale_fontangle   Int describing the angle at which to draw the scale
00186                                 labels (linear only)
00187 
00188             o scale_ticks       Boolean, 1 if ticks should be drawn at all on the
00189                                 scale
00190 
00191             o scale_largeticks  Float (0->1) describing the height of large
00192                                 scale ticks relative to the track height.
00193 
00194             o scale_smallticks  Float (0->1) describing the height of large
00195                                 scale ticks relative to the track height.
00196 
00197             o scale_largetick_interval  Int, describing the number of bases that
00198                                         should separate large ticks
00199 
00200             o scale_smalltick_interval  Int, describing the number of bases that
00201                                         should separate small ticks
00202 
00203             o scale_largetick_labels    Boolean describing whether position labels
00204                                         should be written over large ticks
00205                                         
00206             o scale_smalltick_labels    Boolean describing whether position labels
00207                                         should be written over small ticks
00208 
00209             o name          String to help identify the track
00210             
00211             o height        Relative height to draw the track
00212 
00213             o axis_labels       Boolean describing whether the value labels should
00214                                 be placed on the Y axes
00215         """
00216         #Let the UK spelling (colour) override the USA spelling (color)
00217         if greytrack_font_colour is not None:
00218             greytrack_font_color = greytrack_font_colour
00219         if scale_colour is not None:
00220             scale_color = scale_colour
00221 
00222         self._next_id = 0       # This will count sets as they are added to the track
00223         self._sets = {}         # Holds sets, keyed by unique ID
00224 
00225         # Assign attribute values from instantiation
00226         self.height = height
00227         if name is not None:
00228             self.name = str(name)
00229         else:
00230             self.name = "Track"
00231         self.hide = hide
00232         self.start = start
00233         self.end = end
00234 
00235         # Attributes for the grey track background and labels
00236         self.greytrack = greytrack
00237         self.greytrack_labels = greytrack_labels
00238         self.greytrack_fontsize = greytrack_fontsize
00239         self.greytrack_font = greytrack_font
00240         self.greytrack_font_rotation = greytrack_font_rotation
00241         self.greytrack_fontcolor = greytrack_font_color
00242 
00243         # Attributes for the track scale
00244         self.scale = scale
00245         self.scale_format = scale_format
00246         self.scale_color = scale_color
00247         self.scale_font = scale_font
00248         self.scale_fontsize = scale_fontsize
00249         self.scale_fontangle = scale_fontangle
00250         self.scale_ticks = scale_ticks
00251         self.scale_largeticks = scale_largeticks
00252         self.scale_smallticks = scale_smallticks
00253         self.scale_largetick_interval = scale_largetick_interval
00254         self.scale_smalltick_interval = scale_smalltick_interval
00255         self.scale_largetick_labels = scale_largetick_labels
00256         self.scale_smalltick_labels = scale_smalltick_labels
00257         self.axis_labels = axis_labels
00258         
00259 
00260     def add_set(self, set):
00261         """ add_set(self, set)
00262 
00263             o set       A FeatureSet or GraphSet object
00264 
00265             Add a preexisting FeatureSet or GraphSet object to the track
00266         """
00267         set.id = self._next_id          # Assign unique id to set
00268         set.parent = self               # Make set's parent this track
00269         self._sets[self._next_id] = set # Add set, keyed by unique id
00270         self._next_id += 1              # Increment unique set ids
00271 
00272 
00273     def new_set(self, type='feature', **args):
00274         """ new_set(self, type='feature') -> FeatureSet or GraphSet
00275 
00276             Create a new FeatureSet or GraphSet object, add it to the
00277             track, and return for user manipulation
00278         """
00279         type_dict = {'feature': FeatureSet,
00280                      'graph': GraphSet
00281                      }        
00282         set = type_dict[type]()
00283         for key in args:
00284             setattr(set, key, args[key])        
00285         set.id = self._next_id          # Assign unique id to set
00286         set.parent = self               # Make set's parent this track
00287         self._sets[self._next_id] = set # Add set, keyed by unique id
00288         self._next_id += 1              # Increment unique set ids
00289         return set
00290 
00291 
00292     def del_set(self, set_id):
00293         """ del_set(self, set_id)
00294 
00295             o set_id        The unique id for the set in this track
00296 
00297             Remove the set with the passed id from the track
00298         """
00299         del self._sets[set_id]
00300 
00301 
00302     def get_sets(self):
00303         """ get_sets(self) -> FeatureSet or GraphSet
00304 
00305             Return the sets contained in this track
00306         """
00307         return self._sets.values()
00308 
00309 
00310     def get_ids(self):
00311         """ get_ids(self) -> [int, int, ...]
00312 
00313             Return the ids of all sets contained in this track
00314         """
00315         return self._sets.keys()
00316 
00317 
00318     def range(self):
00319         """ range(self) -> (int, int)
00320 
00321             Returns the lowest and highest base (or mark) numbers as a tuple
00322         """
00323         lows, highs = [], []            # Holds set of low and high values from sets
00324         if self.start is not None:
00325             lows.append(self.start)
00326         if self.end is not None:
00327             highs.append(self.end)
00328         for set in self._sets.values():
00329             low, high = set.range()     # Get each set range
00330             lows.append(low)
00331             highs.append(high)
00332         if lows:
00333             low = min(lows)
00334         else:
00335             low = None
00336         if highs:
00337             high = max(highs)
00338         else:
00339             high = None
00340         return low, high  # Return lowest and highest values
00341     
00342 
00343     def to_string(self, verbose=0):
00344         """ to_string(self, verbose=0) -> ""
00345 
00346             o verbose       Boolean indicating whether a short or complete
00347                             account of the track is required
00348 
00349             Returns a formatted string with information about the track
00350         """
00351         if not verbose:             # Return the short description
00352             return "%s" % self      # Use __str__ method instead
00353         else:                       # Return the long desription
00354             outstr = ["\n<%s: %s>" % (self.__class__, self.name)]
00355             outstr.append("%d sets" % len(self._sets))
00356             for key in self._sets:
00357                 outstr.append("set: %s" % self._sets[key])
00358             return "\n".join(outstr)      
00359 
00360 
00361     def __getitem__(self, key):
00362         """ __getitem__(self, key) -> int
00363 
00364             o key       The id of a set in the track
00365 
00366             Return the set with the passed id
00367         """
00368         return self._sets[key]
00369 
00370 
00371     def __str__(self):
00372         """ __str__(self) -> ""
00373 
00374             Returns a formatted string with information about the Track
00375         """
00376         outstr = ["\n<%s: %s>" % (self.__class__, self.name)]
00377         outstr.append("%d sets" % len(self._sets))
00378         return "\n".join(outstr)
00379     
00380 
00381 
00382 ################################################################################
00383 # RUN AS SCRIPT
00384 ################################################################################
00385 
00386 if __name__ == '__main__':
00387 
00388     # test code
00389     from Bio import SeqIO
00390     from Bio.SeqFeature import SeqFeature
00391     from _FeatureSet import FeatureSet
00392     from _GraphSet import GraphSet
00393     from random import normalvariate
00394     
00395     genbank_entry = SeqIO.read('/data/genomes/Bacteria/Nanoarchaeum_equitans/NC_005213.gbk', 'gb')
00396 
00397     gdfs1 = FeatureSet(0, 'Nanoarchaeum equitans CDS - CDS')
00398     gdfs2 = FeatureSet(1, 'Nanoarchaeum equitans CDS - gene')
00399     for feature in genbank_entry.features:
00400         if feature.type == 'CDS':
00401             gdfs1.add_feature(feature)
00402         if feature.type == 'gene':
00403             gdfs2.add_feature(feature)
00404 
00405     gdt = Track()
00406     gdt.add_set(gdfs1)
00407     gdt.add_set(gdfs2)
00408 
00409     graphdata = []
00410     for pos in xrange(1, len(genbank_entry.seq), 1000):
00411         graphdata.append((pos, normalvariate(0.5, 0.1)))
00412     gdgs = GraphSet(2, 'test data')
00413     gdgs.add_graph(graphdata, 'Test Data')
00414     gdt.add_set(gdgs)
00415     
00416     print gdt.get_ids()
00417     sets = gdt.get_sets()
00418     for set in sets:
00419         print set
00420 
00421     print gdt.get_element_limits()