예제 #1
0
파일: model.py 프로젝트: tiwarip1/mesa
    def __init__(self,
                 population=100,
                 width=100,
                 height=100,
                 speed=1,
                 vision=10,
                 separation=2,
                 cohere=0.025,
                 separate=0.25,
                 match=0.04):
        '''
        Create a new Flockers model.

        Args:
            population: Number of Boids
            width, height: Size of the space.
            speed: How fast should the Boids move.
            vision: How far around should each Boid look for its neighbors
            separation: What's the minimum distance each Boid will attempt to
                    keep from any other
            cohere, separate, match: factors for the relative importance of
                    the three drives.        '''
        self.population = population
        self.vision = vision
        self.speed = speed
        self.separation = separation
        self.schedule = RandomActivation(self)
        self.space = ContinuousSpace(width, height, True)
        self.factors = dict(cohere=cohere, separate=separate, match=match)
        self.make_agents()
        self.running = True
    def __init__(self, ax, ax2):
        self.schedule = RandomActivation(self)
        self.grid = ContinuousSpace(400, 400, True)
        self.ax = ax
        self.ax2 = ax2

        # Creating all agents
        enemy_inf1 = EnInfantry(1, self, 10, enemy1_locx, enemy1_locy, self.ax)
        self.schedule.add(enemy_inf1)
        self.grid.place_agent(enemy_inf1, (enemy1_locx, enemy1_locy))

        enemy_arty1 = EnArty(10, self, 30, enemy2_locx, enemy2_locy, self.ax)
        self.schedule.add(enemy_arty1)
        self.grid.place_agent(enemy_arty1, (enemy2_locx, enemy2_locy))

        enemy_tank1 = EnArmour(20, self, 20, enemy3_locx, enemy3_locy, self.ax)
        self.schedule.add(enemy_tank1)
        self.grid.place_agent(enemy_tank1, (enemy3_locx, enemy3_locy))

        friendly_unit1 = FrUnit(30, self, friendly_unit_health,
                                frUnit_init_locx, frUnit_init_locy, self.ax,
                                self.ax2)
        self.schedule.add(friendly_unit1)
        self.grid.place_agent(friendly_unit1,
                              (frUnit_init_locx, frUnit_init_locy))

        friendly_arty = FrArty(40, self, 10, fs_init_locx, fs_init_locy,
                               self.ax)
        self.schedule.add(friendly_arty)
        self.grid.place_agent(friendly_arty, (fs_init_locx, fs_init_locy))
예제 #3
0
파일: model.py 프로젝트: tropappar/flocking
    def __init__(self, formation, population, width, height, vision, min_dist,
                 flock_vel, accel_time, equi_dist, repulse_max, repulse_spring,
                 align_frict, align_slope, align_min, wall_decay, wall_frict,
                 form_shape, form_track, form_decay, wp_tolerance):
        '''
        Create a new Flockers model.

        Args:
            population: Number of agents.
            width, height: Size of the space.
            vision: How far around should each agents look for its neighbors.
            min_dist: Minimum allowed distance between agents before a collision occurs. This is only used for statistics.
        '''
        # set parameters
        self.population = population
        self.space = ContinuousSpace(width, height, torus=False)
        self.vision = vision
        self.min_dist = min_dist
        self.params = dict(formation=formation,
                           population=population,
                           flock_vel=flock_vel,
                           accel_time=accel_time,
                           equi_dist=equi_dist,
                           repulse_max=repulse_max,
                           repulse_spring=repulse_spring,
                           align_frict=align_frict,
                           align_slope=align_slope,
                           align_min=align_min,
                           wall_decay=wall_decay,
                           wall_frict=wall_frict,
                           form_shape=form_shape,
                           form_track=form_track,
                           form_decay=form_decay,
                           wp_tolerance=wp_tolerance)

        # data collection for plots
        self.datacollector = DataCollector(
            model_reporters={
                "Minimum Distance": minimum_distance,
                "Maximum Distance": maximum_distance,
                "Average Distance": average_distance,
                "Collisions": collisions,
                "Messags Distributed": messages_distributed,
                "Messags Centralized": messages_centralized
            })

        # execute agents sequentially in a random order
        self.schedule = RandomActivation(self)

        # place agents
        self.make_agents()

        # pairwise distances
        self.agent_distances()

        # run model
        self.running = True

        # collect initial data sample
        self.datacollector.collect(self)
