2. Practice - An Introduction to NetLogo
NetLogo is a programmable modeling environment for simulating natural and social phenomena, based on Logo by Seymour Papert. It is designed to model complex system development over time.
Are there any other programmable modeling environments out there? Yes, there are.
Many competing modeling environments use programming languages inspired by or similar to Logo. Most of these platforms integrate another high-level programming language, such as Java, to enhance the user experience. However, much of the Java code in these systems has become outdated.
Feature | GAMA | NetLogo | Repast |
---|---|---|---|
License | Open-source (GPL v3.0) | Open-source (GPL) | Open-source (BSD) |
Programming Language | GAML (Gama Modeling Language) for simulations; Java for extensions | NetLogo language | Java (RepastS, RepastJ); Python (Repast4Py); .NET languages (Repast.NET) |
Operating Systems | Cross-platform: Windows, Linux, macOS | Cross-platform: Windows, Linux, macOS | Cross-platform: Windows, Linux, macOS |
Primary Domain | Spatially explicit agent-based simulations | Social and natural sciences; educational purposes | Social sciences; complex adaptive systems |
User Support | Tutorials, manual, FAQ, forums, documentation, selected publications, examples | Documentation, FAQ, selected references, tutorials, third-party extensions, mailing lists | Documentation, mailing list, defect list, reference papers, external tools, tutorials, FAQ, examples |
GIS Capabilities | Advanced GIS support, allowing integration and manipulation of spatial data | Basic GIS support; can handle simple spatial data | Extensive GIS capabilities; supports integration with various spatial data formats |
3D Capabilities | Supports 3D simulations and visualizations | Basic 3D capabilities; primarily 2D | Supports 3D simulations and visualizations |
Learning Curve | Moderate; requires understanding of GAML and modeling concepts | Beginner-friendly; designed for ease of use and learning | Steeper; requires proficiency in Java or other supported languages |
Performance | Suitable for large-scale simulations; performance depends on model complexity | Best suited for small to medium-scale models; performance may degrade with very large models | Designed for high-performance simulations; suitable for large-scale and complex models |
Debugging | Reports syntactic and semantic errors and gives semantic warnings that indicate “flaws in the logic of the model” | Limited amount of debugging functionalities | Many syntax errors are only identified at runtime |
Simulation Speed | Slowest (tested on Game of Life) | Fastest (tested on Game of Life) | Fast (tested on Game of Life) |
Multi-Threading | Yes | No | Yes with Repast HPC |
Latest Version | 2.11 (as of January 20, 2025) | 6.4.0 (as of January 20, 2025) | 1.9.3 (as of January 20, 2025) |
Reference: Raab, R., Lenger, K., Stickler, D., Granigg, W., & Lichtenegger, K. (2022). An Initial Comparison of Selected Agent-Based Simulation Tools in the Context of Industrial Health and Safety Management. Proceedings of the 2022 8th International Conference on Computer Technology Applications, 106–112. Presented at the Vienna, Austria. doi:10.1145/3543712.3543745
New competitor modeling environments aim to leverage multi-threading and more efficient, faster programming languages as their backbone to outperform traditional Java-based platforms. The market remains highly competitive, with ongoing efforts to develop the most comprehensive and versatile programmable modeling software.
Reference: Datseris, G., Vahdati, A. R., & DuBois, T. C. (2022). Agents.jl: a performant and feature-full agent-based modeling software of minimal code complexity. SIMULATION, 100(10), 1019–1031. doi:10.1177/00375497211068820
Other notable advantages of NetLogo:
The whole world is a discrete grid. Each basic region is called a patch.
The environment is composed of agents called turtles that can independently move. Each turtle has a position, coordinates, and a heading, expressed in degrees. 0° is north.
Agents possess descriptive features as well such as their size, color and shape. (Mostly used for visualization purposes)
Just like space, time in simulations is also discrete, progressing in units called ticks. A tick represents a moment in simulation time during which agents perform their actions. By default, a scheduler ensures agents act in a random order each tick, though this behavior can be customized as needed.
Each agent is equipped with a set of properties:
The observer in NetLogo acts as an overseer, responsible for managing and modifying the environment and agents without being an agent itself. It can execute commands to create, move, or modify turtles, patches, and links, as well as control the simulation by adjusting global settings, running procedures, and monitoring overall behavior.
Opening NetLogo presents a minimalist interface with a blank project, including an empty grid window by default. The easiest way to begin interacting with this environment is through the Command Center.
By default, you are acting as the observer, which grants full control over the entire environment with a global perspective. In observer mode, commands are executed at the global level and can directly manipulate the environment, agents, and simulation settings.
create-turtles 1
This code may appear simple, but it performs multiple actions behind the scenes:
who
number, in this case it will be 0).heading
(direction).xcor
and ycor
(position) within the world's boundaries.shape
, color
, size
, and hidden
status (not hidden by default).inpsect turtle 0
The command inspect turtle
is used to inspect all properties of a turtle.
In this window, you can observe additional properties of the turtle that were not mentioned previously:
turtles
breed.up
(not drawing), down
(drawing as it moves), or erase
(erasing lines as it moves).There is also an input field at the bottom of the Inspect window, which allows you to directly modify properties or execute commands for the selected agent or object (such as a turtle, patch, or link) in the simulation.
For example, to change the label of a turtle, you can use the following command:
set label "Shrek"
The set
command modifies the properties of the agent selected in the Inspect window. However, if you want to do this from the observer level, you need to use the ask
command to specify which agent you are targeting:
ask turtle 0 [set label "Donkey"]
This observer-level command is slightly modified from the original, with the inclusion of the ask
keyword, along with the breed (turtle
) and the unique identifier (who
) of the agent in question. The ask
command in NetLogo allows the observer to direct specific agents (or groups of agents) to perform actions.
set
command works within the context of the selected agent and can modify its own properties directly. ask
command, an agent can modify the properties of another agent. When an agent uses ask
, it essentially "steps into" the context of the target agent(s).create-turtles
command in the Command Center to add a new turtle.
You might have noticed that the color
of Turtle 0 is set to 55
, which might seem unusual. This is a greenish color in NetLogo's color scheme. Additionally, the label-color
is set to 9.9
, which corresponds to white.
Let’s try changing the label-color
of Turtle 0 to a different value, such as 19.9
:
set label-color 19.9
Surprisingly, nothing seems to happen. So, let’s explore what’s going on behind the scenes and understand how colors are coded in NetLogo.
NetLogo uses a continuous color scale based on numbers ranging from 0
to 140
. These numbers represent specific colors on the NetLogo color wheel:
0
is black, 15
is red, 65
is green, etc.).19.9
) create shades or variations of the base color. For example: 9.9
: The lightest shade of a color, often close to white and 19.9
: A lighter variation of red.Let’s try changing the label-color
of Turtle 0 to a value that is outside the bounds of NetLogo’s color system:
set label-color 155
Interestingly, the label-color
turns red. This happens because NetLogo handles out-of-bounds color values by applying the following formula: color = set_color % 140
(graceful handling).
For some phenomena, modeling how agents look can be just as important as modeling their behavior. In other cases, creating visually appealing and creative visualizations can enhance our understanding and enjoyment of the modeling process.
NetLogo uses vectorized shapes for turtles, which are built from basic geometric components. By default, turtles use the default
shape, but NetLogo also provides a library of pre-defined shapes that can be assigned to turtles to represent different roles or states visually. These shapes can be customized to suit the needs of your model.
Other notable shapes include the following: airplane
, bug
, butterfly
, person
, house
, car
.
NetLogo has way more turtle shapes than the default ones for us to choose from. All we need to do is to click the Import From Library button, which will bring up a long list of shapes to choose from.
The breed property defines a classification of agents, specifying their roles within the system. NetLogo provides a fallback breed called turtles
, which is the default class for all agents unless explicitly assigned to another breed. This ensures that agents always have a default classification, even if no additional breeds are defined.
You can define additional breeds to represent different roles or behaviors in the system. For example, in a simulation of hunters and prey, you could create two separate breeds:
The pen-mode property enables agents to leave a visual trail, following their trajectory as they move around the environment. The property can take the following values:
up
: The pen is lifted, and no trail is drawn as the agent moves.down
: The pen is lowered, drawing a trail along the agent's path.erase
: The pen erases any previously drawn trails as the agent moves.This feature allows for the creation of intricate visual patterns, showing emergent behaviors in multi-agent systems through simple movement rules. Let's set the pen-mode
of Turtle 0 to down
.
set pen-mode "down"
Basic movement in NetLogo involves the following commands:
forward
: Moves the agent in the direction specified by its current heading
property.right
and left
: Adjust the heading
value of the agent, changing its direction of movement.The left
command subtracts the specified angle from the current heading
, while right
adds the specified angle to it. It's important to note that in NetLogo, the heading
value is measured in degrees, with 0 degrees representing north. For example:
heading
is 180 (facing south) and you execute right 180
, the agent will turn to face north (back to a heading
of 0).You will use the pen-mode property and the basic movement commands (forward
and right
) to accomplish this.
In NetLogo, there are four types of agents: turtles, patches, links, and the observer. Commands can be directed to any of these agents, including patches.
Patches are arranged in a grid with each patch having specific coordinates. The patch at coordinates (0, 0)
is called the origin, and the coordinates of other patches are determined by their horizontal and vertical distances from this origin.
pxcor
: The horizontal coordinate (increases as you move to the right).pycor
: The vertical coordinate (increases as you move upward).These coordinates work similarly to the standard mathematical coordinate plane.
Commands in NetLogo can target a specific turtle or specific patch or the entire set of turtles or patches.
Turtles | Patches | |
---|---|---|
One | ask turtle 0 [ set color red ] |
ask patch 2 3 [set pcolor red] |
All | ask turtles [ set color red ] |
ask patches [set pcolor red] |
See https://ccl.northwestern.edu/netlogo/docs/dictionary.html for additional commands.
Patches also have a set of properties that can be manipulated, such as their color or label. For example, you can change the color of a patch to standard white by setting its color property to 9.9
. Here's how you can do it:
ask patch 9 4 [set pcolor 9.9]
So what would be needed to create, for example, a chessboard pattern on the grid? Is there anything beyond the Inspect Window and the Command Center to write more complex code, such as loops, creating breeds, handling complex data structures, and manipulating multiple elements at once? Of course, there is: The Code Tab.
Instructions to agents can be classified according to three criteria:
Commands are procedures that don't have any output, but only side effects on the environment.
to go
clear-all
create-turtles 10
ask turtles [ forward 1 ]
end
This code defines a procedure called go
, which performs the following actions:
clear-all
: Resets the environment by clearing all agents, patches, and any previously drawn elements on the grid.create-turtles 10
: Creates 10 new turtles, each with default properties like random positions and headings.ask turtles [ forward 1 ]
: Asks all turtles to move forward by 1 step in the direction they are currently facing.This command can then be called in the Command Center with the following line:
go
Is there another way to interact with the Code Pane from the Interface Tab? Yes, through Interface Elements, which allow users to modify and interact with the simulation without directly changing the code. The most notable elements include:
true
and false
for boolean variables.Can you also determine how to call this function continuously within a loop?
Reporters are procedures that compute a value and report it.
to-report double [ num ]
report 2 * num
end
The above code defines a reporter named double
that performs the following actions:
num
, which is the value to be processed.num
) by 2.report
keyword is used to return the computed value (i.e., 2 * num
).This reporter can be called in the Command Center or within other procedures to compute the double of a given number. For example:
show double 5
In the code above, num
acts as an input parameter to the command.
double
reporter.
There isn't an official NetLogo style guide. Nonetheless the official documentation is fairly consistent and follows some good habits:
myProcedure
, Java style)Variables in NetLogo can be divided into three main groups:
let <name> <value>
<agent*>-own [ <name(s)> ]
globals [ <name(s)> ]
radius
and set its value to 5 in a command named setup
. Subsequently, create a reporter called calculate-area
that calculates the area of a circle.
In this function, create a local variable named area
that computes the area of the circle using the formula area = π × radius²
, where radius
is the global variable. The reporter should then return the computed area of the circle.
Use a Button interface element to run the setup
command once, then utilize a Monitor interface element to show the result with 3 decimal places!
globals
keyword to define the global variable radius
. set
command to assign the value 5
to radius
.pi
is already a predefined constant in NetLogo, so you don’t need to define it manually.globals [radius]
to setup
clear-all
set radius 5
end
to-report calculate-area
let area pi * radius * radius
report area
end
When asking to update an agent variables a subset of all the agents, called agentset
, can be used. An agentset
contains one or more agents, all of the same type, and it's always randomly ordered.
ask one-of turtles [ <command> ]
The one-of
primitive in NetLogo randomly selects one agent from a given set of agents, such as turtles, patches, or links. For example, one-of turtles
randomly selects one turtle from the current set of turtles. Additionally, you can create subsets of agents using conditions (e.g., turtles with [color = red]
) and then instruct these specific subsets with targeted commands.
let some-patches patches with [ pxcor < 3 ]
ask some-patches [ set pcolor red ]
Conditionals in NetLogo allow agents to make decisions based on specific criteria using commands like if
, ifelse
, and ifelse-value
. For example, if pcolor = black [ set pcolor white ]
changes a patch's color to white only if its current color is black.
if (<condition>) [ <command(s)> ]
ifelse (<condition>)
[ <command(s) if true]
[ <command(s) if false]
ifelse-value (<condition)
[ <reporter(s) if true]
[ <reporter(s) if false]
if (random-float 1 < 0.5)
[ show "heads" ]
ifelse (random-float 1 < 0.5)
[ show "heads" ]
[ show "tails" ]
ask turtles [
set color ifelse-value (energy < 0)
[ red ]
[ green ]
]
Conditions are logical expressions (=, <, >, and, or, etc.) that evaluate to true
or false
.
if
or ifelse
in an ask
block, the condition is evaluated for each agent individually. ask turtles [ if xcor > 0 [ set color red ] ]
Loops in NetLogo allow repeated execution of commands, enabling dynamic and iterative behaviors. Common looping constructs include repeat
, which runs a block of commands a fixed number of times, and while
, which runs as long as a specified condition is true.
loop [ <command(s)> ]
repeat <num> [ <command(s)> ]
foreach <list> [ [<item>] -> <command(s)> ]
loop [ ifelse (counter > 100)
[ stop ]
[set counter counter + 1]
]
repeat 5 [
ask one-of turtles [ set color red ]
]
foreach [1 2 3] [ [num] -> show num * 2 ]
ask
block are executed independently for each agent. ask turtles [ repeat 5 [ forward 1 ] ]
Lists in NetLogo are ordered collections of items, which can include numbers, strings, agents, or other lists. They are data structures that support operations like adding, removing, or accessing elements.
( list <element(s)> )
[ element(s) ]
( list 1 "two" true)
[ 1 "two" true ]
Some examples:
let colors ["red" "blue" "green"]
show item 1 colors
The output will the firsts element or item
in the list, which is blue
.
let my-list [1 2 3]
set my-list replace-item 1 my-list 99
my-list
will contain the values of [1, 99, 3] after using replace-item
.
The lput
primitive command adds an element to the end of a list, while fput
adds an element to the beginning.
The flexibility of NetLogo and its agent-centered way of building models quickly escalates to complex models that are difficult to work with.
Try to keep your structure as close as possible to:
Even though NetLogo is not a higher-order language we can simulate this behavior using anonymous procedures/reporters.
[ [ <var(s)> ] -> <body> ]
[ ]
: Encloses the entire anonymous procedure or reporter.[ <var(s)> ]
: Specifies input variables (like function parameters) in a nested bracket. These variables can be used within the body.->
: Indicates the start of the body of the procedure or reporter.<body>
: The actual commands or expressions to execute. If it’s a reporter, the result of this expression is returned.[ [ x y ] -> setxy y x ]
Anonymous procedures assigned to variables (tasks):
globals [ stack push ]
to setup
set stack [] ; Initializes the stack as an empty list.
set push [el -> set stack lput el stack] ; Defines the push task.
run push 10
end
Higher-order reporter:
foreach [1 2 3] [ [x] -> show x * x ]
Unlike traditional procedures or reporters, anonymous ones are not stored in the Code Tab and cannot be reused unless redefined. While NetLogo doesn’t directly support higher-order functions, anonymous procedures allow for similar behavior in many cases.
map [ a -> a * a ] [ 1 2 3 ]
filter [ a -> a > 5 ] [ 1 9 2 ]
reduce [ [a b ] -> a + b ] [ 1 9 2 ]
In NetLogo breeds are a way to "subclass" the turtle type.
breed [ <single name> <agentset name> ]
breed [ hunter hunters ]
breed [ prey preys]
After a breed has been created, the ask
command can be used with the breed name (e.g., ask hunters
) to execute actions for agents of that specific breed. All commands and properties applicable to turtles can also be used with the newly defined breed.
setup-chessboard
. This command will clear the simulation environment and create a classic chessboard pattern on the grid using black and white patch colors.
to setup-chessboard
clear-all
ask patches [
if (pxcor + pycor) mod 2 = 0 [ set pcolor black ]
if (pxcor + pycor) mod 2 = 1 [ set pcolor white ]
]
end
Tasks:
setup-garden
to:circle
if flower
is unavailable in your version).ask patches
command to create the checkerboard pattern. ask turtles
command to set their properties dynamically.if
statements), and lists where needed.to setup-garden
clear-all
ask patches [
if (pxcor + pycor) mod 2 = 0 [ set pcolor green ]
if (pxcor + pycor) mod 2 = 1 [ set pcolor brown ]
]
ask patches with [pcolor = green] [
sprout 1 [
set shape "circle"
set size random-float 1.5 + 0.5
set color one-of [red pink yellow orange]
]
]
reset-ticks
end
to grow
ask turtles [
set size size + 0.1
]
tick
end