I am following this example called Virus on Network from the Mesa library which creates network graphs using Networkx.
Here is its function screening a node's neighbors to try to infect them with a virus.
def try_to_infect_neighbors(self):
neighbors_nodes = self.model.grid.get_neighbors(self.pos, include_center=False)
susceptible_neighbors = [agent for agent in self.model.grid.get_cell_list_contents(neighbors_nodes) if
agent.state is State.SUSCEPTIBLE]
for a in susceptible_neighbors:
if self.random.random() < self.virus_spread_chance:
a.state = State.INFECTED
However, I like to get the distance between a node and its neighbor. And here is another example called Sugarscape from Mesa that seems to do just that.
So I modified the code into:
def try_to_infect_neighbors(self):
neighbors_nodes = self.model.grid.get_neighbors(self.pos, include_center=False)
susceptible_neighbors = [agent for agent in self.model.grid.get_cell_list_contents(neighbors_nodes) if
agent.state is State.SUSCEPTIBLE]
for a in susceptible_neighbors:
print('Self position:', self.pos, 'Neightbor position:', neighbor_agent.pos)
# Output: Self position: 52 Neightbor position: 13
neightbor_distance = get_distance(self.pos, neighbor_agent.pos)
# TypeError: 'int' object is not iterable
print(neightbor_distance)
if neightbor_distance <= 1:
if self.random.random() < self.virus_spread_chance:
a.state = State.INFECTED
def get_distance(pos_1, pos_2):
""" Get the distance between two point
Args:
pos_1, pos_2: Coordinate tuples for both points.
"""
x1, y1 = pos_1
x2, y2 = pos_2
dx = x1 - x2
dy = y1 - y2
return math.sqrt(dx**2 + dy**2)
In the Sugarscape example, a.pos
gives a tuple of x and y locations. But in the Virus on Network, a.pos
gives the agent's ID. How can I access agent's x and y location in the Virus on Network example? I tried searching for them from within a.model.G
and a.model.grid
via the variables: self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob)
and self.grid = NetworkGrid(self.G)
, but I couldn't identify them and am thinking it shouldn't be that hidden.