Esempio n. 1
0
    def __init__(self, height, width):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            pos = (x, y)
            init_state = CGoLCell.DEAD
            # Initially, make 10% of the cells ALIVE.
            if random.random() < 0.1:
                init_state = CGoLCell.ALIVE
            cell = CGoLCell(pos, self, init_state)
            # Put this cell in the grid at position (x, y)
            self.grid.place_agent(cell, pos)
            # Add this cell to the scheduler.
            self.schedule.add(cell)
        self.running = True
Esempio n. 2
0
    def __init__(self, height=50, width=50):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a hexagonal grid, where edges wrap around.
        self.grid = HexGrid(height, width, torus=True)

        # Place a dead cell at each location.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        # activate the center(ish) cell.
        centerishCell = self.grid[width // 2][height // 2]

        centerishCell.state = 1
        for a in centerishCell.neighbors:
            a.isConsidered = True

        self.running = True
Esempio n. 3
0
    def __init__(self):
        self.num_agents_sita = 20
        self.num_agents_ue = 20
        self.num_kabe = 1
        self.schedule = SimultaneousActivation(self)
        self.width = 10
        self.height = 50
        self.space = ContinuousSpace(self.width, self.height, True)
        self.syudan_hito_sita = np.zeros((self.num_agents_sita, 2))
        self.syudan_hito_ue = np.zeros((self.num_agents_ue, 2))
        self.syudan_kabe = np.zeros((self.num_kabe, 2))
        self.time = 1000
        # Create agents
        for i in range(self.num_agents_sita):
            a = Hokousya_sita(i, self)
            self.schedule.add(a)
            self.syudan_hito_sita[i,0] = a.iti_x
            self.syudan_hito_sita[i,1] = a.iti_y

        for i in range(self.num_agents_ue):
            b = Hokousya_ue(i, self)
            self.schedule.add(b)
            self.syudan_hito_ue[i,0] = b.iti_x
            self.syudan_hito_ue[i,1] = b.iti_y
        #壁を作る
        for i in range(self.num_kabe):
            c = Kabe(i, self)
            self.schedule.add(c)
            self.syudan_kabe[i, 0] = c.iti[0]
            self.syudan_kabe[i, 1] = c.iti[1]
Esempio n. 4
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"
            })
Esempio n. 5
0
    def __init__(self, N, height, width):
        super().__init__()
        self.N = N
        self.height = height
        self.width = width

        #Multigrid (The visual grid)
        self.grid = MultiGrid(width, height, torus=False) #torus wraps edges

        #Schedule (the logical grid)
        self.schedule = SimultaneousActivation(self)

        #Datacollector to collect our data (pouring time, dispatch time, etc)
        self.datacollector = DataCollector(model_reporters={"pouring_time": lambda m: pouring_time(self),
                                                            "busy": lambda m: busy_employees(self)})

        #Initiate minute, hour and day
        self.time_step = 1
        self.minute_count = 1
        self.hour_count = 1
        self.day_count = 1

        #The location of the beer stalls
        self.stall_positions = [(10,6),(40,6),(15,44),(40,44)]

        self.employees = []
        self.desk_pos = []
        self.busy = []

        self.sceneCoords = [(0,i) for i in range(math.floor(height/2)-7,math.floor(height/2)+6)]
        setUpGuests(self,N)
        setUpScene(self)
        setUpStalls(self)
        setUpEmployees(self)
        setUpFence(self)
Esempio n. 6
0
    def __init__(self, size, net_type):
        self.num_agents = size
        self.num_nodes = self.num_agents
        self.type = net_type
        if self.type == 1:
            self.G, self.avg_degree, self.big_nodes, self.connectivity, self.clustering = netgen_ba(
                100, 4)
        if self.type == 2:
            self.G, self.avg_degree, self.big_nodes, self.connectivity, self.clustering = netgen_er(
                100, .078)
        if self.type == 3:
            self.G, self.avg_degree, self.big_nodes, self.connectivity, self.clustering = netgen_rr(
                100, 4)
        self.grid = NetworkGrid(self.G)
        self.schedule = SimultaneousActivation(self)
        self.running = True
        self.step_counter = 1
        for i, node in enumerate(self.G.nodes()):
            a = NormAgent(i, self)
            self.schedule.add(a)
            self.grid.place_agent(a, node)

        self.datacollector = DataCollector(
            model_reporters={
                "PerHate": percent_haters,
                "AverageSens": average_sensitivity,
            },
            agent_reporters={"Hate": "behavior"})
 def __init__(   self, num_counties, preferences, network_type, \
                 climate_threshold, limited_radius=True, init_time=0):
     super().__init__()
     global TICK
     TICK = init_time
     self.num_agents = 0
     self.agent_index = 0
     self.preferences = preferences
     self.limited_radius = limited_radius
     self.upper_network_size = 3
     self.network_type = network_type
     self.climate_threshold = climate_threshold
     self.schedule = SimultaneousActivation(self)
     self.G = create_graph()
     self.num_counties = num_counties
     self.nodes = self.G.nodes()
     self.grid = NetworkGrid(self.G)
     self.county_climate_ranking = []
     self.county_population_list = [0] * self.num_counties
     self.county_flux = [0] * self.num_counties
     self.deaths = []
     self.births = []
     self.county_income = {}
     self.datacollector = DataCollector(model_reporters={"County Population": lambda m1: list(m1.county_population_list),
                                                         "County Influx": lambda m2: list(m2.county_flux),
                                                         "Deaths": lambda m3: m3.deaths,
                                                         "Births": lambda m4: m4.births,
                                                         "Total Population": lambda m5: m5.num_agents})