예제 #4
0
    def __init__(self, ax, ax2):
        self.schedule = BaseScheduler(self)
        self.grid = ContinuousSpace(400, 400, True)
        self.ax = ax
        self.ax2 = ax2

        # Creating all agents
        # All agents are activated in the order they are added to the scheduler.
        friendly_arty = FrArty(10, self, 10, fsUnit_loc[0], fsUnit_loc[1],
                               self.ax, enemy1_loc, fsUnit_loc,
                               ammunition_heavy_round, ammunition_light_round)
        self.schedule.add(friendly_arty)
        self.grid.place_agent(friendly_arty, (fsUnit_loc[0], fsUnit_loc[1]))

        friendly_unit1 = FrUnit(11, self, friendly_unit_health,
                                frUnit_init_loc[0], frUnit_init_loc[1],
                                self.ax, self.ax2, fsUnit_loc)
        self.schedule.add(friendly_unit1)
        self.grid.place_agent(friendly_unit1,
                              (frUnit_init_loc[0], frUnit_init_loc[1]))

        enemy_inf1 = EnInfantry(1, self, 20, enemy1_loc[0], enemy1_loc[1],
                                self.ax, fsUnit_loc, enemy1_loc)
        self.schedule.add(enemy_inf1)
        self.grid.place_agent(enemy_inf1, (enemy1_loc[0], enemy1_loc[1]))

        enemy_arty1 = EnArty(2, self, 20, enemy2_loc[0], enemy2_loc[1],
                             self.ax, fsUnit_loc, enemy2_loc)
        self.schedule.add(enemy_arty1)
        self.grid.place_agent(enemy_arty1, (enemy2_loc[0], enemy2_loc[1]))

        enemy_tank1 = EnArmour(3, self, 20, enemy3_loc[0], enemy3_loc[1],
                               self.ax, fsUnit_loc, enemy3_loc)
        self.schedule.add(enemy_tank1)
        self.grid.place_agent(enemy_tank1, (enemy3_loc[0], enemy3_loc[1]))
예제 #5
0
    def __init__(self, N=200, width=20, height=20):
        self.num_agents = int(N / 2)
        self.grid = ContinuousSpace(height, width, True)
        self.redAgentList = []
        self.blueAgentList = []
        self.turn = 1

        #redLethality = input("Enter Red team lethality coefficient")
        #blueLethality = input("Enter Blue team lethality coefficient")

        # Create Red and Blue agents
        for i in range(self.num_agents):
            a = RedSoldier(i, self)
            self.redAgentList.append(a)

            # add red soldier to random location on grid
            rx = self.random.randrange(self.grid.width)
            ry = self.random.randrange(self.grid.height)
            self.grid.place_agent(a, (rx, ry))

            b = BlueSoldier(i, self)
            self.blueAgentList.append(b)

            # add blue soldier to random location on grid
            bx = self.random.randrange(self.grid.width)
            by = self.random.randrange(self.grid.height)
            self.grid.place_agent(b, (bx, by))

        self.running = True
예제 #6
0
    def __init__(self, floorplan, human_count):
        super().__init__()
        self.n_agents = human_count
        self.floorplan = []
        self.humans = []
        self.obstacles = []
        self.exits = []
        self.spawns = []
        self.scheduler = DistanceScheduler(self)

        # Loads floorplan textfile
        with open('C:/Users/jozse/github/ABMasters/floorplans/' +
                  floorplan) as f:
            [
                self.floorplan.append(line.strip().split())
                for line in f.readlines()
            ]

        # Creates continuous Mesa space & discrete grid for pathfinding
        size = len(self.floorplan[0]), len(self.floorplan)
        self.space = ContinuousSpace(size[0], size[1], torus=False)
        self.grid = []

        for y in range(6 * size[1]):
            row = []
            for x in range(6 * size[0]):
                row.append(ca.Node((x, y)))
            self.grid.append(row)

