def __init__(self, num_agents=7, num_nodes=10, num_steps=1000, server=True): self.server = server self.num_steps = num_steps self.num_agents = num_agents self.num_nodes = num_nodes if num_nodes >= self.num_agents else self.num_agents self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=0.5) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector( model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": lambda _: _.wealth}) list_of_random_nodes = self.random.sample(self.G.nodes(), self.num_agents) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) # Add the agent to a random node self.grid.place_agent(a, list_of_random_nodes[i]) self.running = True self.datacollector.collect(self)
def __init__(self, **params): super().__init__() config = configparser.ConfigParser() config.read('conf/config.ini') self.sqlite_db = config['SQLITEDB']['file'] self.height = 20 self.width = 20 self.is_init_db = False if params.get( 'write_db') is None else params.get('write_db') self.is_write_db = False if params.get( 'write_db') is None else params.get('write_db') self.max_steps = params['max_steps'] self.initial_saver = params['initial_saver'] self.initial_loan = params['initial_loan'] self.initial_bank = params['initial_bank'] self.rfree = params['rfree'] self.reserve_rates = params[ 'rfree'] / 2.0 # set reserve rates one half of risk free rate self.libor_rate = params['rfree'] self.bankrupt_liquidation = 1 # 1: it is fire sale of assets, 0: bank liquidates loans at face value self.car = params['car'] self.min_reserves_ratio = params['min_reserves_ratio'] self.initial_equity = params['initial_equity'] self.G = nx.empty_graph(self.initial_bank) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector({"BankAsset": get_sum_totasset})
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"})
class COVID_model(Model): def __init__(self): super().__init__(Model) self.susceptible = 0 self.dead = 0 self.recovered = 0 self.infected = 0 interactions = model_params.parameters['interactions'] self.population = model_params.parameters['population'] self.SIR_instance = SIR.Infection( self, ptrans=model_params.parameters['ptrans'], reinfection_rate=model_params.parameters['reinfection_rate'], I0=model_params.parameters["I0"], severe=model_params.parameters["severe"], progression_period=model_params.parameters["progression_period"], progression_sd=model_params.parameters["progression_sd"], death_rate=model_params.parameters["death_rate"], recovery_days=model_params.parameters["recovery_days"], recovery_sd=model_params.parameters["recovery_sd"]) G = SIR.build_network(interactions, self.population) self.grid = NetworkGrid(G) self.schedule = RandomActivation(self) self.dead_agents = [] self.running = True for node in range(self.population): new_agent = agent.human(node, self) #what was self.next_id() self.grid.place_agent(new_agent, node) self.schedule.add(new_agent) #self.meme = 0 self.datacollector = DataCollector( model_reporters={ "infected": lambda m: c_p.compute(m, 'infected'), "recovered": lambda m: c_p.compute(m, 'recovered'), "susceptible": lambda m: c_p.compute(m, "susceptible"), "dead": lambda m: c_p.compute(m, "dead"), "R0": lambda m: c_p.compute(m, "R0"), "severe_cases": lambda m: c_p.compute(m, "severe") }) self.datacollector.collect(self) def step(self): self.schedule.step() self.datacollector.collect(self) ''' for a in self.schedule.agents: if a.alive == False: self.schedule.remove(a) self.dead_agents.append(a.unique_id) ''' if self.dead == self.schedule.get_agent_count(): self.running = False else: 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)
class BoltzmannWealthModelNetwork(Model): """A model with some number of agents.""" def __init__(self, num_agents=7, num_nodes=10): self.num_agents = num_agents self.num_nodes = num_nodes if num_nodes >= self.num_agents else self.num_agents self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=0.5) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector( model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": lambda _: _.wealth} ) list_of_random_nodes = self.random.sample(self.G.nodes(), self.num_agents) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) # Add the agent to a random node self.grid.place_agent(a, list_of_random_nodes[i]) self.running = True self.datacollector.collect(self) def step(self): self.schedule.step() # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
def __init__(self, num_nodes, avg_node_degree, initial_outbreak_size, virus_spread_chance, virus_check_frequency, recovery_chance, gain_resistance_chance): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) 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.virus_spread_chance = virus_spread_chance self.virus_check_frequency = virus_check_frequency self.recovery_chance = recovery_chance self.gain_resistance_chance = gain_resistance_chance self.running = True self.datacollector = DataCollector({"Infected": number_infected, "Susceptible": number_susceptible, "Resistant": number_resistant}) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent(i, self, State.SUSCEPTIBLE, self.virus_spread_chance, self.virus_check_frequency, self.recovery_chance, self.gain_resistance_chance) self.schedule.add(a) # Add the agent to the node self.grid.place_agent(a, node) # Infect some nodes infected_nodes = random.sample(self.G.nodes(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INFECTED
def __init__(self, N, initInfected, percInfect, percRecover, intervention): self.running = True self.num_agents = N self.initInfected = initInfected self.percInfect = percInfect self.percRecover = percRecover self.intervention = intervention #self.grid = nx.ErdosRenyiGraph(self.num_agents,) self.G = nx.complete_graph(self.num_agents) self.grid = NetworkGrid(self.G) self.schedule = RandomSingleActivation(self) # create and initialise agents for i, node in enumerate(self.G.nodes): a = DiseaseAgent(i, self) self.schedule.add(a) self.grid.place_agent(a, node) # make some agents initially infected for a in filter( lambda a: a.unique_id in initInfected, self.schedule.agents ): #random.sample(self.schedule.agents, self.initInfected): a.infect() # set up data collection self.datacollector = DataCollector(agent_reporters={ "State": "state", "Event": "event", "Cause": "cause" })
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 __init__(self): super().__init__(Model) self.susceptible = 0 self.dead = 0 self.recovered = 0 self.infected = 0 interactions = model_params.parameters['interactions'] population = model_params.parameters['population'] self.num_agents = population G = model_functions.build_network(interactions, population) self.grid = NetworkGrid(G) self.schedule = RandomActivation(self) self.running = True for node in range(population): new_agent = agent.human(self.next_id(), node, self) self.grid.place_agent(new_agent, node) self.schedule.add(new_agent) #self.meme = 0 self.datacollector = DataCollector(model_reporters={"infected": model_functions.compute_infected, "recovered": model_functions.compute_recovered, "susceptible": model_functions.compute_susceptible, "dead": model_functions.compute_dead, "R0": model_functions.compute_R0, "severe_cases":model_functions.compute_severe}) self.datacollector.collect(self)
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, 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})
class propagation_model(Model): def __init__(self): super().__init__(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) self.grid = NetworkGrid(G) self.schedule = RandomActivation(self) 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 step(self): self.schedule.step() self.datacollector.collect(self) if self.meme == self.schedule.get_agent_count(): self.running = False
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)
class BoltzmannWealthModelNetwork(Model): """A model with some number of agents.""" def __init__(self, num_agents=7, num_nodes=10): self.num_agents = num_agents self.num_nodes = num_nodes if num_nodes >= self.num_agents else self.num_agents self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=0.5) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector( model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": lambda _: _.wealth} ) list_of_random_nodes = random.sample(self.G.nodes(), self.num_agents) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) # Add the agent to a random node self.grid.place_agent(a, list_of_random_nodes[i]) self.running = True self.datacollector.collect(self) def step(self): self.schedule.step() # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
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, 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, 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))
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.
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)
class WasteNet(Model): """Waste collection network model""" def __init__(self, mode, nb_nodes=10, nb_episodes=1): # Network self.G = generate_graph(nb_nodes) self.grid = NetworkGrid(self.G) # Gym Environment env_config = dict(graph=self.G) self.env = WasteNetEnv(env_config) # RL Agent if mode == WasteNetMode.PPO.name: rl_agent = PPOAgent("WasteNet", WasteNetEnv, env_config, best_config) rl_agent.load("./checkpoints/checkpoint-best") else: rl_agent = None # Scheduler self.schedule = WasteNetActivation(self, mode, rl_agent) # Data Collector self.datacollector = DataCollector( model_reporters={ "Empty": nb_empty, "Medium": nb_medium, "Full": nb_full, "Overflow": nb_overflow, }, agent_reporters={ "Fill level (%)": fill_level, "": lambda a: 100 }, ) # Mesa Agents for i, node in enumerate(self.G.nodes()): if i in (0, self.G.number_of_nodes() - 1): a = BaseAgent(i, self) else: a = DumpsterAgent(i, self, self.env.fill_levels[i - 1]) self.schedule.add(a) self.grid.place_agent(a, node) self.remaining_episodes = nb_episodes self.running = True self.datacollector.collect(self) def step(self): done = self.schedule.step() self.datacollector.collect(self) if done: self.env.reset() self.remaining_episodes -= 1 if self.remaining_episodes == 0: self.running = False
class VirusModel(Model): """A virus model with some number of agents""" def __init__(self, num_nodes, avg_node_degree, initial_outbreak_size, virus_spread_chance, virus_check_frequency, recovery_chance, gain_resistance_chance): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) 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.virus_spread_chance = virus_spread_chance self.virus_check_frequency = virus_check_frequency self.recovery_chance = recovery_chance self.gain_resistance_chance = gain_resistance_chance self.datacollector = DataCollector({ "Infected": number_infected, "Susceptible": number_susceptible, "Resistant": number_resistant }) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent(i, self, State.SUSCEPTIBLE, self.virus_spread_chance, self.virus_check_frequency, self.recovery_chance, self.gain_resistance_chance) self.schedule.add(a) # Add the agent to the node self.grid.place_agent(a, node) # Infect some nodes infected_nodes = random.sample(self.G.nodes(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INFECTED self.running = True self.datacollector.collect(self) def resistant_susceptible_ratio(self): try: return number_state(self, State.RESISTANT) / number_state( self, State.SUSCEPTIBLE) except ZeroDivisionError: return math.inf def step(self): self.schedule.step() # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
class VirusModel(Model): """A virus model with some number of agents""" def __init__(self, num_nodes, avg_node_degree, initial_outbreak_size, alpha, beta, gamma, k, n): self.num_nodes = num_nodes self.avg_node_degree = avg_node_degree self.G = nx.barabasi_albert_graph(n=self.num_nodes, m=avg_node_degree) # _graph(n=self.num_nodes, p=prob) 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.alpha = alpha self.beta = beta self.gamma = gamma self.k = k self.n = n self.datacollector = DataCollector({ "Infected": number_active, "Susceptible": number_susceptible, "Carrier": number_inactive, "Removed": number_removed }) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent(i, self, State.SUSCEPTIBLE, self.alpha, self.beta, self.gamma, self.k, self.n) self.schedule.add(a) # Add the agent to the node self.grid.place_agent(a, node) # Infect some nodes active_nodes = random.sample(self.G.nodes(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(active_nodes): a.state = State.ACTIVE self.running = True self.datacollector.collect(self) def removed_susceptible_ratio(self): try: return number_state(self, State.REMOVED) / number_state( self, State.SUSCEPTIBLE) except ZeroDivisionError: return math.inf def step(self): self.schedule.step() # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
class VirusModel(Model): def __init__(self, num_nodes, avg_node_degree, initial_outbreak_size, alpha, beta): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.initial_outbreak_size = initial_outbreak_size if initial_outbreak_size <= num_nodes else num_nodes self.alpha = alpha self.beta = beta self.G = nx.barabasi_albert_graph(n=self.num_nodes, m=3) # self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.datacollector = DataCollector({ "Susceptible": number_susceptible, "Infected": number_infected, "Removed": number_removed }) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent( i, self, State.SUSCEPTIBLE, self.alpha, self.beta, ) self.schedule.add(a) self.grid.place_agent(a, node) # Infect some nodes infected_nodes = random.sample(self.G.nodes(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INFECTED self.running = True self.datacollector.collect(self) def removed_susceptible_ratio(self): try: return number_state(self, State.REMOVED) / number_state( self, State.SUSCEPTIBLE) except ZeroDivisionError: return math.inf def step(self): self.schedule.step() self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
def __init__(self, N=10, pcontact=0.4, ptrans=0.5, avg_node_degree=3, progression_period=3, progression_sd=2, recovery_rate=0.0193, recovery_days=1/0.0193, recovery_sd=7, incubation_time = 6 , incubation_time_sd = 2, rate_infected = 1/6): #My shit here: self.num_nodes = N self.pcontact=pcontact n = 100 self.A_prob = np.random.rand(N,N) self.A = (self.A_prob<pcontact).astype('int') #----------------------------# # Myshit # #----------------------------# #self.num_nodes = N #self.pcontact=pcontact """All parameters""" prob = avg_node_degree / self.num_nodes self.initial_outbreak_size = 1 self.incubation_time = incubation_time self.incubation_time_sd = incubation_time_sd self.rate_infected = rate_infected self.recovery_sd = recovery_sd self.ptrans = ptrans self.recovery_rate = recovery_rate self.recovery_days = recovery_days self.G = nx.Graph(self.A) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) #activate the step of Agents in random orders self.running = True #self.dead_agents = [] """2 types of agents: intra-agent and out-agent""" # Create out_agents: # Create intra-agents for i, node in enumerate(self.G.nodes()): a = CovidAgent(i+1, self) self.G.add_node(a) #add agent self.grid.place_agent(a, node) self.A_prob = np.random.rand(N+i,N+i) self.A = (self.A_prob<pcontact).astype('int') #make some agents infected at start infected = np.random.choice([0,1], p=[0.99,0.01]) if infected == 1: a.state = State.INFECTED a.recovery_time = self.get_recovery_time() self.datacollector = DataCollector( agent_reporters={"State": 'state'})
def __init__(self, agents=agents, dt=0.1, attention_delta=0.1, persuasion=1, a_min=-0.5, r_min=0.05, sd_opinion=0.15, sd_info=0.005, network_params=None): super().__init__() self.dt = dt self.attention_delta = attention_delta self.persuasion = persuasion self.a_min = a_min self.r_min = r_min self.sd_opinion = sd_opinion self.sd_info = sd_info # initialize a scheduler self.schedule = BaseScheduler(self) # create the population self.population = 0 if network_params is None: network_params = {"method": "er", "p": 0.1} self.init_population(agents, network_params) # self.G = nx.Graph() # generates network topology # not used right now, but can be used for mesa visualization self.grid = NetworkGrid(self.G) # create agents self.create_agents(agents) # agent who will interact this turn self.active_agent = None # add datacollector # collects opinion, information and attention each step self.data_collector = DataCollector({ "Opinion": lambda m: self.collect_opinions(), "Attention": lambda m: self.collect_attentions(), "Information": lambda m: self.collect_informations() }) # this is required for the data_collector to work self.running = True self.data_collector.collect(self)
class Population(Model): """Population Adapted from https://www.medrxiv.org/content/10.1101/2020.03.18.20037994v1.full.pdf Model Parameters: spread_chance: probability of infection based on contact gamma: mean incubation period alpha: probability of become asymptomatic vs symptomatic gamma_AR: infectious period for asymptomatic people gamma_YR: infectious period for symptomatic people delta: death rate due to disease """ 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 step(self): self.datacollector.collect(self) self.schedule.step() def run(self, n): for i in range(n): #logger.info("Steps Completed: " + str(i)) #print("Steps completed: ", i) self.step()
def __init__(self, nodes, initial_RefinedKitten = 100, initial_ImperialKitten = 100, initial_CharmingKitten = 100, initial_HelixKitten = 100, initial_StaticKitten = 100, initial_RemixKitten = 100): super().__init__() self.initial_RefinedKitten = initial_RefinedKitten self.initial_ImperialKitten = initial_ImperialKitten self.initial_CharmingKitten = initial_CharmingKitten self.initial_HelixKitten = initial_HelixKitten self.initial_StaticKitten = initial_StaticKitten self.initial_RemixKitten = initial_RemixKitten self.grid = NetworkGrid(G) self.schedule = RandomActivationByOrg(self) for i in range(self.initial_RefinedKitten): refinedkitten = RefinedKitten(self.next_id(), 'RFK', self) self.grid.place_agent(refinedkitten, 'RFK') self.schedule.add(refinedkitten) for i in range(self.initial_ImperialKitten): imperialkitten = ImperialKitten(self.next_id(), 'IK', self) self.grid.place_agent(imperialkitten, 'IK') self.schedule.add(imperialkitten) for i in range(self.initial_CharmingKitten): charmingkitten = CharmingKitten(self.next_id(), 'CK', self) self.grid.place_agent(charmingkitten, 'CK') self.schedule.add(charmingkitten) for i in range(self.initial_HelixKitten): helixkitten = HelixKitten(self.next_id(), 'HK', self) self.grid.place_agent(helixkitten, 'HK') self.schedule.add(helixkitten) for i in range(self.initial_StaticKitten): statickitten = StaticKitten(self.next_id(), 'SK', self) self.grid.place_agent(statickitten, 'SK') self.schedule.add(statickitten) for i in range(self.initial_RemixKitten): remixkitten = RemixKitten(self.next_id(), 'RMK', self) self.grid.place_agent(remixkitten, 'RMK') self.schedule.add(remixkitten) self.running = True self.datacollector = DataCollector( agent_reporters = {"Organization": "org", "Spear Phishing": "phish", "Zero Day": "zeroday", "Tool Sophistication": "tools", "Attribution Obfuscation": "attrib", "Stealth": "stealth", "Information Weaponization": "iwo","DDoS": "ddos", "Data Destruction": "destruct", "Critical Infrastructure Disruption": "infra"})
def setUp(self): ''' Create a test network grid and populate with Mock Agents. ''' G = nx.complete_graph(TestMultipleNetworkGrid.GRAPH_SIZE) self.space = NetworkGrid(G) self.agents = [] for i, pos in enumerate(TEST_AGENTS_NETWORK_MULTIPLE): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos)
def __init__( self, num_nodes=1740, avg_node_degree=3, initial_with_clean=174, change_clean_chance=0.03, check_frequency=1.0, switch_back_chance=0.02, gain_resistance_chance=0.0, ): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) self.grid = NetworkGrid(self.G) self.schedule = RandomActivation(self) self.initial_with_clean = ( initial_with_clean if initial_with_clean <= num_nodes else num_nodes ) self.change_clean_chance = change_clean_chance self.check_frequency = check_frequency self.switch_back_chance = switch_back_chance self.gain_resistance_chance = gain_resistance_chance self.datacollector = DataCollector( { "has_clean": number_has_clean, "not_clean": number_not_clean, "refuses_clean": number_refuses_clean, } ) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent( i, self, State.not_clean, self.change_clean_chance, self.check_frequency, self.switch_back_chance, self.gain_resistance_chance, ) self.schedule.add(a) # Add the agent to the node self.grid.place_agent(a, node) # Infect some nodes has_clean_nodes = self.random.sample(self.G.nodes(), self.initial_with_clean) for a in self.grid.get_cell_list_contents(has_clean_nodes): a.state = State.has_clean self.running = True self.datacollector.collect(self)
class PopuNetwork(Model): """ The population network which initializes: - the number of agents - the number of incarcerated agents at start - the race of the simulated community - the average number of relationships per individual """ 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 step(self): self.schedule.step() self.months += 1 # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
class VirusOnNetwork(Model): """A virus model with some number of agents""" def __init__(self, num_nodes=10, avg_node_degree=3, initial_outbreak_size=1, virus_spread_chance=0.4, virus_check_frequency=0.4, recovery_chance=0.3, gain_resistance_chance=0.5): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) 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.virus_spread_chance = virus_spread_chance self.virus_check_frequency = virus_check_frequency self.recovery_chance = recovery_chance self.gain_resistance_chance = gain_resistance_chance self.datacollector = DataCollector({"Infected": number_infected, "Susceptible": number_susceptible, "Resistant": number_resistant}) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent(i, self, State.SUSCEPTIBLE, self.virus_spread_chance, self.virus_check_frequency, self.recovery_chance, self.gain_resistance_chance) 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(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INFECTED self.running = True self.datacollector.collect(self) def resistant_susceptible_ratio(self): try: return number_state(self, State.RESISTANT) / number_state(self, State.SUSCEPTIBLE) except ZeroDivisionError: return math.inf def step(self): self.schedule.step() # collect data self.datacollector.collect(self) def run_model(self, n): for i in range(n): self.step()
def __init__(self, num_nodes=10, avg_node_degree=3, initial_outbreak_size=1, virus_spread_chance=0.4, virus_check_frequency=0.4, recovery_chance=0.3, gain_resistance_chance=0.5): self.num_nodes = num_nodes prob = avg_node_degree / self.num_nodes self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob) 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.virus_spread_chance = virus_spread_chance self.virus_check_frequency = virus_check_frequency self.recovery_chance = recovery_chance self.gain_resistance_chance = gain_resistance_chance self.datacollector = DataCollector({"Infected": number_infected, "Susceptible": number_susceptible, "Resistant": number_resistant}) # Create agents for i, node in enumerate(self.G.nodes()): a = VirusAgent(i, self, State.SUSCEPTIBLE, self.virus_spread_chance, self.virus_check_frequency, self.recovery_chance, self.gain_resistance_chance) 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(), self.initial_outbreak_size) for a in self.grid.get_cell_list_contents(infected_nodes): a.state = State.INFECTED self.running = True self.datacollector.collect(self)
class TestMultipleNetworkGrid(unittest.TestCase): GRAPH_SIZE = 3 def setUp(self): ''' Create a test network grid and populate with Mock Agents. ''' G = nx.complete_graph(TestMultipleNetworkGrid.GRAPH_SIZE) self.space = NetworkGrid(G) self.agents = [] for i, pos in enumerate(TEST_AGENTS_NETWORK_MULTIPLE): a = MockAgent(i, None) self.agents.append(a) self.space.place_agent(a, pos) def test_agent_positions(self): ''' Ensure that the agents are all placed properly. ''' for i, pos in enumerate(TEST_AGENTS_NETWORK_MULTIPLE): a = self.agents[i] assert a.pos == pos def test_get_neighbors(self): assert len(self.space.get_neighbors(0, include_center=True)) == TestMultipleNetworkGrid.GRAPH_SIZE assert len(self.space.get_neighbors(0, include_center=False)) == TestMultipleNetworkGrid.GRAPH_SIZE - 1 def test_move_agent(self): initial_pos = 1 agent_number = 1 final_pos = 0 _agent = self.agents[agent_number] assert _agent.pos == initial_pos assert _agent in self.space.G.node[initial_pos]['agent'] assert _agent not in self.space.G.node[final_pos]['agent'] assert len(self.space.G.node[initial_pos]['agent']) == 2 assert len(self.space.G.node[final_pos]['agent']) == 1 self.space.move_agent(_agent, final_pos) assert _agent.pos == final_pos assert _agent not in self.space.G.node[initial_pos]['agent'] assert _agent in self.space.G.node[final_pos]['agent'] assert len(self.space.G.node[initial_pos]['agent']) == 1 assert len(self.space.G.node[final_pos]['agent']) == 2 def test_is_cell_empty(self): assert not self.space.is_cell_empty(0) assert not self.space.is_cell_empty(1) assert self.space.is_cell_empty(2) def test_get_cell_list_contents(self): assert self.space.get_cell_list_contents([0]) == [self.agents[0]] assert self.space.get_cell_list_contents([1]) == [self.agents[1], self.agents[2]] assert self.space.get_cell_list_contents(list(range(TestMultipleNetworkGrid.GRAPH_SIZE))) == [self.agents[0], self.agents[1], self.agents[2]] def test_get_all_cell_contents(self): assert self.space.get_all_cell_contents() == [self.agents[0], self.agents[1], self.agents[2]]