Example #1
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}
        )
Example #2
0
    def __init__(self, N, height, width, exponent, steps, seed):
        self.number_of_agents = N
        self.height = height
        self.width = width
        self.exponent = exponent

        self.x_locs = np.zeros((N, steps + 1))
        self.y_locs = np.zeros((N, steps + 1))

        self.current_step = 0  #NEW

        self.current_step_contacts = []
        self.adjacency_matrix = np.zeros((N, N))
        self.grid = MultiGrid(self.width, self.height, torus=False)
        self.schedule = BaseScheduler(self)  #RandomActivation(self)

        # Add N pedestrians to model (schedule, grid)
        taken_pos = []
        for i in range(self.number_of_agents):
            x = self.random.randrange(1, self.grid.width - 1)
            y = self.random.randrange(1, self.grid.height - 1)

            pos = (x, y)
            new_human = Pedestrian(i, self, pos, self.exponent, seed=i)

            self.schedule.add(new_human)
            self.grid.place_agent(new_human, pos)
            self.x_locs[i][0] = x
            self.y_locs[i][0] = y
            taken_pos.append(pos)

        self.data_collector = DataCollector()

        self.running = True
        self.data_collector.collect(self)
Example #3
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]))
Example #4
0
 def __init__(self, N):
     self.num_agents = N
     self.i = 1
     self.grid = SingleGrid(120, 120, True)
     self.grid1 = SingleGrid(120, 120, True)
     self.schedule = RandomActivation(self)
     self.schedule_dados = BaseScheduler(self)
     # Create agents
     for i in range(self.num_agents):
         a = Ant(i, self)
         self.schedule.add(a)
         x = self.random.randrange(self.grid.width)
         y = self.random.randrange(self.grid.height)
         #z = np.asarray([x,y])
         #print(z)
         plt.axis([-10, 125, -10, 125])
         #plt.scatter(x,y)
         self.grid.place_agent(a, (x, y))
     #create data
     for i in range(150):
         b = dado(i, self)
         self.schedule_dados.add(b)
         x = self.random.randrange(self.grid1.width)
         y = self.random.randrange(self.grid1.height)
         #print(x,y)
         z = np.asarray([x, y])
         plt.axis([-10, 125, -10, 125])
         plt.scatter(x, y)
         self.grid1.place_agent(b, (x, y))
Example #5
0
    def __init__(self, shuffle=False, activation=STAGED):
        """
        Creates a Model instance with a schedule

        Args:
            shuffle (Bool): whether or not to instantiate a scheduler with
                            shuffling.
                            This option is only used for StagedActivation
                            schedulers.

            activation (str): which kind of scheduler to use.
                            'random' will create a RandomActivation scheduler.
                            'staged' will create a StagedActivation scheduler.
                            The default scheduler is a BaseScheduler.
        """
        self.log = []

        # Make scheduler
        if activation == STAGED:
            model_stages = ["stage_one", "stage_two"]
            self.schedule = StagedActivation(self,
                                             model_stages,
                                             shuffle=shuffle)
        elif activation == RANDOM:
            self.schedule = RandomActivation(self)
        elif activation == SIMULTANEOUS:
            self.schedule = SimultaneousActivation(self)
        else:
            self.schedule = BaseScheduler(self)

        # Make agents
        for name in ["A", "B"]:
            agent = MockAgent(name)
            self.schedule.add(agent)
Example #6
0
class EnergyModel(Model):
    # model with some entities
    def __init__(self):

        # list of named activated agents by sheetname
        active_agents = [
            "a" + str(int(i)) for i in wb.sheets['IO'].range("I3:I12").value
            if int(i) > 0
        ]
        print("Active Agents: {}".format(active_agents))
        self.num_agents = len(active_agents)
        self.schedule = BaseScheduler(self)

        # imports timesteps=[1:96] and datetimes(e.g. 00:00)
        self.time = wb.sheets['a1'].range("C3:D99").options(pd.Series).value

        # timesteps=[1:96]
        self.timeindex = self.time.index

        # Create Prosumer agents
        for i in active_agents:
            name = i
            a = Prosumer(i, self, name)
            self.schedule.add(a)

    def step(self):
        self.schedule.step()
