/[escript]/trunk/escript/py_src/esysXML.py
ViewVC logotype

Diff of /trunk/escript/py_src/esysXML.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 122 by jgs, Thu Jun 9 05:38:05 2005 UTC revision 149 by jgs, Thu Sep 1 03:31:39 2005 UTC
# Line 1  Line 1 
1  # $Id$  # $Id$
2  """ A simple tool to handel parameters for a simulation in easy way  """
3      The idea is that all parameters are stored in a single object in a hierachical form  A simple tool to handle parameters for a simulation in easy way.
4      and can accessed using python's attribute notation.  For instance:  
5    The idea is that all parameters are stored in a single object in a
6    hierachical form and can accessed using python's attribute notation.  
7    For instance::
8    
9          parm.parm2.alpha=814.          parm.parm2.alpha=814.
10          parm.parm1.gamma=0.          parm.parm1.gamma=0.
# Line 17  Line 20 
20          parm.parm1.parm11.gamma2=2.          parm.parm1.parm11.gamma2=2.
21          parm.parm1.parm11.gamma3=3.          parm.parm1.parm11.gamma3=3.
22    
23  This structure can be stored/defined through an XML file parm.xml:  This structure can be stored/defined through an XML file parm.xml::
   
 <?xml version="1.0"?>  
 <ESyS>  
    <Component type="Geodynamics">  
    <Name>parm1</Name>  
    <Description>  
      a few examples of parameters  
    </Description>  
    <Parameter><Item>gamma</Item><Value>0.</Value></Parameter>  
    <Parameter type="int"><Item>dim</Item><Value>2</Value></Parameter>  
    <Parameter type="real"><Item>tol_v</Item><Value>0.001</Value></Parameter>  
    <Parameter type="string"><Item>output_file</Item><Value>/tmp/u.%3.3d.dx</Value></Parameter>  
    <Parameter type="bool"><Item>runFlag</Item><Value>true</Value></Parameter>  
    <Parameter type="real" sequence="single"><Item>T</Item><Value>1.</Value><Value>2</Value></Parameter>  
    <Parameter type="real" sequence="list"><Item>x1</Item><Value>-1.</Value><Value>2</Value></Parameter>  
    <Parameter type="real" sequence="tuple"><Item>x2</Item><Value>10</Value><Value>11</Value></Parameter>  
    <Parameter sequence="tuple"><Item>x3</Item><Value>-10.</Value></Parameter>  
    <Component>  
            <Name>parm11</Name>  
            <Description>  
           a sub compoment  
            </Description>  
             <Parameter><Item>gamma1</Item><Value>1.</Value></Parameter>  
             <Parameter><Item>gamma2</Item><Value>2.</Value></Parameter>  
             <Parameter><Item>gamma3</Item><Value>3.</Value></Parameter>  
            </Component>    
    </Component>  
     <Component type="Geodynamics">  
    <Name>parm2</Name>  
    <Description>  
      another component  
    </Description>  
    <Parameter><Item>alpha</Item><Value>0814</Value></Parameter>  
    </Component>  
 </ESyS>  
