Git Product home page Git Product logo

pynetlogo's People

Contributors

dependabot[bot] avatar ewouth avatar jasonrwang avatar kdennijs avatar magni5 avatar marcjaxa avatar quaquel avatar steipatr avatar wolgo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

pynetlogo's Issues

repeat_report with aggregate and agent-level variables

I am using the library to interact with the model Wolf and Sheep Predation and I'd like to do something like this:

netlogo.report_many(['[speed] of sample-car', '[xcor] of turtles'], 100)

But I obtain an (expected) error due to dimension incompatibility in the pandas dataframe. As a fix, I did this:

output = defaultdict(list)
for _ in range(100):
    netlogo.command('go')
    output['sample-car'].append(netlogo.report('[speed] of sample-car'))
    output['cars'].append(netlogo.report('[xcor] of turtles'))

Which is obviously less efficient than report_many. How difficult would it be to detect incompatible output dimensions and to adapt the type of the returned datastructure accordingly?

AttributeError: 'DataFrame' object has no attribute 'ix'

I'm working through your introduction tutorial and I have hit a snag at item [13] for the patch report. When I execute the code its returning https://pynetlogo.readthedocs.io/en/latest/_docs/introduction.html

It looks like this may be related to versions of pandas > 1.0.0 (I have 1.2.4 installed). It was suggested to modify ix to loc or iloc []https://stackoverflow.com/questions/59991397/attributeerror-dataframe-object-has-no-attribute-ix

I updated 'patch_report' in pyNetLogo/core.py and its now working
was: results_df.xi[:, :] = resultsvec.reshape(results_df.shape)
is: results_df.iloc[:, :] = resultsvec.reshape(results_df.shape)

Let me know your thoughts... thanks

Beginner question on execution time

Hi there,

I want my Netlogo model to run for a certain number of ticks with pyNetlogo but I didn't find any method that can help me do this (please let me know if I missed anything useful). So I put these lines in my python code:

while(netlogo.report('ticks') <= max_run_time):
    netlogo.command('go')

As I tried to call and run the Netlogo model through pycharm I noticed that the execution time of 1 replication is much longer than directly running the model in Netlogo, like more than 2hrs vs. 2mins. May I know if there is more efficient way of doing this?

Thanks in advance:)

App doesn't terminate after NetLogo has been used (in a thread)

I'm using pyNetLogo in a GUI app, so have it in a thread. However, when my app ends, it hangs. Looks like there's still some Java running. I've recreated the problem in a simple app.

import threading
import pyNetLogo

def do_work():
    netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home="/opt/NetLogo/", netlogo_version="6.1")
    netlogo.kill_workspace()
    print("work completed")

def main():
    worker_thread = threading.Thread(target=do_work)
    worker_thread.start()

    worker_thread.join()

    print("closing down")

if __name__ == "__main__":
    main()

This application reaches and displays the "closing down" message, but it never returns control to the shell.

I believe there's still some Java code running as I've seen the following message appear if I don't kill the app for a few seconds after the "closing down" message.

Warning: Could not get charToByteConverterClass!

I created a similar test app using jpype that ran a simple java command. That was fine. Everything closed down as expected. So it seems to be something related to launching NetLogo.

Any ideas on how I can terminate NetLogo and have control return to the shell? By this point in the execution the app is ending, so I'd even be happy to nuke any threads/processes---if that's what it takes. Just need it to stop and return control to the shell.

I'm running Python 3.8.2, pyNetLogo 0.4.1 and jpype 0.7.4. Also tried with Python 3.7. Same issue.

My main development environment is Ubuntu 20.04, but I've experienced the same when testing in Windows 10.

while loop

I'm really liking the package. Wondering if pyNetLogo has a direct way of doing a while loop, similar to NLDoReportWhile in RNetLogo. Below is my home-brew solution using the built-in segregation model to collect some output and keep running the model until a condition is met. Is there another approach?

import pyNetLogo
import pandas as pd

netlogo = pyNetLogo.NetLogoLink(gui=True)
netlogo.load_model("Segregation.nlogo")
netlogo.command("set density 70")
netlogo.command("set %-similar-wanted 70")
netlogo.command("setup")

unhappy_df_70 = pd.DataFrame()
while True:
    temp = netlogo.repeat_report(["count turtles with [ not happy? ]",  "count turtles"], 1)
    unhappy_df_70 = pd.concat([unhappy_df_70,temp])
    if temp["count turtles with [ not happy? ]"].values == 0:
        break

Repeat Report cannot handle Reporters containing strings.

pyNetLogo/pyNetLogo/core.py

Lines 573 to 575 in b944208

fn = r'{0}/{1}{2}'.format(tempfolder,
variable,
'.txt')

The problem is that the netlogo code here becomes: file-open "folder/count object where [ string = "value"].txt"
Meaning netlogo understands:

file-open 
"folder/count object where [ string = " 
value
"].txt"

Due to netlogo requiring " for strings like file-open, there is no way to get around this by altering the reporter.
My recommendation would be to simply remove all " from the variable for the filename.

(Possible: variable.replace('"',''))

Cannot run after pack model via Pyinstaller

I was trying to pack a PyNetlogo based python program into a .exe file via pyinstaller. When I run the python program in pycharm it works and interacts with netlogo model without any problem. However, when I packed it into .exe file it reported error:
"pype._jexception.java.lang.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class NetLogoLinkV6.NetLogoLink not found"

I guess it has some issues with java_home path. I have corrected the path but I still encounter with such error message. What is the root cause and how to fix? I installed Jpype using whl file: JPype1-0.6.3-cp36-cp36m-win_amd64.whl. My operating system is windows 10 64 bits.

Many thanks for the clarification.

load_model() fails when .nlogo file includes NetLogo extensions

Hi, I'm new to this project but am very excited about it. I'm having trouble loading models that require a built-in extension. I've ensured that I do have these extensions, e.g.:

$ ls /Applications/NetLogo\ 5.3.1/extensions/sound/
sound.jar

I can also open and run models with no issues by double-clicking the .nlogo file.

Here is a minimal example:

import pyNetLogo
netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home="/Applications/NetLogo 5.3.1/")
netlogo.load_model("/Users/.../model.nlogo")

The last line yields the error:

java.lang.IllegalStateException: Can't find extension: sound/sound.jar
	at org.nlogo.workspace.ExtensionManager.resolvePathAsURL(ExtensionManager.java:315)
	at org.nlogo.workspace.ExtensionManager.importExtension(ExtensionManager.java:153)
	at org.nlogo.compiler.StructureParser.parseImport(StructureParser.scala:459)
	at org.nlogo.compiler.StructureParser.parse(StructureParser.scala:196)
	at org.nlogo.compiler.CompilerMain$.compile(CompilerMain.scala:25)
	at org.nlogo.compiler.Compiler$.compileProgram(Compiler.scala:28)
	at org.nlogo.headless.HeadlessModelOpener.openFromMap(HeadlessModelOpener.scala:53)
	at org.nlogo.headless.HeadlessWorkspace.openString(HeadlessWorkspace.scala:531)
	at org.nlogo.headless.HeadlessWorkspace.open(HeadlessWorkspace.scala:513)
	at NetLogoLinkV5.NetLogoLink.loadModel(Unknown Source)
Traceback (most recent call last):
  File "/Users/.../lib/python3.6/site-packages/pyNetLogo/core.py", line 253, in load_model
    self.link.loadModel(path)
jpype._jexception.CompilerExceptionPyRaisable: Can't find extension: sound at position 12 in 

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/.../lib/python3.6/site-packages/pyNetLogo/core.py", line 255, in load_model
    raise NetLogoException(ex.message())
pyNetLogo.core.NetLogoException: Can't find extension: sound

This occurs when loading a model with any extensions found in my NetLogo path, /Applications/NetLogo\ 5.3.1/extensions.

Is anyone able to help? I've found similar issues before (related to running NetLogo--usually in headless mode--but unrelated to this package), e.g. here and here. Thanks!

Multiprocessing using more than one pool worker doesn't iterate

I followed Example 3 to set-up multiprocessing where I am trying to imitate BehaviorSpace in Netlogo.

`def initializer(modelfile):
    import pyNetLogo
    global netlogo
    netlogo = pyNetLogo.NetLogoLink(gui=False)
    netlogo.load_model(modelfile)

def simulation(i):
    import pandas as pd
    netlogo.command('import-data')
    netlogo.command('set random-seed '+str(i))
    temp = pd.DataFrame(netlogo.report_while(('ticks','agent','status'), 'not endrun?', command='go'))
    temp.rename(columns = {0:"time", 1:"agent",2:"status"}, inplace=True)
    temp['seed'] = i
    print('Run #'+str(i)+' Completed')
    return temp`

However, when I create define the multiprocessing code with a pool of 2 or more workers, it doesn't seem to iterate properly.

