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

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

more fixes to do with various subsetting options

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