Пример #1
0
    def __init__(self, no_agents, width, height, init_infected, perc_masked,
                 prob_trans_masked, prob_trans_unmasked, infection_period,
                 immunity_period):
        self.no_agents = no_agents
        self.grid = MultiGrid(width, height, True)
        self.init_infected = init_infected
        self.perc_masked = perc_masked
        self.prob_trans_masked = prob_trans_masked
        self.prob_trans_unmasked = prob_trans_unmasked
        self.infection_period = infection_period
        self.immunity_period = immunity_period
        self.schedule = RandomActivation(self)
        self.running = True

        # Create agents
        for i in range(self.no_agents):
            a = Agent(i, self)
            self.schedule.add(a)

            # Add the agent to a random grid cell
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))

        # Collect count of susceptible, infected, and recovered agents
        self.datacollector = DataCollector({
            'Susceptible': 'susceptible',
            'Infected': 'infected',
            'Recovered & Immune': 'immune'
        })
Пример #2
0
    def __init__(self, no_people, total_area, no_agents, all_x, all_y,
                 infection_rate, first_infected, mobility, work_store,
                 home_store):
        self.num_agents = no_agents
        grid_size = round(
            math.sqrt((self.num_agents / no_people) * total_area) * 100)
        self.grid = MultiGrid(grid_size, grid_size, False)
        self.schedule = RandomActivation(self)
        self.running = True

        for i in range(self.num_agents):
            a = Agent(i, self, infection_rate, work_store, home_store,
                      mobility)
            self.schedule.add(a)
            self.grid.place_agent(a, (int(all_x[i]), int(all_y[i])))

            if i == first_infected:
                a.infected = 1

        self.datacollector = DataCollector(
            model_reporters={"Tot infections": compute_informed},
            agent_reporters={
                "Infected": "infected",
                "R-Number": "rnumber"
            })
Пример #3
0
    def __init__(self, home_store):
        self.num_agents = 1000
        self.grid = MultiGrid(200, 200, True)
        self.schedule = RandomActivation(self)
        self.running = True

        for i in range(self.num_agents):
            a = Agent(i, self)
            self.schedule.add(a)
            while True:
                #x = round(int(np.random.normal(self.grid.width/2, 10, 1)))
                #y = round(int(np.random.normal(self.grid.height/2, 10, 1)))
                x = self.random.randrange(self.grid.width)
                y = self.random.randrange(self.grid.height)
                if len(
                        self.grid.get_neighbors(
                            (x, y), moore=True, include_center=True,
                            radius=10)) <= 7:
                    self.grid.place_agent(a, (x, y))
                    home_store[i, :] = x, y
                    break

            if i < 1:
                a.infected = 1

        self.datacollector = DataCollector(
            model_reporters={"Tot informed": compute_informed},
            agent_reporters={"Infected": "infected"})
