首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Fortran - Cython工作流

Fortran - Cython工作流
EN

Stack Overflow用户
提问于 2014-03-14 19:44:09
回答 1查看 4.7K关注 0票数 20

我想要设置一个工作流,以便在Windows计算机上使用Cython从Python访问fortran例程

经过一番搜索,我找到了:http://www.fortran90.org/src/best-practices.html#interfacing-with-chttps://stackoverflow.com/tags/fortran-iso-c-binding/info

和一些代码片段:

Fortran端:

pygfunc.h:

代码语言:javascript
复制
void c_gfunc(double x, int n, int m, double *a, double *b, double *c);

pygfunc.f90

代码语言:javascript
复制
module gfunc1_interface
    use iso_c_binding
    use gfunc_module

    implicit none

contains
    subroutine c_gfunc(x, n, m, a, b, c) bind(c)
        real(C_FLOAT), intent(in), value :: x
        integer(C_INT), intent(in), value ::  n, m
        type(C_PTR),    intent(in), value :: a, b
        type(C_PTR),                value :: c

        real(C_FLOAT), dimension(:), pointer :: fa, fb
        real(C_FLOAT), dimension(:,:), pointer :: fc

        call c_f_pointer(a, fa, (/ n /))
        call c_f_pointer(b, fb, (/ m /))
        call c_f_pointer(c, fc, (/ n, m /))
        call gfunc(x, fa, fb, fc)
     end subroutine

end module

gfunc.f90

代码语言:javascript
复制
module gfunc_module

use iso_c_binding

    implicit none
    contains
        subroutine gfunc(x, a, b, c)
            real,                 intent(in) :: x
            real, dimension(:),   intent(in) :: a, b
            real, dimension(:,:), intent(out) :: c

            integer :: i, j, n, m
            n = size(a)
            m = size(b)
            do j=1,m
                do i=1,n
                     c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
                end do
            end do
        end subroutine
end module

Cython端:

pygfunc.pyx

代码语言:javascript
复制
cimport numpy as cnp
import numpy as np

cdef extern from "./pygfunc.h":
    void c_gfunc(double, int, int, double *, double *, double *)

cdef extern from "./pygfunc.h":
    pass

def f(float x, a=-10.0, b=10.0, n=100):
    cdef cnp.ndarray ax, c
    ax = np.arange(a, b, (b-a)/float(n))
    n = ax.shape[0]
    c = np.ndarray((n,n), dtype=np.float64, order='F')
    c_gfunc(x, n, n, <double *> ax.data, <double *> ax.data, <double *> c.data)
    return c

和设置文件:

代码语言:javascript
复制
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np

ext_modules = [Extension('pygfunc', ['pygfunc.pyx'])]

setup(
    name = 'pygfunc',
    include_dirs = [np.get_include()],
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules )

所有文件都在一个目录中

fortran文件编译(使用NAG Fortran Builder ) pygfunc编译

但将它们联系起来会抛出一个问题:

错误LNK2019:函数___pyx_pf_7pygfunc_f中引用的未解析外部符号_c_gfunc

当然还有:

致命错误LNK1120: 1未解析的外部变量

我错过了什么?或者,这种在Python和Fortran之间设置工作流的方式从一开始就遭到了谴责?

THX Martin

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-20 13:18:50

这是一个最小的工作示例。我使用gfortran并将编译命令直接写入设置文件。

gfunc.f90

代码语言:javascript
复制
module gfunc_module
implicit none
contains
subroutine gfunc(x, n, m, a, b, c)
    double precision, intent(in) :: x
    integer, intent(in) :: n, m
    double precision, dimension(n), intent(in) :: a
    double precision, dimension(m), intent(in) :: b
    double precision, dimension(n, m), intent(out) :: c
    integer :: i, j
    do j=1,m
        do i=1,n
             c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
        end do
    end do
end subroutine
end module

pygfunc.f90

代码语言:javascript
复制
module gfunc1_interface
use iso_c_binding, only: c_double, c_int
use gfunc_module, only: gfunc
implicit none
contains
subroutine c_gfunc(x, n, m, a, b, c) bind(c)
    real(c_double), intent(in) :: x
    integer(c_int), intent(in) ::  n, m
    real(c_double), dimension(n), intent(in) :: a
    real(c_double), dimension(m), intent(in) :: b
    real(c_double), dimension(n, m), intent(out) :: c
    call gfunc(x, n, m, a, b, c)
end subroutine
end module

pygfunc.h

代码语言:javascript
复制
extern void c_gfunc(double* x, int* n, int* m, double* a, double* b, double* c);

pygfunc.pyx

代码语言:javascript
复制
from numpy import linspace, empty
from numpy cimport ndarray as ar

cdef extern from "pygfunc.h":
    void c_gfunc(double* a, int* n, int* m, double* a, double* b, double* c)

def f(double x, double a=-10.0, double b=10.0, int n=100):
    cdef:
        ar[double] ax = linspace(a, b, n)
        ar[double,ndim=2] c = empty((n, n), order='F')
    c_gfunc(&x, &n, &n, <double*> ax.data, <double*> ax.data, <double*> c.data)
    return c

setup.py

代码语言:javascript
复制
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# This line only needed if building with NumPy in Cython file.
from numpy import get_include
from os import system

# compile the fortran modules without linking
fortran_mod_comp = 'gfortran gfunc.f90 -c -o gfunc.o -O3 -fPIC'
print fortran_mod_comp
system(fortran_mod_comp)
shared_obj_comp = 'gfortran pygfunc.f90 -c -o pygfunc.o -O3 -fPIC'
print shared_obj_comp
system(shared_obj_comp)

ext_modules = [Extension(# module name:
                         'pygfunc',
                         # source file:
                         ['pygfunc.pyx'],
                         # other compile args for gcc
                         extra_compile_args=['-fPIC', '-O3'],
                         # other files to link to
                         extra_link_args=['gfunc.o', 'pygfunc.o'])]

setup(name = 'pygfunc',
      cmdclass = {'build_ext': build_ext},
      # Needed if building with NumPy.
      # This includes the NumPy headers when compiling.
      include_dirs = [get_include()],
      ext_modules = ext_modules)

test.py

代码语言:javascript
复制
# A script to verify correctness
from pygfunc import f
print f(1., a=-1., b=1., n=4)

import numpy as np
a = np.linspace(-1, 1, 4)**2
A, B = np.meshgrid(a, a, copy=False)
print np.exp(-(A + B))

我所做的大多数改变都不是非常根本的。下面是一些重要的例子。

  • ,你混合了双精度和单精度浮点数。别干那事。将real (Fortran)、float (Cython)和float32 (NumPy)一起使用,并将双精度(Fortran)、double (Cyton)和float64 (NumPy)一起使用。尽量不要在无意中把它们混在一起。我假设你在我的例子中想要双精度的,

  • ,你应该把所有的变量都作为指针传递给Fortran。在这一点上,它与C调用约定不匹配。Fortran中的iso_c_binding模块只符合C语言的命名约定。将数组作为指针传递,并将数组的大小作为单独的值。也许还有其他方法可以做到这一点,但我不知道。

我还在安装文件中添加了一些内容,以显示在构建时可以在何处添加一些更有用的额外参数。

要进行编译,请运行python setup.py build_ext --inplace。要验证它是否正常工作,请运行测试脚本。

下面是fortran90.org上显示的示例:mesh_exp

这是我一段时间前放在一起的两个例子:ftridiagfssor我当然不是这方面的专家,但这些例子可能是一个很好的起点。

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22404060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档