Exemplo n.º 1
0
    def __init__(self, height=20, width=20, density=0.8, minority_pc=0.2, homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})

        # Set up agents
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Exemplo n.º 2
0
 def __init__(self, N=2, width=20, height=10):
     self.N = N  # num of agents
     self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
     self.grid = SingleGrid(width, height, torus=False)
     self.schedule = RandomActivation(self)
     self.make_walker_agents()
     self.running = True
Exemplo n.º 3
0
class ShapeExample(Model):
    def __init__(self, N=2, width=20, height=10):
        self.N = N  # num of agents
        self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
        self.grid = SingleGrid(width, height, torus=False)
        self.schedule = RandomActivation(self)
        self.make_walker_agents()
        self.running = True

    def make_walker_agents(self):
        unique_id = 0
        while True:
            if unique_id == self.N:
                break
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)
            pos = (x, y)
            heading = self.random.choice(self.headings)
            # heading = (1, 0)
            if self.grid.is_cell_empty(pos):
                print("Creating agent {2} at ({0}, {1})".format(
                    x, y, unique_id))
                a = Walker(unique_id, self, pos, heading)
                self.schedule.add(a)
                self.grid.place_agent(a, pos)
                unique_id += 1

    def step(self):
        self.schedule.step()
Exemplo n.º 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
Exemplo n.º 5
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)
Exemplo n.º 6
0
 def setUp(self):
     self.space = SingleGrid(50, 50, False)
     self.agents = []
     for i, pos in enumerate(TEST_AGENTS_GRID):
         a = MockAgent(i, None)
         self.agents.append(a)
         self.space.place_agent(a, pos)
Exemplo n.º 7
0
    def __init__(self,
                 width=50,
                 height=50,
                 torus=True,
                 num_bug=50,
                 seed=42,
                 strategy=None):
        super().__init__(seed=seed)
        self.number_of_bug = num_bug
        if not (strategy in ["stick", "switch"]):
            raise TypeError("'strategy' must be one of {stick, switch}")
        self.strategy = strategy

        self.grid = SingleGrid(width, height, torus)
        self.schedule = RandomActivation(self)
        data = {
            "Bean": lambda m: m.number_of_bean,
            "Corn": lambda m: m.number_of_corn,
            "Soy": lambda m: m.number_of_soy,
            "Bug": lambda m: m.number_of_bug,
        }
        self.datacollector = DataCollector(data)

        # create foods
        self._populate(Bean)
        self._populate(Corn)
        self._populate(Soy)

        # create bugs
        for i in range(self.number_of_bug):
            pos = self.grid.find_empty()
            bug = Bug(i, self)
            bug.strategy = self.strategy
            self.grid.place_agent(bug, pos)
            self.schedule.add(bug)
Exemplo n.º 8
0
    def __init__(self, n_students, n_active: int, width: int, height: int):
        self.running = True
        self.schedule = SimultaneousActivation(self)
        self.grid = SingleGrid(width, height, torus=False)
        self.n_students: int = n_students
        self._semester_gen = self._gen_semester_code()
        self.semester = next(self._semester_gen)
        self.ALL_GENDERS = gen_gender(self.n_students)

        # Majors
        self.F1SEQ1_MAJORS = gen_f1seq1_majors(self.n_students)
        self.major_switcher = MajorSwitch()

        # Adding Student to KSU Environment
        for i in range(self.n_students):
            # Percentage of student agent that will be active and the rest inactive
            per_active = n_active / 100

            if np.random.binomial(1, per_active):
                student = Student(i, self, self.ALL_GENDERS[i])
                student.majors.append(self.F1SEQ1_MAJORS[i])
            else:
                student = Student(i, self, self.ALL_GENDERS[i], False)
                student.majors.append("N/A")

            self.schedule.add(student)
            self.grid.position_agent(student)

        self.datacollector = DataCollector(
            agent_reporters={
                "GPA": "gpa",
                "ATTEMPTED_HRS": "attempted_hrs",
                "EARNED_HRS": "earned_hrs",
                "Major": "curr_major"
            })
Exemplo n.º 9
0
    def __init__(self, height=8, width=8,
                 number_of_agents=2,
                 schedule_type="Simultaneous",
                 rounds=1,):


        # Model Parameters
        self.height = height
        self.width = width
        self.number_of_agents = number_of_agents
        self.step_count = 0
        self.schedule_type = schedule_type
        self.payoffs = {("C", "C"): 3,
                        ("C", "D"): 0,
                        ("D", "C"): 5,
                        ("D", "D"): 2}


        # Model Functions
        self.schedule = self.schedule_types[self.schedule_type](self)
        self.grid = SingleGrid(self.height, self.width, torus=True)

        # Find list of empty cells
        self.coordinates = [(x, y) for x in range(self.width) for y in range(self.height)]

        self.agentIDs = list(range(1, (number_of_agents + 1)))

        self.make_agents()
        self.running = True
Exemplo n.º 10
0
class SchellingModel(Model):
    def __init__(self, height=20, width=20, tolerance=0.3, population=200):
        self.height = height
        self.width = width
        self.tolerance = tolerance
        self.population = population
        self.happy = 0

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)
        self.running = True
        self.setup()

    def setup(self):
        occupied = []
        for i in range(self.population):
            x = np.random.randint(0, self.width)
            y = np.random.randint(0, self.height)
            while [x, y] in occupied:
                x = np.random.randint(0, self.width)
                y = np.random.randint(0, self.height)
            occupied.append([x, y])
            agent = SchellingAgent((x, y), self)
            self.grid.position_agent(agent, (x, y))
            self.schedule.add(agent)

    def happy_ratio(self):
        agents = self.schedule.agents
        return self.happy / len(agents)

    def step(self):
        self.happy = 0  # Reset counter of happy agents
        self.schedule.step()
        if self.happy_ratio() > 0.99:
            self.running = False