Пример #4
0
    def __init__(self, city_to_country, no_people, total_area, city_to_country_area, countryside):
        self.num_agents = 2000
        grid_size = round(math.sqrt((self.num_agents/no_people)*total_area)*100)
        self.grid = MultiGrid(grid_size, grid_size, True)
        self.schedule = RandomActivation(self)
        self.running = True

        centers = np.zeros((1, 2))
        centers[0, :] = random.randrange(10, self.grid.width - 10), random.randrange(10, self.grid.height - 10)
        x = np.zeros((1, round(int(city_to_country * self.num_agents))))
        y = np.zeros((1, round(int(city_to_country * self.num_agents))))
        x[0, :] = np.around(np.random.normal(centers[0, 0], 3, round(int(city_to_country * self.num_agents))))
        y[0, :] = np.around(np.random.normal(centers[0, 1], 3, round(int(city_to_country * self.num_agents))))

        count = 0
        countryside_count = 0
        while countryside_count < (countryside * self.num_agents):
            countryside_count += counter(x)
            runner = True
            while runner:
                new_center = (random.randrange(10, self.grid.width - 10), random.randrange(10, self.grid.height - 10))
                if dist_check(new_center, centers):
                    centers = np.vstack((centers, new_center))
                    runner = False

            new_x = np.around(np.random.normal(centers[count, 0], (1/(6*city_to_country_area*(math.sqrt(count+1))))
                                               * self.grid.width, round(int(city_to_country * self.num_agents)
                                                                        / (count + 2))))
            new_y = np.around(np.random.normal(centers[count, 1], (1/(6*city_to_country_area*(math.sqrt(count+1))))
                                               * self.grid.height, round(int(city_to_country * self.num_agents)
                                                                         / (count + 2))))
            while len(new_x) < round(int(city_to_country * self.num_agents)):
                new_x = np.append(new_x, -1)
                new_y = np.append(new_y, -1)

            x = np.vstack((x, new_x))
            y = np.vstack((y, new_y))
            count += 1

        new_x = np.delete(x.flatten(), np.where(x.flatten() == -1))
        new_y = np.delete(y.flatten(), np.where(y.flatten() == -1))

        x_countryside = np.around(np.random.uniform(0, self.grid.width-1, int(self.num_agents - len(new_x))))
        y_countryside = np.around(np.random.uniform(0, self.grid.height-1, int(self.num_agents - len(new_y))))

        all_x = np.concatenate((new_x, x_countryside))
        all_y = np.concatenate((new_y, y_countryside))

        for i in range(self.num_agents):
            a = Agent(i, self)
            self.schedule.add(a)
            self.grid.place_agent(a, (int(all_x[i]), int(all_y[i])))

            if i == 1:
                a.infected = 1

        self.datacollector = DataCollector(
            model_reporters={"Tot informed": compute_informed},
            agent_reporters={"Infected": "infected"})
    def testGraphMovement3D(self):

        ms, _grid = MeshSpace.read("test/meshes/sphere.msh")
        nodes = ms.G.nodes
        starting_node = 0
        a = Agent(0, None)
        ms.place_agent(a, starting_node)
        possible_steps = ms.get_neighbors(a.pos, include_center=False)
        self.assertEqual(possible_steps, [31, 43, 6])
        new_position = random.choice(possible_steps)
        ms.move_agent(a, new_position)
        self.assertTrue(a.pos == new_position)
    def __init__(self, N, width, height):
        self.agents = N
        self.grid = MultiGrid(width, height, True)
        self.schedule = RandomActivation(self)
        self.running = True
        self.steps = 0
        self.encounters = 0
        self.mean_encounters = 0

        # creating agents by iterating through n_agents
        for i in range(self.agents):
            # specify an agent as an object of class 'Agent' with unique_ID 'i'
            agent = Agent(i, self)
            # specify pitch measures for the agent as type 'float'
            agent.iqr = float(iqr.iloc[i])
            agent.speechrate = float(speechrate.iloc[i])
            agent.mad = float(mad.iloc[i])
            agent.pause = float(pause.iloc[i])
            agent.diagnosis = float(diagnosis.iloc[i])

            agent.symptom_severity = (agent.iqr + agent.mad +
                                      (1 - agent.speechrate) + agent.pause) / 4

            # add the agent to the model schedule
            self.schedule.add(agent)

            # adding the agent to a random grid cell
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)
            self.grid.place_agent(agent, (x, y))

            # add data-collector to the agent
            self.datacollector = DataCollector(
                agent_reporters={
                    "interactions": "unique_interactions",
                    "interaction_time": "interaction_time",
                    "conversation_time": "conversation_time",
                    "change_IQR": "change_iqr",
                    "change_MAD": "change_mad",
                    "change_Speechrate": "change_speechrate",
                    "change_PauseFreq": "change_pause",
                    "abs_change_IQR": "abs_change_iqr",
                    "abs_change_MAD": "abs_change_mad",
                    "abs_change_Speechrate": "abs_change_speechrate",
                    "abs_change_PauseFreq": "abs_change_pause",
                    "activity": "activity",
                    "diagnosis": "diagnosis"
                },
                model_reporters={"Encounters": "encounters"})
Пример #7
0
    def __init__(self, seed, collect_stepwise_data, N, x, y, z):
        from mesa import Agent as Agent
        self.N, self.x, self.y, self.z = N, x, y, z
        self.schedule = RandomActivation(self)
        self.schedule.add(Agent(2, self))
        self.schedule.add(Agent(9, self))

        from mesa.datacollection import DataCollector
        self.datacollector = DataCollector(model_reporters={
            'N': lambda m: m.N,
            'X_1': lambda m: m.x,
            'Y_2': lambda m: m.y,
            'X_3': lambda m: m.z,
        },
                                           agent_reporters={
                                               'id': lambda a: a.unique_id,
                                           })
        self.datacollector.collect(self)
        self.step()
        self.datacollector.collect(self)
        self.step()
        self.datacollector.collect(self)

        self.running = True