# Places all elements in Mesa space and grid
        for x in range(size[0]):
            for y in range(size[1]):
                value = str(self.floorplan[y][x])

                if value == 'W':
                    self.new_agent(ca.Wall, (x, y))
                    for i in range(6 * x, 6 * (x + 1)):
                        for j in range(6 * y, 6 * (y + 1)):
                            self.grid[j][i].done = True

                elif value == 'F':
                    self.new_agent(ca.Furniture, (x, y))
                    for i in range(6 * x, 6 * (x + 1)):
                        for j in range(6 * y, 6 * (y + 1)):
                            self.grid[j][i].done = True

                elif value == 'S':
                    self.spawns.append((x, y))

                elif value == 'E':
                    self.new_agent(ca.Exit, (x, y))
                    i = 6 * x + 1
                    j = 6 * y + 1
                    self.grid[j][i].exit = True

        # Spawn specified number of Humans in spawn points
        humans = rnd.sample(self.spawns, self.n_agents)
        for pos in humans:
            self.new_agent(ca.Human, pos)
        print("Classroom initialised.")
예제 #7
0
파일: model.py 프로젝트: elbertlin168/chaos
    def __init__(self,
                 agent_type,
                 width=500,
                 height=500,
                 num_adversaries=8,
                 road_width=60,
                 frozen=True,
                 epsilon=0,
                 episode_duration=100,
                 Q=None,
                 N=None):
        self.num_adversaries = num_adversaries
        self.road_width = road_width
        self.episode_duration = episode_duration
        self.schedule = RandomActivation(self)

        self.space = ContinuousSpace(width, height, True)
        self.cars = []

        self.make_agents(AgentType(agent_type), frozen, epsilon, Q, N)
        self.running = True

        self.step_count = 0
        self.count = 0
        self.curr_reward = 0

        self.reset()

        self.datacollector = DataCollector(
            model_reporters={"Agent rewards sum": get_rewards_sum_log})
 def __init__(self,
              population=100,
              width=100,
              height=100,
              speed=1,
              vision=10,
              separation=2,
              cohere=0.025,
              separate=0.25,
              match=0.04):
     # Todo: add parameter for blind spot
     """
     Create a new Boids model. Args:
         N: Number of Boids
         width, height: Size of the space.
         speed: how fast the boids should move.
         vision: how far around should each Boid look for its neighbors
         separation: what's the minimum distance each Boid will attempt to
                     keep from any other
         cohere, separate, match: factors for the relative importance of
                                  the three drives.
     """
     self.population = population
     self.vision = vision
     self.speed = speed
     self.separation = separation
     self.schedule = RandomActivation(self)
     self.space = ContinuousSpace(width, height, torus=True,
                                  grid_width=10, grid_height=10)
     self.factors = dict(cohere=cohere, separate=separate, match=match)
     self.make_agents()
     self.running = True
예제 #9
0
    def __init__(self, red_col, red_row, red_squad, blue_col, blue_row,
                 blue_squad, blue_agents_elite_squad, red_movement,
                 blue_movement, width, height):
        self.running = True
        self.space = ContinuousSpace(width, height, False)
        self.schedule = RandomActivation(self)
        self.next_agent_id = 1

        self.RED_MOVEMENT_SPEED = red_movement
        self.BLUE_MOVEMENT_SPEED = blue_movement

        separation_y = 1.5
        # Find center
        red_first_y = ((height / 2 -
                        (red_squad * red_row / 2 * separation_y)) +
                       separation_y / 2) - ((red_squad - 1) * separation_y * 2)
        blue_first_y = (
            (height / 2 - (blue_squad * blue_row / 2 * separation_y)) +
            separation_y / 2) - ((blue_squad - 1) * separation_y * 2)

        # Create agents
        self.spawner(15.0, red_first_y, 1.5, separation_y, red_col, red_row,
                     red_squad, 0, 'red')
        self.spawner(width - 15.0, blue_first_y, -1.5, separation_y, blue_col,
                     blue_row, blue_squad, blue_agents_elite_squad, 'blue')
