/[escript]/temp_trunk_copy/escript/py_src/linearPDEs.py
ViewVC logotype

Diff of /temp_trunk_copy/escript/py_src/linearPDEs.py

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

trunk/esys2/escript/py_src/linearPDEs.py revision 148 by jgs, Tue Aug 23 01:24:31 2005 UTC trunk/escript/py_src/linearPDEs.py revision 430 by gross, Wed Jan 11 06:40:50 2006 UTC
# Line 1  Line 1 
1  # $Id$  # $Id$
2    
3  ## @file linearPDEs.py  #
4    #      COPYRIGHT ACcESS 2004 -  All Rights Reserved
5    #
6    #   This software is the property of ACcESS.  No part of this code
7    #   may be copied in any form or by any means without the expressed written
8    #   consent of ACcESS.  Copying, use or modification of this software
9    #   by any unauthorised person is illegal unless that
10    #   person has a software license agreement with ACcESS.
11    #
12  """  """
13  Functions and classes for linear PDEs  The module provides an interface to define and solve linear partial
14    differential equations (PDEs) within L{escript}. L{linearPDEs} does not provide any
15    solver capabilities in itself but hands the PDE over to
16    the PDE solver library defined through the L{Domain<escript.Domain>} of the PDE.
17    The general interface is provided through the L{LinearPDE} class. The
18    L{AdvectivePDE} which is derived from the L{LinearPDE} class
19    provides an interface to PDE dominated by its advective terms. The L{Poisson},
20    L{Helmholtz}, L{LameEquation}, L{AdvectionDiffusion}
21    classs which are also derived form the L{LinearPDE} class should be used
22    to define of solve these sepecial PDEs.
23    
24    @var __author__: name of author
25    @var __licence__: licence agreement
26    @var __url__: url entry point on documentation
27    @var __version__: version
28    @var __date__: date of the version
29  """  """
30    
31  import escript  import escript
32  import util  import util
33  import numarray  import numarray
34    
35    __author__="Lutz Gross, l.gross@uq.edu.au"
36    __licence__="contact: esys@access.uq.edu.au"
37    __url__="http://www.iservo.edu.au/esys/escript"
38    __version__="$Revision$"
39    __date__="$Date$"
40    
41    
42  class IllegalCoefficient(ValueError):  class IllegalCoefficient(ValueError):
43     """     """
# Line 26  class UndefinedPDEError(ValueError): Line 54  class UndefinedPDEError(ValueError):
54     raised if a PDE is not fully defined yet.     raised if a PDE is not fully defined yet.
55     """     """
56    
57  def _CompTuple2(t1,t2):  class PDECoefficient(object):
       """  
       Compare two tuples  
     
       @param t1 The first tuple  
       @param t2 The second tuple  
     
       """  
     
       dif=t1[0]+t1[1]-(t2[0]+t2[1])  
       if dif<0: return 1  
       elif dif>0: return -1  
       else: return 0  
     
 class PDECoefficient:  
58      """      """
59      A class for PDE coefficients      A class for describing a PDE coefficient
60    
61        @cvar INTERIOR: indicator that coefficient is defined on the interior of the PDE domain
62        @cvar BOUNDARY: indicator that coefficient is defined on the boundary of the PDE domain
63        @cvar CONTACT: indicator that coefficient is defined on the contact region within the PDE domain
64        @cvar SOLUTION: indicator that coefficient is defined trough a solution of the PDE
65        @cvar REDUCED: indicator that coefficient is defined trough a reduced solution of the PDE
66        @cvar BY_EQUATION: indicator that the dimension of the coefficient shape is defined by the number PDE equations
67        @cvar BY_SOLUTION: indicator that the dimension of the coefficient shape is defined by the number PDE solutions
68        @cvar BY_DIM: indicator that the dimension of the coefficient shape is defined by the spatial dimension
69        @cvar OPERATOR: indicator that the the coefficient alters the operator of the PDE
70        @cvar RIGHTHANDSIDE: indicator that the the coefficient alters the right hand side of the PDE
71        @cvar BOTH: indicator that the the coefficient alters the operator as well as the right hand side of the PDE
72    
73      """      """
     # identifier for location of Data objects defining COEFFICIENTS  
74      INTERIOR=0      INTERIOR=0
75      BOUNDARY=1      BOUNDARY=1
76      CONTACT=2      CONTACT=2
77      CONTINUOUS=3      SOLUTION=3
78      # identifier in the pattern of COEFFICIENTS:      REDUCED=4
79      # the pattern is a tuple of EQUATION,SOLUTION,DIM where DIM represents the spatial dimension, EQUATION the number of equations and SOLUTION the      BY_EQUATION=5
80      # number of unknowns.      BY_SOLUTION=6
81      EQUATION=3      BY_DIM=7
82      SOLUTION=4      OPERATOR=10
83      DIM=5      RIGHTHANDSIDE=11
84      # indicator for what is altered if the coefficient is altered:      BOTH=12
85      OPERATOR=5  
     RIGHTHANDSIDE=6  
     BOTH=7  
86      def __init__(self,where,pattern,altering):      def __init__(self,where,pattern,altering):
87         """         """
88         Initialise a PDE Coefficient type         Initialise a PDE Coefficient type
89    
90           @param where: describes where the coefficient lives
91           @type where: one of L{INTERIOR}, L{BOUNDARY}, L{CONTACT}, L{SOLUTION}, L{REDUCED}
92           @param pattern: describes the shape of the coefficient and how the shape is build for a given
93                  spatial dimension and numbers of equation and solution in then PDE. For instance,
94                  (L{BY_EQUATION},L{BY_SOLUTION},L{BY_DIM}) descrbes a rank 3 coefficient which
95                  is instanciated as shape (3,2,2) in case of a three equations and two solution components
96                  on a 2-dimensional domain. In the case of single equation and a single solution component
97                  the shape compoments marked by L{BY_EQUATION} or L{BY_SOLUTION} are dropped. In this case
98                  the example would be read as (2,).
99           @type pattern: C{tuple} of L{BY_EQUATION}, L{BY_SOLUTION}, L{BY_DIM}
100           @param altering: indicates what part of the PDE is altered if the coefficiennt is altered
101           @type altering: one of L{OPERATOR}, L{RIGHTHANDSIDE}, L{BOTH}
102    
103         """         """
104           super(PDECoefficient, self).__init__()
105         self.what=where         self.what=where
106         self.pattern=pattern         self.pattern=pattern
107         self.altering=altering         self.altering=altering
# Line 74  class PDECoefficient: Line 113  class PDECoefficient:
113         """         """
114         self.value=escript.Data()         self.value=escript.Data()
115    
116      def getFunctionSpace(self,domain):      def getFunctionSpace(self,domain,reducedEquationOrder=False,reducedSolutionOrder=False):
117         """         """
118         defines the FunctionSpace of the coefficient on the domain         defines the L{FunctionSpace<escript.FunctionSpace>} of the coefficient
119    
120         @param domain:         @param domain: domain on which the PDE uses the coefficient
121         """         @type domain: L{Domain<escript.Domain>}
122         if self.what==self.INTERIOR: return escript.Function(domain)         @param reducedEquationOrder: True to indicate that reduced order is used to represent the equation
123         elif self.what==self.BOUNDARY: return escript.FunctionOnBoundary(domain)         @type domain: C{bool}
124         elif self.what==self.CONTACT: return escript.FunctionOnContactZero(domain)         @param reducedSolutionOrder: True to indicate that reduced order is used to represent the solution
125         elif self.what==self.CONTINUOUS: return escript.ContinuousFunction(domain)         @type domain: C{bool}
126           @return:  L{FunctionSpace<escript.FunctionSpace>} of the coefficient
127           @rtype:  L{FunctionSpace<escript.FunctionSpace>}
128           """
129           if self.what==self.INTERIOR:
130                return escript.Function(domain)
131           elif self.what==self.BOUNDARY:
132                return escript.FunctionOnBoundary(domain)
133           elif self.what==self.CONTACT:
134                return escript.FunctionOnContactZero(domain)
135           elif self.what==self.SOLUTION:
136                if reducedEquationOrder and reducedSolutionOrder:
137                    return escript.ReducedSolution(domain)
138                else:
139                    return escript.Solution(domain)
140           elif self.what==self.REDUCED:
141                return escript.ReducedSolution(domain)
142    
143      def getValue(self):      def getValue(self):
144         """         """
145         returns the value of the coefficient:         returns the value of the coefficient
146    
147           @return:  value of the coefficient
148           @rtype:  L{Data<escript.Data>}
149         """         """
150         return self.value         return self.value
151    
152      def setValue(self,domain,numEquations=1,numSolutions=1,newValue=None):      def setValue(self,domain,numEquations=1,numSolutions=1,reducedEquationOrder=False,reducedSolutionOrder=False,newValue=None):
153         """         """
154         set the value of the coefficient to new value         set the value of the coefficient to a new value
155    
156           @param domain: domain on which the PDE uses the coefficient
157           @type domain: L{Domain<escript.Domain>}
158           @param numEquations: number of equations of the PDE
159           @type numEquations: C{int}
160           @param numSolutions: number of components of the PDE solution
161           @type numSolutions: C{int}
162           @param reducedEquationOrder: True to indicate that reduced order is used to represent the equation
163           @type domain: C{bool}
164           @param reducedSolutionOrder: True to indicate that reduced order is used to represent the solution
165           @type domain: C{bool}
166           @param newValue: number of components of the PDE solution
167           @type newValue: any object that can be converted into a L{Data<escript.Data>} object with the appropriate shape and L{FunctionSpace<escript.FunctionSpace>}
168           @raise IllegalCoefficientValue: if the shape of the assigned value does not match the shape of the coefficient
169         """         """
170         if newValue==None:         if newValue==None:
171             newValue=escript.Data()             newValue=escript.Data()
172         elif isinstance(newValue,escript.Data):         elif isinstance(newValue,escript.Data):
173             if not newValue.isEmpty():             if not newValue.isEmpty():
174                newValue=escript.Data(newValue,self.getFunctionSpace(domain))                try:
175                     newValue=escript.Data(newValue,self.getFunctionSpace(domain,reducedEquationOrder,reducedSolutionOrder))
176                  except:
177                     raise IllegalCoefficientValue,"Unable to interpolate coefficient to function space %s"%self.getFunctionSpace(domain)
178         else:         else:
179             newValue=escript.Data(newValue,self.getFunctionSpace(domain))             newValue=escript.Data(newValue,self.getFunctionSpace(domain,reducedEquationOrder,reducedSolutionOrder))
180         if not newValue.isEmpty():         if not newValue.isEmpty():
181             if not self.getShape(domain,numEquations,numSolutions)==newValue.getShape():             if not self.getShape(domain,numEquations,numSolutions)==newValue.getShape():
182                 raise IllegalCoefficientValue,"Expected shape for coefficient %s is %s but actual shape is %s."%(self.getShape(domain,numEquations,numSolutions),newValue.getShape())                 raise IllegalCoefficientValue,"Expected shape of coefficient is %s but actual shape is %s."%(self.getShape(domain,numEquations,numSolutions),newValue.getShape())
183         self.value=newValue         self.value=newValue
184    
185      def isAlteringOperator(self):      def isAlteringOperator(self):
186          """          """
187      return true if the operator of the PDE is changed when the coefficient is changed          checks if the coefficient alters the operator of the PDE
188    
189            @return:  True if the operator of the PDE is changed when the coefficient is changed
190            @rtype:  C{bool}
191      """      """
192          if self.altering==self.OPERATOR or self.altering==self.BOTH:          if self.altering==self.OPERATOR or self.altering==self.BOTH:
193              return not None              return not None
# Line 118  class PDECoefficient: Line 196  class PDECoefficient:
196    
197      def isAlteringRightHandSide(self):      def isAlteringRightHandSide(self):
198          """          """
199      return true if the right hand side of the PDE is changed when the coefficient is changed          checks if the coefficeint alters the right hand side of the PDE
200    
201        @rtype:  C{bool}
202            @return:  True if the right hand side of the PDE is changed when the coefficient is changed
203      """      """
204          if self.altering==self.RIGHTHANDSIDE or self.altering==self.BOTH:          if self.altering==self.RIGHTHANDSIDE or self.altering==self.BOTH:
205              return not None              return not None
# Line 127  class PDECoefficient: Line 208  class PDECoefficient:
208    
209      def estimateNumEquationsAndNumSolutions(self,domain,shape=()):      def estimateNumEquationsAndNumSolutions(self,domain,shape=()):
210         """         """
211         tries to estimate the number of equations in a given tensor shape for a given spatial dimension dim         tries to estimate the number of equations and number of solutions if the coefficient has the given shape
212    
213         @param shape:         @param domain: domain on which the PDE uses the coefficient
214         @param dim:         @type domain: L{Domain<escript.Domain>}
215           @param shape: suggested shape of the coefficient
216           @type shape: C{tuple} of C{int} values
217           @return: the number of equations and number of solutions of the PDE is the coefficient has shape s.
218                     If no appropriate numbers could be identified, C{None} is returned
219           @rtype: C{tuple} of two C{int} values or C{None}
220         """         """
221         dim=domain.getDim()         dim=domain.getDim()
222         if len(shape)>0:         if len(shape)>0:
# Line 138  class PDECoefficient: Line 224  class PDECoefficient:
224         else:         else:
225             num=1             num=1
226         search=[]         search=[]
227         for u in range(num):         if self.definesNumEquation() and self.definesNumSolutions():
228            for e in range(num):            for u in range(num):
229               search.append((e,u))               for e in range(num):
230         search.sort(_CompTuple2)                  search.append((e,u))
231         for item in search:            search.sort(self.__CompTuple2)
232              for item in search:
233               s=self.getShape(domain,item[0],item[1])               s=self.getShape(domain,item[0],item[1])
234               if len(s)==0 and len(shape)==0:               if len(s)==0 and len(shape)==0:
235                   return (1,1)                   return (1,1)
236               else:               else:
237                   if s==shape: return item                   if s==shape: return item
238           elif self.definesNumEquation():
239              for e in range(num,0,-1):
240                 s=self.getShape(domain,e,0)
241                 if len(s)==0 and len(shape)==0:
242                     return (1,None)
243                 else:
244                     if s==shape: return (e,None)
245    
246           elif self.definesNumSolutions():
247              for u in range(num,0,-1):
248                 s=self.getShape(domain,0,u)
249                 if len(s)==0 and len(shape)==0:
250                     return (None,1)
251                 else:
252                     if s==shape: return (None,u)
253         return None         return None
254        def definesNumSolutions(self):
255           """
256           checks if the coefficient allows to estimate the number of solution components
257    
258           @return: True if the coefficient allows an estimate of the number of solution components
259           @rtype: C{bool}
260           """
261           for i in self.pattern:
262                 if i==self.BY_SOLUTION: return True
263           return False
264    
265        def definesNumEquation(self):
266           """
267           checks if the coefficient allows to estimate the number of equations
268    
269           @return: True if the coefficient allows an estimate of the number of equations
270           @rtype: C{bool}
271           """
272           for i in self.pattern:
273                 if i==self.BY_EQUATION: return True
274           return False
275    
276        def __CompTuple2(self,t1,t2):
277          """
278          Compare two tuples of possible number of equations and number of solutions
279    
280          @param t1: The first tuple
281          @param t2: The second tuple
282    
283          """
284    
285          dif=t1[0]+t1[1]-(t2[0]+t2[1])
286          if dif<0: return 1
287          elif dif>0: return -1
288          else: return 0
289    
290      def getShape(self,domain,numEquations=1,numSolutions=1):      def getShape(self,domain,numEquations=1,numSolutions=1):
291          """         """
292      builds the required shape for a given number of equations e, number of unknowns u and spatial dimension dim         builds the required shape of the coefficient
293    
294      @param e:         @param domain: domain on which the PDE uses the coefficient
295      @param u:         @type domain: L{Domain<escript.Domain>}
296      @param dim:         @param numEquations: number of equations of the PDE
297      """         @type numEquations: C{int}
298          dim=domain.getDim()         @param numSolutions: number of components of the PDE solution
299          s=()         @type numSolutions: C{int}
300          for i in self.pattern:         @return: shape of the coefficient
301               if i==self.EQUATION:         @rtype: C{tuple} of C{int} values
302           """
303           dim=domain.getDim()
304           s=()
305           for i in self.pattern:
306                 if i==self.BY_EQUATION:
307                  if numEquations>1: s=s+(numEquations,)                  if numEquations>1: s=s+(numEquations,)
308               elif i==self.SOLUTION:               elif i==self.BY_SOLUTION:
309                  if numSolutions>1: s=s+(numSolutions,)                  if numSolutions>1: s=s+(numSolutions,)
310               else:               else:
311                  s=s+(dim,)                  s=s+(dim,)
312          return s         return s
313    
314  class LinearPDE:  class LinearPDE(object):
315     """     """
316     Class to define a linear PDE of the form     This class is used to define a general linear, steady, second order PDE
317       for an unknown function M{u} on a given domain defined through a L{Domain<escript.Domain>} object.
318    
319     \f[     For a single PDE with a solution with a single component the linear PDE is defined in the following form:
      -(A_{ijkl}u_{k,l})_{,j} -(B_{ijk}u_k)_{,j} + C_{ikl}u_{k,l} +D_{ik}u_k = - (X_{ij})_{,j} + Y_i  
    \f]  
