How can I perform operations on dolfin functions? - Follow up


Currently, I have a dolfin.function.function.Function that I obtain from solving a variational problem. What I want to do is normalize it, i.e. divide each entry by the largest entry. The following page suggests there is a function to do so but the documentation is not clear enough for me:

Thanks for your help,

The following code doesn’t use the normalize function, but it does what it sounds like you’re looking for:

from dolfin import *

# Function in a CG1 space going from 0 to 2:
mesh = UnitIntervalMesh(4)
u = project(2.0*SpatialCoordinate(mesh)[0],FunctionSpace(mesh,"CG",1))

# The $\ell^\infty$ ("linf") norm is the maximum absolute
# value of all entries in a vector.
u_vec_max = u.vector().norm("linf")

# The `*` operator is overloaded to implement scalar
# multiplication, returning another vector.
u_vec_normalized = (1.0/u_vec_max)*u.vector()
1 Like

Hello again,

That is indeed what I meant by “normalizing”, however, this returns a different type, namely, while I need it to remain dolfin.function.function.Function

You can assign data from one vector to another vector (such as the vector associated with a Function) as follows:

u_normalized = Function(FunctionSpace(mesh,"CG",1))
u_normalized.vector()[:] = u_vec_normalized
1 Like

@kamensky , I get the following error:
fridge_mesh is the mesh I am currently using.

TypeError Traceback (most recent call last)
~/ in
16 u_normalized = Function(FunctionSpace(fridge_mesh,“CG”,1))
—> 17 u_normalized.vector()[:] = u_normalized
19 u2_normalized = Function(FunctionSpace(fridge_mesh,“CG”,1))

TypeError: setitem(): incompatible function arguments. The following argument types are supported:
1. (self:, arg0: slice, arg1: float) → None
2. (self:, arg0: slice, arg1: → None
3. (self:, arg0: slice, arg1: numpy.ndarray[numpy.float64]) → None
4. (self:, arg0: numpy.ndarray[numpy.int32], arg1: float) → None
5. (self:, arg0: numpy.ndarray[numpy.int32], arg1: numpy.ndarray[numpy.float64]) → None

Invoked with: < object at 0x7fa3f01c78b0>, slice(None, None, None), Coefficient(FunctionSpace(Mesh(VectorElement(FiniteElement(‘Lagrange’, tetrahedron, 1), dim=3), 14), FiniteElement(‘Lagrange’, tetrahedron, 1)), 52)

The line

u_normalized.vector()[:] = u_normalized

triggering the error looks like a typo, where the right-hand argument to the assignment (=) should be a vector (e.g., u_vec_normalized in my earlier example), but is instead a Function (and the same one you are attempting to assign the vector of, which wouldn’t make sense).

1 Like