Exemple #1
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()
Exemple #3
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)
Exemple #4
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
Exemple #5
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()
Exemple #6
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()
Exemple #7
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()
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()
Exemple #9
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
Exemple #10
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()
Exemple #11
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()
Exemple #12
0
class ConveyModel(Model):
    """A model with some number of agents."""

    def __init__(self, N, width, height):
        super().__init__()
        self.num_agents = N
        self.grid = MultiGrid(width, height, True)
        self.schedule = BaseScheduler(self)

        # Create agents
        for i in range(self.num_agents):
            a = ConwayAgent(i, self)
            # Add the agent to a random grid cell
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            while(len(self.grid.get_cell_list_contents((x,y)))):
                x = random.randrange(self.grid.width)
                y = random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))
            self.schedule.add(a)
        self.i = i

        self.datacollector = DataCollector(
            agent_reporters={"State": lambda a: a.die})

    def step(self):
        self.datacollector.collect(self)
        new_agents = []
        for (x, y) in product(range(self.grid.width), range(self.grid.height)):
            ns = self.grid.iter_neighbors((x,y), True)
            neighbors = 0
            for n in ns:
                if(n):
                    neighbors += 1
            if(self.grid[x][y]):  # live cell
                if(neighbors < 2):  # underpopulation
                    list(self.grid[x][y])[0].die = 1
                elif(neighbors > 3):  # overpopulation
                    list(self.grid[x][y])[0].die = 1
            else:  # dead cell
                if(neighbors == 3):
                    new_agents.append((x, y))
        for (x, y) in product(range(self.grid.width), range(self.grid.height)):
            if self.grid[x][y]:
                a = list(self.grid[x][y])[0]
                if a.die:
                    self.grid.remove_agent(a)
                    self.schedule.remove(a)
        for na in new_agents:
            self.i += 1
            a = ConwayAgent(self.i, self)
            self.grid.place_agent(a, na)
            self.schedule.add(a)
Exemple #13
0
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()
class RandomDilemma(Model):
    """
	A model with two agents, prisoners in a game where their actions are
	distributed according to each agent's attribute probability of cooperation.
	"""
    def __init__(self, pdt_a, pdt_b, pdt_c, pdt_d, alpha_actions, beta_actions,
                 dummy):
        super().__init__()
        self.num_agents = 2
        self.a, self.b, self.c, self.d = pdt_a, pdt_b, pdt_c, pdt_d
        self.running = True

        # create agents. They will be activated one at a time in the order of add
        self.schedule = BaseScheduler(self)
        alpha = Prisoner("alpha", self, prob_coop=alpha_actions)
        beta = Prisoner("beta", self, prob_coop=beta_actions)
        self.schedule.add(alpha)
        self.schedule.add(beta)

        # collect wealth of agents
        self.data_collector = DataCollector(
            model_reporters=dict(pref_GI=pref_GI),
            agent_reporters=dict(Wealth="wealth", Action="action"))
        self.data_collector.collect(self)

    def step(self):
        """
		Advance the model by one step.
			- all agents take their actions.
			- increment agent's wealth according to their actions.
			- collect the data on individual wealth.
			
		"""
        self.schedule.step()
        if self.schedule.agents[0].action == 'C' and self.schedule.agents[
                1].action == 'C':
            self.schedule.agents[0].wealth += self.a
            self.schedule.agents[1].wealth += self.a
        elif self.schedule.agents[0].action == 'C' and self.schedule.agents[
                1].action == 'D':
            self.schedule.agents[0].wealth += self.b
            self.schedule.agents[1].wealth += self.c
        elif self.schedule.agents[0].action == 'D' and self.schedule.agents[
                1].action == 'C':
            self.schedule.agents[0].wealth += self.c
            self.schedule.agents[1].wealth += self.b
        elif self.schedule.agents[0].action == 'D' and self.schedule.agents[
                1].action == 'D':
            self.schedule.agents[0].wealth += self.d
            self.schedule.agents[1].wealth += self.d
        self.data_collector.collect(self)
Exemple #15
0
class MultiAgentModel(Model):
    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)

    def step(self):
        self.schedule.step()
Exemple #16
0
class ExposureDecay(Model):
    """A model with some number of agents."""
    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 step(self):
        self.datacollector.collect(self)
        self.schedule.step()
class Modelo (Model):
    
    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
        

    def step(self):
        self.schedule.step()    
Exemple #18
0
class WasteModel(Model):
    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)

    def step(self) -> None:
        self.schedule.step()
Exemple #19
0
class MockModel(Model):
    """
    Minimalistic model for testing purposes
    """
    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()

    def init_agents(self):
        if self.variable_agent_param is None:
            agent_val = 1
        else:
            agent_val = self.variable_agent_param
        for i in range(self.n_agents):
            self.schedule.add(MockAgent(i, self, agent_val))

    def get_local_model_param(self):
        return 42

    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()
