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

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

Fixed problem with relative paths in CSML documents

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