source: TI02-CSML/trunk/csml/API/ops_GridSeriesFeature.py @ 2500

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI02-CSML/trunk/csml/API/ops_GridSeriesFeature.py@2500
Revision 2500, 13.1 KB checked in by domlowe, 12 years ago (diff)

fix to CRS catalogue and to ops_gridseriesfeature

Line 
1''' ops_GridSeriesFeature  contains operations for GridSeriesFeatures'''
2
3import csml.parser
4import csml.csmllibs.csmltime
5import csml.csmllibs.csmldocument
6import csml.API.ops_AbstractFeature
7import csml.API.genSubset
8import csml.csmllibs.netCDFWriter
9import csmlutils
10
11
12import sys  #remove later
13
14def testmethod(self):
15    #print 'testmethod for gridseries feature'
16    return 'testmethod - gridseries'
17
18def getAllowedSubsettings(self):
19    return ['subsetToGridSeries', 'subsetToProfileSeries']  #other operations
20
21def getSliceIndices(self, selection):
22    ''' Calculates indices to use in slicing (eg for RawFileExtracts) and adds them to the selection dictionary
23    '''
24    selLower=[]
25    selUpper=[]
26     
27    #create artificial range for single selections so that (60) becomes (60,60)
28    for sel in selection:
29        if type(selection[sel]) in [int,float]:  #ie. single value as opposed to a list containing a range
30            tmp=selection[sel]
31            selection[sel]=[tmp,tmp] 
32       
33    for sel in selection:
34        for item in enumerate(self.domain[sel]):
35            index=item[0]
36            value=item[1]   
37            if value==selection[sel][0]:
38                #selLower.append(self.domain[sel].index(item))
39                limit1=index
40                #selLower.append(item[0])
41            if value==selection[sel][1]:
42                #selUpper.append(self.domain[sel].index(item))
43                limit2=index
44               
45        #make sure the lower limit is the smaller of the two selection criteria       
46        if limit1 <= limit2:
47            selLower.append(limit1)
48            selUpper.append(limit2+1)#plus 1 to take account of the fact that Numeric (and python) slicing returns only 6 values for [0:6] so, to get the first 7 values say you need to pass [0:7]
49        else:
50            selLower.append(limit2)
51            selUpper.append(limit1 +1)
52   
53    selection['lower']=tuple(selLower)
54    selection['upper']=tuple(selUpper) 
55    return selection
56
57
58def getDomain(self):
59    #returns domain as a dictionary of ordinates {name: [values], ...}
60    self.domain={}
61    self.gridnames={}
62    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
63        name=gridOrd.coordAxisLabel.CONTENT
64        self.gridnames[gridOrd.gridAxesSpanned.CONTENT]=name
65        if hasattr(gridOrd.coordAxisValues, 'insertedExtract'):
66            self.domain[name], fill, axisorder, units=gridOrd.coordAxisValues.insertedExtract.getData()
67        else:           
68            valList=[]
69            try:
70                vals=gridOrd.coordAxisValues.coordinateList.CONTENT
71                for val in vals.split(): 
72                    valList.append(eval(val))
73            except:
74                vals=gridOrd.coordAxisValues.timePositionList.CONTENT
75                for val in vals.split(): 
76                    valList.append(val)           
77            self.domain[name]=valList   
78    return self.domain
79
80def getUom(self):
81    uom=None
82    #returns the uom of the phenomenon.
83    try: 
84        uom=self.value.rangeSet.valueArray.valueComponent.quantityList.insertedExtract.uom.CONTENT
85    except AttributeError:
86        uom =None
87    return uom
88
89def _subsetGrid(self, csmlpath=None, ncpath=None,**kwargs):
90    '''this takes a selection from a gridseries object (be it a profile, a grid, whatever, it is still just a selection'''
91           
92    #set self.domain:
93    self.getDomain()     
94   
95    #if request doesn't match domain points find nearest neighbours
96    kwargs=csml.API.genSubset.checkNeighbours(self.domain, self.gridnames, **kwargs)
97    #get the CRS from a  the  catalogue
98    cat=csml.csmllibs.csmlcrs.CRSCatalogue()
99    crs=cat.getCRS(self.value.gridSeriesDomain.srsName, self.value.gridSeriesDomain.axisLabels) 
100   
101    #non-feature specific setup code, mainly handles the time dimension/calendar
102   
103    pathToSubsetNetCDF, kwargs, timeAxis, timeName, caltype, times=csml.API.genSubset.genericSubset(self, csmlpath, ncpath, self.domain, kwargs)
104     
105    ##Get names of variables in file and relate them to the subset selection
106    selection={}
107    frame=''
108    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
109        try:
110            selection[gridOrd.gridAxesSpanned.CONTENT]=kwargs[gridOrd.coordAxisLabel.CONTENT]
111        except KeyError:
112            allValues=tuple(self.domain[gridOrd.coordAxisLabel.CONTENT])
113        if hasattr(gridOrd.coordAxisValues, 'timePositionList'):
114            if hasattr(gridOrd.coordAxisValues, 'frame'):
115                frame=gridOrd.coordAxisValues.frame
116
117    try:
118        del selection[timeAxis] #NOTE: Haven't resolved the single CRS issue so cannot subset by time within an individual file for now
119    except KeyError:
120        pass
121   
122    #get slice indices
123    selection=self.getSliceIndices(selection)
124
125           
126    strTimes, axisorder, units, fulldata, fillvalue =csml.API.genSubset.getTheData(self, selection, times, timeName)
127    return pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs
128   
129def subsetToGridSeries(self, csmlpath=None, ncpath=None,**kwargs):
130    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
131    pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
132    #Okay, got the data now. Need to write CSML feature and NetCDF files.
133    #Writing out the CSML feature
134   
135    # define domain/coverage  to use in 'value' attribute   
136    newdomain=csml.parser.GridSeriesDomain()
137    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
138    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame)
139    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
140    newdomain.coordTransformTable=cTT
141    newdomain.srsName=self.value.gridSeriesDomain.srsName 
142    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
143    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
144    newdomain.dimension=self.value.gridSeriesDomain.dimension
145    env=csml.parser.GridEnvelope()
146    env.low=csml.parser.csString('0 0 0') #TODO
147    env.high=csml.parser.csString('0 0 0')
148    newdomain.limits=env
149    newdomain.aLabels=self.value.gridSeriesDomain.aLabels
150    rs=csml.parser.RangeSet()
151    sdid=csml.csmllibs.csmlextra.getRandomID()
152    descriptor=csml.parser.NetCDFExtract(id=sdid,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=self.name,arraySize=csml.parser.csString(totalArraySize))
153    rs=csml.parser.RangeSet()
154    va=csml.parser.ValueArray()
155    vc=csml.parser.MeasureOrNullList()
156    vc.href='#%s'%sdid
157    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
158    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
159    vc.show='embed'
160    try:
161        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
162    except:
163        vc.uom = 'unknown'  #TODO,
164    va.valueComponent=vc
165    va.id=csml.csmllibs.csmlextra.getRandomID()
166    rs.valueArray=va
167    #gridseries coverage
168    cvg=csml.parser.GridSeriesCoverage()
169    cvg.id=csml.csmllibs.csmlextra.getRandomID()
170    cvg.rangeSet=rs
171    cvg.gridSeriesDomain=newdomain   
172   
173    #parameter, as before subsetting.
174    param = self.parameter
175       
176    #create a stand alone gridseries feature containing this coverage
177    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
178    subsettedFeature=csmlWrap.createGridSeriesFeature(value=cvg,parameter=param,featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
179 
180    ### write netcdf using NCWriter class (wraps cdms) ###
181    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
182    ords=cTT.gridOrdinates
183    axislist=[]
184    for a in axisorder:
185        axislist.append(self.gridnames[a])
186    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue)
187    nc.closeFinishedFile()
188    print 'NetCDF file written to %s'%pathToSubsetNetCDF
189    return subsettedFeature, pathToSubsetNetCDF, descriptor
190   
191
192def subsetToProfileSeries(self, csmlpath=None, ncpath=None,**kwargs):
193    #TODO   !!!!!!!!! Need to perform some sort of testing on the kwargs to check it is a profileseries request.
194   
195   
196    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
197    pathToSubsetNetCDF, crs,frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
198    latName=crs.axes[crs.latAxis]
199    lonName=crs.axes[crs.lonAxis]
200    #Okay, got the data now. Need to write CSML feature and NetCDF files.
201    #Writing out the CSML feature
202   
203    # define domain/coverage  to use in 'value' attribute   
204    newdomain=csml.parser.ProfileSeriesDomain()
205   
206   
207    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
208    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame) 
209   
210    #Need to remove location (lat/lon) axes from the cTT
211    newGridOrds=[]
212    for gridOrd in cTT.gridOrdinates:
213        if gridOrd.coordAxisLabel.CONTENT not in  [latName,lonName]:
214            newGridOrds.append(gridOrd)
215    cTT.gridOrdinates=newGridOrds
216    axes=[]
217    for ord in newGridOrds:
218        axes.append(ord.coordAxisLabel.CONTENT)
219    cat = csml.csmllibs.csmlcrs.CRSCatalogue()
220    crsInfo=cat.determineCRS(knownCRSAxes=axes)   
221    crs=cat.getCRS(crsInfo[0].srsName)
222   
223    newdomain.coordTransformTable=cTT   
224    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
225    #TODO need to remove 'location' from this srs
226    newdomain.srsName=crsInfo[0].srsName
227    axisLabels=csml.csmllibs.csmlextra.stringify(crsInfo[1].keys())
228    newdomain.axisLabels=axisLabels
229    newdomain.srsDimension=2
230    newdomain.dimension=2
231    env=csml.parser.GridEnvelope()
232    env.low=csml.parser.csString('0 0 0') #TODO
233    env.high=csml.parser.csString('0 0 0')
234    newdomain.limits=env
235    newdomain.aLabels=self.value.gridSeriesDomain.aLabels #todo 
236    rangeSet=csml.parser.RangeSet()
237    descid=csml.csmllibs.csmlextra.getRandomID()
238    descriptor=csml.parser.NetCDFExtract(id=descid,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
239    rs=csml.parser.RangeSet()
240    va=csml.parser.ValueArray()
241    vc=csml.parser.MeasureOrNullList()
242    vc.href='#%s'%descid
243    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
244    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
245    vc.show='embed'
246    try:
247        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
248    except:
249        vc.uom = 'unknown'  #TODO,
250    va.valueComponent=vc
251    va.id=csml.csmllibs.csmlextra.getRandomID()
252    rs.valueArray=va
253    #profileseries coverage
254    cvg=csml.parser.ProfileSeriesCoverage()
255    cvg.id=csml.csmllibs.csmlextra.getRandomID()
256    cvg.rangeSet=rs
257    cvg.profileSeriesDomain=newdomain   
258    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
259   
260    #parameter, as before subsetting.
261    param = self.parameter
262   
263    #create 'location' attribute:
264    if (latName, lonName) is not (None, None):
265        locStr ='%s %s'%(kwargs[latName], kwargs[lonName])
266        loc=csml.parser.csString(locStr)
267    else:
268        loc = csml.parser.csString('unknown location')
269       
270   
271    #create a stand alone gridseries feature containing this coverage
272    subsettedFeature=csmlWrap.createProfileSeriesFeature(value=cvg,parameter=param, location=loc, featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
273 
274   
275    ### write netcdf using NCWriter class (wraps cdms) ###
276    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
277    ords=cTT.gridOrdinates
278    axislist=[]
279       
280    for a in axisorder:
281        axislist.append(self.gridnames[a])
282    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue, latitude=kwargs[latName], longitude=kwargs[lonName])
283    nc.closeFinishedFile()
284   
285    return subsettedFeature, pathToSubsetNetCDF, descriptor
286
287def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
288    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to Profile
289    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
290    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
291    del kwargs['longitude']
292    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToProfile(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
293    return subsettedFeature, pathToSubsetNetCDF
294
295def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
296    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to PointSeries
297    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
298    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
299    del kwargs['longitude']
300    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToPointSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
301    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.