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

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

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

trunk/esys2/escript/py_src/linearPDEs.py revision 104 by jgs, Fri Dec 17 07:43:12 2004 UTC trunk/escript/py_src/linearPDEs.py revision 2596 by lgao, Thu Aug 6 03:09:03 2009 UTC
# Line 1  Line 1 
 # $Id$  
1    
2  ## @file linearPDEs.py  ########################################################
3    #
4    # Copyright (c) 2003-2009 by University of Queensland
5    # Earth Systems Science Computational Center (ESSCC)
6    # http://www.uq.edu.au/esscc
7    #
8    # Primary Business: Queensland, Australia
9    # Licensed under the Open Software License version 3.0
10    # http://www.opensource.org/licenses/osl-3.0.php
11    #
12    ########################################################
13    
14    __copyright__="""Copyright (c) 2003-2009 by University of Queensland
15    Earth Systems Science Computational Center (ESSCC)
16    http://www.uq.edu.au/esscc
17    Primary Business: Queensland, Australia"""
18    __license__="""Licensed under the Open Software License version 3.0
19    http://www.opensource.org/licenses/osl-3.0.php"""
20    __url__="https://launchpad.net/escript-finley"
21    
22  """  """
23  @brief Functions and classes for linear PDEs  The module provides an interface to define and solve linear partial
24    differential equations (PDEs) and Transport problems within L{escript}.
25    L{linearPDEs} does not provide any solver capabilities in itself but hands the
26    PDE over to the PDE solver library defined through the L{Domain<escript.Domain>}
27    of the PDE. The general interface is provided through the L{LinearPDE} class.
28    L{TransportProblem} provides an interface to initial value problems dominated
29    by its advective terms.
30    
31    @var __author__: name of author
32    @var __copyright__: copyrights
33    @var __license__: licence agreement
34    @var __url__: url entry point on documentation
35    @var __version__: version
36    @var __date__: date of the version
37  """  """
38    
39    import math
40  import escript  import escript
41  import util  import util
42  import numarray  import numpy
43    
44  def identifyDomain(domain=None,data={}):  __author__="Lutz Gross, l.gross@uq.edu.au"
45       """  
46       @brief Return the Domain which is equal to the input domain (if not None)  
47       and is the domain of all Data objects in the dictionary data.  class SolverOptions(object):
48       An exception is raised if this is not possible      """
49        this class defines the solver options for a linear or non-linear solver.
50       @param domain      
51       @param data      The option also supports the handling of diagnostic informations.
52       """      
53       # get the domain used by any Data object in the list data:      Typical usage is
54       data_domain=None      
55       for d in data.itervalues():      opts=SolverOptions()
56            if isinstance(d,escript.Data):      print opts
57               if not d.isEmpty(): data_domain=d.getDomain()      opts.resetDiagnostics()
58       # check if domain and data_domain are identical?      u=solver(opts)
59       if domain == None:      print "number of iteration steps: =",opts.getDiagnostics("num_iter")
60           if data_domain == None:      
61                raise ValueError,"Undefined PDE domain. Specify a domain or use a Data class object as coefficient"  
62       else:      @cvar DEFAULT: The default method used to solve the system of linear equations
63           if data_domain == None:      @cvar DIRECT: The direct solver based on LDU factorization
64                data_domain=domain      @cvar CHOLEVSKY: The direct solver based on LDLt factorization (can only be applied for symmetric PDEs)
65           else:      @cvar PCG: The preconditioned conjugate gradient method (can only be applied for symmetric PDEs)
66             if not data_domain == domain:      @cvar CR: The conjugate residual method
67                   raise ValueError,"Domain of coefficients doesnot match specified domain"      @cvar CGS: The conjugate gradient square method
68       # now we check if all Data class object coefficients are defined on data_domain:      @cvar BICGSTAB: The stabilized Bi-Conjugate Gradient method
69       for i,d in data.iteritems():      @cvar TFQMR: Transport Free Quasi Minimal Residual method
70           if isinstance(d,escript.Data):      @cvar MINRES: Minimum residual method
71              if not d.isEmpty():      @cvar SSOR: The symmetric over-relaxation method
72                 if not data_domain==d.getDomain():      @cvar ILU0: The incomplete LU factorization preconditioner with no fill-in
73                   raise ValueError,"Illegal domain for coefficient %s."%i      @cvar ILUT: The incomplete LU factorization preconditioner with fill-in
74       # done:      @cvar JACOBI: The Jacobi preconditioner
75       return data_domain      @cvar GMRES: The Gram-Schmidt minimum residual method
76        @cvar PRES20: Special GMRES with restart after 20 steps and truncation after 5 residuals
77  def identifyNumEquationsAndSolutions(dim,coef={}):      @cvar LUMPING: Matrix lumping
78       # get number of equations and number of unknowns:      @cvar NO_REORDERING: No matrix reordering allowed
79       numEquations=0      @cvar MINIMUM_FILL_IN: Reorder matrix to reduce fill-in during factorization
80       numSolutions=0      @cvar NESTED_DISSECTION: Reorder matrix to improve load balancing during factorization
81       for i in coef.iterkeys():      @cvar PASO: PASO solver package
82          if not coef[i].isEmpty():      @cvar SCSL: SGI SCSL solver library
83             res=_PDECoefficientTypes[i].estimateNumEquationsAndNumSolutions(coef[i].getShape(),dim)      @cvar MKL: Intel's MKL solver library
84             if res==None:      @cvar UMFPACK: The UMFPACK library
85                 raise ValueError,"Illegal shape %s of coefficient %s"%(coef[i].getShape().__str__(),i)      @cvar TRILINOS: The TRILINOS parallel solver class library from Sandia National Labs
86             else:      @cvar ITERATIVE: The default iterative solver
87                 numEquations=max(numEquations,res[0])      @cvar AMG: Algebraic Multi Grid
88                 numSolutions=max(numSolutions,res[1])      @cvar REC_ILU: recursive ILU0
89       return numEquations,numSolutions      @cvar RILU: relaxed ILU0
90        @cvar GAUSS_SEIDEL: Gauss-Seidel solver
91        @cvar DEFAULT_REORDERING: the reordering method recommended by the solver
92        @cvar SUPER_LU: the Super_LU solver package
93        @cvar PASTIX: the Pastix direct solver_package
94        @cvar YAIR_SHAPIRA_COARSENING: AMG coarsening method by Yair-Shapira
95        @cvar RUGE_STUEBEN_COARSENING: AMG coarsening method by Ruge and Stueben
96        @cvar AGGREGATION_COARSENING: AMG coarsening using (symmetric) aggregation
97        @cvar MIN_COARSE_MATRIX_SIZE: minimum size of the coarsest level matrix to use direct solver.
98        @cvar NO_PRECONDITIONER: no preconditioner is applied.
99        """
100        DEFAULT= 0
101        DIRECT= 1
102        CHOLEVSKY= 2
103        PCG= 3
104        CR= 4
105        CGS= 5
106        BICGSTAB= 6
107        SSOR= 7
108        ILU0= 8
109        ILUT= 9
110        JACOBI= 10
111        GMRES= 11
112        PRES20= 12
113        LUMPING= 13
114        NO_REORDERING= 17
115        MINIMUM_FILL_IN= 18
116        NESTED_DISSECTION= 19
117        MKL= 15
118        UMFPACK= 16
119        ITERATIVE= 20
120        PASO= 21
121        AMG= 22
122        REC_ILU = 23
123        TRILINOS = 24
124        NONLINEAR_GMRES = 25
125        TFQMR = 26
126        MINRES = 27
127        GAUSS_SEIDEL=28
128        RILU=29
129        DEFAULT_REORDERING=30
130        SUPER_LU=31
131        PASTIX=32
132        YAIR_SHAPIRA_COARSENING=33
133        RUGE_STUEBEN_COARSENING=34
134        AGGREGATION_COARSENING=35
135        NO_PRECONDITIONER=36
136        MIN_COARSE_MATRIX_SIZE=37
137        
138        def __init__(self):
139            self.setLevelMax()
140            self.setCoarseningThreshold()
141            self.setNumSweeps()
142            self.setNumPreSweeps()
143            self.setNumPostSweeps()
144            self.setTolerance()
145            self.setAbsoluteTolerance()
146            self.setInnerTolerance()
147            self.setDropTolerance()
148            self.setDropStorage()
149            self.setIterMax()
150            self.setInnerIterMax()
151            self.setTruncation()
152            self.setRestart()
153            self.setSymmetry()
154            self.setVerbosity()
155            self.setInnerToleranceAdaption()
156            self.setAcceptanceConvergenceFailure()
157            self.setReordering()
158            self.setPackage()
159            self.setSolverMethod()
160            self.setPreconditioner()
161            self.setCoarsening()
162            self.setMinCoarseMatrixSize()
163            self.setRelaxationFactor()        
164            self.resetDiagnostics(all=True)
165    
166        def __str__(self):
167            return self.getSummary()
168        def getSummary(self):
169            """
170            Returns a string reporting the current settings
171            """
172            out="Solver Package: %s"%(self.getName(self.getPackage()))
173            out+="\nVerbosity = %s"%self.isVerbose()
174            out+="\nAccept failed convergence = %s"%self.acceptConvergenceFailure()
175            out+="\nRelative tolerance = %e"%self.getTolerance()
176            out+="\nAbsolute tolerance = %e"%self.getAbsoluteTolerance()
177            out+="\nSymmetric problem = %s"%self.isSymmetric()
178            out+="\nMaximum number of iteration steps = %s"%self.getIterMax()
179            out+="\nInner tolerance = %e"%self.getInnerTolerance()
180            out+="\nAdapt innner tolerance = %s"%self.adaptInnerTolerance()
181        
182            if self.getPackage() == self.PASO:
183                out+="\nSolver method = %s"%self.getName(self.getSolverMethod())
184                if self.getSolverMethod() == self.GMRES:
185                    out+="\nTruncation  = %s"%self.getTruncation()
186                    out+="\nRestart  = %s"%self.getRestart()
187                if self.getSolverMethod() == self.AMG:
188                    out+="\nNumber of pre / post sweeps = %s / %s, %s"%(self.getNumPreSweeps(), self.getNumPostSweeps(), self.getNumSweeps())
189                    out+="\nMaximum number of levels = %s"%self.LevelMax()
190                    out+="\nCoarsening threshold = %e"%self.getCoarseningThreshold()
191                    out+="\Coarsening method = %s"%self.getName(self.getCoarsening())
192                out+="\nPreconditioner = %s"%self.getName(self.getPreconditioner())
193                if self.getPreconditioner() == self.AMG:
194                    out+="\nMaximum number of levels = %s"%self.LevelMax()
195                    out+="\nCoarsening method = %s"%self.getName(self.getCoarsening())
196                    out+="\nCoarsening threshold = %e"%self.getMinCoarseMatrixSize()
197                    out+="\nMinimum size of the coarsest level matrix = %e"%self.getCoarseningThreshold()
198                    out+="\nNumber of pre / post sweeps = %s / %s, %s"%(self.getNumPreSweeps(), self.getNumPostSweeps(), self.getNumSweeps())
199                if self.getPreconditioner() == self.GAUSS_SEIDEL:
200                    out+="\nNumber of sweeps = %s"%self.getNumSweeps()
201                if self.getPreconditioner() == self.ILUT:
202                    out+="\nDrop tolerance = %e"%self.getDropTolerance()
203                    out+="\nStorage increase = %e"%self.getDropStorage()
204                if self.getPreconditioner() == self.RILU:
205                    out+="\nRelaxation factor = %e"%self.getRelaxationFactor()
206            return out
207            
208        def getName(self,key):
209            """
210            returns the name of a given key
211            
212            @param key: a valid key
213            """
214            if key == self.DEFAULT: return "DEFAULT"
215            if key == self.DIRECT: return "DIRECT"
216            if key == self.CHOLEVSKY: return "CHOLEVSKY"
217            if key == self.PCG: return "PCG"
218            if key == self.CR: return "CR"
219            if key == self.CGS: return "CGS"
220            if key == self.BICGSTAB: return "BICGSTAB"
221            if key == self.SSOR: return "SSOR"
222            if key == self.ILU0: return "ILU0:"
223            if key == self.ILUT: return "ILUT"
224            if key == self.JACOBI: return "JACOBI"
225            if key == self.GMRES: return "GMRES"
226            if key == self.PRES20: return "PRES20"
227            if key == self.LUMPING: return "LUMPING"
228            if key == self.NO_REORDERING: return "NO_REORDERING"
229            if key == self.MINIMUM_FILL_IN: return "MINIMUM_FILL_IN"
230            if key == self.NESTED_DISSECTION: return "NESTED_DISSECTION"
231            if key == self.MKL: return "MKL"
232            if key == self.UMFPACK: return "UMFPACK"
233            if key == self.ITERATIVE: return "ITERATIVE"
234            if key == self.PASO: return "PASO"
235            if key == self.AMG: return "AMG"
236            if key == self.REC_ILU: return "REC_ILU"
237            if key == self.TRILINOS: return "TRILINOS"
238            if key == self.NONLINEAR_GMRES: return "NONLINEAR_GMRES"
239            if key == self.TFQMR: return "TFQMR"
240            if key == self.MINRES: return "MINRES"
241            if key == self.GAUSS_SEIDEL: return "GAUSS_SEIDEL"
242            if key == self.RILU: return "RILU"
243            if key == self.DEFAULT_REORDERING: return "DEFAULT_REORDERING"
244            if key == self.SUPER_LU: return "SUPER_LU"
245            if key == self.PASTIX: return "PASTIX"
246            if key == self.YAIR_SHAPIRA_COARSENING: return "YAIR_SHAPIRA_COARSENING"
247            if key == self.RUGE_STUEBEN_COARSENING: return "RUGE_STUEBEN_COARSENING"
248            if key == self.AGGREGATION_COARSENING: return "AGGREGATION_COARSENING"
249            if key == self.NO_PRECONDITIONER: return "NO_PRECONDITIONER"
250            if key == self.MIN_COARSE_MATRIX_SIZE: return "MIN_COARSE_MATRIX_SIZE"
251            
252        def resetDiagnostics(self,all=False):
253            """
254            resets the diagnostics
255            
256            @param all: if C{all} is C{True} all diagnostics including accumulative counters are reset.
257            @type all: C{bool}
258            """
259            self.__num_iter=None
260            self.__num_level=None
261            self.__num_inner_iter=None
262            self.__time=None
263            self.__set_up_time=None
264            self.__net_time=None
265            self.__residual_norm=None
266            self.__converged=None
267            if all:
268                self.__cum_num_inner_iter=0
269                self.__cum_num_iter=0
270                self.__cum_time=0
271                self.__cum_set_up_time=0
272                self.__cum_net_time=0
273    
274        def _updateDiagnostics(self, name, value):
275            """
276            Updates diagnostic information
277            
278            @param name: name of  diagnostic information
279            @type name: C{str} in the list "num_iter", "num_level", "num_inner_iter", "time", "set_up_time", "net_time", "residual_norm", "converged".
280            @param vale: new value of the diagnostic information
281            @note: this function is used by a solver to report diagnostics informations.
282            """
283            if name == "num_iter":
284                self.__num_iter=int(value)
285                self.__cum_num_iter+=self.__num_iter
286            if name == "num_level":
287                self.__num_level=int(value)
288            if name == "num_inner_iter":
289                self.__num_inner_iter=int(value)
290                self.__cum_num_inner_iter+=self.__num_inner_iter
291            if name == "time":
292                self.__time=float(value)
293                self.__cum_time+=self.__time
294            if name == "set_up_time":
295                self.__set_up_time=float(value)
296                self.__cum_set_up_time+=self.__set_up_time
297            if name == "net_time":
298                self.__net_time=float(value)
299                self.__cum_net_time+=self.__net_time
300            if name == "residual_norm":
301                self.__residual_norm=float(value)
302            if name == "converged":
303                self.__converged = (value == True)
304        def getDiagnostics(self, name):
305            """
306            Returns the diagnostic information C{name}
307            
308            @param name: name of diagnostic information where
309            - "num_iter": the number of iteration steps
310            - "cum_num_iter": the cumulative number of iteration steps
311            - "num_level": the number of level in multi level solver
312            - "num_inner_iter": the number of inner iteration steps
313            - "cum_num_inner_iter": the cumulative number of inner iteration steps
314            - "time": execution time
315            - "cum_time": cumulative execution time
316            - "set_up_time": time to set up of the solver, typically this includes factorization and reordering
317            - "cum_set_up_time": cumulative time to set up of the solver
318            - "net_time": net execution time, excluding setup time for the solver and execution time for preconditioner
319            - "cum_net_time": cumulative net execution time
320            - "residual_norm": norm of the final residual
321            - "converged": return self.__converged    
322            @type name: C{str} in the list "num_iter", "num_level", "num_inner_iter", "time", "set_up_time", "net_time", "residual_norm", "converged".
323            @return: requested value. C{None} is returned if the value is undefined.
324            @note: If the solver has thrown an exception diagnostic values have an undefined status.
325            """
326            if name == "num_iter": return self.__num_iter
327            elif name == "cum_num_iter": return self.__cum_num_iter
328            elif name == "num_level": return self.__num_level
329            elif name == "num_inner_iter": return self.__num_inner_iter
330            elif name == "cum_num_inner_iter": return self.__cum_num_inner_iter
331            elif name == "time": return self.__time
332            elif name == "cum_time": return self.__cum_time
333            elif name == "set_up_time": return self.__set_up_time
334            elif name == "cum_set_up_time": return self.__cum_set_up_time
335            elif name == "net_time": return self.__net_time
336            elif name == "cum_net_time": return self.__cum_net_time
337            elif name == "residual_norm": return self.__residual_norm
338            elif name == "converged": return self.__converged      
339            else:
340                raise ValueError,"unknown diagnostic item %s"%name
341        def hasConverged(self):
342            """
343            Returns C{True} if the last solver call has been finalized successfully.
344            @note: if an exception has been thrown by the solver the status of this flag is undefined.
345            """
346            return self.getDiagnostics("converged")
347        def setCoarsening(self,method=0):
348            """
349            Sets the key of the coarsening method to be applied in AMG.
350    
351            @param method: selects the coarsening method .
352            @type method: in {SolverOptions.DEFAULT}, L{SolverOptions.YAIR_SHAPIRA_COARSENING},
353            L{SolverOptions.RUGE_STUEBEN_COARSENING}, L{SolverOptions.AGGREGATION_COARSENING}
354            """
355        if method==None: method=0
356            if not method in [self.DEFAULT, self.YAIR_SHAPIRA_COARSENING, self.RUGE_STUEBEN_COARSENING, self.AGGREGATION_COARSENING]:
357                 raise ValueError,"unknown coarsening method %s"%method
358            self.__coarsening=method
359        
360        def getCoarsening(self):
361            """
362            Returns the key of the coarsening algorithm to be applied AMG.
363    
364            @rtype: in the list L{SolverOptions.DEFAULT}, L{SolverOptions.YAIR_SHAPIRA_COARSENING},
365            L{SolverOptions.RUGE_STUEBEN_COARSENING}, L{SolverOptions.AGGREGATION_COARSENING}
366            """
367            return self.__coarsening
368          
369        def setMinCoarseMatrixSize(self,size=500):
370            """
371            Sets the minumum size of the coarsest level matrix in AMG.
372    
373            @param size: minumum size of the coarsest level matrix .
374            @type size: positive C{int} or C{None}
375            """
376            size=int(size)
377            if size<0:
378               raise ValueError,"minumum size of the coarsest level matrix must be non-negative."
379        if size==None: size=500
380            self.__MinCoarseMatrixSize=size
381            
382        def getMinCoarseMatrixSize(self):
383            """
384            Returns the minumum size of the coarsest level matrix in AMG.
385    
386            @rtype: C{int}
387            """
388            return self.__MinCoarseMatrixSize
389          
390        def setPreconditioner(self, preconditioner=10):
391            """
392            Sets the preconditioner to be used.
393    
394            @param preconditioner: key of the preconditioner to be used.
395            @type preconditioner: in L{SolverOptions.SSOR}, L{SolverOptions.ILU0}, L{SolverOptions.ILUT}, L{SolverOptions.JACOBI},
396                                        L{SolverOptions.AMG}, L{SolverOptions.REC_ILU}, L{SolverOptions.GAUSS_SEIDEL}, L{SolverOptions.RILU},
397                                        L{SolverOptions.NO_PRECONDITIONER}
398            @note: Not all packages support all preconditioner. It can be assumed that a package makes a reasonable choice if it encounters
399            an unknown preconditioner.
400            """
401        if preconditioner==None: preconditioner=10
402            if not preconditioner in [ SolverOptions.SSOR, SolverOptions.ILU0, SolverOptions.ILUT, SolverOptions.JACOBI,
403                                        SolverOptions.AMG, SolverOptions.REC_ILU, SolverOptions.GAUSS_SEIDEL, SolverOptions.RILU,
404                                        SolverOptions.NO_PRECONDITIONER] :
405                 raise ValueError,"unknown preconditioner %s"%preconditioner
406            self.__preconditioner=preconditioner    
407        def getPreconditioner(self):
408            """
409            Returns key of the preconditioner to be used.
410    
411            @rtype: in the list L{SolverOptions.SSOR}, L{SolverOptions.ILU0}, L{SolverOptions.ILUT}, L{SolverOptions.JACOBI},
412                                        L{SolverOptions.AMG}, L{SolverOptions.REC_ILU}, L{SolverOptions.GAUSS_SEIDEL}, L{SolverOptions.RILU},
413                                        L{SolverOptions.NO_PRECONDITIONER}
414            """
415            return self.__preconditioner
416        def setSolverMethod(self, method=0):
417            """
418            Sets the solver method to be used. Use C{method}=C{SolverOptions.DIRECT} to indicate that a direct rather than an iterative
419            solver should be used and Use C{method}=C{SolverOptions.ITERATIVE} to indicate that an iterative rather than a direct
420            solver should be used.
421    
422            @param method: key of the solver method to be used.
423            @type method: in L{SolverOptions.DEFAULT}, L{SolverOptions.DIRECT}, L{SolverOptions.CHOLEVSKY}, L{SolverOptions.PCG},
424                            L{SolverOptions.CR}, L{SolverOptions.CGS}, L{SolverOptions.BICGSTAB}, L{SolverOptions.SSOR},
425                            L{SolverOptions.GMRES}, L{SolverOptions.PRES20}, L{SolverOptions.LUMPING}, L{SolverOptions.ITERATIVE},
426                            L{SolverOptions.AMG}, L{SolverOptions.NONLINEAR_GMRES}, L{SolverOptions.TFQMR}, L{SolverOptions.MINRES},
427                            L{SolverOptions.GAUSS_SEIDEL}
428            @note: Not all packages support all solvers. It can be assumed that a package makes a reasonable choice if it encounters
429            an unknown solver method.
430            """
431        if method==None: method=0
432            if not method in [ SolverOptions.DEFAULT, SolverOptions.DIRECT, SolverOptions.CHOLEVSKY, SolverOptions.PCG,
433                               SolverOptions.CR, SolverOptions.CGS, SolverOptions.BICGSTAB, SolverOptions.SSOR,
434                               SolverOptions.GMRES, SolverOptions.PRES20, SolverOptions.LUMPING, SolverOptions.ITERATIVE, SolverOptions.AMG,
435                               SolverOptions.NONLINEAR_GMRES, SolverOptions.TFQMR, SolverOptions.MINRES, SolverOptions.GAUSS_SEIDEL]:
436                 raise ValueError,"unknown solver method %s"%method
437            self.__method=method
438        def getSolverMethod(self):
439            """
440            Returns key of the solver method to be used.
441    
442            @rtype: in the list L{SolverOptions.DEFAULT}, L{SolverOptions.DIRECT}, L{SolverOptions.CHOLEVSKY}, L{SolverOptions.PCG},
443                            L{SolverOptions.CR}, L{SolverOptions.CGS}, L{SolverOptions.BICGSTAB}, L{SolverOptions.SSOR},
444                            L{SolverOptions.GMRES}, L{SolverOptions.PRES20}, L{SolverOptions.LUMPING}, L{SolverOptions.ITERATIVE},
445                            L{SolverOptions.AMG}, L{SolverOptions.NONLINEAR_GMRES}, L{SolverOptions.TFQMR}, L{SolverOptions.MINRES},
446                            L{SolverOptions.GAUSS_SEIDEL}
447            """
448            return self.__method
449            
450        def setPackage(self, package=0):
451            """
452            Sets the solver package to be used as a solver.  
453    
454            @param package: key of the solver package to be used.
455            @type package: in L{SolverOptions.DEFAULT}, L{SolverOptions.PASO}, L{SolverOptions.SUPER_LU}, L{SolverOptions.PASTIX}, L{SolverOptions.MKL}, L{SolverOptions.UMFPACK}, L{SolverOptions.TRILINOS}
456            @note: Not all packages are support on all implementation. An exception may be thrown on some platforms if a particular is requested.
457            """
458        if package==None: package=0
459            if not package in [SolverOptions.DEFAULT, SolverOptions.PASO, SolverOptions.SUPER_LU, SolverOptions.PASTIX, SolverOptions.MKL, SolverOptions.UMFPACK, SolverOptions.TRILINOS]:
460                 raise ValueError,"unknown solver package %s"%package
461            self.__package=package
462        def getPackage(self):
463            """
464            Returns the solver package key
465    
466            @rtype: in the list L{SolverOptions.DEFAULT}, L{SolverOptions.PASO}, L{SolverOptions.SUPER_LU}, L{SolverOptions.PASTIX}, L{SolverOptions.MKL}, L{SolverOptions.UMFPACK}, L{SolverOptions.TRILINOS}
467            """
468            return self.__package
469        def setReordering(self,ordering=30):
470            """
471            Sets the key of the reordering method to be applied if supported by the solver. Some direct solvers support reordering
472            to optimize compute time and storage use during elimination.
473    
474            @param ordering: selects the reordering strategy.
475            @type ordering: in L{SolverOptions.NO_REORDERING}, L{SolverOptions.NO_REORDERING},
476            L{SolverOptions.NO_REORDERING}, L{SolverOptions.DEFAULT_REORDERING}
477            """
478            if not ordering in [self.NO_REORDERING, self.MINIMUM_FILL_IN, self.NESTED_DISSECTION, self.DEFAULT_REORDERING]:
479                 raise ValueError,"unknown reordering strategy %s"%ordering
480            self.__reordering=ordering
481        def getReordering(self):
482            """
483            Returns the key of the reordering method to be applied if supported by the solver.
484    
485            @rtype: in the list L{SolverOptions.NO_REORDERING}, L{SolverOptions.NO_REORDERING},
486            L{SolverOptions.NO_REORDERING}, L{SolverOptions.DEFAULT_REORDERING}
487            """
488            return self.__reordering
489        def setRestart(self,restart=None):
490            """
491            Sets the number of iterations steps after which GMRES is performing a restart.
492    
493            @param restart: number of iteration steps after which to perform a restart. If equal to C{None} no
494                            restart is performed.
495            @type restart: C{int} or C{None}
496            """
497            if restart == None:
498                self.__restart=restart
499            else:
500                restart=int(restart)
501                if restart<1:
502                    raise ValueError,"restart must be positive."
503                self.__restart=restart
504            
505        def getRestart(self):
506            """
507            Returns the number of iterations steps after which GMRES is performing a restart.
508            If C{None} is returned no restart is performed.
509    
510            @rtype: C{int} or C{None}
511            """
512            if self.__restart < 0:
513                return None
514            else:
515                return self.__restart
516        def _getRestartForC(self):
517            r=self.getRestart()
518            if r == None:
519                return -1
520                else:
521                return r
522        def setTruncation(self,truncation=20):
523            """
524            Sets the number of residuals in GMRES to be stored for orthogonalization.  The more residuals are stored
525            the faster GMRES converged but
526    
527            @param truncation: truncation
528            @type truncation: C{int}
529            """
530            truncation=int(truncation)
531            if truncation<1:
532               raise ValueError,"truncation must be positive."
533            self.__truncation=truncation
534        def getTruncation(self):
535            """
536            Returns the number of residuals in GMRES to be stored for orthogonalization
537    
538            @rtype: C{int}
539            """
540            return self.__truncation
541        def setInnerIterMax(self,iter_max=10):
542            """
543            Sets the maximum number of iteration steps for the inner iteration.
544    
545            @param iter_max: maximum number of inner iterations
546            @type iter_max: C{int}
547            """
548            iter_max=int(iter_max)
549            if iter_max<1:
550               raise ValueError,"maximum number of inner iteration must be positive."
551            self.__inner_iter_max=iter_max
552        def getInnerIterMax(self):
553            """
554            Returns maximum number of inner iteration steps
555    
556            @rtype: C{int}
557            """
558            return self.__inner_iter_max
559        def setIterMax(self,iter_max=100000):
560            """
561            Sets the maximum number of iteration steps
562    
563            @param iter_max: maximum number of iteration steps
564            @type iter_max: C{int}
565            """
566            iter_max=int(iter_max)
567            if iter_max<1:
568               raise ValueError,"maximum number of iteration steps must be positive."
569            self.__iter_max=iter_max
570        def getIterMax(self):
571            """
572            Returns maximum number of iteration steps
573    
574            @rtype: C{int}
575            """
576            return self.__iter_max
577        def setLevelMax(self,level_max=10):
578            """
579            Sets the maximum number of coarsening levels to be used in an algebraic multi level solver or preconditioner
580    
581            @param level_max: maximum number of levels
582            @type level_max: C{int}
583            """
584            level_max=int(level_max)
585            if level_max<0:
586               raise ValueError,"maximum number of coarsening levels must be non-negative."
587            self.__level_max=level_max
588        def getLevelMax(self):
589            """
590            Returns the maximum number of coarsening levels to be used in an algebraic multi level solver or preconditioner
591    
592            @rtype: C{int}
593            """
594            return self.__level_max
595        def setCoarseningThreshold(self,theta=0.05):
596            """
597            Sets the threshold for coarsening in the algebraic multi level solver or preconditioner
598    
599            @param theta: threshold for coarsening
600            @type theta: positive C{float}
601            """
602            theta=float(theta)
603            if theta<0 or theta>1:
604               raise ValueError,"threshold must be non-negative and less or equal 1."
605            self.__coarsening_threshold=theta
606        def getCoarseningThreshold(self):
607            """
608            Returns the threshold for coarsening in the algebraic multi level solver or preconditioner
609    
610            @rtype: C{float}
611            """
612            return self.__coarsening_threshold
613        def setNumSweeps(self,sweeps=2):
614            """
615            Sets the number of sweeps in a Jacobi or Gauss-Seidel/SOR preconditioner.
616    
617            @param sweeps: number of sweeps
618            @type theta: positive C{int}
619            """
620            sweeps=int(sweeps)
621            if sweeps<1:
622               raise ValueError,"number of sweeps must be positive."
623            self.__sweeps=sweeps
624        def getNumSweeps(self):
625            """
626            Returns the number of sweeps in a Jacobi or Gauss-Seidel/SOR preconditioner.
627    
628            @rtype: C{int}
629            """
630            return self.__sweeps
631        def setNumPreSweeps(self,sweeps=2):
632            """
633            Sets the number of sweeps in the pre-smoothing step of a multi level solver or preconditioner
634    
635            @param sweeps: number of sweeps
636            @type theta: positive C{int}
637            """
638            sweeps=int(sweeps)
639            if sweeps<1:
640               raise ValueError,"number of sweeps must be positive."
641            self.__pre_sweeps=sweeps
642        def getNumPreSweeps(self):
643            """
644            Returns he number of sweeps in the pre-smoothing step of a multi level solver or preconditioner
645    
646            @rtype: C{int}
647            """
648            return self.__pre_sweeps
649        def setNumPostSweeps(self,sweeps=2):
650            """
651            Sets the number of sweeps in the post-smoothing step of a multi level solver or preconditioner
652    
653            @param sweeps: number of sweeps
654            @type theta: positive C{int}
655            """
656            sweeps=int(sweeps)
657            if sweeps<1:
658               raise ValueError,"number of sweeps must be positive."
659            self.__post_sweeps=sweeps
660        def getNumPostSweeps(self):
661            """
662            Returns he number of sweeps in the post-smoothing step of a multi level solver or preconditioner
663    
664            @rtype: C{int}
665            """
666            return self.__post_sweeps
667    
668        def setTolerance(self,rtol=1.e-8):
669            """
670            Sets the relative tolerance for the solver
671    
672            @param rtol: relative tolerance
673            @type rtol: non-negative C{float}
674            """
675            rtol=float(rtol)
676            if rtol<0 or rtol>1:
677               raise ValueError,"tolerance must be non-negative and less or equal 1."
678            self.__tolerance=rtol
679        def getTolerance(self):
680            """
681            Returns the relative tolerance for the solver
682    
683            @rtype: C{float}
684            """
685            return self.__tolerance
686        def setAbsoluteTolerance(self,atol=0.):
687            """
688            Sets the absolute tolerance for the solver
689    
690            @param atol:  absolute tolerance
691            @type atol: non-negative C{float}
692            """
693            atol=float(atol)
694            if atol<0:
695               raise ValueError,"tolerance must be non-negative."
696            self.__absolute_tolerance=atol
697        def getAbsoluteTolerance(self):
698            """
699            Returns the absolute tolerance for the solver
700    
701            @rtype: C{float}
702            """
703            return self.__absolute_tolerance
704    
705        def setInnerTolerance(self,rtol=0.9):
706            """
707             Sets the relative tolerance for an inner iteration scheme for instance
708            on the coarsest level in a multi-level scheme.
709    
710            @param rtol: inner relative tolerance
711            @type rtol: positive C{float}
712            """
713            rtol=float(rtol)
714            if rtol<=0 or rtol>1:
715                raise ValueError,"tolerance must be positive and less or equal 1."
716            self.__inner_tolerance=rtol
717        def getInnerTolerance(self):
718            """
719            Returns the relative tolerance for an inner iteration scheme
720    
721            @rtype: C{float}
722            """
723            return self.__inner_tolerance
724        def setDropTolerance(self,drop_tol=0.01):
725            """
726            Sets the relative drop tolerance in ILUT
727    
728            @param drop_tol: drop tolerance
729            @type drop_tol: positive C{float}
730            """
731            drop_tol=float(drop_tol)
732            if drop_tol<=0 or drop_tol>1:
733                raise ValueError,"drop tolerance must be positive and less or equal 1."
734            self.__drop_tolerance=drop_tol
735        def getDropTolerance(self):
736            """
737            Returns the relative drop tolerance in ILUT
738    
739            @rtype: C{float}
740            """
741            return self.__drop_tolerance
742        def setDropStorage(self,storage=2.):
743            """
744            Sets the maximum allowed increase in storage for ILUT. C{storage}=2 would mean that
745            a doubling of the storage needed for the coefficient matrix is allowed in the ILUT factorization.
746    
747            @param storage: allowed storage increase
748            @type storage: C{float}
749            """
750            storage=float(storage)
751            if storage<1:
752                raise ValueError,"allowed storage increase must be greater or equal to 1."
753            self.__drop_storage=storage
754        def getDropStorage(self):
755        
756            """
757            Returns the maximum allowed increase in storage for ILUT
758    
759            @rtype: C{float}
760            """
761            return self.__drop_storage
762        def setRelaxationFactor(self,factor=0.3):
763            """
764            Sets the relaxation factor used to add dropped elements in RILU to the main diagonal.
765    
766            @param factor: relaxation factor
767            @type factor: C{float}
768            @note: RILU with a relaxation factor 0 is identical to ILU0
769            """
770            factor=float(factor)
771            if factor<0:
772                raise ValueError,"relaxation factor must be non-negative."
773            self.__relaxation=factor
774        def getRelaxationFactor(self):
775        
776            """
777            Returns the relaxation factor used to add dropped elements in RILU to the main diagonal.
778    
779            @rtype: C{float}
780            """
781            return self.__relaxation
782        def isSymmetric(self):
783            """
784            Checks if symmetry of the  coefficient matrix is indicated.
785    
786            @return: True if a symmetric PDE is indicated, False otherwise
787            @rtype: C{bool}
788            """
789            return self.__symmetric
790        def setSymmetryOn(self):
791            """
792            Sets the symmetry flag to indicate that the coefficient matrix is symmetric.
793            """
794            self.__symmetric=True
795        def setSymmetryOff(self):
796            """
797            Clears the symmetry flag for the coefficient matrix.
798            """
799            self.__symmetric=False
800        def setSymmetry(self,flag=False):
801            """
802            Sets the symmetry flag for the coefficient matrix to C{flag}.
803    
804            @param flag: If True, the symmetry flag is set otherwise reset.
805            @type flag: C{bool}
806            """
807            if flag:
808                self.setSymmetryOn()
809            else:
810                self.setSymmetryOff()
811        def isVerbose(self):
812            """
813            Returns C{True} if the solver is expected to be verbose.
814    
815            @return: True if verbosity of switched on.
816            @rtype: C{bool}
817            """
818            return self.__verbose
819    
820  def _CompTuple2(t1,t2):      def setVerbosityOn(self):
821            """
822            Switches the verbosity of the solver on.
823            """
824            self.__verbose=True
825        def setVerbosityOff(self):
826            """
827            Switches the verbosity of the solver off.
828            """
829            self.__verbose=False
830        def setVerbosity(self,verbose=False):
831            """
832            Sets the verbosity flag for the solver to C{flag}.
833    
834            @param flag: If C{True}, the verbosity of the solver is switched on.
835            @type flag: C{bool}
836            """
837            if verbose:
838                self.setVerbosityOn()
839            else:
840                self.setVerbosityOff()
841            
842        def adaptInnerTolerance(self):
843            """
844            Returns C{True} if the tolerance of the inner solver is selected automatically.
845            Otherwise the inner tolerance set by L{setInnerTolerance} is used.
846    
847            @return: C{True} if inner tolerance adaption is chosen.
848            @rtype: C{bool}
849            """
850            return self.__adapt_inner_tolerance
851    
852        def setInnerToleranceAdaptionOn(self):
853            """
854            Switches the automatic selection of inner tolerance on
855            """
856            self.__adapt_inner_tolerance=True
857        def setInnerToleranceAdaptionOff(self):
858            """
859            Switches the automatic selection of inner tolerance off.
860            """
861            self.__adapt_inner_tolerance=False
862        def setInnerToleranceAdaption(self,adapt=True):
863            """
864            Sets a flag to indicate automatic selection of the inner tolerance.
865    
866            @param adapt: If C{True}, the inner tolerance is selected automatically.
867            @type adapt: C{bool}
868            """
869            if adapt:
870                self.setInnerToleranceAdaptionOn()
871            else:
872                self.setInnerToleranceAdaptionOff()
873    
874        def acceptConvergenceFailure(self):
875            """
876            Returns C{True} if a failure to meet the stopping criteria within the
877            given number of iteration steps is not raising in exception. This is useful
878            if a solver is used in a non-linear context where the non-linear solver can
879            continue even if the returned the solution does not necessarily meet the
880            stopping criteria. One can use the L{hasConverged} method to check if the
881            last call to the solver was successful.
882    
883            @return: C{True} if a failure to achieve convergence is accepted.
884            @rtype: C{bool}
885            """
886            return self.__accept_convergence_failure
887    
888        def setAcceptanceConvergenceFailureOn(self):
889            """
890            Switches the acceptance of a failure of convergence on
891            """
892            self.__accept_convergence_failure=True
893        def setAcceptanceConvergenceFailureOff(self):
894            """
895            Switches the acceptance of a failure of convergence off.
896            """
897            self.__accept_convergence_failure=False
898        def setAcceptanceConvergenceFailure(self,accept=False):
899            """
900            Sets a flag to indicate the acceptance of a failure of convergence.
901    
902            @param accept: If C{True}, any failure to achieve convergence is accepted.
903            @type accept: C{bool}
904            """
905            if accept:
906                self.setAcceptanceConvergenceFailureOn()
907            else:
908                self.setAcceptanceConvergenceFailureOff()
909    
910    class IllegalCoefficient(ValueError):
911       """
912       Exception that is raised if an illegal coefficient of the general or
913       particular PDE is requested.
914       """
915       pass
916    
917    class IllegalCoefficientValue(ValueError):
918       """
919       Exception that is raised if an incorrect value for a coefficient is used.
920       """
921       pass
922    
923    class IllegalCoefficientFunctionSpace(ValueError):
924       """
925       Exception that is raised if an incorrect function space for a coefficient
926       is used.
927     """     """
    @brief  
928    
929     @param t1  class UndefinedPDEError(ValueError):
930     @param t2     """
931       Exception that is raised if a PDE is not fully defined yet.
932     """     """
933     dif=t1[0]+t1[1]-(t2[0]+t2[1])     pass
    if dif<0: return 1  
    elif dif>0: return -1  
    else: return 0  