Example #7
0
    class MesaModel(Model):
        """A MESA Model"""
        def __init__(self):
            self.schedule = BaseScheduler(self)

        def add_agent(self, agent: MesaAgent):
            self.schedule.add(agent)
            return agent

        def get_agent(self, agentName: str) -> Optional[AgentMET4FOF]:
            agent = next(
                (x for x in self.schedule.agents if x.name == agentName), None)
            return agent

        def step(self):
            """Advance the model by one step."""
            self.schedule.step()

        def agents(self):
            return [agent.name for agent in self.schedule.agents]

        def shutdown(self):
            """Shutdown entire MESA model with all agents and schedulers"""
            for agent in self.agents():
                agent_obj = self.get_agent(agent)
                agent_obj.shutdown()
    def __init__(self, N, height, width, exponent, steps):
        self.number_of_agents = N
        self.height = height
        self.width = width
        self.exponent = exponent

        #self.x_locs = np.zeros((N, steps))
        #self.y_locs = np.zeros((N))

        self.direction_range=3
        self.directions = Directions(self.direction_range)
        self.current_step_contacts=[]
        self.adjacency_matrix = np.zeros((N, N))
        self.grid = MultiGrid(self.width, self.height, torus=False)
        self.schedule = BaseScheduler(self)

        self.current_step = 0

         # Add N pedestrians to model (schedule, grid)
        for i in range(self.number_of_agents):
            x = self.random.randrange(1, self.grid.width-1)
            y = self.random.randrange(1, self.grid.height-1)

            pos = (x, y)
            new_human = Pedestrian(i, self, pos, self.exponent, self.directions)

            self.schedule.add(new_human)
            self.grid.place_agent(new_human, pos)

        self.data_collector=DataCollector()

        self.running=True
        self.data_collector.collect(self)
Example #9
0
 def __init__(self, **other_params):
     super().__init__()
     self.variable_name = other_params.get("variable_name", 42)
     self.fixed_name = other_params.get("fixed_name")
     self.running = True
     self.schedule = BaseScheduler(None)
     self.schedule.add(MockAgent(1, self, 0))
Example #10
0
    def __init__(self, shuffle=False, activation=STAGED):
        '''
        Creates a Model instance with a schedule

        Args:
            shuffle (Bool): whether or not to instantiate a scheduler
                            with shuffling.
                            This option is only used for
                            StagedActivation schedulers.

            activation (str): which kind of scheduler to use.
                              'random' creates a RandomActivation scheduler.
                              'staged' creates a StagedActivation scheduler.
                              The default scheduler is a BaseScheduler.
        '''
        self.log = []

        # Make scheduler
        if activation == STAGED:
            model_stages = ["stage_one", "stage_two"]
            self.schedule = StagedActivation(self,
                                             model_stages,
                                             shuffle=shuffle)
        elif activation == RANDOM:
            self.schedule = RandomActivation(self)
        elif activation == SIMULTANEOUS:
            self.schedule = SimultaneousActivation(self)
        else:
            self.schedule = BaseScheduler(self)

        # Make agents
        for name in ["A", "B"]:
            agent = MockAgent(name, self)
            self.schedule.add(agent)
Example #11
0
class MockModel(Model):
    """
    Minimalistic model for testing purposes
    """
    def __init__(self,
                 variable_model_param,
                 variable_agent_param,
                 fixed_model_param=None,
                 schedule=None,
                 **kwargs):
        super().__init__()
        self.schedule = BaseScheduler(None) if schedule is None else schedule
        self.variable_model_param = variable_model_param
        self.variable_agent_param = variable_agent_param
        self.fixed_model_param = fixed_model_param
        self.n_agents = kwargs.get('n_agents', NUM_AGENTS)
        self.running = True
        self.init_agents()

    def init_agents(self):
        for i in range(self.n_agents):
            self.schedule.add(MockAgent(i, self, self.variable_agent_param))

    def step(self):
        self.schedule.step()
class ForestFire(Model):
    """
    Simple Forest Fire model.
    """
    def __init__(self, height=100, width=100, density=0.7):
        """
        Create a new forest fire model.
        Args:
            height, width: The size of the grid to model
            density: What fraction of grid cells have a tree in them.
        """
        # Set up model objects
        self.schedule = BaseScheduler(self)
        self.grid = Grid(height, width, torus=False)

        # Place a tree in each cell with Prob = density
        for (contents, x, y) in self.grid.coord_iter():
            if self.random.random() < density:
                # Create a tree
                new_tree = TreeCell((x, y), self)
                # Set all trees in the first column on fire.
                if x == 0:
                    new_tree.condition = "On Fire"
                self.grid._place_agent((x, y), new_tree)
                self.schedule.add(new_tree)

    def step(self):
        """
        Advance the model by one step.
        """
        self.schedule.step()
