source: cows/branches/wcsmerge/cows/service/imps/csmlbackend/wcs_csmllayer.py @ 4634

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/branches/wcsmerge/cows/service/imps/csmlbackend/wcs_csmllayer.py@4634
Revision 4634, 6.0 KB checked in by domlowe, 12 years ago (diff)

more merging

Line 
1"""
2implementation of ILayerMapper, IwmsLayer, IwmsDimension, ILayerSlab interfaces, as defined in wms_iface.py & wxs_iface.py
3
4"""
5import os, string
6import csml
7try:
8    import cdms2 as cdms
9except:
10    import cdms
11from pylons import config, request, session
12from copy import copy
13
14import logging
15log = logging.getLogger(__name__)
16
17from cows.model.contents import DatasetSummary
18from cows.service.imps.csmlbackend.csmlcommon import CSMLLayerMapper, CSMLConnector, extractToNetCDF
19
20
21class CSMLwcsCoverageMapper(CSMLLayerMapper): #Todo define IwcsCoverageMapper
22    """
23    Map keyword arguments to a collection of layers (coverages)
24    Supports the retrieval of coverages according to arbitrary
25    keyword/value pairs. 
26    """
27    def __init__(self):
28        super(CSMLwcsCoverageMapper, self).__init__()
29       
30   
31    def getInfo(self, feature):
32        ''' given a csml feature, return info about the layer/feature
33        @return:   title, abstract, units, crss '''
34
35        title, abstract = super(CSMLwcsCoverageMapper, self).getInfo(feature)
36        units=feature.getDomainUnits()
37        tmpunits=copy(units)
38        tmpunits.reverse()
39#        domain = feature.getDomain()
40        crs=feature.getNativeCRS()
41        crss=[self._crscat.getCRS(crs).twoD]
42        if 'EPSG:4326' in crss:
43            crss.append('CRS:84')
44            crss.append('WGS84')
45        return title, abstract, units, crss
46       
47       
48     
49    def map(self, **kwargs):
50        """
51        Given csml.parser.Dataset object list the names of
52        all layers available.
53       
54        @return: A mapping of layer names to ILayer implementations.
55        @raise ValueError: If no layers are available for these keywords.
56        """
57        fileoruri=kwargs['fileoruri']
58        if fileoruri in self.layermapcache.keys():
59            #we've accessed this layer map before, get it from the cache dictionary
60            return self.layermapcache[fileoruri]
61         
62        ds = self.connector.getCsmlDoc(fileoruri)
63        layermap={}
64        self._crscat=csml.csmllibs.csmlcrs.CRSCatalogue()
65        for feature in csml.csmllibs.csmlextra.listify(ds.featureCollection.featureMembers):
66            title, abstract, units, crss=self.getInfo(feature)
67            layermap[feature.id]=CSMLCoverage(title,abstract, units, crss, feature)
68        if len(layermap) > 0:
69            self.layermapcache[fileoruri]=layermap
70            return layermap
71        else:
72            raise ValueError
73
74class CoverageDescription(DatasetSummary): #ToDo define ICoverageDescription?
75    """
76    Extends DatasetSummary from cows.model.contents
77    """
78    def __init__(self, identifier, timeDomain, crs=None, **kw):
79        super(CoverageDescription, self).__init__(**kw)
80        self.identifier=identifier
81        self.timeLimits=timeDomain
82        self.crs=crs
83
84
85class CSMLCoverage(): #TODO: define ICoverage
86    """ represents a WCS Coverage. Implements ICoverage """
87   
88    def __init__(self, title, abstract,  units, crss, feature):
89        self.title=title
90        self.abstract=abstract
91        self.description='TO DO - coverage description'
92        self.timeLimits='t1, t2'
93        self.units=units
94        self.crss=crss
95        self._feature=feature
96        self.id=feature.id
97        bb= self._feature.getCSMLBoundingBox().getBox()
98        #convert 0 - 360 to -180, 180 as per common WXS convention
99        if abs(bb[2]-bb[0]) >= 359 and abs(bb[2]-bb[0]) < 361:
100            bb[0], bb[2]=-180, 180
101        self.wgs84BBox = bb
102        self.featureInfoFormats = ['text/html']
103       
104    def getDescription(self):
105        pass
106   
107    def getBBox(self, crs):
108        """
109        @return: A 4-typle of the bounding box in the given coordinate
110            reference system.
111        """
112        #TODO: make this generic
113        return self.wgs84BBox
114   
115    def getCvg(self, bbox, time=None, crs=None, response_crs=None):
116        """
117        Creates a subset of the layer in a particular CRS and set of
118        dimensions.
119        #TODO: this is all out of synch
120        @param crs: The coordinate reference system.
121        @param dimValues: A mapping of dimension names to dimension values
122            as specified in the IDimension.extent
123        @param renderOpts: A generic mapping object for passing rendering
124            options
125        @return: An object implementing ILayerSlab
126        #create netcdf for whole lat/lon for given dimValues, use to init slab
127        """
128
129        log.debug('WCS: getSubset(%s, %s, %s)' % (bbox, time, crs))
130        #unpack the Boundingbox.
131       
132       
133        ############################# from old WCS stack #################
134        boundingbox=bbox
135        lon=self._feature.getLongitudeAxis()
136        lat=self._feature.getLatitudeAxis()
137        t=self._feature.getTimeAxis()
138        if None in [lon, lat, t]:
139            #TODO need to return a suitable wcs error.
140            print 'warning, could not get correct axis info'
141            #best guess!
142            if t is None:
143                t='time'
144            if lon is None:
145                lon = 'longitude'
146            if lat is None:
147                lat = 'latitude'
148       
149        #create selection dictionary:
150        sel={}
151        sel[lat]=(boundingbox[1], boundingbox[3])
152        sel[lon]=(boundingbox[0], boundingbox[2])
153        if time is not None:
154            if  type(time) is unicode:
155                sel[t]=str(time)
156            else:
157                sel[t]=time
158        #z is the 4th axis (eg height or pressure).
159        #NOTE, need to decide whether bounding box is of form: x1,y1,z1,x2,y2,z2 or x1,y1,x2,y2,z1,z2
160        #currently the latter is implemented.
161           
162        if len(boundingbox)  == 6:
163            for ax in self._feature.getAxisLabels():
164                if ax not in [lat, lon, t]:
165                    #must be Z 
166                    z=str(ax)
167                    sel[z]=(boundingbox[4], boundingbox[5])
168           
169           
170        axisNames=self._feature.getAxisLabels()
171        ##################################################################
172       
173        filename = extractToNetCDF(self._feature, sel)
174        return filename
175       
Note: See TracBrowser for help on using the repository browser.