R Simmer - 使用set_attribute和get_attribute以及复制(使用lapply)

时间:2018-05-16 09:56:51

标签: r

我正在尝试组合set_attribute和get_attribute复制(使用lapply) 没有“get_attribute”的以下代码运行良好:

library(simmer)    

SystemTime <- 200
delay= c(20,40,60,80,100,120,140,160,180,200)/60
set.seed(1234)

elevators <- simmer()

worker <-
  trajectory("elevators service") %>% #trajectory name
  log_("new worker arrived") %>% #
  set_attribute("start_time", function() {now(elevators)}) %>%
  seize("elevator",amount = 1) %>% #elevator queue and service 
  timeout(function() sample(delay,1)) %>%
  release("elevator") 


elevators <-lapply(1:100, function(i) {
  simmer("elevators") %>%
  add_generator("worker", worker, function() exp(2)) %>% 
    add_resource("elevator",capacity = 2) %>% 
  run(until = SystemTime)

})

当我添加“get_attribute”时,如下所示:

library(simmer) 

SystemTime <- 200
delay= c(20,40,60,80,100,120,140,160,180,200)/60
set.seed(1234)

elevators <- simmer()

worker <-
  trajectory("elevators service") %>% #trajectory name
  log_("new worker arrived") %>% #
  set_attribute("start_time", function() {now(elevators)}) %>%
  seize("elevator",amount = 1) %>% #elevator queue and service 
  timeout(function() sample(delay,1)) %>%
  log_(function() {paste("Waited: ", now(elevators) - get_attribute(elevators, "start_time"))}) %>%
  release("elevator") 


elevators <-lapply(1:100, function(i) {
  simmer("elevators") %>%
  add_generator("worker", worker, function() exp(2)) %>% 
    add_resource("elevator",capacity = 2) %>% 
  run(until = SystemTime)

})

我收到以下错误:

  

run_中的错误(私有$ sim_obj,直到):评估错误:有   没有到来跑。

寻求帮助,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的第一个示例运行时没有错误,但实际上效果不佳。基本上,你有一个范围问题。模拟环境必须在轨迹范围内,以便get_attribute(和now)可以看到它。解决方案是将所有内容放在同一个函数中:

library(simmer) 

SystemTime <- 200
delay= c(20,40,60,80,100,120,140,160,180,200)/60
set.seed(1234)

elevators <-lapply(1:100, function(i) {
  elevator <- simmer("elevator")

  worker <-
    trajectory("elevator service") %>% #trajectory name
    log_("new worker arrived") %>% #
    set_attribute("start_time", function() {now(elevator)}) %>%
    seize("elevator",amount = 1) %>% #elevator queue and service 
    timeout(function() sample(delay,1)) %>%
    log_(function() {paste("Waited: ", now(elevator) - get_attribute(elevator, "start_time"))}) %>%
    release("elevator") 

  elevator %>%
    add_generator("worker", worker, function() rexp(1, 2)) %>% 
    add_resource("elevator", capacity = 2) %>% 
    run(until = SystemTime)
})

另请注意,我在您的生成器中将exp(2)替换为rexp(1, 2),我认为这是您真正想要的。