24    
25        <?xml version="1.0"?>
26        <ESyS>
27           <Component type="Geodynamics">
28           <Name>parm1</Name>
29           <Description>
30         a few examples of parameters
31           </Description>
32           <Parameter><Item>gamma</Item><Value>0.</Value></Parameter>
33           <Parameter type="int"><Item>dim</Item><Value>2</Value></Parameter>
34           <Parameter type="real"><Item>tol_v</Item><Value>0.001</Value></Parameter>
35           <Parameter type="string"><Item>output_file</Item><Value>/tmp/u.%3.3d.dx</Value></Parameter>
36           <Parameter type="bool"><Item>runFlag</Item><Value>true</Value></Parameter>
37           <Parameter type="real" sequence="single"><Item>T</Item><Value>1.</Value><Value>2</Value></Parameter>
38           <Parameter type="real" sequence="list"><Item>x1</Item><Value>-1.</Value><Value>2</Value></Parameter>
39           <Parameter type="real" sequence="tuple"><Item>x2</Item><Value>10</Value><Value>11</Value></Parameter>
40           <Parameter sequence="tuple"><Item>x3</Item><Value>-10.</Value></Parameter>
41           <Component>
42               <Name>parm11</Name>
43               <Description>
44             a sub compoment
45               </Description>
46            <Parameter><Item>gamma1</Item><Value>1.</Value></Parameter>
47            <Parameter><Item>gamma2</Item><Value>2.</Value></Parameter>
48            <Parameter><Item>gamma3</Item><Value>3.</Value></Parameter>
49           </Component>
50           <Component type="Geodynamics">
51           <Name>parm2</Name>
52           <Description>
53         another component
54           </Description>
55           <Parameter><Item>alpha</Item><Value>0814</Value></Parameter>
56           </Component>
57        </ESyS>
58  """  """
59    
60  import types  import types
# Line 61  from xml.dom import minidom Line 62  from xml.dom import minidom
62  from string import atoi,atof  from string import atoi,atof
63    
64  class ESySParameters:  class ESySParameters:
65     """is an object to store simulation parameters in the form of a tree and      """
66        access their values in an easy form      Is an object to store simulation parameters in the form of a tree and
67        access their values in an easy form
68                
69        Leaves of  an ESySParameters objects can be      Leaves of an ESySParameters object can be:
70    
71             a single real number or a list or tuple of real numbers          - a single real number or a list or tuple of real numbers
72             a single integer number or a list or tuple of integer  numbers          - a single integer number or a list or tuple of integer  numbers
73             a single strings or a list or tuple of strings          - a single strings or a list or tuple of strings
74             a single boolean value or a list or tuple of boolean values          - a single boolean value or a list or tuple of boolean values
75             a ESySParameters object          - a ESySParameters object
76             any other object (not considered by writeESySXML and writeXML)          - any other object (not considered by writeESySXML and writeXML)
   
           Example how to create an ESySParameters object:  
   
                 parm=ESySParameters()  
                 parm.parm1=ESySParameters()  
                 parm.parm1.gamma=0.  
                 parm.parm1.dim=2  
                 parm.parm1.tol_v=0.001  
                 parm.parm1.output_file="/tmp/u.%3.3d.dx"  
                 parm.parm1.runFlag=True  
                 parm.parm1.T=1.  
                 parm.parm1.x1=[-1.,2]  
                 parm.parm1.x2=(10.,11)  
                 parm.parm1.x3=(-10.,)  
                 parm.parm1.parm11=ESySParameters()  
                 parm.parm1.parm11.gamma1=1.  
                 parm.parm1.parm11.gamma2=2.  
                 parm.parm1.parm11.gamma3=3.  
                 parm.parm2=ESySParameters()  
                 parm.parm2.alpha=814.  
   
                 print parm  
