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 _mp_function(input): count, iter_args = input max_steps = iter_args[0] model_reporters = iter_args[1] vals = iter_args[2] vals[2] = int(vals[2]) variable_parameters = {} names = ['active_threshold_t', 'initial_legitimacy_l0', 'max_jail_term'] for name, val in zip(names, vals): variable_parameters[name] = val # dictionary batch = BatchRunner(CivilViolenceModel, max_steps=max_steps, variable_parameters={name: [] for name in names}, model_reporters=model_reporters) batch.run_iteration(variable_parameters, tuple(vals), count) iteration_data = batch.get_model_vars_dataframe() iteration_data[ 'Run'] = count # Don't know what causes this, but iteration number is not correctly filled return count, vals, iteration_data
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 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 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 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 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_FIFA_model(): # We define our variables and bounds problem = { 'num_vars': 3, 'names': ['sheep_reproduce', 'wolf_reproduce', 'wolf_gain_from_food'], 'bounds': [[0.01, 0.1], [0.01, 0.1], [10, 40]] } # Set the repetitions, the amount of steps, and the amount of distinct values per variable replicates = 10 max_steps = 100 distinct_samples = 10 # We get all our samples here param_values = saltelli.sample(problem, distinct_samples) # READ NOTE BELOW CODE batch = BatchRunner( FIFA_Simulation, max_steps=max_steps, variable_parameters={name: [] for name in problem['names']}, model_reporters=model_reporters) count = 0 for i in range(replicates): for vals in param_values: # Change parameters that should be integers vals = list(vals) vals[2] = int(vals[2]) # Transform to dict with parameter names and their values variable_parameters = {} for name, val in zip(problem['names'], vals): variable_parameters[name] = val batch.run_iteration(variable_parameters, tuple(vals), count) count += 1 clear_output() print( f'{count / (len(param_values) * (replicates)) * 100:.2f}% done' ) data = batch.get_model_vars_dataframe() print(data)
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
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 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
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 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 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 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 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)
def evaluate_equality(model): """ Evaluate a model by its alignment with respect to equality. """ 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}, display_progress=False) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() algn = 1 - 2 * run_data["Gini_wealth"].mean() return algn
import matplotlib.pyplot as plt from mesa.batchrunner import BatchRunner from ForestFireModel import ForestFireModel, compute_cluster import numpy as np if __name__ == '__main__': fixed_params = {"L": 100} variable_params = {"p": np.arange(0, 1.05, 0.05)} batch_run = BatchRunner(ForestFireModel, variable_params, fixed_params, iterations=3, model_reporters={"cluster": compute_cluster}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() data = run_data.groupby('p').mean() plt.plot(data['cluster'], '-o') plt.title(r'The biggest cluster dependent of $p$') plt.xlabel(r'$p$') plt.ylabel('average size of the biggest cluster') plt.show()
batch_run = BatchRunner(pm.ProxyModel, variable_parameters, parameters, iterations=2, max_steps=finalStep + 1, model_reporters={ "DataCollector": lambda ProxyModel: ProxyModel.datacollector }) batch_run.run_all() print('model runs complete') #batch_run.run_all() #print('model runs complete') ''' Batch run data ''' data_pre = batch_run.get_model_vars_dataframe() ''' Data Collector data (all steps, model level) ''' collector_data = pd.DataFrame() data_collect_interval = parameters["data_collect_interval"] for run in data_pre.Run: current_run = data_pre.DataCollector[run].get_model_vars_dataframe() current_run["Run"] = run current_run["Step"] = current_run.index * data_collect_interval collector_data = collector_data.append(current_run) ''' Full data (model level)''' modeldata = pd.merge(data_pre, collector_data, on="Run") modeldata = modeldata.drop("DataCollector", 1) modeldata.to_pickle("model_data.pkl") ''' Data Collector data (all steps, agent level) ''' collector_data = pd.DataFrame()
from SIR_Model.model import infection_model from mesa.batchrunner import BatchRunner #import matplotlib.pyplot as plt #import pandas fixed_params = { "hood": "Moore", "density": 0.1, "p_reinf": 0.01, "p_death": 0.02, "p_inf": 0.1, "p_rec": 0.1 } var_params = {"p_test": [0.5, 0.1, 0.15], "test_n": [True, False]} mod = infection_model() batch_runn = BatchRunner(infection_model, var_params, fixed_params, iterations=1, max_steps=250, model_reporters=mod.datacollector.model_reporters) batch_runn.run_all() coll = batch_runn.get_model_vars_dataframe() coll.to_csv("data.csv") #plt.scatter(coll."Fraction Infected", coll.
# Define the fixed parameters fixed_params = {"DSAs": "ALL", # ""CAOP,ILIP,INOP,MNOP", "output": False, "average_lifespan": 91, #"seed": s, "years": 20, "smart_listing": True, "advantage_prob": float(sys.argv[2])/100} # Define the varied parameters variable_params = {"seed": [s * 100 for s in range(5)]} # Create the batch runner param_run = BatchRunner(WaitingList, fixed_parameters=fixed_params, variable_parameters=variable_params, model_reporters=model_reporter) param_run.run_all() # Sort the columns c = ["DSAs","advantage_prob", "seed", "Primary_Transplants", "Alternate_Transplants", "Transplants", "Primary_Listings", "Alternate_Listings", "Count_Waiting", "Count_Deceased", "Count_Advantaged_Deceased", "Advantaged_Transplants", "Average_Wait", "Death_Region", "Primary_WL", "Primary_TX", "Wait_Rates", "Advantaged_Wait"] df = param_run.get_model_vars_dataframe() df[c].to_csv(sys.argv[3])
sum_a = 0 for player in self.players: sum_a += sum( [t.armies for t in self.get_territories_by_player(player)]) return sum_a / len(self.players) # parameter lists for each parameter to be tested in batch run # n_players, points_limit, strategy, goal br_params = { "n_players": [3], "points_limit": [150], "strategy": ["Random"], "goal": ["PP", "BE", "LA"] } br = BatchRunner(SPQRisiko, br_params, iterations=200, 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 = pandas.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("diff_strat_same_goal_150.csv")
# Change parameters that should be integers vals = list(vals) vals[1] = int(vals[1]) vals[0] = int(vals[0]) # Transform to dict with parameter names and their values variable_parameters = {} for name, val in zip(problem['names'], vals): variable_parameters[name] = val batch.run_iteration(variable_parameters, tuple(vals), count) count += 1 print(f'{count / (len(param_values) * (replicates)) * 100:.2f}% done') data = batch.get_model_vars_dataframe() print(data) Si_sheep = sobol.analyze(problem, data['Finished Cyan Walkers'].as_matrix(), print_to_console=True) Si_wolves = sobol.analyze(problem, data['Finished Red Walkers'].as_matrix(), print_to_console=True) def plot_index(s, params, inner_i, title=''): if inner_i == '2': p = len(params)
# 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")