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

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

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

revision 795 by ksteube, Mon Jul 31 01:23:58 2006 UTC revision 1044 by gross, Mon Mar 19 07:29:31 2007 UTC
# Line 26  import math Line 26  import math
26  import numarray  import numarray
27  import escript  import escript
28  import os  import os
29    from esys.escript import C_GeneralTensorProduct
30    
31  #=========================================================  #=========================================================
32  #   some helpers:  #   some helpers:
33  #=========================================================  #=========================================================
34    def getTagNames(domain):
35        """
36        returns a list of the tag names used by the domain
37    
38        
39        @param domain: a domain object
40        @type domain: L{escript.Domain}
41        @return: a list of the tag name used by the domain.
42        @rtype: C{list} of C{str}
43        """
44        return [n.strip() for n in domain.showTagNames().split(",") ]
45    
46    def insertTagNames(domain,**kwargs):
47        """
48        inserts tag names into the domain
49    
50        @param domain: a domain object
51        @type domain: C{escript.Domain}
52        @keyword <tag name>: tag key assigned to <tag name>
53        @type <tag name>: C{int}
54        """
55        for  k in kwargs:
56             domain.setTagMap(k,kwargs[k])
57    
58    def insertTaggedValues(target,**kwargs):
59        """
60        inserts tagged values into the tagged using tag names
61    
62        @param target: data to be filled by tagged values
63        @type target: L{escript.Data}
64        @keyword <tag name>: value to be used for <tag name>
65        @type <tag name>: C{float} or {numarray.NumArray}
66        @return: C{target}
67        @rtype: L{escript.Data}
68        """
69        for k in kwargs:
70            target.setTaggedValue(k,kwargs[k])
71        return target
72    
73        
74  def saveVTK(filename,domain=None,**data):  def saveVTK(filename,domain=None,**data):
75      """      """
76      writes a L{Data} objects into a files using the the VTK XML file format.      writes a L{Data} objects into a files using the the VTK XML file format.
# Line 238  def inf(arg): Line 279  def inf(arg):
279  #=========================================================================  #=========================================================================
280  #   some little helpers  #   some little helpers
281  #=========================================================================  #=========================================================================
282  def pokeShape(arg):  def getRank(arg):
283        """
284        identifies the rank of its argument
285    
286        @param arg: a given object
287        @type arg: L{numarray.NumArray},L{escript.Data},C{float}, C{int}, C{Symbol}
288        @return: the rank of the argument
289        @rtype: C{int}
290        @raise TypeError: if type of arg cannot be processed
291        """
292    
293        if isinstance(arg,numarray.NumArray):
294            return arg.rank
295        elif isinstance(arg,escript.Data):
296            return arg.getRank()
297        elif isinstance(arg,float):
298            return 0
299        elif isinstance(arg,int):
300            return 0
301        elif isinstance(arg,Symbol):
302            return arg.getRank()
303        else:
304          raise TypeError,"getShape: cannot identify shape"
305    def getShape(arg):
306      """      """
307      identifies the shape of its argument      identifies the shape of its argument
308    
# Line 260  def pokeShape(arg): Line 324  def pokeShape(arg):
324      elif isinstance(arg,Symbol):      elif isinstance(arg,Symbol):
325          return arg.getShape()          return arg.getShape()
326      else:      else:
327        raise TypeError,"pokeShape: cannot identify shape"        raise TypeError,"getShape: cannot identify shape"
328    
329  def pokeDim(arg):  def pokeDim(arg):
330      """      """
# Line 283  def commonShape(arg0,arg1): Line 347  def commonShape(arg0,arg1):
347      """      """
348      returns a shape to which arg0 can be extendent from the right and arg1 can be extended from the left.      returns a shape to which arg0 can be extendent from the right and arg1 can be extended from the left.
349    
350      @param arg0: an object with a shape (see L{pokeShape})      @param arg0: an object with a shape (see L{getShape})
351      @param arg1: an object with a shape (see L{pokeShape})      @param arg1: an object with a shape (see L{getShape})
352      @return: the shape of arg0 or arg1 such that the left port equals the shape of arg0 and the right end equals the shape of arg1.      @return: the shape of arg0 or arg1 such that the left port equals the shape of arg0 and the right end equals the shape of arg1.
353      @rtype: C{tuple} of C{int}      @rtype: C{tuple} of C{int}
354      @raise ValueError: if no shape can be found.      @raise ValueError: if no shape can be found.
355      """      """
356      sh0=pokeShape(arg0)      sh0=getShape(arg0)
357      sh1=pokeShape(arg1)      sh1=getShape(arg1)
358      if len(sh0)<len(sh1):      if len(sh0)<len(sh1):
359         if not sh0==sh1[:len(sh0)]:         if not sh0==sh1[:len(sh0)]:
360               raise ValueError,"argument 0 cannot be extended to the shape of argument 1"               raise ValueError,"argument 0 cannot be extended to the shape of argument 1"
# Line 440  def matchShape(arg0,arg1): Line 504  def matchShape(arg0,arg1):
504      @type arg0: L{numarray.NumArray},L{escript.Data},C{float}, C{int}, L{Symbol}      @type arg0: L{numarray.NumArray},L{escript.Data},C{float}, C{int}, L{Symbol}
505      @param arg1: a given object      @param arg1: a given object
506      @type arg1: L{numarray.NumArray},L{escript.Data},C{float}, C{int}, L{Symbol}      @type arg1: L{numarray.NumArray},L{escript.Data},C{float}, C{int}, L{Symbol}
507      @return: arg0 and arg1 where copies are returned when the shape has to be changed.      @return: C{arg0} and C{arg1} where copies are returned when the shape has to be changed.
508      @rtype: C{tuple}      @rtype: C{tuple}
509      """      """
510      sh=commonShape(arg0,arg1)      sh=commonShape(arg0,arg1)
511      sh0=pokeShape(arg0)      sh0=getShape(arg0)
512      sh1=pokeShape(arg1)      sh1=getShape(arg1)
513      if len(sh0)<len(sh):      if len(sh0)<len(sh):
514         return outer(arg0,numarray.ones(sh[len(sh0):],numarray.Float64)),arg1         return outer(arg0,numarray.ones(sh[len(sh0):],numarray.Float64)),arg1
515      elif len(sh1)<len(sh):      elif len(sh1)<len(sh):
# Line 573  class Symbol(object): Line 637  class Symbol(object):
637            if isinstance(a,Symbol):            if isinstance(a,Symbol):
638               out.append(a.substitute(argvals))               out.append(a.substitute(argvals))
639            else:            else:
640                s=pokeShape(s)+arg.getShape()                s=getShape(s)+arg.getShape()
641                if len(s)>0:                if len(s)>0:
642                   out.append(numarray.zeros(s),numarray.Float64)                   out.append(numarray.zeros(s),numarray.Float64)
643                else:                else:
# Line 1310  def whereNonZero(arg,tol=0.): Line 1374  def whereNonZero(arg,tol=0.):
1374     else:     else:
1375        raise TypeError,"whereNonZero: Unknown argument type."        raise TypeError,"whereNonZero: Unknown argument type."
1376    
1377    def erf(arg):
1378       """
1379       returns erf of argument arg
1380    
1381       @param arg: argument
1382       @type arg: C{float}, L{escript.Data}, L{Symbol}, L{numarray.NumArray}.
1383       @rtype: C{float}, L{escript.Data}, L{Symbol}, L{numarray.NumArray} depending on the type of arg.
1384       @raises TypeError: if the type of the argument is not expected.
1385       """
1386       if isinstance(arg,escript.Data):
1387          return arg._erf()
1388       else:
1389          raise TypeError,"erf: Unknown argument type."
1390    
1391  def sin(arg):  def sin(arg):
1392     """     """
1393     returns sine of argument arg     returns sine of argument arg
# Line 2930  def trace(arg,axis_offset=0): Line 3008  def trace(arg,axis_offset=0):
3008    
3009     @param arg: argument     @param arg: argument
3010     @type arg: L{escript.Data}, L{Symbol}, L{numarray.NumArray}.     @type arg: L{escript.Data}, L{Symbol}, L{numarray.NumArray}.
3011     @param axis_offset: axis_offset to components to sum over. C{axis_offset} must be non-negative and less than the rank of arg +1. The dimensions on component     @param axis_offset: C{axis_offset} to components to sum over. C{axis_offset} must be non-negative and less than the rank of arg +1. The dimensions on component
3012                    axis_offset and axis_offset+1 must be equal.                    C{axis_offset} and axis_offset+1 must be equal.
3013     @type axis_offset: C{int}     @type axis_offset: C{int}
3014     @return: trace of arg. The rank of the returned object is minus 2 of the rank of arg.     @return: trace of arg. The rank of the returned object is minus 2 of the rank of arg.
3015     @rtype: L{escript.Data}, L{Symbol}, L{numarray.NumArray} depending on the type of arg.     @rtype: L{escript.Data}, L{Symbol}, L{numarray.NumArray} depending on the type of arg.
# Line 2963  def trace(arg,axis_offset=0): Line 3041  def trace(arg,axis_offset=0):
3041        s=list(arg.getShape())                s=list(arg.getShape())        
3042        if not s[axis_offset] == s[axis_offset+1]:        if not s[axis_offset] == s[axis_offset+1]:
3043          raise ValueError,"dimensions of component %s and %s must match."%(axis_offset.axis_offset+1)          raise ValueError,"dimensions of component %s and %s must match."%(axis_offset.axis_offset+1)
3044        return arg._matrixtrace(axis_offset)        return arg._trace(axis_offset)
3045     elif isinstance(arg,float):     elif isinstance(arg,float):
3046        raise TypeError,"illegal argument type float."        raise TypeError,"illegal argument type float."
3047     elif isinstance(arg,int):     elif isinstance(arg,int):
# Line 2982  class Trace_Symbol(DependendSymbol): Line 3060  class Trace_Symbol(DependendSymbol):
3060        initialization of trace L{Symbol} with argument arg        initialization of trace L{Symbol} with argument arg
3061        @param arg: argument of function        @param arg: argument of function
3062        @type arg: L{Symbol}.        @type arg: L{Symbol}.
3063        @param axis_offset: axis_offset to components to sum over. C{axis_offset} must be non-negative and less than the rank of arg +1. The dimensions on component        @param axis_offset: C{axis_offset} to components to sum over. C{axis_offset} must be non-negative and less than the rank of arg +1. The dimensions on component
3064                    axis_offset and axis_offset+1 must be equal.                    C{axis_offset} and axis_offset+1 must be equal.
3065        @type axis_offset: C{int}        @type axis_offset: C{int}
3066        """        """
3067        if arg.getRank()<2:        if arg.getRank()<2:
# Line 3049  class Trace_Symbol(DependendSymbol): Line 3127  class Trace_Symbol(DependendSymbol):
3127    
3128  def transpose(arg,axis_offset=None):  def transpose(arg,axis_offset=None):
3129     """     """
3130     returns the transpose of arg by swaping the first axis_offset and the last rank-axis_offset components.     returns the transpose of arg by swaping the first C{axis_offset} and the last rank-axis_offset components.
3131    
3132     @param arg: argument     @param arg: argument
3133     @type arg: L{escript.Data}, L{Symbol}, L{numarray.NumArray}, C{float}, C{int}     @type arg: L{escript.Data}, L{Symbol}, L{numarray.NumArray}, C{float}, C{int}
3134     @param axis_offset: the first axis_offset components are swapped with rest. If C{axis_offset} must be non-negative and less or equal the rank of arg.     @param axis_offset: the first C{axis_offset} components are swapped with rest. If C{axis_offset} must be non-negative and less or equal the rank of arg.
3135                         if axis_offset is not present C{int(r/2)} where r is the rank of arg is used.                         if C{axis_offset} is not present C{int(r/2)} where r is the rank of arg is used.
3136     @type axis_offset: C{int}     @type axis_offset: C{int}
3137     @return: transpose of arg     @return: transpose of arg
3138     @rtype: L{escript.Data}, L{Symbol}, L{numarray.NumArray},C{float}, C{int} depending on the type of arg.     @rtype: L{escript.Data}, L{Symbol}, L{numarray.NumArray},C{float}, C{int} depending on the type of arg.
# Line 3092  class Transpose_Symbol(DependendSymbol): Line 3170  class Transpose_Symbol(DependendSymbol):
3170    
3171        @param arg: argument of function        @param arg: argument of function
3172        @type arg: L{Symbol}.        @type arg: L{Symbol}.
3173        @param axis_offset: the first axis_offset components are swapped with rest. If C{axis_offset} must be non-negative and less or equal the rank of arg.        @param axis_offset: the first C{axis_offset} components are swapped with rest. If C{axis_offset} must be non-negative and less or equal the rank of arg.
3174                         if axis_offset is not present C{int(r/2)} where r is the rank of arg is used.                         if C{axis_offset} is not present C{int(r/2)} where r is the rank of arg is used.
3175        @type axis_offset: C{int}        @type axis_offset: C{int}
3176        """        """
3177        if axis_offset==None: axis_offset=int(arg.getRank()/2)        if axis_offset==None: axis_offset=int(arg.getRank()/2)
3178        if axis_offset<0 or axis_offset>arg.getRank():        if axis_offset<0 or axis_offset>arg.getRank():
3179          raise ValueError,"axis_offset must be between 0 and %s"%r          raise ValueError,"axis_offset must be between 0 and %s"%arg.getRank()
3180        s=arg.getShape()        s=arg.getShape()
3181        super(Transpose_Symbol,self).__init__(args=[arg,axis_offset],shape=s[axis_offset:]+s[:axis_offset],dim=arg.getDim())        super(Transpose_Symbol,self).__init__(args=[arg,axis_offset],shape=s[axis_offset:]+s[:axis_offset],dim=arg.getDim())
3182    
# Line 3153  class Transpose_Symbol(DependendSymbol): Line 3231  class Transpose_Symbol(DependendSymbol):
3231           return identity(self.getShape())           return identity(self.getShape())
3232        else:        else:
3233           return transpose(self.getDifferentiatedArguments(arg)[0],axis_offset=self.getArgument()[1])           return transpose(self.getDifferentiatedArguments(arg)[0],axis_offset=self.getArgument()[1])
3234    
3235    def swap_axes(arg,axis0=0,axis1=1):
3236       """
3237       returns the swap of arg by swaping the components axis0 and axis1
3238    
3239       @param arg: argument
3240       @type arg: L{escript.Data}, L{Symbol}, L{numarray.NumArray}.
3241       @param axis0: axis. C{axis0} must be non-negative and less than the rank of arg.
3242       @type axis0: C{int}
3243       @param axis1: axis. C{axis1} must be non-negative and less than the rank of arg.
3244       @type axis1: C{int}
3245       @return: C{arg} with swaped components
3246       @rtype: L{escript.Data}, L{Symbol}, L{numarray.NumArray} depending on the type of arg.
3247       """
3248       if axis0 > axis1:
3249          axis0,axis1=axis1,axis0
3250       if isinstance(arg,numarray.NumArray):
3251          return numarray.swapaxes(arg,axis0,axis1)
3252       elif isinstance(arg,escript.Data):
3253          return arg._swap_axes(axis0,axis1)
3254       elif isinstance(arg,float):
3255          raise TyepError,"float argument is not supported."
3256       elif isinstance(arg,int):
3257          raise TyepError,"int argument is not supported."
3258       elif isinstance(arg,Symbol):
3259          return SwapAxes_Symbol(arg,axis0,axis1)
3260       else:
3261          raise TypeError,"Unknown argument type."
3262    
3263    class SwapAxes_Symbol(DependendSymbol):
3264       """
3265       L{Symbol} representing the result of the swap function
3266       """
3267       def __init__(self,arg,axis0=0,axis1=1):
3268          """
3269          initialization of swap L{Symbol} with argument arg
3270    
3271          @param arg: argument
3272          @type arg: L{Symbol}.
3273          @param axis0: axis. C{axis0} must be non-negative and less than the rank of arg.
3274          @type axis0: C{int}
3275          @param axis1: axis. C{axis1} must be non-negative and less than the rank of arg.
3276          @type axis1: C{int}
3277          """
3278          if arg.getRank()<2:
3279             raise ValueError,"argument must have at least rank 2."
3280          if axis0<0 or axis0>arg.getRank()-1:
3281             raise ValueError,"axis0 must be between 0 and %s"%arg.getRank()-1
3282          if axis1<0 or axis1>arg.getRank()-1:
3283             raise ValueError,"axis1 must be between 0 and %s"%arg.getRank()-1
3284          if axis0 == axis1:
3285             raise ValueError,"axis indices must be different."
3286          if axis0 > axis1:
3287             axis0,axis1=axis1,axis0
3288          s=arg.getShape()
3289          s_out=[]
3290          for i in range(len(s)):
3291             if i == axis0:
3292                s_out.append(s[axis1])
3293             elif i == axis1:
3294                s_out.append(s[axis0])
3295             else:
3296                s_out.append(s[i])
3297          super(SwapAxes_Symbol,self).__init__(args=[arg,axis0,axis1],shape=tuple(s_out),dim=arg.getDim())
3298    
3299       def getMyCode(self,argstrs,format="escript"):
3300          """
3301          returns a program code that can be used to evaluate the symbol.
3302    
3303          @param argstrs: gives for each argument a string representing the argument for the evaluation.
3304          @type argstrs: C{str} or a C{list} of length 1 of C{str}.
3305          @param format: specifies the format to be used. At the moment only "escript" ,"text" and "str" are supported.
3306          @type format: C{str}
3307          @return: a piece of program code which can be used to evaluate the expression assuming the values for the arguments are available.
3308          @rtype: C{str}
3309          @raise NotImplementedError: if the requested format is not available
3310          """
3311          if format=="escript" or format=="str"  or format=="text":
3312             return "swap(%s,axis_offset=%s)"%(argstrs[0],argstrs[1])
3313          else:
3314             raise NotImplementedError,"SwapAxes_Symbol does not provide program code for format %s."%format
3315    
3316       def substitute(self,argvals):
3317          """
3318          assigns new values to symbols in the definition of the symbol.
3319          The method replaces the L{Symbol} u by argvals[u] in the expression defining this object.
3320    
3321          @param argvals: new values assigned to symbols
3322          @type argvals: C{dict} with keywords of type L{Symbol}.
3323          @return: result of the substitution process. Operations are executed as much as possible.
3324          @rtype: L{escript.Symbol}, C{float}, L{escript.Data}, L{numarray.NumArray} depending on the degree of substitution
3325          @raise TypeError: if a value for a L{Symbol} cannot be substituted.
3326          """
3327          if argvals.has_key(self):
3328             arg=argvals[self]
3329             if self.isAppropriateValue(arg):
3330                return arg
3331             else:
3332                raise TypeError,"%s: new value is not appropriate."%str(self)
3333          else:
3334             arg=self.getSubstitutedArguments(argvals)
3335             return swap_axes(arg[0],axis0=arg[1],axis1=arg[2])
3336    
3337       def diff(self,arg):
3338          """
3339          differential of this object
3340    
3341          @param arg: the derivative is calculated with respect to arg
3342          @type arg: L{escript.Symbol}
3343          @return: derivative with respect to C{arg}
3344          @rtype: typically L{Symbol} but other types such as C{float}, L{escript.Data}, L{numarray.NumArray}  are possible.
3345          """
3346          if arg==self:
3347             return identity(self.getShape())
3348          else:
3349             return swap_axes(self.getDifferentiatedArguments(arg)[0],axis0=self.getArgument()[1],axis1=self.getArgument()[2])
3350    
3351  def symmetric(arg):  def symmetric(arg):
3352      """      """
3353      returns the symmetric part of the square matrix arg. This is (arg+transpose(arg))/2      returns the symmetric part of the square matrix arg. This is (arg+transpose(arg))/2
# Line 3528  class Add_Symbol(DependendSymbol): Line 3723  class Add_Symbol(DependendSymbol):
3723         @raise ValueError: if both arguments do not have the same shape.         @raise ValueError: if both arguments do not have the same shape.
3724         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
3725         """         """
3726         sh0=pokeShape(arg0)         sh0=getShape(arg0)
3727         sh1=pokeShape(arg1)         sh1=getShape(arg1)
3728         if not sh0==sh1:         if not sh0==sh1:
3729            raise ValueError,"Add_Symbol: shape of arguments must match"            raise ValueError,"Add_Symbol: shape of arguments must match"
3730         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])
# Line 3603  def mult(arg0,arg1): Line 3798  def mult(arg0,arg1):
3798         """         """
3799         args=matchShape(arg0,arg1)         args=matchShape(arg0,arg1)
3800         if testForZero(args[0]) or testForZero(args[1]):         if testForZero(args[0]) or testForZero(args[1]):
3801            return numarray.zeros(pokeShape(args[0]),numarray.Float64)            return numarray.zeros(getShape(args[0]),numarray.Float64)
3802         else:         else:
3803            if isinstance(args[0],Symbol) or isinstance(args[1],Symbol) :            if isinstance(args[0],Symbol) or isinstance(args[1],Symbol) :
3804                return Mult_Symbol(args[0],args[1])                return Mult_Symbol(args[0],args[1])
# Line 3627  class Mult_Symbol(DependendSymbol): Line 3822  class Mult_Symbol(DependendSymbol):
3822         @raise ValueError: if both arguments do not have the same shape.         @raise ValueError: if both arguments do not have the same shape.
3823         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
3824         """         """
3825         sh0=pokeShape(arg0)         sh0=getShape(arg0)
3826         sh1=pokeShape(arg1)         sh1=getShape(arg1)
3827         if not sh0==sh1:         if not sh0==sh1:
3828            raise ValueError,"Mult_Symbol: shape of arguments must match"            raise ValueError,"Mult_Symbol: shape of arguments must match"
3829         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])
# Line 3703  def quotient(arg0,arg1): Line 3898  def quotient(arg0,arg1):
3898         """         """
3899         args=matchShape(arg0,arg1)         args=matchShape(arg0,arg1)
3900         if testForZero(args[0]):         if testForZero(args[0]):
3901            return numarray.zeros(pokeShape(args[0]),numarray.Float64)            return numarray.zeros(getShape(args[0]),numarray.Float64)
3902         elif isinstance(args[0],Symbol):         elif isinstance(args[0],Symbol):
3903            if isinstance(args[1],Symbol):            if isinstance(args[1],Symbol):
3904               return Quotient_Symbol(args[0],args[1])               return Quotient_Symbol(args[0],args[1])
# Line 3732  class Quotient_Symbol(DependendSymbol): Line 3927  class Quotient_Symbol(DependendSymbol):
3927         @raise ValueError: if both arguments do not have the same shape.         @raise ValueError: if both arguments do not have the same shape.
3928         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
3929         """         """
3930         sh0=pokeShape(arg0)         sh0=getShape(arg0)
3931         sh1=pokeShape(arg1)         sh1=getShape(arg1)
3932         if not sh0==sh1:         if not sh0==sh1:
3933            raise ValueError,"Quotient_Symbol: shape of arguments must match"            raise ValueError,"Quotient_Symbol: shape of arguments must match"
3934         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])         DependendSymbol.__init__(self,dim=commonDim(arg0,arg1),shape=sh0,args=[arg0,arg1])
# Line 3809  def power(arg0,arg1): Line 4004  def power(arg0,arg1):
4004         """         """
4005         args=matchShape(arg0,arg1)         args=matchShape(arg0,arg1)
4006         if testForZero(args[0]):         if testForZero(args[0]):
4007            return numarray.zeros(pokeShape(args[0]),numarray.Float64)            return numarray.zeros(getShape(args[0]),numarray.Float64)
4008         elif testForZero(args[1]):         elif testForZero(args[1]):
4009            return numarray.ones(pokeShape(args[1]),numarray.Float64)            return numarray.ones(getShape(args[1]),numarray.Float64)
4010         elif isinstance(args[0],Symbol) or isinstance(args[1],Symbol):         elif isinstance(args[0],Symbol) or isinstance(args[1],Symbol):
4011            return Power_Symbol(args[0],args[1])            return Power_Symbol(args[0],args[1])
4012         elif isinstance(args[0],numarray.NumArray) and not isinstance(args[1],numarray.NumArray):         elif isinstance(args[0],numarray.NumArray) and not isinstance(args[1],numarray.NumArray):
# Line 3834  class Power_Symbol(DependendSymbol): Line 4029  class Power_Symbol(DependendSymbol):
4029         @raise ValueError: if both arguments do not have the same shape.         @raise ValueError: if both arguments do not have the same shape.
4030         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
4031         """         """
4032         sh0=pokeShape(arg0)         sh0=getShape(arg0)
4033         sh1=pokeShape(arg1)         sh1=getShape(arg1)
4034         if not sh0==sh1:         if not sh0==sh1:
4035            raise ValueError,"Power_Symbol: shape of arguments must match"            raise ValueError,"Power_Symbol: shape of arguments must match"
4036         d0=pokeDim(arg0)         d0=pokeDim(arg0)
# Line 3934  def minimum(*args): Line 4129  def minimum(*args):
4129            out=add(out,mult(whereNegative(diff),diff))            out=add(out,mult(whereNegative(diff),diff))
4130      return out      return out
4131    
4132  def clip(arg,minval=0.,maxval=1.):  def clip(arg,minval=None,maxval=None):
4133      """      """
4134      cuts the values of arg between minval and maxval      cuts the values of arg between minval and maxval
4135    
4136      @param arg: argument      @param arg: argument
4137      @type arg: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{int} or C{float}      @type arg: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{int} or C{float}
4138      @param minval: lower range      @param minval: lower range. If None no lower range is applied
4139      @type minval: C{float}      @type minval: C{float} or C{None}
4140      @param maxval: upper range      @param maxval: upper range. If None no upper range is applied
4141      @type maxval: C{float}      @type maxval: C{float} or C{None}
4142      @return: is on object with all its value between minval and maxval. value of the argument that greater then minval and      @return: is on object with all its value between minval and maxval. value of the argument that greater then minval and
4143               less then maxval are unchanged.               less then maxval are unchanged.
4144      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{int} or C{float} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{int} or C{float} depending on the input
4145      @raise ValueError: if minval>maxval      @raise ValueError: if minval>maxval
4146      """      """
4147      if minval>maxval:      if not minval==None and not maxval==None:
4148         raise ValueError,"minval = %s must be less then maxval %s"%(minval,maxval)         if minval>maxval:
4149      return minimum(maximum(minval,arg),maxval)            raise ValueError,"minval = %s must be less then maxval %s"%(minval,maxval)
4150        if minval == None:
4151            tmp=arg
4152        else:
4153            tmp=maximum(minval,arg)
4154        if maxval == None:
4155            return tmp
4156        else:
4157            return minimum(tmp,maxval)
4158    
4159        
4160  def inner(arg0,arg1):  def inner(arg0,arg1):
# Line 3972  def inner(arg0,arg1): Line 4175  def inner(arg0,arg1):
4175      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{float} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol}, C{float} depending on the input
4176      @raise ValueError: if the shapes of the arguments are not identical      @raise ValueError: if the shapes of the arguments are not identical
4177      """      """
4178      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4179      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4180      if not sh0==sh1:      if not sh0==sh1:
4181          raise ValueError,"inner: shape of arguments does not match"          raise ValueError,"inner: shape of arguments does not match"
4182      return generalTensorProduct(arg0,arg1,axis_offset=len(sh0))      return generalTensorProduct(arg0,arg1,axis_offset=len(sh0))
# Line 4024  def matrix_mult(arg0,arg1): Line 4227  def matrix_mult(arg0,arg1):
4227      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4228      @raise ValueError: if the shapes of the arguments are not appropriate      @raise ValueError: if the shapes of the arguments are not appropriate
4229      """      """
4230      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4231      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4232      if not len(sh0)==2 :      if not len(sh0)==2 :
4233          raise ValueError,"first argument must have rank 2"          raise ValueError,"first argument must have rank 2"
4234      if not len(sh1)==2 and not len(sh1)==1:      if not len(sh1)==2 and not len(sh1)==1:
# Line 4073  def tensor_mult(arg0,arg1): Line 4276  def tensor_mult(arg0,arg1):
4276      @return: the tensor product of arg0 and arg1 at each data point      @return: the tensor product of arg0 and arg1 at each data point
4277      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4278      """      """
4279      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4280      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4281      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):
4282         return generalTensorProduct(arg0,arg1,axis_offset=1)         return generalTensorProduct(arg0,arg1,axis_offset=1)
4283      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):
# Line 4148  class GeneralTensorProduct_Symbol(Depend Line 4351  class GeneralTensorProduct_Symbol(Depend
4351         @raise ValueError: illegal dimension         @raise ValueError: illegal dimension
4352         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
4353         """         """
4354         sh_arg0=pokeShape(arg0)         sh_arg0=getShape(arg0)
4355         sh_arg1=pokeShape(arg1)         sh_arg1=getShape(arg1)
4356         sh0=sh_arg0[:len(sh_arg0)-axis_offset]         sh0=sh_arg0[:len(sh_arg0)-axis_offset]
4357         sh01=sh_arg0[len(sh_arg0)-axis_offset:]         sh01=sh_arg0[len(sh_arg0)-axis_offset:]
4358         sh10=sh_arg1[:axis_offset]         sh10=sh_arg1[:axis_offset]
# Line 4196  class GeneralTensorProduct_Symbol(Depend Line 4399  class GeneralTensorProduct_Symbol(Depend
4399           args=self.getSubstitutedArguments(argvals)           args=self.getSubstitutedArguments(argvals)
4400           return generalTensorProduct(args[0],args[1],args[2])           return generalTensorProduct(args[0],args[1],args[2])
4401    
4402  def escript_generalTensorProductNew(arg0,arg1,axis_offset):  def escript_generalTensorProduct(arg0,arg1,axis_offset,transpose=0):
4403      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"
4404      # calculate the return shape:      return C_GeneralTensorProduct(arg0, arg1, axis_offset, transpose)
     shape0=arg0.getShape()[:arg0.getRank()-axis_offset]  
     shape01=arg0.getShape()[arg0.getRank()-axis_offset:]  
     shape10=arg1.getShape()[:axis_offset]  
     shape1=arg1.getShape()[axis_offset:]  
     if not shape01==shape10:  
         raise ValueError,"dimensions of last %s components in left argument don't match the first %s components in the right argument."%(axis_offset,axis_offset)  
     # Figure out which functionspace to use (look at where operator+ is defined maybe in BinaryOp.h to get the logic for this)  
     # fs=(escript.Scalar(0.,arg0.getFunctionSpace())+escript.Scalar(0.,arg1.getFunctionSpace())).getFunctionSpace()  
     out=GeneralTensorProduct(arg0, arg1, axis_offset)  
     return out  
   
 def escript_generalTensorProduct(arg0,arg1,axis_offset): # this should be escript._generalTensorProduct  
     "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"  
     # calculate the return shape:  
     shape0=arg0.getShape()[:arg0.getRank()-axis_offset]  
     shape01=arg0.getShape()[arg0.getRank()-axis_offset:]  
     shape10=arg1.getShape()[:axis_offset]  
     shape1=arg1.getShape()[axis_offset:]  
     if not shape01==shape10:  
         raise ValueError,"dimensions of last %s components in left argument don't match the first %s components in the right argument."%(axis_offset,axis_offset)  
   
     # whatr function space should be used? (this here is not good!)  
     fs=(escript.Scalar(0.,arg0.getFunctionSpace())+escript.Scalar(0.,arg1.getFunctionSpace())).getFunctionSpace()  
     # create return value:  
     out=escript.Data(0.,tuple(shape0+shape1),fs)  
     #  
     s0=[[]]  
     for k in shape0:  
           s=[]  
           for j in s0:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s0=s  
     s1=[[]]  
     for k in shape1:  
           s=[]  
           for j in s1:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s1=s  
     s01=[[]]  
     for k in shape01:  
           s=[]  
           for j in s01:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s01=s  
   
     for i0 in s0:  
        for i1 in s1:  
          s=escript.Scalar(0.,fs)  
          for i01 in s01:  
             s+=arg0.__getitem__(tuple(i0+i01))*arg1.__getitem__(tuple(i01+i1))  
          out.__setitem__(tuple(i0+i1),s)  
     return out  
   