320    
321     with boundary conditons:     M{-grad(A[j,l]*grad(u)[l]+B[j]u)[j]+C[l]*grad(u)[l]+D*u =-grad(X)[j,j]+Y}
322    
323     \f[     where M{grad(F)} denotes the spatial derivative of M{F}. Einstein's summation convention,
324     n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_{ik}u_k = - n_j*X_{ij} + y_i     ie. summation over indexes appearing twice in a term of a sum is performed, is used.
325     \f]     The coefficients M{A}, M{B}, M{C}, M{D}, M{X} and M{Y} have to be specified through L{Data<escript.Data>} objects in the
326       L{Function<escript.Function>} on the PDE or objects that can be converted into such L{Data<escript.Data>} objects.
327       M{A} is a rank two, M{B}, M{C} and M{X} are rank one and M{D} and M{Y} are scalar.
328    
329     and contact conditions     The following natural boundary conditions are considered:
330    
331     \f[     M{n[j]*(A[i,j]*grad(u)[l]+B[j]*u)+d*u=n[j]*X[j]+y}
    n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_contact_{ik}[u_k] = - n_j*X_{ij} + y_contact_i  
    \f]  
332    
333     and constraints:     where M{n} is the outer normal field calculated by L{getNormal<escript.FunctionSpace.getNormal>} of L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
334       Notice that the coefficients M{A}, M{B} and M{X} are defined in the PDE. The coefficients M{d} and M{y} are
335       each a scalar in the L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
336    
337    
338       Constraints for the solution prescribing the value of the solution at certain locations in the domain. They have the form
339    
340       M{u=r}  where M{q>0}
341    
342       M{r} and M{q} are each scalar where M{q} is the characteristic function defining where the constraint is applied.
343       The constraints override any other condition set by the PDE or the boundary condition.
344    
345       The PDE is symmetrical if
346    
347       M{A[i,j]=A[j,i]}  and M{B[j]=C[j]}
348    
349       For a system of PDEs and a solution with several components the PDE has the form
350    
351     \f[     M{-grad(A[i,j,k,l]*grad(u[k])[l]+B[i,j,k]*u[k])[j]+C[i,k,l]*grad(u[k])[l]+D[i,k]*u[k] =-grad(X[i,j])[j]+Y[i] }
352     u_i=r_i \quad \mathrm{where} \quad q_i>0  
353     \f]     M{A} is a ramk four, M{B} and M{C} are each a rank three, M{D} and M{X} are each a rank two and M{Y} is a rank one.
354       The natural boundary conditions take the form:
355    
356       M{n[j]*(A[i,j,k,l]*grad(u[k])[l]+B[i,j,k]*u[k])+d[i,k]*u[k]=n[j]*X[i,j]+y[i]}
357    
358    
359       The coefficient M{d} is a rank two and M{y} is a  rank one both in the L{FunctionOnBoundary<escript.FunctionOnBoundary>}. Constraints take the form
360    
361    
362       M{u[i]=r[i]}  where  M{q[i]>0}
363    
364       M{r} and M{q} are each rank one. Notice that at some locations not necessarily all components must have a constraint.
365    
366       The system of PDEs is symmetrical if
367    
368            - M{A[i,j,k,l]=A[k,l,i,j]}
369            - M{B[i,j,k]=C[k,i,j]}
370            - M{D[i,k]=D[i,k]}
371            - M{d[i,k]=d[k,i]}
372    
373       L{LinearPDE} also supports solution discontinuities over a contact region in the domain. To specify the conditions across the
374       discontinuity we are using the generalised flux M{J} which is in the case of a systems of PDEs and several components of the solution
375       defined as
376    
377       M{J[i,j]=A[i,j,k,l]*grad(u[k])[l]+B[i,j,k]*u[k]-X[i,j]}
378    
379       For the case of single solution component and single PDE M{J} is defined
380    
381       M{J_{j}=A[i,j]*grad(u)[j]+B[i]*u-X[i]}
382    
383       In the context of discontinuities M{n} denotes the normal on the discontinuity pointing from side 0 towards side 1
384       calculated from L{getNormal<escript.FunctionSpace.getNormal>} of L{FunctionOnContactZero<escript.FunctionOnContactZero>}. For a system of PDEs
385       the contact condition takes the form
386    
387       M{n[j]*J0[i,j]=n[j]*J1[i,j]=y_contact[i]- d_contact[i,k]*jump(u)[k]}
388    
389       where M{J0} and M{J1} are the fluxes on side 0 and side 1 of the discontinuity, respectively. M{jump(u)}, which is the difference
390       of the solution at side 1 and at side 0, denotes the jump of M{u} across discontinuity along the normal calcualted by
391       L{jump<util.jump>}.
392       The coefficient M{d_contact} is a rank two and M{y_contact} is a rank one both in the L{FunctionOnContactZero<escript.FunctionOnContactZero>} or L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
393       In case of a single PDE and a single component solution the contact condition takes the form
394    
395       M{n[j]*J0_{j}=n[j]*J1_{j}=y_contact-d_contact*jump(u)}
396    
397       In this case the the coefficient M{d_contact} and M{y_contact} are eaach scalar
398       both in the L{FunctionOnContactZero<escript.FunctionOnContactZero>} or L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
399    
400       @cvar DEFAULT: The default method used to solve the system of linear equations
401       @cvar DIRECT: The direct solver based on LDU factorization
402       @cvar CHOLEVSKY: The direct solver based on LDLt factorization (can only be applied for symmetric PDEs)
403       @cvar PCG: The preconditioned conjugate gradient method (can only be applied for symmetric PDEs)
404       @cvar CR: The conjugate residual method
405       @cvar CGS: The conjugate gardient square method
406       @cvar BICGSTAB: The stabilized BiConjugate Gradient method.
407       @cvar SSOR: The symmetric overrealaxtion method
408       @cvar ILU0: The incomplete LU factorization preconditioner  with no fill in
409       @cvar ILUT: The incomplete LU factorization preconditioner with will in
410       @cvar JACOBI: The Jacobi preconditioner
411       @cvar GMRES: The Gram-Schmidt minimum residual method
412       @cvar PRES20: Special GMRES with restart after 20 steps and truncation after 5 residuals
413       @cvar LUMPING: Matrix lumping.
414       @cvar NO_REORDERING: No matrix reordering allowed
415       @cvar MINIMUM_FILL_IN: Reorder matrix to reduce fill-in during factorization
416       @cvar NESTED_DISSECTION: Reorder matrix to improve load balancing during factorization
417       @cvar PASO: PASO solver package
418       @cvar SCSL: SGI SCSL solver library
419       @cvar MKL: Intel's MKL solver library
420       @cvar UMFPACK: the UMFPACK library
421       @cvar ITERATIVE: The default iterative solver
422       @cvar AMG: algebraic multi grid
423       @cvar RILU: recursive ILU
424    
425     """     """
426     TOL=1.e-13     DEFAULT= 0
427     # solver methods     DIRECT= 1
428     UNKNOWN=-1     CHOLEVSKY= 2
429     DEFAULT_METHOD=0     PCG= 3
430     DIRECT=1     CR= 4
431     CHOLEVSKY=2     CGS= 5
432     PCG=3     BICGSTAB= 6
433     CR=4     SSOR= 7
434     CGS=5     ILU0= 8
435     BICGSTAB=6     ILUT= 9
436     SSOR=7     JACOBI= 10
437     ILU0=8     GMRES= 11
438     ILUT=9     PRES20= 12
439     JACOBI=10     LUMPING= 13
440     GMRES=11     NO_REORDERING= 17
441     PRES20=12     MINIMUM_FILL_IN= 18
442     LUMPING=13     NESTED_DISSECTION= 19
443     # matrix reordering:     SCSL= 14
444     NO_REORDERING=0     MKL= 15
445     MINIMUM_FILL_IN=1     UMFPACK= 16
446     NESTED_DISSECTION=2     ITERATIVE= 20
447     # important keys in the dictonary used to hand over options to the solver library:     PASO= 21
448     METHOD_KEY="method"     AMG= 22
449     SYMMETRY_KEY="symmetric"     RILU = 23
450     TOLERANCE_KEY="tolerance"  
451       __TOL=1.e-13
452       __PACKAGE_KEY="package"
453       __METHOD_KEY="method"
454       __SYMMETRY_KEY="symmetric"
455       __TOLERANCE_KEY="tolerance"
456       __PRECONDITIONER_KEY="preconditioner"
457    
458    
459     def __init__(self,domain,numEquations=None,numSolutions=None,debug=False):     def __init__(self,domain,numEquations=None,numSolutions=None,debug=False):
# Line 228  class LinearPDE: Line 461  class LinearPDE:
461       initializes a new linear PDE       initializes a new linear PDE
462    
463       @param domain: domain of the PDE       @param domain: domain of the PDE
464       @type domain: L{Domain}       @type domain: L{Domain<escript.Domain>}
465       @param numEquations: number of equations. If numEquations==None the number of equations       @param numEquations: number of equations. If numEquations==None the number of equations
466                            is exracted from the PDE coefficients.                            is exracted from the PDE coefficients.
467       @param numSolutions: number of solution components. If  numSolutions==None the number of solution components       @param numSolutions: number of solution components. If  numSolutions==None the number of solution components
468                            is exracted from the PDE coefficients.                            is exracted from the PDE coefficients.
469       @param debug: if True debug informations are printed.       @param debug: if True debug informations are printed.
470    
   
471       """       """
472         super(LinearPDE, self).__init__()
473       #       #
474       #   the coefficients of the general PDE:       #   the coefficients of the general PDE:
475       #       #
476       self.__COEFFICIENTS_OF_GENEARL_PDE={       self.__COEFFICIENTS_OF_GENEARL_PDE={
477         "A"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM,PDECoefficient.SOLUTION,PDECoefficient.DIM),PDECoefficient.OPERATOR),         "A"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_DIM,PDECoefficient.BY_SOLUTION,PDECoefficient.BY_DIM),PDECoefficient.OPERATOR),
478         "B"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),         "B"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_DIM,PDECoefficient.BY_SOLUTION),PDECoefficient.OPERATOR),
479         "C"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION,PDECoefficient.DIM),PDECoefficient.OPERATOR),         "C"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_SOLUTION,PDECoefficient.BY_DIM),PDECoefficient.OPERATOR),
480         "D"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),         "D"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_SOLUTION),PDECoefficient.OPERATOR),
481         "X"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM),PDECoefficient.RIGHTHANDSIDE),         "X"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_DIM),PDECoefficient.RIGHTHANDSIDE),
482         "Y"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),         "Y"         : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
483         "d"         : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),         "d"         : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_SOLUTION),PDECoefficient.OPERATOR),
484         "y"         : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),         "y"         : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
485         "d_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),         "d_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_SOLUTION),PDECoefficient.OPERATOR),
486         "y_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),         "y_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
487         "r"         : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),         "r"         : PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_SOLUTION,),PDECoefficient.RIGHTHANDSIDE),
488         "q"         : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.SOLUTION,),PDECoefficient.BOTH)}         "q"         : PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_SOLUTION,),PDECoefficient.BOTH)}
489    
490       # COEFFICIENTS can be overwritten by subclasses:       # COEFFICIENTS can be overwritten by subclasses:
491       self.COEFFICIENTS=self.__COEFFICIENTS_OF_GENEARL_PDE       self.COEFFICIENTS=self.__COEFFICIENTS_OF_GENEARL_PDE
492         self.__altered_coefficients=False
493       # initialize attributes       # initialize attributes
494       self.__debug=debug       self.__debug=debug
495       self.__domain=domain       self.__domain=domain
# Line 264  class LinearPDE: Line 498  class LinearPDE:
498       self.__resetSystem()       self.__resetSystem()
499    
500       # set some default values:       # set some default values:
501       self.__homogeneous_constraint=True       self.__reduce_equation_order=False
502       self.__row_function_space=escript.Solution(self.__domain)       self.__reduce_solution_order=False
      self.__column_function_space=escript.Solution(self.__domain)  
503       self.__tolerance=1.e-8       self.__tolerance=1.e-8
504       self.__solver_method=self.DEFAULT_METHOD       self.__solver_method=self.DEFAULT
505       self.__matrix_type=self.__domain.getSystemMatrixTypeId(self.DEFAULT_METHOD,False)       self.__solver_package=self.DEFAULT
506         self.__preconditioner=self.DEFAULT
507         self.__matrix_type=self.__domain.getSystemMatrixTypeId(self.DEFAULT,self.DEFAULT,False)
508       self.__sym=False       self.__sym=False
509    
510       self.resetCoefficients()       self.resetCoefficients()
# Line 278  class LinearPDE: Line 513  class LinearPDE:
513     #    general stuff:     #    general stuff:
514     # =============================================================================     # =============================================================================
515     def __str__(self):     def __str__(self):
516         return "<LinearPDE %d>"%id(self)       """
517         returns string representation of the PDE
518    
519         @return: a simple representation of the PDE
520         @rtype: C{str}
521         """
522         return "<LinearPDE %d>"%id(self)
523     # =============================================================================     # =============================================================================
524     #    debug :     #    debug :
525     # =============================================================================     # =============================================================================
526     def setDebugOn(self):     def setDebugOn(self):
527       """       """
528       switches on debugging       switches on debugging
529       """       """
530       self.__debug=not None       self.__debug=not None
# Line 296  class LinearPDE: Line 537  class LinearPDE:
537    
538     def trace(self,text):     def trace(self,text):
539       """       """
540       print the text message if debugging is swiched on.       print the text message if debugging is swiched on.
541         @param text: message
542       @param name: name of the coefficient enquired.       @type text: C{string}
      @type name: C{string}  
543       """       """
544       if self.__debug: print "%s: %s"%(str(self),text)       if self.__debug: print "%s: %s"%(str(self),text)
545    
# Line 309  class LinearPDE: Line 549  class LinearPDE:
549     def getDomain(self):     def getDomain(self):
550       """       """
551       returns the domain of the PDE       returns the domain of the PDE
       
      @return : the domain of the PDE  
      @rtype : C{Domain}  
552    
553         @return: the domain of the PDE
554         @rtype: L{Domain<escript.Domain>}
555       """       """
556       return self.__domain       return self.__domain
557    
# Line 320  class LinearPDE: Line 559  class LinearPDE:
559       """       """
560       returns the spatial dimension of the PDE       returns the spatial dimension of the PDE
561    
562       @return : the spatial dimension of the PDE domain       @return: the spatial dimension of the PDE domain
563       @rtype : C{int}       @rtype: C{int}
564       """       """
565       return self.getDomain().getDim()       return self.getDomain().getDim()
566    
# Line 329  class LinearPDE: Line 568  class LinearPDE:
568       """       """
569       returns the number of equations       returns the number of equations
570    
571       @return : the number of equations       @return: the number of equations
572       @rtype : C{int}       @rtype: C{int}
573       @raise UndefinedPDEError: if the number of equations is not be specified yet.       @raise UndefinedPDEError: if the number of equations is not be specified yet.
574       """       """
575       if self.__numEquations==None:       if self.__numEquations==None:
# Line 342  class LinearPDE: Line 581  class LinearPDE:
581       """       """
582       returns the number of unknowns       returns the number of unknowns
583    
584       @return : the number of unknowns       @return: the number of unknowns
585       @rtype : C{int}       @rtype: C{int}
586       @raise UndefinedPDEError: if the number of unknowns is not be specified yet.       @raise UndefinedPDEError: if the number of unknowns is not be specified yet.
587       """       """
588       if self.__numSolutions==None:       if self.__numSolutions==None:
# Line 351  class LinearPDE: Line 590  class LinearPDE:
590       else:       else:
591          return self.__numSolutions          return self.__numSolutions
592    
593       def reduceEquationOrder(self):
594         """
595         return status for order reduction for equation
596    
597         @return: return True is reduced interpolation order is used for the represenation of the equation
598         @rtype: L{bool}
599         """
600         return self.__reduce_equation_order
601    
602       def reduceSolutionOrder(self):
603         """
604         return status for order reduction for the solution
605    
606         @return: return True is reduced interpolation order is used for the represenation of the solution
607         @rtype: L{bool}
608         """
609         return self.__reduce_solution_order
610    
611     def getFunctionSpaceForEquation(self):     def getFunctionSpaceForEquation(self):
612       """       """
613       returns the L{escript.FunctionSpace} used to discretize the equation       returns the L{FunctionSpace<escript.FunctionSpace>} used to discretize the equation
       
      @return : representation space of equation  
      @rtype : L{escript.FunctionSpace}  
