Space.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. from enum import Enum
  2. from typing import NamedTuple, Optional, Callable, List, Tuple
  3. from pypdevs.infinity import INFINITY
  4. from pypdevs.DEVS import AtomicDEVS, CoupledDEVS
  5. from Agents import Neigbours
  6. class State(Enum):
  7. Idle = "Idle"
  8. Processing = "Processing"
  9. class SpaceState(NamedTuple):
  10. State: State
  11. Neighbours: list
  12. Killed: list
  13. ToBeBorn: list
  14. class Space(AtomicDEVS):
  15. def __init__(self, width, height, rng, stats):
  16. AtomicDEVS.__init__(self, "Grid")
  17. self.stats = stats
  18. self.rng = rng
  19. self.width = width
  20. self.height = height
  21. self.next_aid = 0
  22. self.grid = {} # y * width + x -> (variant, aid)
  23. self.agent_pos = {} # aid -> y * width + x
  24. self.state = SpaceState(State.Idle, [], [], [])
  25. self.requestVictim = self.addInPort("request victim")
  26. self.move = self.addInPort("move")
  27. self.reproduce = self.addInPort("duplicate")
  28. self.kill = self.addInPort("murdered")
  29. self.agent_out_ports = {}
  30. def print_grid(self,
  31. moves=None,
  32. attacker: int | None = None,
  33. victim: int | None = None,
  34. original: int | None = None,
  35. duplicate: int | None = None):
  36. if moves is None:
  37. moves = []
  38. print(f"\n--- Grid ---")
  39. # 1. Print the column headers
  40. header = " " + "".join([f"{x:^3}" for x in range(self.width)])
  41. print(header)
  42. for y in range(self.height):
  43. # 2. Print the row number at the start of each line
  44. row_chars = [f"{y:2} "]
  45. for x in range(self.width):
  46. index = y * self.width + x
  47. # Determine the base character
  48. if index in self.grid:
  49. variant, aid = self.grid[index]
  50. v_name = variant.name if hasattr(variant, 'name') else str(variant)
  51. char = v_name.split('.')[-1][0].upper()
  52. else:
  53. char = "."
  54. # 3. Apply highlighting if the current (x, y) is in the target list
  55. index = y*self.width + x
  56. if index in moves:
  57. row_chars.append(f"[{char}]")
  58. elif index == attacker:
  59. row_chars.append(f"<{char}>")
  60. elif index == victim:
  61. row_chars.append(f">{char}<")
  62. elif index == original:
  63. row_chars.append(f"{{{char}}}")
  64. elif index == duplicate:
  65. row_chars.append(f"({char})")
  66. else:
  67. row_chars.append(f" {char} ")
  68. print("".join(row_chars))
  69. print("-" * (self.width * 3 + 3) + "\n")
  70. def init_agent(self, variant, x, y):
  71. aid = self.next_aid
  72. self.next_aid += 1
  73. index = y * self.width + x
  74. self.grid[index] = (variant, aid)
  75. self.agent_pos[aid] = index
  76. self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
  77. return aid, self.agent_out_ports[aid]
  78. def timeAdvance(self):
  79. action, neighbours, killed, ToBeBorn = self.state
  80. if action is State.Idle:
  81. return INFINITY
  82. return 0
  83. def intTransition(self):
  84. action, neighbours, killed, ToBeBorn = self.state
  85. return SpaceState(State.Idle, [], killed, ToBeBorn)
  86. def get_neighbouring_pos(self, aid: int, radius: int = 1,
  87. condition: Optional[Callable[[int], bool]] = None) -> int | None:
  88. """
  89. Returns a list of neighbouring positions within a given radius
  90. that satisfy an optional condition.
  91. """
  92. if aid not in self.agent_pos:
  93. return None
  94. index = self.agent_pos[aid]
  95. x, y = index % self.width, index // self.width
  96. neighbours = []
  97. for dx in range(-radius, radius + 1):
  98. for dy in range(-radius, radius + 1):
  99. if dx == 0 and dy == 0:
  100. continue
  101. nx = (x + dx) % self.width
  102. ny = (y + dy) % self.height
  103. neighbor_index = ny * self.width + nx
  104. if condition is None or condition(neighbor_index):
  105. neighbours.append(neighbor_index)
  106. if neighbours:
  107. # return self.rng.choice(neighbours)
  108. return neighbours[0]
  109. return None
  110. def get_victim(self, aid, neighbours):
  111. contender_pos = self.get_neighbouring_pos(aid, condition=lambda pos: pos in self.grid)
  112. if contender_pos:
  113. contender = self.grid[contender_pos]
  114. out_port = self.agent_out_ports[aid]
  115. neighbours.append((out_port, contender))
  116. # index = self.agent_pos[aid]
  117. # variant, _ = self.grid[index]
  118. # print("=" * 246)
  119. # print(f"{variant} Agent_{aid} attacks {contender[0]} Agent_{contender[1]}")
  120. # self.print_grid(attacker=index, victim=contender_pos)
  121. def move_agent(self, aid):
  122. target_pos = self.get_neighbouring_pos(aid)
  123. if target_pos is None:
  124. return
  125. occupant = self.grid.get(target_pos)
  126. index = self.agent_pos[aid]
  127. agent = self.grid[index]
  128. # variant, _ = self.grid[index]
  129. # print("=" * 246)
  130. # x, y = index % self.width, index // self.width
  131. # nx, ny = target_pos % self.width, target_pos // self.width
  132. # print(f"MOVE: {variant} agent_{aid} from {x, y} to {nx, ny} deplacing: {occupant}")
  133. # self.print_grid(moves=[index, target_pos])
  134. if occupant is None:
  135. del self.grid[index]
  136. self.grid[target_pos] = agent
  137. self.agent_pos[aid] = target_pos
  138. else:
  139. occupant_variant, occupant_aid = occupant
  140. self.grid[target_pos] = agent
  141. self.grid[index] = occupant
  142. self.agent_pos[aid] = target_pos
  143. self.agent_pos[occupant_aid] = index
  144. # self.print_grid(moves=[index, target_pos])
  145. def extTransition(self, inputs):
  146. action, neighbours, killed, ToBeBorn = self.state
  147. if self.requestVictim in inputs:
  148. self.stats["attacks"] += len(inputs[self.requestVictim])
  149. for aid in inputs[self.requestVictim]:
  150. self.get_victim(aid, neighbours)
  151. if self.move in inputs:
  152. self.stats["moves"] += len(inputs[self.move])
  153. for aid in inputs[self.move]:
  154. self.move_agent(aid)
  155. if self.kill in inputs:
  156. for victim_aid in inputs[self.kill]:
  157. if victim_aid not in self.agent_pos:
  158. continue
  159. self.stats["kills"] += 1
  160. index = self.agent_pos.pop(victim_aid)
  161. variant, _ = self.grid[index]
  162. del self.grid[index]
  163. killed.append(victim_aid)
  164. # print("=" * 246)
  165. # x, y = index % self.width, index // self.width
  166. # print(f"KILLED: {variant} Agent_{victim_aid} at {x, y}")
  167. # self.print_grid()
  168. if self.reproduce in inputs:
  169. self.stats["reproduces"] += len(inputs[self.reproduce])
  170. for aid, variant in inputs[self.reproduce]:
  171. if aid not in self.agent_pos:
  172. continue
  173. target = self.get_neighbouring_pos(aid, condition=lambda pos: pos not in self.grid)
  174. if target is None:
  175. continue
  176. self.stats["babies"] += 1
  177. # print("=" * 246)
  178. # index = self.agent_pos[aid]
  179. # x, y = index % self.width, index // self.width
  180. # nx, ny = target % self.width, target // self.width
  181. # print(f"Duplicating: {variant} Agent_{aid} at {x, y} to {nx, ny}")
  182. # self.print_grid(original=index, duplicate=target)
  183. new_aid = self.next_aid
  184. self.next_aid += 1
  185. self.grid[target] = (variant, new_aid)
  186. self.agent_pos[new_aid] = target
  187. ToBeBorn.append((variant, new_aid))
  188. return SpaceState(State.Processing, neighbours, killed, ToBeBorn)
  189. def outputFnc(self):
  190. out_dict = {}
  191. action, neighbours, killed, ToBeBorn = self.state
  192. if action is State.Processing and neighbours:
  193. for port, contender in neighbours:
  194. if port not in out_dict:
  195. out_dict[port] = []
  196. out_dict[port].append(contender)
  197. return out_dict
  198. def add_agent(self, aid, variant, x, y):
  199. index = y * self.width + x
  200. self.grid[index] = (variant, aid)
  201. self.agent_pos[aid] = index
  202. if aid not in self.agent_out_ports:
  203. self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
  204. return self.agent_out_ports[aid]
  205. def remove_agent(self, aid):
  206. if aid in self.agent_pos:
  207. index = self.agent_pos.pop(aid)
  208. del self.grid[index]
  209. def modelTransition(self, state):
  210. """
  211. When reproducing send a signal to parent coupled
  212. to create a new agent of the agent's type
  213. When the killed agent has been removed send a signal
  214. to parent coupled to remove the agent from the model space
  215. """
  216. action, neighbours, killed, ToBeBorn = self.state
  217. structural_change = False
  218. if killed:
  219. for dead in killed:
  220. self.removePort(self.agent_out_ports[dead])
  221. state["remove"] = killed.copy()
  222. killed.clear()
  223. structural_change = True
  224. if ToBeBorn:
  225. for variant, aid in ToBeBorn:
  226. self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
  227. state["mitosis"] = ToBeBorn.copy()
  228. ToBeBorn.clear()
  229. structural_change = True
  230. return structural_change