[petsc-users] petsc4py and numpy

Lisandro Dalcin dalcinl at gmail.com
Tue May 8 10:10:52 CDT 2012

On 8 May 2012 10:50, Christian Staudt <christian.staudt at ira.uka.de> wrote:
> I am currently getting to know PETSc via petsc4py.  Because I am writing a Python offshoot of a project originally in MATLAB, I have to
> come up with equivalents of built-in MATLAB functions. I am discovering that numpy already provides many equivalents (this page documents some numpy equivalents for common MATLAB expressions: [1])
> However, the goal is shared-memory parallelism, so numpy is not sufficient. This is where PETSc comes in, and the petsc4py bindings are very convenient. As far as I know, petsc4py is based on numpy.

Well, petsc4py is not "based" on NumPy, but uses NumPy to pass arrays
back and forth between Python land and C land.

> My questions to users of petsc4py and numpy:
> a) Is there an easy and efficient way to convert a numpy.ndarray to a PETSc.Vec or PETSc.Mat (and vice-versa)?  (A PETSc.Vec.getArray() returns a numpy.ndarray, though I have found no such method for PETSc.Mat yet. )

To get a NumPy array out of a PETSc.Vec instance, you just call
vec.getArray(), the returned NumPy array shares the memory buffer with
the PETSc Vec, so no copies involved, it is very fast. For the other
way, you can do PETSc.Vec().createWithArray(array), then the Vec will
use the memory buffer of the NumPy array, again no copies involved.

For matrices, it depends on the matrix type. For dense matrices,
currently petsc4py does not support getting the array. For sparse (aka
AIJ) matrices, you can use mat.getValuesCSR(), however this will
involve copies. For the other way, you can use
PETSc.Mat().createAIJ(size=(nrows,ncols), csr=(ai,aj,aa)).

Please take into account that PETSc is basically designed and
optimized to work with SPARSE matrices.

> b) In MATLAB, arrays are used everywhere, also for small collections, where one would use tuples or lists in Python (e.g. multiple return values from a function). When I encounter an array in the original MATLAB code, I have to decide whether a tuple, a list, a numpy.ndarray or a PETSc.Vec/PETSc.Mat is appropriate. One approach would be to use PETSc wherever the array can be larger than a typical tuple. Is there a performance penalty associated with using PETSc Vec/Mat for rather small arrays?

Not really (other than the usual Python calling overhead when you
compare to C or Fotran code)

> Regards & thank you for your answers,
> Chris
> [1] http://www.scipy.org/NumPy_for_Matlab_Users

Lisandro Dalcin
Predio CONICET-Santa Fe
Colectora RN 168 Km 472, Paraje El Pozo
3000 Santa Fe, Argentina
Tel: +54-342-4511594 (ext 1011)
Tel/Fax: +54-342-4511169

More information about the petsc-users mailing list