首页 > 解决方案 > 如何在 NetLogo 6.2 中调整文件以导出数据?

问题描述

我正在尝试在 NetLogo 6.2 中导出文件。但我有两个困难:

  1. 在输出中仅放置 1 个标头。它只有多个标题或没有标题(见下图)

多个标题:

在此处输入图像描述

没有标题:

在此处输入图像描述

我希望它看起来像这样(下图)。是否可以?

在此处输入图像描述

  1. 关闭文件,这样多个结果就不会写入同一个文件。当我使用命令“小心”、“文件删除”和“[]”时,只会出现海龟的结果:

在此处输入图像描述

如果我删除“小心”、“文件删除”和“[]”命令,所有海龟的结果都会出现。但是,如果我多次运行模型,结果将保存在顶部。如何在不更改结果的情况下关闭文件?

编码:

globals [ outifile ]
turtles-own [ my-xcor my-ycor my-timer ]

to output 
;  carefully ;; using this command to close the file only saves the path of the last turtle
;  [ file-delete ( word outfile name ".csv" ) ] ;; using this command to close the file only saves the path of the last turtle
;  [ ] ;; using this command to close the file only saves the path of the last turtle
  file-open ( word outifile ".csv" )
  file-print ( word "id;my_xcor;my_ycor;my_timer" ) ;; when removing this line, there is no header
  file-print ( word self  " ; " my-xcor " ; " my-ycor " ; " my-timer )  
  file-close
end

标签: netlogo

解决方案


这两个问题有相同的原因和相同的解决方案。

对于第 1 点

这是因为显然to output是由每个 turtle执行的,这意味着每个 turtle 将首先打印标题然后打印值。请注意,这正是您要求他们执行的操作,每个海龟都执行以下两行代码:

file-print ( word "id;my_xcor;my_ycor;my_timer" )
file-print ( word self  " ; " my-xcor " ; " my-ycor " ; " my-timer )

因此,在要求海龟做任何事情之前,您必须先打印标题(即观察者必须打印标题,然后必须要求海龟打印值)。

对于第 2 点

这个问题也来自于你让每只海龟都执行整个to output过程的事实。在这种情况下,这意味着每只海龟都会跑

carefully
 [file-delete (word outfile name ".csv")]
 []

因此,每只海龟都会在写入它们的输出之前确保该文件已被删除(或它不存在)。

同样,这是观察者应该做的事情,因为它只需要做一次。

使固定

要解决这些问题,您有两个绝对等价的选择:

选项1

留下to output一个海龟上下文过程(即由海龟执行的过程)并将观察者的任务放在代码中的其他位置,您知道它们只会执行一次- 例如在setup或某些等效位置:

to setup
 ; Here you have your normal 'setup' code, plus:
 prepare-output
end

to prepare-output
 carefully
  [file-delete (word outfile name ".csv")]
  []

 file-open (word outifile ".csv")
 file-print (word "id;my_xcor;my_ycor;my_timer")
 file-close
end

所以观察者将负责清理文件并创建标题,当海龟运行时,to output它们只需要打印它们的值。

选项 2

从由海龟执行的过程更改to output为由观察者执行的过程。在这种情况下,在程序开始时,观察者将做一次它的观察者的事情,然后才要求所有海龟打印它们的值。一旦海龟完成,观察者关闭文件。例如:

to go
 ; Here you have your normal 'go' code, plus something like:
 if (stop-condition-reached?) [
  output
  stop
 ]
end

to output
 carefully
  [file-delete (word outfile name ".csv")]
  []

 file-open (word outifile ".csv")
 file-print (word "id;my_xcor;my_ycor;my_timer")

 ask turtles [
  file-print (word self  " ; " my-xcor " ; " my-ycor " ; " my-timer)  
 ]

 file-close
end


这两个选项背后的逻辑完全相同:观察者只做一次(删除旧文件并创建一个带有标题的新文件),然后每个海龟打印它的值。

这两个选项之间的区别仅在于代码的组织方式 - 即是to output由海龟执行的过程,还是由观察者(然后要求海龟打印)?

一般来说,跟踪谁在执行什么是很重要的。出于这个原因,在我的代码中,我总是用注释说明每个过程的声明是从哪个上下文执行的(例如观察者上下文、乌龟上下文、补丁上下文、链接上下文)。


推荐阅读