def batchrun(): """This function performs a batchrun depending on the parameters. Here you can se the parameters you want to check.""" tactics = ["Offset", "Proportional", "Lookahead", "GreenWave"] spawnrates = [1, 2, 3, 4, 5] variableParams = { "tactic": tactics, "spawnrate": spawnrates, } fixedparams = {"offset": 0, "cycletime": 90} # Initialize batchrunner br = BatchRunner( Intersection, variable_parameters=variableParams, fixed_parameters=fixedparams, iterations=1, max_steps=50000, model_reporters={"Data Collector": lambda m: m.datacollector}, ) # Run batch and collect data br.run_all() br_df = br.get_model_vars_dataframe() br_step_data = pd.DataFrame() for i in range(len(br_df["Data Collector"])): if isinstance(br_df["Data Collector"][i], DataCollector): i_run_data = br_df["Data Collector"][i].get_model_vars_dataframe() br_step_data = br_step_data.append(i_run_data, ignore_index=True) br_step_data.to_csv("./Data/Offsetworse10.csv")
def evaluate_justice(model): """ Evaluate a model by its alignment with respect to justice. """ params = { 'num_agents': model.num_agents, 'collecting_rates': model.collecting_rates, 'redistribution_rates': model.redistribution_rates, 'invest_rate': model.invest_rate, 'num_evaders': model.num_evaders, 'catch': model.catch, 'fine_rate': model.fine_rate } batch_run = BatchRunner(model_cls=Society, fixed_parameters=params, iterations=paths, max_steps=length, agent_reporters={ "Position": "position", "Evader": "is_evader" }, display_progress=False) batch_run.run_all() info = batch_run.get_agent_vars_dataframe() evaders_info = info[info['Evader']] algn = -1 + 2 * evaders_info["Position"].mean() / (params["num_agents"] - 1) return algn
def run(variable_key, variable_value): fixed_parameters = { "people_inside": 200, "people_outside": 200, "outside_person_econ_dist_mean": 1.0, "share_threshold": 0.7, "property_value_dist_mean": 0.0, "num_residential": 250, "num_commercial": 50, "num_streets": 10, "width": 20, "height": 20 } # Remove variable parameters from fixed parameters del fixed_parameters[variable_key] runner = BatchRunner(m.GentrifiedNeighbourhood, fixed_parameters=fixed_parameters, variable_parameters={variable_key: variable_value}, iterations=10, max_steps=20, model_reporters=m.model_reporters) runner.run_all() return runner
def run_model(): fixed_params = {"width": 80, "height": 80, "initial_bravery": 10, "battery_size": 75} variable_params = {"N": np.arange(100,500,150), # 3 "n_poles": [1/10,1/8,1/6,1/4], # 4 "vision": [1,2], # 3 "grid_positions": ["LHS", "circle"], # 2 "open_grid": ["True", "False"]} # 2 # 3*4*3*2*2 = 144 batch_run = BatchRunner(EV_Model, fixed_parameters=fixed_params, variable_parameters=variable_params, iterations=1, max_steps=2500, model_reporters={"Usage": avg_usage, "Total_attempts": totalAttempts, "Percentage_failed": percentageFailed, "Average_lifespan": averageLifespan}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() return run_data.values.tolist()
def batch_run_classroom(j): """ Helper function. The function containing the batchrunner for the classroom simulations. :param j: j is the setup type. eg j=2 => setup type [2,2,2] :return: Returns lists of average number of infected for every timestep. Saves the raw data from the datacollector into a csv file. """ batch_run = BatchRunner(covid_Model, variable_parameters={"N": range(24,25,1)}, fixed_parameters={"width": 11, "height": 11, "setUpType": [j]}, iterations=antal_iterationer, max_steps=antal_tidsskridt_per_simulation) batch_run.run_all() #run batchrunner ordered_df = batch_run.get_collector_model() data_list = list(ordered_df.values()) #saves batchrunner data in list for i in range(len(data_list)): data_list[i]['Iteration'] = i+1 pd.concat(data_list).to_csv('csvdata/classroom_test'+str(j)+'.csv') num_of_infected = [0]*(antal_tidsskridt_per_simulation+1) for i in range(len(data_list)): temp_list = [] for k in range(len(data_list[i]["infected"])): num_of_infected[k]+=data_list[i]["infected"][k] temp_list.append(data_list[i]["infected"][k]) num_of_infected = [number / antal_iterationer for number in num_of_infected] #avg number of infected return num_of_infected
def sim_w_beta(w, beta, alpha=0.5, omega=0.5, N=15, iters=200, max_steps=300): fixed_params = { "alpha": alpha, "omega": omega, "N": N, } variable_params = { "w": w, "beta": beta, } batch_run = BatchRunner( InteractionModel, variable_params, fixed_params, iterations=iters, max_steps=max_steps, model_reporters={"AP": compute_average_performance}) run_name = f"base_model_{batch_run.iterations}_rep_{int(time.time())}_beta_w" batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() grouped = run_data.groupby("w", as_index=False) data = grouped.aggregate(np.average) plt.scatter(data.w, data.AP) plt.savefig("./data/" + run_name + "_scatter.png") run_data.to_csv("./data/" + run_name) df = data.loc[:, ['w', 'AP']] df.rolling(10).mean().plot.scatter(x='w', y='AP') plt.savefig("./data/" + run_name + "_smoothed.png") return run_data, run_name
def batch_run(j): """ Helper function. The function containing the batchrunner for the full simulations. :param j: j is the setup type. eg j=2 => setup type [2,2,2] :return: Returns lists of average number of Infected, Susceptible, Recovered for every timestep. Saves the raw data from the datacollector into a csv file. """ batch_run = BatchRunner(covid_Model, variable_parameters={"N": range(24,25,1)}, fixed_parameters={"width": 26, "height": 38, "setUpType": [j,j,j]}, iterations=antal_iterationer, max_steps=antal_tidsskridt_per_simulation, model_reporters={"infected": lambda m: get_infected_count(m)}) batch_run.run_all() #run batchrunner ordered_df = batch_run.get_collector_model() data_list = list(ordered_df.values()) #saves batchrunner data in list for i in range(len(data_list)): data_list[i]['Iteration'] = i+1 pd.concat(data_list).to_csv('csvdata/rawdata'+str(j)+'.csv') num_of_infected = [0]*(antal_tidsskridt_per_simulation+1) num_of_susceptible = [0]*(antal_tidsskridt_per_simulation+1) num_of_recovered = [0]*(antal_tidsskridt_per_simulation+1) for i in range(len(data_list)): for j in range(len(data_list[i]["infected"])): num_of_infected[j]+=data_list[i]["infected"][j] num_of_susceptible[j] += data_list[i]["Agent_count"][j]-(data_list[i]["infected"][j]+data_list[i]["recovered"][j]+number_of_vaccinated) #number of susceptible at each time step num_of_recovered[j] += data_list[i]["recovered"][j] num_of_infected =[number / antal_iterationer for number in num_of_infected] #avg number of infected num_of_susceptible = [number / antal_iterationer for number in num_of_susceptible] num_of_recovered = [number / antal_iterationer for number in num_of_recovered] return num_of_infected, num_of_susceptible, num_of_recovered
def plot_busy(fix_par, var_par, model, iter, steps): batch_run = BatchRunner( model, variable_parameters=var_par, fixed_parameters=fix_par, iterations=iter, max_steps=steps, model_reporters={"busy": lambda m: busy_employees(m)}, ) batch_run.run_all() #run batchrunner data_list = list(batch_run.get_collector_model().values() ) # saves batchrunner data in a list sum_of_busy = [0] * (steps + 1) #makes list for y-values for i in range(len(data_list)): for j in range(len(data_list[i]["busy"])): sum_of_busy[j] += data_list[i]["busy"][ j] #at the right index add number of infected sum_of_infected = [number / iter for number in sum_of_busy ] #divide list with number of iterations to get avg time = [i for i in range(0, steps + 1)] #makes list of x-values for plotting plt.plot(time, sum_of_busy, label='# busy employees', color='Green') # plt.plot(time, num_of_susceptible, label= 'Number of Susceptible', color = 'Green', linestyle='dashed') plt.xlabel('Tidsskridt') plt.ylabel('Mean busy employees') plt.title('ved %s simulationer' % iter) plt.legend() return
def fitness(nrobots, maps_index): fixed_params = { "nrobots": nrobots, "radar_radius": 6, "wifi_range": 3, "alpha": 8.175, "gamma": 0.65, "dump_datas": True, "optimization_task": True, "load_file": "./robot_exploration/maps/30_maps/random{}.py".format(maps_index) } batch_run = BatchRunner(ExplorationArea, None, fixed_params, iterations=1, max_steps=10000, model_reporters={ "step": lambda m: m.schedule.steps, "total_idling": lambda m: m.total_idling_time }) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() return run_data["step"].iloc[0] + (run_data["total_idling"].iloc[0] / nrobots)
def launch_batch_processing(self): batch = BatchRunner(self.mock_model, variable_parameters=self.variable_params, fixed_parameters=self.fixed_params, iterations=self.iterations, max_steps=self.max_steps, model_reporters=self.model_reporters, agent_reporters=self.agent_reporters) batch.run_all() return batch
def generate_winners_data(): parameters = {"n_partys": [10] * 10, "n_voters": [1000] * 100} batch_run = BatchRunner( PrefrenceModel, parameters, max_steps=100, model_reporters={"Winner": lambda m: m.compute_winner().color}) batch_run.run_all() batch_df = batch_run.get_model_vars_dataframe() batch_df.to_csv('data.csv')
def launch_batch_processing(self): batch = BatchRunner( self.mock_model, variable_parameters=self.variable_params, fixed_parameters=self.fixed_params, iterations=self.iterations, max_steps=self.max_steps, model_reporters=self.model_reporters, agent_reporters=self.agent_reporters) batch.run_all() return batch
def get_batchrun(model, variable_params, fixed_params, iterations, max_steps, model_reporters): """Return one batchrun.""" batchrun = BatchRunner( model, variable_params, fixed_params, iterations=iterations, max_steps=max_steps, model_reporters=model_reporters) batchrun.run_all() return batchrun
def launch_batch_processing_fixed(self): # Adding second batchrun to test fixed params increase coverage batch = BatchRunner( self.mock_model, fixed_parameters={"fixed": "happy"}, iterations=4, max_steps=self.max_steps, model_reporters=self.model_reporters, agent_reporters=None, ) batch.run_all() return batch
def batch_run(self): fix_params = {"width": 100, "height": 100} variable_params = { # Variáveis de controle "density": [0.65, 0.5], "wind": [43.0, 48.0], } experiments_per_parameter_configuration = 150 max_steps_per_simulation = 100 batch_run = BatchRunner( ForestFire, variable_params, fix_params, iterations=experiments_per_parameter_configuration, max_steps=max_steps_per_simulation, model_reporters={ # Variáveis dependentes "Number of clusters (Fine)": lambda m: self.count_clusters(m, self.width, self.height, "Fine"), "Number of clusters (Fire Put Out)": lambda m: self.count_clusters(m, self.width, self.height, "Fire Put Out"), "Total steps of the fire forest": lambda m: self.total_steps(m), "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"), "Fire Put Out": lambda m: self.count_type(m, "Fire Put Out"), }, agent_reporters={ #"Condition of tree": lambda x: x.condition }) batch_run.run_all() run_model_data = batch_run.get_model_vars_dataframe() #run_agent_data = batch_run.get_agent_vars_dataframe() now = str(datetime.now()).replace(':', '-') file_name_sufix = ("_iter_" + str(experiments_per_parameter_configuration) + "_steps_" + str(max_steps_per_simulation) + "_" + now) run_model_data.to_csv("model_data" + file_name_sufix + ".csv")
def run_mesa_example(): fixed_params = {"width": 10, "height": 10} variable_params = {"N": range(10, 500, 10)} # The variables parameters will be invoke along with the fixed parameters allowing for either or both to be honored. batch_run = BatchRunner(MoneyModel, variable_params, fixed_params, iterations=5, max_steps=100, model_reporters={"Gini": compute_gini}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() return run_data
def aggregate_equality_justice(model): """ Evaluate a model by its alignment aggregated over equality and justice. """ params = { 'num_agents': model.num_agents, 'collecting_rates': model.collecting_rates, 'redistribution_rates': model.redistribution_rates, 'invest_rate': model.invest_rate, 'num_evaders': model.num_evaders, 'catch': model.catch, 'fine_rate': model.fine_rate } batch_run = BatchRunner( model_cls=Society, fixed_parameters=params, iterations=paths, max_steps=length, model_reporters={"Gini_wealth": compute_gini_wealth}, agent_reporters={ "Position": "position", "Evader": "is_evader" }, display_progress=False) batch_run.run_all() # get gini index info model_data = batch_run.get_model_vars_dataframe() f = (1 - 2 * model_data["Gini_wealth"]).values # get justice-related info agent_data = batch_run.get_agent_vars_dataframe() evaders_data = agent_data[agent_data["Evader"]] g = np.array([]) for run in evaders_data["Run"].unique(): evaders_info_run = evaders_data[evaders_data["Run"] == run] g = np.append(g, [ -1 + 2 * evaders_info_run["Position"].mean() / (model.num_agents - 1) ]) # get F function algn = 0 for x, y in zip(f, g): if x < 0 and y < 0: algn -= x * y else: algn += x * y return algn / paths
class TestBatchRunner(unittest.TestCase): """ Test that BatchRunner is running batches """ def setUp(self): """ Create the model and run it for some steps """ self.model_reporter = {"model": lambda m: m.model_param} self.agent_reporter = { "agent_id": lambda a: a.unique_id, "agent_val": lambda a: a.val } self.params = { 'model_param': range(3), 'agent_param': [1, 8], } self.iterations = 17 self.batch = BatchRunner(MockModel, self.params, iterations=self.iterations, max_steps=3, model_reporters=self.model_reporter, agent_reporters=self.agent_reporter) self.batch.run_all() def test_model_level_vars(self): """ Test that model-level variable collection is of the correct size """ model_vars = self.batch.get_model_vars_dataframe() rows = len(self.params['model_param']) * \ len(self.params['agent_param']) * \ self.iterations assert model_vars.shape == (rows, 4) def test_agent_level_vars(self): """ Test that agent-level variable collection is of the correct size """ agent_vars = self.batch.get_agent_vars_dataframe() rows = NUM_AGENTS * \ len(self.params['agent_param']) * \ len(self.params['model_param']) * \ self.iterations assert agent_vars.shape == (rows, 6)
class TestBatchRunner(unittest.TestCase): """ Test that BatchRunner is running batches """ def setUp(self): """ Create the model and run it for some steps """ self.model_reporter = {"model": lambda m: m.model_param} self.agent_reporter = { "agent_id": lambda a: a.unique_id, "agent_val": lambda a: a.val} self.params = { 'model_param': range(3), 'agent_param': [1, 8], } self.iterations = 17 self.batch = BatchRunner( MockModel, self.params, iterations=self.iterations, max_steps=3, model_reporters=self.model_reporter, agent_reporters=self.agent_reporter) self.batch.run_all() def test_model_level_vars(self): """ Test that model-level variable collection is of the correct size """ model_vars = self.batch.get_model_vars_dataframe() rows = len(self.params['model_param']) * \ len(self.params['agent_param']) * \ self.iterations assert model_vars.shape == (rows, 4) def test_agent_level_vars(self): """ Test that agent-level variable collection is of the correct size """ agent_vars = self.batch.get_agent_vars_dataframe() rows = NUM_AGENTS * \ len(self.params['agent_param']) * \ len(self.params['model_param']) * \ self.iterations assert agent_vars.shape == (rows, 6)
def experiment_1(replicates=40, max_steps=200, graph_type="None"): """ Experiment 1 - Run simulations of civil violence with network model. Function to generates data which are used for comparison of network topology influence on civil violence model. """ path = 'archives/saved_data_experiment_1_{0}_{1}'.format( int(time.time()), graph_type) configuration = read_configuration() model_params = {} model_params.update( configuration ) # Overwritten user parameters don't appear in the graphic interface model_params.update({'seed': None}) model_params['graph_type'] = graph_type model_params['max_iter'] = max_steps batch = BatchRunner( CivilViolenceModel, max_steps=max_steps, iterations=replicates, fixed_parameters=model_params, model_reporters={ 'All_Data': lambda m: m.datacollector, "QUIESCENT": lambda m: m.count_type_citizens("QUIESCENT"), "ACTIVE": lambda m: m.count_type_citizens("ACTIVE"), "JAILED": lambda m: m.count_type_citizens("JAILED"), "OUTBREAKS": lambda m: m.outbreaks }, # attempt all display_progress=True) batch.run_all() batch_df = batch.get_model_vars_dataframe() batch_df = batch_df.drop('All_Data', axis=1) data = batch_df run_data = batch.get_collector_model() with open(path, 'ab') as f: np.save(f, data) run_path = path + '_run' with open(run_path, 'ab') as f: np.save(f, run_data)
def perlocationDirection(direction): fixed_params = {"L": 25, "strength": 0.5, "direction": direction} variable_params = {"p": np.arange(0, 1.1, 0.1)} batch_run = BatchRunner(ForestFireModel, variable_params, fixed_params, iterations=100, model_reporters={"p*": compute_p}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() data = run_data.groupby('p').mean() return data["p*"]
def fitness(list_params): ''' list_params[0] is the number of the robots which has to be an integer list_params[1] is the radar radius which has to be an integer list_params[2] is the alpha - it represents how much the cost of the path influences the chosen cell by the robot list_params[3] is the gamma - it represents how much the utility of the neighborood is reduced when a robot reaches a cell ''' nrobots = int(round(list_params[0])) radar_radius = int(round(list_params[1])) alpha = list_params[2] gamma = list_params[3] fixed_params = { "nrobots": nrobots, "radar_radius": radar_radius, "ncells": 5, "obstacles_dist": 0.01, "wifi_range": 3, "alpha": alpha, "gamma" : gamma, "ninjured": 4, "dump_datas": False, "optimization_task": True, "load_file" : "" } print(str(list_params[0]) + " " + str(list_params[1]) + " " + str(list_params[2]) + " " + str(list_params[3])) batch_run = BatchRunner( ExplorationArea, None, fixed_params, iterations = 1, max_steps = 10000, model_reporters = {"step": lambda m: m.schedule.steps, "total_idling": lambda m: m.total_idling_time} ) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() # it is actually one row return run_data["step"].iloc[0] + (run_data["total_idling"].iloc[0] / nrobots)
def alignment_equality(model_cls, model_params, length, paths): """ Compute alignment with respect to equality. """ batch = BatchRunner( model_cls=model_cls, fixed_parameters=model_params, variable_parameters={'dummy': [0]}, iterations=paths, max_steps=length, model_reporters={ "all_steps": lambda m: m.data_collector.get_model_vars_dataframe() }, display_progress=True) batch.run_all() all_dfs = batch.get_model_vars_dataframe() algn = 0 for _, df in all_dfs['all_steps'].iteritems(): algn += df['pref_GI'][1:].mean() return algn / paths
def clusterStrength(strength): fixed_params = {"L": 25, "strength": strength, "direction": (1, 1)} variable_params = {"p": np.arange(0, 1.1, 0.1)} batch_run = BatchRunner( ForestFireModel, variable_params, fixed_params, iterations=100, model_reporters={"cluster": compute_cluster} ) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() data = run_data.groupby('p').mean() return data["cluster"]
def batch_run(width, height, elev_cells, veg_cells): fixed_params = {"width": width, "height": height, "elev": elev_cells, "veg": veg_cells, "N": 25} variable_params = {"N": range(10, 50, 1), "tracking_type": ['satellite', 'planes', 'helicopters', 'stations']} # variable_params = {"tracking_type": ['satellite', 'planes', 'helicopters', 'stations']} batch_run = BatchRunner(WolfModel, variable_params, fixed_params, iterations=30, max_steps=365, model_reporters={"pack_health": compute_pack_health, "track_error": compute_track_error_average}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() run_data.head() # plt.scatter(run_data.N, run_data.pack_health) plt.scatter(run_data.track_error, run_data.tracking_type) # plt.scatter(run_data.track_error, run_data.number_agents) plt.show()
def run_model(method): if method == "single": total_results = [] for x in range(1000): test = SocialDyn(4, 60, 10) #results = None print("RUN ", x) for i in range(20): #print ("STEP " , i, "\n\n\n") test.step() # results = test.datacollector.get_agent_vars_dataframe() total_results.append(results) res2 = pd.concat(total_results) res2.to_csv("single_results.csv") else: variable_params = { "width": range(10, 25, 5), "N": range(10, 50, 10), "R": range(10, 50, 10) } batch_run = BatchRunner(SocialDyn, fixed_parameters=None, variable_parameters=variable_params, iterations=5, max_steps=100, agent_reporters = {"Scaling A": 'scaling_a' ,\ "Scaling B" : 'scaling_b', \ "Capacity": 'capacity', \ "Land Owned": 'land_owned', \ "Conquered": 'conquered'}) batch_run.run_all() results = batch_run.get_agent_vars_dataframe() results.to_csv("results.csv")
def simulate(config, rollouts=10, seed=None): """Simulate repeated runs of the Schelling model for config. Parameters ---------- config: whynot.simulators.Schelling Configuration of the grid, agent properties, and model dynamics. rollouts: int How many times to run the model for the same configuration. seed: int (Optional) Seed all randomness in rollouts Returns ------- segregated_fraction: pd.Series What fraction of the agents are segrated at the end of the run for each rollout. """ model_reporters = {"Segregated_Agents": get_segregation} rng = np.random.RandomState(seed) param_sweep = BatchRunner( Schelling, fixed_parameters=dataclasses.asdict(config), max_steps=200, model_reporters=model_reporters, display_progress=False, # Use a different seed for each rollout variable_parameters={"seed": rng.randint(9999999, size=rollouts)}, # Single rollout for each seed iterations=1, ) param_sweep.run_all() dataframe = param_sweep.get_model_vars_dataframe() # Currently just reports the fraction segregated. return dataframe.Segregated_Agents.mean()
def job(problem): ''' Function that performs the OFAT job for one repetition, returns the data and problem it belongs to. ''' # Set the repetitions, the amount of steps, and the amount of distinct values per variable replicates = 1 max_steps = 4800 distinct_samples = 50 # Set the outputs model_reporters = { "Fish mean": lambda m: m.fish_mean, "Fish slope": lambda m: m.fish_slope, "Fish variance": lambda m: m.fish_variance, "Cumulative gain": lambda m: m.cumulative_gain } data = {} for i, var in enumerate(problem['names']): # Get the bounds for this variable and get <distinct_samples> samples within this space (uniform) samples = np.linspace(*problem['bounds'][i], num=distinct_samples, dtype=float) batch = BatchRunner(FishingModel, max_steps=max_steps, iterations=replicates, variable_parameters={var: samples}, model_reporters=model_reporters, display_progress=True) batch.run_all() data[var] = batch.get_model_vars_dataframe() return [data, problem]
def alignment_gain(model_cls, model_params, max_M, min_M, length, paths): """ Compute alignment with respect to personal gain. """ batch = BatchRunner( model_cls=model_cls, fixed_parameters=model_params, variable_parameters={'dummy': [0]}, iterations=paths, max_steps=length, model_reporters={ "all_steps": lambda m: m.data_collector.get_agent_vars_dataframe() }, display_progress=True) batch.run_all() all_dfs = batch.get_model_vars_dataframe() algn = 0 for _, df in all_dfs['all_steps'].iteritems(): df = df.xs('alpha', level='AgentID') gains = df['Wealth'].diff()[1:] pref_gain = (2 * gains - max_M - min_M) / (max_M - min_M) algn += pref_gain.mean() return algn / paths
def main(parameters, iterations=50, max_steps=None): model_reporters = { "Denounce": lambda m: m.count_type_citizens(m, 'denounce'), "Got attacked": lambda m: m.count_type_citizens(m, 'got_attacked'), "Females": lambda m: m.count_type_citizens(m, 'female'), "Stress": lambda m: m.count_stress(m) } if not max_steps: batch_run = BatchRunner(model.Home, variable_parameters=parameters, max_steps=10, iterations=iterations, model_reporters=model_reporters) else: batch_run = BatchRunner(model.Home, max_steps=max_steps, iterations=iterations, model_reporters=model_reporters) batch_run.run_all() batch_df = batch_run.get_model_vars_dataframe() return batch_df
def run_batch(N=[35], timer=[2], iterations=5, max_steps=100): """ Runs the simulation for every combination of N and timer N is the number of Cars on the road Timer is the amount of seconds the traffic light will wait to let agents through :param N: List of each number of initial cars on the road :param timer: List of each timing that needs to be simulated :param iterations: Integer of the amount of times every single combination needs to be repeated :param max_steps: Maximum amount of steps each simulation will run :return: DataFrame with the Average Velocity and Standard Deviation of the velocity for every combination """ # Parameters that won't be changed during any of the iterations fixed_params = {"length": 100, "lanes": 1} # The variables parameters will be invoke along with the fixed parameters allowing for either or both to be honored. variable_params = {"N": N, "timer": timer} batch_run = BatchRunner( RoadModel, variable_params, fixed_params, iterations=iterations, # Iterations per combination of parameters max_steps=max_steps, model_reporters={ "Average Velocity": get_average_velocity, # Average velocity per simulation "Standard Deviation": get_standard_deviation_velocity, "On Ramp Queue": get_on_ramp_queue, "Waiting Queue": get_waiting_queue }) batch_run.run_all() # Run all simulations run_data = batch_run.get_model_vars_dataframe( ) # Get DataFrame with collected data return run_data
def run_FIFA_model(): # We define our variables and bounds problem = { 'num_vars': 3, 'names': ['mu', 'sigma', 'earnings_ratio'], 'bounds': [[25000000, 50000000], [2500000, 5000000], [(1 / 20), (1 / 5)]] } # Set the repetitions, the amount of steps, and the amount of distinct values per variable replicates = 1 max_steps = 15 distinct_samples = 1 # Set the outputs (STILL NEED TO IMPLEMENT THIS IN ACTUAL MODEL) model_reporters = { "Manager assets": lambda m: m.schedule.get_manager_assets(), "Manager reputation": lambda m: m.schedule.get_manager_reputation() } data = {} for i, var in enumerate(problem['names']): # Get the bounds for this variable and get <distinct_samples> samples within this space (uniform) samples = np.linspace(*problem['bounds'][i], num=distinct_samples) batch = BatchRunner(FIFA_Simulation, max_steps=max_steps, iterations=replicates, variable_parameters={var: samples}, model_reporters=model_reporters, display_progress=True) batch.run_all() data[var] = batch.get_model_vars_dataframe() print(data)
# collect data self.datacollector.collect(self) # tell all the agents in the model to run their step function self.schedule.step() def run_model(self): for i in range(self.run_time): self.step() # parameter lists for each parameter to be tested in batch run br_params = {"init_people": [25, 100, 150, 200], "rich_threshold": [5, 10, 15, 20], "reserve_percent": [0, 50, 100]} br = BatchRunner(BankReservesModel, br_params, iterations=1, max_steps=1000, model_reporters={"Data Collector": lambda m: m.datacollector}) if __name__ == '__main__': br.run_all() br_df = br.get_model_vars_dataframe() br_step_data = pd.DataFrame() for i in range(len(br_df["Data Collector"])): if isinstance(br_df["Data Collector"][i], DataCollector): i_run_data = br_df["Data Collector"][i].get_model_vars_dataframe() br_step_data = br_step_data.append(i_run_data, ignore_index=True) br_step_data.to_csv("BankReservesModel_Step_Data.csv")