614    
615         @return: representation space of equation
616         @rtype: L{FunctionSpace<escript.FunctionSpace>}
617       """       """
618       return self.__row_function_space       if self.reduceEquationOrder():
619             return escript.ReducedSolution(self.getDomain())
620         else:
621             return escript.Solution(self.getDomain())
622    
623     def getFunctionSpaceForSolution(self):     def getFunctionSpaceForSolution(self):
624       """       """
625       returns the L{escript.FunctionSpace} used to represent the solution       returns the L{FunctionSpace<escript.FunctionSpace>} used to represent the solution
       
      @return : representation space of solution  
      @rtype : L{escript.FunctionSpace}  
626    
627         @return: representation space of solution
628         @rtype: L{FunctionSpace<escript.FunctionSpace>}
629       """       """
630       return self.__column_function_space       if self.reduceSolutionOrder():
631             return escript.ReducedSolution(self.getDomain())
632         else:
633             return escript.Solution(self.getDomain())
634    
635    
636     def getOperator(self):     def getOperator(self):
637       """       """
638       provides access to the operator of the PDE       provides access to the operator of the PDE
639    
640       @return : the operator of the PDE       @return: the operator of the PDE
641       @rtype : L{Operator}       @rtype: L{Operator<escript.Operator>}
642       """       """
643       m=self.getSystem()[0]       m=self.getSystem()[0]
644       if self.isUsingLumping():       if self.isUsingLumping():
# Line 388  class LinearPDE: Line 649  class LinearPDE:
649     def getRightHandSide(self):     def getRightHandSide(self):
650       """       """
651       provides access to the right hand side of the PDE       provides access to the right hand side of the PDE
652         @return: the right hand side of the PDE
653       @return : the right hand side of the PDE       @rtype: L{Data<escript.Data>}
      @rtype : L{escript.Data}  
654       """       """
655       r=self.getSystem()[1]       r=self.getSystem()[1]
656       if self.isUsingLumping():       if self.isUsingLumping():
# Line 404  class LinearPDE: Line 664  class LinearPDE:
664    
665       @param u: argument of the operator. It must be representable in C{elf.getFunctionSpaceForSolution()}. If u is not present or equals L{None}       @param u: argument of the operator. It must be representable in C{elf.getFunctionSpaceForSolution()}. If u is not present or equals L{None}
666                 the current solution is used.                 the current solution is used.
667       @type u: L{escript.Data} or None       @type u: L{Data<escript.Data>} or None
668       @return : image of u       @return: image of u
669       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
670       """       """
671       if u==None:       if u==None:
672            return self.getOperator()*self.getSolution()            return self.getOperator()*self.getSolution()
673       else:       else:
674          self.getOperator()*escript.Data(u,self.getFunctionSpaceForSolution())          self.getOperator()*escript.Data(u,self.getFunctionSpaceForSolution())
# Line 419  class LinearPDE: Line 679  class LinearPDE:
679    
680       @param u: argument in the residual calculation. It must be representable in C{elf.getFunctionSpaceForSolution()}. If u is not present or equals L{None}       @param u: argument in the residual calculation. It must be representable in C{elf.getFunctionSpaceForSolution()}. If u is not present or equals L{None}
681                 the current solution is used.                 the current solution is used.
682       @type u: L{escript.Data} or None       @type u: L{Data<escript.Data>} or None
683       @return : residual of u       @return: residual of u
684       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
685       """       """
686       return self.applyOperator(u)-self.getRightHandSide()       return self.applyOperator(u)-self.getRightHandSide()
687    
# Line 429  class LinearPDE: Line 689  class LinearPDE:
689        """        """
690        test the PDE for symmetry.        test the PDE for symmetry.
691    
692          @param verbose: if equal to True or not present a report on coefficients which are breaking the symmetry is printed.
693       @param verbose: if equal to True or not present a report on coefficients which are breaking the symmetry is printed.        @type verbose: C{bool}
694       @type verbose: C{bool}        @return:  True if the PDE is symmetric.
695       @return:  True if the PDE is symmetric.        @rtype: L{Data<escript.Data>}
      @rtype : C{escript.Data}  
   
696        @note: This is a very expensive operation. It should be used for degugging only! The symmetry flag is not altered.        @note: This is a very expensive operation. It should be used for degugging only! The symmetry flag is not altered.
697        """        """
698        verbose=verbose or self.debug()        verbose=verbose or self.__debug
699        out=True        out=True
700        if self.getNumSolutions()!=self.getNumEquations():        if self.getNumSolutions()!=self.getNumEquations():
701           if verbose: print "non-symmetric PDE because of different number of equations and solutions"           if verbose: print "non-symmetric PDE because of different number of equations and solutions"
# Line 445  class LinearPDE: Line 703  class LinearPDE:
703        else:        else:
704           A=self.getCoefficientOfGeneralPDE("A")           A=self.getCoefficientOfGeneralPDE("A")
705           if not A.isEmpty():           if not A.isEmpty():
706              tol=util.Lsup(A)*self.TOL              tol=util.Lsup(A)*self.__TOL
707              if self.getNumSolutions()>1:              if self.getNumSolutions()>1:
708                 for i in range(self.getNumEquations()):                 for i in range(self.getNumEquations()):
709                    for j in range(self.getDim()):                    for j in range(self.getDim()):
# Line 469  class LinearPDE: Line 727  class LinearPDE:
727              if verbose: print "non-symmetric PDE because C is not present but B is"              if verbose: print "non-symmetric PDE because C is not present but B is"
728              out=False              out=False
729           elif not B.isEmpty() and not C.isEmpty():           elif not B.isEmpty() and not C.isEmpty():
730              tol=(util.Lsup(B)+util.Lsup(C))*self.TOL/2.              tol=(util.Lsup(B)+util.Lsup(C))*self.__TOL/2.
731              if self.getNumSolutions()>1:              if self.getNumSolutions()>1:
732                 for i in range(self.getNumEquations()):                 for i in range(self.getNumEquations()):
733                     for j in range(self.getDim()):                     for j in range(self.getDim()):
# Line 485  class LinearPDE: Line 743  class LinearPDE:
743           if self.getNumSolutions()>1:           if self.getNumSolutions()>1:
744             D=self.getCoefficientOfGeneralPDE("D")             D=self.getCoefficientOfGeneralPDE("D")
745             if not D.isEmpty():             if not D.isEmpty():
746               tol=util.Lsup(D)*self.TOL               tol=util.Lsup(D)*self.__TOL
747               for i in range(self.getNumEquations()):               for i in range(self.getNumEquations()):
748                  for k in range(self.getNumSolutions()):                  for k in range(self.getNumSolutions()):
749                    if util.Lsup(D[i,k]-D[k,i])>tol:                    if util.Lsup(D[i,k]-D[k,i])>tol:
750                        if verbose: print "non-symmetric PDE because D[%d,%d]!=D[%d,%d]"%(i,k,k,i)                        if verbose: print "non-symmetric PDE because D[%d,%d]!=D[%d,%d]"%(i,k,k,i)
751                        out=False                        out=False
752               d=self.getCoefficientOfGeneralPDE("d")
753               if not d.isEmpty():
754                 tol=util.Lsup(d)*self.__TOL
755                 for i in range(self.getNumEquations()):
756                    for k in range(self.getNumSolutions()):
757                      if util.Lsup(d[i,k]-d[k,i])>tol:
758                          if verbose: print "non-symmetric PDE because d[%d,%d]!=d[%d,%d]"%(i,k,k,i)
759                          out=False
760               d_contact=self.getCoefficientOfGeneralPDE("d_contact")
761               if not d_contact.isEmpty():
762                 tol=util.Lsup(d_contact)*self.__TOL
763                 for i in range(self.getNumEquations()):
764                    for k in range(self.getNumSolutions()):
765                      if util.Lsup(d_contact[i,k]-d_contact[k,i])>tol:
766                          if verbose: print "non-symmetric PDE because d_contact[%d,%d]!=d_contact[%d,%d]"%(i,k,k,i)
767                          out=False
768        return out        return out
769    
770     def getSolution(self,**options):     def getSolution(self,**options):
771         """         """
772         returns the solution of the PDE. If the solution is not valid the PDE is solved.         returns the solution of the PDE. If the solution is not valid the PDE is solved.
773    
774         @return: the solution         @return: the solution
775         @rtype: L{escript.Data}         @rtype: L{Data<escript.Data>}
776         @param options: solver options         @param options: solver options
777         @keyword verbose:         @keyword verbose: True to get some information during PDE solution
778         @keyword reordering: reordering scheme to be used during elimination         @type verbose: C{bool}
779         @keyword preconditioner: preconditioner method to be used         @keyword reordering: reordering scheme to be used during elimination. Allowed values are
780                                L{NO_REORDERING}, L{MINIMUM_FILL_IN}, L{NESTED_DISSECTION}
781         @keyword iter_max: maximum number of iteration steps allowed.         @keyword iter_max: maximum number of iteration steps allowed.
782         @keyword drop_tolerance:         @keyword drop_tolerance: threshold for drupping in L{ILUT}
783         @keyword drop_storage:         @keyword drop_storage: maximum of allowed memory in L{ILUT}
784         @keyword truncation:         @keyword truncation: maximum number of residuals in L{GMRES}
785         @keyword restart:         @keyword restart: restart cycle length in L{GMRES}
786         """         """
787         if not self.__solution_isValid:         if not self.__solution_isValid:
788            mat,f=self.getSystem()            mat,f=self.getSystem()
789            if self.isUsingLumping():            if self.isUsingLumping():
790               self.__solution=self.copyConstraint(f*mat)               self.__solution=self.copyConstraint(f*mat)
791            else:            else:
792               options[self.TOLERANCE_KEY]=self.getTolerance()               options[self.__TOLERANCE_KEY]=self.getTolerance()
793               options[self.METHOD_KEY]=self.getSolverMethod()               options[self.__METHOD_KEY]=self.getSolverMethod()[0]
794               options[self.SYMMETRY_KEY]=self.isSymmetric()               options[self.__PRECONDITIONER_KEY]=self.getSolverMethod()[1]
795                 options[self.__PACKAGE_KEY]=self.getSolverPackage()
796                 options[self.__SYMMETRY_KEY]=self.isSymmetric()
797               self.trace("PDE is resolved.")               self.trace("PDE is resolved.")
798               self.trace("solver options: %s"%str(options))               self.trace("solver options: %s"%str(options))
799               self.__solution=mat.solve(f,options)               self.__solution=mat.solve(f,options)
# Line 526  class LinearPDE: Line 802  class LinearPDE:
802    
803     def getFlux(self,u=None):     def getFlux(self,u=None):
804       """       """
805       returns the flux J_ij for a given u       returns the flux M{J} for a given M{u}
806    
807         \f[       M{J[i,j]=A[i,j,k,l]*grad(u[k])[l]+B[i,j,k]u[k]-X[i,j]}
        J_ij=A_{ijkl}u_{k,l}+B_{ijk}u_k-X_{ij}  
        \f]  
808    
809       @param u: argument in the flux. If u is not present or equals L{None} the current solution is used.       or
810       @type u: L{escript.Data} or None  
811       @return : flux       M{J[j]=A[i,j]*grad(u)[l]+B[j]u-X[j]}
      @rtype : L{escript.Data}  
812    
813         @param u: argument in the flux. If u is not present or equals L{None} the current solution is used.
814         @type u: L{Data<escript.Data>} or None
815         @return: flux
816         @rtype: L{Data<escript.Data>}
817       """       """
818       if u==None: u=self.getSolution()       if u==None: u=self.getSolution()
819       return util.tensormult(self.getCoefficientOfGeneralPDE("A"),util.grad(u))+util.matrixmult(self.getCoefficientOfGeneralPDE("B"),u)-util.self.getCoefficientOfGeneralPDE("X")       return util.tensormult(self.getCoefficientOfGeneralPDE("A"),util.grad(u))+util.matrixmult(self.getCoefficientOfGeneralPDE("B"),u)-util.self.getCoefficientOfGeneralPDE("X")
   
820     # =============================================================================     # =============================================================================
821     #   solver settings:     #   solver settings:
822     # =============================================================================     # =============================================================================
823     def setSolverMethod(self,solver=None):     def setSolverMethod(self,solver=None,preconditioner=None):
824         """         """
825         sets a new solver         sets a new solver
826    
827         @param solver: sets a new solver method.         @param solver: sets a new solver method.
828         @type solver: C{int}         @type solver: one of L{DEFAULT}, L{ITERATIVE} L{DIRECT}, L{CHOLEVSKY}, L{PCG}, L{CR}, L{CGS}, L{BICGSTAB}, L{SSOR}, L{GMRES}, L{PRES20}, L{LUMPING}.
829           @param preconditioner: sets a new solver method.
830         """         @type solver: one of L{DEFAULT}, L{JACOBI} L{ILU0}, L{ILUT},L{SSOR}
831         if solver==None: solve=self.DEFAULT_METHOD         """
832         if not solver==self.getSolverMethod():         if solver==None: solve=self.DEFAULT
833           if preconditioner==None: preconditioner=self.DEFAULT
834           if not (solver,preconditioner)==self.getSolverMethod():
835             self.__solver_method=solver             self.__solver_method=solver
836               self.__preconditioner=preconditioner
837             self.__checkMatrixType()             self.__checkMatrixType()
838             self.trace("New solver is %s"%self.getSolverMethodName())             self.trace("New solver is %s"%self.getSolverMethodName())
839    
# Line 562  class LinearPDE: Line 841  class LinearPDE:
841         """         """
842         returns the name of the solver currently used         returns the name of the solver currently used
843    
844         @return : the name of the solver currently used.         @return: the name of the solver currently used.
845         @rtype: C{string}         @rtype: C{string}
846         """         """
847    
848         m=self.getSolverMethod()         m=self.getSolverMethod()
849         if m==self.DEFAULT_METHOD: return "DEFAULT_METHOD"         p=self.getSolverPackage()
850         elif m==self.DIRECT: return "DIRECT"         method=""
851         elif m==self.CHOLEVSKY: return "CHOLEVSKY"         if m[0]==self.DEFAULT: method="DEFAULT"
852         elif m==self.PCG: return "PCG"         elif m[0]==self.DIRECT: method= "DIRECT"
853         elif m==self.CR: return "CR"         elif m[0]==self.ITERATIVE: method= "ITERATIVE"
854         elif m==self.CGS: return "CGS"         elif m[0]==self.CHOLEVSKY: method= "CHOLEVSKY"
855         elif m==self.BICGSTAB: return "BICGSTAB"         elif m[0]==self.PCG: method= "PCG"
856         elif m==self.SSOR: return "SSOR"         elif m[0]==self.CR: method= "CR"
857         elif m==self.GMRES: return "GMRES"         elif m[0]==self.CGS: method= "CGS"
858         elif m==self.PRES20: return "PRES20"         elif m[0]==self.BICGSTAB: method= "BICGSTAB"
859         elif m==self.LUMPING: return "LUMPING"         elif m[0]==self.SSOR: method= "SSOR"
860         return None         elif m[0]==self.GMRES: method= "GMRES"
861                 elif m[0]==self.PRES20: method= "PRES20"
862           elif m[0]==self.LUMPING: method= "LUMPING"
863           if m[1]==self.DEFAULT: method+="+DEFAULT"
864           elif m[1]==self.JACOBI: method+= "+JACOBI"
865           elif m[1]==self.ILU0: method+= "+ILU0"
866           elif m[1]==self.ILUT: method+= "+ILUT"
867           elif m[1]==self.SSOR: method+= "+SSOR"
868           if p==self.DEFAULT: package="DEFAULT"
869           elif p==self.PASO: package= "PASO"
870           elif p==self.MKL: package= "MKL"
871           elif p==self.SCSL: package= "SCSL"
872           elif p==self.UMFPACK: package= "UMFPACK"
873           else : method="unknown"
874           return "%s solver of %s package"%(method,package)
875    
876    
877     def getSolverMethod(self):     def getSolverMethod(self):
878         """         """
879         returns the solver method         returns the solver method
880      
881         @return : the solver method currently be used.         @return: the solver method currently be used.
882         @rtype : C{int}         @rtype: C{int}
883           """
884           return self.__solver_method,self.__preconditioner
885    
886       def setSolverPackage(self,package=None):
887           """
888           sets a new solver package
889    
890           @param solver: sets a new solver method.
891           @type solver: one of L{DEFAULT}, L{PASO} L{SCSL}, L{MKL}, L{UMLPACK}
892           """
893           if package==None: package=self.DEFAULT
894           if not package==self.getSolverPackage():
895               self.__solver_method=solver
896               self.__checkMatrixType()
897               self.trace("New solver is %s"%self.getSolverMethodName())
898    
899       def getSolverPackage(self):
900         """         """
901         return self.__solver_method         returns the package of the solver
902    
903           @return: the solver package currently being used.
904           @rtype: C{int}
905           """
906           return self.__solver_package
907    
908     def isUsingLumping(self):     def isUsingLumping(self):
909        """        """
910        checks if matrix lumping is used a solver method        checks if matrix lumping is used a solver method
911    
912        @return : True is lumping is currently used a solver method.        @return: True is lumping is currently used a solver method.
913        @rtype: C{bool}        @rtype: C{bool}
914        """        """
915        return self.getSolverMethod()==self.LUMPING        return self.getSolverMethod()[0]==self.LUMPING
916    
917     def setTolerance(self,tol=1.e-8):     def setTolerance(self,tol=1.e-8):
918         """         """
919         resets the tolerance for the solver method to tol where for an appropriate norm |.|         resets the tolerance for the solver method to tol where for an appropriate norm M{|.|}
920    
921                 |self.getResidual()|<tol*|self.getRightHandSide()|         M{|L{getResidual}()|<tol*|L{getRightHandSide}()|}
922    
923         defines the stopping criterion.         defines the stopping criterion.
924    
925         @param tol: new tolerance for the solver. If the tol is lower then the current tolerence         @param tol: new tolerance for the solver. If the tol is lower then the current tolerence
926                     the system will be resolved.                     the system will be resolved.
927         @type solver: C{float}         @type tol: positive C{float}
928         @raise ValueException: if tolerance is not positive.         @raise ValueException: if tolerance is not positive.
929         """         """
930         if not tol>0:         if not tol>0:
# Line 634  class LinearPDE: Line 949  class LinearPDE:
949     def isSymmetric(self):     def isSymmetric(self):
950        """        """
951        checks if symmetry is indicated.        checks if symmetry is indicated.
952        
953        @return : True is a symmetric PDE is indicated, otherwise False is returned        @return: True is a symmetric PDE is indicated, otherwise False is returned
954        @rtype : C{bool}        @rtype: C{bool}
955        """        """
956        return self.__sym        return self.__sym
957    
# Line 661  class LinearPDE: Line 976  class LinearPDE:
976     def setSymmetryTo(self,flag=False):     def setSymmetryTo(self,flag=False):
977        """        """
978        sets the symmetry flag to flag        sets the symmetry flag to flag
979    
980        @param flag: If flag, the symmetry flag is set otherwise the symmetry flag is released.        @param flag: If flag, the symmetry flag is set otherwise the symmetry flag is released.
981        @type flag: C{bool}        @type flag: C{bool}
982        """        """
# Line 670  class LinearPDE: Line 985  class LinearPDE:
985        else:        else:
986           self.setSymmetryOff()           self.setSymmetryOff()
987    
     
