예제 #1
0
    def test_run_experiment(self):
        """
        Tests if run_experiment works properly
        """
        try:
            nl4py.initialize(self.nl_path)
        except:
            self.fail("NL4Py.intialize() fails!")

        def setup_model(run):
            return "setup-full"

        run_count = 20
        tick_count = 10
        reporters = ["ticks", "count turtles"]
        all_runs_results = nl4py.run_experiment(
            model_name=self.ethnocentrism_model,
            setup_callback=setup_model,
            setup_data=range(run_count),
            reporters=reporters,
            start_at_tick=0,
            interval_ticks=1,
            stop_at_tick=tick_count)
        self.assertEqual(all_runs_results.Run.unique().shape[0], run_count)
        for _, run_results in all_runs_results.groupby("Run"):
            self.assertEqual(
                run_results['Setup Commands'].iloc[0].replace(" ", ""),
                setup_model(0).replace(" ", ""))
            self.assertEqual(len(run_results['ticks'].unique()), tick_count)
            self.assertEqual(
                run_results.drop(['Run', 'Setup Commands'], axis=1).shape[1],
                len(reporters))
            self.assertEqual(
                run_results.ticks.astype(float).astype(int).tolist(),
                list(range(1, tick_count + 1)))
예제 #2
0
 def test_int(self):
     """
     Test that nl4py intializes
     """
     try:
         nl4py.initialize(self.nl_path)
     except:
         self.fail("NL4Py.intialize() fails!")
     try:
         nl4py.initialize(self.nl_path)
     except:
         self.fail("NL4Py.intialize() fails when called more than once!")
    def __init__(self,
                 netlogo_path: str,
                 model_path: str,
                 setup_commands: List[str],
                 measurement_reporters: List[str],
                 ticks_to_run: int,
                 go_command: str = 'go',
                 agg_func: Callable = np.mean) -> None:
        """
        Evolutionary model discovery experiment. Can be used to perform genetic programming 
        of NetLogo models and factor importance analysis of resulting data using random 
        forest importance analysis. 

        See: 
            Gunaratne, C., & Garibay, I. (2020). Evolutionary model discovery 
            3of causal factors behind the socio-agricultural behavior of the 
            Ancestral Pueblo. Plos one, 15(12), e0239922.

            Gunaratne, C., Rand, W., & Garibay, I. (2021). Inferring mechanisms 
            of response prioritization on social media under information overload. 
            Scientific reports, 11(1), 1-12.

        :param netlogo_path: str path to folder with NetLogo executable
        :param model_path: str path to NetLogo .nlogo model file
        :param setup_commands: List[str] or List[List[str]] of NetLogo commands to be executed on simulation setup. 
                                            List[List[str]] indicates simulation replicates per element of major list.
        :param measurement_reporters: List[str] of NetLogo reporters to be run per simulation
                                            executed per simulation tick and reported to 
                                            objective function callback
        :param ticks_to_run: int number of ticks to run each simulation for
        :param go_command: str command to run NetLogo simulations (default: 'go')
        :param agg_func: Callable function used to aggregate results of multiple replicates

        """
        # Initialize ABM
        self.model_init_data = {
            'model_path': model_path,
            'setup_commands': setup_commands,
            'measurement_commands': measurement_reporters,
            'ticks_to_run': ticks_to_run,
            'go_command': go_command,
            'agg_func': agg_func
        }
        self.replications = 1
        ModelFactors, netlogo_writer = self._parse_model_into_factors()
        # Starting NL4Py
        nl4py.initialize(netlogo_path)
        self.gp = SimpleDEAPGP(self.model_init_data, ModelFactors,
                               netlogo_writer)
        self.factor_scores_file_name = 'FactorScores.csv'
예제 #4
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)
예제 #5
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)
예제 #6
0
import os
import sys
import multiprocessing
import nl4py

netlogo_path = str(sys.argv[1])
model_path = str(sys.argv[2])
runs_needed = int(sys.argv[3])
ticks_needed = int(sys.argv[4])
nl4py.initialize(netlogo_path)


def init(model_path):
    global netlogo
    netlogo = nl4py.create_headless_workspace()
    netlogo.open_model(model_path)


def run_simulation_fire(runId):
    global netlogo
    # Same netlogo commands as used for the NL4Py evaluation
    netlogo.command("random-seed " + str(runId))
    netlogo.command("set dddddensity 57")
    netlogo.command('setup')
    measures = ['ticks', 'burned-trees']
    results = netlogo.schedule_reporters(measures, stopAtTick=ticks_needed)
    return results


def run_simulation_ethnocentrism(runId):
    global netlogo
### This file measures the execution time by NL4Py to run 200 runs of the
### Fire.nlogo model for 100 ticks or until stop condition is met
### To run provide the location of your NetLogo installation as a commandline argument
### Example: >>>python nl4py_gunaratne2018_5.1.1.py "C:/Program Files/NetLogo 6.0.2"

import time
import sys

import nl4py

nl4py.initialize(sys.argv[1])
workspace = nl4py.create_headless_workspace()
modelRuns = 100
ticks_to_run = 100
workspace.open_model("Models/Fire.nlogo")


def is_running(workspace):
    #print("{} {}".format(float(workspace.report("ticks")) ,
    #         str(workspace.report("not any? turtles")).lower()))
    return (float(workspace.report("ticks")) != ticks_to_run
            and str(workspace.report("not any? turtles")).lower() != "true")


for i in range(0, modelRuns):
    workspace.command("set density random 99")
    workspace.command("setup")
    workspace.command("repeat {} [go]".format(ticks_to_run))
    while is_running(workspace):
        time.sleep(0.001)
    r1 = workspace.report("burned-trees")