2016-12-13 117 views
1

我需要運行一堆混合隨機/確定性反應網絡模擬,其算法在class Markov中說明。編號喜歡並行執行,並將所有輸出寫入單個文件,這在進一步分析中很容易使用。現在即時將它存儲在npz文件中。在從屬進程中創建Markov的實例時,我得到的錯誤是:global name 'Markov' is not defined。所以問題是:我如何在我的slave進程中創建一個Markov的實例?該代碼下面列出了更多(一般)問題。多處理,實例創建和函數實例的傳遞

import numpy as np 
import pathos.multiprocessing as mp 


class Markov(object): 
    def __init__(self,SRN_name,rates,stoich_mat): 
     self.S=stoich_mat 
     self.SRN_name=SRN_name #SRN = Stochastic Reaction Network 
     self.rates=rates 
     self.nr_reactions=rates.shape[1] 

def worker(SRN_name,rates,stoich_mat,init_state,tf,species_continuous): 
    result = [] 
    try: 
     sim=Markov(SRN_name=SRN_name,rates=rates,stoich_mat=stoich_mat) 
    except Exception as e: 
     print e 

    result=None #here some methods of sim are executed 

    return result 

def handle_output(result): 
    data=np.load("niks.npz").files 
    data.append(result) 
    np.savez("niks",data) 

if __name__ == '__main__': 
    def sinput(t,amplitude=6.0,period=0.05,offset=1.0): 
     return amplitude*np.sin(period*t)+amplitude+offset 
    phospho_cascade=np.array(
          [[ 0, 0, 0, 0, 0, 0, 0, 0], # input 
          [-1, 1, 0, 0, 0, 0, 0, 0]])# A 

    phospho_rates=np.array([(0.2,0),2.0],dtype=object,ndmin=2) 

    phspho_init=np.array([sinput,5.0],ndmin=2).T 

    tf=1.0 
    S_C=[0] 

    np.savez("niks",stoich_mat=phospho_cascade,rates=phospho_rates,init_state=phspho_init) 
    kwargs={"SRN_name":"niks","rates":phospho_rates,"stoich_mat":phospho_cascade,"init_state":rates,"tf":tf,"species_continuous":S_C} 
    pool = mp.Pool(processes=mp.cpu_count()) 
    for i in range(2): 
     pool.apply_async(worker,kwds=kwargs,callback=handle_output) 
    pool.close() 
    pool.join() 

謝謝!

回答

0

只是回答你的問題的第二部分,是的,有更簡單的方法來做多處理。我建議再次嘗試您的代碼,但使用「線程」模塊。線程示例如下所示:

import threading 

#Just define any functions you'd like to thread: 
def RandomFunction(): 
    print('Hello World') 

#Now create the thread(s) as so: 
threadName = threading.Thread(target = RandomFunction , args =()) 

#Now start the threads. You may also use threadName.join(), if you'd like to wait for a thread to complete, before continuing. 
threadName.start() 

使用相同的語法,可以根據需要創建多個函數的線程,並同時運行它們。相信我,這要容易得多! :)

+2

嘿,Id寧願使用多處理,因爲線程是由GIL限制。 – Patrickens