/[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 838 by gross, Tue Sep 5 22:45:55 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 itertools  import itertools
# Line 73  def parse(xml): Line 95  def parse(xml):
95    
96      return sim      return sim
97    
98    def importName(modulename, name):
99        """ Import a named object from a module in the context of this function,
100            which means you should use fully qualified module paths.
101            
102            Return None on failure.
103    
104            This function from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52241
105        """
106        module = __import__(modulename, globals(), locals(), [name])
107            
108        try:
109            return vars(module)[name]
110        except KeyError:
111            raise ImportError("Could not import %s from %s" % (name, modulename))
112    
113  def getComponent(doc):  def getComponent(doc):
114      """      """
115      Used to get components of Simualtions, Models.      Used to get components of Simualtions, Models.
# Line 84  def getComponent(doc): Line 121  def getComponent(doc):
121                  if node.getAttribute("type") == 'Simulation':                  if node.getAttribute("type") == 'Simulation':
122                      return Simulation.fromDom(node)                      return Simulation.fromDom(node)
123              if node.tagName == 'Model':              if node.tagName == 'Model':
124                  model_type = node.getAttribute("type")                  if (node.getAttribute("module")):
125                  model_subclasses = Model.__subclasses__()                      model_module = node.getAttribute("module")
126                  for model in model_subclasses:                      model_type = node.getAttribute("type")
127                      if model_type == model.__name__:                      return importName(model_module, model_type).fromDom(node)
128                          return Model.fromDom(node)                  else:
129                        model_type = node.getAttribute("type")
130                        model_subclasses = Model.__subclasses__()
131                        for model in model_subclasses:
132                            if model_type == model.__name__:
133                                return Model.fromDom(node)
134              if node.tagName == 'ParameterSet':              if node.tagName == 'ParameterSet':
135                  parameter_type = node.getAttribute("type")                  parameter_type = node.getAttribute("type")
136                  return ParameterSet.fromDom(node)                  return ParameterSet.fromDom(node)
# Line 424  class ParameterSet(LinkableObject): Line 466  class ParameterSet(LinkableObject):
466          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
467    
468      def _parametersToDom(self, document, node):      def _parametersToDom(self, document, node):
469          node.setAttribute ('id', str(self.id))          node.setAttribute('id', str(self.id))
470            node.setIdAttribute("id")
471          for name,value in self:          for name,value in self:
472              param = document.createElement('Parameter')              param = document.createElement('Parameter')
473              param.setAttribute('type', value.__class__.__name__)              param.setAttribute('type', value.__class__.__name__)
# Line 467  class ParameterSet(LinkableObject): Line 510  class ParameterSet(LinkableObject):
510    
511          def _boolfromValue(doc):          def _boolfromValue(doc):
512              return bool(doc.nodeValue.strip())              return bool(doc.nodeValue.strip())
513    
514            def _nonefromValue(doc):
515                return None
516                
517          # 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
518          ptypemap = {"Simulation": Simulation.fromDom,          ptypemap = {"Simulation": Simulation.fromDom,
# Line 476  class ParameterSet(LinkableObject): Line 522  class ParameterSet(LinkableObject):
522                      "float":_floatfromValue,                      "float":_floatfromValue,
523                      "int":_intfromValue,                      "int":_intfromValue,
524                      "str":_stringfromValue,                      "str":_stringfromValue,
525                      "bool":_boolfromValue                      "bool":_boolfromValue,
526                        "NoneType":_nonefromValue
527                      }                      }
528    
529  #        print doc.toxml()  #        print doc.toxml()
# Line 555  class Model(ParameterSet): Line 602  class Model(ParameterSet):
602      """      """
603          pset = document.createElement('Model')          pset = document.createElement('Model')
604          pset.setAttribute('type', self.__class__.__name__)          pset.setAttribute('type', self.__class__.__name__)
605            if not self.__class__.__module__.startswith('esys.escript'):
606                pset.setAttribute('module', self.__class__.__module__)
607          node.appendChild(pset)          node.appendChild(pset)
608          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
609    
# Line 644  class Simulation(Model): Line 693  class Simulation(Model):
693            
694      FAILED_TIME_STEPS_MAX=20      FAILED_TIME_STEPS_MAX=20
695      MAX_ITER_STEPS=50      MAX_ITER_STEPS=50
696        MAX_CHANGE_OF_DT=2.
697            
698      def __init__(self, models=[], **kwargs):      def __init__(self, models=[], **kwargs):
699          """          """
# Line 685  class Simulation(Model): Line 735  class Simulation(Model):
735      Sets the i-th model.      Sets the i-th model.
736      """      """
737          if not isinstance(value,Model):          if not isinstance(value,Model):
738              raise ValueError("assigned value is not a Model")              raise ValueError,"assigned value is not a Model but instance of %s"%(value.__class__.__name__,)
739          for j in range(max(i-len(self.__models)+1,0)):          for j in range(max(i-len(self.__models)+1,0)):
740              self.__models.append(None)              self.__models.append(None)
741          self.__models[i]=value          self.__models[i]=value
# Line 720  class Simulation(Model): Line 770  class Simulation(Model):
770          document, rootnode = esysDoc()          document, rootnode = esysDoc()
771          self.toDom(document, rootnode)          self.toDom(document, rootnode)
772          targetsList = document.getElementsByTagName('Target')          targetsList = document.getElementsByTagName('Target')
773          for i in targetsList:          
774              targetId = int(i.firstChild.nodeValue.strip())          for element in targetsList:
775                targetId = int(element.firstChild.nodeValue.strip())
776                if document.getElementById(str(targetId)):
777                    continue
778              targetObj = LinkableObjectRegistry[targetId]              targetObj = LinkableObjectRegistry[targetId]
779              targetObj.toDom(document, rootnode)              targetObj.toDom(document, rootnode)
780          ostream.write(document.toprettyxml())          ostream.write(document.toprettyxml())
# Line 733  class Simulation(Model): Line 786  class Simulation(Model):
786          This is the minimum over the time step sizes of all models.          This is the minimum over the time step sizes of all models.
787      """      """
788          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])
789          print "%s: safe step size is %e."%(str(self),out)          #print "%s: safe step size is %e."%(str(self),out)
790          return out          return out
791            
792      def doInitialization(self):      def doInitialization(self):
# Line 827  class Simulation(Model): Line 880  class Simulation(Model):
880          while not self.finalize():          while not self.finalize():
881              step_fail_counter=0              step_fail_counter=0
882              iteration_fail_counter=0              iteration_fail_counter=0
883              dt_new=self.getSafeTimeStepSize(dt)              if self.n==0:
884                    dt_new=self.getSafeTimeStepSize(dt)
885                else:
886                    dt_new=min(max(self.getSafeTimeStepSize(dt),dt/self.MAX_CHANGE_OF_DT),dt*self.MAX_CHANGE_OF_DT)
887              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))
888              end_of_step=False              end_of_step=False
889              while not end_of_step:              while not end_of_step:
890                 end_of_step=True                 end_of_step=True
891                 if not dt_new>0:                 if not dt_new>0:
892                    raise NonPositiveStepSizeError("non-positive step size in step %d",self.n+1)                    raise NonPositiveStepSizeError("non-positive step size in step %d"%(self.n+1))
893                 try:                 try:
894                    self.doStepPreprocessing(dt_new)                    self.doStepPreprocessing(dt_new)
895                    self.doStep(dt_new)                    self.doStep(dt_new)
# Line 843  class Simulation(Model): Line 899  class Simulation(Model):
899                    end_of_step=False                    end_of_step=False
900                    iteration_fail_counter+=1                    iteration_fail_counter+=1
901                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:
902                             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)
903                    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)
904                 except FailedTimeStepError:                 except FailedTimeStepError:
905                    dt_new=self.getSafeTimeStepSize(dt)                    dt_new=self.getSafeTimeStepSize(dt)
906                    end_of_step=False                    end_of_step=False
907                    step_fail_counter+=1                    step_fail_counter+=1
908                    self.trace("time step is repeated.")                    self.trace("Time step is repeated with new time step size %s."%dt_new)
909                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:
910                          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)
911              dt=dt_new              dt=dt_new
912              if not check_point==None:              if not check_point==None:
913                  if n%check_point==0:                  if n%check_point==0:

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

  ViewVC Help
Powered by ViewVC 1.1.26