Mar*_*cel 2 python fortran f2py
我编写了一个小型 Fortran 函数,并使用 f2py 在 Python 中向它传递参数。不知怎的,参数的顺序在传输过程中被搞乱了,我不明白为什么。
Fortran 函数的相关部分(位于名为 calc_密度.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
Run Code Online (Sandbox Code Playgroud)
f2py编译命令:
f2py -c --fcompiler=gnu95 -m fortran_calc_density calc_density.f95
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
显示所有传输变量不匹配的屏幕输出示例:
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
Run Code Online (Sandbox Code Playgroud)
Python 的打印输出显示了这些值,但密度数组的长度除外,密度数组的长度应等于 ncells,因此根据 Fortran 函数的设计为 20,与它们应该的完全一样。然而,Fortran 值完全偏离,因此在传输过程中一定发生了一些事情,从而扰乱了争论。
我在这里做错了什么?
查看 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)
Run Code Online (Sandbox Code Playgroud)
您可以看到这nparticles
是可选的(这是由 f2py 自动完成的)并且默认值为len(position)
. 默认情况下,可选参数被移动到参数列表的末尾。因此,在您的调用中,最后一个参数被解释为nparticles
。
您可以省略nparticles
函数调用或将其移至最后一个参数。两个都:
density = densityCalc(position, ncells, L)
density = densityCalc(position, ncells, L, nparticles)
Run Code Online (Sandbox Code Playgroud)
应该会产生正确的结果。如果你想保持 fortran 子例程参数列表的顺序,你也可以使用关键字:
density = densityCalc(position=position, nparticles=nparticles, ncells=ncells, l=L)
Run Code Online (Sandbox Code Playgroud)
请注意,fortran 不区分大小写,因此关键字必须小写l = L
。