6

Do recent versions of f2py support wrapping array-valued fortran functions? In some ancient documentation this wasn't supported. How about it now?

Let's for example save the following function as func.f95.

function func(x)
    implicit none
    double precision :: x(:),func(size(x))
    integer :: i
    do i=1,size(x)
        func(i) = i*x(i)
    end do
end function

I compile this with f2py --fcompiler=gnu95 -c -m func func.f95

Then let the following python code be test_func.py

import func
from numpy import array

x = array(xrange(1,10),dtype='float64')
print 'x=',x

y = func.func(x)
print 'func(x)=',y

The output from
python test_func.py is

x= [ 1.  2.  3.  4.  5.  6.  7.  8.  9.]
Segmentation fault
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Tentresh
  • 159
  • 1
  • 7
  • you can do [the workaround explained in this answer...](http://stackoverflow.com/q/17474225/832621), but it will require more evaluations than required. For this case I'd go for `Cython` – Saullo G. P. Castro Aug 13 '13 at 04:50

1 Answers1

3

The mechanism of f2py turns Fortran subroutines into python functions. It doesn't understand how to turn a Fortran function into a python function. I have found that I need to wrap all Fortran functions with a subroutine, or even better, rewrite them as subroutines.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
  • Is f2py **that** powerful? Is it reliable enough that writing the whole fortran codebase in this special way is a fair price? – Tentresh Jun 06 '12 at 14:28
  • I've never had problems with reliability, but like I said, it is frustrating. Personally, I only use it for small projects because of the restrictions it imposes. There is another tool, [fwrap](http://fwrap.sourceforge.net/), that is supposed to be better than f2py, but I haven't tested it. – SethMMorton Jun 06 '12 at 14:48