← Back to team overview

dolfin team mailing list archive

Re: Vector to numpy array and vice verse

 

On Friday 08 August 2008 10:15:11 Martin Sandve Alnæs wrote:
> 2008/8/8 Johan Hake <hake@xxxxxxxxx>:
> > On Friday 08 August 2008 09:50:58 Martin Sandve Alnæs wrote:
> >> How would you do this? The way the dolfin.Function class is created
> >> destroys the documentation of constructor signatures, which in my
> >> opinion is really really bad.
> >
> > I agree. We should add at least add some good documentation to the python
> > version of Function.
> >
> > They way I thought of was to just check for the type ndarray in addition
> > to dolfin.Vector, dolfin.GenericVector in __init__, and then if it is a
> > numpy array create a vector and pass that one.
>
> In which __init__? If you mean dolfin.Function.__init__, I don't see a
> problem with adding the two-liner "v = Vector(n); v.set(x)".

I agree.

> > As you say this can be done using the same interface of Vector of course.
> > However I thought it would be "natural" to be able to create a Vector
> > from a numpy array.
>
> I think the best solution would be adding a constructor to
> dolfin::Vector that takes a pointer to some data to copy, and
> typemapping this properly with SWIG to recognize numpy arrays (or
> really any python sequence).

This is probably the best solution. I just thought of doing it without 
touching the c++ interface.

Johan

> > Johan
> >
> >> You could just add:
> >>
> >> def as_vector(x):
> >>     v = Vector(len(x))
> >>     v.set(x)
> >>     return v
> >>
> >> then we can do
> >> x = zeros(10)
> >> v = as_vector(x)
> >>
> >> and the dolfin.Function constructor can just as easily do this step.




References