[petsc-dev] [petsc4py] Vec.getArray()

Lisandro Dalcin dalcinl at gmail.com
Sat Aug 28 07:58:29 CDT 2010


On 28 August 2010 06:23, Matthew Knepley <knepley at gmail.com> wrote:
> On Fri, Aug 27, 2010 at 6:14 PM, Lisandro Dalcin <dalcinl at gmail.com> wrote:
>>
>> 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?
>
> I am for 2). PETSc users generally want to sacrifice safety for performance.
>    Matt
>

Matt, that was not a list to choose from. I'm proposing to provide
both models. a=x.getArray() & x.setArray(a) will be the slow and safe,
and a=numpy.asarray(x) will be the fast and safe, Additionally, we
could add with statement support for (2), and other syntax sugar
currently supported that is a=x[...]


-- 
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



More information about the petsc-dev mailing list