我正在尝试模拟NetLogo中的容量限制和优先级(5.3.1,在Mac Sierra上)。它归结为要求有限数量的海龟(比如n
)做某些事情,并选择那些海龟以便(1)它们满足某些条件,(2)它们是n
海龟具有变量my-variable
的最大值。
我试图通过以下方式做到这一点:
let subset-of-turtles turtles with [ condition-variable = some-value ]
ask max-n-of n subset-of-turtles [ my-variable ] [< do something >]
但它有多个问题。
首先,如果没有乌龟满足[ condition-variable = some-value ]
的条件,NetLogo会抛出错误
从一组仅有0个代理中请求n个随机代理。
我尝试通过在ask
命令之前插入一行来解决:
let subset-of-turtles turtles with [ condition-variable = some-value ]
if subset-of-turtles != nobody [
ask max-n-of n subset-of-turtles [ my-variable ] [< do something >]
]
但它不起作用:
observer> show turtles with [ condition-variable = some-value ]
observer: (agentset, 0 turtles)
observer> let subset-of-turtles turtles with [ condition-variable = some-value ] show subset-of-turtles != nobody
observer: true
NetLogo认为空代理集仍然是代理集,因此它将通过与nobody
不同的测试。
其次,即使有些海龟符合条件,如果NetLogo少于n
,也会抛出同样的错误。我的模型是一个增长模型,其中容量在开始时就足够了,然后达到约束。因此,这将在模型的每次运行中发生。
我希望NetLogo最多ask
次在n
块中执行命令。假设有m
只乌龟满足条件:
1.如果m <= n
,请对所有m
乌龟执行命令
2. If m > n
,执行n
具有最高值my-variable
的海龟的命令。有人可以提供建议吗?
答案 0 :(得分:5)
一般情况下,我不建议测试是否count <agentset> = 0
,因为NetLogo仍然需要构建代理集来计算它。但是,这项任务有一个非常方便的any?
报告人。因此,请尝试对原始代码进行以下修改:
let subset-of-turtles turtles with [ condition-variable = some-value ]
if any? subset-of-turtles [
ask max-n-of n subset-of-turtles [ my-variable ] [< do something >]
]
答案 1 :(得分:2)
假设这样设置:
turtles-own [
condition-variable
my-variable
]
to setup
ca
reset-ticks
crt 10 [
setxy random 30 - 15 random 30 - 15
set condition-variable random 2
set my-variable 1 + random 10
]
end
首先,您可以使用count
快速检查代理集是否为空,并将其用作条件。 德尔>
any?
原语。
其次,您可以使用ifelse
来表示类似&#34;如果子集中的海龟数量少于n,则只询问子集中的海龟。否则,请问子集中的n只龟。&#34;
to go
let n 5
let subset-of-turtles turtles with [ condition-variable = 1 ]
;; obtain the number of turtles in the subset
let subcount count subset-of-turtles
;; If there are more than 0 turtles in the subset, do the following
if subcount > 0 [
;; If n is greater than the number in the subset, only ask the subset
ifelse n >= subcount [
ask max-n-of subcount subset-of-turtles [ my-variable ] [
set size 2
]
]
;; If n is NOT greater than the number in the subset, ask n of the subset
[
ask max-n-of n subset-of-turtles [ my-variable ][
set size 2
]
]
]
end