934    
935  class PDECoefficientType:  class PDECoef(object):
936      """      """
937      @brief      A class for describing a PDE coefficient.
938    
939        @cvar INTERIOR: indicator that coefficient is defined on the interior of
940                        the PDE domain
941        @cvar BOUNDARY: indicator that coefficient is defined on the boundary of
942                        the PDE domain
943        @cvar CONTACT: indicator that coefficient is defined on the contact region
944                       within the PDE domain
945        @cvar INTERIOR_REDUCED: indicator that coefficient is defined on the
946                                interior of the PDE domain using a reduced
947                                integration order
948        @cvar BOUNDARY_REDUCED: indicator that coefficient is defined on the
949                                boundary of the PDE domain using a reduced
950                                integration order
951        @cvar CONTACT_REDUCED: indicator that coefficient is defined on the contact
952                               region within the PDE domain using a reduced
953                               integration order
954        @cvar SOLUTION: indicator that coefficient is defined through a solution of
955                        the PDE
956        @cvar REDUCED: indicator that coefficient is defined through a reduced
957                       solution of the PDE
958        @cvar BY_EQUATION: indicator that the dimension of the coefficient shape is
959                           defined by the number of PDE equations
960        @cvar BY_SOLUTION: indicator that the dimension of the coefficient shape is
961                           defined by the number of PDE solutions
962        @cvar BY_DIM: indicator that the dimension of the coefficient shape is
963                      defined by the spatial dimension
964        @cvar OPERATOR: indicator that the the coefficient alters the operator of
965                        the PDE
966        @cvar RIGHTHANDSIDE: indicator that the the coefficient alters the right
967                             hand side of the PDE
968        @cvar BOTH: indicator that the the coefficient alters the operator as well
969                    as the right hand side of the PDE
970    
971      """      """
     # identifier for location of Data objects defining coefficients  
