[英]making python and fortran friends
Assume we need to call fortran function, which returns some values, in python program. 假设我们需要在python程序中调用fortran函数,它返回一些值。 I found out that rewriting fortran code in such way: 我发现以这种方式重写fortran代码:
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
!f2py real, intent(in, out) :: out_x
real, intent(out) :: out_x
out_x = in_x ** 2
return
end
and calling it in python in such way: 并以这种方式在python中调用它:
import modulename
a = 2.0
b = 0.0
b = modulename.pow2(a, b)
gives us working result. 给我们工作的结果。 Can I call fortran function in other way, cause I think the first way is a bit clumsy? 我可以用其他方式调用fortran函数,因为我认为第一种方式有点笨拙吗?
I think you just need to change your f2py function signature slightly (so that out_x
is only intent(out)
and in_x
is only intent(in)
): 我认为你只需稍微改变你的f2py函数签名(这样out_x
只是intent(out)
而in_x
只是intent(in)
):
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
!f2py real, intent(in) :: in_x
real, intent(out) :: out_x
!f2py real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
Now compile: 现在编译:
f2py -m test -c test.f90
Now run: 现在运行:
>>> import test
>>> test.pow2(3) #only need to pass intent(in) parameters :-)
9.0
>>>
Note that in this case, f2py
is able to correctly scan the signature of the function without the special !f2py
comments: 请注意,在这种情况下, f2py
能够正确扫描函数的签名,而无需特殊的!f2py
注释:
!test2.f90
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
Compile: 编译:
f2py -m test2 -c test2.f90
run: 跑:
>>> import test2
>>> test2.pow2(3) #only need to pass intent(in) parameters :-)
9.0
>>>
Another benefit to avoiding intent(inout)
arguments is (with a few other restrictions) the resulting function can be considered PURE
. 避免intent(inout)
参数的另一个好处是(有一些其他限制),结果函数可以被认为是PURE
。 This is related to the no-side-effects approach taken by functional languages and pays off with better optimization and error detection by the Fortran compiler and is especially important for auto-parallelization. 这与函数式语言采用的无副作用方法有关,并且通过Fortran编译器进行更好的优化和错误检测而获得回报,这对于自动并行化尤其重要。
If you're using IPython, try magic command, which makes it able to write 如果您正在使用IPython,请尝试使用magic命令,这样就可以编写
%%fortran
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
and then simply use this function in your code (without additional imports). 然后只需在代码中使用此函数(无需其他导入)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.