This my code:
import random
from mesa import Agent, Model
from mesa.space import MultiGrid
import math
import pandas as pd
import matplotlib.pyplot as plt
class MyAgent(Agent):
def __init__(self, unique_id, model, pos, opinion, stubborn=False):
super().__init__(unique_id, model)
self.pos = pos
self.opinion = opinion
self.stubborn = stubborn
self.neighbors = []
class MyModel(Model):
def __init__(self):
self.schedule = None
self.grid = None
def create_population(num_agents, stubborn_ratio=0.1):
model = MyModel()
agents = []
for i in range(num_agents):
opinion = random.choice(["conservative", "liberal", "neutral"])
is_stubborn = random.random() < stubborn_ratio
agents.append(MyAgent(unique_id=i, model=model, pos=None, opinion=opinion, stubborn=is_stubborn))
return agents
def assign_neighbors(agents, grid_width = None, grid_height = None):
# Here, we are choosing the width and height of our matrix. if user
# already choose, use it. If not, assign it acc to agent num.
if not grid_width or not grid_height:
grid_width = int(math.ceil(math.sqrt(len(agents))))
grid_height = grid_width
# create the matrix. "grid" will be 2D matrix.
grid = MultiGrid(width=grid_width,height=grid_height, torus=True)
for agent in agents:
x = random.randint(0, grid_width - 1)
y = random.randint(0, grid_height - 1)
agent.pos = (x, y)
grid.place_agent(agent, (x, y)) #place agents on the grid.
for agent in agents:
x,y = agent.pos
agent.neighbors = grid.get_neighbors((x,y), moore=True, include_center=False)
return grid
def visualise_agents(agents):
data = []
for agent in agents:
color = "gray"
if agent.opinion == "conservative":
color = "red"
elif agent.opinion == "liberal":
color = "blue"
data.append({"x": agent.pos[0], "y": agent.pos[1], "opinion": agent.opinion, "color": color})
df = pd.DataFrame(data)
plt.figure(figsize=(8,8))
scatter = plt.scatter(df["x"], df["y"], c=df["color"], label=df["opinion"],alpha=0.7)
red_patch = plt.Line2D([0], [0], marker="o", color="w", markerfacecolor="red", markersize=10, label = "Conservative")
blue_patch = plt.Line2D([0], [0], marker="o", color="w", markerfacecolor="blue", markersize=10, label = "Liberal")
gray_patch = plt.Line2D([0], [0], marker="o", color="w", markerfacecolor="gray", markersize=10, label = "Neutral")
plt.legend(handles=[red_patch, blue_patch, gray_patch])
plt.title("Agent positions and Ideologies")
plt.xlabel("X position")
plt.ylabel("Y position")
plt.grid(True)
plt.show()
agents = create_population(100)
assign_neighbors(agents)
visualise_agents(agents)
and this is the error:
Traceback (most recent call last):
File "c:Users...project.py", line 79, in <module>
agents = create_population(100)
^^^^^^^^^^^^^^^^^^^^^^
File "c:Users...project.py", line 28, in create_population
agents.append(MyAgent(unique_id=i, model=model, pos=None, opinion=opinion, stubborn=is_stubborn))
^^^^^^^^^^^^^
File "c:Users...project.py", line 10, in __init__
super().__init__(unique_id, model)
File "C:Users...AppDataLocalProgramsPythonPython312Libsite-packagesmesaagent.py", line 64, in __init__
super().__init__(*args, **kwargs)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
I have been trying to fix this issue for a while. Basically i am just learning python, and now i am trying to build ABM with mesa. Because i couldn’t find detailed tutorials in youtube i am moving with AI but it also couldn’t help me with this. I am trying to simulate political ideology changes of people. Before i continue and detail the whole code deeply, i wanted to see what i have done but now it is not working.
Abdurrahman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1