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

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

second attempt at fixing longitude bug

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