使用f2py在Fortran代码中调用LAPACK函数

2024-09-29 17:15:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Fortran90代码和LAPACK库对矩阵求逆,并使用f2py使其与Python一起使用。下面是我想用f2py在Python中实现的子程序:

subroutine inv(A,Ainv)
    implicit none

  real(kind=8), dimension(:,:), intent(in) :: A
  real(kind=8), dimension(size(A,1) ,size(A,2)),intent(out) :: Ainv

  real(kind=8), dimension(size(A,1)) :: work  ! work array for LAPACK
  integer, dimension(size(A,1)) :: ipiv   ! pivot indices
  integer :: n, info

  ! External procedures defined in LAPACK
  external DGETRF
  external DGETRI

  ! Store A in Ainv to prevent it from being overwritten by LAPACK
  Ainv = A
  n = size(A,1)

  ! DGETRF computes an LU factorization of a general M-by-N matrix A
  ! using partial pivoting with row interchanges.
  call DGETRF(n, n, Ainv, n, ipiv, info)

  if (info /= 0) then
     stop 'Matrix is numerically singular!'
  end if

  ! DGETRI computes the inverse of a matrix using the LU factorization
  ! computed by DGETRF.
  call DGETRI(n, Ainv, n, ipiv, work, n, info)

  if (info /= 0) then
     stop 'Matrix inversion failed!'
  end if
end subroutine inv

当我在fortran程序中编译并运行它时,这段代码可以工作

然后,要使用f2py编译它,我使用以下命令:

f2py -c inverse.f90 -m inverse --fcompiler=gnu95 --compiler=mingw32 -L. -lliblapack

它编译并创建模块inverse.cp38-win_amd64.pyd,通常我应该能够在Python shell中导入它,但我有以下错误:

>>> import inverse
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing inverse: the specified module is not found.

我认为DLL文件是使用的LAPACK库,因此我想知道是否有一种方法可以将LAPACK库链接到与-L/path/to/library and -l<library.dll>不同的f2py

我使用的gfortran编译器与MinGW 64位一起使用,我的python版本是3.8.5和64位,我的LAPACK库也是64位的预构建库,我使用的是Windows 10

谢谢你的帮助

多利安


Tags: ininfosizeifrealworkdimensionf2py

热门问题