def __init__(self, pop, width, height): '''Initialize the model''' self.N = pop # number of slime agents to spawn self.grid = MultiGrid(width, height, True) # torus = True self.schedule = RandomActivation(self) self.running = True # True so that the model runs # Spawn agents # Add chem agent to every grid cell for coord in self.grid.coord_iter(): coord_content, x, y = coord # pull contents, x/y pos from coord obj id = str(x) + '_' + str(y) # unique_id is x_y position a = ChemAgent(id, self) # instantiate a chem agent self.schedule.add(a) # add to the schedule self.grid.place_agent(a, (x, y)) # spawn the chem agent # Add slime agent randomly, population specified by N for i in range(self.N): slm = SlimeAgent(i, self) self.schedule.add(slm) x = self.random.randrange(self.grid.width) y = self.random.randrange(self.grid.height) self.grid.place_agent(slm, (x, y)) # Initialize datacollector self.datacollector = DataCollector(model_reporters={ "Total_Chem": compute_total_chemical, "Average_Distance": compute_distance_matrix }, agent_reporters={"Chem": "chem"})
def __init__(self, height, width, schedule_type, payoffs=None): ''' Create a new Spatial Prisoners' Dilemma Model. Args: height, width: Grid size. There will be one agent per grid cell. schedule_type: Can be "Sequential", "Random", or "Simultaneous". Determines the agent activation regime. payoffs: (optional) Dictionary of (move, neighbor_move) payoffs. ''' self.grid = SingleGrid(height, width, torus=True) self.schedule_type = schedule_type self.schedule = self.schedule_types[self.schedule_type](self) # Create agents for x in range(width): for y in range(height): agent = PDAgent((x, y), self) self.grid.place_agent(agent, (x, y)) self.schedule.add(agent) self.datacollector = DataCollector({ "Cooperating_Agents": lambda m: len([a for a in m.schedule.agents if a.move == "C"]) }) self.running = True self.datacollector.collect(self)
def __init__(self, formation, population, width, height, vision, min_dist, flock_vel, accel_time, equi_dist, repulse_max, repulse_spring, align_frict, align_slope, align_min, wall_decay, wall_frict, form_shape, form_track, form_decay, wp_tolerance): ''' Create a new Flockers model. Args: population: Number of agents. width, height: Size of the space. vision: How far around should each agents look for its neighbors. min_dist: Minimum allowed distance between agents before a collision occurs. This is only used for statistics. ''' # set parameters self.population = population self.space = ContinuousSpace(width, height, torus=False) self.vision = vision self.min_dist = min_dist self.params = dict(formation=formation, population=population, flock_vel=flock_vel, accel_time=accel_time, equi_dist=equi_dist, repulse_max=repulse_max, repulse_spring=repulse_spring, align_frict=align_frict, align_slope=align_slope, align_min=align_min, wall_decay=wall_decay, wall_frict=wall_frict, form_shape=form_shape, form_track=form_track, form_decay=form_decay, wp_tolerance=wp_tolerance) # data collection for plots self.datacollector = DataCollector( model_reporters={ "Minimum Distance": minimum_distance, "Maximum Distance": maximum_distance, "Average Distance": average_distance, "Collisions": collisions, "Messags Distributed": messages_distributed, "Messags Centralized": messages_centralized }) # execute agents sequentially in a random order self.schedule = RandomActivation(self) # place agents self.make_agents() # pairwise distances self.agent_distances() # run model self.running = True # collect initial data sample self.datacollector.collect(self)
def __init__(self, height, width, density): ''' Create a new forest fire model. Args: height, width: The size of the grid to model density: What fraction of grid cells have a tree in them. ''' # Initialize model parameters self.height = height self.width = width self.density = density # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.dc = DataCollector({"Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out")}) # Place a tree in each cell with Prob = density for x in range(self.width): for y in range(self.height): if self.random.random() < self.density: # Create a tree new_tree = TreeCell(self, (x, y)) # Set all trees in the first column on fire. if x == 0: new_tree.condition = "On Fire" self.grid[y][x] = new_tree self.schedule.add(new_tree) self.running = True
def __init__(self, N_buenos_empleo=10, N_educados=20, colegiatura=0.25, seed=None): #Parámetro por default self.current_id = 0 self.running = True self.width = 7 self.height = 7 self.N_buenos_empleo = N_buenos_empleo #Parámetro que indica el número inicial de buenos empleos self.N_educados = N_educados #Parámetro que indica el número inicial de educados self.colegiatura = colegiatura #Parámetro que indica la colegiatura #Definimos el schedule para hacer la ejecucion en orden aleatorio self.schedule = RandomActivation(self) #Definimos el grid de tamanio 7x7 y sin torus self.grid = MultiGrid(self.width, self.height, False) #Declaración del grid for y in range(0, self.height): for x in range(0, self.width): a = Agente(self.next_id(), self, N_buenos_empleo, N_educados, colegiatura) self.schedule.add(a) self.grid.place_agent(a, [x, y]) #Especificacion del datacollector self.datacollector = DataCollector( model_reporters={ "Empleo calificado": contarAgentesCal, "NumberTicks": getCurrentTick, "Educados sin empleo calificado": contarAgentesEdu, "No educados": contarAgentesNoEdu })
def __init__(self, num_nodes=1000, avg_node_degree=3, initial_outbreak_size=10, race="black"): self.num_nodes = num_nodes self.race = race self.months = 0 prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) self.sentence = generate_sentence(race) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.initial_outbreak_size = initial_outbreak_size if initial_outbreak_size <= num_nodes else num_nodes self.datacollector = DataCollector({ "Incarcerated": number_incarcerated, "Susceptible": number_susceptible, "Released": number_released }) for i, node in enumerate(self.G.nodes()): a = Person(i, self, State.SUSCEPTIBLE, self.sentence) self.schedule.add(a) self.grid.place_agent(a, node) # Begin with some portion of the population in prison infected_nodes = self.random.sample(self.G.nodes(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INCARCERATED self.running = True self.datacollector.collect(self)
def __init__(self,N,width,height,num_of_food=64): self.num_agents = N self.num_food = num_of_food self.grid = MultiGrid(width,height,True) self.schedule= RandomActivation(self) self.running = True for i in range(self.num_agents): a = HungryAgent(i,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)) for i in range(self.num_food): kombinacija = sve_kombinacije[i] id_offset = i+1000 f = FoodAgent(id_offset,self, kombinacija[0],kombinacija[1],kombinacija[2]) self.schedule.add(f) x = self.random.randrange(self.grid.width) y = self.random.randrange(self.grid.height) self.grid.place_agent(f,(x,y)) self.datacollector = DataCollector( model_reporters = {"TotalKnowledge":compute_knowledge,"TotalEnergy":total_energy,"TotalExperience":measure_experience,"TotalFood":total_pojedena_hrana,"TotalPoison":total_pojedeni_otrovi})
def __init__(self, G, verbosity=0, testing=True, exposure_duration=4, time_until_symptoms=6,infection_duration=11, quarantine_duration=14, subclinical_modifier=1, infection_risk_contact_type_weights={ 'very_far': 0.1, 'far': 0.5, 'intermediate': 1, 'close': 3}, K1_contact_types=['close'], diagnostic_test_type='one_day_PCR', preventive_screening_test_type='one_day_PCR', follow_up_testing_interval=None, liberating_testing=False, index_case='employee', agent_types={'type1': {'screening_interval': None, 'index_probability': None, 'transmission_risk': 0.015, 'reception_risk': 0.015, 'symptom_probability': 0.6}}, seed=None): super().__init__(G, verbosity, testing, exposure_duration, time_until_symptoms, infection_duration, quarantine_duration, subclinical_modifier, infection_risk_contact_type_weights, K1_contact_types, diagnostic_test_type, preventive_screening_test_type, follow_up_testing_interval, liberating_testing, index_case, agent_types, seed) # data collectors to save population counts and agent states every # time step model_reporters = {} for agent_type in self.agent_types: for state in ['E','I','I_asymptomatic','I_symptomatic','R','X']: model_reporters.update({'{}_{}'.format(state, agent_type):\ data_collection_functions[agent_type][state]}) model_reporters.update(\ { 'screen_students_reactive':check_reactive_student_screen, 'screen_students_follow_up':check_follow_up_student_screen, 'screen_students_preventive':check_preventive_student_screen, 'screen_teachers_reactive':check_reactive_teacher_screen, 'screen_teachers_follow_up':check_follow_up_teacher_screen, 'screen_teachers_preventive':check_preventive_teacher_screen, 'screen_family_members_reactive':check_reactive_family_member_screen, 'screen_family_members_follow_up':check_follow_up_family_member_screen, 'screen_family_members_preventive':check_preventive_family_member_screen, 'N_diagnostic_tests':get_N_diagnostic_tests, 'N_preventive_screening_tests':get_N_preventive_screening_tests, 'undetected_infections':get_undetected_infections, 'predetected_infections':get_predetected_infections, 'pending_test_infections':get_pending_test_infections }) agent_reporters =\ { 'infection_state':get_infection_state, 'quarantine_state':get_quarantine_state } self.datacollector = DataCollector( model_reporters = model_reporters, agent_reporters = agent_reporters)
def __init__(self): ################################### # SET INITIAL NUMBERS ################################### self.num_agents = 10000 self.wealth_per = np.loadtxt("data_abm/init_wealth_percentile.txt") self.num_decs = int(self.num_agents/100) self.decile = self.create_deciles(self.wealth_per) ################################### # Create Income and Top Down World ###################################### self.schedule = RandomActivation(self) self.rank_list = [] self.world = world.World(self) self.time = 1966 ##################################### # Create agent and add to schedule ######################################## for i in range(self.num_agents): #get correct decile for agent population pos = i//100 #print (len(self.decile[pos])) wealth=self.decile[pos][i%self.num_decs] a = da.DecileAgent(i, self, wealth,i) self.schedule.add(a) self.rank_list.append(a) self.datacollector = DataCollector(agent_reporters = {"Wealth" : "wealth", "Rank":"rank"})
def __init__(self, N): self.schedule = RandomActivation( self ) # This implies that agents are selected in a random order each period # Define the grid and set some global values self.grid = MultiGrid(20, 20, False) self.current_id = 1 self.running = True # Add energy (food) to grid for x in range(20): for y in range(20): f = Food(self.next_id(), self) self.grid.place_agent(f, (x, y)) #Create all the agents self.num_agents = N for i in range(N): a = FoodAgent(self.next_id(), self) self.schedule.add( a ) # We have to add all agents to the scheduler (to have access) self.grid.place_agent( a, (10, 10)) # We start by putting them all in the centre # Define which data is collected during the simulation self.datacollector = DataCollector(model_reporters={ "Collected energy": sumEnergy, "Active agents": activeAgents })
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 })
def __init__(self, number_of_agents, width, height, happiness_threshold, minority_rate): self.num_agents = number_of_agents self.grid = MultiGrid(width, height, False) self.schedule = RandomActivation(self) ## Create Agents number_of_minority = round(number_of_agents * (minority_rate)) for i in range(number_of_agents): if (i + 1) <= number_of_minority: ethnicity = 1 else: ethnicity = 2 a = SegregationAgent(i, ethnicity, happiness_threshold, self) self.schedule.add(a) # place agent on grid # x = self.random.randrange(self.grid.width) # y = self.random.randrange(self.grid.height) empty_place = self.grid.find_empty() self.grid.place_agent(a, empty_place) logger.info("Agent " + str(i) + " placed in " + str(empty_place)) self.datacollector = DataCollector( agent_reporters={"Happiness": "happy"}, model_reporters={"Overall_happiness": overall_happiness}, )
def __init__(self, N=100): self.num_agents = N self.schedule = RandomActivation(self) self.datacollector = DataCollector(model_reporters={ "bid_price": get_highest_bid, "ask_price": get_lowest_ask, "volume": compute_volume }, agent_reporters={ "Certainty": "prob", "Bids": "bid", "Asks": "ask" }) self.bidders = OrderedDict() self.askers = OrderedDict() self.volume = 0 # Create agents print('creating {} agents..'.format(self.num_agents)) for i in range(self.num_agents): # Create probability distribution #prob = np.random.normal(mu, sigma) #prob = np.random.uniform(0.01, 0.99) if random.randint(0, 1): prob = np.random.normal(0.83, 0.05) else: prob = np.random.normal(0.53, 0.05) a = PredictionAgent(prob, i, self) self.schedule.add(a) print('running model...') self.running = True
def __init__(self, height, width, density, esquinas): super().__init__() # Parámetros para inicializar modelo self.height = height self.width = width self.density = density self.esquinas = esquinas self.initialTrees = 0 self.burnedTrees = 0 self.percen = 0 # Creación del planificador y del grid self.schedule = RandomActivation(self) self.grid = Grid(width, height, torus=False) # Recolector de datos para gráfica self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out") }) # Creación de los agentes del modelo y configuración de parámetros self.setup() # Ejecución en navegador despues de crear self.running = True
def __init__(self): super().__init__(Model) print("Starting Model") density = model_params.parameters['density'] nodes = model_params.parameters['network_size'] neg_bias = model_params.parameters['neg_bias'] meme_density = model_params.parameters['meme_density'] self.num_agents = nodes self.meme = 0 #G = model_functions.build_network(density, nodes) #nx.write_gpickle(G, "population.gpickle") #END G = nx.read_gpickle("population.gpickle") self.grid = NetworkGrid(G) self.schedule = RandomActivation(self) print("Network Created") self.running = True for node in range(nodes): new_agent = agent.tweeter(self.next_id(), node, self, neg_bias, meme_density) self.grid.place_agent(new_agent, node) self.schedule.add(new_agent) #self.meme = 0 self.datacollector = DataCollector( model_reporters={ "meme_density": model_functions.compute_meme_density }) self.datacollector.collect(self)
def initialize_datacollector(self): """ Setup the initial datacollector """ self.datacollector = DataCollector( model_reporters={ "Susceptible": lambda m: m.get_population_fraction_by_state( AgentState.SUSCEPTIBLE), # noqa "Exposed": lambda m: m.get_population_fraction_by_state(AgentState.EXPOSED ), # noqa "Infectious": lambda m: m.get_population_fraction_by_state( AgentState.INFECTIOUS), # noqa "Symptomatic": lambda m: m.get_population_fraction_by_state( AgentState.SYMPTOMATIC), # noqa "Recovered": lambda m: m.get_population_fraction_by_state( AgentState.RECOVERED), # noqa "Vaccinated": lambda m: m.get_population_fraction_by_state( AgentState.VACCINATED), # noqa "R0/10": lambda m: m.contact_network.compute_R0() / 10.0 })
def __init__(self, number_of_car_agents=100, number_of_bar_agents=2, number_of_toll_agents=1): #set params self.number_of_car_agents = number_of_car_agents self.number_of_bar_agents = number_of_bar_agents self.number_of_toll_agents = number_of_toll_agents self.schedule = CustomBaseSheduler(self) self.datacollector = DataCollector( {"Car agents": lambda m: m.schedule.get_breed_count(CarAgent)}) #gate agent for i in range(self.number_of_toll_agents): gate_agent = GateAgent("Gate " + str(i), self, 40) self.schedule.add(gate_agent) #bar agents for i in range(self.number_of_bar_agents): bar_agent = BarAgent("Bar " + str(i), self, 20) self.schedule.add(bar_agent) #car agents for i in range(self.number_of_car_agents): car_agent = CarAgent("Car " + str(i), self) self.schedule.add(car_agent) #trade road_state = RoadInterface(0, self) self.schedule.add(road_state)
def __init__(self, height=100, width=100, density=0.65): self.height = height self.width = width self.density = density self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector({ "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out"), }) for (contents, x, y) in self.grid.coord_iter(): if self.random.random() < self.density: new_tree = TreeCell((x, y), self) # Set all trees in the first column on fire. if x == 0: new_tree.condition = "On Fire" self.grid._place_agent((x, y), new_tree) self.schedule.add(new_tree) self.running = True self.datacollector.collect(self)
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, height=100, width=100, density=0.65): """ Create a new forest fire model. Args: height, width: The size of the grid to model density: What fraction of grid cells have a tree in them. """ # Set up model objects self.schedule = RandomActivation(self) self.grid = Grid(height, width, torus=False) self.datacollector = DataCollector( { "Fine": lambda m: self.count_type(m, "Fine"), "On Fire": lambda m: self.count_type(m, "On Fire"), "Burned Out": lambda m: self.count_type(m, "Burned Out"), } ) # Place a tree in each cell with Prob = density for (contents, x, y) in self.grid.coord_iter(): if self.random.random() < density: # Create a tree new_tree = TreeCell((x, y), self) # Set all trees in the first column on fire. if x == 0: new_tree.condition = "On Fire" self.grid._place_agent((x, y), new_tree) self.schedule.add(new_tree) self.running = True self.datacollector.collect(self)
def __init__(self, N, K, width=10, height=10, trade=True): super().__init__() self.N = N self.K = K self.consume = False self.trade = trade self.solo_update = True self.money = False self.running = True self.history = [] self.grid = MultiGrid(width, height, True) self.schedule = RandomActivation(self) # create agents for a in range(self.N): a = ant(a, 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)) all_utility = [agent.utility() for agent in self.schedule.agents] self.mean_utility = sum(all_utility) / self.N all_spec = [agent.specialization() for agent in self.schedule.agents] self.mean_specialization = sum(all_spec) / self.N self.datacollector = DataCollector(model_reporters={ "Mean_Utility": "mean_utility", "Mean_Specialization": "mean_specialization" }, agent_reporters={ "Utility": utility_reporter, "Specialization": specialization_reporter })
def __init__(self, N, width, height, infection_rate, proportion_infected, die_rate, max_infection_time): self.num_agents = N self.grid = MultiGrid(width, height, True) self.schedule = RandomActivation(self) self.infection_rate = infection_rate self.running = True self.susceptible = 0 self.infected = 0 self.recovered = 0 self.dead = 0 self.dead_agents = [] for i in range(self.num_agents): a = AgentSchelling(i, self, die_rate, max_infection_time) 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)) # make some agents infected at start infected = np.random.choice([0, 1], p=[1 - proportion_infected, proportion_infected]) if infected == 1: a.status = 1 self.datacollector = DataCollector( model_reporters={"Infected": "infected", "Susceptible": "susceptible", "Recovered": "recovered", "Dead": "dead"} )
def __init__(self, N, height, width, exponent, steps): self.number_of_agents = N self.height = height self.width = width self.exponent = exponent #self.x_locs = np.zeros((N, steps)) #self.y_locs = np.zeros((N)) self.direction_range=3 self.directions = Directions(self.direction_range) self.current_step_contacts=[] self.adjacency_matrix = np.zeros((N, N)) self.grid = MultiGrid(self.width, self.height, torus=False) self.schedule = BaseScheduler(self) self.current_step = 0 # Add N pedestrians to model (schedule, grid) for i in range(self.number_of_agents): x = self.random.randrange(1, self.grid.width-1) y = self.random.randrange(1, self.grid.height-1) pos = (x, y) new_human = Pedestrian(i, self, pos, self.exponent, self.directions) self.schedule.add(new_human) self.grid.place_agent(new_human, pos) self.data_collector=DataCollector() self.running=True self.data_collector.collect(self)
def init_dc(self): # data collector enables tracking of metric at each time step self.datacollector = DataCollector( model_reporters={ "time": self.get_time, "m": self.get_m, "n": self.get_n, "j": self.get_j, "p_1": self.get_p_1, "p_2": self.get_p_2, "p_3": self.get_p_3, "q_h1": self.get_q_h1, "q_h2": self.get_q_h2, "q_ml": self.get_q_ml_basic, "alpha_ml": self.get_alpha_ml, "p_turb": self.get_p_turb, "q_ml_scaling": self.get_q_ml_scaling_int, "avg_q_ml": calc_avg_q_ml, "code_kl": calc_code_kl, "human_kl": calc_human_kl, "human_kl_var": calc_kl_var, "human_kl_dissim": calc_dissim, }) # collect metrics for time step 0 self.datacollector.collect(self) return
def __init__(self, height=20, width=20, initial_sheep=100, initial_wolves=30, sheep_reproduction_chance=0.05, wolf_death_chance=0.05): super().__init__() self.height = height self.width = width self.initial_sheep = initial_sheep self.initial_wolves = initial_wolves self.sheep_reproduction_chance = sheep_reproduction_chance self.wolf_death_chance = wolf_death_chance # Add a schedule for sheep and wolves seperately to prevent # race-conditions self.schedule_Sheep = RandomActivation(self) self.schedule_Wolf = RandomActivation(self) self.grid = MultiGrid(self.width, self.height, torus=True) self.datacollector = DataCollector( {"Sheep": lambda m: self.schedule_Sheep.get_agent_count(), "Wolves": lambda m: self.schedule_Wolf.get_agent_count(), "Mean": mean_wolf}) # Create sheep and wolves self.init_population(Sheep, self.initial_sheep) self.init_population(Wolf, self.initial_wolves) # This is required for the datacollector to work self.running = True self.datacollector.collect(self)
def make_fish(self): """ Create N "Fish" agents. A random position and starting velocity is assigned for each fish. Call data collectors for fish collective behaviour """ for i in range(self.n_fish): x = random.randrange(2, (self.space.x_max - 1)) y = random.randrange(2, (self.space.y_max - 1)) pos = np.array((x, y)) velocity = np.random.random( 2) * 2 - 1 # [-1.0 .. 1.0, -1.0 .. 1.0] fish = Fish(i, self, pos, self.speed, velocity, self.vision, self.separation, **self.factors) self.space.place_agent(fish, pos) self.schedule.add(fish) self.datacollector = DataCollector( # model_reporters={"test": test}) model_reporters={ "Polarization": polar, "Nearest Neighbour Distance": nnd, "Shoal Area": area, "Mean Distance from Centroid": centroid_dist })
def __init__(self, N, avg_node_degree, rule='CMR', zero_prob=0.5): self.num_agents = N self.rule = rule self.schedule = RandomActivation(self) prob = avg_node_degree / self.num_agents self.G = nx.erdos_renyi_graph(n=self.num_agents, p=prob) self.grid = NetworkGrid(self.G) #create the agents for i, node in enumerate(self.G.nodes()): a = OpinionAgent( i, self, initial_opinion=self.random.choices( [0, 1], weights=[zero_prob, 1 - zero_prob], k=1)[0]) #we can seed w/a non-equal probability self.schedule.add(a) self.grid.place_agent(a, node) self.datacollector = DataCollector(model_reporters={ 'opinion_0': opinion_0_ct, 'opinion_1': opinion_1_ct }) self.running = True #we could check to see if we've reached a steady state self.datacollector.collect(self)
def __init__(self, height=20, width=20, density=.8, group_ratio=.66, minority_ratio=.5, homophily=3): self.height = height self.width = width self.density = density self.group_ratio = group_ratio self.minority_ratio = minority_ratio self.homophily = homophily self.happy = 0 self.segregated = 0 self.schedule = RandomActivation(self) self.grid = SingleGrid(height, width, torus=False) self.place_agents() self.datacollector = DataCollector({ 'happy': (lambda m: m.happy), 'segregated': (lambda m: m.segregated) }) self.running = True
def __init__(self, N, limit_time, infected_init, neighbors): self.num_agents = N prob = neighbors / self.num_agents self.G = nx.erdos_renyi_graph(n=self.num_agents, p=prob) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector( { "Infected": number_infected, "Susceptible": number_susceptible, "Resistant": number_resistant, } ) # Create agents for i, node in enumerate(self.G.nodes()): a = PeopleAgent(i,limit_time, self) self.schedule.add(a) # Add the agent to the node self.grid.place_agent(a, node) # Infect some nodes infected_nodes = self.random.sample(self.G.nodes(), infected_init) for a in self.grid.get_cell_list_contents(infected_nodes): a.status = State.ACTIVE self.datacollector.collect(self)
def __init__(self, N=100, infection_rate=0.05, first_infection_time=10, incubation_period=20, recover_period=100, width=10, height=10): self.num_agents = N self.infection_rate = infection_rate self.first_infection_time = first_infection_time self.incubation_period = incubation_period self.recover_period = recover_period self.grid = MultiGrid(height, width, True) self.schedule = RandomActivation(self) self.datacollector = DataCollector(model_reporters={ "Susceptibles": get_num_susceptible, "Exposed": get_num_exposed, "Infected": get_num_infected, "Recovered": get_num_recovered }, agent_reporters={"State": "state"}) # Create agents for i in range(self.num_agents): a = Person(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)) self.running = True self.datacollector.collect(self)