pythonnumpyfortranf2py

f2py - understanding how to pass an integer (and avoiding message Deprecated NumPy 1.25.)


I am using f2py to link my old Fortran codes to Python. Although I did not have much trouble doing it, I still don't know how to handle integers. For instance, below is a piece of Fortran code where some integers are used with intent(inout) (mlag, nyt, nut, and net).

subroutine maxlags(iext, nump, degree, nsuby, mlag, npt, nnt, nyt, nut, net)
implicit none
integer, intent(in) :: nump, degree, nsuby
integer, intent(in) :: iext(nump, degree, nsuby)
integer, intent(inout) :: mlag, npt(nsuby), nnt(nsuby), nyt, nut, net
...
end subroutine maxlags

In python, if I define them as

nst = np.array([0])
nyt = np.array([0])
nut = np.array([0])
net = np.array([0])

calling the subroutine works, the values of mlag, nyt, nut and net are updated, but a warning msg comes out

/var/folders/sj/q_5xy_n50ps10lg75p99wbw80000gn/T/ipykernel_87520/378702212.py:18: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.)

If I define them as

nst = np.int32(0)
nyt = np.int32(0)
nut = np.int32(0)
net = np.int32(0)

there is no warning msg anymore, however the values of mlag, nyt, nut and net are no longer updated.

How do I get rid of the warning msg? Or is there another to define integers to avoid the warning msg and get their values updated?

Many thanks.

PS. Output of print(.maxlagm.doc)

maxlagm(iext,nst,npt,nnt,nyt,nut,net,[nump,degree,nsuby])

Wrapper for maxlagm.

Parameters

iext : input rank-3 array('i') with bounds (nump,degree,nsuby) nst : in/output rank-0 array(int,'i') npt : in/output rank-1 array('i') with bounds (nsuby) nnt : in/output rank-1 array('i') with bounds (nsuby) nyt : in/output rank-0 array(int,'i') nut : in/output rank-0 array(int,'i') net : in/output rank-0 array(int,'i')

Other Parameters

nump : input int, optional Default: shape(iext, 0) degree : input int, optional Default: shape(iext, 1) nsuby : input int, optional Default: shape(iext, 2)


Solution

  • Try making them 0d arrays like:

    nst = np.array(0)
    

    Notice that the square brackets have been removed.

    Alternatives include squeezeing or reshapeing the 1d arrays after creating them, but this is more direct.