John Peach

Mind-sized STEM ideas and experiments, beyond the textbook.

Introduction to NetLogo.png

Home

keywords: agent-based modeling, emergent systems, NetLogo tutorial, simulation software, predator-prey model

Have you ever wondered how a flock of birds moves in perfect synchronization, or how ant colonies manage to find the most efficient paths to food? These fascinating phenomena emerge from simple rules followed by individual agents, creating complex patterns that seem almost magical. Today, I'm going to introduce you to NetLogo, a powerful tool that lets you explore and create these kinds of emergent systems through agent-based modeling.

Imagine being able to simulate a world where wolves chase sheep, where cities grow organically, or where diseases spread through populations - all by writing a few simple rules. That's exactly what NetLogo allows you to do. In this article, I'll show you how to write a simple program that produces a surprising and beautiful outcome. But I won't reveal the result just yet - you'll need to download the software and try it yourself to experience the magic of emergence firsthand.

Whether you're a curious citizen scientist, a researcher, or just someone fascinated by how complex systems work, NetLogo offers an accessible way to explore these ideas through hands-on experimentation. Let's dive in and discover how simple rules can create extraordinary results.

Interface

When you first start NetLogo you'll see a screen like this: netlogo-start-screen.png

The black square is the environment or world where agents move and follow the instructions you've written. The white area to the left is reserved for buttons, sliders, plots, and other interactive devices. At the bottom are the Command Center and a blank space where you can enter one line commands as the observer.

You write agent commands in the Code tab, and the Info tab is where you document your model.

A Sample Problem

When you install NetLogo you'll get hundreds of agent-based model examples. This sample problem is a slight variant of the Turtles Circliing Simple.nlogo program from Uri Wilensky and William Rand's book, "An Introduction to Agent-Based Modeling: Modeling Natural, Social, and Engineered Complex Systems with NetLogo". In NetLogo, agents are called "turtles" unless you rename them (to sheep or wolves or something).

Start NetLogo, and when you see the initial screen, as shown above, click on the Code tab to begin writing the functions for this simulation. Almost all NetLogo programs have two required features - a Setup function and a Go function. The Setup initializes the simulation, arranging the turtles and giving them their starting commands, while the Go function tells them how to behave at each tick.

In the setup function which begins with to setup and ends with end

to setup
  setup-circle
  reset-ticks
end

there are two calls, setup-circle, and reset-ticks. The reset-ticks command resets the timer so the simulation begins at zero ticks. The real action begins with setup-circle:

to setup-circle
  clear-all
  set-default-shape turtles "dot"
  ;; turtles should be evenly spaced around the circle
  create-ordered-turtles 40 [
    set size 2 ;; easier to see
    set speed .35 ;; this is the size of each step the turtles take in a tick
    fd 20 ;; move turtles to perimeter of circle
    rt 90 ;; turtles face tangent to the circle
  ]
end

The command clear-all clears the display window, removing all agents and any background patches. Next, the turtle shapes are set to "dot". The last command creates 40 new turtles with the create-ordered-turtles command. Usually, you would use create-turtles, but creating ordered turtles gives each agent its own heading with directions spaced evenly between 0 and 360 degrees. When it gets a fd 20 (forward) command the turtle moves 20 paces outward so they all remain on the edge of a circle with radius 20. The last command is rt 90 which causes each turtle to turn right 90 degrees. The command set speed .35 sets the step size every turtle will make during each tick. It effectively sets the speed of the turtle.

The to-go function is pretty simple:

to go
  ;; move forward then turn
  ask turtles [fd speed rt 1]
  tick
end

The turtles are asked to move forward at speed speed and then turn right one degree. Next, the tick counter is updated. The variable speed is not defined in NetLogo, and we're using it in the context of turtles, so the turtles need to own the speed variable. This is done with a single line at the beginning of the code:

turtles-own [speed]

In the Interface area, we need to add two buttons to run the code just written. Make sure the drop-down next to "Add" is set to "Button" and then click on "Button" followed by a click in the white space which will create a button. A pop-up box will open where you need to enter the command to-setup and change the Display name to Setup, make-setup-button.png

Make another button with the command to-go, Display name Go and check the box next to "Forever". When you run the simulation, first click on "Setup" then "Go". Because you checked "Forever" for the "Go" button, the simulation will continue running until you click "Go" again.

We'll add in one more bit of code and two more buttons. This code changes the turtle's speed,

to change-speed
  ask turtles [set speed speed -.15] ;; decrease the step-size by .15
end

reducing the speed from the current speed to speed - .15. Add these two buttons below the "Setup" and "Go" buttons: change-speed-track-turtle.png The command for the "Change speed" button is a call to the change-speed function and the "Track turtle" button needs this command: ask one-of turtles [pen-down] which randomly selects one of the turtles and tells it to put its pen down. When the pen is down you'll be able to see a track of where the turtle has been. Right-click on the buttons and select "Edit" to add the commands.

You now have a complete NetLogo program. Click the "Setup" button to generate a circle of colored dots. Click on the "Go" button and the dots will spin clockwise around the circle. Don't click the "Change speed" button just yet, though. turtle-setup.png

