source: TI02-CSML/trunk/csml/API/ops_GridSeriesFeature.py @ 2061

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

lots of changes to do with subsetting

Line 
1''' ops_GridSeriesFeature  contains operations for GridSeriesFeatures'''
2
3import csml.parser
4import csml.csmllibs.csmltime
5import csml.csmllibs.csmldocument
6import csml.API.ops_AbstractFeature
7import csml.csmllibs.netCDFWriter
8import csmlutils
9
10import sys  #remove later
11
12def testmethod(self):
13    #print 'testmethod for gridseries feature'
14    return 'testmethod - gridseries'
15
16def getAllowedSubsettings(self):
17    return ['subsetToGridSeries']  #other operations
18
19def getDomain(self):
20    #returns domain as a dictionary of ordinates {name: [values], ...}
21    self.domain={}
22    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
23        name=gridOrd.coordAxisLabel.CONTENT
24        if hasattr(gridOrd.coordAxisValues, '__insertedExtract'):
25            self.domain[name]=gridOrd.coordAxisValues.__insertedExtract.getData()
26        else:
27            vals=gridOrd.coordAxisValues.coordinateList.CONTENT
28            valList=[]
29            print 'splitting'
30            for val in vals.split(): 
31                valList.append(val)
32                print val
33            self.domain[name]=valList
34    return self.domain
35
36def subsetToGridSeries(self, csmlpath=None, ncpath=None,**kwargs):
37    #pathToSubsetCSML = container.csmlpath
38    if ncpath is not None:
39        pathToSubsetNetCDF=ncpath
40    else:
41        pathToSubsetNetCDF='temp.nc'
42   
43    self.getDomain()
44   
45    #TODO - incoporate the crsCatalogue. into this
46    #deal with longitude requests
47    #if the request is in -ve,+ve eg (-30,30) but the data is in (0,360) need to handle this by changing the args.
48    kwargs=csmlutils.fixLongitude(self.domain,kwargs)
49   
50    #deal with times   
51    #need to find the time axis:
52    cat=csml.csmllibs.csmlcrs.CRSCatalogue()
53    crs=cat.getCRS(self.value.gridSeriesDomain.srsName)
54    #get the position of the time axis in crs/ axis labels
55    timeAxisPos=crs.timeAxis
56    #get the name of the time axis in the crs
57    timeName=crs.axes[timeAxisPos]
58    #get the ordinate with that name and find the original time name for the file.
59    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
60        if gridOrd.coordAxisLabel.CONTENT==timeName:
61            timeAxis = gridOrd.gridAxesSpanned.CONTENT  #only works for regular grids atm
62        else: 
63            print 'crs not supported'
64   
65   
66    #here, timeName is the name given to the time axis by the CRS,
67    #and timeAxis is the name given to the time axis in the file.
68    #currently supporting domain subsetting only by CRS name
69    #(but should be easy to extend later)
70    self.times=kwargs[timeName]
71    self.files=[]
72    strTimes=''
73    fulldata=[]
74   
75    #set the reference system for the time axis
76    calset=False
77    for gridOrd in self.value.gridSeriesDomain.coordTransformTable.gridOrdinates:
78        if gridOrd.coordAxisLabel.CONTENT==timeName:
79            try:
80                caltype=gridOrd.coordAxisValues.frame.split(':',1)[0]
81                calunits=gridOrd.coordAxisValues.frame.split(':',1)[1]
82                csml.csmllibs.csmltime.setcdtimeCalendar(caltype)
83                calset=True
84            except:pass
85    if calset!=True:
86        csml.csmllibs.csmltime.setcdtimeCalendar(csml.csmllibs.csmltime.cdtime.DefaultCalendar)   
87    try:
88        caltype=self.domain.domainReference.frame.split(':',1)[0]
89        calunits=self.domain.domainReference.frame.split(':',1)[1]
90        csml.csmllibs.csmltime.setcdtimeCalendar(caltype)
91    except:
92        csml.csmllibs.csmltime.setcdtimeCalendar(csml.csmllibs.csmltime.cdtime.DefaultCalendar)
93 
94       
95    if len(self.times) == 2:
96        #then this is a range of times (t1, tn)
97        try:
98            tone=csml.API.ops_AbstractFeature.__getCDtime(self.times[0])
99        except:
100            tone=self.times[0]
101        try:
102            ttwo=csml.API.ops_AbstractFeature.__getCDtime(self.times[1])
103        except:
104            ttwo=self.times[1]
105        self.times=[]
106        if hasattr(self, 'domain'):
107            pass
108        else:
109            self.getDomain()
110           
111        for time in self.domain[timeName]:
112            timeok=csml.API.ops_AbstractFeature.__compareTimes(tone,time,ttwo)
113            if timeok ==1:
114                self.times.append(time)
115     #okay up to here!
116
117    if hasattr(self.value.rangeSet, 'aggregatedArray'):
118        #handle aggregatedArray
119        numFiles=len(csmlutils.listify(self.value.rangeSet.aggregatedArray.components)[0].fileName.CONTENT.split())
120        timeToFileRatio=len(self.domain[timeAxis][0].split())/numFiles
121        #to keep track of files that have already been fetched. eg. if multiple times are in a single file only need to get data from that file once...
122        filesFetched=[]
123        #get data:
124        selection={}
125        for kw in kwargs:
126                    if kw != timeAxis:
127                        selection[kw]=kwargs[kw]
128        for time in self.times:
129            listPosition=self.domain[timeAxis][0].split().index(time)
130            strTimes= strTimes + ' ' + time
131            for comp in csmlutils.listify(self.value.rangeSet.aggregatedArray.components): 
132                filePos=(listPosition)/timeToFileRatio
133                if filePos in filesFetched:
134                    continue #already got data from this file, try next time
135                print comp
136                print dir(comp)
137                data=comp.getData(fileposition=filePos, **selection)
138                self.files.append(comp.fileName.CONTENT.split()[filePos])
139                if fulldata ==[]:
140                    fulldata = data.tolist()
141                else:
142                    for item in data.tolist():
143                        fulldata.append(item)
144                filesFetched.append(filePos)
145            axisorder = data.getAxisIds()  #will need later!
146            for comp in csmlutils.listify(self.value.rangeSet.aggregatedArray.components):
147                filePos=(listPosition)/timeToFileRatio
148                if filePos in filesFetched:
149                    continue #already got data from this file, try next time
150                data=comp.getData(fileposition=filePos, **selection)
151                self.files.append(comp.fileName.CONTENT.split()[filePos])
152                if fulldata ==[]:
153                    fulldata = data.tolist()
154                else:
155                    for item in data.tolist():
156                        fulldata.append(item)
157                filesFetched.append(filePos)
158            axisorder = data.getAxisIds()  #will need later!
159
160    elif hasattr(self.value.rangeSet, 'datablock'): #not tested
161        pass
162
163 
164
165    ### define domain and rangeSet to use for feature in csml document####
166    #TODO - rewrite this section for version 2 parser ###
167   
168    #domain=csml.parser.GridSeriesDomain()
169    #domain.domainReference=csml.parser.TimePositionList(timePositions=strTimes)
170    #grid=csml.parser.Grid()
171    ##dc = self.getDomainComplement()
172    ordinates= []
173    i=0
174    valueStore=[]  # use the values again later to generate netcdf
175    arraySize=0
176    totalArraySize=1
177    for key in self.domain.keys():
178        arraySize=0
179        i=i+1
180        god=csml.parser.GridOrdinateDescription()
181        god.gridAxesSpanned='dim%s'%i
182        god.sequenceRule='+x+y+z'
183        god.definesAxis=key
184        straxisValues=''
185        #now deal with each argument:
186   
187        if key in kwargs:
188            if key ==timeName:
189                continue #dealt with time earlier           
190            elif kwargs[key][0] < kwargs[key][1]:   
191                for val in self.domain[key]:
192                    if val is not '':
193                            if float(val) >= kwargs[key][0]:
194                                if float(val) <= kwargs[key] [1]:
195                                    arraySize=arraySize+1
196                                    straxisValues=straxisValues+ str(val) + ', '
197            else:#this if deals with selections such as longitude (330,30) where the lower limit is 'greater' than the upper limit in a mathematical sense.
198                    for val in self.domain[key]:
199                        if val is not '':
200                            if val >= kwargs[key][0]:
201                                arraySize=arraySize+1
202                                straxisValues=straxisValues+ str(val) + ', '
203                    for val in self.domain[key]:
204                        if val is not '':
205                            if val <= kwargs[key] [1]:
206                                arraySize=arraySize+1
207                                straxisValues=straxisValues+ str(val) + ', '
208        else: # this dimension has not been subsetted at all
209            for val in self.domain[key]:
210                if val is not '':
211                    arraySize=arraySize+1
212                    straxisValues=straxisValues+ str(val) + ', '       
213        totalArraySize=totalArraySize*arraySize
214        god.axisValues=straxisValues[:-2]
215        ordinates.append(god)
216    #totalArraySize=totalArraySize*len(self.times)
217    #grid.ordinates=ordinates
218    #domain.domainComplement=grid
219    #rangeSet=csml.parser.RangeSet()
220    #rangeSet.arrayDescriptor=csml.parser.NetCDFExtract(id=self.id,fileName=pathToSubsetNetCDF,variableName=self.id,arraySize=[arraySize])
221
222    #csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
223    #subsettedFeature=csmlWrap.createGridSeriesFeature(domain,rangeSet,datasetID="A",featureID="B",description="C")
224    ##container.appendFeature(subsettedFeature)
225
226    ### write netcdf using NCWriter class (wraps cdms) ###
227    nc=csml.csmllibs.netCDFWriter.NCwriter(pathToSubsetNetCDF)
228    floatTimes=[]
229    for time in self.times:
230        time=csml.API.ops_AbstractFeature.__getCDtime(time).torel(calunits)
231        floatTimes.append(time.value)
232    nc.addAxis('t',floatTimes,isTime=1,units=calunits,calendar=caltype)
233    #USE CRS!   
234    for ordinate in ordinates:
235        lon,lat=None,None
236        if ordinate.definesAxis=='longitude':
237            lon=1
238        if ordinate.definesAxis=='latitude':
239            lat=1
240        #convert to list
241        vals=[]
242        for val in ordinate.axisValues.split(','):
243            vals.append(float(val))
244        nc.addAxis(ordinate.definesAxis,vals,isLon=lon,isLat=lat,units='')#to do, units attribute for CF compliance
245    if len(ordinates)==3:
246        axes=['t',axisorder[1],axisorder[2],axisorder[3]]
247    elif len(ordinates)==2:
248        axes=['t',axisorder[1],axisorder[2]]
249    nc.addVariable(fulldata,self.id, axes,units='') #to do, units attribute for CF compliance
250    nc.closeFinishedFile()
251    return subsettedFeature, pathToSubsetNetCDF
252    #container.attachNetCDFFile(nc)
253    #MUST be supplied with a CSMLContainer object to store the subsetted feature in
254    return subsettedFeature, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.