I cannot figure out how to implement a copy-free and safe VecGetArray()/VecRestoreArray() pattern in Python (not even by using the 'with' statement, it leaks the target variable!!!!).
1) Provide a 100% safe but slow, copy-based way: a = x.getArray() #gives you a copy. It is implemented with VecGetArrayRead(x, &p), memcpy p->a.data, VecRestoreArray(x,&p) on a freshly allocated numpy array that is returned to the user. a.base is None # True, the array owns its memory buffer x.setArray(a) #writes array on the vector. It is implemented with VecGetArray(x,&p) and memcpy a.data -> p, VecRestoreArray(x,&p) 2) Provide a unsafe but fast, copy-free way to get a numpy array sharing memory with PETSc vectors: a = numpy.asarray(x) # gives you a numpy array that shares mem with the vec, it is implemented with VecGetArray() and special Python/NumPy protocols for buffer sharing. a.base is x # True, the base attr holds a ref to the Vec instance, the array does not own its memory buffer. del a # force garbage collection explicitily, then VecRestoreArray() will be called when a gets deallocated. Relying in explicit use of del for garbage collection is not reliable. NumPy is designed to support array views, these views hold references to the base array. So users have to be very careful about how the arrays obtained the fast way are used. Comments ? Suggestions? Complaints? -- Lisandro Dalcin --------------- CIMEC (INTEC/CONICET-UNL) Predio CONICET-Santa Fe Colectora RN 168 Km 472, Paraje El Pozo Tel: +54-342-4511594 (ext 1011) Tel/Fax: +54-342-4511169
