Skip to content

Commit

Permalink
fix: update schelling model neighbor similarity calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
Sahil-Chhoker authored Nov 25, 2024
1 parent dbb9264 commit a51aa5c
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions mesa/examples/basic/schelling/agents.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
from mesa import Agent


class SchellingAgent(Agent):
"""Schelling segregation agent."""

def __init__(self, model, agent_type: int) -> None:
"""Create a new Schelling agent.
Args:
model: The model instance the agent belongs to
agent_type: Indicator for the agent's type (minority=1, majority=0)
Expand All @@ -19,12 +16,23 @@ def step(self) -> None:
neighbors = self.model.grid.iter_neighbors(
self.pos, moore=True, radius=self.model.radius
)

# Count similar neighbors
similar = sum(neighbor.type == self.type for neighbor in neighbors)

# If unhappy, move to a random empty cell:
if similar < self.model.homophily:
self.model.grid.move_to_empty(self)
else:
self.model.happy += 1

# Filter out empty cells
similar_neighbors = [
neighbor for neighbor in neighbors
if hasattr(neighbor, 'type') and neighbor.type == self.type
]
total_neighbors = [
neighbor for neighbor in neighbors
if hasattr(neighbor, 'type')
]

# Calculate fraction of similar neighbors
if len(total_neighbors) > 0:
similarity_fraction = len(similar_neighbors) / len(total_neighbors)

# If unhappy, move to a random empty cell
if similarity_fraction < self.model.homophily / 8.0:
self.model.grid.move_to_empty(self)
else:
self.model.happy += 1

0 comments on commit a51aa5c

Please sign in to comment.