← Back to team overview

dolfin team mailing list archive

Re: Vector to numpy array and vice verse

 

> 2008/8/8 Kent-Andre Mardal <kent-and@xxxxxxxxx>:
>> On fr., 2008-08-08 at 10:15 +0200, Martin Sandve Alnæs wrote:
>>> 2008/8/8 Kent-Andre Mardal <kent-and@xxxxxxxxx>:
>>> > On fr., 2008-08-08 at 09:50 +0200, 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.
>>> >>
>>> >> 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.
>>> >>
>>> >
>>> > We could add something like this to the SWIG interface file.
>>> >
>>> > %extend dolfin::Vector {
>>> >  %pythoncode %{
>>> >
>>> >    def __init__(self, v):
>>> >      a = Vector(len(v))
>>> >      a.set(v)
>>> >      return a
>>> >  %}
>>> > }
>>> >
>>> >
>>> > This might remove other constructors ? I'm not exactly sure how SWIG
>>> > deal with constructors both in Python and C++.
>>> >
>>> > Kent
>>>
>>> Python doesn't even have function overriding, so that doesn't make
>>> much sense (there would be two conflicting __init__ functions).
>>>
>>
>> I know Python does not support overloading, but you can write a __init__
>> function that parses the arguments and either does something in Python
>> or pass the arguments to the constructors in the extension module.
>> Whether SWIG will do this when parsing both constructors in Python and
>> C++ I don't know, probably not automatically. It should still be
>> possible, but maybe not worth the effort.
>>
>> Kent
>
> SWIG can't possibly implement this kind of code rewriting logic.
>
> Doing it manually requires either removing the constructors SWIG
> generates somehow (don't know if that's even possible), or making a
> subclass like Function, which hides the constructor signatures from
> the documentation.
>
> --
> Martin
>


SWIG does not really make constructors. It makes C functions like
new_Vector. Then SWIG creates a small Python layer on top with a
__init__ function that calls this C function. It looks like this:

class Vector(GenericVector,Variable):
    def __init__(self, *args):
          this = _dolfin.new_Vector(*args)

My guess was that one might alter this Python layer in some way.
It certainly is not hard to do it by hand, but I have not tried with SWIG.


Kent








References