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

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

various fixes to subsetting output

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']  #other operations
20
21def getDomain(self):
22    #returns domain as a dictionary of ordinates {name: [values], ...}
23    self.domain={}
24    self.gridnames={}
25    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
26        name=gridOrd.coordAxisLabel.CONTENT
27        self.gridnames[gridOrd.gridAxesSpanned.CONTENT]=name
28        if hasattr(gridOrd.coordAxisValues, '__insertedExtract'):
29            self.domain[name], fill, axisorder, units=gridOrd.coordAxisValues.__insertedExtract.getData()
30        else:           
31            try:
32                vals=gridOrd.coordAxisValues.coordinateList.CONTENT
33            except:
34                vals=gridOrd.coordAxisValues.timePositionList.CONTENT
35            valList=[]
36            for val in vals.split(): 
37                valList.append(val)
38            self.domain[name]=valList
39    return self.domain
40
41def getUom(self):
42    uom=None
43    #returns the uom of the phenomenon.
44    try: 
45        uom=self.value.rangeSet.valueArray.valueComponent.quantityList.__insertedExtract.uom.CONTENT
46    except AttributeError:
47        uom =None
48    return uom
49
50def _subsetGrid(self, csmlpath=None, ncpath=None,**kwargs):
51    '''this takes a selection from a gridseries object (be it a profile, a grid, whatever, it is still just a selection'''
52           
53    #set self.domain:
54    self.getDomain()     
55   
56    #if request doesn't match domain points find nearest neighbours
57    kwargs=csml.API.genSubset.checkNeighbours(self.domain, self.gridnames, **kwargs)
58    #get the CRS from a  the  catalogue
59    cat=csml.csmllibs.csmlcrs.CRSCatalogue()
60    crs=cat.getCRS(self.value.gridSeriesDomain.srsName, self.value.gridSeriesDomain.axisLabels) 
61   
62    #non-feature specific setup code, mainly handles the time dimension/calendar
63    pathToSubsetNetCDF, kwargs, timeAxis, timeName,calunits, caltype, times=csml.API.genSubset.genericSubset(self, csmlpath, ncpath, self.domain, kwargs)
64     
65    ##Get names of variables in file and relate them to the subset selection
66    selection={}
67    frame=''
68    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
69        try:
70            selection[gridOrd.gridAxesSpanned.CONTENT]=kwargs[gridOrd.coordAxisLabel.CONTENT]
71        except KeyError:
72            allValues=tuple(self.domain[gridOrd.coordAxisLabel.CONTENT])
73        if hasattr(gridOrd.coordAxisValues, 'timePositionList'):
74            if hasattr(gridOrd.coordAxisValues, 'frame'):
75                frame=gridOrd.coordAxisValues.frame
76
77    del selection[timeAxis] #NOTE: Haven't resolved the single CRS issue so cannot subset by time within an individual file for now
78    strTimes, axisorder, units, fulldata, fillvalue =csml.API.genSubset.getTheData(self, selection, times, timeName)
79    return pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs
80   
81def subsetToGridSeries(self, csmlpath=None, ncpath=None,**kwargs):
82    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
83    pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
84   
85    #Okay, got the data now. Need to write CSML feature and NetCDF files.
86    #Writing out the CSML feature
87   
88    # define domain/coverage  to use in 'value' attribute   
89    newdomain=csml.parser.GridSeriesDomain()
90    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
91    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame)
92    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
93    newdomain.coordTransformTable=cTT
94    newdomain.srsName=self.value.gridSeriesDomain.srsName 
95    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
96    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
97    newdomain.dimension=self.value.gridSeriesDomain.dimension
98    env=csml.parser.GridEnvelope()
99    env.low=csml.parser.csString('0 0 0') #TODO
100    env.high=csml.parser.csString('0 0 0')
101    newdomain.limits=env
102    newdomain.aLabels=self.value.gridSeriesDomain.aLabels
103    rangeSet=csml.parser.RangeSet()
104    rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=csml.csmllibs.csmlextra.getRandomID(),fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
105   
106    #gridseries coverage
107    cvg=csml.parser.GridSeriesCoverage()
108    cvg.id=csml.csmllibs.csmlextra.getRandomID()
109    cvg.rangeSet=rangeSet
110    cvg.gridSeriesDomain=newdomain   
111   
112    #parameter, as before subsetting.
113    param = self.parameter
114       
115    #create a stand alone gridseries feature containing this coverage
116    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
117    subsettedFeature=csmlWrap.createGridSeriesFeature(value=cvg,parameter=param,featureID=self.id,description=self.description)
118 
119    ### write netcdf using NCWriter class (wraps cdms) ###
120    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
121    ords=cTT.gridOrdinates
122    axislist=[]
123    for a in axisorder:
124        axislist.append(self.gridnames[a])
125    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue)
126    nc.closeFinishedFile()
127    print 'NetCDF file written to %s'%pathToSubsetNetCDF
128    return subsettedFeature, pathToSubsetNetCDF
129   
130
131def subsetToProfileSeries(self, csmlpath=None, ncpath=None,**kwargs):
132    #TODO   !!!!!!!!! Need to perform some sort of testing on the kwargs to check it is a profileseries request.
133   
134   
135    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
136    pathToSubsetNetCDF, crs,frame, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
137   
138    #Okay, got the data now. Need to write CSML feature and NetCDF files.
139    #Writing out the CSML feature
140   
141    # define domain/coverage  to use in 'value' attribute   
142    newdomain=csml.parser.ProfileSeriesDomain()
143    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
144    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame) 
145   
146    #Need to remove location (lat/lon) axes from the cTT
147    newGridOrds=[]
148    for gridOrd in cTT.gridOrdinates:
149        if gridOrd.coordAxisLabel.CONTENT not in  ['latitude', 'longitude']:
150            newGridOrds.append(gridOrd)
151    cTT.gridOrdinates=newGridOrds
152   
153   
154   
155    newdomain.coordTransformTable=cTT   
156    #TODO need to remove 'location' from this srs
157    newdomain.srsName=self.value.gridSeriesDomain.srsName 
158    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
159    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
160    rangeSet=csml.parser.RangeSet()
161    rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
162   
163    #gridseries coverage
164    cvg=csml.parser.ProfileSeriesCoverage()
165    cvg.rangeSet=rangeSet
166    cvg.profileSeriesDomain=newdomain   
167    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
168   
169    #parameter, as before subsetting.
170    param = self.parameter
171   
172    #create 'location' attribute:
173    latName=crs.axes[crs.latAxis]
174    lonName=crs.axes[crs.lonAxis]
175    if (latName, lonName) is not (None, None):
176        locStr ='%s %s'%(kwargs[latName], kwargs[lonName])
177        loc=csml.parser.csString(locStr)
178    else:
179        loc = csml.parser.csString('unknown location')
180       
181   
182    #create a stand alone gridseries feature containing this coverage
183    subsettedFeature=csmlWrap.createProfileSeriesFeature(value=cvg,parameter=param, location=loc, featureID=self.id,description=self.description)
184 
185   
186    ### write netcdf using NCWriter class (wraps cdms) ###
187    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
188    ords=cTT.gridOrdinates
189    axislist=[]
190       
191    for a in axisorder:
192        axislist.append(self.gridnames[a])
193    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, latitude=kwargs[latName], longitude=kwargs[lonName])
194    nc.closeFinishedFile()
195   
196    return subsettedFeature, pathToSubsetNetCDF
197
198def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
199    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to Profile
200    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
201    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
202    del kwargs['longitude']
203    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToProfile(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
204    return subsettedFeature, pathToSubsetNetCDF
205
206def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
207    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to PointSeries
208    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
209    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
210    del kwargs['longitude']
211    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToPointSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
212    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.