Esempio n. 8
0
    def __init__(self,
                 start_date: datetime,
                 sim_time_step=timedelta(minutes=15)):
        super().__init__()
        self.schedule = SimultaneousActivation(self)
        self.current_date = start_date
        self.sim_time_step = sim_time_step

        self.datacollector = DataCollector(
            model_reporters={
                "Date": self.report_current_date,
                "S": self.report_s,
                "E": self.report_e,
                "I": self.report_i,
                "R": self.report_r
            })
        self.seir_counts = [0, 0, 0, 0]
        self.persons = []
        self.locations = []

        logging.basicConfig(filename='debug.log', level=logging.DEBUG)
        logging.info("-- Started Epidexus Simulation --")
        logging.info("Current date: " + str(self.current_date))
        logging.info("Simulation time step: " + str(self.sim_time_step))
        logging.info("---------------------------------")
Esempio n. 9
0
    def __init__(self, population_size, initial_outbreak_size, spread_chance):
        print("Beginning model setup...\n")
        self.population_size = population_size
        print("Creating graph...")
        self.graph = nx.powerlaw_cluster_graph(population_size, 100, 0.5)
        #self.graph = nx.complete_graph(population_size)
        print(len(self.graph.edges))
        print("Initializing grid...")
        self.grid = NetworkGrid(self.graph)
        self.schedule = SimultaneousActivation(self)
        self.initial_outbreak_size = initial_outbreak_size
        self.spread_chance = spread_chance

        print("Initializing data collector...")
        self.datacollector = DataCollector({
            "Infected:": count_infected,
            "Susceptible:": count_susceptible,
            "Removed:": count_removed
        })

        for i, node in enumerate(self.graph.nodes()):
            a = Person(i, self, State.SUSCEPTIBLE, spread_chance)
            self.schedule.add(a)
            self.grid.place_agent(a, i)
            if i % 100 == 0:
                print("Finished with agent ", i)

        infected_nodes = self.random.sample(self.graph.nodes(),
                                            self.initial_outbreak_size)
        for a in self.grid.get_cell_list_contents(infected_nodes):
            a.status = State.INFECTED

        self.datacollector.collect(self)
        print("Model initialized...\n")
Esempio n. 10
0
    def __init__(self, N, width=10, height=10):
        self.num_agents = N
        self.width = width
        self.height = height
        self.grid = MultiGrid(height, width, False)  #non toroidal grid
        self.schedule = SimultaneousActivation(
            self)  #all active agents move together
        self.moveStimulus = random.randint(0, maxLifeTimeAlgae)

        self.threshold = [
            0 for _ in range(N)
        ]  #response threshold of N agents in the model, variable. This will not be used
        #only for initialization

        self.abCount = 0  #initial abnormality count
        self.detectedAb = 0

        # Create map of abnormalities
        self.anomalyMap = np.zeros(
            (height, width))  # a 2D array represent the grid
        self.fail = 0  #fail = 1 when there are algae exceed maximum allowed lifetime

        # Create agents
        for i in range(self.num_agents):
            #create and add agent with id number i to the scheduler
            a = MoniAgent(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))
    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
Esempio n. 12
0
class NormModel(Model):
    def __init__(self, size):
        self.num_agents = size
        self.num_nodes = self.num_agents
        # self.G = the_network[0]
        self.G = another_network
        self.grid = NetworkGrid(self.G)
        self.schedule = SimultaneousActivation(self)
        self.running = True

        for i, node in enumerate(self.G.nodes()):
            a = NormAgent(i, self)
            self.schedule.add(a)
            self.grid.place_agent(a, node)

        self.datacollector = DataCollector(
            model_reporters={
                "PerHate": percent_haters,
                "AverageSens": average_sensitivity,
            },
            agent_reporters={"Hate": "behavior"})

    def step(self):
        self.datacollector.collect(self)
        self.schedule.step()
        if percent_haters(
                self
        ) > 0.8:  # When the percentage of haters in the model exceeds 80,
            self.running = False  # the simulation is stopped, data collected, and next one is started.
