在Ubuntu上集成Fortran與Python可以通過多種方法實現,以下是幾種常見的方法:
f2py是NumPy提供的一個工具,可以將Fortran代碼轉換為Python模塊,從而在Python中調用Fortran程序。以下是具體步驟:
編寫Fortran代碼:創建一個.f90擴展名的Fortran源文件,例如hello.f90:
subroutine hello(a)
implicit none
integer, intent(in) :: a
print *, 'Hello from Fortran90!!!', a
end subroutine hello
編譯Fortran代碼:在終端中運行以下命令來編譯Fortran代碼:
f2py -c hello.f90
這將生成一個名為hello.cpython-<version>-linux-gnu.so的文件。
在Python中調用Fortran函數:在Python控制臺中運行以下代碼:
import hello
hello.hello(15)
輸出將是:
Hello from Fortran90!!! 15
Cython是一個編程語言,它擴展了Python,使得編寫高性能的Python代碼變得更加容易。你可以使用Cython將Fortran代碼封裝在Python中。
編寫Fortran代碼:創建一個名為example.f90的文件:
subroutine add(a, b, c) bind(c, name="add")
use, intrinsic :: iso_c_binding
real(c_double), intent(in) :: a, b
real(c_double), intent(out) :: c
c = a + b
end subroutine add
編寫Cython接口代碼:創建一個名為example_wrapper.pyx的文件:
cdef extern from "example.f90":
void add_(double *a, double *b, double *c)
def py_add(double a, double b):
cdef double c
add_(&a, &b, &c)
return c
創建setup.py文件:
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("example_wrapper.pyx"),
include_dirs=[],
libraries=["example"],
library_dirs=['.']
)
編譯Cython代碼:
python setup.py build_ext --inplace
在Python中使用生成的模塊:
import example_wrapper
result = example_wrapper.py_add(4.0, 5.0)
print(f"{4.0} * {5.0} = {result}")
輸出將是:
4.0 * 5.0 = 20.0
ctypes是Python內置的一個庫,可以用來調用外部C動態鏈接庫,因此也可以用于調用Fortran程序。
編寫Fortran代碼:創建一個Fortran源文件,例如circle.f90:
subroutine area_of_circle(r, area) use iso_c_binding
implicit none
real(c_double), intent(in) :: r
real(c_double), intent(out) :: area
area = 4 * atan(1.0) * r**2
end subroutine area_of_circle
編譯Fortran代碼為動態鏈接庫:
gfortran -shared -fPIC -o circle.so circle.f90
在Python中調用Fortran函數:編寫Python調用腳本test_mat.py:
import numpy as np
from numpy.ctypeslib import load_library, ndpointer
from ctypes import c_int
# 加載動態鏈接庫
lib = load_library("circle", "./circle.so")
# 指定參數和返回數據類型
lib.area_of_circle.argtypes = [ndpointer(dtype=np.float64, ndim=1), c_int]
lib.area_of_circle.restype = c_double
# 創建一個二維數組
data = np.empty(shape=(4, 5), dtype=np.float64, order='F')
# 將數組首地址傳入Fortran中進行計算
lib.area_of_circle(data.ctypes.data, 4)
# 打印結果
print("Area of circle with radius 2.0 is", data[0, 0])
運行Python腳本:
python test_mat.py
輸出將是:
Area of circle with radius 2.0 is 31.41592653589793
通過以上方法,你可以在Ubuntu上成功地將Fortran代碼集成到Python中。選擇哪種方法取決于你的具體需求和偏好。