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

revision 148 by jgs, Fri Aug 12 01:45:47 2005 UTC revision 149 by jgs, Thu Sep 1 03:31:39 2005 UTC
# Line 15  from xml.dom import minidom Line 15  from xml.dom import minidom
15    
16  def dataNode(document, tagName, data):  def dataNode(document, tagName, data):
17      """      """
18      dataNodes are the building blocks of the xml documents constructed in      C{dataNode}s are the building blocks of the xml documents constructed in
19      this module. document is the current xml document, tagName is the      this module.  
20      associated xml tag, and data is the values in the tag.      
21        @param document: the current xml document
22        @param tagName: the associated xml tag
23        @param data: the values in the tag
24      """      """
25      t = document.createTextNode(str(data))      t = document.createTextNode(str(data))
26      n = document.createElement(tagName)      n = document.createElement(tagName)
# Line 57  def registerLink(obj_id, l): Line 60  def registerLink(obj_id, l):
60    
61  def parse(xml):  def parse(xml):
62      """      """
63      Generic parse method for EsysXML. Without this, Links don't work.      Generic parse method for EsysXML.  Without this, Links don't work.
64      """      """
65      global LinkRegistry, LinkableObjectRegistry      global LinkRegistry, LinkableObjectRegistry
66      LinkRegistry = []      LinkRegistry = []
# Line 97  def getComponent(doc): Line 100  def getComponent(doc):
100    
101  class Link:  class Link:
102      """      """
103      a Link makes an attribute of an object callable:      A Link makes an attribute of an object callable::
104    
105            o.object()            o.object()
106            o.a=8            o.a=8
107            l=Link(o,"a")            l=Link(o,"a")
# Line 106  class Link: Line 110  class Link:
110            
111      def __init__(self,target,attribute=None):      def __init__(self,target,attribute=None):
112          """          """
113          creates a link to the object target. If attribute is given, the link is          Creates a link to the object target. If attribute is given, the link is
114          establised to this attribute of the target.  Otherwise the attribute is          establised to this attribute of the target.  Otherwise the attribute is
115          undefined.          undefined.
116          """          """
# Line 116  class Link: Line 120  class Link:
120            
121      def setAttributeName(self,attribute):      def setAttributeName(self,attribute):
122          """          """
123          set a new attribute name to be collected from the target object. The          Set a new attribute name to be collected from the target object. The
124          target object must have the attribute with name attribute.          target object must have the attribute with name attribute.
125          """          """
126          if attribute and self.target:          if attribute and self.target:
# Line 130  class Link: Line 134  class Link:
134            
135      def hasDefinedAttributeName(self):      def hasDefinedAttributeName(self):
136          """          """
137          returns true if an attribute name is set          Returns true if an attribute name is set.
138          """          """
139          return self.attribute != None          return self.attribute != None
140            
141      def __repr__(self):      def __repr__(self):
142          """          """
143          returns a string representation of the link          Returns a string representation of the link.
144          """          """
145          if self.hasDefinedAttributeName():          if self.hasDefinedAttributeName():
146              return "<Link to attribute %s of %s>" % (self.attribute, self.target)              return "<Link to attribute %s of %s>" % (self.attribute, self.target)
# Line 145  class Link: Line 149  class Link:
149            
150      def __call__(self,name=None):      def __call__(self,name=None):
151          """          """
152          returns the value of the attribute of the target object. If the          Returns the value of the attribute of the target object. If the
153          atrribute is callable then the return value of the call is returned.          atrribute is callable then the return value of the call is returned.
154          """          """
155          if name:          if name:
# Line 160  class Link: Line 164  class Link:
164    
165      def toDom(self, document, node):      def toDom(self, document, node):
166          """          """
167          toDom method of Link. Creates a Link node and appends it to the current XML          C{toDom} method of Link. Creates a Link node and appends it to the
168          document      current XML document.
169          """          """
170          link = document.createElement('Link')          link = document.createElement('Link')
171          assert (self.target != None), ("Target was none, name was %r" % self.attribute)          assert (self.target != None), ("Target was none, name was %r" % self.attribute)
# Line 183  class Link: Line 187  class Link:
187            
188      def writeXML(self,ostream=stdout):      def writeXML(self,ostream=stdout):
189          """          """
190          writes an XML representation of self to the output stream ostream.          Writes an XML representation of self to the output stream ostream.
191          If ostream is nor present the standart output stream is used.  If          If ostream is nor present the standart output stream is used.  If
192          esysheader==True the esys XML header is written          esysheader==True the esys XML header is written
193          """          """
# Line 196  class Link: Line 200  class Link:
200  class LinkableObject(object):  class LinkableObject(object):
201      """      """
202      An object that allows to link its attributes to attributes of other objects      An object that allows to link its attributes to attributes of other objects
203      via a Link object. For instance      via a Link object. For instance::
204                        
205             p = LinkableObject()             p = LinkableObject()
206             p.x = Link(o,"name")             p.x = Link(o,"name")
207             print p.x             print p.x
208            
209      links attribute x of p to the attribute name of object o.      links attribute C{x} of C{p} to the attribute name of object C{o}.
210    
211      p.x will contain the current value of attribute name of object o.        C{p.x} will contain the current value of attribute C{name} of object
212        C{o}.  
213    
214      If the value of getattr(o, "name") is callable, p.x will rturn the return      If the value of C{getattr(o, "name")} is callable, C{p.x} will return
215      value of the call.      the return value of the call.
216      """      """
217        
218      number_sequence = itertools.count(100)      number_sequence = itertools.count(100)
219            
220      def __init__(self, debug=False):      def __init__(self, debug=False):
221          """ initializes LinkableObject so that we can operate on Links """          """
222        Initializes LinkableObject so that we can operate on Links
223        """
224          self.debug = debug          self.debug = debug
225          self.__linked_attributes={}          self.__linked_attributes={}
226          self.id = self.number_sequence.next()          self.id = self.number_sequence.next()
227            registerLinkableObject(self.id, self)
228    
229      def trace(self, msg):      def trace(self, msg):
230          """ If debugging is on, print the message, otherwise do nothing          """
231        If debugging is on, print the message, otherwise do nothing
232          """          """
233          if self.debug:          if self.debug:
234              print "%s: %s"%(str(self),msg)              print "%s: %s"%(str(self),msg)
235            
236      def __getattr__(self,name):      def __getattr__(self,name):
237          """returns the value of attribute name. If the value is a Link object the          """
238          object is called and the return value is returned."""      Returns the value of attribute name. If the value is a Link object the
239            object is called and the return value is returned.
240        """
241          out = self.getAttributeObject(name)          out = self.getAttributeObject(name)
242          if isinstance(out,Link):          if isinstance(out,Link):
243              return out()              return out()
# Line 234  class LinkableObject(object): Line 245  class LinkableObject(object):
245              return out              return out
246            
247      def getAttributeObject(self,name):      def getAttributeObject(self,name):
248          """return the object stored for attribute name."""          """
249        Return the object stored for attribute name.
250        """
251    
252          if self.__dict__.has_key(name):          if self.__dict__.has_key(name):
253              return self.__dict__[name]              return self.__dict__[name]
# Line 248  class LinkableObject(object): Line 261  class LinkableObject(object):
261          raise AttributeError,"No attribute %s."%name          raise AttributeError,"No attribute %s."%name
262            
263      def hasAttribute(self,name):      def hasAttribute(self,name):
264          """returns True if self as attribute name"""          """
265        Returns True if self as attribute name.
266        """
267          return self.__dict__.has_key(name) or self.__linked_attributes.has_key(name) or  self.__class__.__dict__.has_key(name)          return self.__dict__.has_key(name) or self.__linked_attributes.has_key(name) or  self.__class__.__dict__.has_key(name)
268    
269      def __setattr__(self,name,value):      def __setattr__(self,name,value):
270          """sets the value for attribute name. If value is a Link the target          """
271          attribute is set to name if no attribute has been specified."""      Sets the value for attribute name. If value is a Link the target
272            attribute is set to name if no attribute has been specified.
273        """
274    
275          if self.__dict__.has_key(name):          if self.__dict__.has_key(name):
276              del self.__dict__[name]              del self.__dict__[name]
# Line 269  class LinkableObject(object): Line 285  class LinkableObject(object):
285              self.__dict__[name] = value              self.__dict__[name] = value
286            
287      def __delattr__(self,name):      def __delattr__(self,name):
288          """removes the attribute name."""          """
289        Removes the attribute name.
290        """
291    
292          if self.__linked_attributes.has_key[name]:          if self.__linked_attributes.has_key[name]:
293              del self.__linked_attributes[name]              del self.__linked_attributes[name]
# Line 292  class _ParameterIterator: Line 310  class _ParameterIterator:
310          return self          return self
311    
312  class ParameterSet(LinkableObject):  class ParameterSet(LinkableObject):
313      """a class which allows to emphazise attributes to be written and read to XML      """
314        A class which allows to emphazise attributes to be written and read to XML
315                
316         Leaves of  an ESySParameters objects can be      Leaves of an ESySParameters object can be:
317            
318              a real number       - a real number
319              a integer number       - a integer number
320              a string       - a string
321              a boolean value       - a boolean value
322              a ParameterSet object       - a ParameterSet object
323              a Simulation object       - a Simulation object
324              a Model object       - a Model object
325              any other object (not considered by writeESySXML and writeXML)       - any other object (not considered by writeESySXML and writeXML)
326            
327             Example how to create an ESySParameters object:      Example how to create an ESySParameters object::
328            
329                   p11=ParameterSet(gamma1=1.,gamma2=2.,gamma3=3.)          p11=ParameterSet(gamma1=1.,gamma2=2.,gamma3=3.)
330                   p1=ParameterSet(dim=2,tol_v=0.001,output_file="/tmp/u.%3.3d.dx",runFlag=True,parm11=p11)          p1=ParameterSet(dim=2,tol_v=0.001,output_file="/tmp/u.%3.3d.dx",runFlag=True,parm11=p11)
331                   parm=ParameterSet(parm1=p1,parm2=ParameterSet(alpha=Link(p11,"gamma1")))          parm=ParameterSet(parm1=p1,parm2=ParameterSet(alpha=Link(p11,"gamma1")))
332            
333             This can be accessed as      This can be accessed as::
334            
335                   parm.parm1.gamma=0.      parm.parm1.gamma=0.
336                   parm.parm1.dim=2          parm.parm1.dim=2
337                   parm.parm1.tol_v=0.001          parm.parm1.tol_v=0.001
338                   parm.parm1.output_file="/tmp/u.%3.3d.dx"          parm.parm1.output_file="/tmp/u.%3.3d.dx"
339                   parm.parm1.runFlag=True          parm.parm1.runFlag=True
340                   parm.parm1.parm11.gamma1=1.          parm.parm1.parm11.gamma1=1.
341                   parm.parm1.parm11.gamma2=2.          parm.parm1.parm11.gamma2=2.
342                   parm.parm1.parm11.gamma3=3.          parm.parm1.parm11.gamma3=3.
343                   parm.parm2.alpha=1. (value of parm.parm1.parm11.gamma1)          parm.parm2.alpha=1. (value of parm.parm1.parm11.gamma1)
               
