netlogo-connector.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import pyNetLogo
  2. import pprint, time
  3. def turtles_created(new_turtles):
  4. for turtle_idx in set(new_turtles.keys()) - set(turtles.keys()):
  5. print "Turtle %i created." % turtle_idx
  6. def turtles_deleted(new_turtles):
  7. for turtle_idx in set(turtles.keys()) - set(new_turtles.keys()):
  8. print "Turtle %i deleted." % turtle_idx
  9. link = pyNetLogo.NetLogoLink(gui=False,
  10. netlogo_home="C:\\Program Files\\NetLogo 6.0.3",
  11. netlogo_version="6")
  12. turtles = {}
  13. link.load_model('BouncingBalls.nlogo')
  14. link.command("setup")
  15. print "Ready to go..."
  16. print link.report("reflection:turtles")
  17. state = "paused"
  18. to_setup = False
  19. ignored_attributes = set(["WHO", "HEADING", "SHAPE", "LABEL", "LABEL-COLOR", "BREED", "HIDDEN?", "PEN-SIZE", "PEN-MODE"])
  20. def user_inputter():
  21. global state
  22. global to_setup
  23. while 1:
  24. cmd = raw_input()
  25. if cmd == "reset":
  26. to_setup = True
  27. elif cmd == "step":
  28. state = "stepping"
  29. elif cmd == "continuous":
  30. state = "continuous"
  31. elif cmd == "pause":
  32. state = "paused"
  33. else:
  34. print "invalid command %s" % cmd
  35. import threading
  36. thrd = threading.Thread(target=user_inputter)
  37. thrd.start()
  38. while 1:
  39. if state in ["stepping", "continuous"]:
  40. start_time = time.time()
  41. link.command("go")
  42. #attr_names = [attr_name for attr_name in link.report('last last reflection:breeds') if attr_name not in ["WHO", "HEADING", "SHAPE", "LABEL", "LABEL-COLOR", "BREED", "HIDDEN?", "PEN-SIZE", "PEN-MODE"]]
  43. #new_turtles = {int(turtle_id): {attr_name: str(link.report('[' + attr_name + '] of turtle ' + str(turtle_id))) for attr_name in attr_names} for turtle_id in link.report('[who] of turtles')}
  44. attr_names = link.report('last last reflection:breeds')
  45. all_turtle_attributes = link.report("reflection:turtles")
  46. new_turtles = {}
  47. for turtle_attributes in all_turtle_attributes:
  48. the_turtle = dict(zip(attr_names, turtle_attributes.getResultAsObject()))
  49. new_turtles[int(float(the_turtle["WHO"]))] = the_turtle
  50. new_turtles = {k: {ak: av for ak, av in new_turtles[k].iteritems() if ak not in ignored_attributes} for k in new_turtles.keys()}
  51. turtles_created(new_turtles)
  52. turtles_deleted(new_turtles)
  53. turtles = new_turtles
  54. pprint.pprint(new_turtles)
  55. if state == "stepping":
  56. state = "paused"
  57. print time.time() - start_time
  58. if to_setup:
  59. link.command("setup")
  60. to_setup = False
  61. print "Done"