Before you change the turtle speed, think about what you expect to happen when the speed changes. What we know will happen is that each turtle will be taking a slightly shorter step size during every tick. But what does the collective behavior look like? What is the resulting emergent system? Now, go ahead and click "Change speed" and watch the system for a while. Change the speed a second time. You can restart at any time by clicking the "Go" button and then resetting the simulation with the "Setup" button.

If you reset, click the "Go" button followed by "Track turtle". You should see a circle drawn by one of the turtles and all of them spinning exactly on the circle. Try changing speed and then tracking a few turtles. What happens if you change speed twice and then track turtles?

Debugging

Many computer languages have Integrated Development Environments (IDEs) where you develop your program code, test it, and debug it. IDEs let you stop the execution of the code at breakpoints, and give you the ability to inspect variables and write a few lines of code to examine what the code is doing.

Since NetLogo is agent-based, each class of turtle is doing the same thing all at the same time. Instead of using breakpoints, you can click the "Go" button to stop the simulation. Right-click on an agent to see a pop-up menu. At the bottom of the menu, you can choose to inspect the turtle (here it's turtle #18) or inspect the patch under the turtle. Patches are small squares with integer coordinates, so in this case, the patch is at x = 20 x = 20 x=20, y = − 3 y = -3 y=3. debug-turtle.png

Clicking on "inspect turtle 18" brings up this dialog: inspect-turtle.png

Here, you can see the properties of this turtle, including the special turtles-own speed. Change the speed to 0.2 and set the pen-mode to "down", then press "Go" again. At the bottom of the Interface screen are the Command Center and an input area labeled "observer >", observer-command.png where you can enter single lines of code such as show [speed] of turtle 18 one to show the speed of turtle #18. In the Command Center, you'll see the results. These commands may be entered even if the program is running. command-center.png Every programming language has its own syntax. Besides working through example problems and tutorials, the Models Library contains sample programs in the "Code Examples" section that may be useful for your own programs. Usually, agents passing through the left wall reappear at the right wall, and going through the top makes them come back from the bottom of the screen. If you'd rather have them bounce off the walls, take a look at the "Bounce Example".

Challenges and Further Experiments

Now that you've gotten your feet wet with NetLogo, here are some engaging challenges to deepen your understanding and spark your creativity. Each challenge builds upon the concepts we've covered and introduces new ideas to explore.

Beginner Challenges

  1. Modified Predator-Prey
    • Add a new food source for the sheep (like grass patches)
    • Modify wolf behavior to prefer hunting weaker sheep
    • Add seasonal changes that affect reproduction rates
  2. Traffic Flow Simulation
    • Create a simple one-way street with cars
    • Add traffic lights at intersections
    • Challenge: Can you prevent traffic jams?
  3. Disease Spread Model
    • Start with a population of healthy agents
    • Add one infected agent
    • Implement simple transmission rules
    • Track and graph the infection rate

Intermediate Experiments

  1. Forest Fire Simulation
    • Create a grid of trees
    • Add lightning strikes as fire starters
    • Implement fire spread based on wind direction
    • Add firefighter agents
    • Question: How does the density of trees affect fire spread?
  2. Market Economy Model
    • Create buyer and seller agents
    • Implement simple trading rules
    • Add price fluctuation mechanisms
    • Challenge: Can you create a stable market?

Advanced Projects

  1. City Growth Simulation
    • Start with an empty grid
    • Add residential and commercial zones
    • Implement population growth
    • Add transportation networks
    • Question: What patterns emerge in your virtual city?
  2. Flocking Behavior
    • Create bird agents that follow three rules:
      • Separation (avoid crowding)
      • Alignment (steer towards average heading)
      • Cohesion (steer towards center of mass)
    • Challenge: Add predators and observe how flocking behavior changes

Research Extensions

For those interested in using NetLogo for research:

  1. Data Collection Project
    • Choose one of the above models
    • Design experiments to test specific hypotheses
    • Collect data over multiple runs
    • Create visualizations of your results
    • Write up your findings
  2. Model Comparison Study
    • Implement the same phenomenon using different rule sets
    • Compare outcomes quantitatively
    • Analyze which approach better matches real-world data

Tips for Success

  • Start simple and add complexity gradually
  • Document your changes and their effects
  • Use the NetLogo Dictionary for new commands
  • Share your models with the community
  • Don't forget to save versions of working models

Discussion Questions

  • How do small changes in rules affect overall system behavior?
  • What real-world systems could you model using these techniques?
  • How might these models help in decision-making?

Image credits

Hero: Netlogo screenshot, An Introduction to Agent-Based Modeling

Code and Software

Turtles Circling Sun and Moon.nlogo - NetLogo demonstration of circling turtles

  • NetLogo: NetLogo is a multi-agent programmable modeling environment.

See all software used on Wild Peaches →

References and further reading

📬 Subscribe and stay in the loop. · Email · GitHub · Forum · Facebook

© 2020 – 2025 Jan De Wilde & John Peach