`if __name__ == '__main__':
    numsimulations = range(1,3)
    with Pool(2, initializer=initializer, initargs=(modelfile,)) as pool:
        output = pd.DataFrame()
        for entry in pool.map(simulation, numsimulations):
            output = output.append(entry)`

My model output gives that the random-seed value changes from 1 to 2, but the values of agent and status are exactly the same though the random seed is different.

When I try the same code with one process worker - Pool(1, initializer=initializer, initargs=(modelfile,)) as pool:, the model outputs for random-seed 1 and random-seed 2 are correct. Is there something I am doing wrong?

kill_workspace()/killWorkspace() returns too quickly

The killWorkspace() Java method seems to interrupt the NetLogo thread, but doesn't seem to wait for the thread to respond to the interruption signal. This results in the kill_workspace() function potentially returning before NetLogo has closed.

This seems to cause some odd crashes, especially when running consecutive simulations.

add support for NestedList

currently pyNetLogo breaks when a reporter returns a nested list. Fixing this requires extending NLResult. I don't know whether the R or Mathematica link do support NestedLists, if so the fix should not be too difficult.

I am not able to load Netlogo

Hello,

Nice package. I am trying to load NetLogo 6.0 on my Mac with no success. I get this error. Any ideas on what the problem might be?

import pyNetLogo as nl

path = '/Applications/NetLogo 6.0'

netlogo = nl.NetLogoLink(gui=False, netlogo_home=path, netlogo_version='6')
---------------------------------------------------------------------------
java.lang.RuntimeExceptionPyRaisable      Traceback (most recent call last)
<ipython-input-11-faf2fd1d0f65> in <module>()
----> 1 netlogo = nl.NetLogoLink(gui=False)

~/miniconda3/lib/python3.6/site-packages/pyNetLogo/core.py in __init__(self, gui, thd, netlogo_home, netlogo_version, jvm_home)
    225                 jpype.java.lang.System.setProperty('java.awt.headless', 'true')
    226 
--> 227         link = jpype.JClass(module_name[self.netlogo_version])
    228 
    229         if sys.platform == 'darwin' and gui:

~/miniconda3/lib/python3.6/site-packages/jpype/_jclass.py in JClass(name)
     53     jc = _jpype.findClass(name)
     54     if jc is None:
---> 55         raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
     56 
     57     return _getClassFor(jc)

java.lang.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class NetLogoLinkV6.NetLogoLink not found

Problem running an example from the documentation

Hi,

PyNetLogo looks like an ideal package for some of my work. Unfortunately, I am experiencing a problem running the example in the documentation:

%matplotlib inline

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
sns.set_context('talk')

import pyNetLogo

netlogo = pyNetLogo.NetLogoLink(gui=True)

nfile = 'C:/Program Files/NetLogo 6.1.1/app/models/Sample Models/Biology/Wolf Sheep Predation.nlogo'
netlogo.load_model(nfile)
netlogo.command('setup')

The error I am getting is as follows:

java.lang.NullPointerException
	at NetLogoLinkV61.NetLogoLink.command(NetLogoLink.java:180)

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
~\anaconda3\envs\netlogo\lib\site-packages\_jpype.cp37-win_amd64.pyd in NetLogoLinkV61.NetLogoLink.command()

Exception: Java Exception

The above exception was the direct cause of the following exception:

java.lang.NullPointerException            Traceback (most recent call last)
~\anaconda3\envs\netlogo\lib\site-packages\pyNetLogo\core.py in command(self, netlogo_command)
    333         try:
--> 334             self.link.command(netlogo_command)
    335         except jpype.JException as ex:

java.lang.NullPointerException: java.lang.NullPointerException

During handling of the above exception, another exception occurred:

NetLogoException                          Traceback (most recent call last)
<ipython-input-3-d57d55e75631> in <module>
     13 nfile = 'C:/Program Files/NetLogo 6.1.1/app/models/Sample Models/Biology/Wolf Sheep Predation.nlogo'
     14 netlogo.load_model(nfile)
---> 15 netlogo.command('setup')

~\anaconda3\envs\netlogo\lib\site-packages\pyNetLogo\core.py in command(self, netlogo_command)
    335         except jpype.JException as ex:
    336             print(ex.stacktrace())
--> 337             raise NetLogoException(str(ex))
    338 
    339     def report(self, netlogo_reporter):

NetLogoException: java.lang.NullPointerException


Here is some information about my system:

Windows 10 pro v1903
Netlogo v6.1.1
Python v3.7.7 (Anaconda)
pyNetLogo v0.4.1
jpype v1.0.1

Thanks for your help.

-Brad

Error while executing repeat_report

OS: Fedora 36
Netlogo version: 6.2.2
pyNetlogo version 0.4.2
python version 3.10

Netlogo Model:

to setup
  clear-all
  reset-ticks
  crt 10
end

to go
  ask turtles [
    move-to one-of patches
  ]
  tick
end

pyNetlogo Code:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pyNetLogo

netlogo_path = './Applications/NetLogo'
netlogo_version = '6.2'
jvm_home = './Applications/NetLogo/runtime/lib/amd64/server/libjvm.so'

netlogo = pyNetLogo.NetLogoLink(gui=True, netlogo_home=netlogo_path, netlogo_version=netlogo_version, jvm_home=jvm_home)

model_path = './NetLogo/test.nlogo'
netlogo.load_model(model_path)

netlogo.command('setup')
df = netlogo.repeat_report('[xcor] of turtles',100)

Error:
ValueError Traceback (most recent call last)
/tmp/ipykernel_66101/872701698.py in
1 netlogo.command('setup')
----> 2 df = netlogo.repeat_report('[xcor] of turtles',100)

~/.local/lib/python3.10/site-packages/pyNetLogo/core.py in repeat_report(self, netlogo_reporter, reps, go, include_t0)
615 for entry in result.split()])
616
--> 617 results_df.loc[:, key] = result
618
619 os.remove(value)

~/.local/lib/python3.10/site-packages/pandas/core/indexing.py in setitem(self, key, value)
721
722 iloc = self if self.name == "iloc" else self.obj.iloc
--> 723 iloc._setitem_with_indexer(indexer, value, self.name)
724
725 def _validate_key(self, key, axis: int):

~/.local/lib/python3.10/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value, name)
1730 self._setitem_with_indexer_split_path(indexer, value, name)
1731 else:
-> 1732 self._setitem_single_block(indexer, value, name)
1733
1734 def _setitem_with_indexer_split_path(self, indexer, value, name: str):

~/.local/lib/python3.10/site-packages/pandas/core/indexing.py in _setitem_single_block(self, indexer, value, name)
1966
1967 # actually do the set
-> 1968 self.obj._mgr = self.obj._mgr.setitem(indexer=indexer, value=value)
1969 self.obj._maybe_update_cacher(clear=True)
1970

~/.local/lib/python3.10/site-packages/pandas/core/internals/managers.py in setitem(self, indexer, value)
353
354 def setitem(self: T, indexer, value) -> T:
--> 355 return self.apply("setitem", indexer=indexer, value=value)
356
357 def putmask(self, mask, new, align: bool = True):

~/.local/lib/python3.10/site-packages/pandas/core/internals/managers.py in apply(self, f, align_keys, ignore_failures, **kwargs)
325 applied = b.apply(f, **kwargs)
326 else:
--> 327 applied = getattr(b, f)(**kwargs)
328 except (TypeError, NotImplementedError):
329 if not ignore_failures:

~/.local/lib/python3.10/site-packages/pandas/core/internals/blocks.py in setitem(self, indexer, value)
981 values, len(values[indexer]), value # type: ignore[arg-type]
982 )
--> 983 values[indexer] = value
984
985 if transpose:

ValueError: could not broadcast input array from shape (101,10) into shape (101,)

Setup dependencies of pynetlogo on install_requires

Hi,
Is there a particular reason for not stating the dependencies (pandas, numpy, scipy, JPype1) on the install_requires of the setup command? This would make the installation much smoother. I can make a PR, if you want, but I am not sure if there are particular versions of the dependencies that would be more suitable.

"Duplicate Keys not allowed" error for repeated execution

I wrote a Python function to extract views/snapshots from NetLogo runs. Eventually I want to generate GIFs, MP4s etc. of the runs. The function imports pyNetLogo, loads a specified model, runs it until the desired tick, saves the world view of the tick, and kills NetLogo. This works fine when executed once, but the second execution (e.g. for a different model file) hangs or returns an error (see attached). Restarting the Python kernel resets the issue, but I am hoping there is a smoother option, or I am missing something?

Possibly related to #10 ?

Versions:

  • Windows: 7 Enterprise, SP1
  • Python: 3.6
  • Jupyter Notebook: 5.0
  • pyNetLogo: 0.3
  • Java: 8 Update 201 (build 1.8.0_201-b09)
  • NetLogo: 6.0.2

Attached in ZIP:

  • minimal working example Jupyter notebook
  • two NetLogo model files to go with the notebook
  • screenshot of the error message which sometimes appears

pyNetLogo Duplicate Keys Error.zip

