Flocking.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import random
  2. import math
  3. import os
  4. from Space import Space
  5. from Bird import Bird
  6. if os.getenv("PYPDEVS_MINIMAL") == "1":
  7. from pypdevs.minimal import CoupledDEVS
  8. else:
  9. from pypdevs.DEVS import CoupledDEVS
  10. class Flocking(CoupledDEVS):
  11. def __init__(self, seed: int, extent: tuple[int, int], num_birds: int, visual_distance: float):
  12. super().__init__("Flocking")
  13. self.rng = random.Random(seed)
  14. space_width, space_depth = extent
  15. speed = 1.0
  16. cohere_factor = 0.03
  17. separation = 1.0
  18. separate_factor = 0.015
  19. match_factor = 0.05
  20. initial_positions = {}
  21. for bird_id in range(num_birds):
  22. start_x = self.rng.uniform(0, space_width)
  23. start_y = self.rng.uniform(0, space_depth)
  24. angle = self.rng.uniform(0, 2 * math.pi)
  25. vel_x = math.cos(angle)
  26. vel_y = math.sin(angle)
  27. initial_positions[bird_id] = ((start_x, start_y), (vel_x, vel_y))
  28. # test for onestep comparison with Agents.JL
  29. # num_birds = 3
  30. # initial_positions = {
  31. # 0: ((10.0, 10.0), (1.0, 0.0)),
  32. # 1: ((12.0, 11.0), (0.0, 1.0)),
  33. # 2: ((9.0, 9.5), (-1.0, 0.0))
  34. # }
  35. self.space = self.addSubModel(Space(
  36. extent=extent,
  37. visual_distance=visual_distance,
  38. initial_positions=initial_positions,
  39. rng=self.rng
  40. ))
  41. for bird_id in range(num_birds):
  42. pos, vel = initial_positions[bird_id]
  43. bird = self.addSubModel(Bird(
  44. bid=bird_id,
  45. extent=extent,
  46. pos=pos,
  47. vel=vel,
  48. speed=speed,
  49. separation=separation,
  50. visual_distance=visual_distance,
  51. cohere_factor=cohere_factor,
  52. match_factor=match_factor,
  53. separate_factor=separate_factor
  54. ))
  55. self.connectPorts(bird.out_position, self.space.in_bird_pos)
  56. self.connectPorts(self.space.out_neighbours[bird_id], bird.in_neighbours)