344      """      """
345      def __init__(self, parameters=[], **kwargs):      def __init__(self, parameters=[], **kwargs):
346          """creates a ParameterSet with parameters parameters"""          """
347        Creates a ParameterSet with parameters parameters.
348        """
349          LinkableObject.__init__(self, **kwargs)          LinkableObject.__init__(self, **kwargs)
350          self.parameters = set()          self.parameters = set()
351          self.declareParameters(parameters)          self.declareParameters(parameters)
# Line 335  class ParameterSet(LinkableObject): Line 355  class ParameterSet(LinkableObject):
355                              [(p, getattr(self, p, None)) for p in self.parameters])                              [(p, getattr(self, p, None)) for p in self.parameters])
356            
357      def declareParameter(self,**parameters):      def declareParameter(self,**parameters):
358          """declares a new parameter(s) and its (their) inital value."""          """
359        Declares a new parameter(s) and its (their) initial value.
360        """
361          self.declareParameters(parameters)          self.declareParameters(parameters)
362            
363      def declareParameters(self,parameters):      def declareParameters(self,parameters):
364          """declares a set of parameters. parameters can be a list, a dictonary or a ParameterSet."""          """
365        Declares a set of parameters. parameters can be a list, a dictionary
366        or a ParameterSet.
367        """
368          if isinstance(parameters,ListType):          if isinstance(parameters,ListType):
369              parameters = zip(parameters, itertools.repeat(None))              parameters = zip(parameters, itertools.repeat(None))
370          if isinstance(parameters,DictType):          if isinstance(parameters,DictType):
# Line 352  class ParameterSet(LinkableObject): Line 377  class ParameterSet(LinkableObject):
377              self.trace("parameter %s has been declared."%prm)              self.trace("parameter %s has been declared."%prm)
378    
379      def releaseParameters(self,name):      def releaseParameters(self,name):
380          """removes parameter name from the paramameters"""          """
381        Removes parameter name from the paramameters.
382        """
383          if self.isParameter(name):          if self.isParameter(name):
384              self.parameters.remove(name)              self.parameters.remove(name)
385              self.trace("parameter %s has been removed."%name)              self.trace("parameter %s has been removed."%name)
386            
387      def __iter__(self):      def __iter__(self):
388          """creates an iterator over the parameter and their values"""          """
389        Creates an iterator over the parameter and their values.
390        """
391          return _ParameterIterator(self)          return _ParameterIterator(self)
392            
393      def showParameters(self):      def showParameters(self):
394          """returns a descrition of the parameters"""                  """
395        Returns a descrition of the parameters.
396        """        
397          out="{"          out="{"
398          notfirst=False          notfirst=False
399          for i,v in self:          for i,v in self:
# Line 375  class ParameterSet(LinkableObject): Line 406  class ParameterSet(LinkableObject):
406          return out+"}"          return out+"}"
407            
408      def __delattr__(self,name):      def __delattr__(self,name):
409          """removes the attribute name."""          """
410        Removes the attribute name.
411        """
412          LinkableObject.__delattr__(self,name)          LinkableObject.__delattr__(self,name)
413          try:          try:
414              self.releaseParameter(name)              self.releaseParameter(name)
# Line 383  class ParameterSet(LinkableObject): Line 416  class ParameterSet(LinkableObject):
416              pass              pass
417    
418      def toDom(self, document, node):      def toDom(self, document, node):
419          """ toDom method of ParameterSet class """          """
420        C{toDom} method of ParameterSet class.
421        """
422          pset = document.createElement('ParameterSet')          pset = document.createElement('ParameterSet')
423          node.appendChild(pset)          node.appendChild(pset)
424          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
# Line 416  class ParameterSet(LinkableObject): Line 451  class ParameterSet(LinkableObject):
451          # Define a host of helper functions to assist us.          # Define a host of helper functions to assist us.
452          def _children(node):          def _children(node):
453              """              """
454              Remove the empty nodes from the children of this node              Remove the empty nodes from the children of this node.
455              """              """
456              return [x for x in node.childNodes              return [x for x in node.childNodes
457                      if not isinstance(x, minidom.Text) or x.nodeValue.strip()]                      if not isinstance(x, minidom.Text) or x.nodeValue.strip()]
# Line 471  class ParameterSet(LinkableObject): Line 506  class ParameterSet(LinkableObject):
506      fromDom = classmethod(fromDom)      fromDom = classmethod(fromDom)
507            
508      def writeXML(self,ostream=stdout):      def writeXML(self,ostream=stdout):
509          """writes the object as an XML object into an output stream"""          """
510        Writes the object as an XML object into an output stream.
511        """
512          # ParameterSet(d) with d[Name]=Value          # ParameterSet(d) with d[Name]=Value
513          document, node = esysDoc()          document, node = esysDoc()
514          self.toDom(document, node)          self.toDom(document, node)
# Line 479  class ParameterSet(LinkableObject): Line 516  class ParameterSet(LinkableObject):
516    
517  class Model(ParameterSet):  class Model(ParameterSet):
518      """      """
519        A Model object represents a processess marching over time until a
520      A Model object represents a processess marching over time      finalizing condition is fullfilled. At each time step an iterative
521      until a finalizing condition is fullfilled. At each time step an iterative      process can be performed and the time step size can be controlled. A
522      process can be performed and the time step size can be controlled. A Model has      Model has the following work flow::
     the following work flow:  
