【问题标题】:F2PY modules in parallel并行 F2PY 模块
【发布时间】:2020-06-23 14:08:02
【问题描述】:

我有一个想要并行运行的现有 Fortran 模块。例如,我想要模块的 8 个实例,每个实例都有自己的变量范围,所有实例都同时工作。 f2py 有可能吗?从文档看来,当您导入模块时,您只能访问 Fortran 对象的单个副本。

我对 Python 很陌生,对 Fortran 也很陌生,所以请告诉我这种方法是否值得研究。

【问题讨论】:

  • 可能,在 Python 中使用一些多处理库并从每个进程加载一个 Fortran 模块?
  • 当然可以。您正常导入 F2PY 创建的库。您可以使用concurrent.futures 中的ProcessPoolExecutor 来运行包括F2PY 函数在内的任何事物的多个实例。无需从不同进程导入。

标签: python fortran f2py


【解决方案1】:

是的,您可以像任何其他并行函数一样从 f2py 对象运行导入的函数,例如使用 concurrent.futures。例如,它在 python 端可以是这样的:

import concurrent.futures as cf
import f2py_module as fm
# Or if a fortran module "my_module" is wrapped, do
from f2py_module import my_module as fm

print (fm.__doc__) # to see functions definitions, comment out

def task(arg):
    """This wrapper is not needed, but usually convenient to define
    redundant arguments or transforming the result somehow"""
    res = fm.calculate(arg) # calculate is a Fortran subroutine
    return res 

PEX = cf.ProcessPoolExecutor(4) # 4 threads here

args = [1,2,3,4,5] 

processes = [PEX.submit(task,arg) for arg in args]
res = [pr.result() for pr in processes]

for re in res:
    print(re)

【讨论】:

  • 根据 OP 所说的“每个都有自己的变量范围”的含义,这种方法可能无法按预期工作。考虑以下 my_module.f90 的输出:module my_module; implicit none; integer :: mod_num = 0; contains; subroutine calculate(num, res); integer, intent(in) :: num; integer, intent(out) :: res; mod_num = mod_num + num; res = mod_num; end subroutine calculate; end module my_module
  • 我同意,好点。如果执行改变了 Fortran 模块的状态,这将产生意想不到的结果。因此,需要确保不要这样做。考虑到 python 导入的工作方式,可能很难为每个进程对模块进行沙箱处理。
  • 但是,对于任何模块中的任何 python 函数,情况都不是这样吗?它们“不能”被重新导入,如果它们改变模块的状态(可能使用global),它们会产生意想不到的行为。可能从全局索引中删除它们然后导入在这两种情况下都可以。
  • 我同意你所说的,只是认为这可能是一个有用的澄清,可以添加到答案中,考虑到我如何理解 OP 提出的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多