988     # =============================================================================     # =============================================================================
989     # function space handling for the equation as well as the solution     # function space handling for the equation as well as the solution
990     # =============================================================================     # =============================================================================
991     def setReducedOrderOn(self):     def setReducedOrderOn(self):
992       """       """
993       switches on reduced order for solution and equation representation       switches on reduced order for solution and equation representation
994    
995         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
996       """       """
997       self.setReducedOrderForSolutionOn()       self.setReducedOrderForSolutionOn()
998       self.setReducedOrderForEquationOn()       self.setReducedOrderForEquationOn()
# Line 684  class LinearPDE: Line 1000  class LinearPDE:
1000     def setReducedOrderOff(self):     def setReducedOrderOff(self):
1001       """       """
1002       switches off reduced order for solution and equation representation       switches off reduced order for solution and equation representation
1003    
1004         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1005       """       """
1006       self.setReducedOrderForSolutionOff()       self.setReducedOrderForSolutionOff()
1007       self.setReducedOrderForEquationOff()       self.setReducedOrderForEquationOff()
1008    
1009     def setReducedOrderTo(self,flag=False):     def setReducedOrderTo(self,flag=False):
1010       """       """
1011       sets order reduction for both solution and equation representation according to flag.       sets order reduction for both solution and equation representation according to flag.
1012         @param flag: if flag is True, the order reduction is switched on for both  solution and equation representation, otherwise or
      @param flag: if flag is True, the order reduction is switched on for both  solution and equation representation, otherwise or  
1013                    if flag is not present order reduction is switched off                    if flag is not present order reduction is switched off
1014       @type flag: C{bool}       @type flag: C{bool}
1015         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1016       """       """
1017       self.setReducedOrderForSolutionTo(flag)       self.setReducedOrderForSolutionTo(flag)
1018       self.setReducedOrderForEquationTo(flag)       self.setReducedOrderForEquationTo(flag)
# Line 703  class LinearPDE: Line 1021  class LinearPDE:
1021     def setReducedOrderForSolutionOn(self):     def setReducedOrderForSolutionOn(self):
1022       """       """
1023       switches on reduced order for solution representation       switches on reduced order for solution representation
1024    
1025         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1026       """       """
1027       new_fs=escript.ReducedSolution(self.getDomain())       if not self.__reduce_solution_order:
1028       if self.getFunctionSpaceForSolution()!=new_fs:           if self.__altered_coefficients:
1029                  raise RuntimeError,"order cannot be altered after coefficients have been defined."
1030           self.trace("Reduced order is used to solution representation.")           self.trace("Reduced order is used to solution representation.")
1031           self.__column_function_space=new_fs           self.__reduce_solution_order=True
1032           self.__resetSystem()           self.__resetSystem()
1033    
1034     def setReducedOrderForSolutionOff(self):     def setReducedOrderForSolutionOff(self):
1035       """       """
1036       switches off reduced order for solution representation       switches off reduced order for solution representation
1037    
1038         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1039       """       """
1040       new_fs=escript.Solution(self.getDomain())       if self.__reduce_solution_order:
1041       if self.getFunctionSpaceForSolution()!=new_fs:           if self.__altered_coefficients:
1042                  raise RuntimeError,"order cannot be altered after coefficients have been defined."
1043           self.trace("Full order is used to interpolate solution.")           self.trace("Full order is used to interpolate solution.")
1044           self.__column_function_space=new_fs           self.__reduce_solution_order=False
1045           self.__resetSystem()           self.__resetSystem()
1046    
1047     def setReducedOrderForSolutionTo(self,flag=False):     def setReducedOrderForSolutionTo(self,flag=False):
1048       """       """
1049       sets order for test functions according to flag       sets order for test functions according to flag
1050    
1051       @param flag: if flag is True, the order reduction is switched on for solution representation, otherwise or       @param flag: if flag is True, the order reduction is switched on for solution representation, otherwise or
1052                    if flag is not present order reduction is switched off                    if flag is not present order reduction is switched off
1053       @type flag: C{bool}       @type flag: C{bool}
1054         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1055       """       """
1056       if flag:       if flag:
1057          self.setReducedOrderForSolutionOn()          self.setReducedOrderForSolutionOn()
# Line 736  class LinearPDE: Line 1061  class LinearPDE:
1061     def setReducedOrderForEquationOn(self):     def setReducedOrderForEquationOn(self):
1062       """       """
1063       switches on reduced order for equation representation       switches on reduced order for equation representation
1064    
1065         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1066       """       """
1067       new_fs=escript.ReducedSolution(self.getDomain())       if not self.__reduce_equation_order:
1068       if self.getFunctionSpaceForEquation()!=new_fs:           if self.__altered_coefficients:
1069                  raise RuntimeError,"order cannot be altered after coefficients have been defined."
1070           self.trace("Reduced order is used for test functions.")           self.trace("Reduced order is used for test functions.")
1071           self.__row_function_space=new_fs           self.__reduce_equation_order=True
1072           self.__resetSystem()           self.__resetSystem()
1073    
1074     def setReducedOrderForEquationOff(self):     def setReducedOrderForEquationOff(self):
1075       """       """
1076       switches off reduced order for equation representation       switches off reduced order for equation representation
1077    
1078         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1079       """       """
1080       new_fs=escript.Solution(self.getDomain())       if self.__reduce_equation_order:
1081       if self.getFunctionSpaceForEquation()!=new_fs:           if self.__altered_coefficients:
1082                  raise RuntimeError,"order cannot be altered after coefficients have been defined."
1083           self.trace("Full order is used for test functions.")           self.trace("Full order is used for test functions.")
1084           self.__row_function_space=new_fs           self.__reduce_equation_order=False
1085           self.__resetSystem()           self.__resetSystem()
1086    
1087     def setReducedOrderForEquationTo(self,flag=False):     def setReducedOrderForEquationTo(self,flag=False):
1088       """       """
1089       sets order for test functions according to flag       sets order for test functions according to flag
1090    
1091       @param flag: if flag is True, the order reduction is switched on for equation representation, otherwise or       @param flag: if flag is True, the order reduction is switched on for equation representation, otherwise or
1092                    if flag is not present order reduction is switched off                    if flag is not present order reduction is switched off
1093       @type flag: C{bool}       @type flag: C{bool}
1094         @raise RuntimeError: if order reduction is altered after a coefficient has been set.
1095       """       """
1096       if flag:       if flag:
1097          self.setReducedOrderForEquationOn()          self.setReducedOrderForEquationOn()
# Line 773  class LinearPDE: Line 1105  class LinearPDE:
1105       """       """
1106       reassess the matrix type and, if a new matrix is needed, resets the system.       reassess the matrix type and, if a new matrix is needed, resets the system.
1107       """       """
1108       new_matrix_type=self.getDomain().getSystemMatrixTypeId(self.getSolverMethod(),self.isSymmetric())       new_matrix_type=self.getDomain().getSystemMatrixTypeId(self.getSolverMethod()[0],self.getSolverPackage(),self.isSymmetric())
1109       if not new_matrix_type==self.__matrix_type:       if not new_matrix_type==self.__matrix_type:
1110           self.trace("Matrix type is now %d."%new_matrix_type)           self.trace("Matrix type is now %d."%new_matrix_type)
1111           self.__matrix_type=new_matrix_type           self.__matrix_type=new_matrix_type
1112           self.__resetSystem()           self.__resetSystem()
1113     #     #
1114     #   rebuild switches :     #   rebuild switches :
1115     #     #
1116     def __invalidateSolution(self):     def __invalidateSolution(self):
1117         """         """
1118         indicates the PDE has to be resolved if the solution is requested         indicates the PDE has to be resolved if the solution is requested
# Line 792  class LinearPDE: Line 1124  class LinearPDE:
1124         """         """
1125         indicates the operator has to be rebuilt next time it is used         indicates the operator has to be rebuilt next time it is used
1126         """         """
1127         if self.__operator_isValid: self.trace("Operator has to be rebuilt.")         if self.__operator_is_Valid: self.trace("Operator has to be rebuilt.")
1128         self.__invalidateSolution()         self.__invalidateSolution()
1129         self.__operator_isValid=False         self.__operator_is_Valid=False
1130    
1131     def __invalidateRightHandSide(self):     def __invalidateRightHandSide(self):
1132         """         """
# Line 819  class LinearPDE: Line 1151  class LinearPDE:
1151         """         """
1152         self.trace("New System is built from scratch.")         self.trace("New System is built from scratch.")
1153         self.__operator=escript.Operator()         self.__operator=escript.Operator()
1154         self.__operator_isValid=False         self.__operator_is_Valid=False
1155         self.__righthandside=escript.Data()         self.__righthandside=escript.Data()
1156         self.__righthandside_isValid=False         self.__righthandside_isValid=False
1157         self.__solution=escript.Data()         self.__solution=escript.Data()
1158         self.__solution_isValid=False         self.__solution_isValid=False
1159     #     #
1160     #    system initialization:     #    system initialization:
1161     #     #
1162     def __getNewOperator(self):     def __getNewOperator(self):
1163         """         """
1164         returns an instance of a new operator         returns an instance of a new operator
# Line 888  class LinearPDE: Line 1220  class LinearPDE:
1220         if self.__operator.isEmpty():         if self.__operator.isEmpty():
1221             self.__operator=self.__getNewOperator()             self.__operator=self.__getNewOperator()
1222         else:         else:
1223             self.__operator.setValue(0.)             self.__operator.resetValues()
1224             self.trace("Operator reset to zero")             self.trace("Operator reset to zero")
1225         return self.__operator         return self.__operator
1226    
# Line 909  class LinearPDE: Line 1241  class LinearPDE:
1241               else:               else:
1242                  r_s=escript.Data(r,self.getFunctionSpaceForSolution())                  r_s=escript.Data(r,self.getFunctionSpaceForSolution())
1243               u.copyWithMask(r_s,col_q)               u.copyWithMask(r_s,col_q)
1244               if not self.__righthandside.isEmpty():               if not self.__righthandside.isEmpty():
1245                  self.__righthandside-=self.__operator*u                  self.__righthandside-=self.__operator*u
1246                  self.__righthandside=self.copyConstraint(self.__righthandside)                  self.__righthandside=self.copyConstraint(self.__righthandside)
1247               self.__operator.nullifyRowsAndCols(row_q,col_q,1.)               self.__operator.nullifyRowsAndCols(row_q,col_q,1.)
# Line 920  class LinearPDE: Line 1252  class LinearPDE:
1252       """       """
1253       return the value of the coefficient name of the general PDE.       return the value of the coefficient name of the general PDE.
1254    
1255       @note This method is called by the assembling routine it can be overwritten       @note: This method is called by the assembling routine it can be overwritten
1256             to map coefficients of a particular PDE to the general PDE.             to map coefficients of a particular PDE to the general PDE.
1257         @param name: name of the coefficient requested.
      @param name: name of the coefficient requested.  
1258       @type name: C{string}       @type name: C{string}
1259       @return : the value of the coefficient  name       @return: the value of the coefficient  name
1260       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
1261       @raise IllegalCoefficient: if name is not one of coefficients       @raise IllegalCoefficient: if name is not one of coefficients
1262                    "A", "B", "C", "D", "X", "Y", "d", "y", "d_contact", "y_contact", "r" or "q".                    M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1263       """       """
1264       if self.hasCoefficientOfGeneralPDE(name):       if self.hasCoefficientOfGeneralPDE(name):
1265          return self.getCoefficient(name)          return self.getCoefficient(name)
# Line 938  class LinearPDE: Line 1269  class LinearPDE:
1269     def hasCoefficientOfGeneralPDE(self,name):     def hasCoefficientOfGeneralPDE(self,name):
1270       """       """
1271       checks if name is a the name of a coefficient of the general PDE.       checks if name is a the name of a coefficient of the general PDE.
1272        
1273       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1274       @type name: C{string}       @type name: C{string}
1275       @return : True if name is the name of a coefficient of the general PDE. Otherwise False.       @return: True if name is the name of a coefficient of the general PDE. Otherwise False.
1276       @rtype : C{bool}       @rtype: C{bool}
1277        
1278       """       """
1279       return self.__COEFFICIENTS_OF_GENEARL_PDE.has_key(name)       return self.__COEFFICIENTS_OF_GENEARL_PDE.has_key(name)
1280    
# Line 953  class LinearPDE: Line 1284  class LinearPDE:
1284    
1285       @param name: name of the coefficient requested.       @param name: name of the coefficient requested.
1286       @type name: C{string}       @type name: C{string}
1287       @return : a coefficient name initialized to 0.       @return: a coefficient name initialized to 0.
1288       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
1289       @raise IllegalCoefficient: if name is not one of coefficients       @raise IllegalCoefficient: if name is not one of coefficients
1290                    "A", "B", "C", "D", "X", "Y", "d", "y", "d_contact", "y_contact", "r" or "q".                    M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1291       """       """
1292       if self.hasCoefficientOfGeneralPDE(name):       if self.hasCoefficientOfGeneralPDE(name):
1293          return escript.Data(0,self.getShapeOfCoefficientOfGeneralPDE(name),self.getFunctionSpaceForCoefficientOfGeneralPDE(name))          return escript.Data(0,self.getShapeOfCoefficientOfGeneralPDE(name),self.getFunctionSpaceForCoefficientOfGeneralPDE(name))
# Line 965  class LinearPDE: Line 1296  class LinearPDE:
1296    
1297     def getFunctionSpaceForCoefficientOfGeneralPDE(self,name):     def getFunctionSpaceForCoefficientOfGeneralPDE(self,name):
1298       """       """
1299       return the L{escript.FunctionSpace} to be used for coefficient name of the general PDE       return the L{FunctionSpace<escript.FunctionSpace>} to be used for coefficient name of the general PDE
1300    
1301       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1302       @type name: C{string}       @type name: C{string}
1303       @return : the function space to be used for coefficient name       @return: the function space to be used for coefficient name
1304       @rtype : L{escript.FunctionSpace}       @rtype: L{FunctionSpace<escript.FunctionSpace>}
1305       @raise IllegalCoefficient: if name is not one of coefficients       @raise IllegalCoefficient: if name is not one of coefficients
1306                    "A", "B", "C", "D", "X", "Y", "d", "y", "d_contact", "y_contact", "r" or "q".                    M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1307       """       """
1308       if self.hasCoefficientOfGeneralPDE(name):       if self.hasCoefficientOfGeneralPDE(name):
1309          return self.__COEFFICIENTS_OF_GENEARL_PDE[name].getFunctionSpace(self.getDomain())          return self.__COEFFICIENTS_OF_GENEARL_PDE[name].getFunctionSpace(self.getDomain())
# Line 985  class LinearPDE: Line 1316  class LinearPDE:
1316    
1317       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1318       @type name: C{string}       @type name: C{string}
1319       @return : the shape of the coefficient name       @return: the shape of the coefficient name
1320       @rtype : C{tuple} of C{int}       @rtype: C{tuple} of C{int}
1321       @raise IllegalCoefficient: if name is not one of coefficients       @raise IllegalCoefficient: if name is not one of coefficients
1322                    "A", "B", "C", "D", "X", "Y", "d", "y", "d_contact", "y_contact", "r" or "q".                    M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
   