Exemplo n.º 11
0
    def __init__(self,
                 height=20,
                 width=20,
                 density=.8,
                 group_ratio=.66,
                 minority_ratio=.5,
                 homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.group_ratio = group_ratio
        self.minority_ratio = minority_ratio
        self.homophily = homophily
        self.happy = 0
        self.segregated = 0

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.place_agents()
        self.datacollector = DataCollector({
            'happy': (lambda m: m.happy),
            'segregated': (lambda m: m.segregated)
        })
        self.running = True
Exemplo n.º 12
0
Arquivo: model.py Projeto: GeoESW/mesa
class ShapesModel(Model):
    def __init__(self, N, width=20, height=10):
        self.running = True
        self.N = N    # num of agents
        self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
        self.grid = SingleGrid(width, height, torus=False)
        self.schedule = RandomActivation(self)
        self.make_walker_agents()

    def make_walker_agents(self):
        unique_id = 0
        while True:
            if unique_id == self.N:
                break
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            pos = (x, y)
            heading = random.choice(self.headings)
            # heading = (1, 0)
            if self.grid.is_cell_empty(pos):
                print("Creating agent {2} at ({0}, {1})"
                      .format(x, y, unique_id))
                a = Walker(unique_id, self, pos, heading)
                self.schedule.add(a)
                self.grid.place_agent(a, pos)
                unique_id += 1

    def step(self):
        self.schedule.step()
Exemplo n.º 13
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))
Exemplo n.º 14
0
 def initialize_grid(self):
     """
     Initializes the initial Grid
     """
     self.grid = SingleGrid(width=self.width,
                            height=self.height,
                            torus=self.toric)
Exemplo n.º 15
0
    def __init__(self, width, height, eta, theta, gamma):
        super().__init__()
        self.grid = SingleGrid(width, height, True)
        self.schedule = RandomActivation(self)
        self.eta = eta
        self.theta = theta
        self.gamma = gamma
        self.nAgents = width * height

        self.avgA = self.A0
        self.avgBD = theta * gamma / self.OMEGA
        self.avgN = (gamma * self.DELTA_T /
                     (1 - math.exp(-self.avgA * self.DELTA_T)))

        for i in range(width):
            for j in range(height):

                newId = self.id + 1
                newAgent = LatticeAgent(newId, self, [], (j, i))
                self.schedule.add(newAgent)
                self.grid.position_agent(newAgent, j, i)
                self.id = newId + 1

        for k in range(round(self.avgN * width * height)):
            acell = random.choice(self.schedule.agents)
            acell.burglers.append(Burgler())
    def __init__(self, grid_height, grid_width, percentage_of_cell_alive):
        """
        Constructor
        """

        self.grid = SingleGrid(grid_width, grid_height, False)
        self.scheduler = SimultaneousActivation(self)
        self.number_of_agent = grid_width * grid_height

        # Creation of all agent
        for i in range(self.number_of_agent):

            # Randomly chooses the initial state of the agent (0 is alive and 1 is dead)
            # We use choices from the random module because it allows us to specify a distribution
            # (ie. a list of probability for each state). Choices will return a list with ne element
            # which is our state
            probability_alive = percentage_of_cell_alive / 100
            probability_dead = 1 - probability_alive
            state = choices([0, 1], [probability_dead, probability_alive])[0]

            # Creating the agent and adding it to the scheduler
            agent = CellAgent(i, state, self)
            self.scheduler.add(agent)

            # Adding the new agent to the grid
            agent_coordinates = self.grid.find_empty()
            self.grid.place_agent(agent, agent_coordinates)

        # Define if the simulation is running or not
        self.running = True
Exemplo n.º 17
0
    def __init__(self, height=30, width=30, density=0.1, oxy_den_count=1):
        """
        """

        self.height = height
        self.width = width
        self.density = density

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=True)
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {
                "x": lambda a: a.pos[0],
                "y": lambda a: a.pos[1]
            },
        )

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                agent = SchellingAgent((x, y), self)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
    def __init__(self, n_agents: int, width: int, height: int,
                 agent_reach_radius: int, prior_sample_size: int,
                 initial_sd: float, start_p_h: float, *args: Any,
                 **kwargs: Any) -> None:
        """
        Create the model.
        :param n_agents: Number of agents to place.
        :param width: Width of the grid.
        :param height: Height of the grid.
        :param agent_reach_radius: Radius around the agent in which it can connect.
        :param prior_sample_size: Size of initial belief sample.
        :param initial_sd: Initial standard deviation of the agents' beliefs.
        :param start_p_h: Initial p|h value.
        """
        super().__init__(*args, **kwargs)
        self.n_agents = n_agents

        self.agent_range = agent_reach_radius

        self.prior_sample_size = prior_sample_size
        self.initial_sd = initial_sd
        self.start_p_h = start_p_h

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

        print('Placing agents.')
        for i in range(self.n_agents):
            agent = ConspiracyAgent(i, self)
            self.schedule.add(agent)

            self.grid.position_agent(agent)
        print('Finished placing agents.')
