Create a New Gridfunction from an existing vector

My code involves some computations on vectors, thus I have a BaseVector v. Now I would like to create a Gridfunction using this vector. Essentially, I know the FEM so currently I do:

gf = GridFunction(fem)
gf.vec.data = v

However, this creates a copy of the vector. So far, I have not been able to find a method to do that. Does there exist a way to link the vector of a Gridfunction to the existing vector, preferably already at initialization?

A GridFunction always has its own basevector member. If you want to do calculations on this basevector use gf.vec in the calculations. I think there is currently no possiblity to set the vector from Python.

Ok then, I have to find a workaround. Does such a feature exist in the C code, and if so, could you maybe expose that to the Python interface?

This actually works out of the box.

gf = GridFunction(fes)
gf.Set(cos(x)*sin(y))

v = gf.vec.FV().NumPy()[:]
Draw(gf) # Values between -1 and 1
v *= 2

Draw(gf) # Values between -2 and 2

Thanks Christian for your nice response. I know this and will construct a workaround with it. But my initial question was not: Given a gridfunction how to get an object that points to its vector, but rather given a vector, create a grid whose vector is pointing to this vector.

I think this is not possible now, but the following snippet comes close. A multidim-Gridfunction contains several solution vectors, and one may add another:

from ngsolve import *
mesh = Mesh(unit_square.GenerateMesh(maxh=0.2))
fes = H1(mesh, order=1)

gf = GridFunction(fes, multidim=0)
print (gf.vecs, len(gf.vecs))

v = BaseVector(fes.ndof)
gf.AddMultiDimComponent(v, copy=False)
print (gf.vecs, len(gf.vecs))

The copy=False option is new and will be available in the upcoming prerelease. By now, always a copy of the existing vector was created.

best, Joachim

the prerelease is available

1 Like