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

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

storage descriptor separated from feature collection

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