972      INTERIOR=0      INTERIOR=0
973      BOUNDARY=1      BOUNDARY=1
974      CONTACT=2      CONTACT=2
975      CONTINUOUS=3      SOLUTION=3
976      # identifier in the pattern of coefficients:      REDUCED=4
977      # 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
978      # number of unknowns.      BY_SOLUTION=6
979      EQUATION=3      BY_DIM=7
980      SOLUTION=4      OPERATOR=10
981      DIM=5      RIGHTHANDSIDE=11
982      # indicator for what is altered if the coefficient is altered:      BOTH=12
983      OPERATOR=5      INTERIOR_REDUCED=13
984      RIGHTHANDSIDE=6      BOUNDARY_REDUCED=14
985      BOTH=7      CONTACT_REDUCED=15
986      def __init__(self,where,pattern,altering):  
987         """      def __init__(self, where, pattern, altering):
988         @brief Initialise a PDE Coefficient type         """
989           Initialises a PDE coefficient type.
990    
991           @param where: describes where the coefficient lives
992           @type where: one of L{INTERIOR}, L{BOUNDARY}, L{CONTACT}, L{SOLUTION},
993                        L{REDUCED}, L{INTERIOR_REDUCED}, L{BOUNDARY_REDUCED},
994                        L{CONTACT_REDUCED}
995           @param pattern: describes the shape of the coefficient and how the shape
996                           is built for a given spatial dimension and numbers of
997                           equations and solutions in then PDE. For instance,
998                           (L{BY_EQUATION},L{BY_SOLUTION},L{BY_DIM}) describes a
999                           rank 3 coefficient which is instantiated as shape (3,2,2)
1000                           in case of three equations and two solution components
1001                           on a 2-dimensional domain. In the case of single equation
1002                           and a single solution component the shape components
1003                           marked by L{BY_EQUATION} or L{BY_SOLUTION} are dropped.
1004                           In this case the example would be read as (2,).
1005           @type pattern: C{tuple} of L{BY_EQUATION}, L{BY_SOLUTION}, L{BY_DIM}
1006           @param altering: indicates what part of the PDE is altered if the
1007                            coefficient is altered
1008           @type altering: one of L{OPERATOR}, L{RIGHTHANDSIDE}, L{BOTH}
1009         """         """
1010           super(PDECoef, self).__init__()
1011         self.what=where         self.what=where
1012         self.pattern=pattern         self.pattern=pattern
1013         self.altering=altering         self.altering=altering
1014           self.resetValue()
1015    
1016      def getFunctionSpace(self,domain):      def resetValue(self):
1017         """         """
1018         @brief defines the FunctionSpace of the coefficient on the domain         Resets the coefficient value to the default.
   
        @param domain  
1019         """         """
1020         if self.what==self.INTERIOR: return escript.Function(domain)         self.value=escript.Data()
1021         elif self.what==self.BOUNDARY: return escript.FunctionOnBoundary(domain)  
1022         elif self.what==self.CONTACT: return escript.FunctionOnContactZero(domain)      def getFunctionSpace(self,domain,reducedEquationOrder=False,reducedSolutionOrder=False):
1023         elif self.what==self.CONTINUOUS: return escript.ContinuousFunction(domain)         """
1024           Returns the L{FunctionSpace<escript.FunctionSpace>} of the coefficient.
1025    
1026           @param domain: domain on which the PDE uses the coefficient
1027           @type domain: L{Domain<escript.Domain>}
1028           @param reducedEquationOrder: True to indicate that reduced order is used
1029                                        to represent the equation
1030           @type reducedEquationOrder: C{bool}
1031           @param reducedSolutionOrder: True to indicate that reduced order is used
1032                                        to represent the solution
1033           @type reducedSolutionOrder: C{bool}
1034           @return: L{FunctionSpace<escript.FunctionSpace>} of the coefficient
1035           @rtype: L{FunctionSpace<escript.FunctionSpace>}
1036           """
1037           if self.what==self.INTERIOR:
1038                return escript.Function(domain)
1039           elif self.what==self.INTERIOR_REDUCED:
1040                return escript.ReducedFunction(domain)
1041           elif self.what==self.BOUNDARY:
1042                return escript.FunctionOnBoundary(domain)
1043           elif self.what==self.BOUNDARY_REDUCED:
1044                return escript.ReducedFunctionOnBoundary(domain)
1045           elif self.what==self.CONTACT:
1046                return escript.FunctionOnContactZero(domain)
1047           elif self.what==self.CONTACT_REDUCED:
1048                return escript.ReducedFunctionOnContactZero(domain)
1049           elif self.what==self.SOLUTION:
1050                if reducedEquationOrder and reducedSolutionOrder:
1051                    return escript.ReducedSolution(domain)
1052                else:
1053                    return escript.Solution(domain)
1054           elif self.what==self.REDUCED:
1055                return escript.ReducedSolution(domain)
1056    
1057        def getValue(self):
1058           """
1059           Returns the value of the coefficient.
1060    
1061           @return: value of the coefficient
1062           @rtype: L{Data<escript.Data>}
1063           """
1064           return self.value
1065    
1066        def setValue(self,domain,numEquations=1,numSolutions=1,reducedEquationOrder=False,reducedSolutionOrder=False,newValue=None):
1067           """
1068           Sets the value of the coefficient to a new value.
1069    
1070           @param domain: domain on which the PDE uses the coefficient
1071           @type domain: L{Domain<escript.Domain>}
1072           @param numEquations: number of equations of the PDE
1073           @type numEquations: C{int}
1074           @param numSolutions: number of components of the PDE solution
1075           @type numSolutions: C{int}
1076           @param reducedEquationOrder: True to indicate that reduced order is used
1077                                        to represent the equation
1078           @type reducedEquationOrder: C{bool}
1079           @param reducedSolutionOrder: True to indicate that reduced order is used
1080                                        to represent the solution
1081           @type reducedSolutionOrder: C{bool}
1082           @param newValue: number of components of the PDE solution
1083           @type newValue: any object that can be converted into a
1084                           L{Data<escript.Data>} object with the appropriate shape
1085                           and L{FunctionSpace<escript.FunctionSpace>}
1086           @raise IllegalCoefficientValue: if the shape of the assigned value does
1087                                           not match the shape of the coefficient
1088           @raise IllegalCoefficientFunctionSpace: if unable to interpolate value
1089                                                   to appropriate function space
1090           """
1091           if newValue==None:
1092               newValue=escript.Data()
1093           elif isinstance(newValue,escript.Data):
1094               if not newValue.isEmpty():
1095                  if not newValue.getFunctionSpace() == self.getFunctionSpace(domain,reducedEquationOrder,reducedSolutionOrder):
1096                    try:
1097                      newValue=escript.Data(newValue,self.getFunctionSpace(domain,reducedEquationOrder,reducedSolutionOrder))
1098                    except:
1099                      raise IllegalCoefficientFunctionSpace,"Unable to interpolate coefficient to function space %s"%self.getFunctionSpace(domain)
1100           else:
1101               newValue=escript.Data(newValue,self.getFunctionSpace(domain,reducedEquationOrder,reducedSolutionOrder))
1102           if not newValue.isEmpty():
1103               if not self.getShape(domain,numEquations,numSolutions)==newValue.getShape():
1104                   raise IllegalCoefficientValue,"Expected shape of coefficient is %s but actual shape is %s."%(self.getShape(domain,numEquations,numSolutions),newValue.getShape())
1105           self.value=newValue
1106    
1107      def isAlteringOperator(self):      def isAlteringOperator(self):
1108          """          """
1109      @brief 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.
1110      """  
1111            @return: True if the operator of the PDE is changed when the
1112                     coefficient is changed
1113            @rtype: C{bool}
1114            """
1115          if self.altering==self.OPERATOR or self.altering==self.BOTH:          if self.altering==self.OPERATOR or self.altering==self.BOTH:
1116              return not None              return not None
1117          else:          else:
# Line 119  class PDECoefficientType: Line 1119  class PDECoefficientType:
1119    
1120      def isAlteringRightHandSide(self):      def isAlteringRightHandSide(self):
1121          """          """
1122      @brief return true if the right hand side of the PDE is changed when the coefficient is changed          Checks if the coefficient alters the right hand side of the PDE.
1123      """  
1124            @rtype: C{bool}
1125            @return: True if the right hand side of the PDE is changed when the
1126                     coefficient is changed, C{None} otherwise.
1127            """
1128          if self.altering==self.RIGHTHANDSIDE or self.altering==self.BOTH:          if self.altering==self.RIGHTHANDSIDE or self.altering==self.BOTH:
1129              return not None              return not None
1130          else:          else:
1131              return None              return None
1132    
1133      def estimateNumEquationsAndNumSolutions(self,shape=(),dim=3):      def estimateNumEquationsAndNumSolutions(self,domain,shape=()):
1134         """         """
1135         @brief 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
1136           the coefficient has the given shape.
1137    
1138         @param shape         @param domain: domain on which the PDE uses the coefficient
1139         @param dim         @type domain: L{Domain<escript.Domain>}
1140           @param shape: suggested shape of the coefficient
1141           @type shape: C{tuple} of C{int} values
1142           @return: the number of equations and number of solutions of the PDE if
1143                    the coefficient has given shape. If no appropriate numbers
1144                    could be identified, C{None} is returned
1145           @rtype: C{tuple} of two C{int} values or C{None}
1146         """         """
1147           dim=domain.getDim()
1148         if len(shape)>0:         if len(shape)>0:
1149             num=max(shape)+1             num=max(shape)+1
1150         else:         else:
1151             num=1             num=1
1152         search=[]         search=[]
1153         for u in range(num):         if self.definesNumEquation() and self.definesNumSolutions():
1154            for e in range(num):            for u in range(num):
1155               search.append((e,u))               for e in range(num):
1156         search.sort(_CompTuple2)                  search.append((e,u))
1157         for item in search:            search.sort(self.__CompTuple2)
1158               s=self.buildShape(item[0],item[1],dim)            for item in search:
1159                 s=self.getShape(domain,item[0],item[1])
1160               if len(s)==0 and len(shape)==0:               if len(s)==0 and len(shape)==0:
1161                   return (1,1)                   return (1,1)
1162               else:               else:
1163                   if s==shape: return item                   if s==shape: return item
1164         return None         elif self.definesNumEquation():
1165              for e in range(num,0,-1):
1166      def buildShape(self,e=1,u=1,dim=3):               s=self.getShape(domain,e,0)
1167          """               if len(s)==0 and len(shape)==0:
1168      @brief builds the required shape for a given number of equations e, number of unknowns u and spatial dimension dim                   return (1,None)
1169                 else:
1170                     if s==shape: return (e,None)
1171    
1172      @param e         elif self.definesNumSolutions():
1173      @param u            for u in range(num,0,-1):
1174      @param dim               s=self.getShape(domain,0,u)
1175      """               if len(s)==0 and len(shape)==0:
1176          s=()                   return (None,1)
         for i in self.pattern:  
              if i==self.EQUATION:  
                 if e>1: s=s+(e,)  
              elif i==self.SOLUTION:  
                 if u>1: s=s+(u,)  
1177               else:               else:
1178                  s=s+(dim,)                   if s==shape: return (None,u)
1179          return s         return None
1180    
1181  _PDECoefficientTypes={      def definesNumSolutions(self):
1182  "A"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,PDECoefficientType.DIM,PDECoefficientType.SOLUTION,PDECoefficientType.DIM),PDECoefficientType.OPERATOR),         """
1183  "B"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,PDECoefficientType.DIM,PDECoefficientType.SOLUTION),PDECoefficientType.OPERATOR),         Checks if the coefficient allows to estimate the number of solution
1184  "C"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,PDECoefficientType.SOLUTION,PDECoefficientType.DIM),PDECoefficientType.OPERATOR),         components.
 "D"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,PDECoefficientType.SOLUTION),PDECoefficientType.OPERATOR),  
 "X"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,PDECoefficientType.DIM),PDECoefficientType.RIGHTHANDSIDE),  
 "Y"         : PDECoefficientType(PDECoefficientType.INTERIOR,(PDECoefficientType.EQUATION,),PDECoefficientType.RIGHTHANDSIDE),  
 "d"         : PDECoefficientType(PDECoefficientType.BOUNDARY,(PDECoefficientType.EQUATION,PDECoefficientType.SOLUTION),PDECoefficientType.OPERATOR),  
 "y"         : PDECoefficientType(PDECoefficientType.BOUNDARY,(PDECoefficientType.EQUATION,),PDECoefficientType.RIGHTHANDSIDE),  
 "d_contact" : PDECoefficientType(PDECoefficientType.CONTACT,(PDECoefficientType.EQUATION,PDECoefficientType.SOLUTION),PDECoefficientType.OPERATOR),  
 "y_contact" : PDECoefficientType(PDECoefficientType.CONTACT,(PDECoefficientType.EQUATION,),PDECoefficientType.RIGHTHANDSIDE),  
 "r"         : PDECoefficientType(PDECoefficientType.CONTINUOUS,(PDECoefficientType.EQUATION,),PDECoefficientType.RIGHTHANDSIDE),  
 "q"         : PDECoefficientType(PDECoefficientType.CONTINUOUS,(PDECoefficientType.SOLUTION,),PDECoefficientType.BOTH),  
 }  
1185    
1186  class LinearPDE:         @return: True if the coefficient allows an estimate of the number of
1187     """                  solution components, False otherwise
1188     @brief Class to define a linear PDE         @rtype: C{bool}
1189             """
1190     class to define a linear PDE of the form         for i in self.pattern:
1191                 if i==self.BY_SOLUTION: return True
1192           return False
1193    
1194       -(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      def definesNumEquation(self):
1195           """
1196           Checks if the coefficient allows to estimate the number of equations.
1197    
1198       with boundary conditons:         @return: True if the coefficient allows an estimate of the number of
1199                    equations, False otherwise
1200           @rtype: C{bool}
1201           """
1202           for i in self.pattern:
1203                 if i==self.BY_EQUATION: return True
1204           return False
1205    
1206          n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_{ik}u_k = - n_j*X_{ij} + y_i      def __CompTuple2(self,t1,t2):
1207          """
1208          Compares two tuples of possible number of equations and number of
1209          solutions.
1210    
1211      and contact conditions        @param t1: the first tuple
1212          @param t2: the second tuple
1213          @return: 0, 1, or -1
1214          """
1215    
1216          n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_contact_{ik}[u_k] = - n_j*X_{ij} + y_contact_i        dif=t1[0]+t1[1]-(t2[0]+t2[1])
1217          if dif<0: return 1
1218          elif dif>0: return -1
1219          else: return 0
1220    
1221      and constraints:      def getShape(self,domain,numEquations=1,numSolutions=1):
1222           """
1223           Builds the required shape of the coefficient.
1224    
1225           u_i=r_i where q_i>0         @param domain: domain on which the PDE uses the coefficient
1226           @type domain: L{Domain<escript.Domain>}
1227           @param numEquations: number of equations of the PDE
1228           @type numEquations: C{int}
1229           @param numSolutions: number of components of the PDE solution
1230           @type numSolutions: C{int}
1231           @return: shape of the coefficient
1232           @rtype: C{tuple} of C{int} values
1233           """
1234           dim=domain.getDim()
1235           s=()
1236           for i in self.pattern:
1237                 if i==self.BY_EQUATION:
1238                    if numEquations>1: s=s+(numEquations,)
1239                 elif i==self.BY_SOLUTION:
1240                    if numSolutions>1: s=s+(numSolutions,)
1241                 else:
1242                    s=s+(dim,)
1243           return s
1244    
1245    #====================================================================================================================
1246    
1247    class LinearProblem(object):
1248     """     """
1249     DEFAULT_METHOD=util.DEFAULT_METHOD     This is the base class to define a general linear PDE-type problem for
1250     DIRECT=util.DIRECT     for an unknown function M{u} on a given domain defined through a
1251     CHOLEVSKY=util.CHOLEVSKY     L{Domain<escript.Domain>} object. The problem can be given as a single
1252     PCG=util.PCG     equation or as a system of equations.
1253     CR=util.CR  
1254     CGS=util.CGS     The class assumes that some sort of assembling process is required to form
1255     BICGSTAB=util.BICGSTAB     a problem of the form
1256     SSOR=util.SSOR  
1257     GMRES=util.GMRES     M{L u=f}
1258     PRES20=util.PRES20  
1259       where M{L} is an operator and M{f} is the right hand side. This operator
1260       problem will be solved to get the unknown M{u}.
1261    
1262     def __init__(self,domain,numEquations=0,numSolutions=0):     """
1263       def __init__(self,domain,numEquations=None,numSolutions=None,debug=False):
1264       """       """
1265       @brief initializes a new linear PDE.       Initializes a linear problem.
1266    
1267         @param domain: domain of the PDE
1268         @type domain: L{Domain<escript.Domain>}
1269         @param numEquations: number of equations. If C{None} the number of
1270                              equations is extracted from the coefficients.
1271         @param numSolutions: number of solution components. If C{None} the number
1272                              of solution components is extracted from the
1273                              coefficients.
1274         @param debug: if True debug information is printed
1275    
      @param args  