Exemplo n.º 19
0
    def __init__(self, width, height, num_agents):
        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus = True)
        self.num_agents = num_agents
        
        # to collect info about how many agents are happy, average similarity of neighbors, length of residence
        self.datacollector = DataCollector(model_reporters = {"Happy": lambda m: m.happy, "Similar": lambda m: m.similar, "Residence": lambda m: m.avg_residence}, agent_reporters = {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
        
        self.avg_residence = 0
        self.happy = 0
        self.similar = 0
        self.running = True
        
        for i in range(self.num_agents):   
            # white
            if random.random() < 0.70:
                agent_type = 1
                income = np.random.normal(54000, 41000)
            
            # black
            else:
                agent_type = 0
                income = np.random.normal(32000, 40000)

            # add new agents
            agent = NewAgent(i, self, agent_type, income)
            self.schedule.add(agent)
            
            # assign the initial coords of the agents
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)

            self.grid.position_agent(agent, (x, y))
Exemplo n.º 20
0
    def __init__(self, height=50, width=50, density=0.8, minority_pc=0.5, homophily=3):
        '''
        '''

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if random.random() < self.density:
                if random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
Exemplo n.º 21
0
    def __init__(self, N, length=100, lanes=1, timer=3):
        self.num_agents = N
        self.grid = SingleGrid(length, lanes, torus=True)
        model_stages = [
            "acceleration", "braking", "randomisation", "move", "delete"
        ]
        self.schedule = StagedActivation(self, stage_list=model_stages)

        # Create agent
        for i in range(self.num_agents):
            agent = CarAgent(i, self, False)
            # Add to schedule
            self.schedule.add(agent)
            # Add to grid (randomly)
            self.grid.position_agent(agent)

        # Add the traffic light
        self.traffic_light = TrafficLight(0, self, timer, 20, 20)
        self.average_velocity = CarAgent.init_velocity
        self.datacollector = DataCollector(agent_reporters={
            "Position": "pos",
            "Velocity": "velocity"
        },
                                           model_reporters={
                                               "Average Velocity":
                                               "average_velocity",
                                               "Amount of cars": "agent_count",
                                               "On Ramp Queue":
                                               get_on_ramp_queue,
                                               "Waiting Queue":
                                               get_waiting_queue
                                           })

        self.running = True
Exemplo n.º 22
0
    def __init__(self, height, width, schedule_type, payoffs=None):
        '''
        Create a new Spatial Prisoners' Dilemma Model.

        Args:
            height, width: Grid size. There will be one agent per grid cell.
            schedule_type: Can be "Sequential", "Random", or "Simultaneous".
                           Determines the agent activation regime.
            payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
        '''
        self.grid = SingleGrid(height, width, torus=True)
        self.schedule_type = schedule_type
        self.schedule = self.schedule_types[self.schedule_type](self)

        # Create agents
        for x in range(width):
            for y in range(height):
                agent = PDAgent((x, y), self)
                self.grid.place_agent(agent, (x, y))
                self.schedule.add(agent)

        self.datacollector = DataCollector({
            "Cooperating_Agents":
            lambda m: len([a for a in m.schedule.agents if a.move == "C"])
        })

        self.running = True
        self.datacollector.collect(self)
Exemplo n.º 23
0
    def __init__(self,
                 height=20,
                 width=20,
                 density=0.8,
                 minority_fraction=0.2,
                 tolerance_threshold=4,
                 seed=None):
        super().__init__(seed=seed)
        self.height = height
        self.width = width
        self.density = density
        self.minority_fraction = minority_fraction

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=True)
        self.datacollector = DataCollector(
            model_reporters={'happy': count_happy})

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_fraction:
                    agent_color = Color.RED
                else:
                    agent_color = Color.BLUE

                agent = SchellingAgent((x, y), self, agent_color,
                                       tolerance_threshold)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
Exemplo n.º 24
0
class WorldModel(Model):
    def __init__(self, N, width, height):
        self.grid = SingleGrid(height, width, True)

        self.schedule = RandomActivation(self)
        self.num_agents = N
        self.running = True
        
        for i in range(self.num_agents):
            ethnicity = random.choice(Ethnicities)
            a = PersonAgent(unique_id=i,
                            model=self,
                            ethnicity=int(ethnicity)
                            )
            self.schedule.add(a)
            # Add the agent to a random grid cell

            self.grid.position_agent(a)
            
        self.datacollector = DataCollector(
            agent_reporters={
                "Nationalism": lambda a: a.nationalism,
                "X": lambda a: a.pos[0],
                "Y": lambda a: a.pos[1]
            }
        )

    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()
Exemplo n.º 25
0
    def __init__(
        self,
        height=20,
        width=20,
        density=0.8,
        minority_pc=0.2,
        homophily=3,
        education_boost=0,
        education_pc=0.2,
        seed=None,
    ):
        """Seed is used to set randomness in the __new__ function of the Model superclass."""
        # pylint: disable-msg=unused-argument,super-init-not-called

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily
        self.education_boost = education_boost
        self.education_pc = education_pc

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

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {
                "x": lambda a: a.pos[0],
                "y": lambda a: a.pos[1]
            },
        )

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x_coord = cell[1]
            y_coord = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent_homophily = homophily
                if self.random.random() < self.education_pc:
                    agent_homophily += self.education_boost

                agent = SchellingAgent((x_coord, y_coord), self, agent_type,
                                       agent_homophily)
                self.grid.position_agent(agent, (x_coord, y_coord))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Exemplo n.º 26
0
class Schelling(Model):
    """
    Model class for the Schelling segregation model.
    """
    def __init__(self,
                 height=20,
                 width=20,
                 density=0.8,
                 schedule="RandomActivation",
                 **kwargs):
        """"""

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = 0.4
        self.homophily = 3

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

        self.happy = 0

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True

    def step(self):
        """
        Run one step of the model. If All agents are happy, halt the model.
        """
        self.happy = 0  # Reset counter of happy agents
        self.schedule.step()

        if self.happy == self.schedule.get_agent_count():
            self.running = False

    def on_click(self, x, y, agent_type, **kwargs):
        """Change agent type on click."""
        self.grid[x][y].type = 1 if agent_type == 0 else 0

    @property
    def Step(self):
        return self.schedule.steps
Exemplo n.º 27
0
    def __init__(self, config):
        '''
        Create a new Spatial Game Model

        Args:
            self.dimension: GameGrid size. There will be one agent per grid cell.
            self.num_moves_per_set: The number of moves each player makes with each other before evolving
            self.game_type: The type of game to play
            self.game_mode: The mode of that game to play
            self.cull_score: The minimum score a player must achieve in order to survive
        '''
        super().__init__()

        if config['square']:
            self.dimension = config['dimension']
            self.grid = SingleGrid(self.dimension, self.dimension, torus=config['periodic_BC'])
            self.height = self.dimension
            self.width = self.dimension
        else:
            self.height = config['height']
            self.width = config['width']
            self.dimension = self.width
            self.grid = SingleGrid(self.width, self.height, torus=config['periodic_BC'])

        self.step_num = 0

        self.num_moves_per_set = config['num_moves_per_set']

        self.initial_population_sizes = config['initial_population_sizes']
        self.biomes = config['biomes']
        if self.biomes:
            self.biome_boundaries = biome_boundaries(self.initial_population_sizes, self.width)

        self.cull_score = config['cull_score']
        self.kill_crowded = config['kill_crowded']

        self.probability_adoption = config['probability_adoption']
        self.probability_mutation = config['probability_mutation']
        self.probability_exchange = config['probability_exchange']
        self.probability_playing = config['probability_playing']
        self.probability_death = config['probability_death']

        self.agent_strategies = config['agent_strategies']
        self.agent_moves = config['agent_moves']

        self.schedule = RandomActivation(self)
        self.running = True

        # self.datacollector_populations = DataCollector()
        # self.datacollector_probabilities = DataCollector()

        self.num_mutating = 0
        self.fraction_mutating = 0

        self.num_dead = 0
        self.num_dying = 0
        self.num_evolving = 0
        self.fraction_evolving = 0
        self.crowded_players = []