523    
524            doInitialization()            doInitialization()
525            while not finalize():            while not finalize():
# Line 493  class Model(ParameterSet): Line 529  class Model(ParameterSet):
529                 doStepPostprocessing(dt)                 doStepPostprocessing(dt)
530            doFinalization()            doFinalization()
531    
532            where doInitialization,finalize, getSafeTimeStepSize, doStepPreprocessing, terminateIteration, doStepPostprocessing, doFinalization      where C{doInitialization}, C{finalize}, C{getSafeTimeStepSize},
533            are methods of the particular instance of a Model. The default implementations of these methods have to be overwritten by      C{doStepPreprocessing}, C{terminateIteration}, C{doStepPostprocessing},
534            the subclass implementinf a Model.      C{doFinalization} are methods of the particular instance of a Model. The
535        default implementations of these methods have to be overwritten by the
536        subclass implementing a Model.
537      """      """
538    
539      UNDEF_DT=1.e300      UNDEF_DT=1.e300
540    
541      def __init__(self,parameters=[],**kwarg):      def __init__(self,parameters=[],**kwarg):
542          """creates a model          """
543        Creates a model.
544    
545              Just calls the parent constructor.          Just calls the parent constructor.
546          """          """
547          ParameterSet.__init__(self, parameters=parameters,**kwarg)          ParameterSet.__init__(self, parameters=parameters,**kwarg)
548    
# Line 512  class Model(ParameterSet): Line 550  class Model(ParameterSet):
550         return "<%s %d>"%(self.__class__,id(self))         return "<%s %d>"%(self.__class__,id(self))
551    
552      def toDom(self, document, node):      def toDom(self, document, node):
553          """ toDom method of Model class """          """
554        C{toDom} method of Model class
555        """
556          pset = document.createElement('Model')          pset = document.createElement('Model')
557          pset.setAttribute('type', self.__class__.__name__)          pset.setAttribute('type', self.__class__.__name__)
558          node.appendChild(pset)          node.appendChild(pset)
559          self._parametersToDom(document, pset)          self._parametersToDom(document, pset)
560    
561      def doInitialization(self):      def doInitialization(self):
562          """initializes the time stepping scheme. This function may be overwritten."""          """
563        Initializes the time stepping scheme.  
564        
565        This function may be overwritten.
566        """
567          pass          pass
568            
569      def getSafeTimeStepSize(self,dt):      def getSafeTimeStepSize(self,dt):
570          """returns a time step size which can safely be used.          """
571             dt gives the previously used step size.      Returns a time step size which can safely be used.
572             This function may be overwritten."""  
573            C{dt} gives the previously used step size.
574    
575            This function may be overwritten.
576        """
577          return self.UNDEF_DT          return self.UNDEF_DT
578            
579      def finalize(self):      def finalize(self):
580          """returns False if the time stepping is finalized. This function may be          """
581          overwritten."""      Returns False if the time stepping is finalized.
582        
583        This function may be overwritten.
584        """
585          return False          return False
586                
587      def doFinalization(self):      def doFinalization(self):
588          """finalizes the time stepping. This function may be overwritten."""          """
589        Finalizes the time stepping.
590        
591        This function may be overwritten.
592        """
593          pass          pass
594            
595      def doStepPreprocessing(self,dt):      def doStepPreprocessing(self,dt):
596          """sets up a time step of step size dt. This function may be overwritten."""          """
597        Sets up a time step of step size dt.
598        
599        This function may be overwritten.
600        """
601          pass          pass
602            
603      def doStep(self,dt):      def doStep(self,dt):
604          """executes an iteration step at a time step.          """
605             dt is the currently used time step size.      Executes an iteration step at a time step.
606             This function may be overwritten."""  
607            C{dt} is the currently used time step size.
608    
609            This function may be overwritten.
610        """
611          pass          pass
612            
613      def terminateIteration(self):      def terminateIteration(self):
614          """returns True if iteration on a time step is terminated."""          """
615        Returns True if iteration on a time step is terminated.
616        """
617          return True          return True
618                
619      def doStepPostprocessing(self,dt):      def doStepPostprocessing(self,dt):
620          """finalalizes the time step.          """
621             dt is the currently used time step size.      Finalalizes the time step.
622             This function may be overwritten."""  
623            dt is the currently used time step size.
624    
625            This function may be overwritten.
626        """
627          pass          pass
628            
629      def writeXML(self, ostream=stdout):      def writeXML(self, ostream=stdout):
# Line 562  class Model(ParameterSet): Line 631  class Model(ParameterSet):
631          self.toDom(document, node)          self.toDom(document, node)
632          ostream.write(document.toprettyxml())          ostream.write(document.toprettyxml())
633            
       
