root/Python/trunk/csml/parser.py

Subversion URL: http://proj.badc.rl.ac.uk/svn/csml/Python/trunk/csml/parser.py
Revision 4315, 61.0 kB (checked in by domlowe, 13 months ago)

modifying Xlink attributes inline with ogc proposal

Line 
1#import cElementTree as ET
2#import elementtree.ElementTree as etree
3try: #python 2.5
4    from xml.etree import ElementTree as etree
5except ImportError:
6    try:
7        # if you've installed it yourself it comes this way
8        import ElementTree as etree
9    except ImportError:
10        # if you've egged it this is the way it comes
11        from elementtree import ElementTree as etree
12
13try: #python 2.5
14    from xml.etree import cElementTree as ET
15except ImportError:
16    try:
17        # if you've installed it yourself it comes this way
18        import cElementTree as ET
19    except ImportError:
20        # if you've egged it this is the way it comes
21        from celementtree import cElementTree as ET
22
23import sys, traceback
24import csml
25import re
26'''CSML v2 Parser ''' 
27
28etree._namespace_map.update({'http://www.opengis.net/om': 'om', 'http://www.opengis.net/swe': 'swe',  'http://www.opengis.net/gml': 'gml','http://ndg.nerc.ac.uk/csml' : 'csml', 'http://www.w3.org/1999/xlink':'xlink'})
29
30nsCSML = 'http://ndg.nerc.ac.uk/csml'
31nsGML = 'http://www.opengis.net/gml'
32nsOM = 'http://www.opengis.net/om'
33nsXLINK = 'http://www.w3.org/1999/xlink'
34nsXML = 'http://ndg.nerc.ac.uk/csml'
35nsMOLES='http://ndg.nerc.ac.uk/moles'
36nsSWE='http://www.opengis.net/swe'
37
38MAINATTRIBUTELIST=[]
39
40def CSML(tag):
41    return "{"+nsCSML+"}"+tag
42
43def GML(tag):
44    return "{"+nsGML+"}"+tag
45
46def SWE(tag):
47    return "{"+nsSWE+"}"+tag
48
49def XLINK(tag):
50    return "{"+nsXLINK+"}"+tag
51
52def MOLES(tag):
53    return "{"+nsMOLES+"}"+tag
54
55def addchildren(obj, dict):
56    ''' merges (adds) dictionary to existing self.CHILDREN dictionary '''
57    dict1 = dict
58    if 'CHILDREN' in obj.__dict__:
59      dict2=obj.CHILDREN
60    else:
61      dict2={}
62    dict3={}
63    for item in dict1:
64        dict3[item] =dict1[item]
65    for item in dict2:
66        dict3[item] =dict2[item]
67    obj.CHILDREN=dict3
68   
69
70def addatts(obj, atts):
71  ''' merges self.ATTRIBUTES  of inherited classes'''
72  if 'ATTRIBUTES' in obj.__dict__:
73    for att in atts:
74        obj.ATTRIBUTES.append(att)
75        if att not in MAINATTRIBUTELIST:
76            MAINATTRIBUTELIST.append(att)
77  else:
78    obj.ATTRIBUTES=atts
79 
80
81def addelems(obj, elems):
82  ''' merges self.elems of inherited classes'''
83  if 'ELEMORDER' in obj.__dict__:
84    for elem in elems:
85        obj.ELEMORDER.append(elem)
86  else:
87    obj.ELEMORDER=elems
88
89
90#Some variable definitions: these things are often repeated so store in variables.
91FILEFORMATS=[CSML('NetCDFExtract'),CSML('NASAAmesExtract'), CSML('GRIBExtract'),CSML('CDMLExtract'), CSML('RawFileExtract'), CSML('ImageFileExtract'), CSML('AggregatedArray')]
92
93class subAI:
94    ''' This is Alan Iwi's substitute and replace orphan <> and & code '''
95    def __init__(self):
96        self.r1=re.compile('<([^>]*(<|$))')
97        self.r2=re.compile('((^|>)[^<]*)>')
98        self.r3=re.compile('&(?!(amp|lt|gt);)')
99    def sub(self,s):
100        old=''
101        s=self.r3.sub(r'&amp;',s)
102        s=s.replace(';amp',';')
103        while s != old:
104            old=s
105            s=self.r1.sub(r'&lt;\1',s)
106            s=self.r2.sub(r'\1&gt;',s)
107        return s
108
109
110class csElement(object):
111    ''' main csElement class - all other elements inherit from this baseclass 
112    all the from/to XML conversion is done by this class'''
113   
114    def __init__(self, **kwargs):
115        for kw in kwargs:
116            self.__setattr__(kw, kwargs[kw])
117        if not hasattr(self, 'ATTRIBUTES'):
118            self.__dict__['ATTRIBUTES']=[]
119        if not hasattr(self, 'ELEMORDER'):
120            self.__dict__['ELEMORDER']=[]       
121        if not hasattr(self, 'CHILDREN'):
122            self.__dict__['CHILDREN']={}
123        self.cleanup=subAI()
124    #The __setattr__ and __getattribute__ special methods have been overridden.
125    #This is so that attributes can be called by their fully qualified name internally
126    #while being referenced by their short name externally.
127    # so 'id' and {'http://www.opengis.net/gml'}id always have the same value
128    #you can set either of them at any time and the other will be kept in sync.
129       
130    def __setattr__(self, name, value):
131        if CSML(name) in self.__dict__:
132            object.__setattr__(self, CSML(name), value)
133            object.__setattr__(self, name, value)
134        elif GML(name) in self.__dict__:       
135            object.__setattr__(self, GML(name), value)
136            object.__setattr__(self, name, value)
137        elif XLINK(name) in self.__dict__:       
138            object.__setattr__(self, XLINK(name), value)
139            object.__setattr__(self, name, value) 
140        else:
141            if 'ATTRIBUTES' in self.__dict__:
142                if CSML(name) in self.__dict__['ATTRIBUTES']:
143                    object.__setattr__(self, CSML(name), value)
144                    object.__setattr__(self, name, value)
145                elif GML(name) in self.__dict__['ATTRIBUTES']:
146                    object.__setattr__(self, GML(name), value)
147                    object.__setattr__(self, name, value)
148                elif XLINK(name) in self.__dict__['ATTRIBUTES']:
149                    object.__setattr__(self, XLINK(name), value)
150                    object.__setattr__(self, name, value)
151                elif name in self.__dict__['ATTRIBUTES']:
152                    object.__setattr__(self, name, value)
153                    try:
154                        name=name.split('}')[1]
155                    except IndexError:
156                        pass
157                    object.__setattr__(self, name, value)
158                else:
159                    object.__setattr__(self, name, value)
160            else:
161                    object.__setattr__(self, name, value)
162   
163    def __getattribute__(self, name):
164        if name in MAINATTRIBUTELIST:
165            if CSML(name) in object.__dict__:
166                return object.__getattribute__(self,CSML(name))
167            elif GML(name) in object.__dict__:
168                return object.__getattribute__(self,GML(name))
169            elif XLINK(name) in object.__dict__:
170                return object.__getattribute__(self,XLINK(name))
171            else:
172                return object.__getattribute__(self,name) 
173        else:
174            return object.__getattribute__(self,name)
175   
176    def __removeURI(self, qname):
177        try:
178            attname = qname.split('}')[1]
179        except IndexError:
180            attname = qname
181        return attname
182       
183    def _getSubstitutionType(self,tag):
184        return tag.split('}')[1]
185       
186   
187    def _getReverseSubsType(self, typename):
188        return typename
189   
190    def addChildElem(self, childname, childobj):
191        #sometimes you want to add a child element but don't know if there is one already. In which case you want to create a list of child objects.
192        if childname in self.__dict__:
193            currentattribute=getattr(self,childname)
194            if type(getattr(self,childname)) is list:
195                currentattribute.append(childobj)
196            else:
197                newlist=[currentattribute]
198                newlist.append(childobj)
199                setattr(self,childname, newlist)
200        else:
201            setattr(self,childname, childobj)
202
203    def toXML(self, csmlfrag, **kwargs):
204        #process self and convert to XML     
205        if 'CONTENT' in self.__dict__:
206            if self.CONTENT is not None: csmlfrag.text=self.cleanup.sub(self.CONTENT)
207        if 'ATTRIBUTES' in self.__dict__:
208            for item in self.__dict__:
209                if item in self.ATTRIBUTES:                   
210                    csmlfrag.set(item, self.cleanup.sub(str((self.__dict__[item]))))
211    # self.CHILDREN (recursive - calls the toXML method of children
212        for child in self.ELEMORDER:
213            if not self.__dict__.has_key(child):
214                continue
215            appendLater=False
216            parserobjects=[]
217            if type(self.__dict__[child]) is list:
218                for a in self.__dict__[child]:
219                    parserobjects.append(a)
220            else:
221                parserobjects.append(self.__dict__[child])
222            parentfrag=None
223            if len(self.CHILDREN[child])>=3:
224                    ename2=self.CHILDREN[child][2]
225                    parentfrag=ET.Element(ename2)
226            for po in parserobjects:
227                if type(self.CHILDREN[child][0]) is not list:
228                    ename=self.CHILDREN[child][0]
229                else:
230                    ename = self._getReverseSubsType(type(po).__name__)
231                if len(self.CHILDREN[child])==3:
232                    frag=ET.Element(ename)
233                    po.toXML(frag)
234                    parentfrag.append(frag)
235                    appendLater=True
236                elif len(self.CHILDREN[child])>=4:
237                    if self.CHILDREN[child][3]==1:
238                        frag=ET.Element(ename)
239                        po.toXML(frag)
240                        parentfrag.append(frag)
241                        csmlfrag.append(parentfrag)
242                        parentfrag=ET.Element(parentfrag.tag)
243                        appendLater=False
244                else:
245                    frag=ET.Element(ename)
246                    try:
247                        po.toXML(frag)
248                    except:
249                        print 'PARSING ERROR - could not convert %s to XML'%frag
250                        print dir(ename)
251                        raise
252                    csmlfrag.append(frag)
253                    appendLater=True
254
255                if appendLater==True and parentfrag != None:             
256                    csmlfrag.append(parentfrag)   
257
258        return csmlfrag
259       
260    def fromXML(self,csmlfrag):
261        self.elem=csmlfrag
262        # deal with attributes, e.g. gml id's
263        if csmlfrag.text is not None:
264                self.CONTENT = csmlfrag.text
265        for item in csmlfrag.items():
266            if item[0] in self.ATTRIBUTES:
267                setattr(self, item[0], item[1])
268        #self.CHILDREN (recursive - calls the fromXML method of children
269        for frag in csmlfrag[:]:
270            #for each child element
271            #iterate through expected CHILDREN to find match
272            for child in self.CHILDREN:
273                if len(self.CHILDREN[child])>=3:
274                    ename = self.CHILDREN[child][2]
275                    ename2 = self.CHILDREN[child][0]
276                else:
277                    ename = self.CHILDREN[child][0] 
278                    ename2=None
279                #if there are options, then find the name that matches the frag
280                if ename2 is not None:
281                    if frag[:] != []:
282                        for subfrag in frag[:]:
283                            etype=None
284                            if type(ename2) is list:
285                                if subfrag.tag in ename2:
286                                    etype=self._getSubstitutionType(subfrag.tag)
287                            if subfrag.tag==ename2:
288                                etype=self.CHILDREN[child][1]
289                            if etype:
290                                childobj=eval(etype)()
291                                if len(self.CHILDREN[child])>=3:
292                                    if frag[:] != []:
293                                        childobj.fromXML(subfrag)
294                                else:
295                                    childobj.fromXML(frag)
296                                #set this object to be an attribute of the 'parent' (self) object
297                                if child in self.__dict__:
298                                    if type(self.__dict__[child]) is not list:
299                                        tmp=self.__dict__[child]
300                                        setattr(self, child, [tmp]) #convert to list
301                                    self.__dict__[child].append(childobj)
302                                else:
303                                    setattr(self, child, childobj)
304                else:
305                    etype=None
306                    if type(ename) is list:
307                        if frag.tag in ename:
308                            etype=self._getSubstitutionType(frag.tag)
309                    elif frag.tag==ename:
310                        etype=self.CHILDREN[child][1]
311                    if etype:
312                        childobj=eval(etype)()
313                        if len(self.CHILDREN[child])>=3:
314                            if frag[:] != []:
315                                childobj.fromXML(frag[0])
316                        else:
317                            childobj.fromXML(frag)
318                           
319                        #set this object to be an attribute of the 'parent' (self) object
320                        if child in self.__dict__:
321                            if type(self.__dict__[child]) is not list:
322                                tmp=self.__dict__[child]
323                                setattr(self, child, [tmp]) #convert to list
324                            self.__dict__[child].append(childobj)
325                        else:
326                            setattr(self, child, childobj)
327
328               
329   
330class AbstractGML(csElement):
331    def __init__(self, **kwargs):
332        a=[GML('id')]
333        addatts(self,a)
334        elems=['metaDataProperty', 'description','name']
335        addelems(self,elems)
336        children={elems[0]:[GML('metaDataProperty'),'csString'],elems[1]:[GML('description'),'csString'],elems[2]:[GML('name'),'csString']}
337        addchildren(self,children)
338        csElement.__init__(self,**kwargs)
339       
340class AssociationAttributeGroup(csElement):
341    def __init__(self, **kwargs):
342        a =[XLINK('href'),XLINK('role'), XLINK('arcrole'),XLINK('title'), XLINK('show'), XLINK('actuate')] 
343        addatts(self,a)
344        csElement.__init__(self,**kwargs)
345       
346class SRSReferenceGroup(csElement):
347    def __init__(self, **kwargs):
348        a =['srsName','srsDimension'] 
349        addatts(self,a)
350        csElement.__init__(self,**kwargs)
351
352class csString(AssociationAttributeGroup, SRSReferenceGroup, csElement):
353    def __init__(self, text=None,**kwargs):
354        #Needed so it can use xlink
355        addelems(self,[])
356        AssociationAttributeGroup.__init__(self,**kwargs)
357        SRSReferenceGroup.__init__(self,**kwargs)
358        if text != None:
359            if type(text) is not str:
360                text=str(text)
361            self.CONTENT=text
362        children={}
363        addchildren(self,children)
364        csElement.__init__(self,**kwargs)
365               
366class SRSInformationGroup(csElement):
367    def __init__(self, **kwargs):
368        a =['uomLabels','axisLabels']
369        addatts(self,a)
370        csElement.__init__(self,**kwargs)
371       
372class ArrayDescriptor(csElement):
373    def __init__(self,**kwargs):
374        a=['id']
375        addatts(self,a)
376        elems=['arraySize', 'uom', 'numericType','regExpTransform','numericTransform']
377        addelems(self,elems)
378        children={elems[0]:[CSML('arraySize'), 'csString'], elems[1]:[CSML('uom'),'csString'], elems[2]:[CSML('numericType'),'csString'], elems[3]:[CSML('regExpTransform'),'csString'], elems[4]:[CSML('numericTransform'),'csString']}
379        addchildren(self,children)
380        csElement.__init__(self,**kwargs)
381               
382class GridEnvelope(AbstractGML,SRSReferenceGroup, csElement):
383    def __init__(self, **kwargs):
384        SRSReferenceGroup.__init__(self,**kwargs)
385        AbstractGML.__init__(self,**kwargs)
386        elems=['low', 'high']
387        addelems(self,elems)
388        children={elems[0]:[GML('low'), 'csString'],elems[1]:[GML('high'), 'csString']}
389        addchildren(self,children)
390        csElement.__init__(self,**kwargs)
391       
392class Envelope(AbstractGML,SRSReferenceGroup, csElement):
393    def __init__(self, **kwargs):
394        SRSReferenceGroup.__init__(self,**kwargs)
395        AbstractGML.__init__(self,**kwargs)
396        elems=['lowerCorner','upperCorner']
397        addelems(self,elems)
398        children={elems[0]:[GML('lowerCorner'), 'csString'],elems[1]:[GML('upperCorner'), 'csString']}
399        addchildren(self,children)
400        csElement.__init__(self,**kwargs)
401       
402class EnvelopeWithTimePeriod(Envelope):
403    def __init__(self, **kwargs):
404        Envelope.__init__(self,**kwargs)
405        elems=['beginPosition', 'endPosition']
406        addelems(self,elems)
407        children={elems[0]:[GML('beginPosition'), 'csString'], elems[1]:[GML('endPosition'), 'csString']}
408        addchildren(self,children)
409        csElement.__init__(self,**kwargs)
410
411class AbstractFeature(AbstractGML,csElement):
412    def __init__(self, **kwargs):
413        AbstractGML.__init__(self,**kwargs)
414        elems=['boundedBy']
415        addelems(self,elems)
416        #this pattern works but can only accept EnvelopeWithTimePeriod for the boundedBy,
417        #which is probably ok   
418        children={elems[0]:[GML('EnvelopeWithTimePeriod'), 'EnvelopeWithTimePeriod', GML('boundedBy')]}
419        addchildren(self,children)
420        csElement.__init__(self,**kwargs)
421       
422class AbstractFeatureCollection(AbstractFeature,csElement):
423    def __init__(self, **kwargs):
424        AbstractFeature.__init__(self,**kwargs)
425        csElement.__init__(self,**kwargs)
426       
427class DomainSet(AbstractGML,AssociationAttributeGroup,csElement):
428    def __init__(self, **kwargs):
429        AbstractGML.__init__(self,**kwargs)
430        addchildren(self,{})
431        csElement.__init__(self,**kwargs)
432       
433class AggregatedArray(ArrayDescriptor,csElement):
434    def __init__(self, **kwargs):
435        ArrayDescriptor.__init__(self,**kwargs)
436        elems=['aggType', 'aggIndex', 'components']
437        addelems(self,elems)
438        children={elems[0]:[CSML('aggType'),'csString'], elems[1]:[CSML('aggIndex'),'csString'],elems[2]:[FILEFORMATS, 'ArrayDescriptor',CSML('component')]}
439        addchildren(self,children)
440        csElement.__init__(self,**kwargs)
441       
442
443class MeasureOrNullList(AbstractGML,AssociationAttributeGroup, csElement):
444    def __init__(self, **kwargs):
445        AbstractGML.__init__(self,**kwargs)
446        AssociationAttributeGroup.__init__(self,**kwargs)
447        elems=['insertedExtract']
448        addelems(self,elems)
449        #note insertedExtract is used in resolving xlinks and shouldn't be written to directly (except by the code which handles the xlink resolutions)
450        children={elems[0]:[FILEFORMATS,'FileExtract',CSML('insertedExtract')]}
451        addchildren(self,children)
452        a =['uom'] 
453        addatts(self,a)
454        csElement.__init__(self,**kwargs)
455       
456    def toXML(self,csmlfrag,**kwargs):
457        temp=None
458        if hasattr(self, 'insertedExtract'):         
459            temp=self.insertedExtract
460            del self.insertedExtract  #don't want to expose this in XML       
461        csmlfrag=csElement.toXML(self,csmlfrag, **kwargs)
462        if temp is not None:
463            self.insertedExtract=temp
464        return csmlfrag
465       
466       
467class CompositeValue(AbstractGML,csElement):
468    def __init__(self, **kwargs):
469        AbstractGML.__init__(self,**kwargs)
470        elems=['measures']
471        addelems(self,elems)
472        children={elems[0]:[GML('measure'),'csString',GML('valueComponents')]}
473        addchildren(self,children)
474        csElement.__init__(self,**kwargs)
475       
476class DataBlock(AbstractGML,csElement):
477    #THIS IS INCOMPLETE
478    def __init__(self, **kwargs):
479        AbstractGML.__init__(self,**kwargs)
480        elems=['doubleOrNullTupleList','rangeParameters']
481        addelems(self,elems)
482        children={elems[0]:[GML('doubleOrNullTupleList'),'csString'],elems[1]:[GML('CompositeValue'), 'CompositeValue', GML('rangeParameters')]}
483        addchildren(self,children)
484        csElement.__init__(self,**kwargs)
485
486class ValueArray(AbstractGML, csElement):
487    def __init__(self, **kwargs):
488        AbstractGML.__init__(self,**kwargs)
489        elems=['valueComponent']
490        addelems(self,elems)
491        children=children={elems[0]:[GML('QuantityList'), 'MeasureOrNullList', GML('valueComponent')]}
492        addchildren(self,children)
493        csElement.__init__(self,**kwargs)
494       
495    def toXML(self, csmlfrag, **kwargs):
496        csmlfrag=AbstractGML.toXML(self, csmlfrag,**kwargs)
497        #promote XLinks up from QuantityList
498        #this all done at the elementtree level
499       
500        for frag in csmlfrag:
501            if frag.tag ==GML('valueComponent'):
502                try:       
503                    frag.set(XLINK('href'),self.valueComponent.href)                               
504                    for subfrag in frag:   
505                        del subfrag.attrib[XLINK('href')]                                                             
506                except:
507                    pass
508                try:       
509                    frag.set(XLINK('show'),self.valueComponent.show)                               
510                    for subfrag in frag:   
511                        del subfrag.attrib[XLINK('show')]                                                             
512                except:
513                    pass
514                try:       
515                    frag.set(XLINK('role'),self.valueComponent.role)                               
516                    for subfrag in frag:   
517                        del subfrag.attrib[XLINK('role')]                                                             
518                except:
519                    pass
520                try:       
521                    frag.set(XLINK('arcrole'),self.valueComponent.arcrole)                               
522                    for subfrag in frag:   
523                        del subfrag.attrib[XLINK('arcrole')]                                                             
524                except:
525                    pass
526        return csmlfrag
527               
528    def fromXML(self, csmlfrag):   
529        #promote xlinks up a level to the  property element
530        for frag in csmlfrag:
531            if frag.tag == GML('valueComponent'):             
532                for att in ['href', 'show', 'role', 'arcrole']:
533                    try: 
534                        for subfrag in frag[:]:
535                            subfrag.set(XLINK(att),frag.attrib[XLINK(att)])     
536                    except:
537                        pass
538        csElement.fromXML(self, csmlfrag)       
539
540class RangeSet(AbstractGML,AssociationAttributeGroup,csElement):
541    def __init__(self, **kwargs):
542        AbstractGML.__init__(self,**kwargs)
543        AssociationAttributeGroup.__init__(self,**kwargs)
544        elems=['quantityList', 'dataBlock', 'arrayDescriptor', 'valueArray']
545        addelems(self,elems)
546        children={elems[0]:[GML('QuantityList'), 'MeasureOrNullList'],        elems[1]:[GML('DataBlock'),'DataBlock'],elems[2]:[FILEFORMATS, 'ArrayDescriptor'],  elems[3]:[CSML('AggregatedArray'), 'AggregatedArray'],
547        elems[3]:[GML('ValueArray'),'ValueArray']}
548        addchildren(self,children)
549        csElement.__init__(self,**kwargs)
550       
551class MultiPoint(AbstractGML, SRSReferenceGroup,csElement):
552    def __init__(self, **kwargs):
553        AbstractGML.__init__(self,**kwargs)
554        SRSReferenceGroup.__init__(self,**kwargs)
555        elems=['pointMember','pointMembers']
556        addelems(self,elems)
557        children={elems[0]:[GML('pointMember'), 'csString'],elems[1]:[GML('pointMembers'), 'csString']}
558        addchildren(self,children)
559        csElement.__init__(self,**kwargs)
560       
561class CSMLMultiPoint(AbstractGML, SRSReferenceGroup,csElement):
562    def __init__(self, **kwargs):
563        AbstractGML.__init__(self,**kwargs)
564        SRSReferenceGroup.__init__(self,**kwargs)
565        elems=['position']
566        addelems(self,elems)
567        children={elems[0]:[CSML('position'), 'csString']}
568        addchildren(self,children)
569        csElement.__init__(self,**kwargs)
570       
571class Point(AbstractGML,SRSReferenceGroup,csElement):
572    def __init__(self, **kwargs):
573        AbstractGML.__init__(self,**kwargs)
574        SRSReferenceGroup.__init__(self,**kwargs)
575        elems=['pos','coordinates']
576        addelems(self,elems)
577        children={elems[0]:[GML('pos'), 'csString'],elems[1]:[GML('coordinates'), 'csString']}
578        addchildren(self,children)
579        csElement.__init__(self,**kwargs)
580       
581class PointDomain(DomainSet, MultiPoint,csElement):
582    def __init__(self, **kwargs):
583        DomainSet.__init__(self,**kwargs)
584        MultiPoint.__init__(self,**kwargs)
585        children={}
586        addchildren(self,children)
587        csElement.__init__(self,**kwargs)
588       
589class oldProfileDomain(DomainSet, MultiPoint,csElement):
590    def __init__(self, **kwargs):
591        DomainSet.__init__(self,**kwargs)
592        MultiPoint.__init__(self,**kwargs)
593        children={}
594        addchildren(self,children)
595        csElement.__init__(self,**kwargs)
596
597class ProfileDomain(DomainSet, CSMLMultiPoint,csElement):
598    def __init__(self, **kwargs):
599        DomainSet.__init__(self,**kwargs)
600        CSMLMultiPoint.__init__(self,**kwargs)
601        children={}
602        addchildren(self,children)
603        csElement.__init__(self,**kwargs)
604
605class AbstractCoverage(AbstractFeature, csElement):
606    def __init__(self, **kwargs):
607        AbstractFeature.__init__(self,**kwargs)
608        csElement.__init__(self,**kwargs)
609       
610class AbstractDiscreteCoverage(AbstractCoverage, csElement):
611    def __init__(self, **kwargs):
612        AbstractCoverage.__init__(self,**kwargs)
613        addchildren(self,{})
614        csElement.__init__(self,**kwargs)
615       
616class Definition(AbstractGML):
617    def __init__(self, **kwargs):
618        AbstractGML.__init__(self,**kwargs)
619        addchildren(self,{})
620        csElement.__init__(self,**kwargs)
621       
622class Phenomenon(Definition,AssociationAttributeGroup):
623    def __init__(self, **kwargs):
624        Definition.__init__(self,**kwargs)
625        AssociationAttributeGroup.__init__(self,**kwargs)
626        children = {'':[CSML(''), '']}   
627        addchildren(self,children)
628        csElement.__init__(self,**kwargs)
629               
630class SpatialOrTemporalPositionList(AssociationAttributeGroup, AbstractGML,  csElement):
631    def __init__(self, **kwargs):
632        AbstractGML.__init__(self,**kwargs)
633        AssociationAttributeGroup.__init__(self,**kwargs)
634        elems=['coordinateList', 'timePositionList','insertedExtract']
635        addelems(self,elems)
636        children={elems[0]:[CSML('coordinateList'),'csString'], elems[1]:[CSML('timePositionList'),'TimePositionList'],elems[2]:[FILEFORMATS,'FileExtract',CSML('insertedExtract')]}
637        addchildren(self,children)
638        csElement.__init__(self,**kwargs)
639   
640    def toXML(self,csmlfrag,**kwargs):
641        temp=None
642        if hasattr(self, 'insertedExtract'):
643            temp=self.insertedExtract
644            del self.insertedExtract  #don't want to expose this in XML       
645        csmlfrag=csElement.toXML(self,csmlfrag, **kwargs)
646        #This is mandatory even if empty when using xlink               
647        if not hasattr(self, 'timePositionList'):
648            if not hasattr(self, 'coordinateList'):
649                 if csmlfrag.get(XLINK('arcrole')) is not None:
650                    #An extra if statement here  to remain backwards compatible with old xllink format
651                    if len(csmlfrag.get(XLINK('arcrole')).split('#'))==2:       #old version
652                        if csmlfrag.get(XLINK('arcrole')).split('#')[1] == 'timePositionList':
653                            ET.SubElement(csmlfrag, CSML('timePositionList'))
654                        elif csmlfrag.get(XLINK('arcrole')).split('#')[1] =='coordinateList':
655                            ET.SubElement(csmlfrag, CSML('coordinateList'))
656                    else: #new version of xlinx encoding
657                        if csmlfrag.get(XLINK('arcrole')) == 'timePositionList':
658                            ET.SubElement(csmlfrag, CSML('timePositionList'))
659                        elif csmlfrag.get(XLINK('arcrole')) =='coordinateList':
660                            ET.SubElement(csmlfrag, CSML('coordinateList'))
661        if temp !=None:
662            self.insertedExtract=temp
663        return csmlfrag
664
665class GridOrdinateDescription(AbstractGML,csElement):
666    def __init__(self, **kwargs):
667        AbstractGML.__init__(self,**kwargs)
668        elems=['coordAxisLabel', 'coordAxisValues', 'gridAxesSpanned', 'sequenceRule']
669        addelems(self,elems)
670        children={elems[0]:[CSML('coordAxisLabel'), 'csString'], elems[1]:[CSML('SpatialOrTemporalPositionList'),'SpatialOrTemporalPositionList',CSML('coordAxisValues')], elems[2]:[CSML('gridAxesSpanned'), 'csString'], elems[3]:[CSML('sequenceRule'),'SequenceRule']}
671        addchildren(self,children)
672        csElement.__init__(self,**kwargs)
673    def toXML(self, csmlfrag, **kwargs):
674        csmlfrag=AbstractGML.toXML(self, csmlfrag,**kwargs)
675        #promote XLinks up from SpatialOrTemporalPositionList       
676        #this all done at the elementtree level
677       
678        for frag in csmlfrag:
679            if frag.tag ==CSML('coordAxisValues'):
680                try:       
681                    frag.set(XLINK('href'),self.coordAxisValues.href)                               
682                    for subfrag in frag:   
683                        del subfrag.attrib[XLINK('href')]                                                             
684                except:
685                    pass
686                try:       
687                    frag.set(XLINK('show'),self.coordAxisValues.show)                               
688                    for subfrag in frag:   
689                        del subfrag.attrib[XLINK('show')]                                                             
690                except:
691                    pass
692                try:       
693                    frag.set(XLINK('role'),self.coordAxisValues.role)                               
694                    for subfrag in frag:   
695                        del subfrag.attrib[XLINK('role')]                                                             
696                except:
697                    pass
698                try:       
699                    frag.set(XLINK('arcrole'),self.coordAxisValues.arcrole)                               
700                    for subfrag in frag:   
701                        del subfrag.attrib[XLINK('arcrole')]                                                             
702                except:
703                    pass
704             
705
706        return csmlfrag
707   
708    def fromXML(self, csmlfrag):
709        #promote xlinks up a level to the coordAxisValues property element
710        for frag in csmlfrag:
711            if frag.tag == CSML('coordAxisValues'):             
712                for att in ['href', 'show', 'role', 'arcrole']:
713                    try: 
714                        for subfrag in frag[:]:
715                            subfrag.set(XLINK(att),frag.attrib[XLINK(att)])     
716                    except:
717                        pass
718               
719        csElement.fromXML(self, csmlfrag)
720
721           
722       
723class SequenceRule(csElement):
724    def __init__(self, **kwargs):
725        a=['axisOrder']
726        addatts(self,a)
727        children={}
728        addchildren(self,children)
729        csElement.__init__(self,**kwargs)
730       
731class GridPointDescription(AbstractGML,csElement):
732    def __init__(self, **kwargs):
733        AbstractGML.__init__(self,**kwargs)
734        elems=['posList', 'sequenceRule']
735        addelems(self,elems)
736        children={elems[0]:[CSML('posList'),'csString'],elems[1]:[CSML('sequenceRule'),'SequenceRule']}
737        addchildren(self,children)
738        csElement.__init__(self,**kwargs)
739
740class TimePositionList(AbstractGML,csString,csElement):
741    def __init__(self, **kwargs):
742        AbstractGML.__init__(self,**kwargs)
743        csString.__init__(self, **kwargs)
744        elems=[]
745        addelems(self,elems)
746        a=['frame', 'calendarEraName','indeterminatePosition']
747        addatts(self,a)
748        addchildren(self,{})
749        csElement.__init__(self,**kwargs)
750
751class GridCoordinatesTable(AbstractGML,csElement):
752    def __init__(self,**kwargs):
753        '''the additional value '1' in the children dictionary is used to signify that the elements must be nested as:
754        <gml:ordinate>
755            <gml:GridOrdinateDescription>
756        </gml:ordinate>
757        <gml:ordinate>
758            <gml:GridOrdinateDescription>
759        </gml:ordinate>
760       
761        not as:
762        <gml:ordinate>
763            <gml:GridOrdinateDescription>
764            <gml:GridOrdinateDescription>
765        </gml:ordinate> '''
766        AbstractGML.__init__(self,**kwargs)
767        elems=['gridOrdinates' , 'gridPoints']
768        addelems(self,elems)
769        children={elems[0]:[CSML('GridOrdinateDescription'), 'GridOrdinateDescription',CSML('gridOrdinate'),1], elems[1]:[CSML('GridPointDescription'),'GridPointDescription',CSML('gridPoints')]}
770        addchildren(self,children)
771        csElement.__init__(self,**kwargs)
772       
773class Grid(AbstractGML, AssociationAttributeGroup, SRSInformationGroup, SRSReferenceGroup, csElement):
774    def __init__(self, **kwargs):
775        AbstractGML.__init__(self,**kwargs)
776        AssociationAttributeGroup.__init__(self,**kwargs)
777        SRSReferenceGroup.__init__(self,**kwargs)
778        SRSInformationGroup.__init__(self,**kwargs)
779        a=['dimension']
780        addatts(self,a)
781        elems=['limits', 'aLabels','axisName']
782        addelems(self, elems)
783        children = {elems[1]:[CSML('axisLabels'),'csString'],elems[2]:[CSML('axisName'),'csString'], elems[0]:[GML('GridEnvelope'),'GridEnvelope',CSML('limits')]}
784        addchildren(self,children)
785        csElement.__init__(self,**kwargs)
786           
787class ReferenceableGrid(Grid, csElement):
788    def __init__(self, **kwargs):
789        Grid.__init__(self,**kwargs)
790        elems=['coordTransformTable']
791        addelems(self,elems)
792        children={elems[0]:[CSML('GridCoordinatesTable'), 'GridCoordinatesTable', CSML('coordTransformTable')]}
793        addchildren(self,children)
794        csElement.__init__(self,**kwargs)
795
796class ReferenceableGridCoverage(AbstractDiscreteCoverage, csElement):
797    def __init__(self, **kwargs):
798        AbstractDiscreteCoverage.__init__(self,**kwargs)
799        elems=[referenceableGridDomain]
800        addelems(self,elems)
801        children={elems[0]:[CSML('ReferenceableGrid'),'ReferenceableGrid' ,CSML('referenceableGridDomain') ]}
802        addchildren(self,children)
803        csElement.__init__(self,**kwargs)
804       
805class AlternatePointCoverage(AbstractDiscreteCoverage, csElement):
806    def __init__(self, **kwargs):
807        AbstractDiscreteCoverage.__init__(self,**kwargs)
808        elems=['alternatePointDomain','rangeSet','coverageFunction']
809        addelems(self,elems)
810        children={elems[0]:[GML('Point'),'Point', CSML('alternatePointDomain')], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
811        addchildren(self,children)
812        csElement.__init__(self,**kwargs)
813
814class ProfileCoverage(AbstractDiscreteCoverage, csElement):
815    def __init__(self, **kwargs):
816        AbstractDiscreteCoverage.__init__(self,**kwargs)
817        elems=['profileDomain', 'rangeSet' ,'coverageFunction']
818        addelems(self,elems)
819        children={elems[0]:[CSML('ProfileDomain'),'ProfileDomain' ,CSML('profileDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
820        addchildren(self,children)
821        csElement.__init__(self,**kwargs)
822       
823class PointCoverage(AbstractDiscreteCoverage, csElement):
824    def __init__(self, **kwargs):
825        AbstractDiscreteCoverage.__init__(self,**kwargs)
826        elems=['pointDomain','rangeSet', 'coverageFunction']
827        addelems(self,elems)
828        children={elems[0]:[CSML('PointDomain'),'PointDomain' ,CSML('pointDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
829        addchildren(self,children)
830        csElement.__init__(self,**kwargs)
831       
832class TimeSeries(AbstractGML, AssociationAttributeGroup, csElement):
833    def __init__(self, **kwargs):
834        AbstractGML.__init__(self,**kwargs)
835        AssociationAttributeGroup.__init__(self,**kwargs)
836        elems=['timePositionList']
837        addelems(self,elems)
838        children={elems[0]:[CSML('timePositionList'), 'TimePositionList']}
839        addchildren(self,children)
840        csElement.__init__(self,**kwargs)
841
842class PointSeriesCoverage(AbstractDiscreteCoverage, csElement):
843    def __init__(self, **kwargs):
844        AbstractDiscreteCoverage.__init__(self,**kwargs)
845        elems=['pointSeriesDomain','rangeSet','coverageFunction']
846        addelems(self,elems)
847        children={elems[0]:[CSML('TimeSeries'),'TimeSeries' ,CSML('pointSeriesDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
848        addchildren(self,children)
849        csElement.__init__(self,**kwargs)
850       
851           
852    def toXML(self, csmlfrag, **kwargs):
853        csmlfrag=AbstractGML.toXML(self, csmlfrag,**kwargs)
854        #promote XLinks up from SpatialOrTemporalPositionList       
855        #this all done at the elementtree level
856        for frag in csmlfrag:
857            if frag.tag ==CSML('pointSeriesDomain'):
858                try:       
859                    frag.set(XLINK('href'),self.pointSeriesDomain.href)                               
860                    for subfrag in frag:   
861                        del subfrag.attrib[XLINK('href')]                                                             
862                except:
863                    pass
864                try:       
865                    frag.set(XLINK('show'),self.pointSeriesDomain.show)                               
866                    for subfrag in frag:   
867                        del subfrag.attrib[XLINK('show')]                                                             
868                except:
869                    pass
870                try:       
871                    frag.set(XLINK('role'),self.pointSeriesDomain.role)                               
872                    for subfrag in frag:   
873                        del subfrag.attrib[XLINK('role')]                                                             
874                except:
875                    pass
876                try:       
877                    frag.set(XLINK('arcrole'),self.pointSeriesDomain.arcrole)                               
878                    for subfrag in frag:   
879                        del subfrag.attrib[XLINK('arcrole')]                                                             
880                except:
881                    pass
882             
883
884        return csmlfrag
885   
886    def fromXML(self, csmlfrag):
887        #promote xlinks up a level to the pointSeriesDomain element
888        for frag in csmlfrag:
889            if frag.tag == CSML('pointSeriesDomain'):             
890                for att in ['href', 'show', 'role', 'arcrole']:
891                    try: 
892                        for subfrag in frag[:]:
893                            subfrag.set(XLINK(att),frag.attrib[XLINK(att)])     
894                    except:
895                        pass
896        csElement.fromXML(self, csmlfrag)
897       
898class ProfileSeriesDomain(ReferenceableGrid, DomainSet, csElement):
899    def __init__(self, **kwargs):
900        DomainSet.__init__(self,**kwargs)
901        ReferenceableGrid.__init__(self,**kwargs)
902        children={}
903        addchildren(self,children)
904        csElement.__init__(self,**kwargs)
905       
906class ProfileSeriesCoverage(AbstractDiscreteCoverage,csElement):
907    def __init__(self, **kwargs):
908        AbstractDiscreteCoverage.__init__(self,**kwargs)
909        elems=['profileSeriesDomain', 'rangeSet', 'coverageFunction']
910        addelems(self,elems)
911        children={elems[0]:[CSML('ProfileSeriesDomain'),'ProfileSeriesDomain' ,CSML('profileSeriesDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
912        addchildren(self,children)
913        csElement.__init__(self,**kwargs)
914       
915class SectionDomain(ReferenceableGrid, DomainSet, csElement):
916    def __init__(self, **kwargs):
917        DomainSet.__init__(self,**kwargs)
918        ReferenceableGrid.__init__(self,**kwargs)
919        children={}
920        addchildren(self,children)
921        csElement.__init__(self,**kwargs)
922       
923class SectionCoverage(AbstractDiscreteCoverage,csElement):
924    def __init__(self, **kwargs):
925        AbstractDiscreteCoverage.__init__(self,**kwargs)
926        elems=['sectionDomain', 'rangeSet' , 'coverageFunction']
927        addelems(self,elems)
928        children={elems[0]:[CSML('SectionDomain'),'SectionDomain' ,CSML('sectionDomain') ],elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
929        addchildren(self,children)
930        csElement.__init__(self,**kwargs)
931       
932class TrajectoryDomain(ReferenceableGrid, DomainSet, csElement):
933    def __init__(self, **kwargs):
934        DomainSet.__init__(self,**kwargs)
935        ReferenceableGrid.__init__(self,**kwargs)
936        children={}
937        addchildren(self,children)
938        csElement.__init__(self,**kwargs)
939       
940class TrajectoryCoverage(AbstractDiscreteCoverage,csElement):
941    def __init__(self, **kwargs):
942        AbstractDiscreteCoverage.__init__(self,**kwargs)
943        elems=['trajectoryDomain', 'rangeSet', 'coverageFunction']
944        addelems(self,elems)
945        children={elems[0]:[CSML('TrajectoryDomain'),'TrajectoryDomain' ,CSML('trajectoryDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
946        addchildren(self,children)
947        csElement.__init__(self,**kwargs)
948
949class ScanningRadarDomain(ReferenceableGrid, DomainSet, csElement):
950    def __init__(self, **kwargs):
951        DomainSet.__init__(self,**kwargs)
952        ReferenceableGrid.__init__(self,**kwargs)
953        children={}
954        addchildren(self,children)
955        csElement.__init__(self,**kwargs)
956       
957class ScanningRadarCoverage(AbstractDiscreteCoverage,csElement):
958    def __init__(self, **kwargs):
959        AbstractDiscreteCoverage.__init__(self,**kwargs)
960        elems=['scanningRadarDomain', 'rangeSet','coverageFunction']
961        addelems(self,elems)
962        children={elems[0]:[CSML('ScanningRadarDomain'),'ScanningRadarDomain' ,CSML('scanningRadarDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
963        addchildren(self,children)
964        csElement.__init__(self,**kwargs)
965
966
967class GridSeriesDomain(ReferenceableGrid, csElement):
968    def __init__(self, **kwargs):
969        #DomainSet.__init__(self,**kwargs)
970        ReferenceableGrid.__init__(self,**kwargs)
971        children={}
972        addchildren(self,children)
973        csElement.__init__(self,**kwargs)
974
975class GridSeriesCoverage(AbstractDiscreteCoverage,csElement):
976    def __init__(self, **kwargs):
977        elems=['gridSeriesDomain', 'rangeSet', 'coverageFunction']
978        addelems(self,elems)
979        children={elems[0]:[CSML('GridSeriesDomain'),'GridSeriesDomain' ,CSML('gridSeriesDomain') ], elems[1]:[GML('rangeSet'), 'RangeSet'],elems[2]:[GML('coverageFunction'),'csString']}
980        addchildren(self,children)
981        AbstractDiscreteCoverage.__init__(self,**kwargs)
982        csElement.__init__(self,**kwargs)
983
984class AlternatePointFeature(AbstractFeature, csElement):
985    def __init__(self, **kwargs):
986        AbstractFeature.__init__(self,**kwargs)
987        self.featureType='AlternatePointFeature'
988        elems=['location', 'time', 'value','parameter']
989        addelems(self,elems)
990        children={elems[0]:[CSML('location'), 'csString'],elems[1]:[CSML('time'), 'csString'], elems[2]:[CSML('AlternatePointCoverage'), 'AlternatePointCoverage', CSML('value')],elems[3]:[CSML('parameter'), 'Phenomenon']}
991        addchildren(self,children)
992        csElement.__init__(self,**kwargs)
993
994class DirectPositionList(SRSReferenceGroup, csElement):
995    def __init__(self, **kwargs):
996        SRSReferenceGroup.__init__(self,**kwargs)
997        children=[]
998        addchildren(self,children)
999        csElement.__init__(self,**kwargs)
1000       
1001class PointFeature(AbstractFeature, csElement):
1002    def __init__(self, **kwargs):
1003        AbstractFeature.__init__(self,**kwargs)
1004        self.featureType='PointFeature'
1005        elems=['location', 'time', 'value','parameter']
1006        addelems(self,elems)
1007        children={elems[0]:[CSML('location'), 'DirectPositionList'],elems[1]:[CSML('time'), 'csString'], elems[2]:[CSML('PointCoverage'), 'PointCoverage', CSML('value')], elems[3]:[CSML('parameter'), 'Phenomenon']}
1008        addchildren(self,children)
1009        csElement.__init__(self,**kwargs)
1010
1011class PointCollectionFeature(AbstractFeature, csElement):
1012    def __init__(self, **kwargs):
1013        AbstractFeature.__init__(self,**kwargs)
1014        self.featureType='PointCollectionFeature'
1015        elems=['time', 'value', 'parameter']
1016        addelems(self,elems)
1017        children={elems[0]:[CSML('time'), 'csString'], elems[1]:[CSML('MultiPointCoverage'), 'MultiPointCoverage', CSML('value')], elems[2]:[CSML('parameter'), 'Phenomenon']}
1018        addchildren(self,children)
1019        csElement.__init__(self,**kwargs)
1020
1021
1022class PointSeriesFeature(AbstractFeature, csElement):
1023    def __init__(self, **kwargs):
1024        AbstractFeature.__init__(self,**kwargs)
1025        self.featureType='PointSeriesFeature'
1026        elems=['location','value','parameter']
1027        addelems(self,elems)
1028        children={elems[0]:[CSML('location'), 'csString'], elems[1]:[CSML('PointSeriesCoverage'), 'PointSeriesCoverage', CSML('value')], elems[2]:[CSML('parameter'), 'Phenomenon']}
1029        addchildren(self,children)
1030        csElement.__init__(self,**kwargs)
1031
1032
1033class GridFeature(AbstractFeature, csElement):
1034    def __init__(self, **kwargs):
1035        AbstractFeature.__init__(self,**kwargs)
1036        self.featureType='GridFeature'
1037        elems=['time', 'value', 'parameter']
1038        addelems(self,elems)
1039        children={elems[0]:[CSML('time'), 'csString'], elems[1]:[CSML('ReferenceableGridCoverage'), 'ReferenceableGridCoverage', CSML('value')], elems[2]:[CSML('parameter'), 'Phenomenon']}
1040        addchildren(self,children)
1041        csElement.__init__(self,**kwargs)
1042
1043class GridSeriesFeature(AbstractFeature, csElement):
1044    def __init__(self, **kwargs):
1045        AbstractFeature.__init__(self,**kwargs)
1046        self.featureType='GridSeriesFeature'
1047        elems=['value','parameter']
1048        addelems(self,elems)
1049        children={elems[0]:[CSML('GridSeriesCoverage'), 'GridSeriesCoverage', CSML('value')],elems[1]:[CSML('parameter'), 'Phenomenon']}
1050        addchildren(self,children)
1051        csElement.__init__(self,**kwargs)
1052
1053class ProfileFeature(AbstractFeature, csElement):
1054    def __init__(self, **kwargs):
1055        AbstractFeature.__init__(self,**kwargs)
1056        self.featureType='ProfileFeature'
1057        elems=['location', 'time','value', 'parameter']
1058        addelems(self,elems)
1059        children={elems[0]:[CSML('location'), 'csString'],elems[1]:[CSML('time'), 'csString'], elems[2]:[CSML('ProfileCoverage'), 'ProfileCoverage', CSML('value')], elems[3]:[CSML('parameter'), 'Phenomenon']}
1060        addchildren(self,children)
1061        csElement.__init__(self,**kwargs)
1062
1063class ProfileSeriesFeature(AbstractFeature, csElement):
1064    def __init__(self, **kwargs):
1065        AbstractFeature.__init__(self,**kwargs)
1066        self.featureType='ProfileSeriesFeature'
1067        elems=['location', 'value', 'parameter']
1068        addelems(self,elems)
1069        children={elems[0]:[CSML('location'), 'csString'], elems[1]:[CSML('ProfileSeriesCoverage'), 'ProfileSeriesCoverage', CSML('value')], elems[2]:[CSML('parameter'), 'Phenomenon']}
1070        addchildren(self,children)
1071        csElement.__init__(self,**kwargs)
1072
1073class RaggedProfileSeriesFeature(AbstractFeature, csElement):
1074    def __init__(self, **kwargs):
1075        AbstractFeature.__init__(self,**kwargs)
1076        self.featureType='RaggedProfileSeriesFeature'
1077        elems=['location', 'profileLength', 'value', 'parameter']
1078        addelems(self,elems)
1079        children={elems[0]:[CSML('location'), 'csString'], elems[1]:[CSML('profileLength'), 'csString'],elems[2]:[CSML('ProfileSeriesCoverage'), 'ProfileSeriesCoverage', CSML('value')], elems[3]:[CSML('parameter'), 'Phenomenon']}
1080        addchildren(self,children)
1081        csElement.__init__(self,**kwargs)
1082
1083class RaggedSectionFeature(AbstractFeature, csElement):
1084    def __init__(self, **kwargs):
1085        AbstractFeature.__init__(self,**kwargs)
1086        self.featureType='RaggedSectionFeature'
1087        elems=['stationLocations', 'stationTimes', 'profileLength', 'value','parameter']
1088        addelems(self,elems)
1089        children={elems[0]:[CSML('stationLocations'), 'csString'], elems[1]:[CSML('stationTimes'), 'csString'],elems[2]:[CSML('profileLength'),'csString'],elems[3]:[CSML('SectionCoverage'), 'SectionCoverage', CSML('value')], elems[4]:[CSML('parameter'), 'Phenomenon']}
1090        addchildren(self,children)
1091        csElement.__init__(self,**kwargs)
1092
1093class SectionFeature(AbstractFeature, csElement):
1094    def __init__(self, **kwargs):
1095        AbstractFeature.__init__(self,**kwargs)
1096        self.featureType='SectionFeature'
1097        elems=['stationLocations', 'stationTimes','value', 'parameter']
1098        addelems(self,elems)
1099        children={elems[0]:[CSML('stationLocations'), 'csString'], elems[1]:[CSML('stationTimes'), 'TimePositionList'],elems[2]:[CSML('SectionCoverage'), 'SectionCoverage', CSML('value')], elems[3]:[CSML('parameter'), 'Phenomenon']}
1100        addchildren(self,children)
1101        csElement.__init__(self,**kwargs)
1102
1103class ScanningRadarFeature(AbstractFeature, csElement):
1104    def __init__(self, **kwargs):
1105        AbstractFeature.__init__(self,**kwargs)
1106        self.featureType='ScanningRadarFeature'
1107        elems=['elevation','value', 'parameter']
1108        addelems(self,elems)
1109        children={elems[0]:[CSML('elevation'), 'csString'], elems[1]:[CSML('ScanningRadarCoverage'), 'ScanningRadarCoverage', CSML('value')], elems[2]:[CSML('parameter'), 'Phenomenon']}
1110        addchildren(self,children)
1111        csElement.__init__(self,**kwargs)
1112
1113       
1114class SwathFeature(AbstractFeature, csElement):
1115    def __init__(self, **kwargs):
1116        AbstractFeature.__init__(self,**kwargs)
1117        self.featureType='SwathFeature'
1118        elems=['eqCrossLon', 'eqCrossTime', 'value', 'parameter']
1119        addelems(self,elems)
1120        children={elems[0]:[CSML('eqCrossLon'), 'csString'],elems[1]:[CSML('eqCrossTime'), 'csString'], elems[2]:[CSML('ReferenceableGridCoverage'), 'ReferenceableGridCoverage', CSML('value')], elems[3]:[CSML('parameter'), 'Phenomenon']}
1121        addchildren(self,children)
1122        csElement.__init__(self,**kwargs)
1123       
1124class TrajectoryFeature(AbstractFeature, csElement):
1125    def __init__(self, **kwargs):
1126        AbstractFeature.__init__(self,**kwargs)
1127        self.featureType='TrajectoryFeature'
1128        elems=['value', 'parameter']
1129        addelems(self,elems)
1130        children={elems[0]:[CSML('TrajectoryCoverage'), 'TrajectoryCoverage', CSML('value')], elems[1]:[CSML('parameter'), 'Phenomenon']}
1131        addchildren(self,children)
1132        csElement.__init__(self,**kwargs)
1133       
1134class FileList(AssociationAttributeGroup,csElement):
1135    def __init__(self,**kwargs):
1136        AssociationAttributeGroup.__init__(self,**kwargs)       
1137        a=['id']
1138        addatts(self,a)
1139        elems=['fileNames']
1140        addelems(self,elems)
1141        children= {elems[0]:[CSML('fileNames'), 'csString']}
1142        addchildren(self,children)
1143        csElement.__init__(self,**kwargs)
1144       
1145class FileExtract(ArrayDescriptor, csElement):
1146    def __init__(self,**kwargs):
1147        ArrayDescriptor.__init__(self,**kwargs)
1148        elems=['fileName', 'fileList', 'fileListXLINK']
1149        addelems(self,elems)
1150        children= {elems[0]:[CSML('fileName'), 'csString'],  elems[1]:[CSML('FileList'), 'FileList', CSML('fileList')],elems[2]:[CSML('fileList'), 'csString']}
1151        addchildren(self,children)
1152        csElement.__init__(self,**kwargs)
1153   
1154    def fromXML(self,csmlfrag):       
1155        ArrayDescriptor.fromXML(self,csmlfrag)         
1156        if hasattr(self, 'fileListXLINK'):
1157            if hasattr(self, 'fileList'):
1158                del self.fileListXLINK
1159   
1160   
1161class NetCDFExtract(FileExtract, csElement):
1162    def __init__(self,**kwargs):
1163        FileExtract.__init__(self, **kwargs)
1164        elems=['variableName']
1165        addelems(self,elems)
1166        children={elems[0]:[CSML('variableName'), 'csString']}
1167        addchildren(self,children)
1168        csElement.__init__(self,**kwargs)
1169
1170class NASAAmesExtract(FileExtract, csElement):
1171    def __init__(self,**kwargs):
1172        FileExtract.__init__(self, **kwargs)
1173        elems=['variableName', 'index']
1174        addelems(self,elems)
1175        children={elems[0]:[CSML('variableName'), 'csString'],elems[1]:[CSML('index'),'csString']}
1176        addchildren(self,children)
1177        csElement.__init__(self,**kwargs)
1178
1179class RawFileExtract(FileExtract, csElement):
1180
1181   # Note: Unlike the other file extracts, this sets a self.dataInterface
1182   # attribute, which is used by the overridden getData to determine which
1183   # Data Interface is used to read the file. This is necessary because the
1184   # getUnknownDataInterface() method determines which DI to use based on
1185   # filename suffix (raw files could be called anything) or by inspecting
1186   # the file (raw files have no magic numbers or other markers that could
1187   # be used to unequivocally determine the file type).
1188   def __init__(self,**kwargs):
1189      FileExtract.__init__(self, **kwargs)
1190      elems=['endianness', 'fillValue']
1191      addelems(self,elems)
1192      children={elems[0]:[CSML('endianness'), 'csString'],elems[1]:[CSML('fillValue'), 'csString']}
1193      addchildren(self,children)
1194      csElement.__init__(self,**kwargs)
1195      self.dataInterface = csml.csmllibs.csmldataiface.RawFileInterface
1196 
1197class ImageFileExtract(RawFileExtract, csElement):
1198   def __init__(self,**kwargs):
1199      FileExtract.__init__(self, **kwargs)
1200      elems=['fillValue']
1201      addelems(self,elems)
1202      children={elems[0]:[CSML('fillValue'), 'csString']}
1203      addchildren(self,children)
1204      csElement.__init__(self,**kwargs)
1205      self.dataInterface = csml.csmllibs.csmldataiface.ImageFileInterface
1206   
1207
1208class SimpleCondition(csElement): 
1209    '''from moles'''
1210    def __init__(self,**kwargs):
1211        addatts(self, [])
1212        elems= ['dgAttributeAuthority', 'attrauthRole']
1213        addelems(self,elems)
1214        children={elems[0]:[MOLES('dgAttributeAuthority'), 'csString'],elems[1]:[MOLES('attrauthRole'), 'csString']}
1215        addchildren(self,children)
1216        csElement.__init__(self, **kwargs)
1217
1218
1219class ComplexCondition(csElement): 
1220    '''from moles (stub class)'''
1221    def __init__(self,**kwargs):
1222        addatts(self, [])
1223        elems= []
1224        addelems(self,elems)
1225        children={}
1226        addchildren(self,children)
1227        csElement.__init__(self, **kwargs)
1228
1229class DgSecurityCondition(csElement): 
1230    '''from moles'''
1231    def __init__(self,**kwargs):
1232        addatts(self, [])
1233        elems=['effect', 'conditionExplanationText', 'simpleCondition', 'complexCondition']
1234        addelems(self,elems)
1235        children={elems[0]:[MOLES('effect'), 'csString'],elems[1]:[MOLES('conditionExplanationText'),'csString'],elems[2]:[MOLES('simpleCondition'), 'SimpleCondition'],elems[3]:[MOLES('complexCondition'), 'ComplexCondition']}
1236        addchildren(self,children)
1237        csElement.__init__(self,**kwargs)
1238
1239class AccessControlPolicy(csElement):
1240    def __init__(self,**kwargs):
1241        addatts(self,[])
1242        elems=['accessControlPolicyURL', 'accessControlPolicyText', 'dgSecurityCondition']     
1243        addelems(self,elems)
1244        children={elems[0]:[CSML('accessControlPolicyURL'), 'csString'],elems[1]:[CSML('accessControlPolicyText'),'csString'],elems[2]:[CSML('dgSecurityCondition'), 'DgSecurityCondition']}
1245        addchildren(self,children)
1246        csElement.__init__(self,**kwargs)
1247       
1248class CSMLStorageDescriptor(csElement):
1249    def __init__(self,**kwargs):
1250        addatts(self,[])
1251        elems=['descriptors']
1252        addelems(self,elems)
1253        children={elems[0]:[[CSML('NetCDFExtract'),CSML('AggregatedArray'), CSML('RawFileExtract')], 'FileExtract', CSML('descriptor'),1]}
1254        addchildren(self,children)
1255        csElement.__init__(self,**kwargs)
1256
1257class CSMLFeatureCollection(AbstractFeatureCollection,csElement,):
1258    def __init__(self,**kwargs):
1259        AbstractFeatureCollection.__init__(self,**kwargs)
1260        elems=['featureMembers']
1261        addelems(self,elems)
1262        children={elems[0]:[[CSML('GridFeature'), CSML('GridSeriesFeature'),CSML('PointFeature'),CSML('TrajectoryFeature'),CSML('ProfileFeature'),CSML('ProfileSeriesFeature'),CSML('RaggedProfileSeriesFeature'),CSML('RaggedSectionFeature'),CSML('SectionFeature'),CSML('ScanningRadarFeature'),CSML('PointSeriesFeature'),CSML('AlternatePointFeature')], 'AbstractFeature', CSML('featureMember'),1]}
1263        addchildren(self,children)
1264        csElement.__init__(self,**kwargs)
1265    def _getSubstitutionType(self,tag):
1266        if tag==CSML('GridFeature'):
1267            return 'GridFeature'
1268        elif tag==CSML('GridSeriesFeature'):
1269            return 'GridSeriesFeature'
1270        elif tag==CSML('PointFeature'):
1271            return 'PointFeature'
1272        elif tag==CSML('TrajectoryFeature'):
1273            return 'TrajectoryFeature'
1274        elif tag==CSML('PointSeriesFeature'):
1275            return 'PointSeriesFeature'
1276        elif tag==CSML('ProfileFeature'):
1277            return 'ProfileFeature'
1278        elif tag==CSML('ProfileSeriesFeature'):
1279            return 'ProfileSeriesFeature'
1280        elif tag==CSML('RaggedProfileSeriesFeature'):
1281            return 'RaggedProfileSeriesFeature'
1282        elif tag==CSML('RaggedSectionFeature'):
1283            return 'RaggedSectionFeature'
1284        elif tag==CSML('SectionFeature'):
1285            return 'SectionFeature'
1286        elif tag==CSML('ScanningRadarFeature'):
1287            return 'ScanningRadarFeature'
1288        elif tag==CSML('AlternatePointFeature'):
1289            return 'AlternatePointFeature'
1290        else: return 'AbstractFeature'
1291    def _getReverseSubsType(self, typename):
1292        if typename== 'GridFeature':
1293            return CSML('GridFeature')
1294        elif typename == 'GridSeriesFeature':
1295            return CSML('GridSeriesFeature')
1296        elif typename == 'PointSeriesFeature':
1297            return CSML('PointSeriesFeature')
1298        elif typename == 'ProfileFeature':
1299            return CSML('ProfileFeature')
1300        elif typename == 'ProfileSeriesFeature':
1301            return CSML('ProfileSeriesFeature')
1302        elif typename == 'SectionFeature':
1303            return CSML('SectionFeature')
1304        elif typename == 'ScanningRadarFeature':
1305            return CSML('ScanningRadarFeature')
1306        elif typename == 'RaggedSectionFeature':
1307            return CSML('RaggedSectionFeature')
1308        elif typename == 'RaggedProfileSeriesFeature':
1309            return CSML('RaggedProfileSeriesFeature')
1310        elif typename == 'PointFeature':
1311            return CSML('PointFeature')
1312        elif typename == 'TrajectoryFeature':
1313            return CSML('TrajectoryFeature')
1314        elif typename == 'AlternatePointFeature':
1315            return CSML('AlternatePointFeature')
1316        else: return CSML('AbstractFeature')
1317
1318       
1319class Dataset(csElement):   
1320    ''' Dataset class, needed as root of tree'''
1321    def __init__(self, file=None, **kwargs):
1322        a=['id']
1323        addatts(self,a)
1324        elems=['name','accessControlPolicy','featureCollection','storageDescriptor']
1325        addelems(self,elems)
1326        children = {elems[0]:[CSML('name') ,'csString'], elems[1]:[CSML('AccessControlPolicy') ,'AccessControlPolicy'], elems[2]:[CSML('CSMLFeatureCollection') ,'CSMLFeatureCollection'],elems[3]:[CSML('CSMLStorageDescriptor'),'CSMLStorageDescriptor']}
1327        addchildren(self,children)
1328        csElement.__init__(self,**kwargs)
1329        if file is not None:
1330            self.parse(file)
1331   
1332    def __getitem__(self,name):
1333        ''' check featureMembers list to allow dict like access to features'''
1334        feature= None
1335        try:
1336            fc =self.__getattribute__('featureCollection')
1337        except AttributeError:
1338            raise AttributeError, "This Dataset object has no featureCollection associated with it. Try: Dataset.parse('yourcsmlfile.xml')"
1339        fc =self.__getattribute__('featureCollection')
1340        for f in fc.featureMembers:
1341            if name==f.id:
1342                feature=f
1343                break
1344        if feature:
1345            return feature
1346        else: 
1347            raise KeyError, "No feature with ID: %s" % name
1348   
1349    def toXML(self):
1350        ''' returns XML as elementtree instance'''
1351        csmlfrag=ET.Element(CSML('Dataset'))
1352        csElement.toXML(self, csmlfrag)
1353        return csmlfrag
1354   
1355    def toPrettyXML(self):
1356        '''returns nicely formatted XML as string '''
1357        csmldoc = self.toXML()
1358        #pretty print the result
1359        strCSML=csml.parser_extra.PrettyPrint(csmldoc)
1360        #and fix elementtree namespaces
1361        strCSML=csml.parser_extra.removeInlineNS(strCSML)
1362        return strCSML
1363   
1364    def items(self):
1365        '''supports dict-like items() access to features e.g. ds['Temperature']'''
1366        try:
1367            items=self.featureCollection.featureMembers
1368        except AttributeError:
1369            raise AttributeError, "This Dataset object has no featureCollection associated with it. Try: Dataset.parse('yourcsmlfile.xml')"
1370           
1371#        for item in self.featureCollection.featureMembers:
1372#            items.append((item,self.featureCollection.featureMembers[item]))
1373        return items
1374   
1375def main():
1376    '''round trip for testing purposes:'''
1377    import parser_extra
1378    print '\n'
1379    #tree=ET.ElementTree(file='/home/dom/coapec/TESTocean.xml')
1380    tree=ET.ElementTree(file='/home/dom/CSTEST/testout.xml')
1381    import time
1382    time1=time.time()
1383    #ds=Dataset()
1384    ds=csml.parser.Dataset()
1385    ds.fromXML(tree.getroot()) 
1386    #ds =csml.parser_extra.ParserPostProcessor(ds).resolveReferences()
1387    print 'time=',time.time()-time1
1388   
1389    csmltree=ds.toXML()   
1390    csmlout=parser_extra.PrettyPrint(csmltree)
1391    csmlout=parser_extra.removeInlineNS(csmlout)
1392    f=open('temp.xml', 'w')
1393    f.write(csmlout)
1394    f.close()
1395       
1396    print 'time=',time.time()-time1
1397    print '\n %s'% csmlout
1398    #for member in ds.featureCollection.members:
1399      #print dir(member.value)
1400       
1401
1402if __name__=='__main__':
1403    #import profile
1404    #profile.run('main()')
1405    main()
Note: See TracBrowser for help on using the browser.