1323       """       """
1324       if self.hasCoefficientOfGeneralPDE(name):       if self.hasCoefficientOfGeneralPDE(name):
1325          return self.__COEFFICIENTS_OF_GENEARL_PDE[name].getShape(self.getDomain(),self.getNumEquations(),self.getNumSolutions())          return self.__COEFFICIENTS_OF_GENEARL_PDE[name].getShape(self.getDomain(),self.getNumEquations(),self.getNumSolutions())
# Line 1003  class LinearPDE: Line 1333  class LinearPDE:
1333       """       """
1334       returns the value of the coefficient name       returns the value of the coefficient name
1335    
1336       @param name: name of the coefficient requested.       @param name: name of the coefficient requested.
1337       @type name: C{string}       @type name: C{string}
1338       @return : the value of the coefficient name       @return: the value of the coefficient name
1339       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
1340       @raise IllegalCoefficient: if name is not a coefficient of the PDE.       @raise IllegalCoefficient: if name is not a coefficient of the PDE.
1341       """       """
1342       if self.hasCoefficient(name):       if self.hasCoefficient(name):
# Line 1020  class LinearPDE: Line 1350  class LinearPDE:
1350    
1351       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1352       @type name: C{string}       @type name: C{string}
1353       @return : True if name is the name of a coefficient of the general PDE. Otherwise False.       @return: True if name is the name of a coefficient of the general PDE. Otherwise False.
1354       @rtype : C{bool}       @rtype: C{bool}
1355       """       """
1356       return self.COEFFICIENTS.has_key(name)       return self.COEFFICIENTS.has_key(name)
1357    
1358     def createCoefficient(self, name):     def createCoefficient(self, name):
1359       """       """
1360       create a L{escript.Data} object corresponding to coefficient name       create a L{Data<escript.Data>} object corresponding to coefficient name
1361    
1362       @return : a coefficient name initialized to 0.       @return: a coefficient name initialized to 0.
1363       @rtype : L{escript.Data}       @rtype: L{Data<escript.Data>}
1364       @raise IllegalCoefficient: if name is not a coefficient of the PDE.       @raise IllegalCoefficient: if name is not a coefficient of the PDE.
1365       """       """
1366       if self.hasCoefficient(name):       if self.hasCoefficient(name):
# Line 1040  class LinearPDE: Line 1370  class LinearPDE:
1370    
1371     def getFunctionSpaceForCoefficient(self,name):     def getFunctionSpaceForCoefficient(self,name):
1372       """       """
1373       return the L{escript.FunctionSpace} to be used for coefficient name       return the L{FunctionSpace<escript.FunctionSpace>} to be used for coefficient name
1374    
1375       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1376       @type name: C{string}       @type name: C{string}
1377       @return : the function space to be used for coefficient name       @return: the function space to be used for coefficient name
1378       @rtype : L{escript.FunctionSpace}       @rtype: L{FunctionSpace<escript.FunctionSpace>}
1379       @raise IllegalCoefficient: if name is not a coefficient of the PDE.       @raise IllegalCoefficient: if name is not a coefficient of the PDE.
1380       """       """
1381       if self.hasCoefficient(name):       if self.hasCoefficient(name):
1382          return self.COEFFICIENTS[name].getFunctionSpace(self.getDomain())          return self.COEFFICIENTS[name].getFunctionSpace(self.getDomain())
1383       else:       else:
1384          raise ValueError,"unknown coefficient %s requested"%name          raise ValueError,"unknown coefficient %s requested"%name
   
1385     def getShapeOfCoefficient(self,name):     def getShapeOfCoefficient(self,name):
1386       """       """
1387       return the shape of the coefficient name       return the shape of the coefficient name
1388    
1389       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1390       @type name: C{string}       @type name: C{string}
1391       @return : the shape of the coefficient name       @return: the shape of the coefficient name
1392       @rtype : C{tuple} of C{int}       @rtype: C{tuple} of C{int}
1393       @raise IllegalCoefficient: if name is not a coefficient of the PDE.       @raise IllegalCoefficient: if name is not a coefficient of the PDE.
1394       """       """
1395       if self.hasCoefficient(name):       if self.hasCoefficient(name):
# Line 1082  class LinearPDE: Line 1411  class LinearPDE:
1411       @param name: name of the coefficient enquired.       @param name: name of the coefficient enquired.
1412       @type name: C{string}       @type name: C{string}
1413       @raise IllegalCoefficient: if name is not a coefficient of the PDE.       @raise IllegalCoefficient: if name is not a coefficient of the PDE.
1414         @note: if name is q or r, the method will not trigger a rebuilt of the system as constraints are applied to the solved system.
1415       """       """
1416       if self.hasCoefficient(name):       if self.hasCoefficient(name):
1417          self.trace("Coefficient %s has been altered."%name)          self.trace("Coefficient %s has been altered."%name)
1418          if self.COEFFICIENTS[name].isAlteringOperator(): self.__invalidateOperator()          if not ((name=="q" or name=="r") and self.isUsingLumping()):
1419          if self.COEFFICIENTS[name].isAlteringRightHandSide(): self.__invalidateRightHandSide()             if self.COEFFICIENTS[name].isAlteringOperator(): self.__invalidateOperator()
1420               if self.COEFFICIENTS[name].isAlteringRightHandSide(): self.__invalidateRightHandSide()
1421       else:       else:
1422          raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name          raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1423    
1424     def copyConstraint(self,u):     def copyConstraint(self,u):
1425        """        """
1426        copies the constraint into u and returns u.        copies the constraint into u and returns u.
   
       @param u: a function of rank 0 is a single PDE is solved and of shape (numSolution,) for a system of PDEs  
       @type u: L{escript.Data}  
       @return : the input u modified by the constraints.  
       @rtype : L{escript.Data}  
       @warning: u is altered if it has the appropriate L{escript.FunctionSpace}  
1427    
1428          @param u: a function of rank 0 is a single PDE is solved and of shape (numSolution,) for a system of PDEs
1429          @type u: L{Data<escript.Data>}
1430          @return: the input u modified by the constraints.
1431          @rtype: L{Data<escript.Data>}
1432          @warning: u is altered if it has the appropriate L{FunctionSpace<escript.FunctionSpace>}
1433        """        """
1434        q=self.getCoefficientOfGeneralPDE("q")        q=self.getCoefficientOfGeneralPDE("q")
1435        r=self.getCoefficientOfGeneralPDE("r")        r=self.getCoefficientOfGeneralPDE("r")
# Line 1116  class LinearPDE: Line 1446  class LinearPDE:
1446        """        """
1447        sets new values to coefficients        sets new values to coefficients
1448    
1449        @note This method is called by the assembling routine it can be overwritten        @param coefficients: new values assigned to coefficients
1450             to map coefficients of a particular PDE to the general PDE.        @keyword A: value for coefficient A.
1451          @type A: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
       @param name: name of the coefficient requested.  
       @type name: C{string}  
       @keyword A: value for coefficient A.  
       @type A: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.  