634    
635  class Simulation(Model):  class Simulation(Model):
636      """      """
637            A Simulation object is special Model which runs a sequence of Models.      A Simulation object is special Model which runs a sequence of Models.
638    
639            The methods doInitialization,finalize, getSafeTimeStepSize, doStepPreprocessing,      The methods C{doInitialization}, C{finalize}, C{getSafeTimeStepSize},
640            terminateIteration, doStepPostprocessing, doFinalization      C{doStepPreprocessing}, C{terminateIteration}, C{doStepPostprocessing},
641            are executing the corresponding methods of the models in the simulation.      C{doFinalization} are executing the corresponding methods of the models in
642                  the simulation.
643      """      """
644            
645      FAILED_TIME_STEPS_MAX=20      FAILED_TIME_STEPS_MAX=20
646      MAX_ITER_STEPS=50      MAX_ITER_STEPS=50
647            
648      def __init__(self, models=[], **kwargs):      def __init__(self, models=[], **kwargs):
649          """initiates a simulation from a list of models. """          """
650        Initiates a simulation from a list of models.
651        """
652          Model.__init__(self, **kwargs)          Model.__init__(self, **kwargs)
653          self.__models=[]          self.__models=[]
654            
655          for i in range(len(models)):          for i in range(len(models)):
656              self[i] = models[i]              self[i] = models[i]
657                
658    
659      def __repr__(self):      def __repr__(self):
660          """          """
661          returns a string representation of the Simulation          Returns a string representation of the Simulation.
662          """          """
663          return "<Simulation %r>" % self.__models          return "<Simulation %r>" % self.__models
664    
665      def __str__(self):      def __str__(self):
666          """          """
667          returning Simulation as a string          Returning Simulation as a string.
668          """          """
669          return "<Simulation %d>"%id(self)          return "<Simulation %d>"%id(self)
670            
671      def iterModels(self):      def iterModels(self):
672          """returns an iterator over the models"""          """
673        Returns an iterator over the models.
674        """
675          return self.__models          return self.__models
676            
677      def __getitem__(self,i):      def __getitem__(self,i):
678          """returns the i-th model"""          """
679        Returns the i-th model.
680        """
681          return self.__models[i]          return self.__models[i]
682            
683      def __setitem__(self,i,value):      def __setitem__(self,i,value):
684          """sets the i-th model"""          """
685        Sets the i-th model.
686        """
687          if not isinstance(value,Model):          if not isinstance(value,Model):
688              raise ValueError("assigned value is not a Model")              raise ValueError("assigned value is not a Model")
689          for j in range(max(i-len(self.__models)+1,0)): self.__models.append(None)          for j in range(max(i-len(self.__models)+1,0)):
690                self.__models.append(None)
691          self.__models[i]=value          self.__models[i]=value
692            
693      def __len__(self):      def __len__(self):
694          """returns the number of models"""          """
695        Returns the number of models.
696        """
697          return len(self.__models)          return len(self.__models)
698    
699      def toDom(self, document, node):      def toDom(self, document, node):
700          """ toDom method of Simulation class """          """
701        C{toDom} method of Simulation class.
702        """
703          simulation = document.createElement('Simulation')          simulation = document.createElement('Simulation')
704          simulation.setAttribute('type', self.__class__.__name__)          simulation.setAttribute('type', self.__class__.__name__)
705    
# Line 632  class Simulation(Model): Line 714  class Simulation(Model):
714          node.appendChild(simulation)          node.appendChild(simulation)
715    
716      def writeXML(self,ostream=stdout):      def writeXML(self,ostream=stdout):
717          """writes the object as an XML object into an output stream"""          """
718        Writes the object as an XML object into an output stream.
719        """
720          document, rootnode = esysDoc()          document, rootnode = esysDoc()
721          self.toDom(document, rootnode)          self.toDom(document, rootnode)
722            targetsList = document.getElementsByTagName('Target')
723            for i in targetsList:
724                targetId = int(i.firstChild.nodeValue.strip())
725                targetObj = LinkableObjectRegistry[targetId]
726                targetObj.toDom(document, rootnode)
727          ostream.write(document.toprettyxml())          ostream.write(document.toprettyxml())
728            
729      def getSafeTimeStepSize(self,dt):      def getSafeTimeStepSize(self,dt):
730          """returns a time step size which can safely be used by all models.          """
731             This is the minimum over the time step sizes of all models."""      Returns a time step size which can safely be used by all models.
732    
733            This is the minimum over the time step sizes of all models.
734        """
735          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])          out=min([o.getSafeTimeStepSize(dt) for o in self.iterModels()])
736          print "%s: safe step size is %e."%(str(self),out)          print "%s: safe step size is %e."%(str(self),out)
737          return out          return out
738            
739      def doInitialization(self):      def doInitialization(self):
740          """initializes all models """          """
741        Initializes all models.
742        """
743          self.n=0          self.n=0
744          self.tn=0.          self.tn=0.
745          for o in self.iterModels():          for o in self.iterModels():
746              o.doInitialization()              o.doInitialization()
747            
748      def finalize(self):      def finalize(self):
749          """returns True if any of the models is to be finalized"""          """
750        Returns True if any of the models is to be finalized.
751        """
752          return any([o.finalize() for o in self.iterModels()])          return any([o.finalize() for o in self.iterModels()])
753                
754      def doFinalization(self):      def doFinalization(self):
755          """finalalizes the time stepping for all models."""          """
756        Finalalizes the time stepping for all models.
757        """
758          for i in self.iterModels(): i.doFinalization()          for i in self.iterModels(): i.doFinalization()
759          self.trace("end of time integation.")          self.trace("end of time integation.")
760            
761      def doStepPreprocessing(self,dt):      def doStepPreprocessing(self,dt):
762          """initializes the time step for all models."""          """
763        Initializes the time step for all models.
764        """
765          for o in self.iterModels():          for o in self.iterModels():
766              o.doStepPreprocessing(dt)              o.doStepPreprocessing(dt)
767            
768      def terminateIteration(self):      def terminateIteration(self):
769          """returns True if all iterations for all models are terminated."""          """
770        Returns True if all iterations for all models are terminated.
771        """
772          out=all([o.terminateIteration() for o in self.iterModels()])          out=all([o.terminateIteration() for o in self.iterModels()])
773          return out          return out
774                
775      def doStepPostprocessing(self,dt):      def doStepPostprocessing(self,dt):
776          """finalalizes the iteration process for all models."""          """
777        Finalalizes the iteration process for all models.
778        """
779          for o in self.iterModels():          for o in self.iterModels():
780              o.doStepPostprocessing(dt)              o.doStepPostprocessing(dt)
781          self.n+=1          self.n+=1
# Line 679  class Simulation(Model): Line 783  class Simulation(Model):
783            
784      def doStep(self,dt):      def doStep(self,dt):
785          """          """
786               executes the iteration step at a time step for all model:      Executes the iteration step at a time step for all model::
787    
788                    self.doStepPreprocessing(dt)              self.doStepPreprocessing(dt)
789                    while not self.terminateIteration(): for all models: self.doStep(dt)              while not self.terminateIteration():
790                    self.doStepPostprocessing(dt)              for all models:
791                self.doStep(dt)
792                    self.doStepPostprocessing(dt)
793          """          """
794          self.iter=0          self.iter=0
795          while not self.terminateIteration():          while not self.terminateIteration():
# Line 697  class Simulation(Model): Line 802  class Simulation(Model):
802    
803      def run(self,check_point=None):      def run(self,check_point=None):
804          """          """
805        Run the simulation by performing essentially::
            run the simulation by performing essentially  
