pythonnumpyfortranf2py

I am encountering an f2py dimension error when passing numpy array to fortran


I have been trying to wrap a fortran module that takes several 1-dimensional arrays and returns calculated values CTP and HILOW.

subroutine ctp_hi_low ( nlev_in, tlev_in, qlev_in, plev_in,  &
                          t2m_in , q2m_in , psfc_in, CTP, HILOW , missing )

   implicit none
!
! Input/Output Variables
!
   integer, intent(in )                      ::  nlev_in   ! *** # of pressure levels
   real(4), intent(in )                      ::  missing   ! *** missing value - useful for obs
   real(4), intent(in ), dimension(nlev_in)  ::  tlev_in   ! *** air temperature at pressure levels [K]
   real(4), intent(in ), dimension(nlev_in)  ::  qlev_in   ! *** specific humidity levels [kg/kg]
   real(4), intent(in ), dimension(nlev_in)  ::  plev_in   ! *** pressure levels [Pa]
   real(4), intent(in )                      ::  psfc_in   ! *** surface pressure [Pa]
   real(4), intent(in )                      ::  t2m_in    ! *** 2-meter temperature [K]
   real(4), intent(in )                      ::  q2m_in    ! *** 2-meter specific humidity [kg/kg]
   real(4), intent(out)                      ::  CTP       ! *** Convective Triggering Potential [K]
   real(4), intent(out)                      ::  HILOW     ! *** Low-level humidity [K]

<internal variables and calculations>

The wrapping was successful, but when running the program I receive the following error.

I have been passing dummy data to ensure that all arrays have the same shape.

Traceback (most recent call last):
  File "/mnt/d/ResearchProjects/NSF-Drought/coupling-metrics/minimal/test.py", line 47, in <module>
    conv_trig_pot_mod.ctp_hi_low(10, arr, arr, arr, 1,1, 1)
ValueError: ctp_hilow.ctp_hilow.conv_trig_pot_mod.ctp_hi_low: failed to create array from the 2nd argument `qlev_in` -- 0-th dimension must be fixed to 1 but got 10

I have been trying to pass my 1-D arrays in varying dimensions, but all of them produce the same error.

arr  = np.ones([10,], order='F')
arr  = np.ones([10,1], order='F')
arr  = np.ones([1,10], order='F')

I also have been trying to pass a list.

I simply cannot figure out how to satisfy f2py's shape requirement.

Any help is appreciated


Solution

  • It is better to call fortran subroutine from python with explicit argument name:

    conv_trig_pot_mod.ctp_hi_low(nlev_in=10, tlev_in=arr, qlev_in=arr, plev_in=arr, t2m_in=1, q2m_in=1, psfc_in=????, missing=1)
    

    The order of arguments differs between Fortran and Python. you can check the new arguments list and order __doc__ in python:

    # import may be different for different python version
    from xxxx import yyyy as ctp_module
    print(ctp_module.ctp_hi_low.__doc__)