Python中的同时模拟
我有一大堆简单的模拟需要运行,想知道能不能同时进行。让我来描述一下情况:我有1000次关于大约100种疾病的流行率抽样,还有1000次对应这些疾病的残疾权重抽样(也就是得了这种病有多严重,用0到1的比例来表示),这些数据是针对20个年龄组的。我的模拟任务是,给定一组流行率,计算有多少人会有不同组合的疾病。下面是10种疾病的输入数据示例:
from __future__ import division
import numpy as np
disease_number = np.array([1,2,3,4]*10)
age = np.array([5, 10, 15, 20]*10)
prevalence = np.random.uniform(0, 1, (40, 1000))
disability_weight = np.random.uniform(0,1,(40, 1000))
单次抽样的模拟结果大概是这样的,针对5岁,抽样1。
prev_draw1 = prevalence[age==5, 1]
disability_draw1 = disability_weight[age==5, 1]
simulation = np.random.binomial(1, prev_draw1, (100000, prev_draw1.shape[0])
然后为了计算每种疾病的残疾权重,考虑到多种疾病的共病情况,我会这样做:把分母设为当前残疾权重的总和,把某种疾病的残疾权重作为分子。以疾病1为例:
denom = np.sum(disability_draw1**simulaiton)
denom[denom==1]=0
numerator = disability_draw1*simulation[:, 0]
adjusted_dw = np.sum(numerator/denom)
我需要为每种疾病单独进行这个调整后的残疾权重计算。有没有办法让我同时进行这1000次模拟?任何帮助都很感激,我对python还比较陌生,所以多一些描述会很有帮助。
1 个回答
4
如果你的电脑有多个处理器或者核心,可以看看“multiprocessing”这个模块。
同时运行1000个模拟可能会有点耗费资源。你最好是每次只在每个核心上运行一个模拟。
你可以使用“Queue”模块,并结合“Process pool”来工作。
下面是一个简单的示例,可能不是很完美(没有测试过):
from multiprocessing import Process, Queue
def run_simulation(simulations, results):
while simulations.qsize() > 0:
simulation_params = simulations.get()
# run simulation
results.put(simulation_result)
simulations.task_done()
if __name__ == '__main__':
simulations_to_run = Queue()
simulations_to_run.put({}) # simulation parameters go in this dict, add all simulations, one per line (could be done in a loop, with a list of dicts)
results = Queue()
for i in range(8): #number processes you want to run
p = Process(target=run_simulation, args=(simulations_to_run, results))
p.start()
simulations_to_run.join()
# now, all results shoud be in the results Queue