Based on your example and the mention of sign and absolute-value, do you maybe mean the positive part of the tensor? If so, the following appears to work
from dolfin import *
# Apply some scalar-to-scalar mapping `f` to each component of `T`:
def applyElementwise(f,T):
from ufl import shape
sh = shape(T)
if(len(sh)==0):
return f(T)
fT = []
for i in range(0,sh[0]):
fT += [applyElementwise(f,T[i]),]
return as_tensor(fT)
# Example where `f` takes the positive part of its argument:
def positive_part(T):
return applyElementwise(lambda x : 0.5*(abs(x)+x) , T)
# Test:
T = as_tensor([[[1,2],[-3,4]],[[-5,6],[-7,8]]])
print(positive_part(T))
If you have some f
that rounds a UFL object to the nearest integer, you could also take the integer part, although I actually don’t know of a way to do that in general. (The floor
, ceil
and round
functions do not appear to be implemented in UFL.) Choosing f
to be round
seems to work for tensors consisting of floating-point literals:
def integer_part(T):
return applyElementwise(round,T)
T = as_tensor([[[1.1,2],[-3,4]],[[-5.7,6],[-7,8]]])
print(integer_part(T))
However trying to apply round
to, say, an Expression
results in an error.