def launch_netlogo(): global netlogo print("Trying to start netlogo, please wait...") try: sistema = platform.system() if (sistema == 'Windows'): netlogo = pyNetLogo.NetLogoLink(gui=netlogo_gui) elif (sistema == 'Linux'): netlogo = pyNetLogo.NetLogoLink(gui=netlogo_gui, netlogo_home='NetLogo 6.0.4/') else: netlogo = pyNetLogo.NetLogoLink(gui=netlogo_gui) print("Done!") except Exception as e: print("Ocurrio un problema al levantar netlogo!") print(e)
def init_model(): netlogo = pyNetLogo.NetLogoLink( gui=False, netlogo_home="/home/lokitekone/NetLogo 6.1.1", netlogo_version="6.1") netlogo.load_model('./Virus-Parameter-Learning.nlogo') return netlogo
def CONNECT_NL(path): # To connect netlogo import pyNetLogo netlogo = pyNetLogo.NetLogoLink() netlogo.load_model(path) return netlogo
def run(self, index): print("set id " + str(index)) netlogo = pyNetLogo.NetLogoLink(gui=False) netlogo.load_model(r'simulacion.nlogo') netlogo.command("set id " + str(index)) netlogo.command(self.comandos[0] + str(self.poblacion[index].infection_rate)) netlogo.command( self.comandos[1] + str(self.poblacion[index].initial_probability_of_death)) netlogo.command(self.comandos[2] + str(self.poblacion[index]. initial_probability_of_chromatin_condensation)) netlogo.command(self.comandos[3] + str(self.poblacion[index].mNeptune_effectiveness)) netlogo.command(self.comandos[4] + str(self.poblacion[index].viral_reach)) netlogo.command( self.comandos[5] + str(self.poblacion[index].initial_infected_cell_percentage)) netlogo.command(self.comandos[6] + str(self.poblacion[index].cell_density)) netlogo.command('setup') netlogo.repeat_command('go', 3) print("Finished Model process" + str(index))
def fire_up(s, gui=True): # takes the size of the grid and GUI import pyNetLogo import os #this finds the location of the project folder and your netlogo folder so we can both work on it, I kept the old code in case this doesnt work for you os.system( "find /home -type d -name 'autonomous_routing' > find_project_folder.txt" ) os.system( "find /home -type d -name 'netlogo-5.3-64' > find_netlogo_folder.txt") with open("find_project_folder.txt") as f: for line in f: autonomous_routing = line.strip() + "/mars.nlogo" with open("find_netlogo_folder.txt") as f: for line in f: netlogo_location = line.strip() + "/app/" os.system("rm find_project_folder.txt") os.system("rm find_netlogo_folder.txt") netlogo = pyNetLogo.NetLogoLink(gui=gui, netlogo_home=netlogo_location, netlogo_version='5') #path to Netlogo installation (jar files, note the "/app") #netlogo version, either '5' or '6' netlogo.load_model(autonomous_routing) #path to the model #path to the model # adjusts the grid size netlogo.command('set grid-size %d' % (s)) # setup the grid, origins, and destinations netlogo.command('setup') return netlogo
def _run_model(self, B_0, activation_energy, energy_tissue, energy_food, energy_synthesis, half_saturation_coeff, max_ingestion_rate, mass_birth, mass_cocoon, mass_maximum, mass_sexual_maturity, growth_constant, max_reproduction_rate, speed, k): ## Initiate netlogo model netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home=netlogo_home, netlogo_version='5') netlogo.load_model('src/models/g2002_1.nlogo') ## Set parameter values netlogo.command("set B_0 " + str(B_0)) netlogo.command("set activation_energy " + str(activation_energy)) netlogo.command("set energy_tissue " + str(energy_tissue)) netlogo.command("set energy_food " + str(energy_food)) netlogo.command("set energy_synthesis " + str(energy_synthesis)) netlogo.command("set half_saturation_coef " + str(half_saturation_coeff)) netlogo.command("set max_ingestion_rate " + str(max_ingestion_rate)) netlogo.command("set mass_birth " + str(mass_birth)) netlogo.command("set mass_cocoon " + str(mass_cocoon)) netlogo.command("set mass_maximum " + str(mass_maximum)) netlogo.command("set mass_sexual_maturity " + str(mass_sexual_maturity)) netlogo.command("set growth_constant " + str(growth_constant)) netlogo.command("set max_reproduction_rate " + str(max_reproduction_rate)) netlogo.command("set speed " + str(speed)) ## Simulate and save results result = [] for ind in range(k): result_tmp = np.zeros(shape=(27)) netlogo.command("setup") result_tmp[0] = netlogo.report("mean-mass") for t in range(1, 27): netlogo.command("repeat 7 [go]") result_tmp[t] = netlogo.report("mean-mass") result.append(result_tmp.flatten()) netlogo.kill_workspace() return result
def eseguiSimulazione(x): #setup global netlogo, parameters_config, netlogo_path, model_path, simulation_number save_results = [] i = 0 if netlogo is None: #open dialog with netlogo netlogo = pyNetLogo.NetLogoLink(gui='false', netlogo_home=netlogo_path, netlogo_version='5') netlogo.load_model(model_path) #set scenario netlogo.command('set selectScenario "dump" ') while (i < simulation_number): cmd = "setup read-from-string substring date-and-time 9 12" netlogo.command(cmd) #set parameters count = 0 # used for visual debug #optimized_params={} for key, value in parameters_config.paramBoundaries.items(): cmd = "set " + key + " " + str(x[count]) netlogo.command(cmd) #used for debug #optimized_params[key]=x[count] count += 1 #initial target found target_found = netlogo.report('percentageTgtsFound') tick_number = 0 #continue simulation until stop condition while (target_found <= 95): if (tick_number > 1000): tick_number = 1000 break netlogo.repeat_command("go", 1) target_found = netlogo.report('percentageTgtsFound') tick_number = netlogo.report('ticks') #DEBUG #print("[ "+mp.current_process().name+"] ticks simulazione_"+str(i+1)+"= "+str(tick_number)) # append simulation results for AVG save_results.append(tick_number) i += 1 sum_avg = 0 for val in save_results: sum_avg += val #find AVG tick_number = round((sum_avg / simulation_number), 1) print("[ " + mp.current_process().name + " ] avg ticks simulation: " + str(tick_number)) #netlogo.kill_workspace() return tick_number
def run_61(): print("trying 6.1") link = pyNetLogo.NetLogoLink() model_file = os.path.join( link.netlogo_home, 'models/Sample Models/Biology/Wolf Sheep Predation.nlogo') print(os.path.exists(model_file)) link.load_model(model_file)
def run_53(): print("trying 5.3") link = pyNetLogo.NetLogoLink(netlogo_home='/Applications/Netlogo 5.3.1') model_file = os.path.join( link.netlogo_home, 'models/Sample Models/Biology/Wolf Sheep Predation.nlogo') print(os.path.exists(model_file)) link.load_model(model_file)
def init_worker(): global netlogo, netlogo_path, model_path #open dialog with netlogo netlogo = pyNetLogo.NetLogoLink(gui='false', netlogo_home=netlogo_path, netlogo_version='5') netlogo.load_model(model_path) #set scenario netlogo.command('set selectScenario "dump" ')
def initializer(modelfile): '''initialize a subprocess Parameters ---------- modelfile : str ''' # we need to set the instantiated netlogo # link as a global so run_simulation can # use it global netlogo netlogo = pyNetLogo.NetLogoLink(gui=False) netlogo.load_model(modelfile)
def run_experiment(parameters): workspace = pyNetLogo.NetLogoLink(gui=False) workspace.load_model(parameters['document_uri']) setup_netlogo_env(parameters, workspace) workspace.command("setup") finished = 0 MSD = [] time_list = [] load_time = [] free_time = [] stop_time = [] autonomy_value = [] autonomy_per_time_value = [] while finished == 0: workspace.command("repeat 100 [ go ]") time = workspace.report("time") time_list.append(time) MSD.append(workspace.report('MSD')) finished = workspace.report("finished") load_time.append( workspace.report("map [x -> [load_time] of x] ( sort shuttles )")) free_time.append( workspace.report("map [x -> [free_time] of x] ( sort shuttles )")) stop_time.append( workspace.report("map [x -> [stop_time] of x] ( sort shuttles )")) autonomy_value.append(workspace.report("autonomy_value")) autonomy_per_time_value.append( workspace.report("autonomy_value / time")) print('Time' + str(time)) print('running...') Graph_utils.plot_shuttles(stop_time, free_time, load_time, time_list) Graph_utils.simple_plot(autonomy_value, time_list, 'Autonomy') Graph_utils.simple_plot(autonomy_per_time_value, time_list, 'Autonomy per time') Graph_utils.simple_plot(autonomy_per_time_value, autonomy_value, 'Autonomy per time vs Autonomy')
def model_init(self, policy, *args): ''' Method called to initialize the model. :param policy: policy to be run. :param args: arguments to be used by model_init. This gives users the ability to pass any additional arguments. ''' super(ToyModel_MSI, self).model_init(policy) os.chdir(self.working_directory) logging.basicConfig(level=logging.INFO) self.dirs = [self.working_directory + r'/output'] self.netlogo = pyNetLogo.NetLogoLink(self.GUI) logging.info('NetLogo started') self.netlogo.load_model(self.netlogo_filename) logging.info('Model opened')
def initializer(modelfile): '''initialize a subprocess Parameters ---------- modelfile : str ''' # we need to set the instantiated netlogo # link as a global so run_simulation can # use it global netlogo netlogo = pyNetLogo.NetLogoLink( gui=False, #netlogo_home="/home/carrknight/Downloads/netlogo-5.3.1-64", netlogo_home="/opt/netlogo", #netlogo_version="5" netlogo_version="6.1") netlogo.load_model(modelfile)
def _run_model(self, H, Am, AE, PM, I, k): netlogo = pyNetLogo.NetLogoLink( gui=False, netlogo_home='/home/rito/netlogo-5.3.1-64', netlogo_version='5') #netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home='/home/stats/stsqgk/netlogo-5.3.1-64', netlogo_version='5') netlogo.load_model('Bass.nlogo') # Setup the model netlogo.command("setup") # Set up the input values of the parameters netlogo.command("set H " + str(H)) netlogo.command("set Am " + str(Am)) netlogo.command("set AE " + str(AE)) netlogo.command("set PM " + str(PM)) netlogo.command("set I " + str(I * 1e+13)) ## Simulate and save results results = [] for ind in range(k): # spin-up the model netlogo.command("spin-up") # run the model sufficient no. times netlogo.command("go-ABC") tmp = [] # the results are collected within NetLogo tmp = tmp + list(netlogo.report("ABC_SSB")) tmp = tmp + list(netlogo.report("ABC_Rec")) for ind in range(30): tmp = tmp + list(netlogo.report("ABC_M" + str(ind))) for ind in range(30): tmp = tmp + list(netlogo.report("ABC_N" + str(ind))) results.append(np.array(tmp)) netlogo.kill_workspace() return results
def eseguiSimulazione(x): #setup global netlogo, parameters_config, netlogo_path, model_path if netlogo is None: #open dialog with netlogo netlogo = pyNetLogo.NetLogoLink(gui='false', netlogo_home=netlogo_path, netlogo_version='5') netlogo.load_model(model_path) #set scenario netlogo.command('set selectScenario "dump" ') cmd = "setup read-from-string substring date-and-time 9 12" netlogo.command(cmd) #set parameters count = 0 for key, value in parameters_config.paramBoundaries.items(): cmd = "set " + key + " " + str(x[count]) netlogo.command(cmd) count += 1 #initial target found target_found = netlogo.report('percentageTgtsFound') tick_number = 0 #continue simulation until stop condition while (target_found <= 95): if (tick_number > 1000): tick_number = 1000 break netlogo.repeat_command("go", 1) target_found = netlogo.report('percentageTgtsFound') tick_number = netlogo.report('ticks') # debug print('ticks: ' + str(tick_number)) return tick_number
def model_init(self, policy): ''' Method called to initialize the model. Parameters ---------- policy : dict policy to be run. ''' super(BaseNetLogoModel, self).model_init(policy) if not hasattr(self, 'netlogo'): _logger.debug("trying to start NetLogo") self.netlogo = pyNetLogo.NetLogoLink( netlogo_home=self.netlogo_home, netlogo_version=self.netlogo_version, jvm_home=self.jvm_home, gui=self.gui, jvmargs=self.jvmargs) _logger.debug("netlogo started") path = os.path.join(self.working_directory, self.model_file) self.netlogo.load_model(path) _logger.debug("model opened")
# Run for 100 ticks and return the number of sheep and # wolf agents at each time step counts = netlogo.repeat_report(['count sheep', 'count wolves'], 100) results = pd.Series([ counts['count sheep'].values.mean(), counts['count wolves'].values.mean() ], index=['Avg. sheep', 'Avg. wolves']) return results if __name__ == '__main__': modelfile = os.path.abspath('./models/Wolf Sheep Predation_v6.nlogo') netlogo = pyNetLogo.NetLogoLink(gui=False) netlogo.load_model(modelfile) problem = { 'num_vars': 6, 'names': [ 'random-seed', 'grass-regrowth-time', 'sheep-gain-from-food', 'wolf-gain-from-food', 'sheep-reproduce', 'wolf-reproduce' ], 'bounds': [[1, 100000], [20., 40.], [2., 8.], [16., 32.], [2., 8.], [2., 8.]] } n = 1000 param_values = saltelli.sample(problem, n, calc_second_order=True)
''' from __future__ import (unicode_literals, print_function, absolute_import, division) import logging import sys import pyNetLogo # Created on 1 Nov 2016 # # .. codeauthor::jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl> __all__ = [] # logging root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stderr) ch.setLevel(logging.DEBUG) formatter = logging.Formatter(' %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) # on mac there is a stupid issue with getting the default jvm path # this is related to some mac bug in java 8 jvm_home = '/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/jre/lib/server/libjvm.dylib' link = pyNetLogo.NetLogoLink(jvm_home=jvm_home) link.load_model('Wolf Sheep Predation.nlogo')
def run_experiment(parameters): workspace = pyNetLogo.NetLogoLink(gui=False) workspace.load_model(parameters['document_uri']) setup_netlogo_env(parameters, workspace) workspace.command("setup") finished = 0 MSD = [] time_list = [] load_time = [] free_time = [] stop_time = [] autonomy_value = [] autonomy_per_time_value = [] while finished == 0: workspace.command("repeat 10 [ go ]") time = workspace.report("time") autonomy_value.append(workspace.report("autonomy_value")) autonomy_per_time_value.append(autonomy_value[-1] / time) MSD.append(workspace.report('MSD')) #method = OnOffController( # autonomy_per_time_value[-1], # "bio", # parameters['setpoint'], # parameters['range'] #) method = FuzzyController(autonomy_per_time_value[-1], MSD[-1], time) workspace.command("set dispatch_method \"" + method + "\"") time_list.append(time) finished = workspace.report("finished") load_time.append( workspace.report("map [x -> [load_time] of x] ( sort shuttles )")) free_time.append( workspace.report("map [x -> [free_time] of x] ( sort shuttles )")) stop_time.append( workspace.report("map [x -> [stop_time] of x] ( sort shuttles )")) print('Time' + str(time)) print('running...') debut_scenario = workspace.report("debut_scenario") fin_scenario = workspace.report("fin_scenario") last_product = workspace.report("last_product_time") shuttles = workspace.report("count shuttles") # Graph_utils.plot_shuttles(stop_time, free_time, load_time, time_list) for index in range(0, int(shuttles)): Graph_utils.plot_shuttles2( Graph_utils.transform_shuttle_list(stop_time, time_list, index), Graph_utils.transform_shuttle_list(free_time, time_list, index), Graph_utils.transform_shuttle_list(load_time, time_list, index), time_list) Graph_utils.simple_plot(autonomy_value, time_list, 'Autonomy', debut_scenario, fin_scenario, last_product) Graph_utils.simple_plot(autonomy_per_time_value, time_list, 'Autonomy per time', debut_scenario, fin_scenario, last_product) Graph_utils.simple_plot(MSD, time_list, 'MSD', debut_scenario, fin_scenario, last_product) Graph_utils.simple_plot(autonomy_per_time_value, autonomy_value, 'Autonomy per time vs Autonomy') print(MSD[-1])
def calculate_likelihood_dream_wm(parameters): global init if init: print("Setting up packages and Netlogo model") # import packages - again, required due to windows forking. global np from pydream.parameters import SampledParam global pyNetLogo import pyNetLogo global netlogo netlogo = pyNetLogo.NetLogoLink(gui=False) from collections import Counter global math import math global pd import pandas as pd global enum import enum global Counter global namedtuple from collections import namedtuple, Counter def init_WindMasterModel(): netlogo.load_model('../model/prototype/windmaster.nlogo') for entry in ["provideWarnings?", "verbose?", "debug?"]: netlogo.command(f"set {entry} false") netlogo.command("setup") global get_introductionyear def get_introductionyear(): data = pd.read_csv( '../model/prototype/data/yearOfTechnologyIntroduction.csv', header=None) year_of_introduction = {} for name, group in data.groupby(0): group = group.copy() try: assettype = AssetTypes[name.upper()] except KeyError: pass else: group.loc[:, 1] = group.loc[:, 1].apply(str.upper) data = group.loc[:, 1:].set_index(1) year_of_introduction[assettype.name] = data return year_of_introduction global yearofintroduction yearofintroduction = get_introductionyear() global create_paths def create_paths(paths, techEnum, assetTypeName): path_mapping = {} for path in paths.values: path = [ entry for (entry, isnnan) in zip(path, pd.isnull(path)) if not isnnan ] path = [techEnum[entry.upper()] for entry in path] name = '' for entry in path: if name: name += '_' name += entry.name.upper() path_mapping[name] = path name = "{}TechnologyPaths".format(assetTypeName) PathEnum = enum.Enum(name, path_mapping) globals()[name] = PathEnum return PathEnum global generate_enums def generate_enums(): assetTypes = pd.read_csv('../model/prototype/data/assetTypes.csv', header=None) AssetTypes = enum.Enum( "AssetTypes", {n[0].upper(): i for i, n in enumerate(assetTypes.values)}) globals()[AssetTypes.__name__] = AssetTypes assetTypeTechnologies = pd.read_csv( '../model/prototype/data/assetTypeTechnologies.csv', header=None) technologyPaths = pd.read_csv( '../model/prototype/data/technologyPaths.csv', header=None, index_col=0) technologyPaths.dropna(how="all", inplace=True) technologyPaths.index = [c.upper() for c in technologyPaths.index] asset_paths = {} for assetType in AssetTypes: if assetType.name != 'SMR': assetTypeName = assetType.name.lower().capitalize() name = f"{assetTypeName}Technologies" else: assetTypeName = assetType.name name = f"{assetTypeName}Technologies" values = assetTypeTechnologies.loc[ assetType.value, :].dropna().values techEnum = enum.Enum( name, {n.upper(): i for i, n in enumerate(values)}) globals()[name] = techEnum try: paths = technologyPaths.loc[assetType.name] except KeyError: continue if isinstance(paths, pd.Series): continue else: PathEnum = create_paths(paths, techEnum, assetTypeName) asset_paths[assetType.name] = PathEnum return asset_paths global SynethicFuelLocationsEnum class SynethicFuelLocationsEnum(enum.Enum): MAASVLAKTE = 'D34' BOTLEK = 'D35' global paths paths = generate_enums() global get_year_of_availability def get_year_of_availability(assettype, technology): data = yearofintroduction[assettype.name] a = data.loc[technology.name] try: year = int(a.values[0]) except ValueError: year = 2040 return year global get_assets def get_assets(): all_assets = pd.read_csv( "../model/prototype/data/conversionAssets.csv", header=17, usecols=[ "Conversion asset ID [string] – Must be unique", "assetTypes" ]) assetids = {} for name, group in all_assets.groupby('assetTypes'): try: assettype = AssetTypes[name.upper()] except KeyError: pass else: assetids[assettype.name] = group[ "Conversion asset ID [string] – Must be unique"].values return assetids global assets assets = get_assets() global create_event def create_event(asset_id, assettype, technology, year, volume=-1): return asset_id, assettype.value, technology.value, year, volume global sigmoid def sigmoid(k, q, b, time): ''' Parameters ---------- k : float upper asymptote q : float effects Y(0) b : float growth rate time: ''' delta = time[-1] - time[0] t0_delta = time[0] + 10 time = [(t - t0_delta) * 20 / delta for t in time] a = [k / (1 + q * math.e**(-b * t)) for t in time] return a global fixed_unc fixed_unc = [ "yearGunvorPhaseout", "baseload biomass or closure C3", "baseload biomass or closure C6", "C3 year", "C6 year", "yearKochPhaseout", "yearBPOffline", "yearHydrocrackerBP", "year of introduction ELECTROLYSIS_H20", "easterly demand H2", "year end demand gas Roterdam", "SF factory 2032 location", "SF factory 2036 location", "SF factory 2040 location", "SF factory 2044 location", "SF factory 2048 location", "SMR paths", "location h2 production" ] global fixed_values_unc fixed_values_unc = \ {'C3 year': 2030.0, 'C6 year': 2025.0, 'SF factory 2032 location': 'none', 'SF factory 2036 location': 'maasvlakte', 'SF factory 2040 location': 'maasvlakte', 'SF factory 2044 location': 'botlek', 'SF factory 2048 location': 'maasvlakte', 'SMR paths': 'SMRTechnologyPaths.SMR_CCS', 'baseload biomass or closure C3': False, 'baseload biomass or closure C6': True, 'easterly demand H2': 76.0, 'location h2 production': 'none', 'year end demand gas Roterdam': 2032.0, 'year of introduction ELECTROLYSIS_H20': 2040.0, 'yearBPOffline': 2039.0, 'yearGunvorPhaseout': 2025.0, 'yearHydrocrackerBP': True, 'yearKochPhaseout': 2030.0, } global delta_dict delta_dict = { "C1": 4, "C2": 0, "C5": 4, "C10": 1, "C11": 1, "C12": 0, "C16": 0, "C20": 3, "C21": 4, "C22": 4, "C24": 1, "C25": 2, "C27": 3, "C28": 0, "C33": 2, "C34": 5, "C35": 5, "C43": 0, "C45": 0, "C50": 5, "C53": 4, "C56": 5, "C58": 3, "C59": 1, "C69": 1, "C70": 1, "C71": 4, "C7": 4, "C8": 0, "C9": 1, "C17": 0, "C18": 1, "C19": 5, "C26": 4, "C39": 0, "C41": 5, "C42": 3, "C47": 1, "C51": 3, "C54": 5, "C55": 2, "C57": 2, "C72": 5, "C73": 1, "C74": 3, "C4": 5, "C14": 0, "C15": 1, "C23": 2, "C29": 1, "C30": 1, "C36": 5, "C37": 0, "C44": 1, "C52": 5, "C63": 3, "C64": 0, "C31": 1, "C32": 3, "C48": 1, "C49": 4, "C62": 1, "C40 delta": 1, "C66 delta": 0, "C67 delta": 3, "C68 delta": 4, "C13 delta": 0, "C60 delta": 1, "C61 delta": 2 } global WindMasterModel def WindMasterModel(parameters): experiment = { pname: pvalue for pname, pvalue in zip(vars, parameters) } nticks = 30 random_seed = 1 start_h2import = 2025 for unc in fixed_unc: experiment[unc] = fixed_values_unc[unc] if unc == "SMR paths": experiment[unc] = eval(fixed_values_unc[unc]) experiment.update(delta_dict) netlogo.command("startNewRun") yearofintroduction['SMR'].loc["ELECTROLYSIS_H2O"] = experiment[ "year of introduction ELECTROLYSIS_H20"] yearofintroduction['SMR'].loc["SMR_CCS"] = int( np.floor(experiment["timing CCS"])) netlogo.command('random-seed {}'.format(random_seed)) dm = ["Reactive", "Current", "Proactive", "Collaborative" ][int(np.floor(experiment["decisionMakingModel"]))] netlogo.command(f"set decisionMakingModel \"{dm}\"") netlogo.command( "ask infraProviders [set leadtime_factor {}]".format( experiment["leadtime_factor"])) start_h2production = get_year_of_availability( AssetTypes.SMR, experiment[f"{AssetTypes.SMR.name} paths"].value[0]) year_h2 = min(start_h2import, start_h2production) for value in yearofintroduction.values(): for item in ["HYBRIDH2", "H2"]: try: value.loc[item] = year_h2 except ValueError: pass events = [] paths = generate_enums() for assettype, paths in paths.items(): if assettype != "SMR": experiment[f"{assettype} paths"] = list(paths)[int( np.floor(experiment[f"{assettype} paths"]))] # assettypes with pathways paths = generate_enums() for assettype in paths.keys(): assettype = AssetTypes[assettype] try: path = experiment[f"{assettype.name} paths"] except KeyError: # print(f"{assettype.name} path not defined") continue for asset_id in assets[assettype.name]: delta = experiment[asset_id] for bt in path.value: year_of_availability = get_year_of_availability( assettype, bt) year = year_of_availability + delta event = create_event(asset_id, assettype, bt, year) events.append(event) if assettype.name == "SMR": location = experiment["location h2 production"] if location == 'maasvlakte': if len(path.value) == 1: year = get_year_of_availability(assettype, bt) event = create_event('C76', assettype, path.value[0], year) events.append(event) else: for bt, asset_id in zip(path.value, ['C75', 'C76']): year = get_year_of_availability(assettype, bt) event = create_event(asset_id, assettype, bt, year) events.append(event) elif location == 'botlek': if len(path.value) == 1: year = get_year_of_availability(assettype, bt) event = create_event('C79', assettype, path.value[0], year) events.append(event) else: for bt, asset_id in zip(path.value, ['C78', 'C79']): year = get_year_of_availability(assettype, bt) event = create_event(asset_id, assettype, bt, year) events.append(event) assettype = AssetTypes['SyntheticFuelPlant'.upper()] FakeTechnology = namedtuple('SFPTechnology', 'value') for year in [2032, 2036, 2040, 2044, 2048]: location = experiment[f"SF factory {year} location"] if location != 'none': assetid = SynethicFuelLocationsEnum[location.upper()].value event = create_event(assetid, assettype, FakeTechnology(0), year) events.append(event) assettype = AssetTypes["Powergen_baseload".upper()] for assetid in assets[assettype.name]: biomass = experiment[f"baseload biomass or closure {assetid}"] year = experiment[f"{assetid} year"] if biomass: event = create_event(assetid, assettype, FakeTechnology(0), year) else: event = create_event(assetid, FakeTechnology(-1), FakeTechnology(-1), year) events.append(event) for assettype in ["Powergen_baseloadindust", "Powergen_flexible"]: assettype = AssetTypes[assettype.upper()] for assetid in assets[assettype.name]: delta = experiment[f"{assetid} delta"] year = start_h2production + delta event = create_event(assetid, assettype, FakeTechnology(0), year) events.append(event) # offshore wind scenarios offshore_wind = experiment["offshore wind growth"] if offshore_wind > 0.5: time = np.arange(2030, 2050) volumes_mv = sigmoid(1300, 0.5, 1, time) # S2 volumes_sh = sigmoid(1200, 0.5, 1, time) # S3 for year, volume_mv, volume_sh in zip(time, volumes_mv, volumes_sh): event_mv = create_event('S2', AssetTypes["WIND"], FakeTechnology(0), year, volume_mv) event_sh = create_event('S3', AssetTypes["WIND"], FakeTechnology(0), year, volume_sh) events.append(event_mv) events.append(event_sh) # easterly demand H2 easterly_h2 = experiment["easterly demand H2"] time = np.arange(year_h2, 2050) volumes = sigmoid(easterly_h2, 1.25, 1, time) for year, volume in zip(time, volumes): event = create_event('D36', AssetTypes["H2"], FakeTechnology(0), year, volume) events.append(event) # end of demand natgas from built environment Rotterdam year = experiment["year end demand gas Roterdam"] event = create_event('D37', FakeTechnology(-1), FakeTechnology(-1), year) events.append(event) eventstring = '[' for event in events: eventstring += "[\"{}\" {} {} {} {}]".format(*event) eventstring += ']' netlogo.command(f"set scenario {eventstring}") netlogo.command("set yearGunvorPhaseout {}".format( experiment["yearGunvorPhaseout"])) netlogo.command("set yearKochPhaseout {}".format( experiment["yearKochPhaseout"])) bp = experiment["yearHydrocrackerBP"] if bp: netlogo.command("set yearHydrocrackerBP 2025") else: netlogo.command("set yearBPOffline {}".format( experiment["yearBPOffline"])) try: netlogo.command(f"repeat {nticks} [go]") except Exception as e: raise CaseError(repr(e), experiment) capex = netlogo.report('capexOverTime') scenario_execution = netlogo.report('reportRealisedScenarioEvents') scens = [] for entry in scenario_execution: asset = entry[0] type = entry[1] technology = entry[2] year = entry[3] entry = (asset, type, technology, year) scens.append(entry) scenario_execution = scens missed = set([e[0:4] for e in events]) - set(scenario_execution) missed_per_year = Counter() for event in missed: year = event[-1] missed_per_year[year] += 1 missed_per_year = [missed_per_year[yr] for yr in range(2020, 2050)] stedin_capex = sum([entry[0] for entry in capex]) tennet_capex = sum([entry[1] for entry in capex]) gasunie_capex = sum([entry[2] for entry in capex]) collaborative_capex = sum([entry[3] for entry in capex]) missed_over_time = sum(missed_per_year) results = { "stedin capex": sum([entry[0] for entry in capex]), "tennet capex": sum([entry[1] for entry in capex]), "gasunie capex": sum([entry[2] for entry in capex]), "collaborative capex": sum([entry[3] for entry in capex]), "missed_over_time": sum(missed_per_year) } print(results) return missed_over_time init_WindMasterModel() init = False missed_over_time = WindMasterModel(parameters) if missed_over_time > 150: distance = 1 else: distance = missed_over_time - 150 print(distance) return distance
### This file measures the execution time by NL4Py to run 200 runs of the ### Ethnocentrism.nlogo model for 1000 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.3.2.py "C:/Program Files/NetLogo 6.0.2" import time import sys import pyNetLogo n = pyNetLogo.NetLogoLink(gui=False, netlogo_home=sys.argv[1], netlogo_version='6.0') modelRuns = 100 ticks_to_run = 100 n.load_model(r"Models/Wolf Sheep Predation.nlogo") def is_running(netlogo): ticks = int(float(netlogo.report("ticks"))) stop1 = str(netlogo.report("not any? turtles")).lower() stop2 = str( netlogo.report("not any? wolves and count sheep > max-sheep")).lower() return ticks != 100 and stop1 != "true" and stop2 != "true" for i in range(0, modelRuns): n.command("set initial-number-sheep random-float 250") n.command("set initial-number-wolves random-float 250") n.command("set grass-regrowth-time random-float 100") n.command("set sheep-gain-from-food random-float 50") n.command("set wolf-gain-from-food random 100")
import pyNetLogo ''' a = [10, 20, 30, 40, 50] b = [5, 10, 15, 20, 25] c = [3, 5, 10, 15, 20] d = [20, 40, 60, 80, 100] e = [10, 30, 50, 70, 90] for i in a: for j in b: for k in c: for l in d: for m in e: print("{} {} {} {} {}".format(i, j, k, l, m)) ''' netlogo = pyNetLogo.NetLogoLink(gui=True, netlogo_home="/opt/NetLogo-6.1.1-64", netlogo_version="6.1") netlogo.load_model('main.nlogo') netlogo.command('setup') netlogo.repeat_command('go', 500)
import pyNetLogo netlogo = pyNetLogo.NetLogoLink(gui=True) netlogo.load_model('Fire.nlogo') netlogo.kill_workspace()
def initializer(model_path): global netlogo netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home=netlogo_path, netlogo_version='6.0') netlogo.load_model(model_path)
from pandas import DataFrame from classifiers import neural_network_classifier as nnc from data import data_utils as data_utils import pyNetLogo # CONSTANTS FITNESS_THRESHOLD = 0.95 MAX_ITER = 300 POPULATION_SIZE = 30 MUTATION_RATE = 70 CROSSOVER_RATE = 0.02 netlogo = pyNetLogo.NetLogoLink(gui=True, netlogo_version='6') du = data_utils.DataUtils() cache = dict() def setup(): netlogo.command('clear-all') netlogo.command('set population-size ' + str(POPULATION_SIZE)) netlogo.command('set mutation-rate ' + str(MUTATION_RATE)) netlogo.command('set crossover-rate ' + str(CROSSOVER_RATE)) netlogo.command('setup') def main(): global_max = 0 netlogo.load_model( 'C:\\Users\\carlos\\PycharmProjects\\hpo\\resources\\Simple Genetic Algorithm.nlogo' ) setup()
from shapely.geometry import LineString from shapely.geometry import Point from shapely.geometry import MultiPoint import math import matplotlib.patches as patches import seaborn as sns sns.set_style('white') sns.set_context('talk') # Import the sampling and analysis modules for a Sobol variance-based # sensitivity analysis from SALib.sample import saltelli from SALib.analyze import sobol import pyNetLogo netlogo = pyNetLogo.NetLogoLink( gui=False, netlogo_home='/Users/agnesresto/Documents/NetLogo 6.0.4') netlogo.load_model( '/Users/agnesresto/modeling_morphogenesis/modeling_morphogenesis/modeling_morphogenesis/Morphogenesis_3Denv_3Dov-v2.nlogo' ) problem = { 'num_vars': 7, 'names': [ # 'random-seed', 'num-cells', 'max-divisions', 'num-matrix-diff', 'cycles-diff-matrix', 'num-diff-ind', 'cycles-diff-ind', 'undiff-num-inhibition' ], 'bounds': [ # [1, 100000], [10, 100], [1, 2], [1, 5], [1, 10], [1, 5], [1, 10], [1, 5] ] }
import pyNetLogo from PIL import Image from point import Point from functions import bit_matrix, bitmap if __name__ == '__main__': netlogo = pyNetLogo.NetLogoLink() netlogo.load_model("netlogo_models/Flocking.nlogo") netlogo.command("setup") step = 100 max_x, min_x = netlogo.report("min-pxcor"), netlogo.report("max-pxcor") max_y, min_y = netlogo.report("min-pycor"), netlogo.report("max-pycor") Lx, Ly = 300, 300 mat = [] for k in range(step): netlogo.command("go") x = netlogo.report("map [s -> [xcor] of s] sort turtles") y = netlogo.report("map [s -> [ycor] of s] sort turtles") x = ((x - min_x) / (max_x - min_x) * Lx).astype(int) y = ((y - min_y) / (max_y - min_y) * Ly).astype(int) points = [[] for k in range(len(x))] for k, (x_, y_) in enumerate(zip(x, y)): points[k] = Point(k, x_, y_, 0, 0) mat.append(bit_matrix(points, Lx, Ly))
import pyNetLogo netlogo = pyNetLogo.NetLogoLink(gui=False,netlogo_home='/Users/yilmaz/Desktop/NetLogo-6.1.1') #Show NetLogo GUI netlogo.load_model('/Users/yilmaz/Desktop/swarms/Wolf Sheep Predation.nlogo') netlogo.command('setup') netlogo.repeat_command('go', 50) x = netlogo.report('map [s -> [xcor] of s] sort sheep') y = netlogo.report('map [s -> [ycor] of s] sort sheep') p = netlogo.report('map [s -> [energy] of s] sort sheep') energy_wolves = netlogo.report('map [w -> [energy] of w] sort wolves') sheepCount = netlogo.report('count sheep') wolvesCount = netlogo.report('count wolves') print(sheepCount,wolvesCount) netlogo.kill_workspace()