f2py - 函数参数的顺序搞砸了

时间:2016-02-20 20:58:19

标签: python fortran f2py

我编写了一个小的Fortran函数,并使用f2py在Python中传递参数。不知怎的,在转移过程中参数的顺序搞得一团糟,我无法弄清楚原因。

Fortran函数的相关部分(位于名为calc_density.f95的文件中):

subroutine calc_density(position, nparticles, ncells, L, density)

implicit none

integer, intent(in) :: nparticles
integer, intent(in) :: ncells
double precision, intent(in) :: L
double precision, dimension(nparticles), intent(in) :: position
double precision, dimension(ncells), intent(out) :: density

double precision :: sumBuf, offSum
integer :: pLower, pUpper, pBuf, numBuf, last, idx
double precision, dimension(nparticles) :: sorted

 print *, 'Fortran ', 'position length ', size(position), &
  'density length ', size(density), 'nparticles ', nparticles, &
  'ncells ', ncells, 'L ', L

end subroutine calc_density

f2py编译命令:

f2py -c --fcompiler=gnu95 -m fortran_calc_density calc_density.f95

Python代码的相关部分:

from fortran_calc_density import calc_density as densityCalc
from numpy import array, float64

def calc_density(position, ncells, L):
  arg = array(position, dtype = float64, order = 'F')
  nparticles = len(position)
  density = densityCalc(position, nparticles,  ncells, L)

  print 'Python ', 'position length ', len(position), 'density length',  len(density), 'nparticles ', nparticles, 'ncells ', ncells, 'L ', L   
  return density

屏幕输出示例显示所有传输变量不匹配:

Fortran position length           12 density length          100 nparticles           12 ncells          100 L    20.000000000000000    
Python  position length  100 density length  100 nparticles  100 ncells  20 L  12.5663706144

Python中的打印输出显示了值,除了密度数组的长度应该等于ncells,因此Fortran函数的设计是20,完全应该是这样。 然而,Fortran的值完全是关闭的,所以在传输过程中必然会发生一些事情,这些事情扰乱了争论。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:4)

查看由f2py创建的文档(使用gfortran-5.3.0编译):

>>> print calc_density.__doc__

Wrapper for ``calc_density``.

Parameters
----------
position : input rank-1 array('d') with bounds (nparticles)
ncells : input int
l : input float


Other Parameters
----------------
nparticles : input int, optional
    Default: len(position)

Returns
-------
density : rank-1 array('d') with bounds (cells)

您可以看到nparticles是可选的(这由f2py自动完成),默认值为len(position)。默认情况下,可选参数将移动到参数列表的末尾。因此,在您的调用中,最后一个参数被解释为nparticles

您可以将nparticles退出函数调用,也可以将其移至最后一个参数。这两种:

density = densityCalc(position, ncells, L)
density = densityCalc(position, ncells, L, nparticles)

应该会产生正确的结果。如果要保持fortran子例程参数列表的顺序,还可以使用关键字:

density = densityCalc(position=position, nparticles=nparticles, ncells=ncells, l=L)

请注意,fortran不区分大小写,因此关键字必须为小写l = L

相关问题