Exemple #20
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()
Exemple #21
0
class MockModel(Model):

    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.
        '''
        super().__init__()

        self.random_state = MockRandomState()

        self.log = []

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

        # Make agents
        for name in ["A", "B"]:
            agent = MockAgent(name, self)
            self.schedule.add(agent)

    def step(self):
        self.schedule.step()
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()
Exemple #23
0
class PetriDish(Model):
    """
    Main model instance. It assignes one cell in each grid location, selecting
    its type randomly at the time of assignment; it assigns a single activated
    Producer cell in the middle of the grid.
    """
    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)

    def step(self):
        self.schedule.step()  # goes through agents in the order of addition
Exemple #24
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)
Exemple #25
0
class FireSupportModel(Model):
    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]))

        # print(self.schedule.agents[1])

    def step(self):
        self.schedule.step()
Exemple #26
0
class TicTacToe(Model):
    def __init__(self):
        super().__init__()

        self.running = True
        self.endgame = None

        self.grid = SingleGrid(3, 3, False)
        self.schedule = BaseScheduler(self)

        playerX = Player(1, self)
        playerO = Player(-1, self)

        self.schedule.add(playerX)
        self.schedule.add(playerO)

    def step(self):
        if not self.endgame:
            self.schedule.step()
        else:
            self.running = False
Exemple #27
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()
Exemple #28
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",
                "model_calc": self.schedule.get_agent_count,
                "model_calc_comp": [self.test_model_calc_comp, [3, 4]],
                "model_calc_fail": [self.test_model_calc_comp, [12, 0]]
            },
            {
                "value": lambda a: a.val,
                "value2": "val2"
            },
            {"Final_Values": ["agent_id", "final_value"]},
        )

    def test_model_calc_comp(self, input1, input2):
        if input2 > 0:
            return (self.model_val * input1) / input2
        else:
            assert ValueError
            return None

    def step(self):
        self.schedule.step()
        self.datacollector.collect(self)
Exemple #29
0
class MockModel(Model):

    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)

    def step(self):
        self.schedule.step()
Exemple #30
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()
Exemple #31
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.datacollector = DataCollector(model_reporters={
            "reported_model_param":
            self.get_local_model_param
        },
                                           agent_reporters={
                                               "agent_id": "unique_id",
                                               "agent_local": "local"
                                           })
        self.running = True
        self.init_agents()

    def get_local_model_param(self):
        return 42

    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.datacollector.collect(self)
        self.schedule.step()
Exemple #32
0
class Antcluster(Model):
    """A model with some number of agents."""
    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))

    def step(self):
        '''Advance the model by one step.'''
        self.schedule_dados.step()
        self.schedule.step()
Exemple #33
0
class CarModel(Model):
    '''
    Model class for the Nagel-Schreckenberg Car model.
    '''

    def __init__(self, height, width, dawdle_prob, car_amount):
        '''
        '''

        super().__init__()
        self.height = height
        self.width = width
        self.dawdle_prob = dawdle_prob
        self.car_amount = car_amount

        self.schedule = BaseScheduler(self)
        self.grid = SingleGrid(height, width, torus=True)

        self.place_agents()

        self.running = True

    def place_agents(self):
        for i in range(self.car_amount):
            while True:
                try:
                    r = random()
                    agent = CarAgent((int(r*100), 5), self, 10)
                    self.grid.position_agent(agent, int(r*100), 5)
                    self.schedule.add(agent)
                    break
                except Exception:
                    continue

    def step(self):
        self.schedule.step()
Exemple #34
0
class SMA_collab(Model):
    """A model for infection spread."""
    def __init__(self, nb_pop, nb_generations, n_truck, truck_capacity,
                 list_clients, time_matrix, n_pool, radius_pool):
        self.nb_pop = nb_pop
        self.nb_generations = nb_generations
        self.n_truck = n_truck
        self.truck_capacity = truck_capacity
        self.list_clients = list_clients
        self.time_matrix = time_matrix
        self.n_pool = n_pool

        #self.grid = MultiGrid(width, height, True)

        self.datacollector = DataCollector(agent_reporters={"State": "state"})

        #l'ordonnanceur du modele (instance de RandomActivation)
        #tester SimultaneousActivation (qui permet d'activer tous les agents en mêê temps)
        self.schedule = BaseScheduler(self)

        a = gen_agent(1, self, nb_pop, nb_generations, n_trucks,
                      truck_capacity, list_clients)
        self.schedule.add(a)

        # b = tab_agent(2,self)
        # self.schedule.add(b)

        # c = rs_agent(3, self, n_trucks, truck_capacity)
        # self.schedule.add(c)

        # Gestion du pool
        d = pool_agent(4, self, n_pool, radius_pool)
        self.schedule.add(d)

        # Gestion des courbes
        e1 = graphic_agent(5, self, a.solution, self.list_clients)
        # e2 = graphic_agent(6,self,b.solution, self.list_clients)
        # e3 = graphic_agent(7,self,c.solution, self.list_clients)
        #e = graphic_agent()
        self.schedule.add(e1)
        # self.schedule.add(e2)
        # self.schedule.add(e3)

    def step(self):
        #passage de l'instant t à l'instant (t+1)
        self.schedule.step()
Exemple #35
0
class ContactModel(Model):
    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)

    def contact_update(self, contact_ids):

        contact_ids = sorted(contact_ids)
        if contact_ids not in self.current_step_contacts:
            self.current_step_contacts.append(contact_ids)

    def update_adjecency_matrix(self):
        '''
        #TODO: order agent steps, order updates, double or not
        for id_tuple in self.current_step_contacts:
            self.adjacency_matrix[id_tuple[0], id_tuple[1]]+=1
        '''

        agents = self.schedule.agents
        for i, agent in enumerate(agents):
            neighbors = self.grid.get_neighbors(agent.pos,
                                                moore=True,
                                                radius=5)
            for neighbor in neighbors:
                if neighbor.unique_id > agent.unique_id:
                    self.adjacency_matrix[agent.unique_id,
                                          neighbor.unique_id] += 1

    def step(self):
        self.schedule.step()
        self.update_adjecency_matrix()
        #self.current_step_contacts=[]
        #self.data_collector.collect(self)

    def run(self, N):
        for i in range(N):

            self.step()

            self.current_step += 1  #NEW

            for agent in self.schedule.agents:
                self.x_locs[agent.unique_id][i + 1] = agent.pos[0]
                self.y_locs[agent.unique_id][i + 1] = agent.pos[1]

            if i % 100 == 0:
                print(i)
Exemple #36
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