Пример #8
0
    def __init__(self, attributesFile, connectionsFile, xmax, ymax,
                 roleOrder):  # coords of map edge
        attributesDB = pd.read_csv(attributesFile, header=None)
        connectionsDB = pd.read_csv(connectionsFile, header=None)
        self.running = True
        self.grid = MultiGrid(xmax, ymax, True)  # bool = toroidal
        self.schedule = Activation(self, roleOrder)

        self.agents = []

        # WALTHER DATA
        # Create agents
        for index, row in attributesDB.iterrows():
            # From attributesDB: agent id, role, gender, current $, current rice, x coord and y coord
            newAgent = Agent(
                row[0], self, row[1], row[2], row[3], row[4]
            )  # Gotta assume the IDs correspond to the row number because the OECD book says it's matrix-based
            self.schedule.add(newAgent)
            self.grid.place_agent(newAgent, (row[5], row[6]))
            self.agents.append(newAgent)

        # Add links
        for index, row in connectionsDB.iterrows():
            agent = next(
                (x for x in self.agents if x.unique_id == row[0]), None
            )  # I'm gonna say for now you can't assume this list is ordered the way the agents are added even though that's pretty paranoid
            print(agent)
            for i in range(1, len(row)):  # for column index aka other agent id
                if row[i] == 1:
                    agent.pointsTo.append(
                        next(
                            (x for x in self.agents if x.unique_id == (i - 1)),
                            None))
                    agent.pointsToIDs.append(i - 1)

        self.datacollector = DataCollector(
            agent_reporters={
                "unique_id": "unique_id",
                "gender": "gender",
                "role": "role",
                "rice": "rice",
                "capital": "capital",
                "pointsTo": "pointsToIDs",
                "soldTo": "soldTo"
            })
Пример #9
0
    def __init__(self, mobility):
        self.num_agents = 1000
        self.grid = MultiGrid(100, 100, True)
        self.schedule = RandomActivation(self)
        self.running = True

        for i in range(self.num_agents):
            a = Agent(i, mobility, self)
            self.schedule.add(a)
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)
            self.grid.place_agent(a, (x, y))
            if i < 1:
                a.infected = 1

        self.datacollector = DataCollector(
            model_reporters={"Tot informed": compute_informed},
            agent_reporters={"Infected": "infected"})
Пример #10
0
    def __init__(self, height, width, a_density=0.1, r_=0.1, k_=0.1):

        self.height = height
        self.width = width
        self.a_density = a_density
        self.r_ = r_
        self.k_ = k_

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=False)
        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)

        #seed to always start agents in the same place
        random.seed(9001)

        #create food matrix
        n = self.height
        m = self.width
        self.food_matrix = [[100] * m for i in range(n)]

        #randomly place agents
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            a = random.random()
            if a < self.a_density:
                agent = Agent((x, y), self)
                self.grid.place_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Пример #11