netlogo.report()

Hi,
I am using pynetlogo package to write and read some attributes for my agents. In my NetLogo model, I have assigned 156 wells as agents, and each one has its own flow rate named Debi. As you can see in the attached picture, I have defined Debi using matrix extension and I wanna use pynetlogo to read this matrix and save it as a variable as I wanna import this variable in another software named Modflow to run an existing model then report the results.
image

I tried -----> Debiwel = netlogo.report('map [s -> [Debi] of s] sort wels') code to receive Debi variable but I got this error:
image
Is it possible to get a matrix attribute from NetLogo using NetLogo.report ? What should I do to execute the aforementioned process?
Thanks in advance for your answering. I appreciate it.

FileNotFound causes java to segfaults

I'm new to NetLogo and pyNetLogo and I've installed it for some other users on a vanilla Linux box (which we use as a server, with no GUI).

The following very simple thing core dumps on netlogo.load_model()

import pyNetLogo
netlogo = pyNetLogo.NetLogoLink(netlogo_home='/opt/NetLogo 6.0.4', netlogo_version="6", gui=False)
netlogo.load_model(r'Wolf Sheep Predation_v6.nlogo')
netlogo.command('setup')

The logs report a pretty useless stack trace, which seems to indicate that it tried to have a java swing window popping out to say something but could not (granted, on a no GUI machine...)

Fiddling around revealed that the problem was that there was no Wolf Sheep Predation_v6.nlogo file anywhere. Changing that to netlogo.load_model(r'/opt/NetLogo 6.0.4/app/models/Sample Models/Biology/Wolf Sheep Predation.nlogo') fixed the issue.

However that did not produce any output that I can tell: was it supposed to?

I suggest checking the string passed to netlogo.load_model() for being a readable file before passing it to java and letting it spit out such a useless log.

Not working with NetLogo 6.1.0

NetLogo 6.1.0 has just been released. I'm unable to get pyNetLogo working with 6.1.0. There isn't a documented change to the API. Thoughts? Thanks.

Error:

Traceback (most recent call last):
  File "/Users/thomasfrench/miniconda3/envs/pyNetLogo/lib/python3.6/site-packages/pyNetLogo/core.py", line 283, in load_model
    self.link.loadModel(path)
jpype._jexception.NoSuchMethodErrorPyRaisable: java.lang.NoSuchMethodError: org.nlogo.workspace.Controllable.open(Ljava/lang/String;)V

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "model.py", line 22, in simulation
    netlogo.load_model(MODEL_FILENAME)
  File "/Users/thomasfrench/miniconda3/envs/pyNetLogo/lib/python3.6/site-packages/pyNetLogo/core.py", line 285, in load_model
    raise NetLogoException(ex.message())
pyNetLogo.core.NetLogoException: org.nlogo.workspace.Controllable.open(Ljava/lang/String;)V

Different library loading behavior between interactive shell and batch job

Hi,
I will try to be simple in explaining my issue. I am using CentOS 7, I have installed NetLogo 5.3.1 (older version is a requirement of the end-user) and PyNetLogo 0.4.2 under Python 3.7.9. All 64 bits.
I was quite happy when I was able to run the software using the following python script based on the example in the documentation:

import os
import pyNetLogo
print(os.environ['NETLOGO_HOME'])
print(os.environ['NETLOGO_VERSION'])
netlogo = pyNetLogo.NetLogoLink(netlogo_home=os.environ['NETLOGO_HOME'], netlogo_version=os.environ['NETLOGO_VERSION'])
netlogo.load_model('./Wolf Sheep Predation_v6.nlogo')
netlogo.command('setup')
counts = netlogo.repeat_report(['count wolves','count sheep'], 200, go='go')
counts.to_csv('tmp.out')
netlogo.kill_workspace()
exit()

This was run on a login shell. But I am interested in running it, unattended, on the cluster using a job scheduler (in this case, Altair Grid Engine).

When trying to run it through a batch job on that scheduler, the same example using the same software fails with:

Traceback (most recent call last):
  File "NetLogoLink.java", line 76, in NetLogoLinkV5.NetLogoLink.<init>
  File "HeadlessWorkspace.scala", line -1, in org.nlogo.headless.HeadlessWorkspace.newInstance
  File "HeadlessWorkspace.scala", line 31, in org.nlogo.headless.HeadlessWorkspace$.newInstance
  File "HeadlessWorkspace.scala", line 39, in org.nlogo.headless.HeadlessWorkspace$.newInstance
  File "Pico.scala", line 23, in org.nlogo.util.Pico.addScalaObject
  File "Class.java", line 315, in java.lang.Class.forName
  File "Class.java", line -2, in java.lang.Class.forName0
  File "Compiler.scala", line -1, in org.nlogo.compiler.Compiler$.<clinit>
  File "Compiler.scala", line 16, in org.nlogo.compiler.Compiler$.<init>
  File "Femto.scala", line 19, in org.nlogo.util.Femto$.scalaSingleton
  File "Class.java", line 315, in java.lang.Class.forName
  File "Class.java", line -2, in java.lang.Class.forName0
  File "Tokenizer.scala", line -1, in org.nlogo.lex.Tokenizer2D$.<clinit>
  File "Tokenizer.scala", line 7, in org.nlogo.lex.Tokenizer2D$.<init>
  File "TokenMapper.scala", line -1, in org.nlogo.lex.TokenMapper2D$.<clinit>
  File "TokenMapper.scala", line 9, in org.nlogo.lex.TokenMapper2D$.<init>
  File "TokenMapper.scala", line 32, in org.nlogo.lex.TokenMapper.<init>
  File "Color.scala", line -1, in org.nlogo.api.Color$.<clinit>
  File "Color.scala", line 68, in org.nlogo.api.Color$.<init>
  File "ArrayOps.scala", line 38, in scala.collection.mutable.ArrayOps.map
  File "TraversableLike.scala", line 233, in scala.collection.TraversableLike$class.map
  File "ArrayOps.scala", line 38, in scala.collection.mutable.ArrayOps.foreach
  File "IndexedSeqOptimized.scala", line 34, in scala.collection.IndexedSeqOptimized$class.foreach
  File "TraversableLike.scala", line 233, in scala.collection.TraversableLike$$anonfun$map$1.apply
  File "TraversableLike.scala", line 233, in scala.collection.TraversableLike$$anonfun$map$1.apply
  File "Color.scala", line 68, in org.nlogo.api.Color$$anonfun$3.apply
  File "Color.scala", line 69, in org.nlogo.api.Color$$anonfun$3.apply
  File "Color.java", line 275, in java.awt.Color.<clinit>
  File "Toolkit.java", line 1429, in java.awt.Toolkit.<clinit>
  File "Toolkit.java", line 1396, in java.awt.Toolkit.loadLibraries
  File "AccessController.java", line -2, in java.security.AccessController.doPrivileged
  File "Toolkit.java", line 1397, in java.awt.Toolkit$3.run
  File "Toolkit.java", line 1399, in java.awt.Toolkit$3.run
  File "System.java", line 1867, in java.lang.System.loadLibrary
  File "Runtime.java", line 829, in java.lang.Runtime.loadLibrary0
  File "ClassLoader.java", line 2638, in java.lang.ClassLoader.loadLibrary
  File "ClassLoader.java", line 2684, in java.lang.ClassLoader.loadLibrary0
  File "ClassLoader.java", line 2487, in java.lang.ClassLoader$NativeLibrary.loadLibrary
  File "ClassLoader.java", line 2430, in java.lang.ClassLoader$NativeLibrary.load
  File "ClassLoader.java", line -2, in java.lang.ClassLoader$NativeLibrary.load0
  File "System.java", line 1831, in java.lang.System.load
  File "Runtime.java", line 767, in java.lang.Runtime.load0
  File "ClassLoader.java", line 2620, in java.lang.ClassLoader.loadLibrary
Exception: Java Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "example.py", line 5, in <module>
    netlogo = pyNetLogo.NetLogoLink(netlogo_home=os.environ['NETLOGO_HOME'], netlogo_version=os.environ['NETLOGO_VERSION'])
  File "/progs/all/opensource/pynetlogo/0.4.2/lib/python3.7/site-packages/pyNetLogo/core.py", line 286, in __init__
    jpype.java.lang.Boolean(thd))
java.lang.UnsatisfiedLinkError: java.lang.UnsatisfiedLinkError: Can't load library: /usr/lib/jvm/java-11-openjdk-11.0.ea.28-7.el7.x86_64/lib/libawt_xawt.so

My impression is that, instead of using the runtime libraries that can be found on the /runtime/lib of NetLogo, it is trying to use the Java runtime libraries of the OS. Since I am passing the location of NetLogo to netlogo_home and it worked in the interactive shell mode, I do not not know what I may be missing.

Have you seen any issue like this before?

Repeat_report command run twice ValueError

