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

Hello,

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:
https://fenicsproject.org/olddocs/dolfin/1.4.0/python/programmers-reference/cpp/la/normalize.html

Pol

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")
print(u_vec_max)

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

1 Like

Hello again,

That is indeed what I meant by “normalizing”, however, this returns a different type, namely dolfin.cpp.la.PETScVector, 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)
~/skeleton.py in
15
16 u_normalized = Function(FunctionSpace(fridge_mesh,“CG”,1))
—> 17 u_normalized.vector()[:] = u_normalized
18
19 u2_normalized = Function(FunctionSpace(fridge_mesh,“CG”,1))

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

Invoked with: <dolfin.cpp.la.PETScVector 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