0
    def __init__(self, width=5, height=5, threshold=0.5, population_density=0.8, population_breakdown=0.5):
        '''
         Initialize the model

         Args:
            width:     Width  of the grid containing agents.
            height:    Height of the grid containing agents.
            threshold: Homophily threshold, the number, from 0-8, of nearest neighbours at which I am so unhappy that I move.
        	population_density:   Proportion of cells occupied, from 0-1.
        	population_breakdown: Proportion of agents of type 1, from 0-1.
        '''        
        self.running   = True

        self.height    = height
        self.width     = width
        self.threshold = threshold
        self.population_density     = population_density
        self.population_breakdown   = population_breakdown
        self.no_happy_this_timestep = 0
        self.schedule  = RandomActivation(self)
        self.grid      = SingleGrid(width, height, torus=True)
        
        self.datacollector = DataCollector(
            {"happy": lambda m: m.no_happy_this_timestep},
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if random.random() < self.population_density:
                if random.random() < self.population_breakdown:
                    agent_type = 1
                else:
                    agent_type = 0
                agent = Agent(self,(x, y), agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
    def testGraphMovement2D(self):
        ms, _grid = MeshSpace.read("test/meshes/plane.msh")

        nodes = ms.G.nodes
        starting_node = 0
        ending_node = 10
        a = Agent(0, None)
        short_path = (nx.shortest_path(ms.G, starting_node, ending_node))
        # check short path
        self.assertEqual(short_path, [0, 19, 10])
        ms.place_agent(a, starting_node)
        track_move = 0

        while a.pos != ending_node:
            possible_steps = ms.get_neighbors(a.pos, include_center=False)
            #check neighbors for pos 0 pos 1 and pos 2
            if a.pos == short_path[0]:
                self.assertEqual(possible_steps, [4, 19, 2])
            elif a.pos == short_path[1]:
                self.assertEqual(possible_steps, [14, 10, 0])

            for neighbor in possible_steps:
                if neighbor == short_path[track_move + 1]:
                    new_position = neighbor
                    break

            #check we have found the new path
            self.assertNotEqual(a.pos, new_position)

            #new_position = random.choice(possible_steps)
            ms.move_agent(a, new_position)
            self.assertTrue(a.pos == new_position)
            track_move += 1

        #Check that we have arrived to our destination
        self.assertTrue(a.pos == ending_node)
Пример #13
0
    def __init__(self, city_to_country, no_people, total_area, city_to_country_area, countryside, no_agents, Nc_N, n):
        self.num_agents = no_agents
        grid_size = round(math.sqrt((self.num_agents / no_people) * total_area) * 100)
        self.grid = MultiGrid(grid_size, grid_size, False)
        self.schedule = RandomActivation(self)
        self.running = True

        centers = np.zeros((1, 2))
        centers[0, :] = random.randrange(10, self.grid.width - 10), random.randrange(10, self.grid.height - 10)
        x = np.zeros((1, round(int(city_to_country * self.num_agents))))
        y = np.zeros((1, round(int(city_to_country * self.num_agents))))
        x[0, :] = np.around(np.random.normal(centers[0, 0], 3, round(int(city_to_country * self.num_agents))))
        y[0, :] = np.around(np.random.normal(centers[0, 1], 3, round(int(city_to_country * self.num_agents))))

        count = 0
        countryside_count = 0
        while countryside_count < (countryside * self.num_agents):
            countryside_count += counter(x)
            runner = True
            while runner:
                new_center = (random.randrange(10, self.grid.width - 10), random.randrange(10, self.grid.height - 10))
                if dist_check(new_center, centers):
                    centers = np.vstack((centers, new_center))
                    runner = False

            new_x = np.around(
                np.random.normal(centers[count, 0], (1 / (6 * city_to_country_area * (math.sqrt(count + 1))))
                                 * self.grid.width, round(int(city_to_country * self.num_agents)
                                                          / (count + 2))))
            new_y = np.around(
                np.random.normal(centers[count, 1], (1 / (6 * city_to_country_area * (math.sqrt(count + 1))))
                                 * self.grid.height, round(int(city_to_country * self.num_agents)
                                                           / (count + 2))))
            while len(new_x) < round(int(city_to_country * self.num_agents)):
                new_x = np.append(new_x, -1)
                new_y = np.append(new_y, -1)

            x = np.vstack((x, new_x))
            y = np.vstack((y, new_y))
            count += 1

        label = city_labeler(x)
        for i in range(len(label)):
            city_label[i] = label[i]

        new_x = np.delete(x.flatten(), np.where(x.flatten() == -1))
        new_y = np.delete(y.flatten(), np.where(y.flatten() == -1))

        x_countryside = np.around(np.random.uniform(0, self.grid.width - 1, int(self.num_agents - len(new_x))))
        y_countryside = np.around(np.random.uniform(0, self.grid.height - 1, int(self.num_agents - len(new_y))))

        all_x = np.concatenate((new_x, x_countryside))
        all_y = np.concatenate((new_y, y_countryside))

        for i in range(self.num_agents):
            a = Agent(i, self)
            self.schedule.add(a)
            self.grid.place_agent(a, (int(all_x[i]), int(all_y[i])))
            home_store1[i, :] = int(all_x[i]), int(all_y[i])

            if i == 1:
                a.infected = 1
                #a.working = 1

        flux_store = np.zeros((1, 3))

        for i in range(round(len(centers) / 2)):
            print(i)
            #print(round(len(centers))/2)
            n_cities = random.sample(range(1, round(len(centers) / 2)), n)

            for j in range(len(n_cities)):
                mi = np.count_nonzero(city_label == i+1)
                nj = np.count_nonzero(city_label == n_cities[j])
                radius = math.sqrt((centers[i, 0] - centers[n_cities[j], 0]) ** 2 +
                                   (centers[i, 1] - centers[n_cities[j], 1]) ** 2)
                sij = 0

                for k in range(len(all_x)):
                    if (all_x[k] - centers[i, 0]) ** 2 + (all_y[k] - centers[i, 1]) ** 2 < radius ** 2:
                        sij += 1

                sij = sij - mi - nj
                if sij < 0:
                    sij = 0

                try:
                    Tij = (mi * Nc_N * mi * nj) / ((mi + sij) * (mi + nj + sij))*10
                except ZeroDivisionError:
                    Tij = 0

                if Tij > 75:
                    Tij = 75

                if Tij > 1 and (i != n_cities[j]):
                    flux_store = np.vstack((flux_store, (Tij, i+1, n_cities[j])))

        work_place = np.zeros(self.num_agents)
        work_store1 = np.zeros((num, 2))
        flux_store = np.delete(flux_store, 0, 0)

        for i in np.unique(flux_store[:, 1]):
            place = np.where(flux_store[:, 1] == i)[0]
            place1 = np.where(city_label == i)[0]
            for j in place1:
                for k in place:
                    if random.uniform(0, 100) < flux_store[k, 0]:
                        work_place[j] = flux_store[k, 2]

        for i in range(len(work_store1)):
            if work_place[i] != 0:
                n = int(work_place[i])
                work_store1[i, :] = centers[n, 0], centers[n, 1]

        global work_store, home_store
        work_store = np.int64(work_store1)
        home_store = np.int64(home_store1)

        self.datacollector = DataCollector(
            model_reporters={"Tot informed": compute_informed},
            agent_reporters={"Infected": "infected"})
Пример #14
0
    def __init__(self, no_people, total_area, no_agents, Nc_N, n, all_x, all_y,
                 centers, infection_rate, city_label, first_infected,
                 mobility_data):
        self.num_agents = no_agents
        grid_size = round(
            math.sqrt((self.num_agents / no_people) * total_area) * 100)
        self.grid = MultiGrid(grid_size, grid_size, False)
        self.schedule = RandomActivation(self)
        self.running = True

        flux_store = np.zeros((1, 3))
        home_store1 = np.zeros((self.num_agents, 2))

        for i in range(round(len(centers) / 2)):
            print(i, datetime.datetime.now() - begin_time)
            n_cities = random.sample(range(1, round(len(centers) / 2)), n)

            for j in range(len(n_cities)):
                mi = np.count_nonzero(city_label == i + 1)
                nj = np.count_nonzero(city_label == n_cities[j])
                radius = math.sqrt(
                    (centers[i, 0] - centers[n_cities[j], 0])**2 +
                    (centers[i, 1] - centers[n_cities[j], 1])**2)
                sij = 0

                for k in range(len(all_x)):
                    if (all_x[k] - centers[i, 0])**2 + (
                            all_y[k] - centers[i, 1])**2 < radius**2:
                        sij += 1

                sij = sij - mi - nj
                if sij < 0:
                    sij = 0

                try:
                    Tij = (mi * Nc_N * mi * nj) / ((mi + sij) *
                                                   (mi + nj + sij)) * 10
                except ZeroDivisionError:
                    Tij = 0

                if Tij > 75:
                    Tij = 75

                if Tij > 1 and (i != n_cities[j]):
                    flux_store = np.vstack(
                        (flux_store, (Tij, i + 1, n_cities[j])))

        work_place = np.zeros(self.num_agents)
        work_store1 = np.zeros((num, 2))
        flux_store = np.delete(flux_store, 0, 0)

        for i in np.unique(flux_store[:, 1]):
            place = np.where(flux_store[:, 1] == i)[0]
            place1 = np.where(city_label == i)[0]
            for j in place1:
                for k in place:
                    if random.uniform(0, 100) < flux_store[k, 0]:
                        work_place[j] = flux_store[k, 2]

        for i in range(len(work_store1)):
            if work_place[i] != 0:
                n = int(work_place[i])
                work_store1[i, :] = centers[n, 0], centers[n, 1]

        for i in range(self.num_agents):
            home_store1[i, :] = int(all_x[i]), int(all_y[i])

        work_store = np.int64(work_store1)
        home_store = np.int64(home_store1)

        for i in range(self.num_agents):
            if mobility_data:
                a = Agent(i, self, infection_rate, work_store, home_store)
                self.schedule.add(a)
                self.grid.place_agent(a, (int(all_x[i]), int(all_y[i])))
            else:
                a = Agent1(i, self, infection_rate, work_store, home_store)
                self.schedule.add(a)
                self.grid.place_agent(a, (int(all_x[i]), int(all_y[i])))

            if i == first_infected:
                a.infected = 1

        self.datacollector = DataCollector(
            model_reporters={"Tot infections": compute_informed},
            agent_reporters={
                "Infected": "infected",
                "R-Number": "rnumber"
            })
model using Mesa in Python.
'''


'''
Import libraries and packages
'''
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import SingleGrid
from mesa.datacollection import DataCollector
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

'''
Agent (human) class with attributes and a step function
defining what actions to perform during each step
'''
class Human(Agent):

    def __init__(self, unique_id, model, sex, attract, relationship_status, current_dating_partners, focal):
        '''
         Create a new agent.
         Args:
            sex: agent's sex (female or male)
            attract: agent's attractiveness (between 1 and 10)
            relationship_status: agent's marital status (single or union)
            current_dating_partners: list of id's of agent's current dating current_dating_partners
            focal: agent's probability to start a union
        '''