class SenseSiteSwarmEnvironmentModel(Model): """ A environemnt to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(SenseSiteSwarmEnvironmentModel, self).__init__(seed=None) else: super(SenseSiteSwarmEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.target = Sites(id=1, location=(0, 0), radius=11, q_value=0.5) self.grid.add_object_to_grid(self.target.location, self.target) for i in range(self.num_agents): a = SwarmAgentSenseSite(i, self) self.schedule.add(a) x = 45 y = 45 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a def step(self): self.schedule.step()
class SingleCarryModel(Model): """ A environment to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(SingleCarryModel, self).__init__(seed=None) else: super(SingleCarryModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.thing = Debris(id=1, location=(0, 0), radius=4) self.grid.add_object_to_grid(self.thing.location, self.thing) for i in range(self.num_agents): a = SwarmSingleCarry(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a def step(self): self.schedule.step()
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(SenseHubSiteSwarmEnvironmentModel, self).__init__(seed=None) else: super(SenseHubSiteSwarmEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.target = Sites(id=1, location=(10, 10), radius=11, q_value=0.5) self.grid.add_object_to_grid(self.target.location, self.target) self.hub = Hub(id=1, location=(-45, -45), radius=11) self.grid.add_object_to_grid(self.hub.location, self.hub) for i in range(self.num_agents): a = SwarmAgentSenseHubSite(i, self) self.schedule.add(a) x = 45 y = 45 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a
def __init__(self, N, width, height, grid=10, iter=100000, seed=None): """Initialize the attributes.""" if seed is None: super(EnvironmentModel, self).__init__(seed=None) else: super(EnvironmentModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime("%s") + str( self.random.randint(1, 1000, 1)[0]) self.pname = os.getcwd() + '/' + self.runid + "SForagingComm" self.stepcnt = 1 self.iter = iter self.top = None # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, 'SForaging Communication', iter, width, height, grid) self.experiment.insert_experiment() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) # self.site = Sites(id=1, location=(5, 5), radius=11, q_value=0.5) # self.grid.add_object_to_grid(self.site.location, self.site) # self.hub = Hub(id=1, location=(0, 0), radius=11) # self.grid.add_object_to_grid(self.hub.location, self.hub) self.agents = [] # Create agents for i in range(self.num_agents): a = SwarmAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) # x = 0 y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) # y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a)
class GEEnvironmentModel(Model): """ A environemnt to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(GEEnvironmentModel, self).__init__(seed=None) else: super(GEEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] # Create agents for i in range(self.num_agents): a = GEBTAgent(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) def step(self): self.schedule.step()
class WealthEnvironmentModel(Model): """ A environemnt to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(WealthEnvironmentModel, self).__init__(seed=None) else: super(WealthEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = SwarmAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) a.location = (x, y) self.grid.add_object_to_grid((x, y), a) def step(self): self.schedule.step()
def __init__(self, N, width, height, grid=10, seed=None, viewer=False): """Initialize the environment methods.""" if seed is None: super(RandomWalkSwarmEnvironmentModel, self).__init__(seed=None) else: super(RandomWalkSwarmEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.viewer = viewer self.schedule = SimultaneousActivation(self) self.hub = Hub(id=2, location=(0, 0), radius=5) self.grid.add_object_to_grid(self.hub.location, self.hub) self.site = Sites(id=2, location=(25, 25), radius=5) self.grid.add_object_to_grid(self.site.location, self.site) self.agents = [] for i in range(self.num_agents): a = SwarmAgentRandomWalk(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agents.append(a) if self.viewer: self.ui = UI((width, height), [self.hub], self.agents, [self.site])
class GEEnvironmentModel(Model): """ A environemnt to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(GEEnvironmentModel, self).__init__(seed=None) else: super(GEEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] for i in range(self.num_agents): a = GEBTAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) a.location = (x, y) self.grid.add_object_to_grid((x, y), a) # a.operation_threshold = self.num_agents // 10 self.agents.append(a) # exit() def step(self): self.schedule.step()
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(GEEnvironmentModel, self).__init__(seed=None) else: super(GEEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = GEBTAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell # x = self.random.randint( # -self.grid.width / 2, self.grid.width / 2) x = 0 # y = self.random.randint( # -self.grid.height / 2, self.grid.height / 2) y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(MoveTowardsModel, self).__init__(seed=None) else: super(MoveTowardsModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.target = Sites(id=1, location=(45, 45), radius=5, q_value=0.5) self.grid.add_object_to_grid(self.target.location, self.target) for i in range(self.num_agents): a = SwarmMoveTowards(i, self) self.schedule.add(a) x = -45 y = -45 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(SingleCarryFoodModel, self).__init__(seed=None) else: super(SingleCarryFoodModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) for a in range(5): self.thing = Food(id=a, location=(0, 0), radius=16) self.grid.add_object_to_grid(self.thing.location, self.thing) for i in range(self.num_agents): a = SwarmSingleCarryFood(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(MultipleCarryModel, self).__init__(seed=None) else: super(MultipleCarryModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.thing = Debris(id=1, location=(0, 0), radius=40) self.grid.add_object_to_grid(self.thing.location, self.thing) self.agent = [] for i in range(self.num_agents): a = SwarmMultipleCarry(i, self) self.schedule.add(a) x = 1 y = 1 a.location = (x, y) a.direction = 1.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent.append(a)
class RandomWalkSwarmEnvironmentModel(Model): """ A environemnt to model swarms """ def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(RandomWalkSwarmEnvironmentModel, self).__init__(seed=None) else: super(RandomWalkSwarmEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = SwarmAgentRandomWalk(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a def step(self): self.schedule.step()
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(MultipleCarryModel, self).__init__(seed=None) else: super(MultipleCarryModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.thing = Food(id=1, location=(30, 30), radius=40) self.grid.add_object_to_grid(self.thing.location, self.thing) self.thing1 = Food(id=1, location=(30, 30), radius=40) self.grid.add_object_to_grid(self.thing1.location, self.thing1) self.site = Sites(id=1, location=(30, 30), radius=5, q_value=0.5) self.grid.add_object_to_grid(self.site.location, self.site) self.hub = Hub(id=1, location=(0, 0), radius=11) self.grid.add_object_to_grid(self.hub.location, self.hub) self.agent = [] for i in range(self.num_agents): a = SwarmMultipleCarry(i, self) self.schedule.add(a) x = 30 y = 30 a.location = (x, y) a.direction = 2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent.append(a)
def __init__( self, N, width, height, grid=10, iter=100000, seed=None, name='CTForaging', viewer=False, parent=None, ratio=1.0): """Initialize the attributes.""" if seed is None: super(CTModel, self).__init__(seed=None) else: super(CTModel, self).__init__(seed) # Create a unique experiment id self.runid = datetime.datetime.now().timestamp() self.runid = str(self.runid).replace('.', '') # Create the experiment folder # If parent folder exits create inside it if parent is not None and pathlib.Path(parent).is_dir(): self.pname = parent + '/' + self.runid + '-' + str(ratio) + name else: self.pname = '/'.join( os.getcwd().split('/')[:-2] ) + '/results/' + self.runid + '-' + str(iter) + name # Define some parameters to count the step self.stepcnt = 1 self.iter = iter # UI self.viewer = viewer # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment( self.connect, self.runid, N, seed, name, iter, width, height, grid) self.experiment.insert_experiment() # Get the primary key of the experiment table for future use self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) # Number of agents self.num_agents = N # Environmental grid size self.grid = Grid(width, height, grid) # Schedular to active agents self.schedule = SimultaneousActivation(self) # Empty list of hold the agents self.agents = []
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(NMModel, self).__init__(seed=None) else: super(NMModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.hub = Hub(id=1, location=(0, 0), radius=11) self.grid.add_object_to_grid(self.hub.location, self.hub) # Create a place for the agents to drop the derbis self.obstacles = [] try: for i in range(4): dx, dy = self.random.randint(5, 10, 2) dx = self.hub.location[0] + 25 + dx dy = self.hub.location[1] + 25 + dy o = Obstacles(id=i, location=(dx, dy), radius=10) self.grid.add_object_to_grid(o.location, o) self.obstacles.append(o) except AttributeError: pass self.agent = [] for i in range(self.num_agents): a = NM(i, self) self.schedule.add(a) x = 19 y = 10 a.location = (x, y) a.direction = 2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent.append(a) self.debris = [] try: for i in range(self.num_agents * 10): dx, dy = self.random.randint(10, 20, 2) dx = self.hub.location[0] + dx dy = self.hub.location[1] + dy d = Debris( i, location=(dx, dy), radius=5) # print (i, dx, dy) d.agent_name = None self.grid.add_object_to_grid(d.location, d) self.debris.append(d) except KeyError: pass
def __init__(self, N, width, height, grid=10, seed=None, viewer=False): if seed is None: super(SingleCarryDropReturnSwarmEnvironmentModel, self).__init__(seed=None) else: super(SingleCarryDropReturnSwarmEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.viewer = viewer self.schedule = SimultaneousActivation(self) self.hub = Hub(id=2, location=(0, 0), radius=5) self.grid.add_object_to_grid(self.hub.location, self.hub) self.site = Sites(id=3, location=(-35, -5), radius=5) self.grid.add_object_to_grid(self.site.location, self.site) self.agents = [] self.foods = [] for i in range(self.num_agents): f = Food(i, location=(-35, -5), radius=5) self.grid.add_object_to_grid(f.location, f) self.foods.append(f) for i in range(self.num_agents): # a = SwarmAgentRandomSingleCarryDropReturn(i, self) a = SwarmAgentHandCodedForaging(i, self) self.schedule.add(a) x = -45 y = -45 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agents.append(a) if self.viewer: self.ui = UI((width, height), [self.hub], self.agents, [self.site], food=self.foods)
def setUp(self): ''' Create three grids system with different grid size ''' self.grid_four_equal_width_height = Grid(24, 24, grid_size=4) self.grid_four_unequal_width_height = Grid(24, 16, grid_size=4) self.grid_five = Grid(20, 20, grid_size=5)
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(ExploreModel, self).__init__(seed=None) else: super(ExploreModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = SwarmExplore(i, self) self.schedule.add(a) x = 0 y = 0 a.location = (x, y) a.direction = -2.3561944901923448 self.grid.add_object_to_grid((x, y), a) self.agent = a
def __init__(self, N, width, height, grid=10, seed=None): if seed is None: super(XMLEnvironmentModel, self).__init__(seed=None) else: super(XMLEnvironmentModel, self).__init__(seed) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.site = Sites(id=1, location=(45, 45), radius=5, q_value=0.5) self.grid.add_object_to_grid(self.site.location, self.site) self.hub = Hub(id=1, location=(0, 0), radius=11) self.grid.add_object_to_grid(self.hub.location, self.hub) self.agents = [] # Create agents for i in range(self.num_agents): a = XMLTestAgent(i, self) self.schedule.add(a) x = 45 y = 45 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) # Add equal number of food source for i in range(5): # self.num_agents * 2): f = Food(i, location=(45, 45), radius=3) f.agent_name = None self.grid.add_object_to_grid(f.location, f)
def __init__( self, N, width, height, grid=10, iter=100000, xmlstrings=None, seed=None, viewer=False, pname=None, expname='MSFSimulation', agent='SimAgent'): """Initialize the attributes.""" if seed is None: super(SimModel, self).__init__(seed=None) else: super(SimModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime( "%s") + str(self.random.randint(1, 1000, 1)[0]) if pname is None: self.pname = os.getcwd() + '/' + self.runid + expname else: self.pname = pname + '/' + self.runid + expname self.width = width self.height = height self.stepcnt = 1 self.iter = iter self.xmlstrings = xmlstrings self.viewer = viewer # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment( self.connect, self.runid, N, seed, expname, iter, width, height, grid, phenotype=xmlstrings[0]) self.experiment.insert_experiment_simulation() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] bound = np.ceil((self.num_agents * 1.0) / len(self.xmlstrings)) j = 0 # Create agents for i in range(self.num_agents): # print (i, j, self.xmlstrings[j]) a = eval(agent)(i, self, xmlstring=self.xmlstrings[j]) self.schedule.add(a) # Add the agent to a random grid cell # x = self.random.randint( # -self.grid.width / 2, self.grid.width / 2) x = 0 # y = self.random.randint( # -self.grid.height / 2, self.grid.height / 2) y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) if (i + 1) % bound == 0: j += 1
class SimModel(Model): """A environemnt to model swarms.""" def __init__( self, N, width, height, grid=10, iter=100000, xmlstrings=None, seed=None, viewer=False, pname=None, expname='MSFSimulation', agent='SimAgent'): """Initialize the attributes.""" if seed is None: super(SimModel, self).__init__(seed=None) else: super(SimModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime( "%s") + str(self.random.randint(1, 1000, 1)[0]) if pname is None: self.pname = os.getcwd() + '/' + self.runid + expname else: self.pname = pname + '/' + self.runid + expname self.width = width self.height = height self.stepcnt = 1 self.iter = iter self.xmlstrings = xmlstrings self.viewer = viewer # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment( self.connect, self.runid, N, seed, expname, iter, width, height, grid, phenotype=xmlstrings[0]) self.experiment.insert_experiment_simulation() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] bound = np.ceil((self.num_agents * 1.0) / len(self.xmlstrings)) j = 0 # Create agents for i in range(self.num_agents): # print (i, j, self.xmlstrings[j]) a = eval(agent)(i, self, xmlstring=self.xmlstrings[j]) self.schedule.add(a) # Add the agent to a random grid cell # x = self.random.randint( # -self.grid.width / 2, self.grid.width / 2) x = 0 # y = self.random.randint( # -self.grid.height / 2, self.grid.height / 2) y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) if (i + 1) % bound == 0: j += 1 def create_environment_object(self, jsondata, obj): """Create env from jsondata.""" name = obj.__name__.lower() temp_list = [] i = 0 for json_object in jsondata[name]: location = (json_object["x"], json_object["y"]) if "q_value" in json_object: temp_obj = obj( i, location, json_object["radius"], q_value=json_object[ "q_value"]) else: temp_obj = obj(i, location, json_object["radius"]) self.grid.add_object_to_grid(location, temp_obj) temp_list.append(temp_obj) i += 1 return temp_list def build_environment_from_json(self): """Build env from jsondata.""" jsondata = JsonData.load_json_file(filename) # Create a instance of JsonData to store object that # needs to be sent to UI self.render = JsonData() self.render.objects = {} for name in jsondata.keys(): obj = eval(name.capitalize()) self.render.objects[name] = self.create_environment_object( jsondata, obj) self.hub = self.render.objects['hub'][0] try: self.foods = [] for site in self.render.objects['sites']: self.site = site # self.render.objects['sites'][0] for i in range(self.num_agents): f = Food( i, location=self.site.location, radius=self.site.radius) f.agent_name = None self.grid.add_object_to_grid(f.location, f) self.foods.append(f) except KeyError: pass if self.viewer: self.ui = UI( (self.width, self.height), [self.hub], self.agents, [self.site], food=self.foods) def step(self): """Step through the environment.""" # Gather info from all the agents # self.gather_info() # Next step self.schedule.step() # Increment the step count self.stepcnt += 1 if self.viewer: self.ui.step() def find_higest_performer(self): """Find the best agent.""" fitness = self.agents[0].individual[0].fitness fittest = self.agents[0] for agent in self.agents: if agent.individual[0].fitness > fitness: fittest = agent return fittest def find_higest_food_collector(self): """Find the best agent to collect food.""" fitness = self.agents[0].food_collected fittest = self.agents[0] for agent in self.agents: if agent.food_collected > fitness: fittest = agent return fittest def detect_food_moved(self): """Detect food moved.""" grid = self.grid food_loc = self.site.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) # print (food_objects) return food_objects def food_in_hub(self): """Find amount of food in hub.""" grid = self.grid food_loc = self.hub.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) return len(food_objects) def food_in_loc(self, loc): """Find amount of food in hub.""" grid = self.grid neighbours = grid.get_neighborhood(loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) return food_objects
class ForagingModel(Model): """A environemnt to model foraging environment.""" def __init__(self, N, width, height, grid=10, iter=100000, seed=None, name='SForaging', viewer=False, parent=None, ratio=1.0): """Initialize the attributes.""" if seed is None: super(ForagingModel, self).__init__(seed=None) else: super(ForagingModel, self).__init__(seed) # Create a unique experiment id self.runid = datetime.datetime.now().timestamp() self.runid = str(self.runid).replace('.', '') # Create the experiment folder # If parent folder exits create inside it if parent is not None and Path(parent).is_dir(): self.pname = parent + '/' + self.runid + '-' + str(ratio) else: self.pname = '/'.join(os.getcwd().split( '/')[:-2]) + '/results/' + self.runid + '-' + str(iter) + name # Define some parameters to count the step self.stepcnt = 1 self.iter = iter # UI self.viewer = viewer # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, name, iter, width, height, grid) self.experiment.insert_experiment() # Get the primary key of the experiment table for future use self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) # Number of agents self.num_agents = N # Environmental grid size self.grid = Grid(width, height, grid) # Schedular to active agents self.schedule = SimultaneousActivation(self) # Empty list of hold the agents self.agents = [] def create_agents(self, random_init=True, phenotypes=None): """Initialize agents in the environment.""" # This is abstract class. Each class inherting this # must define this on its own pass def create_environment_object(self, jsondata, obj): """Create env from jsondata.""" name = obj.__name__.lower() temp_list = [] i = 0 for json_object in jsondata[name]: location = (json_object["x"], json_object["y"]) if "q_value" in json_object: temp_obj = obj(i, location, json_object["radius"], q_value=json_object["q_value"]) else: temp_obj = obj(i, location, json_object["radius"]) self.grid.add_object_to_grid(location, temp_obj) temp_list.append(temp_obj) i += 1 return temp_list def build_environment_from_json(self): """Build env from jsondata.""" jsondata = JsonData.load_json_file(filename) # Create a instance of JsonData to store object that # needs to be sent to UI self.render = JsonData() self.render.objects = {} # First create the agents in the environment for name in jsondata.keys(): obj = eval(name.capitalize()) self.render.objects[name] = self.create_environment_object( jsondata, obj) self.hub = self.render.objects['hub'][0] self.total_food_units = 0 self.foods = [] try: self.site = self.render.objects['sites'][0] for i in range(self.num_agents * 1): f = Food(i, location=self.site.location, radius=self.site.radius) f.agent_name = None self.grid.add_object_to_grid(f.location, f) self.total_food_units += f.weight f.phenotype = dict() self.foods.append(f) except KeyError: pass def step(self): """Step through the environment.""" # Next step self.schedule.step() # Increment the step count self.stepcnt += 1 def gather_info(self): """Gather information from all the agents.""" # diversity = np.ones(len(self.agents)) exploration = np.ones(len(self.agents)) foraging = np.ones(len(self.agents)) fittest = np.ones(len(self.agents)) prospective = np.ones(len(self.agents)) for id in range(len(self.agents)): # diversity[id] = self.agents[id].diversity_fitness # exploration[id] = self.agents[id].exploration_fitness() # foraging[id] = self.agents[id].food_collected # fittest[id] = self.agents[id].individual[0].fitness # prospective[id] = self.agents[id].carrying_fitness() exploration[id] = self.agents[id].exploration_fitness() foraging[id] = self.agents[id].food_collected fittest[id] = self.agents[id].individual[0].fitness prospective[id] = self.agents[id].carrying_fitness() beta = self.agents[-1].beta mean = Best(self.pname, self.connect, self.sn, 1, 'MEAN', self.stepcnt, beta, np.mean(fittest), np.mean(prospective), np.mean(exploration), np.mean(foraging), "None") mean.save() std = Best(self.pname, self.connect, self.sn, 1, 'STD', self.stepcnt, beta, np.std(fittest), np.std(prospective), np.std(exploration), np.std(foraging), "None") std.save() # Compute best agent for each fitness self.best_agents(prospective, beta, "PROSPE") self.best_agents(exploration, beta, "EXPLORE") self.best_agents(foraging, beta, "FORGE") self.best_agents(fittest, beta, "OVERALL") return np.argmax(foraging) def best_agents(self, data, beta, header): """Find the best agents in each category.""" idx = np.argmax(data) # dfitness = self.agents[idx].diversity_fitness ofitness = self.agents[idx].individual[0].fitness ffitness = self.agents[idx].food_collected efitness = self.agents[idx].exploration_fitness() pfitness = self.agents[idx].carrying_fitness() phenotype = self.agents[idx].individual[0].phenotype best_agent = Best(self.pname, self.connect, self.sn, idx, header, self.stepcnt, beta, ofitness, pfitness, efitness, ffitness, phenotype) best_agent.save() def find_higest_performer(self): """Find the best agent.""" fitness = self.agents[0].individual[0].fitness fittest = self.agents[0] for agent in self.agents: if agent.individual[0].fitness > fitness: fittest = agent return fittest def find_higest_food_collector(self): """Find the best agent to collect food.""" fitness = self.agents[0].food_collected fittest = self.agents[0] for agent in self.agents: if agent.food_collected > fitness: fittest = agent return fittest def detect_food_moved(self): """Detect food moved.""" grid = self.grid food_loc = self.site.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) # print (food_objects) return food_objects def foraging_percent(self): """Compute the percent of the total food in the hub.""" grid = self.grid hub_loc = self.hub.location neighbours = grid.get_neighborhood(hub_loc, self.hub.radius) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) _, hub_grid = grid.find_grid(hub_loc) for food in self.foods: _, food_grid = grid.find_grid(food.location) if food_grid == hub_grid: food_objects += [food] food_objects = set(food_objects) total_food_weights = sum([food.weight for food in food_objects]) return ((total_food_weights * 1.0) / self.total_food_units) * 100
def __init__(self, N, width, height, grid=10, iter=100000, seed=None, expname='COT', agent='EvolAgent', parm='swarm_mcarry.txt'): """Initialize the attributes.""" if seed is None: super(EvolModel, self).__init__(seed=None) else: super(EvolModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime("%s") + str( self.random.randint(1, 1000, 1)[0]) self.pname = '/'.join(os.getcwd().split('/')[:-2]) + '/results/' \ + self.runid + expname self.stepcnt = 1 self.iter = iter self.top = None # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, expname, iter, width, height, grid) self.experiment.insert_experiment() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] self.parm = parm # Create agents for i in range(self.num_agents): a = eval(agent)(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) # x = 0 y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) # y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a)
class EvolModel(Model): """A environemnt to model swarms.""" def __init__(self, N, width, height, grid=10, iter=100000, seed=None, expname='COT', agent='EvolAgent', parm='swarm_mcarry.txt'): """Initialize the attributes.""" if seed is None: super(EvolModel, self).__init__(seed=None) else: super(EvolModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime("%s") + str( self.random.randint(1, 1000, 1)[0]) self.pname = '/'.join(os.getcwd().split('/')[:-2]) + '/results/' \ + self.runid + expname self.stepcnt = 1 self.iter = iter self.top = None # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, expname, iter, width, height, grid) self.experiment.insert_experiment() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) self.agents = [] self.parm = parm # Create agents for i in range(self.num_agents): a = eval(agent)(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) # x = 0 y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) # y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) def create_environment_object(self, jsondata, obj): """Create env from jsondata.""" name = obj.__name__.lower() temp_list = [] i = 0 for json_object in jsondata[name]: location = (json_object["x"], json_object["y"]) if "q_value" in json_object: temp_obj = obj(i, location, json_object["radius"], q_value=json_object["q_value"]) else: temp_obj = obj(i, location, json_object["radius"]) self.grid.add_object_to_grid(location, temp_obj) temp_list.append(temp_obj) i += 1 return temp_list def build_environment_from_json(self): """Build env from jsondata.""" jsondata = JsonData.load_json_file(filename) # Create a instance of JsonData to store object that # needs to be sent to UI self.render = JsonData() self.render.objects = {} for name in jsondata.keys(): obj = eval(name.capitalize()) self.render.objects[name] = self.create_environment_object( jsondata, obj) self.hub = self.render.objects['hub'][0] try: self.foods = [] self.site = self.render.objects['sites'][0] food_radius = self.random.randint(20, 30) for i in range(self.num_agents): f = Food(i, location=self.site.location, radius=food_radius) f.agent_name = None f.phenotype = {} self.grid.add_object_to_grid(f.location, f) self.foods.append(f) except KeyError: pass def step(self): """Step through the environment.""" # Gather info from all the agents self.top = self.gather_info() # Next step self.schedule.step() # Increment the step count self.stepcnt += 1 def gather_info(self): """Gather information from all the agents.""" diversity = np.ones(len(self.agents)) exploration = np.ones(len(self.agents)) foraging = np.ones(len(self.agents)) fittest = np.ones(len(self.agents)) for id in range(len(self.agents)): diversity[id] = self.agents[id].diversity_fitness exploration[id] = self.agents[id].exploration_fitness() foraging[id] = self.agents[id].food_collected fittest[id] = self.agents[id].individual[0].fitness beta = self.agents[-1].beta """ mean = Best( self.pname, self.connect, self.sn, 1, 'MEAN', self.stepcnt, beta, np.mean(fittest), np.mean(diversity), np.mean(exploration), np.mean(foraging), "None" ) mean.save() std = Best( self.pname, self.connect, self.sn, 1, 'STD', self.stepcnt, beta, np.std(fittest), np.std(diversity), np.std(exploration), np.std(foraging), "None" ) std.save() """ # Compute best agent for each fitness self.best_agents(diversity, beta, "DIVERSE") self.best_agents(exploration, beta, "EXPLORE") self.best_agents(foraging, beta, "FORGE") self.best_agents(fittest, beta, "OVERALL") return np.argmax(foraging) def best_agents(self, data, beta, header): """Find the best agents in each category.""" idx = np.argmax(data) dfitness = self.agents[idx].diversity_fitness ofitness = self.agents[idx].individual[0].fitness ffitness = self.agents[idx].food_collected efitness = self.agents[idx].exploration_fitness() phenotype = self.agents[idx].individual[0].phenotype best_agent = Best(self.pname, self.connect, self.sn, idx, header, self.stepcnt, beta, ofitness, dfitness, efitness, ffitness, phenotype) best_agent.save() def find_higest_performer(self): """Find the best agent.""" fitness = self.agents[0].individual[0].fitness fittest = self.agents[0] for agent in self.agents: if agent.individual[0].fitness > fitness: fittest = agent return fittest def find_higest_food_collector(self): """Find the best agent to collect food.""" fitness = self.agents[0].food_collected fittest = self.agents[0] for agent in self.agents: if agent.food_collected > fitness: fittest = agent return fittest def detect_food_moved(self): """Detect food moved.""" grid = self.grid food_loc = self.site.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) # print (food_objects) return food_objects def food_in_loc(self, loc): """Find amount of food in hub.""" grid = self.grid neighbours = grid.get_neighborhood(loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) return food_objects
class TestGrid(unittest.TestCase): ''' Testing the grid system of swarm framework ''' def setUp(self): ''' Create three grids system with different grid size ''' self.grid_four_equal_width_height = Grid(24, 24, grid_size=4) self.grid_four_unequal_width_height = Grid(24, 16, grid_size=4) self.grid_five = Grid(20, 20, grid_size=5) def test_location_grid_four_equal_width_height(self): ''' For grid 24x24, point (-1,1) should lie in grid number 21 ''' grid_key, grid_value = self.grid_four_equal_width_height.find_grid( (-1, 1)) self.assertEqual(grid_value, 21) self.assertEqual(grid_key, ((-4, 0), (0, 4))) grid_key, grid_value = self.grid_four_equal_width_height.find_grid( (4, 4)) self.assertEqual(grid_value, 29) self.assertEqual(grid_key, ((4, 4), (8, 8))) def test_location_grid_four_unequal_width_height(self): ''' For grid 24x16, point (-5,1) should lie in grid number 8 ''' grid_key, grid_value = self.grid_four_unequal_width_height.find_grid( (-5, 1)) self.assertEqual(grid_value, 14) self.assertEqual(grid_key, ((-8, 0), (-4, 4))) grid_key, grid_value = self.grid_four_unequal_width_height.find_grid( (7, 7)) self.assertEqual(grid_value, 23) self.assertEqual(grid_key, ((4, 4), (8, 8))) def test_location_grid_five(self): ''' For grid 20x20, point (-1,4) should lie in grid number 10 ''' grid_key, grid_value = self.grid_five.find_grid((-1, 4)) self.assertEqual(grid_value, 10) self.assertEqual(grid_key, ((-5, 0), (0, 5))) grid_key, grid_value = self.grid_five.find_grid((9, 9)) self.assertEqual(grid_value, 16) self.assertEqual(grid_key, ((5, 5), (10, 10))) grid_key, grid_value = self.grid_five.find_grid((-4, -4)) self.assertEqual(grid_value, 6) self.assertEqual(grid_key, ((-5, -5), (0, 0))) grid_key, grid_value = self.grid_five.find_grid((-9, 3)) self.assertEqual(grid_value, 9) self.assertEqual(grid_key, ((-10, 0), (-5, 5))) def test_neighbour_grid_equal_width_height(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point ''' point = (-2, -2) radius = 5 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [8, 9, 10, 14, 15, 16, 20, 21, 22]) radius = 9 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [ 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29 ]) radius = 4 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [15]) def test_neighbour_grid_equal_width_height_big_radius(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point ''' point = (11, 11) radius = 17 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [ 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36 ]) def test_neighbour_grid_equal_width_height_right_horizontal(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for right horizontal end point ''' point = (10, 6) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [35, 36, 23, 24, 29, 30]) def test_neighbour_grid_equal_width_height_upper_verticle(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for upper verticle end point ''' point = (-2, 10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [32, 33, 34, 26, 27, 28]) def test_neighbour_grid_equal_width_height_lower_verticle(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for lower verticle end point ''' point = (6, -10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [4, 5, 6, 10, 11, 12]) def test_neighbour_grid_equal_width_height_left_horizontal(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for left horizontal end point ''' point = (-10, 2) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [13, 14, 19, 20, 25, 26]) def test_neighbour_grid_equal_width_height_bottom_left(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for bottom left end point ''' point = (-10, -10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [8, 1, 2, 7]) def test_neighbour_grid_equal_width_height_top_left(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for top left end point ''' point = (-10, 10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [32, 25, 26, 31]) def test_neighbour_grid_equal_width_height_bottom_right(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for bottom right end point ''' point = (10, -10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [11, 12, 5, 6]) def test_neighbour_grid_equal_width_height_top_right(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point for bottom right end point ''' point = (10, 10) radius = 6 self.assertEqual( self.grid_four_equal_width_height.get_neighborhood(point, radius), [35, 36, 29, 30]) def test_neighbour_grid_unequal_width_height(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point ''' point = (-2, -2) radius = 4 self.assertEqual( self.grid_four_unequal_width_height.get_neighborhood( point, radius), [9]) radius = 5 self.assertEqual( self.grid_four_unequal_width_height.get_neighborhood( point, radius), [2, 3, 4, 8, 9, 10, 14, 15, 16]) def test_neighbour_grid_unequal_width_height_big_radius(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point ''' point = (11, 7) radius = 17 self.assertEqual( self.grid_four_unequal_width_height.get_neighborhood( point, radius), [ 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24 ]) def test_neighbour_grid_five(self): ''' Ensure gird gives accurate results for neighbouring grids with fixed raidus and fixed point ''' point = (2, -2) radius = 5 self.assertEqual(self.grid_five.get_neighborhood(point, radius), [7]) radius = 6 self.assertEqual(self.grid_five.get_neighborhood(point, radius), [2, 3, 4, 6, 7, 8, 10, 11, 12]) def test_modify_points(self): ''' Ensure modifiy points work for points on the edges of the grid box ''' point = (5, 5) self.assertEqual(self.grid_five.modify_points(point), (6, 6)) # This point is the extrem point. Modify point should decrease it point = (10, 10) self.assertEqual(self.grid_five.modify_points(point), (6, 6)) # This point is the starting point. Modify point should increase it self.assertEqual(self.grid_five.modify_points((-10, -10)), (-9, -9))
def __init__(self, N, width, height, grid=10, iter=100000, xmlstrings=None, seed=None, viewer=False, pname=None): """Initialize the attributes.""" if seed is None: super(SimModelComm, self).__init__(seed=None) else: super(SimModelComm, self).__init__(seed) self.runid = datetime.datetime.now().timestamp() self.runid = str(self.runid).replace( '.', '') + '-' + str(prob).replace('.', '') #self.runid = datetime.datetime.now().strftime( # "%s") + str(self.random.randint(1, 1000, 1)[0]) if pname is None: self.pname = os.getcwd() + '/' + self.runid + "SForagingSimulation" else: self.pname = pname + '/' + self.runid + "SForagingSimulation" # self.pname = os.getcwd() + '/' + self.runid + "SFCommSimulation" self.width = width self.height = height self.stepcnt = 1 self.iter = iter self.xmlstrings = xmlstrings self.viewer = viewer # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, 'Simuation SFComm', iter, width, height, grid, phenotype=xmlstrings[0]) self.experiment.insert_experiment_simulation() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) # self.site = Sites(id=1, location=(5, 5), radius=11, q_value=0.5) # self.grid.add_object_to_grid(self.site.location, self.site) # self.hub = Hub(id=1, location=(0, 0), radius=11) # self.grid.add_object_to_grid(self.hub.location, self.hub) self.agents = [] bound = np.ceil((self.num_agents * 1.0) / len(self.xmlstrings)) j = 0 # Create agents for i in range(self.num_agents): # print (i, j, self.xmlstrings[j]) a = SimAgent(i, self, xmlstring=self.xmlstrings[j]) self.schedule.add(a) # Add the agent to a random grid cell # x = self.random.randint( # -self.grid.width / 2, self.grid.width / 2) x = 0 # y = self.random.randint( # -self.grid.height / 2, self.grid.height / 2) y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) if (i + 1) % bound == 0: j += 1
class RunEnvironmentModel(Model): """A environemnt to model swarms.""" def __init__(self, N, width, height, grid=10, iter=100000, xmlstring=None, seed=None): """Initialize the attributes.""" if seed is None: super(RunEnvironmentModel, self).__init__(seed=None) else: super(RunEnvironmentModel, self).__init__(seed) self.runid = datetime.datetime.now().strftime("%s") + str( self.random.randint(1, 1000, 1)[0]) self.pname = os.getcwd() + '/' + self.runid + "SFCommSimulation" self.stepcnt = 1 self.iter = iter self.xmlstring = xmlstring # Create db connection connect = Connect('swarm', 'swarm', 'swarm', 'localhost') self.connect = connect.tns_connect() # Fill out the experiment table self.experiment = Experiment(self.connect, self.runid, N, seed, 'Simuation SFComm', iter, width, height, grid, phenotype=xmlstring) self.experiment.insert_experiment_simulation() self.sn = self.experiment.sn # Create a folder to store results os.mkdir(self.pname) self.num_agents = N self.grid = Grid(width, height, grid) self.schedule = SimultaneousActivation(self) # self.site = Sites(id=1, location=(5, 5), radius=11, q_value=0.5) # self.grid.add_object_to_grid(self.site.location, self.site) # self.hub = Hub(id=1, location=(0, 0), radius=11) # self.grid.add_object_to_grid(self.hub.location, self.hub) self.agents = [] # Create agents for i in range(self.num_agents): a = RunSwarmAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = self.random.randint(-self.grid.width / 2, self.grid.width / 2) # x = 0 y = self.random.randint(-self.grid.height / 2, self.grid.height / 2) # y = 0 a.location = (x, y) self.grid.add_object_to_grid((x, y), a) a.operation_threshold = 2 # self.num_agents // 10 self.agents.append(a) # Add equal number of food source # for i in range(20): # f = Food(i, location=(-29, -29), radius=5) # self.grid.add_object_to_grid(f.location, f) # print (i,x,y) def create_environment_object(self, jsondata, obj): """Create env from jsondata.""" name = obj.__name__.lower() temp_list = [] i = 0 for json_object in jsondata[name]: location = (json_object["x"], json_object["y"]) if "q_value" in json_object: temp_obj = obj(i, location, json_object["radius"], q_value=json_object["q_value"]) else: temp_obj = obj(i, location, json_object["radius"]) self.grid.add_object_to_grid(location, temp_obj) temp_list.append(temp_obj) i += 1 return temp_list def build_environment_from_json(self): """Build env from jsondata.""" jsondata = JsonData.load_json_file(filename) # Create a instance of JsonData to store object that # needs to be sent to UI self.render = JsonData() self.render.objects = {} for name in jsondata.keys(): obj = eval(name.capitalize()) self.render.objects[name] = self.create_environment_object( jsondata, obj) self.hub = self.render.objects['hub'][0] try: self.site = self.render.objects['sites'][0] for i in range(self.num_agents * 2): f = Food(i, location=self.site.location, radius=self.site.radius) f.agent_name = None self.grid.add_object_to_grid(f.location, f) except KeyError: pass def step(self): """Step through the environment.""" # Gather info from all the agents # self.gather_info() # Next step self.schedule.step() # Increment the step count self.stepcnt += 1 def find_higest_performer(self): """Find the best agent.""" fitness = self.agents[0].individual[0].fitness fittest = self.agents[0] for agent in self.agents: if agent.individual[0].fitness > fitness: fittest = agent return fittest def find_higest_food_collector(self): """Find the best agent to collect food.""" fitness = self.agents[0].food_collected fittest = self.agents[0] for agent in self.agents: if agent.food_collected > fitness: fittest = agent return fittest def detect_food_moved(self): """Detect food moved.""" grid = self.grid food_loc = self.site.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) # print (food_objects) return food_objects def food_in_hub(self): """Find amount of food in hub.""" grid = self.grid food_loc = self.hub.location neighbours = grid.get_neighborhood(food_loc, 10) food_objects = grid.get_objects_from_list_of_grid('Food', neighbours) return len(food_objects)