Example #13
0
class Modelo(Model):
    def __init__(self, N):
        self.num_ind = N
        self.schedule = BaseScheduler(self)
        self.crearciudad()

    def crearciudad(self):
        self.ciudad = Ciudad(self)
        for ind in self.ciudad.generarindividuos():
            self.schedule.add(ind)

        #Se planta un infectado en la simulación
        self.schedule.agents[50].salud = INFECTADO

        #Se crean las casas distribuyendo los individuos
        self.ciudad.crear_hogares()

        #Se agrega una tienda a la ciudad y se conecta con todas las casas
        self.ciudad.add_node(2000,
                             tipo='tienda',
                             habitantes=None,
                             ocupantes=[])
        self.ciudad.conectaracasas(2000)

    def step(self):
        self.schedule.step()
        agente = self.schedule.agents[0]

    def conteo(self):
        #Una función para contar los casos actuales en la ciudad
        datos = [0, 0, 0, 0]
        for a in self.schedule.agents:
            datos[a.salud] += 1
        return datos
Example #14
0
 def __init__(self,
              variable_model_param=None,
              variable_agent_param=None,
              fixed_model_param=None,
              schedule=None,
              enable_agent_reporters=True,
              **kwargs):
     super().__init__()
     self.schedule = BaseScheduler(self) if schedule is None else schedule
     self.variable_model_param = variable_model_param
     self.variable_agent_param = variable_agent_param
     self.fixed_model_param = fixed_model_param
     self.n_agents = 3
     if enable_agent_reporters:
         agent_reporters = {"agent_id": "unique_id", "agent_local": "local"}
     else:
         agent_reporters = None
     self.datacollector = DataCollector(
         model_reporters={
             "reported_model_param": self.get_local_model_param
         },
         agent_reporters=agent_reporters,
     )
     self.running = True
     self.init_agents()
Example #15
0
 def __init__(self, N, width, height):
   self.num_agents = N
   self.grid = MultiGrid(height, width, True)
   self.schedule = BaseScheduler(self)
   self.source = Pituitary("Pituitary")
   self.target = Thyroid("Thyroid")
   self.schedule.add(self.source)
Example #16
0
class MockModel(Model):
    """
    Minimalistic model for testing purposes.
    """

    schedule = BaseScheduler(None)

    def __init__(self):
        self.schedule = BaseScheduler(self)
        self.model_val = 100

        for i in range(10):
            a = MockAgent(i, self, val=i)
            self.schedule.add(a)
        self.datacollector = DataCollector(
            {
                "total_agents": lambda m: m.schedule.get_agent_count(),
                "model_value": "model_val",
            },
            {
                "value": lambda a: a.val,
                "value2": "val2"
            },
            {"Final_Values": ["agent_id", "final_value"]},
        )

    def step(self):
        self.schedule.step()
        self.datacollector.collect(self)
Example #17
0
    def __init__(self, N):

        self.nb_agents = N  # Nombre d'agents
        self.schedule = BaseScheduler(self)  # Timeline basic

        # Initializations spatials des agents
        positions = self.spawn_clusters()
        #print(positions, len(positions))

        for i in range(self.nb_agents):
            # positionne aléatoirement l'agent sur la grille
            agent = CivAgent(i, self)
            agent.x, agent.y, agent.z = positions[i]
            self.schedule.add(agent)  # ajoute les agents à la timeline

        # Calcules les distances entre les agents
        self.distances_log = self.calculate_distance()

        # Timeline
        self.timeline = 0
        self.connection_logs = {}  # connections effectuées dict[tour[int] : list[connections]]
        self.removed_agents = {}  # agents enlevés dict[tour[int] : list[agents]]

        # Chaîne de suspicion
        self.suspicions = {} # key : (agent1, agent2), value : suspicion_cooldown

        # Historique
        self.historique = {} # dict[tour[int], list[agents]]
        self.historique[0] = list(self.schedule._agents.values())