Exemplo n.º 28
0
class BikeShare(Model):
    """A model with some number of potential riders."""
    global hours_per_day
    hours_per_day = 24

    def __init__(self, N, M, width, height):
        # self.running = True
        self.num_agents = N
        # self.grid = MultiGrid(width, height, True)

        self.num_stations = M
        self.radius = np.int(np.sqrt(width * height))
        self.grid = MultiGrid(width, height, True)
        self.grid_stations = SingleGrid(width, height, True)
        self.schedule = RandomActivation(self)
        self.timestamp = 0 # use to find days
        self.datestamp = 0

        threshold = 0.8

        # create agents
        for i in range(self.num_agents):
            a = BikeRider(i, self, threshold)
            self.schedule.add(a)

            # add the agent to a random grid cell
            x = np.random.randint(self.grid.width)
            y = np.random.randint(self.grid.height)
            self.grid.place_agent(a, (x, y))


        for i in range(self.num_stations):
            s = BikeStation(i, self)
            self.schedule.add(s)

            # add the station to a random grid cell
            # x = np.random.randint(self.grid_stations.width)
            # y = np.random.randint(self.grid_stations.height)
            self.grid_stations.position_agent(s) # ensures one station max
            # self.grid.place_agent(s, s.pos)
            print ("Station " + str(s.unique_id) + "; " + str(s.pos))

        # self.datacollector = DataCollector(
        #     model_reporters={"Gini": compute_gini},
        #     agent_reporters={"Wealth": lambda a: a.wealth}
        # )


    def step(self):
        '''Advance the model by 1 step: arbitrary unit of time. '''
        # self.datacollector.collect(self)
        # print ("Step the schedule ...")
        # print (str(self.timestamp))
        self.timestamp += 1
        if self.timestamp % hours_per_day == 0:
            print ("\n**** new day " + str(self.datestamp))
            self.datestamp += 1
            self.timestamp = 0
        self.schedule.step()
