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})
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)
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" })
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)
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})
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("---------------------------------")
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")
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, N) 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
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 __init__(self, shuffle=False, activation=STAGED): ''' Creates a Model instance with a schedule Args: shuffle (Bool): whether or not to instantiate a scheduler with shuffling. This option is only used for StagedActivation schedulers. activation (str): which kind of scheduler to use. 'random' creates a RandomActivation scheduler. 'staged' creates a StagedActivation scheduler. The default scheduler is a BaseScheduler. ''' self.log = [] # Make scheduler if activation == STAGED: model_stages = ["stage_one", "stage_two"] self.schedule = StagedActivation(self, model_stages, shuffle=shuffle) elif activation == RANDOM: self.schedule = RandomActivation(self) elif activation == SIMULTANEOUS: self.schedule = SimultaneousActivation(self) else: self.schedule = BaseScheduler(self) # Make agents for name in ["A", "B"]: agent = MockAgent(name, self) self.schedule.add(agent)
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
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, 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 __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"})
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]
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))
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
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
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))
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
def __init__(self, h=height, w=width): """ Create a action area of (height, width) cells. """ super().__init__() self.height = h self.width = w self.tourists_on_trail = 0 self.frequency = 5 self.steps_of_tourist_1 = 1 self.schedule_tourists = SimultaneousActivation(self) self.schedule_trail_elements = SimultaneousActivation(self) self.step_performed = 1 self.grid = MultiGrid(self.height, self.width, torus=False) self.trail = Trail(self) self.maximum_probability = 0 self.minimum_probability = 1
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
def __init__(self, N, width, height, b_rate, delta, omega, theta, mu, gamma, space): self.num_agents = N 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.delta = delta self.omega = omega self.theta = theta self.mu = mu self.kill_agents = [] self.gamma = gamma self.gen_agent = 1 - math.exp(-self.gamma*self.delta) self.total_agents = self.num_agents self.space = space a_0 = 0.2 # 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.delta, 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) # 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})
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)
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))
def __init__( self, gridsize, cop_density, citizen_density, agent_type, legitimacy, l_state, reduction_constant, active_threshold, include_wealth, rich_threshold, ): # Create a new World instance. # Args: # gridsize: the size of grid # cop_density: density of cops to be placed # citizen_density: density of citizens to be placed # agent_type: the alignment of agent either as cop or citizen # l_state: the legitimacy state # reduction_constant: the constant attribute which decide by what rate # the state of l_state will reduce self.cop_density = cop_density self.citizen_density = citizen_density self.agent_type = agent_type self.legitimacy = legitimacy self.l_state = l_state self.reduction_constant = reduction_constant self.active_threshold = active_threshold self.include_wealth = include_wealth self.rich_threshold = rich_threshold self.ap_constant = 2.3 # Agent count r_c: rich_count, r_a_c: rich_active_count, m_c: middle_count, m_a_c: middle_active_count, p_c: poor_count, p_a_c: poor_active_count,. self.r_c = 0 self.r_a_c = 0 self.m_c = 0 self.m_a_c = 0 self.p_c = 0 self.p_a_c = 0 self.mean = 0 self.kill_agents = [] self.agents_killed = 0 self.grid = MultiGrid(gridsize, gridsize, False) self.schedule = SimultaneousActivation(self) self.placement(gridsize) self.running = True
def __init__(self, N, width, height): self.num_agents = N self.grid = ContinuousSpace(width, height, False) self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): a = StudentAgent(i, self) self.schedule.add(a) x = random.randrange(self.grid.width) y = random.randrange(self.grid.height) self.grid.place_agent(a, (x, y))
def __init__(self, a, b, slices, log_each=1, thr=1.0e-9): """Initialise the DALE model. Parameters ---------- a : (n, n) array_like coefficients matrix. b : (n, 1) or (n,) array_like right hand side vector. slices : list of lists of ints definition of subproblem distribution onto agents. log_each : int, optional if greater then one, data will be collected not at each step. Helps to keep the dataframe sizes low if simulation time is long. thr : float convergence threshold. """ if a.shape[0] != b.shape[0]: raise ValueError("Matrix dimensions must agree") self.log_each = log_each self.num_steps = 0 self.problem_size = b.shape[0] self.a = a self.b = b.squeeze() # Get a set of indices specified in slices idx_in_slices = set(itertools.chain.from_iterable(slices)) if len(idx_in_slices) != self.problem_size: msg = "Not all indices are contained in slices: " raise ValueError(msg + str(idx_in_slices)) self.num_agents = len(slices) self.network = None self.schedule = SimultaneousActivation(self) for i in range(self.num_agents): agent = DaleAgent(str(i + 1), self, slices[i]) self.schedule.add(agent) self.running = True self.thr = thr # TODO: Bandwidth monitor self.datacollector = DataCollector( model_reporters={"step": lambda m: m.num_steps}, agent_reporters={"solution": lambda a: a.sol.copy()}, )
def __init__(self, width=20, height=20, proportion_normal=0.3): self.running = True self.schedule = SimultaneousActivation(self) self.grid = SingleGrid(width, height, torus=False) self.grid.scheduler = self.schedule cancer_x = random.randint(width // 4, width - 1) while True: cancer_y = cancer_x + random.randint(-5, 5) if cancer_y >= 0 and cancer_y < height and cancer_y != cancer_x: break cancer_coords = (cancer_x, cancer_y) ## Rolled into the placement of other cells # self.schedule.add(initial_activator) # self.grid.place_agent(initial_activator, center_coords) # roll a die and place Producer, Consumer or undifferentiated cell for x in range(width): for y in range(height): roll = r.random() coords = (x, y) if roll < 0.05: roll = r.random() agent = Cancer(coords, self) if roll < .33: agent = Cancer(coords, self) Cell_Dict['cancer1'] = Cell_Dict.get('cancer1') + 1 elif roll < .66: agent = Cancer1(coords, self) Cell_Dict['cancer2'] = Cell_Dict.get('cancer2') + 1 else: agent = Cancer2(coords, self) Cell_Dict['cancer3'] = Cell_Dict.get('cancer3') + 1 elif coords[0] == width - 1 or coords[0] == 0: Cell_Dict['capillary'] = Cell_Dict.get('capillary') + 1 agent = Capillary(coords, self) # elif coords == cancer_coords: # agent = Cancer(coords, self) # Cell_Dict['cancer1'] = Cell_Dict.get('cancer1') + 1 elif roll <= proportion_normal: agent = Normal(coords, self) Cell_Dict['n'] = Cell_Dict.get('n') + 1 else: agent = Empty(coords, self) self.schedule.add(agent) self.grid.place_agent(agent, coords)