Search code examples
pythonembednetlogo

Can Python code be included into the body of NetLogo code?


As the title suggests, I am looking for a way to embed Python code into NetLogo. So far I have found the NetLogo Python extension but from my understanding this extension only runs in the NetLogo prompt below (where you put the Observer/Turtle/etc. commands), so more like a built-in interpreter.

My question is whether there is a way, using this extension or otherwise, to embed Python code into the body of a NetLogo project, for example like this:

; This is an extract of some method/subroutine
  print global-peopleNum

  (py:run
    "print('hello')"
  )

  set-patch-size 20
; other regular NetLogo code

so that it resembles compiled code as opposed to interpreted.


Solution

  • You can embed Python code directly into NetLogo code using the Python extension, it is not usable only through the command center. Check out the Python Basic Example and Python Flocking Clusters models that come with NetLogo in the models library.

    Here is the code from the Python Basic Example model:

    extensions [ py ]
    
    to setup ; Here we setup the connection to python and import a few libraries
      py:setup py:python
      py:run "import math"
      py:run "import sys"
      py:run "import os"
      reset-ticks
    end
    
    to go ; make sure everything is ready to go!
      py:run "print('go!')"
    end
    
    to get-sys-info ; Here we use the `sys` package in python to output some system info
      output-print (word "Python directory: " (py:runresult "sys.prefix"))
      output-print (word "Platform: " (py:runresult "sys.platform"))
      output-print (word "Python copyright: " (py:runresult "sys.copyright"))
      output-print ""
    end
    
    to gcd ; Use the `math` package's built-in gcd method to calculate the gcd(a,b)
      py:set "a" a
      py:set "b" b
      let result py:runresult "math.gcd(a, b)"
      output-print (word "Greatest common divisor of " a " and " b " is: " result)
      output-print ""
    end
    
    to get-home-directory ; Use the `os` package to get the home directory of the system
      let home-dir py:runresult "os.environ['HOME']"
      output-print (word "Current home directory is: " home-dir)
      output-print ""
    end
    
    to join-strings ; join some strings in python
      let result joined-strings
      output-print (word "Here they are joined: " result)
      output-print ""
    end
    
    to-report joined-strings ; helper procedure to join strings using a delimiter
      py:set "delim" delimiter
      py:set "list" read-from-string string-list
      report py:runresult "delim.join(list)"
    end
    
    to to-upper-case ; upper case some Strings in Python
      let result joined-strings
      py:set "result" result
      set result py:runresult "result.upper()"
      output-print (word "Here they are in upper case: " result)
      output-print ""
    end