#๐Ÿ”’ ABM project with mesa errors

5 messages ยท Page 1 of 1 (latest)

somber glade
#

In this code I keep getting errors like:
self.grid.place_agent(agent, i)
e:\faculta\Proiect Python\main.py:49: UserWarning: Agent 4997 is being placed with
place_agent() despite already having the position 4997. In most
cases, you'd want to clear the current position with remove_agent()
before placing the agent again.
self.grid.place_agent(agent, i)
e:\faculta\Proiect Python\main.py:49: UserWarning: Agent 4998 is being placed with
place_agent() despite already having the position 4998. In most
cases, you'd want to clear the current position with remove_agent()
before placing the agent again.
self.grid.place_agent(agent, i)
e:\faculta\Proiect Python\main.py:49: UserWarning: Agent 4999 is being placed with
place_agent() despite already having the position 4999. In most
cases, you'd want to clear the current position with remove_agent()
before placing the agent again.
self.grid.place_agent(agent, i)
Traceback (most recent call last):
File "e:\faculta\Proiect Python\main.py", line 81, in <module>
model.step()
~~~~~~~~~~^^
File "e:\faculta\Proiect Python\main.py", line 64, in step
agent.step()
~~~~~~~~~~^^
File "e:\faculta\Proiect Python\main.py", line 19, in step
neighbor_opinions = [self.model.agent_dict[neighbor].opinion for neighbor in neighbors]
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
KeyError: <main.OpinionAgent object at 0x000001B74776CCD0>

vernal hamletBOT
#

@somber glade

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

somber glade
#
import random
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from mesa.space import NetworkGrid
from mesa.datacollection import DataCollector

class OpinionAgent:
    def __init__(self, unique_id, model, influence, opinion):
        self.unique_id = unique_id
        self.model = model
        self.influence = influence  # Influence weight (0 to 1)
        self.opinion = opinion  # Current opinion (-1 to 1)
        self.next_opinion = opinion  # Placeholder for the next opinion
        self.pos = None  # Position attribute required for compatibility with NetworkGrid

    def step(self):
        neighbors = self.model.grid.get_neighbors(self.pos, include_center=False)
        neighbor_opinions = [self.model.agent_dict[neighbor].opinion for neighbor in neighbors]

        if neighbor_opinions:
            peer_influence = np.mean(neighbor_opinions)
            self.next_opinion = (1 - self.influence) * self.opinion + self.influence * peer_influence
        else:
            self.next_opinion = self.opinion

        # Add randomness (independent opinion change)
        if random.random() < 0.05:  # 5% chance of random opinion adjustment
            self.next_opinion += random.uniform(-0.1, 0.1)
            self.next_opinion = np.clip(self.next_opinion, -1, 1)

    def advance(self):
        self.opinion = self.next_opinion

class OpinionModel:
    def __init__(self, num_agents, influencer_fraction):
        self.num_agents = num_agents
        self.influencer_fraction = influencer_fraction
        self.grid = NetworkGrid(nx.scale_free_graph(num_agents))  # Scale-free network
        self.agent_dict = {}  # Use a custom attribute for agent storage

        for i in range(num_agents):
            is_influencer = random.random() < influencer_fraction
            influence = 0.9 if is_influencer else random.uniform(0.1, 0.5)
            opinion = random.uniform(-1, 1)
            agent = OpinionAgent(i, self, influence, opinion)
            agent.pos = i  # Set the position of the agent
            self.agent_dict[i] = agent
            self.grid.place_agent(agent, i)

        self.datacollector = DataCollector(
            model_reporters={"Average Opinion": self.compute_average_opinion},
            agent_reporters={"Opinion": "opinion"}
        )

    @staticmethod
    def compute_average_opinion(model):
        opinions = [agent.opinion for agent in model.agent_dict.values()]
        return np.mean(opinions)

    def step(self):
        # Update each agent's step logic
        for agent in self.agent_dict.values():
            agent.step()
        
        # Advance all agents to the next state
        for agent in self.agent_dict.values():
            agent.advance()

        # Collect data at the end of the step
        self.datacollector.collect(self)

# Run the model
num_agents = 5000
influencer_fraction = 0.05  # 5% influencers
steps = 1000

model = OpinionModel(num_agents, influencer_fraction)

for _ in range(steps):
    model.step()

# Collect results
data = model.datacollector.get_model_vars_dataframe()
agent_data = model.datacollector.get_agent_vars_dataframe()

# Visualization
plt.figure(figsize=(10, 6))
plt.plot(data.index, data["Average Opinion"], label="Average Opinion")
plt.title("Average Opinion Over Time")
plt.xlabel("Time Steps")
plt.ylabel("Average Opinion")
plt.legend()
plt.show()

# Histogram of final opinions
final_opinions = agent_data.xs(steps - 1, level="Step")["Opinion"]
plt.figure(figsize=(10, 6))
plt.hist(final_opinions, bins=20, edgecolor="black")
plt.title("Distribution of Final Opinions")
plt.xlabel("Opinion")
plt.ylabel("Frequency")
plt.show()```
vernal hamletBOT
#

@somber glade

Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.