예제 #1
0
    def __initialize(self):
        self.site_schedule = BaseScheduler(self)
        self.schedule = BaseScheduler(self)
        self.event_list = [
        ]  # reserved event list (function, argument, execution time step)
        self.constructed_unit_list = []
        self.unit_id_generator = utils.unit_id_generator()
        self.__scheduling_site_agents()

        # final result
        self.finished_time_step = 0
        self.inventory_total = 0

        # for reinforcement_learning
        self.reward_at_time_step = 0
예제 #2
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()
예제 #3
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}
        )
예제 #4
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)
예제 #5
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]))
예제 #6
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()
예제 #7
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))
예제 #8
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)
예제 #9
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())
예제 #10
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)
예제 #11
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))
예제 #12
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)
예제 #13
0
    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)
예제 #14
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)
예제 #15
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)
예제 #16
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()
예제 #17
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"]})
예제 #18
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
예제 #19
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()
예제 #20
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()
예제 #21
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)
예제 #22
0
파일: Model.py 프로젝트: mahetoodang/hiom
    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)
예제 #23
0
    def __init__(self, N):
        self.num_agents = N
        self.schedule = BaseScheduler(self)
        # Create agents
        for i in range(self.num_agents):
            a = Consumer(i, self)
            self.schedule.add(a)

        self.datacollector = DataCollector(
            model_reporters={"Awareness": computeLiftandDecay},
            agent_reporters={"Quintile": "quintile"})
 def __init__ (self):
     self.schedule = BaseScheduler(self)
     self.schedule.add( DBAgent(0, self) )
     self.schedule.add( ChatAgent(1, self) )
     
     self.intent = None
     self.entity = None
     self.pendingQuery = False
     
     self.answer = None
     self.pendingAnswer = False
예제 #25
0
    def __init__(self, no_of_agents_local, no_of_population_nodes):
        self.num_agents = no_of_agents_local
        self.schedule = BaseScheduler(self)
        self.list_of_agent_objects = []
        self.no_of_population_nodes = no_of_population_nodes

        for population_node in range(self.no_of_population_nodes):
            agents_in_node = []
            for agent_index in range(self.num_agents):
                agent = ConversationAgent(agent_index, self)
                agents_in_node.append(agent)
            self.list_of_agent_objects.append(agents_in_node)
예제 #26
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"]})
예제 #27
0
    def __init__(self, N):
        self.n_agents = N
        self.schedule = BaseScheduler(self)

        # Creating the environment and adding it to the scheduler, so I can access it on every agent step
        environment = Environment.Environment(N, self)
        self.schedule.add(environment)

        # Creating agents
        for i in range(self.n_agents):
            agent = Consumer.Consumer(i, self)
            self.schedule.add(agent)
예제 #28
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)
예제 #29
0
    def __init__(self, num_generators, num_receivers):
        super().__init__()
        self.num_generators = num_generators
        self.num_receivers = num_receivers
        self.schedule = BaseScheduler(self)

        for i in range(num_generators):
            generator = WasteGenerator(self.next_id(), 1, self)
            self.schedule.add(generator)

        for i in range(num_receivers):
            receiver = WasteReceiver(self.next_id(), self)
            self.schedule.add(receiver)
예제 #30
0
    def __init__(self, N, width=500, height=500):
        self.nb_agents = N
        self.grid = MultiGrid(width, height, True)
        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
            agent.x = self.random.randrange(self.grid.width)
            agent.y = self.random.randrange(self.grid.height)
            agent.pos = agent.x, agent.y
            self.grid.place_agent(agent, agent.pos)