首先,我要感谢StackOverflow社区多年来为我提供的巨大帮助,我不必问任何问题.
我对多进程比较陌生;不久前,我成功地使用了多重处理.以一种非常简单的方式创建池,在子进程之间我不需要任何反馈.
我试图从一个类中构建一个并行回火蒙特卡罗算法.
基本类大致如下:
import numpy as np
class monte_carlo:
def __init__(self):
self.x=np.ones((1000,3))
self.E=np.mean(self.x)
self.Elist=[]
def simulation(self,temperature):
self.T=temperature
for i in range(3000):
self.MC_step()
if i%10==0:
self.Elist.append(self.E)
return
def MC_step(self):
x=self.x.copy()
k = np.random.randint(1000)
x[k] = (x[k] + np.random.uniform(-1,1,3))
temp_E=np.mean(self.x)
if np.random.random()<np.exp((self.E-temp_E)/self.T):
self.E=temp_E
self.x=x
return
显然,我简化了很多(实际的类有500行!),为了简单起见,我们构建了假函数:__init__
将一组参数作为参数,除了自身之外,还有更多的度量列表.Elist,以及许多从self派生的array.我用来计算它们的X.关键的一点是,这个类的每个实例都包含很多我想保存在内存中的信息,我不想一次又一次地复制这些信息,以避免急剧减速.否则我只会使用多重处理.池模块.
现在,我想用伪代码进行并行化:
def proba(dE,pT):
return np.exp(-dE/pT)
Tlist=[1.1,1.2,1.3]
N=len(Tlist)
G=[]
for _ in range(N):
G.append(monte_carlo())
for _ in range(5):
for i in range(N): # this loop should be ran in multiprocess
G[i].simulation(Tlist[i])
for i in range(N//2):
dE=G[i].E-G[i+1].E
pT=G[i].T + G[i+1].T
p=proba(dE,pT) # (proba is a function, giving a probability depending on dE)
if np.random.random() < p:
T_temp = G[i].T
G[i].T = G[i+1].T
G[i+1].T = T_temp
综合:我想在并行子进程中运行monte-carlo类的多个实例,参数T的值不同,然后定期暂停所有操作以更改不同的T,然后从暂停的地方再次运行子进程/类实例.
提前谢谢,如果我不清楚,很抱歉...
编辑:
编辑2:
Edit3:Charchit answer对测试代码非常有效,无论是在我的个人机器上还是在我通常用来运行代码的远程机器上.因此,我认为这是公认的答案.
Unable to init server: Could not connect: Connection refused
(CMC_temper_all.py:55509): Gtk-WARNING **: ##:##:##:###: Locale not supported by C library.
Using the fallback 'C' locale.
Unable to init server: Could not connect: Connection refused
(CMC_temper_all.py:55509): Gdk-CRITICAL **: ##:##:##:###:
gdk_cursor_new_for_display: assertion 'GDK_IS_DISPLAY (display)' failed
(CMC_temper_all.py:55509): Gdk-CRITICAL **: ##:##:##:###: gdk_cursor_new_for_display: assertion 'GDK_IS_DISPLAY (display)' failed
"##:#:#:#:#:#:#:##是(或似乎是)IP地址.
我认为这应该发表一个新的问题,但我还是把它放在这里,以防有人有一个快速的答案.