77    
78              Output is      Example how to create an ESySParameters object::
79    
80              (parm1=(dim=2,output_file=/tmp/u.%3.3d.dx,parm11=(gamma3=3.0,gamma2=2.0,gamma1=1.0),          parm=ESySParameters()
81                      tol_v=0.001,T=1.0,x2=(10,),x3=(-10,),runFlag=True,x1=[-1.0, 2.0],gamma=0.0),parm2=(alpha=814.0))          parm.parm1=ESySParameters()
82            parm.parm1.gamma=0.
83            parm.parm1.dim=2
84            parm.parm1.tol_v=0.001
85            parm.parm1.output_file="/tmp/u.%3.3d.dx"
86            parm.parm1.runFlag=True
87            parm.parm1.T=1.
88            parm.parm1.x1=[-1.,2]
89            parm.parm1.x2=(10.,11)
90            parm.parm1.x3=(-10.,)
91            parm.parm1.parm11=ESySParameters()
92            parm.parm1.parm11.gamma1=1.
93            parm.parm1.parm11.gamma2=2.
94            parm.parm1.parm11.gamma3=3.
95            parm.parm2=ESySParameters()
96            parm.parm2.alpha=814.
97    
98              Notice that parm.parm1.x1 is now a list of two floats although it is defined by a list of a float and an integer.          print parm
99              ESySParameter is trying to use the same type for all items in a list or a tuple.  
100                    Output is::
    """  
101    
102     def __init__(self,description="none",type=None):          (parm1=(dim=2,output_file=/tmp/u.%3.3d.dx,parm11=(gamma3=3.0,gamma2=2.0,gamma1=1.0),
103        self.setDescription(description)              tol_v=0.001,T=1.0,x2=(10,),x3=(-10,),runFlag=True,x1=[-1.0, 2.0],gamma=0.0),parm2=(alpha=814.0))
104        self.setType(type)  
105        Notice that C{parm.parm1.x1} is now a list of two floats although it is
106        defined by a list of a float and an integer.  ESySParameter is trying to
107        use the same type for all items in a list or a tuple.
108        """
109    
110        def __init__(self,description="none",type=None):
111            self.setDescription(description)
112            self.setType(type)
113                
114     def getTypeName(self):      def getTypeName(self):
115         if self.__type==None:         if self.__type==None:
116            return None            return None
117         else:         else:
118            return self.__type.__str__()            return self.__type.__str__()
119    
120     def getDescription(self):      def getDescription(self):
121         return self.__description         return self.__description
122    
123     def setType(self,type=None):      def setType(self,type=None):
124         self.__type=type         self.__type=type
125                    
126     def setDescription(self,description="none"):      def setDescription(self,description="none"):
127         self.__description=description         self.__description=description
128    
129     def __str__(self):      def __str__(self):
130         """returns a string representation"""         """
131           Returns a string representation.
132           """
133         out=""         out=""
134         for name,value in self.__dict__.iteritems():         for name,value in self.__dict__.iteritems():
135             if name[0]!="_":             if name[0]!="_":
# Line 135  class ESySParameters: Line 139  class ESySParameters:
139                     out=out+","+name+"="+str(value)                     out=out+","+name+"="+str(value)
140         return "("+out+")"         return "("+out+")"
141                    
142     def __setattr__(self,name,value):      def __setattr__(self,name,value):
143       """defines attribute name and assigns value. if name does not start          """
144          with an underscore value has to be a valid Parameter."""          Defines attribute C{name} and assigns C{value}.  If name does not start
145       name=name.replace(" ","_")          with an underscore value has to be a valid Parameter.
146       if name[0]!="_":          """
147         if value==None:          name=name.replace(" ","_")
148            self.__dict__[name]=value          if name[0]!="_":
149         elif isinstance(value,ESySParameters):            if value==None:
150            self.__dict__[name]=value               self.__dict__[name]=value
151         elif isinstance(value,types.BooleanType):            elif isinstance(value,ESySParameters):
152            self.__dict__[name]=value                 self.__dict__[name]=value
153         elif isinstance(value,types.ListType):            elif isinstance(value,types.BooleanType):
154            self.__dict__[name]=_mkSameType(value)               self.__dict__[name]=value  
155         elif isinstance(value,types.TupleType):            elif isinstance(value,types.ListType):
156            self.__dict__[name]=tuple(_mkSameType(value))               self.__dict__[name]=_mkSameType(value)
157         elif isinstance(value,types.BooleanType):            elif isinstance(value,types.TupleType):
158            self.__dict__[name]=value               self.__dict__[name]=tuple(_mkSameType(value))
159         elif isinstance(value,types.IntType):            elif isinstance(value,types.BooleanType):
160            self.__dict__[name]=value               self.__dict__[name]=value
161         elif isinstance(value,types.FloatType):            elif isinstance(value,types.IntType):
162            self.__dict__[name]=value               self.__dict__[name]=value
163         elif isinstance(value,types.StringType) or isinstance(value,types.UnicodeType):            elif isinstance(value,types.FloatType):
164            self.__dict__[name]=str(value)               self.__dict__[name]=value
165         else:            elif isinstance(value,types.StringType) or isinstance(value,types.UnicodeType):
166                 self.__dict__[name]=str(value)
167              else:
168                 self.__dict__[name]=value
169            else:
170            self.__dict__[name]=value            self.__dict__[name]=value
      else:  
        self.__dict__[name]=value  
