如何读入一个文件,运行一个模拟,然后读入下一个文件,重复模拟

How to read in a file, run a simulation, then read in the next file and repeat simulation

对于下面的代码,我试图连续读入在 r 中创建的 .txt 文件并将我的工作目录(包含 Netlogo 和 R 脚本)输出到 NetLogo。这些文件本质上是 ascii 网格文件,其编号分配给补丁,通过根据文本文件中网格单元格中的数字对补丁进行着色来生成景观。 NetLogo 代码通过一个简单的设置按钮执行此操作。

patches-own [
  landcover
]

to setup ; procedure to reset netlogo interface once setup button is pressed after one run of various code procedures
  ca ; clears the world
  resize-world 0 600 -600 0
  generate-landscape
  reset-ticks
end

to generate-landscape
  file-open "landscape.txt"
  foreach sort patches [
  the-patch ->
  ask the-patch [ ; read a data element into a patch variable
      set landcover file-read ; color the patch accordingly
      if (landcover = 1) [
        set pcolor green
          ]
      if (landcover = 0.5) [
        set pcolor orange
          ]
      if (landcover = 0) [
        set pcolor grey
          ]
        ]
      ]
   file-close
end

我的问题是,如果我在工作目录中有多个这样的 ascii grid .txt 文件,每个文件代表一个 new/different 景观,我想将它们读入 NetLogo 以一次执行一些模拟怎么办?有没有好的和高效的way/code来做到这一点?

如果您有一个通用文件名(例如 "terrain1.asc"、"terrain2.asc" 等),您可以使用 foreach 进行迭代,这可能是最简单的方法。否则,您可以使用 r 扩展名,如下所示:

extensions [r csv]

globals [ list-of-file-names ]

to setup
  ca
  r:eval "x <- list.files('absolute_folder_path_here')" 
  set list-of-file-names r:get "x"
  reset-ticks
end

to go 
  foreach list-of-file-names [
    fname ->
    let fpath word "absolute_folder_path_here" fname
    print csv:from-file fpath
  ]
end

在上面的示例中,我在一个文件夹中有三个不同的 .csv 文件。我将该文件夹的绝对地址提供给 R 中调用的 list.files 函数以获取保存为列表的文件名列表,然后我可以使用 foreach 遍历每个文件并执行任何你需要的操作.

extensions [r csv]

globals [ 
  list-of-file-names 
  numbers
]

to setup  
  ca
  r:eval "x <- list.files('C:/Users/lukepc/Google Drive/school_2017/nlogo_examples/textfiles')"
  set list-of-file-names r:get "x"
  reset-ticks
end

to scheduler
  foreach list-of-file-names [
    fname ->
    ; Reset the world
    limited-reset

    ; Load the new file/data
    let fpath word "C:/Users/lukepc/Google Drive/school_2017/nlogo_examples/textfiles/" fname
    set numbers csv:from-file fpath

    ; Do your model procedures
    go
  ]
end

to limited-reset
  ; Reset all variables (except list-of-file-names) here
  ; and otherwise return your model to its base state
end


to go
  ; Do the regular model processes as normal
end

编辑:

在这里盗用 Brian Head - 如果他提出这个答案,我将删除我的答案!

如果你想使用 BehaviorSpace,假设一个简单的命名约定会容易得多,你可以像这样进行设置:

扩展 [r csv]

globals [ 
  list-of-file-names 
  filename
]

to setup
  ca
  set filename ( word "landscape" n ".txt" )
  reset-ticks
end

使用这样的小部件:

还有这样的实验:

要获得这样的输出:

这表明对于每次运行,都会生成不同的 filename