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

Contents of /trunk/esys2/escript/py_src/linearPDEs.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 114 - (show annotations)
Fri Mar 4 07:12:37 2005 UTC (14 years, 9 months ago) by jgs
File MIME type: text/x-python
File size: 47740 byte(s)
Merge of development branch back to main trunk on 2005-03-04

1 # $Id$
2
3 ## @file linearPDEs.py
4
5 """
6 @brief Functions and classes for linear PDEs
7 """
8
9 import escript
10 import util
11 import numarray
12
13
14 def _CompTuple2(t1,t2):
15 """
16 @brief
17
18 @param t1
19 @param t2
20 """
21 dif=t1[0]+t1[1]-(t2[0]+t2[1])
22 if dif<0: return 1
23 elif dif>0: return -1
24 else: return 0
25
26 class PDECoefficient:
27 """
28 @brief
29 """
30 # identifier for location of Data objects defining COEFFICIENTS
31 INTERIOR=0
32 BOUNDARY=1
33 CONTACT=2
34 CONTINUOUS=3
35 # identifier in the pattern of COEFFICIENTS:
36 # the pattern is a tuple of EQUATION,SOLUTION,DIM where DIM represents the spatial dimension, EQUATION the number of equations and SOLUTION the
37 # number of unknowns.
38 EQUATION=3
39 SOLUTION=4
40 DIM=5
41 # indicator for what is altered if the coefficient is altered:
42 OPERATOR=5
43 RIGHTHANDSIDE=6
44 BOTH=7
45 def __init__(self,where,pattern,altering):
46 """
47 @brief Initialise a PDE Coefficient type
48 """
49 self.what=where
50 self.pattern=pattern
51 self.altering=altering
52 self.resetValue()
53
54 def resetValue(self):
55 """
56 @brief resets coefficient value to default
57 """
58 self.value=escript.Data()
59
60 def getFunctionSpace(self,domain):
61 """
62 @brief defines the FunctionSpace of the coefficient on the domain
63
64 @param domain
65 """
66 if self.what==self.INTERIOR: return escript.Function(domain)
67 elif self.what==self.BOUNDARY: return escript.FunctionOnBoundary(domain)
68 elif self.what==self.CONTACT: return escript.FunctionOnContactZero(domain)
69 elif self.what==self.CONTINUOUS: return escript.ContinuousFunction(domain)
70
71 def getValue(self):
72 """
73 @brief returns the value of the coefficient:
74 """
75 return self.value
76
77 def setValue(self,newValue):
78 """
79 @brief set the value of the coefficient to new value
80 """
81 self.value=newValue
82
83 def isAlteringOperator(self):
84 """
85 @brief return true if the operator of the PDE is changed when the coefficient is changed
86 """
87 if self.altering==self.OPERATOR or self.altering==self.BOTH:
88 return not None
89 else:
90 return None
91
92 def isAlteringRightHandSide(self):
93 """
94 @brief return true if the right hand side of the PDE is changed when the coefficient is changed
95 """
96 if self.altering==self.RIGHTHANDSIDE or self.altering==self.BOTH:
97 return not None
98 else:
99 return None
100
101 def estimateNumEquationsAndNumSolutions(self,shape=(),dim=3):
102 """
103 @brief tries to estimate the number of equations in a given tensor shape for a given spatial dimension dim
104
105 @param shape
106 @param dim
107 """
108 if len(shape)>0:
109 num=max(shape)+1
110 else:
111 num=1
112 search=[]
113 for u in range(num):
114 for e in range(num):
115 search.append((e,u))
116 search.sort(_CompTuple2)
117 for item in search:
118 s=self.buildShape(item[0],item[1],dim)
119 if len(s)==0 and len(shape)==0:
120 return (1,1)
121 else:
122 if s==shape: return item
123 return None
124
125 def buildShape(self,e=1,u=1,dim=3):
126 """
127 @brief builds the required shape for a given number of equations e, number of unknowns u and spatial dimension dim
128
129 @param e
130 @param u
131 @param dim
132 """
133 s=()
134 for i in self.pattern:
135 if i==self.EQUATION:
136 if e>1: s=s+(e,)
137 elif i==self.SOLUTION:
138 if u>1: s=s+(u,)
139 else:
140 s=s+(dim,)
141 return s
142
143 class LinearPDE:
144 """
145 @brief Class to handel a linear PDE
146
147 class to define a linear PDE of the form
148
149 -(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
150
151 with boundary conditons:
152
153 n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_{ik}u_k = - n_j*X_{ij} + y_i
154
155 and contact conditions
156
157 n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_contact_{ik}[u_k] = - n_j*X_{ij} + y_contact_i
158
159 and constraints:
160
161 u_i=r_i where q_i>0
162
163 """
164 TOL=1.e-13
165 DEFAULT_METHOD=util.DEFAULT_METHOD
166 DIRECT=util.DIRECT
167 CHOLEVSKY=util.CHOLEVSKY
168 PCG=util.PCG
169 CR=util.CR
170 CGS=util.CGS
171 BICGSTAB=util.BICGSTAB
172 SSOR=util.SSOR
173 GMRES=util.GMRES
174 PRES20=util.PRES20
175 ILU0=util.ILU0
176 JACOBI=util.JACOBI
177
178 def __init__(self,domain,numEquations=0,numSolutions=0):
179 """
180 @brief initializes a new linear PDE.
181
182 @param args
183 """
184 # COEFFICIENTS can be overwritten by subclasses:
185 self.COEFFICIENTS={
186 "A" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM,PDECoefficient.SOLUTION,PDECoefficient.DIM),PDECoefficient.OPERATOR),
187 "B" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),
188 "C" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION,PDECoefficient.DIM),PDECoefficient.OPERATOR),
189 "D" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),
190 "X" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,PDECoefficient.DIM),PDECoefficient.RIGHTHANDSIDE),
191 "Y" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),
192 "d" : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),
193 "y" : PDECoefficient(PDECoefficient.BOUNDARY,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),
194 "d_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.EQUATION,PDECoefficient.SOLUTION),PDECoefficient.OPERATOR),
195 "y_contact" : PDECoefficient(PDECoefficient.CONTACT,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),
196 "r" : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),
197 "q" : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.SOLUTION,),PDECoefficient.BOTH)}
198
199 # initialize attributes
200 self.__debug=None
201 self.__domain=domain
202 self.__numEquations=numEquations
203 self.__numSolutions=numSolutions
204 self.cleanCoefficients()
205
206 self.__operator=escript.Operator()
207 self.__operator_isValid=False
208 self.__righthandside=escript.Data()
209 self.__righthandside_isValid=False
210 self.__solution=escript.Data()
211 self.__solution_isValid=False
212
213 # set some default values:
214 self.__homogeneous_constraint=True
215 self.__row_function_space=escript.Solution(self.__domain)
216 self.__column_function_space=escript.Solution(self.__domain)
217 self.__tolerance=1.e-8
218 self.__solver_method=util.DEFAULT_METHOD
219 self.__matrix_type=self.__domain.getSystemMatrixTypeId(util.DEFAULT_METHOD,False)
220 self.__sym=False
221 self.__lumping=False
222
223 def createCoefficient(self, name):
224 """
225 @brief create a data object corresponding to coefficient name
226 @param name
227 """
228 return escript.Data(shape = getShapeOfCoefficient(name), \
229 what = getFunctionSpaceForCoefficient(name))
230
231 def __del__(self):
232 pass
233
234 def getCoefficient(self,name):
235 """
236 @brief return the value of the parameter name
237
238 @param name
239 """
240 return self.COEFFICIENTS[name].getValue()
241
242 def getCoefficientOfPDE(self,name):
243 """
244 @brief return the value of the coefficient name of the general PDE. This method is called by the assembling routine
245 it can be overwritten to map coefficients of a particualr PDE to the general PDE.
246 @param name
247 """
248 return self.getCoefficient(name)
249
250 def hasCoefficient(self,name):
251 """
252 @brief return true if name is the name of a coefficient
253
254 @param name
255 """
256 return self.COEFFICIENTS.has_key(name)
257
258 def getFunctionSpaceForEquation(self):
259 """
260 @brief return true if the test functions should use reduced order
261 """
262 return self.__row_function_space
263
264 def getFunctionSpaceForSolution(self):
265 """
266 @brief return true if the interpolation of the solution should use reduced order
267 """
268 return self.__column_function_space
269
270 def setValue(self,**coefficients):
271 """
272 @brief sets new values to coefficients
273
274 @param coefficients
275 """
276 self._setValue(**coefficients)
277
278
279 def cleanCoefficients(self):
280 """
281 @brief resets all coefficients to default values.
282 """
283 for i in self.COEFFICIENTS.iterkeys():
284 self.COEFFICIENTS[i].resetValue()
285
286 def createNewCoefficient(self,name):
287 """
288 @brief returns a new coefficient appropriate for coefficient name:
289 """
290 return escript.Data(0,self.getShapeOfCoefficient(name),self.getFunctionSpaceForCoefficient(name))
291
292
293 def getShapeOfCoefficient(self,name):
294 """
295 @brief return the shape of the coefficient name
296
297 @param name
298 """
299 if self.hasCoefficient(name):
300 return self.COEFFICIENTS[name].buildShape(self.getNumEquations(),self.getNumSolutions(),self.getDomain().getDim())
301 else:
302 raise ValueError,"Solution coefficient %s requested"%name
303
304 def getFunctionSpaceForCoefficient(self,name):
305 """
306 @brief return the atoms of the coefficient name
307
308 @param name
309 """
310 if self.hasCoefficient(name):
311 return self.COEFFICIENTS[name].getFunctionSpace(self.getDomain())
312 else:
313 raise ValueError,"Solution coefficient %s requested"%name
314
315 def alteredCoefficient(self,name):
316 """
317 @brief annonced that coefficient name has been changed
318
319 @param name
320 """
321 if self.hasCoefficient(name):
322 if self.COEFFICIENTS[name].isAlteringOperator(): self.__rebuildOperator()
323 if self.COEFFICIENTS[name].isAlteringRightHandSide(): self.__rebuildRightHandSide()
324 else:
325 raise ValueError,"unknown coefficient %s requested"%name
326
327 # ===== debug ==============================================================
328 def setDebugOn(self):
329 """
330 @brief
331 """
332 self.__debug=not None
333
334 def setDebugOff(self):
335 """
336 @brief
337 """
338 self.__debug=None
339
340 def debug(self):
341 """
342 @brief returns true if the PDE is in the debug mode
343 """
344 return self.__debug
345
346 #===== Lumping ===========================
347 def setLumpingOn(self):
348 """
349 @brief indicates to use matrix lumping
350 """
351 if not self.isUsingLumping():
352 if self.debug() : print "PDE Debug: lumping is set on"
353 self.__rebuildOperator()
354 self.__lumping=True
355
356 def setLumpingOff(self):
357 """
358 @brief switches off matrix lumping
359 """
360 if self.isUsingLumping():
361 if self.debug() : print "PDE Debug: lumping is set off"
362 self.__rebuildOperator()
363 self.__lumping=False
364
365 def setLumping(self,flag=False):
366 """
367 @brief set the matrix lumping flag to flag
368 """
369 if flag:
370 self.setLumpingOn()
371 else:
372 self.setLumpingOff()
373
374 def isUsingLumping(self):
375 """
376 @brief
377 """
378 return self.__lumping
379
380 #============ method business =========================================================
381 def setSolverMethod(self,solver=util.DEFAULT_METHOD):
382 """
383 @brief sets a new solver
384 """
385 if not solver==self.getSolverMethod():
386 self.__solver_method=solver
387 if self.debug() : print "PDE Debug: New solver is %s"%solver
388 self.__checkMatrixType()
389
390 def getSolverMethod(self):
391 """
392 @brief returns the solver method
393 """
394 return self.__solver_method
395
396 #============ tolerance business =========================================================
397 def setTolerance(self,tol=1.e-8):
398 """
399 @brief resets the tolerance to tol.
400 """
401 if not tol>0:
402 raise ValueException,"Tolerance as to be positive"
403 if tol<self.getTolerance(): self.__rebuildSolution()
404 if self.debug() : print "PDE Debug: New tolerance %e",tol
405 self.__tolerance=tol
406 return
407 def getTolerance(self):
408 """
409 @brief returns the tolerance set for the solution
410 """
411 return self.__tolerance
412
413 #===== symmetry flag ==========================
414 def isSymmetric(self):
415 """
416 @brief returns true is the operator is considered to be symmetric
417 """
418 return self.__sym
419
420 def setSymmetryOn(self):
421 """
422 @brief sets the symmetry flag to true
423 """
424 if not self.isSymmetric():
425 if self.debug() : print "PDE Debug: Operator is set to be symmetric"
426 self.__sym=True
427 self.__checkMatrixType()
428
429 def setSymmetryOff(self):
430 """
431 @brief sets the symmetry flag to false
432 """
433 if self.isSymmetric():
434 if self.debug() : print "PDE Debug: Operator is set to be unsymmetric"
435 self.__sym=False
436 self.__checkMatrixType()
437
438 def setSymmetryTo(self,flag=False):
439 """
440 @brief sets the symmetry flag to flag
441
442 @param flag
443 """
444 if flag:
445 self.setSymmetryOn()
446 else:
447 self.setSymmetryOff()
448
449 #===== order reduction ==========================
450 def setReducedOrderOn(self):
451 """
452 @brief switches to on reduced order
453 """
454 self.setReducedOrderForSolutionOn()
455 self.setReducedOrderForEquationOn()
456
457 def setReducedOrderOff(self):
458 """
459 @brief switches to full order
460 """
461 self.setReducedOrderForSolutionOff()
462 self.setReducedOrderForEquationOff()
463
464 def setReducedOrderTo(self,flag=False):
465 """
466 @brief sets order according to flag
467
468 @param flag
469 """
470 self.setReducedOrderForSolutionTo(flag)
471 self.setReducedOrderForEquationTo(flag)
472
473
474 #===== order reduction solution ==========================
475 def setReducedOrderForSolutionOn(self):
476 """
477 @brief switches to reduced order to interpolate solution
478 """
479 new_fs=escript.ReducedSolution(self.getDomain())
480 if self.getFunctionSpaceForSolution()!=new_fs:
481 if self.debug() : print "PDE Debug: Reduced order is used to interpolate solution."
482 self.__column_function_space=new_fs
483 self.__rebuildSystem(deep=True)
484
485 def setReducedOrderForSolutionOff(self):
486 """
487 @brief switches to full order to interpolate solution
488 """
489 new_fs=escript.Solution(self.getDomain())
490 if self.getFunctionSpaceForSolution()!=new_fs:
491 if self.debug() : print "PDE Debug: Full order is used to interpolate solution."
492 self.__column_function_space=new_fs
493 self.__rebuildSystem(deep=True)
494
495 def setReducedOrderForSolutionTo(self,flag=False):
496 """
497 @brief sets order for test functions according to flag
498
499 @param flag
500 """
501 if flag:
502 self.setReducedOrderForSolutionOn()
503 else:
504 self.setReducedOrderForSolutionOff()
505
506 #===== order reduction equation ==========================
507 def setReducedOrderForEquationOn(self):
508 """
509 @brief switches to reduced order for test functions
510 """
511 new_fs=escript.ReducedSolution(self.getDomain())
512 if self.getFunctionSpaceForEquation()!=new_fs:
513 if self.debug() : print "PDE Debug: Reduced order is used for test functions."
514 self.__row_function_space=new_fs
515 self.__rebuildSystem(deep=True)
516
517 def setReducedOrderForEquationOff(self):
518 """
519 @brief switches to full order for test functions
520 """
521 new_fs=escript.Solution(self.getDomain())
522 if self.getFunctionSpaceForEquation()!=new_fs:
523 if self.debug() : print "PDE Debug: Full order is used for test functions."
524 self.__row_function_space=new_fs
525 self.__rebuildSystem(deep=True)
526
527 def setReducedOrderForEquationTo(self,flag=False):
528 """
529 @brief sets order for test functions according to flag
530
531 @param flag
532 """
533 if flag:
534 self.setReducedOrderForEquationOn()
535 else:
536 self.setReducedOrderForEquationOff()
537
538 # ==== initialization =====================================================================
539 def __makeNewOperator(self):
540 """
541 @brief
542 """
543 return self.getDomain().newOperator( \
544 self.getNumEquations(), \
545 self.getFunctionSpaceForEquation(), \
546 self.getNumSolutions(), \
547 self.getFunctionSpaceForSolution(), \
548 self.__matrix_type)
549
550 def __makeNewRightHandSide(self):
551 """
552 @brief
553 """
554 return escript.Data(0.,(self.getNumEquations(),),self.getFunctionSpaceForEquation(),True)
555
556 def __makeNewSolution(self):
557 """
558 @brief
559 """
560 return escript.Data(0.,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True)
561
562 def __getFreshOperator(self):
563 """
564 @brief
565 """
566 if self.__operator.isEmpty():
567 self.__operator=self.__makeNewOperator()
568 if self.debug() : print "PDE Debug: New operator allocated"
569 else:
570 self.__operator.setValue(0.)
571 self.__operator.resetSolver()
572 if self.debug() : print "PDE Debug: Operator reset to zero"
573 return self.__operator
574
575 def __getFreshRightHandSide(self):
576 """
577 @brief
578 """
579 if self.__righthandside.isEmpty():
580 self.__righthandside=self.__makeNewRightHandSide()
581 if self.debug() : print "PDE Debug: New right hand side allocated"
582 else:
583 print "fix self.__righthandside*=0"
584 self.__righthandside*=0.
585 if self.debug() : print "PDE Debug: Right hand side reset to zero"
586 return self.__righthandside
587
588 #============ some serivice functions =====================================================
589 def getDomain(self):
590 """
591 @brief returns the domain of the PDE
592 """
593 return self.__domain
594
595 def getDim(self):
596 """
597 @brief returns the spatial dimension of the PDE
598 """
599 return self.getDomain().getDim()
600
601 def getNumEquations(self):
602 """
603 @brief returns the number of equations
604 """
605 if self.__numEquations>0:
606 return self.__numEquations
607 else:
608 raise ValueError,"Number of equations is undefined. Please specify argument numEquations."
609
610 def getNumSolutions(self):
611 """
612 @brief returns the number of unknowns
613 """
614 if self.__numSolutions>0:
615 return self.__numSolutions
616 else:
617 raise ValueError,"Number of solution is undefined. Please specify argument numSolutions."
618
619
620 def checkSymmetry(self,verbose=True):
621 """
622 @brief returns if the Operator is symmetric. This is a very expensive operation!!! The symmetry flag is not altered.
623 """
624 verbose=verbose or self.debug()
625 out=True
626 if self.getNumSolutions()!=self.getNumEquations():
627 if verbose: print "non-symmetric PDE because of different number of equations and solutions"
628 out=False
629 else:
630 A=self.getCoefficientOfPDE("A")
631 if not A.isEmpty():
632 tol=util.Lsup(A)*self.TOL
633 if self.getNumSolutions()>1:
634 for i in range(self.getNumEquations()):
635 for j in range(self.getDim()):
636 for k in range(self.getNumSolutions()):
637 for l in range(self.getDim()):
638 if util.Lsup(A[i,j,k,l]-A[k,l,i,j])>tol:
639 if verbose: print "non-symmetric PDE because A[%d,%d,%d,%d]!=A[%d,%d,%d,%d]"%(i,j,k,l,k,l,i,j)
640 out=False
641 else:
642 for j in range(self.getDim()):
643 for l in range(self.getDim()):
644 if util.Lsup(A[j,l]-A[l,j])>tol:
645 if verbose: print "non-symmetric PDE because A[%d,%d]!=A[%d,%d]"%(j,l,l,j)
646 out=False
647 B=self.getCoefficientOfPDE("B")
648 C=self.getCoefficientOfPDE("C")
649 if B.isEmpty() and not C.isEmpty():
650 if verbose: print "non-symmetric PDE because B is not present but C is"
651 out=False
652 elif not B.isEmpty() and C.isEmpty():
653 if verbose: print "non-symmetric PDE because C is not present but B is"
654 out=False
655 elif not B.isEmpty() and not C.isEmpty():
656 tol=(util.Lsup(B)+util.Lsup(C))*self.TOL/2.
657 if self.getNumSolutions()>1:
658 for i in range(self.getNumEquations()):
659 for j in range(self.getDim()):
660 for k in range(self.getNumSolutions()):
661 if util.Lsup(B[i,j,k]-C[k,i,j])>tol:
662 if verbose: print "non-symmetric PDE because B[%d,%d,%d]!=C[%d,%d,%d]"%(i,j,k,k,i,j)
663 out=False
664 else:
665 for j in range(self.getDim()):
666 if util.Lsup(B[j]-C[j])>tol:
667 if verbose: print "non-symmetric PDE because B[%d]!=C[%d]"%(j,j)
668 out=False
669 if self.getNumSolutions()>1:
670 D=self.getCoefficientOfPDE("D")
671 if not D.isEmpty():
672 tol=util.Lsup(D)*self.TOL
673 for i in range(self.getNumEquations()):
674 for k in range(self.getNumSolutions()):
675 if util.Lsup(D[i,k]-D[k,i])>tol:
676 if verbose: print "non-symmetric PDE because D[%d,%d]!=D[%d,%d]"%(i,k,k,i)
677 out=False
678
679 return out
680
681 def getFlux(self,u):
682 """
683 @brief returns the flux J_ij for a given u
684
685 J_ij=A_{ijkl}u_{k,l}+B_{ijk}u_k-X_{ij}
686
687 @param u argument of the operator
688
689 """
690 raise SystemError,"getFlux is not implemented yet"
691 return None
692
693 def applyOperator(self,u):
694 """
695 @brief applies the operator of the PDE to a given solution u in weak from
696
697 @param u argument of the operator
698
699 """
700 return self.getOperator()*escript.Data(u,self.getFunctionSpaceForSolution())
701
702 def getResidual(self,u):
703 """
704 @brief return the residual of u in the weak from
705
706 @param u
707 """
708 return self.applyOperator(u)-self.getRightHandSide()
709
710 def _setValue(self,**coefficients):
711 """
712 @brief sets new values to coefficient
713
714 @param coefficients
715 """
716 # check if the coefficients are legal:
717 for i in coefficients.iterkeys():
718 if not self.hasCoefficient(i):
719 raise ValueError,"Attempt to set unknown coefficient %s"%i
720 # if the number of unknowns or equations is still unknown we try to estimate them:
721 if self.__numEquations<1 or self.__numSolutions<1:
722 for i,d in coefficients.iteritems():
723 if hasattr(d,"shape"):
724 s=d.shape
725 elif hasattr(d,"getShape"):
726 s=d.getShape()
727 else:
728 s=numarray.array(d).shape
729 if s!=None:
730 # get number of equations and number of unknowns:
731 res=self.COEFFICIENTS[i].estimateNumEquationsAndNumSolutions(s,self.getDim())
732 if res==None:
733 raise ValueError,"Illegal shape %s of coefficient %s"%(s,i)
734 else:
735 if self.__numEquations<1: self.__numEquations=res[0]
736 if self.__numSolutions<1: self.__numSolutions=res[1]
737 if self.__numEquations<1: raise ValueError,"unidententified number of equations"
738 if self.__numSolutions<1: raise ValueError,"unidententified number of solutions"
739 # now we check the shape of the coefficient if numEquations and numSolutions are set:
740 for i,d in coefficients.iteritems():
741 if d==None:
742 d2=escript.Data()
743 elif isinstance(d,escript.Data):
744 if d.isEmpty():
745 d2=d
746 else:
747 d2=escript.Data(d,self.getFunctionSpaceForCoefficient(i))
748 else:
749 d2=escript.Data(d,self.getFunctionSpaceForCoefficient(i))
750 if not d2.isEmpty():
751 if not self.getShapeOfCoefficient(i)==d2.getShape():
752 raise ValueError,"Expected shape for coefficient %s is %s but actual shape is %s."%(i,self.getShapeOfCoefficient(i),d2.getShape())
753 # overwrite new values:
754 if self.debug(): print "PDE Debug: Coefficient %s has been altered."%i
755 self.COEFFICIENTS[i].setValue(d2)
756 self.alteredCoefficient(i)
757
758 # reset the HomogeneousConstraintFlag:
759 self.__setHomogeneousConstraintFlag()
760 if len(coefficients)>0 and not self.isUsingLumping() and not self.__homogeneous_constraint: self.__rebuildSystem()
761
762 def __setHomogeneousConstraintFlag(self):
763 """
764 @brief checks if the constraints are homogeneous and sets self.__homogeneous_constraint accordingly.
765 """
766 self.__homogeneous_constraint=True
767 q=self.getCoefficientOfPDE("q")
768 r=self.getCoefficientOfPDE("r")
769 if not q.isEmpty() and not r.isEmpty():
770 if (q*r).Lsup()>=1.e-13*r.Lsup(): self.__homogeneous_constraint=False
771 if self.debug():
772 if self.__homogeneous_constraint:
773 print "PDE Debug: Constraints are homogeneous."
774 else:
775 print "PDE Debug: Constraints are inhomogeneous."
776
777
778 # ==== rebuild switches =====================================================================
779 def __rebuildSolution(self,deep=False):
780 """
781 @brief indicates the PDE has to be reolved if the solution is requested
782 """
783 if self.__solution_isValid and self.debug() : print "PDE Debug: PDE has to be resolved."
784 self.__solution_isValid=False
785 if deep: self.__solution=escript.Data()
786
787
788 def __rebuildOperator(self,deep=False):
789 """
790 @brief indicates the operator has to be rebuilt next time it is used
791 """
792 if self.__operator_isValid and self.debug() : print "PDE Debug: Operator has to be rebuilt."
793 self.__rebuildSolution(deep)
794 self.__operator_isValid=False
795 if deep: self.__operator=escript.Operator()
796
797 def __rebuildRightHandSide(self,deep=False):
798 """
799 @brief indicates the right hand side has to be rebuild next time it is used
800 """
801 if self.__righthandside_isValid and self.debug() : print "PDE Debug: Right hand side has to be rebuilt."
802 self.__rebuildSolution(deep)
803 self.__righthandside_isValid=False
804 if deep: self.__righthandside=escript.Data()
805
806 def __rebuildSystem(self,deep=False):
807 """
808 @brief annonced that all coefficient name has been changed
809 """
810 self.__rebuildSolution(deep)
811 self.__rebuildOperator(deep)
812 self.__rebuildRightHandSide(deep)
813
814 def __checkMatrixType(self):
815 """
816 @brief reassess the matrix type and, if needed, initiates an operator rebuild
817 """
818 new_matrix_type=self.getDomain().getSystemMatrixTypeId(self.getSolverMethod(),self.isSymmetric())
819 if not new_matrix_type==self.__matrix_type:
820 if self.debug() : print "PDE Debug: Matrix type is now %d."%new_matrix_type
821 self.__matrix_type=new_matrix_type
822 self.__rebuildOperator(deep=True)
823
824 #============ assembling =======================================================
825 def __copyConstraint(self):
826 """
827 @brief copies the constrint condition into u
828 """
829 if not self.__righthandside.isEmpty():
830 q=self.getCoefficientOfPDE("q")
831 r=self.getCoefficientOfPDE("r")
832 if not q.isEmpty():
833 if r.isEmpty():
834 r2=escript.Data(0,self.__righthandside.getShape(),self.__righthandside.getFunctionSpace())
835 else:
836 r2=escript.Data(r,self.__righthandside.getFunctionSpace())
837 self.__righthandside.copyWithMask(r2,escript.Data(q,self.__righthandside.getFunctionSpace()))
838
839 def __applyConstraint(self):
840 """
841 @brief applies the constraints defined by q and r to the system
842 """
843 q=self.getCoefficientOfPDE("q")
844 r=self.getCoefficientOfPDE("r")
845 if not q.isEmpty() and not self.__operator.isEmpty():
846 # q is the row and column mask to indicate where constraints are set:
847 row_q=escript.Data(q,self.getFunctionSpaceForEquation())
848 col_q=escript.Data(q,self.getFunctionSpaceForSolution())
849 u=self.__makeNewSolution()
850 if r.isEmpty():
851 r_s=self.__makeNewSolution()
852 else:
853 r_s=escript.Data(r,self.getFunctionSpaceForSolution())
854 u.copyWithMask(r_s,col_q)
855 if self.isUsingLumping():
856 self.__operator.copyWithMask(escript.Data(1,q.getShape(),self.getFunctionSpaceForEquation()),row_q)
857 else:
858 if not self.__righthandside.isEmpty(): self.__righthandside-=self.__operator*u
859 self.__operator.nullifyRowsAndCols(row_q,col_q,1.)
860
861 def getSystem(self):
862 """
863 @brief return the operator and right hand side of the PDE
864 """
865 if not self.__operator_isValid or not self.__righthandside_isValid:
866 if self.isUsingLumping():
867 if not self.__operator_isValid:
868 if not self.getFunctionSpaceForEquation()==self.getFunctionSpaceForSolution():
869 raise TypeError,"Lumped matrix requires same order for equations and unknowns"
870 if not self.getCoefficientOfPDE("A").isEmpty():
871 raise Warning,"Lumped matrix does not allow coefficient A"
872 if not self.getCoefficientOfPDE("B").isEmpty():
873 raise Warning,"Lumped matrix does not allow coefficient B"
874 if not self.getCoefficientOfPDE("C").isEmpty():
875 raise Warning,"Lumped matrix does not allow coefficient C"
876 if self.debug() : print "PDE Debug: New lumped operator is built."
877 mat=self.__makeNewOperator()
878 self.getDomain().addPDEToSystem(mat,escript.Data(), \
879 self.getCoefficientOfPDE("A"), \
880 self.getCoefficientOfPDE("B"), \
881 self.getCoefficientOfPDE("C"), \
882 self.getCoefficientOfPDE("D"), \
883 escript.Data(), \
884 escript.Data(), \
885 self.getCoefficientOfPDE("d"), \
886 escript.Data(),\
887 self.getCoefficientOfPDE("d_contact"), \
888 escript.Data())
889 self.__operator=mat*escript.Data(1,(self.getNumSolutions(),),self.getFunctionSpaceForSolution(),True)
890 self.__applyConstraint()
891 self.__operator_isValid=True
892 if not self.__righthandside_isValid:
893 if self.debug() : print "PDE Debug: New right hand side is built."
894 self.getDomain().addPDEToRHS(self.__getFreshRightHandSide(), \
895 self.getCoefficientOfPDE("X"), \
896 self.getCoefficientOfPDE("Y"),\
897 self.getCoefficientOfPDE("y"),\
898 self.getCoefficientOfPDE("y_contact"))
899 self.__copyConstraint()
900 self.__righthandside_isValid=True
901 else:
902 if not self.__operator_isValid and not self.__righthandside_isValid:
903 if self.debug() : print "PDE Debug: New system is built."
904 self.getDomain().addPDEToSystem(self.__getFreshOperator(),self.__getFreshRightHandSide(), \
905 self.getCoefficientOfPDE("A"), \
906 self.getCoefficientOfPDE("B"), \
907 self.getCoefficientOfPDE("C"), \
908 self.getCoefficientOfPDE("D"), \
909 self.getCoefficientOfPDE("X"), \
910 self.getCoefficientOfPDE("Y"), \
911 self.getCoefficientOfPDE("d"), \
912 self.getCoefficientOfPDE("y"), \
913 self.getCoefficientOfPDE("d_contact"), \
914 self.getCoefficientOfPDE("y_contact"))
915 self.__applyConstraint()
916 self.__copyConstraint()
917 self.__operator_isValid=True
918 self.__righthandside_isValid=True
919 elif not self.__righthandside_isValid:
920 if self.debug() : print "PDE Debug: New right hand side is built."
921 self.getDomain().addPDEToRHS(self.__getFreshRightHandSide(), \
922 self.getCoefficientOfPDE("X"), \
923 self.getCoefficientOfPDE("Y"),\
924 self.getCoefficientOfPDE("y"),\
925 self.getCoefficientOfPDE("y_contact"))
926 self.__copyConstraint()
927 self.__righthandside_isValid=True
928 elif not self.__operator_isValid:
929 if self.debug() : print "PDE Debug: New operator is built."
930 self.getDomain().addPDEToSystem(self.__getFreshOperator(),escript.Data(), \
931 self.getCoefficientOfPDE("A"), \
932 self.getCoefficientOfPDE("B"), \
933 self.getCoefficientOfPDE("C"), \
934 self.getCoefficientOfPDE("D"), \
935 escript.Data(), \
936 escript.Data(), \
937 self.getCoefficientOfPDE("d"), \
938 escript.Data(),\
939 self.getCoefficientOfPDE("d_contact"), \
940 escript.Data())
941 self.__applyConstraint()
942 self.__operator_isValid=True
943 return (self.__operator,self.__righthandside)
944 def getOperator(self):
945 """
946 @brief returns the operator of the PDE
947 """
948 return self.getSystem()[0]
949
950 def getRightHandSide(self):
951 """
952 @brief returns the right hand side of the PDE
953 """
954 return self.getSystem()[1]
955
956 def solve(self,**options):
957 """
958 @brief solve the PDE
959
960 @param options
961 """
962 mat,f=self.getSystem()
963 if self.isUsingLumping():
964 out=f/mat
965 else:
966 options[util.TOLERANCE_KEY]=self.getTolerance()
967 options[util.METHOD_KEY]=self.getSolverMethod()
968 options[util.SYMMETRY_KEY]=self.isSymmetric()
969 if self.debug() : print "PDE Debug: solver options: ",options
970 out=mat.solve(f,options)
971 return out
972
973 def getSolution(self,**options):
974 """
975 @brief returns the solution of the PDE
976
977 @param options
978 """
979 if not self.__solution_isValid:
980 if self.debug() : print "PDE Debug: PDE is resolved."
981 self.__solution=self.solve(**options)
982 self.__solution_isValid=True
983 return self.__solution
984
985
986
987 def ELMAN_RAMAGE(P): return (P-1.).wherePositive()*0.5*(1.-1./(P+1.e-15))
988 def SIMPLIFIED_BROOK_HUGHES(P):
989 c=(P-3.).whereNegative()
990 return P/6.*c+1./2.*(1.-c)
991 def HALF(P): return escript.Scalar(0.5,P.getFunctionSpace())
992
993
994 class AdvectivePDE(LinearPDE):
995 """
996 @brief Class to handel a linear PDE domineated by advective terms:
997
998 class to define a linear PDE of the form
999
1000 -(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
1001
1002 with boundary conditons:
1003
1004 n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_{ik}u_k = - n_j*X_{ij} + y_i
1005
1006 and contact conditions
1007
1008 n_j*(A_{ijkl}u_{k,l}+B_{ijk}u_k)_{,j} + d_contact_{ik}[u_k] = - n_j*X_{ij} + y_contact_i
1009
1010 and constraints:
1011
1012 u_i=r_i where q_i>0
1013
1014 """
1015 def __init__(self,domain,numEquations=0,numSolutions=0,xi=ELMAN_RAMAGE):
1016 LinearPDE.__init__(self,domain,numEquations,numSolutions)
1017 self.__xi=xi
1018 self.__Xi=escript.Data()
1019
1020 def __calculateXi(self,peclet_factor,Z,h):
1021 Z_max=util.Lsup(Z)
1022 if Z_max>0.:
1023 return h*self.__xi(Z*peclet_factor)/(Z+Z_max*self.TOL)
1024 else:
1025 return 0.
1026
1027 def setValue(self,**args):
1028 if "A" in args.keys() or "B" in args.keys() or "C" in args.keys(): self.__Xi=escript.Data()
1029 self._setValue(**args)
1030
1031 def getXi(self):
1032 if self.__Xi.isEmpty():
1033 B=self.getCoefficient("B")
1034 C=self.getCoefficient("C")
1035 A=self.getCoefficient("A")
1036 h=self.getDomain().getSize()
1037 self.__Xi=escript.Scalar(0.,self.getFunctionSpaceForCoefficient("A"))
1038 if not C.isEmpty() or not B.isEmpty():
1039 if not C.isEmpty() and not B.isEmpty():
1040 Z2=escript.Scalar(0,self.getFunctionSpaceForCoefficient("A"))
1041 if self.getNumEquations()>1:
1042 if self.getNumSolutions()>1:
1043 for i in range(self.getNumEquations()):
1044 for k in range(self.getNumSolutions()):
1045 for l in range(self.getDim()): Z2+=(C[i,k,l]-B[i,l,k])**2
1046 else:
1047 for i in range(self.getNumEquations()):
1048 for l in range(self.getDim()): Z2+=(C[i,l]-B[i,l])**2
1049 else:
1050 if self.getNumSolutions()>1:
1051 for k in range(self.getNumSolutions()):
1052 for l in range(self.getDim()): Z2+=(C[k,l]-B[l,k])**2
1053 else:
1054 for l in range(self.getDim()): Z2+=(C[l]-B[l])**2
1055 length_of_Z=util.sqrt(Z2)
1056 elif C.isEmpty():
1057 length_of_Z=util.length(B)
1058 else:
1059 length_of_Z=util.length(C)
1060
1061 Z_max=util.Lsup(length_of_Z)
1062 if Z_max>0.:
1063 length_of_A=util.length(A)
1064 A_max=util.Lsup(length_of_A)
1065 if A_max>0:
1066 inv_A=1./(length_of_A+A_max*self.TOL)
1067 else:
1068 inv_A=1./self.TOL
1069 peclet_number=length_of_Z*h/2*inv_A
1070 xi=self.__xi(peclet_number)
1071 self.__Xi=h*xi/(length_of_Z+Z_max*self.TOL)
1072 print "@ preclet number = %e"%util.Lsup(peclet_number),util.Lsup(xi),util.Lsup(length_of_Z)
1073 return self.__Xi
1074
1075
1076 def getCoefficientOfPDE(self,name):
1077 """
1078 @brief return the value of the coefficient name of the general PDE
1079 @param name
1080 """
1081 if not self.getNumEquations() == self.getNumSolutions():
1082 raise ValueError,"AdvectivePDE expects the number of solution componets and the number of equations to be equal."
1083
1084 if name == "A" :
1085 A=self.getCoefficient("A")
1086 B=self.getCoefficient("B")
1087 C=self.getCoefficient("C")
1088 if B.isEmpty() and C.isEmpty():
1089 Aout=A
1090 else:
1091 if A.isEmpty():
1092 Aout=self.createNewCoefficient("A")
1093 else:
1094 Aout=A[:]
1095 Xi=self.getXi()
1096 if self.getNumEquations()>1:
1097 for i in range(self.getNumEquations()):
1098 for j in range(self.getDim()):
1099 for k in range(self.getNumSolutions()):
1100 for l in range(self.getDim()):
1101 if not C.isEmpty() and not B.isEmpty():
1102 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*(C[p,i,j]-B[p,j,i])*(C[p,k,l]-B[p,l,k])
1103 elif C.isEmpty():
1104 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*B[p,j,i]*B[p,l,k]
1105 else:
1106 for p in range(self.getNumEquations()): Aout[i,j,k,l]+=Xi*C[p,i,j]*C[p,k,l]
1107 else:
1108 for j in range(self.getDim()):
1109 for l in range(self.getDim()):
1110 if not C.isEmpty() and not B.isEmpty():
1111 Aout[j,l]+=Xi*(C[j]-B[j])*(C[l]-B[l])
1112 elif C.isEmpty():
1113 Aout[j,l]+=Xi*B[j]*B[l]
1114 else:
1115 Aout[j,l]+=Xi*C[j]*C[l]
1116 return Aout
1117 elif name == "B" :
1118 B=self.getCoefficient("B")
1119 C=self.getCoefficient("C")
1120 D=self.getCoefficient("D")
1121 if C.isEmpty() or D.isEmpty():
1122 Bout=B
1123 else:
1124 Xi=self.getXi()
1125 if B.isEmpty():
1126 Bout=self.createNewCoefficient("B")
1127 else:
1128 Bout=B[:]
1129 if self.getNumEquations()>1:
1130 for k in range(self.getNumSolutions()):
1131 for p in range(self.getNumEquations()):
1132 tmp=Xi*D[p,k]
1133 for i in range(self.getNumEquations()):
1134 for j in range(self.getDim()):
1135 Bout[i,j,k]+=tmp*C[p,i,j]
1136 else:
1137 tmp=Xi*D
1138 for j in range(self.getDim()): Bout[j]+=tmp*C[j]
1139 return Bout
1140 elif name == "C" :
1141 B=self.getCoefficient("B")
1142 C=self.getCoefficient("C")
1143 D=self.getCoefficient("D")
1144 if B.isEmpty() or D.isEmpty():
1145 Cout=C
1146 else:
1147 Xi=self.getXi()
1148 if C.isEmpty():
1149 Cout=self.createNewCoefficient("C")
1150 else:
1151 Cout=C[:]
1152 if self.getNumEquations()>1:
1153 for k in range(self.getNumSolutions()):
1154 for p in range(self.getNumEquations()):
1155 tmp=Xi*D[p,k]
1156 for i in range(self.getNumEquations()):
1157 for l in range(self.getDim()):
1158 Cout[i,k,l]+=tmp*B[p,l,i]
1159 else:
1160 tmp=Xi*D
1161 for j in range(self.getDim()): Cout[j]+=tmp*B[j]
1162 return Cout
1163 elif name == "D" :
1164 return self.getCoefficient("D")
1165 elif name == "X" :
1166 X=self.getCoefficient("X")
1167 Y=self.getCoefficient("Y")
1168 B=self.getCoefficient("B")
1169 C=self.getCoefficient("C")
1170 if Y.isEmpty() or (B.isEmpty() and C.isEmpty()):
1171 Xout=X
1172 else:
1173 if X.isEmpty():
1174 Xout=self.createNewCoefficient("X")
1175 else:
1176 Xout=X[:]
1177 Xi=self.getXi()
1178 if self.getNumEquations()>1:
1179 for p in range(self.getNumEquations()):
1180 tmp=Xi*Y[p]
1181 for i in range(self.getNumEquations()):
1182 for j in range(self.getDim()):
1183 if not C.isEmpty() and not B.isEmpty():
1184 Xout[i,j]+=tmp*(C[p,i,j]-B[p,j,i])
1185 elif C.isEmpty():
1186 Xout[i,j]-=tmp*B[p,j,i]
1187 else:
1188 Xout[i,j]+=tmp*C[p,i,j]
1189 else:
1190 tmp=Xi*Y
1191 for j in range(self.getDim()):
1192 if not C.isEmpty() and not B.isEmpty():
1193 Xout[j]+=tmp*(C[j]-B[j])
1194 elif C.isEmpty():
1195 Xout[j]-=tmp*B[j]
1196 else:
1197 Xout[j]+=tmp*C[j]
1198 return Xout
1199 elif name == "Y" :
1200 return self.getCoefficient("Y")
1201 elif name == "d" :
1202 return self.getCoefficient("d")
1203 elif name == "y" :
1204 return self.getCoefficient("y")
1205 elif name == "d_contact" :
1206 return self.getCoefficient("d_contact")
1207 elif name == "y_contact" :
1208 return self.getCoefficient("y_contact")
1209 elif name == "r" :
1210 return self.getCoefficient("r")
1211 elif name == "q" :
1212 return self.getCoefficient("q")
1213 else:
1214 raise SystemError,"unknown PDE coefficient %s",name
1215
1216
1217 class Poisson(LinearPDE):
1218 """
1219 @brief Class to define a Poisson equstion problem:
1220
1221 class to define a linear PDE of the form
1222
1223 -u_{,jj} = f
1224
1225 with boundary conditons:
1226
1227 n_j*u_{,j} = 0
1228
1229 and constraints:
1230
1231 u=0 where q>0
1232
1233 """
1234
1235 def __init__(self,domain,f=escript.Data(),q=escript.Data()):
1236 LinearPDE.__init__(self,domain,1,1)
1237 self.COEFFICIENTS={
1238 "f" : PDECoefficient(PDECoefficient.INTERIOR,(PDECoefficient.EQUATION,),PDECoefficient.RIGHTHANDSIDE),
1239 "q" : PDECoefficient(PDECoefficient.CONTINUOUS,(PDECoefficient.EQUATION,),PDECoefficient.BOTH)}
1240 self.setSymmetryOn()
1241 self.setValue(f,q)
1242
1243 def setValue(self,f=escript.Data(),q=escript.Data()):
1244 self._setValue(f=f,q=q)
1245
1246 def getCoefficientOfPDE(self,name):
1247 """
1248 @brief return the value of the coefficient name of the general PDE
1249 @param name
1250 """
1251 if name == "A" :
1252 return escript.Data(numarray.identity(self.getDim()),escript.Function(self.getDomain()))
1253 elif name == "B" :
1254 return escript.Data()
1255 elif name == "C" :
1256 return escript.Data()
1257 elif name == "D" :
1258 return escript.Data()
1259 elif name == "X" :
1260 return escript.Data()
1261 elif name == "Y" :
1262 return self.getCoefficient("f")
1263 elif name == "d" :
1264 return escript.Data()
1265 elif name == "y" :
1266 return escript.Data()
1267 elif name == "d_contact" :
1268 return escript.Data()
1269 elif name == "y_contact" :
1270 return escript.Data()
1271 elif name == "r" :
1272 return escript.Data()
1273 elif name == "q" :
1274 return self.getCoefficient("q")
1275 else:
1276 raise SystemError,"unknown PDE coefficient %s",name

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

  ViewVC Help
Powered by ViewVC 1.1.26