Esempio n. 13
0
    def __init__(self, size, set_no):
        self.num_agents = size
        self.num_nodes = self.num_agents
        self.set = set_no
        self.I = networks_for_use[self.set][0]
        self.net_deg = networks_for_use[self.set][
            1]  # 1st parameter - average node degree
        self.big_nodes = networks_for_use[self.set][
            2]  # 2nd parameter - huge networks allowed?
        self.culling = networks_for_use[self.set][
            3]  # 3rd parameter - maximum node degree allowed. only use if
        # big_nodes = True!
        self.grid = NetworkGrid(self.I)
        self.schedule = SimultaneousActivation(self)
        self.running = True

        for i, node in enumerate(self.I.nodes()):
            a = NormAgent(i, self)
            self.schedule.add(a)
            self.grid.place_agent(a, node)

        self.datacollector = DataCollector(
            model_reporters={
                "PerHate": percent_haters,
                "AveKnowing": percent_hate_knowing,
                "AveHate": average_hate,
                "MeanDeg": net_avg_deg,
                "Culling": net_culling,
                "MaxDeg": max_deg,
            },
            agent_reporters={"Hate": "behavior"})
Esempio n. 14
0
    def __init__(self, config=default_config, disease=dis.covid_disease):
        self.agents_count = config.citizens_count + config.policemen_count
        self.disease = disease
        self.deceased = []
        self.buried = []
        self.deceased_counter = 0
        self.infected_counter = 0
        self.grid = MultiGrid(config.width, config.height, True)
        self.safety_per_cell = np.ones((config.height, config.width))
        self.buildings_map = np.zeros((config.height, config.width))
        self.buildings_id_map = np.zeros((config.height, config.width))
        self.schedule = SimultaneousActivation(self)
        self.datacollector = DataCollector(
            model_reporters={
                "deceased": "deceased_counter",
                "infected": "infected_counter"},
            agent_reporters={
                "hp": lambda a: a.profile["hp"],
                "mask_protection": "mask_protection",
                "infection_day": lambda a: a.profile["infection_day"],
                "obedience": lambda a: a.profile["obedience"],
                "fear": lambda a: a.profile["fear"]}
        )
        self.config = config
        self.buildings = {b["id"] : b for b in self.config.buildings}
        self.houses = [x for x in self.buildings.values() if x['type'] == 'house']
        self.workplaces = [x for x in self.buildings.values() if x['type'] == 'workplace']
        self.shops = [x for x in self.buildings.values() if x['type'] == 'shop']

        self.add_buildings_to_map(self.buildings)

        self.street_positions = []
        for x in range(self.config.width):
            for y in range(self.config.height):
                if self.buildings_map[y][x] == 0:
                    self.street_positions.append((x, y))

        self.house_to_agents = defaultdict(list)
        self.workplace_to_agents = defaultdict(list)

        self.current_location_type = None

        # Create agents
        for i in range(self.agents_count):
            if i < config.policemen_count:
                a = agent.create_distribution_policeman_agent(
                        i, self, config.policemen_mental_features_distribution)
                a.assign_house(self, self.houses)
            elif i < config.policemen_count + config.citizens_count:
                a = agent.create_distribution_citizen_agent(
                        i, self, config.citizens_mental_features_distribution)
                a.assign_house(self, self.houses)
                a.assign_workplace(self, self.workplaces)
            self.add_agent(a)

        for i in self.random.choices(self.schedule.agents, k=config.infected_count):
            i.start_infection()
        self.running = True
        self.steps_count = 0
        self.datacollector.collect(self)
Esempio n. 15
0
    def __init__(self, height, width):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            if random() < .1:
                cell.state = cell.ALIVE
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        self.running = True
Esempio n. 16
0
    def __init__(self, N, width, height, delta_t, R_plus, v, Lambda, alpha,
                 eta, gamma, beta, theta, delta):
        self.num_agents = N
        self.width = width
        self.height = height
        self.grid = MultiGrid(width, height, True)
        self.schedule = SimultaneousActivation(self)
        self.delta_t = 1
        self.R_plus = 200.0
        self.resources = [self.R_plus] * width
        self.v = .04
        self.Lambda = .00001
        self.a = alpha
        self.b = eta
        self.r_fm = gamma
        self.c = beta
        self.d = theta
        self.r_mf = delta
        self.delta_x = v * delta_t

        # print("Resources" + str(self.resources))
        # Create agents
        for i in range(self.num_agents):
            a = LocustAgent(i, self)
            self.schedule.add(a)
            #print ("Hi, Iss am agent " + str(a.unique_id) +" at grid : (" + str(0) + "," + str(a.unique_id) +')')
            # Add the agent to a random grid cell
            self.grid.place_agent(a, (0, (a.unique_id % self.height)))

        self.datacollector = DataCollector(
            model_reporters={"Resources": compute_gini})
