2

I am using MESA to simulate COVID-19 spread. I want to delete agent that dead but when I run it on the web, the agents never decrease even I set the death rate to 100%.

def condition(self):
    self.Infection_time +=1
    if self.Infection_time <= self.stage_one:
        self.stage = 1
    elif self.Infection_time > self.stage_one and self.Infection_time <= self.stage_one+self.stage_two:
        self.stage = 2
    else:
        self.stage = 3
        result = 0#rand_pick([0 , 1],[0.1 , 0.9])
        if result == 0:
            model.schedule.remove(self)
            #self.model.kill_agents.append(self)
chash
  • 3,975
  • 13
  • 29

2 Answers2

3

I'm an amateur programmer using Mesa for my undergraduate thesis work and I figured out your problem (it also happened to be my problem).

First, the error with your code: Your code only removes the 'dead' agent from the scheduler, not the model itself. All you've done is prevent your 'dead agent' from updating. You need to remove it from the grid using the "grid.remove_agent(agent)" command. You do not want to remove your agent from the scheduler where you have it now ("model.schedule.remove(self)") because it may mess up the activation of future agents.

To fix this, first you must append the agent to the "kill_agents" list you have commented out in your code. Then, in your step function in your model, which completes after all of your agents have stepped, you should have the following:

def step(self):
    self.schedule.step()
    for x in self.kill_agents:
        self.grid.remove_agent(x)
        self.schedule.remove(x)
        self.kill_agents.remove(x)

Your code should be ordered like this: First, let the model step. This will prevent errors in activation orders. Then, for every agent in the "kill agents" list, remove them from the grid (Note that the "remove_agent" function is a sub-function of "grid", not the more commonly used "MultiGrid", THEN remove it from the scheduler, THEN remove it from the kill list itself.

Your agents should die in swarms now!

David Buck
  • 3,752
  • 35
  • 31
  • 35
0

Above example causes a KeyError to occur because the agent's pos attribute is set to None before it is removed from the scheduler. When remove_agent is called, it sets the agent's pos attribute to None, which causes an error when the agent is later removed from the scheduler because the scheduler is trying to access the pos attribute that is no longer set.

To avoid this error, you should remove the agent from the scheduler first, before calling the remove_agent function. This way, the scheduler will no longer try to access the agent's pos attribute after it has been set to None.

def step(self):
self.schedule.step()
for x in self.kill_agents:
    self.schedule.remove(x)
    self.grid.remove_agent(x)
    self.kill_agents.remove(x)