예제 #10
0
    def __init__(self):
        self.num_agents_sita = 20
        self.num_agents_ue = 20
        self.num_kabe = 1
        self.schedule = SimultaneousActivation(self)
        self.width = 10
        self.height = 50
        self.space = ContinuousSpace(self.width, self.height, True)
        self.syudan_hito_sita = np.zeros((self.num_agents_sita, 2))
        self.syudan_hito_ue = np.zeros((self.num_agents_ue, 2))
        self.syudan_kabe = np.zeros((self.num_kabe, 2))
        self.time = 1000
        # Create agents
        for i in range(self.num_agents_sita):
            a = Hokousya_sita(i, self)
            self.schedule.add(a)
            self.syudan_hito_sita[i,0] = a.iti_x
            self.syudan_hito_sita[i,1] = a.iti_y

        for i in range(self.num_agents_ue):
            b = Hokousya_ue(i, self)
            self.schedule.add(b)
            self.syudan_hito_ue[i,0] = b.iti_x
            self.syudan_hito_ue[i,1] = b.iti_y
        #壁を作る
        for i in range(self.num_kabe):
            c = Kabe(i, self)
            self.schedule.add(c)
            self.syudan_kabe[i, 0] = c.iti[0]
            self.syudan_kabe[i, 1] = c.iti[1]
    def __init__(self, Prey_count, Tiger_count, width, height, CANVAS):
        self.count = 0  # Number of agents
        self.schedule = mesa.time.RandomActivation(self)
        self.space = ContinuousSpace(width + 1, height + 1, torus=False)
        self.step_num = 0
        self.last_uid = 0
        self.canvas = CANVAS
        self.grass_ticks = dict()
        self.Prey_count = 0
        self.Tiger_count = 0

        # Create patches
        for x, y in itertools.product(range(width), range(height)):
            a = Patch(self.new_uid(), self)
            # self.schedule.add(a)
            self.space.place_agent(a, (x, y))
            a.canvas = CANVAS
            a.draw()

        # Create Animals:
        for i in range(Prey_count):
            x = random.randrange(self.space.width)
            y = random.randrange(self.space.width)
            self.create_baby(x, y, age=random.randint(1, 5))
        for i in range(Tiger_count):
            x = random.randrange(self.space.width)
            y = random.randrange(self.space.width)
            self.create_baby(x, y, age=random.randint(1, 5), type='Tiger')
예제 #12
0
파일: kotu0120.py 프로젝트: tontonchin/m2
    def __init__(self):
        self.num_agents_sita = 30
        self.num_agents_ue = 30
        self.num_kabe = 1
        self.schedule = RandomActivationByBreed(self)
        #self.schedule = RandomActivation(self)
        self.width = 10
        self.height = 50
        self.space = ContinuousSpace(self.width, self.height, True)
        self.syudan_hito_sita = np.zeros((self.num_agents_sita, 2))
        self.syudan_hito_ue = np.zeros((self.num_agents_ue, 2))
        self.syudan_kabe = np.zeros((self.num_kabe, 2))
        self.time = 1000
        # Create agents

        for j in range(self.num_agents_sita):
            a = Hokousya_sita(j, self)
            self.syudan_hito_sita[j, 0] = a.iti_x
            self.syudan_hito_sita[j, 1] = a.iti_y
            self.schedule.add(a)
            #self.syudan_hito_sita[i,0] = a.iti_x
            #self.syudan_hito_sita[i,1] = a.iti_y

        for i in range(self.num_agents_ue):
            b = Hokousya_ue(i, self)
            self.syudan_hito_ue[i, 0] = b.iti_x
            self.syudan_hito_ue[i, 1] = b.iti_y
            self.schedule.add(b)
예제 #13
0
    def __init__(self, width=100, height=100, torus=True):
        self.running = True
        self.unique_id_counter = 0
        # number from 1 to 4, indicating the stage of the day
        self.firm_count = 0
        self.household_count = 0

        self.households = []
        self.firms = []
        self.luxury_firms = []

        self.daily_tick = 0

        self.money_supply = 10e6
        self.population = 10
        self.luxury_price = 0
        self.gdp = 0

        self.space = ContinuousSpace(width, height, torus)
        self.schedule = BaseScheduler(self)

        self._populate()

        # Networking
        self.G = nx.Graph()
        self._make_network()

        # Data collection
        self.datacollector = DataCollector(
            model_reporters={'agg_wealth': compute_agg_wealth}
            #agent_reporters = {TODO if you need to}
        )
