Changeset 5610


Ignore:
Timestamp:
12/08/09 16:10:36 (10 years ago)
Author:
pnorton
Message:

Modified the existing plot_base into a grid_plot class that uses the new map and grid factories.

I've also modified the plot_lat_lon, plot_national and plot_rotated to used the grid_plot as a base class.

Location:
qesdi/geoplot/trunk/lib/geoplot
Files:
4 added
14 edited
1 moved

Legend:

Unmodified
Added
Removed
  • qesdi/geoplot/trunk/lib/geoplot/colour_bar.py

    r5605 r5610  
    153153        min, max = self.colourBarMin, self.colourBarMax 
    154154         
    155         if min == None and dataMin != None: 
     155        if dataMax.__class__.__name__ == 'MaskedArray': 
     156            dataMax = None 
     157             
     158        if dataMin.__class__.__name__ == 'MaskedArray': 
     159            dataMin = None 
     160         
     161        if min is None and not dataMin is None: 
    156162            min = dataMin 
    157         elif min == None: 
     163        elif min is None: 
    158164            min = 0 
    159165             
    160         if max == None and dataMax != None: 
     166        if max is None and not dataMax is None: 
    161167            max = dataMax 
    162         elif max == None: 
     168        elif max is None: 
    163169            max = 1 
    164170         
  • qesdi/geoplot/trunk/lib/geoplot/config.ini

    r5605 r5610  
    33renderer=cairo 
    44 
    5 [PlotBaseDefaults] 
    6 #to specify a default of none, dont include the value here 
    7 format=png 
    8 width=800 
    9 height=600 
    10 drawValues=False 
    11 drawValuesFile=False 
    12 xLimits = (-179.0, 180.0)  
    13 yLimits = ( -89.0,  90.0) 
    14 #xLimits = ( -11.0,  2.8) 
    15 #yLimits = (  49.0, 60.0) 
    16 dpi=100 
    17 valueFormat=%.2f 
    18 drawColourBar=True 
    19 drawLogo=True 
    20 drawCoast=True 
    21 drawRivers=False 
    22 addShapefile=False 
    23 plotTitle= 
    24 fontSize=medium 
    25 units='Unit Definition' 
    26 showGridLines=False 
    27 outputCMYK=False 
    28 drawMetadata = True 
    295 
    306[Defaults:ColourBar] 
     
    4218xLimits = (-180, 180)  
    4319yLimits = (-90, 90) 
     20#xLimits = ( -11.0,  2.8) 
     21#yLimits = (  49.0, 60.0) 
    4422drawCoast = True  
    4523drawRivers = True 
     
    6846numContourLines=10 
    6947contourLabelInterval=1 
     48 
     49[Defaults:GridDrawer] 
     50showGridLines=False 
     51drawValues=False 
     52drawValuesFile=False 
     53valueFormat=%.2f 
    7054 
    7155[PlotProperties] 
  • qesdi/geoplot/trunk/lib/geoplot/contour_plot.py

    r5605 r5610  
    1010    Creates a contour plot form the data stored in a netCDF file 
    1111    ''' 
    12   
     12    _accessableObjects = ['_contourDrawer'] 
     13    _accessableObjects.extend(ContourPlotBase._accessableObjects) 
     14     
    1315    def __init__(self, **kwargs): 
    1416        ''' 
     
    1618        ''' 
    1719         
    18         self._contourDrawer = ContourDrawer(**self._getArgs(kwargs, 'ContourDrawer')) 
    19          
     20        self._contourDrawer = ContourDrawer(**self._getArgs(kwargs, ContourDrawer.__name__)) 
     21                 
    2022        ContourPlotBase.__init__(self, **kwargs) 
    2123         
     
    2830        self._contourDrawer.draw(axes, grid, map.basemap, norm, cmap, self.fontSize) 
    2931     
    30  
    31     def __get_numContourLines(self): return self._contourDrawer.numContourLines 
    32     def __set_numContourLines(self, value): self._contourDrawer.numContourLines = value 
    33     numContourLines = property(__get_numContourLines, __set_numContourLines, None, "") 
    34  
    35     def __get_contourLabelInterval(self): return self._contourDrawer.contourLabelInterval 
    36     def __set_contourLabelInterval(self, value): self._contourDrawer.contourLabelInterval = value 
    37     contourLabelInterval = property(__get_contourLabelInterval, __set_contourLabelInterval, None, "") 
  • qesdi/geoplot/trunk/lib/geoplot/contour_plot_base.py

    r5605 r5610  
    1414log = logging.getLogger(__name__) 
    1515 
    16  
    17 class ContourPlotBase(object): 
     16_construtorDocString = """ 
     17Constructor for the abstract class PlotBase, should be called by any class inheriting 
     18from PlotBase. 
     19 
     20@param cdmsVar:the CDMS variable being plotted 
     21@type cdmsVar: 
     22@keyword format:the format of the output file 
     23@type format: a string , one of ('jpg','pdf','ps','png') 
     24@keyword width:the width of the drawn image in pixels, the actual width of 'pdf' and 'ps' 
     25    files will be altered by the dpi. 
     26@type width: integer 
     27@keyword height:the height of the drawn map in pixels, the actual width of 'pdf' and 'ps' 
     28    files will be altered by the dpi. 
     29@type height: integer 
     30@keyword xLimits:a tuple representing the (longitude) limits of the map 
     31@type xLimits: a tuple of 2 floats, corresponding to (min, max) 
     32@keyword yLimits:a tuple representing the (latitude) limits of the map 
     33@type yLimits: a tuple of 2 floats , corresponding to (min, max) 
     34@keyword dip: the resolution of the produced image 
     35@type dpi: integer 
     36@keyword cmap: the colour map to be used to draw the grid 
     37@type cmap: an instance of matplotlib.colors.LinearSegmentedColormap 
     38 
     39@keyword drawColourBar: indicates if the colour bar should be drawn 
     40@type drawColourBar: boolean 
     41@keyword colourBarLabel: the label for the colour bar 
     42@type colourBarLabel: string 
     43@keyword colourBarPosition: the orientation and position the colour bar is drawn on 
     44    the plot. The default is chosen based on the lat-lon limits of the plot. 
     45@type colourBarPosition: string, one of ['horizontal', 'vertical'] 
     46@keyword colourBarMax: the minimum value for the colour bar 
     47@type colourBarMax: float 
     48@keyword colourBarMin: the maximum value for the colour bar 
     49@type colourBarMin: float 
     50@keyword drawLogo: indicates wheather to draw the UKCIP08 logo 
     51@type drawLogo: boolean 
     52@keyword drawCoast: indicates if coaslines should be drawn 
     53@type drawCoast: boolean 
     54@keyword drawRivers: indicates if rivers should be drawn 
     55@type drawRivers: boolean 
     56@keyword plotTitle: the title of the plot 
     57@type plotTitle: string 
     58@keyword units: the units of the value being plotted 
     59@type units: string 
     60@keyword metadataList: the metadata to be displayed along with the plot, if None no 
     61    metadata box will be drawn 
     62@type metadataList: a list of (key, value) tuples. The keys and values should both be 
     63    strings. 
     64@keyword fontSize: a general indication of the size of the fonts used on the plot 
     65@type fontSize: a string, one of ["small","medium" ,"large", 'xl', 'xxl'] 
     66@keyword units: the units the cdmsVar data is in, if no colourBarLabel is specified 
     67    the units will be used instead. 
     68@type units: string 
     69 
     70@keyword addShapefile: location of shapefile to overlay 
     71@type addShapefile: string 
     72""" 
     73 
     74class PlotBase(object): 
    1875    ''' 
    1976    Creates a contour plot form the data stored in a netCDF file 
     
    2481     
    2582    def __init__(self, **kwargs): 
    26         ''' 
    27         Creates the contour plot 
    28         ''' 
     83        # doc string a top of file 
    2984         
    3085        self.units = kwargs.pop('units', None) 
     
    4499        if len(kwargs.keys()) > 0: 
    45100            log.warning("Unused keyword arguments = %s" % (kwargs,)) 
    46          
     101     
     102    __init__.__doc__ = _construtorDocString 
     103      
    47104    def _getArgs(self, kwargs, className): 
    48105        args = {} 
     
    151208         
    152209        objFoundIn = None 
    153         for objName in ContourPlotBase._accessableObjects: 
     210        for objName in self.__class__._accessableObjects: 
    154211             
    155212    
  • qesdi/geoplot/trunk/lib/geoplot/grid_builder_base.py

    r5552 r5610  
    7676#         
    7777        reducedVar = self._getResizedVar(xLimits, yLimits) 
     78         
    7879             
    7980        (gridBoundsX, gridBoundsY) = self._buildGridBounds(reducedVar) 
     
    8283        gridValues = self._buildGridValues(reducedVar) 
    8384                 
    84 #        log.debug("After resize:") 
    85 #        log.debug("y midpoints min =[" + str(gridMidpointY.min()) + \ 
    86 #                "] max =[" + str(gridMidpointY.max()) + "]") 
    87 #        log.debug("x midpoints min =[" + str(gridMidpointX.min()) + \ 
    88 #                "] max =[" + str(gridMidpointX.max()) + "]") 
    89 #         
    90 #        log.debug("Diff: y [" + str(gridMidpointY.min() - ymid.min()) + \ 
    91 #                  "][" + str(gridMidpointY.max() - ymid.max()) ) 
    92 #        log.debug("Diff: x [" + str(gridMidpointX.min() - xmid.min()) + \ 
    93 #                  "][" + str(gridMidpointX.max() - xmid.max()) +"]") 
    94          
    95  
    96 #        log.debug("gridMidpointX = %s" % (gridMidpointX,)) 
    97 #        log.debug("gridMidpointY = %s" % (gridMidpointY,)) 
    98 #        log.debug("gridBoundsX = %s" % (gridBoundsX,)) 
    99 #        log.debug("gridBoundsY = %s" % (gridBoundsY,)) 
     85        log.debug("After resize:") 
     86        log.debug("y midpoints min =[" + str(gridMidpointY.min()) + \ 
     87                "] max =[" + str(gridMidpointY.max()) + "]") 
     88        log.debug("x midpoints min =[" + str(gridMidpointX.min()) + \ 
     89                "] max =[" + str(gridMidpointX.max()) + "]") 
     90         
     91        log.debug("Diff: y [" + str(gridMidpointY.min() - ymid.min()) + \ 
     92                  "][" + str(gridMidpointY.max() - ymid.max()) ) 
     93        log.debug("Diff: x [" + str(gridMidpointX.min() - xmid.min()) + \ 
     94                  "][" + str(gridMidpointX.max() - xmid.max()) +"]") 
     95         
     96        log.debug("self.cdmsVar.shape = %s" % (self.cdmsVar.shape,)) 
     97        log.debug("gridValues.shape = %s" % (gridValues.shape,)) 
     98        log.debug("gridBoundsX.shape = %s" % (gridBoundsX.shape,)) 
    10099 
    101100        return Grid(gridBoundsX, gridBoundsY, gridMidpointX, gridMidpointY, gridValues) 
     
    231230        """ 
    232231        bounds = [] 
     232        log.debug("values = %s" % (values,)) 
    233233        shift = (values[1] - values[0])/2 
    234234        bounds.append(values[0] - shift) 
  • qesdi/geoplot/trunk/lib/geoplot/grid_builder_national.py

    r5552 r5610  
    2929trueOrigin = (358.0, 49.0) 
    3030falseOrigin = (-400000, 100000) 
     31 
     32maxXBounds=(-20.0,  15.0); maxYBounds=( 40.0, 70.0) 
    3133 
    3234# Create a basemap with the origin at the true origin. 
     
    4951        """ 
    5052        log.debug('Resizing grid, xLimits: ' + repr(xLimits) + ' yLimits: ' + repr(yLimits)) 
     53 
     54        if xLimits[0] < maxXBounds[0] or xLimits[1] > maxXBounds[1]: 
     55            raise Exception("xLimits (=%s) is outside maximum %s" % (xLimits, maxXBounds)) 
     56         
     57        if yLimits[0] < maxYBounds[0] or yLimits[1] > maxYBounds[1]: 
     58            raise Exception("yLimits (=%s) is outside maximum %s" % (yLimits, maxYBounds)) 
     59         
    5160 
    5261        eastLow, northLow = nationalGrid(xLimits[0], yLimits[0]) 
     
    120129        xAxis = cdmsVar.getAxis(1) 
    121130 
     131        log.debug("xAxis = %s" % (xAxis,)) 
     132         
    122133        xBounds = GridBuilderBase._getBoundsFromAxis(xAxis) 
    123134        yBounds = GridBuilderBase._getBoundsFromAxis(yAxis) 
  • qesdi/geoplot/trunk/lib/geoplot/grid_builder_rotated.py

    r5552 r5610  
    5252        falls within the lat-lon limits provided. 
    5353        """ 
    54  
     54     
    5555        (xLimitsMin, xLimitsMax) = (min(xLimits), max(xLimits)) 
    5656        (yLimitsMin, yLimitsMax) = (min(yLimits), max(yLimits))  
     
    124124# 
    125125#        log.debug("self.cdmsVar = %s" % (self.cdmsVar,)) 
    126 #        log.debug("self.cdmsVar.getAxisList() = %s" % (self.cdmsVar.getAxisList(),)) 
     126        log.debug("self.cdmsVar.getAxisIds() = %s" % (self.cdmsVar.getAxisIds(),)) 
    127127         
    128128        newVar = None 
     
    153153        e.g. xBounds[x,y] will give the lower x boundary for the gridbox x,y.  
    154154        """ 
    155          
    156         log.debug("cdmsVar.getAxisList() = %s" % (cdmsVar.getAxisList(),)) 
    157          
     155                 
    158156        # Find the rotated axes for cmdsVar 
    159157        rlon = [x for x in cdmsVar.getAxisList() if x.isLongitude()][0] 
  • qesdi/geoplot/trunk/lib/geoplot/grid_drawer.py

    r5605 r5610  
    5050        self.outline = outline 
    5151 
    52     def draw(self, axes, grid, limits=None, basemap=None, cmapRange=(None,None), 
    53              cmap=None): 
     52    def draw(self, axes, grid, limits=None, basemap=None, norm=None, 
     53             cmap=None, fontSize='medium' ): 
    5454        """ 
    5555        Draws the grid given on the axis. 
     
    6767        if cmap == None: 
    6868            cmap = matplotlib.cm.get_cmap() 
    69             cmap.set_bad("w")         
     69            cmap.set_bad("w")    
     70         
     71        if norm == None: 
     72            norm = matplotlib.colors.Normalize(grid.values.min(), grid.values.max())      
    7073 
    7174#        log.info("Drawing Grid") 
     
    7982 
    8083        #draw the grid return the quadmesh for use 
    81         sm = self._drawGridBoxes(axes, grid_mapUnits, cmapRange, basemap, cmap) 
     84        sm = self._drawGridBoxes(axes, grid_mapUnits, basemap, cmap, norm) 
    8285         
    8386#        log.debug("self.drawValues = %s" % (self.drawValues,)) 
     
    9093            self._drawMeshValues(axes, grid_mapUnits, xLimits, yLimits) 
    9194         
    92         self._setScalarMeshValueLimits(sm, cmapRange) 
    93          
    94         return sm 
    9595 
    9696    def _transformLimits(self, limits, basemap): 
     
    102102            return basemap(limits[0], limits[1]) 
    103103 
    104     def _drawGridBoxes(self, axes,  grid_mapUnits, cmapRange, basemap, cmap): 
     104    def _drawGridBoxes(self, axes,  grid_mapUnits, basemap, cmap, norm): 
    105105        """ 
    106106        Draws the grid boxes onto the axes. 
     
    110110        gridLineWidth = 0.25 
    111111 
    112         kwargs = {'cmap':cmap} 
     112        kwargs = {'cmap':cmap, 'norm':norm} 
    113113         
    114114        if self.outline == True : 
     
    146146         
    147147        if valuesFound == True: 
    148  
    149             #doing this will reset the size of limits/bounds of the plot 
    150             norm = None 
    151             if cmapRange != None and cmapRange != (None, None): 
     148            
     149            st = time.time() 
     150             
     151            log.debug("grid_mapUnits.boundsX.shape = %s" % (grid_mapUnits.boundsX.shape,)) 
     152            log.debug("grid_mapUnits.boundsY.shape = %s" % (grid_mapUnits.boundsY.shape,)) 
     153            log.debug("grid_mapUnits.values.shape = %s" % (grid_mapUnits.values.shape,)) 
     154             
     155            values = grid_mapUnits.values 
     156             
     157            assert grid_mapUnits.boundsX.shape == grid_mapUnits.boundsY.shape 
     158             
     159            boundsShape = grid_mapUnits.boundsX.shape 
     160             
     161            #try to fix the values if they are not the expected shape 
     162            if values.shape[0] != boundsShape[0] -1 and values.shape[1] != boundsShape[1] -1: 
    152163                 
    153                 log.debug("cmapRange = %s" % (cmapRange,)) 
    154                 norm = matplotlib.colors.Normalize(cmapRange[0], cmapRange[1]) 
    155                 levels = N.linspace(cmapRange[0], cmapRange[1], 10) 
    156              
    157                 kwargs['norm'] = norm 
    158                 log.debug("levels = %s" % (levels,)) 
    159              
     164                #check if the axis were in the opposite order 
     165                if values.shape[1] == boundsShape[0] -1 and values.shape[0] == boundsShape[1] -1: 
     166                    values = N.transpose(values) 
     167                  
     168            log.debug("values.shape = %s" % (values.shape,)) 
     169 
     170            axes.pcolormesh(grid_mapUnits.boundsX,  
     171                            grid_mapUnits.boundsY,  
     172                            values,  
     173                            **kwargs) 
     174             
     175            log.debug("drawn mesh in %s" % (time.time() - st ,)) 
     176 
    160177#            st = time.time() 
    161178#             
    162 #            sm = axes.pcolormesh(grid_mapUnits.boundsX,  
    163 #                                 grid_mapUnits.boundsY,  
    164 #                                 grid_mapUnits.values, **kwargs) 
     179#            boundsMin = grid_mapUnits.boundsY[0,0] 
     180#            boundsMax = grid_mapUnits.boundsY[-1,-1] 
    165181#             
    166 #            log.debug("drawn mesh in %s" % (time.time() - st ,)) 
    167  
    168             st = time.time() 
    169              
    170             boundsMin = grid_mapUnits.boundsY[0,0] 
    171             boundsMax = grid_mapUnits.boundsY[-1,-1] 
    172              
    173             log.debug("boundsMin = %s" % (boundsMin,)) 
    174             log.debug("boundsMax = %s" % (boundsMax,)) 
    175              
    176             if boundsMin < boundsMax: 
    177                 extent=(grid_mapUnits.boundsX.min(), grid_mapUnits.boundsX.max(), 
    178                         grid_mapUnits.boundsY.max(), grid_mapUnits.boundsY.min())                 
    179             else: 
    180                 extent=(grid_mapUnits.boundsX.min(), grid_mapUnits.boundsX.max(), 
    181                         grid_mapUnits.boundsY.min(), grid_mapUnits.boundsY.max()) 
    182              
    183             im = axes.imshow(grid_mapUnits.values, extent=extent, 
    184                  interpolation='nearest', 
    185                  norm=norm, 
    186                  cmap=kwargs['cmap'], 
    187             ) 
    188              
    189             sm = matplotlib.collections.Collection() 
    190             sm.set_array(N.array([0,1])) 
    191                          
    192             axes.set_aspect('auto') 
    193              
    194             log.debug("drawn imshow in %s" % (time.time() - st ,)) 
    195                          
    196         else: 
    197              
    198             sm = matplotlib.collections.Collection() 
    199             sm.set_array(N.array([0,1])) 
    200              
    201         return sm 
     182#            log.debug("boundsMin = %s" % (boundsMin,)) 
     183#            log.debug("boundsMax = %s" % (boundsMax,)) 
     184#             
     185#            if boundsMin < boundsMax: 
     186#                extent=(grid_mapUnits.boundsX.min(), grid_mapUnits.boundsX.max(), 
     187#                        grid_mapUnits.boundsY.max(), grid_mapUnits.boundsY.min())                 
     188#            else: 
     189#                extent=(grid_mapUnits.boundsX.min(), grid_mapUnits.boundsX.max(), 
     190#                        grid_mapUnits.boundsY.min(), grid_mapUnits.boundsY.max()) 
     191#             
     192#            im = axes.imshow(grid_mapUnits.values, extent=extent, 
     193#                 interpolation='nearest', 
     194#                 **kwargs 
     195#            ) 
     196#                         
     197#            axes.set_aspect('auto') 
     198#             
     199#            log.debug("drawn imshow in %s" % (time.time() - st ,)) 
     200 
    202201     
    203202    def _drawGridAsLines(self, axes, X, Y, color='0.25', linewidth=0.3): 
     
    251250            drawValuesList = False 
    252251 
    253         ni, nj = N.shape(xMidpoints_mapUnits) 
     252        ni, nj = N.shape(grid_mapUnits.midpointsX) 
    254253         
    255254        if xLimits != None: 
     
    360359 
    361360        return cellList 
    362  
    363  
    364     def _setScalarMeshValueLimits(self, sm, range): 
    365         """ 
    366         Changes the limits of the given scalar mesh to the limits specified in 
    367         the constructor. 
    368  
    369         First checks if the min/max value is not None before using it to set the 
    370         value on the scalar mesh. If the min/max value is None then the mesh 
    371         limit is not changed. 
    372  
    373         @param sm: the scalar mappable generated by applying the grid to the axis 
    374         @type sm: an instance of matplotlib.cm.ScalarMappable 
    375         @param range: the range of mapable values  
    376         @type range: 2 item tuple of (min, max)         
    377         """ 
    378         
    379         (dataMin, dataMax) = sm.get_clim() 
    380         (minVal, maxVal) = range 
    381  
    382         if minVal != None and maxVal != None: 
    383             sm.set_clim(minVal, maxVal) 
    384  
    385         elif minVal != None: 
    386             sm.set_clim(minVal, dataMax) 
    387  
    388         elif maxVal != None: 
    389             sm.set_clim(dataMin, maxVal) 
    390              
    391         (dataMin, dataMax) = sm.get_clim() 
    392361  
    393362if __name__ == '__main__': 
  • qesdi/geoplot/trunk/lib/geoplot/grid_plot.py

    r5605 r5610  
    88 
    99#Standard library imports 
     10import os 
    1011import sys 
    11 import os 
    1212import time 
     13import logging 
    1314 
    14 import cdms2 as cdms 
    15 import matplotlib 
     15from geoplot.contour_plot_base import PlotBase 
     16from geoplot.grid_drawer import GridDrawer 
    1617 
    17 from geoplot.plotarea import PlotArea 
    18 from geoplot.plot_writer import PlotWriter 
    19 from geoplot.colour_bar import ColourBar 
    20 from geoplot.metadata_box import MetadataBox 
    21 from geoplot.grid_drawer import GridDrawer 
    22 from geoplot.contour_drawer import ContourDrawer 
    23  
     18import geoplot.utils as geoplot_utils 
    2419import geoplot.config as geoplot_config 
    25 import geoplot.utils as geoplot_utils 
    2620 
    2721config = geoplot_config.getConfig() 
    28  
    29 import logging 
    3022log = logging.getLogger(__name__) 
    3123 
    32 DEFAULTS_SECTION = 'PlotBaseDefaults' 
     24_construtorDocString = PlotBase.__init__.__doc__ + \ 
     25""" 
     26@type    drawValues: boolean 
     27@keyword drawValues: indicates if values should be drawn in grid boxes 
    3328 
    34 class PlotBase(object): 
     29@type    drawValuesFile: string 
     30@keyword drawValuesFile: indicates if a file should be read to determine which cells to  
     31    draw values inside. Only used if drawValues and this argument are not False. 
     32 
     33@type    valueFormat: a python format string 
     34@keyword valueFormat: format string for the vlaues drawn in the grid boxs 
     35 
     36@type    showGridLines: boolean 
     37@keyword showGridLines: indicates if the gridlines should be shown on the plot 
     38""" 
     39 
     40class GridPlot(PlotBase): 
    3541    """ 
    36     Creates a rotated grid over a map and writes it to a file. 
     42    """ 
     43     
     44    #add the grid drawer to the accessable object via __getatttr__ and __setattr__ 
     45    _accessableObjects = ['_gridDrawer'] 
     46    _accessableObjects.extend(PlotBase._accessableObjects) 
     47     
     48    def __init__(self, **kwargs): 
     49        # docString at top of file # 
     50         
     51        self._gridDrawer = GridDrawer(**self._getArgs(kwargs, GridDrawer.__name__)) 
     52                 
     53        PlotBase.__init__(self, **kwargs) 
     54         
     55    __init__.doc = _construtorDocString 
     56         
     57    def _drawDiagram(self, map, grid, axes): 
     58         
     59        log.debug("grid.values.min() = %s" % (grid.values.min(),)) 
     60        log.debug("grid.values.max() = %s" % (grid.values.max(),)) 
     61         
     62        norm = self._colourBar.getNormalize(dataMin=grid.values.min(), dataMax=grid.values.max()) 
     63        cmap = self._colourBar.getColourMap() 
     64         
     65        self._gridDrawer.draw(axes, grid, limits=(self.xLimits, self.yLimits), 
     66                              basemap=map.basemap,  
     67                              norm=norm, cmap=cmap,  
     68                              fontSize=self.fontSize) 
    3769 
    38     This is an abstract class. Any methods that iherit from this class need to impliment 
    39     self.getMap() and self.getGrid() so that a map and grid class are returned. 
    40     """ 
    41  
    42     validConstructorKWArgs = ['format', 'width', 'height', 'drawValues', 'drawValuesFile', 
    43                               'xLimits', 'yLimits', 'dpi', 'cmap', 'valueFormat', 
    44                               'drawColourBar', 'colourBarLabel', 'colourBarPosition', 
    45                               'colourBarMin', 'colourBarMax', 'drawLogo', 'drawCoast', 
    46                               'drawRivers', 'plotTitle', 'metadataList', 'fontSize' , 
    47                               'units', 'showGridLines', 'outputCMYK', 'addShapefile',  
    48                               'drawMetadata'] 
    49  
    50     def __init__(self, cdmsVar, **kwargs): 
    51         """ 
    52         Constructor for the abstract class PlotBase, should be called by any class inheriting 
    53         from PlotBase. 
    54  
    55         @param cdmsVar:the CDMS variable being plotted 
    56         @type cdmsVar: 
    57         @keyword format:the format of the output file 
    58         @type format: a string , one of ('jpg','pdf','ps','png') 
    59         @keyword width:the width of the drawn image in pixels, the actual width of 'pdf' and 'ps' 
    60             files will be altered by the dpi. 
    61         @type width: integer 
    62         @keyword height:the height of the drawn map in pixels, the actual width of 'pdf' and 'ps' 
    63             files will be altered by the dpi. 
    64         @type height: integer 
    65         @keyword drawValues: indicates if values should be drawn in grid boxes 
    66         @type drawValues: boolean 
    67         @keyword drawValuesFile: indicates if a file should be read to determine which cells to  
    68             draw values inside. Only used if drawValues and this argument are not False. 
    69         @type drawValuesFile: string 
    70         @keyword xLimits:a tuple representing the (longitude) limits of the map 
    71         @type xLimits: a tuple of 2 floats, corresponding to (min, max) 
    72         @keyword yLimits:a tuple representing the (latitude) limits of the map 
    73         @type yLimits: a tuple of 2 floats , corresponding to (min, max) 
    74         @keyword dip: the resolution of the produced image 
    75         @type dpi: integer 
    76         @keyword cmap: the colour map to be used to draw the grid 
    77         @type cmap: an instance of matplotlib.colors.LinearSegmentedColormap 
    78         @keyword valueFormat: format string for the vlaues drawn in the grid boxs 
    79         @type valueFormat: a python format string 
    80         @keyword drawColourBar: indicates if the colour bar should be drawn 
    81         @type drawColourBar: boolean 
    82         @keyword colourBarLabel: the label for the colour bar 
    83         @type colourBarLabel: string 
    84         @keyword colourBarPosition: the orientation and position the colour bar is drawn on 
    85             the plot. The default is chosen based on the lat-lon limits of the plot. 
    86         @type colourBarPosition: string, one of ['horizontal', 'vertical'] 
    87         @keyword colourBarMax: the minimum value for the colour bar 
    88         @type colourBarMax: float 
    89         @keyword colourBarMin: the maximum value for the colour bar 
    90         @type colourBarMin: float 
    91         @keyword drawLogo: indicates wheather to draw the UKCIP08 logo 
    92         @type drawLogo: boolean 
    93         @keyword drawCoast: indicates if coaslines should be drawn 
    94         @type drawCoast: boolean 
    95         @keyword drawRivers: indicates if rivers should be drawn 
    96         @type drawRivers: boolean 
    97         @keyword plotTitle: the title of the plot 
    98         @type plotTitle: string 
    99         @keyword units: the units of the value being plotted 
    100         @type units: string 
    101         @keyword metadataList: the metadata to be displayed along with the plot, if None no 
    102             metadata box will be drawn 
    103         @type metadataList: a list of (key, value) tuples. The keys and values should both be 
    104             strings. 
    105         @keyword fontSize: a general indication of the size of the fonts used on the plot 
    106         @type fontSize: a string, one of ["small","medium" ,"large", 'xl', 'xxl'] 
    107         @keyword units: the units the cdmsVar data is in, if no colourBarLabel is specified 
    108             the units will be used instead. 
    109         @type units: string 
    110         @keyword showGridLines: indicates if the gridlines should be shown on the plot 
    111         @type showGridLines: boolean 
    112         @keyword addShapefile: location of shapefile to overlay 
    113         @type addShapefile: string 
    114         """ 
    115          
    116         #check that all the keywords that appear are in the valid list 
    117         for key in kwargs: 
    118             if key not in self.validConstructorKWArgs: 
    119                 raise TypeError("__init__ got an unexpected keyword argument '" \ 
    120                                 + key + "'") 
    121         
    122         #create an empty argument dictionary 
    123         argDict = {} 
    124         for key in self.validConstructorKWArgs: 
    125             argDict[key] = None 
    126              
    127            
    128         #apply the default arguments form the config file, if an argument 
    129         #dosen't appear in the config file it will remain None.   
    130         argDict.update(config[DEFAULTS_SECTION]) 
    131          
    132          
    133         #apply the kwargs in the function call, these values will overwrite the 
    134         #default ones. 
    135         argDict.update(kwargs) 
    136          
    137         self._setDynamicArgs(argDict) 
    138  
    139         self.units = argDict['units'] 
    140          
    141  
    142         self.map = self._getMap(argDict['xLimits'], argDict['yLimits'],  
    143                                 argDict['drawCoast'], argDict['drawRivers'], 
    144                                 argDict['addShapefile']) 
    145  
    146          
    147         self.gridBuilder = self._getGridBuilder(cdmsVar) 
    148          
    149         self.gridDrawer = GridDrawer( argDict['drawValues'],  
    150                              argDict['drawValuesFile'], 
    151                              argDict['valueFormat'], argDict['showGridLines']) 
    152          
    153          
    154         self.plotArea = PlotArea(argDict['width'], argDict['height'],  
    155                                  argDict['dpi'], argDict['fontSize'],  
    156                                  argDict['plotTitle'], argDict['drawColourBar'], 
    157                                  argDict['drawLogo'], argDict['drawMetadata']) 
    158  
    159         self.metadataBox = MetadataBox(argDict['metadataList']) 
    160  
    161         self.colourBar = ColourBar(colourBarLabel = argDict['colourBarLabel'],  
    162                                    colourBarPosition = argDict['colourBarPosition'], 
    163                                    cmap = argDict['cmap'], 
    164                                    colourBarMin = argDict['colourBarMin'],  
    165                                    colourBarMax =  argDict['colourBarMax']) 
    166  
    167         self.plotWriter = PlotWriter(argDict['format'], argDict['outputCMYK']) 
    168          
    169  
    170     def _setDynamicArgs(self, kwargs): 
    171         #if the colourbar position isn't already set, use the limits to work out 
    172         #the best fit 
    173         if kwargs['colourBarPosition'] == None: 
    174             xRange = kwargs['xLimits'][1] - kwargs['xLimits'][0] 
    175             yRange = kwargs['yLimits'][1] - kwargs['yLimits'][0] 
    176 #            log.debug("xRange:" + str(xRange) + "yRange:" + str(yRange)) 
    177             if xRange > yRange: 
    178                 kwargs['colourBarPosition'] = 'horizontal' 
    179             else: 
    180                 kwargs['colourBarPosition'] = 'vertical' 
    181 #            log.debug('new colour bar position:' + kwargs['colourBarPosition']) 
    182  
    183         #if no colourBarLabel is provided use the units insted 
    184         if kwargs['colourBarLabel']==None :  
    185             kwargs['colourBarLabel'] = kwargs['units'] 
    186              
    187                 #set the default cmap if there is none set 
    188         if kwargs['cmap'] == None: 
    189             kwargs['cmap'] = matplotlib.cm.get_cmap() 
    190             kwargs['cmap'].set_bad("w") 
    191  
    192  
    193     def _getMap(self, xLimits, yLimits, drawCoast, drawRivers, addShapefile): 
    194         """ 
    195         abstract method, should be overidden with a method that constructs 
    196         and returns a Map object to be used in the plot 
    197  
    198         @param xLimits:a tuple representing the (longitude) limits of the map 
    199         @type xLimits: a tuple of 2 floats, corresponding to (min, max) 
    200         @param yLimits:a tuple representing the (latitude) limits of the map 
    201         @type yLimits: a tuple of 2 floats , corresponding to (min, max) 
    202         @param drawCoast: indicates if coaslines should be drawn 
    203         @type drawCoast: boolean 
    204         @param drawRivers: indicates if rivers should be drawn 
    205         @type drawRivers: boolean 
    206         @param addShapefile: location of shapefile to overlay 
    207         @type addShapefile: string 
    208         """ 
    209  
    210         raise NotImplementedError 
    211  
    212     def _getGrid(self, cdmsVar, cmap, drawValues, valueFormat, showGridlines): 
    213         """ 
    214         abstract method, should be overidden with a method that constructs 
    215         and returns a Grid object to be used in the plot 
    216  
    217         @param cdmsVar:the CDMS variable being plotted 
    218         @type cdmsVar: 
    219         @param cmap: the colour map to be used to draw the grid 
    220         @type cmap: an instance of matplotlib.colors.LinearSegmentedColormap 
    221         @param drawValues: indicates if values should be drawn in grid boxes 
    222         @type drawValues: boolean 
    223         @param valueFormat: format string for the vlaues drawn in the grid boxs 
    224         @type valueFormat: a python format string 
    225         @param showGridLines: indicates if the gridlines should be shown on the plot 
    226         @type showGridLines: boolean 
    227         """ 
    228         raise NotImplementedError 
    229  
    230     def drawMap(self, filename): 
    231         """ 
    232         Outputs the map to the filename. 
    233  
    234         @param filename: the name of the file the image should be written to, 
    235             the extension of the filename given should match the intended format 
    236             of the image, i.e. 'test.jpg' for an image with format 'jpg'. 
    237         @type filename: string 
    238         """ 
    239  
    240         startTime = time.time() 
    241          
    242         log.info("Drawing map to " + filename) 
    243  
    244         self.plotWriter.checkFileExtension(filename) 
    245  
    246         self._drawMap() 
    247  
    248         st = time.time() 
    249         self.plotWriter.writeFile(self.plotArea.figure, filename, self.drawLogo, self.plotArea.logoAxes) 
    250         log.debug("wrote output file in %.3fs" % (time.time() - st, )) 
    251          
    252         log.info("Finished drawing " + os.path.split(filename)[1] + " in %.3fs" % (time.time() - startTime,)) 
    253  
    254     def drawToImage(self): 
    255         if self.format not in 'png': 
    256             raise Exception("format %s not yet supported for image retrival" % (self.format,)) 
    257          
    258         self._drawMap() 
    259          
    260         im = geoplot_utils.figureToImage(self.plotArea.figure) 
    261          
    262         return im 
    263      
    264     def _drawMap(self): 
    265         self.plotArea.setupArea(self.colourBarPosition) 
    266  
    267         #get the grid 
    268         st = time.time() 
    269         grid = self.gridBuilder.buildGrid(self.xLimits, self.yLimits) 
    270         log.debug("built grid in %.3fs" % (time.time() - st, )) 
    271          
    272         #draw the grid 
    273         st = time.time() 
    274         sm = self.gridDrawer.draw(self.plotArea.axes, grid,  
    275                                   limits=[self.xLimits, self.yLimits],   
    276                                   basemap=self.map.basemap, 
    277                                   cmap=self.colourBar.getColourMap(), 
    278                                   cmapRange=(self.colourBarMin, self.colourBarMax)) 
    279          
    280         log.debug("drawn grid in %.3fs" % (time.time() - st, )) 
    281  
    282  
    283         st = time.time() 
    284         #the map has to be drawn after the grid, otherwise it distorts the axis 
    285         self.map.drawMap(self.plotArea.axes) 
    286          
    287         log.debug("drawn map in %.3fs" % (time.time() - st, )) 
    288          
    289         if self.drawMetadata: 
    290             st = time.time() 
    291             self.metadataBox.draw(self.plotArea.metadataAxes, self.fontSize, self.height) 
    292             log.debug("drawn metadata in %.3fs" % (time.time() - st, )) 
    293  
    294         if self.drawColourBar: 
    295             st = time.time() 
    296             self.colourBar.draw(self.plotArea.cbAxes, self.fontSize, dataMin=grid.values.min(), dataMax=grid.values.max()) 
    297              
    298             log.debug("drawn colourBar in %.3fs" % (time.time() - st, )) 
    299  
    300 #        self.plotArea.axes.set_xlim(-180, 180) 
    301 #        self.plotArea.axes.set_ylim(-90, 90) 
    302  
    303              
    304  
    305     #properies, because the properties are sread about several internal object 
    306     #to keep a simple interface all of the internal properties are wrapped so 
    307     #they are accessable via the map_ object 
    308  
    309     #plot property wrapping 
    310     def __get_height(self): return self.plotArea.height 
    311     def __set_height(self, value): self.plotArea.height = value 
    312     height = property(__get_height, __set_height, None, 
    313                       "The height in pixesl of the produced image") 
    314  
    315     def __get_width(self): return self.plotArea.width 
    316     def __set_width(self, value): self.plotArea.width = value 
    317     width = property(__get_width, __set_width, None, 
    318                      "The width in pixesl of the produced image") 
    319  
    320     def __get_dpi(self): return self.plotArea.dpi 
    321     def __set_dpi(self, value): self.plotArea.dpi = value 
    322     dpi = property(__get_dpi, __set_dpi, None, 
    323                    "The pixels per inch of pdf or ps output files") 
    324  
    325     def __get_fontSize(self): return self.plotArea.fontSize 
    326     def __set_fontSize(self, value): self.plotArea.fontSize = value 
    327     fontSize = property(__get_fontSize, __set_fontSize, None, 
    328             "The font size used in the output, 'small', 'medium' or 'large'") 
    329  
    330     def __get_metadataList(self): return self.metadataBox.dataList 
    331     def __set_metadataList(self, value): self.metadataBox.dataList = value 
    332     metadataList = property(__get_metadataList, __set_metadataList, None, 
    333                     "A list of key, vlaue pairs containing the plot metadata") 
    334  
    335     def __get_drawMetadata(self): return self.plotArea.drawMetadata 
    336     def __set_drawMetadata(self, value): self.plotArea.drawMetadata=value 
    337     drawMetadata = property(__get_drawMetadata, __set_drawMetadata, None, 
    338                     "value indicating if the metadata should be drawn on the plot.") 
    339  
    340     def __get_drawColourBar(self): return self.plotArea.drawColourBar 
    341     def __set_drawColourBar(self, value): self.plotArea.drawColourBar=value 
    342     drawColourBar = property(__get_drawColourBar, __set_drawColourBar, None, 
    343                     "value indicating if the colour bar should be drawn on the plot.") 
    344  
    345     def __get_drawLogo(self): return self.plotArea.drawLogo 
    346     def __set_drawLogo(self, value): self.plotArea.drawLogo=value 
    347     drawLogo = property(__get_drawLogo, __set_drawLogo, None, 
    348                     "value indicating if the metadata should be drawn on the plot.") 
    349  
    350  
    351  
    352     def __get_plotTitle(self): return self.plotArea.plotTitle 
    353     def __set_plotTitle(self, value): self.plotArea.plotTitle = value 
    354     plotTitle = property(__get_plotTitle, __set_plotTitle, None, 
    355                          "The title of the plot") 
    356  
    357     def __get_colourBarLabel(self): return self.colourBar.colourBarLabel 
    358     def __set_colourBarLabel(self, value): self.colourBar.colourBarLabel = value 
    359     colourBarLabel = property(__get_colourBarLabel, __set_colourBarLabel, 
    360                               None, "The label for the colour bar") 
    361  
    362     def __get_colourBarPosition(self): return self.colourBar.colourBarPosition 
    363     def __set_colourBarPosition(self, value): self.colourBar.colourBarPosition = value 
    364     colourBarPosition = property(__get_colourBarPosition, 
    365                                  __set_colourBarPosition, None, 
    366                     "colour bar position, 'horizontal' or 'vertical'") 
    367  
    368     def __get_colourBarMin(self): return self.colourBar.colourBarMin 
    369     def __set_colourBarMin(self, value): self.colourBar.colourBarMin = value 
    370     colourBarMin = property(__get_colourBarMin, __set_colourBarMin, None, 
    371                         "The minimum for the colour bar range") 
    372  
    373     def __get_colourBarMax(self): return self.colourBar.colourBarMax 
    374     def __set_colourBarMax(self, value): self.colourBar.colourBarMax = value 
    375     colourBarMax = property(__get_colourBarMax, __set_colourBarMax, None, 
    376                         "The maximum for the colour bar range") 
    377  
    378     #map property wrapping 
    379     def __get_xLimits(self): return self.map.xLimits 
    380     def __set_xLimits(self, value): self.map.xLimits = value 
    381     xLimits = property(__get_xLimits, __set_xLimits, None, 
    382                        "The longitude limits of the plot") 
    383  
    384     def __get_yLimits(self): return self.map.yLimits 
    385     def __set_yLimits(self, value): self.map.yLimits = value 
    386     yLimits = property(__get_yLimits,  __set_yLimits,  None, 
    387                        "The latitude limits of the plot") 
    388  
    389     def __get_drawCoast(self): return self.map.drawCoast 
    390     def __set_drawCoast(self, value): self.map.drawCoast = value 
    391     drawCoast = property(__get_drawCoast,  __set_drawCoast,  None, 
    392                          "Bool indicating if the coastline should be drawn") 
    393  
    394     def __get_drawRivers(self): return self.map.drawRivers 
    395     def __set_drawRivers(self, value): self.map.drawRivers = value 
    396     drawRivers = property(__get_drawRivers,  __set_drawRivers,  None, 
    397                           "Bool indicating if rivers should be drawn") 
    398  
    399     def __get_addShapefile(self): return self.map.addShapefile 
    400     def __set_addShapefile(self, value): self.map.addShapefile = value 
    401     addShapefile = property(__get_addShapefile,  __set_addShapefile,  None, 
    402                           "Provides a shapefile to overlay polygons.") 
    403  
    404     #grid property wrapping 
    405     def __get_cdmsVar(self): return self.gridBuilder.cdmsVar 
    406     def __set_cdmsVar(self, value): self.gridBuilder.cdmsVar = value 
    407     cdmsVar = property(__get_cdmsVar, __set_cdmsVar, None, 
    408                        "The cdms variable that conatins the plot data") 
    409  
    410     def __get_cmap(self): return self.colourBar.cmap 
    411     def __set_cmap(self, value): self.colourBar.cmap = value 
    412     cmap = property(__get_cmap, __set_cmap, None, 
    413                     "The colour map used to draw the grid") 
    414  
    415     def __get_drawValues(self): return self.gridDrawer.drawValues 
    416     def __set_drawValues(self, value): self.gridDrawer.drawValues = value 
    417     drawValues = property(__get_drawValues, __set_drawValues, None, 
    418                           "If the values are drawn inside the grid boxes") 
    419  
    420     def __get_drawValuesFile(self): return self.gridDrawer.drawValuesFile 
    421     def __set_drawValuesFile(self, value): self.gridDrawer.drawValuesFile = value 
    422     drawValuesFile = property(__get_drawValuesFile, __set_drawValuesFile, None, 
    423                           "A CSV file indicating which cells have values drawn inside the grid boxes") 
    424  
    425     def __get_valueFormat(self): return self.gridDrawer.valueFormat 
    426     def __set_valueFormat(self, value): self.gridDrawer.valueFormat = value 
    427     valueFormat = property(__get_valueFormat, __set_valueFormat, None, 
    428                      "The format string for the values drawn in the boxes") 
    429  
    430     def __get_showGridLines(self): return self.gridDrawer.showGridLines 
    431     def __set_showGridLines(self, value): self.gridDrawer.showGridLines = value 
    432     showGridLines = property(__get_showGridLines, __set_showGridLines, None, 
    433                      "bool indicating if the grid lines should be drawn") 
    434  
    435     def __get_format(self): return self.plotWriter.format 
    436     def __set_format(self, value): self.plotWriter.format = value 
    437     format = property(__get_format, __set_format, None, 
    438                      "string indicating the format of the output image file.") 
    439  
    440     def __get_outputCMYK(self): return self.plotWriter.outputCMYK 
    441     def __set_outputCMYK(self, value): self.plotWriter.outputCMYK = value 
    442     outputCMYK = property(__get_outputCMYK, __set_outputCMYK, None, 
    443                      "if the output will be in CMYK colours") 
  • qesdi/geoplot/trunk/lib/geoplot/plot_lat_lon.py

    r5552 r5610  
    77""" 
    88 
    9 import sys 
    10 import os 
    11  
    12 import cdms2 as cdms 
    13 import pkg_resources 
    14  
    159#geoplot imports 
    16 from geoplot.plot_base import PlotBase 
    17 from geoplot.map_national_grid import MapNationalGrid 
    18 from geoplot.map_lat_lon import MapLatLon 
    19 from geoplot.grid_builder_lat_lon import GridBuilderLatLon 
     10from geoplot.grid_plot import GridPlot 
    2011 
    2112import logging 
    2213log = logging.getLogger(__name__) 
    2314 
    24 class PlotLatLon(PlotBase): 
     15class PlotLatLon(GridPlot): 
    2516    """ 
    2617    Draws a lat-lon grid map to a specified file. 
    27  
    2818    """ 
    2919 
     
    9383        """ 
    9484 
    95         PlotBase.__init__(self, cdmsVar, **kwargs) 
    96  
    97     def _getMap(self, xLimits, yLimits, drawCoast, drawRivers, addShapefile): 
    98         """ 
    99         Returns a Map object to be used underneath the lat-lon grid. 
    100  
    101         @param xLimits:a tuple representing the (longitude) limits of the map 
    102         @type xLimits: a tuple of 2 floats, corresponding to (min, max) 
    103         @param yLimits:a tuple representing the (latitude) limits of the map 
    104         @type yLimits: a tuple of 2 floats , corresponding to (min, max) 
    105         @param drawCoast: indicates if coaslines should be drawn 
    106         @type drawCoast: boolean 
    107         @param drawRivers: indicates if rivers should be drawn 
    108         @type drawRivers: boolean 
    109         @param addShapefile: location of shapefile to overlay 
    110         @type addShapefile: string 
    111         """ 
    112  
    113         return MapLatLon(xLimits, yLimits, drawCoast, drawRivers, addShapefile) 
    114         #return MapNationalGrid(xLimits, yLimits, drawCoast, drawRivers) 
    115  
    116     def _getGridBuilder(self, cdmsVar): 
    117         return GridBuilderLatLon(cdmsVar) 
    118  
    119 if __name__ == '__main__': 
    120  
    121     outputsDir = os.path.abspath(pkg_resources.resource_filename('geoplot', '../../outputs')) 
    122     testDataDir = pkg_resources.resource_filename('geoplot', 'tests/data') 
    123  
    124     import geoplot.log_util as log_util 
    125     log_util.setupGeoplotConsoleHandler(log) 
    126  
    127     #dataFile = testDataDir + '/ll_test.nc' 
    128     #dataVariable = 'temp' 
    129  
    130     #f = cdms.open(dataFile) 
    131     #var = f(dataVariable, squeeze=1) 
    132  
    133     #f = cdms.open('/disks/westerly1/dump/ammr_example.nc') 
    134     f = cdms.open(testDataDir + '/ammr_example2.nc') 
    135     var = f('temp', squeeze = 1) # remove the additional axis 
    136     #var = f('temperature', s = 1, squeeze = 1) # remove the additional axis 
    137  
    138     #f = cdms.open('/disks/westerly1/20080521/cdml/multi_level_dataset.xml') 
    139     #var = f('potential_temperature_average', meaning_period=1, squeeze=1) 
    140  
    141     plot_format = 'ps' 
    142  
    143     outputFile = outputsDir + '/lat_lon_grid_test.' + plot_format 
    144  
    145     eg_metadata_list = [("Dataset", "MOHC Probabilistic Land"), 
    146                         ("Variable", "Mean Temperature"), 
    147                         ("Emissions Scenario", "Medium (A1B)"), 
    148                         ("Time Slice", "2040-2079"), 
    149                         ("Temporal Av. Period", "Spring"), 
    150                         ("Percentile", "10th")] 
    151  
    152 # show the whole grid xLimits=(-13.0, 6.2), yLimits=(47.0, 61.0) 
    153 # show the whole of the uk xLimits=(-11.0, 2.8), yLimits=(48.0, 60.0) 
    154 #xLimits=( -2.0,   2.0), yLimits=( 50.0, 54.0), 
    155 #xLimits=(  0.0, 359.8), yLimits=(-90.0, 89.8), 
    156 #xLimits=(-20.0,  15.0), yLimits=( 40.0, 70.0), 
    157 #xLimits=( -7.0,   2.0), yLimits=( 54.0, 64.0)  scotland 
    158 #xLimits=( -8.0,   1.0), yLimits=( 52.0, 64.0) , 
    159  
    160     pll = PlotLatLon(var, format = plot_format, 
    161                     fontSize = 'medium', units = 'A Test Plot', 
    162                     plotTitle = "A Test Plot", showGridLines = True, 
    163                     drawLogo = True, metadataList = eg_metadata_list, 
    164                     drawCoast = True, drawRivers = True, 
    165                     drawColourBar = True, drawValues = False) 
    166  
    167     pll.drawMap(outputFile) 
    168     log.debug('wrote %s' % outputFile) 
    169  
     85        GridPlot.__init__(self, cdmsVar=cdmsVar, projection='latlon',  
     86                          dataType='latlon', **kwargs) 
  • qesdi/geoplot/trunk/lib/geoplot/plot_national_grid.py

    r5552 r5610  
    66 
    77""" 
    8  
    98import sys 
    109import os 
    1110 
    12 import cdms2 as cdms 
    13 import pkg_resources 
    14  
    1511#geoplot imports 
    16 from geoplot.plot_base import PlotBase 
    17 from geoplot.map_national_grid import MapNationalGrid 
    18 from geoplot.map_lat_lon import MapLatLon 
    19  
    20 from geoplot.grid_builder_national import GridBuilderNational 
     12from geoplot.grid_plot import GridPlot 
    2113 
    2214import logging 
    2315log = logging.getLogger(__name__) 
    2416 
    25 outputsDir = os.path.abspath(pkg_resources.resource_filename('geoplot', '../../outputs')) 
    26 testDataDir = pkg_resources.resource_filename('geoplot', 'tests/data') 
    27  
    28 class PlotNationalGrid(PlotBase): 
     17class PlotNationalGrid(GridPlot): 
    2918    """ 
    3019    Draws a national grid map to a specified file. 
     
    9786        """ 
    9887 
    99         PlotBase.__init__(self, cdmsVar, **kwargs) 
    100  
    101     def _getMap(self, xLimits, yLimits, drawCoast, drawRivers, addShapefile): 
    102         """ 
    103         Returns a Map object to be used underneath the national grid. 
    104  
    105         @param xLimits:a tuple representing the (longitude) limits of the map 
    106         @type xLimits: a tuple of 2 floats, corresponding to (min, max) 
    107         @param yLimits:a tuple representing the (latitude) limits of the map 
    108         @type yLimits: a tuple of 2 floats , corresponding to (min, max) 
    109         @param drawCoast: indicates if coaslines should be drawn 
    110         @type drawCoast: boolean 
    111         @param drawRivers: indicates if rivers should be drawn 
    112         @type drawRivers: boolean 
    113         @param addShapefile: location of shapefile to overlay 
    114         @type addShapefile: string 
    115         """ 
    116  
    117         return MapNationalGrid(xLimits, yLimits, drawCoast, drawRivers, addShapefile) 
    118         #return MapLatLon(xLimits, yLimits, drawCoast, drawRivers, addShapefile) 
    119  
    120     def _getGridBuilder(self, cdmsVar): 
    121         return GridBuilderNational(cdmsVar) 
    122  
    123 if __name__ == '__main__': 
    124  
    125     import log_util 
    126     log_util.setupGeoplotConsoleHandler(log) 
    127  
    128     dataFile = testDataDir + '/ng_test.nc' 
    129     dataVariable = 'mean_temp' 
    130     f = cdms.open(dataFile) 
    131     var = f(dataVariable, squeeze=1) 
    132  
    133     #dataFile = 'national_grid.nc' 
    134     #dataFile = 'simple_grid.nc' 
    135     #dataVariable = 'grid' 
    136     #f = cdms.open(dataFile) 
    137     #var = f(dataVariable, squeeze=1) 
    138  
    139     #dataFile = 'grid_box_5km_airfrost_dmean_tmean_abs_1961-1990_obs_climate.nc' 
    140     #dataVariable = 'airfrost_dmean_tmean_abs' 
    141     #f = cdms.open(dataFile) 
    142     #var = f(dataVariable, meaning_period=1, squeeze=1) 
    143  
    144     outputFile = outputsDir + '/national_grid_test.png' 
    145  
    146     eg_metadata_list = [("Dataset", "MOHC Probabilistic Land"), 
    147                         ("Variable", "Mean Temperature"), 
    148                         ("Emissions Scenario", "Medium (A1B)"), 
    149                         ("Time Slice", "2040-2079"), 
    150                         ("Temporal Av. Period", "Spring"), 
    151                         ("Percentile", "10th")] 
    152  
    153     c = [( 255, 255, 255)] 
    154     import geoplot.utils 
    155     #cmap = geoplot.utils.generateDiscreteCmap(c, "ukcip08") # create the custom colour map 
     88        GridPlot.__init__(self, cdmsVar=cdmsVar, projection='national',  
     89                          dataType='national', **kwargs) 
    15690 
    15791 
    158     from matplotlib import cm 
    159     cmap = cm.jet 
    16092 
    161     cmap.set_bad('w')   # sets the bad data colour to white (same as the default colour map) 
    162  
    163  
    164 # show the whole grid xLimits=(-13.0, 6.2), yLimits=(47.0, 61.0) 
    165 # show the whole of the uk xLimits=(-11.0, 2.8), yLimits=(48.0, 60.0) 
    166 #xLimits=( -2.0,   2.0), yLimits=( 50.0, 54.0) 
    167 #xLimits=(  0.0, 359.8), yLimits=(-90.0, 89.8), 
    168 #xLimits=(-20.0,  15.0), yLimits=( 40.0, 70.0) 
    169 #xLimits=( -7.0,   2.0), yLimits=( 54.0, 64.0)  scotland 
    170  
    171 #    png = PlotNationalGrid(var, format='png', drawValues=False, 
    172 #                         fontSize="medium", units="degrees C", drawLogo=False, 
    173 #                         plotTitle="A Test Plot", showGridLines=True, 
    174 #                         cmap=cmap, drawColourBar=True, metadataList=None, 
    175 #                         xLimits=(-13.0, 7.0), yLimits=(47.0, 62.0) 
    176 #                         #colourBarMin=-10, colourBarMax=110 
    177 #                         ) 
    178 #                         #xLimits=(-1.0, 0.75), yLimits=(53.0, 54.0)) 
    179 #                         #drawLogo=True, metadataList = eg_metadata_list, 
    180 #                         #drawColourBar = True) 
    181  
    182     png = PlotNationalGrid(var, format='png', units='degrees C', cmap = cmap, 
    183                            metadataList=[('one',1), ('two',2)], 
    184                            plotTitle="A Test Plot",) 
    185  
    186     png.drawMap(outputFile) 
    187  
    188     #png.format = 'ps' 
    189     #outputFile = outputsDir + '/national_grid_test.ps' 
    190     #png.drawMap(outputFile) 
    191  
    192     log.debug( 'wrote %s' % outputFile) 
  • qesdi/geoplot/trunk/lib/geoplot/plot_rotated_grid.py

    r5605 r5610  
    77""" 
    88 
    9 import sys 
    10 import os 
    119import logging 
    12 import pkg_resources 
    13 import cdms2 as cdms 
    14  
    15 from matplotlib import cm 
    16  
    1710#geoplot imports 
    18 from geoplot.plot_base import PlotBase 
    19 from geoplot.map_national_grid import MapNationalGrid 
    20 from geoplot.map_lat_lon import MapLatLon 
    21 from geoplot.grid_builder_rotated import GridBuilderRotated 
     11from geoplot.grid_plot import GridPlot 
    2212 
    2313log = logging.getLogger(__name__) 
    2414 
    25 testDataDir = pkg_resources.resource_filename('geoplot', 'tests/data') 
    26  
    27 class PlotRotatedGrid(PlotBase): 
     15class PlotRotatedGrid(GridPlot): 
    2816    """ 
    2917    Draws a rotated grid map to a specified file. 
     
    10694         
    10795         
    108         PlotBase.__init__(self, cdmsVar, **kwargs) 
    109  
    110     def _getMap(self, xLimits, yLimits, drawCoast, drawRivers, addShapefile): 
    111         """ 
    112         Returns a Map object to be used underneath the rotated grid. 
    113  
    114         @param xLimits:a tuple representing the (longitude) limits of the map 
    115         @type xLimits: a tuple of 2 floats, corresponding to (min, max) 
    116         @param yLimits:a tuple representing the (latitude) limits of the map 
    117         @type yLimits: a tuple of 2 floats , corresponding to (min, max) 
    118         @param drawCoast: indicates if coaslines should be drawn 
    119         @type drawCoast: boolean 
    120         @param drawRivers: indicates if rivers should be drawn 
    121         @type drawRivers: boolean 
    122         @param addShapefile: location of shapefile to overlay 
    123         @type addShapefile: string 
    124         """ 
    125         return MapNationalGrid(xLimits, yLimits, drawCoast, drawRivers, addShapefile) 
    126         #return MapLatLon(xLimits, yLimits, drawCoast, drawRivers, addShapefile) 
    127  
    128     def _getGridBuilder(self, cdmsVar): 
    129         return GridBuilderRotated(cdmsVar, self._rotatedPoleVar) 
    130  
    131     #grid property wrapping 
    132     def __get_rotatedPoleVar(self): return self.gridBuilder.rotatedPoleVar 
    133     def __set_rotatedPoleVar(self, value): self.gridBuilder.rotatedPoleVar = value 
    134     rotatedPoleVar = property(__get_rotatedPoleVar, __set_rotatedPoleVar) 
    135  
    136 if __name__ == '__main__': 
    137     outputsDir = os.path.abspath(pkg_resources.resource_filename('geoplot', '../../outputs')) 
    138  
    139     import geoplot.log_util as log_util 
    140     log_util.setupGeoplotConsoleHandler(log) 
    141  
    142     #dataFile = testDataDir + '/rg_test.nc' 
    143     #dataVariable = 'air_temperature' 
    144  
    145 #    dataFile = testDataDir + '/rg_test3.nc' 
    146 #    dataVariable = 'temp' 
    147  
    148     #dataFile = 'rotated_grid.nc' 
    149     #dataVariable = 'variable_1' 
    150  
    151     #dataFile = 'simple_rgrid.nc' 
    152     #dataVariable = 'out_var' 
    153      
    154 #    dataFile = testDataDir +'/grid_box_25km_subset.nc' 
    155  
    156     dataFile = testDataDir +'/grid_box_25km_subset.cdml' 
    157     dataVariable = 'cdf_temp_dmean_tmean_abs' 
    158      
    159  
    160     f = cdms.open(dataFile) 
    161     var = f(dataVariable, squeeze = 1) 
    162     var.setMissing(0.0) 
    163     #rotated_pole_var = f[var.grid_mapping] 
    164  
    165     #dataFile = 'grid_box_25km_airfrost_dmean_tmean_abs_1961-1990_obs_climate.nc' 
    166     #dataVariable = 'airfrost_dmean_tmean_abs' 
    167  
    168     #f = cdms.open(dataFile) 
    169     #var = f(dataVariable, meaning_period=1, squeeze=1) 
    170     rotated_pole_var = f['rotated_pole'] 
    171     outputFile = outputsDir + '/rotated_grid_test.jpg' 
    172  
    173     eg_metadata_list = [("Dataset", "MOHC Probabilistic Land"), 
    174                         ("Variable", "Mean Temperature"), 
    175                         ("Emissions Scenario", "Medium (A1B)"), 
    176                         ("Time Slice", "2040-2079"), 
    177                         ("Temporal Av. Period", "Spring"), 
    178                         ("Percentile", "10th")] 
    179  
    180     #c = [( 255, 255, 255)] 
    181     #import geoplot.utils 
    182     #cmap = geoplot.utils.generateDiscreteCmap(c, "ukcip08") # create the custom colour map 
    183     #cmap.set_bad('w')   # sets the bad data colour to white (same as the default colour map) 
    184  
    185 #southwest xLimits = (-6.0, -1.0), yLimits = (50.0, 54.0) 
    186 #wales xLimits = (-5.7, -2.0), yLimits = (51.0, 53.5), 
    187 #southeast xLimits = (-2.0, 2.0), yLimits = (50.0, 54.0), 
    188 #northeast xLimits = (-3.0, 0.5), yLimits = (52.0, 60.0), 
    189 #northwest xLimits = (-3.5, -1.5), yLimits = (53.0, 55.0), 
    190 #scotland xLimits = (-7.5, -0.5), yLimits = (54.0, 61.0), 
    191 #northernireland xLimits = (-8.0,-5.0), yLimits = (53.0, 56.0), 
    192 #isleofman xLimits = (-4.8,-4.2), yLimits = (54.0, 54.5), 
    193  
    194     prg = PlotRotatedGrid(var, rotated_pole_var, 
    195                          drawValues=False, fontSize="large", 
    196                          units="degrees C", plotTitle="A Test Plot", 
    197                          drawLogo=True, metadataList=eg_metadata_list, showGridLines=True, 
    198 #                         xLimits = (-8.0,-5.0), yLimits = (53.0, 56.0), 
    199                          #xLimits=(-13.0, 7.0), yLimits=(47.0, 62.0), 
    200                          xLimits=(-7.0, 7.0), yLimits=(47.0, 62.0), 
    201 #                         xLimits=(-15.0, 7.0), yLimits=(47.0, 52.0),                          
    202                          colourBarPosition='horizontal', 
    203                          drawColourBar=True, format='jpg', outputCMYK=False) 
    204  
    205     prg.drawMap(outputFile) 
    206     log.debug('wrote %s' % outputFile) 
    207  
    208     #prg.format = "ps" 
    209     #outputFile = outputsDir + '/rotated_grid_test.' + prg.format 
    210     #prg.drawMap(outputFile) 
    211     #log.debug('wrote %s' % outputFile) 
     96        GridPlot.__init__(self, cdmsVar=cdmsVar, projection='latlon',  
     97                          dataType='rotated', **kwargs) 
  • qesdi/geoplot/trunk/lib/geoplot/tests/drawing/draw_test_contour_plot.py

    r5605 r5610  
    99log = logging.getLogger(__name__) 
    1010 
    11  
    12  
    13 def drawColourBar( colourBarLabel=None ,colourBarPosition=None,  
    14                    cmap=None, colourBarMin=None, colourBarMax=None): 
    15      
    16      
    17  
    18     im = geoplot.colour_bar.getColourBarImage(width,height, label='Units of Measure: mm/day') 
    19      
    20     filename = os.path.join(outputDir, '%scolourBar.png' % (name_segment,)) 
    21     im.save(filename, 'PNG') 
    22     print "Written %s" % (filename,) 
    23          
    2411 
    2512if __name__ == '__main__': 
  • qesdi/geoplot/trunk/lib/geoplot/tests/drawing/draw_test_grid_plot_latlon.py

    r5605 r5610  
    11import os 
    22import logging 
     3import pkg_resources 
     4import cdms2 as cdms 
    35 
    46log = logging.getLogger(__name__) 
     
    1820    plot_format = 'png' 
    1921    outputFile = outputDir + '/lat_lon_grid_plot.' + plot_format 
    20  
     22    testDataDir = pkg_resources.resource_filename('geoplot', 'tests/data') 
     23     
    2124    eg_metadata_list = [("Dataset", "MOHC Probabilistic Land"), 
    2225                        ("Variable", "Mean Temperature"), 
     
    3639    #xLimits=( -8.0,   1.0), yLimits=( 52.0, 64.0) , 
    3740 
    38     var = makeLLVar(lonBounds=xLimits, latBounds=yLimits, nx=20, ny=20) 
     41    f = cdms.open(testDataDir + '/ammr_example2.nc') 
     42    var = f('temp', squeeze = 1) # remove the additional axis 
     43 
     44#    var = makeLLVar(lonBounds=xLimits, latBounds=yLimits, nx=20, ny=20) 
    3945 
    4046    pll = PlotLatLon(var, format = plot_format, 
  • qesdi/geoplot/trunk/lib/geoplot/tests/unit/test_contour_plot.py

    r5605 r5610  
    77import nose.tools as nt 
    88import nose 
     9import logging 
    910 
     11from geoplot.contour_plot import ContourPlot 
     12from geoplot.config import getConfig 
     13 
     14config = getConfig() 
    1015log = logging.getLogger(__name__) 
     16 
     17testValues ={'_contourDrawer':{'numContourLines':11, 'contourLabelInterval':61}} 
     18 
    1119 
    1220class TestContourPlot(unittest.TestCase): 
     
    1826        pass 
    1927     
    20     #produces a plot 
    21      
    22     #applies default arguments 
    23      
     28    def test_001_appliesContourDrawerDefaults(self): 
     29        plot = ContourPlot() 
     30         
     31        for att in testValues.keys(): 
     32             
     33            #check the object has been created 
     34            obj = getattr(plot, att) 
     35            name = obj.__class__.__name__ 
     36             
     37            assert obj != None 
     38                         
     39            #check you can get the default from the base object 
     40            for k, v in config['Defaults'][name].items(): 
     41                assert getattr(obj, k) == v 
    2442 
     43    def test_002_dynamicAttributeReading(self): 
     44         
     45        plot = ContourPlot() 
     46         
     47        #first set the values on the private attributes directly 
     48        for attribute, testVals in testValues.items(): 
     49            obj = getattr(plot, attribute) 
     50            for att, val in testVals.items(): 
     51                setattr(obj,att,val) 
     52                 
     53        #now try and read the values back via the 'base' object directly 
     54        for attribute, testVals in testValues.items(): 
     55             
     56            for att, val in testVals.items(): 
     57                nt.assert_equal(getattr(plot, att), val)  
     58         
     59 
     60    def test_003_dynamicAttributeSetting(self): 
     61         
     62        plot = ContourPlot() 
     63         
     64        #set the values using the base directly 
     65        for attribute, testVals in testValues.items(): 
     66             
     67            for att, val in testVals.items(): 
     68                setattr(plot, att, val) 
     69                 
     70        #now try and read the values back via private objects 
     71        for attribute, testVals in testValues.items(): 
     72             
     73            obj = getattr(plot, attribute) 
     74             
     75            for att, val in testVals.items(): 
     76                 
     77                nt.assert_equal(getattr(obj, att), val)     
    2578 
    2679def suite(): 
Note: See TracChangeset for help on using the changeset viewer.