Jen*_*enB 5 social-networking netlogo
我的模型中有大约 5000 个代理(人)。我想给他们任意数量的朋友,并有互惠但随机的配对。因此,如果 A 选择 B 则 B 也选择 A。我的代码运行良好,但速度相当慢。我很可能想在未来增加朋友的数量和人数。有更快的建议吗?
ask people
[ let new-links friends - count my-links
if new-links > 0
[ let candidates other people with [ count my-links < friends ]
create-links-with n-of min (list new-links count candidates) candidates
[ hide-link ]
]
]
Run Code Online (Sandbox Code Playgroud)
请注意,在上面的代码中,朋友是一个全局变量,但我最终的代码可能会概括wanted-number-of-friends为人的一个属性。
已编辑添加了if new-links > 0条件,以便在ask不需要找到候选时避免嵌套。这提高了速度,但仍然不能真正扩展。
很好的问题。这实际上是非常具有挑战性的优化。有问题的行是:
let candidates other people with [ count my-links < friends ]
这很慢,因为每个代理都会与其他代理进行检查。拥有 5000 名代理人,相当于 25,000,000 张支票!不幸的是,如果没有一些奇特的数据结构,就没有真正的好方法来优化这个特定的行。
幸运的是,有一个解决方案可以很好地概括为在网络中生成任何度数分布(听起来这就是您最终想要的)。不幸的是,该解决方案并不能很好地转化为 NetLogo。但它是这样的:
let pairs [] ;; pairs will hold a pairs of turtles to be linked
while [ pairs = [] ] [ ;; we might mess up creating these pairs (by making self loops), so we might need to try a couple of times
let half-pairs reduce sentence [ n-values friends [ self ] ] of turtles ;; create a big list where each turtle appears once for each friend it wants to have
set pairs (map list half-pairs shuffle half-pairs) ;; pair off the items of half-pairs with a randomized version of half-pairs, so we end up with a list like: [[ turtle 0 turtle 5 ] [ turtle 0 turtle 376 ] ... [ turtle 1 turtle 18 ]]
;; make sure that no turtle is paired with itself
if not empty? filter [ first ? = last ? ] pairs [
set pairs []
]
]
;; now that we have pairs that we know work, create the links
foreach pairs [
ask first ? [
create-link-with last ?
]
]
Run Code Online (Sandbox Code Playgroud)
friends这里是全局变量还是海龟变量并不重要。这花费的时间取决于它需要尝试配对的次数,这是随机的。经过实验,我发现,对于 5000 个代理,每个代理的级别为 5,通常需要大约 3 秒。相比之下,在我的机器上,使用您原来的方式执行此操作大约需要 60 秒(就其价值而言,这就是我想要的方式)建议在使用较少的试剂时使用)。