Esempio n. 17
0
    def __init__(self, height=50, width=50, server = True, num_steps = 1000):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)
        self.num_steps = num_steps
        # Use a hexagonal grid, where edges wrap around.
        self.grid = HexGrid(height, width, torus=True)
        self.server = server
        # Place a dead cell at each location.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        # activate the center(ish) cell.
        centerishCell = self.grid[width // 2][height // 2]

        centerishCell.state = 1
        for a in centerishCell.neighbors:
            a.isConsidered = True

        self.running = True
        
        #Datacollector -- default for this model is no data collection, but one can use OABM to assign one. 
        #so this is an empty DataCollector instance from MESA

        self.datacollector = DataCollector()
Esempio n. 18
0
    def __init__(self, height=50, width=50):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # Computing their next state simultaneously.
        # This needs to be done because each cell's next state depends on
        # the current state of all its neighbors -- before they've changed
        self.schedule = SimultaneousActivation(self)

        # Use a single grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            if self.random.random() < 0.1:
                cell.state = cell.ALIVE
            # place_agent: Position an agent on the Grid, and set its pos variable
            self.grid.place_agent(cell, (x, y))
            # add(): Add an agent object to the schedule
            self.schedule.add(cell)

        self.running = True
Esempio n. 19
0
    def __init__(self, num_agents, width, height, b_rate, omega, theta, mu,
                 gamma, space, kappa, chi, epsilon):
        self.num_agents = num_agents
        self.grid = MultiGrid(width, height, True)
        self.width = width
        self.height = height
        self.houses = self.width * self.height
        self.schedule = SimultaneousActivation(self)
        self.house_schedule = SimultaneousActivation(self)
        self.b_rate = b_rate
        self.omega = omega
        self.theta = theta
        self.mu = mu
        self.kill_agents = []
        self.gamma = gamma
        self.gen_agent = 1 - math.exp(-self.gamma)
        self.total_agents = self.num_agents
        self.space = space
        self.kappa = kappa
        self.chi = chi
        self.epsilon = epsilon

        a_0 = 0.1
        # place houses on grid, 1 house per grid location
        for i in range(self.width):
            for j in range(self.height):
                num = str(i) + str(j)
                num = int(num)
                a = House(num, self, a_0, i, j, self.omega, self.theta,
                          self.mu, self.space)
                self.grid.place_agent(a, (a.x_point, a.y_point))
                self.house_schedule.add(a)

        # place the criminals
        for k in range(self.num_agents):
            unique_id = "criminal" + str(k)
            criminal = Criminal(unique_id, self, self.width, self.height)
            self.grid.place_agent(criminal,
                                  (criminal.x_point, criminal.y_point))
            self.schedule.add(criminal)

        for cops in range(self.kappa):
            unique_id = "cop" + str(cops)
            cop = Cop(unique_id, self, self.width, self.height)
            self.grid.place_agent(cop, (cop.x_point, cop.y_point))
            self.schedule.add(cop)

        # set up data collection
        self.datacollector = DataCollector(
            model_reporters={
                "Mean_Attractiveness": get_mean_att,
                "Max_Attractiveness": get_max_att,
                "Min_Attractiveness": get_min_att,
                "CrimeEvents": get_num_burgles,
                "Criminals": get_num_criminals,
                "MaxPos": get_max_att_pos
            },
            agent_reporters={
                "Att": lambda x: x.att_t if x.unique_id[:1] != "c" else None
            })
Esempio n. 20
0
    def __init__(self, graph, model_parameters):

        # Model initialization
        self.population_size = model_parameters['population_size']
        self.initial_outbreak_size = model_parameters['initial_outbreak_size']
        self.graph = graph
        self.grid = NetworkGrid(self.graph)
        self.schedule = SimultaneousActivation(self)

        self.datacollector = DataCollector({
            "Exposed": count_exposed,
            "Susceptible": count_susceptible,
            "Removed": count_removed,
            "Asymptomatic": count_asymptomatic,
            "Symptomatic": count_symptomatic
        })
        self.model_parameters = model_parameters

        for i, node in enumerate(self.graph.nodes()):
            a = Person(i, self, State.SUSCEPTIBLE, model_parameters)
            self.schedule.add(a)
            self.grid.place_agent(a, i)
            if i % 100 == 0:
                logger.info("Finished with agent " + str(i))

        infected_nodes = self.random.sample(self.graph.nodes(),
                                            self.initial_outbreak_size)
        for a in self.grid.get_cell_list_contents(infected_nodes):
            a.status = State.EXPOSED

        self.datacollector.collect(self)
        print("Model initialized...\n", str(self.model_parameters))
Esempio n. 21
0
    def __init__(self, N, width=10, height=10):
        self.num_agents = N
        self.width = width
        self.height = height
        self.grid = MultiGrid(height, width, False)  #non toroidal grid
        self.schedule = SimultaneousActivation(self)

        #        self.threshold = [random.randint(0,1) for i in range(N)]
        self.threshold = [
            random.randint(0, 5) for _ in range(N)
        ]  #response threshold of N agents in the model, variable
        #        self.threshold = [1 for _ in range(N)] #fix
        #        self.threshold = [1,2,3,4,5,6,7,8,9,10]

        self.abCount = 0  #initial abnormality count
        self.detectedAb = 0
        # Create agent

        self.anomalyMap = np.zeros((height, width))
        self.fail = 0

        for i in range(self.num_agents):

            x = floor(self.width / N * i + self.width / N / 2)
            #            create and add agent with id number i to the scheduler
            a = MoniAgent(i, self)
            self.schedule.add(a)

            #place agent at the center of its limit coor
            self.grid.place_agent(a, (x, 0))

#        this part is for visualization only
        self.running = True
Esempio n. 22
0
    def __init__(self, height=50, width=50, server=True):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)
        self.server = server
        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        #Datacollector -- default for this model is no data collection, but one can use OABM to assign one.
        #so this is an empty DataCollector instance from MESA

        self.datacollector = DataCollector()

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            if self.random.random() < 0.1:
                cell.state = cell.ALIVE
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        self.running = True
Esempio n. 23
0
    def __init__(self, N, width, height):

        #Monitoring space
        self.width = width
        self.height = height
        self.grid = MultiGrid(height, width, False)  #non toroidal grid

        self.schedule = SimultaneousActivation(self)

        self.abCount = 0  #initial abnormality count
        self.detectedAb = 0
        self.interactionCount = 0
        # =============================================================================
        #         self.coveredArea = []

        #         self.interactionRateAverage = 0
        #         self.coveragePercentage = 0
        #         self.coveragePercentageAverage = 0
        # =============================================================================
        # Create agents

        self.num_agents = N
        for i in range(self.num_agents):
            x = floor(self.width / N * i + self.width / N / 2)
            #           create and add agent with id number i to the scheduler
            a = MoniAgent(i, self)
            self.schedule.add(a)
            #place agent at the center of its limit coor
            self.grid.place_agent(a, (x, 0))