예제 #14
0
    def __init__(self,
                 N=1,
                 O=1,
                 sensorRange=5,
                 target_speed=1.0,
                 active_prediction=False,
                 a=1,
                 width=150,
                 height=150):
        super().__init__()
        #self.running = True
        self.num_agents = N
        self.num_observer_agents = O
        self.target_speed = target_speed
        self.multiplication_factor = 1.0 / target_speed
        self.sensor_range = sensorRange  # * self.multiplication_factor
        self.targets_observed = set()
        self.grid = ContinuousSpace(int(width), int(height), False)
        self.schedule = RandomActivation(self)
        self.observers_indications = []
        self.a = a
        self.active_prediction = active_prediction

        self.verbose = False  # Print-monitoring

        #        self.datacollector = DataCollector(
        #            {"Wolves": lambda m: m.schedule.get_breed_count(Wolf),
        #             "Sheep": lambda m: m.schedule.get_breed_count(Sheep)})

        # Create targets
        for i in range(self.num_agents):
            # Add the agent to a random grid cell
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)
            a = TargetAgent("t_" + str(i), (x, y), self, self.target_speed)
            self.schedule.add(a)

            self.grid.place_agent(a, (x, y))

        # Create observers
        for i in range(self.num_observer_agents):
            #b = ObserverAgent("o_"+str(i), self.sensor_range, self.multiplication_factor, self)

            # Add the agent to a kmens indication
            self.observers_indications = self.kmeans_indications()
            point = self.observers_indications[i]
            x = math.floor(point[0])
            y = math.floor(point[1])
            b = ObserverAgent("o_" + str(i), (x, y), self, self.sensor_range,
                              self.multiplication_factor)
            self.schedule.add(b)

            self.grid.place_agent(b, (x, y))

        self.datacollector = DataCollector(
            model_reporters={"Observation": "mean_observation"})
예제 #15
0
    def __init__(self,
                 height=100,
                 width=100,
                 init_prey=100,
                 prey_reproduction=0.03,
                 init_predator=10,
                 predator_vision=1,
                 predator_reproduction=0.5,
                 predator_death=0.02,
                 local_offspring=False,
                 max_iters=500,
                 seed=None):

        super().__init__()

        self.height = height
        self.width = width
        self.init_prey = init_prey
        self.prey_reproduction = prey_reproduction
        self.init_predator = init_predator
        self.predator_vision = predator_vision
        self.predator_reproduction = predator_reproduction
        self.predator_death = predator_death
        self.local_offspring = local_offspring
        self.iteration = 0
        self.max_iters = max_iters
        self.schedule = RandomActivation(self)
        self.space = ContinuousSpace(height, width, torus=True)
        model_reporters = {
            'Prey': lambda model: self.count('Prey'),
            'Predator': lambda model: self.count('Predator'),
        }

        self.datacollector = DataCollector(model_reporters=model_reporters)

        # Place prey
        for i in range(self.init_prey):
            x = self.random.uniform(0, self.width)
            y = self.random.uniform(0, self.height)
            # next_id() starts at 1
            prey = Prey(self.next_id(), self, (x, y), self.prey_reproduction)
            self.space.place_agent(prey, (x, y))
            self.schedule.add(prey)

        # Place predators
        for i in range(self.init_predator):
            x = self.random.uniform(0, self.width)
            y = self.random.uniform(0, self.height)
            predator = Predator(self.next_id(), self, (x, y),
                                self.predator_reproduction,
                                self.predator_death, self.predator_vision)
            self.space.place_agent(predator, (x, y))
            self.schedule.add(predator)

        self.running = True
        self.datacollector.collect(self)
예제 #16
0
파일: test_space.py 프로젝트: tubks/mesa
 def setUp(self):
     """
     Create a test space and populate with Mock Agents.
     """
     self.space = ContinuousSpace(70, 50, False, -30, -30)
     self.agents = []
     for i, pos in enumerate(REMOVAL_TEST_AGENTS):
         a = MockAgent(i, None)
         self.agents.append(a)
         self.space.place_agent(a, pos)
예제 #17
0
 def setUp(self):
     '''
     Create a test space and populate with Mock Agents.
     '''
     self.space = ContinuousSpace(70, 20, False, -30, -30, 100, 100)
     self.agents = []
     for i, pos in enumerate(TEST_AGENTS):
         a = MockAgent(i, None)
         self.agents.append(a)
         self.space.place_agent(a, pos)
