diff --git a/mesa/examples/basic/schelling/agents.py b/mesa/examples/basic/schelling/agents.py index 67940b5654e..49825825127 100644 --- a/mesa/examples/basic/schelling/agents.py +++ b/mesa/examples/basic/schelling/agents.py @@ -6,7 +6,6 @@ class SchellingAgent(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) @@ -20,11 +19,22 @@ def step(self) -> None: self.pos, moore=True, radius=self.model.radius ) - # Count similar neighbors - similar = sum(neighbor.type == self.type for neighbor in neighbors) + # 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 similar < self.model.homophily: - self.model.grid.move_to_empty(self) - else: - self.model.happy += 1 + # 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