Example #18
0
class TurtleModel(Model):
    def __init__(self, width: int = 5, height: int = 5):
        super().__init__()
        self.active_agent = Turtle(self.next_id(), self)
        self.active_agent.active = True

        self.grid = SingleGrid(width, height, True)
        self.grid.position_agent(self.active_agent, width // 2, height // 2)

        self.schedule = BaseScheduler(self)
        self.schedule.add(self.active_agent)

    def step(self):
        direction = self.random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
        self.active_agent.move(direction)

    def on_key(self, key):
        key_to_direction = {
            "ArrowUp": (0, 1),
            "ArrowDown": (0, -1),
            "ArrowLeft": (-1, 0),
            "ArrowRight": (1, 0),
        }

        direction = key_to_direction.get(key, "")
        if direction:
            self.active_agent.move(direction)

    def on_click(self, **kwargs):
        self.active_agent.active = False
        unique_id = kwargs.get("unique_id")
        for agent in self.schedule.agents:
            if agent.unique_id == unique_id:
                self.active_agent = agent
                self.active_agent.active = True
Example #19
0
class ScientistModel(Model):
    def __init__(self, scientists_per_cycle, ideas_per_cycle, cycles, granularity, max_idea_effort, \
                    true_means_mean, true_means_std_dev, true_std_devs_mean, true_std_devs_std_dev, \
                    starting_effort_mean, starting_effort_std_dev, k_mean, k_std_dev):

        self.schedule = BaseScheduler(self) # has a .time() function

        # Constant variables
        self.scientists_per_cycle = scientists_per_cycle
        self.ideas_per_cycle = ideas_per_cycle
        self.total_scientists = scientists_per_cycle * cycles
        self.total_ideas = ideas_per_cycle * cycles
        self.granularity = granularity
        self.current_idea_effort = np.zeros(self.total_ideas)
        self.max_idea_effort = max_idea_effort

        # Varied variables
        self.true_means_mean = true_means_mean
        self.true_means_std_dev = true_means_std_dev
        self.true_std_devs_mean = true_std_devs_mean
        self.true_std_devs_std_dev = true_std_devs_std_dev 
        self.starting_effort_mean = starting_effort_mean
        self.starting_effort_std_dev = starting_effort_std_dev
        self.k_mean = k_mean
        self.k_std_dev = k_std_dev

    def step(self):
        for i in range(self.scientists_per_cycle):
            a = Scientist(self.schedule.time, self.scientists_per_cycle, self.ideas_per_cycle, self.total_scientists, \
                            self.total_ideas, self.granularity, self.current_idea_effort, self.max_idea_effort, \
                            self.true_means_mean, self.true_means_std_dev, self.true_std_devs_mean, self.true_std_devs_std_dev, \
                            self.starting_effort_mean, self.starting_effort_std_dev, self.k_mean, self.k_std_dev, self)
            self.schedule.add(a)
        self.schedule.step()
Example #20
0
    def __init__(self,
                 width=50,
                 height=50,
                 proportion_producers=0.3,
                 proportion_consumers=0.3):
        self.running = True
        self.schedule = BaseScheduler(self)
        self.grid = SingleGrid(width, height, torus=False)

        initial_activator = Producer("Initial activator", self, activated=True)
        center_coords = (math.floor(width / 2), math.floor(height / 2))

        ## Rolled into the placement of other cells
        # self.schedule.add(initial_activator)
        # self.grid.place_agent(initial_activator, center_coords)

        # roll a die and place Producer, Consumer or undifferentiated cell
        for x in range(width):
            for y in range(height):
                roll = r.random()
                coords = (x, y)

                if coords == center_coords:
                    agent = initial_activator
                elif roll <= proportion_producers:
                    agent = Producer(coords, self)
                elif roll <= proportion_producers + proportion_consumers:
                    agent = Consumer(coords, self)
                else:
                    agent = Cell(coords, self)

                self.schedule.add(agent)
                self.grid.place_agent(agent, coords)
Example #21
0
class CollisionModel(Model):
    def __init__(self, N, width, height, init_value):
        self.num_agents = N
        self.init_value = init_value
        self.grid = MultiGrid(width, height, True)
        self.schedule = BaseScheduler(self)
        
        # Create Agents
        for i in range(self.num_agents):
            a = CollisionAgent(i, self)
            self.schedule.add(a)
            # Add the agent to a random grid cell
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))
        
        self.datacollector = DataCollector(
            #model_reporters={"AvgReward": compute_avgreward},
            #model_reporters={"AvgCollision": compute_avgcollision},
            model_reporters={"0": compute_avg_reward_angle_0, "90": compute_avg_reward_angle_1, "180": compute_avg_reward_angle_2, "270": compute_avg_reward_angle_3},
            agent_reporters={"Reward": lambda a: a.reward})

    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()
