tags:

views:

52

answers:

2

Hi,

I am trying to get coordinates for turtles in NetLogo by using the Java API. I have managed to get the workspace loaded and have been using the following code that I made:

public static int getX(HeadlessWorkspace workspace, String playerName, int agentNum)
{

    Double doubleX = null;
    int xVal = 0;
    try
    {
        xVal = doubleX.valueOf((workspace.report("[xcor] of "+playerName+" "+agentNum).toString()).trim()).intValue();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return xVal;
}

However, there is one small problem. It is extremely slow when there are more than 5 turtles. When I run the Flocking code with 200 turtles, without getting the coordinates, then I get about 300 ticks in 10 seconds. When I run the code with the coordinates, then each tick takes about 3 seconds. Is there a more efficient way of achieving this?

Thanks,

Nadim

A: 

So, you are using the Java API just so you can get the

[xcor] of "bob" 10

I am very confused.

I can tell you that your workspace.report() call above is very expensive as you are asking netlogo to parse then evaluate the expression you create, then you parse it into an integer to pass back to netlogo.

It seems it would be much easier to just store all the players in a list or map and refer to them by their index in the list. That is, I don't think you need to use the API to do what you seem to be doing.

Jose M Vidal
Hi jmvidal,I was writing a program in Java that makes use of NetLogo to do the processing, and thus I needed to use the Java API. I couldn't find an easy way of using the API and I had found this workaround. Unfortunately as you have rightly mentioned, it is an expensive workaround. I managed to find out how to do the code and have reproduced it below.Thanks,Nadim
Nadim
+1  A: 

I managed to find out what the proper way should be. This is the code in the NetLogo mailing list as given by Seth Tisue.

import org.nlogo.headless.*;
import org.nlogo.api.*;
class J {
   public static void main(String[] args) {
      try {
         HeadlessWorkspace ws = HeadlessWorkspace.newInstance();
         ws.openString(org.nlogo.util.Utils.url2String("/system/empty.nlogo"));
         ws.command("cro 8 [ fd 5 ]");
         org.nlogo.api.Turtle turtle =(org.nlogo.api.Turtle) ws.world().turtles().agent(3);
         System.out.println("[xcor] of turtle 3 = " + turtle.xcor());
         ws.dispose();
      }
      catch(Exception ex) {
         ex.printStackTrace();
      }
   }
}

I have reproduced the code here so it may benefit others. To see a list of what information you can get from Turtle, look at the NetLogo API documentation.

Nadim

Nadim