예제 #18
0
    def __init__(self):
        super().__init__()
        self.schedule = SimultaneousActivation(self)
        self.grid = ContinuousSpace(75, 40, False)

        ## Creation des agents de base
        for _ in range(1):
            a = Walker(self.next_id(), self)
            self.schedule.add(a)
            self.grid.place_agent(a, (0, 0))
예제 #19
0
    def __init__(self,
                 seed=None,
                 population=100,
                 width=500,
                 height=500,
                 initial_proportion_sick=0.1,
                 proportion_moving=0.5,
                 speed=1.0,
                 time_until_symptomatic=3,
                 transmission_probability=0.2,
                 transmission_distance=1.0,
                 recovery_probability=0.6,
                 death_probability=0.02,
                 quarantine_probability=0.5):
        """
        Create a new Transmission model.



Potential things to add
# age as an attribute.
# differential mobility as a function of age.
# differential recovery as a function of age.
# time dependence of recovery (e.g., sick for longer = higher probability of death?)
# non random walking
# add another state that is self quarantied (based on time to symptoms), so movers and nonmovers can become
# self quarantied after symptoms arise. Then they don't transmit.

                     """
        super(Transmission, self).__init__(seed=seed)
        self.population = population
        self.proportion_moving = proportion_moving
        self.initial_proportion_sick = initial_proportion_sick
        self.speed = speed

        self.schedule = RandomActivation(self)
        self.space = ContinuousSpace(width, height, True)
        self.factors = dict(transmission_probability=transmission_probability,
                            recovery_probability=recovery_probability,
                            death_probability=death_probability,
                            transmission_distance=transmission_distance,
                            time_until_symptomatic=time_until_symptomatic,
                            quarantine_probability=quarantine_probability)

        self.make_agents()
        self.running = True

        self.datacollector = DataCollector(
            model_reporters={
                "uninfected": analyze_uninfected,
                "sick": analyze_sick,
                "recovered": analyze_recovered,
                "dead": analyze_dead,
                "quarantined": analyze_quarantined,
            })
예제 #20
0
    def __init__(self, N, width, height):
        self.num_agents = N
        self.grid = ContinuousSpace(width, height, False)
        self.schedule = SimultaneousActivation(self)
        for i in range(self.num_agents):
            a = StudentAgent(i, self)
            self.schedule.add(a)

            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))
예제 #21
0
    def __init__(self, floorplan, human_count):
        super().__init__()
        self.n_agents = human_count
        self.floorplan = []
        self.humans = []
        self.obstacles = []
        self.exits = []
        self.spawns = []
        self.scheduler = DistanceScheduler(self)

        # Creates continuous Mesa space & discrete grid for pathfinding
        size = len(self.floorplan[0]), len(self.floorplan)
        self.space = ContinuousSpace(size[0], size[1], torus=False)
        self.grid = []

        for y in range(6 * size[1]):
            row = []
            for x in range(6 * size[0]):
                row.append(ca.Node((x, y)))
            self.grid.append(row)

# Places all elements in Mesa space and grid
        for x in range(size[0]):
            for y in range(size[1]):
                value = str(self.floorplan[y][x])

                if value == 'W':
                    self.new_agent(ca.Wall, (x, y))
                    for i in range(6 * x, 6 * (x + 1)):
                        for j in range(6 * y, 6 * (y + 1)):
                            self.grid[j][i].done = True

                elif value == 'F':
                    self.new_agent(ca.Furniture, (x, y))
                    for i in range(6 * x, 6 * (x + 1)):
                        for j in range(6 * y, 6 * (y + 1)):
                            self.grid[j][i].done = True

                elif value == 'S':
                    self.spawns.append((x, y))

                elif value == 'E':
                    self.new_agent(ca.Exit, (x, y))
                    i = 6 * x + 1
                    j = 6 * y + 1
                    self.grid[j][i].exit = True

        # Spawn n_agents according to floorplan
        for pos in rnd.sample(self.spawns, self.n_agents):
            self.new_agent(ca.Human, pos)
예제 #22
0
    def __init__(self, x_max, y_max, species, iterations):
        super(SimulationModel, self).__init__()

        self.starved = 0
        self.space = ContinuousSpace(x_max,
                                     y_max,
                                     grid_width=20,
                                     grid_height=20,
                                     torus=True)
        self.schedule = SimultaneousActivation(self)

        self.iterations = iterations

        self.species = []
        self.create_population(species)
