Taking function converting it to petsc4py vector, and then putting it back into function?

Howdy,

So essentially my example is more complicated but I have an example - I take a function, make it a petsc4py vector, manipulate it a bit, and then I want to put it back into the function. But it seems that it isn’t trivial, anyone know how to do this easily?

from petsc4py import PETSc
from dolfin import *


size=128
p1 = Point(-1.0,-1.0)
p2 = Point(1.0,1.0)
mesh = RectangleMesh(p1,p2,size,size)
singlespace = FunctionSpace(mesh,'CG',1)
w=Function(singlespace)
w=w.vector()


lb=w.vec()



vec_size = lb.size

for i in range(0,vec_size):
	lb.setValue(i,20.0)


w_new = Function(singlespace)

#how to put lb back into w_new- this doesn't work?
#ValueError: allocator<T>::allocate(size_t n) 'n' exceeds maximum supported size
w_new.vector().set_local(lb)

Consider

w_new = Function(singlespace)  # 0
w_new.vector().axpy(1, w)      # w_new = w_new + 1*w

Hey MiroK,

I wanted to put lb into w_new not w. lb is a petsc4py vector

from petsc4py import PETSc
from dolfin import *


size=128
p1 = Point(-1.0,-1.0)
p2 = Point(1.0,1.0)
mesh = RectangleMesh(p1,p2,size,size)
singlespace = FunctionSpace(mesh,'CG',1)
w=Function(singlespace)
w=w.vector()


lb=w.vec()



vec_size = lb.size

for i in range(0,vec_size):
	lb.setValue(i,20.0)


w_new = Function(singlespace)

#how to put lb back into w_new- this doesn't work?
#ValueError: allocator<T>::allocate(size_t n) 'n' exceeds maximum supported size
w_new.vector().axpy(1,lb)
'''

Traceback (most recent call last):
  File "test.py", line 28, in <module>
    w_new.vector().axpy(1,lb)
TypeError: axpy(): incompatible function arguments. The following argument types are supported:
    1. (self: dolfin.cpp.la.GenericVector, arg0: float, arg1: dolfin.cpp.la.GenericVector) -> None

Invoked with: <dolfin.cpp.la.PETScVector object at 0x11d05ad00>, 1, <petsc4py.PETSc.Vec object at 0x11d05aca8>
'''

Above lb = w.vec() does not give you a copy so manipulating lb is reflected in w and the rest of the code should be fine

print assemble(inner(w_new-Constant(20), w_new-Constant(20))*dx)

To be more detailed, I’m essentially calling TAO which takes a petsc vector and returns a petsc vector, I wanted to save that back into a function.

Hey. I have the same problem. Can you tell me please if you could solve it?

Thanks!

1 Like