I've been starting to use the examples from https://readthedocs.org/projects/pynetlogo/downloads/pdf/latest/, and I've found an issue in the repeat_report command as used on page 9. It appears that running repeat_report after other simulation commands leads to it raising a value error

If I run this script

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pyNetLogo

netlogo = pyNetLogo.NetLogoLink(gui=True,netlogo_home='''/home/ben/binaries/NetLogo 6.2.2''',netlogo_version='6.2')

netlogo.load_model('./Wolf_Sheep_Predation.nlogo')
netlogo.command('setup')

test_energy = netlogo.repeat_report(['[energy] of sheep'],10) #no problem

energy_df = netlogo.repeat_report(['[energy] of wolves',
    '[energy] of sheep',
    'count sheep'], 200)

print(energy_df)

#netlogo.command('setup')

energy_df = netlogo.repeat_report(['[energy] of sheep',
    '[energy] of sheep',
    'count sheep',
    'count wolves'], 1)

print(energy_df)

I get the error

ValueError: could not broadcast input array from shape (4,) into shape (2,2)

If I change the number of steps in the second repeat_report command the error remains, but the first command is robust. If I uncomment the repeat of the setup line this does not prevent the error.

Tested with the latest commit from github and from an installation through pip, on ubuntu focal.

High-level API

It would be useful to have an API dealing with inputs and outputs rather than with raw commands. Something like this:

class Model:
    def __init__(self, path, inputs, outputs, **kwargs):
        self._link = pyNetLogo.NetLogoLink(**kwargs)
        self._link.load_model(path)
        self.inputs = inputs
        self.outputs = outputs
        
    def configure(self, inputs):
        for name, input in self.inputs.items():
            val = inputs.get(name, input['default'])
            low, high = input['bounds']
            assert low <= val <= high
            self._link.command('set {0} {1}'.format(name, val))

    def setup(self, inputs=None):
        if inputs is not None:
            self.configure(inputs)
        self._link.command('setup')
        return {
            o: self._link.report(o)
            for o in self.outputs
        }
    
    def step(self, steps, inputs=None, go='go'):
        if inputs is not None:
            self.configure(inputs)
        return self._link.report_many(self.outputs, steps, go=go)
        
    def run(self, steps, inputs=None):
        setup_data = self.setup(inputs=inputs)
        step_data = self.step(steps)
        return {
            o: [setup_data[o], *step_data[o]]
            for o in self.outputs
        }

Which would be used like this:

inputs = {
    'initial-number-sheep': {
        'bounds': [0, 250],
        'default': 50
    },
    # ...
}
outputs = ['count sheep']
model = Model('abm.nlogo', inputs, outputs, netlogo_home='...', netlogo_version='6')
data = model.run(100, {'initial-number-sheep': 73})

Multiprocessing: Ubuntu VM out of memory and kills processes

Dear pyNetLogo Developers

first, thank you very much for your great work!

I have a problem when running pyNetLogo with multiprocessing.
I ran the code below on a linux server and the issues is that the servers runs out of memory and starts to kill processes.
Below you find the setting for Linux, the error message and the python code.

The processes relativly quickly are around 800 MB and then after couple of minutes hit 1 GB. If this is the case the OS kills the process and the pool respawns a process and the routine repeats itselve.

We assume the problem is that the Java VM takes too much ram.

Does anyone have an idea what we could do?

Thank you very much.

Environment Linux

  • Openstack VM
  • OS: Ubuntu
  • 16 VCPUs
  • 16 GB RAM

Error Message on Linux

Apr 25 19:05:01 netlogo01 kernel: [ 7097.004932] GC Thread#9 invoked oom-killer: gfp_mask=0x100cca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.004954] CPU: 2 PID: 25671 Comm: GC Thread#9 Not tainted 5.4.0-109-generic #123-Ubuntu
Apr 25 19:05:01 netlogo01 kernel: [ 7097.004955] Hardware name: OpenStack Foundation OpenStack Nova, BIOS 1.13.0-1ubuntu1.1 04/01/2014
Apr 25 19:05:01 netlogo01 kernel: [ 7097.004960] Call Trace:
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005000]ย  dump_stack+0x6d/0x8b
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005004]ย  dump_header+0x4f/0x1eb
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005006]ย  oom_kill_process.cold+0xb/0x10
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005011]ย  out_of_memory+0x1cf/0x4d0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005017]ย  __alloc_pages_slowpath+0xd5e/0xe50
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005020]ย  __alloc_pages_nodemask+0x2d0/0x320
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005023]ย  alloc_pages_current+0x87/0xe0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005028]ย  __page_cache_alloc+0x72/0x90
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005030]ย  pagecache_get_page+0xbf/0x300
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005032]ย  filemap_fault+0x6b2/0xa50
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005036]ย  ? unlock_page_memcg+0x12/0x20
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005038]ย  ? page_add_file_rmap+0xff/0x1a0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005041]ย  ? filemap_map_pages+0x24c/0x380
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005045]ย  ext4_filemap_fault+0x32/0x50
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005048]ย  __do_fault+0x3c/0x130
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005050]ย  do_fault+0x24b/0x640
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005051]ย  __handle_mm_fault+0x4c5/0x7a0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005053]ย  handle_mm_fault+0xca/0x200
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005057]ย  do_user_addr_fault+0x1f9/0x450
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005059]ย  __do_page_fault+0x58/0x90
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005061]ย  ? schedule+0x42/0xb0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005063]ย  do_page_fault+0x2c/0xe0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005067]ย  do_async_page_fault+0x39/0x70
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005071]ย  async_page_fault+0x34/0x40
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005083] RIP: 0033:0x7fa66c0b0160
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005097] Code: Bad RIP value.
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005098] RSP: 002b:00007fa5965f4a18 EFLAGS: 00010246
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005100] RAX: 00007fa622eaccc9 RBX: 000000000445b000 RCX: 0000000000000007
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005101] RDX: 00007fa622eacb80 RSI: 00007fa622eaccc9 RDI: 00007fa5965f4a50
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005102] RBP: 00007fa5965f5cd0 R08: 00007fa622eacb90 R09: 00007fa622eac000
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005102] R10: 00007fa676372000 R11: 000000000000000b R12: 00007fa66cc15568
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005103] R13: 00007fa5965f4a50 R14: 00007fa5965f4a20 R15: 00007fa66b779918
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005109] Mem-Info:
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119] active_anon:3989999 inactive_anon:46 isolated_anon:0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119]ย  active_file:85 inactive_file:41 isolated_file:0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119]ย  unevictable:4619 dirty:7 writeback:0 unstable:0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119]ย  slab_reclaimable:12889 slab_unreclaimable:33002
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119]ย  mapped:2107 shmem:269 pagetables:10297 bounce:0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005119]ย  free:33828 free_pcp:0 free_cma:0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005122] Node 0 active_anon:15959996kB inactive_anon:184kB active_file:340kB inactive_file:164kB unevictable:18476kB isolated(anon):0kB isolated(file):0kB mapped:8428kB dirty:28kB writeback:0kB shmem:1076kB shmem_thp: 0kB shmem_pmdmapped: 0kB anon_thp: 0kB writeback_tmp:0kB unstable:0kB all_unreclaimable? no
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005126] Node 0 DMA free:15908kB min:64kB low:80kB high:96kB active_anon:0kB inactive_anon:0kB active_file:0kB inactive_file:0kB unevictable:0kB writepending:0kB present:15992kB managed:15908kB mlocked:0kB kernel_stack:0kB pagetables:0kB bounce:0kB free_pcp:0kB local_pcp:0kB free_cma:0kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005129] lowmem_reserve[]: 0 2911 15902 15902 15902
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005132] Node 0 DMA32 free:64272kB min:12360kB low:15448kB high:18536kB active_anon:2987768kB inactive_anon:0kB active_file:4kB inactive_file:0kB unevictable:0kB writepending:8kB present:3129196kB managed:3063660kB mlocked:0kB kernel_stack:448kB pagetables:6108kB bounce:0kB free_pcp:0kB local_pcp:0kB free_cma:0kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005135] lowmem_reserve[]: 0 0 12991 12991 12991
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005137] Node 0 Normal free:55132kB min:55156kB low:68944kB high:82732kB active_anon:12972228kB inactive_anon:184kB active_file:416kB inactive_file:0kB unevictable:18476kB writepending:20kB present:13631488kB managed:13310972kB mlocked:18476kB kernel_stack:9008kB pagetables:35080kB bounce:0kB free_pcp:0kB local_pcp:0kB free_cma:0kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005141] lowmem_reserve[]: 0 0 0 0 0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005143] Node 0 DMA: 14kB (U) 08kB 016kB 132kB (U) 264kB (U) 1128kB (U) 1256kB (U) 0512kB 11024kB (U) 12048kB (M) 34096kB (M) = 15908kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005149] Node 0 DMA32: 138
4kB (UME) 1198kB (UME) 6016kB (UME) 11232kB (UME) 4964kB (UME) 19128kB (UME) 4256kB (U) 1512kB (U) 31024kB (UME) 02048kB 124096kB (M) = 65376kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005157] Node 0 Normal: 14034kB (UME) 5898kB (UME) 53616kB (UME) 21832kB (UME) 11864kB (UME) 47128kB (UME) 7256kB (ME) 3512kB (ME) 11024kB (M) 12048kB (U) 3*4096kB (M) = 58132kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005172] Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=1048576kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005173] Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005176] 2811 total pagecache pages
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005184] 0 pages in swap cache
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005185] Swap cache stats: add 0, delete 0, find 0/0
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005185] Free swapย  = 0kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005186] Total swap = 0kB
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005187] 4194169 pages RAM
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005187] 0 pages HighMem/MovableOnly
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005189] 96534 pages reserved
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005190] 0 pages cma reserved
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005190] 0 pages hwpoisoned
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005191] Tasks state (memory values in pages):

