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

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

subsetting to point series working

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) 
53   
54    #non-feature specific setup code, mainly handles the time dimension/calendar
55    pathToSubsetNetCDF, kwargs, timeAxis, timeName,calunits, caltype, times=csml.API.genSubset.genericSubset(self, csmlpath, ncpath, self.domain, kwargs)
56     
57    ##Get names of variables in file and relate them to the subset selection
58    selection={}
59   
60   
61    for gridOrd in self.value.profileSeriesDomain.coordTransformTable.gridOrdinates:
62        try:
63            selection[gridOrd.gridAxesSpanned.CONTENT]=kwargs[gridOrd.coordAxisLabel.CONTENT]
64        except KeyError:
65            allValues=tuple(self.domain[gridOrd.coordAxisLabel.CONTENT])
66    strTimes, axisorder, units, fulldata, fillvalue =csml.API.genSubset.getTheData(self, selection, times, timeName)
67    return pathToSubsetNetCDF, crs, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs
68           
69           
70def subsetToProfile(self, csmlpath=None, ncpath=None,**kwargs):
71    #perform the subset
72    pathToSubsetNetCDF, crs, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(csmlpath, ncpath,**kwargs) 
73   
74    (time, lat, lon)=(crs.axes[crs.timeAxis],crs.axes[crs.latAxis], crs.axes[crs.lonAxis])
75   
76    for axis in axisorder:
77        if axis not in [time, lat, lon]:
78            #this should be the 'profile' axis
79            if len(self.domain[axis]) ==1:
80                prof=self.domain[axis][0]
81            else:
82                prof=self.domain[axis]
83           
84            profName=axis
85   
86   
87    #Okay, got the data now. Need to write CSML feature and NetCDF files.
88    #Writing out the CSML feature
89    # define domain/coverage  to use in 'value' attribute   
90   
91    newdomain=csml.parser.csString(prof)
92   
93    rangeSet=csml.parser.RangeSet()
94    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
95   
96    #gridseries coverage
97    cvg=csml.parser.ProfileSeriesCoverage()
98    cvg.rangeSet=rangeSet
99    cvg.profileSeriesDomain=newdomain   
100   
101    #parameter, as before subsetting.
102    param = self.parameter
103       
104    #create 'location' attribute:
105    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
106   
107    #create 'time' attribute
108    tName=crs.axes[crs.timeAxis]
109    try:
110        t=kwargs[tName]
111    except:
112        t=csml.parser.csString('unknown')
113               
114    #create a stand alone profile feature containing this coverage
115    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
116    subsettedFeature=csmlWrap.createProfileFeature(value=cvg,parameter=param,location=loc, time=t, featureID=self.id,description=self.description)
117 
118    ### write netcdf using NCWriter class (wraps cdms) ###
119    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
120    axislist=[]
121    for a in axisorder:
122        if self.gridnames.has_key(a):
123            axislist.append(self.gridnames[a])
124        else:
125            axislist.append(a)
126    ords=None 
127    #need to pass in all dimensions except time as the kwargs..
128    otherdims={}
129    otherdims[profName]=prof
130    otherdims['latitude']=float(loc.CONTENT.split()[0])
131    otherdims['longitude']=float(loc.CONTENT.split()[1])
132    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, **otherdims)
133    nc.closeFinishedFile()
134    print 'NetCDF file written to %s'%pathToSubsetNetCDF
135    return subsettedFeature, pathToSubsetNetCDF
136
137
138def subsetToPointSeries(self, csmlpath=None, ncpath=None,**kwargs):
139    #perform the subset
140    pathToSubsetNetCDF, crs, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(csmlpath, ncpath,**kwargs) 
141   
142    (time, lat, lon)=(crs.axes[crs.timeAxis],crs.axes[crs.latAxis], crs.axes[crs.lonAxis])
143    print axisorder
144    for axis in axisorder:
145        if axis not in [time, lat, lon]:
146            #another axis
147            if len(self.domain[axis]) ==1:
148                extraAxis=self.domain[axis][0]
149            else:
150                extraAxis=self.domain[axis]
151            extraName=axis
152   
153    newdomain=csml.parser.TimeSeries()
154    newdomain.timePositionList=csml.parser.csString(csml.csmllibs.csmlextra.cleanString(str(times)))
155   
156    rangeSet=csml.parser.RangeSet()
157    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
158   
159    #gridseries coverage
160    cvg=csml.parser.PointSeriesCoverage()
161    cvg.rangeSet=rangeSet
162    cvg.pointSeriesDomain=newdomain   
163   
164    #parameter, as before subsetting.
165    param = self.parameter
166       
167    #create 'location' attribute:
168    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
169   
170               
171    #create a stand alone point series feature containing this coverage
172    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
173    subsettedFeature=csmlWrap.createPointSeriesFeature(value=cvg,parameter=param,location=loc, featureID=self.id,description=self.description)
174 
175    ### write netcdf using NCWriter class (wraps cdms) ###
176    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
177    axislist=[]
178    for a in axisorder:
179        if self.gridnames.has_key(a):
180            axislist.append(self.gridnames[a])
181        else:
182            axislist.append(a)
183    ords=None
184    #need to pass in all dimensions except time as the kwargs..
185    otherdims={}
186    otherdims[extraName]=extraAxis
187    otherdims['latitude']=float(loc.CONTENT.split()[0])
188    otherdims['longitude']=float(loc.CONTENT.split()[1])
189   
190   
191    nc.genWriteVar(self.id,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, **otherdims)
192    nc.closeFinishedFile()
193    print 'NetCDF file written to %s'%pathToSubsetNetCDF
194    return subsettedFeature, pathToSubsetNetCDF
195
Note: See TracBrowser for help on using the repository browser.