Julia,多次运行函数,将结果保存在数组中 [英] Julia, run function multiple times, save results in array
问题描述
我正在Julia建立一个微观模拟模型。我已经建立了我的功能结构,并且对于1个人来说它运行得非常好。我希望编写脚本来通过模型运行100000多人,并将结果保存在一个位置。
I am building a microsimulation model in Julia. I have built the structure of my function and it runs great for for 1 "person". I'd like to write the script to run 100000+ people through the model and save the results in one location.
最后,我想要并行执行此操作。
Eventually I'd like to execute this in parallel.
下面我已经包含了一个带有虚拟概率的代码的简单工作版本。
Below I have included a simple working version of the code with dummy probabilities.
using Distributions
# Microsim function
function MicroSim(start_age, stages)
stage = 0
age = start_age
# Set all trackers to 0
Death_tracker = 0
Disease_tracker = 0
# While loop
while stage <= stages
age = age
###########################################################
# Probability of Death
pD = 0.02
if age == 100
pD = 1.0
else
pD = pD
end
# Coin flip
dist_pD = Bernoulli(pD)
Died = rand(dist_pD, 1)
if Died == [1]
Death_tracker = 1
# death tracker loop break
if Death_tracker == 1
# println("I died")
break
end
else
Death_tracker = Death_tracker
end
###########################################################
# Update age and stage
age = age + 1
stage = stage + 1
end
return age, Death_tracker
end
MicroSim(18,100)
推荐答案
您正在寻找函数 map
和 pmap
(用于并行化)。我简化了你的功能,给出了一个更简单的工作示例。 (未来,请参阅此链接,以获取关于在您的问题中创建最小示例的指导)。
You are looking for the functions map
and pmap
(for parallelization). I've simplified your function to give a more minimal working example. (in the future, please see this link for guidance on creating such minimal examples in your questions).
map
采用一个函数(您指定)并将其应用于数组中的所有元素。如果你的函数需要多个参数(就像你的那样),那么你只需提供 map
多个连续数组。 map
然后返回一个包含所有函数结果的新数组。
map
takes a function (that you specify) and applies it to all of the elements in an array. If your function takes multiple arguments (as yours does), then you simply feed map
multiple successive arrays. map
then returns a new array with the results of all your functions.
function MicroSim(start_age, stages)
return rand(start_age), rand(stages)
end
Start_Ages = [10, 20, 15]
Stages = [1, 4, 5]
Results = map(MicroSim, Start_Ages, Stages)
如果你想平行化,只需要三个简单的调整。 1.使用 addprocs()
函数添加所需的许多其他进程。 2.在声明你的函数时使用 @everywhere
宏,这样你的工作进程也可以访问它。 3.使用函数 pmap
而不是 map
:
If you want to parallelize things, there are just three simple adjustments. 1. use the addprocs()
function to add however many additional processes you want. 2. use the @everywhere
macro when declaring your function so that your worker processes also have access to it. 3. use the function pmap
instead of map
:
addprocs(2)
@everywhere begin
function MicroSim(start_age, stages)
return rand(start_age), rand(stages)
end
end
Results = pmap(MicroSim, Start_Ages, Stages)
这篇关于Julia,多次运行函数,将结果保存在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!