source: TI02-CSML/trunk/csml/API/ops_PointSeriesFeature.py @ 3271

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

More docstrings

Line 
1''' ops_PointSeriesFeature  contains operations for PointSeriesFeatures. These methods are attached to PointSeriesFeature instances at runtime.'''
2import csml,sys
3import cdms, MV, MA
4
5def testmethod(self):
6    ''' testmethod for gridseries feature'''
7    print 'testmethod for pointSeries feature'
8    return 'testmethod pointSeries'
9
10def getAllowedSubsettings(self):
11    '''get the allowed operations
12    @return:    list of operations'''
13    return ['subsetToPointSeries']
14   
15def getDomain(self):
16    ''' returns domain as a dictionary of ordinates {name: [values], ...} '''
17    self.domain={}
18    valList=[]
19    for val in self.value.pointSeriesDomain.timePositionList.CONTENT.split():
20        valList.append(val)
21    self.domain['time']=valList
22    [lat,lon]=self.location.CONTENT.split()
23    self.domain['longitude']=lon
24    self.domain['latitude']=lat
25
26    return self.domain   
27   
28def getLongitudeAxis(self):
29    ''' get the index of the longitude axis'''
30    return 'longitude' #dummy value not used, subsetting is by time only
31
32def getLatitudeAxis(self):
33    ''' get the index of the latitude axis'''
34    return 'latitude' #dummy value not used,  subsetting is by time only
35
36def getTimeAxis(self):
37    ''' get the index of the time axis'''
38    return 'times'
39   
40def subsetToPointSeries(self, outputdir=None, ncname='pointseries.nc' ,times=None):
41    '''Subset a PointSeriesFeature to a PointSeriesFeature. Performs the subset (note this includes nearest neighbour searching, so may return a different set of kwargs.
42   
43    @param outputdir:    name of directory to write data files to
44    @param ncname:     name of netcdf file to write out
45    @param times:       selection by times
46    @return:     subsettedFeature (PointSeriesFeature instance)  pathToSubsetNetCDF (filepath), descriptor (array descriptor instance)'''
47    if outputdir is not None:
48        self.outputdir=outputdir
49    elif csml.API.csmlContainer.globalContainer.OUTPUTDIR is not None:
50        self.outputdir=csml.API.csmlContainer.globalContainer.OUTPUTDIR
51     
52    if self.outputdir is not None:
53        pathToSubsetNetCDF=self.outputdir + '/' +ncname
54    else: 
55        pathToSubsetNetCDF=ncname
56    if self.outputdir is not None:
57        csml.csmllibs.csmlextra.checkDirExists(self.outputdir)
58 
59    if type(times) is str:
60        selection = tuple(csml.csmllibs.csmlextra.listify(times))
61    else:
62        selection = times 
63    tlist=[]   
64    for val in self.value.pointSeriesDomain.timePositionList.CONTENT.split():
65        tlist.append(val)
66   
67    indices=[]
68    if  len(selection) ==2:       
69        selectedTimes=[]
70        for domaintime in tlist:
71            if selection[0] == domaintime:
72                minIndex=tlist.index(domaintime)
73                selectedTimes.append(domaintime)
74            if domaintime > selection[0]:
75                if domaintime < selection[1]:
76                    selectedTimes.append(domaintime)         
77            if selection[1] == domaintime:
78                maxIndex=tlist.index(domaintime)
79                selectedTimes.append(domaintime)         
80                break   
81                   
82    elif len(selection)==1:   #point only
83        for domaintime in tlist:
84            if selection[0] == domaintime:
85               
86                minIndex=tlist.index(domaintime)
87                maxIndex=minIndex
88                selectedTimes=selection
89                break
90   
91   
92   
93    fileList=[]
94    if hasattr(self.value.rangeSet, 'valueArray'):
95        fextract=self.value.rangeSet.valueArray.valueComponent.insertedExtract.components
96        uom = self.value.rangeSet.valueArray.valueComponent.insertedExtract.uom
97    else:
98        fextract=self.value.rangeSet.arrayDescriptor.components
99        uom = self.value.rangeSet.arrayDescriptor.uom
100    for f in fextract.fileList.fileNames.CONTENT.split():
101        fileList.append(f)
102   
103    data, fillvalue=fextract.getDataFromChunks(minIndex, maxIndex)
104   
105    units=[uom.CONTENT]
106   
107    #Now write out the CSML Feature:
108    #create a PointSeriesCoverage
109    cvg=csml.parser.PointSeriesCoverage()
110    cvg.id=csml.csmllibs.csmlextra.getRandomID()
111   
112    #create a TimeSeriesDomain (appropriate domain for a PointSeriesFeature
113    ptsd=csml.parser.TimeSeries()
114    ptsd.id=csml.csmllibs.csmlextra.getRandomID()
115    #create (and populate) a TimePositionList. Using keyword arguements for conciseness.
116    ptsd.timePositionList=csml.parser.TimePositionList(CONTENT=csml.csmllibs.csmlextra.stringify(selectedTimes))
117       
118    sdid=csml.csmllibs.csmlextra.getRandomID() # for the storage descriptor
119    #create a RangeSet
120    rs=csml.parser.RangeSet()
121    va=csml.parser.ValueArray()
122    vc=csml.parser.MeasureOrNullList()
123    vc.href='#%s'%sdid
124    vc.arcrole="http://ndg.nerc.ac.uk/xlinkUsage/insert#QuantityList"
125    vc.role="http://ndg.nerc.ac.uk/fileFormat/csmlStorageDescriptor"
126    vc.show='embed'
127    try:
128        vc.uom=self.value.rangeSet.valueArray.valueComponent.uom
129    except:
130        vc.uom = 'unknown'  #TODO,
131    va.valueComponent=vc
132    va.id=csml.csmllibs.csmlextra.getRandomID()
133    rs.valueArray=va
134   
135   
136    #Add the domain and rangeSet as attributes of the coverage
137    cvg.pointSeriesDomain=ptsd
138    cvg.rangeSet=rs
139   
140    totalArraySize=10
141    descriptor=csml.parser.NetCDFExtract(id=sdid,fileName=csml.parser.csString(ncname),variableName=self.name,arraySize=csml.parser.csString(totalArraySize))
142
143   
144    #the parameter of the feature is of type Phenomenon, here href creates "xlink:href=..."
145    param=self.parameter
146   
147     
148    #create a stand alone pointseries feature containing this coverage
149    csmlWrap=csml.csmllibs.csmlfeaturewrap.CSMLWrapper()
150    subsettedFeature=csmlWrap.createPointSeriesFeature(value=cvg,parameter=param,location=self.location,featureID=self.id,description=self.description)
151   
152     
153   
154    #Now write out the NetCDF File:   
155    nc=cdms.open(pathToSubsetNetCDF,'w')
156    var=MV.array(data)
157    var.id=self.name.CONTENT
158    var.name=self.name.CONTENT
159    var.units=units[0] # hopefully there is just one unit in this list..
160    setattr(var, 'missing_value' ,fillvalue)
161   
162    floatTimes=[]
163   
164    tOne=csml.csmllibs.csmltime.getCDtime(selection[0])
165    tbase=csml.csmllibs.csmltime.getBaseUnits(tOne)
166    for time in selectedTimes:
167        time=csml.csmllibs.csmltime.getCDtime(time).torel(tbase)
168        floatTimes.append(time.value)
169    timeAx=cdms.createAxis(floatTimes)
170    timeAx.designateTime()
171    timeAx.id='time'
172    timeAx.units=tbase 
173    var.setAxis(0,timeAx)     
174    nc.write(var)
175    nc.close()   
176    print 'NetCDF file written to %s'%pathToSubsetNetCDF
177    return subsettedFeature, pathToSubsetNetCDF, descriptor
178   
179   
180def subsetToPoint(self, outputdir=None, ncname='point.nc',time=None):
181    '''Subset a PointSeriesFeature to a PointFeature. Performs the subset (note this includes nearest neighbour searching, so may return a different set of kwargs.
182       
183    @param outputdir:    name of directory to write data files to
184    @param ncname:     name of netcdf file to write out
185    @param time:       selection by single time
186    @return:     subsettedFeature (PointFeature instance)  pathToSubsetNetCDF (filepath), descriptor (array descriptor instance)'''
187    if outputdir is not None:
188        self.outputdir=outputdir
189    elif csml.API.csmlContainer.globalContainer.OUTPUTDIR is not None:
190        self.outputdir=csml.API.csmlContainer.globalContainer.OUTPUTDIR
191    pseriesFeature, pathToSubsetNetCDF, descriptor=self.subsetToPointSeries(self.outputdir, ncname,time)         
192    #now need to take this point series feature containing one time and rewrite it as a point feature.
193    pointFeature=csml.parser.PointFeature()
194    pointFeature.location=pseriesFeature.location
195    pointFeature.parameter=pseriesFeature.parameter
196    pointFeature.description=pseriesFeature.description
197    cvg=csml.parser.PointCoverage()
198    domain=csml.parser.PointDomain()
199    domain.id=csml.csmllibs.csmlextra.getRandomID()
200    domain.pointMember=csml.parser.csString(pseriesFeature.location.CONTENT)
201    #create (and populate) a TimePositionList. Using keyword arguements for conciseness.
202    cvg.pointDomain=domain
203    pointFeature.value=cvg
204    pointFeature.time=csml.parser.csString(time)
205    return pointFeature, pathToSubsetNetCDF, descriptor
Note: See TracBrowser for help on using the repository browser.