예제 #23
0
 def __init__(self, num_agents, num_food, width, height, prob_pheromones,
              prob_create_nest, min_dist_between_nests):
     self.width = width
     self.height = height
     self.center = (width / 2, height / 2)
     self.num_agents = num_agents
     self.num_food = num_food
     self.prob_pheromones = prob_pheromones
     self.prob_create_nest = prob_create_nest
     self.min_dist_between_nests = min_dist_between_nests
     self.space = ContinuousSpace(width, height, True, 0, 0)
     self.schedule = RandomActivation(self)
     self.running = True
     self.agent_count = 0
     self.food_distribution = "clustered"
     self.generate_nest(self.center)
     self.generate_ants()
     self.generate_food()
예제 #24
0
    def __init__(self, grid_size=GRID_DIM, gang_info=GANGS, pars=PARS):
        super().__init__()

        self.width, self.height = grid_size
        self.area = ContinuousSpace(self.width, self.height, False)
        self.gang_info = gang_info
        self.parameters = pars
        self.total_gangs = len(self.gang_info)
        self.rivalry_matrix = np.zeros((self.total_gangs, self.total_gangs))
        self.road_density = np.random.rand(self.width, self.height)
        self.schedule_GangMember = OneRandomActivation(self)
        self.init_population()
        self.datacollector = DataCollector({
            "Interaction":
            lambda m: self.schedule_GangMember.get_agent_count()
        })
        self.running = True
        self.datacollector.collect(self)
예제 #25
0
    def __init__(self, N, width, height, neighbor_distance):
        self.num_agents = N
        self.neighbor_distance = neighbor_distance
        self.grid = ContinuousSpace(width, height,
                                    True)  # True is for torroidal
        self.schedule = RandomActivation(self)
        # Create agents
        for i in range(self.num_agents):
            agent = PrestigeAgent(i, i, self)
            self.schedule.add(agent)

            # Add the agent to a random grid cell
            #x = random.randrange(self.grid.width)
            x = i % self.grid.width
            #y = random.randrange(self.grid.height)
            y = i // self.grid.height

            self.grid.place_agent(agent, (x, y))

        agents_pos = [a.pos for a in self.schedule.agents]
        for a in self.schedule.agents:
            #all the agents including themselves
            a.all_agents = self.schedule.agents

            # all the agents, but not themselves -- if the other agents position isn't your your own position
            a.other_agents = [aa for aa in self.schedule.agents if aa != a]

            # use the get_distance function to calc distance from you to all the agents (including themselves)
            a.agents_dist = [self.get_distance(a.pos, p) for p in agents_pos]

            # all the agents close enough to you to count as a neighbor (but not yourself)
            a.neighbors = [
                aa for aa, d in zip(a.all_agents, a.agents_dist)
                if aa != a and d < self.neighbor_distance
            ]
            #zip together the two lists to iterate through both, then create new list of neighbors who meet neighbor_distance criteria

            #print("**********")
            #print(a.unique_id)
            #print([b.unique_id for b in a.all_agents])
            #print(a.agents_dist)

        self.datacollector = DataCollector(
            agent_reporters={"Copies": lambda a: a.copies})
예제 #26
0
    def __init__(self, number_of_customers, number_of_infected, social_distance_prob=0.80,
                 size='small'):

        super(SupermarketModel).__init__()

        self._num_customers = number_of_customers
        self._num_infected = number_of_infected
        self._step_count = 0
        self._enter_time = 0

        #  store environment
        self.width, self.height = STORE_SIZES[size][0] // 2, STORE_SIZES[size][1] // 2
        floor_area = self.width * self.height
        #  TODO: Environment should become non-toroidal.
        self.space = ContinuousSpace(self.width, self.height, True)
        model_description = {  # this gets updated during store planning
            "area": floor_area,
            "width": self.width,
            "height": self.height,
        }
        self._store_environment = Store(model_description)
        self.shelves = self._store_environment.generate_store()
        self._generate_store_shelves()

        #  scheduler
        self.schedule = RandomActivation(self)
        if social_distance_prob > 1.0:
            social_distance_prob = social_distance_prob / 100
        self._social_distance_prob = social_distance_prob

        #  data collector
        self._simulated_dataset = pd.DataFrame()
        self.datacollector = DataCollector(
            {
                "Healthy": lambda m: self.count_agents_with_state(m, "Healthy"),
                "Risky": lambda m: self.count_agents_with_state(m, "Risky"),
                "Exposed": lambda m: self.count_agents_with_state(m, "Exposed"),
                "Infected": lambda m: self.count_agents_with_state(m, "Infected"),
            })

        #  add shoppers into the supermarket
        self.add_agents(self._num_customers, self._num_infected)
        self.running = True
        self.datacollector.collect(self)
