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
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 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()
# "competition": np.linspace(0.1, 0.9, 9), "numAgents": 100, "talent_sd": 1, "goal_scale": 2, "goal_angle": np.pi / 4, "selection_pressure": 0.1, "practice_mutation_rate": np.pi / 90, "survival_uncertainty": 3 } # currently not in model (KT) print(parameters) 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"]
from mesa.batchrunner import BatchRunner from model import MoneyModel, compute_gini import matplotlib.pyplot as plt 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() run_data.head() plt.scatter(run_data.N, run_data.Gini) plt.xlabel("Max time steps") plt.ylabel("Gini coef") plt.show()
# 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")
if MP: batch_run = BatchRunnerMP( DeliveryModel, nr_processes=30, fixed_parameters=fixed_params, variable_parameters=variable_params, iterations=n_iterations, max_steps=max_steps, model_reporters=model_reporter_parameters, ) elif not MP: batch_run = BatchRunner( DeliveryModel, fixed_parameters=fixed_params, variable_parameters=variable_params, iterations=n_iterations, max_steps=max_steps, model_reporters=model_reporter_parameters, ) batch_run.run_all() # Plot data run_data = batch_run.get_model_vars_dataframe() # run_data.head() # run_data["Collective risk"] = run_data["Individual_risk_map"].apply( # lambda x: sum(sum(np.multiply(x, density_matrix_scaled_risk))) * 10000 * (3.8 * 4.6) / ( # width_risk * height_risk)) run_data["Collective risk"] = run_data.apply( lambda row: np.sum((np.multiply( row["Individual_risk_map"][0], row["area_risk_grid_m"] * row[
# run.py from model import MoneyModel from mesa.batchrunner import BatchRunner batch_run = BatchRunner( MoneyModel, variable_parameters={"num_agents": range(10, 500, 10)}, fixed_parameters={ "width": 10, "height": 10 }, iterations=1, max_steps=100, model_reporters=None, # {'agent_count': 'num'}, agent_reporters=None, # {'unique_id': 'unique_id', 'model': 'model'} display_progress=True) batch_run.run_all()
sys.path.append("/Users/rafael/Documents/GitHub/InCES-model/Industrial_communities") from mesa.datacollection import DataCollector from Model import Modelrun ##Batchrun from mesa.batchrunner import BatchRunner import pandas as pd #Run parameters m_step_data = pd.DataFrame() n_communities = [25] n_industries = [75] model_param = {"n_industries": n_industries, "n_communities": n_communities} #All variables in place - Everything that can be changed enters here #Batchrun settings br = BatchRunner(Modelrun, model_param, iterations = 500, max_steps = 20, model_reporters = {"Data Collector": lambda m: m.datacollector}) br.run_all() #Data generation m_df = br.get_model_vars_dataframe() m_step_data = pd.DataFrame() print(range(len(m_df["Data Collector"]))) for i in range(len(m_df["Data Collector"])): if isinstance(m_df["Data Collector"][i], DataCollector): i_run_data = m_df["Data Collector"][i].get_model_vars_dataframe() #a_run_data = a_df["data Collector"][i].get_agent_vars_dataframe() m_step_data = m_step_data.append(i_run_data, ignore_index=True) m_step_data.to_csv("Model_run_USA_S3-03.csv")
"align_min": 0.1, "wall_decay": 10, "wall_frict": 1, "form_shape": 1, "form_track": 1, "form_decay": 10, "wp_tolerance": 10, } if __name__ == "__main__": # repetitions of each setup iterations = 3 # run simulations batch_run = BatchRunner(BoidFlockers, params_variable, params_fixed, iterations=iterations, max_steps=250, model_reporters={"Data Collector": lambda m: m.datacollector}) batch_run.run_all() # get data of simulation runs # beware of this bug: column headers are sometimes wrong: https://github.com/projectmesa/mesa/issues/877 df_raw = batch_run.get_model_vars_dataframe() # list of parameters params = list(params_variable.keys()) # write raw data to csv files # df_raw.to_csv("data/runs.csv") # for i,d in enumerate(df_raw["Data Collector"]): # d.get_model_vars_dataframe().to_csv("data/run_{0}.csv".format(i)) # aggregate steps of each run
# 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])
# print(agent_wealth.head()) # # end_wealth = agent_wealth.xs(99, level="Step")["Wealth"] # end_wealth.hist(bins=range(agent_wealth.Wealth.max()+1)) # plt.show() # # one_agent_wealth = agent_wealth.xs(14, level="AgentID") # one_agent_wealth.Wealth.plot() # plt.show() fixed_params = {"width": 10, "height": 10} variable_params = {"N": range(10, 500, 10)} batch_run = BatchRunner(ParkingModel, 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() run_data.head() plt.scatter(run_data.N, run_data.Gini) plt.show() #Get the Agent DataCollection data_collector_agents = batch_run.get_collector_agents() print(data_collector_agents[(10, 2)]) #Get the Model DataCollection.
"n_init_arg": n_init_arg, "experiment_case": experiment_case, "sigma": 0.25, "arg_weight_vector": arg_weight_vector } variable_params = {"N": range(1, n_doctors, 1)} # Create dictionary where the diagnosis probabilities will be tracked dict_batch_collector = {"Final_decision": get_final_decision} for i, disease in enumerate(MedicalModel.LIST_OF_DISEASES.values()): disease_prob = partial(get_diagnosis_probabilities, i) dict_batch_collector[disease] = disease_prob batch_run = BatchRunner(MedicalModel, variable_params, fixed_params, iterations=n_batch_iter, max_steps=50, model_reporters=dict_batch_collector) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() # All this dictionary approach is in case we want to show something else than just counting the correct # answers.. # Create dict that contains the correct_diagnosis dictionaries keyed by the number of agents dict_correct_diagnosis = {} for i in range(1, n_doctors, 1): # Get the data frame relevant for N = i df = run_data[run_data.N == i] # for i number of doctors # Create dict that contains the tuples of probabilities for the diseases where the diagnosis was correct,
"firm_goods_price": [25], "firm_wage_rate": [68], } # Run for 6000 months plus 1000 months burn in # burn_in = 1000 # run_length = 6000 burn_in = 0 run_length = 1500 total_steps = (run_length + burn_in) * 21 br = BatchRunner( BaselineEconomyModel, br_params, iterations=1, max_steps=total_steps, model_reporters={"Data Collector": lambda m: m.datacollector}, ) # Drop the burn in period from the data collection if __name__ == "__main__": br.run_all() br_df = br.get_model_vars_dataframe() for i in range(len(br_df["Data Collector"])): hh_liquidity = br_df["household_liquidity"][i] firm_liquidity = br_df["firm_liquidity"][i] marker = "_hh{0}_f{1}_i{2}".format(hh_liquidity, firm_liquidity, i) if isinstance(br_df["Data Collector"][i], DataCollector): i_run_data = ( br_df["Data Collector"][i]
# grid size #"width": [100, 200, 300, 400, 500] # number of agents #"density": [1000, 2000, 3000, 4000, 5000] # density "width": [100] "density": [1000] } # assign active params model_params = dorm_model_params variable_params = dorm_variable_params batch_run = BatchRunner(Covid, variable_params, model_params, iterations=5, max_steps=200*dorm_model_params['day_steps'], model_reporters={"infected": getInfected, "days":getDays, "stats":getStats}) batch_run.run_all() data = batch_run.get_model_vars_dataframe() data['total_infected'] = data['infected']+data['initial_infected'] data['%'] = 100*data['total_infected']/model_params['density'] data.to_csv("agents_%d.csv"%int(time.time()), index=False) # #sdata = data[["initial_infected", "width", "days", "total_infected", "%"]] #sdata = sdata.groupby(['initial_infected', 'width']).mean() #sdata.to_csv("width_grouped_%d.csv"%int(time.time()), index=True)
variable_params = { "subset_no": np.arange(a), "type_no": (1, 2), } batch_run = BatchRunner( NormModel, variable_params, fixed_params, iterations=50, max_steps=255, model_reporters={ "PerHate": percent_haters, "NetworkType": network_type, "AveSensitivity": average_sensitivity, "MeanDeg": net_avg_deg, "MaxDeg": net_max_deg, "NetConnect": net_conn, "NetClust": net_clust, "FinalStep": final_step, }, # agent_reporters={"Hate": "behavior", # "Step": "step_no"} ) batch_run.run_all() # agent_data = batch_run.get_agent_vars_dataframe() run_data = batch_run.get_model_vars_dataframe() run_data.to_csv('counting_steps.csv')
iterations = 10 max_steps = 200 fixed_params = {'grass': True} variable_params = { 'initial_hunter': range(5, 30, 5), 'hunting_season_end': range(1, 11, 1) } batchrun = BatchRunner(model_cls=HuntersModel, fixed_parameters=fixed_params, variable_parameters=variable_params, iterations=iterations, max_steps=max_steps, model_reporters={ 'average_welfare': lambda m: m.average_welfare(), }, agent_reporters=None, display_progress=True) batchrun.run_all() #batchdata = batchrun.get_model_vars_dataframe() data2 = batchrun.get_model_vars_dataframe() #print(batchdata.head()) #batchdata.head() plt.scatter(data2.hunting_season_end, data2.average_welfare) plt.xlabel('hunting_season_end') plt.ylabel('average_welfare')
#regular batch runner input fixed_params = {"avg_node_degree":10, "num_nodes": 400, "initial_outbreak_size" : 1, "threshold" : 3 } variable_params = { "rewire_prob": [0.000001, 0.00001,0.0001,0.001,0.01,0.1,1] } # {"rewire_prob": range(0.05, 1.0, 0.05)} batch_run = BatchRunner(InfoSpread, variable_params, fixed_params, iterations=1, max_steps=100, model_reporters={"infection_list": infected_list}) #Batch runner GUI set up if __name__ == '__main__': # running the full iteration of model: round = variable parameter x rounds of iteration batch_run.run_all() # getting the pandas data frame run_data = batch_run.get_model_vars_dataframe() #data processing #This instance shows only the x = run_data.rewire_prob time = calculate_infection_time(run_data)
from mesa.batchrunner import BatchRunner from simulation import InteractionModel from data_collection import compute_average_performance fixed_params = { "beta": 0.0, "alpha": 0.5, "omega": 0.5, "N": 15, } variable_params = {"w": np.arange(0.01, 1.01, 0.01)} batch_run = BatchRunner(InteractionModel, variable_params, fixed_params, iterations=400, max_steps=300, model_reporters={"AP": compute_average_performance}) run_name = fr"run_iter_{batch_run.iterations}_rep_{datetime.now()}_beta_{fixed_params['beta']}" 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.show() plt.savefig("./data/" + run_name + ".png") run_data.to_csv("./data/" + run_name) df = data.loc[:, ['w', 'AP']]
#run.py from model_space import * #imports everything from that python code import matplotlib.pyplot as plt import numpy as np from mesa.batchrunner import BatchRunner from server import server fixed_params = {"width": 10, "height": 10} variable_params = {"N": range(10, 50, 10)} batch_run = BatchRunner(MoneyModel, variable_parameters=variable_params, fixed_parameters=fixed_params, iterations=5, max_steps=100, model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": "wealth"}, display_progress=True) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() run_data.head() run_data_agents = batch_run.get_agent_vars_dataframe() plt.scatter(run_data.N, run_data.Gini) server.port = 8521 server.launch() # =============================================================================
info_type = "blocked" #distributed blocked # these are the model params, tweak them to run different models #br_params = {"use_team": [False], "info_type":[info_type] } br_params = {"use_team": [True], "info_type":[info_type] } ''' 30 iterations: correct: 17 Wrong: 13 percent correct: 0.5666666666666667 ''' #they only get 30 tries for the task br = BatchRunner(RadarTask, br_params, iterations=3, max_steps=200, model_reporters={"Data Collector": lambda m: m.datacollector}) if __name__ == '__main__': print('--------------------------------------------------------------') print('TALLY HO') print('--------------------------------------------------------------') 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() #print("IRUNDATA") #print(i_run_data)
#%% fixed_params = { "width": 100, "height": 100, "vision": 4, "separation": 2, "size_factor": 2, 'speed': 0.1 } variable_params = {"rate": [2, 4]} batch_run = BatchRunner(BoidFlockers, variable_params, fixed_params, iterations=1, max_steps=200, model_reporters={"Data Collector": lambda m: \ m.datacollector}, ) #%% #%% batch_run.run_all() #%% #%% run_data = batch_run.get_model_vars_dataframe() br_step_data = pd.DataFrame() for i in range(len(run_data["Data Collector"])): if isinstance(run_data["Data Collector"][i], DataCollector):
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.
total_costs_without_trading = \ model.total_profit_without_trading_seller + model.total_profit_without_trading_buyer total_costs_with_trading = \ model.total_profit_with_trading_seller + model.total_profit_with_trading_buyer money_saved = total_costs_without_trading - total_costs_with_trading return money_saved / total_costs_without_trading fixed_params = {'width': 1, 'height': 1} variable_params = {'seller_num': range(2, 3), 'buyer_num': range(2, 3)} # fixed_params = {'width': 1, 'height': 1, 'num_per_agent': 2} # variable_params = None batch_run = BatchRunner(WasteModel, variable_params, fixed_params, iterations=2, max_steps=3, model_reporters={'Recycling_Rate': compute_recycling_rate, 'Seller_Savings': compute_seller_savings, 'Buyer_Savings': compute_buyer_savings, 'Overall_Savings': compute_overall_savings }) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() run_data.head() plot_list = list(range(1, 3)) plt.scatter(plot_list, run_data.Recycling_Rate) plt.scatter(plot_list, run_data.Seller_Savings) plt.scatter(plot_list, run_data.Buyer_Savings) plt.scatter(plot_list, run_data.Overall_Savings) # plt.show()
filename, n_civilians, step_civilians, n_stewards, step_stewards, info_exchange, fire_init = parse_arguments( ) fixed_params = { "civil_info_exchange": info_exchange, "fire_x": fire_init[0], "fire_y": fire_init[1], } variable_params = { "N": range(100, n_civilians, step_civilians), "K": range(0, n_stewards, step_stewards), } batch_run = BatchRunner( EvacuationModel, variable_params, fixed_params, iterations=10, # For now, then could be 100 max_steps=500, model_reporters={ "Agents saved": get_agents_saved, "List saved agents": get_list_saved_agents, "List dead agents": get_list_dead_agents }) batch_run.run_all() batch_dir = Path.cwd() / "batch_results" if not batch_dir.exists(): Path.mkdir(batch_dir) run_data = batch_run.get_model_vars_dataframe() run_data.to_csv(path_or_buf=(batch_dir / filename))
results_adoption = model.dc_adoption.get_model_vars_dataframe() results_adoption.plot() # Now let's do it with batch runs: # In[9]: #height, width, wus, and density are fixed fixed_params = {"height": 50, "width": 50, "density": 0.7, "wus": 1000, "wts": 1000, "wms":1000, "td":10000, "ve": 0} # Vary wms, wts, wus variable_params = {"ae": np.arange(0.5, 0.8, 0.01)} model_reporter={"AlgoEffect": compute_algo_effect} param_run = BatchRunner(HITLAdopt, variable_parameters=variable_params, fixed_parameters=fixed_params, max_steps = 100, model_reporters=model_reporter) # In[10]: param_run.run_all() # In[11]: df = param_run.get_model_vars_dataframe() df.head()
# Set all parameters that have to be varied in the experiments variable_params = set_variable_params() # Set all parameters that are not varied and thus fixed for all experiments fixed_params = set_fixed_params() # Prepare the batch of experiments batch_run = BatchRunner(AgSimulator, variable_params, fixed_params, iterations=1, max_steps=6500, model_reporters={ "harvest_score": get_harvest_score, "total_steps_dehydrated": get_total_steps_dehydrated, "total_steps_sick": get_total_steps_sick, "total_steps_weeds": get_total_steps_weeds, }, agent_reporters={"pos": "pos"} ) # Run the batch of experiments batch_run.run_all() # %% # Get all agent data # agent_data = batch_run.get_agent_vars_dataframe() # print(agent_data.head())
# iterations += step_it # batch_run = BatchRunner(FormationFlying, # fixed_parameters=model_params, # variable_parameters=variable_params, # iterations=iterations, # max_steps=max_steps, # model_reporters=model_reporter_parameters, # agent_reporters=agent_reporter_parameters # ) # # batch_run.run_all() # # run_data = batch_run.get_model_vars_dataframe() # run_data.head() # # run_data.to_csv(f"C:\\Users\\afons\\Desktop\\Simulations\\coefficient of variance\\fuel_saved\\B{i}") batch_run = BatchRunner(FormationFlying, fixed_parameters=model_params, variable_parameters=variable_params, iterations=n_iterations, max_steps=max_steps, model_reporters=model_reporter_parameters, agent_reporters=agent_reporter_parameters) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() run_data.head() run_data.to_csv(r"C:\Users\afons\Desktop\Simulations\compare\middle_point")
"n_offenders": 15, # Number of offenders "n_criminal_generators": 3, # Number of criminal generators "r_criminal_generators": 4, # Radius of criminal generators # "max_cp": 0.5, # Maximum criminal preference "pop_count": 335000, # Population count "width": 50, "height": 50 } # variable_params = None variable_params = {"max_cp": np.arange(0, 1.1, 0.1)} batch_run = BatchRunner( Model, variable_params, fixed_params, iterations=7, # Number of iterations the model runs for max_steps=100, model_reporters={"crimerate": compute_crime_rate}) batch_run.run_all() run_data = batch_run.get_model_vars_dataframe() print(run_data) reduced_data = run_data.loc[:, ["max_cp", "crimerate"]] reduced_data = reduced_data.groupby(["max_cp"], as_index=False).max() x = list(round(i, 2) for i in reduced_data.max_cp) y = list(reduced_data.crimerate) x_pos = [i for i, _ in enumerate(x)]
def __init__(self, N): self.running = True self.num_agents = N self.schedule = \ RandomActivation(self) for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) self.collector = DataCollector(agent_reporters={"Wealth": "wealth"}) def step(self): self.collector.collect(self) self.schedule.step() # Perform single run model = MoneyModel(10) for i in range(10): model.step() # Perform multiple runs variable_params = {"N": range(10, 500, 10)} batch_run = BatchRunner(MoneyModel, variable_params, iterations=5, max_steps=10, agent_reporters={"Wealth": "wealth"}) batch_run.run_all()
# -*- coding: utf-8 -*- #runBatch.py: prepares and executes the batch run from FoodModel import FoodModel,Agent,Food,sumEnergy from mesa.batchrunner import BatchRunner import matplotlib.pyplot as plt # Define the parameters (here we only have variable parameters) fixed_params ={} variable_params = {"N":range(1,9,1)} # Setup the batch-run batch_run = BatchRunner(FoodModel, # Model selection fixed_parameters=fixed_params, # Select fixed parameters variable_parameters=variable_params, # Select variable parameters iterations=25, # How many identical runs? max_steps=1000, #Max number of ticks (to avoid never-ending-runs) model_reporters={"Energy":sumEnergy}) #Indicate what information to collect batch_run.run_all() #Actually execute the batch run # post-simulation: use of the data (standard python programming) run_data = batch_run.get_model_vars_dataframe() print(run_data.head()) print(run_data) plt.scatter(run_data.N,run_data.Energy) plt.show()
"impactParticipants": [.04], "impactCompetitors": [.08], "impactPredators": [.08], "initial_predators": [3], "initial_competitors": [5], } model_paramsFixed = { "initial_explorers": 5, 'visibility': False, } nombreCSV = "model_paramsTEx1cond5" + ".csv" br = BatchRunner(PsyRTSGame, variable_parameters=model_paramsTEx1cond5, fixed_parameters=model_paramsFixed, iterations=50, max_steps=150, 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) concat = br_step_data df = concat
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()
# 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")