Esempio n. 24
0
    def __init__(self, num_nodes=10, avg_node_degree=3, rewire_prob=.1, initial_outbreak_size=1, threshold_fake = 2, threshold_real = -2):
        self.num_nodes = num_nodes
        self.G = nx.watts_strogatz_graph(n=self.num_nodes, k= avg_node_degree, p=rewire_prob)   #G generate graph structure
        self.grid = NetworkGrid(self.G) #grid is the Masa native defintion of space: a coorindate with specified topology on which agents sits and interact
        self.schedule = SimultaneousActivation(self)
        self.initial_outbreak_size = (
            initial_outbreak_size if initial_outbreak_size <= num_nodes else num_nodes
        )

        self.datacollector = DataCollector(
            {
                "Infected_fake": number_infected_fake,
                "Infected_real": number_infected_real,
            }
        )

        # Create agents
        for i, node in enumerate(self.G.nodes()):
            a = User(
                i,
                self,
                0,  #make the state a int
                threshold_fake,
                threshold_real
            )
            self.schedule.add(a)
            # Add the agent to the node
            self.grid.place_agent(a, node)

        # Infect some nodes, initial infection bug free
        infected_nodes_fake = self.random.sample(self.G.nodes(), self.initial_outbreak_size)
        infected_nodes_real = self.random.sample(self.G.nodes(), self.initial_outbreak_size) 

        for a in self.grid.get_cell_list_contents(infected_nodes_fake):
            a.state = 1
            neighbors_nodes = self.grid.get_neighbors(a.pos)
            for n in self.grid.get_cell_list_contents(neighbors_nodes):
                n.state = 1
                
        for a in self.grid.get_cell_list_contents(infected_nodes_real):
            a.state = -1
            neighbors_nodes = self.grid.get_neighbors(a.pos)
            for n in self.grid.get_cell_list_contents(neighbors_nodes):
                n.state = -1  
                
        """
        state measures fake score!! the more negative the less likely to spread fake news
        also this model assumes that 
        1
        one piece of real news can cancel out one piece of fake news
        This model can be modulated by changing the value of fake and real
        
        2
        the inital braeakout size of fake and real news are the same
        This can be chaged by introducing a different initial breaksize for real and fake news
        however this score is kepet the same intentionally because too uch complexity is not good for modeling
        """        

        self.running = True
        self.datacollector.collect(self)
Esempio n. 25
0
class MoniModel(Model):
    """
    A model for monitoring agents
    """
    def __init__(self, N, width, height):

        #Monitoring space
        self.width = width
        self.height = height
        self.grid = MultiGrid(height, width, False)  #non toroidal grid

        self.schedule = SimultaneousActivation(self)

        self.abCount = 0  #initial abnormality count
        self.detectedAb = 0
        self.interactionCount = 0
        # =============================================================================
        #         self.coveredArea = []

        #         self.interactionRateAverage = 0
        #         self.coveragePercentage = 0
        #         self.coveragePercentageAverage = 0
        # =============================================================================
        # Create agents

        self.num_agents = N
        for i in range(self.num_agents):
            x = floor(self.width / N * i + self.width / N / 2)
            #           create and add agent with id number i to the scheduler
            a = MoniAgent(i, self)
            self.schedule.add(a)
            #place agent at the center of its limit coor
            self.grid.place_agent(a, (x, 0))

