Example #1
0
    def __init__(
        self,
        name="",
        host=None,
        serializer=None,
        transport=None,
        attributes=None,
        backend=Backend.OSBRAIN,
        mesa_model=None,
    ):
        self.backend = self.validate_backend(backend)

        if self.backend == Backend.OSBRAIN:
            self._remove_methods(MesaAgent)
            osBrainAgent.__init__(
                self,
                name=name,
                host=host,
                serializer=serializer,
                transport=transport,
                attributes=attributes,
            )

        elif self.backend == Backend.MESA:
            MesaAgent.__init__(self, name, mesa_model)
            self._remove_methods(osBrainAgent)
            self.init_mesa(name)
            self.unique_id = name
            self.name = name
            self.mesa_model = mesa_model
Example #2
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"})
Example #3
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"
            })
    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"})
Example #5
0
 def __init__(self, pos, model, init_state=DEAD):
     '''
     Create a cell, in the given state, at the given x, y position.
     '''
     Agent.__init__(self, pos, model)
     self.x, self.y = pos
     self.state = init_state
     self._nextState = None
Example #6
0
    def __init__(self, unique_id, model, fsm_size, num_tokens):
        Agent.__init__(self, unique_id, model)
        self.state = 0
        self.unique_id = unique_id
        self.scores = []
        self.decision = NO_ACTION

        self.gen_automata(fsm_size, num_tokens)
Example #7
0
 def __init__(self, pos, model, initial_state):
     '''
     Create a cell, in the given state, at the given row, col position.
     '''
     Agent.__init__(self, pos, model)
     self._row = pos[1]
     self._col = pos[0]
     self._state = initial_state
     self._next_state = None
Example #8
0
 def __init__(self, pos, model, init_state):
     '''
     Create a cell, in the given state, at the given x, y position.
     '''
     Agent.__init__(self, pos, model)
     self._x = pos[0]
     self._y = pos[1]
     self._state = init_state
     self._nextState = None
Example #9
0
 def __init__(self, pos, model, initial_state):
     '''
     Create a cell, in the given state, at the given row, col position.
     '''
     Agent.__init__(self, pos, model)
     self._row = pos[1]
     self._col = pos[0]
     self._state = initial_state
     self._next_state = None
Example #10
0
 def __init__(self, intersection, model):
     unique_id = uuid4()
     Agent.__init__(self, unique_id, model)
     Intersection.__init__(
         self,
         intersection.name,
         intersection.geometry,
         intersection.input_links,
         intersection.output_links,
     )
 def __init__(self, unique_id, model, homeLoc, workLoc):
     Agent.__init__(self, unique_id, model)
     self.age = random.randint(18, 87)
     degredation_age = 37
     max_age = 100
     # self.ability = random.random()**4 * (((min(abs((max_age+degredation_age)-self.age)),max_age))/max_age)		#based on formula A_b on pg. 354
     self.ability = 1
     self.attitude = random.random()**3  # based on A_t on pg. 354
     self.home = homeLoc
     self.work = workLoc
Example #12
0
    def __init__(self, id, model, params):
        Agent.__init__(self, id, model)

        student_params= {
            'join_chat_prob': 0.15,
            'join_board_prob': 0.15,
            'post_prob': 0.3,
            'reduced_post_prob': 0.1,
            'chat_social_prob': 0.5,
            'post_social_prob': 0.1,
            'discount': 0.95
        }

        student_params.update(params)

        self.in_chat = False
        self.in_board = False
        self.engaged = False

        self.chats_read = 0
        self.chats_social_read = 0
        self.overload_chats_read = 0
        self.overload_chats_social_read = 0
        self.contrib_chat = 0
        self.contrib_social_chat = 0

        self.at_post = 0
        self.at_social_post = 0
        self.posts_read = 0
        self.posts_social_read = 0
        self.overload_posts_read = 0
        self.overload_posts_social_read = 0
        self.contrib_post = 0
        self.contrib_social_post = 0

        self.join_chat_prob = student_params['join_chat_prob']
        self.join_board_prob = student_params['join_board_prob']
        self.post_prob = student_params['post_prob']
        self.reduced_post_prob = student_params['reduced_post_prob']

        self.chat_social_prob = student_params['chat_social_prob']
        self.post_social_prob = student_params['post_social_prob']
        self.discount = student_params['discount']

        self.post_overload_lim = 50
        self.chat_overload_lim = 50
        self.post_overloaded = False
        self.chat_overloaded = False
Example #13
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'
        })
Example #14
0
 def __init__(self, unique_id, model, belief, age=18):
     Agent.__init__(self, unique_id, model)
     self.unique_id = unique_id
     self.belief = belief
     self.age = age
     self.pro_friend = 0
     self.anti_friend = 0
     self.none = 0
     self.num_rounds = 0
     if self.age <= 19:
         self.prob_ref = 0
     elif self.age <= 24:
         self.prob_ref = 1
     elif self.age <= 29:
         self.prob_ref = 2
     else:
         self.prob_ref = 3
Example #15
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"})
Example #16
0
 def __init__(self, id, model=None):
   Agent.__init__( self, id, model)
   #_configure_logging()
   self.l = logging.getLogger(self.__class__.__name__)        
   self._xd = XMLObject('Agent')
   self._meta = self._xd.add("metadata")
   self._meta.el.set("id", str(id))
   self._events = self._xd.add("events")
   self._envdata = self._xd.add("environments")
   self._body = self._xd.add("body")
   self._behaviours = []
   self._sensors = [Sensor()]
   self._next_reward = 0.0
   self._last_reward = 0.0
   self.avStates = []
   self.avActions = []
   self.exists = False
   self._brain = BaseBrain(self)
   self.pos = (0,0)
    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"})
Example #19
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
Example #20
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"
            })
Example #21
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)
    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)
Example #23
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)
Example #24
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"})
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
        '''
Example #26
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"
            })
Example #27
0
 def __init__(self, pos, model, age=0):
     Agent.__init__(self, pos, model)
     AgingEntity.__init__(self, age)
 def __init__(self, unique_id, model):
     Agent.__init__(self, unique_id, model)
     self.wealth = 1
Example #29
0
 def __init__(self, pos, model, energy):
     Agent.__init__(self, pos, model)
     EnergyConsumingEntity.__init__(self, energy)
Example #30
0
 def __init__(self, unique_id, model, intitial_state):
     Agent.__init__(self, unique_id, model)
     self.belief = intitial_state