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

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

Fixed problem with relative paths in CSML documents

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, **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, self.outputdir, self.ncname, 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, outputdir, ncname='gridseries.nc',**kwargs):
130    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
131    self.outputdir=outputdir
132    csml.csmllibs.csmlextra.checkDirExists(self.outputdir)
133    self.ncname=ncname
134    pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(**kwargs) 
135    #Okay, got the data now. Need to write CSML feature and NetCDF files.
136    #Writing out the CSML feature
137   
138    # define domain/coverage  to use in 'value' attribute   
139    newdomain=csml.parser.GridSeriesDomain()
140    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
141    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame)
142    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
143    newdomain.coordTransformTable=cTT
144    newdomain.srsName=self.value.gridSeriesDomain.srsName 
145    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
146    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
147    newdomain.dimension=self.value.gridSeriesDomain.dimension
148    env=csml.parser.GridEnvelope()
149    env.low=csml.parser.csString('0 0 0') #TODO
150    env.high=csml.parser.csString('0 0 0')
151    newdomain.limits=env
152    newdomain.aLabels=self.value.gridSeriesDomain.aLabels
153    rs=csml.parser.RangeSet()
154    sdid=csml.csmllibs.csmlextra.getRandomID()
155    descriptor=csml.parser.NetCDFExtract(id=sdid,fileName=csml.parser.csString(self.ncname),variableName=self.name,arraySize=csml.parser.csString(totalArraySize))
156    rs=csml.parser.RangeSet()
157    va=csml.parser.ValueArray()
158    vc=csml.parser.MeasureOrNullList()
159    vc.href='#%s'%sdid
160    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
161    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
162    vc.show='embed'
163    try:
164        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
165    except:
166        vc.uom = 'unknown'  #TODO,
167    va.valueComponent=vc
168    va.id=csml.csmllibs.csmlextra.getRandomID()
169    rs.valueArray=va
170    #gridseries coverage
171    cvg=csml.parser.GridSeriesCoverage()
172    cvg.id=csml.csmllibs.csmlextra.getRandomID()
173    cvg.rangeSet=rs
174    cvg.gridSeriesDomain=newdomain   
175   
176    #parameter, as before subsetting.
177    param = self.parameter
178       
179    #create a stand alone gridseries feature containing this coverage
180    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
181    subsettedFeature=csmlWrap.createGridSeriesFeature(value=cvg,parameter=param,featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
182 
183    ### write netcdf using NCWriter class (wraps cdms) ###
184    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
185    ords=cTT.gridOrdinates
186    axislist=[]
187    for a in axisorder:
188        axislist.append(self.gridnames[a])
189    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue)
190    nc.closeFinishedFile()
191    print 'NetCDF file written to %s'%pathToSubsetNetCDF
192    return subsettedFeature, pathToSubsetNetCDF, descriptor
193   
194
195def subsetToProfileSeries(self, outputdir, ncname='profileseries.nc',**kwargs):
196    #TODO   !!!!!!!!! Need to perform some sort of testing on the kwargs to check it is a profileseries request.
197    self.outputdir=outputdir
198    csml.csmllibs.csmlextra.checkDirExists(self.outputdir)
199    self.ncname=ncname   
200   
201    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
202    pathToSubsetNetCDF, crs,frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(**kwargs) 
203    latName=crs.axes[crs.latAxis]
204    lonName=crs.axes[crs.lonAxis]
205    #Okay, got the data now. Need to write CSML feature and NetCDF files.
206    #Writing out the CSML feature
207   
208    # define domain/coverage  to use in 'value' attribute   
209    newdomain=csml.parser.ProfileSeriesDomain()
210   
211   
212    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
213    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame) 
214   
215    #Need to remove location (lat/lon) axes from the cTT
216    newGridOrds=[]
217    for gridOrd in cTT.gridOrdinates:
218        if gridOrd.coordAxisLabel.CONTENT not in  [latName,lonName]:
219            newGridOrds.append(gridOrd)
220    cTT.gridOrdinates=newGridOrds
221    axes=[]
222    for ord in newGridOrds:
223        axes.append(ord.coordAxisLabel.CONTENT)
224    cat = csml.csmllibs.csmlcrs.CRSCatalogue()
225    crsInfo=cat.determineCRS(knownCRSAxes=axes)   
226    crs=cat.getCRS(crsInfo[0].srsName, labels=axes)
227   
228    newdomain.coordTransformTable=cTT   
229    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
230    #TODO need to remove 'location' from this srs
231    newdomain.srsName=crsInfo[0].srsName
232    axisLabels=csml.csmllibs.csmlextra.stringify(crsInfo[1].keys())
233    newdomain.axisLabels=axisLabels
234    newdomain.srsDimension=2
235    newdomain.dimension=2
236    env=csml.parser.GridEnvelope()
237    env.low=csml.parser.csString('0 0 0') #TODO
238    env.high=csml.parser.csString('0 0 0')
239    newdomain.limits=env
240    newdomain.aLabels=self.value.gridSeriesDomain.aLabels #todo 
241    rangeSet=csml.parser.RangeSet()
242    descid=csml.csmllibs.csmlextra.getRandomID()
243    descriptor=csml.parser.NetCDFExtract(id=descid,fileName=csml.parser.csString(ncname),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
244    rs=csml.parser.RangeSet()
245    va=csml.parser.ValueArray()
246    vc=csml.parser.MeasureOrNullList()
247    vc.href='#%s'%descid
248    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
249    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
250    vc.show='embed'
251    vc.insertedExtract=descriptor
252    try:
253        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
254    except:
255        vc.uom = 'unknown'  #TODO,
256   
257    va.valueComponent=vc
258    va.id=csml.csmllibs.csmlextra.getRandomID()
259    rs.valueArray=va
260    #profileseries coverage
261    cvg=csml.parser.ProfileSeriesCoverage()
262    cvg.id=csml.csmllibs.csmlextra.getRandomID()
263    cvg.rangeSet=rs
264    cvg.profileSeriesDomain=newdomain   
265    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
266   
267    #parameter, as before subsetting.
268    param = self.parameter
269   
270    #create 'location' attribute:
271    if (latName, lonName) is not (None, None):
272        locStr ='%s %s'%(kwargs[latName], kwargs[lonName])
273        loc=csml.parser.csString(locStr)
274    else:
275        loc = csml.parser.csString('unknown location')
276       
277   
278    #create a stand alone gridseries feature containing this coverage
279    subsettedFeature=csmlWrap.createProfileSeriesFeature(value=cvg,parameter=param, location=loc, featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
280 
281   
282    ### write netcdf using NCWriter class (wraps cdms) ###
283    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
284    ords=cTT.gridOrdinates
285    axislist=[]
286       
287    for a in axisorder:
288        axislist.append(self.gridnames[a])
289    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue, latitude=kwargs[latName], longitude=kwargs[lonName])
290    nc.closeFinishedFile()
291   
292    return subsettedFeature, pathToSubsetNetCDF, descriptor
293
294def subsetToProfile(self, outputdir, ncname='profile.nc',**kwargs):
295    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to Profile
296    profileSeries, pSfile=self.subsetToProfileSeries(outputdir, ncname, **kwargs)   
297    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
298    del kwargs['longitude']
299    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToProfile(ouputdir,ncname, **kwargs)   
300    return subsettedFeature, pathToSubsetNetCDF
301
302def subsetToPointSeries(self, outputdir, ncname='pointseries.nc',**kwargs):
303    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to PointSeries
304    profileSeries, pSfile=self.subsetToProfileSeries(outputdir, ncname, **kwargs)   
305    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
306    del kwargs['longitude']
307    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToPointSeries(outputdir, ncname, **kwargs)   
308    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.