Exemplo n.º 29
0
 def __init__(self, N, width=20, height=10):
     self.running = True
     self.N = N  # num of agents
     self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
     self.grid = SingleGrid(width, height, torus=False)
     self.schedule = RandomActivation(self)
     load_scene('shape_model/crossing.txt', self.grid, self)
     """
Exemplo n.º 30
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)
Exemplo n.º 31
0
class PredatorPreyModel(Model):
    def __init__(self,
                 N_predator,
                 N_prey,
                 width,
                 height,
                 random_seed=None,
                 predator_probdiv=0.15,
                 predator_probdie=0.2,
                 predator_probdiv_init=0.25):
        self.num_predators = N_predator
        self.num_prey = N_prey
        self.num_ids = N_predator + N_prey
        self.grid = SingleGrid(width, height, False)
        self.schedule = RandomActivation(self)
        model_reporters = {}
        agent_reporters = {}
        used_pos_set = set()
        random.seed(a=random_seed)

        for i in range(self.num_predators):
            a = Predator(i,
                         self,
                         probdiv=predator_probdiv,
                         probdie=predator_probdie,
                         probdiv_init=predator_probdiv_init)
            # Generate x,y pos
            xcoor = int(random.random() * width)
            ycoor = int(random.random() * height)
            while str([xcoor, ycoor]) in used_pos_set:
                xcoor = int(random.random() * width)
                ycoor = int(random.random() * height)
            used_pos_set.add(str([xcoor, ycoor]))
            self.grid.position_agent(a, x=xcoor, y=ycoor)

            self.schedule.add(a)

        for i in range(self.num_prey):
            a = Prey(i + self.num_predators, self)
            # Generate x,y pos
            xcoor = int(random.random() * width)
            ycoor = int(random.random() * height)
            while str([xcoor, ycoor]) in used_pos_set:
                xcoor = int(random.random() * width)
                ycoor = int(random.random() * height)
            used_pos_set.add(str([xcoor, ycoor]))
            self.grid.position_agent(a, x=xcoor, y=ycoor)

            self.schedule.add(a)

        self.datacollector = DataCollector(model_reporters=model_reporters,
                                           agent_reporters=agent_reporters)
        self.running = True
        self.datacollector.collect(self)

    def step(self):
        self.schedule.step()
        self.datacollector.collect(self)
Exemplo n.º 32
0
    def __init__(self, height, width, depreciation_rate, mobility, status,
                 stat_var, d_factor):
        # Set model parameters
        self.depreciation_rate = depreciation_rate
        self.mobility = mobility
        self.status = status
        self.stat_var = stat_var
        self.d_factor = d_factor
        self.height = height

        # Global tracking variables
        self.mean_income = 0.0

        self.schedule = SimultaneousActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.datacollector = DataCollector(model_reporters={
            "status":
            lambda m: m.status,
            "income":
            lambda m: m.mean_income,
            "condition":
            lambda m: m.mean_condition
        },
                                           agent_reporters={
                                               "x": lambda a: a.pos[0],
                                               "y": lambda a: a.pos[1]
                                           })

        self.running = True
        self.hit_bottom = False
        self.last_bottom = 0
        self.gent_time = None

        self.conditions = np.zeros((width, height))

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x, y = cell[1], cell[2]

            self.conditions[x, y] = bounded_normal(0.50, 0.1, 0.0, 1.0)

            # Income initially differs little from property conditions
            while True:
                income = self.conditions[x, y] + np.random.normal(0.0, 0.025)
                if income >= 0.0 and income <= 1.0:
                    self.mean_income += income
                    break

            agent = PropertyAgent((x, y), self, income)
            self.grid.position_agent(agent, (x, y))
            self.schedule.add(agent)

        self.mean_condition = np.sum(self.conditions) / self.conditions.size
        self.mean_income /= self.conditions.size
Exemplo n.º 33
0
class Schelling(Model):
    '''
    Model class for the Schelling segregation model.
    '''

    def __init__(self, height=20, width=20, density=0.8, minority_pc=0.2, homophily=3):
        '''
        '''

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)

    def step(self):
        '''
        Run one step of the model. If All agents are happy, halt the model.
        '''
        self.happy = 0  # Reset counter of happy agents
        self.schedule.step()
        # collect data
        self.datacollector.collect(self)

        if self.happy == self.schedule.get_agent_count():
            self.running = False
Exemplo n.º 34
0
class SchellingModel(Model):
    """
    Model class for the Schelling segregation model.
    """

    def __init__(self, height, width, density, minority_pc, homophily):
        """
        """

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.total_agents = 0
        self.datacollector = DataCollector(
            {"unhappy": lambda m: m.total_agents - m.happy},
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[X], "y": lambda a: a.pos[Y]},
        )

        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell, x, y in self.grid.coord_iter():
            if random.random() < self.density:
                if random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent(self.total_agents, agent_type)
                self.grid.position_agent(agent, x, y)
                self.schedule.add(agent)
                self.total_agents += 1

    def step(self):
        """
        Run one step of the model. If All agents are happy, halt the model.
        """
        self.happy = 0  # Reset counter of happy agents
        self.schedule.step()
        self.datacollector.collect(self)

        if self.happy == self.total_agents:
            self.running = False
Exemplo n.º 35
0
class PD_Model(Model):
    '''
    Model class for iterated, spatial prisoner's dilemma model.
    '''

    schedule_types = {"Sequential": BaseScheduler,
                      "Random": RandomActivation,
                      "Simultaneous": SimultaneousActivation}

    # This dictionary holds the payoff for this agent,
    # keyed on: (my_move, other_move)

    payoff = {("C", "C"): 1,
              ("C", "D"): 0,
              ("D", "C"): 1.6,
              ("D", "D"): 0}

    def __init__(self, height, width, schedule_type, payoffs=None):
        '''
        Create a new Spatial Prisoners' Dilemma Model.

        Args:
            height, width: Grid size. There will be one agent per grid cell.
            schedule_type: Can be "Sequential", "Random", or "Simultaneous".
                           Determines the agent activation regime.
            payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
        '''
        self.running = True
        self.grid = SingleGrid(height, width, torus=True)
        self.schedule_type = schedule_type
        self.schedule = self.schedule_types[self.schedule_type](self)

        # Create agents
        for x in range(width):
            for y in range(height):
                agent = PD_Agent((x, y), self)
                self.grid.place_agent(agent, (x, y))
                self.schedule.add(agent)

        self.datacollector = DataCollector({
            "Cooperating_Agents":
            lambda m: len([a for a in m.schedule.agents if a.move == "C"])
        })

    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()

    def run(self, n):
        '''
        Run the model for a certain number of steps.
        '''
        for _ in range(n):
            self.step()
Exemplo n.º 36
0
class SchellingModel(Model):
    '''
    Model class for the Schelling segregation model.
    '''

    def __init__(self, height, width, density, type_pcs=[.2, .2, .2, .2, .2]):
        '''
        '''

        self.height = height
        self.width = width
        self.density = density
        self.type_pcs = type_pcs

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": lambda m: m.happy},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})

        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)

        total_agents = self.height * self.width * self.density
        agents_by_type = [total_agents*val for val in self.type_pcs]

        for loc, types in enumerate(agents_by_type):
            for i in range(int(types)):
                pos = self.grid.find_empty()
                agent = SchellingAgent(pos, self, loc)
                self.grid.position_agent(agent, pos)
                self.schedule.add(agent)

    def step(self):
        '''
        Run one step of the model. If All agents are happy, halt the model.
        '''
        self.happy = 0  # Reset counter of happy agents
        self.schedule.step()
        self.datacollector.collect(self)

        if self.happy == self.schedule.get_agent_count():
            self.running = False
Exemplo n.º 37
0
Arquivo: model.py Projeto: GeoESW/mesa
 def __init__(self, N, width=20, height=10):
     self.running = True
     self.N = N    # num of agents
     self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
     self.grid = SingleGrid(width, height, torus=False)
     self.schedule = RandomActivation(self)
     self.make_walker_agents()
Exemplo n.º 38
0
 def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
     super().__init__(seed=seed)
     self.number_of_bug = num_bug
     if not(strategy in ["stick", "switch"]):
         raise TypeError("'strategy' must be one of {stick, switch}")
     self.strategy = strategy
     
     self.grid = SingleGrid(width, height, torus)
     self.schedule = RandomActivation(self)
     data = {"Bean": lambda m: m.number_of_bean,
             "Corn": lambda m: m.number_of_corn,
             "Soy": lambda m: m.number_of_soy,
             "Bug": lambda m: m.number_of_bug,
             }
     self.datacollector = DataCollector(data)
     
     # create foods
     self._populate(Bean)
     self._populate(Corn)
     self._populate(Soy)
     
     # create bugs
     for i in range(self.number_of_bug):
         pos = self.grid.find_empty()
         bug = Bug(i, self)
         bug.strategy = self.strategy
         self.grid.place_agent(bug, pos)
         self.schedule.add(bug)
Exemplo n.º 39
0
    def __init__(self, height, width, schedule_type, payoffs=None):
        """
        Create a new Spatial Prisoners' Dilemma Model.

        Args:
            height, width: Grid size. There will be one agent per grid cell.
            schedule_type: Can be "Sequential", "Random", or "Simultaneous".
                           Determines the agent activation regime.
            payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
        """
        self.running = True
        self.grid = SingleGrid(height, width, torus=True)
        self.schedule_type = schedule_type
        self.schedule = self.schedule_types[self.schedule_type](self)

        # Create agents
        for x in range(width):
            for y in range(height):
                agent = PD_Agent((x, y))
                self.grid.place_agent(agent, (x, y))
                self.schedule.add(agent)

        self.datacollector = DataCollector(
            {"Cooperating_Agents": lambda m: len([a for a in m.schedule.agents if a.move == "C"])}
        )
Exemplo n.º 40
0
 def setUp(self):
     self.space = SingleGrid(50, 50, False)
     self.agents = []
     for i, pos in enumerate(TEST_AGENTS_GRID):
         a = MockAgent(i, None)
         self.agents.append(a)
         self.space.place_agent(a, pos)
Exemplo n.º 41
0
class Foraging(Model):
    
    number_of_bean = 0
    number_of_corn = 0
    number_of_soy = 0
    
    def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
        super().__init__(seed=seed)
        self.number_of_bug = num_bug
        if not(strategy in ["stick", "switch"]):
            raise TypeError("'strategy' must be one of {stick, switch}")
        self.strategy = strategy
        
        self.grid = SingleGrid(width, height, torus)
        self.schedule = RandomActivation(self)
        data = {"Bean": lambda m: m.number_of_bean,
                "Corn": lambda m: m.number_of_corn,
                "Soy": lambda m: m.number_of_soy,
                "Bug": lambda m: m.number_of_bug,
                }
        self.datacollector = DataCollector(data)
        
        # create foods
        self._populate(Bean)
        self._populate(Corn)
        self._populate(Soy)
        
        # create bugs
        for i in range(self.number_of_bug):
            pos = self.grid.find_empty()
            bug = Bug(i, self)
            bug.strategy = self.strategy
            self.grid.place_agent(bug, pos)
            self.schedule.add(bug)
    
    def step(self):
        self.schedule.step()
        self.datacollector.collect(self)
        
        if not(self.grid.exists_empty_cells()):
            self.running = False
    
    def _populate(self, food_type):
        prefix = "number_of_{}"
        
        counter = 0
        while counter < food_type.density * (self.grid.width * self.grid.height):
            pos = self.grid.find_empty()
            food = food_type(counter, self)
            self.grid.place_agent(food, pos)
            self.schedule.add(food)
            food_name = food_type.__name__.lower()
            attr_name = prefix.format(food_name)
            val = getattr(self, attr_name)
            val += 1
            setattr(self, attr_name, val)
            counter += 1
Exemplo n.º 42
0
    def __init__(self, height, width, palestinian_density, settlement_density,
                 settlers_violence_rate, settlers_growth_rate, suicide_rate, greed_level,
                 settler_vision=1, palestinian_vision=1, 
                 movement=True, max_iters=1000):

        super(SeparationBarrierModel, self).__init__()
        self.height = height
        self.width = width
        self.palestinian_density = palestinian_density
        self.settler_vision = settler_vision
        self.palestinian_vision = palestinian_vision
        self.settlement_density = settlement_density
        self.movement = movement
        self.running = True
        self.max_iters = max_iters
        self.iteration = 0
        self.schedule = RandomActivation(self)
        self.settlers_violence_rate = settlers_violence_rate
        self.settlers_growth_rate = settlers_growth_rate
        self.suicide_rate = suicide_rate
        self.greed_level = greed_level

        self.total_violence = 0

        self.grid = SingleGrid(height, width, torus=False)

        model_reporters = {
        }
        agent_reporters = {
#           "x": lambda a: a.pos[0],
#           "y": lambda a: a.pos[1],
        }
        self.dc = DataCollector(model_reporters=model_reporters,
                                agent_reporters=agent_reporters)
        self.unique_id = 0

        # Israelis and palestinans split the region in half
        for (contents, x, y) in self.grid.coord_iter():
            if random.random() < self.palestinian_density:
                palestinian = Palestinian(self.unique_id, (x, y), vision=self.palestinian_vision, breed="Palestinian",
                          model=self)
                self.unique_id += 1
                self.grid.position_agent(palestinian, x,y)
                self.schedule.add(palestinian)
            elif ((y > (self.grid.height) * (1-self.settlement_density)) and random.random() < self.settlement_density):
                settler = Settler(self.unique_id, (x, y),
                                  vision=self.settler_vision, model=self, breed="Settler")
                self.unique_id += 1
                self.grid.position_agent(settler, x,y)
                self.schedule.add(settler)
Exemplo n.º 43
0
    def __init__(self, height=20, width=20, density=.8, group_ratio=.66, minority_ratio=.5, homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.group_ratio = group_ratio
        self.minority_ratio = minority_ratio
        self.homophily = homophily
        self.happy = 0
        self.segregated = 0

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.place_agents()
        self.datacollector = DataCollector( {'happy': (lambda m: m.happy), 'segregated': (lambda m: m.segregated)})
        self.running = True
Exemplo n.º 44
0
 def setUp(self):
     '''
     Create a test non-toroidal grid and populate it with Mock Agents
     '''
     self.grid = SingleGrid(3, 5, True)
     self.agents = []
     counter = 0
     for y in range(3):
         for x in range(5):
             if TEST_GRID[y][x] == 0:
                 continue
             counter += 1
             # Create and place the mock agent
             a = MockAgent(counter, None)
             self.agents.append(a)
             self.grid.place_agent(a, (x, y))
Exemplo n.º 45
0
 def setUp(self):
     '''
     Create a test non-toroidal grid and populate it with Mock Agents
     '''
     width = 3
     height = 5
     self.grid = SingleGrid(width, height, True)
     self.agents = []
     counter = 0
     for x in range(width):
         for y in range(height):
             if TEST_GRID[x][y] == 0:
                 continue
             counter += 1
             # Create and place the mock agent
             a = MockAgent(counter, None)
             self.agents.append(a)
             self.grid.place_agent(a, (x, y))
Exemplo n.º 46
0
    def __init__(self, height, width, density, minority_pc, homophily):
        """
        """

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.total_agents = 0
        self.datacollector = DataCollector(
            {"unhappy": lambda m: m.total_agents - m.happy},
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[X], "y": lambda a: a.pos[Y]},
        )

        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell, x, y in self.grid.coord_iter():
            if random.random() < self.density:
                if random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent(self.total_agents, agent_type)
                self.grid.position_agent(agent, x, y)
                self.schedule.add(agent)
                self.total_agents += 1
Exemplo n.º 47
0
Arquivo: model.py Projeto: GeoESW/mesa
    def __init__(self, height, width, density, minority_pc, homophily):
        '''
        '''

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

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

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": lambda m: m.happy},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})

        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if random.random() < self.density:
                if random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
Exemplo n.º 48
0
class TestSingleGrid(unittest.TestCase):
    def setUp(self):
        self.space = SingleGrid(50, 50, False)
        self.agents = []
        for i, pos in enumerate(TEST_AGENTS_GRID):
            a = MockAgent(i, None)
            self.agents.append(a)
            self.space.place_agent(a, pos)

    def test_agent_positions(self):
        '''
        Ensure that the agents are all placed properly.
        '''
        for i, pos in enumerate(TEST_AGENTS_GRID):
            a = self.agents[i]
            assert a.pos == pos

    def test_remove_agent(self):
        for i, pos in enumerate(TEST_AGENTS_GRID):
            a = self.agents[i]
            assert a.pos == pos
            assert self.space.grid[pos[0]][pos[1]] == a
            self.space.remove_agent(a)
            assert a.pos is None
            assert self.space.grid[pos[0]][pos[1]] is None

    def move_agent(self):
        agent_number = 0
        initial_pos = TEST_AGENTS_GRID[agent_number]
        final_pos = (7, 7)

        _agent = self.agents[agent_number]

        assert _agent.pos == initial_pos
        assert self.space.grid[initial_pos[0]][initial_pos[1]] == _agent
        assert self.space.grid[final_pos[0]][final_pos[1]] is None
        self.space.move_agent(_agent, final_pos)
        assert _agent.pos == final_pos
        assert self.space.grid[initial_pos[0]][initial_pos[1]] is None
        assert self.space.grid[final_pos[0]][final_pos[1]] == _agent
Exemplo n.º 49
0
class SchellingModel(Model):
    '''Model class for Schelling segregation model'''

    def __init__(self, height=20, width=20, density=.8, group_ratio=.66, minority_ratio=.5, homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.group_ratio = group_ratio
        self.minority_ratio = minority_ratio
        self.homophily = homophily
        self.happy = 0
        self.segregated = 0

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.place_agents()
        self.datacollector = DataCollector( {'happy': (lambda m: m.happy), 'segregated': (lambda m: m.segregated)})
        self.running = True


    def step(self):
        '''Run one step of model'''
        self.schedule.step()
        self.calculate_stats()
        self.datacollector.collect(self)

        if self.happy == self.schedule.get_agent_count():
            self.running = False


    def place_agents(self):
        for cell in self.grid.coord_iter():
            x, y = cell[1:3]
            if random.random() < self.density:
                if random.random() < self.group_ratio:
                    if random.random() < self.minority_ratio:
                        group = 0
                    else:
                        group = 1
                else:
                    group = 2

                agent = SchellingAgent((x,y), group)
                self.grid.position_agent(agent, (x,y))
                self.schedule.add(agent)

        for agent in self.schedule.agents:
            count = 0
            for neighbour in self.grid.iter_neighbors(agent.pos, moore=False):
                if neighbour.group == agent.group:
                    count += 1
            agent.similar = count


    def calculate_stats(self):
        happy_count = 0
        avg_seg = 0
        for agent in self.schedule.agents:
            avg_seg += agent.similar
            if agent.similar >= self.homophily:
                happy_count += 1

        self.happy = happy_count
        self.segregated = avg_seg/self.schedule.get_agent_count()
Exemplo n.º 50
0
class TestSingleGrid(unittest.TestCase):
    '''
    Test the SingleGrid object.

    Since it inherits from Grid, all the functionality tested above should
    work here too. Instead, this tests the enforcement.
    '''

    def setUp(self):
        '''
        Create a test non-toroidal grid and populate it with Mock Agents
        '''
        width = 3
        height = 5
        self.grid = SingleGrid(width, height, True)
        self.agents = []
        counter = 0
        for x in range(width):
            for y in range(height):
                if TEST_GRID[x][y] == 0:
                    continue
                counter += 1
                # Create and place the mock agent
                a = MockAgent(counter, None)
                self.agents.append(a)
                self.grid.place_agent(a, (x, y))

    def test_enforcement(self):
        '''
        Test the SingleGrid empty count and enforcement.
        '''

        assert len(self.grid.empties) == 9
        a = MockAgent(100, None)
        with self.assertRaises(Exception):
            self.grid._place_agent((0, 1), a)

        # Place the agent in an empty cell
        self.grid.position_agent(a)
        # Test whether after placing, the empty cells are reduced by 1
        assert a.pos not in self.grid.empties
        assert len(self.grid.empties) == 8
        for i in range(10):
            self.grid.move_to_empty(a)
        assert len(self.grid.empties) == 8

        # Place agents until the grid is full
        empty_cells = len(self.grid.empties)
        for i in range(empty_cells):
            a = MockAgent(101 + i, None)
            self.grid.position_agent(a)
        assert len(self.grid.empties) == 0

        a = MockAgent(110, None)
        with self.assertRaises(Exception):
            self.grid.position_agent(a)
        with self.assertRaises(Exception):
            self.move_to_empty(self.agents[0])
Exemplo n.º 51
0
class SeparationBarrierModel(Model):
    def __init__(self, height, width, palestinian_density, settlement_density,
                 settlers_violence_rate, settlers_growth_rate, suicide_rate, greed_level,
                 settler_vision=1, palestinian_vision=1, 
                 movement=True, max_iters=1000):

        super(SeparationBarrierModel, self).__init__()
        self.height = height
        self.width = width
        self.palestinian_density = palestinian_density
        self.settler_vision = settler_vision
        self.palestinian_vision = palestinian_vision
        self.settlement_density = settlement_density
        self.movement = movement
        self.running = True
        self.max_iters = max_iters
        self.iteration = 0
        self.schedule = RandomActivation(self)
        self.settlers_violence_rate = settlers_violence_rate
        self.settlers_growth_rate = settlers_growth_rate
        self.suicide_rate = suicide_rate
        self.greed_level = greed_level

        self.total_violence = 0

        self.grid = SingleGrid(height, width, torus=False)

        model_reporters = {
        }
        agent_reporters = {
#           "x": lambda a: a.pos[0],
#           "y": lambda a: a.pos[1],
        }
        self.dc = DataCollector(model_reporters=model_reporters,
                                agent_reporters=agent_reporters)
        self.unique_id = 0

        # Israelis and palestinans split the region in half
        for (contents, x, y) in self.grid.coord_iter():
            if random.random() < self.palestinian_density:
                palestinian = Palestinian(self.unique_id, (x, y), vision=self.palestinian_vision, breed="Palestinian",
                          model=self)
                self.unique_id += 1
                self.grid.position_agent(palestinian, x,y)
                self.schedule.add(palestinian)
            elif ((y > (self.grid.height) * (1-self.settlement_density)) and random.random() < self.settlement_density):
                settler = Settler(self.unique_id, (x, y),
                                  vision=self.settler_vision, model=self, breed="Settler")
                self.unique_id += 1
                self.grid.position_agent(settler, x,y)
                self.schedule.add(settler)

    def add_settler(self, pos):
        settler = Settler(self.unique_id, pos,
                          vision=self.settler_vision, model=self, breed="Settler")
        self.unique_id += 1
        self.grid.position_agent(settler, pos[0], pos[1])
        self.schedule.add(settler)

    def set_barrier(self,victim_pos, violent_pos):
        #print("Set barrier - Greed level", self.greed_level)
        visible_spots = self.grid.get_neighborhood(victim_pos,
                                                        moore=True, radius=self.greed_level + 1)
        furthest_empty  = self.find_furthest_empty_or_palestinian(victim_pos, visible_spots)
        x,y = furthest_empty
        current = self.grid[y][x]
        #print ("Set barrier!!", pos, current)
        free = True
        if (current is not None and current.breed == "Palestinian"):
            #print ("Relocating Palestinian")
           free =  self.relocate_palestinian(current, current.pos)

        if (free):
            barrier = Barrier(-1, furthest_empty, model=self)
            self.grid.position_agent(barrier, x,y)
        
        # Relocate the violent palestinian
        #violent_x, violent_y = violent_pos
        #if violent_pos != furthest_empty:
        #    violent_palestinian = self.grid[violent_y][violent_x]
        #    self.relocate_palestinian(violent_palestinian, furthest_empty)

    def relocate_palestinian(self, palestinian, destination):
        #print ("Relocating Palestinian in ", palestinian.pos, "To somehwhere near ", destination)
        visible_spots = self.grid.get_neighborhood(destination,
                                                        moore=True, radius=palestinian.vision)
        nearest_empty = self.find_nearest_empty(destination, visible_spots)
        #print("First Nearest empty to ", palestinian.pos, " Is ", nearest_empty)
        if (nearest_empty):
            self.grid.move_agent(palestinian, nearest_empty)
        else:
            #print ("Moveing to random empty")
            if (self.grid.exists_empty_cells()):
                self.grid.move_to_empty(palestinian)
            else:
                return False

        return True

    def find_nearest_empty(self, pos, neighborhood):
        nearest_empty = None
        sorted_spots = self.sort_neighborhood_by_distance(pos, neighborhood)
        index = 0
        while (nearest_empty is None and index < len(sorted_spots)):
            if self.grid.is_cell_empty(sorted_spots[index]):
                nearest_empty = sorted_spots[index]
            index += 1

        return nearest_empty

    def find_furthest_empty_or_palestinian(self, pos, neighborhood):
        furthest_empty = None
        sorted_spots = self.sort_neighborhood_by_distance(pos, neighborhood)
        sorted_spots.reverse()
        index = 0
        while (furthest_empty is None and index < len(sorted_spots)):
            spot = sorted_spots[index]
            if self.grid.is_cell_empty(spot) or self.grid[spot[1]][spot[0]].breed == "Palestinian" :
                furthest_empty = sorted_spots[index]
            index += 1

        return furthest_empty



    def sort_neighborhood_by_distance(self, from_pos, neighbor_spots):
        from_x, from_y = from_pos
        return sorted(neighbor_spots, key = lambda spot: self.eucledean_distance(from_x, spot[0], from_y, spot[1], self.grid.width, self.grid.height))


    def eucledean_distance(self, x1,x2,y1,y2,w,h):
        # http://stackoverflow.com/questions/2123947/calculate-distance-between-two-x-y-coordinates
        return math.sqrt(min(abs(x1 - x2), w - abs(x1 - x2)) ** 2 + min(abs(y1 - y2), h - abs(y1-y2)) ** 2)
        

    def step(self):
        """
        Advance the model by one step and collect data.
        """
        self.violence_count = 0
      #  for i in range(100):
        self.schedule.step()
        self.total_violence += self.violence_count
      #  average = self.violence_count / 100
        #print("Violence average %f " % average)
        print("Total Violence: ", self.total_violence)
Exemplo n.º 52
0
class TestSingleGrid(unittest.TestCase):
    '''
    Test the SingleGrid object.

    Since it inherits from Grid, all the functionality tested above should
    work here too. Instead, this tests the enforcement.
    '''

    def setUp(self):
        '''
        Create a test non-toroidal grid and populate it with Mock Agents
        '''
        self.grid = SingleGrid(3, 5, True)
        self.agents = []
        counter = 0
        for y in range(3):
            for x in range(5):
                if TEST_GRID[y][x] == 0:
                    continue
                counter += 1
                # Create and place the mock agent
                a = MockAgent(counter, None)
                self.agents.append(a)
                self.grid.place_agent(a, (x, y))

    def test_enforcement(self):
        '''
        Test the SingleGrid empty count and enforcement.
        '''

        assert len(self.grid.empties) == 10
        a = MockAgent(100, None)
        with self.assertRaises(Exception):
            self.grid._place_agent((1, 0), a)

        # Place the agent in an empty cell
        self.grid.position_agent(a)
        assert a.pos not in self.grid.empties
        assert len(self.grid.empties) == 9
        for i in range(10):
            self.grid.move_to_empty(a)
        assert len(self.grid.empties) == 9

        # Place agents until the grid is full
        for i in range(9):
            a = MockAgent(101 + i, None)
            self.grid.position_agent(a)
        assert len(self.grid.empties) == 0

        a = MockAgent(110, None)
        with self.assertRaises(Exception):
            self.grid.position_agent(a)
        with self.assertRaises(Exception):
            self.move_to_empty(self.agents[0])