예제 #27
0
 def __init__(self, airports, steps_per_hour, width=500, height=500):
     '''
     Create a new Fleet model.
     Args:
         airports: a pandas DataFrame with airport name ,  location ,
             probability density function parameters and refuelingRate
             {name, x, y, pdfParams ,refuelingRate, num_uavs}
         steps_per_hour: the number of steps per hour unit of time
         width, height: Size of the space.
     '''
     self._airports = airports
     #        self._num_uav_per_airport = num_uav_per_airport
     #        self._number_of_uavs = self._num_uav_per_airport * len(airports)
     self._steps_per_hour = steps_per_hour
     self.schedule = RandomActivationByType(self)
     self.space = ContinuousSpace(width, height, False)
     self.parcel_aggregator = list()
     self.make_agents()
     self.running = True
예제 #28
0
    def __init__(self,
                 population=100,
                 width=100,
                 height=100,
                 mobility=6,
                 social_distance=2,
                 asymptomatic_percentage=50.0,
                 imperial=True):
        '''
        Create a new Covid model.

        Args:
            population: Number of people (density) with one asymptomatic infected person.
            imperial: Agent rotates between home, work and community.  For home the agent returns to a random point near a fixed home position.  Community has the agent randomly placed in the space.  Work has 90% like home but with a fixed work position and 10% random like community.  This is patterned after the Imperial College model.  Turning off imperial iterates with each agent traveling a random direction and distance from the current position.
            asymptomatic_percentage: Percentage of infected people that are asymptomatic.  Asymptomatic people transmit the virus for 42 time steps versus 15 time steps for those that are symptomatic.
            social_distance: Distance at which neighboring susceptible agents can b ecome infected.
            mobility: The maximum distance that an agent can travel.
        '''

        self.current_id = 0
        self.population = population
        self.mobility = mobility
        self.social_distance = social_distance
        self.asymptomatic_percentage = asymptomatic_percentage
        self.imperial = imperial
        if imperial:
            self.state = "home"
        else:
            self.state = "diffusion"
        self.schedule = RandomActivation(self)
        self.space = ContinuousSpace(width, height, True)
        self.make_agents()
        self.running = True

        self.datacollector = DataCollector({
            "Susceptible":
            lambda m: self.count("Susceptible"),
            "Infected":
            lambda m: self.count("Infected"),
            "Recovered":
            lambda m: self.count("Recovered")
        })
 def __init__(self,
              n_fish=50,
              width=50,
              height=50,
              speed=2,
              vision=10,
              separation=2,
              cohere=0.25,
              separate=0.025,
              match=0.3):
     assert speed < width and speed < height, "speed can't be greater than model area dimensions"
     self.n_fish = n_fish
     self.vision = vision
     self.speed = speed
     self.separation = separation
     self.schedule = RandomActivation(self)
     self.space = ContinuousSpace(width, height, torus=True)
     self.factors = dict(cohere=cohere, separate=separate, match=match)
     # self.make_obstructions()  # Todo: un-comment this line to include obstructions
     self.make_fish()
     self.running = True
예제 #30
0
    def __init__(self, N, width, height, speed, vision, separation):
        '''
        Create a new Flockers model.

        Args:
            N: Number of Boids
            width, height: Size of the space.
            speed: How fast should the Boids move.
            vision: How far around should each Boid look for its neighbors
            separtion: What's the minimum distance each Boid will attempt to
                       keep from any other
        '''
        self.N = N
        self.vision = vision
        self.speed = speed
        self.separation = separation
        self.schedule = RandomActivation(self)
        self.space = ContinuousSpace(width, height, True,
            grid_width=10, grid_height=10)
        self.make_agents()
        self.running = True