调用nlrx包simdesign_lhs时出现Atomic Vector Error求助
问题与解决方案
问题描述
在使用R的nlrx包为NetLogo模型集成优化功能时,执行nl@simdesign <- simdesign_lhs(nl=nl)语句时出现错误:
Error in x$min : $ operator is invalid for atomic vectors
相关代码如下:
library(nlrx) root_d <- file.path("/home/imantha/workspace/CRTT") netlogo_p <- file.path("/home/imantha/tools/NetLogo-6.4.0-64") model_p <- file.path(root_d, "model","crtt_v2.nlogo") # 创建结果存储目录 dir.create(file.path(root_d, "results"), showWarnings = FALSE) out_p <- file.path(root_d, "results") nl <- nl(nlversion = "6.4.0", nlpath = netlogo_p, modelpath = model_p, jvmmem = 1024) # 绑定实验配置 nl@experiment <- experiment( expname = "crtt-test", outpath = out_p, repetition = 1, tickmetrics = "true", idsetup = "Setup", idgo = "Go", runtime = 7201, evalticks = seq(180,7200,60), metrics = c( "count cas-agents with [pma-name = 'Vieux Habitants PMA' and in-queue? = True and deceased? = False]" ), variables = list( "heli-rescue?" = FALSE, "Speed-Helicopter" = 200, "no-heli-agent" = 3, "heli-agent-cap" = 2, "no-resc-agent-A" = 20, "no-resc-agent-B" = 15, "resc-agent-cap" = 3, "resc-agent-A-only" = TRUE, "Rescue-Time-Mins" = 10, "Transfer-Time-Mins" = 5, "Speed" = 30, "increase-rescue-agents-at-time" = 60, "Increase-Rescue-Agents" = 2, "transfer-hosp-vh" = 10, "transfer-hosp-sm" = 8, "pma-cap-t1" = 5, "pma-cap-t2" = 30, "pma-operational-t1" = 180, "pma-operational-t2" = 300, "stabilisation-t" = 17, "no-bb" = 6, "no-nbb" = 212 ), constants = list() ) nl@simdesign <- simdesign_lhs(nl=nl)
错误原因与解决方法
错误原因
simdesign_lhs()是生成拉丁超立方抽样设计的函数,要求**variables列表中的每个变量必须定义min和max取值范围**,这样函数才能生成有效抽样值。但当前代码里的variables所有元素都是单一固定值(如"no-heli-agent" = 3),属于原子向量,没有min属性,函数调用时尝试访问x$min就会触发错误。
解决步骤
- 区分变量与常量:将不需要优化的固定值移到
constants列表中,仅把需要抽样优化的变量留在variables里。 - 为变量定义取值范围:将
variables中的元素改为包含min和max的列表格式。
示例修改后的代码片段:
nl@experiment <- experiment( expname = "crtt-test", outpath = out_p, repetition = 1, tickmetrics = "true", idsetup = "Setup", idgo = "Go", runtime = 7201, evalticks = seq(180,7200,60), metrics = c( "count cas-agents with [pma-name = 'Vieux Habitants PMA' and in-queue? = True and deceased? = False]" ), # 仅保留需要优化的变量,并定义取值范围 variables = list( "no-heli-agent" = list(min=1, max=5), "no-resc-agent-A" = list(min=10, max=30), "no-resc-agent-B" = list(min=10, max=20) ), # 固定值移到constants中 constants = list( "heli-rescue?" = FALSE, "Speed-Helicopter" = 200, "heli-agent-cap" = 2, "resc-agent-cap" = 3, "resc-agent-A-only" = TRUE, "Rescue-Time-Mins" = 10, "Transfer-Time-Mins" = 5, "Speed" = 30, "increase-rescue-agents-at-time" = 60, "Increase-Rescue-Agents" = 2, "transfer-hosp-vh" = 10, "transfer-hosp-sm" = 8, "pma-cap-t1" = 5, "pma-cap-t2" = 30, "pma-operational-t1" = 180, "pma-operational-t2" = 300, "stabilisation-t" = 17, "no-bb" = 6, "no-nbb" = 212 ) ) # 现在可以正常生成抽样设计 nl@simdesign <- simdesign_lhs(nl=nl)
额外说明
- 对于布尔类型的变量(如
heli-rescue?),如果需要优化,可定义min=FALSE, max=TRUE,函数会自动处理布尔值的抽样。 - 执行前确保NetLogo模型路径正确,且模型中的变量名与代码中的完全一致(注意大小写和特殊字符)。
内容的提问来源于stack exchange,提问作者imantha
相关产品推荐
相关产品推荐

