# Diff of /trunk/escript/py_src/util.py

revision 148 by jgs, Tue Aug 23 01:24:31 2005 UTC revision 149 by jgs, Thu Sep 1 03:31:39 2005 UTC
# Line 3  Line 3
3  ## @file util.py  ## @file util.py
4
5  """  """
6  @brief Utility functions for escript  Utility functions for escript
7
8  TODO for Data:  @todo:
9
10    * binary operations @:               (a@b)[:,*]=a[:]@b[:,*] if rank(a)<rank(b)    - binary operations @ (@=+,-,*,/,**)::
11                  @=+,-,*,/,**           (a@b)[:]=a[:]@b[:] if rank(a)=rank(b)        (a@b)[:,*]=a[:]@b[:,*] if rank(a)<rank(b)
12                                         (a@b)[*,:]=a[*,:]@b[:] if rank(a)>rank(b)        (a@b)[:]=a[:]@b[:] if rank(a)=rank(b)
13            (a@b)[*,:]=a[*,:]@b[:] if rank(a)>rank(b)
14    * implementation of outer outer(a,b)[:,*]=a[:]*b[*]    - implementation of outer::
15    * trace: trace(arg,axis0=a0,axis1=a1)(:,&,*)=sum_i trace(:,i,&,i,*) (i are at index a0 and a1)        outer(a,b)[:,*]=a[:]*b[*]
16      - trace::
17          trace(arg,axis0=a0,axis1=a1)(:,&,*)=sum_i trace(:,i,&,i,*) (i are at index a0 and a1)
18  """  """
19
20  import numarray  import numarray
# Line 23  import escript Line 25  import escript
25  #===========================================================  #===========================================================
26
27  class Symbol:  class Symbol:
28     """symbol class"""     """
29       Symbol class.
30       """
31     def __init__(self,name="symbol",shape=(),dim=3,args=[]):     def __init__(self,name="symbol",shape=(),dim=3,args=[]):
32         """creates an instance of a symbol of shape shape and spatial dimension dim         """
33            The symbol may depending on a list of arguments args which         Creates an instance of a symbol of shape shape and spatial dimension
34            may be symbols or other objects. name gives the name of the symbol."""         dim.
35
36           The symbol may depending on a list of arguments args which may be
37           symbols or other objects. name gives the name of the symbol.
38           """
39
40         self.__args=args         self.__args=args
41         self.__name=name         self.__name=name
42         self.__shape=shape         self.__shape=shape
# Line 40  class Symbol: Line 49  class Symbol:
49         self.__cache_argval=None         self.__cache_argval=None
50
51     def getArgument(self,i):     def getArgument(self,i):
52         """returns the i-th argument"""         """
53           Returns the i-th argument.
54           """
55         return self.__args[i]         return self.__args[i]
56
57     def getDim(self):     def getDim(self):
58         """returns the spatial dimension of the symbol"""         """
59           Returns the spatial dimension of the symbol.
60           """
61         return self.__dim         return self.__dim
62
63     def getRank(self):     def getRank(self):
64         """returns the rank of the symbol"""         """
65           Returns the rank of the symbol.
66           """
67         return len(self.getShape())         return len(self.getShape())
68
69     def getShape(self):     def getShape(self):
70         """returns the shape of the symbol"""         """
71           Returns the shape of the symbol.
72           """
73         return self.__shape         return self.__shape
74
75     def getEvaluatedArguments(self,argval):     def getEvaluatedArguments(self,argval):
76         """returns the list of evaluated arguments by subsituting symbol u by argval[u]."""         """
77           Returns the list of evaluated arguments by subsituting symbol u by
78           argval[u].
79           """
80         if argval==self.__cache_argval:         if argval==self.__cache_argval:
81             print "%s: cached value used"%self             print "%s: cached value used"%self
82             return self.__cache_val             return self.__cache_val
# Line 72  class Symbol: Line 92  class Symbol:
92             return out             return out
93
94     def getDifferentiatedArguments(self,arg):     def getDifferentiatedArguments(self,arg):
95         """returns the list of the arguments _differentiated by arg"""         """
96           Returns the list of the arguments _differentiated by arg.
97           """
98         out=[]         out=[]
99         for a in self.__args:         for a in self.__args:
100            if isinstance(a,Symbol):            if isinstance(a,Symbol):
# Line 82  class Symbol: Line 104  class Symbol:
104         return out         return out
105
106     def diff(self,arg):     def diff(self,arg):
107         """returns the _differention of self by arg."""         """
108           Returns the _differention of self by arg.
109           """
110         if self==arg:         if self==arg:
111            out=numarray.zeros(tuple(2*list(self.getShape())),numarray.Float)            out=numarray.zeros(tuple(2*list(self.getShape())),numarray.Float)
112            if self.getRank()==0:            if self.getRank()==0:
# Line 112  class Symbol: Line 136  class Symbol:
136            return self._diff(arg)            return self._diff(arg)
137
138     def _diff(self,arg):     def _diff(self,arg):
139         """return derivate of self with respect to arg (!=self).         """
140            This method is overwritten by a particular symbol"""         Return derivate of self with respect to arg (!=self).
141
142           This method is overwritten by a particular symbol.
143           """
144         return 0         return 0
145
146     def eval(self,argval):     def eval(self,argval):
147         """subsitutes symbol u in self by argval[u] and returns the result. If         """
148            self is not a key of argval then self is returned."""         Subsitutes symbol u in self by argval[u] and returns the result. If
149           self is not a key of argval then self is returned.
150           """
151         if argval.has_key(self):         if argval.has_key(self):
152           return argval[self]           return argval[self]
153         else:         else:
154           return self           return self
155
156     def __str__(self):     def __str__(self):
157         """returns a string representation of the symbol"""         """
158           Returns a string representation of the symbol.
159           """
160         return self.__name         return self.__name
161
163         """adds other to symbol self. if _testForZero(other) self is returned."""         """
164           Adds other to symbol self. if _testForZero(other) self is returned.
165           """
166         if _testForZero(other):         if _testForZero(other):
167            return self            return self
168         else:         else:
# Line 137  class Symbol: Line 170  class Symbol:
171
173         """adds other to symbol self. if _testForZero(other) self is returned."""         """
174           Adds other to symbol self. if _testForZero(other) self is returned.
175           """
176         return self+other         return self+other
177
178     def __neg__(self):     def __neg__(self):
179         """returns -self."""         """
180           Returns -self.
181           """
182         return self*(-1.)         return self*(-1.)
183
184     def __pos__(self):     def __pos__(self):
185         """returns +self."""         """
186           Returns +self.
187           """
188         return self         return self
189
190     def __abs__(self):     def __abs__(self):
191         """returns absolute value"""         """
192           Returns absolute value.
193           """
194         return Abs_Symbol(self)         return Abs_Symbol(self)
195
196     def __sub__(self,other):     def __sub__(self,other):
197         """subtracts other from symbol self. if _testForZero(other) self is returned."""         """
198           Subtracts other from symbol self.
199
200           If _testForZero(other) self is returned.
201           """
202         if _testForZero(other):         if _testForZero(other):
203            return self            return self
204         else:         else:
205            return self+(-other)            return self+(-other)
206
207     def __rsub__(self,other):     def __rsub__(self,other):
208         """subtracts symbol self from other."""         """
209           Subtracts symbol self from other.
210           """
211         return -self+other         return -self+other
212
213     def __div__(self,other):     def __div__(self,other):
214         """divides symbol self by other."""         """
215           Divides symbol self by other.
216           """
217         if isinstance(other,Symbol):         if isinstance(other,Symbol):
218            a=_matchShape([self,other])            a=_matchShape([self,other])
219            return Div_Symbol(a[0],a[1])            return Div_Symbol(a[0],a[1])
# Line 172  class Symbol: Line 221  class Symbol:
221            return self*(1./other)            return self*(1./other)
222
223     def __rdiv__(self,other):     def __rdiv__(self,other):
224         """dived other by symbol self. if _testForZero(other) 0 is returned."""         """
225           Dived other by symbol self. if _testForZero(other) 0 is returned.
226           """
227         if _testForZero(other):         if _testForZero(other):
228            return 0            return 0
229         else:         else:
# Line 180  class Symbol: Line 231  class Symbol:
231            return Div_Symbol(a[0],a[1])            return Div_Symbol(a[0],a[1])
232
233     def __pow__(self,other):     def __pow__(self,other):
234         """raises symbol self to the power of other"""         """
235           Raises symbol self to the power of other.
236           """
237         a=_matchShape([self,other])         a=_matchShape([self,other])
238         return Power_Symbol(a[0],a[1])         return Power_Symbol(a[0],a[1])
239
240     def __rpow__(self,other):     def __rpow__(self,other):
241         """raises other to the symbol self"""         """
242           Raises other to the symbol self.
243           """
244         a=_matchShape([self,other])         a=_matchShape([self,other])
245         return Power_Symbol(a[1],a[0])         return Power_Symbol(a[1],a[0])
246
247     def __mul__(self,other):     def __mul__(self,other):
248         """multiplies other by symbol self. if _testForZero(other) 0 is returned."""         """
249           Multiplies other by symbol self. if _testForZero(other) 0 is returned.
250           """
251         if _testForZero(other):         if _testForZero(other):
252            return 0            return 0
253         else:         else:
# Line 198  class Symbol: Line 255  class Symbol:
255            return Mult_Symbol(a[0],a[1])            return Mult_Symbol(a[0],a[1])
256
257     def __rmul__(self,other):     def __rmul__(self,other):
258         """multiplies other by symbol self. if _testSForZero(other) 0 is returned."""         """
259           Multiplies other by symbol self. if _testSForZero(other) 0 is returned.
260           """
261         return self*other         return self*other
262
263     def __getitem__(self,sl):     def __getitem__(self,sl):
264            print sl            print sl
265
266  def Float_Symbol(Symbol):  class Float_Symbol(Symbol):
267      def __init__(self,name="symbol",shape=(),args=[]):      def __init__(self,name="symbol",shape=(),args=[]):
268          Symbol.__init__(self,dim=0,name="symbol",shape=(),args=[])          Symbol.__init__(self,dim=0,name="symbol",shape=(),args=[])
269
270  class ScalarSymbol(Symbol):  class ScalarSymbol(Symbol):
271     """a scalar symbol"""     """
272       A scalar symbol.
273       """
274     def __init__(self,dim=3,name="scalar"):     def __init__(self,dim=3,name="scalar"):
275        """creates a scalar symbol of spatial dimension dim"""        """
276          Creates a scalar symbol of spatial dimension dim.
277          """
278        if hasattr(dim,"getDim"):        if hasattr(dim,"getDim"):
279             d=dim.getDim()             d=dim.getDim()
280        else:            else:
# Line 219  class ScalarSymbol(Symbol): Line 282  class ScalarSymbol(Symbol):
282        Symbol.__init__(self,shape=(),dim=d,name=name)        Symbol.__init__(self,shape=(),dim=d,name=name)
283
284  class VectorSymbol(Symbol):  class VectorSymbol(Symbol):
285     """a vector symbol"""     """
286       A vector symbol.
287       """
288     def __init__(self,dim=3,name="vector"):     def __init__(self,dim=3,name="vector"):
289        """creates a vector symbol of spatial dimension dim"""        """
290          Creates a vector symbol of spatial dimension dim.
291          """
292        if hasattr(dim,"getDim"):        if hasattr(dim,"getDim"):
293             d=dim.getDim()             d=dim.getDim()
294        else:            else:
# Line 229  class VectorSymbol(Symbol): Line 296  class VectorSymbol(Symbol):
296        Symbol.__init__(self,shape=(d,),dim=d,name=name)        Symbol.__init__(self,shape=(d,),dim=d,name=name)
297
298  class TensorSymbol(Symbol):  class TensorSymbol(Symbol):
299     """a tensor symbol"""     """
300       A tensor symbol.
301       """
302     def __init__(self,dim=3,name="tensor"):     def __init__(self,dim=3,name="tensor"):
303        """creates a tensor symbol of spatial dimension dim"""        """
304          Creates a tensor symbol of spatial dimension dim.
305          """
306        if hasattr(dim,"getDim"):        if hasattr(dim,"getDim"):
307             d=dim.getDim()             d=dim.getDim()
308        else:            else:
# Line 239  class TensorSymbol(Symbol): Line 310  class TensorSymbol(Symbol):
310        Symbol.__init__(self,shape=(d,d),dim=d,name=name)        Symbol.__init__(self,shape=(d,d),dim=d,name=name)
311
312  class Tensor3Symbol(Symbol):  class Tensor3Symbol(Symbol):
313     """a tensor order 3 symbol"""     """
314       A tensor order 3 symbol.
315       """
316     def __init__(self,dim=3,name="tensor3"):     def __init__(self,dim=3,name="tensor3"):
317        """creates a tensor order 3 symbol of spatial dimension dim"""        """
318          Creates a tensor order 3 symbol of spatial dimension dim.
319          """
320        if hasattr(dim,"getDim"):        if hasattr(dim,"getDim"):
321             d=dim.getDim()             d=dim.getDim()
322        else:            else:
# Line 249  class Tensor3Symbol(Symbol): Line 324  class Tensor3Symbol(Symbol):
324        Symbol.__init__(self,shape=(d,d,d),dim=d,name=name)        Symbol.__init__(self,shape=(d,d,d),dim=d,name=name)
325
326  class Tensor4Symbol(Symbol):  class Tensor4Symbol(Symbol):
327     """a tensor order 4 symbol"""     """
328       A tensor order 4 symbol.
329       """
330     def __init__(self,dim=3,name="tensor4"):     def __init__(self,dim=3,name="tensor4"):
331        """creates a tensor order 4 symbol of spatial dimension dim"""            """
332          Creates a tensor order 4 symbol of spatial dimension dim.
333          """
334        if hasattr(dim,"getDim"):        if hasattr(dim,"getDim"):
335             d=dim.getDim()             d=dim.getDim()
336        else:            else:
# Line 259  class Tensor4Symbol(Symbol): Line 338  class Tensor4Symbol(Symbol):
338        Symbol.__init__(self,shape=(d,d,d,d),dim=d,name=name)        Symbol.__init__(self,shape=(d,d,d,d),dim=d,name=name)
339
341     """symbol representing the sum of two arguments"""     """
342       Symbol representing the sum of two arguments.
343       """
344     def __init__(self,arg0,arg1):     def __init__(self,arg0,arg1):
345         a=[arg0,arg1]         a=[arg0,arg1]
346         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)
354         return a[0]+a[1]         return a[0]+a[1]
355
356  class Mult_Symbol(Symbol):  class Mult_Symbol(Symbol):
357     """symbol representing the product of two arguments"""     """
358       Symbol representing the product of two arguments.
359       """
360     def __init__(self,arg0,arg1):     def __init__(self,arg0,arg1):
361         a=[arg0,arg1]         a=[arg0,arg1]
362         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)
# Line 287  class Mult_Symbol(Symbol): Line 370  class Mult_Symbol(Symbol):
370         return self.getArgument(1)*a[0]+self.getArgument(0)*a[1]         return self.getArgument(1)*a[0]+self.getArgument(0)*a[1]
371
372  class Div_Symbol(Symbol):  class Div_Symbol(Symbol):
373     """symbol representing the quotient of two arguments"""     """
374       Symbol representing the quotient of two arguments.
375       """
376     def __init__(self,arg0,arg1):     def __init__(self,arg0,arg1):
377         a=[arg0,arg1]         a=[arg0,arg1]
378         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)
# Line 302  class Div_Symbol(Symbol): Line 387  class Div_Symbol(Symbol):
387                            (self.getArgument(1)*self.getArgument(1))                            (self.getArgument(1)*self.getArgument(1))
388
389  class Power_Symbol(Symbol):  class Power_Symbol(Symbol):
390     """symbol representing the power of the first argument to the power of the second argument"""     """
391       Symbol representing the power of the first argument to the power of the
392       second argument.
393       """
394     def __init__(self,arg0,arg1):     def __init__(self,arg0,arg1):
395         a=[arg0,arg1]         a=[arg0,arg1]
396         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)         Symbol.__init__(self,dim=_extractDim(a),shape=_extractShape(a),args=a)
# Line 316  class Power_Symbol(Symbol): Line 404  class Power_Symbol(Symbol):
404         return self*(a[1]*log(self.getArgument(0))+self.getArgument(1)/self.getArgument(0)*a[0])         return self*(a[1]*log(self.getArgument(0))+self.getArgument(1)/self.getArgument(0)*a[0])
405
406  class Abs_Symbol(Symbol):  class Abs_Symbol(Symbol):
407     """symbol representing absolute value of its argument"""     """
408       Symbol representing absolute value of its argument.
409       """
410     def __init__(self,arg):     def __init__(self,arg):
411         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
412     def __str__(self):     def __str__(self):
# Line 330  class Abs_Symbol(Symbol): Line 420  class Abs_Symbol(Symbol):
420  #   some little helpers  #   some little helpers
421  #=========================================================  #=========================================================
422  def _testForZero(arg):  def _testForZero(arg):
423     """returns True is arg is considered of being zero"""     """
424       Returns True is arg is considered to be zero.
425       """
426     if isinstance(arg,int):     if isinstance(arg,int):
427        return not arg>0        return not arg>0
428     elif isinstance(arg,float):     elif isinstance(arg,float):
# Line 356  def _extractDim(args): Line 448  def _extractDim(args):
448      return dim      return dim
449
450  def _identifyShape(arg):  def _identifyShape(arg):
451     """identifies the shape of arg."""     """
452       Identifies the shape of arg.
453       """
454     if hasattr(arg,"getShape"):     if hasattr(arg,"getShape"):
455         arg_shape=arg.getShape()         arg_shape=arg.getShape()
456     elif hasattr(arg,"shape"):     elif hasattr(arg,"shape"):
# Line 370  def _identifyShape(arg): Line 464  def _identifyShape(arg):
464     return arg_shape     return arg_shape
465
466  def _extractShape(args):  def _extractShape(args):
467      """extracts the common shape of the list of arguments args"""      """
468        Extracts the common shape of the list of arguments args.
469        """
470      shape=None      shape=None
471      for a in args:      for a in args:
472         a_shape=_identifyShape(a)         a_shape=_identifyShape(a)
# Line 381  def _extractShape(args): Line 477  def _extractShape(args):
477      return shape      return shape
478
479  def _matchShape(args,shape=None):  def _matchShape(args,shape=None):
480      """returns the list of arguments args as object which have all the specified shape.      """
481         if shape is not given the shape "largest" shape of args is used."""      Returns the list of arguments args as object which have all the
482        specified shape.
483
484        If shape is not given the shape "largest" shape of args is used.
485        """
486      # identify the list of shapes:      # identify the list of shapes:
487      arg_shapes=[]      arg_shapes=[]
488      for a in args: arg_shapes.append(_identifyShape(a))      for a in args: arg_shapes.append(_identifyShape(a))
# Line 407  def _matchShape(args,shape=None): Line 507  def _matchShape(args,shape=None):
507  #   wrappers for various mathematical functions:  #   wrappers for various mathematical functions:
508  #=========================================================  #=========================================================
509  def diff(arg,dep):  def diff(arg,dep):
510      """returns the derivative of arg with respect to dep. If arg is not Symbol object      """
511         0 is returned"""      Returns the derivative of arg with respect to dep.
512
513        If arg is not Symbol object 0 is returned.
514        """
515      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
516         return arg.diff(dep)         return arg.diff(dep)
517      elif hasattr(arg,"shape"):      elif hasattr(arg,"shape"):
# Line 421  def diff(arg,dep): Line 524  def diff(arg,dep):
524
525  def exp(arg):  def exp(arg):
526      """      """
527      @brief applies the exponential function to arg      Applies the exponential function to arg.
528      @param arg (input): argument
529        @param arg: argument
530      """      """
531      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
532         return Exp_Symbol(arg)         return Exp_Symbol(arg)
# Line 432  def exp(arg): Line 536  def exp(arg):
536         return numarray.exp(arg)         return numarray.exp(arg)
537
538  class Exp_Symbol(Symbol):  class Exp_Symbol(Symbol):
539     """symbol representing the power of the first argument to the power of the second argument"""     """
540       Symbol representing the power of the first argument to the power of the
541       second argument.
542       """
543     def __init__(self,arg):     def __init__(self,arg):
544         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
545     def __str__(self):     def __str__(self):
# Line 444  class Exp_Symbol(Symbol): Line 551  class Exp_Symbol(Symbol):
551
552  def sqrt(arg):  def sqrt(arg):
553      """      """
554      @brief applies the squre root function to arg      Applies the squre root function to arg.
555      @param arg (input): argument
556        @param arg: argument
557      """      """
558      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
559         return Sqrt_Symbol(arg)         return Sqrt_Symbol(arg)
# Line 455  def sqrt(arg): Line 563  def sqrt(arg):
563         return numarray.sqrt(arg)               return numarray.sqrt(arg)
564
565  class Sqrt_Symbol(Symbol):  class Sqrt_Symbol(Symbol):
566     """symbol representing square root of argument"""     """
567       Symbol representing square root of argument.
568       """
569     def __init__(self,arg):     def __init__(self,arg):
570         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
571     def __str__(self):     def __str__(self):
# Line 467  class Sqrt_Symbol(Symbol): Line 577  class Sqrt_Symbol(Symbol):
577
578  def log(arg):  def log(arg):
579      """      """
580      @brief applies the logarithmic function bases exp(1.) to arg      Applies the logarithmic function bases exp(1.) to arg
581      @param arg (input): argument
582        @param arg: argument
583      """      """
584      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
585         return Log_Symbol(arg)         return Log_Symbol(arg)
# Line 478  def log(arg): Line 589  def log(arg):
589         return numarray.log(arg)         return numarray.log(arg)
590
591  class Log_Symbol(Symbol):  class Log_Symbol(Symbol):
592     """symbol representing logarithm of the argument"""     """
593       Symbol representing logarithm of the argument.
594       """
595     def __init__(self,arg):     def __init__(self,arg):
596         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
597     def __str__(self):     def __str__(self):
# Line 490  class Log_Symbol(Symbol): Line 603  class Log_Symbol(Symbol):
603
604  def ln(arg):  def ln(arg):
605      """      """
606      @brief applies the natural logarithmic function to arg      Applies the natural logarithmic function to arg.
607      @param arg (input): argument
608        @param arg: argument
609      """      """
610      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
611         return Ln_Symbol(arg)         return Ln_Symbol(arg)
# Line 501  def ln(arg): Line 615  def ln(arg):
615         return numarray.log(arg)         return numarray.log(arg)
616
617  class Ln_Symbol(Symbol):  class Ln_Symbol(Symbol):
618     """symbol representing natural logarithm of the argument"""     """
619       Symbol representing natural logarithm of the argument.
620       """
621     def __init__(self,arg):     def __init__(self,arg):
622         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
623     def __str__(self):     def __str__(self):
# Line 513  class Ln_Symbol(Symbol): Line 629  class Ln_Symbol(Symbol):
629
630  def sin(arg):  def sin(arg):
631      """      """
632      @brief applies the sin function to arg      Applies the sin function to arg.
633      @param arg (input): argument
634        @param arg: argument
635      """      """
636      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
637         return Sin_Symbol(arg)         return Sin_Symbol(arg)
# Line 524  def sin(arg): Line 641  def sin(arg):
641         return numarray.sin(arg)         return numarray.sin(arg)
642
643  class Sin_Symbol(Symbol):  class Sin_Symbol(Symbol):
644     """symbol representing sin of the argument"""     """
645       Symbol representing sin of the argument.
646       """
647     def __init__(self,arg):     def __init__(self,arg):
648         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
649     def __str__(self):     def __str__(self):
# Line 536  class Sin_Symbol(Symbol): Line 655  class Sin_Symbol(Symbol):
655
656  def cos(arg):  def cos(arg):
657      """      """
658      @brief applies the cos function to arg      Applies the cos function to arg.
659      @param arg (input): argument
660        @param arg: argument
661      """      """
662      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
663         return Cos_Symbol(arg)         return Cos_Symbol(arg)
# Line 547  def cos(arg): Line 667  def cos(arg):
667         return numarray.cos(arg)         return numarray.cos(arg)
668
669  class Cos_Symbol(Symbol):  class Cos_Symbol(Symbol):
670     """symbol representing cos of the argument"""     """
671       Symbol representing cos of the argument.
672       """
673     def __init__(self,arg):     def __init__(self,arg):
674         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
675     def __str__(self):     def __str__(self):
# Line 559  class Cos_Symbol(Symbol): Line 681  class Cos_Symbol(Symbol):
681
682  def tan(arg):  def tan(arg):
683      """      """
684      @brief applies the tan function to arg      Applies the tan function to arg.
685      @param arg (input): argument
686        @param arg: argument
687      """      """
688      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
689         return Tan_Symbol(arg)         return Tan_Symbol(arg)
# Line 570  def tan(arg): Line 693  def tan(arg):
693         return numarray.tan(arg)         return numarray.tan(arg)
694
695  class Tan_Symbol(Symbol):  class Tan_Symbol(Symbol):
696     """symbol representing tan of the argument"""     """
697       Symbol representing tan of the argument.
698       """
699     def __init__(self,arg):     def __init__(self,arg):
700         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
701     def __str__(self):     def __str__(self):
# Line 583  class Tan_Symbol(Symbol): Line 708  class Tan_Symbol(Symbol):
708
709  def sign(arg):  def sign(arg):
710      """      """
711      @brief applies the sign function to arg      Applies the sign function to arg.
712      @param arg (input): argument
713        @param arg: argument
714      """      """
715      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
716         return Sign_Symbol(arg)         return Sign_Symbol(arg)
# Line 595  def sign(arg): Line 721  def sign(arg):
721                numarray.less(arg,numarray.zeros(arg.shape,numarray.Float))                numarray.less(arg,numarray.zeros(arg.shape,numarray.Float))
722
723  class Sign_Symbol(Symbol):  class Sign_Symbol(Symbol):
724     """symbol representing the sign of the argument"""     """
725       Symbol representing the sign of the argument.
726       """
727     def __init__(self,arg):     def __init__(self,arg):
728         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
729     def __str__(self):     def __str__(self):
# Line 605  class Sign_Symbol(Symbol): Line 733  class Sign_Symbol(Symbol):
733
734  def maxval(arg):  def maxval(arg):
735      """      """
736      @brief returns the maximum value of argument arg""      Returns the maximum value of argument arg.
737      @param arg (input): argument
738        @param arg: argument
739      """      """
740      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
741         return Max_Symbol(arg)         return Max_Symbol(arg)
# Line 618  def maxval(arg): Line 747  def maxval(arg):
747         return arg         return arg
748
749  class Max_Symbol(Symbol):  class Max_Symbol(Symbol):
750     """symbol representing the maximum value of the argument"""     """
751       Symbol representing the maximum value of the argument.
752       """
753     def __init__(self,arg):     def __init__(self,arg):
754         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
755     def __str__(self):     def __str__(self):
# Line 628  class Max_Symbol(Symbol): Line 759  class Max_Symbol(Symbol):
759
760  def minval(arg):  def minval(arg):
761      """      """
762      @brief returns the minimum value of argument arg""      Returns the minimum value of argument arg.
763      @param arg (input): argument
764        @param arg: argument
765      """      """
766      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
767         return Min_Symbol(arg)         return Min_Symbol(arg)
# Line 641  def minval(arg): Line 773  def minval(arg):
773         return arg         return arg
774
775  class Min_Symbol(Symbol):  class Min_Symbol(Symbol):
776     """symbol representing the minimum value of the argument"""     """
777       Symbol representing the minimum value of the argument.
778       """
779     def __init__(self,arg):     def __init__(self,arg):
780         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
781     def __str__(self):     def __str__(self):
# Line 651  class Min_Symbol(Symbol): Line 785  class Min_Symbol(Symbol):
785
786  def wherePositive(arg):  def wherePositive(arg):
787      """      """
788      @brief returns the positive values of argument arg""      Returns the positive values of argument arg.
789      @param arg (input): argument
790        @param arg: argument
791      """      """
792      if _testForZero(arg):      if _testForZero(arg):
793        return 0        return 0
# Line 669  def wherePositive(arg): Line 804  def wherePositive(arg):
804            return 0.            return 0.
805
806  class WherePositive_Symbol(Symbol):  class WherePositive_Symbol(Symbol):
807     """symbol representing the wherePositive function"""     """
808       Symbol representing the wherePositive function.
809       """
810     def __init__(self,arg):     def __init__(self,arg):
811         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
812     def __str__(self):     def __str__(self):
# Line 679  class WherePositive_Symbol(Symbol): Line 816  class WherePositive_Symbol(Symbol):
816
817  def whereNegative(arg):  def whereNegative(arg):
818      """      """
819      @brief returns the negative values of argument arg""      Returns the negative values of argument arg.
820      @param arg (input): argument
821        @param arg: argument
822      """      """
823      if _testForZero(arg):      if _testForZero(arg):
824        return 0        return 0
# Line 697  def whereNegative(arg): Line 835  def whereNegative(arg):
835            return 0.            return 0.
836
837  class WhereNegative_Symbol(Symbol):  class WhereNegative_Symbol(Symbol):
838     """symbol representing the whereNegative function"""     """
839       Symbol representing the whereNegative function.
840       """
841     def __init__(self,arg):     def __init__(self,arg):
842         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])         Symbol.__init__(self,shape=arg.getShape(),dim=arg.getDim(),args=[arg])
843     def __str__(self):     def __str__(self):
# Line 706  class WhereNegative_Symbol(Symbol): Line 846  class WhereNegative_Symbol(Symbol):
846         return whereNegative(self.getEvaluatedArguments(argval)[0])         return whereNegative(self.getEvaluatedArguments(argval)[0])
847
848  def maximum(arg0,arg1):  def maximum(arg0,arg1):
849      """return arg1 where arg1 is bigger then arg0 otherwise arg0 is returned"""      """
850        Return arg1 where arg1 is bigger then arg0 otherwise arg0 is returned.
851        """
852      m=whereNegative(arg0-arg1)      m=whereNegative(arg0-arg1)
853      return m*arg1+(1.-m)*arg0      return m*arg1+(1.-m)*arg0
854
855  def minimum(arg0,arg1):  def minimum(arg0,arg1):
856      """return arg0 where arg1 is bigger then arg0 otherwise arg1 is returned"""      """
857        Return arg0 where arg1 is bigger then arg0 otherwise arg1 is returned.
858        """
859      m=whereNegative(arg0-arg1)      m=whereNegative(arg0-arg1)
860      return m*arg0+(1.-m)*arg1      return m*arg0+(1.-m)*arg1
861
# Line 736  def outer(arg0,arg1): Line 880  def outer(arg0,arg1):
880            raise ValueError,"outer is not fully implemented yet."            raise ValueError,"outer is not fully implemented yet."
881
882  class Outer_Symbol(Symbol):  class Outer_Symbol(Symbol):
883     """symbol representing the outer product of its two arguments"""     """
884       Symbol representing the outer product of its two arguments.
885       """
886     def __init__(self,arg0,arg1):     def __init__(self,arg0,arg1):
887         a=[arg0,arg1]         a=[arg0,arg1]
888         s=tuple(list(_identifyShape(arg0))+list(_identifyShape(arg1)))         s=tuple(list(_identifyShape(arg0))+list(_identifyShape(arg1)))
# Line 752  class Outer_Symbol(Symbol): Line 898  class Outer_Symbol(Symbol):
898
899  def interpolate(arg,where):  def interpolate(arg,where):
900      """      """
901      @brief interpolates the function into the FunctionSpace where.      Interpolates the function into the FunctionSpace where.
902
903      @param arg    interpolant      @param arg:    interpolant
904      @param where  FunctionSpace to interpolate to      @param where:  FunctionSpace to interpolate to
905      """      """
906      if _testForZero(arg):      if _testForZero(arg):
907        return 0        return 0
# Line 764  def interpolate(arg,where): Line 910  def interpolate(arg,where):
910      else:      else:
911         return escript.Data(arg,where)         return escript.Data(arg,where)
912
913  def Interpolated_Symbol(Symbol):  class Interpolated_Symbol(Symbol):
914     """symbol representing the integral of the argument"""     """
915       Symbol representing the integral of the argument.
916       """
917     def __init__(self,arg,where):     def __init__(self,arg,where):
918          Symbol.__init__(self,shape=_extractShape(arg),dim=_extractDim([arg]),args=[arg,where])          Symbol.__init__(self,shape=_extractShape(arg),dim=_extractDim([arg]),args=[arg,where])
919     def __str__(self):     def __str__(self):
# Line 779  def Interpolated_Symbol(Symbol): Line 927  def Interpolated_Symbol(Symbol):
927
928  def div(arg,where=None):  def div(arg,where=None):
929      """      """
930      @brief returns the divergence of arg at where.      Returns the divergence of arg at where.
931
932      @param arg:   Data object representing the function which gradient to be calculated.      @param arg:   Data object representing the function which gradient to
933      @param where: FunctionSpace in which the gradient will be calculated. If not present or                    be calculated.
934                    None an appropriate default is used.      @param where: FunctionSpace in which the gradient will be calculated.
935                      If not present or C{None} an appropriate default is used.
936      """      """
938
939    def jump(arg):
940        """
941        Returns the jump of arg across a continuity.
942
943        @param arg:   Data object representing the function which gradient
944                      to be calculated.
945        """
946        d=arg.getDomain()
947        return arg.interpolate(escript.FunctionOnContactOne())-arg.interpolate(escript.FunctionOnContactZero())
948
949
951      """      """
952      @brief returns the spatial gradient of arg at where.      Returns the spatial gradient of arg at where.
953
954      @param arg:   Data object representing the function which gradient to be calculated.      @param arg:   Data object representing the function which gradient
955      @param where: FunctionSpace in which the gradient will be calculated. If not present or                    to be calculated.
956                    None an appropriate default is used.      @param where: FunctionSpace in which the gradient will be calculated.
957                      If not present or C{None} an appropriate default is used.
958      """      """
959      if _testForZero(arg):      if _testForZero(arg):
960        return 0        return 0
968      else:      else:
969         return arg*0.         return arg*0.
970
972     """symbol representing the gradient of the argument"""     """
973       Symbol representing the gradient of the argument.
974       """
975     def __init__(self,arg,where=None):     def __init__(self,arg,where=None):
976         d=_extractDim([arg])         d=_extractDim([arg])
977         s=tuple(list(_identifyShape([arg])).append(d))         s=tuple(list(_identifyShape([arg])).append(d))
987
988  def integrate(arg,where=None):  def integrate(arg,where=None):
989      """      """
990      @brief return the integral if the function represented by Data object arg over its domain.      Return the integral if the function represented by Data object arg over
991        its domain.
992
993      @param arg:   Data object representing the function which is integrated.      @param arg:   Data object representing the function which is integrated.
994      @param where: FunctionSpace in which the integral is calculated. If not present or      @param where: FunctionSpace in which the integral is calculated.
995                    None an appropriate default is used.                    If not present or C{None} an appropriate default is used.
996      """      """
997      if _testForZero(arg):      if _testForZero(arg):
998        return 0        return 0
# Line 841  def integrate(arg,where=None): Line 1005  def integrate(arg,where=None):
1005         else:         else:
1006           return arg.integrate()           return arg.integrate()
1007
1008  def Integral_Symbol(Float_Symbol):  class Integral_Symbol(Float_Symbol):
1009     """symbol representing the integral of the argument"""     """
1010       Symbol representing the integral of the argument.
1011       """
1012     def __init__(self,arg,where=None):     def __init__(self,arg,where=None):
1013         Float_Symbol.__init__(self,shape=_identifyShape([arg]),args=[arg,where])         Float_Symbol.__init__(self,shape=_identifyShape([arg]),args=[arg,where])
1014     def __str__(self):     def __str__(self):
# Line 867  def Integral_Symbol(Float_Symbol): Line 1033  def Integral_Symbol(Float_Symbol):
1033
1034  def transpose(arg,axis=None):  def transpose(arg,axis=None):
1035      """      """
1036      @brief returns the transpose of the Data object arg.      Returns the transpose of the Data object arg.
1037
1038      @param arg      @param arg:
1039      """      """
1040      if axis==None:      if axis==None:
1041         r=0         r=0
# Line 895  def transpose(arg,axis=None): Line 1061  def transpose(arg,axis=None):
1061
1062  def trace(arg,axis0=0,axis1=1):  def trace(arg,axis0=0,axis1=1):
1063      """      """
1064      @brief return      Return
1065
1066      @param arg      @param arg:
1067      """      """
1068      if isinstance(arg,Symbol):      if isinstance(arg,Symbol):
1069         s=list(arg.getShape())                 s=list(arg.getShape())
# Line 921  def Trace_Symbol(Symbol): Line 1087  def Trace_Symbol(Symbol):
1087
1088  def length(arg):  def length(arg):
1089      """      """
@brief
1090
1091      @param arg      @param arg:
1092      """      """
1093      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1094         if arg.isEmpty(): return escript.Data()         if arg.isEmpty(): return escript.Data()
# Line 965  def length(arg): Line 1130  def length(arg):
1130
1131  def deviator(arg):  def deviator(arg):
1132      """      """
1133      @brief      @param arg:

@param arg0
1134      """      """
1135      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1136          shape=arg.getShape()          shape=arg.getShape()
# Line 981  def deviator(arg): Line 1144  def deviator(arg):
1144
1145  def inner(arg0,arg1):  def inner(arg0,arg1):
1146      """      """
1147      @brief      @param arg0:
1148        @param arg1:
@param arg0, arg1
1149      """      """
1150      if isinstance(arg0,escript.Data):      if isinstance(arg0,escript.Data):
1151         arg=arg0         arg=arg0
# Line 1019  def inner(arg0,arg1): Line 1181  def inner(arg0,arg1):
1181            raise SystemError,"inner is not been implemented yet"            raise SystemError,"inner is not been implemented yet"
1182      return out      return out
1183
1184    def tensormult(arg0,arg1):
1185        # check LinearPDE!!!!
1186        raise SystemError,"tensormult is not implemented yet!"
1187
1188  def matrixmult(arg0,arg1):  def matrixmult(arg0,arg1):
1189
1190      if isinstance(arg1,numarray.NumArray) and isinstance(arg0,numarray.NumArray):      if isinstance(arg1,numarray.NumArray) and isinstance(arg0,numarray.NumArray):
# Line 1046  def matrixmult(arg0,arg1): Line 1212  def matrixmult(arg0,arg1):
1212  #=========================================================  #=========================================================
1213  def sum(arg):  def sum(arg):
1214      """      """
1215      @brief      @param arg:

@param arg
1216      """      """
1217      return arg.sum()      return arg.sum()
1218
1219  def sup(arg):  def sup(arg):
1220      """      """
1221      @brief      @param arg:

@param arg
1222      """      """
1223      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1224         return arg.sup()         return arg.sup()
# Line 1067  def sup(arg): Line 1229  def sup(arg):
1229
1230  def inf(arg):  def inf(arg):
1231      """      """
1232      @brief      @param arg:

@param arg
1233      """      """
1234      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1235         return arg.inf()         return arg.inf()
# Line 1080  def inf(arg): Line 1240  def inf(arg):
1240
1241  def L2(arg):  def L2(arg):
1242      """      """
1243      @brief returns the L2-norm of the      Returns the L2-norm of the argument
1244
1245      @param arg      @param arg:
1246      """      """
1247      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1248         return arg.L2()         return arg.L2()
# Line 1093  def L2(arg): Line 1253  def L2(arg):
1253
1254  def Lsup(arg):  def Lsup(arg):
1255      """      """
1256      @brief      @param arg:

@param arg
1257      """      """
1258      if isinstance(arg,escript.Data):      if isinstance(arg,escript.Data):
1259         return arg.Lsup()         return arg.Lsup()
1260      elif isinstance(arg,float) or isinstance(arg,int):      elif isinstance(arg,float) or isinstance(arg,int):
1261         return abs(arg)         return abs(arg)
1262      else:      else:
1263         return max(numarray.abs(arg))         return numarray.abs(arg).max()
1264
1265  def dot(arg0,arg1):  def dot(arg0,arg1):
1266      """      """
1267      @brief      @param arg0:
1268        @param arg1:
@param arg
1269      """      """
1270      if isinstance(arg0,escript.Data):      if isinstance(arg0,escript.Data):
1271         return arg0.dot(arg1)         return arg0.dot(arg1)
# Line 1125  def kronecker(d): Line 1282  def kronecker(d):
1282
1283  def unit(i,d):  def unit(i,d):
1284     """     """
1285     @brief return a unit vector of dimension d with nonzero index i     Return a unit vector of dimension d with nonzero index i.
1286     @param d dimension
1287     @param i index     @param d: dimension
1288       @param i: index
1289     """     """
1290     e = numarray.zeros((d,),numarray.Float)     e = numarray.zeros((d,),numarray.Float)
1291     e[i] = 1.0     e[i] = 1.0
# Line 1187  if __name__=="__main__": Line 1345  if __name__=="__main__":
1345
1346  #  #
1347  # \$Log\$  # \$Log\$
1348    # Revision 1.17  2005/09/01 03:31:28  jgs
1349    # Merge of development branch dev-02 back to main trunk on 2005-09-01
1350    #
1351  # Revision 1.16  2005/08/23 01:24:28  jgs  # Revision 1.16  2005/08/23 01:24:28  jgs
1352  # Merge of development branch dev-02 back to main trunk on 2005-08-23  # Merge of development branch dev-02 back to main trunk on 2005-08-23
1353  #  #
1354  # Revision 1.15  2005/08/12 01:45:36  jgs  # Revision 1.15  2005/08/12 01:45:36  jgs
1355  # erge of development branch dev-02 back to main trunk on 2005-08-12  # erge of development branch dev-02 back to main trunk on 2005-08-12
1356  #  #
1357    # Revision 1.14.2.8  2005/08/26 05:06:37  cochrane
1358    # Corrected errors in docstrings.  Improved output formatting of docstrings.
1359    # Other minor improvements to code and docs (eg spelling etc).
1360    #
1361    # Revision 1.14.2.7  2005/08/26 04:45:40  cochrane
1362    # Fixed and tidied markup and docstrings.  Some *Symbol classes were defined
1363    # as functions, so changed them to classes (hopefully this was the right thing
1364    # to do).
1365    #
1366    # Revision 1.14.2.6  2005/08/26 04:30:13  gross
1367    # gneric unit testing for linearPDE
1368    #
1369    # Revision 1.14.2.5  2005/08/24 02:02:52  gross
1371    #
1372  # Revision 1.14.2.4  2005/08/18 04:39:32  gross  # Revision 1.14.2.4  2005/08/18 04:39:32  gross
1373  # the constants have been removed from util.py as they not needed anymore. PDE related constants are accessed through LinearPDE attributes now  # the constants have been removed from util.py as they not needed anymore. PDE related constants are accessed through LinearPDE attributes now
1374  #  #
# Line 1296  if __name__=="__main__": Line 1472  if __name__=="__main__":
1472  # Bug in Assemble_NodeCoordinates fixed  # Bug in Assemble_NodeCoordinates fixed
1473  #  #
1474  #  #
1475
1476    # vim: expandtab shiftwidth=4:

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