| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 |
- from enum import Enum
- from typing import NamedTuple, Optional, Callable, List, Tuple
- from pypdevs.infinity import INFINITY
- from pypdevs.DEVS import AtomicDEVS, CoupledDEVS
- from Agents import Neigbours
- class State(Enum):
- Idle = "Idle"
- Processing = "Processing"
- class SpaceState(NamedTuple):
- State: State
- Neighbours: list
- Killed: list
- ToBeBorn: list
- class Space(AtomicDEVS):
- def __init__(self, width, height, rng, stats):
- AtomicDEVS.__init__(self, "Grid")
- self.stats = stats
- self.rng = rng
- self.width = width
- self.height = height
- self.next_aid = 0
- self.grid = {} # y * width + x -> (variant, aid)
- self.agent_pos = {} # aid -> y * width + x
- self.state = SpaceState(State.Idle, [], [], [])
- self.requestVictim = self.addInPort("request victim")
- self.move = self.addInPort("move")
- self.reproduce = self.addInPort("duplicate")
- self.kill = self.addInPort("murdered")
- self.agent_out_ports = {}
- def print_grid(self,
- moves=None,
- attacker: int | None = None,
- victim: int | None = None,
- original: int | None = None,
- duplicate: int | None = None):
- if moves is None:
- moves = []
- print(f"\n--- Grid ---")
- # 1. Print the column headers
- header = " " + "".join([f"{x:^3}" for x in range(self.width)])
- print(header)
- for y in range(self.height):
- # 2. Print the row number at the start of each line
- row_chars = [f"{y:2} "]
- for x in range(self.width):
- index = y * self.width + x
- # Determine the base character
- if index in self.grid:
- variant, aid = self.grid[index]
- v_name = variant.name if hasattr(variant, 'name') else str(variant)
- char = v_name.split('.')[-1][0].upper()
- else:
- char = "."
- # 3. Apply highlighting if the current (x, y) is in the target list
- index = y*self.width + x
- if index in moves:
- row_chars.append(f"[{char}]")
- elif index == attacker:
- row_chars.append(f"<{char}>")
- elif index == victim:
- row_chars.append(f">{char}<")
- elif index == original:
- row_chars.append(f"{{{char}}}")
- elif index == duplicate:
- row_chars.append(f"({char})")
- else:
- row_chars.append(f" {char} ")
- print("".join(row_chars))
- print("-" * (self.width * 3 + 3) + "\n")
- def init_agent(self, variant, x, y):
- aid = self.next_aid
- self.next_aid += 1
- index = y * self.width + x
- self.grid[index] = (variant, aid)
- self.agent_pos[aid] = index
- self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
- return aid, self.agent_out_ports[aid]
- def timeAdvance(self):
- action, neighbours, killed, ToBeBorn = self.state
- if action is State.Idle:
- return INFINITY
- return 0
- def intTransition(self):
- action, neighbours, killed, ToBeBorn = self.state
- return SpaceState(State.Idle, [], killed, ToBeBorn)
- def get_neighbouring_pos(self, aid: int, radius: int = 1,
- condition: Optional[Callable[[int], bool]] = None) -> int | None:
- """
- Returns a list of neighbouring positions within a given radius
- that satisfy an optional condition.
- """
- if aid not in self.agent_pos:
- return None
- index = self.agent_pos[aid]
- x, y = index % self.width, index // self.width
- neighbours = []
- for dx in range(-radius, radius + 1):
- for dy in range(-radius, radius + 1):
- if dx == 0 and dy == 0:
- continue
- nx = (x + dx) % self.width
- ny = (y + dy) % self.height
- neighbor_index = ny * self.width + nx
- if condition is None or condition(neighbor_index):
- neighbours.append(neighbor_index)
- if neighbours:
- # return self.rng.choice(neighbours)
- return neighbours[0]
- return None
- def get_victim(self, aid, neighbours):
- contender_pos = self.get_neighbouring_pos(aid, condition=lambda pos: pos in self.grid)
- if contender_pos:
- contender = self.grid[contender_pos]
- out_port = self.agent_out_ports[aid]
- neighbours.append((out_port, contender))
- # index = self.agent_pos[aid]
- # variant, _ = self.grid[index]
- # print("=" * 246)
- # print(f"{variant} Agent_{aid} attacks {contender[0]} Agent_{contender[1]}")
- # self.print_grid(attacker=index, victim=contender_pos)
- def move_agent(self, aid):
- target_pos = self.get_neighbouring_pos(aid)
- if target_pos is None:
- return
- occupant = self.grid.get(target_pos)
- index = self.agent_pos[aid]
- agent = self.grid[index]
- # variant, _ = self.grid[index]
- # print("=" * 246)
- # x, y = index % self.width, index // self.width
- # nx, ny = target_pos % self.width, target_pos // self.width
- # print(f"MOVE: {variant} agent_{aid} from {x, y} to {nx, ny} deplacing: {occupant}")
- # self.print_grid(moves=[index, target_pos])
- if occupant is None:
- del self.grid[index]
- self.grid[target_pos] = agent
- self.agent_pos[aid] = target_pos
- else:
- occupant_variant, occupant_aid = occupant
- self.grid[target_pos] = agent
- self.grid[index] = occupant
- self.agent_pos[aid] = target_pos
- self.agent_pos[occupant_aid] = index
- # self.print_grid(moves=[index, target_pos])
- def extTransition(self, inputs):
- action, neighbours, killed, ToBeBorn = self.state
- if self.requestVictim in inputs:
- self.stats["attacks"] += len(inputs[self.requestVictim])
- for aid in inputs[self.requestVictim]:
- self.get_victim(aid, neighbours)
- if self.move in inputs:
- self.stats["moves"] += len(inputs[self.move])
- for aid in inputs[self.move]:
- self.move_agent(aid)
- if self.kill in inputs:
- for victim_aid in inputs[self.kill]:
- if victim_aid not in self.agent_pos:
- continue
- self.stats["kills"] += 1
- index = self.agent_pos.pop(victim_aid)
- variant, _ = self.grid[index]
- del self.grid[index]
- killed.append(victim_aid)
- # print("=" * 246)
- # x, y = index % self.width, index // self.width
- # print(f"KILLED: {variant} Agent_{victim_aid} at {x, y}")
- # self.print_grid()
- if self.reproduce in inputs:
- self.stats["reproduces"] += len(inputs[self.reproduce])
- for aid, variant in inputs[self.reproduce]:
- if aid not in self.agent_pos:
- continue
- target = self.get_neighbouring_pos(aid, condition=lambda pos: pos not in self.grid)
- if target is None:
- continue
- self.stats["babies"] += 1
- # print("=" * 246)
- # index = self.agent_pos[aid]
- # x, y = index % self.width, index // self.width
- # nx, ny = target % self.width, target // self.width
- # print(f"Duplicating: {variant} Agent_{aid} at {x, y} to {nx, ny}")
- # self.print_grid(original=index, duplicate=target)
- new_aid = self.next_aid
- self.next_aid += 1
- self.grid[target] = (variant, new_aid)
- self.agent_pos[new_aid] = target
- ToBeBorn.append((variant, new_aid))
- return SpaceState(State.Processing, neighbours, killed, ToBeBorn)
- def outputFnc(self):
- out_dict = {}
- action, neighbours, killed, ToBeBorn = self.state
- if action is State.Processing and neighbours:
- for port, contender in neighbours:
- if port not in out_dict:
- out_dict[port] = []
- out_dict[port].append(contender)
- return out_dict
- def add_agent(self, aid, variant, x, y):
- index = y * self.width + x
- self.grid[index] = (variant, aid)
- self.agent_pos[aid] = index
- if aid not in self.agent_out_ports:
- self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
- return self.agent_out_ports[aid]
- def remove_agent(self, aid):
- if aid in self.agent_pos:
- index = self.agent_pos.pop(aid)
- del self.grid[index]
- def modelTransition(self, state):
- """
- When reproducing send a signal to parent coupled
- to create a new agent of the agent's type
- When the killed agent has been removed send a signal
- to parent coupled to remove the agent from the model space
- """
- action, neighbours, killed, ToBeBorn = self.state
- structural_change = False
- if killed:
- for dead in killed:
- self.removePort(self.agent_out_ports[dead])
- state["remove"] = killed.copy()
- killed.clear()
- structural_change = True
- if ToBeBorn:
- for variant, aid in ToBeBorn:
- self.agent_out_ports[aid] = self.addOutPort(f"send_neighbour_{aid}")
- state["mitosis"] = ToBeBorn.copy()
- ToBeBorn.clear()
- structural_change = True
- return structural_change
|