def simulate(
    model_path: str,
    all_setup_commands: List[Any],
    measurement_reporters: List[str],
    ticks_to_run: int,
    go_command: str,
    agg_func: Callable = np.mean,
) -> pd.DataFrame:
    """
    Creates a workspace for the NetLogo model and runs it by specified parameters, returning workspace results as pandas dataframe

    :param model_path: str file path to .nlogo model file.
    :param all_setup_commands: list of str NetLogo commands for simulation setup.
    :param measurement_reporters: list of str NetLogo reporters to measure simulation state per tick.
    :param ticks_to_run: int number of ticks to run simulation for.
    :param go_command: str NetLogo command to run simulation.
    :param agg_func: function use to aggregate results of replicates.
    :returns: pd.DataFrame of simulation fitness.
    """

    workspace = nl4py.create_headless_workspace()
    workspace.open_model(model_path)
    assert (
        type(all_setup_commands[0]) == str
        or type(all_setup_commands[0]) == list
    ), f"setup_commands must be of type List[str] or List[List[str]]!"
    if type(all_setup_commands[0]) == str:
        all_setup_commands = [all_setup_commands]
    if ticks_to_run < 0:
        # Run "forever" because no stop condition provided.
        ticks_to_run = math.pow(2, 31)
    all_results = []
    for setup_commands_replicate in all_setup_commands:
        for setup_command in setup_commands_replicate:
            workspace.command(setup_command)
        measures = workspace.schedule_reporters(
            measurement_reporters, 0, 1, ticks_to_run, go_command
        )
        measures = pd.DataFrame(measures, columns=measurement_reporters)
        all_results.append(OBJECTIVE_FUNCTION(measures))
    workspace.deleteWorkspace()
    return (agg_func(all_results),)
Example #2
0
 def test_schedule_reporters(self):
     """
     Tests if schedule_reporters works properly
     """
     try:
         nl4py.initialize(self.nl_path)
     except:
         self.fail("NL4Py.intialize() fails!")
     workspace = nl4py.create_headless_workspace()
     workspace.open_model(self.ethnocentrism_model)
     workspace.command("setup-full")
     tick_count = 10
     reporters = ["ticks", "count turtles"]
     results = workspace.schedule_reporters(reporters=reporters,
                                            start_at_tick=0,
                                            interval_ticks=1,
                                            stop_at_tick=tick_count,
                                            go_command='go')
     self.assertEqual(len(results), tick_count)
     for idx, result in enumerate(results):
         self.assertEqual(len(result), len(reporters))
         self.assertEqual(eval(result[0]), idx + 1)
Example #3
0
 def test_basic_model_execution(self):
     """
     Tests model running basics with the Ethnocentrism.nlogo model.
     """
     try:
         nl4py.initialize(self.nl_path)
     except:
         self.fail("NL4Py.intialize() fails!")
     workspace = nl4py.create_headless_workspace()
     workspace.open_model(self.ethnocentrism_model)
     workspace.command("setup-empty")
     ticks = workspace.report("ticks")
     turtle_count = workspace.report("count turtles")
     self.assertEqual(ticks, 0)
     self.assertEqual(turtle_count, 0)
     workspace.command("setup-full")
     ticks = workspace.report("ticks")
     turtle_count = workspace.report("count turtles")
     self.assertEqual(ticks, 0)
     self.assertGreater(turtle_count, 0)
     workspace.command("repeat 10 [go]")
     ticks = workspace.report("ticks")
     self.assertEqual(ticks, 10)
Example #4
0
def init(model_path):
    global netlogo
    netlogo = nl4py.create_headless_workspace()
    netlogo.open_model(model_path)
Example #5
0
def init(model_path):
    global workspace
    workspace = nl4py.create_headless_workspace()
    workspace.open_model(model_path)    
Example #6
0
            workspace.command('random-seed {}'.format(simulation_parameters[i]))
        else:
            workspace.command('set {0} {1}'.format(name, simulation_parameters[i]))
    workspace.command('set model-version "sheep-wolves-grass"')
    workspace.command('set initial-number-sheep 100')
    workspace.command('set initial-number-wolves 100')
    workspace.command('setup')
    newResults = workspace.schedule_reporters(["ticks",'count sheep','count wolves'], 0,1,500,"go") 
    aggregate_metric = calculate_population_stability(newResults)
    return aggregate_metric


'''
Next, we use NL4Py to read in the parameters from the NetLogo model's interface and populate the problem space, required by SALib for sensitivity analysis, with both the names and ranges, automatically.
'''
ws = nl4py.create_headless_workspace()
ws.open_model(model_path)
#Read in the parameter info with NL4Py functions and generate a SALib problem
problem = { 
  'num_vars': 6,
  'names': ['random-seed'],
  'bounds': [[1, 100000]] 
}
problem['names'].extend(ws.get_param_names()[:-2])
problem['bounds'].extend( [item[0::2] for item in ws.get_param_ranges()[:-2]])
#Remove the initial conditions from the problem space. These are set to fixed values in the simulate function
del problem['bounds'][problem['names'].index("initial-number-wolves")]
problem['names'].remove("initial-number-wolves")
del problem['bounds'][problem['names'].index("initial-number-sheep")]
problem['names'].remove("initial-number-sheep")
print("Problem parameter space: ")

print('\n2) Starting the model runs... ')

try:
	n = sys.argv[1]
except:
	print("ERROR: Please provide the number of concurrent model runs required as a commandline argument.")

model = "./Fire.nlogo"

print(f'\n2.1) Creating {n} NetLogo HeadlessWorkspaces with: workspace = nl4py.newNetLogoHeadlessWorkspace()')
print(f'\n2.2) Opening {n} copies of the model at {model} on the NetLogo HeadlessWorkspaces with: workspace.openModel("model")')
workspaces = []
for i in range(0,int(n)):
	workspaces.append(nl4py.create_headless_workspace())
	workspaces[i].open_model(model)
	
print("\n2.3) Get all workspaces back with: workspaces = nl4py.getAllExistingWorkspaces() \n\tSetting the parameters for all {n} models to random values with workspace.setParamsRandom()")
for workspace in workspaces:
	workspace.set_params_random()

print('\n2.4) Send setup and go commands to each model using: workspace.command("setup") and workspace.command("go") ')
for workspace in workspaces:
	workspace.command("setup")
	workspace.command("go")

print('\n2.5) Get back current state from all executing models using a NetLogo reporter: workspace.report("burned-trees")')
for workspace in workspaces:
	print(workspace.report("burned-trees"))