我有一个名为“Males.csv”的 csv,其中包含三列“turning_angles”“speed”“step_length”
我在空白环境中创建了一个非常简单的代理模型
to set-up
clear-all
reset-ticks
ask patches [set pcolor green]
ask n-of home patches [set pcolor brown]
ask patches with [pcolor = brown] [
sprout n-turtles [set breed turtle set shape "arrow" set sex one-of ["male" "female"]]]
end
我想编写名为
step
和 turn
的程序,其中代理移动并从 csv 中的列中提取参数。是否可以将 csv 列转换为列表,然后从数据分布中随机选择?
例如 - 作为伪代码。
turtles-own [step-length turn]
to step
ask turtle fd random step-length from_column "step_length" "Males.csv"
end
to turn
ask turtle fd random turn from_column "turning_angles" "Males.csv"
end
to go
ask turtles [step turn]
end
有 CSV 扩展。您还可以在模型库中找到示例模型(请参阅CSV 示例。
扩展程序逐行读取您的 CSV 文件,因此您需要循环并将列的值一一提取到列表中。如果您不是将分布保存在列中而是保存在行中,那么您的生活会更轻松一些,当然它也适用于列。您可以使用
one-of
绘制该列表中的随机项目。
我在下面附上了如何解决您的问题的代码示例。
extensions [ csv ]
globals [
step_length_ls
turning_angles_ls
]
to read_csv
; close file connections
file-close-all
; open your csv file
file-open "males.csv"
; read first line of csv file (headers), alternatively just hardcode the index of columns
let header csv:from-row file-read-line
; determine position of columns according to header
let idx_step_col position "step_length" header
let idx_turning_col position "turning_angles" header
; initialize global variables as lists
set step_length_ls []
set turning_angles_ls []
; read data in via a while loop
while [ not file-at-end? ] [
; here the CSV extension grabs a single line and puts the data of that in the data variable (list)
let data csv:from-row file-read-line
; append the values to the global list
set step_length_ls lput (item idx_step_col data) step_length_ls
set turning_angles_ls lput (item idx_turning_col data) turning_angles_ls
]
end
to step
fd one-of step_length_ls
end
to turn_turtle
; not sure if fd is what you want here, but according to your pseudocode it is
fd one-of turning_angles_ls
end
to setup
read_csv
create-turtles 1
end
to go
ask turtles [step turn_turtle]
end