/[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

trunk/esys2/escript/py_src/esysXML.py revision 122 by jgs, Thu Jun 9 05:38:05 2005 UTC temp/escript/py_src/esysXML.py revision 1387 by trankine, Fri Jan 11 07:45:26 2008 UTC
# Line 1  Line 1 
1    #
2  # $Id$  # $Id$
3  """ A simple tool to handel parameters for a simulation in easy way  #
4      The idea is that all parameters are stored in a single object in a hierachical form  #######################################################
5      and can accessed using python's attribute notation.  For instance:  #
6    #           Copyright 2003-2007 by ACceSS MNRF
7    #       Copyright 2007 by University of Queensland
8    #
9    #                http://esscc.uq.edu.au
10    #        Primary Business: Queensland, Australia
11    #  Licensed under the Open Software License version 3.0
12    #     http://www.opensource.org/licenses/osl-3.0.php
13    #
14    #######################################################
15    #
16    
17    """
18    A simple tool to handle parameters for a simulation in easy way.
19    
20    The idea is that all parameters are stored in a single object in a
21    hierachical form and can accessed using python's attribute notation.  
22    For instance::
23    
24          parm.parm2.alpha=814.          parm.parm2.alpha=814.
25          parm.parm1.gamma=0.          parm.parm1.gamma=0.
# Line 17  Line 35 
35          parm.parm1.parm11.gamma2=2.          parm.parm1.parm11.gamma2=2.
36          parm.parm1.parm11.gamma3=3.          parm.parm1.parm11.gamma3=3.
37    
38  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>  
39    
40        <?xml version="1.0"?>
41        <ESyS>
42           <Component type="Geodynamics">
43           <Name>parm1</Name>
44           <Description>
45         a few examples of parameters
46           </Description>
47           <Parameter><Item>gamma</Item><Value>0.</Value></Parameter>
48           <Parameter type="int"><Item>dim</Item><Value>2</Value></Parameter>
49           <Parameter type="real"><Item>tol_v</Item><Value>0.001</Value></Parameter>
50           <Parameter type="string"><Item>output_file</Item><Value>/tmp/u.%3.3d.dx</Value></Parameter>
51           <Parameter type="bool"><Item>runFlag</Item><Value>true</Value></Parameter>
52           <Parameter type="real" sequence="single"><Item>T</Item><Value>1.</Value><Value>2</Value></Parameter>
53           <Parameter type="real" sequence="list"><Item>x1</Item><Value>-1.</Value><Value>2</Value></Parameter>
54           <Parameter type="real" sequence="tuple"><Item>x2</Item><Value>10</Value><Value>11</Value></Parameter>
55           <Parameter sequence="tuple"><Item>x3</Item><Value>-10.</Value></Parameter>
56           <Component>
57               <Name>parm11</Name>
58               <Description>
59             a sub compoment
60               </Description>
61            <Parameter><Item>gamma1</Item><Value>1.</Value></Parameter>
62            <Parameter><Item>gamma2</Item><Value>2.</Value></Parameter>
63            <Parameter><Item>gamma3</Item><Value>3.</Value></Parameter>
64           </Component>
65           <Component type="Geodynamics">
66           <Name>parm2</Name>
67           <Description>
68         another component
69           </Description>
70           <Parameter><Item>alpha</Item><Value>0814</Value></Parameter>
71           </Component>
72        </ESyS>
73  """  """
74    
75    __copyright__="""  Copyright (c) 2006 by ACcESS MNRF
76                        http://www.access.edu.au
77                    Primary Business: Queensland, Australia"""
78    __license__="""Licensed under the Open Software License version 3.0
79                 http://www.opensource.org/licenses/osl-3.0.php"""
80    
81  import types  import types
82  from xml.dom import minidom  from xml.dom import minidom
83  from string import atoi,atof  from string import atoi,atof
84    
85  class ESySParameters:  class ESySParameters:
86     """is an object to store simulation parameters in the form of a tree and      """
87        access their values in an easy form      Is an object to store simulation parameters in the form of a tree and
88        access their values in an easy form
89                
90        Leaves of  an ESySParameters objects can be      Leaves of an ESySParameters object can be:
91    
92             a single real number or a list or tuple of real numbers          - a single real number or a list or tuple of real numbers
93             a single integer number or a list or tuple of integer  numbers          - a single integer number or a list or tuple of integer  numbers
94             a single strings or a list or tuple of strings          - a single strings or a list or tuple of strings
95             a single boolean value or a list or tuple of boolean values          - a single boolean value or a list or tuple of boolean values
96             a ESySParameters object          - a ESySParameters object
97             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  
98    
99              Output is      Example how to create an ESySParameters object::
100    
101              (parm1=(dim=2,output_file=/tmp/u.%3.3d.dx,parm11=(gamma3=3.0,gamma2=2.0,gamma1=1.0),          parm=ESySParameters()
102                      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()
103            parm.parm1.gamma=0.
104            parm.parm1.dim=2
105            parm.parm1.tol_v=0.001
106            parm.parm1.output_file="/tmp/u.%3.3d.dx"
107            parm.parm1.runFlag=True
108            parm.parm1.T=1.
109            parm.parm1.x1=[-1.,2]
110            parm.parm1.x2=(10.,11)
111            parm.parm1.x3=(-10.,)
112            parm.parm1.parm11=ESySParameters()
113            parm.parm1.parm11.gamma1=1.
114            parm.parm1.parm11.gamma2=2.
115            parm.parm1.parm11.gamma3=3.
116            parm.parm2=ESySParameters()
117            parm.parm2.alpha=814.
118    
119              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
120              ESySParameter is trying to use the same type for all items in a list or a tuple.  
121                    Output is::
    """  
122    
123     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),
124        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))
125        self.setType(type)  
126        Notice that C{parm.parm1.x1} is now a list of two floats although it is
127        defined by a list of a float and an integer.  ESySParameter is trying to
128        use the same type for all items in a list or a tuple.
129        """
130    
131        def __init__(self,description="none",type=None):
132            self.setDescription(description)
133            self.setType(type)
134                
135     def getTypeName(self):      def getTypeName(self):
136         if self.__type==None:         if self.__type==None:
137            return None            return None
138         else:         else:
139            return self.__type.__str__()            return self.__type.__str__()
140    
141     def getDescription(self):      def getDescription(self):
142         return self.__description         return self.__description
143    
144     def setType(self,type=None):      def setType(self,type=None):
145         self.__type=type         self.__type=type
146                    
147     def setDescription(self,description="none"):      def setDescription(self,description="none"):
148         self.__description=description         self.__description=description
149    
150     def __str__(self):      def __str__(self):
151         """returns a string representation"""         """
152           Returns a string representation.
153           """
154         out=""         out=""
155         for name,value in self.__dict__.iteritems():         for name,value in self.__dict__.iteritems():
156             if name[0]!="_":             if name[0]!="_":
# Line 135  class ESySParameters: Line 160  class ESySParameters:
160                     out=out+","+name+"="+str(value)                     out=out+","+name+"="+str(value)
161         return "("+out+")"         return "("+out+")"
162                    
163     def __setattr__(self,name,value):      def __setattr__(self,name,value):
164       """defines attribute name and assigns value. if name does not start          """
165          with an underscore value has to be a valid Parameter."""          Defines attribute C{name} and assigns C{value}.  If name does not start
166       name=name.replace(" ","_")          with an underscore value has to be a valid Parameter.
167       if name[0]!="_":          """
168         if value==None:          name=name.replace(" ","_")
169            self.__dict__[name]=value          if name[0]!="_":
170         elif isinstance(value,ESySParameters):            if value==None:
171            self.__dict__[name]=value               self.__dict__[name]=value
172         elif isinstance(value,types.BooleanType):            elif isinstance(value,ESySParameters):
173            self.__dict__[name]=value                 self.__dict__[name]=value
174         elif isinstance(value,types.ListType):            elif isinstance(value,types.BooleanType):
175            self.__dict__[name]=_mkSameType(value)               self.__dict__[name]=value  
176         elif isinstance(value,types.TupleType):            elif isinstance(value,types.ListType):
177            self.__dict__[name]=tuple(_mkSameType(value))               self.__dict__[name]=_mkSameType(value)
178         elif isinstance(value,types.BooleanType):            elif isinstance(value,types.TupleType):
179            self.__dict__[name]=value               self.__dict__[name]=tuple(_mkSameType(value))
180         elif isinstance(value,types.IntType):            elif isinstance(value,types.BooleanType):
181            self.__dict__[name]=value               self.__dict__[name]=value
182         elif isinstance(value,types.FloatType):            elif isinstance(value,types.IntType):
183            self.__dict__[name]=value               self.__dict__[name]=value
184         elif isinstance(value,types.StringType) or isinstance(value,types.UnicodeType):            elif isinstance(value,types.FloatType):
185            self.__dict__[name]=str(value)               self.__dict__[name]=value
186         else:            elif isinstance(value,types.StringType) or isinstance(value,types.UnicodeType):
187                 self.__dict__[name]=str(value)
188              else:
189                 self.__dict__[name]=value
190            else:
191            self.__dict__[name]=value            self.__dict__[name]=value
      else:  
        self.__dict__[name]=value  
192                        
193     def writeXML(self,iostream):      def writeXML(self,iostream):
194       """writes the object as an XML object into an IO stream"""       """
195         Writes the object as an XML object into an IO stream.
196         """
197       for name,value in self.__dict__.iteritems():       for name,value in self.__dict__.iteritems():
198          if name[0]!="_":          if name[0]!="_":
199             if isinstance(value,ESySParameters):             if isinstance(value,ESySParameters):
# Line 198  class ESySParameters: Line 227  class ESySParameters:
227                 iostream.write("</%s>\n"%_PARAMETER)                 iostream.write("</%s>\n"%_PARAMETER)
228    
229    
230     def writeProperties(self, iostream, nameSpace = None):      def writeProperties(self, iostream, nameSpace = None):
231       """writes the object as a property list to an IO stream"""       """
232         Writes the object as a property list to an IO stream.
233         """
234       if nameSpace != None and nameSpace != "":       if nameSpace != None and nameSpace != "":
235          nameSpace += ".";          nameSpace += ".";
236       for name,value in self.__dict__.iteritems():       for name,value in self.__dict__.iteritems():
# Line 218  class ESySParameters: Line 249  class ESySParameters:
249                    type=_getTypeName(value)                    type=_getTypeName(value)
250                 iostream.write("%s = %s\n" % (nameSpace + name, value.__str__()))                 iostream.write("%s = %s\n" % (nameSpace + name, value.__str__()))
251    
252     def writeESySXML(self,iostream):      def writeESySXML(self,iostream):
253          """writes an ESyS XML file"""          """
254        Writes an ESyS XML file.
255        """
256          iostream.write("<?xml version=\"1.0\"?><ESyS>")          iostream.write("<?xml version=\"1.0\"?><ESyS>")
257          self.writeXML(iostream)          self.writeXML(iostream)
258          iostream.write("</ESyS>")          iostream.write("</ESyS>")
259    
260  def readESySXMLFile(filename):  def readESySXMLFile(filename):
261         """reads an ESyS XML file and returns it as a ESySParameter object"""         """
262           Reads an ESyS XML file and returns it as a ESySParameter object.
263           """
264         return _readParametersFromDOM(minidom.parse(filename).getElementsByTagName(_ESYS)[0])         return _readParametersFromDOM(minidom.parse(filename).getElementsByTagName(_ESYS)[0])
265    
266    
# Line 251  _PARAMETER_SEQUENCE_TUPLE="tuple" Line 286  _PARAMETER_SEQUENCE_TUPLE="tuple"
286    
287    
288  def _mkSameType(list):  def _mkSameType(list):
289      """returns list where all items in the list have the same type"""      """
290        Returns list where all items in the list have the same type.
291        """
292      out=[]      out=[]
293      if len(list)>0:      if len(list)>0:
294          type=0          type=0
# Line 294  def _mkSameType(list): Line 331  def _mkSameType(list):
331      return out      return out
332    
333  def _getTypeNameOfList(values):  def _getTypeNameOfList(values):
334      """returns the type of the parameters in list values"""      """
335        Returns the type of the parameters in list values.
336        """
337      if len(values)==0:      if len(values)==0:
338          type=_PARAMETER_TYPE_UNKNOWN          type=_PARAMETER_TYPE_UNKNOWN
339      else:      else:
# Line 302  def _getTypeNameOfList(values): Line 341  def _getTypeNameOfList(values):
341      return type      return type
342    
343  def _getTypeName(value):  def _getTypeName(value):
344      """returns the type of the parameter value"""      """
345        Returns the type of the parameter value.
346        """
347      if isinstance(value,types.FloatType):      if isinstance(value,types.FloatType):
348             type=_PARAMETER_TYPE_REAL             type=_PARAMETER_TYPE_REAL
349      elif isinstance(value,types.BooleanType):      elif isinstance(value,types.BooleanType):
# Line 317  def _getTypeName(value): Line 358  def _getTypeName(value):
358    
359            
360  def _extractStrippedValue(dom):  def _extractStrippedValue(dom):
361      """exracts a string from a DOM node"""      """
362        Exracts a string from a DOM node.
363        """
364      out=""      out=""
365      for i in dom.childNodes:      for i in dom.childNodes:
366          s=i.nodeValue.strip()          s=i.nodeValue.strip()
# Line 399  def _readParametersFromDOM(dom): Line 442  def _readParametersFromDOM(dom):
442  # test section:  # test section:
443  if  (__name__=="__main__"):  if  (__name__=="__main__"):
444      def test(parm):      def test(parm):
445          if parm.parm1.gamma!=0. : raise IOError,"unexpected value for parm.parm1.gamma"          if parm.parm1.gamma!=0. :
446          if parm.parm1.dim!=2: raise IOError,"unexpected value for parm.parm1.dim"          raise IOError,"unexpected value for parm.parm1.gamma"
447          if parm.parm1.tol_v!=0.001: raise IOError,"unexpected value for parm.parm1.tol_v"          if parm.parm1.dim!=2:
448          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"
449          if parm.parm1.runFlag!=True: raise IOError,"unexpected value for parm.parm1.runFlag"          if parm.parm1.tol_v!=0.001:
450          if parm.parm1.T!=1.: raise IOError,"unexpected value for parm.parm1.T"          raise IOError,"unexpected value for parm.parm1.tol_v"
451          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":
452          if parm.parm1.x1[1]!=2.: raise IOError,"unexpected value for parm.parm1.x1[1]"          raise IOError,"unexpected value for parm.parm1.output_file"
453          if parm.parm1.x2[0]!=10.: raise IOError,"unexpected value for parm.parm1.x2[0]"          if parm.parm1.runFlag!=True:
454          if parm.parm1.x2[1]!=11.: raise IOError,"unexpected value for parm.parm1.x2[1]"          raise IOError,"unexpected value for parm.parm1.runFlag"
455          if parm.parm1.x3[0]!=-10: raise IOError,"unexpected value for parm.parm1.x3[0]"          if parm.parm1.T!=1.:
456          if parm.parm1.parm11.gamma1!=1.: raise IOError,"unexpected value for parm.parm1.parm11.gamma1"          raise IOError,"unexpected value for parm.parm1.T"
457          if parm.parm1.parm11.gamma2!=2.: raise IOError,"unexpected value for parm.parm1.parm11.gamma2"          if parm.parm1.x1[0]!=-1.:
458          if parm.parm1.parm11.gamma3!=3.: raise IOError,"unexpected value for parm.parm1.parm11.gamma3"          raise IOError,"unexpected value for parm.parm1.x1[0]"
459          if parm.parm2.alpha!=814.: raise IOError,"unexpected value for parm.parm2.alpha"          if parm.parm1.x1[1]!=2.:
460            raise IOError,"unexpected value for parm.parm1.x1[1]"
461            if parm.parm1.x2[0]!=10.:
462            raise IOError,"unexpected value for parm.parm1.x2[0]"
463            if parm.parm1.x2[1]!=11.:
464            raise IOError,"unexpected value for parm.parm1.x2[1]"
465            if parm.parm1.x3[0]!=-10:
466            raise IOError,"unexpected value for parm.parm1.x3[0]"
467            if parm.parm1.parm11.gamma1!=1.:
468            raise IOError,"unexpected value for parm.parm1.parm11.gamma1"
469            if parm.parm1.parm11.gamma2!=2.:
470            raise IOError,"unexpected value for parm.parm1.parm11.gamma2"
471            if parm.parm1.parm11.gamma3!=3.:
472            raise IOError,"unexpected value for parm.parm1.parm11.gamma3"
473            if parm.parm2.alpha!=814.:
474            raise IOError,"unexpected value for parm.parm2.alpha"
475    
476      print "@@@ explicit construction"        print "@@@ explicit construction"  
477      parm=ESySParameters()      parm=ESySParameters()
# Line 480  if  (__name__=="__main__"): Line 538  if  (__name__=="__main__"):
538      parm3=readESySXMLFile("/tmp/test2.xml")      parm3=readESySXMLFile("/tmp/test2.xml")
539      print parm3      print parm3
540      test(parm3)      test(parm3)
541    
542    # vim: expandtab shiftwidth=4:

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

  ViewVC Help
Powered by ViewVC 1.1.26