5

I have the following minimal Fortran example that I would like to convert using f2py:

Fortran module utils_test.f90:

module utils_test

contains
    elemental real(8) function prod(a, b)
        real(8), intent(in) :: a, b
        prod = a*b
    end function
end module utils_test

Using f2py:

python3 -m numpy.f2py -c utils_test.f9 -m utils_test

In python, I could use it as follows:

import numpy as np
from utils_test import utils_test

x1 = 5.0
y1 = 3.0

print("Scalar product", utils_test.prod(x1, y1)) # The result is 15.0

x = np.linspace(1, 5, 5) # Numpy array
y = np.linspace(10, 15, 5) # Numpy array

print("Array element-wise product:", utils_test.prod(x, y)) # this outputs 10.0 not an array

The output is:

Scalar product 15.0
Array element-wise product: 10.0

In the second example it outputs only the product of the first elements of x and y only.

I could solve that by vectorizing the function utils_test.prod:

prod = np.vectorize(utils_test.prod)

Is it possible to get the expected result in python without manually vectorizing the function? In other words, is it possible for f2py to automatically vectorize the function provided that the original Fortran function is elemental?

Any help is appreciated.

  • Wouldn't it be better not to declare the function as elemental? – norok2 Dec 17 '19 at 23:44
  • @norok2: That was only a minimal example, the function in Fortran is intended also to be used in other Fortan programs where it is expected to be elemental. However, I am curious to know if there is a solution using f2py to automatically vectorize the function even if it is not declared `elemental`. –  Dec 18 '19 at 00:02
  • OK, so, what are you exactly after? From the question it is unclear whether you just want to get your function to be automatically decorated with `np.vectorize()` (thus with the performance penalty associated with it) or something else. – norok2 Dec 18 '19 at 00:05
  • @norok2: As a side question: How numpy manages to convert its functions (e.g from Lapack to make them vectorized?). –  Dec 18 '19 at 00:09
  • I don't know if f2py supports natively elmental functions in Fortran. If not I am looking for the different options to vectorize the functions in this case –  Dec 18 '19 at 00:10
  • according to the [docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html), `np.vectorize()` uses a simple `for` loop. – norok2 Dec 18 '19 at 00:14
  • When I try to compile it, it looks like `elemental` is ignored: `analyzevars: prefix ('elemental real') were not used` – norok2 Dec 18 '19 at 00:28

0 Answers0