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

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

using 2d crs in profile series

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   
64    pathToSubsetNetCDF, kwargs, timeAxis, timeName, caltype, times=csml.API.genSubset.genericSubset(self, csmlpath, ncpath, self.domain, kwargs)
65     
66    ##Get names of variables in file and relate them to the subset selection
67    selection={}
68    frame=''
69    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
70        try:
71            selection[gridOrd.gridAxesSpanned.CONTENT]=kwargs[gridOrd.coordAxisLabel.CONTENT]
72        except KeyError:
73            allValues=tuple(self.domain[gridOrd.coordAxisLabel.CONTENT])
74        if hasattr(gridOrd.coordAxisValues, 'timePositionList'):
75            if hasattr(gridOrd.coordAxisValues, 'frame'):
76                frame=gridOrd.coordAxisValues.frame
77
78    del selection[timeAxis] #NOTE: Haven't resolved the single CRS issue so cannot subset by time within an individual file for now
79    print timeName
80    strTimes, axisorder, units, fulldata, fillvalue =csml.API.genSubset.getTheData(self, selection, times, timeName)
81
82    return pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs
83   
84def subsetToGridSeries(self, csmlpath=None, ncpath=None,**kwargs):
85    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
86    pathToSubsetNetCDF, crs, frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
87   
88    #Okay, got the data now. Need to write CSML feature and NetCDF files.
89    #Writing out the CSML feature
90   
91    # define domain/coverage  to use in 'value' attribute   
92    newdomain=csml.parser.GridSeriesDomain()
93    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
94    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame)
95    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
96    newdomain.coordTransformTable=cTT
97    newdomain.srsName=self.value.gridSeriesDomain.srsName 
98    newdomain.axisLabels=self.value.gridSeriesDomain.axisLabels
99    newdomain.srsDimension=self.value.gridSeriesDomain.srsDimension
100    newdomain.dimension=self.value.gridSeriesDomain.dimension
101    env=csml.parser.GridEnvelope()
102    env.low=csml.parser.csString('0 0 0') #TODO
103    env.high=csml.parser.csString('0 0 0')
104    newdomain.limits=env
105    newdomain.aLabels=self.value.gridSeriesDomain.aLabels
106    rs=csml.parser.RangeSet()
107    sdid=csml.csmllibs.csmlextra.getRandomID()
108    descriptor=csml.parser.NetCDFExtract(id=sdid,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=self.name,arraySize=csml.parser.csString(totalArraySize))
109    rs=csml.parser.RangeSet()
110    va=csml.parser.ValueArray()
111    vc=csml.parser.ValueComponent()
112    vc.href='#%s'%sdid
113    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
114    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
115    vc.show='embed'
116    ql=csml.parser.MeasureOrNullList()
117    try:
118        ql.uom=self.value.rangeSet.valueArray.valueComponent.quantityList.uom
119    except:
120        ql.upm = 'unknown'  #TODO,
121    vc.quantityList=ql
122    va.valueComponent=vc
123    va.id=csml.csmllibs.csmlextra.getRandomID()
124    rs.valueArray=va
125    #gridseries coverage
126    cvg=csml.parser.GridSeriesCoverage()
127    cvg.id=csml.csmllibs.csmlextra.getRandomID()
128    cvg.rangeSet=rs
129    cvg.gridSeriesDomain=newdomain   
130   
131    #parameter, as before subsetting.
132    param = self.parameter
133       
134    #create a stand alone gridseries feature containing this coverage
135    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
136    subsettedFeature=csmlWrap.createGridSeriesFeature(value=cvg,parameter=param,featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
137 
138    ### write netcdf using NCWriter class (wraps cdms) ###
139    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
140    ords=cTT.gridOrdinates
141    axislist=[]
142    for a in axisorder:
143        axislist.append(self.gridnames[a])
144    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue)
145    nc.closeFinishedFile()
146    print 'NetCDF file written to %s'%pathToSubsetNetCDF
147    return subsettedFeature, pathToSubsetNetCDF, descriptor
148   
149
150def subsetToProfileSeries(self, csmlpath=None, ncpath=None,**kwargs):
151    #TODO   !!!!!!!!! Need to perform some sort of testing on the kwargs to check it is a profileseries request.
152   
153   
154    #perform the subset (note this included nearest neighbour searching, so may return a different set of kwargs
155    pathToSubsetNetCDF, crs,frame, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetGrid(csmlpath, ncpath,**kwargs) 
156    latName=crs.axes[crs.latAxis]
157    lonName=crs.axes[crs.lonAxis]
158    #Okay, got the data now. Need to write CSML feature and NetCDF files.
159    #Writing out the CSML feature
160   
161    # define domain/coverage  to use in 'value' attribute   
162    newdomain=csml.parser.ProfileSeriesDomain()
163    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
164    cTT=csml.API.genSubset.getCoordTransformTable(domainSubset, crs, frame) 
165   
166    #Need to remove location (lat/lon) axes from the cTT
167    newGridOrds=[]
168    for gridOrd in cTT.gridOrdinates:
169        if gridOrd.coordAxisLabel.CONTENT not in  [latName,lonName]:
170            newGridOrds.append(gridOrd)
171    cTT.gridOrdinates=newGridOrds
172    axes=[]
173    for ord in newGridOrds:
174        axes.append(ord.coordAxisLabel.CONTENT)
175    cat = csml.csmllibs.csmlcrs.CRSCatalogue()
176    crsInfo=cat.determineCRS(knownCRSAxes=axes)   
177    crs=cat.getCRS(crsInfo[0].srsName)
178   
179    newdomain.coordTransformTable=cTT   
180    newdomain.id=csml.csmllibs.csmlextra.getRandomID()
181    #TODO need to remove 'location' from this srs
182    newdomain.srsName=crsInfo[0].srsName
183    axisLabels=csml.csmllibs.csmlextra.stringify(crsInfo[1].keys())
184    newdomain.axisLabels=axisLabels
185    newdomain.srsDimension=2
186    newdomain.dimension=2
187    rangeSet=csml.parser.RangeSet()
188    descriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
189    rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
190   
191    #gridseries coverage
192    cvg=csml.parser.ProfileSeriesCoverage()
193    cvg.id=csml.csmllibs.csmlextra.getRandomID()
194    cvg.rangeSet=rangeSet
195    cvg.profileSeriesDomain=newdomain   
196    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
197   
198    #parameter, as before subsetting.
199    param = self.parameter
200   
201    #create 'location' attribute:
202    if (latName, lonName) is not (None, None):
203        locStr ='%s %s'%(kwargs[latName], kwargs[lonName])
204        loc=csml.parser.csString(locStr)
205    else:
206        loc = csml.parser.csString('unknown location')
207       
208   
209    #create a stand alone gridseries feature containing this coverage
210    subsettedFeature=csmlWrap.createProfileSeriesFeature(value=cvg,parameter=param, location=loc, featureID=csml.csmllibs.csmlextra.getRandomID(),name=self.name,description=self.description)
211 
212   
213    ### write netcdf using NCWriter class (wraps cdms) ###
214    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
215    ords=cTT.gridOrdinates
216    axislist=[]
217       
218    for a in axisorder:
219        axislist.append(self.gridnames[a])
220    nc.genWriteVar(self.id,ords, times, caltype, axislist, units, fulldata, fillvalue, latitude=kwargs[latName], longitude=kwargs[lonName])
221    nc.closeFinishedFile()
222   
223    return subsettedFeature, pathToSubsetNetCDF, descriptor
224
225def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
226    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to Profile
227    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
228    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
229    del kwargs['longitude']
230    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToProfile(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
231    return subsettedFeature, pathToSubsetNetCDF
232
233def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
234    #Two step process - subset GridSeries to ProfileSeries, then ProfileSeries to PointSeries
235    profileSeries, pSfile=self.subsetToProfileSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
236    del kwargs['latitude']    #TODO - need to remove excess kwargs based on the domain of the temporary profileSeries feature
237    del kwargs['longitude']
238    subsettedFeature, pathToSubsetNetCDF=profileSeries.subsetToPointSeries(csmlpath=csmlpath, ncpath=ncpath, **kwargs)   
239    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.