source: TI02-CSML/trunk/csml/API/genSubset.py @ 2282

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

resolved problem with mismatched axis/grid names

Line 
1'''#getSubset.py contains generic subsetting code that can be reused for multiple features
2Dominic Lowe, CCLRC, 31/01/2007'''
3
4import csml
5import csmlutils
6import sys
7import Numeric
8
9def checkNeighbours(domain, gridnames, **kwargs):
10    #for any non-range requests, get nearest neighbour
11    #e.g if 'latitude': (11) requested, latitude=12 may be the nearest value
12     
13    for key in kwargs:
14    #need to skip time axis
15        #handle single values
16        if type(kwargs[key]) is not tuple:
17            if type(domain[key]) is not list:
18                axeslist=domain[key].tolist()
19            else:
20                axeslist = domain[key]
21            nearestNeighbour=csml.API.csmlutils.nudgeSingleValuesToAxisValues(kwargs[key],axeslist)
22            if nearestNeighbour is not None:
23                kwargs[key]=nearestNeighbour   
24        else:
25            #handle ranges
26            tmpkey=[]
27            for val in kwargs[key]:
28                nearestNeighbour=csml.API.csmlutils.nudgeSingleValuesToAxisValues(val, domain[key])
29                if nearestNeighbour is not None:
30                    tmpkey.append(nearestNeighbour)   
31                kwargs[key]=tuple(tmpkey)
32    return kwargs
33
34def subsetDomain(timeaxis,times, domain,**kwargs):
35    '''takes the domain and returns a subset according to the keyword selection criteria
36    time = name of time dimension
37    times = string of times
38    '''   
39    strTimes=times
40    subsetDomain={}
41    totalArraySize=1
42    for key in domain.keys():
43        straxisValues=''
44        if key in kwargs:
45            if key ==timeaxis:
46                straxisValues=strTimes
47                arraySize=len(strTimes.split())
48            elif type(kwargs[key]) is not tuple:
49                #only one value not a range
50                straxisValues=str(kwargs[key]) 
51            elif kwargs[key][0] < kwargs[key][1]:   
52                for val in domain[key]:
53                      if val is not '':
54                            if float(val) >= kwargs[key][0]:
55                                if float(val) <= kwargs[key] [1]:
56                                    straxisValues=straxisValues+ str(val) + ','
57                straxisValues=straxisValues[:-1]
58            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.
59                    for val in domain[key]:
60                        if val is not '':
61                            if val >= kwargs[key][0]:
62                                straxisValues=straxisValues+ str(val) + ','
63                    for val in domain[key]:
64                        if val is not '':
65                            if val <= kwargs[key] [1]:
66                                straxisValues=straxisValues+ str(val) + ','
67                    straxisValues=straxisValues[:-1]                                             
68        else: # this dimension has not been subsetted at all - CHECK  THIS
69            for val in domain[key]:
70                if val is not '':
71                    straxisValues=straxisValues+ str(val) + ','       
72            straxisValues=straxisValues[:-1]                       
73                                           
74        subsetDomain[key]=straxisValues
75        if key != timeaxis:
76            arraySize=len(subsetDomain[key].split(','))
77        else:
78            arraySize=len(subsetDomain[key].split())
79        totalArraySize = totalArraySize * arraySize
80    return subsetDomain, totalArraySize
81   
82def _setCalendar(feature, timeName, ords):
83    '''sets the cdtime calendar needed for conversion from CSML to NetCDF'''
84    calset=False
85    for gridOrd in ords:
86        if gridOrd.coordAxisLabel.CONTENT==timeName:
87            try:
88                caltype=gridOrd.coordAxisValues.frame.split(':',1)[0]
89                calunits=gridOrd.coordAxisValues.frame.split(':',1)[1]
90                csml.csmllibs.csmltime.setcdtimeCalendar(caltype)
91                calset=True
92            except:pass
93    if calset!=True:
94        csml.csmllibs.csmltime.setcdtimeCalendar(csml.csmllibs.csmltime.cdtime.DefaultCalendar)   
95    try:
96        caltype=gridOrd.coordAxisValues.frame.split(':',1)[0]
97        calunits=gridOrd.coordAxisValues.frame.split(':',1)[1]
98        csml.csmllibs.csmltime.setcdtimeCalendar(caltype)
99    except:
100        csml.csmllibs.csmltime.setcdtimeCalendar(csml.csmllibs.csmltime.cdtime.DefaultCalendar)
101    return calunits, caltype
102
103
104def _getTimes(timeSelection, timeName, domain):
105    #currently supporting domain subsetting only by CRS name
106    #(but should be easy to extend later)
107    if type(timeSelection) is str:
108        times=(timeSelection,)
109    else:
110        times=timeSelection
111   
112    if len(times)==0:
113        #no time specified, select all.
114        times= domain[timeName]
115    tone=csml.csmllibs.csmltime.getCDtime(times[0])
116    if len(times) == 2:
117        #then this is a range of times (t1, tn), and not a list
118        try:
119            tone=csml.csmllibs.csmltime.getCDtime(times[0])
120        except:
121            tone=times[0]
122        try:
123            ttwo=csml.csmllibs.csmltime.getCDtime(times[1])
124        except:
125            ttwo=times[1]
126        times=[]         
127        for time in domain[timeName]:
128            timeok=csml.csmllibs.csmltime.compareTimes(tone,time,ttwo)
129            if timeok ==1:
130                times.append(time)
131    return times
132
133def _getTimeToFileRatio(feature,domain, timeName):
134    if hasattr(feature.value.rangeSet, 'valueArray'):
135        if hasattr(feature.value.rangeSet.valueArray.valueComponent.quantityList, '__insertedExtract'):
136            numFiles= len( csmlutils.listify(feature.value.rangeSet.valueArray.valueComponent.quantityList.__insertedExtract.components)[0].fileList.fileNames.CONTENT.split())
137            return len(domain[timeName])/numFiles
138
139def getCoordTransformTable(domainSubset, crs):
140    cTT=csml.parser.GridCoordinatesTable()
141    ords =[]
142    for key in domainSubset.keys():
143        go=csml.parser.GridOrdinateDescription()
144        go.coordAxisLabel=csml.parser.csString(key)
145        go.gridAxesSpanned=csml.parser.csString(key)
146        go.coordAxisValues = csml.parser.SpatialOrTemporalPositionList()
147        if key==crs.axes[crs.timeAxis]:
148            go.coordAxisValues.timePositionList=csml.parser.csString(domainSubset[key]) #self.domain.key placeholder
149        else:
150            go.coordAxisValues.coordinateList=csml.parser.csString(domainSubset[key]) #self.domain.key placeholder
151        ords.append(go) #go needs a few more properties setting
152    cTT.gridOrdinates=ords
153    return cTT
154
155
156
157def getTheData(feature, selection, times,timeName):
158    print selection
159    print times
160    print timeName
161   
162    #SOME OF THIS SHOULD PROBABLY BE IN THE DATA IO LAYER
163    domain = feature.domain
164    value=feature.value
165    files=[]
166    strTimes=''
167    fulldata=None
168    #get the ratio of times to files
169    timeToFileRatio = _getTimeToFileRatio(feature, domain, timeName)
170           
171    #list 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...
172    filesFetched=[]
173    for time in times:
174        listPosition=domain[timeName].index(time)
175        strTimes= strTimes + ' ' + time
176        for comp in csmlutils.listify(value.rangeSet.valueArray.valueComponent.quantityList.__insertedExtract.components): 
177            filePos=int(float(listPosition)/timeToFileRatio)
178            if filePos in filesFetched:
179                continue #already got data from this file, try next time         
180            data, fillvalue, axisorder, units=comp.getData(fileposition=filePos, **selection)
181            files.append(comp.fileList.fileNames.CONTENT[filePos]) #TODO, get the right file name
182            if fulldata is None:
183                fulldata=data
184            else:
185                newfulldata=Numeric.concatenate([fulldata,data], axis=0)   
186                fulldata=newfulldata
187            filesFetched.append(filePos)
188    units.append(value.rangeSet.valueArray.valueComponent.quantityList.uom) # final unit is that of the
189    return strTimes, axisorder, units, fulldata, fillvalue
190
191def genericSubset(feature, csmlpath, ncpath, domain, kwargs):
192    if ncpath is not None:
193        pathToSubsetNetCDF=ncpath
194    else:
195        pathToSubsetNetCDF='temp.nc'
196   
197    #deal with longitude requests
198    #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.
199    kwargs=csmlutils.fixLongitude(domain,kwargs)
200       
201    #get the name of the time axis in the coordinate reference system
202    cat=csml.csmllibs.csmlcrs.CRSCatalogue()
203    if type(feature) == csml.parser.GridSeriesFeature:
204        crs=cat.getCRS(feature.value.gridSeriesDomain.srsName)
205        gridordinates = feature.value.gridSeriesDomain.coordTransformTable.gridOrdinates
206    elif type(feature) == csml.parser.ProfileSeriesFeature:
207        crs=cat.getCRS(feature.value.profileSeriesDomain.srsName)
208        gridordinates = feature.value.profileSeriesDomain.coordTransformTable.gridOrdinates
209    timeName=crs.axes[crs.timeAxis]
210    #Find the original time name (timeAxis) for the file.
211    for gridOrd in gridordinates:
212        if gridOrd.coordAxisLabel.CONTENT==timeName:
213            timeAxis = gridOrd.gridAxesSpanned.CONTENT  #only works for regular grids atm
214            break
215    #set the reference system for the time axis
216    calunits, caltype=_setCalendar(feature, timeName, gridordinates)
217   
218    try:
219        timeSelection=kwargs[timeName]
220    except KeyError:
221        timeSelection=[]
222   
223    times=_getTimes(timeSelection, timeName,domain)   
224    return pathToSubsetNetCDF, kwargs, timeAxis,timeName, calunits, caltype, times
Note: See TracBrowser for help on using the repository browser.