I'm facing trouble in modifying object attributes.
The TeamAgent() objects have two attributes: neighbors and notneighbors. These are list-type attributes. These values are initialized based on a NetworkX graph declared as G. As an example, if node 0 (self) is directly connected to nodes 1 and 3 but not 2, 4, and 5, then self.neighbors = [1,3] and self.notneighbors = [2,4,5].
The function linkage() acts as a "motivator" for TeamAgent() objects. In this function, the self object (node) instructs each of its neighbors to form a link with any one of their respective notneighbors. Therefore, first, the list of neighbors for each neighbor of the self should be appended with one of their notneighbors. Second, consequently, the notneighbors attribute of each neighbor of self should remove the newly-connected node from its list since the latter is now a neighbor. These two actions should also happen to the newly-connected node's attributes, since if i is connected to j, then j is also connected to i.
However, my code below does not modify either neighbors or notneighbors attribute. Can anyone suggest why this is happening?
from mesa import Agent, Model
from mesa.time import RandomActivation
import networkx as nx
G = nx.path_graph(4)
class TeamAgent(Agent):
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.neighbors = [n for n in G.neighbors(self.unique_id)]
self.notneighbors = [item for item in list(G) if item not in self.neighbors and item not in [self.unique_id]]
def linkage(self):
for neighbor in self.neighbors:
list_of_non_neighbors = TeamAgent(neighbor,TeamModel).notneighbors
if list_of_non_neighbors:
one_non_neighbor = random.choice(list_of_non_neighbors)
TeamAgent(neighbor,TeamModel).neighbors.append(one_non_neighbor)
TeamAgent(neighbor,TeamModel).notneighbors.remove(one_non_neighbor)
TeamAgent(one_non_neighbor,TeamModel).neighbors.append(neighbor)
TeamAgent(one_non_neighbor,TeamModel).notneighbors.remove(neighbor)
def step(self):
self.linkage()
print(self.unique_id, self.neighbors) #to check whether neighbors are being added. They should, but they are not being.
class TeamModel(Model):
def __init__(self):
self.schedule = RandomActivation(self)
for i, node in enumerate(G.nodes()):
a = TeamAgent(i, self)
self.schedule.add(a)
def step(self):
self.schedule.step()
my_model = TeamModel()
my_model.step()