Sundararajan's Weblog

Fun with NetLogo using Nashorn JavaScript engine

NetLogo is a multi-agent programmable modeling environment running for the Java platform. In addition to being a GUI program to edit and run NetLogo models, NetLogo supports Controlling API so that NetLogo can be invoked and controlled by a program running on JVM. The "controlling api" supports both GUI and 'headless' mode.

I used Nashorn javascript engine to use NetLogo "controlling API" from a script. I ran the bundled Maxwell's demon model in "headless mode" using the following Nashorn script:

File: nl_maxwell_demon.js

// NetLogo "controlling API" example in Nashorn
// java classes used
var HeadlessWorkspace = org.nlogo.headless.HeadlessWorkspace;
var Thread = java.lang.Thread;
// set the thread context loader for correct working of NetLogo!
Thread.currentThread().contextClassLoader = HeadlessWorkspace.class.classLoader;
// new headless workspace
var ws = HeadlessWorkspace.newInstance();
// change this as per your installation directory!
// My NetLogo installation dir is "C:\Program Files (x86)\NetLogo 5.2.1"
var NL = "C:\\Program Files (x86)\\NetLogo 5.2.1\\";
ws.open(NL + "models\\Curricular Models\\GasLab\\GasLab Maxwells Demon.nlogo");
// setup and call "go" (100 iterations)
ws.command("repeat 100 [ go ]");
// print average left and right speeds
print("average speed (left) = " + ws.report("avg-speed-left"));
print("average speec (right) = " +ws.report("avg-speed-right"));
// We're done!

I used the jjs nashorn shell command to run the above script:

$ jjs -cp "C:\\Program Files (x86)\\NetLogo 5.2.1\\NetLogo.jar" nl_maxwell_demon.js
average speed (left) = 8.712072244000128
average speec (right) = 9.08120463863075

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.