171                        
172     def writeXML(self,iostream):      def writeXML(self,iostream):
173       """writes the object as an XML object into an IO stream"""       """
174         Writes the object as an XML object into an IO stream.
175         """
176       for name,value in self.__dict__.iteritems():       for name,value in self.__dict__.iteritems():
177          if name[0]!="_":          if name[0]!="_":
178             if isinstance(value,ESySParameters):             if isinstance(value,ESySParameters):
# Line 198  class ESySParameters: Line 206  class ESySParameters:
206                 iostream.write("</%s>\n"%_PARAMETER)                 iostream.write("</%s>\n"%_PARAMETER)
207    
208    
209     def writeProperties(self, iostream, nameSpace = None):      def writeProperties(self, iostream, nameSpace = None):
210       """writes the object as a property list to an IO stream"""       """
211         Writes the object as a property list to an IO stream.
212         """
213       if nameSpace != None and nameSpace != "":       if nameSpace != None and nameSpace != "":
214          nameSpace += ".";          nameSpace += ".";
215       for name,value in self.__dict__.iteritems():       for name,value in self.__dict__.iteritems():
# Line 218  class ESySParameters: Line 228  class ESySParameters:
228                    type=_getTypeName(value)                    type=_getTypeName(value)
229                 iostream.write("%s = %s\n" % (nameSpace + name, value.__str__()))                 iostream.write("%s = %s\n" % (nameSpace + name, value.__str__()))
230    
231     def writeESySXML(self,iostream):      def writeESySXML(self,iostream):
232          """writes an ESyS XML file"""          """
233        Writes an ESyS XML file.
234        """
235          iostream.write("<?xml version=\"1.0\"?><ESyS>")          iostream.write("<?xml version=\"1.0\"?><ESyS>")
236          self.writeXML(iostream)          self.writeXML(iostream)
237          iostream.write("</ESyS>")          iostream.write("</ESyS>")
238    
239  def readESySXMLFile(filename):  def readESySXMLFile(filename):
240         """reads an ESyS XML file and returns it as a ESySParameter object"""         """
241           Reads an ESyS XML file and returns it as a ESySParameter object.
242           """
243         return _readParametersFromDOM(minidom.parse(filename).getElementsByTagName(_ESYS)[0])         return _readParametersFromDOM(minidom.parse(filename).getElementsByTagName(_ESYS)[0])
244    
245    
# Line 251  _PARAMETER_SEQUENCE_TUPLE="tuple" Line 265  _PARAMETER_SEQUENCE_TUPLE="tuple"
265    
266    
267  def _mkSameType(list):  def _mkSameType(list):
268      """returns list where all items in the list have the same type"""      """
269        Returns list where all items in the list have the same type.
270        """
271      out=[]      out=[]
272      if len(list)>0:      if len(list)>0:
273          type=0          type=0
# Line 294  def _mkSameType(list): Line 310  def _mkSameType(list):
310      return out      return out
311    
312  def _getTypeNameOfList(values):  def _getTypeNameOfList(values):
313      """returns the type of the parameters in list values"""      """
314        Returns the type of the parameters in list values.
315        """
316      if len(values)==0:      if len(values)==0:
317          type=_PARAMETER_TYPE_UNKNOWN          type=_PARAMETER_TYPE_UNKNOWN
318      else:      else:
# Line 302  def _getTypeNameOfList(values): Line 320  def _getTypeNameOfList(values):
320      return type      return type
321    
322  def _getTypeName(value):  def _getTypeName(value):
323      """returns the type of the parameter value"""      """
324        Returns the type of the parameter value.
325        """
326      if isinstance(value,types.FloatType):      if isinstance(value,types.FloatType):
327             type=_PARAMETER_TYPE_REAL             type=_PARAMETER_TYPE_REAL
328      elif isinstance(value,types.BooleanType):      elif isinstance(value,types.BooleanType):
# Line 317  def _getTypeName(value): Line 337  def _getTypeName(value):
337    
338            
339  def _extractStrippedValue(dom):  def _extractStrippedValue(dom):
340      """exracts a string from a DOM node"""      """
341        Exracts a string from a DOM node.
342        """
343      out=""      out=""
344      for i in dom.childNodes:      for i in dom.childNodes:
345          s=i.nodeValue.strip()          s=i.nodeValue.strip()
# Line 399  def _readParametersFromDOM(dom): Line 421  def _readParametersFromDOM(dom):
421  # test section:  # test section:
422  if  (__name__=="__main__"):  if  (__name__=="__main__"):
423      def test(parm):      def test(parm):
424          if parm.parm1.gamma!=0. : raise IOError,"unexpected value for parm.parm1.gamma"          if parm.parm1.gamma!=0. :
425          if parm.parm1.dim!=2: raise IOError,"unexpected value for parm.parm1.dim"          raise IOError,"unexpected value for parm.parm1.gamma"
426          if parm.parm1.tol_v!=0.001: raise IOError,"unexpected value for parm.parm1.tol_v"          if parm.parm1.dim!=2:
427          if parm.parm1.output_file!="/tmp/u.%3.3d.dx": raise IOError,"unexpected value for parm.parm1.output_file"          raise IOError,"unexpected value for parm.parm1.dim"
428          if parm.parm1.runFlag!=True: raise IOError,"unexpected value for parm.parm1.runFlag"          if parm.parm1.tol_v!=0.001:
429          if parm.parm1.T!=1.: raise IOError,"unexpected value for parm.parm1.T"          raise IOError,"unexpected value for parm.parm1.tol_v"
430          if parm.parm1.x1[0]!=-1.: raise IOError,"unexpected value for parm.parm1.x1[0]"          if parm.parm1.output_file!="/tmp/u.%3.3d.dx":
431          if parm.parm1.x1[1]!=2.: raise IOError,"unexpected value for parm.parm1.x1[1]"          raise IOError,"unexpected value for parm.parm1.output_file"
432          if parm.parm1.x2[0]!=10.: raise IOError,"unexpected value for parm.parm1.x2[0]"          if parm.parm1.runFlag!=True:
433          if parm.parm1.x2[1]!=11.: raise IOError,"unexpected value for parm.parm1.x2[1]"          raise IOError,"unexpected value for parm.parm1.runFlag"
434          if parm.parm1.x3[0]!=-10: raise IOError,"unexpected value for parm.parm1.x3[0]"          if parm.parm1.T!=1.:
435          if parm.parm1.parm11.gamma1!=1.: raise IOError,"unexpected value for parm.parm1.parm11.gamma1"          raise IOError,"unexpected value for parm.parm1.T"
436          if parm.parm1.parm11.gamma2!=2.: raise IOError,"unexpected value for parm.parm1.parm11.gamma2"          if parm.parm1.x1[0]!=-1.:
437          if parm.parm1.parm11.gamma3!=3.: raise IOError,"unexpected value for parm.parm1.parm11.gamma3"          raise IOError,"unexpected value for parm.parm1.x1[0]"
438          if parm.parm2.alpha!=814.: raise IOError,"unexpected value for parm.parm2.alpha"          if parm.parm1.x1[1]!=2.:
439            raise IOError,"unexpected value for parm.parm1.x1[1]"
440            if parm.parm1.x2[0]!=10.:
441            raise IOError,"unexpected value for parm.parm1.x2[0]"
442            if parm.parm1.x2[1]!=11.:
443            raise IOError,"unexpected value for parm.parm1.x2[1]"
444            if parm.parm1.x3[0]!=-10:
445            raise IOError,"unexpected value for parm.parm1.x3[0]"
446            if parm.parm1.parm11.gamma1!=1.:
447            raise IOError,"unexpected value for parm.parm1.parm11.gamma1"
448            if parm.parm1.parm11.gamma2!=2.:
449            raise IOError,"unexpected value for parm.parm1.parm11.gamma2"
450            if parm.parm1.parm11.gamma3!=3.:
451            raise IOError,"unexpected value for parm.parm1.parm11.gamma3"
452            if parm.parm2.alpha!=814.:
453            raise IOError,"unexpected value for parm.parm2.alpha"
454    
455      print "@@@ explicit construction"        print "@@@ explicit construction"  
456      parm=ESySParameters()      parm=ESySParameters()
# Line 480  if  (__name__=="__main__"): Line 517  if  (__name__=="__main__"):
517      parm3=readESySXMLFile("/tmp/test2.xml")      parm3=readESySXMLFile("/tmp/test2.xml")
518      print parm3      print parm3
519      test(parm3)      test(parm3)
520    
521    # vim: expandtab shiftwidth=4:

Legend:
Removed from v.122  
changed lines
  Added in v.149

  ViewVC Help
Powered by ViewVC 1.1.26