source: DPPP/kml/csml2kml/python/csml2kmlpylon/csml2kmlpylon/controllers/csmlGrapher.py @ 3657

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/DPPP/kml/csml2kml/python/csml2kmlpylon/csml2kmlpylon/controllers/csmlGrapher.py@3657
Revision 3657, 14.5 KB checked in by mkochan, 11 years ago (diff)

Changed to version 1.0b.

Line 
1# Pylons-specific imports
2import logging
3from csml2kmlpylon.lib.base import *
4from paste.httpexceptions import HTTPBadRequest, HTTPNotFound
5
6# Other imports
7import Image
8from pylab import *
9from matplotlib import dates
10import re
11from cStringIO import StringIO
12from tempfile import NamedTemporaryFile
13import urllib
14
15# CSML and csml2kml imports
16import csml
17import csml2kml.Station
18from csml2kml.utils import wget
19from csml2kml.ET import Element, SubElement, ElementTree, XML
20
21log = logging.getLogger(__name__)
22
23class CsmlgrapherController(BaseController):
24
25    def __call__(self, environ, start_response):
26        '''
27        Initialise the web service by overriding a method that always get called upon controller construction.
28        More specifically, read in the config file.
29        '''
30
31        # The name of the config file is set in the server's "development.ini" file.
32        configFileName = config['app_conf']['csmlGrapher.configfile']
33       
34        # Load the configuration XML element (but only the part pertaining to the web service)
35        testConfig = ElementTree().parse(configFileName)
36        print testConfig
37        grapherConfig = (ElementTree().parse(configFileName))
38
39        # Set the configurable variables
40        self.displayIntervalStart = dates.dateutil.parser.parse(grapherConfig.find('DisplayIntervalStart').text)
41        self.displayIntervalEnd = dates.dateutil.parser.parse(grapherConfig.find('DisplayIntervalEnd').text)
42        self.geoServerUrl = grapherConfig.find('GeoServerURL').text
43        self.servedFromUrl = grapherConfig.find('ServedFromURL').text
44
45        # Call the __call__ method of the parent class
46        return BaseController.__call__(self, environ, start_response)
47
48    def _datetimeToGeoServerDate(self, datetime):
49        monthCodes = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
50        return repr(datetime.day) + '-' + monthCodes[datetime.month-1] + '-' + repr(datetime.year)
51
52    def _retrieveCsmlPointSeriesFeature(self, station_name, feature_id):
53        '''
54        @return: A C{PointSeriesFeature} object representing the single CSML feature if the feature was found;
55        C{None} if a feature collection has been returned, but contains no CSML features (this happens when
56        there are no measured time points in the used time interval).
57        @throws: A C{LookupError} exception with a message if there is no response from the server.
58        '''
59       
60        # Prepare the request for the GeoServer.
61        geoServerRequestUrl = urllib.quote(self.geoServerUrl + '?request=getfeature&service=wfs&version=1.1.0&typename=csml:PointSeriesFeature&filter=<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><ogc:And><ogc:PropertyIsEqualTo><ogc:PropertyName>gml:description</ogc:PropertyName><ogc:Literal>'+ station_name +'</ogc:Literal></ogc:PropertyIsEqualTo><ogc:PropertyIsEqualTo><ogc:PropertyName>csml:parameter/swe:Phenomenon/gml:name</ogc:PropertyName><ogc:Literal>'+ feature_id +'</ogc:Literal></ogc:PropertyIsEqualTo><ogc:PropertyIsBetween><ogc:PropertyName>csml:value/csml:PointSeriesCoverage/csml:pointSeriesDomain/csml:TimeSeries/csml:timePositionList</ogc:PropertyName><ogc:LowerBoundary><ogc:Literal>'+ self._datetimeToGeoServerDate(self.displayIntervalStart) +'</ogc:Literal></ogc:LowerBoundary><ogc:UpperBoundary><ogc:Literal>'+ self._datetimeToGeoServerDate(self.displayIntervalEnd) +'</ogc:Literal></ogc:UpperBoundary></ogc:PropertyIsBetween></ogc:And></ogc:Filter>', '/._:?&=')
62
63        # Acquire the GeoServer response and parse it into a CSMLFeatureCollection object
64        geoServerResponse = wget(geoServerRequestUrl)
65        if not geoServerResponse:
66            raise LookupError('Cannot acquire response from server (wrong URL or server down)')
67        csmlFeatureCollection = csml.parser.CSMLFeatureCollection()
68        csmlFeatureCollection.fromXML( XML(geoServerResponse) )
69
70        # If csmlFeatureCollection contains a single CSML feature, the isolate it. If it contains no feature,
71        # probably no data points are available for that interval.
72        try:
73            csmlFeature = csmlFeatureCollection.featureMembers
74        except AttributeError:
75            raise LookupError(
76                'No data points available for the given time interval. ' + 
77                'Perhaps the interval is shorter than the frequency of data points, ' +
78                'or collection of data for this feature was interrupted at the time.'
79                )
80
81        # Make sure that the feature is a PointSeriesFeature
82        if not isinstance(csmlFeature, csml.parser.PointSeriesFeature):
83            raise LookupError('CSML feature not a PointSeriesFeature')
84        csmlPointSeriesFeature = csmlFeature
85
86        return csmlPointSeriesFeature
87
88    def plot(self):
89        '''
90        Handler for plotting a specific PointSeries feature given by URL parameter "feature_id".
91        Retrieves the data from a web service, which should preferably run on the same machine.
92
93        Request parameters:
94                               feature_id      Unique identifier of the requested CSML PointSeries feature.
95                               station_name    Name of the requested station.
96                               
97        Response:              An image/png of the time series for the CSML PointSeries feature.
98        '''
99        def _plot_feature(feature):
100            '''
101            Plot a PointSeries feature using matplotlib, into a temporary file
102            '''
103           
104            # Make sure that time is considered to be UTC time. This is because all CSML data is supposed to be in UTC,
105            # but actually pylab is "time zone aware" and will interpret the time as local time zone time.
106            # Not quite sure if this would be a problem, but rather enforce it is UTC.
107            def _enforce_UTC_timezone(datestr):
108                if datestr[-1] == 'Z':
109                    return datestr
110                else:
111                    return datestr + 'Z'
112           
113            # Isolate time points
114            times=feature.value.pointSeriesDomain.timePositionList.CONTENT.split()
115            times = map(_enforce_UTC_timezone, times)
116
117            # Make a list of times as float numbers being days passed since start of epoch (here 01-01-0001)
118            elapsed_times = map(datestr2num, times)
119
120            # Get values of the measured quantity
121            ql = feature.value.rangeSet.quantityList
122            vals = map(float, ql.CONTENT.split())
123
124            # Make sure the times are sorted in ascending order (and rearrange the values accordingly),
125            # this is because we get them potentially unsorted from GeoServer. Also have to handle the sad fact,
126            # that sometimes we are getting duplicate time-value samples from the MIDAS dataset!
127            sortTimesExplicitly = True
128            if sortTimesExplicitly:
129                reorder = {}
130                for i in range(len(elapsed_times)):
131                    reorder[elapsed_times[i]] = i
132                elapsed_times = reorder.keys()
133                elapsed_times.sort()
134                times2 = []
135                vals2 = []
136                for et in elapsed_times:
137                    times2.append(times[reorder[et]])
138                    vals2.append(vals[reorder[et]])
139                times = times2
140                vals = vals2
141
142            print '---times (' + str(len(times)) + ' of them):\n' + str(times)
143            print '---vals (' + str(len(times)) + ' of them):\n' + str(vals)
144
145            # Note the start and end date (they are actually date+time), and time span between them
146
147            start_date = dates.num2date(elapsed_times[0])
148            end_date = dates.num2date(elapsed_times[-1])
149            span = elapsed_times[-1] - elapsed_times[0]
150
151            # Generate tick locator and formatter; these determine the time axis: locator determines tick positions
152            # and formatter format of time
153            print '---start_date:' + str(start_date)
154            print '---end_date:' + str(end_date)
155            print '---span: ' + str(span)
156            (tickLocator, tickFormatter) = dates.date_ticker_factory(span, numticks=8)
157
158            # Determine the units of measurement
159            uom=ql.uom.title()
160            if ql.uom.islower():
161                uom = uom.lower()
162            if ql.uom.isupper():
163                uom = uom.upper()
164
165            # Prepare the plot the figure (actual plotting actions are postponed until save)
166            fig = figure()
167            plot_date(elapsed_times, vals, 'b-', xdate=True, lw=1)
168            plot_date(elapsed_times, vals, 'go', markeredgecolor = 'g', xdate=True, lw=2)
169            ax = gca()
170            ax.xaxis.set_major_locator(tickLocator)
171            ax.xaxis.set_major_formatter(tickFormatter)
172            fig.autofmt_xdate()  # show times without overlaps
173            time_format = '%d-%b-%Y %H:%M:%S UTC'
174            xlabel('Times between %s and %s ' % (start_date.strftime(time_format), end_date.strftime(time_format)))
175            ylabel('Values [%s]' % uom)
176            title('"%s" (%s)' % (feature.id, feature.description.CONTENT))
177            grid(True)
178
179            # Save the figure to a temporary file
180            tempFile = NamedTemporaryFile(suffix='.png')
181            savefig(tempFile.name)
182           
183            return tempFile
184
185        def _set_response(tempFile):
186            '''
187            Set the WSGI response to an image, containing image read from a temporary location.
188            '''
189            img = Image.open(tempFile.name)
190            buf = StringIO()
191            img.save(buf, 'PNG')
192            response.content_type = 'image/png'
193            response.content = buf.getvalue()
194           
195        #----------------------
196
197        # Get parameters from the request object
198        try:
199            feature_id = str(request.params['feature_id'])     # convert back from Unicode
200            station_name = str(request.params['station_name']) # convert back from Unicode
201        except KeyError:
202            raise HTTPBadRequest('Parameters "feature_id" and "station_name" must be supplied.')
203
204        # Try to retrieve the csmlPointSeriesFeature object
205        try:
206            csmlPointSeriesFeature = self._retrieveCsmlPointSeriesFeature(station_name, feature_id)
207        except LookupError, e:
208            errorMessage = e.args[0]
209            httpNotFound = HTTPNotFound()
210            httpNotFound.explanation = ''
211            httpNotFound.detail = errorMessage
212            raise httpNotFound
213
214        # Try to plot the feature into a temporary file, and put the contents of that file into the response
215        try:
216            tempFile = _plot_feature(csmlPointSeriesFeature)    # plot the feature into a temporary file
217            _set_response(tempFile)                             # set the response as an image containing the plot
218        finally:
219            try:
220                tempFile.close()
221            except NameError:
222                pass  # tempFile undefined -- no need to close
223
224    def list(self):
225        '''
226        Handler for generating a list of CSML features per station, with dynamic links to the plot service.
227        Request parameters:
228                               station_name    Name of the requested station.
229                               
230        Response:              A text/html with the page containing links to the plot service on the same server.
231        '''
232
233        # Get parameters from the request object
234        try:
235            station_name = str(request.params['station_name']) # convert back from Unicode
236        except KeyError:
237            raise HTTPBadRequest('Parameter "station_name" must be supplied.')
238
239        # Prepare the request for the GeoServer -- to return a collection of np:Station, containing a single np:Station,
240        # which contains a list of CSML features.
241        geoServerRequestUrl = urllib.quote(self.geoServerUrl + '?request=getFeature&service=wfs&version=1.1.0&typename=np:Station&filter=<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><ogc:PropertyIsEqualTo><ogc:PropertyName>stationName</ogc:PropertyName><ogc:Literal>' + station_name + '</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>', '/._:?&=')
242
243        # Acquire the GeoServer response and parse it into a WFSStationCollection object
244        geoServerResponse = wget(geoServerRequestUrl)
245        if not geoServerResponse:
246            raise LookupError('Cannot acquire response from server (wrong URL or server down)')
247        wfsStationCollection = csml2kml.Station.WFSStationCollection()
248        wfsStationCollection.parseString(geoServerResponse)
249        if len(wfsStationCollection.stations) != 1:
250            raise ValueError('Multiple stations match OGC selection filter (only one must match)')
251        wfsStation = wfsStationCollection.stations[0]
252
253        # Generate HTML with a list of CSML features contained in the station.
254        # Currently, this is done simply by directly generating HTML (i.e. no template was used).
255        htmlElement = Element('html')
256        SubElement(htmlElement, 'title').text = 'List of CSML features for station ' + station_name
257        bodyElement = SubElement(htmlElement, 'body')
258        SubElement(bodyElement, 'h2').text = 'List of CSML features for station ' + station_name
259        tableElement = SubElement(bodyElement, 'table')
260        tableElement.set('border', '1')
261        headingRowElement = SubElement(tableElement, 'tr')
262        SubElement(headingRowElement, 'th').text = 'Feature name'
263        SubElement(headingRowElement, 'th').text = 'Data collected since'
264        SubElement(headingRowElement, 'th').text = 'Data collected until '
265        for stationFeature in wfsStation.stationFeatures:
266            if self.displayIntervalStart >= stationFeature.collectBeginDate and self.displayIntervalEnd <= stationFeature.collectEndDate:
267                rowElement = SubElement(tableElement, 'tr')
268                featureNameElement = SubElement(rowElement, 'td')
269                anchorElement = SubElement(featureNameElement, 'a')
270                linkToGrapher = self.servedFromUrl + '/plot?station_name=' + station_name + '&feature_id=' + stationFeature.featureId
271                anchorElement.set('href', linkToGrapher)
272                anchorElement.text = stationFeature.featureId
273                SubElement(rowElement, 'td').text = self._datetimeToGeoServerDate(stationFeature.collectBeginDate)
274                SubElement(rowElement, 'td').text = self._datetimeToGeoServerDate(stationFeature.collectEndDate)
275
276        htmlStringIO = StringIO()
277        ElementTree(htmlElement).write(htmlStringIO)
278
279        response.content_type = 'text/html'
280        response.content = htmlStringIO.getvalue()
Note: See TracBrowser for help on using the repository browser.