首页 文章

如何将我的(7,3,3,3)数组传递给fortran子程序?

提问于
浏览
1

我已经通过f2py命令在python中编写了一个fortran子例程 .

子程序采用numpy ndarray形状(7,3,3,3) . 该数组是7个立方体的数组,大小为3x3x3 . 我还将整数7和3传递给子程序 .

这是代码

subroutine fit(n, m, a)

c ===================================================================
c                            ArrayTest.f
c ===================================================================
c       n            - number of cubes being passed
c
c       m            - edge of cube size
c
c       a(n,m,m,m)   - array of shape (n,m,m,m)
c
c ===================================================================

        implicit none
        integer m
        integer n
        double precision a(n,m,m,m)

        end subroutine fit

这只是为了看看我是否可以传递数组 . 当我从python编译并调用它时,我收到以下错误 .

import ArrayTest as AT 
import numpy as np

n = 7
m = 3
a = np.ones((n,m,m,m))

AT.fit(n, m, a)

ArrayTest.error: (shape(a,0)==n) failed for 1st keyword n: fit:n=3

我不知道发生了什么事 . 将fortran中的数组定义为(m,m,m,m)会引发没有问题,只有当我尝试从两个整数定义它才会导致问题时,即使我同时设置m = n = 3 . 将(7,3,3,3)数组传递给fortran子程序?

1 回答

  • 2

    看一下f2py创建的Python函数的docstring:

    fit(a,[n,m])
    
    Wrapper for ``fit``.
    
    Parameters
    ----------
    a : input rank-4 array('d') with bounds (n,m,m,m)
    
    Other Parameters
    ----------------
    n : input int, optional
        Default: shape(a,0)
    m : input int, optional
        Default: shape(a,1)
    

    f2py认识到 nm 描述了 a 的形状,因此不是Python函数的必需参数,因为可以通过检查numpy数组的形状找到它们 . 所以它们是Python函数 fit 的可选第二和第三个参数:

    In [8]: import ArrayTest as AT
    
    In [9]: n = 7
    
    In [10]: m = 3
    
    In [11]: a = np.zeros((n, m, m, m))
    
    In [12]: AT.fit(a, n, m)
    
    In [13]: AT.fit(a)
    

相关问题