在将numpy数组传递给fortran时遇到f2py维度错误

2 投票
1 回答
31 浏览
提问于 2025-04-12 09:25

我一直在尝试包装一个Fortran模块,这个模块需要几个一维数组作为输入,并返回计算出的值CTP和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>

包装工作成功了,但在运行程序时,我遇到了以下错误。

我一直在传递一些虚拟数据,以确保所有数组的形状都是一样的。

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

我尝试传递不同维度的一维数组,但所有的数组都产生了相同的错误。

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

我也尝试过传递一个列表。

我就是搞不懂如何满足f2py对数组形状的要求。

任何帮助都非常感谢。

1 个回答

1

从Python调用Fortran子程序时,最好使用明确的参数名称:

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)

因为Fortran和Python的参数顺序是不同的。你可以在Python中查看新的参数列表和顺序,方法是使用__doc__:

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

撰写回答