4405    
4406  def transposed_matrix_mult(arg0,arg1):  def transposed_matrix_mult(arg0,arg1):
4407      """      """
# Line 4275  def transposed_matrix_mult(arg0,arg1): Line 4425  def transposed_matrix_mult(arg0,arg1):
4425      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4426      @raise ValueError: if the shapes of the arguments are not appropriate      @raise ValueError: if the shapes of the arguments are not appropriate
4427      """      """
4428      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4429      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4430      if not len(sh0)==2 :      if not len(sh0)==2 :
4431          raise ValueError,"first argument must have rank 2"          raise ValueError,"first argument must have rank 2"
4432      if not len(sh1)==2 and not len(sh1)==1:      if not len(sh1)==2 and not len(sh1)==1:
# Line 4320  def transposed_tensor_mult(arg0,arg1): Line 4470  def transposed_tensor_mult(arg0,arg1):
4470      @return: the tensor product of tarnsposed of arg0 and arg1 at each data point      @return: the tensor product of tarnsposed of arg0 and arg1 at each data point
4471      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4472      """      """
4473      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4474      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4475      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):
4476         return generalTransposedTensorProduct(arg0,arg1,axis_offset=1)         return generalTransposedTensorProduct(arg0,arg1,axis_offset=1)
4477      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):
# Line 4398  class GeneralTransposedTensorProduct_Sym Line 4548  class GeneralTransposedTensorProduct_Sym
4548         @raise ValueError: inconsistent dimensions of arguments.         @raise ValueError: inconsistent dimensions of arguments.
4549         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
4550         """         """
4551         sh_arg0=pokeShape(arg0)         sh_arg0=getShape(arg0)
4552         sh_arg1=pokeShape(arg1)         sh_arg1=getShape(arg1)
4553         sh01=sh_arg0[:axis_offset]         sh01=sh_arg0[:axis_offset]
4554         sh10=sh_arg1[:axis_offset]         sh10=sh_arg1[:axis_offset]
4555         sh0=sh_arg0[axis_offset:]         sh0=sh_arg0[axis_offset:]
# Line 4448  class GeneralTransposedTensorProduct_Sym Line 4598  class GeneralTransposedTensorProduct_Sym
4598    
4599  def escript_generalTransposedTensorProduct(arg0,arg1,axis_offset): # this should be escript._generalTransposedTensorProduct  def escript_generalTransposedTensorProduct(arg0,arg1,axis_offset): # this should be escript._generalTransposedTensorProduct
4600      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"
4601      # calculate the return shape:      return C_GeneralTensorProduct(arg0, arg1, axis_offset, 1)
     shape01=arg0.getShape()[:axis_offset]  
     shape10=arg1.getShape()[:axis_offset]  
     shape0=arg0.getShape()[axis_offset:]  
     shape1=arg1.getShape()[axis_offset:]  
     if not shape01==shape10:  
         raise ValueError,"dimensions of first %s components in left argument don't match the first %s components in the right argument."%(axis_offset,axis_offset)  
   
     # whatr function space should be used? (this here is not good!)  
     fs=(escript.Scalar(0.,arg0.getFunctionSpace())+escript.Scalar(0.,arg1.getFunctionSpace())).getFunctionSpace()  
     # create return value:  
     out=escript.Data(0.,tuple(shape0+shape1),fs)  
     #  
     s0=[[]]  
     for k in shape0:  
           s=[]  
           for j in s0:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s0=s  
     s1=[[]]  
     for k in shape1:  
           s=[]  
           for j in s1:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s1=s  
     s01=[[]]  
     for k in shape01:  
           s=[]  
           for j in s01:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s01=s  
   
     for i0 in s0:  
        for i1 in s1:  
          s=escript.Scalar(0.,fs)  
          for i01 in s01:  
             s+=arg0.__getitem__(tuple(i01+i0))*arg1.__getitem__(tuple(i01+i1))  
          out.__setitem__(tuple(i0+i1),s)  
     return out  
   
