【问题标题】:How pass an array and its dimension from Python to Fortran and use it among subroutines?如何将数组及其维度从 Python 传递到 Fortran 并在子例程中使用它?
【发布时间】:2022-11-09 03:46:06
【问题描述】:

所以我想要实现的是以下几点:

  1. 在 Python 中定义一个数组;
  2. 传递该数组及其维度通过f2py 进入 Fortran;
  3. 在 Fortran 代码中的各种子例程中使用该数组。 (Fortran 代码不会更改数组。)

    我已经知道在this answer 的公共块中这是不可能的。 Fortran 代码由许多单独的脚本组成,因此我也不能使用contains。 是否有可能以其他方式实现? 提前致谢!

【问题讨论】:

    标签: python arrays fortran f2py


    【解决方案1】:

    是的,这是可能的。这是一种方法。

    像这样创建fortran代码......

    !example.f90
    subroutine compute(x_1d, x_2d, nx, ny)
    
      implicit none
      integer, parameter :: dp = selected_real_kind(15, 307) !double precision
    
      ! input variables
      integer, intent(in)       :: nx
      integer, intent(in)       :: ny
      real(kind=dp), intent(in) :: x_1d(nx), x_2d(nx, ny)
    
      !f2py intent(in) x_1d, x_2d
    
      print *, 'Inside fortran code'
      print *, 'shape(x_1d) = ',  shape(x_1d)
      print *, 'shape(x_2d) = ',  shape(x_2d)
    
    end subroutine compute
    

    使用 f2py 编译它以制作一个可以导入 python 的模块。

    python -m numpy.f2py -m example -h example.pyf example.f90
    python -m numpy.f2py -c --fcompiler=gnu95 example.pyf example.f90
    

    现在你应该有一个名为example.cpython-39-x86_64-linux-gnu.so 的共享对象文件,可以像这样直接导入python:

    #example.py
    from example import compute
    import numpy as np
    
    def main():
    
        nx = 2
        ny = 4
    
        x = np.random.rand(nx)
        y = np.random.rand(nx, ny)
    
        print(compute.__doc__)
    
        compute(x, y)
    
        return
    
    if __name__ == "__main__":
        main()
    

    运行python example.py 给出:

    compute(x_1d,x_2d,[nx,ny])
    
    Wrapper for ``compute``.
    
    Parameters
    ----------
    x_1d : input rank-1 array('d') with bounds (nx)
    x_2d : input rank-2 array('d') with bounds (nx,ny)
    
    Other Parameters
    ----------------
    nx : input int, optional
        Default: shape(x_1d, 0)
    ny : input int, optional
        Default: shape(x_2d, 1)
    
     Inside fortran code
     shape(x_1d) =            2
     shape(x_2d) =            2           4
    

    请注意,您不需要显式传递维度。它由f2py 和我们放入fortran 代码!f2py 的指令自动处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 2018-01-15
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2017-06-11
      • 2014-01-06
      相关资源
      最近更新 更多