Space.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from typing import NamedTuple
  2. from pypdevs.infinity import INFINITY
  3. import os
  4. if os.getenv("PYPDEVS_MINIMAL") == "1":
  5. from pypdevs.minimal import AtomicDEVS
  6. else:
  7. from pypdevs.DEVS import AtomicDEVS
  8. class SpaceState(NamedTuple):
  9. grid: dict[tuple[int, int], tuple[int, int]] # (x,y): (aid, group) find neighbours
  10. empty: list[tuple[int, int]] # (x,y) move to empty space
  11. action: str
  12. class Space(AtomicDEVS):
  13. def __init__(self, width, height, radius: int, threshold: int, grid: dict[tuple[int, int], tuple[int, int]], empty: list[tuple[int, int]], rng) -> None:
  14. AtomicDEVS.__init__(self, "Space")
  15. self.width = width
  16. self.height = height
  17. self.offsets = [
  18. (dx, dy)
  19. for dx in range(-radius, radius + 1)
  20. for dy in range(-radius, radius + 1)
  21. if not (dx == 0 and dy == 0)
  22. ]
  23. self.threshold = threshold
  24. self.rng = rng
  25. self.state = SpaceState(grid, empty, "Idle")
  26. self.neighbourCheck = self.addInPort("neighbour check")
  27. self.changeConditionPorts = {} # dict with output ports to update an agents emotional condition
  28. self.newPositionsPorts = {} # dict with output ports to update an agents position
  29. for aid, group in grid.values():
  30. self.changeConditionPorts[aid] = self.addOutPort(f"change condition {aid}")
  31. self.newPositionsPorts[aid] = self.addOutPort(f"new position {aid}")
  32. self.happy: list[int] = [] # (aid) list of agents which will become happy
  33. self.move: list[tuple[int, tuple[int, int]]] = [] # (aid, (x,y)) list of agents which will move in an attempt to become happy
  34. def isHappy(self, position: tuple[int, int], group) -> int:
  35. x, y = position
  36. similar = 0
  37. grid = self.state.grid
  38. threshold = self.threshold
  39. remaining_checks = len(self.offsets)
  40. for dx, dy in self.offsets:
  41. # threshold unreachable
  42. if similar + remaining_checks < threshold:
  43. return False
  44. neighbor = grid.get((x + dx, y + dy))
  45. if neighbor is not None and neighbor[1] == group:
  46. similar += 1
  47. if similar == threshold:
  48. return True
  49. remaining_checks -= 1
  50. return False
  51. def extTransition(self, inputs):
  52. grid, empty, action = self.state
  53. if self.neighbourCheck in inputs:
  54. self.happy = []
  55. self.move = []
  56. queries = inputs[self.neighbourCheck]
  57. self.rng.shuffle(queries)
  58. for aid, pos, group in queries:
  59. if self.isHappy(pos, group):
  60. # print(f"Agent {aid} at {pos} is HAPPY ({similar} similar).")
  61. self.happy.append(aid)
  62. continue
  63. idx = self.rng.randrange(len(empty))
  64. new_pos = empty[idx]
  65. empty[idx] = pos
  66. del grid[pos]
  67. grid[new_pos] = (aid, group)
  68. # print(f"Agent {aid} at {pos} is UNHAPPY ({similar} similar). Moving to {new_pos}...")
  69. self.move.append((aid, new_pos))
  70. return SpaceState(grid, empty, "Send")
  71. return self.state
  72. def intTransition(self):
  73. grid, empty, action = self.state
  74. if action == "Send":
  75. return SpaceState(grid, empty, "Idle")
  76. return self.state
  77. def outputFnc(self):
  78. grid, empty, action = self.state
  79. if action == "Send":
  80. output = {}
  81. for aid in self.happy:
  82. output[self.changeConditionPorts[aid]] = [True]
  83. for aid, pos in self.move:
  84. output[self.newPositionsPorts[aid]] = [pos]
  85. return output
  86. return {}
  87. def timeAdvance(self):
  88. grid, empty, action = self.state
  89. if action == "Send":
  90. return 0.0
  91. return INFINITY