Example #22
0
 def __init__(
     self,
     num_humans=50,
     num_ml=5,
     belief_dims=30,
     p_1=0.1,
     p_2=0.9,
     p_3=0.9,
     p_h1=0.1,
     p_h2=0.1,
     p_ml=0.5,
 ):
     # reset random seeds prior to each iteration
     np.random.seed()
     random.seed()
     # save configuration
     self.conf = {
         "num_humans": num_humans,
         "num_ml": num_ml,
         "belief_dims": belief_dims,
         "p_1": p_1,
         "p_2": p_2,
         "p_3": p_3,
         "p_h1": p_h1,
         "p_h2": p_h2,
         "p_ml": p_ml,
     }
     self.running = True
     self.schedule = BaseScheduler(self)
     # init environment and data collector
     self.init_env()
     self.init_dc()
Example #23
0
    def __init__(self, wiggle_angle, number_particles, probability_of_sticking, 
                 neighbor_influence, num_seeds):
        self.running = True # necessário para que o modelo seja chamado pelo servidor web
        self.wiggle_angle = wiggle_angle
        self.number_particles = number_particles
        " indica com que probabilidade uma partícula vermelha se torna verde " 
        " e pára ao tocar uma partícula verde"
        self.probability_of_sticking = probability_of_sticking
        "indica se o número de vizinhos verdes influencia a probabilidade de"
        "grudar"
        self.neighbor_influence = neighbor_influence
        if num_seeds <= 0: # número de sementes deve ser positivo
            raise ValueError("Number of seeds should be greater than zero.")
        self.num_seeds = num_seeds
        "direções das particulas"
        "(1,0) direita; (0, 1) cima; (-1, 0) esquerda (0, -1) baixo"
        self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))
        self.schedule = BaseScheduler(self)

        "tamanho do grid definido em função do número de partículas, como na" 
        "visualização; pode ser um valor comum aos dois"
        width = height = round(2 * round(math.sqrt(number_particles)))
        
        "apenas um agente por célula"
        self.grid = SingleGrid(width, height, True)
        
        "Cria as sementes"
        for i in range(self.num_seeds):
            if self.num_seeds == 1:
                """
                Coloca a semente no centro do grid. O modelo final do NetLogo,
                com a extensão 3, não coloca uma semente unitária no centro,
                mas em uma posição aleatória também.
                """
                x = round(self.grid.width / 2);
                y = round(self.grid.height / 2);
                "o angulo e o a probabilidade de colar não são relevantes, já" 
                "que as sementes não se movem"
                particle = Particle(i, self, GREEN_COLOR, 0, (x, y))
                self.grid.place_agent(particle, (x, y))
            else:
                """
                Coloca as sementes em posições aleatórias. A posição 
                será atribuída pelo método position_agent
                """
                particle = Particle(i, self, GREEN_COLOR, 0, (0, 0))
                self.grid.position_agent(particle)
            
            self.schedule.add(particle)

        "Cria as partículas"
        for i in range(self.number_particles):
           
            "a posição será atribuída pelo método position_agent"
            heading = self.random.choice(self.headings)
            particle = Particle(i, self, RED_COLOR, heading, (0, 0))
            self.grid.position_agent(particle)
            self.schedule.add(particle)
Example #24
0
    def __init__(self, width, height):
        self.running = True
        self.grid = MultiGrid(width, height, False)  #true for toroidal grid
        self.schedule = BaseScheduler(self)

        self.adversary_pieces = []
        self.agent_pieces = []

        self.initialize_grid()