Apr 25 19:05:01 netlogo01 kernel: [ 7097.005193] [ย  pidย  ] ย  uidย  tgid total_vmย  ย  ย  rss pgtables_bytes swapents oom_score_adj name
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005215] [ย  ย  489] ย  ย  0 ย  489ย  ย  16956 ย  ย  1002 ย  110592ย  ย  ย  ย  0ย  ย  ย  ย  ย  -250 systemd-journal
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005219] [ย  ย  520] ย  ย  0 ย  520 ย  ย  5412ย  ย  ย  928ย  ย  73728ย  ย  ย  ย  0 ย  ย  ย  ย  -1000 systemd-udevd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005232] [ย  ย  635] ย  ย  0 ย  635ย  ย  70035 ย  ย  4488ย  ย  98304ย  ย  ย  ย  0 ย  ย  ย  ย  -1000 multipathd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005235] [ย  ย  683] ย  102 ย  683ย  ย  22547ย  ย  ย  723ย  ย  81920ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 systemd-timesyn
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005239] [ย  ย  734] ย  100 ย  734 ย  ย  6643ย  ย  ย  874ย  ย  73728ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 systemd-network
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005241] [ย  ย  743] ย  101 ย  743 ย  ย  5998 ย  ย  1338ย  ย  86016ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 systemd-resolve
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005244] [ย  ย  793] ย  ย  0 ย  793ย  ย  59571ย  ย  ย  586ย  ย  98304ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 accounts-daemon
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005246] [ย  ย  803] ย  ย  0 ย  803 ย  ย  2134ย  ย  ย  556ย  ย  53248ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 cron
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005248] [ย  ย  805] ย  103 ย  805 ย  ย  1876ย  ย  ย  834ย  ย  57344ย  ย  ย  ย  0ย  ย  ย  ย  ย  -900 dbus-daemon
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005251] [ย  ย  812] ย  ย  0 ย  812ย  ย  20489ย  ย  ย  532ย  ย  65536ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 irqbalance
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005253] [ย  ย  814] ย  ย  0 ย  814 ย  ย  7319 ย  ย  2701ย  ย  98304ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 networkd-dispat
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005262] [ย  ย  815] ย  104 ย  815ย  ย  56086ย  ย  ย  528ย  ย  81920ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 rsyslogd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005264] [ย  ย  818] ย  ย  0 ย  818 ย  495509 ย  ย  3975 ย  376832ย  ย  ย  ย  0ย  ย  ย  ย  ย  -900 snapd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005266] [ย  ย  831] ย  ย  0 ย  831 ย  ย  4196ย  ย  ย  578ย  ย  73728ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 systemd-logind
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005268] [ย  ย  835] ย  ย  0 ย  835ย  ย  ย  948ย  ย  ย  490ย  ย  45056ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 atd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005270] [ย  ย  845] ย  ย  0 ย  845 ย  ย  1838ย  ย  ย  445ย  ย  53248ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 agetty
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005272] [ย  ย  863] ย  ย  0 ย  863 ย  ย  1457ย  ย  ย  386ย  ย  45056ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 agetty
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005274] [ย  ย  868] ย  ย  0 ย  868ย  ย  27026 ย  ย  2692 ย  106496ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 unattended-upgr
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005276] [ย  ย  872] ย  ย  0 ย  872 ย  ย  3043ย  ย  ย  890ย  ย  65536ย  ย  ย  ย  0 ย  ย  ย  ย  -1000 sshd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005278] [ย  ย  914] ย  ย  0 ย  914ย  ย  58178ย  ย  ย  396ย  ย  81920ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 polkitd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005282] [ ย  1066]ย  1000ย  1066 ย  ย  4596 ย  ย  1137ย  ย  73728ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 systemd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005285] [ ย  1067]ย  1000ย  1067ย  ย  42155ย  ย  ย  815 ย  102400ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 (sd-pam)
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005301] [ ย  1564]ย  1000ย  1564 ย  ย  1776ย  ย  ย  718ย  ย  53248ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 dbus-daemon
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005303] [ย  23476]ย  1000 23476 ย  359438ย  ย  19492 ย  495616ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005305] [ย  23509]ย  1000 23509ย  2427262 ย  397571ย  4079616ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005307] [ย  23510]ย  1000 23510ย  2378715 ย  389342ย  4112384ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005310] [ย  23511]ย  1000 23511ย  2393942 ย  401891ย  4206592ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005313] [ย  23512]ย  1000 23512ย  2412028 ย  472853ย  4644864ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005316] [ย  23515]ย  1000 23515ย  2394432 ย  433659ย  4300800ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005318] [ย  23517]ย  1000 23517ย  2475568 ย  494803ย  4919296ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005320] [ย  23518]ย  1000 23518ย  2381472 ย  553995ย  5267456ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005321] [ย  23519]ย  1000 23519ย  2414080 ย  425594ย  4411392ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005323] [ย  23522]ย  1000 23522ย  2396526 ย  471481ย  4628480ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 python
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005325] [ย  26579] ย  ย  0 26579 ย  ย  3449 ย  ย  1024ย  ย  65536ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 sshd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005327] [ย  26685]ย  1000 26685 ย  ย  3483ย  ย  ย  663ย  ย  65536ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 sshd
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005331] [ย  26686]ย  1000 26686 ย  ย  2512ย  ย  ย  889ย  ย  61440ย  ย  ย  ย  0 ย  ย  ย  ย  ย  ย  0 bash
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005334] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/user.slice/user-1000.slice/session-1.scope,task=python,pid=23518,uid=1000
Apr 25 19:05:01 netlogo01 kernel: [ 7097.005475] Out of memory: Killed process 23518 (python) total-vm:9525888kB, anon-rss:2215972kB, file-rss:0kB, shmem-rss:8kB, UID:1000 pgtables:5144kB oom_score_adj:0
Apr 25 19:05:02 netlogo01 kernel: [ 7097.110971] oom_reaper: reaped process 23518 (python), now anon-rss:0kB, file-rss:0kB, shmem-rss:8kB

Code:

The idea is to perform the sensitivity analysis for different settings of the base-model.

`
import json
import os
import shutil
from datetime import datetime
import numpy as np
import pandas as pd
import multiprocess as multiprocessing
from multiprocessing import set_start_methodset_start_method("spawn")
import dill
import sys
import pyNetLogo
from SALib.sample import saltelli
import time

  def initializer(modelfile, variable, setting):
      '''initialize a subprocess
  
      Parameters
      ----------
      ----------
      modelfile : str
  
      '''
  
      p = multiprocessing.current_process()
      print("Initializing Process : {}".format(p.name))
  
      if hpc:
          jvm_home = '/data/opt/tools/openjdk-16.0.0/bin/java'
          netlogo_version = '6.2'
          netlogo_home = 'netlogo_6_2_2'
  
      # we need to set the instantiated netlogo
      # link as a global so run_simulation can
      # use it
      global netlogo
  
      if hpc:
          netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_home=netlogo_home,
                                          netlogo_version=netlogo_version, jvm_home=jvm_home)
      else:
          netlogo = pyNetLogo.NetLogoLink(gui=False)
  
      netlogo.load_model(modelfile)
      netlogo.command('set {0} {1}'.format(variable, setting))
  
  def run_simulation(experiments):
  
      '''run a netlogo model
  
      Parameters
      ----------
      experiments : dict
      '''
  
      #print("Start experiment {}".format(experiments))
  
      # Set the input parameters
      for key, value in experiments.items():
          if key == 'random-seed':
              # The NetLogo random seed requires a different syntax
              netlogo.command('random-seed {}'.format(value))
          else:
              # Otherwise, assume the input parameters are global variables
              netlogo.command('set {0} {1}'.format(key, value))
  
      netlogo.command('setup')
  
      counts = netlogo.repeat_report([dv], ticks, include_t0=False)
  
      results = pd.Series([counts[dv].values.max()], index=[dv])
      
      return results
  
  
  current_module = sys.modules[__name__]
  work = [current_module]
  dill.detect.trace(True)
  dill.pickles(work)
  
  if __name__ == '__main__':
  
  ....
      for variable, settings in dct_model_settings.items():
          for setting in settings:
  
              path_model_results = os.path.join(path_results, '{}_{}.csv'.format(variable, setting))
  
              if not os.path.exists(path_model_results):
                  os.mkdir(path_model_results)
  
              t0 = time.time()
          
              p = 2 * len(dct_sa_settings.keys()) + 2
  
              print("Start experiments:{} -- v: {} -- set:{}".format(exp_runs * p, variable, setting))
          
              ### Create experiments
          
              experiments = pd.DataFrame(param_values, columns=dct_problem['names'])
          
              ### Multiprocessing
          
              map_result = multiprocessing.Pool(None,
                                                initializer=initializer,
                                                initargs=(modelfile, variable, setting,)).map(run_simulation,
                                                                           experiments.to_dict('records'))
          
              print(map_result)
          
              results = pd.DataFrame(map_result)

`

