source: TI02-CSML/trunk/csml/API/ops_ProfileSeriesFeature.py @ 2550

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

more on pointseries and qxf

Line 
1''' ops_ProfileSeriesFeature  contains operations for ProfileSeriesFeatures'''
2import csml
3
4def testmethod(self):
5    print 'testmethod for profileSeries feature'
6    return 'testmethod profileseries'
7
8
9def getDomain(self):
10    #returns domain as a dictionary of ordinates {name: [values], ...}
11    #For ProfileSeries this is a combination of the location attribute and the time ordinate.
12    self.domain={}
13    self.gridnames={}
14    for gridOrd in self.value.profileSeriesDomain.coordTransformTable.gridOrdinates:
15        name=gridOrd.coordAxisLabel.CONTENT
16        self.gridnames[gridOrd.gridAxesSpanned.CONTENT]=name
17        #handle time axis
18        if hasattr(gridOrd.coordAxisValues, 'timePositionList'):  #..it should do..
19            if hasattr(gridOrd.coordAxisValues, 'insertedExtract'):
20                self.domain[name], fill, axisorder, units=gridOrd.timePositionList.insertedExtract.getData()
21            else:
22                vals=gridOrd.coordAxisValues.timePositionList.CONTENT             
23                valList=[]
24                for val in vals.split(): 
25                    valList.append(val)
26                self.domain[name]=valList
27
28        #handle other axes , eg pressure levels, but ignore location
29        #TODO should use lonAxis at latAxis from CRS rather than latitude, longitude.
30        if hasattr(gridOrd.coordAxisValues, 'coordinateList'): 
31            if gridOrd.coordAxisLabel not in ['latitude', 'longitude']:
32                if hasattr(gridOrd.coordAxisValues, 'insertedExtract'):
33                    self.domain[name], fill, axisorder, units=gridOrd.coordinateList.insertedExtract.getData()
34                else:
35                    vals=gridOrd.coordAxisValues.coordinateList.CONTENT             
36                    valList=[]
37                    for val in vals.split(): 
38                        valList.append(float(val))
39                    self.domain[name]=valList
40    return self.domain
41
42def _subsetProfileSeries(self, csmlpath=None, ncpath=None,**kwargs):
43    '''this takes a temporal selection from a ProfileSeries object  - i.e. returns one or more 'profiles', can be used to make another ProfileSeriesFeature or a Profile feature in the case of a single selection'''
44           
45    #set self.domain:
46    self.getDomain()     
47   
48    #if request doesn't match domain points find nearest neighbours
49    kwargs=csml.API.genSubset.checkNeighbours(self.domain, self.gridnames, **kwargs)
50    #get the CRS from a  the  catalogue
51    cat=csml.csmllibs.csmlcrs.CRSCatalogue()
52    crs=cat.getCRS(self.value.profileSeriesDomain.srsName, labels = self.value.profileSeriesDomain.axisLabels) 
53   
54    #non-feature specific setup code, mainly handles the time dimension/calendar
55    pathToSubsetNetCDF, kwargs, timeAxis, timeName, caltype, times=csml.API.genSubset.genericSubset(self, csmlpath, ncpath, self.domain, kwargs)
56     
57     
58    ##Get names of variables in file and relate them to the subset selection
59    selection={}
60   
61   
62    for gridOrd in self.value.profileSeriesDomain.coordTransformTable.gridOrdinates:
63        try:
64            selection[gridOrd.gridAxesSpanned.CONTENT]=kwargs[gridOrd.coordAxisLabel.CONTENT]
65        except KeyError:
66            allValues=tuple(self.domain[gridOrd.coordAxisLabel.CONTENT])
67    strTimes, axisorder, units, fulldata, fillvalue =csml.API.genSubset.getTheData(self, selection, times, timeName)
68    return pathToSubsetNetCDF, crs, timeName, times, strTimes, caltype, axisorder,units, fulldata, fillvalue, kwargs
69           
70           
71def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
72    #perform the subset
73    pathToSubsetNetCDF, crs, timeName, times, strTimes,  caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(csmlpath, ncpath,**kwargs) 
74   
75    try:
76        lat=crs.axes[crs.latAxis]
77    except:
78        lat='latitude'
79    try:
80        lon=crs.axes[crs.lonAxis]
81    except:
82        lon='longitude'
83    time=crs.axes[crs.timeAxis]
84   
85    for axis in axisorder:
86        if axis not in [time, lat, lon]:
87            #this should be the 'profile' axis
88            if len(self.domain[axis]) ==1:
89                prof=self.domain[axis][0]
90            else:
91                prof=self.domain[axis]
92           
93            profName=axis
94   
95   
96    #get the totalArraySize
97    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
98
99    #Okay, got the data now. Need to write CSML feature and NetCDF files.
100    #Writing out the CSML feature
101    # define domain/coverage  to use in 'value' attribute   
102   
103    newdomain=csml.parser.csString(prof)
104   
105    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
106    descid=csml.csmllibs.csmlextra.getRandomID()
107    descriptor=csml.parser.NetCDFExtract(id=descid,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
108    rs=csml.parser.RangeSet()
109    va=csml.parser.ValueArray()
110    vc=csml.parser.MeasureOrNullList()
111    vc.href='#%s'%descid
112    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
113    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
114    vc.show='embed'
115    vc.insertedExtract=descriptor
116    try:
117        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
118    except:
119        vc.uom = 'unknown'  #TODO,
120   
121    va.valueComponent=vc
122    va.id=csml.csmllibs.csmlextra.getRandomID()
123    rs.valueArray=va
124   
125
126   
127   
128   
129    #profileseries coverage
130    cvg=csml.parser.ProfileSeriesCoverage()
131    cvg.rangeSet=rs
132    cvg.profileSeriesDomain=newdomain   
133   
134    #parameter, as before subsetting.
135    param = self.parameter
136       
137    #create 'location' attribute:
138    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
139   
140    #create 'time' attribute
141    tName=crs.axes[crs.timeAxis]
142    try:
143        t=kwargs[tName]
144    except:
145        t=csml.parser.csString('unknown')
146               
147    #create a stand alone profile feature containing this coverage
148    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
149    subsettedFeature=csmlWrap.createProfileFeature(value=cvg,parameter=param,location=loc, time=t, featureID=self.id,description=self.description)
150 
151    ### write netcdf using NCWriter class (wraps cdms) ###
152    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
153    axislist=[]
154    for a in axisorder:
155        if self.gridnames.has_key(a):
156            axislist.append(self.gridnames[a])
157        else:
158            axislist.append(a)
159    ords=None 
160    #need to pass in all dimensions except time as the kwargs..
161    otherdims={}
162    otherdims[profName]=prof
163    otherdims['latitude']=float(loc.CONTENT.split()[0])
164    otherdims['longitude']=float(loc.CONTENT.split()[1])
165    nc.genWriteVar(descid,ords, times,  caltype, axislist, units, fulldata, fillvalue, **otherdims)
166    nc.closeFinishedFile()
167    print 'NetCDF file written to %s'%pathToSubsetNetCDF
168    return subsettedFeature, pathToSubsetNetCDF,descriptor
169
170def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
171    #perform the subset
172    pathToSubsetNetCDF, crs, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(csmlpath, ncpath,**kwargs) 
173   
174    (time, lat, lon)=(crs.axes[crs.timeAxis],crs.axes[crs.latAxis], crs.axes[crs.lonAxis])
175    print axisorder
176    for axis in axisorder:
177        if axis not in [time, lat, lon]:
178            #another axis
179            if len(self.domain[axis]) ==1:
180                extraAxis=self.domain[axis][0]
181            else:
182                extraAxis=self.domain[axis]
183            extraName=axis
184   
185    newdomain=csml.parser.TimeSeries()
186    newdomain.timePositionList=csml.parser.csString(csml.csmllibs.csmlextra.cleanString(str(times)))
187   
188    rangeSet=csml.parser.RangeSet()
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.PointSeriesCoverage()
193    cvg.rangeSet=rangeSet
194    cvg.pointSeriesDomain=newdomain   
195   
196    #parameter, as before subsetting.
197    param = self.parameter
198       
199    #create 'location' attribute:
200    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
201   
202               
203    #create a stand alone point series feature containing this coverage
204    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
205    subsettedFeature=csmlWrap.createPointSeriesFeature(value=cvg,parameter=param,location=loc, featureID=self.id,description=self.description)
206 
207    ### write netcdf using NCWriter class (wraps cdms) ###
208    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
209    axislist=[]
210    for a in axisorder:
211        if self.gridnames.has_key(a):
212            axislist.append(self.gridnames[a])
213        else:
214            axislist.append(a)
215    ords=None
216    #need to pass in all dimensions except time as the kwargs..
217    otherdims={}
218    otherdims[extraName]=extraAxis
219    otherdims['latitude']=float(loc.CONTENT.split()[0])
220    otherdims['longitude']=float(loc.CONTENT.split()[1])
221   
222   
223    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, **otherdims)
224    nc.closeFinishedFile()
225    print 'NetCDF file written to %s'%pathToSubsetNetCDF
226    return subsettedFeature, pathToSubsetNetCDF
227
Note: See TracBrowser for help on using the repository browser.