Example #25
0
    def __init__(self, agent_class, num_col_left, num_col_mid, num_col_right,
                 num_row, dist_bw_seats, num_infected, breath_prob, cough_prob,
                 sneeze_prob, breath_dist, cough_dist, sneeze_dist,
                 prob_infected):

        # mesa required attributes
        self.running = True
        self.grid = GeoSpace()
        self.schedule = BaseScheduler(
            self
        )  # scheduler dictates model level agent behavior, aka. step function

        # variables used for later functions that need descriptions of the model
        dim_bus = [num_col_left, num_col_mid, num_col_right, num_row]
        self.max_columns = (dim_bus[0] + dim_bus[1] +
                            dim_bus[2]) * dist_bw_seats
        self.max_rows = dim_bus[3] * dist_bw_seats
        self.seat_dist = dist_bw_seats

        i = 1
        for x in range(0, dim_bus[0] * dist_bw_seats, dist_bw_seats):
            for y in range(0, dim_bus[3] * dist_bw_seats, dist_bw_seats):
                pnt = Point(x, y)
                i += 1
                a = agent_class(model=self,
                                shape=pnt,
                                unique_id="na" + str(i),
                                breath_prob=breath_prob,
                                cough_prob=cough_prob,
                                sneeze_prob=sneeze_prob,
                                breath_dist=breath_dist,
                                cough_dist=cough_dist,
                                sneeze_dist=sneeze_dist,
                                prob_infected=prob_infected)
                self.grid.add_agents(a)
                self.schedule.add(a)
        for x in range((dim_bus[0] + dim_bus[1]) * dist_bw_seats,
                       (dim_bus[0] + dim_bus[1] + dim_bus[2]) * dist_bw_seats,
                       dist_bw_seats):
            for y in range(0, dim_bus[3] * dist_bw_seats, dist_bw_seats):
                pnt = Point(x, y)
                i += 1
                a = agent_class(model=self,
                                shape=pnt,
                                unique_id="na" + str(i),
                                breath_prob=breath_prob,
                                cough_prob=cough_prob,
                                sneeze_prob=sneeze_prob,
                                breath_dist=breath_dist,
                                cough_dist=cough_dist,
                                sneeze_dist=sneeze_dist,
                                prob_infected=prob_infected)
                self.grid.add_agents(a)
                self.schedule.add(a)
        infected_agents = random.sample(self.grid.agents, num_infected)
        for i in infected_agents:
            i.infected = True
Example #26
0
 def __init__(self):
     self.schedule = BaseScheduler(self)
     for i in range(10):
         a = MockAgent(i, i)
         self.schedule.add(a)
     self.datacollector = DataCollector(
         {"total_agents": lambda m: m.schedule.get_agent_count()},
         {"value": lambda a: a.val},
         {"Final_Values": ["agent_id", "final_value"]})
Example #27
0
    def __init__(self, N):
        self.nb_agents = N
        self.schedule = BaseScheduler(self)  # Créer une timeline

        for i in range(self.nb_agents):
            agent = CivAgent(i, self)
            self.schedule.add(agent)  # ajoute N agent à la timeline
            # positionne aléatoirement l'agent sur la grille

        self.distances_log = self.calculate_distance()
 def __init__(self, variable_model_param, variable_agent_param,
              fixed_model_param=None, schedule=None, **kwargs):
     super().__init__()
     self.schedule = BaseScheduler(None) if schedule is None else schedule
     self.variable_model_param = variable_model_param
     self.variable_agent_param = variable_agent_param
     self.fixed_model_param = fixed_model_param
     self.n_agents = kwargs.get('n_agents', NUM_AGENTS)
     self.running = True
     self.init_agents()