4602    
4603  def matrix_transposed_mult(arg0,arg1):  def matrix_transposed_mult(arg0,arg1):
4604      """      """
# Line 4507  def matrix_transposed_mult(arg0,arg1): Line 4618  def matrix_transposed_mult(arg0,arg1):
4618      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4619      @raise ValueError: if the shapes of the arguments are not appropriate      @raise ValueError: if the shapes of the arguments are not appropriate
4620      """      """
4621      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4622      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4623      if not len(sh0)==2 :      if not len(sh0)==2 :
4624          raise ValueError,"first argument must have rank 2"          raise ValueError,"first argument must have rank 2"
4625      if not len(sh1)==2 and not len(sh1)==1:      if not len(sh1)==2 and not len(sh1)==1:
# Line 4543  def tensor_transposed_mult(arg0,arg1): Line 4654  def tensor_transposed_mult(arg0,arg1):
4654      @return: the tensor product of tarnsposed of arg0 and arg1 at each data point      @return: the tensor product of tarnsposed of arg0 and arg1 at each data point
4655      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input      @rtype: L{numarray.NumArray}, L{escript.Data}, L{Symbol} depending on the input
4656      """      """
4657      sh0=pokeShape(arg0)      sh0=getShape(arg0)
4658      sh1=pokeShape(arg1)      sh1=getShape(arg1)
4659      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):      if len(sh0)==2 and ( len(sh1)==2 or len(sh1)==1 ):
4660         return generalTensorTransposedProduct(arg0,arg1,axis_offset=1)         return generalTensorTransposedProduct(arg0,arg1,axis_offset=1)
4661      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):      elif len(sh0)==4 and (len(sh1)==2 or len(sh1)==3 or len(sh1)==4):
# Line 4621  class GeneralTensorTransposedProduct_Sym Line 4732  class GeneralTensorTransposedProduct_Sym
4732         @raise ValueError: inconsistent dimensions of arguments.         @raise ValueError: inconsistent dimensions of arguments.
4733         @note: if both arguments have a spatial dimension, they must equal.         @note: if both arguments have a spatial dimension, they must equal.
4734         """         """
4735         sh_arg0=pokeShape(arg0)         sh_arg0=getShape(arg0)
4736         sh_arg1=pokeShape(arg1)         sh_arg1=getShape(arg1)
4737         sh0=sh_arg0[:len(sh_arg0)-axis_offset]         sh0=sh_arg0[:len(sh_arg0)-axis_offset]
4738         sh01=sh_arg0[len(sh_arg0)-axis_offset:]         sh01=sh_arg0[len(sh_arg0)-axis_offset:]
4739         sh10=sh_arg1[len(sh_arg1)-axis_offset:]         sh10=sh_arg1[len(sh_arg1)-axis_offset:]
# Line 4671  class GeneralTensorTransposedProduct_Sym Line 4782  class GeneralTensorTransposedProduct_Sym
4782    
4783  def escript_generalTensorTransposedProduct(arg0,arg1,axis_offset): # this should be escript._generalTensorTransposedProduct  def escript_generalTensorTransposedProduct(arg0,arg1,axis_offset): # this should be escript._generalTensorTransposedProduct
4784      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"      "arg0 and arg1 are both Data objects but not neccesrily on the same function space. they could be identical!!!"
4785      # calculate the return shape:      return C_GeneralTensorProduct(arg0, arg1, axis_offset, 2)
     shape01=arg0.getShape()[arg0.getRank()-axis_offset:]  
     shape0=arg0.getShape()[:arg0.getRank()-axis_offset]  
     shape10=arg1.getShape()[arg1.getRank()-axis_offset:]  
     shape1=arg1.getShape()[:arg1.getRank()-axis_offset]  
     if not shape01==shape10:  
         raise ValueError,"dimensions of first %s components in left argument don't match the first %s components in the right argument."%(axis_offset,axis_offset)  
   
     # whatr function space should be used? (this here is not good!)  
     fs=(escript.Scalar(0.,arg0.getFunctionSpace())+escript.Scalar(0.,arg1.getFunctionSpace())).getFunctionSpace()  
     # create return value:  
     out=escript.Data(0.,tuple(shape0+shape1),fs)  
     #  
     s0=[[]]  
     for k in shape0:  
           s=[]  
           for j in s0:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s0=s  
     s1=[[]]  
     for k in shape1:  
           s=[]  
           for j in s1:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s1=s  
     s01=[[]]  
     for k in shape01:  
           s=[]  
           for j in s01:  
                 for i in range(k): s.append(j+[slice(i,i)])  
           s01=s  
   
     for i0 in s0:  
        for i1 in s1:  
          s=escript.Scalar(0.,fs)  
          for i01 in s01:  
             s+=arg0.__getitem__(tuple(i0+i01))*arg1.__getitem__(tuple(i1+i01))  
          out.__setitem__(tuple(i0+i1),s)  
     return out  
   
4786    
4787  #=========================================================  #=========================================================
4788  #  functions dealing with spatial dependency  #  functions dealing with spatial dependency

Legend:
Removed from v.795  
changed lines
  Added in v.1044

  ViewVC Help
Powered by ViewVC 1.1.26