1452        @keyword B: value for coefficient B        @keyword B: value for coefficient B
1453        @type B: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.        @type B: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1454        @keyword C: value for coefficient C        @keyword C: value for coefficient C
1455        @type C: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.        @type C: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1456        @keyword D: value for coefficient D        @keyword D: value for coefficient D
1457        @type D: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.        @type D: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1458        @keyword X: value for coefficient X        @keyword X: value for coefficient X
1459        @type X: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.        @type X: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1460        @keyword Y: value for coefficient Y        @keyword Y: value for coefficient Y
1461        @type Y: any type that can be interpreted as L{escript.Data} object on L{escript.Function}.        @type Y: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1462        @keyword d: value for coefficient d        @keyword d: value for coefficient d
1463        @type d: any type that can be interpreted as L{escript.Data} object on L{escript.FunctionOnBoundary}.        @type d: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1464        @keyword y: value for coefficient y        @keyword y: value for coefficient y
1465        @type y: any type that can be interpreted as L{escript.Data} object on L{escript.FunctionOnBoundary}.        @type y: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1466        @keyword d_contact: value for coefficient d_contact        @keyword d_contact: value for coefficient d_contact
1467        @type d_contact: any type that can be interpreted as L{escript.Data} object on L{escript.FunctionOnContactOne}.        @type d_contact: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
1468                         or  L{escript.FunctionOnContactZero}.                         or  L{FunctionOnContactZero<escript.FunctionOnContactZero>}.
1469        @keyword y_contact: value for coefficient y_contact        @keyword y_contact: value for coefficient y_contact
1470        @type y_contact: any type that can be interpreted as L{escript.Data} object on L{escript.FunctionOnContactOne}.        @type y_contact: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
1471                         or  L{escript.FunctionOnContactZero}.                         or  L{FunctionOnContactZero<escript.FunctionOnContactZero>}.
1472        @keyword r: values prescribed to the solution at the locations of constraints        @keyword r: values prescribed to the solution at the locations of constraints
1473        @type r: any type that can be interpreted as L{escript.Data} object on L{escript.Solution} or L{escript.ReducedSolution}        @type r: any type that can be casted to L{Data<escript.Data>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1474                 depending of reduced order is used for the solution.                 depending of reduced order is used for the solution.
1475        @keyword q: mask for location of constraints        @keyword q: mask for location of constraints
1476        @type q: any type that can be interpreted as L{escript.Data} object on L{escript.Solution} or L{escript.ReducedSolution}        @type q: any type that can be casted to L{Data<escript.Data>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1477                 depending of reduced order is used for the representation of the equation.                 depending of reduced order is used for the representation of the equation.
1478        @raise IllegalCoefficient: if an unknown coefficient keyword is used.        @raise IllegalCoefficient: if an unknown coefficient keyword is used.
   
1479        """        """
1480        # check if the coefficients are  legal:        # check if the coefficients are  legal:
1481        for i in coefficients.iterkeys():        for i in coefficients.iterkeys():
# Line 1178  class LinearPDE: Line 1503  class LinearPDE:
1503        # now we check the shape of the coefficient if numEquations and numSolutions are set:        # now we check the shape of the coefficient if numEquations and numSolutions are set:
1504        for i,d in coefficients.iteritems():        for i,d in coefficients.iteritems():
1505          try:          try:
1506             self.COEFFICIENTS[i].setValue(self.getDomain(),self.getNumEquations(),self.getNumSolutions(),d)             self.COEFFICIENTS[i].setValue(self.getDomain(),self.getNumEquations(),self.getNumSolutions(),self.reduceEquationOrder(),self.reduceSolutionOrder(),d)
1507          except IllegalCoefficientValue,m:          except IllegalCoefficientValue,m:
1508             raise IllegalCoefficientValue("Coefficient %s:%s"%(i,m))             raise IllegalCoefficientValue("Coefficient %s:%s"%(i,m))
1509          self.alteredCoefficient(i)          self.alteredCoefficient(i)
1510    
1511          self.__altered_coefficients=True
1512        # check if the systrem is inhomogeneous:        # check if the systrem is inhomogeneous:
1513        if len(coefficients)>0 and not self.isUsingLumping():        if len(coefficients)>0 and not self.isUsingLumping():
1514           q=self.getCoefficientOfGeneralPDE("q")           q=self.getCoefficientOfGeneralPDE("q")
1515           r=self.getCoefficientOfGeneralPDE("r")           r=self.getCoefficientOfGeneralPDE("r")
1516           homogeneous_constraint=True           homogeneous_constraint=True
1517           if not q.isEmpty() and not r.isEmpty():           if not q.isEmpty() and not r.isEmpty():
1518               if util.Lsup(q*r)>=1.e-13*util.Lsup(r):               if util.Lsup(q*r)>=1.e-13*util.Lsup(r):
1519                 self.trace("Inhomogeneous constraint detected.")                 self.trace("Inhomogeneous constraint detected.")
1520                 self.__invalidateSystem()                 self.__invalidateSystem()
1521    
   
1522     def getSystem(self):     def getSystem(self):
1523         """         """
1524         return the operator and right hand side of the PDE         return the operator and right hand side of the PDE
1525    
1526           @return: the discrete version of the PDE
1527           @rtype: C{tuple} of L{Operator,<escript.Operator>} and L{Data<escript.Data>}.
1528         """         """
1529         if not self.__operator_isValid or not self.__righthandside_isValid:         if not self.__operator_is_Valid or not self.__righthandside_isValid:
1530            if self.isUsingLumping():            if self.isUsingLumping():
1531                if not self.__operator_isValid:                if not self.__operator_is_Valid:
1532                   if not self.getFunctionSpaceForEquation()==self.getFunctionSpaceForSolution(): raise TypeError,"Lumped matrix requires same order for equations and unknowns"                   if not self.getFunctionSpaceForEquation()==self.getFunctionSpaceForSolution(): raise TypeError,"Lumped matrix requires same order for equations and unknowns"
1533                   if not self.getCoefficientOfGeneralPDE("A").isEmpty(): raise Warning,"Lumped matrix does not allow coefficient A"                   if not self.getCoefficientOfGeneralPDE("A").isEmpty(): raise Warning,"Using coefficient A in lumped matrix can produce wrong results"
1534                   if not self.getCoefficientOfGeneralPDE("B").isEmpty(): raise Warning,"Lumped matrix does not allow coefficient B"                   if not self.getCoefficientOfGeneralPDE("B").isEmpty(): raise Warning,"Using coefficient B in lumped matrix can produce wrong results"
1535                   if not self.getCoefficientOfGeneralPDE("C").isEmpty(): raise Warning,"Lumped matrix does not allow coefficient C"                   if not self.getCoefficientOfGeneralPDE("C").isEmpty(): raise Warning,"Using coefficient C in lumped matrix can produce wrong results"
1536                   mat=self.__getNewOperator()                   mat=self.__getNewOperator()
1537                   self.getDomain().addPDEToSystem(mat,escript.Data(), \                   self.getDomain().addPDEToSystem(mat,escript.Data(), \
1538                             self.getCoefficientOfGeneralPDE("A"), \                             self.getCoefficientOfGeneralPDE("A"), \
# Line 1220  class LinearPDE: Line 1548  class LinearPDE:
1548                   self.__operator=1./(mat*escript.Data(1,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True))                   self.__operator=1./(mat*escript.Data(1,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True))
1549                   del mat                   del mat
1550                   self.trace("New lumped operator has been built.")                   self.trace("New lumped operator has been built.")
1551                   self.__operator_isValid=True                   self.__operator_is_Valid=True
1552                if not self.__righthandside_isValid:                if not self.__righthandside_isValid:
1553                   self.getDomain().addPDEToRHS(self.__makeFreshRightHandSide(), \                   self.getDomain().addPDEToRHS(self.__makeFreshRightHandSide(), \
1554                                 self.getCoefficientOfGeneralPDE("X"), \                                 self.getCoefficientOfGeneralPDE("X"), \
# Line 1230  class LinearPDE: Line 1558  class LinearPDE:
1558                   self.trace("New right hand side as been built.")                   self.trace("New right hand side as been built.")
1559                   self.__righthandside_isValid=True                   self.__righthandside_isValid=True
1560            else:            else:
1561               if not self.__operator_isValid and not self.__righthandside_isValid:               if not self.__operator_is_Valid and not self.__righthandside_isValid:
1562                   self.getDomain().addPDEToSystem(self.__makeFreshOperator(),self.__makeFreshRightHandSide(), \                   self.getDomain().addPDEToSystem(self.__makeFreshOperator(),self.__makeFreshRightHandSide(), \
1563                                 self.getCoefficientOfGeneralPDE("A"), \                                 self.getCoefficientOfGeneralPDE("A"), \
1564                                 self.getCoefficientOfGeneralPDE("B"), \                                 self.getCoefficientOfGeneralPDE("B"), \
# Line 1245  class LinearPDE: Line 1573  class LinearPDE:
1573                   self.__applyConstraint()                   self.__applyConstraint()
1574                   self.__righthandside=self.copyConstraint(self.__righthandside)                   self.__righthandside=self.copyConstraint(self.__righthandside)
1575                   self.trace("New system has been built.")                   self.trace("New system has been built.")
1576                   self.__operator_isValid=True                   self.__operator_is_Valid=True
1577                   self.__righthandside_isValid=True                   self.__righthandside_isValid=True
1578               elif not self.__righthandside_isValid:               elif not self.__righthandside_isValid:
1579                   self.getDomain().addPDEToRHS(self.__makeFreshRightHandSide(), \                   self.getDomain().addPDEToRHS(self.__makeFreshRightHandSide(), \
# Line 1256  class LinearPDE: Line 1584  class LinearPDE:
1584                   self.__righthandside=self.copyConstraint(self.__righthandside)                   self.__righthandside=self.copyConstraint(self.__righthandside)
1585                   self.trace("New right hand side has been built.")                   self.trace("New right hand side has been built.")
1586                   self.__righthandside_isValid=True                   self.__righthandside_isValid=True
1587               elif not self.__operator_isValid:               elif not self.__operator_is_Valid:
1588                   self.getDomain().addPDEToSystem(self.__makeFreshOperator(),escript.Data(), \                   self.getDomain().addPDEToSystem(self.__makeFreshOperator(),escript.Data(), \
1589                              self.getCoefficientOfGeneralPDE("A"), \                              self.getCoefficientOfGeneralPDE("A"), \
1590                              self.getCoefficientOfGeneralPDE("B"), \                              self.getCoefficientOfGeneralPDE("B"), \
# Line 1270  class LinearPDE: Line 1598  class LinearPDE:
1598                              escript.Data())                              escript.Data())
1599                   self.__applyConstraint()                   self.__applyConstraint()
1600                   self.trace("New operator has been built.")                   self.trace("New operator has been built.")
1601                   self.__operator_isValid=True                   self.__operator_is_Valid=True
1602         return (self.__operator,self.__righthandside)         return (self.__operator,self.__righthandside)
1603    
1604    
1605    class Poisson(LinearPDE):
1606       """
1607       Class to define a Poisson equation problem, which is genear L{LinearPDE} of the form
1608    
1609       M{-grad(grad(u)[j])[j] = f}
1610    
1611       with natural boundary conditons
1612    
1613       M{n[j]*grad(u)[j] = 0 }
1614    
1615       and constraints:
1616    
1617       M{u=0} where M{q>0}
1618    
1619       """
1620    
1621       def __init__(self,domain,debug=False):
1622         """
1623         initializes a new Poisson equation
1624    
1625         @param domain: domain of the PDE
1626         @type domain: L{Domain<escript.Domain>}
1627         @param debug: if True debug informations are printed.
1628    
1629         """
1630         super(Poisson, self).__init__(domain,1,1,debug)
1631         self.COEFFICIENTS={"f": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1632                              "q": PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH)}
1633         self.setSymmetryOn()
1634    
1635       def setValue(self,**coefficients):
1636         """
1637         sets new values to coefficients
1638    
1639         @param coefficients: new values assigned to coefficients
1640         @keyword f: value for right hand side M{f}
1641         @type f: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1642         @keyword q: mask for location of constraints
1643         @type q: any type that can be casted to rank zeo L{Data<escript.Data>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1644                   depending of reduced order is used for the representation of the equation.
1645         @raise IllegalCoefficient: if an unknown coefficient keyword is used.
1646         """
1647         super(Poisson, self).setValue(**coefficients)
1648    
1649       def getCoefficientOfGeneralPDE(self,name):
1650         """
1651         return the value of the coefficient name of the general PDE
1652         @param name: name of the coefficient requested.
1653         @type name: C{string}
1654         @return: the value of the coefficient  name
1655         @rtype: L{Data<escript.Data>}
1656         @raise IllegalCoefficient: if name is not one of coefficients
1657                      M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1658         @note: This method is called by the assembling routine to map the Possion equation onto the general PDE.
1659         """
1660         if name == "A" :
1661             return escript.Data(util.kronecker(self.getDim()),escript.Function(self.getDomain()))
1662         elif name == "B" :
1663             return escript.Data()
1664         elif name == "C" :
1665             return escript.Data()
1666         elif name == "D" :
1667             return escript.Data()
1668         elif name == "X" :
1669             return escript.Data()
1670         elif name == "Y" :
1671             return self.getCoefficient("f")
1672         elif name == "d" :
1673             return escript.Data()
1674         elif name == "y" :
1675             return escript.Data()
1676         elif name == "d_contact" :
1677             return escript.Data()
1678         elif name == "y_contact" :
1679             return escript.Data()
1680         elif name == "r" :
1681             return escript.Data()
1682         elif name == "q" :
1683             return self.getCoefficient("q")
1684         else:
1685            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1686    
1687    class Helmholtz(LinearPDE):
1688       """
1689       Class to define a Helmhotz equation problem, which is genear L{LinearPDE} of the form
1690    
1691       M{S{omega}*u - grad(k*grad(u)[j])[j] = f}
1692    
1693       with natural boundary conditons
1694    
1695       M{k*n[j]*grad(u)[j] = g- S{alpha}u }
1696    
1697       and constraints:
1698    
1699       M{u=r} where M{q>0}
1700    
 class AdvectivePDE(LinearPDE):  
1701     """     """
    Class to handle a linear PDE dominated by advective terms:  
1702    
1703     class to define a linear PDE of the form     def __init__(self,domain,debug=False):
1704         """
1705         initializes a new Poisson equation
1706    
1707         @param domain: domain of the PDE
1708         @type domain: L{Domain<escript.Domain>}
1709         @param debug: if True debug informations are printed.
1710    
1711         """
1712         super(Helmholtz, self).__init__(domain,1,1,debug)
1713         self.COEFFICIENTS={"omega": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.OPERATOR),
1714                            "k": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.OPERATOR),
1715                            "f": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1716                            "alpha": PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.OPERATOR),
1717                            "g": PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1718                            "r": PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH),
1719                            "q": PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH)}
1720         self.setSymmetryOn()
1721    
1722       def setValue(self,**coefficients):
1723         """
1724         sets new values to coefficients
1725    
1726         @param coefficients: new values assigned to coefficients
1727         @keyword omega: value for coefficient M{S{omega}}
1728         @type omega: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1729         @keyword k: value for coefficeint M{k}
1730         @type k: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1731         @keyword f: value for right hand side M{f}
1732         @type f: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1733         @keyword alpha: value for right hand side M{S{alpha}}
1734         @type alpha: any type that can be casted to L{Scalar<escript.Scalar>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1735         @keyword g: value for right hand side M{g}
1736         @type g: any type that can be casted to L{Scalar<escript.Scalar>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1737         @keyword r: prescribed values M{r} for the solution in constraints.
1738         @type r: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1739                   depending of reduced order is used for the representation of the equation.
1740         @keyword q: mask for location of constraints
1741         @type q: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1742                   depending of reduced order is used for the representation of the equation.
1743         @raise IllegalCoefficient: if an unknown coefficient keyword is used.
1744         """
1745         super(Helmholtz, self).setValue(**coefficients)
1746    
1747       def getCoefficientOfGeneralPDE(self,name):
1748         """
1749         return the value of the coefficient name of the general PDE
1750    
1751     \f[       @param name: name of the coefficient requested.
1752     -(A_{ijkl}u_{k,l})_{,j} -(B_{ijk}u_k)_{,j} + C_{ikl}u_{k,l} +D_{ik}u_k = - (X_{ij})_{,j} + Y_i       @type name: C{string}
1753     \f]       @return: the value of the coefficient  name
1754         @rtype: L{Data<escript.Data>}
1755         @raise IllegalCoefficient: if name is not one of coefficients
1756                      "A", M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1757         @note: This method is called by the assembling routine to map the Possion equation onto the general PDE.
1758         """
1759         if name == "A" :
1760             return escript.Data(numarray.identity(self.getDim()),escript.Function(self.getDomain()))*self.getCoefficient("k")
1761         elif name == "B" :
1762             return escript.Data()
1763         elif name == "C" :
1764             return escript.Data()
1765         elif name == "D" :
1766             return self.getCoefficient("omega")
1767         elif name == "X" :
1768             return escript.Data()
1769         elif name == "Y" :
1770             return self.getCoefficient("f")
1771         elif name == "d" :
1772             return self.getCoefficient("alpha")
1773         elif name == "y" :
1774             return self.getCoefficient("g")
1775         elif name == "d_contact" :
1776             return escript.Data()
1777         elif name == "y_contact" :
1778             return escript.Data()
1779         elif name == "r" :
1780             return self.getCoefficient("r")
1781         elif name == "q" :
1782             return self.getCoefficient("q")
1783         else:
1784            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1785    
1786     with boundary conditons:  class LameEquation(LinearPDE):
1787       """
1788       Class to define a Lame equation problem:
1789    
1790     \f[     M{-grad(S{mu}*(grad(u[i])[j]+grad(u[j])[i]))[j] - grad(S{lambda}*grad(u[j])[i])[j] = F_i -grad(S{sigma}[i,j])[j] }
    n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_{ik}u_k = - n_j*X_{ij} + y_i  
    \f]  
1791    
1792     and contact conditions     with natural boundary conditons:
1793    
1794     \f[     M{n[j]*(S{mu}*(grad(u[i])[j]+grad(u[j])[i]) - S{lambda}*grad(u[j])[i]) = f_i -n[j]*S{sigma}[i,j] }
    n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d^{contact}_{ik}[u_k] = - n_j*X_{ij} + y^{contact}_{i}  
    \f]  
1795    
1796     and constraints:     and constraints:
1797    
1798     \f[     M{u[i]=r[i]} where M{q[i]>0}
1799     u_i=r_i \quad \mathrm{where} \quad q_i>0  
1800     \f]     """
1801    
1802       def __init__(self,domain,debug=False):
1803          super(LameEquation, self).__init__(domain,\
1804                                             domain.getDim(),domain.getDim(),debug)
1805          self.COEFFICIENTS={ "lame_lambda"  : PDECoefficient(PDECoefficient.INTERIOR,(),PDECoefficient.OPERATOR),
1806                              "lame_mu"      : PDECoefficient(PDECoefficient.INTERIOR,(),PDECoefficient.OPERATOR),
1807                              "F"            : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1808                              "sigma"        : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,PDECoefficient.BY_DIM),PDECoefficient.RIGHTHANDSIDE),
1809                              "f"            : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1810                              "r"            : PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH),
1811                              "q"            : PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH)}
1812          self.setSymmetryOn()
1813    
1814       def setValue(self,**coefficients):
1815         """
1816         sets new values to coefficients
1817    
1818         @param coefficients: new values assigned to coefficients
1819         @keyword lame_mu: value for coefficient M{S{mu}}
1820         @type lame_mu: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1821         @keyword lame_lambda: value for coefficient M{S{lambda}}
1822         @type lame_lambda: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
1823         @keyword F: value for internal force M{F}
1824         @type F: any type that can be casted to L{Vector<escript.Vector>} object on L{Function<escript.Function>}
1825         @keyword sigma: value for initial stress M{S{sigma}}
1826         @type sigma: any type that can be casted to L{Tensor<escript.Tensor>} object on L{Function<escript.Function>}
1827         @keyword f: value for extrenal force M{f}
1828         @type f: any type that can be casted to L{Vector<escript.Vector>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}
1829         @keyword r: prescribed values M{r} for the solution in constraints.
1830         @type r: any type that can be casted to L{Vector<escript.Vector>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1831                   depending of reduced order is used for the representation of the equation.
1832         @keyword q: mask for location of constraints
1833         @type q: any type that can be casted to L{Vector<escript.Vector>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1834                   depending of reduced order is used for the representation of the equation.
1835         @raise IllegalCoefficient: if an unknown coefficient keyword is used.
1836         """
1837         super(LameEquation, self).setValue(**coefficients)
1838    
1839       def getCoefficientOfGeneralPDE(self,name):
1840         """
1841         return the value of the coefficient name of the general PDE
1842    
1843         @param name: name of the coefficient requested.
1844         @type name: C{string}
1845         @return: the value of the coefficient  name
1846         @rtype: L{Data<escript.Data>}
1847         @raise IllegalCoefficient: if name is not one of coefficients
1848                      "A", M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
1849         @note: This method is called by the assembling routine to map the Possion equation onto the general PDE.
1850         """
1851         if name == "A" :
1852             out =self.createCoefficientOfGeneralPDE("A")
1853             for i in range(self.getDim()):
1854               for j in range(self.getDim()):
1855                 out[i,i,j,j] += self.getCoefficient("lame_lambda")
1856                 out[i,j,j,i] += self.getCoefficient("lame_mu")
1857                 out[i,j,i,j] += self.getCoefficient("lame_mu")
1858             return out
1859         elif name == "B" :
1860             return escript.Data()
1861         elif name == "C" :
1862             return escript.Data()
1863         elif name == "D" :
1864             return escript.Data()
1865         elif name == "X" :
1866             return self.getCoefficient("sigma")
1867         elif name == "Y" :
1868             return self.getCoefficient("F")
1869         elif name == "d" :
1870             return escript.Data()
1871         elif name == "y" :
1872             return self.getCoefficient("f")
1873         elif name == "d_contact" :
1874             return escript.Data()
1875         elif name == "y_contact" :
1876             return escript.Data()
1877         elif name == "r" :
1878             return self.getCoefficient("r")
1879         elif name == "q" :
1880             return self.getCoefficient("q")
1881         else:
1882            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1883    
1884    class AdvectivePDE(LinearPDE):
1885     """     """
1886     def __init__(self,domain,numEquations=0,numSolutions=0,xi=None,debug=False):     In cases of PDEs dominated by the advection terms M{B} and M{C} against the adevctive terms M{A}
1887        LinearPDE.__init__(self,domain,numEquations,numSolutions,debug)     up-winding has been used.  The L{AdvectivePDE} class applies SUPG upwinding to the advective terms.
1888    
1889       In the following we set
1890    
1891       M{Z[j]=C[j]-B[j]}
1892    
1893       or
1894    
1895       M{Z[i,k,l]=C[i,k,l]-B[i,l,k]}
1896    
1897       To measure the dominance of the advective terms over the diffusive term M{A} the
1898       X{Pelclet number} M{P} is used. It is defined as
1899    
1900       M{P=h|Z|/(2|A|)}
1901    
1902       where M{|.|} denotes the L{length<util.length>} of the arument and M{h} is the local cell size
1903       from L{getSize<escript.Domain.getSize>}. Where M{|A|==0} M{P} is M{S{infinity}}.
1904    
1905       From the X{Pelclet number} the stabilization parameters M{S{Xi}} and M{S{Xi}} are calculated:
1906    
1907       M{S{Xi}=S{xi}(P) h/|Z|}
1908    
1909       where M{S{xi}} is a suitable function of the Peclet number.
1910    
1911       In the case of a single PDE the coefficient are up-dated in the following way:
1912             - M{A[i,j] S{<-} A[i,j] + S{Xi} * Z[j] * Z[l]}
1913             - M{B[j] S{<-} B[j] + S{Xi} * C[j] * D}
1914             - M{C[j] S{<-} C[j] + S{Xi} * B[j] * D}
1915             - M{X[j] S{<-} X[j] + S{Xi} * Z[j] * Y}
1916    
1917       Similar for the case of a systems of PDEs:
1918             - M{A[i,j,k,l] S{<-} A[i,j,k,l]+ S{delta}[p,m] * S{Xi} * Z[p,i,j] * Z[m,k,l]}
1919             - M{B[i,j,k] S{<-} B[i,j,k] +  S{delta}[p,m] * S{Xi} * D[p,k] * C[m,i,j]}
1920             - M{C[i,k,l] S{<-} C[i,k,l] +  S{delta}[p,m] * S{Xi} * D[p,k] * B[m,l,i]}
1921             - M{X[i,j] S{<-} X[i,j] + S{delta}[p,m] * S{Xi}  * Y[p] * Z[m,i,j]}
1922    
1923       where M{S{delta}} is L{kronecker}.
1924       Using upwinding in this form, introduces an additonal error which is proprtional to the cell size M{h}
1925       but with the intension to stabilize the solution.
1926    
1927       """
1928       def __init__(self,domain,numEquations=None,numSolutions=None,xi=None,debug=False):
1929          """
1930          creates a linear, steady, second order PDE on a L{Domain<escript.Domain>}
1931    
1932          @param domain: domain of the PDE
1933          @type domain: L{Domain<escript.Domain>}
1934          @param numEquations: number of equations. If numEquations==None the number of equations
1935                               is exracted from the PDE coefficients.
1936          @param numSolutions: number of solution components. If  numSolutions==None the number of solution components
1937                               is exracted from the PDE coefficients.
1938          @param xi: defines a function which returns for any given Preclet number as L{Scalar<escript.Scalar>} object the
1939                     M{S{xi}}-value used to define the stabilization parameters. If equal to None, L{ELMAN_RAMAGE} is used.
1940          @type xi: callable object which returns a L{Scalar<escript.Scalar>} object.
1941          @param debug: if True debug informations are printed.
1942          """
1943          super(AdvectivePDE, self).__init__(domain,\
1944                                             numEquations,numSolutions,debug)
1945        if xi==None:        if xi==None:
1946           self.__xi=AdvectivePDE.ELMAN_RAMAGE           self.__xi=AdvectivePDE.ELMAN_RAMAGE
1947        else:        else:
1948           self.__xi=xi           self.__xi=xi
1949        self.__Xi=escript.Data()        self.__Xi=escript.Data()
1950    
1951     def __calculateXi(self,peclet_factor,Z,h):     def setValue(**coefficients):
1952         Z_max=util.Lsup(Z)        """
1953         if Z_max>0.:        sets new values to coefficients
1954            return h*self.__xi(Z*peclet_factor)/(Z+Z_max*self.TOL)  
1955         else:        @param coefficients: new values assigned to coefficients
1956            return 0.        @keyword A: value for coefficient A.
1957          @type A: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1958          @keyword B: value for coefficient B
1959          @type B: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1960          @keyword C: value for coefficient C
1961          @type C: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1962          @keyword D: value for coefficient D
1963          @type D: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1964          @keyword X: value for coefficient X
1965          @type X: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1966          @keyword Y: value for coefficient Y
1967          @type Y: any type that can be casted to L{Data<escript.Data>} object on L{Function<escript.Function>}.
1968          @keyword d: value for coefficient d
1969          @type d: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1970          @keyword y: value for coefficient y
1971          @type y: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
1972          @keyword d_contact: value for coefficient d_contact
1973          @type d_contact: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
1974                           or  L{FunctionOnContactZero<escript.FunctionOnContactZero>}.
1975          @keyword y_contact: value for coefficient y_contact
1976          @type y_contact: any type that can be casted to L{Data<escript.Data>} object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
1977                           or  L{FunctionOnContactZero<escript.FunctionOnContactZero>}.
1978          @keyword r: values prescribed to the solution at the locations of constraints
1979          @type r: any type that can be casted to L{Data<escript.Data>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1980                   depending of reduced order is used for the solution.
1981          @keyword q: mask for location of constraints
1982          @type q: any type that can be casted to L{Data<escript.Data>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
1983                   depending of reduced order is used for the representation of the equation.
1984          @raise IllegalCoefficient: if an unknown coefficient keyword is used.
1985    
1986          """
1987          if "A" in coefficients.keys()   or "B" in coefficients.keys() or "C" in coefficients.keys(): self.__Xi=escript.Data()
1988          super(AdvectivePDE, self).setValue(**coefficients)
1989    
1990       def ELMAN_RAMAGE(self,P):
1991         """
1992         Predefined function to set a values for M{S{xi}} from a Preclet number M{P}.
1993         This function uses the method suggested by H.C. Elman and A. Ramage, I{SIAM J. Numer. Anal.}, B{40} (2002)
1994              - M{S{xi}(P)=0} for M{P<1}
1995              - M{S{xi}(P)=(1-1/P)/2} otherwise
1996    
1997         @param P: Preclet number
1998         @type P: L{Scalar<escript.Scalar>}
1999         @return: up-wind weightimg factor
2000         @rtype: L{Scalar<escript.Scalar>}
2001         """
2002         return util.wherePositive(P-1.)*0.5*(1.-1./(P+1.e-15))
2003    
2004       def SIMPLIFIED_BROOK_HUGHES(self,P):
2005         """
2006         Predefined function to set a values for M{S{xi}} from a Preclet number M{P}.
2007         The original methods is
2008    
2009     def setValue(self,**args):       M{S{xi}(P)=coth(P)-1/P}
2010         if "A" in args.keys()   or "B" in args.keys() or "C" in args.keys(): self.__Xi=escript.Data()  
2011         LinearPDE.setValue(**args)       As the evaluation of M{coth} is expensive we are using the approximation:
2012    
2013     def ELMAN_RAMAGE(P):           - M{S{xi}(P)=P/3} where M{P<3}
2014       """   """           - M{S{xi}(P)=1/2} otherwise
2015       return (P-1.).wherePositive()*0.5*(1.-1./(P+1.e-15))  
2016     def SIMPLIFIED_BROOK_HUGHES(P):       @param P: Preclet number
2017       """   """       @type P: L{Scalar<escript.Scalar>}
2018       c=(P-3.).whereNegative()       @return: up-wind weightimg factor
2019         @rtype: L{Scalar<escript.Scalar>}
2020         """
2021         c=util.whereNegative(P-3.)
2022       return P/6.*c+1./2.*(1.-c)       return P/6.*c+1./2.*(1.-c)
2023    
2024     def HALF(P):     def HALF(self,P):
2025      """ """       """
2026      return escript.Scalar(0.5,P.getFunctionSpace())       Predefined function to set value M{1/2} for M{S{xi}}
2027    
2028         @param P: Preclet number
2029         @type P: L{Scalar<escript.Scalar>}
2030         @return: up-wind weightimg factor
2031         @rtype: L{Scalar<escript.Scalar>}
2032         """
2033         return escript.Scalar(0.5,P.getFunctionSpace())
2034    
2035       def __calculateXi(self,peclet_factor,flux,h):
2036           flux=util.Lsup(flux)
2037           if flux_max>0.:
2038              return h*self.__xi(flux*peclet_factor)/(flux+flux_max*self.__TOL)
2039           else:
2040              return 0.
2041    
2042     def getXi(self):     def __getXi(self):
2043        if self.__Xi.isEmpty():        if self.__Xi.isEmpty():
2044           B=self.getCoefficient("B")           B=self.getCoefficient("B")
2045           C=self.getCoefficient("C")           C=self.getCoefficient("C")
# Line 1344  class AdvectivePDE(LinearPDE): Line 2048  class AdvectivePDE(LinearPDE):
2048           self.__Xi=escript.Scalar(0.,self.getFunctionSpaceForCoefficient("A"))           self.__Xi=escript.Scalar(0.,self.getFunctionSpaceForCoefficient("A"))
2049           if not C.isEmpty() or not B.isEmpty():           if not C.isEmpty() or not B.isEmpty():
2050              if not C.isEmpty() and not B.isEmpty():              if not C.isEmpty() and not B.isEmpty():
2051                  Z2=escript.Scalar(0,self.getFunctionSpaceForCoefficient("A"))                  flux2=escript.Scalar(0,self.getFunctionSpaceForCoefficient("A"))
2052                  if self.getNumEquations()>1:                  if self.getNumEquations()>1:
2053                     if self.getNumSolutions()>1:                     if self.getNumSolutions()>1:
2054                        for i in range(self.getNumEquations()):                        for i in range(self.getNumEquations()):
2055                           for k in range(self.getNumSolutions()):                           for k in range(self.getNumSolutions()):
2056                              for l in range(self.getDim()): Z2+=(C[i,k,l]-B[i,l,k])**2                              for l in range(self.getDim()): flux2+=(C[i,k,l]-B[i,l,k])**2
2057                          # flux=C-util.reorderComponents(B,[0,2,1])
2058                     else:                     else:
2059                        for i in range(self.getNumEquations()):                        for i in range(self.getNumEquations()):
2060                           for l in range(self.getDim()): Z2+=(C[i,l]-B[i,l])**2                           for l in range(self.getDim()): flux2+=(C[i,l]-B[i,l])**2
2061                          # flux=C-B
2062                  else:                  else:
2063                     if self.getNumSolutions()>1:                     if self.getNumSolutions()>1:
2064                        for k in range(self.getNumSolutions()):                        for k in range(self.getNumSolutions()):
2065                           for l in range(self.getDim()): Z2+=(C[k,l]-B[l,k])**2                           for l in range(self.getDim()): flux2+=(C[k,l]-B[l,k])**2
2066                          # flux=C-util.reorderComponents(B,[1,0])
2067                     else:                     else:
2068                        for l in range(self.getDim()): Z2+=(C[l]-B[l])**2                        for l in range(self.getDim()): flux2+=(C[l]-B[l])**2
2069                  length_of_Z=util.sqrt(Z2)                        #flux=C-B
2070                    length_of_flux=util.sqrt(flux2)
2071              elif C.isEmpty():              elif C.isEmpty():
2072                length_of_Z=util.length(B)                length_of_flux=util.length(B)
2073                  #flux=B
2074              else:              else:
2075                length_of_Z=util.length(C)                length_of_flux=util.length(C)
2076                  #flux=C
2077    
2078              Z_max=util.Lsup(length_of_Z)              #length_of_flux=util.length(flux)
2079              if Z_max>0.:              flux_max=util.Lsup(length_of_flux)
2080                if flux_max>0.:
2081                   # length_of_A=util.inner(flux,util.tensormutiply(A,flux))
2082                 length_of_A=util.length(A)                 length_of_A=util.length(A)
2083                 A_max=util.Lsup(length_of_A)                 A_max=util.Lsup(length_of_A)
2084                 if A_max>0:                 if A_max>0:
2085                      inv_A=1./(length_of_A+A_max*self.TOL)                      inv_A=1./(length_of_A+A_max*self.__TOL)
2086                 else:                 else:
2087                      inv_A=1./self.TOL                      inv_A=1./self.__TOL
2088                 peclet_number=length_of_Z*h/2*inv_A                 peclet_number=length_of_flux*h/2*inv_A
2089                 xi=self.__xi(peclet_number)                 xi=self.__xi(peclet_number)
2090                 self.__Xi=h*xi/(length_of_Z+Z_max*self.TOL)                 self.__Xi=h*xi/(length_of_flux+flux_max*self.__TOL)
2091                 print "@ preclet number = %e"%util.Lsup(peclet_number),util.Lsup(xi),util.Lsup(length_of_Z)                 self.trace("preclet number = %e"%util.Lsup(peclet_number))
2092        return self.__Xi        return self.__Xi
2093    
2094    
# Line 1384  class AdvectivePDE(LinearPDE): Line 2096  class AdvectivePDE(LinearPDE):
2096       """       """
2097       return the value of the coefficient name of the general PDE       return the value of the coefficient name of the general PDE
2098    
2099       @param name:       @param name: name of the coefficient requested.
2100         @type name: C{string}
2101         @return: the value of the coefficient name
2102         @rtype: L{Data<escript.Data>}
2103         @raise IllegalCoefficient: if name is not one of coefficients
2104                      M{A}, M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
2105         @note: This method is called by the assembling routine to map the Possion equation onto the general PDE.
2106       """       """
2107       if not self.getNumEquations() == self.getNumSolutions():       if not self.getNumEquations() == self.getNumSolutions():
2108            raise ValueError,"AdvectivePDE expects the number of solution componets and the number of equations to be equal."            raise ValueError,"AdvectivePDE expects the number of solution componets and the number of equations to be equal."
# Line 1400  class AdvectivePDE(LinearPDE): Line 2118  class AdvectivePDE(LinearPDE):
2118                 Aout=self.createNewCoefficient("A")                 Aout=self.createNewCoefficient("A")
2119              else:              else:
2120                 Aout=A[:]                 Aout=A[:]
2121              Xi=self.getXi()              Xi=self.__getXi()
2122              if self.getNumEquations()>1:              if self.getNumEquations()>1:
2123                  for i in range(self.getNumEquations()):                  for i in range(self.getNumEquations()):
2124                     for j in range(self.getDim()):                     for j in range(self.getDim()):
2125                        for k in range(self.getNumSolutions()):                        for k in range(self.getNumSolutions()):
2126                           for l in range(self.getDim()):                           for l in range(self.getDim()):
2127                              if not C.isEmpty() and not B.isEmpty():                              if not C.isEmpty() and not B.isEmpty():
2128                                   # tmp=C-util.reorderComponents(B,[0,2,1])
2129                                   # Aout=Aout+Xi*util.generalTensorProduct(util.reorder(tmp,[1,2,0]),tmp,offset=1)
2130                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*(C[p,i,j]-B[p,j,i])*(C[p,k,l]-B[p,l,k])                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*(C[p,i,j]-B[p,j,i])*(C[p,k,l]-B[p,l,k])
2131                              elif C.isEmpty():                              elif C.isEmpty():
2132                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*B[p,j,i]*B[p,l,k]                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*B[p,j,i]*B[p,l,k]
2133                                   # Aout=Aout+Xi*util.generalTensorProduct(util.reorder(B,[2,1,0]),util.reorder(B,[0,2,1]),offset=1)
2134                              else:                              else:
2135                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*C[p,i,j]*C[p,k,l]                                 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*C[p,i,j]*C[p,k,l]
2136                                   # Aout=Aout+Xi*util.generalTensorProduct(util.reorder(C,[1,2,0]),C,offset=1)
2137              else:              else:
2138                  for j in range(self.getDim()):                  for j in range(self.getDim()):
2139                     for l in range(self.getDim()):                     for l in range(self.getDim()):
# Line 1421  class AdvectivePDE(LinearPDE): Line 2143  class AdvectivePDE(LinearPDE):
2143                            Aout[j,l]+=Xi*B[j]*B[l]                            Aout[j,l]+=Xi*B[j]*B[l]
2144                        else:                        else:
2145                            Aout[j,l]+=Xi*C[j]*C[l]                            Aout[j,l]+=Xi*C[j]*C[l]
2146                     # if not C.isEmpty() and not B.isEmpty():
2147                     #    tmp=C-B
2148                     #    Aout=Aout+Xi*util.outer(tmp,tmp)
2149                     # elif C.isEmpty():
2150                     #    Aout=Aout+Xi*util.outer(B,B)
2151                     # else:
2152                     # Aout=Aout+Xi*util.outer(C,C)
2153           return Aout           return Aout
2154       elif name == "B" :       elif name == "B" :
2155           B=self.getCoefficient("B")           B=self.getCoefficient("B")
# Line 1429  class AdvectivePDE(LinearPDE): Line 2158  class AdvectivePDE(LinearPDE):
2158           if C.isEmpty() or D.isEmpty():           if C.isEmpty() or D.isEmpty():
2159              Bout=B              Bout=B
2160           else:           else:
2161              Xi=self.getXi()              Xi=self.__getXi()
2162              if B.isEmpty():              if B.isEmpty():
2163                  Bout=self.createNewCoefficient("B")                  Bout=self.createNewCoefficient("B")
2164              else:              else:
# Line 1441  class AdvectivePDE(LinearPDE): Line 2170  class AdvectivePDE(LinearPDE):
2170                       for i in range(self.getNumEquations()):                       for i in range(self.getNumEquations()):
2171                          for j in range(self.getDim()):                          for j in range(self.getDim()):
2172                             Bout[i,j,k]+=tmp*C[p,i,j]                             Bout[i,j,k]+=tmp*C[p,i,j]
2173                               # Bout=Bout+Xi*util.generalTensorProduct(util.reorder(C,[1,2,0]),D,offset=1)
2174              else:              else:
2175                 tmp=Xi*D                 tmp=Xi*D
2176                 for j in range(self.getDim()): Bout[j]+=tmp*C[j]                 for j in range(self.getDim()): Bout[j]+=tmp*C[j]
2177                   # Bout=Bout+Xi*D*C
2178           return Bout           return Bout
2179       elif name == "C" :       elif name == "C" :
2180           B=self.getCoefficient("B")           B=self.getCoefficient("B")
# Line 1452  class AdvectivePDE(LinearPDE): Line 2183  class AdvectivePDE(LinearPDE):
2183           if B.isEmpty() or D.isEmpty():           if B.isEmpty() or D.isEmpty():
2184              Cout=C              Cout=C
2185           else:           else:
2186              Xi=self.getXi()              Xi=self.__getXi()
2187              if C.isEmpty():              if C.isEmpty():
2188                  Cout=self.createNewCoefficient("C")                  Cout=self.createNewCoefficient("C")
2189              else:              else:
# Line 1464  class AdvectivePDE(LinearPDE): Line 2195  class AdvectivePDE(LinearPDE):
2195                        for i in range(self.getNumEquations()):                        for i in range(self.getNumEquations()):
2196                          for l in range(self.getDim()):                          for l in range(self.getDim()):
2197                                   Cout[i,k,l]+=tmp*B[p,l,i]                                   Cout[i,k,l]+=tmp*B[p,l,i]
2198                                     # Cout=Cout+Xi*B[p,l,i]*D[p,k]
2199              else:              else:
2200                 tmp=Xi*D                 tmp=Xi*D
2201                 for j in range(self.getDim()): Cout[j]+=tmp*B[j]                 for j in range(self.getDim()): Cout[j]+=tmp*B[j]
2202                   # Cout=Cout+tmp*D*B
2203           return Cout           return Cout
2204       elif name == "D" :       elif name == "D" :
2205           return self.getCoefficient("D")           return self.getCoefficient("D")
# Line 1482  class AdvectivePDE(LinearPDE): Line 2215  class AdvectivePDE(LinearPDE):
2215                  Xout=self.createNewCoefficient("X")                  Xout=self.createNewCoefficient("X")
2216              else:              else:
2217                  Xout=X[:]                  Xout=X[:]
2218              Xi=self.getXi()              Xi=self.__getXi()
2219              if self.getNumEquations()>1:              if self.getNumEquations()>1:
2220                   for p in range(self.getNumEquations()):                   for p in range(self.getNumEquations()):
2221                      tmp=Xi*Y[p]                      tmp=Xi*Y[p]
# Line 1490  class AdvectivePDE(LinearPDE): Line 2223  class AdvectivePDE(LinearPDE):
2223                         for j in range(self.getDim()):                         for j in range(self.getDim()):
2224                            if not C.isEmpty() and not B.isEmpty():                            if not C.isEmpty() and not B.isEmpty():
2225                               Xout[i,j]+=tmp*(C[p,i,j]-B[p,j,i])                               Xout[i,j]+=tmp*(C[p,i,j]-B[p,j,i])
2226                                 # Xout=X_out+Xi*util.inner(Y,C-util.reorderComponents(B,[0,2,1]),offset=1)
2227                            elif C.isEmpty():                            elif C.isEmpty():
2228                               Xout[i,j]-=tmp*B[p,j,i]                               Xout[i,j]-=tmp*B[p,j,i]
2229                                 # Xout=X_out-Xi*util.inner(Y,util.reorderComponents(B,[0,2,1]),offset=1)
2230                            else:                            else:
2231                               Xout[i,j]+=tmp*C[p,i,j]                               Xout[i,j]+=tmp*C[p,i,j]
2232                                 # Xout=X_out+Xi*util.inner(Y,C,offset=1)
2233              else:              else:
2234                   tmp=Xi*Y                   tmp=Xi*Y
2235                   for j in range(self.getDim()):                   for j in range(self.getDim()):
2236                      if not C.isEmpty() and not B.isEmpty():                      if not C.isEmpty() and not B.isEmpty():
2237                         Xout[j]+=tmp*(C[j]-B[j])                         Xout[j]+=tmp*(C[j]-B[j])
2238                           # Xout=Xout+Xi*Y*(C-B)
2239                      elif C.isEmpty():                      elif C.isEmpty():
2240                         Xout[j]-=tmp*B[j]                         Xout[j]-=tmp*B[j]
2241                           # Xout=Xout-Xi*Y*B
2242                      else:                      else:
2243                         Xout[j]+=tmp*C[j]                         Xout[j]+=tmp*C[j]
2244                           # Xout=Xout+Xi*Y*C
2245           return Xout           return Xout
2246       elif name == "Y" :       elif name == "Y" :
2247           return self.getCoefficient("Y")           return self.getCoefficient("Y")
# Line 1519  class AdvectivePDE(LinearPDE): Line 2258  class AdvectivePDE(LinearPDE):
2258       elif name == "q" :       elif name == "q" :
2259           return self.getCoefficient("q")           return self.getCoefficient("q")
2260       else:       else:
2261           raise SystemError,"unknown PDE coefficient %s",name          raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
   
2262    
2263  class Poisson(LinearPDE):  class AdvectionDiffusion(LinearPDE):
2264     """     """
2265     Class to define a Poisson equation problem:     Class to define PDE equation of the unisotropic advection-diffusion problem, which is genear L{LinearPDE} of the form
2266    
2267       M{S{omega}*u + inner(v,grad(u))- grad(matrixmult(k_bar,grad(u))[j])[j] = f}
2268    
2269       with natural boundary conditons
2270    
2271     class to define a linear PDE of the form     M{n[j]*matrixmult(k,grad(u))[j] = g- S{alpha}u }
    \f[  
    -u_{,jj} = f  
    \f]  
   
    with boundary conditons:  
   
    \f[  
    n_j*u_{,j} = 0  
    \f]  
2272    
2273     and constraints:     and constraints:
2274    
2275     \f[     M{u=r} where M{q>0}
    u=0 \quad \mathrm{where} \quad q>0  
    \f]  
    """  
2276    
2277     def __init__(self,domain,f=escript.Data(),q=escript.Data(),debug=False):     and
        LinearPDE.__init__(self,domain,1,1,debug)  
        self.COEFFICIENTS={"f": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),  
                           "q": PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.BOTH)}  
        self.setSymmetryOn()  
        self.setValue(f,q)  
   
    def setValue(self,f=escript.Data(),q=escript.Data()):  
        """set value of PDE parameters f and q"""  
        self._LinearPDE__setValue(f=f,q=q)  
2278    
2279     def getCoefficientOfGeneralPDE(self,name):     M{k_bar[i,j]=k[i,j]+upwind[i]*upwind[j]}
2280       """  
2281       return the value of the coefficient name of the general PDE     """
2282    
2283       @param name:     def __init__(self,domain,debug=False):
2284       """       """
2285       if name == "A" :       initializes a new Poisson equation
          return escript.Data(numarray.identity(self.getDim()),escript.Function(self.getDomain()))  
      elif name == "B" :  
          return escript.Data()  
      elif name == "C" :  
          return escript.Data()  
      elif name == "D" :  
          return escript.Data()  
      elif name == "X" :  
          return escript.Data()  
      elif name == "Y" :  
          return self.getCoefficient("f")  
      elif name == "d" :  
          return escript.Data()  
      elif name == "y" :  
          return escript.Data()  
      elif name == "d_contact" :  
          return escript.Data()  
      elif name == "y_contact" :  
          return escript.Data()  
      elif name == "r" :  
          return escript.Data()  
      elif name == "q" :  
          return self.getCoefficient("q")  
      else:  
          raise SystemError,"unknown PDE coefficient %s",name  
2286    
2287  class LameEquation(LinearPDE):       @param domain: domain of the PDE
2288     """       @type domain: L{Domain<escript.Domain>}
2289     Class to define a Lame equation problem:       @param debug: if True debug informations are printed.
2290    
2291     class to define a linear PDE of the form       """
2292     \f[       super(AdvectionDiffusion, self).__init__(domain,1,1,debug)
2293     -(\mu (u_{i,j}+u_{j,i}))_{,j} - \lambda u_{j,ji}} = F_i -\sigma_{ij,j}       self.COEFFICIENTS={"omega": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.OPERATOR),
2294     \f]                          "k": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_DIM,PDECoefficient.BY_DIM),PDECoefficient.OPERATOR),
2295                            "f": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
2296     with boundary conditons:                          "v": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_DIM,),PDECoefficient.OPERATOR),
2297                            "upwind": PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.BY_DIM,),PDECoefficient.OPERATOR),
2298     \f[                          "alpha": PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.OPERATOR),
2299     n_j(\mu (u_{i,j}+u_{j,i})-sigma_{ij}) + n_i\lambda u_{j,j} = f_i                          "g": PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.BY_EQUATION,),PDECoefficient.RIGHTHANDSIDE),
2300     \f]                          "r": PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH),
2301                            "q": PDECoefficient(PDECoefficient.SOLUTION,(PDECoefficient.BY_EQUATION,),PDECoefficient.BOTH)}
2302    
2303     and constraints:     def setValue(self,**coefficients):
2304         """
2305         sets new values to coefficients
2306    
2307     \f[       @param coefficients: new values assigned to coefficients
2308     u_i=r_i \quad \mathrm{where} \quad q_i>0       @keyword omega: value for coefficient M{S{omega}}
2309     \f]       @type omega: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
2310     """       @keyword k: value for coefficient M{k}
2311         @type k: any type that can be casted to L{Tensor<escript.Tensor>} object on L{Function<escript.Function>}.
2312         @keyword v: value for coefficient M{v}
2313         @type v: any type that can be casted to L{Vector<escript.Vector>} object on L{Function<escript.Function>}.
2314         @keyword upwind: value for upwind term M{upwind}
2315         @type upwind: any type that can be casted to L{Vector<escript.Vector>} object on L{Function<escript.Function>}.
2316         @keyword f: value for right hand side M{f}
2317         @type f: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Function<escript.Function>}.
2318         @keyword alpha: value for right hand side M{S{alpha}}
2319         @type alpha: any type that can be casted to L{Scalar<escript.Scalar>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
2320         @keyword g: value for right hand side M{g}
2321         @type g: any type that can be casted to L{Scalar<escript.Scalar>} object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}.
2322         @keyword r: prescribed values M{r} for the solution in constraints.
2323         @type r: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
2324                   depending of reduced order is used for the representation of the equation.
2325         @keyword q: mask for location of constraints
2326         @type q: any type that can be casted to L{Scalar<escript.Scalar>} object on L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
2327                   depending of reduced order is used for the representation of the equation.
2328         @raise IllegalCoefficient: if an unknown coefficient keyword is used.
2329         """
2330         super(AdvectionDiffusion, self).setValue(**coefficients)
2331    
    def __init__(self,domain,f=escript.Data(),q=escript.Data(),debug=False):  
        LinearPDE.__init__(self,domain,domain.getDim(),domain.getDim(),debug)  
        self.COEFFICIENTS={ "lame_lambda"  : PDECoefficient(PDECoefficient.INTERIOR,(),PDECoefficient.OPERATOR),  
                           "lame_mu"      : PDECoefficient(PDECoefficient.INTERIOR,(),PDECoefficient.OPERATOR),  
                           "F"            : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),  
                           "sigma"        : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM),PDECoefficient.RIGHTHANDSIDE),  
                           "f"            : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),  
                           "r"            : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.BOTH),  
                           "q"            : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.BOTH)}  
        self.setSymmetryOn()  
   
    def setValue(self,lame_lambda=escript.Data(),lame_mu=escript.Data(),F=escript.Data(),sigma=escript.Data(),f=escript.Data(),r=escript.Data(),q=escript.Data()):  
        """set value of PDE parameters"""  
        self._LinearPDE__setValue(lame_lambda=lame_lambda, \  
                                  lame_mu=lame_mu, \  
                                  F=F, \  
                                  sigma=sigma, \  
                                  f=f, \  
                                  r=r, \  
                                  q=q)  
2332     def getCoefficientOfGeneralPDE(self,name):     def getCoefficientOfGeneralPDE(self,name):
2333       """       """
2334       return the value of the coefficient name of the general PDE       return the value of the coefficient name of the general PDE
2335    
2336       @param name:       @param name: name of the coefficient requested.
2337         @type name: C{string}
2338         @return: the value of the coefficient  name
2339         @rtype: L{Data<escript.Data>}
2340         @raise IllegalCoefficient: if name is not one of coefficients
2341                      "A", M{B}, M{C}, M{D}, M{X}, M{Y}, M{d}, M{y}, M{d_contact}, M{y_contact}, M{r} or M{q}.
2342         @note: This method is called by the assembling routine to map the Possion equation onto the general PDE.
2343       """       """
2344       if name == "A" :       if name == "A" :
2345           out =self.createCoefficientOfGeneralPDE("A")           return self.getCoefficient("k")+util.outer(self.getCoefficient("upwind"),self.getCoefficient("upwind"))
          for i in range(self.getDim()):  
            for j in range(self.getDim()):  
              out[i,i,j,j] += self.getCoefficient("lame_lambda")  
              out[i,j,j,i] += self.getCoefficient("lame_mu")  
              out[i,j,i,j] += self.getCoefficient("lame_mu")  
          return out  
2346       elif name == "B" :       elif name == "B" :
2347           return escript.Data()           return escript.Data()
2348       elif name == "C" :       elif name == "C" :
2349           return escript.Data()           return self.getCoefficient("v")
2350       elif name == "D" :       elif name == "D" :
2351           return escript.Data()           return self.getCoefficient("omega")
2352       elif name == "X" :       elif name == "X" :
2353           return self.getCoefficient("sigma")           return escript.Data()
2354       elif name == "Y" :       elif name == "Y" :
2355           return self.getCoefficient("F")           return self.getCoefficient("f")
2356       elif name == "d" :       elif name == "d" :
2357           return escript.Data()           return self.getCoefficient("alpha")
2358       elif name == "y" :       elif name == "y" :
2359           return self.getCoefficient("f")           return self.getCoefficient("g")
2360       elif name == "d_contact" :       elif name == "d_contact" :
2361           return escript.Data()           return escript.Data()
2362       elif name == "y_contact" :       elif name == "y_contact" :
# Line 1667  class LameEquation(LinearPDE): Line 2366  class LameEquation(LinearPDE):
2366       elif name == "q" :       elif name == "q" :
2367           return self.getCoefficient("q")           return self.getCoefficient("q")
2368       else:       else:
2369           raise SystemError,"unknown PDE coefficient %s",name          raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
2370    
2371    
2372  # $Log$  # $Log$
2373    # Revision 1.14  2005/09/22 01:54:57  jgs
2374    # Merge of development branch dev-02 back to main trunk on 2005-09-22
2375    #
2376    # Revision 1.13  2005/09/15 03:44:19  jgs
2377    # Merge of development branch dev-02 back to main trunk on 2005-09-15
2378    #
2379    # Revision 1.12  2005/09/01 03:31:28  jgs
2380    # Merge of development branch dev-02 back to main trunk on 2005-09-01
2381    #
2382  # Revision 1.11  2005/08/23 01:24:28  jgs  # Revision 1.11  2005/08/23 01:24:28  jgs
2383  # Merge of development branch dev-02 back to main trunk on 2005-08-23  # Merge of development branch dev-02 back to main trunk on 2005-08-23
2384  #  #
2385  # Revision 1.10  2005/08/12 01:45:36  jgs  # Revision 1.10  2005/08/12 01:45:36  jgs
2386  # erge of development branch dev-02 back to main trunk on 2005-08-12  # erge of development branch dev-02 back to main trunk on 2005-08-12
2387  #  #
2388    # Revision 1.9.2.17  2005/09/21 07:03:33  matt
2389    # PDECoefficient and LinearPDE are now new style classes (introduced in Python
2390    # 2.2). Classes Poisson, Helmholtz, LameEquation and AdvectivePDE have been
2391    # modified to instead use portable/cooperative "super" calls to extend base
2392    # class methods.
2393    #
2394    # Revision 1.9.2.16  2005/09/16 01:54:37  matt
2395    # Removed redundant if-loop.
2396    #
2397    # Revision 1.9.2.15  2005/09/14 08:09:18  matt
2398    # Added "REDUCED" solution PDECoefficient descriptors for LinearPDEs.
2399    #
2400    # Revision 1.9.2.14  2005/09/07 06:26:16  gross
2401    # the solver from finley are put into the standalone package paso now
2402    #
2403    # Revision 1.9.2.13  2005/08/31 08:45:03  gross
2404    # in the case of lumping no new system is allocated if the constraint is changed.
2405    #
2406    # Revision 1.9.2.12  2005/08/31 07:10:23  gross
2407    # test for Lumping added
2408    #
2409    # Revision 1.9.2.11  2005/08/30 01:53:45  gross
2410    # bug in format fixed.
2411    #
2412    # Revision 1.9.2.10  2005/08/26 07:14:17  gross
2413    # a few more bugs in linearPDE fixed. remaining problem are finley problems
2414    #
2415    # Revision 1.9.2.9  2005/08/26 06:30:45  gross
2416    # fix for reported bug  0000004. test_linearPDE passes a few more tests
2417    #
2418    # Revision 1.9.2.8  2005/08/26 04:30:13  gross
2419    # gneric unit testing for linearPDE
2420    #
2421    # Revision 1.9.2.7  2005/08/25 07:06:50  gross
2422    # linearPDE documentation is parsed now by epydoc. there is still a problem with links into escriptcpp.so
2423    #
2424    # Revision 1.9.2.6  2005/08/24 05:01:24  gross
2425    # problem with resetting the matrix in case of resetting its values to 0 fixed.
2426    #
2427    # Revision 1.9.2.5  2005/08/24 02:03:28  gross
2428    # epydoc mark up partially fixed
2429    #
2430  # Revision 1.9.2.4  2005/08/22 07:11:09  gross  # Revision 1.9.2.4  2005/08/22 07:11:09  gross
2431  # some problems with LinearPDEs fixed.  # some problems with LinearPDEs fixed.
2432  #  #
# Line 1803  class LameEquation(LinearPDE): Line 2554  class LameEquation(LinearPDE):
2554  # Revision 1.1  2004/08/28 12:58:06  gross  # Revision 1.1  2004/08/28 12:58:06  gross
2555  # SimpleSolve is not running yet: problem with == of functionsspace  # SimpleSolve is not running yet: problem with == of functionsspace
2556  #  #
 #  

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

  ViewVC Help
Powered by ViewVC 1.1.26