Netlogo 6.2.0 with pyNetLogo

Dear Devs,

I'm using Netlogo for my final year project and have ran into issues running the Example1 on your documentation. Below is my code and error.

image

image

I'm running windows 10, I have reinstalled netlogo once to see if it was a path issue, It seems to be a version issue and was wondering if pynetlogo works with netlogo 6.2 or should I install an older version.

Java version is:
java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)

Python Version:
Python 3.7.6

Jpype:
image

Reporting a 3D list from netlogo gives error

I want to report a 3D list from NetLogo in python using pyNetLogo.

I am running a NetLogo model with "n" turtles. Each day turtles investigate the world and generate 8 values which I save in a list named 'today-value' and I keep a list of list 'turtle-table-daily' to keep values of all days of each turtle.

initialisation:
set turtle-table-daily (list 0 0 0 0 0 0 0 0)

and in each day:
set turtle-table-daily lput today-value turtle-table-daily

So after "K" days, for each agent I have a K*8 list.

I want to report a list where each row of it is 'turtle-table-daily' of one turtle. Here is what I did:

to create-output-table
let X count turtles
set global-table-daily n-values X [0]

let i 0
while [ i < X ] [
ask turtles with [who = i] [
set global-table-daily replace-item i global-table-daily turtle-table-daily
set i i + 1
]]
end

to-report tableGlobal
report global-table-daily
end

So, global-table-daily is a list of nK8.

Finally, in python, I call NetLogo using pyNetLogo and after running the model I ask for reporting tableGlobal:

netlogo.report('tableGlobal')
But I get the following error: 'NetLogoLinkV6.NLResult' object is not iterable

Any help?

repeat_report doesn't report final tick

For instance:

> print(netlogo.repeat_report(["ticks"], 1))

     ticks
0.0      0

> print(netlogo.repeat_report(["ticks"], 1))

     ticks
1.0      1

> print(netlogo.repeat_report(["ticks"], 1))

     ticks
2.0      2

As can be seen here, go is being called once on each call. The output of reporters is being returned from before the call but not after the call. That is, you get the initial state of the model but not the final state of the model.

Licensing terms?

Hi.

Thanks for developing pyNetLogo!

What license are you releasing this project under?

Also, I've created a pull request with a small fix.

Thanks.

Unable to load NetLogo version 5

I am unable to load NetLogo version 5. I keep getting the error java.lang.RuntimeException: Class NetLogoLinkV5.NetLogoLink not found:

>>> netlogo = pyNetLogo.NetLogoLink(gui=False, netlogo_version='5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/pyNetLogo/core.py", line 255, in __init__
    link = jpype.JClass(module_name[self.netlogo_version])
  File "/usr/local/lib/python3.7/site-packages/jpype/_jclass.py", line 73, in JClass
    raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class NetLogoLinkV5.NetLogoLink not found

I'm using macOS Mojave.
Python version is: Python 3.7.2 installed via Homebrew
Install location for Python: /usr/local/bin/python3
The default java jvm is:

>>> jpype.getDefaultJVMPath()
'/Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home/lib/jli/libjli.dylib'

Version 6 loads normally. However, I do need version 5.

jpype depedency not correctly specified in pip

While installing pyNetLogo with pip, its dependencies should be automatically pulled, however jpype is not and must be installed manually in a separate command with pip install jpype1. Not a big deal, but still a bug in my book

reps in repeat_report not matching the ticks

Hello,
I have to measure the time in Netlogo and got this problem. I summed it up to keep the essential:

In Netlogo.

globals [
  time
  step-time
]

to setup
  clear-all
  reset-ticks
  set time 0
  set step-time 0.1
end

to go
  every step-time [
    set time (time + step-time)
    tick
  ]
end

So I have one tick every 0.1s. But when I use pynetlogo with this code:

import pyNetLogo
import matplotlib.pyplot as plt

netlogo = pyNetLogo.NetLogoLink(gui=True)
netlogo_file = "pb_pynetlogo.nlogo"
netlogo.load_model(netlogo_file)
netlogo.command('setup')

t = netlogo.repeat_report(['time'], 10000, go='go') 
plt.figure()
plt.plot(t)
plt.show()

netlogo.kill_workspace()

I get this graph. I'm stuck at tick 2, I don't know what does 10000 correspond to exactly.

step_time

Maybe I should put what follows in an another issue, but I tried to use another function to bypass this problem.
I used :

t = netlogo.report_while(['time'], 'True', command='go')

And got the error message :

 File "C:\Users\...\lib\site-packages\pyNetLogo\core.py", line 389, in report_while
    result = self.link.doReportWhile(command, netlogo_reporter, condition, max_seconds)
AttributeError: 'NetLogoLinkV61.NetLogoLink' object has no attribute 'doReportWhile'

I thought of updating pynetlogo with the current version on Github but I got another Java error (52 can't run 59 or something like that, I don't seem it is relevant.)

Would it be possible to obtain a list of global variables and initial settings when a model is loaded?

First of all, thanks for building this package which I am just learning how to use.

Regarding my question, I am envisioning a function called get_globals(), called after the model is loaded. With the wolf and sheep model used to illustrate how pyNetLogo works, a call to get_globals() could return the following dict:

{'grass-regrowth-time': {'minimum': 0, 'increment': 1, 'maximum': 250, 'value': 30},
'sheep-gain-from-food': {as above},
'wolf-gain-from-food': {as above},
'sheep-reproduce': {as above},
'wolf-reproduce': {as above}}

The creation of the dict "problem" could then be partially automated, parameterized, and less dependent on cutting and pasting between the Python script and the NetLogo model. Likewise for the definition of the function run_simulation.

In any case, thanks again for this development. Python and NetLogo together present some real possibilities for creating very useful ABMs.

ipyparallel with pynetlogo Example 2 not working

I found an Example to parallelize simulations for pynetlogo using ipyparallel documented here:
Example 2: Sensitivity analysis for a NetLogo model with SALib and ipyparallel

Following this guide, I cannot perform the simulations due to an error given when using the map_sync method. I have tested if netlogo loads properly, which is does. The code I use and the resulting error are given in the following. I sticked simply to the original code provided in the link above with some minor adaptions of netlogo_home, netlogo_version, cwd, n and ticks.

#Ensuring compliance of code with both python2 and python3

from __future__ import division, print_function
try:
    from itertools import izip as zip
except ImportError: # will be 3.x series
    pass
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
sns.set_context('talk')


import pyNetLogo

#Import the sampling and analysis modules for a Sobol variance-based
#sensitivity analysis
from SALib.sample import saltelli
from SALib.analyze import sobol

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 = 1 #test value
param_values = saltelli.sample(problem, n, calc_second_order=True)

#param_values.shape


import ipyparallel

client = ipyparallel.Client()
#client.ids

direct_view = client[:]

import os

#Push the current working directory to a "cwd" variable on the engines that can be accessed later
direct_view.push(dict(cwd=os.getcwd()))
cwd=os.getcwd()

#Push the "problem" variable from the notebook to a corresponding variable on the engines
direct_view.push(dict(problem=problem))

##%%px

import os
os.chdir(cwd)

import pyNetLogo
import pandas as pd

netlogo = pyNetLogo.NetLogoLink(gui=False, \
                                netlogo_version = "6", \
                                netlogo_home = "D:\\Programme\\Netlogo" \
                                )
netlogo.load_model(r'Wolf Sheep Predation_v6.nlogo')


def simulation(experiment):

    #Set the input parameters
    for i, name in enumerate(problem['names']):
        if name == 'random-seed':
            #The NetLogo random seed requires a different syntax
            netlogo.command('random-seed {}'.format(experiment[i]))
        else:
            #Otherwise, assume the input parameters are global variables
            netlogo.command('set {0} {1}'.format(name, experiment[i]))

    netlogo.command('setup')
    #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'], 1)

    results = pd.Series([counts['count sheep'].values.mean(),
                         counts['count wolves'].values.mean()],
                         index=['Avg. sheep', 'Avg. wolves'])

    return results

lview = client.load_balanced_view()

results = pd.DataFrame(lview.map_sync(simulation, param_values))

results.to_csv('Sobol_parallel.csv')

results.head(5)

Resulting in multiple Error messages:

[0:apply]: 
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<string> in <module>()
d:\programme\anaconda\lib\site-packages\ipyparallel\client\remotefunction.py in <lambda>(f, *sequences)
    141 
    142 if sys.version_info[0] >= 3:
--> 143     _map = lambda f, *sequences: list(map(f, *sequences))
    144 else:
    145     _map = map
C:/Users/..../myfile.py in simulation(experiment)
     88         if name == 'random-seed':
     89             #The NetLogo random seed requires a different syntax
---> 90             netlogo.command('random-seed {}'.format(experiment[i]))
     91         else:
     92             #Otherwise, assume the input parameters are global variables
NameError: name 'netlogo' is not defined

10 more exceptions ...

Default NetLogo cannot be found

Hello,

I'm trying to run pynetlogo, but I'm getting this error:

image

I built NetLogo (https://github.com/NetLogo/NetLogo/wiki/Building) in a Linux system (centOS) and have Liberica JDK 8 installed. The warning comes up when core.py is trying to check if the default extension folder exists. It's checking under an 'app' folder that I don't have in my NetLogo folder.

Do you know what I should do in this case?

Thanks,
Agnes

__includes["..."]extensions [gis]

1.) Within my NetLogo file I work with a "gis extension", defined at the beginning of the Code in the NetLogo file by extensions [gis]. When opening the NetLogo file manually and not through python everything works fine.
However, when starting the NetLogo file through python using netlogo.load_model(...) the GUI of NetLogo opens, but an error message appears saying "Can't find extension: gis".

2.) Within my NetLogo file I have separated the code and have outsourced certain procedures from the main code into a different file which I read in at the beginning of the NetLogo Code by using __includes["file_name"]. When opening the NetLogo file manually and not through python everything works fine and I can start e.g. the setup procedure from the NetLogo GUI.
However, when trying to setup the NetLogo model through python using netlogo.command('setup') I receive the following error message in python: "NetLogoException: Nothing named SETUP has been defined."