1276       """       """
1277         super(LinearProblem, self).__init__()
1278    
1279       # initialize attributes       self.__debug=debug
      self.__debug=None  
1280       self.__domain=domain       self.__domain=domain
1281       self.__numEquations=numEquations       self.__numEquations=numEquations
1282       self.__numSolutions=numSolutions       self.__numSolutions=numSolutions
1283       self.cleanCoefficients()       self.__altered_coefficients=False
1284         self.__reduce_equation_order=False
1285       self.__operator=escript.Operator()       self.__reduce_solution_order=False
      self.__operator_isValid=False  
      self.__righthandside=escript.Data()  
      self.__righthandside_isValid=False  
      self.__solution=escript.Data()  
      self.__solution_isValid=False  
   
      # set some default values:  
      self.__homogeneous_constraint=True  
      self.__row_function_space=escript.Solution(self.__domain)  
      self.__column_function_space=escript.Solution(self.__domain)  
      self.__tolerance=1.e-8  
      self.__solver_method=util.DEFAULT_METHOD  
      self.__matrix_type=self.__domain.getSystemMatrixTypeId(util.DEFAULT_METHOD,False)  
1286       self.__sym=False       self.__sym=False
1287       self.__lumping=False       self.setSolverOptions()
1288         self.__is_RHS_valid=False
1289         self.__is_operator_valid=False
1290         self.__COEFFICIENTS={}
1291         self.__solution_rtol=1.e99
1292         self.__solution_atol=1.e99
1293         self.setSymmetryOff()
1294         # initialize things:
1295         self.resetAllCoefficients()
1296         self.initializeSystem()
1297       # ==========================================================================
1298       #    general stuff:
1299       # ==========================================================================
1300       def __str__(self):
1301         """
1302         Returns a string representation of the PDE.
1303    
1304         @return: a simple representation of the PDE
1305         @rtype: C{str}
1306         """
1307         return "<LinearProblem %d>"%id(self)
1308       # ==========================================================================
1309       #    debug :
1310       # ==========================================================================
1311       def setDebugOn(self):
1312         """
1313         Switches debug output on.
1314         """
1315         self.__debug=not None
1316    
1317     def getCoefficient(self,name):     def setDebugOff(self):
1318         """
1319         Switches debug output off.
1320       """       """
1321       @brief return the value of the coefficient name       self.__debug=None
1322    
1323       @param name     def setDebug(self, flag):
1324       """       """
1325       return self.__coefficient[name]       Switches debug output on if C{flag} is True otherwise it is switched off.
1326    
1327     def setValue(self,**coefficients):       @param flag: desired debug status
1328        """       @type flag: C{bool}
1329        @brief sets new values to coefficients       """
1330         if flag:
1331             self.setDebugOn()
1332         else:
1333             self.setDebugOff()
1334    
1335        @param coefficients     def trace(self,text):
1336        """       """
1337        self._setValue(**coefficients)       Prints the text message if debug mode is switched on.
         
1338    
1339     def _setValue(self,**coefficients):       @param text: message to be printed
1340        """       @type text: C{string}
1341        @brief sets new values to coefficients       """
1342         if self.__debug: print "%s: %s"%(str(self),text)
1343    
1344        @param coefficients     # ==========================================================================
1345        """     # some service functions:
1346             # ==========================================================================
1347        # get the dictionary of the coefficinets been altered:     def introduceCoefficients(self,**coeff):
1348        alteredCoefficients={}         """
1349        for i,d in coefficients.iteritems():         Introduces new coefficients into the problem.
          if self.hasCoefficient(i):  
             if d == None:  
                 alteredCoefficients[i]=escript.Data()  
             elif isinstance(d,escript.Data):  
                 if d.isEmpty():  
                   alteredCoefficients[i]=escript.Data()  
                 else:  
                   alteredCoefficients[i]=escript.Data(d,self.getFunctionSpaceOfCoefficient(i))  
             else:  
                 alteredCoefficients[i]=escript.Data(d,self.getFunctionSpaceOfCoefficient(i))  
          else:  
             raise ValueError,"Attempt to set undefined coefficient %s"%i  
       # if numEquations and numSolutions is undefined we try identify their values based on the coefficients:  
       if self.__numEquations<1 or self.__numSolutions<1:  
             numEquations,numSolutions=identifyNumEquationsAndSolutions(self.getDomain().getDim(),alteredCoefficients)  
             if self.__numEquations<1 and numEquations>0: self.__numEquations=numEquations  
             if self.__numSolutions<1 and numSolutions>0: self.__numSolutions=numSolutions  
             if self.debug() and self.__numEquations>0: print "PDE Debug: identified number of equations is ",self.__numEquations  
             if self.debug() and self.__numSolutions>0: print "PDE Debug: identified number of solutions is ",self.__numSolutions  
1350    
1351        # now we check the shape of the coefficient if numEquations and numSolutions are set:         Use::
       if  self.__numEquations>0 and  self.__numSolutions>0:  
          for i in self.__coefficient.iterkeys():  
              if alteredCoefficients.has_key(i) and not alteredCoefficients[i].isEmpty():  
                  if not self.getShapeOfCoefficient(i)==alteredCoefficients[i].getShape():  
                     raise ValueError,"Expected shape for coefficient %s is %s but actual shape is %s."%(i,self.getShapeOfCoefficient(i),alteredCoefficients[i].getShape())  
              else:  
                  if not self.__coefficient[i].isEmpty():  
                     if not self.getShapeOfCoefficient(i)==self.__coefficient[i].getShape():  
                        raise ValueError,"Expected shape for coefficient %s is %s but actual shape is %s."%(i,self.getShapeOfCoefficient(i),self.__coefficient[i].getShape())  
       # overwrite new values:  
       for i,d in alteredCoefficients.iteritems():  
          if self.debug(): print "PDE Debug: Coefficient %s has been altered."%i  
          self.__coefficient[i]=d  
          self.alteredCoefficient(i)  
   
       # reset the HomogeneousConstraintFlag:  
       self.__setHomogeneousConstraintFlag()  
       if not "q" in alteredCoefficients and not self.__homogeneous_constraint: self.__rebuildSystem()  
   
    def cleanCoefficients(self):  
      """  
      @brief resets all coefficients to default values.  
      """  
      self.__coefficient={}  
      for i in _PDECoefficientTypes.iterkeys():  
          self.__coefficient[i]=escript.Data()  
1352    
1353     def getShapeOfCoefficient(self,name):         p.introduceCoefficients(A=PDECoef(...), B=PDECoef(...))
1354    
1355           to introduce the coefficients M{A} ans M{B}.
1356           """
1357           for name, type in coeff.items():
1358               if not isinstance(type,PDECoef):
1359                  raise ValueError,"coefficient %s has no type."%name
1360               self.__COEFFICIENTS[name]=type
1361               self.__COEFFICIENTS[name].resetValue()
1362               self.trace("coefficient %s has been introduced."%name)
1363    
1364       def getDomain(self):
1365       """       """
1366       @brief return the shape of the coefficient name       Returns the domain of the PDE.
1367    
1368       @param name       @return: the domain of the PDE
1369         @rtype: L{Domain<escript.Domain>}
1370       """       """
1371       if self.hasCoefficient(name):       return self.__domain
1372          return _PDECoefficientTypes[name].buildShape(self.getNumEquations(),self.getNumSolutions(),self.getDomain().getDim())     def getDomainStatus(self):
1373       else:       """
1374          raise ValueError,"Solution coefficient %s requested"%name       Return the status indicator of the domain
1375         """
1376         return self.getDomain().getStatus()
1377    
1378     def getFunctionSpaceOfCoefficient(self,name):     def getSystemStatus(self):
1379       """       """
1380       @brief return the atoms of the coefficient name       Return the domain status used to build the current system
1381         """
1382         return self.__system_status
1383       def setSystemStatus(self,status=None):
1384         """
1385         Sets the system status to C{status} if C{status} is not present the
1386         current status of the domain is used.
1387         """
1388         if status == None:
1389             self.__system_status=self.getDomainStatus()
1390         else:
1391             self.__system_status=status
1392    
1393       @param name     def getDim(self):
1394       """       """
1395       if self.hasCoefficient(name):       Returns the spatial dimension of the PDE.
         return _PDECoefficientTypes[name].getFunctionSpace(self.getDomain())  
      else:  
         raise ValueError,"Solution coefficient %s requested"%name  
1396    
1397     def alteredCoefficient(self,name):       @return: the spatial dimension of the PDE domain
1398         @rtype: C{int}
1399       """       """
1400       @brief annonced that coefficient name has been changed       return self.getDomain().getDim()
1401    
1402       @param name     def getNumEquations(self):
1403       """       """
1404       if self.hasCoefficient(name):       Returns the number of equations.
         if _PDECoefficientTypes[name].isAlteringOperator(): self.__rebuildOperator()  
         if _PDECoefficientTypes[name].isAlteringRightHandSide(): self.__rebuildRightHandSide()  
      else:  
         raise ValueError,"Solution coefficient %s requested"%name  
1405    
1406     def __setHomogeneousConstraintFlag(self):       @return: the number of equations
1407        """       @rtype: C{int}
1408        @brief checks if the constraints are homogeneous and sets self.__homogeneous_constraint accordingly.       @raise UndefinedPDEError: if the number of equations is not specified yet
1409        """       """
1410        self.__homogeneous_constraint=True       if self.__numEquations==None:
1411        q=self.getCoefficient("q")           if self.__numSolutions==None:
1412        r=self.getCoefficient("r")              raise UndefinedPDEError,"Number of equations is undefined. Please specify argument numEquations."
1413        if not q.isEmpty() and not r.isEmpty():           else:
1414           print (q*r).Lsup(), 1.e-13*r.Lsup()              self.__numEquations=self.__numSolutions
1415           if (q*r).Lsup()>=1.e-13*r.Lsup(): self.__homogeneous_constraint=False       return self.__numEquations
       if self.debug():  
            if self.__homogeneous_constraint:  
                print "PDE Debug: Constraints are homogeneous."  
            else:  
                print "PDE Debug: Constraints are inhomogeneous."  
   
1416    
1417     def hasCoefficient(self,name):     def getNumSolutions(self):
1418        """       """
1419        @brief return true if name is the name of a coefficient       Returns the number of unknowns.
1420    
1421        @param name       @return: the number of unknowns
1422        """       @rtype: C{int}
1423        return self.__coefficient.has_key(name)       @raise UndefinedPDEError: if the number of unknowns is not specified yet
1424         """
1425         if self.__numSolutions==None:
1426            if self.__numEquations==None:
1427                raise UndefinedPDEError,"Number of solution is undefined. Please specify argument numSolutions."
1428            else:
1429                self.__numSolutions=self.__numEquations
1430         return self.__numSolutions
1431    
1432     def getFunctionSpaceForEquation(self):     def reduceEquationOrder(self):
      """  
      @brief return true if the test functions should use reduced order  
1433       """       """
1434       return self.__row_function_space       Returns the status of order reduction for the equation.
1435    
1436     def getFunctionSpaceForSolution(self):       @return: True if reduced interpolation order is used for the
1437                  representation of the equation, False otherwise
1438         @rtype: L{bool}
1439       """       """
1440       @brief return true if the interpolation of the solution should use reduced order       return self.__reduce_equation_order
      """  
      return self.__column_function_space  
1441    
1442     # ===== debug ==============================================================     def reduceSolutionOrder(self):
1443     def setDebugOn(self):       """
1444         """       Returns the status of order reduction for the solution.
        @brief  
        """  
        self.__debug=not None  
   
    def setDebugOff(self):  
        """  
        @brief  
        """  
        self.__debug=None  
   
    def debug(self):  
        """  
        @brief returns true if the PDE is in the debug mode  
        """  
        return self.__debug  
   
    #===== Lumping ===========================  
    def setLumpingOn(self):  
       """  
       @brief indicates to use matrix lumping  
       """  
       if not self.isUsingLumping():  
          raise SystemError,"Lumping is not working yet! Talk to the experts"  
          if self.debug() : print "PDE Debug: lumping is set on"  
          self.__rebuildOperator()  
          self.__lumping=True  
1445    
1446     def setLumpingOff(self):       @return: True if reduced interpolation order is used for the
1447        """                representation of the solution, False otherwise
1448        @brief switches off matrix lumping       @rtype: L{bool}
1449        """       """
1450        if self.isUsingLumping():       return self.__reduce_solution_order
          if self.debug() : print "PDE Debug: lumping is set off"  
          self.__rebuildOperator()  
          self.__lumping=False  
1451    
1452     def setLumping(self,flag=False):     def getFunctionSpaceForEquation(self):
1453        """       """
1454        @brief set the matrix lumping flag to flag       Returns the L{FunctionSpace<escript.FunctionSpace>} used to discretize
1455        """       the equation.
       if flag:  
          self.setLumpingOn()  
       else:  
          self.setLumpingOff()  
1456    
1457     def isUsingLumping(self):       @return: representation space of equation
1458        """       @rtype: L{FunctionSpace<escript.FunctionSpace>}
1459        @brief       """
1460        """       if self.reduceEquationOrder():
1461        return self.__lumping           return escript.ReducedSolution(self.getDomain())
1462         else:
1463             return escript.Solution(self.getDomain())
1464    
1465     #============ method business =========================================================     def getFunctionSpaceForSolution(self):
1466     def setSolverMethod(self,solver=util.DEFAULT_METHOD):       """
1467         """       Returns the L{FunctionSpace<escript.FunctionSpace>} used to represent
1468         @brief sets a new solver       the solution.
        """  
        if not solver==self.getSolverMethod():  
            self.__solver_method=solver  
            if self.debug() : print "PDE Debug: New solver is %s"%solver  
            self.__checkMatrixType()  
1469    
1470     def getSolverMethod(self):       @return: representation space of solution
1471         """       @rtype: L{FunctionSpace<escript.FunctionSpace>}
1472         @brief returns the solver method       """
1473         """       if self.reduceSolutionOrder():
1474         return self.__solver_method           return escript.ReducedSolution(self.getDomain())
1475         else:
1476             return escript.Solution(self.getDomain())
1477    
1478     #============ tolerance business =========================================================     # ==========================================================================
1479     def setTolerance(self,tol=1.e-8):     #   solver settings:
1480         """     # ==========================================================================
1481         @brief resets the tolerance to tol.     def setSolverOptions(self,options=None):
1482         """         """
1483         if not tol>0:         Sets the solver options.
1484             raise ValueException,"Tolerance as to be positive"  
1485         if tol<self.getTolerance(): self.__rebuildSolution()         @param options: the new solver options. If equal C{None}, the solver options are set to the default.
1486         if self.debug() : print "PDE Debug: New tolerance %e",tol         @type options: L{SolverOptions} or C{None}
1487         self.__tolerance=tol         @note: The symmetry flag of options is overwritten by the symmetry flag of the L{LinearProblem}.
1488         return         """
1489     def getTolerance(self):         if options==None:
1490              self.__solver_options=SolverOptions()
1491           elif isinstance(options, SolverOptions):
1492              self.__solver_options=options
1493           else:
1494              raise ValueError,"options must be a SolverOptions object."
1495           self.__solver_options.setSymmetry(self.__sym)
1496        
1497       def getSolverOptions(self):
1498         """         """
1499         @brief returns the tolerance set for the solution         Returns the solver options
1500      
1501           @rtype: L{SolverOptions}
1502         """         """
1503         return self.__tolerance         self.__solver_options.setSymmetry(self.__sym)
1504           return self.__solver_options
1505          
1506       def isUsingLumping(self):
1507          """
1508          Checks if matrix lumping is the current solver method.
1509    
1510     #===== symmetry  flag ==========================        @return: True if the current solver method is lumping
1511          @rtype: C{bool}
1512          """
1513          return self.getSolverOptions().getSolverMethod()==self.getSolverOptions().LUMPING
1514       # ==========================================================================
1515       #    symmetry  flag:
1516       # ==========================================================================
1517     def isSymmetric(self):     def isSymmetric(self):
1518        """        """
1519        @brief returns true is the operator is considered to be symmetric        Checks if symmetry is indicated.
1520    
1521          @return: True if a symmetric PDE is indicated, False otherwise
1522          @rtype: C{bool}
1523          @note: the method is equivalent to use getSolverOptions().isSymmetric()
1524        """        """
1525        return self.__sym        self.getSolverOptions().isSymmetric()
1526    
1527     def setSymmetryOn(self):     def setSymmetryOn(self):
1528        """        """
1529        @brief sets the symmetry flag to true        Sets the symmetry flag.
1530          @note: The method overwrites the symmetry flag set by the solver options
1531        """        """
1532        if not self.isSymmetric():        self.__sym=True
1533           if self.debug() : print "PDE Debug: Operator is set to be symmetric"        self.getSolverOptions().setSymmetryOn()
          self.__sym=True  
          self.__checkMatrixType()  