#        this part is for visualization only
#        self.running = True

    def step(self):
        #        self.interactionCount = 0
        self.schedule.step()

    def run_model(self, n):
        for i in range(n):
            #           self.initPos()
            self.step()
#           print(self.schedule.steps)

    """
    Calculate fitness of a swarm (success ratio)
    """
    def fitness(self):
        for _ in range(100):
            self.step()
        if self.abCount == 0:
            self.abCount = 1  #avoid division by 0 error


#        return self.detectedAb/self.abCount
        return (sum(self.schedule.agents[0].genome))
Esempio n. 26
0
class EpidexusModel(Model):
    """The main simulation model.

    This is the entry point for MESA-based simulations.
    """
    def __init__(self, start_date: datetime, sim_time_step=timedelta(minutes=15)):
        self.schedule = SimultaneousActivation(self)
        self.current_date = start_date
        self.sim_time_step = sim_time_step

        self.datacollector = DataCollector(model_reporters={"S": self.report_s,
                                                            "E": self.report_e,
                                                            "I": self.report_i,
                                                            "R": self.report_r})
        self.seir_counts = [0, 0, 0, 0]

        logging.basicConfig(filename='debug.log',level=logging.DEBUG)
        logging.info("-- Started Epidexus Simulation --")
        logging.info("Current date: " + str(self.current_date))
        logging.info("Simulation time step: " + str(self.sim_time_step))
        logging.info("---------------------------------")

    def step(self):
        last_date = copy(self.current_date)
        self.current_date = self.current_date + self.sim_time_step

        # Report SEIR only once a day
        if self.current_date.date() > last_date.date():
            self.count_seir()
            self.datacollector.collect(self)

        self.schedule.step()

    def add_person(self, person: Agent):
        self.schedule.add(person)
        logging.debug("Added person: " + str(person))

    def count_seir(self):
        """Count the agents in each bin.

        Run this function before the report_x functions to update
        the counts. This is to avoid iterating over all agent for
        each of the four reporters.
        """
        self.seir_counts = [0, 0, 0, 0]
        for a in self.schedule.agents:
            self.seir_counts[a.infection_state.seir.value] += 1

    def report_s(self, model):
        return self.seir_counts[0]

    def report_e(self, model):
        return self.seir_counts[1]

    def report_i(self, model):
        return self.seir_counts[2]

    def report_r(self, model):
        return self.seir_counts[3]
