source: cows/trunk/cows/service/imps/pywms/impl.py @ 5399

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/trunk/cows/service/imps/pywms/impl.py@5399
Revision 5399, 5.0 KB checked in by domlowe, 12 years ago (diff)

Changing PIL imports in cows

Line 
1# BSD Licence
2# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
3# All rights reserved.
4#
5# See the LICENSE file in the source distribution of this software for
6# the full license text.
7
8"""
9Implements the WMS interfaces for simple CDMS variables
10
11This implementation is for backward compatibility between the old interface and
12the new.  Only one CRS per layer is supported.
13
14"""
15from ows_common.service.wms_iface import ILayer, ILayerSlab, IDimension
16from wms_cdms import SimpleCdmsLayer, CdmsTimeDimension, CdmsGrid
17import cdtime
18from render_imp import RGBARenderer
19from matplotlib.cm import get_cmap
20from matplotlib.colorbar import ColorbarBase
21from matplotlib.ticker import LinearLocator
22from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
23from matplotlib.figure import Figure
24from numpy import arange
25
26from cStringIO import StringIO
27try: 
28    from PIL import Image
29except ImportError:
30    import Image
31
32import logging
33log = logging.getLogger(__name__)
34
35class CdmsLayer(ILayer):
36    """
37    The ILayer interface has superceded model.Layer and therefore CdmsLayer
38    does not inherit from model.Layer or SimpleCdmsLayer.  Instead encapsulation
39    is used.
40
41    """
42
43    featureInfoFormats = ['text/html']
44   
45    def __init__(self, cdmsVar, GridClass=CdmsGrid, minValue=None, maxValue=None,
46                 units=None):
47        try:
48            self.title = cdmsVar.long_name
49        except AttributeError:
50            self.title = cdmsVar.id
51
52        self._layer = SimpleCdmsLayer(cdmsVar, GridClass=GridClass)
53        self.abstract = None
54        self.crss = [GridClass.crs]
55        #!TODO: do this properly
56        self.wgs84BBox = (-15.0, 45.0, 15.0, 60.0)
57        if units:
58            self.units = units
59        else:
60            self.units = self._layer.units
61        self.minValue = minValue
62        self.maxValue = maxValue
63
64        self.legendSize=(100, 500)
65
66        dims = {}
67        for dimName, dim in self._layer.dimensions.items():
68            dims[dimName] = Dimension(dim)
69        self.dimensions = dims
70
71    def getBBox(self, crs):
72        # Get BBOX from pywms layer
73        var = self._layer.var
74        xAxis = var.getAxis(var.getAxisIndex('eastings'))
75        yAxis = var.getAxis(var.getAxisIndex('northings'))
76        #!NOTE order specific code
77        return (xAxis[0], yAxis[-1], xAxis[-1], yAxis[0])
78
79    def getSlab(self, crs, dimValues=None, renderOpts={}):
80        if crs != self.crss[0]:
81            raise ValueError("CRS %s not supported on this layer" % crs)
82       
83        return CdmsLayerSlab(crs, dimValues, renderOpts, self)
84
85    def getCacheKey(self, crs, dimValues=None, renderOpts={}):
86        # Don't support caching
87        return None
88
89    def getLegendImage(self, orientation='vertical', renderOpts={}):
90        if 'vert' in orientation:
91            figsize = (1, 5)
92            rect = (0.05, 0.05, 0.4, 0.9)
93        else:
94            figsize = (5, 1)
95            rect = (0.05, 0.55, 0.9, 0.4)
96           
97       
98        fig = Figure(figsize=figsize, dpi=100)
99        ax = fig.add_axes(rect)
100        boundaries = arange(self.minValue, self.maxValue,
101                           float(self.maxValue-self.minValue)/256)
102        loc = LinearLocator()
103        loc.set_bounds(self.minValue, self.maxValue)
104        ColorbarBase(ax, boundaries=boundaries, orientation=orientation, ticks=loc(),
105                     cmap=get_cmap(renderOpts.get('cmap', 'Paired')))
106
107        if 'vert' in orientation:
108            ax.set_ylabel(self.units)
109        else:
110            ax.set_xlabel(self.units)
111
112        c = FigureCanvas(fig)
113        c.draw()
114        buf = StringIO()
115        c.print_png(buf)
116        buf.seek(0)
117        img = Image.open(buf)
118
119        return img
120
121    def getFeatureInfo(self, format, crs, point, dimValues):
122        # We assume here format and crs are valid (the framework should check).
123        (x, y) = point
124
125        var = self._layer.var
126        # Get the data at that point
127        sel = dict(eastings=x, northings=y)
128        # Ignore dimvalues
129        # sel.update(dimValues)
130        val = var(**sel)
131       
132        return '''
133<html>
134<body>
135<h1>GetFeatureInfoResponse for layer: %s</h1>
136Selection: %s<br/>
137Value: %s<br/>
138</body>
139</html>
140''' % (self.title, sel, val)
141       
142
143class CdmsLayerSlab(ILayerSlab):
144    def __init__(self, crs, dimValues, renderOpts, layer):
145        self.crs = crs
146        self.dimValues = dimValues
147        self.renderOpts = renderOpts
148        self.layer = layer
149        self.bbox = layer.getBBox(crs)
150
151        self._renderer = RGBARenderer(self.layer.minValue, self.layer.maxValue)
152
153    def getImage(self, bbox, width, height):
154        grid = self.layer._layer.selectGrid(bbox, self.dimValues)
155        cmap = get_cmap(self.renderOpts.get('cmap', 'Paired'))
156        img = self._renderer.renderGrid(grid, bbox, width, height, cmap)
157
158        return img
159
160    def getCacheKey(self):
161        raise NotImplementedError
162   
163
164class Dimension(IDimension):
165    """
166    Wrapper to fix some interface differences.
167
168    """
169    def __init__(self, pywmsDim):
170        self.units = pywmsDim.units
171        self.extent = pywmsDim.extent.split(',')
Note: See TracBrowser for help on using the repository browser.