随机游走-并行处理

use*_*423 5 python parallel-processing montecarlo

我目前正在实施蒙特卡洛方法来求解扩散方程。该解可以表示为phi(W)的数学期望,其中phi是一个函数(根据扩散方程而变化),而W是在域边界处停止的对称随机游动。为了评估x点处的函数,我需要按照x的期望开始每一次步行。

我想对函数进行大量评估。所以这就是我要做的:

  1. 我从每一点开始同时散步
  2. 我对每一点都使用相同的步骤
  3. 每次步行到达边界后,我都会停下来
  4. 我将这些操作重复N次,以便通过N次模拟的频率来近似数学期望。

我的代码(Python)如下所示:

for k in range(N): #For each "walk"
    step = 0
    while not(every walk has reach the boundary):
        map(update_walk,points) #update the walk starting from each x in points
        incr(step)
Run Code Online (Sandbox Code Playgroud)

问题是:由于N可能很大,并且点数也很长,所以它非常长。我正在寻找可以帮助我优化此代码的任何解决方案。

我曾考虑过使用IPython进行并行处理(每次遍历是独立的),但是我没有成功,因为它在函数内部(它返回了类似的错误

“无法启动功能'f',因为未将其作为'file.f'找到”,但'f'在file.big_f中定义)

omu*_*gru 0

在单独的进程中启动计算(这是您想要避免 GIL 的方法)可能会利用多处理模块。可以使用以下代码启动 X 个并行进程:

from multiprocessing import Process
from Queue import Queue
queue = Queue(maxsize=MAX_NODES) # this is the number of processes you will spawn
procs = [Process(target=f, args=(node, queue) for node in nodes] # node will be the node for each process , the queue is common to all of the processes
[p.start() for p in procs] # start them
results = []
for i in range(len(nodes):
    results.append(queue.get())
Run Code Online (Sandbox Code Playgroud)

您需要做的就是修改 func(目标函数)以获取相关数量的参数加上队列,并在计算结束时调用queue.put(result)

希望这是有道理的