← Back to team overview

dolfin team mailing list archive

Re: numpy ndarray from/to dolfin matrix

 

On Wednesday 14 January 2009 14:07:27 A Navaei wrote:
> Just to add, numpy.array is of type of numpy.ndarray, I don't
> understand why this shouldn't work:
>
> a = numpy.array([3., 4., 5.])
> m = dolfin.Matrix()
> m.set(a, 1, 3)

First the error message corresponds to the type numpy.ndarray, even if it says 
Numpy array.

The PyDOLFIN matrix interface is not intended to be a dynamical highlevel 
interface a là MATLAB or Numpy. We have provided some functionality for basic 
linear algebra, add, sub, mult with scalar and vector, and its corresponding 
ifoo operators. You can multiply a PyDOLFIN.Matrix with a Numpy array, 
triggering an usuall matrix vector multiplication. This operation returns a 
Numpy array. You can also convert a matrix or vector to a numpy equivalent by 
foo.array(). 

You can use v.set(a) where v is a PyDOLFIN.Vector and a is a corresponding 
numpy array. For now you have to take care of the dimension being suitable 
for the PyDOLFIN.Vector, otherwise you can trigger a segfault. (Not your 
fault but rather ours...)

With PyDOLFIN.Matrix it is a bit more tricky. As these structurs are intended 
to be the result of an assemble(form). Think of these objects as quite static 
ones, only mutable by low level library operations.

All this said, you can do what you want above by:

  >>> a = numpy.array([3., 4., 5.])
  >>> m = dolfin.Matrix(1,3)
  >>> m.set(a, numpy.array([0],numpy.uint0), numpy.array([0,1,2],numpy.uint0))
  >>> m.apply()
  >>> m.disp()
  row 0: (0, 3)  (1, 4)  (2, 5)

Note the strange requirement of numpy.uint0.

Good luck!

Johan


> Traceback (most recent call last):
>  File "<console>", line 1, in <module>
>  File "/usr/lib/python2.5/site-packages/dolfin/cpp.py", line 4434, in set
>    return _cpp.Matrix_set(*args)
> TypeError: Numpy array expected
>
>
> 2009/1/14 A Navaei <axnavaei@xxxxxxxxx>:
> - Hide quoted text -
>
> > Hi,
> >
> > Is it possible to convert numpy ndarray from/to dolfin matrix? It
> > seems dolfin matrix only accepts numpy array while ndarray is a better
> > choice.
> >
> >
> > -Ali
>
> _______________________________________________
> DOLFIN-dev mailing list
> DOLFIN-dev@xxxxxxxxxx
> http://www.fenics.org/mailman/listinfo/dolfin-dev




References