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

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

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

trunk/esys2/escript/py_src/modelframe.py revision 149 by jgs, Thu Sep 1 03:31:39 2005 UTC trunk/escript/py_src/modelframe.py revision 874 by elspeth, Tue Oct 17 12:06:11 2006 UTC
# Line 1  Line 1 
1  # $Id$  # $Id$
2    
3    """
4    Environment for implementing models in escript
5    
6    @var __author__: name of author
7    @var __copyright__: copyrights
8    @var __license__: licence agreement
9    @var __url__: url entry point on documentation
10    @var __version__: version
11    @var __date__: date of the version
12    """
13    
14    __author__="Lutz Gross, l.gross@uq.edu.au"
15    __copyright__="""  Copyright (c) 2006 by ACcESS MNRF
16                        http://www.access.edu.au
17                    Primary Business: Queensland, Australia"""
18    __license__="""Licensed under the Open Software License version 3.0
19                 http://www.opensource.org/licenses/osl-3.0.php"""
20    __url__="http://www.iservo.edu.au/esys"
21    __version__="$Revision$"
22    __date__="$Date$"
23    
24    
25  from types import StringType,IntType,FloatType,BooleanType,ListType,DictType  from types import StringType,IntType,FloatType,BooleanType,ListType,DictType
26  from sys import stdout  from sys import stdout
27    import numarray
28    import operator
29  import itertools  import itertools
30  # import modellib  temporarily removed!!!  # import modellib  temporarily removed!!!
31    
# Line 73  def parse(xml): Line 97  def parse(xml):
97    
98      return sim      return sim
99    
100    def importName(modulename, name):
101        """ Import a named object from a module in the context of this function,
102            which means you should use fully qualified module paths.
103            
104            Return None on failure.
105    
106            This function from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52241
107        """
108        module = __import__(modulename, globals(), locals(), [name])
109            
110        try:
111            return vars(module)[name]
112        except KeyError:
113            raise ImportError("Could not import %s from %s" % (name, modulename))
114    
115  def getComponent(doc):  def getComponent(doc):
116      """      """
117      Used to get components of Simualtions, Models.      Used to get components of Simualtions, Models.
# Line 84  def getComponent(doc): Line 123  def getComponent(doc):
123                  if node.getAttribute("type") == 'Simulation':                  if node.getAttribute("type") == 'Simulation':
124                      return Simulation.fromDom(node)                      return Simulation.fromDom(node)
125              if node.tagName == 'Model':              if node.tagName == 'Model':
126                  model_type = node.getAttribute("type")                  if (node.getAttribute("module")):
127                  model_subclasses = Model.__subclasses__()                      model_module = node.getAttribute("module")
128                  for model in model_subclasses:                      model_type = node.getAttribute("type")
129                      if model_type == model.__name__:                      return importName(model_module, model_type).fromDom(node)
130                          return Model.fromDom(node)                  else:
131                        model_type = node.getAttribute("type")
132                        model_subclasses = Model.__subclasses__()
133                        for model in model_subclasses:
134                            if model_type == model.__name__:
135                                return Model.fromDom(node)
136              if node.tagName == 'ParameterSet':              if node.tagName == 'ParameterSet':
137                  parameter_type = node.getAttribute("type")                  parameter_type = node.getAttribute("type")
138                  return ParameterSet.fromDom(node)                  return ParameterSet.fromDom(node)
# Line 322  class ParameterSet(LinkableObject): Line 366  class ParameterSet(LinkableObject):
366       - a ParameterSet object       - a ParameterSet object
367       - a Simulation object       - a Simulation object
368       - a Model object       - a Model object
369       - any other object (not considered by writeESySXML and writeXML)       - a numarray object
370             - a list of booleans
371            - any other object (not considered by writeESySXML and writeXML)
372            
373      Example how to create an ESySParameters object::      Example how to create an ESySParameters object::
374            
# Line 424  class ParameterSet(LinkableObject): Line 470  class ParameterSet(LinkableObject):
470          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
471    
472      def _parametersToDom(self, document, node):      def _parametersToDom(self, document, node):
473          node.setAttribute ('id', str(self.id))          node.setAttribute('id', str(self.id))
474            node.setIdAttribute("id")
475          for name,value in self:          for name,value in self:
476              param = document.createElement('Parameter')              param = document.createElement('Parameter')
477              param.setAttribute('type', value.__class__.__name__)              param.setAttribute('type', value.__class__.__name__)
# Line 433  class ParameterSet(LinkableObject): Line 480  class ParameterSet(LinkableObject):
480    
481              val = document.createElement('Value')              val = document.createElement('Value')
482    
483              if isinstance(value,ParameterSet):              if isinstance(value,(ParameterSet,Link)):
484                  value.toDom(document, val)                  value.toDom(document, val)
485                  param.appendChild(val)                  param.appendChild(val)
486              elif isinstance(value, Link):              elif isinstance(value, numarray.NumArray):
487                  value.toDom(document, val)                  shape = value.getshape()
488                    if isinstance(shape, tuple):
489                        size = reduce(operator.mul, shape)
490                        shape = ' '.join(map(str, shape))
491                    else:
492                        size = shape
493                        shape = str(shape)
494    
495                    arraytype = value.type()
496                    numarrayElement = document.createElement('NumArray')
497                    numarrayElement.appendChild(dataNode(document, 'ArrayType', str(arraytype)))
498                    numarrayElement.appendChild(dataNode(document, 'Shape', shape))
499                    numarrayElement.appendChild(dataNode(document, 'Data', ' '.join(
500                        [str(x) for x in numarray.reshape(value, size)])))
501                    val.appendChild(numarrayElement)
502                  param.appendChild(val)                  param.appendChild(val)
503              elif isinstance(value,StringType):              elif isinstance (value, list):
504                  param.appendChild(dataNode(document, 'Value', value))                  param.appendChild(dataNode(document, 'Value', ' '.join(
505                        [str(x) for x in value])
506                    ))
507              else:              else:
508                  param.appendChild(dataNode(document, 'Value', str(value)))                  param.appendChild(dataNode(document, 'Value', str(value)))
509    
# Line 453  class ParameterSet(LinkableObject): Line 516  class ParameterSet(LinkableObject):
516              """              """
517              Remove the empty nodes from the children of this node.              Remove the empty nodes from the children of this node.
518              """              """
519              return [x for x in node.childNodes              ret = []
520                      if not isinstance(x, minidom.Text) or x.nodeValue.strip()]              for x in node.childNodes:
521                    if isinstance(x, minidom.Text):
522                        if x.nodeValue.strip():
523                            ret.append(x)
524                    else:
525                        ret.append(x)
526                return ret
527    
528          def _floatfromValue(doc):          def _floatfromValue(doc):
529              return float(doc.nodeValue.strip())              return float(doc.nodeValue.strip())
# Line 466  class ParameterSet(LinkableObject): Line 535  class ParameterSet(LinkableObject):
535              return int(doc.nodeValue.strip())              return int(doc.nodeValue.strip())
536    
537          def _boolfromValue(doc):          def _boolfromValue(doc):
538              return bool(doc.nodeValue.strip())              return _boolfromstring(doc.nodeValue.strip())
539          
540            def _nonefromValue(doc):
541                return None
542    
543            def _numarrayfromValue(doc):
544                for node in _children(doc):
545                    if node.tagName == 'ArrayType':
546                        arraytype = node.firstChild.nodeValue.strip()
547                    if node.tagName == 'Shape':
548                        shape = node.firstChild.nodeValue.strip()
549                        shape = [int(x) for x in shape.split()]
550                    if node.tagName == 'Data':
551                        data = node.firstChild.nodeValue.strip()
552                        data = [float(x) for x in data.split()]
553                return numarray.reshape(numarray.array(data, type=getattr(numarray, arraytype)),
554                                        shape)
555          
556            def _listfromValue(doc):
557                return [_boolfromstring(x) for x in doc.nodeValue.split()]
558    
559    
560            def _boolfromstring(s):
561                if s == 'True':
562                    return True
563                else:
564                    return False
565          # Mapping from text types in the xml to methods used to process trees of that type          # Mapping from text types in the xml to methods used to process trees of that type
566          ptypemap = {"Simulation": Simulation.fromDom,          ptypemap = {"Simulation": Simulation.fromDom,
567                      "Model":Model.fromDom,                      "Model":Model.fromDom,
# Line 476  class ParameterSet(LinkableObject): Line 570  class ParameterSet(LinkableObject):
570                      "float":_floatfromValue,                      "float":_floatfromValue,
571                      "int":_intfromValue,                      "int":_intfromValue,
572                      "str":_stringfromValue,                      "str":_stringfromValue,
573                      "bool":_boolfromValue                      "bool":_boolfromValue,
574                        "list":_listfromValue,
575                        "NumArray":_numarrayfromValue,
576                        "NoneType":_nonefromValue,
577                      }                      }
578    
579  #        print doc.toxml()  #        print doc.toxml()
# Line 493  class ParameterSet(LinkableObject): Line 590  class ParameterSet(LinkableObject):
590    
591                  if childnode.tagName == "Value":                  if childnode.tagName == "Value":
592                      nodes = _children(childnode)                      nodes = _children(childnode)
593                    #    if ptype == 'NumArray':
594                     #       pvalue = _numarrayfromValue(nodes)
595                     #   else:
596                      pvalue = ptypemap[ptype](nodes[0])                      pvalue = ptypemap[ptype](nodes[0])
597    
598              parameters[pname] = pvalue              parameters[pname] = pvalue
# Line 555  class Model(ParameterSet): Line 655  class Model(ParameterSet):
655      """      """
656          pset = document.createElement('Model')          pset = document.createElement('Model')
657          pset.setAttribute('type', self.__class__.__name__)          pset.setAttribute('type', self.__class__.__name__)
658            if not self.__class__.__module__.startswith('esys.escript'):
659                pset.setAttribute('module', self.__class__.__module__)
660          node.appendChild(pset)          node.appendChild(pset)
661          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
662    
# Line 644  class Simulation(Model): Line 746  class Simulation(Model):
746            
747      FAILED_TIME_STEPS_MAX=20      FAILED_TIME_STEPS_MAX=20
748      MAX_ITER_STEPS=50      MAX_ITER_STEPS=50
749        MAX_CHANGE_OF_DT=2.
750            
751      def __init__(self, models=[], **kwargs):      def __init__(self, models=[], **kwargs):
752          """          """
# Line 685  class Simulation(Model): Line 788  class Simulation(Model):
788      Sets the i-th model.      Sets the i-th model.
789      """      """
790          if not isinstance(value,Model):          if not isinstance(value,Model):
791              raise ValueError("assigned value is not a Model")              raise ValueError,"assigned value is not a Model but instance of %s"%(value.__class__.__name__,)
792          for j in range(max(i-len(self.__models)+1,0)):          for j in range(max(i-len(self.__models)+1,0)):
793              self.__models.append(None)              self.__models.append(None)
794          self.__models[i]=value          self.__models[i]=value
# Line 720  class Simulation(Model): Line 823  class Simulation(Model):
823          document, rootnode = esysDoc()          document, rootnode = esysDoc()
824          self.toDom(document, rootnode)          self.toDom(document, rootnode)
825          targetsList = document.getElementsByTagName('Target')          targetsList = document.getElementsByTagName('Target')
826          for i in targetsList:          
827              targetId = int(i.firstChild.nodeValue.strip())          for element in targetsList:
828                targetId = int(element.firstChild.nodeValue.strip())
829                if document.getElementById(str(targetId)):
830                    continue
831              targetObj = LinkableObjectRegistry[targetId]              targetObj = LinkableObjectRegistry[targetId]
832              targetObj.toDom(document, rootnode)              targetObj.toDom(document, rootnode)
833          ostream.write(document.toprettyxml())          ostream.write(document.toprettyxml())
# Line 733  class Simulation(Model): Line 839  class Simulation(Model):
839          This is the minimum over the time step sizes of all models.          This is the minimum over the time step sizes of all models.
840      """      """
841          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])
842          print "%s: safe step size is %e."%(str(self),out)          #print "%s: safe step size is %e."%(str(self),out)
843          return out          return out
844            
845      def doInitialization(self):      def doInitialization(self):
# Line 827  class Simulation(Model): Line 933  class Simulation(Model):
933          while not self.finalize():          while not self.finalize():
934              step_fail_counter=0              step_fail_counter=0
935              iteration_fail_counter=0              iteration_fail_counter=0
936              dt_new=self.getSafeTimeStepSize(dt)              if self.n==0:
937                    dt_new=self.getSafeTimeStepSize(dt)
938                else:
939                    dt_new=min(max(self.getSafeTimeStepSize(dt),dt/self.MAX_CHANGE_OF_DT),dt*self.MAX_CHANGE_OF_DT)
940              self.trace("%d. time step %e (step size %e.)" % (self.n+1,self.tn+dt_new,dt_new))              self.trace("%d. time step %e (step size %e.)" % (self.n+1,self.tn+dt_new,dt_new))
941              end_of_step=False              end_of_step=False
942              while not end_of_step:              while not end_of_step:
943                 end_of_step=True                 end_of_step=True
944                 if not dt_new>0:                 if not dt_new>0:
945                    raise NonPositiveStepSizeError("non-positive step size in step %d",self.n+1)                    raise NonPositiveStepSizeError("non-positive step size in step %d"%(self.n+1))
946                 try:                 try:
947                    self.doStepPreprocessing(dt_new)                    self.doStepPreprocessing(dt_new)
948                    self.doStep(dt_new)                    self.doStep(dt_new)
# Line 843  class Simulation(Model): Line 952  class Simulation(Model):
952                    end_of_step=False                    end_of_step=False
953                    iteration_fail_counter+=1                    iteration_fail_counter+=1
954                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:
955                             raise SimulationBreakDownError("reduction of time step to achieve convergence failed.")                             raise SimulationBreakDownError("reduction of time step to achieve convergence failed after %s steps."%self.FAILED_TIME_STEPS_MAX)
956                    self.trace("iteration fails. time step is repeated with new step size.")                    self.trace("Iteration failed. Time step is repeated with new step size %s."%dt_new)
957                 except FailedTimeStepError:                 except FailedTimeStepError:
958                    dt_new=self.getSafeTimeStepSize(dt)                    dt_new=self.getSafeTimeStepSize(dt)
959                    end_of_step=False                    end_of_step=False
960                    step_fail_counter+=1                    step_fail_counter+=1
961                    self.trace("time step is repeated.")                    self.trace("Time step is repeated with new time step size %s."%dt_new)
962                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:
963                          raise SimulationBreakDownError("time integration is given up after %d attempts."%step_fail_counter)                          raise SimulationBreakDownError("Time integration is given up after %d attempts."%step_fail_counter)
964              dt=dt_new              dt=dt_new
965              if not check_point==None:              if not check_point==None:
966                  if n%check_point==0:                  if n%check_point==0:

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

  ViewVC Help
Powered by ViewVC 1.1.26