806            
807                 self.doInitialization()          self.doInitialization()
808                 while not self.finalize():          while not self.finalize():
809                    dt=self.getSafeTimeStepSize()              dt=self.getSafeTimeStepSize()
810                    self.doStep(dt)              self.doStep(dt)
811                    if n%check_point==0: self.writeXML()              if n%check_point==0:
812                 self.doFinalization()              self.writeXML()
813            self.doFinalization()
814             If one of the models in throws a FailedTimeStepError exception a new time step size is  
815             computed through getSafeTimeStepSize() and the time step is repeated.          If one of the models in throws a C{FailedTimeStepError} exception a
816        new time step size is computed through getSafeTimeStepSize() and the
817        time step is repeated.
818        
819             If one of the models in throws a IterationDivergenceError exception the time step size          If one of the models in throws a C{IterationDivergenceError}
820             is halved and the time step is repeated.      exception the time step size is halved and the time step is repeated.
   
            In both cases the time integration is given up after Simulation.FAILED_TIME_STEPS_MAX  
            attempts.  
821    
822                In both cases the time integration is given up after
823        C{Simulation.FAILED_TIME_STEPS_MAX} attempts.
824          """          """
825          dt=self.UNDEF_DT          dt=self.UNDEF_DT
826          self.doInitialization()          self.doInitialization()
# Line 770  class Simulation(Model): Line 874  class Simulation(Model):
874    
875  class IterationDivergenceError(Exception):  class IterationDivergenceError(Exception):
876      """      """
877         excpetion which is thrown if there is no convergence of the iteration process at a time step      Exception which is thrown if there is no convergence of the iteration
878         but there is a chance taht a smaller step could help to reach convergence.      process at a time step.
879    
880        But there is a chance that a smaller step could help to reach convergence.
881      """      """
882      pass      pass
883    
884  class FailedTimeStepError(Exception):  class FailedTimeStepError(Exception):
885      """excpetion which is thrown if the time step fails because of a step size that have been choosen to be too large"""      """
886        Exception which is thrown if the time step fails because of a step
887        size that have been choosen to be too large.
888        """
889      pass      pass
890    
891  class SimulationBreakDownError(Exception):  class SimulationBreakDownError(Exception):
892      """excpetion which is thrown if the simulation does not manage to progress in time."""      """
893        Exception which is thrown if the simulation does not manage to
894        progress in time.
895        """
896      pass      pass
897    
898  class NonPositiveStepSizeError(Exception):  class NonPositiveStepSizeError(Exception):
899      """excpetion which is thrown if the step size is not positive"""      """
900        Exception which is thrown if the step size is not positive.
901        """
902      pass      pass
903    
904    # vim: expandtab shiftwidth=4:

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

  ViewVC Help
Powered by ViewVC 1.1.26