test_schelling.py 917 B

1234567891011121314151617181920212223242526272829303132333435
  1. import os
  2. os.environ["PYPDEVS_MINIMAL"] = "1"
  3. from pypdevs.minimal import Simulator
  4. from Schelling import Schelling
  5. def get_happiness_ratio(space_model):
  6. happy_count = 0
  7. total_agents = len(space_model.state.grid)
  8. for position, (aid, group) in space_model.state.grid.items():
  9. if space_model.isHappy(position, group):
  10. happy_count += 1
  11. return happy_count / total_agents
  12. def verify_schelling_pypdevs():
  13. target_steps = [1, 2, 5, 10, 20]
  14. print("PyPDEVS Schelling Happiness Ratio:")
  15. for target in target_steps:
  16. model = Schelling(dim=40, num_agents=1000, radius=1, happy_threshold=3, seed=42)
  17. sim = Simulator(model)
  18. sim.setTerminationTime(target + 1e-3)
  19. sim.simulate()
  20. ratio = get_happiness_ratio(model.space)
  21. print(f"After {target} steps: {round(ratio, 4)}")
  22. if __name__ == '__main__':
  23. verify_schelling_pypdevs()