1534    
1535     def setSymmetryOff(self):     def setSymmetryOff(self):
1536        """        """
1537        @brief sets the symmetry flag to false        Clears the symmetry flag.
1538          @note: The method overwrites the symmetry flag set by the solver options
1539        """        """
1540        if self.isSymmetric():        self.__sym=False
1541           if self.debug() : print "PDE Debug: Operator is set to be unsymmetric"        self.getSolverOptions().setSymmetryOff()
          self.__sym=False  
          self.__checkMatrixType()  
   
    def setSymmetryTo(self,flag=False):  
      """  
      @brief sets the symmetry flag to flag  
1542    
1543       @param flag     def setSymmetry(self,flag=False):
1544       """        """
1545       if flag:        Sets the symmetry flag to C{flag}.
         self.setSymmetryOn()  
      else:  
         self.setSymmetryOff()  
1546    
1547     #===== order reduction ==========================        @param flag: If True, the symmetry flag is set otherwise reset.
1548          @type flag: C{bool}
1549          @note: The method overwrites the symmetry flag set by the solver options
1550          """
1551          self.getSolverOptions().setSymmetry(flag)
1552       # ==========================================================================
1553       # function space handling for the equation as well as the solution
1554       # ==========================================================================
1555     def setReducedOrderOn(self):     def setReducedOrderOn(self):
1556       """       """
1557       @brief switches to on reduced order       Switches reduced order on for solution and equation representation.
1558    
1559         @raise RuntimeError: if order reduction is altered after a coefficient has
1560                              been set
1561       """       """
1562       self.setReducedOrderForSolutionOn()       self.setReducedOrderForSolutionOn()
1563       self.setReducedOrderForEquationOn()       self.setReducedOrderForEquationOn()
1564    
1565     def setReducedOrderOff(self):     def setReducedOrderOff(self):
1566       """       """
1567       @brief switches to full order       Switches reduced order off for solution and equation representation
1568    
1569         @raise RuntimeError: if order reduction is altered after a coefficient has
1570                              been set
1571       """       """
1572       self.setReducedOrderForSolutionOff()       self.setReducedOrderForSolutionOff()
1573       self.setReducedOrderForEquationOff()       self.setReducedOrderForEquationOff()
1574    
1575     def setReducedOrderTo(self,flag=False):     def setReducedOrderTo(self,flag=False):
1576       """       """
1577       @brief sets order according to flag       Sets order reduction state for both solution and equation representation
1578         according to flag.
1579    
1580       @param flag       @param flag: if True, the order reduction is switched on for both solution
1581                      and equation representation, otherwise or if flag is not
1582                      present order reduction is switched off
1583         @type flag: C{bool}
1584         @raise RuntimeError: if order reduction is altered after a coefficient has
1585                              been set
1586       """       """
1587       self.setReducedOrderForSolutionTo(flag)       self.setReducedOrderForSolutionTo(flag)
1588       self.setReducedOrderForEquationTo(flag)       self.setReducedOrderForEquationTo(flag)
                                                                                                                                                             
1589    
1590     #===== order reduction solution ==========================  
1591     def setReducedOrderForSolutionOn(self):     def setReducedOrderForSolutionOn(self):
1592       """       """
1593       @brief switches to reduced order to interpolate solution       Switches reduced order on for solution representation.
1594    
1595         @raise RuntimeError: if order reduction is altered after a coefficient has
1596                              been set
1597       """       """
1598       new_fs=escript.ReducedSolution(self.getDomain())       if not self.__reduce_solution_order:
1599       if self.getFunctionSpaceForSolution()!=new_fs:           if self.__altered_coefficients:
1600           if self.debug() : print "PDE Debug: Reduced order is used to interpolate solution."                raise RuntimeError,"order cannot be altered after coefficients have been defined."
1601           self.__column_function_space=new_fs           self.trace("Reduced order is used for solution representation.")
1602           self.__rebuildSystem(deep=True)           self.__reduce_solution_order=True
1603             self.initializeSystem()
1604    
1605     def setReducedOrderForSolutionOff(self):     def setReducedOrderForSolutionOff(self):
1606       """       """
1607       @brief switches to full order to interpolate solution       Switches reduced order off for solution representation
1608    
1609         @raise RuntimeError: if order reduction is altered after a coefficient has
1610                              been set.
1611       """       """
1612       new_fs=escript.Solution(self.getDomain())       if self.__reduce_solution_order:
1613       if self.getFunctionSpaceForSolution()!=new_fs:           if self.__altered_coefficients:
1614           if self.debug() : print "PDE Debug: Full order is used to interpolate solution."                raise RuntimeError,"order cannot be altered after coefficients have been defined."
1615           self.__column_function_space=new_fs           self.trace("Full order is used to interpolate solution.")
1616           self.__rebuildSystem(deep=True)           self.__reduce_solution_order=False
1617             self.initializeSystem()
1618    
1619     def setReducedOrderForSolutionTo(self,flag=False):     def setReducedOrderForSolutionTo(self,flag=False):
1620       """       """
1621       @brief sets order for test functions according to flag       Sets order reduction state for solution representation according to flag.
1622    
1623       @param flag       @param flag: if flag is True, the order reduction is switched on for
1624                      solution representation, otherwise or if flag is not present
1625                      order reduction is switched off
1626         @type flag: C{bool}
1627         @raise RuntimeError: if order reduction is altered after a coefficient has
1628                              been set
1629       """       """
1630       if flag:       if flag:
1631          self.setReducedOrderForSolutionOn()          self.setReducedOrderForSolutionOn()
1632       else:       else:
1633          self.setReducedOrderForSolutionOff()          self.setReducedOrderForSolutionOff()
1634                                                                                                                                                              
    #===== order reduction equation ==========================  
1635     def setReducedOrderForEquationOn(self):     def setReducedOrderForEquationOn(self):
1636       """       """
1637       @brief switches to reduced order for test functions       Switches reduced order on for equation representation.
1638    
1639         @raise RuntimeError: if order reduction is altered after a coefficient has
1640                              been set
1641       """       """
1642       new_fs=escript.ReducedSolution(self.getDomain())       if not self.__reduce_equation_order:
1643       if self.getFunctionSpaceForEquation()!=new_fs:           if self.__altered_coefficients:
1644           if self.debug() : print "PDE Debug: Reduced order is used for test functions."                raise RuntimeError,"order cannot be altered after coefficients have been defined."
1645           self.__row_function_space=new_fs           self.trace("Reduced order is used for test functions.")
1646           self.__rebuildSystem(deep=True)           self.__reduce_equation_order=True
1647             self.initializeSystem()
1648    
1649     def setReducedOrderForEquationOff(self):     def setReducedOrderForEquationOff(self):
1650       """       """
1651       @brief switches to full order for test functions       Switches reduced order off for equation representation.
1652    
1653         @raise RuntimeError: if order reduction is altered after a coefficient has
1654                              been set
1655       """       """
1656       new_fs=escript.Solution(self.getDomain())       if self.__reduce_equation_order:
1657       if self.getFunctionSpaceForEquation()!=new_fs:           if self.__altered_coefficients:
1658           if self.debug() : print "PDE Debug: Full order is used for test functions."                raise RuntimeError,"order cannot be altered after coefficients have been defined."
1659           self.__row_function_space=new_fs           self.trace("Full order is used for test functions.")
1660           self.__rebuildSystem(deep=True)           self.__reduce_equation_order=False
1661             self.initializeSystem()
1662    
1663     def setReducedOrderForEquationTo(self,flag=False):     def setReducedOrderForEquationTo(self,flag=False):
1664       """       """
1665       @brief sets order for test functions according to flag       Sets order reduction state for equation representation according to flag.
1666    
1667       @param flag       @param flag: if flag is True, the order reduction is switched on for
1668                      equation representation, otherwise or if flag is not present
1669                      order reduction is switched off
1670         @type flag: C{bool}
1671         @raise RuntimeError: if order reduction is altered after a coefficient has
1672                              been set
1673       """       """
1674       if flag:       if flag:
1675          self.setReducedOrderForEquationOn()          self.setReducedOrderForEquationOn()
1676       else:       else:
1677          self.setReducedOrderForEquationOff()          self.setReducedOrderForEquationOff()
1678                                                                                                                                                                 def getOperatorType(self):
1679          """
1680          Returns the current system type.
1681          """
1682          return self.__operator_type
1683    
1684       def checkSymmetricTensor(self,name,verbose=True):
1685          """
1686          Tests a coefficient for symmetry.
1687    
1688          @param name: name of the coefficient
1689          @type name: C{str}
1690          @param verbose: if set to True or not present a report on coefficients
1691                          which break the symmetry is printed.
1692          @type verbose: C{bool}
1693          @return: True if coefficient C{name} is symmetric
1694          @rtype: C{bool}
1695          """
1696          SMALL_TOLERANCE=util.EPSILON*10.
1697          A=self.getCoefficient(name)
1698          verbose=verbose or self.__debug
1699          out=True
1700          if not A.isEmpty():
1701             tol=util.Lsup(A)*SMALL_TOLERANCE
1702             s=A.getShape()
1703             if A.getRank() == 4:
1704                if s[0]==s[2] and s[1] == s[3]:
1705                   for i in range(s[0]):
1706                      for j in range(s[1]):
1707                         for k in range(s[2]):
1708                            for l in range(s[3]):
1709                                if util.Lsup(A[i,j,k,l]-A[k,l,i,j])>tol:
1710                                   if verbose: print "non-symmetric problem as %s[%d,%d,%d,%d]!=%s[%d,%d,%d,%d]"%(name,i,j,k,l,name,k,l,i,j)
1711                                   out=False
1712                else:
1713                     if verbose: print "non-symmetric problem because of inappropriate shape %s of coefficient %s."%(s,name)
1714                     out=False
1715             elif A.getRank() == 2:
1716                if s[0]==s[1]:
1717                   for j in range(s[0]):
1718                      for l in range(s[1]):
1719                         if util.Lsup(A[j,l]-A[l,j])>tol:
1720                            if verbose: print "non-symmetric problem because %s[%d,%d]!=%s[%d,%d]"%(name,j,l,name,l,j)
1721                            out=False
1722                else:
1723                     if verbose: print "non-symmetric problem because of inappropriate shape %s of coefficient %s."%(s,name)
1724                     out=False
1725             elif A.getRank() == 0:
1726                pass
1727             else:
1728                 raise ValueError,"Cannot check rank %s of %s."%(A.getRank(),name)
1729          return out
1730    
1731       def checkReciprocalSymmetry(self,name0,name1,verbose=True):
1732          """
1733          Tests two coefficients for reciprocal symmetry.
1734    
1735          @param name0: name of the first coefficient
1736          @type name0: C{str}
1737          @param name1: name of the second coefficient
1738          @type name1: C{str}
1739          @param verbose: if set to True or not present a report on coefficients
1740                          which break the symmetry is printed
1741          @type verbose: C{bool}
1742          @return: True if coefficients C{name0} and C{name1} are reciprocally
1743                   symmetric.
1744          @rtype: C{bool}
1745          """
1746          SMALL_TOLERANCE=util.EPSILON*10.
1747          B=self.getCoefficient(name0)
1748          C=self.getCoefficient(name1)
1749          verbose=verbose or self.__debug
1750          out=True
1751          if B.isEmpty() and not C.isEmpty():
1752             if verbose: print "non-symmetric problem because %s is not present but %s is"%(name0,name1)
1753             out=False
1754          elif not B.isEmpty() and C.isEmpty():
1755             if verbose: print "non-symmetric problem because %s is not present but %s is"%(name0,name1)
1756             out=False
1757          elif not B.isEmpty() and not C.isEmpty():
1758             sB=B.getShape()
1759             sC=C.getShape()
1760             tol=(util.Lsup(B)+util.Lsup(C))*SMALL_TOLERANCE/2.
1761             if len(sB) != len(sC):
1762                 if verbose: print "non-symmetric problem because ranks of %s (=%s) and %s (=%s) are different."%(name0,len(sB),name1,len(sC))
1763                 out=False
1764             else:
1765                 if len(sB)==0:
1766                   if util.Lsup(B-C)>tol:
1767                      if verbose: print "non-symmetric problem because %s!=%s"%(name0,name1)
1768                      out=False
1769                 elif len(sB)==1:
1770                   if sB[0]==sC[0]:
1771                      for j in range(sB[0]):
1772                         if util.Lsup(B[j]-C[j])>tol:
1773                            if verbose: print "non-symmetric PDE because %s[%d]!=%s[%d]"%(name0,j,name1,j)
1774                            out=False
1775                   else:
1776                     if verbose: print "non-symmetric problem because of inappropriate shapes %s and %s of coefficients %s and %s, respectively."%(sB,sC,name0,name1)
1777                 elif len(sB)==3:
1778                   if sB[0]==sC[1] and sB[1]==sC[2] and sB[2]==sC[0]:
1779                       for i in range(sB[0]):
1780                          for j in range(sB[1]):
1781                             for k in range(sB[2]):
1782                                if util.Lsup(B[i,j,k]-C[k,i,j])>tol:
1783                                     if verbose: print "non-symmetric problem because %s[%d,%d,%d]!=%s[%d,%d,%d]"%(name0,i,j,k,name1,k,i,j)
1784                                     out=False
1785                   else:
1786                     if verbose: print "non-symmetric problem because of inappropriate shapes %s and %s of coefficients %s and %s, respectively."%(sB,sC,name0,name1)
1787                 else:
1788                     raise ValueError,"Cannot check rank %s of %s and %s."%(len(sB),name0,name1)
1789          return out
1790    
1791       def getCoefficient(self,name):
1792         """
1793         Returns the value of the coefficient C{name}.
1794    
1795         @param name: name of the coefficient requested
1796         @type name: C{string}
1797         @return: the value of the coefficient
1798         @rtype: L{Data<escript.Data>}
1799         @raise IllegalCoefficient: if C{name} is not a coefficient of the PDE
1800         """
1801         if self.hasCoefficient(name):
1802             return self.__COEFFICIENTS[name].getValue()
1803         else:
1804            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1805    
1806       def hasCoefficient(self,name):
1807         """
1808         Returns True if C{name} is the name of a coefficient.
1809    
1810         @param name: name of the coefficient enquired
1811         @type name: C{string}
1812         @return: True if C{name} is the name of a coefficient of the general PDE,
1813                  False otherwise
1814         @rtype: C{bool}
1815         """
1816         return self.__COEFFICIENTS.has_key(name)
1817    
1818       def createCoefficient(self, name):
1819         """
1820         Creates a L{Data<escript.Data>} object corresponding to coefficient
1821         C{name}.
1822    
1823         @return: the coefficient C{name} initialized to 0
1824         @rtype: L{Data<escript.Data>}
1825         @raise IllegalCoefficient: if C{name} is not a coefficient of the PDE
1826         """
1827         if self.hasCoefficient(name):
1828            return escript.Data(0.,self.getShapeOfCoefficient(name),self.getFunctionSpaceForCoefficient(name))
1829         else:
1830            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1831    
1832       def getFunctionSpaceForCoefficient(self,name):
1833         """
1834         Returns the L{FunctionSpace<escript.FunctionSpace>} to be used for
1835         coefficient C{name}.
1836    
1837         @param name: name of the coefficient enquired
1838         @type name: C{string}
1839         @return: the function space to be used for coefficient C{name}
1840         @rtype: L{FunctionSpace<escript.FunctionSpace>}
1841         @raise IllegalCoefficient: if C{name} is not a coefficient of the PDE
1842         """
1843         if self.hasCoefficient(name):
1844            return self.__COEFFICIENTS[name].getFunctionSpace(self.getDomain())
1845         else:
1846            raise ValueError,"unknown coefficient %s requested"%name
1847    
1848       def getShapeOfCoefficient(self,name):
1849         """
1850         Returns the shape of the coefficient C{name}.
1851    
1852     # ==== initialization =====================================================================       @param name: name of the coefficient enquired
1853     def __makeNewOperator(self):       @type name: C{string}
1854         @return: the shape of the coefficient C{name}
1855         @rtype: C{tuple} of C{int}
1856         @raise IllegalCoefficient: if C{name} is not a coefficient of the PDE
1857         """
1858         if self.hasCoefficient(name):
1859            return self.__COEFFICIENTS[name].getShape(self.getDomain(),self.getNumEquations(),self.getNumSolutions())
1860         else:
1861            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1862    
1863       def resetAllCoefficients(self):
1864         """
1865         Resets all coefficients to their default values.
1866         """
1867         for i in self.__COEFFICIENTS.iterkeys():
1868             self.__COEFFICIENTS[i].resetValue()
1869    
1870       def alteredCoefficient(self,name):
1871         """
1872         Announces that coefficient C{name} has been changed.
1873    
1874         @param name: name of the coefficient affected
1875         @type name: C{string}
1876         @raise IllegalCoefficient: if C{name} is not a coefficient of the PDE
1877         @note: if C{name} is q or r, the method will not trigger a rebuild of the
1878                system as constraints are applied to the solved system.
1879         """
1880         if self.hasCoefficient(name):
1881            self.trace("Coefficient %s has been altered."%name)
1882            if not ((name=="q" or name=="r") and self.isUsingLumping()):
1883               if self.__COEFFICIENTS[name].isAlteringOperator(): self.invalidateOperator()
1884               if self.__COEFFICIENTS[name].isAlteringRightHandSide(): self.invalidateRightHandSide()
1885         else:
1886            raise IllegalCoefficient,"illegal coefficient %s requested for general PDE."%name
1887    
1888       def validSolution(self):
1889         """         """
1890         @brief         Marks the solution as valid.
1891         """         """
1892         return self.getDomain().newOperator( \         self.__is_solution_valid=True
                            self.getNumEquations(), \  
                            self.getFunctionSpaceForEquation(), \  
                            self.getNumSolutions(), \  
                            self.getFunctionSpaceForSolution(), \  
                            self.__matrix_type)  