Esempio n. 27
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
Esempio n. 28
0
class HexSnowflake(Model):
    '''
    Represents the hex grid of cells. The grid is represented by a 2-dimensional array of cells with adjacency rules specific to hexagons.
    '''

    def __init__(self, height=50, width=50, server = True, num_steps = 1000):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)
        self.num_steps = num_steps
        # Use a hexagonal grid, where edges wrap around.
        self.grid = HexGrid(height, width, torus=True)
        self.server = server
        # Place a dead cell at each location.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        # activate the center(ish) cell.
        centerishCell = self.grid[width // 2][height // 2]

        centerishCell.state = 1
        for a in centerishCell.neighbors:
            a.isConsidered = True

        self.running = True
        
        #Datacollector -- default for this model is no data collection, but one can use OABM to assign one. 
        #so this is an empty DataCollector instance from MESA

        self.datacollector = DataCollector()

    def step(self):
        '''
        Have the scheduler advance each cell by one step
        '''
        self.schedule.step()
    def run_model(self, n = None):

        if n:
            self.num_steps = n
        if self.server == False:
            for _ in range(self.num_steps):
                self.step()
            return self
        else:
            from .server import server

            server.launch()
Esempio n. 29
0
    def __init__(self, N, width, height):
        self.num_agents = N
        self.width = width
        self.height = height
        self.grid = MultiGrid(height, width, False) #non toroidal grid
        self.schedule = SimultaneousActivation(self)
        self.datacollector = DataCollector(
            model_reporters={"Coverage": compute_coverage},
            agent_reporters={"Wealth": "wealth"}
        )
        # Create agents
        self.coveredArea = []
        self.interactionCount = 0
        self.interactionRateAverage = 0
        self.coveragePercentage = 0
        self.coveragePercentageAverage = 0
        
#        distribute the agents evently
        areaNum = ceil(sqrt(self.num_agents))
        areaDistx = self.width/(sqrt(self.num_agents))
        areaDistx = floor(areaDistx)
        areaDisty = self.height/(sqrt(self.num_agents))
        areaDisty = floor(areaDisty)
        
        self.dtx = areaDistx
        self.dty = areaDisty
        
        for i in range(self.num_agents):
            
            xlow = (i%areaNum)*areaDistx
            xup = xlow + areaDistx-1
            
            ylow = floor(i/areaNum)*areaDisty
            yup = ylow + areaDisty-1
        
            x = floor((xlow+xup)/2)+1
            y = floor((ylow+yup)/2)+1
            
           
            
            
            xlow = x-1
            xup = x+1
            ylow = y-1
            yup = y+1
            
#            create and add agent with id number i to the scheduler
            a = MoniAgent(i, self, xup, xlow, yup, ylow)
            self.schedule.add(a)
            
            #place agent at the center of its limit coor
            self.grid.place_agent(a, (x, y))
            # Add the agent to a random grid cell
            
#        this part is for visualization only
        self.running = True
        self.datacollector.collect(self)
Esempio n. 30
0
    def __init__(self):
        super().__init__()
        self.schedule = SimultaneousActivation(self)
        self.grid = ContinuousSpace(75, 40, False)

        ## Creation des agents de base
        for _ in range(1):
            a = Walker(self.next_id(), self)
            self.schedule.add(a)
            self.grid.place_agent(a, (0, 0))
Esempio n. 31
0
    def __init__(self, g=None, outbreak_size=3, si_trans=0.025):
        self.schedule = SimultaneousActivation(self)
        
        if g is None:
            g = nx.random_graphs.watts_strogatz_graph(100, 4, 0.05) 

        self.si_trans = si_trans

        nodes = g.nodes()
        agent_nodes = list(map(lambda x: SI_Agent(x), nodes))
        n_map = dict(zip(nodes, agent_nodes))
        agent_edges = list(map(lambda e: (n_map[e[0]], n_map[e[1]])  , g.edges()))

        for agent in agent_nodes:
            self.schedule.add(agent)
        # set the initial outbreak
        for node in sample(list(agent_nodes), outbreak_size):
            node.state = State.infected

        self.network = NetworkSpace(agent_nodes, agent_edges)
        self.dc = DataCollector({"susceptible": lambda m: self.count_state(m, State.susceptible),
                                "infected": lambda m: self.count_state(m, State.infected)},
                                {"state": lambda a: a.state.value}
                                )
        self.dc.collect(self) #initial state

        self.running = True
Esempio n. 32
0
    def __init__(self, height=50, width=50):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a hexagonal grid, where edges wrap around.
        self.grid = HexGrid(height, width, torus=True)

        # Place a dead cell at each location.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        # activate the center(ish) cell.
        centerishCell = self.grid[width // 2][height // 2]

        centerishCell.state = 1
        for a in centerishCell.neighbors:
            a.isConsidered = True

        self.running = True
Esempio n. 33
0
    def __init__(self, height, width):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            pos = (x, y)
            init_state = CGoLCell.DEAD
            # Initially, make 10% of the cells ALIVE.
            if random.random() < 0.1:
                init_state = CGoLCell.ALIVE
            cell = CGoLCell(pos, self, init_state)
            # Put this cell in the grid at position (x, y)
            self.grid.place_agent(cell, pos)
            # Add this cell to the scheduler.
            self.schedule.add(cell)
        self.running = True
Esempio n. 34
0
    def __init__(self, height, width):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            if random() < .1:
                cell.state = cell.ALIVE
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)
        self.running = True
Esempio n. 35
0
class SIR_Network_Model(Model):
    def __init__(self, g=None, outbreak_size=3, si_trans=0.025, ir_trans=0.05):
        self.schedule = SimultaneousActivation(self)
        
        if g is None:
            g = nx.random_graphs.watts_strogatz_graph(100, 4, 0.05) 

        self.si_trans = si_trans
        self.ir_trans = ir_trans

        nodes = g.nodes()
        agent_nodes = list(map(lambda x: SIR_Agent(x), nodes))
        n_map = dict(zip(nodes, agent_nodes))
        agent_edges = list(map(lambda e: (n_map[e[0]], n_map[e[1]])  , g.edges()))

        for agent in agent_nodes:
            self.schedule.add(agent)
        # set the initial outbreak
        for node in sample(list(agent_nodes), outbreak_size):
            node.state = State.infected

        self.network = NetworkSpace(agent_nodes, agent_edges)
        self.dc = DataCollector({"susceptible": lambda m: self.count_state(m, State.susceptible),
                                "infected": lambda m: self.count_state(m, State.infected),
                                "resistant": lambda m: self.count_state(m, State.resistant)},
                                {"state": lambda a: a.state.value}
                                )
        self.dc.collect(self) #initial state

        self.running = True

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

        # disease dead?
        if self.count_state(self, State.infected) == 0:
            self.running = False

    @staticmethod
    def count_state(model,state):
        count = 0
        for agent in model.schedule.agents:
            if agent.state == state:
                count +=1
        return count
Esempio n. 36
0
class MockModel(Model):
    """ Test model for testing """

    def __init__(self, width, height, key1=103, key2=104):

        self.width = width
        self.height = height
        self.key1 = key1,
        self.key2 = key2
        self.schedule = SimultaneousActivation(self)
        self.grid = Grid(width, height, torus=True)

        for (c, x, y) in self.grid.coord_iter():
            a = MockAgent(x + y * 100, self, x * y * 3)
            self.grid.place_agent(a, (x, y))
            self.schedule.add(a)

    def step(self):
        self.schedule.step()
Esempio n. 37
0
class HexSnowflake(Model):
    '''
    Represents the hex grid of cells. The grid is represented by a 2-dimensional array of cells with adjacency rules specific to hexagons.
    '''

    def __init__(self, height=50, width=50):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a hexagonal grid, where edges wrap around.
        self.grid = HexGrid(height, width, torus=True)

        # Place a dead cell at each location.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        # activate the center(ish) cell.
        centerishCell = self.grid[width // 2][height // 2]

        centerishCell.state = 1
        for a in centerishCell.neighbors:
            a.isConsidered = True

        self.running = True

    def step(self):
        '''
        Have the scheduler advance each cell by one step
        '''
        self.schedule.step()
Esempio n. 38
0
class ConwaysGameOfLife(Model):
    '''
    Represents the 2-dimensional array of cells in Conway's
    Game of Life.
    '''

    def __init__(self, height=50, width=50):
        '''
        Create a new playing area of (height, width) cells.
        '''

        # Set up the grid and schedule.

        # Use SimultaneousActivation which simulates all the cells
        # computing their next state simultaneously.  This needs to
        # be done because each cell's next state depends on the current
        # state of all its neighbors -- before they've changed.
        self.schedule = SimultaneousActivation(self)

        # Use a simple grid, where edges wrap around.
        self.grid = Grid(height, width, torus=True)

        # Place a cell at each location, with some initialized to
        # ALIVE and some to DEAD.
        for (contents, x, y) in self.grid.coord_iter():
            cell = Cell((x, y), self)
            if self.random.random() < 0.1:
                cell.state = cell.ALIVE
            self.grid.place_agent(cell, (x, y))
            self.schedule.add(cell)

        self.running = True

    def step(self):
        '''
        Have the scheduler advance each cell by one step
        '''
        self.schedule.step()
Esempio n. 39
0
    def __init__(self, height, width):
        '''
        Create a 2D lattice with strict borders where agents live
        The agents next state is first determined before updating the grid
        '''

        self._grid = Grid(height, width, torus=False)
        self._schedule = SimultaneousActivation(self)

        # self._grid.coord_iter()
        #  --> should really not return content + col + row
        #  -->but only col & row
        # for (contents, col, row) in self._grid.coord_iter():
        # replaced content with _ to appease linter
        for (_, col, row) in self._grid.coord_iter():
            cell = ColorCell((col, row), self, ColorCell.OPINIONS[random.randrange(0, 16)])
            self._grid.place_agent(cell, (col, row))
            self._schedule.add(cell)

        self.running = True
Esempio n. 40
0
File: model.py Progetto: GeoESW/mesa
class ColorPatchModel(Model):
    '''
    represents a 2D lattice where agents live
    '''

    def __init__(self, width, height):
        '''
        Create a 2D lattice with strict borders where agents live
        The agents next state is first determined before updating the grid
        '''

        self._grid = Grid(width, height, torus=False)
        self._schedule = SimultaneousActivation(self)

        # self._grid.coord_iter()
        #  --> should really not return content + col + row
        #  -->but only col & row
        # for (contents, col, row) in self._grid.coord_iter():
        # replaced content with _ to appease linter
        for (_, row, col) in self._grid.coord_iter():
            cell = ColorCell((row, col), self,
                             ColorCell.OPINIONS[random.randrange(0, 16)])
            self._grid.place_agent(cell, (row, col))
            self._schedule.add(cell)

        self.running = True

    def step(self):
        '''
        Advance the model one step.
        '''
        self._schedule.step()

    # the following is a temporary fix for the framework classes accessing
    # model attributes directly
    # I don't think it should
    #   --> it imposes upon the model builder to use the attributes names that
    #       the framework expects.
    #
    # Traceback included in docstrings

    @property
    def grid(self):
        """
        /mesa/visualization/modules/CanvasGridVisualization.py
        is directly accessing Model.grid
             76     def render(self, model):
             77         grid_state = defaultdict(list)
        ---> 78         for y in range(model.grid.height):
             79             for x in range(model.grid.width):
             80                 cell_objects = model.grid.get_cell_list_contents([(x, y)])

        AttributeError: 'ColorPatchModel' object has no attribute 'grid'
        """
        return self._grid

    @property
    def schedule(self):
        """
        mesa_ABM/examples_ABM/color_patches/mesa/visualization/ModularVisualization.py",
        line 278, in run_model
            while self.model.schedule.steps < self.max_steps and self.model.running:
        AttributeError: 'NoneType' object has no attribute 'steps'
        """
        return self._schedule