Thank you for helping me out :)

pyNetLogo with Dash and Plotly

Dear Devs,

I'm using Netlogo for my final year project and have ran into an unusual issue. I've searched the web and talked to my supervisor but I could not solve the issue and was wondering if you could help me.

My project is Visualising Public Health Interventions Using Agent-Based Modelling, for this I have a tech stack of Netlogo -> Python -> Dash.
However some of the pynetlogo commands won't run when called in a callback function from Dash, example below:

image

Here the netlogo.load_model(model) line works, but when I used the netlogo.command() function for any button I have in my model it wil return this error:

java.lang.NullPointerException
at org.nlogo.generate.CustomClassLoader.loadClass(CustomClassLoader.scala:28)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at org.nlogo.generate.CustomClassLoader.loadClass(CustomClassLoader.scala:27)
at org.nlogo.generate.CustomClassLoader.loadBytecodeClass(CustomClassLoader.scala:32)
at org.nlogo.generate.Generator$InstructionGenerator.finish(Generator.scala:254)
at org.nlogo.generate.Generator$InstructionGenerator.generate(Generator.scala:105)
at org.nlogo.generate.Generator.org$nlogo$generate$Generator$$recurse(Generator.scala:29)
at org.nlogo.generate.Generator.$anonfun$generate$1(Generator.scala:25)
at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:237)
at scala.collection.IndexedSeqOptimized.foreach(IndexedSeqOptimized.scala:36)
at scala.collection.IndexedSeqOptimized.foreach$(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:198)
at scala.collection.TraversableLike.map(TraversableLike.scala:237)
at scala.collection.TraversableLike.map$(TraversableLike.scala:230)
at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:198)
at org.nlogo.generate.Generator.generate(Generator.scala:25)
at org.nlogo.compile.CompilerMain$.assembleProcedure(CompilerMain.scala:86)
at org.nlogo.compile.CompilerMain$.$anonfun$compile$1(CompilerMain.scala:62)
at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:237)
at scala.collection.immutable.List.foreach(List.scala:392)
at scala.collection.TraversableLike.map(TraversableLike.scala:237)
at scala.collection.TraversableLike.map$(TraversableLike.scala:230)
at scala.collection.immutable.List.map(List.scala:298)
at org.nlogo.compile.CompilerMain$.compile(CompilerMain.scala:62)
at org.nlogo.compile.Compiler.compileMoreCode(Compiler.scala:86)
at org.nlogo.compile.Compiler.compileMoreCode(Compiler.scala:100)
at org.nlogo.workspace.Evaluator.invokeCompiler(Evaluator.scala:159)
at org.nlogo.workspace.Evaluator.evaluateCommands(Evaluator.scala:20)
at org.nlogo.workspace.Evaluating.evaluateCommands(Evaluating.scala:28)
at org.nlogo.workspace.Evaluating.evaluateCommands$(Evaluating.scala:27)
at org.nlogo.workspace.AbstractWorkspaceScala.evaluateCommands(AbstractWorkspaceScala.scala:26)
at org.nlogo.app.App.command(App.scala:964)
at NetLogoLinkV61.NetLogoLink.command(NetLogoLink.java:180)

java.lang.NullPointerException
at org.nlogo.generate.CustomClassLoader.loadClass(CustomClassLoader.scala:28)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at org.nlogo.generate.CustomClassLoader.loadClass(CustomClassLoader.scala:27)
at org.nlogo.generate.CustomClassLoader.loadBytecodeClass(CustomClassLoader.scala:32)
at org.nlogo.generate.Generator$InstructionGenerator.finish(Generator.scala:254)
at org.nlogo.generate.Generator$InstructionGenerator.generate(Generator.scala:105)
at org.nlogo.generate.Generator.org$nlogo$generate$Generator$$recurse(Generator.scala:29)
at org.nlogo.generate.Generator.$anonfun$generate$1(Generator.scala:25)
at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:237)
at scala.collection.IndexedSeqOptimized.foreach(IndexedSeqOptimized.scala:36)
at scala.collection.IndexedSeqOptimized.foreach$(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:198)
at scala.collection.TraversableLike.map(TraversableLike.scala:237)
at scala.collection.TraversableLike.map$(TraversableLike.scala:230)
at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:198)
at org.nlogo.generate.Generator.generate(Generator.scala:25)
at org.nlogo.compile.CompilerMain$.assembleProcedure(CompilerMain.scala:86)
at org.nlogo.compile.CompilerMain$.$anonfun$compile$1(CompilerMain.scala:62)
at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:237)
at scala.collection.immutable.List.foreach(List.scala:392)
at scala.collection.TraversableLike.map(TraversableLike.scala:237)
at scala.collection.TraversableLike.map$(TraversableLike.scala:230)
at scala.collection.immutable.List.map(List.scala:298)
at org.nlogo.compile.CompilerMain$.compile(CompilerMain.scala:62)
at org.nlogo.compile.Compiler.compileMoreCode(Compiler.scala:86)
at org.nlogo.compile.Compiler.compileMoreCode(Compiler.scala:100)
at org.nlogo.workspace.Evaluator.invokeCompiler(Evaluator.scala:159)
at org.nlogo.workspace.Evaluator.evaluateCommands(Evaluator.scala:20)
at org.nlogo.workspace.Evaluating.evaluateCommands(Evaluating.scala:28)
at org.nlogo.workspace.Evaluating.evaluateCommands$(Evaluating.scala:27)
at org.nlogo.workspace.AbstractWorkspaceScala.evaluateCommands(AbstractWorkspaceScala.scala:26)
at org.nlogo.app.App.command(App.scala:964)
at NetLogoLinkV61.NetLogoLink.command(NetLogoLink.java:180)

Sorry for the long error message but I'm not sure what to do, I would really like to create buttons in Dash that will make callbacks to netlogo to do things such as Setup and Go, and show the visualisation on a Dashboard like Dash that could be included on websites or news articles.

Allow for heterogeneous lists

Currently, attempting to report a heterogeneous list gives a ParseException pyNetLogo attempts to the elements of a LogoList based on the type first element:

> netlogo.report('["hi" 8]')

java.text.ParseException: Java error in converting result: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
	at NetLogoLinkV61.NLResult.cast_logolist(NLResult.java:179)
	at NetLogoLinkV61.NLResult.logoToType(NLResult.java:69)
	at NetLogoLinkV61.NLResult.setResultValue(NLResult.java:15)
	at NetLogoLinkV61.NetLogoLink.report(NetLogoLink.java:198)

Heterogeneous lists are quite useful, especially when associating results with parameters.