1893    
1894     def __makeNewRightHandSide(self):     def invalidateSolution(self):
1895         """         """
1896         @brief         Indicates the PDE has to be resolved if the solution is requested.
1897         """         """
1898         return escript.Data(0.,(self.getNumEquations(),),self.getFunctionSpaceForEquation(),True)         self.trace("System will be resolved.")
1899           self.__is_solution_valid=False
1900    
1901     def __makeNewSolution(self):     def isSolutionValid(self):
1902         """         """
1903         @brief         Returns True if the solution is still valid.
1904         """         """
1905         return escript.Data(0.,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True)         if not self.getDomainStatus()==self.getSystemStatus(): self.invalidateSolution()
1906           if self.__solution_rtol>self.getSolverOptions().getTolerance() or \
1907              self.__solution_atol>self.getSolverOptions().getAbsoluteTolerance():
1908             self.invalidateSolution()  
1909           return self.__is_solution_valid
1910    
1911     def __getFreshOperator(self):     def validOperator(self):
1912         """         """
1913         @brief         Marks the operator as valid.
1914         """         """
1915         if self.__operator.isEmpty():         self.__is_operator_valid=True
            self.__operator=self.__makeNewOperator()  
            if self.debug() : print "PDE Debug: New operator allocated"  
        else:  
            self.__operator.setValue(0.)  
            if self.debug() : print "PDE Debug: Operator reset to zero"  
        return self.__operator  
1916    
1917     def __getFreshRightHandSide(self):     def invalidateOperator(self):
1918         """         """
1919         @brief         Indicates the operator has to be rebuilt next time it is used.
1920         """         """
1921         if self.__righthandside.isEmpty():         self.trace("Operator will be rebuilt.")
1922             self.__righthandside=self.__makeNewRightHandSide()         self.invalidateSolution()
1923             if self.debug() : print "PDE Debug: New right hand side allocated"         self.__is_operator_valid=False
        else:  
            print "fix self.__righthandside*=0"  
            self.__righthandside*=0.  
            if self.debug() : print "PDE Debug: Right hand side reset to zero"  
        return  self.__righthandside  
1924    
1925     # ==== rebuild switches =====================================================================     def isOperatorValid(self):
    def __rebuildSolution(self,deep=False):  
1926         """         """
1927         @brief indicates the PDE has to be reolved if the solution is requested         Returns True if the operator is still valid.
1928         """         """
1929         if self.__solution_isValid and self.debug() : print "PDE Debug: PDE has to be resolved."         if not self.getDomainStatus()==self.getSystemStatus(): self.invalidateOperator()
1930         self.__solution_isValid=False         if not self.getRequiredOperatorType()==self.getOperatorType(): self.invalidateOperator()
1931         if deep: self.__solution=escript.Data(deep)         return self.__is_operator_valid
1932    
1933       def validRightHandSide(self):
1934           """
1935           Marks the right hand side as valid.
1936           """
1937           self.__is_RHS_valid=True
1938    
1939     def __rebuildOperator(self,deep=False):     def invalidateRightHandSide(self):
1940         """         """
1941         @brief indicates the operator has to be rebuilt next time it is used         Indicates the right hand side has to be rebuilt next time it is used.
1942         """         """
1943         if self.__operator_isValid and self.debug() : print "PDE Debug: Operator has to be rebuilt."         self.trace("Right hand side has to be rebuilt.")
1944         self.__rebuildSolution(deep)         self.invalidateSolution()
1945         self.__operator_isValid=False         self.__is_RHS_valid=False
        if deep: self.__operator=escript.Operator()  
1946    
1947     def __rebuildRightHandSide(self,deep=False):     def isRightHandSideValid(self):
1948         """         """
1949         @brief indicates the right hand side has to be rebuild next time it is used         Returns True if the operator is still valid.
1950         """         """
1951         if self.__righthandside_isValid and self.debug() : print "PDE Debug: Right hand side has to be rebuilt."         if not self.getDomainStatus()==self.getSystemStatus(): self.invalidateRightHandSide()
1952         self.__rebuildSolution(deep)         return self.__is_RHS_valid
        self.__righthandside_isValid=False  
        if not self.__homogeneous_constraint: self.__rebuildOperator()  
        if deep: self.__righthandside=escript.Data()  
1953    
1954     def __rebuildSystem(self,deep=False):     def invalidateSystem(self):
1955         """         """
1956         @brief annonced that all coefficient name has been changed         Announces that everything has to be rebuilt.
1957         """         """
1958         self.__rebuildSolution(deep)         self.invalidateSolution()
1959         self.__rebuildOperator(deep)         self.invalidateOperator()
1960         self.__rebuildRightHandSide(deep)         self.invalidateRightHandSide()
1961      
1962     def __checkMatrixType(self):     def isSystemValid(self):
1963           """
1964           Returns True if the system (including solution) is still vaild.
1965           """
1966           return self.isSolutionValid() and self.isOperatorValid() and self.isRightHandSideValid()
1967    
1968       def initializeSystem(self):
1969           """
1970           Resets the system clearing the operator, right hand side and solution.
1971           """
1972           self.trace("New System has been created.")
1973           self.__operator_type=None
1974           self.setSystemStatus()
1975           self.__operator=escript.Operator()
1976           self.__righthandside=escript.Data()
1977           self.__solution=escript.Data()
1978           self.invalidateSystem()
1979    
1980       def getOperator(self):
1981       """       """
1982       @brief reassess the matrix type and, if needed, initiates an operator rebuild       Returns the operator of the linear problem.
1983    
1984         @return: the operator of the problem
1985       """       """
1986       new_matrix_type=self.getDomain().getSystemMatrixTypeId(self.getSolverMethod(),self.isSymmetric())       return self.getSystem()[0]
      if not new_matrix_type==self.__matrix_type:  
          if self.debug() : print "PDE Debug: Matrix type is now %d."%new_matrix_type  
          self.__matrix_type=new_matrix_type  
          self.__rebuildOperator(deep=True)  
1987    
1988     #============ assembling =======================================================     def getRightHandSide(self):
1989     def __copyConstraint(self,u):       """
1990        """       Returns the right hand side of the linear problem.
1991        @brief copies the constrint condition into u  
1992        """       @return: the right hand side of the problem
1993        q=self.getCoefficient("q")       @rtype: L{Data<escript.Data>}
1994        r=self.getCoefficient("r")       """
1995        if not q.isEmpty():       return self.getSystem()[1]
           if r.isEmpty():  
              r2=escript.Data(0,u.getShape(),u.getFunctionSpace())  
           else:  
              r2=escript.Data(r,u.getFunctionSpace())  
           u.copyWithMask(r2,escript.Data(q,u.getFunctionSpace()))  
1996    
1997     def __applyConstraint(self,rhs_update=True):     def createRightHandSide(self):
1998         """         """
1999         @brief applies the constraints  defined by q and r to the system         Returns an instance of a new right hand side.
2000         """         """
2001         q=self.getCoefficient("q")         self.trace("New right hand side is allocated.")
2002         r=self.getCoefficient("r")         if self.getNumEquations()>1:
2003         if not q.isEmpty() and not self.__operator.isEmpty():             return escript.Data(0.,(self.getNumEquations(),),self.getFunctionSpaceForEquation(),True)
2004            # q is the row and column mask to indicate where constraints are set:         else:
2005            row_q=escript.Data(q,self.getFunctionSpaceForEquation())             return escript.Data(0.,(),self.getFunctionSpaceForEquation(),True)
           col_q=escript.Data(q,self.getFunctionSpaceForSolution())  
           u=self.__makeNewSolution()  
           if r.isEmpty():  
              r_s=self.__makeNewSolution()  
           else:  
              r_s=escript.Data(r,self.getFunctionSpaceForSolution())  
           u.copyWithMask(r_s,col_q)  
           if not self.__righthandside.isEmpty() and rhs_update: self.__righthandside-=self.__operator*u  
           self.__operator.nullifyRowsAndCols(row_q,col_q,1.)  
2006    
2007     def getOperator(self):     def createSolution(self):
2008           """
2009           Returns an instance of a new solution.
2010           """
2011           self.trace("New solution is allocated.")
2012           if self.getNumSolutions()>1:
2013               return escript.Data(0.,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True)
2014           else:
2015               return escript.Data(0.,(),self.getFunctionSpaceForSolution(),True)
2016    
2017       def resetSolution(self):
2018           """
2019           Sets the solution to zero.
2020           """
2021           if self.__solution.isEmpty():
2022               self.__solution=self.createSolution()
2023           else:
2024               self.__solution.setToZero()
2025               self.trace("Solution is reset to zero.")
2026    
2027       def setSolution(self,u):
2028           """
2029           Sets the solution assuming that makes the system valid with the tolrance
2030           defined by the solver options
2031           """
2032           self.__solution_rtol=self.getSolverOptions().getTolerance()
2033           self.__solution_atol=self.getSolverOptions().getAbsoluteTolerance()
2034           self.__solution=u
2035           self.validSolution()
2036    
2037       def getCurrentSolution(self):
2038           """
2039           Returns the solution in its current state.
2040           """
2041           if self.__solution.isEmpty(): self.__solution=self.createSolution()
2042           return self.__solution
2043    
2044       def resetRightHandSide(self):
2045           """
2046           Sets the right hand side to zero.
2047           """
2048           if self.__righthandside.isEmpty():
2049               self.__righthandside=self.createRightHandSide()
2050           else:
2051               self.__righthandside.setToZero()
2052               self.trace("Right hand side is reset to zero.")
2053    
2054       def getCurrentRightHandSide(self):
2055           """
2056           Returns the right hand side in its current state.
2057           """
2058           if self.__righthandside.isEmpty(): self.__righthandside=self.createRightHandSide()
2059           return self.__righthandside
2060    
2061       def resetOperator(self):
2062         """         """
2063         @brief returns the operator of the PDE         Makes sure that the operator is instantiated and returns it initialized
2064           with zeros.
2065         """         """
2066         if not self.__operator_isValid:         if self.getOperatorType() == None:
            # some Constraints are applying for a lumpled stifness matrix:  
2067             if self.isUsingLumping():             if self.isUsingLumping():
2068                if self.getFunctionSpaceForEquation()==self.getFunctionSpaceForSolution():                 self.__operator=self.createSolution()
                        raise TypeError,"Lumped matrix requires same order for equations and unknowns"  
               if not self.getCoefficient("A").isEmpty():  
                        raise Warning,"Lumped matrix does not allow coefficient A"  
               if not self.getCoefficient("B").isEmpty():  
                        raise Warning,"Lumped matrix does not allow coefficient B"  
               if not self.getCoefficient("C").isEmpty():  
                        raise Warning,"Lumped matrix does not allow coefficient C"  
               if not self.getCoefficient("D").isEmpty():  
                        raise Warning,"Lumped matrix does not allow coefficient D"  
               if self.debug() : print "PDE Debug: New lumped operator is built."  
               mat=self.__makeNewOperator(self)  
2069             else:             else:
2070                if self.debug() : print "PDE Debug: New operator is built."                 self.__operator=self.createOperator()
2071                mat=self.__getFreshOperator()         self.__operator_type=self.getRequiredOperatorType()
2072           else:
            self.getDomain().addPDEToSystem(mat,escript.Data(), \  
                         self.getCoefficient("A"), \  
                         self.getCoefficient("B"), \  
                         self.getCoefficient("C"), \  
                         self.getCoefficient("D"), \  
                         escript.Data(), \  
                         escript.Data(), \  
                         self.getCoefficient("d"), \  
                         escript.Data(),\  
                         self.getCoefficient("d_contact"), \  
                         escript.Data())  