Example #29
0
    def __init__(self, width: int = 5, height: int = 5):
        super().__init__()
        self.active_agent = Turtle(self.next_id(), self)
        self.active_agent.active = True

        self.grid = SingleGrid(width, height, True)
        self.grid.position_agent(self.active_agent, width // 2, height // 2)

        self.schedule = BaseScheduler(self)
        self.schedule.add(self.active_agent)
Example #30
0
    def __init__(self,
                 agents=agents,
                 dt=0.1,
                 attention_delta=0.1,
                 persuasion=1,
                 a_min=-0.5,
                 r_min=0.05,
                 sd_opinion=0.15,
                 sd_info=0.005,
                 network_params=None):

        super().__init__()

        self.dt = dt
        self.attention_delta = attention_delta
        self.persuasion = persuasion
        self.a_min = a_min
        self.r_min = r_min
        self.sd_opinion = sd_opinion
        self.sd_info = sd_info

        # initialize a scheduler
        self.schedule = BaseScheduler(self)

        # create the population
        self.population = 0
        if network_params is None:
            network_params = {"method": "er", "p": 0.1}
        self.init_population(agents, network_params)
        # self.G = nx.Graph()

        # generates network topology
        # not used right now, but can be used for mesa visualization
        self.grid = NetworkGrid(self.G)

        # create agents
        self.create_agents(agents)

        # agent who will interact this turn
        self.active_agent = None

        # add datacollector
        # collects opinion, information and attention each step
        self.data_collector = DataCollector({
            "Opinion":
            lambda m: self.collect_opinions(),
            "Attention":
            lambda m: self.collect_attentions(),
            "Information":
            lambda m: self.collect_informations()
        })

        # this is required for the data_collector to work
        self.running = True
        self.data_collector.collect(self)
Example #31
0
class MockMixedModel(Model):
    def __init__(self, **other_params):
        super().__init__()
        self.variable_name = other_params.get('variable_name', 42)
        self.fixed_name = other_params.get('fixed_name')
        self.running = True
        self.schedule = BaseScheduler(None)
        self.schedule.add(MockAgent(1, self, 0))

    def step(self):
        self.schedule.step()
Example #32
0
class MockMixedModel(Model):

    def __init__(self, **other_params):
        super().__init__()
        self.variable_name = other_params.get('variable_name', 42)
        self.fixed_name = other_params.get('fixed_name')
        self.running = True
        self.schedule = BaseScheduler(None)
        self.schedule.add(MockAgent(1, self, 0))

    def step(self):
        self.schedule.step()
class Bloodstream(Model):
  # initialise source organ
  def __init__(self, N, width, height):
    self.num_agents = N
    self.grid = MultiGrid(height, width, True)
    self.schedule = BaseScheduler(self)
    self.source = Pituitary("Pituitary")
    self.target = Thyroid("Thyroid")
    self.schedule.add(self.source)

  # advance a step
  def step(self):
    self.schedule.step()
Example #34
0
 def __init__(self, variable_model_param, variable_agent_param,
              fixed_model_param=None, schedule=None, **kwargs):
     super().__init__()
     self.schedule = BaseScheduler(None) if schedule is None else schedule
     self.variable_model_param = variable_model_param
     self.variable_agent_param = variable_agent_param
     self.fixed_model_param = fixed_model_param
     self.n_agents = kwargs.get('n_agents', NUM_AGENTS)
     self.running = True
     self.init_agents()
Example #35
0
class MockModel(Model):
    """
    Minimalistic model for testing purposes
    """
    def __init__(self, model_param, agent_param):
        """
        Args:
            model_param (any): parameter specific to the model
            agent_param (int): parameter specific to the agent
        """
        self.schedule = BaseScheduler(None)
        self.model_param = model_param
        self.running = True
        for i in range(NUM_AGENTS):
            a = MockAgent(i, agent_param)
            self.schedule.add(a)

    def step(self):
        self.schedule.step()
Example #36
0
class MockModel(Model):
    '''
    Minimalistic model for testing purposes.
    '''

    schedule = BaseScheduler(None)

    def __init__(self):
        self.schedule = BaseScheduler(self)
        for i in range(10):
            a = MockAgent(i, i)
            self.schedule.add(a)
        self.datacollector = DataCollector(
            {"total_agents": lambda m: m.schedule.get_agent_count()},
            {"value": lambda a: a.val},
            {"Final_Values": ["agent_id", "final_value"]})

    def step(self):
        self.schedule.step()
        self.datacollector.collect(self)
Example #37
0
class MockModel(Model):
    """
    Minimalistic model for testing purposes
    """
    def __init__(self, variable_model_param, variable_agent_param,
                 fixed_model_param=None, schedule=None, **kwargs):
        super().__init__()
        self.schedule = BaseScheduler(None) if schedule is None else schedule
        self.variable_model_param = variable_model_param
        self.variable_agent_param = variable_agent_param
        self.fixed_model_param = fixed_model_param
        self.n_agents = kwargs.get('n_agents', NUM_AGENTS)
        self.running = True
        self.init_agents()

    def init_agents(self):
        for i in range(self.n_agents):
            self.schedule.add(MockAgent(i, self, self.variable_agent_param))

    def step(self):
        self.schedule.step()
Example #38
0
    def __init__(self):
        self.schedule = BaseScheduler(self)
        self.model_val = 100

        for i in range(10):
            a = MockAgent(i, self, val=i)
            self.schedule.add(a)
        self.datacollector = DataCollector(
            {"total_agents": lambda m: m.schedule.get_agent_count(),
             "model_value": "model_val"},
            {"value": lambda a: a.val, "value2": "val2"},
            {"Final_Values": ["agent_id", "final_value"]})
Example #39
0
 def __init__(self, model_param, agent_param):
     """
     Args:
         model_param (any): parameter specific to the model
         agent_param (int): parameter specific to the agent
     """
     self.schedule = BaseScheduler(None)
     self.model_param = model_param
     self.running = True
     for i in range(NUM_AGENTS):
         a = MockAgent(i, agent_param)
         self.schedule.add(a)
Example #40
0
class ScientistModel(Model):
    def __init__(self, N, ideas_per_time, time_periods):
        self.num_scientists = N
        
        self.total_ideas = ideas_per_time*time_periods
        
        # Store the max investment allowed in any idea
        self.max_investment = poisson(lam=50, size=self.total_ideas)
        
        # Store parameters for true idea return distribution
        self.true_sds = poisson(4, size=self.total_ideas)
        self.true_means = poisson(50, size=self.total_ideas)

        # Create array to keep track of total effort allocated to each idea
        self.total_effort = np.zeros(self.total_ideas)
        
        self.schedule = BaseScheduler(self)
        for i in range(self.num_scientists):
            a = Scientist(i, self)
            self.schedule.add(a)
            
    def step(self):
        self.schedule.step()
Example #41
0
    def __init__(self, networks=None, season_length=91, n_agents=100, max_steps=1000):
        self.n_steps = 0
        self.max_steps = max_steps
        self.season_length = season_length
        self.schedule = BaseScheduler(self)
        if networks is None:
            networks = self._demo_networks()
        self.n_seasons = len(networks)
        
        # space
        nodes = networks[0].nodes()
        edges = []
        for network in networks:
            edges.append(network.edges(data=True))

        self.network = MultilayerNetworkSpace(nodes,edges)

        # agents
        for n in range(n_agents):
            start, dest = sample(nodes,2)
            start_time = randrange(self.n_seasons * self.season_length )
            agent = Travel_Agent(start,dest,start_time,n)

            self.schedule.add(agent)
        
        # data collection
        self.dc = DataCollector(
                {
                    "enroute": lambda m: self.count_en_route(m)
                    },
                {
                    "position": lambda a: a.pos,
                    "travel_time": lambda a: a.travel_time
                    }
                )
        self.dc.collect(self)

        self.running = True
Example #42
0
class Travel_Model(Model):
    def __init__(self, networks=None, season_length=91, n_agents=100, max_steps=1000):
        self.n_steps = 0
        self.max_steps = max_steps
        self.season_length = season_length
        self.schedule = BaseScheduler(self)
        if networks is None:
            networks = self._demo_networks()
        self.n_seasons = len(networks)
        
        # space
        nodes = networks[0].nodes()
        edges = []
        for network in networks:
            edges.append(network.edges(data=True))

        self.network = MultilayerNetworkSpace(nodes,edges)

        # agents
        for n in range(n_agents):
            start, dest = sample(nodes,2)
            start_time = randrange(self.n_seasons * self.season_length )
            agent = Travel_Agent(start,dest,start_time,n)

            self.schedule.add(agent)
        
        # data collection
        self.dc = DataCollector(
                {
                    "enroute": lambda m: self.count_en_route(m)
                    },
                {
                    "position": lambda a: a.pos,
                    "travel_time": lambda a: a.travel_time
                    }
                )
        self.dc.collect(self)

        self.running = True

    def step(self):
        self.schedule.step()
        self.dc.collect(self)
        self.n_steps +=1

        if self.count_en_route(self) == 0 or self.n_steps >= self.max_steps:
            self.running = False

    def get_season(self, time):
        return (time // self.season_length) % self.n_seasons 


    def _demo_networks(self):
        networks = []
        for i in range(3):
            g = nx.random_graphs.watts_strogatz_graph(100, 2, 0.05)
            dists = np.random.randint(1,30, g.number_of_edges())
            dists = dict(zip(g.edges(),dists))
            nx.set_edge_attributes(g, 'distance', dists)
            networks.append(g)
        return networks

    @staticmethod
    def count_en_route(model):
        count = len(model.schedule.agents)
        for agent in model.schedule.agents:
            if agent.pos == agent.dest:
                count -=1
        return count