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

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

subsetting to point series working

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) 
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.coordTransformTable=cTT
93    newdomain.srsName=self.value.gridSeriesDomain.srsName 
94    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
95    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
96    rangeSet=csml.parser.RangeSet()
97    rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
98   
99    #gridseries coverage
100    cvg=csml.parser.GridSeriesCoverage()
101    cvg.rangeSet=rangeSet
102    cvg.gridSeriesDomain=newdomain   
103   
104    #parameter, as before subsetting.
105    param = self.parameter
106       
107    #create a stand alone gridseries feature containing this coverage
108    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
109    subsettedFeature=csmlWrap.createGridSeriesFeature(value=cvg,parameter=param,featureID=self.id,description=self.description)
110 
111    ### write netcdf using NCWriter class (wraps cdms) ###
112    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
113    ords=cTT.gridOrdinates
114    axislist=[]
115    for a in axisorder:
116        axislist.append(self.gridnames[a])
117    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue)
118    nc.closeFinishedFile()
119    print 'NetCDF file written to %s'%pathToSubsetNetCDF
120    return subsettedFeature, pathToSubsetNetCDF
121   
122
123def subsetToProfileSeries(self, csmlpath=None, ncpath=None,**kwargs):
124    #TODO   !!!!!!!!! Need to perform some sort of testing on the kwargs to check it is a profileseries request.
125   
126   
127    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
128    pathToSubsetNetCDF, crs,frame, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
129   
130    #Okay, got the data now. Need to write CSML feature and NetCDF files.
131    #Writing out the CSML feature
132   
133    # define domain/coverage  to use in 'value' attribute   
134    newdomain=csml.parser.ProfileSeriesDomain()
135    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
136    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame) 
137   
138    #Need to remove location (lat/lon) axes from the cTT
139    newGridOrds=[]
140    for gridOrd in cTT.gridOrdinates:
141        if gridOrd.coordAxisLabel.CONTENT not in  ['latitude', 'longitude']:
142            newGridOrds.append(gridOrd)
143    cTT.gridOrdinates=newGridOrds
144   
145   
146   
147    newdomain.coordTransformTable=cTT   
148    #TODO need to remove 'location' from this srs
149    newdomain.srsName=self.value.gridSeriesDomain.srsName 
150    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
151    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
152    rangeSet=csml.parser.RangeSet()
153    rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
154   
155    #gridseries coverage
156    cvg=csml.parser.ProfileSeriesCoverage()
157    cvg.rangeSet=rangeSet
158    cvg.profileSeriesDomain=newdomain   
159    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
160   
161    #parameter, as before subsetting.
162    param = self.parameter
163   
164    #create 'location' attribute:
165    latName=crs.axes[crs.latAxis]
166    lonName=crs.axes[crs.lonAxis]
167    if (latName, lonName) is not (None, None):
168        locStr ='%s %s'%(kwargs[latName], kwargs[lonName])
169        loc=csml.parser.csString(locStr)
170    else:
171        loc = csml.parser.csString('unknown location')
172       
173   
174    #create a stand alone gridseries feature containing this coverage
175    subsettedFeature=csmlWrap.createProfileSeriesFeature(value=cvg,parameter=param, location=loc, featureID=self.id,description=self.description)
176 
177   
178    ### write netcdf using NCWriter class (wraps cdms) ###
179    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
180    ords=cTT.gridOrdinates
181    axislist=[]
182       
183    for a in axisorder:
184        axislist.append(self.gridnames[a])
185    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, latitude=kwargs[latName], longitude=kwargs[lonName])
186    nc.closeFinishedFile()
187   
188    return subsettedFeature, pathToSubsetNetCDF
189
190def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
191    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to Profile
192    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
193    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
194    del kwargs['longitude']
195    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToProfile(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
196    return subsettedFeature, pathToSubsetNetCDF
197
198def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
199    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to PointSeries
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.subsetToPointSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
204    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.