source: TI02-CSML/trunk/parser/API/ops_GridSeriesFeature.py @ 1042

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

subsetToGridSeries part working

Line 
1''' ops_GridSeriesFeature  contains operations for GridSeriesFeatures'''
2from API import *
3
4def testmethod(self):
5    print 'testmethod for gridseries feature'
6    return 'testmethod - gridseries'
7
8def getAllowedSubsettings(self):
9    return ['subsetToGridSeries']
10
11def getDomainReference(self):
12    #Inspects a time position list for the domain reference.
13    #TODO, does not handle a file extract in place of a list.
14    if isinstance(self.domain.domainReference,Parser.TimePositionList):
15        time = {}
16        time['t'] = self.domain.domainReference.timePositions
17        domainref  = time
18    return domainref
19   
20def getDomainComplement(self):
21    #This will return a list containing one or more ordinates:
22    #currently in form [Name, values]
23    #assumes ordinate.axisValues is a file extract
24    #TODO axisValues may be inline -see also domainReference for similar problem
25    domaincomp ={}
26    dc = self.domain.domainComplement
27    #dc should be a grid!
28    if isinstance(dc, Parser.Grid):
29        for ordinate in dc.ordinates:
30            domaincomp[ordinate.definesAxis]=ordinate.axisValues.getData()
31    return domaincomp
32
33def getDomain(self):
34    #returns both the domain reference axes and domain compliment axes in a single domain dictionary
35    #axes are in no particular order
36    domain = {}
37    dr=getDomainReference(self)
38    dc=getDomainComplement(self)
39    for key in dc.keys():
40        domain[key]=dc[key]
41    for key in dr.keys():
42        domain[key]=dr[key]
43    return domain
44   
45
46def subsetToGridSeries(self, timeSubset,  **kwargs):
47    pathToSubsetCSML = 'temp.xml'
48    pathToSubsetNetCDF='temp.nc'
49    domainref = getDomainReference(self) 
50    self.times=timeSubset
51    self.files=[]
52    strTimes=''
53    fulldata=None
54    for time in self.times:
55        listPosition=domainref['t'].split().index(time)
56        strTimes= strTimes + ' ' + time
57        for comp in self.rangeSet.aggregatedArray.component:
58            #comp should be a file extract
59            #var = comp.variableName
60            #f=CSMLAnyFile(comp.fileName.split()[listPosition])
61#TODO - get this bit working properly:
62            data=comp.getData(fileposition=listPosition, **kwargs)
63            self.files.append(comp.fileName.split()[listPosition])
64            if fulldata is None:
65                fulldata = data.tolist()
66            else:
67                for item in data.tolist():
68                    fulldata.append(item)
69   
70    ### create csml document####
71    domain=GridSeriesDomain()
72    domain.domainReference=TimePositionList(timePositions=strTimes) 
73    grid=Grid()
74    dc = self.__getDomainComplement()
75    ordinates= []
76    i=0
77    valueStore=[]  # use the values again later to generate netcdf
78    for key in dc.keys():
79        i=i+1
80        god=GridOrdinateDescription()
81        god.gridAxesSpanned='dim%s'%i
82        god.sequenceRule='+x+y+z'
83        god.definesAxis=key
84        straxisValues=''
85        if key in kwargs:
86            for val in dc[key]:
87                if val >= kwargs[key][0]:
88                    if val <= kwargs[key] [1]:
89                        straxisValues=straxisValues+ str(val) + ', '
90        else: # this dimension has not been subsetted
91            for val in dc[key]:
92                straxisValues=straxisValues+ str(val) + ', '
93        god.axisValues=straxisValues[:-2]
94        ordinates.append(god)
95    grid.ordinates=ordinates
96    domain.domainComplement=grid
97    rangeSet=RangeSet()
98    rangeSet.arrayDescriptor=NetCDFExtract(fileName='f',variableName='v',arraySize='as')
99    feat=FeatureBuilder()
100    subsetCSML=feat.makeGridSeries(domain,rangeSet)
101
102    #### write csml document #####
103    output=open(pathToSubsetCSML,'w')
104    output.write(subsetCSML)
105    output.close()
106
107    ### create and write netcdf####
108    ncfile=NetCDFFile(pathToSubsetNetCDF,'w')
109    # create the dimensions       
110    ncfile.createDimension ( 'time', len(timeSubset))
111    time_var = ncfile.createVariable ( 'time', Float, ('time',) )
112    time_var.longname = 'time'
113    floatTimes=[]
114    for time in timeSubset:
115        floatTimes.append(5) # NEED TO CONVERT 'back' from string to standard julian day.. .
116    time_var[:] =floatTimes[:]
117
118    for ordinate in ordinates:
119        ncfile.createDimension(ordinate.definesAxis, len(ordinate.axisValues.split())) 
120        item_var = ncfile.createVariable (ordinate.definesAxis, Float, (ordinate.definesAxis,) )
121        #convert to list
122        vals=[]
123        for val in ordinate.axisValues.split(','):
124            vals.append(float(val))
125        ordinate.axisValues=vals
126        item_var[:]=vals[:]
127        print ordinate.definesAxis
128    #this needs rethinking.
129    if len(ordinates)==3:
130        feature_var = ncfile.createVariable (self.parsedFeature.id, Float, ('time',ordinates[1].definesAxis,ordinates[0].definesAxis,ordinates[2].definesAxis))
131    elif len(grid.ordinates)==2:
132        feature_var = ncfile.createVariable (self.parsedFeature.id, Float, ('time',ordinates[1].definesAxis,ordinates[0].definesAxis))
133    print shape(feature_var)
134    print shape(fulldata)
135    feature_var[:]=fulldata[:]
136    ncfile.close()
137
138    return pathToSubsetCSML, pathToSubsetNetCDF
Note: See TracBrowser for help on using the repository browser.