/[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 871 by elspeth, Sat Oct 14 08:25:54 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 424  class ParameterSet(LinkableObject): Line 468  class ParameterSet(LinkableObject):
468          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
469    
470      def _parametersToDom(self, document, node):      def _parametersToDom(self, document, node):
471          node.setAttribute ('id', str(self.id))          node.setAttribute('id', str(self.id))
472            node.setIdAttribute("id")
473          for name,value in self:          for name,value in self:
474              param = document.createElement('Parameter')              param = document.createElement('Parameter')
475              param.setAttribute('type', value.__class__.__name__)              param.setAttribute('type', value.__class__.__name__)
# Line 439  class ParameterSet(LinkableObject): Line 484  class ParameterSet(LinkableObject):
484              elif isinstance(value, Link):              elif isinstance(value, Link):
485                  value.toDom(document, val)                  value.toDom(document, val)
486                  param.appendChild(val)                  param.appendChild(val)
487                elif isinstance(value, numarray.NumArray):
488                    shape = value.getshape()
489                    if isinstance(shape, tuple):
490                        size = reduce(operator.mul, shape)
491                        shape = ' '.join(map(str, shape))
492                    else:
493                        size = shape
494                        shape = str(shape)
495    
496                    arraytype = value.type()
497                    val.appendChild(dataNode(document, 'ArrayType', str(arraytype)))
498                    val.appendChild(dataNode(document, 'Shape', shape))
499                    val.appendChild(dataNode(document, 'Data', ' '.join(
500                        [str(x) for x in numarray.reshape(value, size)])))
501                    param.appendChild(val)
502              elif isinstance(value,StringType):              elif isinstance(value,StringType):
503                  param.appendChild(dataNode(document, 'Value', value))                  param.appendChild(dataNode(document, 'Value', value))
504              else:              else:
# Line 453  class ParameterSet(LinkableObject): Line 513  class ParameterSet(LinkableObject):
513              """              """
514              Remove the empty nodes from the children of this node.              Remove the empty nodes from the children of this node.
515              """              """
516              return [x for x in node.childNodes              ret = []
517                      if not isinstance(x, minidom.Text) or x.nodeValue.strip()]              for x in node.childNodes:
518                    if isinstance(x, minidom.Text):
519                        if x.nodeValue.strip():
520                            ret.append(x)
521                    else:
522                        ret.append(x)
523                return ret
524    
525          def _floatfromValue(doc):          def _floatfromValue(doc):
526              return float(doc.nodeValue.strip())              return float(doc.nodeValue.strip())
# Line 467  class ParameterSet(LinkableObject): Line 533  class ParameterSet(LinkableObject):
533    
534          def _boolfromValue(doc):          def _boolfromValue(doc):
535              return bool(doc.nodeValue.strip())              return bool(doc.nodeValue.strip())
536    
537            def _nonefromValue(doc):
538                return None
539    
540            def _numarrayfromValue(doc):
541                for node in doc:
542                    if node.tagName == 'ArrayType':
543                        arraytype = node.firstChild.nodeValue.strip()
544                    if node.tagName == 'Shape':
545                        shape = node.firstChild.nodeValue.strip()
546                        shape = [int(x) for x in shape.split()]
547                    if node.tagName == 'Data':
548                        data = node.firstChild.nodeValue.strip()
549                        data = [float(x) for x in data.split()]
550                return numarray.reshape(numarray.array(data, type=getattr(numarray, arraytype)),
551                                        shape)
552                
553          # 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
554          ptypemap = {"Simulation": Simulation.fromDom,          ptypemap = {"Simulation": Simulation.fromDom,
# Line 476  class ParameterSet(LinkableObject): Line 558  class ParameterSet(LinkableObject):
558                      "float":_floatfromValue,                      "float":_floatfromValue,
559                      "int":_intfromValue,                      "int":_intfromValue,
560                      "str":_stringfromValue,                      "str":_stringfromValue,
561                      "bool":_boolfromValue                      "bool":_boolfromValue,
562                        "NoneType":_nonefromValue,
563                      }                      }
564    
565  #        print doc.toxml()  #        print doc.toxml()
# Line 493  class ParameterSet(LinkableObject): Line 576  class ParameterSet(LinkableObject):
576    
577                  if childnode.tagName == "Value":                  if childnode.tagName == "Value":
578                      nodes = _children(childnode)                      nodes = _children(childnode)
579                      pvalue = ptypemap[ptype](nodes[0])                      if ptype == 'NumArray':
580                            pvalue = _numarrayfromValue(nodes)
581                        else:
582                            pvalue = ptypemap[ptype](nodes[0])
583    
584              parameters[pname] = pvalue              parameters[pname] = pvalue
585    
# Line 555  class Model(ParameterSet): Line 641  class Model(ParameterSet):
641      """      """
642          pset = document.createElement('Model')          pset = document.createElement('Model')
643          pset.setAttribute('type', self.__class__.__name__)          pset.setAttribute('type', self.__class__.__name__)
644            if not self.__class__.__module__.startswith('esys.escript'):
645                pset.setAttribute('module', self.__class__.__module__)
646          node.appendChild(pset)          node.appendChild(pset)
647          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
648    
# Line 644  class Simulation(Model): Line 732  class Simulation(Model):
732            
733      FAILED_TIME_STEPS_MAX=20      FAILED_TIME_STEPS_MAX=20
734      MAX_ITER_STEPS=50      MAX_ITER_STEPS=50
735        MAX_CHANGE_OF_DT=2.
736            
737      def __init__(self, models=[], **kwargs):      def __init__(self, models=[], **kwargs):
738          """          """
# Line 685  class Simulation(Model): Line 774  class Simulation(Model):
774      Sets the i-th model.      Sets the i-th model.
775      """      """
776          if not isinstance(value,Model):          if not isinstance(value,Model):
777              raise ValueError("assigned value is not a Model")              raise ValueError,"assigned value is not a Model but instance of %s"%(value.__class__.__name__,)
778          for j in range(max(i-len(self.__models)+1,0)):          for j in range(max(i-len(self.__models)+1,0)):
779              self.__models.append(None)              self.__models.append(None)
780          self.__models[i]=value          self.__models[i]=value
# Line 720  class Simulation(Model): Line 809  class Simulation(Model):
809          document, rootnode = esysDoc()          document, rootnode = esysDoc()
810          self.toDom(document, rootnode)          self.toDom(document, rootnode)
811          targetsList = document.getElementsByTagName('Target')          targetsList = document.getElementsByTagName('Target')
812          for i in targetsList:          
813              targetId = int(i.firstChild.nodeValue.strip())          for element in targetsList:
814                targetId = int(element.firstChild.nodeValue.strip())
815                if document.getElementById(str(targetId)):
816                    continue
817              targetObj = LinkableObjectRegistry[targetId]              targetObj = LinkableObjectRegistry[targetId]
818              targetObj.toDom(document, rootnode)              targetObj.toDom(document, rootnode)
819          ostream.write(document.toprettyxml())          ostream.write(document.toprettyxml())
# Line 733  class Simulation(Model): Line 825  class Simulation(Model):
825          This is the minimum over the time step sizes of all models.          This is the minimum over the time step sizes of all models.
826      """      """
827          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])
828          print "%s: safe step size is %e."%(str(self),out)          #print "%s: safe step size is %e."%(str(self),out)
829          return out          return out
830            
831      def doInitialization(self):      def doInitialization(self):
# Line 827  class Simulation(Model): Line 919  class Simulation(Model):
919          while not self.finalize():          while not self.finalize():
920              step_fail_counter=0              step_fail_counter=0
921              iteration_fail_counter=0              iteration_fail_counter=0
922              dt_new=self.getSafeTimeStepSize(dt)              if self.n==0:
923                    dt_new=self.getSafeTimeStepSize(dt)
924                else:
925                    dt_new=min(max(self.getSafeTimeStepSize(dt),dt/self.MAX_CHANGE_OF_DT),dt*self.MAX_CHANGE_OF_DT)
926              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))
927              end_of_step=False              end_of_step=False
928              while not end_of_step:              while not end_of_step:
929                 end_of_step=True                 end_of_step=True
930                 if not dt_new>0:                 if not dt_new>0:
931                    raise NonPositiveStepSizeError("non-positive step size in step %d",self.n+1)                    raise NonPositiveStepSizeError("non-positive step size in step %d"%(self.n+1))
932                 try:                 try:
933                    self.doStepPreprocessing(dt_new)                    self.doStepPreprocessing(dt_new)
934                    self.doStep(dt_new)                    self.doStep(dt_new)
# Line 843  class Simulation(Model): Line 938  class Simulation(Model):
938                    end_of_step=False                    end_of_step=False
939                    iteration_fail_counter+=1                    iteration_fail_counter+=1
940                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if iteration_fail_counter>self.FAILED_TIME_STEPS_MAX:
941                             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)
942                    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)
943                 except FailedTimeStepError:                 except FailedTimeStepError:
944                    dt_new=self.getSafeTimeStepSize(dt)                    dt_new=self.getSafeTimeStepSize(dt)
945                    end_of_step=False                    end_of_step=False
946                    step_fail_counter+=1                    step_fail_counter+=1
947                    self.trace("time step is repeated.")                    self.trace("Time step is repeated with new time step size %s."%dt_new)
948                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:                    if step_fail_counter>self.FAILED_TIME_STEPS_MAX:
949                          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)
950              dt=dt_new              dt=dt_new
951              if not check_point==None:              if not check_point==None:
952                  if n%check_point==0:                  if n%check_point==0:

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

  ViewVC Help
Powered by ViewVC 1.1.26