source: TI02-CSML/trunk/newparser/csmlio.py @ 864

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI02-CSML/trunk/newparser/csmlio.py@864
Revision 864, 7.1 KB checked in by domlowe, 14 years ago (diff)

csmlio - getDomainComplement,getDomainReference linked up with file extracts

Line 
1#csmlio.py
2#Contains Parser wrapper'functions to enable reading of data
3
4from  Parser import *
5import nappy
6import cdms
7import parser_extra
8from xml.dom.minidom import parseString
9import elementtree.ElementTree as etree
10
11#import the DataInterface module from the Scanner, assumes it is in a sibling directory to the one containing csmlio.py
12#TODO - how best to organise modules...
13import os
14currentPath=os.getcwd()
15parentPath=os.sep.join(currentPath.split(os.sep)[:-1])
16parserPath=parentPath + '/Scanner/csmllibs'
17sys.path.append(parserPath) #append the parser path to sys.path
18try:
19    import csmldataiface
20except:
21    print 'Could not import CSML Data Interface module. Make sure the Parser code is in ../newparser directory on the same level as ../Scanner directory.'
22    sys.exit()
23
24
25class CSMLinterface:
26    #Wrapper class containing methods to read/write from/to CSML
27    #Uses parser.
28    def __init__(self):
29        self.dataset=None
30        self.currentFeature=None
31        self.currentArrayDescriptor = None
32        #this is a fix to the  ElementTree namespace problem that namespaces are usually represented as ns0, ns1, ns2 etc.
33        etree._namespace_map.update({
34        'http://www.opengis.net/om': 'om',  'http://www.opengis.net/gml': 'gml','http://ndg.nerc.ac.uk/csml' : 'csml', 'http://www.w3.org/1999/xlink':'xlink'})
35   
36    def __setFeature(self,featureID):
37        #given a featureID, set the currentFeature if it is not already set
38        #this is used to check the correct feature is always set.   
39            for member in self.dataset.featureCollection.members:
40                if member.id == featureID:
41                    self.currentFeature = member
42
43    def __setArrayDescriptor(self,fileExtractID):
44        #given a fileExtractID, set the currentArrayDescriptor if it is not already set
45        if self.currentArrayDescriptor is None:
46            for arrayDescriptor in self.dataset.arrayDescriptors:
47                if arrayDescriptor.id == fileExtractID:
48                    self.currentArrayDescriptor=arrayDescriptor
49        if self.currentArrayDescriptor.id != fileExtractID:
50            for arrayDescriptor in self.dataset.arrayDescriptors:
51                if arrayDescriptor.id == fileExtractID:
52                    self.currentArrayDescriptor=arrayDescriptor
53
54    def parse(self,csmldoc):
55        #takes incoming csml document and parses it.
56        tree = ElementTree(file=csmldoc)
57        self.dataset=Dataset()
58        self.dataset.fromXML(tree.getroot())
59        self.dataset =parser_extra.ParserPostProcessor(self.dataset).resolveReferences()
60        #self.currentFeature holds a feature object
61        self.currentFeature = None
62       
63    def getDatasetObj(self):
64        #if you want to bypass this wrapper layer, call this method and it will
65        #return a Parser.Dataset object, which you can interrogate...
66        return self.dataset
67
68    def getCSMLasString(self):
69        #returns csml document as a string
70        strCSML=self.dataset.toXML()
71        strCSML= parseString(tostring(strCSML)).toprettyxml()
72        strCSML= parser_extra.removeInlineNS(strCSML)
73        return strCSML
74
75    def getFeatureList(self):
76        #returns a list of feature ids
77        self.featureList = []
78        for member in self.dataset.featureCollection.members:
79             self.featureList.append(member.id)
80        return self.featureList
81       
82    def getFeatureType(self,featureID):
83        self.__setFeature(featureID)
84        print featureID
85        if isinstance(self.currentFeature, PointFeature):
86            featureType = 'PointFeature'
87        elif isinstance(self.currentFeature, PointSeriesFeature):
88            featureType = 'PointSeriesFeature'
89        elif isinstance(self.currentFeature, ProfileFeature):
90            featureType = 'ProfileFeature'
91        elif isinstance(self.currentFeature, ProfileSeriesFeature):
92            featureType = 'ProfileSeriesFeature'
93        elif isinstance(self.currentFeature, GridFeature):
94            featureType = 'GridFeature'
95        elif isinstance(self.currentFeature, GridSeriesFeature):
96            featureType = 'GridSeriesFeature'
97        elif isinstance(self.currentFeature, TrajectoryFeature):
98            featureType = 'TrajectoryFeature'
99        else:
100             featureType = 'Unknown feature'
101        return featureType
102   
103    def getFeatureDescription(self,featureID):
104        #returns gml:description (== long name) of feature
105        #returns empty string if not available
106        self.__setFeature(featureID)
107        if hasattr(self.currentFeature, 'description'):
108            desc = self.currentFeature.description
109        else:
110            desc =""
111        return desc
112       
113    def getFileExtractList(self):
114        fileExtractList=[]
115        for arrayDescriptor in self.dataset.arrayDescriptors:
116            fileExtractList.append(arrayDescriptor.id)
117        return fileExtractList
118   
119    def getData(self, fileExtractID):
120        #getData, given the gml:id of a file extract, returns the (full) data for that extract
121        self.__setArrayDescriptor(fileExtractID)
122        file = self.currentArrayDescriptor.fileName
123        print self.currentArrayDescriptor.arraySize
124        variable = self.currentArrayDescriptor.variableName
125        DI = csmldataiface.DataInterface()
126        DI=DI.getUnknownInterfaceType(file)       
127        DI.openFile(file)
128        DI.setAxis(variable)
129        fulldata = DI.getDataForAxis()
130        DI.closeFile()
131        return fulldata
132       
133   
134    def getDomainReference(self, featureID):
135        #This will return a list containing one or more ordinates:
136        #[Name, values, units(optional)]
137        self.__setFeature(featureID)
138        domainref=[]
139        #domainReference could be one of:
140        #Trajectory
141        #OrientedTrajectory
142        #TimePositionList
143        if isinstance(self.currentFeature.domain.domainReference,TimePositionList):
144            time = []
145            time.append('Time')
146            time.append(self.currentFeature.domain.domainReference.timePositions)
147            domainref.append(time)
148        #Position
149        #OrientedPosition
150        #TimeInstant
151        return domainref
152   
153    def getDomainComplement(self, featureID):
154        #This will return a list containing one or more ordinates:
155        #[Name, values, units(optional)]
156        domaincomp =[]
157        self.__setFeature(featureID)
158        dc = self.currentFeature.domain.domainComplement
159       
160        #domainComplement could be one of:
161        #Null
162        #DirectPositionList
163        #Grid
164        if isinstance(dc, Grid):
165            for ordinate in dc.ordinates:
166                newaxis = []
167                newaxis.append(ordinate.definesAxis)
168                data = self.getData(ordinate.axisValues.id) # axisValues has already been resolved to the fileExtract so the gml:id can be passed straight to getData()
169                newaxis.append(data)
170                domaincomp.append(newaxis)
171        return domaincomp
172   
173    def getDomain(self, featureID):
174        #returns both the domain reference axes and domain compliment axes in a single domain
175        domain = []
176        domain.append(self.getDomainReference(featureID))
177        domain.append(self.getDomainComplement(featureID))
178        return domain
Note: See TracBrowser for help on using the repository browser.