Schelling.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import random
  2. import os
  3. if os.getenv("PYPDEVS_MINIMAL") == "1":
  4. from pypdevs.minimal import CoupledDEVS
  5. else:
  6. from pypdevs.DEVS import CoupledDEVS
  7. from Space import Space
  8. from Agent import Agent
  9. class Schelling(CoupledDEVS):
  10. def __init__(self, dim: int, num_agents: int, radius: int, happy_threshold: int, seed: int) -> None:
  11. CoupledDEVS.__init__(self, "Schelling")
  12. self.rng = random.Random(seed)
  13. self.agents = []
  14. grid = {}
  15. empty = []
  16. for x in range(dim):
  17. for y in range(dim):
  18. empty.append((x, y))
  19. aid = 0
  20. for i in range(num_agents):
  21. pos = self.rng.choice(empty)
  22. empty.remove(pos)
  23. group = i % 2
  24. grid[pos] = (aid, group)
  25. agent = self.addSubModel(Agent(aid, group, pos))
  26. self.agents.append(agent)
  27. aid += 1
  28. self.space = self.addSubModel(Space(dim, dim, radius, happy_threshold, grid, empty, self.rng))
  29. for a in self.agents:
  30. self.connectPorts(a.queryNeighbours, self.space.neighbourCheck)
  31. self.connectPorts(self.space.newPositionsPorts[a.aid], a.move)
  32. self.connectPorts(self.space.changeConditionPorts[a.aid], a.updateCondition)