Search code examples
pythonarraysfortranf2py

F2PY. Passing array. "failed in converting 2nd argument `xmin' of mga.init to C/Fortran array"


I am using F2PY for the first time. I have a FORTRAN routine similar to:

    SUBROUTINE init(ranMatr,low,upp,nbvar,size)

    IMPLICIT NONE
    INCLUDE 'parameter.h'

    DOUBLE PRECISION ranMatr(dimpop,dim), low(dim), upp(dim),sigma
    INTEGER k, j, nbvar,size

CF2PY   intent(in) low, upp, nbvar, size
CF2PY   intent(in,out) ranMatr

    DO k = 1, size
    DO j = 1, nbvar
        CALL uniforme(1,sigma)
        ranMatr(k,j) = low(j) + sigma * (upp(j) - low(j))        
    ENDDO
    ENDDO
    RETURN
    END

It basically initialize a random matrix called "ranMatr" with values within the range defined by low and upp. Uniforme is a routine returning a value from an uniform distribution.

Now, I installed numpy and f2py and I tried to test it with this code.

I create the python inputs as follows:

ranMatr = [[0 for col in range(0, 5)] for row in range(0,10)]
low = numpy.array([1,2,3,4,5])
upp = numpy.array([6,7,8,9,10])

and then tried to run the routine:

init(ranMatr, low, upp, 5, 20)

But I always get this error message:

0-th dimension must be fixed to 100 but got 5
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
mga.error: failed in converting 2nd argument `low' of mga.init to C/Fortran array

I suppose that the problem is with dimensions but I understand that dim should be the upper bound for "low" vector dimensions.

What I am doing wrong ?


Solution

  • You have to pass low array with dimension dim as specifies in the error message. Some information may be found here, point "2". Or you can always use size instead of dim:

    SUBROUTINE init(ranMatr,low,upp,nbvar,size)
    ...
    INTEGER k, j, nbvar,size
    DOUBLE PRECISION ranMatr(dimpop,size), low(size), upp(size),sigma
    ...