It should be possible to return heterogeneous lists by leaving the LogoList elements boxed and converting to an object array (instead of a value array), or surfacing the LogoList to jpype directly and converting on the Python side (though I don't know much about jpype). These options could have a performance hit depending on how jpype's memory sharing works, but they could be done as fallback options when returning a value array would fail.

InvocationTargetException when opening model Linux

I am running Ubuntu 18.10
Python 3.6.7 in virtualenv
Jupyter notebook
Oracle Java 11
NetLogo 6.1.0

import pyNetLogo
netlogo = pyNetLogo.NetLogoLink(gui=True,netlogo_home='/home/ric/Software/NetLogo/', netlogo_version='6')
this does start nlogo
netlogo.load_model('/home/ric/Projects/NetLogo/agent01.nlogo')
this produces a InvocationTargetException form NetLogo
when dismissed produces the following from the python code
java.lang.RuntimeExceptionPyRaisable Traceback (most recent call last)
~/Projects/Python/env/lib/python3.6/site-packages/pyNetLogo/core.py in load_model(self, path)
282 try:
--> 283 self.link.loadModel(path)
284 except jpype.JavaException as ex:

java.lang.RuntimeExceptionPyRaisable: java.lang.RuntimeException

During handling of the above exception, another exception occurred:

NetLogoException Traceback (most recent call last)
in
----> 1 netlogo.load_model('agent01.nlogo')

~/Projects/Python/env/lib/python3.6/site-packages/pyNetLogo/core.py in load_model(self, path)
283 self.link.loadModel(path)
284 except jpype.JavaException as ex:
--> 285 raise NetLogoException(ex.message())
286
287 def kill_workspace(self):

NetLogoException: None

I have tried placing the netlogo model in the same directory and replacing it with a model from the examples

However
If i run
netlogo = pyNetLogo.NetLogoLink(gui=True,netlogo_home='/home/ric/Software/NetLogo/', netlogo_version='6')

then open the file from within the netlogo running instance ( ie from the menu)
I can call the procedures from with in the jupyter script
ie
netlogo.command('setup')
will work.
So the problem is in loading the model with load_model

I cant see any other attributes that are required for load_model from the documentation.
What am I doing wrong?
Your help would be much appreciated

Flexibly change the variable value

Is there a way to systematically change the variable value (e.g. sheep/wolf qty) in the netlogo.command() where the variable is surrounded by the quotes...

5

Model with R-Extension crashes

Dear authors of pyNetLogo,

I have a NetLogo model which uses the R-Extension to run R commands within the NetLogo model.

I would like to use PyNetLogo to automate work with multiple instances but I am unable to load_model that uses the R Extension in any way. One can replicate using any of the example netlogo models provided with the R-Extension included since NetLogo 6.04

import pyNetLogo
netlogo = pyNetLogo.NetLogoLink(gui=True)
netlogo.load_model('C:/Program Files/NetLogo 6.0.4/app/extensions/r/models/example1.nlogo')

Copying the entire R extension as in issue #13 does not solve this issue unfortunately. I would appreciate any help!

EDIT:
I have been able to get around this issue in one sense by setting JAVA_HOME environment variable to point to NetLogo's own internal JVM. However I fear this is not a long term solution as the official installation instructions (from the JPype instructions) point towards setting JAVA_HOME to whatever JDK is installed.

PyNetLogo on Linux cluster - NameError when running the pd.DataFrame

Hello everyone!

This is my first post here so I hope it's the right place to ask my question - please let me know if not :-)

I try to use PyNetLogo to run a global sensitivity analysis on a computer cluster that runs on Linux centos. I am following the PyNetLogo documentation for the Sobol sensitivity analysis pretty closely but unfortunately keep encountering an error when trying to run this line: results = pd.DataFrame(lview.map_sync(simulation, param_values)) :

NameError: name 'netlogo' is not defined (see full error message below and attached).

I designed the model in NetLogo 6.2.0, but use a 6.0.4. version on the cluster since the 6.2.0 version gave me problems. I tried using PyNetLogo 0.3, 0.4.1 and 0.4.2, but unfortunately the error persists. Java version is 11.0.11.
I'm also working with the cluster computer service team on this issue, but they are running out of ideas, which is why I'm posting here :)

Any tips and suggestions are highly recommended - thanks a lot in advance

All the best,
Marius

0:apply]: ---------------------------------------------------------------------------NameError Traceback (most recent call last)<string> in <module> ~/.local/lib/python3.6/site-packages/ipyparallel/client/remotefunction.py in <lambda>(f, *sequences) 141 142 if sys.version_info[0] >= 3: --> 143 _map = lambda f, *sequences: list(map(f, *sequences)) 144 else: 145 _map = map <ipython-input-13-647b15be93cd> in simulation(experiment) NameError: name 'netlogo' is not defined
[1:apply]: ---------------------------------------------------------------------------NameError Traceback (most recent call last)<string> in <module> ~/.local/lib/python3.6/site-packages/ipyparallel/client/remotefunction.py in <lambda>(f, *sequences) 141 142 if sys.version_info[0] >= 3: --> 143 _map = lambda f, *sequences: list(map(f, *sequences)) 144 else: 145 _map = map <ipython-input-13-647b15be93cd> in simulation(experiment) NameError: name 'netlogo' is not defined
[2:apply]: ---------------------------------------------------------------------------NameError Traceback (most recent call last)<string> in <module> ~/.local/lib/python3.6/site-packages/ipyparallel/client/remotefunction.py in <lambda>(f, *sequences) 141 142 if sys.version_info[0] >= 3: --> 143 _map = lambda f, *sequences: list(map(f, *sequences)) 144 else: 145 _map = map <ipython-input-13-647b15be93cd> in simulation(experiment) NameError: name 'netlogo' is not defined
[3:apply]: ---------------------------------------------------------------------------NameError Traceback (most recent call last)<string> in <module> ~/.local/lib/python3.6/site-packages/ipyparallel/client/remotefunction.py in <lambda>(f, *sequences) 141 142 if sys.version_info[0] >= 3: --> 143 _map = lambda f, *sequences: list(map(f, *sequences)) 144 else: 145 _map = map <ipython-input-13-647b15be93cd> in simulation(experiment) NameError: name 'netlogo' is not defined ... 60 more exceptions ... 

Capture

Using PyQT5 to start NetLogo

Hi,

I am developing a GUI app using PyQt5 to start NetLogo 3D using pyNetLogo. I simply add a button in the UI and bing the click event to its function to call NetLogo. However, the opened 3D view showed just like this (the world size is reduced as the below image shown):

problem

My program is below:

import PyQt5
import pyNetLogo
from PyQt5 import QtCore,  QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from test1 import Ui_MainWindow
import ctypes
import sys

class NetLogoWin(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(NetLogoWin, self).__init__(parent)
        self.setupUi(self)
        self.btn_start.clicked.connect(self.start_netlogo)

    def start_netlogo(self):
        self.netlogo = pyNetLogo.NetLogoLink(gui=True, thd=True
                                             )
if __name__ == "__main__":
    app = QApplication(sys.argv)

    myWin = NetLogoWin()
    myWin.show()
    try:
        r = app.exec_()
    except Exception as err:
        print(err)

Are there any solution to solve this? Thanks!

Failure to assign attributes - UnboundLocalError

While following the Example1 from readthedocs, it is not possible to assign attributes using:

netlogo.write_NetLogo_attriblist(agent_xy[['who','xcor','ycor']], 'a-sheep')

The following error appears:
UnboundLocalError: local variable 'commandstr' referenced before assignment

All packages are installed successfully and NetLogo opens correctly. However, here (and the following commands in Example 1) I get stuck.

jpype.startJVM arguments

line 245 in core.py causing a TypeError due to argument 'convertStrings':
TypeError: startJVM() got an unexpected keyword argument 'convertStrings'
After removing this argument everything executes as expected. Please update the except case to try to start JVM without this parameter.

line 245:
jpype.startJVM(jvm_home, convertStrings=False, *jvm_args)

Parameter optimization using "ipyparallel"

Hi, I would like to determine the value of a certain input variable of my NetLogo file in order to get an output result that matches a predefined value best (Optimisation of input value).
Therefore I would like to...
(1.1) ... set a particular value for my input variable and run the program 100 times for this input value,
(2.1) ... take the median of the results of all 100 runs and compare this median to my intended output value,
(1.2) ... adjust the value for my input variable and run the program again 100 times for the new input value,
(2.2.) ... and so on.

While just using one core of my cpu it works fine. Now, in order to speed the process up I would like to parallelize the simulations. This means, I would like to distribute the 100 runs to all my cpu cores, then analyse the median result, set a new input value and again distribute the next 100 runs across the cores.

Optimally I would like to only define the particular input value for which the program needs to be executed 100 times while the distribution of the runs across the cores is managed automatically.

Every of the 100 runs starts with a new complete setup of the program and undergoes the go-procedure a predetermined amount of times.

Does anyone have an idea how to implement this best? :)
Thank you!

Netlogo Extension not found

Hello,
I want to use pynetlogo on a netlogo file that includes a netlogo extension. I use the extension nw for network applications, which is properly installed and when opening netlogo without python, it works just fine. However, using pynetlogo gives me an error, stating that the extension cannot be found.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.