NetLogo中基于入度创建跨种群链接及代码问题咨询
解决NetLogo跨种群偏好依附链接创建问题
首先,咱们先搞清楚你遇到的错误根源:你定义的LINKS是有向繁殖(directed breed),而create-link-with是专门用来创建无向链接的命令,在有向链接场景下直接调用它自然会报错,得换成有向版本的create-link-to或者create-link-from。
接下来逐个解决你的两个问题:
1. 如何基于入度选择人类种群的海龟?
要实现偏好依附模型(选中概率与入度成正比),NetLogo里有个现成的便捷命令:weighted-one-of。这个命令会根据你指定的权重值随机筛选海龟,权重越高,被选中的概率越大。针对你的需求,直接把人类的in-degree(入度)作为权重即可,代码示例如下:
let target-human weighted-one-of humans [in-degree]
如果担心初始状态下所有人类入度都是0的情况,可以加个兜底判断避免异常:
let target-human ifelse-value (any? humans with [in-degree > 0]) [weighted-one-of humans [in-degree]] [one-of humans] ; 若所有入度为0,就随机选一个人类
2. 跨不同种群的场景下,使用create-link-with one-of both-ends是否正确?
答案是不正确,主要有两个原因:
- 一是前面提到的链接类型不匹配:你的链接是有向的,
create-link-with仅适用于无向链接,必须替换为有向链接命令; - 二是逻辑不符合需求:
one-of both-ends of one-of links是从现有链接里随机选一个,再从它的两端挑一个节点,这既不能保证选中的是人类,也完全没有体现“基于人类入度”的偏好依附规则,和你的核心需求脱节。
修正后的完整代码片段
结合你的需求,调整后的ADD-ZOMBIE过程如下(假设你需要让新僵尸作为链接起点,指向选中的人类):
create-zombies 1 [ if targeting = "first model" [ let thisZombie self ask one-of humans [ ifelse random-float 1 < p [ create-link-from thisZombie [set color red] ; 用有向的create-link-from创建链接 ] [ ask thisZombie [die] ] ] ] if targeting = "second model (preferential_attachment)" [ ; 基于入度选择目标人类 let target-human ifelse-value (any? humans with [in-degree > 0]) [weighted-one-of humans [in-degree]] [one-of humans] ; 创建有向链接:僵尸 → 人类(若需要反向链接,换成create-link-from即可) create-link-to target-human [set color red] ] ]
内容的提问来源于stack exchange,提问作者still_learning
相关产品推荐
相关产品推荐

