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

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

fixing ID/naming issues and paths

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, **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, self.outputdir,self.ncname, 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, outputdir=None,ncname ='profile.nc',**kwargs):
72    #perform the subset
73    if outputdir is not None:
74        self.outputdir=outputdir
75    elif csml.API.csmlContainer.globalContainer.OUTPUTDIR is not None:
76        self.outputdir=csml.API.csmlContainer.globalContainer.OUTPUTDIR
77    self.ncname=ncname
78    pathToSubsetNetCDF, crs, timeName, times, strTimes,  caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(**kwargs) 
79   
80    try:
81        lat=crs.axes[crs.latAxis]
82    except:
83        lat='latitude'
84    try:
85        lon=crs.axes[crs.lonAxis]
86    except:
87        lon='longitude'
88    time=crs.axes[crs.timeAxis]
89   
90    for axis in axisorder:
91        if axis not in [time, lat, lon]:
92            #this should be the 'profile' axis
93            if len(self.domain[axis]) ==1:
94                prof=self.domain[axis][0]
95            else:
96                prof=self.domain[axis]
97           
98            profName=axis
99   
100   
101    #get the totalArraySize
102    domainSubset, totalArraySize=csml.API.genSubset.subsetDomain(timeName,strTimes,self.domain, **kwargs)
103
104    #Okay, got the data now. Need to write CSML feature and NetCDF files.
105    #Writing out the CSML feature
106    # define domain/coverage  to use in 'value' attribute   
107   
108    newdomain=csml.parser.csString(prof)
109   
110    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
111    descid=csml.csmllibs.csmlextra.getRandomID()
112    descriptor=csml.parser.NetCDFExtract(id=descid,fileName=csml.parser.csString(ncname),variableName=self.name,arraySize=csml.parser.csString(totalArraySize))
113    rs=csml.parser.RangeSet()
114    va=csml.parser.ValueArray()
115    vc=csml.parser.MeasureOrNullList()
116    vc.href='#%s'%descid
117    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
118    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
119    vc.show='embed'
120    vc.insertedExtract=descriptor
121    try:
122        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
123    except:
124        vc.uom = 'unknown'  #TODO,
125   
126    va.valueComponent=vc
127    va.id=csml.csmllibs.csmlextra.getRandomID()
128    rs.valueArray=va
129   
130
131   
132   
133   
134    #profileseries coverage
135    cvg=csml.parser.ProfileSeriesCoverage()
136    cvg.rangeSet=rs
137    cvg.profileSeriesDomain=newdomain   
138   
139    #parameter, as before subsetting.
140    param = self.parameter
141       
142    #create 'location' attribute:
143    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
144   
145    #create 'time' attribute
146    tName=crs.axes[crs.timeAxis]
147    try:
148        t=kwargs[tName]
149    except:
150        t=csml.parser.csString('unknown')
151               
152    #create a stand alone profile feature containing this coverage
153    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
154    subsettedFeature=csmlWrap.createProfileFeature(value=cvg,parameter=param,location=loc, time=t, featureID=self.id,description=self.description)
155 
156    ### write netcdf using NCWriter class (wraps cdms) ###
157    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
158    axislist=[]
159    for a in axisorder:
160        if self.gridnames.has_key(a):
161            axislist.append(self.gridnames[a])
162        else:
163            axislist.append(a)
164    ords=None 
165    #need to pass in all dimensions except time as the kwargs..
166    otherdims={}
167    otherdims[profName]=prof
168    otherdims['latitude']=float(loc.CONTENT.split()[0])
169    otherdims['longitude']=float(loc.CONTENT.split()[1])
170    nc.genWriteVar(self.name.CONTENT,ords, times,  caltype, axislist, units, fulldata, fillvalue, **otherdims)
171    nc.closeFinishedFile()
172    print 'NetCDF file written to %s'%pathToSubsetNetCDF
173    return subsettedFeature, pathToSubsetNetCDF,descriptor
174
175def subsetToPointSeries(self, outputdir=None,  ncname='pointseries.nc',**kwargs):
176    #this operation needs more testing.
177    #perform the subset
178    if outputdir is not None:
179        self.outputdir=outputdir
180    elif csml.API.csmlContainer.globalContainer.OUTPUTDIR is not None:
181        self.outputdir=csml.API.csmlContainer.globalContainer.OUTPUTDIR
182   
183    pathToSubsetNetCDF, crs, timeName, times, strTimes, calunits, caltype, axisorder,units, fulldata, fillvalue, kwargs=self._subsetProfileSeries(**kwargs) 
184   
185    (time, lat, lon)=(crs.axes[crs.timeAxis],crs.axes[crs.latAxis], crs.axes[crs.lonAxis])
186    print axisorder
187    for axis in axisorder:
188        if axis not in [time, lat, lon]:
189            #another axis
190            if len(self.domain[axis]) ==1:
191                extraAxis=self.domain[axis][0]
192            else:
193                extraAxis=self.domain[axis]
194            extraName=axis
195   
196    newdomain=csml.parser.TimeSeries()
197    newdomain.timePositionList=csml.parser.csString(csml.csmllibs.csmlextra.cleanString(str(times)))
198   
199    rangeSet=csml.parser.RangeSet()
200    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=csml.parser.csString(pathToSubsetNetCDF),variableName=csml.parser.csString(self.id),arraySize=csml.parser.csString(totalArraySize))
201   
202    #gridseries coverage
203    cvg=csml.parser.PointSeriesCoverage()
204    cvg.rangeSet=rangeSet
205    cvg.pointSeriesDomain=newdomain   
206   
207    #parameter, as before subsetting.
208    param = self.parameter
209       
210    #create 'location' attribute:
211    loc=self.location  #locataion attribute of profile is same as that of parent profileseries
212   
213               
214    #create a stand alone point series feature containing this coverage
215    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
216    subsettedFeature=csmlWrap.createPointSeriesFeature(value=cvg,parameter=param,location=loc, featureID=self.id,description=self.description)
217 
218    ### write netcdf using NCWriter class (wraps cdms) ###
219    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
220    axislist=[]
221    for a in axisorder:
222        if self.gridnames.has_key(a):
223            axislist.append(self.gridnames[a])
224        else:
225            axislist.append(a)
226    ords=None
227    #need to pass in all dimensions except time as the kwargs..
228    otherdims={}
229    otherdims[extraName]=extraAxis
230    otherdims['latitude']=float(loc.CONTENT.split()[0])
231    otherdims['longitude']=float(loc.CONTENT.split()[1])
232   
233    nc.genWriteVar(self.name.CONTENT,ords, times, calunits, caltype, axislist, units, fulldata, fillvalue, **otherdims)
234    nc.closeFinishedFile()
235    print 'NetCDF file written to %s'%pathToSubsetNetCDF
236    return subsettedFeature, pathToSubsetNetCDF
237
Note: See TracBrowser for help on using the repository browser.