2073             if self.isUsingLumping():             if self.isUsingLumping():
2074                self.__operator=mat*escript.Data(1,(self.getNumSolutions(),),self.getFunctionSpaceOfSolution(),True)                 self.__operator.setToZero()
2075             else:             else:
2076                self.__applyConstraint(rhs_update=False)                 if self.getOperatorType() == self.getRequiredOperatorType():
2077             self.__operator_isValid=True                     self.__operator.resetValues()
2078                   else:
2079                       self.__operator=self.createOperator()
2080                   self.__operator_type=self.getRequiredOperatorType()
2081               self.trace("Operator reset to zero")
2082    
2083       def getCurrentOperator(self):
2084           """
2085           Returns the operator in its current state.
2086           """
2087         return self.__operator         return self.__operator
2088    
2089     def getRightHandSide(self,ignoreConstraint=False):     def setValue(self,**coefficients):
2090          """
2091          Sets new values to coefficients.
2092    
2093          @raise IllegalCoefficient: if an unknown coefficient keyword is used
2094          """
2095          # check if the coefficients are  legal:
2096          for i in coefficients.iterkeys():
2097             if not self.hasCoefficient(i):
2098                raise IllegalCoefficient,"Attempt to set unknown coefficient %s"%i
2099          # if the number of unknowns or equations is still unknown we try to estimate them:
2100          if self.__numEquations==None or self.__numSolutions==None:
2101             for i,d in coefficients.iteritems():
2102                if hasattr(d,"shape"):
2103                    s=d.shape
2104                elif hasattr(d,"getShape"):
2105                    s=d.getShape()
2106                else:
2107                    s=numpy.array(d).shape
2108                if s!=None:
2109                    # get number of equations and number of unknowns:
2110                    res=self.__COEFFICIENTS[i].estimateNumEquationsAndNumSolutions(self.getDomain(),s)
2111                    if res==None:
2112                        raise IllegalCoefficientValue,"Illegal shape %s of coefficient %s"%(s,i)
2113                    else:
2114                        if self.__numEquations==None: self.__numEquations=res[0]
2115                        if self.__numSolutions==None: self.__numSolutions=res[1]
2116          if self.__numEquations==None: raise UndefinedPDEError,"unidentified number of equations"
2117          if self.__numSolutions==None: raise UndefinedPDEError,"unidentified number of solutions"
2118          # now we check the shape of the coefficient if numEquations and numSolutions are set:
2119          for i,d in coefficients.iteritems():
2120            try:
2121               self.__COEFFICIENTS[i].setValue(self.getDomain(),
2122                         self.getNumEquations(),self.getNumSolutions(),
2123                         self.reduceEquationOrder(),self.reduceSolutionOrder(),d)
2124               self.alteredCoefficient(i)
2125            except IllegalCoefficientFunctionSpace,m:
2126                # if the function space is wrong then we try the reduced version:
2127                i_red=i+"_reduced"
2128                if (not i_red in coefficients.keys()) and i_red in self.__COEFFICIENTS.keys():
2129                    try:
2130                        self.__COEFFICIENTS[i_red].setValue(self.getDomain(),
2131                                                          self.getNumEquations(),self.getNumSolutions(),
2132                                                          self.reduceEquationOrder(),self.reduceSolutionOrder(),d)
2133                        self.alteredCoefficient(i_red)
2134                    except IllegalCoefficientValue,m:
2135                        raise IllegalCoefficientValue("Coefficient %s:%s"%(i,m))
2136                    except IllegalCoefficientFunctionSpace,m:
2137                        raise IllegalCoefficientFunctionSpace("Coefficient %s:%s"%(i,m))
2138                else:
2139                    raise IllegalCoefficientFunctionSpace("Coefficient %s:%s"%(i,m))
2140            except IllegalCoefficientValue,m:
2141               raise IllegalCoefficientValue("Coefficient %s:%s"%(i,m))
2142          self.__altered_coefficients=True
2143    
2144       # ==========================================================================
2145       # methods that are typically overwritten when implementing a particular
2146       # linear problem
2147       # ==========================================================================
2148       def getRequiredOperatorType(self):
2149          """
2150          Returns the system type which needs to be used by the current set up.
2151    
2152          @note: Typically this method is overwritten when implementing a
2153                 particular linear problem.
2154          """
2155          return None
2156    
2157       def createOperator(self):
2158         """         """
2159         @brief returns the right hand side of the PDE         Returns an instance of a new operator.
2160    
2161         @param ignoreConstraint         @note: This method is overwritten when implementing a particular
2162                  linear problem.
2163         """         """
2164         if not self.__righthandside_isValid:         return escript.Operator()
2165             if self.debug() : print "PDE Debug: New right hand side is built."  
2166             self.getDomain().addPDEToRHS(self.__getFreshRightHandSide(), \     def checkSymmetry(self,verbose=True):
2167                           self.getCoefficient("X"), \        """
2168                           self.getCoefficient("Y"),\        Tests the PDE for symmetry.
2169                           self.getCoefficient("y"),\  
2170                           self.getCoefficient("y_contact"))        @param verbose: if set to True or not present a report on coefficients
2171             self.__righthandside_isValid=True                        which break the symmetry is printed
2172             if ignoreConstraint: self.__copyConstraint(self.__righthandside)        @type verbose: C{bool}
2173         return self.__righthandside        @return: True if the problem is symmetric
2174          @rtype: C{bool}
2175          @note: Typically this method is overwritten when implementing a
2176                 particular linear problem.
2177          """
2178          out=True
2179          return out
2180    
2181       def getSolution(self,**options):
2182           """
2183           Returns the solution of the problem.
2184    
2185           @return: the solution
2186           @rtype: L{Data<escript.Data>}
2187    
2188           @note: This method is overwritten when implementing a particular
2189                  linear problem.
2190           """
2191           return self.getCurrentSolution()
2192    
2193       def getSystem(self):
2194           """
2195           Returns the operator and right hand side of the PDE.
2196    
2197           @return: the discrete version of the PDE
2198           @rtype: C{tuple} of L{Operator,<escript.Operator>} and L{Data<escript.Data>}.
2199    
2200           @note: This method is overwritten when implementing a particular
2201                  linear problem.
2202           """
2203           return (self.getCurrentOperator(), self.getCurrentRightHandSide())
2204    
2205    class LinearPDE(LinearProblem):
2206       """
2207       This class is used to define a general linear, steady, second order PDE
2208       for an unknown function M{u} on a given domain defined through a
2209       L{Domain<escript.Domain>} object.
2210    
2211       For a single PDE having a solution with a single component the linear PDE
2212       is defined in the following form:
2213    
2214       M{-(grad(A[j,l]+A_reduced[j,l])*grad(u)[l]+(B[j]+B_reduced[j])u)[j]+(C[l]+C_reduced[l])*grad(u)[l]+(D+D_reduced)=-grad(X+X_reduced)[j,j]+(Y+Y_reduced)}
2215    
2216       where M{grad(F)} denotes the spatial derivative of M{F}. Einstein's
2217       summation convention, ie. summation over indexes appearing twice in a term
2218       of a sum performed, is used.
2219       The coefficients M{A}, M{B}, M{C}, M{D}, M{X} and M{Y} have to be specified
2220       through L{Data<escript.Data>} objects in L{Function<escript.Function>} and
2221       the coefficients M{A_reduced}, M{B_reduced}, M{C_reduced}, M{D_reduced},
2222       M{X_reduced} and M{Y_reduced} have to be specified through
2223       L{Data<escript.Data>} objects in L{ReducedFunction<escript.ReducedFunction>}.
2224       It is also allowed to use objects that can be converted into such
2225       L{Data<escript.Data>} objects. M{A} and M{A_reduced} are rank two, M{B},
2226       M{C}, M{X}, M{B_reduced}, M{C_reduced} and M{X_reduced} are rank one and
2227       M{D}, M{D_reduced}, M{Y} and M{Y_reduced} are scalar.
2228    
2229       The following natural boundary conditions are considered:
2230    
2231       M{n[j]*((A[i,j]+A_reduced[i,j])*grad(u)[l]+(B+B_reduced)[j]*u)+(d+d_reduced)*u=n[j]*(X[j]+X_reduced[j])+y}
2232    
2233       where M{n} is the outer normal field. Notice that the coefficients M{A},
2234       M{A_reduced}, M{B}, M{B_reduced}, M{X} and M{X_reduced} are defined in the
2235       PDE. The coefficients M{d} and M{y} are each a scalar in
2236       L{FunctionOnBoundary<escript.FunctionOnBoundary>} and the coefficients
2237       M{d_reduced} and M{y_reduced} are each a scalar in
2238       L{ReducedFunctionOnBoundary<escript.ReducedFunctionOnBoundary>}.
2239    
2240       Constraints for the solution prescribe the value of the solution at certain
2241       locations in the domain. They have the form
2242    
2243       M{u=r} where M{q>0}
2244    
2245       M{r} and M{q} are each scalar where M{q} is the characteristic function
2246       defining where the constraint is applied. The constraints override any
2247       other condition set by the PDE or the boundary condition.
2248    
2249       The PDE is symmetrical if
2250    
2251       M{A[i,j]=A[j,i]}  and M{B[j]=C[j]} and M{A_reduced[i,j]=A_reduced[j,i]}
2252       and M{B_reduced[j]=C_reduced[j]}
2253    
2254       For a system of PDEs and a solution with several components the PDE has the
2255       form
2256    
2257       M{-grad((A[i,j,k,l]+A_reduced[i,j,k,l])*grad(u[k])[l]+(B[i,j,k]+B_reduced[i,j,k])*u[k])[j]+(C[i,k,l]+C_reduced[i,k,l])*grad(u[k])[l]+(D[i,k]+D_reduced[i,k]*u[k] =-grad(X[i,j]+X_reduced[i,j])[j]+Y[i]+Y_reduced[i] }
2258    
2259       M{A} and M{A_reduced} are of rank four, M{B}, M{B_reduced}, M{C} and
2260       M{C_reduced} are each of rank three, M{D}, M{D_reduced}, M{X_reduced} and
2261       M{X} are each of rank two and M{Y} and M{Y_reduced} are of rank one.
2262       The natural boundary conditions take the form:
2263    
2264       M{n[j]*((A[i,j,k,l]+A_reduced[i,j,k,l])*grad(u[k])[l]+(B[i,j,k]+B_reduced[i,j,k])*u[k])+(d[i,k]+d_reduced[i,k])*u[k]=n[j]*(X[i,j]+X_reduced[i,j])+y[i]+y_reduced[i]}
2265    
2266       The coefficient M{d} is of rank two and M{y} is of rank one both in
2267       L{FunctionOnBoundary<escript.FunctionOnBoundary>}. The coefficients
2268       M{d_reduced} is of rank two and M{y_reduced} is of rank one both in
2269       L{ReducedFunctionOnBoundary<escript.ReducedFunctionOnBoundary>}.
2270    
2271       Constraints take the form
2272    
2273       M{u[i]=r[i]}  where  M{q[i]>0}
2274    
2275       M{r} and M{q} are each rank one. Notice that at some locations not
2276       necessarily all components must have a constraint.
2277    
2278       The system of PDEs is symmetrical if
2279    
2280          - M{A[i,j,k,l]=A[k,l,i,j]}
2281          - M{A_reduced[i,j,k,l]=A_reduced[k,l,i,j]}
2282          - M{B[i,j,k]=C[k,i,j]}
2283          - M{B_reduced[i,j,k]=C_reduced[k,i,j]}
2284          - M{D[i,k]=D[i,k]}
2285          - M{D_reduced[i,k]=D_reduced[i,k]}
2286          - M{d[i,k]=d[k,i]}
2287          - M{d_reduced[i,k]=d_reduced[k,i]}
2288    
2289       L{LinearPDE} also supports solution discontinuities over a contact region
2290       in the domain. To specify the conditions across the discontinuity we are
2291       using the generalised flux M{J} which, in the case of a system of PDEs
2292       and several components of the solution, is defined as
2293    
2294       M{J[i,j]=(A[i,j,k,l]+A_reduced[[i,j,k,l])*grad(u[k])[l]+(B[i,j,k]+B_reduced[i,j,k])*u[k]-X[i,j]-X_reduced[i,j]}
2295    
2296       For the case of single solution component and single PDE M{J} is defined as
2297    
2298       M{J[j]=(A[i,j]+A_reduced[i,j])*grad(u)[j]+(B[i]+B_reduced[i])*u-X[i]-X_reduced[i]}
2299    
2300       In the context of discontinuities M{n} denotes the normal on the
2301       discontinuity pointing from side 0 towards side 1 calculated from
2302       L{getNormal<escript.FunctionSpace.getNormal>} of L{FunctionOnContactZero<escript.FunctionOnContactZero>}.
2303       For a system of PDEs the contact condition takes the form
2304    
2305       M{n[j]*J0[i,j]=n[j]*J1[i,j]=(y_contact[i]+y_contact_reduced[i])- (d_contact[i,k]+d_contact_reduced[i,k])*jump(u)[k]}
2306    
2307       where M{J0} and M{J1} are the fluxes on side 0 and side 1 of the
2308       discontinuity, respectively. M{jump(u)}, which is the difference of the
2309       solution at side 1 and at side 0, denotes the jump of M{u} across
2310       discontinuity along the normal calculated by L{jump<util.jump>}.
2311       The coefficient M{d_contact} is of rank two and M{y_contact} is of rank one
2312       both in L{FunctionOnContactZero<escript.FunctionOnContactZero>} or
2313       L{FunctionOnContactOne<escript.FunctionOnContactOne>}.
2314       The coefficient M{d_contact_reduced} is of rank two and M{y_contact_reduced}
2315       is of rank one both in L{ReducedFunctionOnContactZero<escript.ReducedFunctionOnContactZero>}
2316       or L{ReducedFunctionOnContactOne<escript.ReducedFunctionOnContactOne>}.
2317       In case of a single PDE and a single component solution the contact
2318       condition takes the form
2319    
2320       M{n[j]*J0_{j}=n[j]*J1_{j}=(y_contact+y_contact_reduced)-(d_contact+y_contact_reduced)*jump(u)}
2321    
2322       In this case the coefficient M{d_contact} and M{y_contact} are each scalar
2323       both in L{FunctionOnContactZero<escript.FunctionOnContactZero>} or
2324       L{FunctionOnContactOne<escript.FunctionOnContactOne>} and the coefficient
2325       M{d_contact_reduced} and M{y_contact_reduced} are each scalar both in
2326       L{ReducedFunctionOnContactZero<escript.ReducedFunctionOnContactZero>} or
2327       L{ReducedFunctionOnContactOne<escript.ReducedFunctionOnContactOne>}.
2328    
2329       Typical usage::
2330    
2331           p = LinearPDE(dom)
2332           p.setValue(A=kronecker(dom), D=1, Y=0.5)
2333           u = p.getSolution()
2334    
2335       """
2336    
2337       def __init__(self,domain,numEquations=None,numSolutions=None,debug=False):
2338         """
2339         Initializes a new linear PDE.
2340    
2341         @param domain: domain of the PDE
2342         @type domain: L{Domain<escript.Domain>}
2343         @param numEquations: number of equations. If C{None} the number of
2344                              equations is extracted from the PDE coefficients.
2345         @param numSolutions: number of solution components. If C{None} the number
2346                              of solution components is extracted from the PDE
2347                              coefficients.
2348         @param debug: if True debug information is printed
2349    
2350         """
2351         super(LinearPDE, self).__init__(domain,numEquations,numSolutions,debug)
2352         #
2353         #   the coefficients of the PDE:
2354         #
2355         self.introduceCoefficients(
2356           A=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,PDECoef.BY_DIM,PDECoef.BY_SOLUTION,PDECoef.BY_DIM),PDECoef.OPERATOR),
2357           B=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,PDECoef.BY_DIM,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2358           C=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION,PDECoef.BY_DIM),PDECoef.OPERATOR),
2359           D=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2360           X=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,PDECoef.BY_DIM),PDECoef.RIGHTHANDSIDE),
2361           Y=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2362           d=PDECoef(PDECoef.BOUNDARY,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2363           y=PDECoef(PDECoef.BOUNDARY,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2364           d_contact=PDECoef(PDECoef.CONTACT,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2365           y_contact=PDECoef(PDECoef.CONTACT,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2366           A_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_DIM,PDECoef.BY_SOLUTION,PDECoef.BY_DIM),PDECoef.OPERATOR),
2367           B_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_DIM,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2368           C_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION,PDECoef.BY_DIM),PDECoef.OPERATOR),
2369           D_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2370           X_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_DIM),PDECoef.RIGHTHANDSIDE),
2371           Y_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2372           d_reduced=PDECoef(PDECoef.BOUNDARY_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2373           y_reduced=PDECoef(PDECoef.BOUNDARY_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2374           d_contact_reduced=PDECoef(PDECoef.CONTACT_REDUCED,(PDECoef.BY_EQUATION,PDECoef.BY_SOLUTION),PDECoef.OPERATOR),
2375           y_contact_reduced=PDECoef(PDECoef.CONTACT_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2376           r=PDECoef(PDECoef.SOLUTION,(PDECoef.BY_SOLUTION,),PDECoef.RIGHTHANDSIDE),
2377           q=PDECoef(PDECoef.SOLUTION,(PDECoef.BY_SOLUTION,),PDECoef.BOTH) )
2378    
2379       def __str__(self):
2380         """
2381         Returns the string representation of the PDE.
2382    
2383         @return: a simple representation of the PDE
2384         @rtype: C{str}
2385         """
2386         return "<LinearPDE %d>"%id(self)
2387    
2388       def getRequiredOperatorType(self):
2389          """
2390          Returns the system type which needs to be used by the current set up.
2391          """
2392          solver_options=self.getSolverOptions()
2393          return self.getDomain().getSystemMatrixTypeId(solver_options.getSolverMethod(), solver_options.getPreconditioner(),solver_options.getPackage(), solver_options.isSymmetric())
2394    
2395       def checkSymmetry(self,verbose=True):
2396          """
2397          Tests the PDE for symmetry.
2398    
2399          @param verbose: if set to True or not present a report on coefficients
2400                          which break the symmetry is printed.
2401          @type verbose: C{bool}
2402          @return: True if the PDE is symmetric
2403          @rtype: L{bool}
2404          @note: This is a very expensive operation. It should be used for
2405                 degugging only! The symmetry flag is not altered.
2406          """
2407          out=True
2408          out=out and self.checkSymmetricTensor("A", verbose)
2409          out=out and self.checkSymmetricTensor("A_reduced", verbose)
2410          out=out and self.checkReciprocalSymmetry("B","C", verbose)
2411          out=out and self.checkReciprocalSymmetry("B_reduced","C_reduced", verbose)
2412          out=out and self.checkSymmetricTensor("D", verbose)
2413          out=out and self.checkSymmetricTensor("D_reduced", verbose)
2414          out=out and self.checkSymmetricTensor("d", verbose)
2415          out=out and self.checkSymmetricTensor("d_reduced", verbose)
2416          out=out and self.checkSymmetricTensor("d_contact", verbose)
2417          out=out and self.checkSymmetricTensor("d_contact_reduced", verbose)
2418          return out
2419    
2420       def createOperator(self):
2421           """
2422           Returns an instance of a new operator.
2423           """
2424           optype=self.getRequiredOperatorType()
2425           self.trace("New operator of type %s is allocated."%optype)
2426           return self.getDomain().newOperator( \
2427                               self.getNumEquations(), \
2428                               self.getFunctionSpaceForEquation(), \
2429                               self.getNumSolutions(), \
2430                               self.getFunctionSpaceForSolution(), \
2431                               optype)
2432    
2433       def getSolution(self):
2434           """
2435           Returns the solution of the PDE.
2436    
2437           @return: the solution
2438           @rtype: L{Data<escript.Data>}
2439           """
2440           option_class=self.getSolverOptions()
2441           if not self.isSolutionValid():
2442              mat,f=self.getSystem()
2443              if self.isUsingLumping():
2444                 self.setSolution(f*1/mat)
2445              else:
2446                 self.trace("PDE is resolved.")
2447                 self.trace("solver options: %s"%str(option_class))
2448                 self.setSolution(mat.solve(f,option_class))
2449           return self.getCurrentSolution()
2450    
2451     def getSystem(self):     def getSystem(self):
2452         """         """
2453         @brief         Returns the operator and right hand side of the PDE.
2454    
2455           @return: the discrete version of the PDE
2456           @rtype: C{tuple} of L{Operator,<escript.Operator>} and
2457                   L{Data<escript.Data>}
2458         """         """
2459         if not self.__operator_isValid and not self.__righthandside_isValid:         if not self.isOperatorValid() or not self.isRightHandSideValid():
           if self.debug() : print "PDE Debug: New PDE is built."  
2460            if self.isUsingLumping():            if self.isUsingLumping():
2461                self.getRightHandSide(ignoreConstraint=True)                if not self.isOperatorValid():
2462                self.getOperator()                   if not self.getFunctionSpaceForEquation()==self.getFunctionSpaceForSolution():
2463                          raise TypeError,"Lumped matrix requires same order for equations and unknowns"
2464                     if not self.getCoefficient("A").isEmpty():
2465                          raise ValueError,"coefficient A in lumped matrix may not be present."
2466                     if not self.getCoefficient("B").isEmpty():
2467                          raise ValueError,"coefficient B in lumped matrix may not be present."
2468                     if not self.getCoefficient("C").isEmpty():
2469                          raise ValueError,"coefficient C in lumped matrix may not be present."
2470                     if not self.getCoefficient("d_contact").isEmpty():
2471                          raise ValueError,"coefficient d_contact in lumped matrix may not be present."
2472                     if not self.getCoefficient("A_reduced").isEmpty():
2473                          raise ValueError,"coefficient A_reduced in lumped matrix may not be present."
2474                     if not self.getCoefficient("B_reduced").isEmpty():
2475                          raise ValueError,"coefficient B_reduced in lumped matrix may not be present."
2476                     if not self.getCoefficient("C_reduced").isEmpty():
2477                          raise ValueError,"coefficient C_reduced in lumped matrix may not be present."
2478                     if not self.getCoefficient("d_contact_reduced").isEmpty():
2479                          raise ValueError,"coefficient d_contact_reduced in lumped matrix may not be present."
2480                     D=self.getCoefficient("D")
2481                     d=self.getCoefficient("d")
2482                     D_reduced=self.getCoefficient("D_reduced")
2483                     d_reduced=self.getCoefficient("d_reduced")
2484                     if not D.isEmpty():
2485                         if self.getNumSolutions()>1:
2486                            D_times_e=util.matrix_mult(D,numpy.ones((self.getNumSolutions(),)))
2487                         else:
2488                            D_times_e=D
2489                     else:
2490                        D_times_e=escript.Data()
2491                     if not d.isEmpty():
2492                         if self.getNumSolutions()>1:
2493                            d_times_e=util.matrix_mult(d,numpy.ones((self.getNumSolutions(),)))
2494                         else:
2495                            d_times_e=d
2496                     else:
2497                        d_times_e=escript.Data()
2498    
2499                     if not D_reduced.isEmpty():
2500                         if self.getNumSolutions()>1:
2501                            D_reduced_times_e=util.matrix_mult(D_reduced,numpy.ones((self.getNumSolutions(),)))
2502                         else:
2503                            D_reduced_times_e=D_reduced
2504                     else:
2505                        D_reduced_times_e=escript.Data()
2506                     if not d_reduced.isEmpty():
2507                         if self.getNumSolutions()>1:
2508                            d_reduced_times_e=util.matrix_mult(d_reduced,numpy.ones((self.getNumSolutions(),)))
2509                         else:
2510                            d_reduced_times_e=d_reduced
2511                     else:
2512                        d_reduced_times_e=escript.Data()
2513    
2514                     self.resetOperator()
2515                     operator=self.getCurrentOperator()
2516                     if False and hasattr(self.getDomain(), "addPDEToLumpedSystem") :
2517                        self.getDomain().addPDEToLumpedSystem(operator, D_times_e, d_times_e)
2518                        self.getDomain().addPDEToLumpedSystem(operator, D_reduced_times_e, d_reduced_times_e)
2519                     else:
2520                        self.getDomain().addPDEToRHS(operator, \
2521                                                     escript.Data(), \
2522                                                     D_times_e, \
2523                                                     d_times_e,\
2524                                                     escript.Data())
2525                        self.getDomain().addPDEToRHS(operator, \
2526                                                     escript.Data(), \
2527                                                     D_reduced_times_e, \
2528                                                     d_reduced_times_e,\
2529                                                     escript.Data())
2530                     self.trace("New lumped operator has been built.")
2531                  if not self.isRightHandSideValid():
2532                     self.resetRightHandSide()
2533                     righthandside=self.getCurrentRightHandSide()
2534                     self.getDomain().addPDEToRHS(righthandside, \
2535                                   self.getCoefficient("X"), \
2536                                   self.getCoefficient("Y"),\
2537                                   self.getCoefficient("y"),\
2538                                   self.getCoefficient("y_contact"))
2539                     self.getDomain().addPDEToRHS(righthandside, \
2540                                   self.getCoefficient("X_reduced"), \
2541                                   self.getCoefficient("Y_reduced"),\
2542                                   self.getCoefficient("y_reduced"),\
2543                                   self.getCoefficient("y_contact_reduced"))
2544                     self.trace("New right hand side has been built.")
2545                     self.validRightHandSide()
2546                  self.insertConstraint(rhs_only=False)
2547                  self.validOperator()
2548            else:            else:
2549                self.getDomain().addPDEToSystem(self.__getFreshOperator(),self.__getFreshRightHandSide(), \               if not self.isOperatorValid() and not self.isRightHandSideValid():
2550                     self.resetRightHandSide()
2551                     righthandside=self.getCurrentRightHandSide()
2552                     self.resetOperator()
2553                     operator=self.getCurrentOperator()
2554                     self.getDomain().addPDEToSystem(operator,righthandside, \
2555                                   self.getCoefficient("A"), \
2556                                   self.getCoefficient("B"), \
2557                                   self.getCoefficient("C"), \
2558                                   self.getCoefficient("D"), \
2559                                   self.getCoefficient("X"), \
2560                                   self.getCoefficient("Y"), \
2561                                   self.getCoefficient("d"), \
2562                                   self.getCoefficient("y"), \
2563                                   self.getCoefficient("d_contact"), \
2564                                   self.getCoefficient("y_contact"))
2565                     self.getDomain().addPDEToSystem(operator,righthandside, \
2566                                   self.getCoefficient("A_reduced"), \
2567                                   self.getCoefficient("B_reduced"), \
2568                                   self.getCoefficient("C_reduced"), \
2569                                   self.getCoefficient("D_reduced"), \
2570                                   self.getCoefficient("X_reduced"), \
2571                                   self.getCoefficient("Y_reduced"), \
2572                                   self.getCoefficient("d_reduced"), \
2573                                   self.getCoefficient("y_reduced"), \
2574                                   self.getCoefficient("d_contact_reduced"), \
2575                                   self.getCoefficient("y_contact_reduced"))
2576                     self.insertConstraint(rhs_only=False)
2577                     self.trace("New system has been built.")
2578                     self.validOperator()
2579                     self.validRightHandSide()
2580                 elif not self.isRightHandSideValid():
2581                     self.resetRightHandSide()
2582                     righthandside=self.getCurrentRightHandSide()
2583                     self.getDomain().addPDEToRHS(righthandside,
2584                                   self.getCoefficient("X"), \
2585                                   self.getCoefficient("Y"),\
2586                                   self.getCoefficient("y"),\
2587                                   self.getCoefficient("y_contact"))
2588                     self.getDomain().addPDEToRHS(righthandside,
2589                                   self.getCoefficient("X_reduced"), \
2590                                   self.getCoefficient("Y_reduced"),\
2591                                   self.getCoefficient("y_reduced"),\
2592                                   self.getCoefficient("y_contact_reduced"))
2593                     self.insertConstraint(rhs_only=True)
2594                     self.trace("New right hand side has been built.")
2595                     self.validRightHandSide()
2596                 elif not self.isOperatorValid():
2597                     self.resetOperator()
2598                     operator=self.getCurrentOperator()
2599                     self.getDomain().addPDEToSystem(operator,escript.Data(), \
2600                              self.getCoefficient("A"), \                              self.getCoefficient("A"), \
2601                              self.getCoefficient("B"), \                              self.getCoefficient("B"), \
2602                              self.getCoefficient("C"), \                              self.getCoefficient("C"), \
2603                              self.getCoefficient("D"), \                              self.getCoefficient("D"), \
2604                              self.getCoefficient("X"), \                              escript.Data(), \
2605                              self.getCoefficient("Y"), \                              escript.Data(), \
2606                              self.getCoefficient("d"), \                              self.getCoefficient("d"), \
2607                              self.getCoefficient("y"), \                              escript.Data(),\
2608                              self.getCoefficient("d_contact"), \                              self.getCoefficient("d_contact"), \
2609                              self.getCoefficient("y_contact"))                              escript.Data())
2610            self.__operator_isValid=True                   self.getDomain().addPDEToSystem(operator,escript.Data(), \
2611            self.__righthandside_isValid=True                              self.getCoefficient("A_reduced"), \
2612            self.__applyConstraint()                              self.getCoefficient("B_reduced"), \
2613            self.__copyConstraint(self.__righthandside)                              self.getCoefficient("C_reduced"), \
2614         elif not self.__operator_isValid:                              self.getCoefficient("D_reduced"), \
2615            self.getOperator()                              escript.Data(), \
2616         elif not self.__righthandside_isValid:                              escript.Data(), \
2617            self.getRightHandSide()                              self.getCoefficient("d_reduced"), \
2618         return (self.__operator,self.__righthandside)                              escript.Data(),\
2619                                self.getCoefficient("d_contact_reduced"), \
2620     def solve(self,**options):                              escript.Data())
2621        """                   self.insertConstraint(rhs_only=False)
2622        @brief solve the PDE                   self.trace("New operator has been built.")
2623                     self.validOperator()
2624        @param options         self.setSystemStatus()
2625        """         self.trace("System status is %s."%self.getSystemStatus())
2626        mat,f=self.getSystem()         return (self.getCurrentOperator(), self.getCurrentRightHandSide())
2627        if self.isUsingLumping():  
2628           out=f/mat     def insertConstraint(self, rhs_only=False):
2629           self.__copyConstraint(out)        """
2630        else:        Applies the constraints defined by q and r to the PDE.
2631           options[util.TOLERANCE_KEY]=self.getTolerance()  
2632           options[util.METHOD_KEY]=self.getSolverMethod()        @param rhs_only: if True only the right hand side is altered by the
2633           options[util.SYMMETRY_KEY]=self.isSymmetric()                         constraint
2634           if self.debug() : print "PDE Debug: solver options: ",options        @type rhs_only: C{bool}
2635           out=mat.solve(f,options)        """
2636        return out        q=self.getCoefficient("q")
2637          r=self.getCoefficient("r")
2638          righthandside=self.getCurrentRightHandSide()
2639          operator=self.getCurrentOperator()
2640    
2641     def getSolution(self,**options):        if not q.isEmpty():
2642         """           if r.isEmpty():
2643         @brief returns the solution of the PDE              r_s=self.createSolution()
2644             else:
2645                r_s=r
2646             if not rhs_only and not operator.isEmpty():
2647                 if self.isUsingLumping():
2648                     operator.copyWithMask(escript.Data(1.,q.getShape(),q.getFunctionSpace()),q)
2649                 else:
2650                     row_q=escript.Data(q,self.getFunctionSpaceForEquation())
2651                     col_q=escript.Data(q,self.getFunctionSpaceForSolution())
2652                     u=self.createSolution()
2653                     u.copyWithMask(r_s,col_q)
2654                     righthandside-=operator*u
2655                     operator.nullifyRowsAndCols(row_q,col_q,1.)
2656             righthandside.copyWithMask(r_s,q)
2657    
2658         @param options     def setValue(self,**coefficients):
2659         """        """
2660         if not self.__solution_isValid:        Sets new values to coefficients.
2661             if self.debug() : print "PDE Debug: PDE is resolved."  
2662             self.__solution=self.solve(**options)        @param coefficients: new values assigned to coefficients
2663             self.__solution_isValid=True        @keyword A: value for coefficient C{A}
2664         return self.__solution        @type A: any type that can be cast to a L{Data<escript.Data>} object on
2665     #============ some serivice functions  =====================================================                 L{Function<escript.Function>}
2666     def getDomain(self):        @keyword A_reduced: value for coefficient C{A_reduced}
2667          @type A_reduced: any type that can be cast to a L{Data<escript.Data>}
2668                           object on L{ReducedFunction<escript.ReducedFunction>}
2669          @keyword B: value for coefficient C{B}
2670          @type B: any type that can be cast to a L{Data<escript.Data>} object on
2671                   L{Function<escript.Function>}
2672          @keyword B_reduced: value for coefficient C{B_reduced}
2673          @type B_reduced: any type that can be cast to a L{Data<escript.Data>}
2674                           object on L{ReducedFunction<escript.ReducedFunction>}
2675          @keyword C: value for coefficient C{C}
2676          @type C: any type that can be cast to a L{Data<escript.Data>} object on
2677                   L{Function<escript.Function>}
2678          @keyword C_reduced: value for coefficient C{C_reduced}
2679          @type C_reduced: any type that can be cast to a L{Data<escript.Data>}
2680                           object on L{ReducedFunction<escript.ReducedFunction>}
2681          @keyword D: value for coefficient C{D}
2682          @type D: any type that can be cast to a L{Data<escript.Data>} object on
2683                   L{Function<escript.Function>}
2684          @keyword D_reduced: value for coefficient C{D_reduced}
2685          @type D_reduced: any type that can be cast to a L{Data<escript.Data>}
2686                           object on L{ReducedFunction<escript.ReducedFunction>}
2687          @keyword X: value for coefficient C{X}
2688          @type X: any type that can be cast to a L{Data<escript.Data>} object on
2689                   L{Function<escript.Function>}
2690          @keyword X_reduced: value for coefficient C{X_reduced}
2691          @type X_reduced: any type that can be cast to a L{Data<escript.Data>}
2692                           object on L{ReducedFunction<escript.ReducedFunction>}
2693          @keyword Y: value for coefficient C{Y}
2694          @type Y: any type that can be cast to a L{Data<escript.Data>} object on
2695                   L{Function<escript.Function>}
2696          @keyword Y_reduced: value for coefficient C{Y_reduced}
2697          @type Y_reduced: any type that can be cast to a L{Data<escript.Data>}
2698                           object on L{ReducedFunction<escript.Function>}
2699          @keyword d: value for coefficient C{d}
2700          @type d: any type that can be cast to a L{Data<escript.Data>} object on
2701                   L{FunctionOnBoundary<escript.FunctionOnBoundary>}
2702          @keyword d_reduced: value for coefficient C{d_reduced}
2703          @type d_reduced: any type that can be cast to a L{Data<escript.Data>}
2704                           object on L{ReducedFunctionOnBoundary<escript.ReducedFunctionOnBoundary>}
2705          @keyword y: value for coefficient C{y}
2706          @type y: any type that can be cast to a L{Data<escript.Data>} object on
2707                   L{FunctionOnBoundary<escript.FunctionOnBoundary>}
2708          @keyword d_contact: value for coefficient C{d_contact}
2709          @type d_contact: any type that can be cast to a L{Data<escript.Data>}
2710                           object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}
2711                           or L{FunctionOnContactZero<escript.FunctionOnContactZero>}
2712          @keyword d_contact_reduced: value for coefficient C{d_contact_reduced}
2713          @type d_contact_reduced: any type that can be cast to a L{Data<escript.Data>}
2714                                   object on L{ReducedFunctionOnContactOne<escript.ReducedFunctionOnContactOne>}
2715                                   or L{ReducedFunctionOnContactZero<escript.ReducedFunctionOnContactZero>}
2716          @keyword y_contact: value for coefficient C{y_contact}
2717          @type y_contact: any type that can be cast to a L{Data<escript.Data>}
2718                           object on L{FunctionOnContactOne<escript.FunctionOnContactOne>}
2719                           or L{FunctionOnContactZero<escript.FunctionOnContactZero>}
2720          @keyword y_contact_reduced: value for coefficient C{y_contact_reduced}
2721          @type y_contact_reduced: any type that can be cast to a L{Data<escript.Data>}
2722                                   object on L{ReducedFunctionOnContactOne<escript.FunctionOnContactOne>}
2723                                   or L{ReducedFunctionOnContactZero<escript.FunctionOnContactZero>}
2724          @keyword r: values prescribed to the solution at the locations of
2725                      constraints
2726          @type r: any type that can be cast to a L{Data<escript.Data>} object on
2727                   L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
2728                   depending on whether reduced order is used for the solution
2729          @keyword q: mask for location of constraints
2730          @type q: any type that can be cast to a L{Data<escript.Data>} object on
2731                   L{Solution<escript.Solution>} or L{ReducedSolution<escript.ReducedSolution>}
2732                   depending on whether reduced order is used for the
2733                   representation of the equation
2734          @raise IllegalCoefficient: if an unknown coefficient keyword is used
2735          """
2736          super(LinearPDE,self).setValue(**coefficients)
2737          # check if the systrem is inhomogeneous:
2738          if len(coefficients)>0 and not self.isUsingLumping():
2739             q=self.getCoefficient("q")
2740             r=self.getCoefficient("r")
2741             if not q.isEmpty() and not r.isEmpty():
2742                 if util.Lsup(q*r)>0.:
2743                   self.trace("Inhomogeneous constraint detected.")
2744                   self.invalidateSystem()
2745    
2746    
2747       def getResidual(self,u=None):
2748         """
2749         Returns the residual of u or the current solution if u is not present.
2750    
2751         @param u: argument in the residual calculation. It must be representable
2752                   in L{self.getFunctionSpaceForSolution()}. If u is not present
2753                   or equals C{None} the current solution is used.
2754         @type u: L{Data<escript.Data>} or None
2755         @return: residual of u
2756         @rtype: L{Data<escript.Data>}
2757       """       """
2758       @brief returns the domain of the PDE       if u==None:
2759            return self.getOperator()*self.getSolution()-self.getRightHandSide()
2760         else:
2761            return self.getOperator()*escript.Data(u,self.getFunctionSpaceForSolution())-self.getRightHandSide()
2762    
2763       def getFlux(self,u=None):
2764       """       """
2765       return self.__domain       Returns the flux M{J} for a given M{u}.
2766    
2767     def getDim(self):       M{J[i,j]=(A[i,j,k,l]+A_reduced[A[i,j,k,l]]*grad(u[k])[l]+(B[i,j,k]+B_reduced[i,j,k])u[k]-X[i,j]-X_reduced[i,j]}
2768    
2769         or
2770    
2771         M{J[j]=(A[i,j]+A_reduced[i,j])*grad(u)[l]+(B[j]+B_reduced[j])u-X[j]-X_reduced[j]}
2772    
2773         @param u: argument in the flux. If u is not present or equals L{None} the
2774                   current solution is used.
2775         @type u: L{Data<escript.Data>} or None
2776         @return: flux
2777         @rtype: L{Data<escript.Data>}
2778       """       """
2779       @brief returns the spatial dimension of the PDE       if u==None: u=self.getSolution()
2780         return util.tensormult(self.getCoefficient("A"),util.grad(u,Funtion(self.getDomain))) \
2781               +util.matrixmult(self.getCoefficient("B"),u) \
2782               -util.self.getCoefficient("X") \
2783               +util.tensormult(self.getCoefficient("A_reduced"),util.grad(u,ReducedFuntion(self.getDomain))) \
2784               +util.matrixmult(self.getCoefficient("B_reduced"),u) \
2785               -util.self.getCoefficient("X_reduced")
2786    
2787    
2788    class Poisson(LinearPDE):
2789       """
2790       Class to define a Poisson equation problem. This is generally a
2791       L{LinearPDE} of the form
2792    
2793       M{-grad(grad(u)[j])[j] = f}
2794    
2795       with natural boundary conditions
2796    
2797       M{n[j]*grad(u)[j] = 0 }
2798    
2799       and constraints:
2800    
2801       M{u=0} where M{q>0}
2802    
2803       """
2804    
2805       def __init__(self,domain,debug=False):
2806       """       """
2807       return self.getDomain().getDim()       Initializes a new Poisson equation.
2808    
2809     def getNumEquations(self):       @param domain: domain of the PDE
2810         @type domain: L{Domain<escript.Domain>}
2811         @param debug: if True debug information is printed
2812    
2813         """
2814         super(Poisson, self).__init__(domain,1,1,debug)
2815         self.introduceCoefficients(
2816                            f=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2817                            f_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE))
2818         self.setSymmetryOn()
2819    
2820       def setValue(self,**coefficients):
2821         """
2822         Sets new values to coefficients.
2823    
2824         @param coefficients: new values assigned to coefficients
2825         @keyword f: value for right hand side M{f}
2826         @type f: any type that can be cast to a L{Scalar<escript.Scalar>} object
2827                  on L{Function<escript.Function>}
2828         @keyword q: mask for location of constraints
2829         @type q: any type that can be cast to a rank zero L{Data<escript.Data>}
2830                  object on L{Solution<escript.Solution>} or
2831                  L{ReducedSolution<escript.ReducedSolution>} depending on whether
2832                  reduced order is used for the representation of the equation
2833         @raise IllegalCoefficient: if an unknown coefficient keyword is used
2834       """       """
2835       @brief returns the number of equations       super(Poisson, self).setValue(**coefficients)
2836    
2837    
2838       def getCoefficient(self,name):
2839       """       """
2840       if self.__numEquations>0:       Returns the value of the coefficient C{name} of the general PDE.
2841           return self.__numEquations  
2842         @param name: name of the coefficient requested
2843         @type name: C{string}
2844         @return: the value of the coefficient C{name}
2845         @rtype: L{Data<escript.Data>}
2846         @raise IllegalCoefficient: invalid coefficient name
2847         @note: This method is called by the assembling routine to map the Poisson
2848                equation onto the general PDE.
2849         """
2850         if name == "A" :
2851             return escript.Data(util.kronecker(self.getDim()),escript.Function(self.getDomain()))
2852         elif name == "Y" :
2853             return self.getCoefficient("f")
2854         elif name == "Y_reduced" :
2855             return self.getCoefficient("f_reduced")
2856       else:       else:
2857           raise ValueError,"Number of equations is undefined. Please specify argument numEquations."           return super(Poisson, self).getCoefficient(name)
2858    
2859     def getNumSolutions(self):  class Helmholtz(LinearPDE):
2860       """
2861       Class to define a Helmholtz equation problem. This is generally a
2862       L{LinearPDE} of the form
2863    
2864       M{S{omega}*u - grad(k*grad(u)[j])[j] = f}
2865    
2866       with natural boundary conditions
2867    
2868       M{k*n[j]*grad(u)[j] = g- S{alpha}u }
2869    
2870       and constraints:
2871    
2872       M{u=r} where M{q>0}
2873    
2874       """
2875    
2876       def __init__(self,domain,debug=False):
2877       """       """
2878       @brief returns the number of unknowns       Initializes a new Helmholtz equation.
2879    
2880         @param domain: domain of the PDE
2881         @type domain: L{Domain<escript.Domain>}
2882         @param debug: if True debug information is printed
2883    
2884         """
2885         super(Helmholtz, self).__init__(domain,1,1,debug)
2886         self.introduceCoefficients(
2887                            omega=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,),PDECoef.OPERATOR),
2888                            k=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,),PDECoef.OPERATOR),
2889                            f=PDECoef(PDECoef.INTERIOR,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2890                            f_reduced=PDECoef(PDECoef.INTERIOR_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2891                            alpha=PDECoef(PDECoef.BOUNDARY,(PDECoef.BY_EQUATION,),PDECoef.OPERATOR),
2892                            g=PDECoef(PDECoef.BOUNDARY,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE),
2893                            g_reduced=PDECoef(PDECoef.BOUNDARY_REDUCED,(PDECoef.BY_EQUATION,),PDECoef.RIGHTHANDSIDE))
2894         self.setSymmetryOn()
2895    
2896       def setValue(self,**coefficients):
2897       """       """
2898       if self.__numSolutions>0:       Sets new values to coefficients.
2899          return self.__numSolutions  
2900         @param coefficients: new values assigned to coefficients
2901         @keyword omega: value for coefficient M{S{omega}}
2902         @type omega: any type that can be cast to a L{Scalar<escript.Scalar>}
2903                      object on L{Function<escript.Function>}
2904         @keyword k: value for coefficient M{k}
2905         @type k: any type that can be cast to a L{Scalar<escript.Scalar>} object
2906                  on L{Function<escript.Function>}
2907         @keyword f: value for right hand side M{f}
2908         @type f: any type that can be cast to a L{Scalar<escript.Scalar>} object
2909                  on L{Function<escript.Function>}
2910         @keyword alpha: value for right hand side M{S{alpha}}
2911         @type alpha: any type that can be cast to a L{Scalar<escript.Scalar>}
2912                      object on L{FunctionOnBoundary<escript.FunctionOnBoundary>}
2913         @keyword g: value for right hand side M{g}
2914         @type g: any type that can be cast to a L{Scalar<escript.Scalar>} object
2915                  on L{FunctionOnBoundary<escript.FunctionOnBoundary>}
2916         @keyword r: prescribed values M{r} for the solution in constraints
2917         @type r: any type that can be cast to a L{Scalar<escript.Scalar>} object
2918                  on L{Solution<escript.Solution>} or