从NetLogo中的列表创建矩阵

时间:2018-01-30 21:37:57

标签: list matrix netlogo

我使用NetLogo模拟人群中的病毒感染。受感染的个体是红色的,它们还存储数值以表示它们被感染的病毒株。我想制作一个矩阵,对于每个时间步长,只存储感染个体的菌株标签(并且可能使用一些占位符用于未感染的个体)。

我的人口中有100个人,每个模拟运行365次,所以我知道矩阵有100列和365行 - 我只是不知道如何将其转换为NetLogo语法。例如:

  to track-strain-diversity
    report list ([tflu-strain] of turtles with [color = red])

 how do I store this list as a row for a single timestep in a matrix?
 how do I then fill in each subsequent row with the flu strains found in each timestep?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

如果您希望使用索引来访问某些值,或者如果您想在收集应变信息后在模型中进行某些矩阵运算,则可能需要查看matrix extension 。如果您想要使用此路线,请查看该扩展程序中的matrix:set-row原语。

如果您只是记录这些值,然后将它们输出到其他地方进行分析,您可能会满意只使用列表列表来存储每个滴答的菌株,然后使用{{3}输出最后的列表列表}。

以下示例使用此设置:

extensions [ csv ]
globals [ strains strain_list_list ]
turtles-own [ infected? flu-strain ]

to setup
  ca
  set strains [  1 2 3 ]
  crt 5 [
    ifelse random 2 = 0 [
      set infected? true
      set flu-strain one-of strains
    ] [
      set infected? false
    ]
  ]
  set strain_list_list ( list t-sorted-strain-list )
  print strain_list_list
  reset-ticks
end

使用此选项,您仍需要提供某种占位符,以便您的行长度相同。您可以让记者这样做,例如:

to-report my-strain ; turtle reporter
  ifelse infected? [
    report flu-strain
  ] [
    report 0
  ]  
end

那位记者(被乌龟打电话)报告说,如果龟有一个,那么就会出现流感应变数,如果没有则为零。为了整洁,您可以将其报告为按海龟分类的列表,以便每个“列”对应一只乌龟:

to-report t-sorted-strain-list
  report map [ i -> [flu-strain] of i ]  sort turtles
end

然后,只需运行模型并将t-sorted-strain-list记录为列表列表中的新条目(strain-list-list)即可。当您的模型一直运行时,您可以将整个列表列表输出为csv文件,以便使用csv:to-file进行分析。在此示例中,模型将go直到所有海龟都被感染,此时模型将strain_list_list输出到名为“strain_each_tick.csv”的csv文件,然后模型将stop。< / p>

to go
  if not any? turtles with [ not infected? ] [
    csv:to-file "strains_each_tick.csv" strain_list_list
    stop
  ]
  ask turtles with [ not infected? ] [
    if random 5 = 0 [
      set flu-strain one-of strains 
      set infected? true
    ]
  ]
  set strain_list_list lput t-sorted-strain-list strain_list_list
  tick
end

加载到R中的输出文件类似于:

> df
  V1 V2 V3 V4 V5
1  2  0  0  3  2
2  2  0  0  3  2
3  2  0  2  3  2
4  2  0  2  3  2
5  2  3  2  3  2