Agent-Based Modelling For The Self Learner Tutorials Edition
Agent-Based Modelling For The Self Learner Tutorials Edition
Tutorials Edition
Jennifer Badham
ii
These tutorials are extracted from a book I am writing (but probably will not nish). This
document is v1.0 (June 2019) and downloadable from:
www.criticalconnections.com.au/ABMbook.
This book arose because I was fortunate to be a researcher at the Centre for Research in Social
Simulation (University of Surrey) when Professor Nigel Gilbert and Dr Corinna Elsenbroich
decided that it was time to oer a new short course in agent-based modelling for social scientists,
and that such a course should have a signicant component teaching NetLogo. I volunteered
to develop such a component in the form of a tutorial that has participants gradually write a
(pre-written) NetLogo model.
The idea was to support a 'learn by doing' approach, to move participants through the two-fold
change of perspective required to build their own models: agent-centric thinking, and computer
programming. Programming itself has many strands, including explicitly and specically de-
signing what the program is supposed to do (which overlaps with agent-centric thinking), good
programming practices such as continuous verication, and the keywords and syntax of the
programming language used. Those three programming strands were woven into the NetLogo
tutorial. We used NetLogo because it is a standalone language (so no need to also learn python
or java) that is designed for agent-based modelling, relatively easy to learn, and many resources
are available for the participants once the course is over.
The initial tutorial was a housing model, which required far too much code to deal with technical
aspects of the UK housing market. I then took up a position with the Centre for Public Health,
Queen's University Belfast and was given the opportunity to update the course. As the revised
course was to be targeted to public health researchers, the housing tutorial had to be replaced
with something more relevant. With the experience of the previous courses, I was able to develop
a shorter and simpler tutorial model that (I believe) still covered the most important agent-based
modelling concepts and NetLogo language.
That public health tutorial is the main tutorial of this book. The interwoven structure of the
tutorial is also maintained for the book. The material is presented in the same way as for one
of the courses. Topics are introduced in the order in which they are needed for the model.
New concepts are described immediately before being included in the model, then coded into the
model to provide a concrete example. The reader is expected to run the model at multiple points
as the code is developed. Such a structure leads to a certain amount of repetition. It also means
that topics that may be introduced together in other books due to their similarity are instead
introduced far apart. The payo of this structure is that the novice reader is able to experience
the process of building a NetLogo model in the same way as they would build their own model:
iteratively.
This tutorial would not be possible without the commitment of both the University of Surrey
and Queen's University Belfast to provide a course (and the time to prepare materials for that
course). In addition, I would like to acknowledge the many students who asked interesting
questions, colleagues who taught the course with me, and several alpha-testers who worked
through earlier versions of the main tutorial. They all improved the tutorial in uncountable
ways, as well as supported me in making the tutorial available.
iii
iv
Contents
1 Orientation 1
1.1 Complex Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 What is an Agent-Based Model? . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Agent-based modelling for complex systems . . . . . . . . . . . . . . . . . . . . . 5
1.4 Introducing Netlogo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Rabbits Grass Weeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Virus on a Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.7 More Library Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8 Model Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.9 Doing the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.10 Tutorial Progress Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
v
vi CONTENTS
vii
viii LIST OF FIGURES
4.5 Model 3d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.6 Model 3e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.1 Model 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
1
Orientation
You are presumably reading this book because you have seen an agent-based model (or read about
one) and decided that agent-based modelling is the most appropriate simulation methodology
to help you investigate some research question. Or maybe one of your colleagues has suggested
it? Unfortunately, there are few courses available, and many people building their rst model
are doing so with limited programming experience and without the assistance of experienced
colleagues. If you are in this situation, this book is intended for you.
The book is structured like a course rather than a textbook or reference book. The core of the
book is a tutorial that will gradually take you from a `blank page' (what you see when you open
NetLogo ) to a fully developed model. Like an in-person course, there is a certain amount of
foreshadowing of future material and reviewing material already presented to help you connect
what you are doing in the tutorial to the broader theory of agent-based modelling.
This tutorial is constructed so as to teach three aspects of agent-based modelling simultaneously.
(1) Agent-centric thinking is interpreting the world to be simulated as individual agents
taking actions that implement some process. The particular computer programming language
we use to build the model is (2) NetLogo. However, programming is not simply a matter of
learning what each dened keyword in a language does, but (3) good programming practices
are required to use that language eectively. Throughout the tutorial, highlight boxes (marked
with the I icon) extract key ideas for each of these aspects.
I Key points
Boxes like this contain denitions, concept summaries, programming tips, and other im-
portant points. They do not, however, describe NetLogo language keywords, which are
displayed in a dierent type of box.
The tutorial model concerns protective behaviour (such as good hand hygiene) when faced with
an epidemic. It is unlikely that the model that you want to build is about the same topic.
However, regardless of your topic, the core process being simulated is common to many agent-
based models: people making decisions based on their own motivations and circumstances and
those decisions in turn aecting the world around them.
It is essential that you actually do the tutorial. This book will not help you learn agent-based
modelling or NetLogo if you simply read it. Furthermore, `doing the tutorial' does not mean just
following the instructions, typing in the programming code and running the model. It is also
important to think about how the code works. The particular commands are explained in the
text and I describe what each section of code does, but you need to be sure that you understand
how that code achieves its objective.
While the tutorial model was developed to use many of the most important parts of the NetLogo
1
2 CHAPTER 1. ORIENTATION
programming language, it does not cover all of them. In particular, the agents in the tutorial
model do not move, so mobile agents are dealt with separately (see chapter 8). The full book
will also cover important topics such as lists and extensions, but they are not included in the
Tutorials Edition.
Before starting the tutorial, it is worth considering in what situations agent-based modelling is
useful. The requires an understanding of what is meant by complex systems, and what agent-
based modelling can oer as a lens to examine complex systems.
Consider a trac jam. This is a behaviour generated not just because there are many moving
cars, but because of the way in which interactions between the drivers of those cars introduce
cascades of braking and accelerating. A single blockage, such as a set of trac lights, braking to
avoid an animal on the road, or correcting a drift too close to the car in front, can trigger a trac
jam. Dierences in drivers' preferred speeds, separation and reaction speeds all amplify any slight
variations. Analysing individual cars would not provide any understanding of the phenomenon
of a trac jam. In dierent circumstances, such as moving smoothly on a highway, the same
cars can be considered somewhat independently as their behaviour does not signicantly aect
the behaviour of others.
The modern term of complexity was introduced to describe a set of problems which involve
dealing simultaneously with a sizable number of factors which are interrelated into an organic
whole (Weaver, 1948, pg 539). However, the essence of the idea was encapsulated much earlier
by Aristotle in the phrase the whole is one, not in the manner of a heap but of a syllable (Aristotle,
2011, 1041b, more familiar as `the whole is other than the sum of its parts').
Weaver (1948) recognised that complex problems represented a relatively unexplored area in sci-
ence and were particularly prevalent in biological, medical, psychological, economic and political
sciences. A modern commentator would add social and environmental sciences, at least, to this
list. Complex systems questions include some of the most pressing policy issues: how to limit the
extremes of economic cycles, what species are critical to maintaining the food web, where is the
point at which we cannot recover from climate change, how to avoid an inuenza pandemic. All
of these questions involve behaviour arising from interactions. For example, inuenza is trans-
mitted between people, which can only occur through contact between infected and susceptible
people. Economic cycles are the consequence of millions of transactions where institutions, rms
and individuals purchase goods and services from other institutions, rms and entities.
While economies, food webs and epidemics may be referred to as complex systems, this language
is somewhat misleading. What is of interest is a particular behaviour of the system, not the
obvious entities within the system. To bridge this gap, the term `system' must be understood
in its widest sense, so that the parts of the system are not just the individual components, but
also the rules of interaction. To return to the trac jam example, the system does not consist
only of cars, drivers and roads, but must also include the characteristics and behaviour of the
drivers that contribute to the trac jam. To make this comprehensive scope of `system' clearer,
this book uses a denition of complex systems that explicitly focuses on behaviour.
1.2. WHAT IS AN AGENT-BASED MODEL? 3
I Complex System
A system is complex if the system's behaviour of interest is driven by the interactions
between the individual parts, not simply the behaviour of the parts independently.
As well as identifying the class of complex problems, Weaver (1948) also suggested that progress
could only be made by multidisciplinary teams developing new computer assisted methods.
Agent-based modelling is one such method.
The rst is that the model is standing in for something else. Even the fashion model is a substitute
for the people who will eventually purchase and wear the clothing line being presented.
The second is that the model is an imperfect stand-in. The imperfections take two forms: some
parts of the system are not included in the model at all and some are included but in a simplied
way. The model car may look like a car, but it can't be used to travel. The equations only describe
some of the processes involved in climate change. And most people who will eventually wear the
clothes being modelled have dierent body shapes than most fashion models. Ultimately, the
choice of what to include in the model, and at what level of detail, is guided by what the model
is for. For example, the lack of an engine is immaterial in a collectible model car, the goal is a
faithful representation of the body shape and styling.
These commonalities suggest a denition for model that focuses on representing something. In
addition, we wish to exclude mental models because a model is only of use in understanding
complex systems if it can be shared.
I Model
A model is a formal representation of relevant features and relationships of some target
system.
2. Relevant features and relationships: the model is simpler than the full target system
and there is some purpose or question that guides the decisions about what to include and
exclude in the representation;
How does this denition of model relate to the specic type of model that is dealt with in agent-
based modelling? An agent-based model is constructed in a computer programming language
(such as NetLogo ). But the specics of the target system and its relevant features are less
immediately clear.
Agent-based models are a type of simulation, and a simulation is simply a model of a process. By
this, we mean that the target system for a simulation is a series of actions, decisions, consequences
and other changes that occur through time.
4 CHAPTER 1. ORIENTATION
I Simulation
A simulation is a model of a process.
There are at least two ways to think about a process, and therefore to represent it. One way is to
describe the process from the perspective of an external observer. Alternatively, the process can
be described from the perspective of the participants what actions they take and why. Returning
to the trac jam example, an observer may describe it as a line of vehicles that are moving
slowly (or stalled) over a distance of several hundred metres. The drivers, however, are within
the trac jam and do not know its length or other characteristics. Instead, they perceive only the
local trac, and respond to the vehicle in front of them by starting and stopping as appropriate.
Some drivers may look further ahead, but any information gained has little inuence on their
progress.
Agent-based modelling adopts the perspective of the agents within the system. The model is
comprised of many agents, each representing an individual person, car and driver, household,
business, or some other entity. The model moves through time, with each agent taking a series of
actions that are chosen by that agent, without central control. The computer program is written
to model the world from this agent-centric perspective.
The implementation of this perspective in code is best understood with specic code examples,
so will be revisited throughout the tutorial (for example, see section 1.5.2). At this stage, it is
sucient to recognise that agent-based models represent the target system from the agent-centric
perspective.
I Agent-centric perspective
I, the agent, have certain characteristics and beliefs of my own as well as information
about the world around me, and therefore will decide on some action.
I Agent-based model
An agent-based model is a computer program that represents individual entities taking
actions in accordance with their own characteristics, resources, beliefs, and perception of
their social and physical environment.
While agent-based models are typically run on a computer, that part of the denition is descrip-
tive rather than prescriptive. For example, the segregation model (described in section 1.7) is an
agent-based model that was originally implemented physically with a checkerboard and counters
(Hegselmann, 2017). Descriptions of agent-based modelling may also include non-denitional
aspects of the method, such as experimentation with dierent scenarios (Abdou et al., 2012), or
advanced agent features such as the capacity to adapt (Macal and North, 2010).
To confuse the denition further, there are other simulation methods that overlap with agent-
based modelling. Microsimulation (or Markov chain) models have simulated individuals inde-
pendently change states over time, typically based entirely on probability. These simulations
therefore have heterogeneity but no interaction. In cellular automata simulations, cells in a grid
take on dierent states (such as alive or dead) based on the states of the cells around them.
1.3. AGENT-BASED MODELLING FOR COMPLEX SYSTEMS 5
Thus, interaction is limited to a xed set of other cells that are dened spatially. These are
(generally) considered to be distinct model types, but agent-based modelling tools can be used
to implement these simulations.
Understanding the connection between individual (micro-level) behaviour mechanisms and over-
all (macro-level) system behaviour is an important use of agent-based models. It is particularly
valuable where interactions are combined with heterogeneity because the methodology enables
dierent agents in the same situations to take dierent actions, and the same agent in dier-
ent situations to take dierent actions. Real-world richness can therefore be represented in the
model.
For the purposes of this book, we will assume that both interaction and heterogeneity are impor-
tant in the process that you wish to simulate. The processes modelled in the tutorial includes
both aspects to help reinforce the relationship between agent-based modelling and complex sys-
tem behaviour.
So let's jump in . . .
NetLogo (Wilensky, 1999) is specialist agent-based modelling environment that includes its own
programming language. It can be downloaded from https://ccl.northwestern.edu/netlogo and is
available (for free) for Windows, Mac OS X and Linux. This book assumes you are using version
6 (the latest available at the time of writing). Download and install NetLogo.
There is also an online version of NetLogo (called NetLogo Web ) that can be run over the internet,
without installing any software. However, only some NetLogo keywords are included, and the
tutorial cannot be completed over NetLogo Web.
I Keyword
A keyword in a computer programming language is a word that is part of the language
and has a special meaning. Keywords allow the programmer to tell the computer what to
do. The programmer cannot use those words for other purposes (such as variable names),
they are reserved for their specied meaning. In NetLogo, the keywords that operate on
agents (rather than the model as a whole) are also referred to as primitives.
6 CHAPTER 1. ORIENTATION
(1)
(2) (4)
(3) (5)
(6) (7)
(8)
Figure 1.1: Screenshot of an empty NetLogo model with parts of the interface labelled. (1) is the
menu. (2) is the tabs to switch between the Interface, Info and Code views. (3) adds widgets (input
controls and output reporters) to the interface. (4) contains the speed slider and update controls. (5) is
the settings controls. (6) is a blank area of the interface where input and output widgets are added. (7)
is the world, or main view of the model. (8) is the command center, with input (bottom) and output
(upper) areas.
The functions of the other areas will be described as they are needed. Briey, the model developer
uses the widget (3) and settings (5) items to design the interface for the user to interact with the
model. The main interface contains a view of the world (7), various input and output widgets to
control and interpret the model (in the currently blank area 6) and controls for the simulation
speed (4). Finally, the Command Center (8) allows the developer or the user to directly enter
NetLogo code for immediate running.
1.5. RABBITS GRASS WEEDS 7
I Widget
A widget is an interface component such as a button, plot or slider.
Figure 1.2: Partial screenshot of an empty NetLogo model. The menu option for the models library is
highlighted.
When initially opened, the interface has widgets on the left (in the area marked (6) in Figure
1.1) but the world (area (7)) remains empty. Once the model is running, it will look like Figure
1.3.
The user controls consist of two buttons (labelled `setup' and `go') and six sliders with various
labels (section (1) of Figure 1.3). In addition, there are two output widgets, a plot labelled
1 The Logo programming language was used in the 1980's in education settings to program robot turtles to
draw by crawling on a piece of paper with a pen. Creating a pattern requires taking the turtle's perspective
instead of an observer's.
8 CHAPTER 1. ORIENTATION
`Populations' and a small box labelled `count rabbits' (section (2) of Figure 1.3).
Drag the `number' slider to 180. Do this by placing the mouse pointer on the red marker and
hold down the mouse button to move the marker. You can also move the marker a small amount
by clicking the mouse cursor on the right or left of the marker. Press (with a mouse click) the
button labelled `setup'. The `setup' button is used to initialise the simulation, creating some
patches with grass and a starting population of rabbits. The world should now have some small
green squares and 180 white rabbit icons scattered (numbered (4) in Figure 1.3).
Start the simulation running by pressing the `go' button. To pause (or stop) the simulation,
press the `go' button again and then continue the run with the same button.
Once the simulation is running, the plot will display the number of patches with grass (green)
and rabbits through time. The current number of rabbits is in the monitor (small box below the
plot). Use the speed slider (numbered (4) in Figure 1.3) to speed up or slow down the simulation.
(4)
(1)
(2)
(3)
Figure 1.3: Interface for the Rabbits Grass Weeds model part way through a simulation run. In this
model, the input controls are in the top left section of the interface (1), key information about the
simulation is reported in the bottom left section (2) and the world (3) displays the location of rabbits
and patches of grass.
Play with the model for at least several minutes. Try out dierent values for the sliders. Remem-
ber to press the `setup' button to intialise a new simulation and then the `go' button to start it
running. Here's some things you should try, and some questions to consider while playing:
• How would you describe the system level behaviour to someone who can't see the model
running? For example, is there a pattern over time for the rabbit population? Does there
appear to be a relationship between the dierent populations (curves in the plot)?
• What happens if you move the slider labelled `grass-growth-rate' ?
• What about the other sliders?
• Try moving several sliders at once and then just one slider at a time.
1.5. RABBITS GRASS WEEDS 9
• While the simulation has been running for a while, move the `birth-threshold' slider while
the model is running.
• Can you work out what is happening within the model just by playing with it?
Do not read past this sentence until you have completed playing with the model. The next
paragraphs will discuss some of these experiences and you will not learn as much if you simply
read the discussion.
The next step is to look at the Info tab. This contains text written by the modeller. As Rabbits
Grass Weeds is a library model included with the NetLogo software, the text follows a specic
format that is geared toward eduction. It includes a brief description of the behaviour mechanisms
within the model, what to adjust and what to look for. There is also some information about
aspects of the NetLogo language that are particularly interesting. The language discussion can
be ignored at this stage and will be revisited at the appropriate point in the tutorial.
weed-growth-rate set to 0). You also had the benet of informative variable names. None of this
is true when trying to understand real world complex behaviour.
to go
if not any? rabbits [ stop ]
grow-grass-and-weeds
ask rabbits
[ move
eat-grass
eat-weeds
reproduce
death ]
tick
end
Figure 1.4: The `go' procedure of the Rabbits Grass Weeds model contains the main structure of the
program. Part of this code instructs each rabbit to do the ve actions described in the procedures named
in the square brackets.
Looking rst at the `move' procedure, this code has the rabbit turn a small random amount to
the right and left, thereby ending up facing in a similar but no identical direction as it started,
and then move forward. The rabbit's energy is also reduced slightly.
So the `go' procedure instructs the computer to focus on one rabbit and have it do ve tasks.
First, the rabbit follows the instructions in the `move' procedure, to slightly change direction, go
forward a little, and consume some of its energy store. The next two tasks instruct the rabbit
to look at where it is standing and, if there is grass or weeds available, eat the grass or weeds
and obtain the energy that it holds (see Figure 1.6). If the rabbit has acquired enough energy, it
births another rabbit (not shown). But if there was no food and its energy runs out, the rabbit
dies (not shown). After running through all those actions for one rabbit, the program changes
focus to the next rabbit until all rabbits have completed the actions.
This group of procedures demonstrates several aspects of agent-centric thinking, and how to
implement such a perspective in a programming language. The `go' procedure explicitly changes
the focus to each rabbit in turn and the model is implemented through the actions of the rabbits.
The rabbit is able to perceive its own environment, in particular whether there is grass or weeds
to eat. If so, the rabbit eats that grass or weeds and increases its own energy. The rabbit's
1.6. VIRUS ON A NETWORK 11
Figure 1.5: The `move' procedure of the Rabbits Grass Weeds model contains the rst action that
rabbits are instructed to follow in the `go' procedure. First the rabbit performs a right turn (`rt') of a
randomly chosen amount up to 50 degrees, then a similar left turn (`lt'). The rabbit then moves forward
(`fd') a distance of 1 unit. Its energy is reduced by the amount 0.5.
Figure 1.6: The `eat-grass' procedure of the Rabbits Grass Weeds model contains the second action
that rabbits are instructed to follow in the `go' procedure. The rabbit looks at the colour of the patch
where it is standing (`pcolor') and, if it is green (indicating grass), then the patch colour is changed to
black and the rabbit's energy is increased by the amount of energy contained in grass.
action changes its environment, eating the weed or grass means that any other rabbits on the
same patch are not able to obtain food. Therefore, although each rabbit operates independently,
the behaviour of each rabbit aects the others and there is interaction between rabbits as well
as between rabbits and their environment.
As an aside, the code extracts also demonstrate the use of comments. The semicolon indicates
to NetLogo to ignore the rest of the line (such as the `;' at the beginning of the second line in
Figure 1.6). The programmer includes comments to assist human readers to understand what
the code is intended to achieve.Comments are discussed in more detail within the tutorial (see
section 2.2.2).
immunity).
There are two important sliders to explore the system behaviour. The slider named `average-
node-degree' varies the number of edges for each node (good values are about 10 to 30). The
slider named `gain-resistance-chance' sets the probability that a node will become immune to
further infections when it recovers from the infection.
Play with the model. Remember to press the `setup' button to intialise a new simulation and
then the `go' button to start it running. Focus particularly on the how you would describe the
system behaviour, and how it varies in response to changes in the slider values. Once you have
experimented a little, read the Info tab to get some additional understanding of the model and
further ideas about what to explore.
to spread-virus
ask turtles with [infected?]
[ ask link-neighbors with [not resistant?]
[ if random-float 100 < virus-spread-chance
[ become-infected ] ] ]
end
Figure 1.7: The `spread-virus' procedure of the Virus on a Network model is the main procedure called
by the `go' procedure. Infected network nodes (turtles) check the nodes at the other end of each of the
links to which they are attached and, if the node is not resistant, there is a probability of infecting that
node.
The actions entailed in becoming infected are implemented in the `become-infected' procedure
(Figure 1.8). The node's infected status is set to `true' so that it will be included in the set of
infected nodes in the next iteration of the `spread-virus' procedure. The node is also coloured
red for the convenience of the model user, providing a visual representation of the spread of the
virus.
Figure 1.8: The `become-infected' procedure of the Virus on a Network model is called by the `spread-
virus' for those nodes that are to be infected. It changes the colour and some status indicators of the
node.
can be seen in the interface plots by an increases then decrease in the infected (red) proportion
of nodes. That is, an epidemic is an example of complex system behaviour.
In the classic SIR model of dierential equations (Kermack and McKendrick, 1927), the infection
is spread by contact but a key assumption is that everyone has an equal chance of coming into
contact with anyone else. That is, social networks are ignored. The initially infected people are
embedded in a population of susceptible people and are able to transmit with every interaction.
Consider the case where, on average, a person is infected long enough to transmit to 2 other
people. This means that initially the infection spreads fast, doubling the new infections each
generation. Eventually, however, infected people are coming into contact with people who are
already infected (or recovered and immune). so the spread slows down. This sequence generates
the classic diusion curve that is observed in the Virus on a Network plots, where the number
of nodes currently infected initially increases and then decreases. If the number of nodes ever
infected is plotted, it would display an S-shaped curve. This is characteristic of diusion models
generally, such as adoption of a new product or other innovation (Bass, 1969; Rogers, 2003).
An SIR epidemic on a network shows similar behaviour, but the transmission is attenuated. As
the infection can only be transmitted along network edges, the area of the network where the
epidemic is active has a relatively high proportion of nodes that are already infected or immune.
Slow the NetLogo model (using the speed slider, numbered (4) in Figure 1.1) and try to identify
areas where the epidemic is being blocked by an immune node. For an SIR model, the `gain-
resistance-chance' slider should be set at 100%. Blocking of the epidemic is more visible (and
more extreme) with a lower number of edges per node because there are fewer options for the
infection to access other areas of the network.
However, there is heterogeneity in agent locations and therefore in their environments. The
agents interact through their contribution to each other's neighbourhoods. When an agent moves,
it can trigger a cascade because it occupies a previously empty space and therefore changes the
proportion of neighbours in each of the two groups for each of the agents surrounding that
previously empty space.
The Ants model (in the Biology section) implements a
model where each ant interacts only with its own local
environment but the entire colony eciently nds food
and returns it to the nest. The ants communicate locally
with pheromones to inform each other where the food
is located. The ants explore randomly until one (or
more) nds food. When an ant nds food, it brings
the food back to the nest. While carrying food, the ant
leaves a pheromone trail, which gradually spreads out
and evaporates. Ants that cross a pheromone trail move
in the direction of the strongest pheromone and then
reinforce that trail when they nd the food. However,
ants only respond to trails with a positive but not large
amount of pheromone; this ensures they react to the
edges of the trail rather than simply following a recently
passed ant back to the nest.
The Ethnocentrism model (in the Social Science section) is a particular example of evolutionary
game theory. This class of models explores the eect on the evolution of the population of
repeated interactions between individuals who are able to assist each other at some personal
cost. They were initially developed to explain how altruism could arise despite its evolutionary
disadvantage (Smith, 1964).
In the Ethnocentrism model (Hammond and Axelrod,
2006), each agent has one of four strategies: whether or
not it assists (cooperates) with agents of the same colour
as itself, and whether or not it assists with agents of a
dierent colour. Each agent also has one of four colours
(unrelated to the strategy). Assistance takes the form
of giving up some of its own chance to reproduce to in-
crease its neighbour's chance to reproduce. When an
agent reproduces, the new agent has the same colour
and strategy as its parent, so strategies that confer an
evolutionary advantage come to dominate the popula-
tion.
The nal library model to explore is the Trac 2 Lanes
model (in the Social Science section). This model re-
turns to our initial presentation of complexity, demon-
strating how a trac jam can emerge from drivers with
dierent desired speeds reacting to the variations of speed of the driver in front of them.
The rst consideration is what to model. In most situations, the research question is decided
rst and then agent-based modelling would be chosen as the methodology because it is the
most appropriate to respond to that particular question. Many questions concern whether an
individual level mechanism is a plausible explanation for an observed system behaviour (such as
the Segregation and Ethnocentrism described in section 1.7). Agent-based models are also useful
for `what if' explorations, for example to gain insight into the potential consequences of policy
options.
The question for this tutorial is of the `what if' type: How is epidemic spread aected by
protective behaviour? Potential scenarios could examine the eect of increasing the attitude of
all individuals by some amount to inform a communications campaign, or identify whether there
is a minimum ecacy for a protective measure to have any signicant reduction in epidemic
impact.
Having determined the question, it must be rened into a conceptual design for the model.
There are three key elements: process, entities, and interactions. The conceptual design would
typically include operationalisation of these elements, but these aspects will be partly deferred
until required during model construction.
I Operationalisation
Operationalisation is the process of specifying the detailed model rules that are to be
translated into code. This includes how each relevant feature is measured within the
model, how the relevant features that inuence any action are combined, what is known
to each agent, and each possible situation and its consequences.
As an agent-based model is a simulation, the focus of the design is the process or processes to
be modelled. There are two processes in the tutorial model, adoption (and abandonment) of
protective behaviour, and the epidemic (which includes both infecting new people and disease
state changes for infected people). In a real model, the design for each process would be informed
by some combination of existing subject matter knowledge, advice from subject matter experts
(including disciplinary and local stakeholders), experiment, empirical data, and published liter-
ature.
Consider rst the protective behaviour process. This process is a series of decisions by individuals
or people, the main agent in the model. For the purposes of this tutorial, we assume that there
are only three inuences on a person's behaviour: their attitude or belief that the protective
16 CHAPTER 1. ORIENTATION
behaviour is useful, the behaviour of people around them, and the extent to which they feel
threatened by the epidemic. This brings in one personal characteristic, one for social norms, and
one that responds to the other process being modelled - the epidemic.
The inuenza epidemic process is well studied and the standard mathematical operationalisation
is the SIR model introduced for the Virus on a Network model (see section 1.6). Although
inuenza is spread from person to person, it is not necessary to individually model infectious
people coming into contact with susceptible people. The virus survives on surfaces and in the
air for several hours so it is reasonable to instead treat the epidemic at the population level, and
infectivity as a characteristic of the spatial environment.
Epidemic spread is to be operationalised with dierential equations that describe the change in
the proportion of the population in each of three states: susceptible (never infected), infected,
and recovered. The equations will be spatially explicit, so that the infected population can
only infect others who are located nearby. Further details of the epidemic operationalisation are
provided in Chapter 3), where this process is coded.
The two processes interact with each other. If the epidemic is active nearby, with a large number
of new infections, that increases a person's likelihood to adopt protective behaviour via the
threat component in the behaviour operationalisation. As the proportion of people who have
adopted protective behaviour increases, epidemic transmission reduces, with the reduction also
depending on the ecacy of the protective behaviour. The inuence ows of the conceptual
design are summarised in Figure 1.9.
Figure 1.9: The broad design of the tutorial model. Individuals adopt protective behaviour based on
some combination of their own attitude, the extent to which they observe other individuals adopting
protective behaviour, and their perceived threat. Protective behaviour aects the transmission potential
of the epidemic, which in turn aects the actual spread and hence the perceived threat.
• Agents: people
• Resources: none
1.9. DOING THE TUTORIAL 17
2
Model 1: Model Entities
The rst version of the model establishes the world and the agents that populate the world.
However, there is no behaviour or simulation as there is no progression of time, so no processes
are modelled. This version will also be used to introduce some basic NetLogo concepts, and take
the rst steps in good programming practices.
pxcor, pycor
pxcor and pycor are the horizontal and vertical co-ordinates respectively of a patch.
19
20 CHAPTER 2. MODEL 1: MODEL ENTITIES
For the tutorial model, we want to increase the number of patches to 51x51 and turn o the
wrapping. We also want to reduce the size (amount of screen) for each patch so that the
additional patches don't make the world too large for the screen. These changes are all made
from the settings dialogue box.
Press the `Settings. . . ' button (top right of screen) to open the dialogue box that controls the
World. The dialogue box is displayed at Figure 2.1, with the settings to be changed highlighted.
Change the values of `max-pxcor' and `max-pycor' to 25, and the patch size to 8. Uncheck both
the horizontal and vertical wrap checkboxes. Once the settings are correct, press the `OK' button
to apply the settings and close the dialogue box.
Figure 2.1: Screenshot of an empty NetLogo model with the Settings dialogue box open. Click on the
`Settings. . . ' button at the top right of the screen to open the dialogue box. The highlighted settings
should be changed to match the settings displayed.
The World and other interface components can be positioned anywhere within the NetLogo
interface. A pop-up context menu is available (typically accessed by right-click on Windows
systems, Ctrl-click on Mac OS) that has choices for Edit, Select and other options. Note that
the Edit option is an alternative way of accessing the Settings. . . dialogue box because these are
the settings to edit for the World.
First, make the Interface larger by dragging its edges or corners (with the mouse). Second,
choose the Select option from the context menu. A grey box will surround the World with eight
small black squares. That box indicates that the World is currently selected. Dragging the grey
box will reposition the World and dragging the small black squares will resize it. Drag the World
to the right side of the now larger Interface.
2.2. FUNDAMENTAL CODING CONCEPTS 21
2.2.1 Procedures
The main NetLogo code is comprised of procedures: blocks of code that perform a task. Each
procedure is delimited by the keywords to and end, and the name of the procedure immediately
follows the keyword to. You, as the model builder, can name the procedure whatever you like,
but good practice is to use a name that is reasonably short but also descriptive. For example,
the names of procedures already seen include `eat-grass' (Figure 1.6) and `spread-virus' (Figure
1.7).
A second type of procedure is delimited by the keywords to-report and end. These are discussed
later in the tutorial (see section 4.3).
Many procedures call other procedures. That is, the block of code for one procedure includes
the name of another procedure. NetLogo implements the instructions line by line starting at
the top of the procedure. When it gets to a call to a dierent procedure, implementation moves
to the start of that other procedure, running from the top to the bottom. Control is returned
to the original procedure when the end keyword is reached, and any remaining instructions
are completed. NetLogo programs can have several levels of procedure, with one procedure
calling several others, which each call further procedures and so on. For example, in the Virus
on a Network model, the `go' procedure called the `spread-virus' procedure, which (with some
probability) called the `become-infected' procedure. Eventually, the procedure that is deepest in
the calls gets to its end statement and the implementation steps back up a level and continues
until either a call to another procedure or the end of that higher procedure.
2.2.2 Comments
All programming languages have a way to leave comments in the code. These are for a human
reader to help them interpret what the code is intended to do (Knuth, 1984). The instruction to
the computer is to simply ignore them.
In NetLogo, a comment is indicated by a semicolon (;). The semicolon and anything after it on
the same line is skipped when the computer interprets the program.
Comments are useful to explain what a section of code does but, also, why that section of
code is needed. For example, the comment in the Rabbits Grass Weeds move procedure (Figure
22 CHAPTER 2. MODEL 1: MODEL ENTITIES
comment (;)
The computer ignores anything appearing between a semicolon (;) and the end of that
line. It is used to indicate a comment from the programmer to any humans reading the
code.
NetLogo setup go
Figure 2.2: A model must be initialised to describe the state of the world at some arbitrary start point,
which also captures the outcomes of actions taken in the past. It is the run to estimate the future. In
NetLogo, this separation is typically constructed in a setup procedure for the initialisation, and a go
procedure that represents the actions occurring during the model run.
1.5) states that `moving takes some energy', which explains the purpose of the following line of
code where energy is reduced. The line of code is straightforward to interpret, so it would be
uninformative to have a comment that simply says `reduce energy'.
In this model, we also use comments as headings for groups of procedures. The dropdown list
of procedures is ordered alphabetically. This is sucient for small models or if you are able to
remember the name of the procedure you want to nd, but grouping procedures provides an
alternative way to nd the one you need. Procedures can be organised by however is convenient
for the modeller. The group heading is written over multiple lines to make it easily visible when
scrolling through the model.
contains the interactions, decisions and actions that describe the model behaviour and change
the agent attributes or environmental features. For example, in the Rabbits Grass Weeds model,
the go procedure had the rabbits move, eat, reproduce and die.
code for errors such as mismatched brackets and words that NetLogo doesn't know what to do
with. These are typically typographical errors such as misspelling a keyword or procedure name.
If there is such an error, a yellow bar will be placed at the top of the screen together with an
error message (see Figure 2.5). In addition the Code tab label will be red to indicate there are
unresolved errors. Unfortunately, there are many errors of other types (such as logic errors) that
NetLogo does not identify automatically.
If you do have errors, make the appropriate changes to the code and Check the code again.
Once there are no errors (and the Check icon returns to grey), save the model. Look at the
interface, the button labels should be black text. Now that the procedures exist, NetLogo is able
to interpret the button command to call the procedure.
;--------------------------------------------------
; MAIN CONTROL PROCEDURES
;--------------------------------------------------
to setup
; initialisation procedures go here
end
to go
; model step procedures go here
end
You can now run the model. Go to the interface and press the setup and go buttons. Nothing
will happen, but NetLogo should not give an error either.
At this point, the model looks like the screenshot at Figure 2.6. Buttons can be moved in the
same way that the World can be moved. Access the context menu, press `Select' and the grey
box can be used to drag the button as required. Once the widgets are in their appropriate places,
model version 1a is complete. Save the model (Save item in the File menu).
2.5 Variables
A variable is simply a way of storing information. You can think of it as a box with a labelled lid.
The actual contents of the box can change, and the box may even be empty, but the label stays
the same. Variables provide a convenient way of keeping track of information that the computer
needs to know, such as the energy of a rabbit in the Rabbits Grass Weeds library model, and
referring to that information as required in the code.
The value of the variable (or contents of the box) can be a number (eg 10), string (eg "high"),
boolean value (true or false), agentset (see section 4.4) or list. There is no need to specify the
type of contents for the variable.
2.5. VARIABLES 25
Figure 2.5: Screenshot of a typical error message presented after clicking on the green tick Check icon.
In this case, the word `End' is mistyped to end the `setup' procedure, so the error message is reporting
that a new procedure is being started (with the to keyword) before the previous procedure has been
terminated (with the end keyword).
Figure 2.6: Screenshot of the interface after completing version 1a of the model.
I Variables
A variable is a way to link a meaningful name to a piece of information that can be stored,
changed and retrieved. There are three types of variables in NetLogo : global variables
contain information available to all model entities, agent variables store information about
individual agents (including patches or links), and local variables are temporary storage.
26 CHAPTER 2. MODEL 1: MODEL ENTITIES
variable for their population density. However, all patches are of the same size, so we will instead
use population because that makes the transmission equations easier conceptually.
We will also introduce a global variable for the maximum population of any patch and show its
contents on the interface. This allows a sanity check, which is a quick assessment of whether
results are reasonable. For example, if we write code that is intended to assign population values
in the thousands, but the maximum population shows millions, then there is an error in the
assignment method. Similarly, if the maximum population shows 0, then population values are
not being assigned. Such sanity checks are essential while building the model to make sure that
the model being built is actually consistent with its design.
Create a variable to store the maximum population value (Snippet 1b-1 (page 27)). This snip-
pet introduces the globals keyword, which is used to list the global variables. Note the short
descriptive variable name, and that a comment has been used to provide a more detailed de-
scription.
globals
[ max-popn ; maximum population of a patch (for
colour scale)
]
globals
The globals keyword is used to identify all the global variables except those that are con-
trolled by the widgets that provide information to the model (sliders, switches, choosers,
and inputs). The variable names are listed between square brackets.
This code only instructs NetLogo to create the variable. We need to separately create a monitor
widget to display its value, and set a value to display. A monitor is an interface widget to show
the contents of a single variable. It is created in a very similar way as a button. Go to the
Interface tab and add a monitor (change the widget dropdown to `Monitor' and click on `Add',
or access the context menu).
The dialogue box (see Figure 2.7) has a box for NetLogo code and the Display name, which is
the same as the button widget. It also has settings for how the results are displayed, such as
decimal places. As the contents of a variable are accessed simply from the name, the variable
name is the only code required in the Reporter box.
At this point, the monitor should display 0. A NetLogo variable, once created, has a value of
0 until it is set to some other value. The global variable named max-popn is created by the
globals statement and assigned the value of 0 by default. But patches do not yet have a variable
for population, so no maximum can be calculated and assigned to max-popn.
For patches (and turtles and links ), the variables available are declared with the patches-own
keyword (and similarly for the other entities). Each patch has its own copy of the variable with
potentially dierent values. First, we must create a variable to store the population value for
each patch, to be named `popn' (see Snippet 1b-2 (page 28)).
Having made the variable available, the next task is to assign a suitable value of population to
each patch. In the real world, population density varies greatly. Typically, most people will live
in one of a small number of cities. For the model, three patches will be assigned large population
values, with small values for all other patches.
28 CHAPTER 2. MODEL 1: MODEL ENTITIES
Figure 2.7: Partial screenshot with dialogue box for maximum population monitor. Note that the title
of the monitor matches the text in the `Display Name' box.
Snippet 1b-3 (page 29) creates a new procedure (called setup-patches) that uses the random
primitive to generate random numbers and assign them as population values. It also calculates
the maximum of these and changes the value of the max-popn variable to that maximum. The
new procedure is called by the setup procedure simply by including the procedure name in the
code for the setup procedure. This means that clicking on the setup button starts the setup
procedure, and the setup procedure in turn diverts to the setup-patches procedure.
There are several new primitives introduced in this snippet. In setup-patches, random 10000
returns a randomly generated integer from 0 to 9999 and that number is added to 2000 to assign
a population count (with the set primitive) to each patch. Three of the patches are randomly
chosen for a higher population count, representing cities. For these, random 3 is used to generate
a random number from the set {0, 1, 2}, which is then added to 3 and multiplied by 1 million.
So the city patches each have a population value of 3 million, 4 million or 5 million. Other new
primitives are explained later in the tutorial.
Having added some code, the next step is a sanity check, does it work as expected? The green
tick only checks syntax. Logic errors in agent-based models can be dicult to diagnose, so it is
important to add code gradually and verify it before adding any further code. You should have
patches-own
The patches-own keyword is used to identify all the variables (listed between the square
brackets) that are available to patches to describe attributes of the spatial environment.
Each patch has its own value for each of the variables named.
2.6. DESCRIBING THE PHYSICAL ENVIRONMENT 29
to setup
clear-all
setup-patches
end
to go
; model step procedures go here
end
;--------------------------------------------------
; IMPLEMENTATION PROCEDURES
;--------------------------------------------------
to setup-patches
ask patches [ set popn 2000 + random 10000 ]
ask n-of 3 patches [ set popn 1000000 * (3 + random 3) ]
set max-popn max [popn] of patches
end
random
Generates an integer between 0 and n-1 where n is the number immediately following the
word random. Each integer in the range is equally likely to be generated.
a clear idea of what to expect; after all, the code is intended to implement the model design.
The most obvious check is to press the setup button and look at the number in the Max Popn
monitor. From the discussion of how the setup-patches procedure is intended to work, the value
should be 3, 4 or 5 million. Because the maximum is randomly generated, repeated button
pressing should also lead to some changes in the number returned. Note that a common error is
to create a new procedure, but forget to include the call to that procedure in one of the main
procedures. In this case, the value of max-popn would never change from its default of 0. You
can see this by commenting out the call to the setup-patches procedure in the setup procedure.
I Sanity check
Whenever you add code to your model, do a sanity check. Test the code to see if it does
what you expect it to do. The green tick only checks syntax, not logic.
This check only conrms that appropriate values are assigned for the patches representing cities.
What about the others? Checking can be made more rigorous by commenting out the line that
generates the city populations (by placing a semicolon at the beginning of the line), the maximum
population value generated for other patches will be displayed in the monitor. You should expect
to see a value slightly below 12,000. Remember to delete the semicolon after checking.
30 CHAPTER 2. MODEL 1: MODEL ENTITIES
At this point, the model looks like the screenshot at Figure 2.8. Once the maximum population
is correctly calculated after clicking the setup button, model version 1b is complete. Save the
model (Save item in the File menu).
Figure 2.8: Screenshot of the interface after completing version 1b of the model.
How would you calculate the value of x? I'm hoping you don't start at the left and work your
way along (so 1 + 2 = 3 then 3 × 3 = 9 then . . . ). You should start with the brackets, then do
the `power of' (called exponentiation), multiplication and division, then nish with the addition
and subtraction. Breaking the calculation into small steps:
x = 1 + 2 × 3 − (4 + 5) ÷ 62 step done:
2
=1+2×3−9÷6 4+5=9
= 1 + 2 × 3 − 9 ÷ 36 62 = 36
= 1 + 6 − 0.25 2 × 3 = 6 and 9 ÷ 36 = 0.25
= 6.75 1 + 6 − 0.25 = 6.75
same. Exponentiation uses the `caret' or `hat' symbol (^), to point up. The asterisk (∗) is used
for multiplication, a sort of × with extra arms; and division is indicated with the forward slash
(/), a standard alternative for ÷ in equations.
Because NetLogo is very exible with variable names, all mathematical operators must have a
space immediately before and after. For example, 6 to the power of 2 would be written as 6 ^ 2,
not as 6^2. The only exception to spacing is brackets, no space is required before or after either
a normal bracket or a square bracket.
I Precedence
Precendence is the order in which pieces of an equation are calculated. Brackets are
used to change precedence, anything in brackets is done rst. The mathematical op-
erators follow the standard mathematical precedence order of exponentiation (^), then
multiplication (∗) and division (/), then addition (+) and subtraction (−).
Putting the symbols and spacing rules together, and remembering that set is used to assign a
value to a variable, equation 2.1 would be written as follows in NetLogo :
set x 1 + 2 * 3 − (4 + 5) / 6 ^ 2
NetLogo also oers a range of other mathematical functions. These are all implemented with
primitives rather than symbols. For example, the square root of 4 would be written as sqrt 4
and the logarithm can be found with log (base 10) or ln (base e ). Also available are statistical
functions for manipulating multiple values (eg sum, mean), trigometric functions for geometry (eg
sin) and logical operators (eg and) and comparisons (eg >=). The full list is available in the
NetLogo Dictionary (Help menu).
I Spaces in code
NetLogo is very sensitive to the presence of space. Every keyword, operator, procedure
name, variable name, mathematical operator or other code element must be separated
with at least one space. The only exception is brackets; so any of ( or ) or [ or ] can
be used without leaving a space. The number of spaces does not matter, any number of
spaces is treated as a separator.
breed
Turtle agents can be of dierent types, referred to as a breed. To dene a breed, the
breed keyword is followed by the plural form of the breed name, then the singular form.
turtles-own
The turtles-own keyword is used to identify all the variables (listed between the square
brackets) that are available to turtles to describe their attributes. Dierent sets of at-
tributes can be dened for dierent breeds of turtles, with the name of the breed used in
the keyword instead.
Multiple people are needed so that there is the opportunity for people on a patch to make
dierent decisions and therefore contribute to dierent levels of protection. A larger number of
people allows ner gradations in the proportion protected.
There are three dierent primitives for creating turtles, depending on the type of agent issuing the
instruction (or the agent whose perspective is being taken). The observer can create-turtles,
patches can sprout and turtles can hatch. To create/sprout/hatch turtles of a particular breed,
then the (plural form) name of the breed is used instead of turtles. For example, the tutorial
model will create turtles using sprout-people to instruct the patches to create turtle agents of
the people type (in Snippet 1c-2 (page 33)) shortly).
Why does NetLogo need three dierent ways of doing the same thing, creating turtles? Because
they represent dierent process mechanisms, allowing better matching between the real world
and simulated behaviour. In particular, hatch is reproduction, which occurs while the simulation
is running, it is part of the behaviour. In contrast, create-turtles and sprout are typically
used to create turtles during initialisation, to make them available for the simulation. The key
dierence between these two is that sprout is convenient for spatially distributed turtles.
Regardless of the primitive used to create the turtles, it is followed with a number, indicating the
number of turtles to be created, then an optional block of code in square brackets (like [ ]) that
each turtle is to run on creation. This block of code is used to set values for the attributes. In
addition, turtles created with sprout inherit their location from the patch doing the sprouting,
and turtles created by hatch inherit variable values from its parent. In both cases, those values
can be overwritten using a set statement in the block of code.
Follow the instructions for Snippet 1c-2 (page 33). Think about what the code is doing be-
fore continuing. As already noted, this snippet uses the sprout primitive to create agents. It
demonstrates several other things about NetLogo as well.
to make-people
ask patches
[ sprout-people (2 + floor ( popn / 10000 ))
[ set protect? FALSE
]
]
end
The turtles being created are of the breed people. Comment out2 the code created in Snippet 1c-1
(page 32), then check syntax (green tick) and NetLogo will highlight the sprout statement with
an error. So the breed statement denes a type of turtle that is then available to be used.
Remember to uncomment when nished.
The number of people to create is included in the code as a calculation rather than a specic
number. Each patch has a value for the popn variable and that value is used so that patches
with a larger population also have more people. The floor primitive3 is a mathematical way
of saying `take the integer part'. For example 19/10 is 1.9 and rounding to the closest integer
would result in 2, whereas floor 19/10 is 1. In this case, the value of the popn variable will be
a few million in the city patches, which will consequently have a few hundred turtle agents, and
a few thousand in the other patches, which will have either 2 or 3 agents. NetLogo will report
an error if the number of turtles to be created is not an integer. If you accidentally have the
call to the make-people procedure before the call to the setup-patches procedure (in the setup
procedure), then the popn variable values will all be 0 when the number of turtles is calculated
and two turtles will be created at each patch.
As each person is created, the new person runs the code in the square brackets to set the
protect? variable to FALSE. This variable is available because of the people-own statement in
Snippet 1c-1 (page 32). It needs to be set to FALSE to indicate that the person has not adopted
protective behaviour.
2 It is easy to comment or uncomment a block of code by highlighting the code (click and drag the mouse over
the block) and then use the menu item Edit > Comment/Uncomment.
3 See also the related functions: ceiling, round, precision
34 CHAPTER 2. MODEL 1: MODEL ENTITIES
After pressing the setup button, the model looks like the screenshot at Figure 2.9. Each coloured
icon in the World is one person. Once turtle agents are being created successfully, model version
1c is complete. Save the model (Save item in the File menu).
Figure 2.9: Screenshot of the interface after completing version 1c of the model.
and can be seen as set to false. At the bottom of the window is a box where NetLogo commands
can be entered.
You can also open inspect windows for patches (and links,
once there are some in the model). Open the context menu
again, and this time select the `inspect patch. . . ' option. The
inspect window for a patch has the same structure as for a
turtle: the title bar identies the patch, with a section of the
World immediately below, variables and then a code box.
For patches, there are only ve built-in variables instead of
the 13 for turtles.
Open an inspect window for an agent. In the code box at the bottom, type set size 10 and
then press Enter. The icon for the person you are inspecting will increase to size 10 in both
the inspect window and the main World widget. This is an example of controlling NetLogo
interactively, entering code for immediate implementation.
clear-all
The primitive clear-all is used to reset NetLogo to its default state, as if no code has
been run. It is sometimes seen in code in its abbreviated form, ca.
2.10 Colours
Unless otherwise specied, patches are coloured black and turtle agents are randomly coloured.
The next model iteration makes the interface informative by using colours eectively. First,
however, we need to understand how NetLogo denes colours.
Open the tutorial model and press setup. Open an inspect window for a person and one for a
patch. In the person window's code box, enter set color red (note the US spelling). In the
patch's code box, enter set pcolor 15. What happened? What should happen is that both the
person icon and the patch background change to red.
Colours in NetLogo have equivalent numerical values, and the name and number can be used
36 CHAPTER 2. MODEL 1: MODEL ENTITIES
interchangeably. Valid colour numbers are from 0 to 1404 . Each interval of length 10 refers to
a broad colour such as red, which runs [10,20) or magenta, which runs [120,130). The lowest
numbers in an interval are dark, and the higher numbers are pale. The mid number (that is,
integer ending in 5) are the named colours.
The colour map is available from the NetL-
ogo menu, at Tools > Color Swatches. Select-
ing that item will open the map displayed at
Figure 2.11. Move the mouse pointer to the
number 15 and click. The colour map will up-
date, with the word `red' in the bottom left
text box, and a red turtle icon against various
coloured backgrounds down the right column.
Now try the number 123. In the text box, this
colour is described as `magenta - 2', conrm-
ing the equivalence of a colour and number.
Note that the colour number does not have
to be an integer. In the bottom right, change
the radio button to 0.1 increment to see ner Figure 2.11:
Colours available in NetLogo with
gradations. their numerical equivalents.
The use of numbers for colours supports great exibility in using colour to provide information
about the model. We have already seen patches coloured to display whether food is available in
the Rabbits Grass Weeds library model. The next step of the tutorial model is to use colour and
other visual elements to communicate with the model user, highlighting important information.
scale-color
The scale-color primitive is used to map a value to a colour range. The full syntax is
pcolor <colour-group> <number-to-map> <minimum-value> <maximum-value>. The
minimum and maximum values can be swapped, and the colours will invert accordingly.
Follow the instructions for Snippet 1d-1 (page 37). We rst create a local (temporary) variable
named max-scale and assign it a value higher than the maximum that will be required for scaling
the colour. Remember that the let primitive is used to simultaneously create a variable and
store a value in that variable (with set used to change it later if required). A logarithmic
transformation is applied to the population values to reduce the extreme dierence between the
city patch populations and the other patch populations. The primitive ln is the mathematical
function of natural logarithm. The multiplication by 1.3 ensures that even the highest values of
population density do not generate colours that are too pale to be visible.
let
The primitive let is used to create a local variable and assign a value. The full command
is let <variable name> <value>. The value can be specied explicity (eg 10 or "hello")
or as the output of some piece of code. The variable created by let is temporary and will
be deleted at the end of the block of code (delimited by [ ] square brackets) or procedure
in which it is created.
4 Other numbers are not treated as errors, they are instead mapped back to the relevant range using modulo
arithmetic.
2.11. COMMUNICATION THROUGH INTERFACE DESIGN 37
;--------------------------------------------------
; UTILITY PROCEDURES
;--------------------------------------------------
to colour-patches
let max-scale 1.3 * ln max-popn
ask patches
[ set pcolor scale-color blue ln popn max-scale 3.2
]
end
The variable pcolor is the built-in colour variable for patches. So set pcolor . . . instructs the
patch to change its colour to the stated value. In this case the stated value is derived from the
scale-color primitive, with the logarithm of the value of the patch variable popn mapped to the
blue colour range. In this example, the maximum possible popn value is 5 million, which would
result in a value of approximately 20 for max-scale. So the population values are transformed
logarithmically and then mapped to a scale between 3.2 and 20.05 and applied to the blue range
of the NetLogo colour system (numbered 100 to 110).
pcolor
The built-in variable for patches to store their colour is named pcolor. It can be changed
with set pcolor <value>. The colour value can be specied with either a name (eg
red + 1.3) or the numerical equivalent (eg 16.3).
After completing this snippet, press the setup button and see what happens. The black back-
ground in the World is now blue, but the turtle icons are obscuring any variation in the shades,
so the next step is to consider how to colour the turtle agents or people. The most relevant in-
formation about people is whether they have adopted protective behaviour. However, the people
on a patch are all in the same place, only the last created person is visible as it obscures all the
others. It is therefore more sensible to hide the turtle agents entirely.
There are two ways to hide turtle agents from the World. The rst way is using the hide-turtle
primitive. Follow the instructions for Snippet 1d-2v1 (page 38).
After completing the snippet, press the setup button. The colouring to indicate population is
now visible because the people agents are not visible. They are still created though. You can
see this by opening an inspect window for a person. However, the context menu is not available.
Try it, and you will nd that the menu does not include items for turtle agents. This is because
hide-turtle hides the turtle from the World, not simply turning o the visible display. Instead,
go to the command center (bottom of the interface, see section labelled (8) in Figure 1.1) and
enter the code inspect person 100 at the bottom space.
A more useful approach (for our purposes) is to make the turtle icons so small they are invisible
but not actually `hide' the turtles. Complete Snippet 1d-2v2 (page 38) to set the size of the
turtles to 0. Make sure you delete the line you added in Snippet 1d-2v1 (page 38). Now press
the setup button. The World should look the same but you should also have access to the context
38 CHAPTER 2. MODEL 1: MODEL ENTITIES
to make-people
...
[ sprout-people ...
[ ...
hide-turtle ∠∠
]
]
end
to make-people
...
[ sprout-people ...
[ ...
set size 0 ∠∠
]
]
end
Now that you can see the variation in population (blue shading for patches), does anything strike
you as odd? Remember that the population was assigned randomly for each patch. This means
that cities with high population can be adjacent to other patches with very low population. But
this is not realistic. In the real world, big cities are surrounded by relatively high population areas
and, similarly, low population areas tend to congregate. The next step is to create a smoother
transition in population values instead of sharp dierences at patch boundaries.
The diffuse primitive moves part of a variable's value to the surrounding patches. Complete
Snippet 1d-3 (page 39), which uses diffuse to smooth population. Each patch takes 40% of its
own value of popn and shares it between the eight neighbouring patches. This means that the
city centres create an initial ring of relatively high population values. This spreading operation
occurs three time (due to the repeat primitive), so that there are three rings with gradually
decreasing population values around each city. The city loses 40% of its population each time
(leaving it with 0.63 or 21.6% of its initial value) but also gains some population from the sharing
of its neighbours.
Informative interface design is not only useful for communicating model results to the user, but it
also reduces the need for explicit sanity checking as the code is constructed. The World displays
the population values with the blue shading, making it clear whether the objective of smoother
population has been achieved. But some checking is still appropriate. Inspect a dark blue patch
and also patches in one direction outward, is the population value decrease reasonable? Also, is
2.12. TUTORIAL PROGRESS CHECK 39
to setup-patches
ask patches ...
ask n-of ...
repeat 3 [ diffuse popn 0.4 ] ∠∠
set max-popn ...
end
diuse
The diffuse primitive removes the specied proportion of a patch's variable and shares
that portion equally between each of the eight neighbouring patches, adding the share
to whatever value the receiving patch already has for that variable. The full syntax is
diffuse <variable-name> <proportion-to-share>.
Figure 2.12: Screenshot of the interface after completing version 1d of the model.
repeat
The repeat primitive instructs NetLogo to perform the following code block multiple
times. The full syntax is repeat <number-of-occurrences> [code-to-repeat].
40 CHAPTER 2. MODEL 1: MODEL ENTITIES
A key part of the developing the model is designing the interface. In NetLogo, the interface is
automatically connected to the code. Interface widgets that are used to input variables (such as
sliders) automatically dene a global variable simply by their presence on the interface. Buttons
are able to call procedures to run. And output widgets have a code box that contains the NetLogo
code to identify the variable value or other information to report.
The World widget displays the model's world. It is comprised of a grid of patches, each of which
represents a physical location and contains information about the environment. This world is
populated by turtles, which represent decision makers or actors in the processes to be simulated.
Turtles come in dierent breeds.
Information in the model is stored in variables. Global variables contain information that is
accessible to all model entities. There is only a single copy of each global variable, with each
variable dened by either an interface widget or by being named in the globals list. Agent
variables contain information about a specic patch or turtle agent. There is one copy for each
patch or turtle, and are dened by patches-own or turtles-own lists. Finally, local variables
are temporary storage created as required for convenience and then destroyed at the end of the
code block or procedure where they are created.
3
Model 2: Introducing Time and Space
Model version 2 implements the epidemic process, at which point the model is a simulation.
Key to implementing a simulation is modelling the passage of time and changes in model states
through time. This version also introduces some relatively simple interaction, the actions occur-
ring in one patch aect other patches. Such inuence arises because of the spatial relationships
between patches, and this version will also introduce the key spatial primitive of neighbors.
β γ
Susceptible Infected Recovered
Figure 3.1: Epidemic state transitions for a population in the SIR model. There are no births or
deaths, so the population is constant. For the given unit of time, the transition parameter β denotes the
probability that a susceptible person becomes infected, and γ denotes the probability that an infected
person recovers (and becomes immune).
43
44 CHAPTER 3. MODEL 2: INTRODUCING TIME AND SPACE
changing states from I to S. From above, β is equivalent to the number of people able to be infected
by a single infectious person (in the given time period) if everybody else in the population is
susceptible. But only a proportion of their contacts are actually susceptible, that proportion
is S/N . Further, the number of people instigating such infections is given by I. This leads to
∆S = −βI S/N . Similarly, if γ is the probability of an infected individual recovering (in the given
time period), then the infected population recovering is given by ∆R = γI . Finally, the change
in the infected population is the gains from those becoming infected and the losses from those
recovering. The relevant equations are therefore:
S
∆S = −βI
N
S
∆I = βI − γI
N
∆R = γI
Some mathematical manipulation (see (Diekmann and Heesterbeek, 2000) or another epidemiol-
ogy text) provides a more intuitive pair of parameters that can be used to derive β and γ . The
duration of infection is 1/γ and the basic reproduction ratio is β/γ . The basic reproduction ratio
is the number of new infections that would be generated by an average infected person if every
contact they had was with a susceptible person.
Note that time is built in to these equations, change (∆) in the population counts requires a time
period over which the change occurs. Further, this process is complex, new infections arise from
the interaction between the susceptible and infected populations. However, the representation is
not agent-centric. The population is simply counted by epidemic state, and all people are treated
as identical apart from their state. There is no concept of local interaction as occurred with the
Virus on a Network library model, and individuals are not represented in the equations.
Refer to Figure 1.9, both protective behaviour and the ecacy of that behaviour also inuence
the epidemic process. However, those elements cannot be introduced until the model includes
protective behaviour. This is an example of starting with the simplest model possible and then
rening it gradually.
As part of the detailed design, the modeller should identify the requirements to implement the
process to be represented and the expected behaviour of the model. This planning helps to
organise the order in which to introduce new code, and the tests to conduct to assess whether
the code is correct.
Looking at the equations, each patch needs a variable for the populations in each state and
global variables are required for the state transition parameters β and γ . From general epidemic
theory, an SIR epidemic has a characteristic pattern of infections, with incidence (new infections)
and prevalence (current infections) increasing and then decreasing in the classic diusion curve.
Eventually, the epidemic dies out because of the lack of accessible susceptibles. In addition, a
basic check is that the total population in each patch does not change, just the allocation to
dierent states.
Figure 3.2: NetLogo represents time with a clock counter, accessed with the ticks reporter. The clock
is initialised with the reset-ticks command, usually the last command in the setup procedure. It is
incremented with the tick command, usually the last command in the go procedure.
Processes that occur in continuous time can also be modelled mathematically in continuous time
by measuring activity or changes over a given interval of time.
In practice, however, simulations generally model time as a discrete variable. That is, the model
includes an internal clock and each tick of the clock represents the same period of time such as
an hour or a week. The advantage of this method is that empirical observations about processes
are typically recorded for some regular period of time, such as quarterly economic activity.
patches-own
[ popn ; population of patch
incidence ; new infections this tick ∠∠
popn-S ; susceptible population ∠∠
popn-I ; infectious population ∠∠
popn-R ; recovered population ∠∠
]
to setup-patches
...
repeat ...
ask patches ∠∠
[ set popn round popn ∠∠
set incidence 0 ∠∠
set popn-S popn ∠∠
set popn-I 0 ∠∠
set popn-R 0 ∠∠
] ∠∠
set max-popn ...
end
In these snippets, the letters `S', `I' and `R' refer to the three possible epidemic states: susceptible,
infected and removed (or recovered) respectively. The variable `incidence' is the number of new
infections. The population is initialised as entirely susceptible, so the values for I and R are set
to 0 and the value for S is set to the patch population.
The tutorial has already used the set primitive to assign values to variables (such as the popn
variables in Snippet 1b-3 (page 29)) with limited discussion. This primitive is used to assign a
value to an existing variable, regardless of the variable type (global, agent or local) or the type
of value (string, number, agentset, list, . . . ).
Here, set is being used to initialise the global variables. Note that some of these values are
being set to 0 even though a variable is automatically assigned the value 0 when it is created.
Systematically assigning values to all variables reduces the likelihood of missing a variable acci-
dentally. It is also used to round1 the population values to an integer after the diffuse command
introduces non-integers.
set
The primitive set is used to assign a value to a named variable. The full command is
set <variable name> <new value>. The new value can be specied explicity (eg 10 or
"hello") or as the output of some piece of code such as a calculation.
The changes introduced in these snippets are not visible in the model. After pressing the setup
button, the model interface will be identical to that for model 1d (Figure 2.12).
Now that there is a way to store information about the epidemic, the epidemic can be seeded. In
the real world, epidemics require a critical mass of infected people to act as a source. To represent
this in the model, a small number of high population patches must be selected as seeds, with a
proportion of their population set to infected status. This is implemented in Snippet 2b (page
47).
to start-epidemic
ask n-of 3 max-n-of 20 patches [ popn ]
[ set popn-I round (0.005 * popn)
set popn-S popn-S - popn-I
]
end
This snippet introduces two important primitives used for selecting a subset of model entities.
max-n-of is used to identify the 20 patches with the highest values of the popn variable. From
these 20 patches, 3 are randomly selected with n-of. The population state counts are adjusted in
these three patches: the number of infected (popn-I) is set at 0.5% of the population (rounded to
the nearest integer with round) and the susceptible population (popn-S) is reduced accordingly.
n-of
The full syntax is n-of <number> <agentset>. Selects a subset of specied size (num-
ber of entities) from the specied agentset, with each entity having an equal chance of
selection. See also one-of.
max-n-of
The full syntax is n-of <number> <agentset> [<variable-name>]. Selects a subset of
specied size (number of entities) from the specied agentset, selecting those with the
largest values of the specied attribute variable. Ordering is random for those entities
with the same value. This primitive has been presented as using a variable to order
the entities, which is a common use. However, the primitive is more general, and any
calculation that can be made for each entity can be used for ordering. The equivalent
for selecting the entities with the smallest values is min-n-of. See also max-one-of and
min-one-of.
The Command Center (labelled (8) in Figure 1.1) has an area at the bottom to enter NetLogo
code to be run immediately. You can use this to report the number of patches with a non-zero
value for popn-I and open an inspect window for one of these patches.
Press the setup button to initialise the epidemic. Enter the code count patches with [popn-I
> 0] into the input box. The output area repeats back the entered code (with show at the front)
and reports the results of the count (see gure 3.3; as expected, there are three patches with
popn-I values greater than 0.
Figure 3.3: Command Center with results from code. The blue lines mark the perspective dropdown
box and the Command Center expansion toggle.
count
The count primitive reports the size (number of entities) in the specied agentset. The
agentset can be specied explicitly by name (such as patches) or as the result from a
piece of code.
There are other aspects of the Command Center to notice. Both the input area and the output
have the word `observer' at the start. This is to inform the user which perspective is being taken.
Change the perspective to `patches' using the dropdown box at the left of input area. Enter the
code set pcolor red and you should see that all patches change their colour to red. Change
back to the `observer' perspective and enter colour-patches. This will run the procedure named
colour-patches in exactly the same way as it is called from the `setup' procedure when the setup
button is pressed. As only the entered procedure is run, the maximum population and the
location of the cities is unchanged.
At the top right of the Command Center there is a double ended arrow. Click on that and the
text area will expand to take up the right half of the model interface. Click again and it will
return to the small area at the bottom. The bar between the main interface and the Command
Center can be dragged to change the size.
With the perspective set to `observer', enter the code inspect max-one-of patches [popn-I].
What does this code do? First, it searches through the patches and nds the one with the largest
value of popn-I (infected population) and then opens an inspect window for that patch. You
should check that the values of the population in the dierent epidemic states look reasonable.
In particular, check that popn-I approximately 0.5% of popn, and that popn is the sum of popn-I
and popn-S.
3.4. CONDITIONAL CODING: UPDATING THE COLOUR SCHEME 49
Figure 3.4: ifelse-value can be used instead of an ifelse construction where the two paths are setting
the same variable to dierent values. The left code box is the ifelse-value as included in Snippet 2c
(page 49), and the right code box shows the ifelse with separate set commands. Note also the use of
numbers for colours: 16 is a darker shade of red than 18.
to colour-patches
let max-scale 1.3 * ln max-popn
ask patches
[ ifelse popn-S > popn-R ∠∠
[ set pcolor scale-color blue ln popn max-scale 3.2 ]
[ set pcolor scale-color green ln popn max-scale 1.5 ] ∠∠
if popn-I >= 1 ∠∠
[ set pcolor ifelse-value (popn-I > 0.03 * popn) [16] [18] ]
∠∠
]
end
This snippet introduces all three versions of the conditional branching IF / THEN / ELSE.
This is a fundamental construct of many programming languages and consists of a test, with
one set of commands run if the test returns true and a dierent set run if the test returns false.
It is essential for agent-centric behaviour because it translates the dierent characteristics and
circumstances of each agent into potentially dierent actions.
The rst use is the ifelse format. The test compares the susceptible and removed population
counts. If the test is true then the rst code block is run (using a blue colour scale when
susceptible is larger) and if it is not true then the second code block is run (green colour scale).
The second use is the if format to test whether there is any infected population. The dierence
between if and ifelse is that nothing happens if the test is false with if, the code block is
simply skipped. Finally, ifelse-value is used if the two actions to be taken are simply to set
the same variable to two dierent values. Figure 3.4 displays the full ifelse alternative for
ifelse-value.
After completing this snippet, press the setup button. Three patches should be coloured light
red (see Figure 3.5). Further, those three patches should all be in the high population areas
of the model. It is now straightforward to open an inspect window for one of these patches to
conrm that the population values in each state are sensible. This example also demonstrates
that sanity checking is much easier with an informative interface design.
50 CHAPTER 3. MODEL 2: INTRODUCING TIME AND SPACE
Figure 3.5: Screenshot of the interface after completing version 2c of the model.
There are four types of widgets that allow values to be entered by the user into the model. A
slider allows only numbers to be entered, and the specic number is selected by moving a slider.
The developer sets the range of permitted values (maximum and minimum), which can be used
to restrict entry to sensible values. A switch is used to enter a value that is either true (switch on)
or false (switch o). A chooser (or dropdown box) is used to select between multiple pre-dened
choices, which could be numbers, text or some combination. Finally, an input box allows any
value to be directly typed by the user, and the only restriction is the form of the value (such as
number or string).
Regardless of the type of input widget used, the top of dialogue box has a space titled `Global
variable'. The text entered in that box must satisfy the variable naming conventions (see section
2.5). This is because the widget creates a global variable with the given name. The variable is
available to the code in exactly the same way as a variable listed in a globals statement. The
value is assigned by the input rather than a set statement. Note that a set statement in the
code will change the variable's value, both internally and on the interface. That is, the interface
widget is `live' throughout the simulation and can even be changed during a simulation run.
3.6. THE ASK COMMAND 51
I User Inputs
An important part of the interface design is identifying the key parameters that users
will want to change. Those parameters should be included in the interface with sliders
or other input widgets, and less important parameters included within the model code as
global variables with sensible default values applied with a set command.
ask
The full syntax is ask <agentset> [<instructions>]. The ask command instructs the
specied agentset to implement the code in the square brackets.
The ask command steps through each entity in the agentset and runs all the code for that entity
before moving on to the next entity. Each ask moves through the entities in a random order. In
a simulation, much of the code is run each time step (or tick), so any ask is also run multiple
times. The random ordering avoids artefacts arising with same agent always accrues any benets
of going rst.
Figure 3.6: Screenshot of the slider dialogue box for the variable R0, which is the basic reproduction
ratio. The top text box is used to enter the name of the global variable that is created by the slider.
S
∆S = −βI
N
S
∆I = βI − γI
N
∆R = γI
Before implementing Snippet 2d-2 (page 53), it is worth thinking about how you would translate
these equations into NetLogo code. What order would you update these equations and why is
that order important? Are there any checks you need to make during the calculations?
The individual primitives in this procedure are relatively simple and have all been introduced
already, comprising only ask, if, let and set. Operating with information stored in variables,
careful ordering of these simple commands is able to create complex behaviour.
The logic in this procedure is:
3.7. MAKING THE MODEL A SIMULATION 53
to spread-epidemic
ask patches
[ ; calculate the number of new infections generated by the patch
let beta (R0 / recovery-period)
set incidence popn-I * beta * popn-S / popn
; update the population counts in each epidemic state
let recovered popn-I / recovery-period
if incidence > popn-S [ set incidence popn-S ]
set popn-S popn-S - incidence
set popn-I popn-I - recovered + incidence
if popn-I < 1 [ set popn-I 0 ]
set popn-R round (popn-R + recovered)
]
end
1. Calculate expected incidence rst, before the S and I population counts are adjusted.
2. Make sure that incidence does not exceed the number of susceptible available. This can
occur because, conceptually, each infected person nds their own susceptible targets simul-
taneously so susceptibles can be infected multiple times. Reduce incidence if required.
3. Calculate the population to recover before the newly infected are added to the infected
population.
4. Mathematically, the infected population would never reach 0 after it is non-zero because
all the relevant equations simply multiply numbers together. Instead, both incidence and
popn-I would approach 0, though rounding to nearest integer may resolve this. To guarantee
resolution, the infected population is set to 0 when it falls below 1.
Note that rounding (to the nearest integer) is included in this code as it is not possible to have
fractional people infected in the real world. However, this can introduce subtle errors when
dealing with small numbers. This is the reason that popn-R is rounded rather than the local
variable `recovered'; the number of people recovering as the epidemic dies out will be less than
1, and rounding to 0 would mean that the last infected person never recovers.
Snippet 2d-2 (page 53) implements the spread of the epidemic in a single time unit (day). The
next step is to set up the passage of time, instructing NetLogo to repeatedly run the procedure
to spread the epidemic spread. This is implemented in Snippet 2d-3 (page 54). Once coded (and
syntax checked), press the setup button and then the do it! button. After the simulation has
run for awhile, press the do it! button again to stop it. The interfact should look similar to the
screenshot at Figure 3.7.
NetLogo links together the do it! button and the go procedure. The button calls the procedure
when pressed. Checking the `Forever' box means that the go procedure continues to get called
until the button is pressed again. That is, a single press of the button requests multiple iterations
through the go procedure (as depicted in Figure 3.2).
Each iteration through the go procedure rst runs the spread-epidemic procedure, which updates
the epidemic status counts for each patch. It then calls the colour-patches procedure, which we
previously created so that the patches were appropriately coloured during initialisation (that is,
the setup procedure). Finally, it instructs NetLogo to increment the tick counter with the tick
command.
54 CHAPTER 3. MODEL 2: INTRODUCING TIME AND SPACE
to go
spread-epidemic
colour-patches
tick
end
Figure 3.7: Screenshot of the interface after completing version 2d of the model. Notice the tick
counter (below the speed slider) reading 249 in this example and the green colour of the patches where
the epidemic occurred.
If reset-ticks command has not already occurred, then tick will generate an error. So the
setup procedure is amended to include reset-ticks.
tick
The tick command increments the tick counter. The number of ticks is used to represent
the passage of time and can be accessed with the ticks reporter. See also reset-ticks,
which is used to initialise the tick counter.
I Code order
It is standard practice to locate clear-all as the rst command in the setup procedure,
reset-ticks as the last command in the setup procedure, and tick as the last command
in the go procedure. As reset-ticks also initiates any plots, this order ensures that all
the model entities are initialised before their values are plotted.
3.8. COMMANDS, REPORTERS AND PROCEDURES 55
To understand what is happening and as a sanity check, you can edit the do it! button to uncheck
`Forever', then press the setup button once and then the go button. Open an inspect window for
one of the red patches. Each press of the do it! button will run through the go procedure once,
updating the epidemic state population counts and incrementing the tick counter. Watch the
incidence and population values in the inspect window as you press the button. See if you can
use the equations to calculate the expected values for the epidemic state populations for the next
go step then press the go button and see if you are correct. Try it again with dierent parameter
settings; for example, you would expect a more intensive epidemic with a higher value of R0 and
a shorter recovery-period. When you have nished, check `Forever' again for the do it! button.
What did you notice while running the simulation? First, you had to stop the simulation by
pressing the go button, even though the epidemic had run its course. Second, the epidemic
didn't spread out, it was trapped in the patches where it started. Fixing these two issues, and
plotting some simulation results, are the remainder of the tutorial model version 2. However,
some additional theory is required rst.
Those primitives that are used to obtain information are referred to as reporters. Important
reporters include n-of and patches, as well as several that will be introduced in the next
version of the model. Other primitives that can be used within procedures are referred to as
commands. Commands are primarily used to instruct one or more turtles or patches (or links) to
do something. Important commands include ask, set and ifelse. Looking at this paragraph,
you will see that all the reporters are purple and commands are blue, this is part of the automatic
formatting in the NetLogo code area. And keywords are formatted in green.
In the same way that the primitives are split between reporters and commands, two types of
procedures are available. A reporter procedure runs the contents and then provides some piece
of information back to the procedure that called it. Command procedures implement actions.
All the procedures included in the tutorial model so far are command procedures, and have been
delimited with to and end. Reporter procedures are delimited with to-report and end and
must include a report command identifying the value to be returned to the calling procedure.
I Command or reporter?
It is not always obvious when to construct a procedure as a command procedure (using
to) or as a reporter procedure (using to-report). A good rule of thumb is that, if the
procedure changes anything in the model, it should be a command procedure. Reporter
procedures should be completely passive, accessing information but not aecting the
model in any way.
56 CHAPTER 3. MODEL 2: INTRODUCING TIME AND SPACE
to-report all-done?
let test-result 0
let total-infected sum [popn-I] of patches
ifelse total-infected > 0
[ set test-result FALSE ]
[ set test-result TRUE ]
report test-result
end
Figure 3.8: An expanded equivalent to the code in Snippet 2e-1 (page 56) to assist with understanding.
to-report all-done?
report ifelse-value (sum [popn-I] of patches > 0) [FALSE] [TRUE]
end
In Snippet 1b-3 (page 29), the maximum of the population values over patches was calculated and
assigned to the global variable max-popn. This procedure takes a similar approach, calculating
the sum (total) instead of the max (maximum). Both sum and max are mathematical primitives
that operate over a list.. A list is a particular type of data structure, where multiple data items
(numeric values, text strings, turtles, other sub-lists) are stored in a single variable in a xed
order. While lists are useful, they are outside the scope of this tutorial. What is important here
is that the primitive of returns a list. In this snippet, the list contains the values of the popn-I
3.9. SPATIAL AWARENESS 57
variable for each patch (in whatever random order the ask runs through the patches). That list
is used as soon as it is created by the sum operator, without being explicitly stored.
of
Model entities automatically know the values of their own variables, including global
variables and turtles have access to the variables of the patch where they are located.
The reporter of is used to access variables owned by other entities; it identies the owner
of the variable to be accessed. The full syntax is [<reporter>] of <agentset>.
I Truth values
TRUE and FALSE are special values recognised by NetLogo. They are created by logical
tests or conditions and can be manipulated with logical operators.
If you want to test whether a variable has a specic value, then the test would have similar syntax
as if varname = "xyz" [ ]. Further, to test whether it any value other than the specied one,
the code would be if varname != "xyz" [ ] (the combination ` !=' is the operator for `not
equal to'). Equivalently, for a variable being used to store boolean values, the syntax would be
if varname? = TRUE [ ].
However, if the test is of a truth value (that is, either TRUE or FALSE), it is sucient to drop the
`=' part of the test. The code if varname? will resolve to TRUE or FALSE as appropriate, and
return an error if the variable `varname?' has any other value (such as 0 or the string "TRUE").
But what if you want to test for FALSE? Just as there are mathematical operators to manipulate
numbers (such as +), there are logical operators to manipulate truth values. In particular, not
converts TRUE to FALSE and FALSE to TRUE. So, if not varname? would resolve to TRUE only
when the value of `varname?' is FALSE. Another common logical operator is and.
Instead of explicit variables, Snippet 2e-2 (page 58) tests the truth value of the procedure created
in Snippet 2e-1 (page 56) to break out of the `go' loop once the epidemic has run its course. Each
loop through the go procedure, the all-done? procedure is called and, if that procedure returns
TRUE, then the condition is met and the stop command breaks NetLogo out of the forever
instruction issued by the button for the go procedure.
This snippet completes model 2e. No screenshot is presented as it is identical to Figure 3.7.
However, the simulation should stop running automatically. Press the setup button and then
the do it! button to check the termination.
to go
if all-done? [ stop ] ∠∠
spread-epidemic
colour-patches
tick
end
stop
stop forces the model entity (including the observer) to terminate the code block that it
is running. If implemented within a code block delimited with square brackets, the eect
is the same as jumping to the closing bracket (and then continuing). It can also be used
to terminate a procedure called by a button with forever checked.
Similarly, turtle agents locations are specied with a pair of variables named xcor and ycor.
Turtle positions are continuous, for example xcor of -5.2345 and ycor of 2.6789. The co-ordinate
system for turtles is the same as the co-ordinate system for patches (despite the dierent names).
The integration of the co-ordinate systems means that a patch is exactly 1 × 1 spatial units in
size. The patch that a turtle occupies is the one identied by rounding the co-ordinate values for
the turtle, with 0.5 always rounded up. For example, the turtle with xcor of -5.2345 and ycor
of 2.6789 would be on patch -5 3. Similarly, patch 0 0 covers -0.5 <= xcor < 0.5 and -0.5 <=
ycor < 0.5.
This built in co-ordinate system allows spatial concepts such as distance and directions to be
meaningful. Turtle agents also have a heading automatically, even if they are not moving; it is a
number from 0 to 360 (degrees) with 0 as `up'. The spatial structure also supports concepts such
as `here' (referring to the same patch) and, for turtles, `forward' and `the patch in front of me'.
For the tutorial model, the turtle agents will be stationary. Movement is discussed in Chapter 8.
to color-neighbours
clear-all
ask n-of 3 patches
[ ask neighbors
[ set pcolor red
]
]
ask n-of 3 patches
[ ask neighbors4
[ set pcolor blue
]
]
end
Figure 3.9: Demonstration of the neighbors (8 patches) and neighbors4 (4 patches) reporters. Each
of three randomly selected patches instruct their neighbors to turn red, and another three instruct their
neighbors4 to turn blue.
neighbors
The eight patches adjacent to a patch are referred to as the patch's neighbors. A turtle
can also access the neighbors of the patch where it is located. See also neighbors4.
to initialise-globals
set travel-rate 0.1
end
The globals statement declares the existence of this new variable. The initialise-globals proce-
dure uses set to assign a value. Setting all the global variable initial values in a single procedure
60 CHAPTER 3. MODEL 2: INTRODUCING TIME AND SPACE
allows them to to easily found and changed if necessary, even by a model user. The call to that
procedure must occur before any of the variables are used by other procedures, otherwise the
value 0 will be used instead. Incorrect global values can introduce subtle logic errors that are
dicult to detect and NetLogo will not report an error (unless, for example, the variable has a
value of 0 and is the denominator in a division).
Snippet 2f-2 (page 60) uses the new global variable to allocate some of the change in total
infected population to neighbouring patches rather than just the patches where the infections
are generated. The patch does this by randomly selecting one of the eight patches surrounding
it and changing the incidence value in that patch. However, a patch could receive new infections
from more than one patch, so care must be taken with the sequencing of actions.
The various sources of new infections must be summed within each patch to calculate the total
incidence for that patch. This means that all patches must have the opportunity to generate new
infections before the value of new infections is used to update patch epidemic status counts. In
addition, since incidence is being cumulated rather than calculated, it must be explicitly set to 0
at the beginning of each time step so that only the new infections in the new time step are added
together. Therefore, the spread-epidemic procedure must have multiple ask patches [ ] code
blocks.
As well as the already discussed neighbors primitive, this snippet introduces one-of. This is
similar to n-of, discussed at 47, but randomly selects only one member of the specied set of
agents (patches, in this case).
This snippet also introduces myself but this is a dicult primitive to understand, and some
further work is required before it can be fully explained. At this point, it is sucient to recognise
that it is referring to the patch that did the asking.
to spread-epidemic
ask patches [ set incidence 0 ] ∠∠
ask patches
[ ; calculate the number of new infections generated by the patch
let beta (R0 / recovery-period)
let new-cases popn-I * beta * popn-S / popn ∠∠
ask one-of neighbors [ set incidence incidence + travel-rate *
[new-cases] of myself ] ∠∠
set incidence incidence + (1 - travel-rate) * new-cases ∠∠
] ∠∠
ask patches ∠∠
[ ; update the population counts in each epidemic state ∠∠
...
...
end
3.10. OUTPUT WIDGETS FOR MODEL RESULTS 61
After implementing Snippet 2f-2 (page 60), press the setup and then do it! buttons to see the
eect of the changes. You should have the epidemic spread throughout the world, as shown in
Figure 3.10.
Figure 3.10: Screenshot of the interface after completing version 2f of the model. The epidemic should
spread throughout the world, with a darker red epidemic frontier and patches turning green as the
epidemic has passed.
to compare numbers than curves across multiple simulations and a monitor will be added to the
interface to report the impact of the epidemic, the total population ever infected. You should
think about how to calculate these values before moving on.
Note that you may need to move the existing widgets to make room for the plot. This can be
achieved by selecting the widget (popup menu) to highlight it and then dragging it with the
mouse. Selecting a widget also allows it to be resized by dragging an edge or corner.
Snippet 2g (page 62) describes the plot and monitor to be added to the interface. The plot has
two pens (dierent coloured lines), one for incidence and the other for prevalence. Figure 3.11
displays the relevant plot dialogue box with the code and other details lled in. The monitor
will display the total of the popn-I and popn-R values.
Figure 3.11: Screenshot of the plot dialogue box for the epidemic progress. The top text box is used
to enter the title of the plot. To the right are the (starting) limits of the axes. The x-axis is for ticks,
so the default value of 10 is reasonable. However, the y-axis is proportion of the total population, and
a small number is required to make sure the plot curves are visible. The Auto scale? checkbox allows
these axis limits to increase as required, and is essential when plotting against ticks. The button at the
bottom of the dialogue box creates extra pens. Each pen is a line with a colour (changed by clicking on
the coloured area), name, and code (commands). If there is insucient space in the code box, press the
pencil icon button at the right to access a further dialogue box.
After implementing Snippet 2g (page 62), press the setup and then do it! buttons to see the
eect of the changes. As the epidemic spreads, you should see the plot curves increase and then
decrease (see Figure 3.12), potentially with additional peaks as the epidemic reaches areas with
high population density.
3.11. TUTORIAL PROGRESS CHECK 63
Figure 3.12: Screenshot of the interface after completing version 2g of the model, with the plots and
impact monitor. This screenshot was captured at the end of the simulation, when the epidemic is over,
to show the classic shape of the epidemic curves.
Try changing the epidemic parameters and seeing the eect on the epidemic. You should nd
that a larger value of R0 and/or shorter recovery period increases the intensity of the epidemic
(steeper curves) and also the impact (total population aected). However, regardless of the
parameter values, the impact will not reach 1, some population will remain susceptible. What
happens if you reduce R0 to below 1? This means that each infected person infects less than
one other person on average, so the epidemic dies out very quickly. Because of the spatial eects
(where infected people are concentrated), this dying out will actually occur at some value greater
than 1.
used to control the ow of the code, so that dierent commands can be implemented in dierent
situations. So far, this has only been used for visualisation, to colour the world. In the next
version of the model, conditional code will allow agents to make decisions that reect their own
characteristics and circumstances, the essence of agent-based modelling.
Also formally presented was the fundamental command ask to pass instructions to specic
agentsets, which had been used in version 1 code snippets without comment. Detailed discussion
is deferred until agentsets have also been presented.
4
Model 3: Agents Making Decisions
Model 3 implements the behaviour decision process: people adopting (and dropping) protective
behaviour. Once implemented, this version is a full agent-based model because it represents in-
dividuals enacting a process based on their situation and characteristics. That situation involves
interaction with other individuals, so all the essential elements of the denition of an agent-based
model are in place.
From this point in the tutorial, there are fewer additional keywords introduced in each model
version. While NetLogo is a rich language, only a small subset is necessary to implement many
agent-based models. However, only a small part of writing code is knowing the relevant keywords,
and there are many important concepts remaining.
65
66 CHAPTER 4. MODEL 3: AGENTS MAKING DECISIONS
t
X
Bi = ωA Ai + ωN Nr1 + (1 − ωA − ωN ) (1 − δ)t−j It,r2
j=0
where i species the individual, r1 and r2 denote the relevant regions for the perception of norms
and threat respectively, t is the time step, A, N and I represent attitude, norms and incidence,
and ωA and ωN are the weights for attitude and norms. The behaviour score is compared to a
threshold and behaviour is adopted or dropped accordingly.
In addition, people's protective behaviour must inuence the epidemic process. The capacity
of the epidemic to spread in a region (r) should reduce with increases in the proportion of
people adopting protective behaviour (Pr ) and the ecacy of that behaviour (E ). Ecacy is
the reduction in probability that a protected person is able to become infected or, if already
infected, transmit the infection. For example, if 100% of the population have adopted protective
behaviour and that behaviour is 40% ecacious, then infections should be 40% lower than
they would be without such behaviour and, if 40% of the population have adopted protective
behaviour and that behaviour is 100% ecacious, then infections should also be 40% lower than
they would be without such behaviour. What happens if 60% of the population have adopted
protective behaviour and that behaviour is 50% ecacious? This would reduce infections by
30% (calculated as 50% of 60%). Since β in the epidemic transmission equations represents that
capacity, this parameter must be adjusted for local behaviour, with the adjustment given by:
βr = β (1 − Pr E)
What is needed to implement this design? Try to identify the information (variables) and actions
(procedures) required before moving on. Are the variables global or do they potentially have
dierent values for some patches or turtle agents? Which procedures required for initialisation
(called by setup) or during the simulation (called by go)? All of this detail is part of the conversion
from a design to a fully operationalised specication suitable for translating into code.
Consider the code at Figure 4.1. Each version changes the colours of the patches along the
diagonal to either red (left) or blue (right). You can test this by adding the procedure(s) to the
code tab, then typing the name of the procedure in the Command Center.
The diag-observer procedure is written from the perspective of the observer, an external entity
that can pass instructions to the model and, in some sense, stands in for the model developer or
user. The rst step is to ask patches to follow the instructions in the code block (delimited by
[ ]). The ask instructs the simulation to randomly choose a patch, apply the code in the code
block to that patch, then move to another randomly chosen patch until all patches have run the
code. When interpreting (or writing) the code, you might nd yourself imagining yourself as a
patch and thinking about what happens to you. That is, all the code in the code block is from
the perspective of the patch, you don't have to specify the patch to check its pxcor and pycor
and changes colour if they are equal, it is automatically whichever patch is the current patch in
the ask order. In NetLogo terms, the opening bracket changes the context from the observer to
the patch, and the closing bracket changes it back.
4.2. CONTEXT AND PERSPECTIVE 67
to diag-bypatch
to diag-observer ask patches [ do-patch ]
ask patches end
[ if pxcor = pycor
[ set pcolor red to do-patch
] if pxcor = pycor
] [ set pcolor blue
end ]
end
Figure 4.1: Running procedure diag-observer (left) and diag-bypatch (right) achieves the same outcome.
The code on the left takes the perspective of the observer, instructing some patches to change colour
to red. In the code on the right, the procedure diag-bypatch instructs each patch to run the do-patch
procedure. The diag-bypatch procedure is observer context, and the do-patch procedure is patch context.
The diag-bypatch procedure is also written from the perspective of the observer. It starts the
same way, but then transfers control to a separate procedure. As before, the context changes
with the square brackets. In this version, however, the dierent context occurs in a separate
procedure. The do-patch procedure is written from the perspective of an individual patch and
is run once for each patch (controlled by the ask patches in diag-bypatch).
The primitive myself can only be interpreted from an understanding of context. When one model
entity instructs a second model entity to do something, that second entity may need information
that is known to the original entity. But the switch of context with the ask statement means
that NetLogo is running code from the perspective of the second entity. So the myself primitive
provides a link back to the rst entity, the one issuing the ask.
myself
myself is used inside an ask code block. It refers to the agent (or model entity) that
issued the ask. See also self.
NetLogo keeps track of the context automatically. While most keywords can be used in any
context (such as ask or if), others can only be used within certain contexts. These are marked
by an icon in the NetLogo dictionary: observer has an eye ( ), patch has a checkerboard ( ),
turtle agent has a turtle ( ) and link has a chain link ( ). For example, tick can only be
used by the observer, and xcor is only accessible from the turtle context.
In the diag-observer procedure, the rst line of ask patches signals to NetLogo that the pro-
cedure is intended to run in the observer context. NetLogo does not allow a patch (or turtle or
link) to ask all the patches (or turtles or links) to do something. In the do-patch procedure, the
rst line refers to the patch only primitive pxcor, signalling to NetLogo that the procedure is to
be run by patches.
68 CHAPTER 4. MODEL 3: AGENTS MAKING DECISIONS
t
X
Tt,r = (1 − δ)t−j Ij,r
j=0
t−1
X
= (1 − δ)0 It,r + (1 − δ) (1 − δ)(t−1)−j Ij,r
j=0
= It,r + (1 − δ)T(t−1),r
The update-threat procedure at Snippet 3a (page 68) uses this relationship to calculate the new
value of threat each tick. The procedure is a patch context procedure because the call to the
procedure will be inserted within an ask patches [ ] block in the epidemic-spread procedure.
Threat must be updated after the epidemic has been updated because it requires the value of
incidence for the patch.
Note that the same variable is being used for both the assignment and within the calculation.
Mathematically, this would introduce an error for circular reasoning. However, this construction
in NetLogo and many other programming languages is interpreted as: calculate the expression us-
ing the current value of the variable named `threat' and then assign the results of that calculation
to the variable named `threat'.
This snippet makes no visible change so the model remains as in Figure 3.12. However, a sanity
check is necessary to ensure the code works as intended. Press setup and then open an inspect
window for one of the patches where infections are present. Type `go' into the Command Center
to run the go procedure once. Look at the values of incidence and threat, then type `go' again
and look at the updated values. At tick 1, the value of threat should be incidence / popn. At
tick 2, the value of threat should be 0.9 × tick 1 threat + incidence / popn. More generally,
inspect a patch outside of the epidemic area and note that the threat is zero until the epidemic
is close then increases as the epidemic reaches the patch and decreases once the epidemic has
passed.
4.3. PROCEDURES WITH ARGUMENTS (INPUTS) 69
This is similar to mathematical functions. For example, the function f (x) = x2 + 3 returns
dierent values for dierent values of x. For x = 2, f (x) = 7 and for x = 5, f (x) = 28 and so on.
In the same way, procedures can be written that include an input (referred to as an argument)
in the processing of the code. This is true for both command procedures (dened by to) and
reporter procedures (dened by to-report).
The arguments are named immediately after the procedure name and included in square brackets.
When the procedure is called, the values for those arguments follow the procedure name without
any special syntax.
√
X= Um for U < m
for U ≥ m
p
X = 1 − (1 − U )(1 − m)
If a procedure might be relevant to many dierent models, it is useful to have a general purpose
procedure with arguments rather than x values within the code. This makes it more exi-
ble. Snippet 3b-1 (page 70) creates a general procedure for generating random numbers from a
triangular distribution with three parameters for the limits and the mode. The triangular0to1
procedure calls the general procedure, passing the mode and setting the limits as 0 and 1. This
latter procedure is used to generate attitude values in Snippet 3b-2 (page 70).
How can this code be checked? Random number generators can only be tested by drawing many
random numbers and examining the distribution of the values. However, there is no need for strict
tests of randomness; that is the responsibility of the NetLogo developers in their construction
of the random-float primitive. It is instead sucient to examine whether the conversion to a
triangular distribution is working as expected.
Snippet 3b-3 (page 71) constructs a histogram of the attitude values. It will populate after you
press the setup button. What do you expect? Since you have assigned a mode of 0.8, you should
see a triangular shape with the highest point at the value of 0.8 similar to Figure 4.2. Note that
if you have only a single bar, you probably did not follow the instruction to set the interval (bar
width) to 0.05.
70 CHAPTER 4. MODEL 3: AGENTS MAKING DECISIONS
random-oat
The full syntax is random-float n. Generates a number anywhere in the continuum from
0 to n. The random number is uniformly generated along the continuum.
More thorough testing would vary the mode and see if the histogram adjusts accordingly. The
most comprehensive testing would check the random-triangular procedure with dierent limits
to make sure that the limits of 0 and 1 are not the only ones that work. Try code such as
set attitude random-triangular 3 2 5 for assigning attitude values. Remember to change
the code back after testing.
I Operationalising probability
The random-float reporter is particularly useful for implementing code that should be
run with some probability, replicating the outcomes of rolling a fair die with an appropri-
ate number of sides. For example if random-float 1 < 0.2 will be true with a 20%
probability.
to make-people
...
set size 0
set attitude triangular0to1 0.8 ∠∠
]
...
end
4.4. AGENTSETS 71
Figure 4.2: Screenshot of the histogram displaying the distribution of attitude values. Note the peak
at 0.8 and the triangular shape.
4.4 Agentsets
An agentset is simply a group of patches or turtles or links but not a mix. An agent can only
appear once in an agentset; if an attempt is made to add an agent to an agentset in which it is
already a member, nothing happens.
Whenever an agentset is accessed, for example with an ask command, the access is in a random
order. That order changes each time the agentset is accessed. This means that sequencing eects
are automatically avoided; for example, no agent gets the advantage of always being the rst to
make a choice.
Agentsets provide much of the power of the NetLogo language. They support clear and concise
short coding of the fundamental representation in agent-based modelling, taking the perspective
of each agent individually so that it can take some action.
So far, the tutorial model has extensively used the built in patches dataset, which is the group
of all the patches. There are also equivalent agentsets for all turtles or all links. In addition,
if breeds have been dened, then there is also an `all members' type agentset for each breed.
These agentsets are not only automatically available for any model, they are updated as agents
are added (for example, with a hatch command) or removed (with a die command). Another
important agentset built into the NetLogo language is neighbors.
Agentsets can also be created explicitly with a patch-set or turtle-set or link-set com-
mand. This command instructs NetLogo to combine the agentsets that are specied into a single
agentset. That is, these commands are the set operator `union'.
72 CHAPTER 4. MODEL 3: AGENTS MAKING DECISIONS
patches
The patches agentset consists of all patches. It is automatically generated and updated
(for example, if the size of the World is changed) and available to all model entities. See
also turtles and links.
The nal method of creating agentsets is by selecting agents from an existing agentset. This
has also been used already in the tutorial model with n-of and max-n-of. Another common
subsetting command is with to select those agents that meet some condition, which will be used
in Snippet 3e (page 77).
Agentsets can be assigned to a variable in exactly the same way as any other variable value,
using a set or let command. But they can also be used in the code without being assigned to
a variable. For example, in Snippet 1b-3 (page 29), the instruction to assign a high population
value to some patches was in the form: ask n-of 3 patches [ set ... ]. A set of 3 patches
was created by the n-of statement and used by the ask command without ever being assigned
to a variable.
to decide-behaviour
ask patches
[ let visible (patch-set self neighbors)
set prop-protect (count (people-on visible) with [protect?]) /
(count people-on visible)
set max-threat max [threat] of visible
]
ask people
[ let decision-value wt-attitude * attitude + wt-norms *
prop-protect + (1 - wt-attitude - wt-norms) * max-threat
set protect? ifelse-value (decision-value >= threshold) [TRUE]
[FALSE]
]
end
self
self is the agentset comprised of one agent, the one from whose perspective the code is
being implemented. See also myself.
truth values are consistent; it doesn't matter whether it's a boolean variable or a conditional
test, true is true.
By now, you should be considering what sanity check to use to check this code. One option is
to run the model and stop it when the epidemic is very active. You can then simply count the
people currently protected by typing code into the Command Center. Suitable code would be
count people with [protect?]. You could also inspect some people and the patch where
they are located to see the values of the various decision inputs and the protection state of the
person. Or you could add a monitor to the interface to count the protected people and let the
model run, deleting the monitor when you are condent the model is operating correctly.
I Interface design
Organise the interface so that related widgets are close to each other. Another option is
to have the basic controls in one area and more advanced settings in another area. The
goal is to make the model easy to use and understand.
patch-set
The full syntax is (patch-set input-patchset1 input-patchset2 input-patchset3
...). It is a union operator to combine multiple specied patchsets into one patchset.
Even if a patch appears in more that one of the input patchsets, it will only appear once
in the combined patchset. See also turtle-set and link-set.
74 CHAPTER 4. MODEL 3: AGENTS MAKING DECISIONS
turtles-on
The full syntax is turtles-on <some-patchset>. Creates an agentset of all the turtles
that are located on the patches in the specied patchset. The turtles can be all turtle
agents, or just those of a specic breed.
with
The reporter with subsets an agentset, creating a new agentset that only contains the
agents that meet the specied condition.
An easier way to check whether the protective behaviour process is working as expected is to
construct a plot of the proportion of the population who are protected. This is also useful
information for users, and the plot to add is described at Snippet 3c-2 (page 75). However, such
a plot does not negate the need to inspect some people to ensure the detailed calculations are
correct. With a plot, it is easy to test the eect of dierent threshold values; with a low threshold
almost every person should be protected, and none would be protected if the threshold was set
very high.
Once the plot is created, press the setup and do it! buttons. The model should be similar as
shown in Figure 4.4. Notice that the interface widgets are grouped so that epidemic controls are
together, as are protective behaviour settings.
Figure 4.3: These two lines of code are equivalent. The rst explicitly sets the truth value of the variable
based on whether the conditional is true. The second simply assigns the result of the conditional and is
shorter, but more dicult for a human reader.
4.6. TUTORIAL PROGRESS CHECK 75
plot count people with [protect?] / count people ; code for pen
Figure 4.4: Screenshot of the interface after completing version 3c of the model. Approximately half
the population quickly adopts protective behaviour, with protection levels starting to decline as the
epidemic is dying out.
switch is used for boolean variables, it is either on (true) or o (false). As with other widgets,
it is added directly to the interface and its value assigned to a global variable by entering an
appropriate variable name.
Change the ecacy slider to 0 and run the model twice, once with the switch on, and once with
the switch o. Because ecacy is set to 0, the level of protective behaviour has no eect on
the epidemic impact and there should be little dierence in model results (averaged over many
runs). However, in the runs with the switch set to not reversible, the proportion protected should
increase (or remain stable), even when the epidemic has passed. This can be seen in Figure 4.6.
to spread-epidemic
...
ask patches
[ ; calculate the number of new infections generated by the patch
let beta (R0 / recovery-period) * (1 - efficacy * (count
people-here with [protect?] / count people-here)) ∠∠
let new-cases popn-I * beta * popn-S / popn
...
end
turtles-here
turtles-here creates an agentset of all the turtles that located on the instructing patch,
or the patch where the instructing turtle is located. The turtles can be all turtle agents,
or just those of a specic breed.
Figure 4.5: Screenshot of the interface after completing version 3d of the model. The eect of protected
behaviour is visible, with much of the World coloured blue at the end of the epidemic, indicating that
less than half the population were ever infected.
• is a computer program. . . : yes, it is written in the NetLogo language and runs on the
computer;
• that represents individual entities. . . : yes, the turtle breed `people' are individuals;
• taking actions. . . : yes, the simulated people adopt and abandon protective behaviour;
• in accordance with their own characteristics, resources, beliefs. . . : yes, the personal at-
tribute of attitude is a component in their choice of action;
• and perception of their social and physical environment.: yes, the simulated people are
able to perceive the proportion of people nearby that are behaving protectively and the
4.6. TUTORIAL PROGRESS CHECK 77
to decide-behaviour
...
ask people
[ let decision-value wt-attitude * attitude + wt-norms *
prop-protect + (1 - wt-attitude - wt-norms) * max-threat
ifelse reversible? ∠∠
[ set protect? ifelse-value (decision-value >= threshold)
[TRUE] [FALSE] ] ∠∠
[ if not protect? and (decision-value >= threshold) [ set
protect? TRUE ] ] ∠∠
]
end
Logical operators
Logical operators manipulate truth values in the same way that mathematical operators
(such as +) manipulate numbers. Common logical operators are: not which converts
true to false and false to true; and which is true only if all input values are true;
and or which is true if any input value is true.
Figure 4.6: Screenshot of the interface after completing version 3e of the model. The eect of irreversible
behaviour is displayed in the proportion protected plot, which increases throughout the epidemic and
does not decline once the epidemic is over.
resented. The behaviour of the epidemic is driven by the interactions between the epidemic
and protective behaviour processes. This was immediately apparent when the processes were
connected in Snippet 3d (page 76) and the epidemic was throttled by eective protection.
Two important concepts were introduced in model 3: agentsets and context. Agentsets are
fundamental to the NetLogo approach to coding an agent-based model. They allow concise
identication and selection of relevant agents, both overtly or more subtly underpinning the
exibility of NetLogo. Agentsets can be combined or subsetted, stored in variables, and issued
instructions.
Each time NetLogo accesses an agentset, the context changes and the perspective is taken of each
individual agent in turn. The order in which NetLogo iterates through the agents is random, and
is reordered each access.
When developing code, it is often easiest to imagine yourself as an agent (such as a turtle) and
think about what information you would need and what you would do to perform the required
task. It is also worthwhile to consider whether the same logic applies for all agents, particularly
the ones taking the rst turn, a middle turn, and the last turn. Some of the primitives only make
sense for some agent types and are therefore only available in particular contexts.
In addition, two previously introduced concepts were extended: procedures and working with
truth values. Procedures are used to modularise the code and either instruct agents to perform
some task (command) or provide some information (reporter). The more advanced feature
introduced is the use of arguments, inputs that the procedure can use for more exibility. The
tutorial model used this capacity to construct a procedure that provides random numbers from
a triangular distribution with the limits and mode of that distribution passed as arguments.
This potential for arguments emphasises the equivalence between user written procedures and
the primitives built in to the NetLogo language. Primitives are simply (eciently written)
procedures with arguments.
Truth values (that is true and false) are included in models in dierent ways. They are used as
status ags, such as the variable `protect?'. They are also generated as the outcome of conditional
tests. Such tests are overt in the construction of ifelse and similar constructions, but are also
fundamental to agentsets constructed with the with lter. These truth values are their own type
of value. That is true is not the same as the text string "true", nor is it stored as a number
(such as 1) with a specic indicator on the variable type. Logical operators should be used to
work with truth values, in the same way that mathematical operators are the most appropriate
for numbers (or string operators for text).
Another programming practice built into the tutorial is interface design. The instructions provide
details of what widgets to include on the interface, and the screenshots display one option for
placement. What to include and where to place it are part of the model design. The model must
be accessible for users. Parameters that need to be adjusted should be available, but too many
widgets adds to the clutter and makes it dicult to nd the correct one. The world displays
the current status of the model, but colours and other features can be used to emphasise or
hide particular aspects of that status. Finally, plots and other output should be focused on the
information needs of the user.
This does not mean, however, that the interface cannot include widgets for the convenience of
the model developer, they should just be removed from the released version of the model. In
fact, it can be very useful to have an area of the interface devoted to diagnostic information to
make sure that changes do not introduce errors in already tested code. The attitude distribution
plot and maximum population monitors are both examples of such diagnostic widgets.
5
Model 4: Representing Relationships
While version 3 of the model is a complete agent-based model, it does not fully implement the
original design. In particular, section 1.8 states that people communicate with their friends about
threat. This element is to be added in version 4.
Friendships and other relationships between entities are represented mathematically with net-
works, comprised of nodes for entities and edges for relationships Newman (2010). Nodes can
represent people or rms or countries or many other real world entities. Relationships are equally
broad, such as friendship or shared board membership or international trade. In NetLogo, net-
work nodes are turtle agents and links are used for edges.
Links are a new type of NetLogo model object (referred to as types of agents in the ocial
documentation). The four objects are observer, turtle, patch and link. The observer is external
to the model, patches are used to represent space, turtles to represent agents (as meant in this
tutorial), and links to represent relationships between pairs of turtle agents.
Much of the apparatus that you have already been using for patches and turtles is easily adapted
to links. Some primitives work in exactly the same way, including ask and set. Others have
equivalents, for example link-neighbors creates the agentset of turtles at the other end of
the links connected to the asking turtle(s), which is the link version of the spatial neighbors.
Therefore, while there are many primitives introduced in this chapter, they are mostly related
to previously seen primitives rather than new programming concepts.
Like turtles, dierent breeds can be dened for links. Each breed has variables, dened with a
links-own statement (or its breed equivalent). These variables store attributes of the relation-
ship, not attributes of the turtles that are related. For example, if the relationship represented
by the link is friendship, then an appropriate variable would be the number of times per month
that the two simulated people contact each other.
81
82 CHAPTER 5. MODEL 4: REPRESENTING RELATIONSHIPS
perceives a high threat level, that heightened threat is communicated to all their friends and the
friends adjust their perceived threat accordingly.
to make-network
ask people
[ let needed num-friends - count my-links
if needed > 0
[ let candidates other people with [ count my-links <
num-friends]
create-links-with n-of min (list needed count candidates)
candidates
[ hide-link]
]
]
end
The primitive my-links is the agentset of links connected to the specic turtle. For the rst
person, the count of this agentset is 0, so the local variable `needed' is set to the value of the
num-friends slider. For later people, some links may already have been created and needed is
accordingly lower. If any links need to be created for that person, the code block to create links
is run.
my-links
The agentset of links connected to a specic turtle is generated with the my-links prim-
itive. See also link-neighbors, which is the agentset of turtles at the other end of those
links.
That code block selects all the people who still have capacity for further links, and excludes
the person looking for friends (with the other primitive), assigning that agentset of people to
the variable named candidates. But what if there's not enough people available to connect to?
NetLogo will report an error if it tries to select too many agents (for example, if you are asking
for 5 random turtles from a set with only 3). So the value for the n-of is the minimum of the
number to be selected and the number available.
other
The primitive other excludes the model entity (turtle, patch, link) from the agentset
being selected, even though it satises the conditions for inclusion.
5.3. USING LINKS 83
But the min primitive takes the minimum of a list. The tutorial has previously used max to
nd the maximum popn value. In that case, a list was automatically created by the of reporter
requesting the values of a variable from all patches. Here, however, the list must be explicitly
created with the values that are to be its items. For example, (list 1 2 3) would create a list
of three items, the numbers 1, 2 and 3.
The smaller of the number of links needed and the number of available turtles to link to is
passed to the n-of. That number of people are randomly selected from the agentset stored by
the variable candidates to generate an unnamed agentset.
The primitive create-links-with instructs the person to create an undirected link with each
of the people in the unnamed agentset. Like the turtle creation commands discussed in section
2.8, the following code block is run for each link as it is created. In this snippet, that code block
hides the link so it is not shown in the world (or available in the popup menu).
create-links-with
The full syntax is create-links-with <agentset> [ ]. Instructs a turtle to create
an undirected link with every turtle in the specied agentset. Any code within the
square brackets is run for each link as it is created. See also create-links-from and
create-links-to for directed link versions. Similar primitives are also available that
specify the breed of the links to be created.
Since the links are hidden, they are not available for the
popup menu. Instead, type inspect one-of links into the
Command Center to open the inspect window for a random
link. You can see the built in variables for a link. A specic
link is identied by the who numbers of the two turtles it
joins (top left corner of inspect window).
Finding the person agentset and the linkset to be the same size is not a conclusive test because
links created at random will still give rise to the correct number of links. What you want to check
is that all people have exactly two friends (or equivalently, exactly two links), with the possible
exception of the failed self link attempts. One possibility is a histogram of count [my-links]
of people. But it is easier to simply nd the maximum of the number of links. If the maximum
is 2, then all people must have two friends. The appropriate code is max [count my-links]
of people.
84 CHAPTER 5. MODEL 4: REPRESENTING RELATIONSHIPS
hide-link
The command hide-link makes a link invisible in the world view. It is reversed with
show-link. See also hide-turtle and show-turtle.
to decide-behaviour
...
ask people
[ let friend-threat ifelse-value any? link-neighbors ∠∠
[ max [threat] of link-neighbors ] ∠∠
[ 0 ] ∠∠
let mythreat max (list max-threat friend-threat) ∠∠
let decision-value wt-attitude * attitude + wt-norms *
prop-protect + (1 - wt-attitude - wt-norms) * mythreat ∠∠
ifelse reversible?
...
]
end
link-neigbors
link-neighbors is the agentset of turtles at the other end of the links connected to
the specied turtle. See also my-links, which is the agentset of links representing those
connections.
The user may set number of friends to 0. NetLogo will fail if it is instructed to run code on
an empty agentset. Therefore the calculation of the maximum of the friends' threat values is
preceded by a test as to whether there are friends to calculate over. If not, the friends' threat
value is set to 0. This protection also deals with the case where a non-zero number of friends is
selected but there are no potential friends available for the nal person to have edges created.
This snippet also uses the explicit list constructor. Applying of to an agentset creates a list
of the variable values so that the maximum of the threat values of friends can be calculated.
5.3. USING LINKS 85
any?
any? is a logical operator that reports true if the specied agentset has at least one
member, and false if is empty.
The explicit list is used to create a list with two members, that maximum and the previously
calculated maximum threat from the directly observed patches. Once these two values have been
placed in a list, the max operator can choose the larger to be the relevant perceived threat. The
snippet requires only minor amendments to the previous code because the revised maximum is
inserted into the behaviour decision by simply replacing the maximum from only the observed
patches.
list
The full syntax is (list <item0> <item1> <item2> ...) to create a list with the items
specied as its contents, in the order specied. List member items can be numbers, text
strings, other lists, agentsets, or some combination of these data types.
There is no obvious way to test this code as the threat combining the sources is stored only
as a local variable and therefore cannot be queried while the model is stopped. However, there
are primitives that print information to the Command Center and these can be used to report
relevant values at specic points in the code. Such primitives are commonly used to construct a
basic test.
Save the model so that you can revert to the saved version after testing. Make the changes at
Figure 5.2 but do not save the model. This code modies the decide-behaviour procedure to
provide information about variable contents. The primitives type and print are used to report
the (labelled) threat inputs and then the threat value used. There are also equivalent commands
to send information to an output widget on the interface or to a le. Note that the ask people
has been modied to ask n-of 10 people to limit the amount of information sent each tick.
Press the setup button and type go into the Command Center (to run the go procedure once
only). Remember (from section 3.3.1) that you can expand and collapse the reporting area with
the double ended arrow in the top right corner of the Command Center. As only 10 people are
being queried, you may need to enter go more than once to nd a person whose friends have
higher threat values and therefore see a change in the person's threat value. Once you have
checked the code, close the model without saving (assuming you haven't saved these changes) or
reverse the edits.
print, type
print and type both instruct NetLogo to provide information to the Command Centre.
The dierence is that type sends only the information asked, while print sends the
information and ends the line. See also show and write, which also send information to
the Command Centre but additionally includes the identier for the model entity.
to decide-behaviour
ask patches
[ ...
]
ask n-of 10 people
[ ...
[ 0 ]
type "patch threat is: " print max-threat
type "friend threat is: " print friend-threat
let mythreat max (list max-threat friend-threat)
type "threat is: " print mythreat
let decision-value...
]
end
Figure 5.2: Modications to use output printed to the Command Center to conrm code is implemented
correctly.
the maximum proportion protected achieved during the run and when that maximum is (rst
achieved). Each time step it calculates the current proportion of people with protective be-
haviour. If that value is higher than the stored maximum, that maximum is replaced and the
current time is also stored.
Note that there is a complication arising from the eect of that protective behaviour; with the
epidemic restricted, threat is lower, confounding the eect of the friends. To avoid this, any
simulations to test the hypothesis should be run with ecacy set to zero.
to update-globals
let protected count people with [protect?] / count people
if protected > max-protect
[ set max-protect protected
set when-max-protect ticks
]
end
This snippet demonstrates the use of ticks to obtain the current time during the simulation
(as compared to tick to advance the tick counter). Each tick, the current value of protected
proportion is compared to the stored maximum already achieved. If the new value is higher,
both the maximum and the time at which that maximum is achieved are updated.
ticks
ticks queries the tick counter and reports the current time.
Once implemented, this snippet completes version 4 of the model, displayed at Figure 5.3. No
5.4. TUTORIAL PROGRESS CHECK 87
explicit test is required for this code, because it is easy to check whether the new monitors are
correct by comparing their reported values with the plot of proportion protected. Note that
hovering over the plot (placing the mouse pointer near the line) will reveal the plotted values.
Figure 5.3: Screenshot of the interface after completing version 4c of the model. Note that the values
in the two monitors concerning protective behaviour coincide with the peak in the protective behaviour
plot.
6
Models 5-8: Enhancements
The core NetLogo concepts and language have been presented in model versions 1 to 4. Version 1
established the model entities to represent agents and space: turtles and patches. Version 2 intro-
duced time and space, and implemented the process of epidemic spread in the patches. Version
3 implemented the process of adopting and dropping protective behaviour, relying extensively
on the key concept of agentsets. Finally, version 4 introduced links to represent relationships.
There are many other NetLogo primitives that will not be covered. The majority of these are
specialised and used very rarely. However, there are two topics that are essential for many
models. Any model that includes mobile agents will require primitives that turn, move, look
ahead and similar actions (see Chapter 8). Lists have been introduced, but their true power is
unexplored. They are required where sequence is important, such as remembering only the most
recent interactions. There are also specialised sets of primitives that are not part of the core
language but are instead added with extensions, including primitives to deal with geographic
information or networks. Lists and extensions are not covered in this tutorial.
The rest of the main tutorial enhances the existing model. Each enhancement is independent.
They are intended to stimulate ideas for what can be done with models rather than demonstrate
features of the language. While new primitives are used, they are not formally discussed. Instead,
you should look them up in the NetLogo dictionary.
89
90 CHAPTER 6. MODELS 5-8: ENHANCEMENTS
to make-network
let lonely people
ask people
[ set lonely other lonely
let needed round num-friends - count my-links
if needed > 0
[ let targets n-of min (list needed count lonely) lonely
create-links-with targets [ hide-link]
ask targets [ if count my-links = num-friends [ set lonely
other lonely ] ]
]
]
end
With these snippets implemented, a small black X will be displayed in those patches where the
protected proportion of the people is at least the level set by the slider. As many patches have
only 2 or 3 people, a useful level is 0.75 so that a single high attitude person does not trigger the
visualisation. You should expect to see a higher density of marked patches near the epidemic
frontier, where threat is highest, particularly if the number of friends is set to 0 so that only
local threat is perceived.
to make-barriers
ask patches
[ sprout-barriers 1
[ set shape "x"
set size 0.7
set color black
hide-turtle
]
]
end
to colour-barriers
ask barriers
[ if-else count people-here with [protect?] / count people-here
>= show-protect
[show-turtle]
[hide-turtle]
]
end
is for eciency. The patchsets never change so can be created once during setup and stored,
which is quicker than the previous approach of creating it each time step. This improvement is
particularly important when calculating the patches in range with in-radius, a relatively slow
operation.
to setup-patches
...
ask patches
[ ...
set visible patches in-radius see-distance
]
...
end
perceived threat if a friend becomes infected. This does not require changing the transmission
representation. Instead, the local incidence can be used to trigger simulated people becoming
infected.
The basic approach is to allow susceptible people on a patch to become infected with probability
given by the incidence on that patch (as a proportion of the susceptible population). However,
people who have adopted protective behaviour should derive benet from that behaviour, so the
probabilities must be adjusted to average at the appropriate proportion but also recognise the
ecacy of protective behaviour. Once a person has become infected, the probability to recover
is the same as used for the patch based epidemic.
If E is the ecacy of the protective behaviour, Pr the protected proportion of people, and q the
susceptible fraction becoming infected, the probability of a susceptible person becoming infected
is given by:
q Pr = 0, Pr = 1
1
q unprotected
P = 1 − Pr E
q 1 − E
protected
1 − Pr E
As the infection probability depends on the proportion of susceptible becoming infected in that
time step, the new procedures to infect people must be called after the spread-epidemic proce-
dure. Snippet 8 (page 93) implements infection and recovery, as well as monitors to report the
proportion infected by protective behaviour status.
The only new primitive introduced is all?. The equation to be implemented is expressed with
one of the cases arising for proportion protected of 1. However, it is bad practice to test whether
two calculated numbers are equal as they may dier slightly at the limits of precision. The
snippet instead checks whether all people on the patch are protected directly instead of checking
whether the proportion protected equals 1.
This snippet also demonstrates turtles accessing patch variables. The susceptibles agentset has
turtle members, so the ask shifts NetLogo into the turtle context. Nevertheless, patch variables
such as `incidence' are used directly, there is no need for a construction such as [incidence]
of patch-here. This capacity for turtles to access the variables owned by the patch where they
are located is built into the architecture of NetLogo.
6.4. MODEL 8: INFECTING INDIVIDUALS 93
to epidemic-people
; infected to recovered
let infecteds people with [state = "I"]
if any? infecteds
[ ask infecteds
[ if random-float 1 < (1 / recovery-period) [ set state "R" ]
]
]
; susceptible to infected
let susceptibles people with [state = "S"]
if any? susceptibles
[ ask susceptibles
[ let protect-here count people-here with [protect?] / count
people-here
let infect-here incidence / (incidence + popn-S)
ifelse all? people-here [protect?]
[ if random-float 1 < infect-here [ set state "I" ] ]
[ let prob ifelse-value protect?
[ infect-here * (1 - efficacy) / (1 - protect-here *
efficacy) ]
[ infect-here / (1 - protect-here * efficacy) ]
if random-float 1 < prob [ set state "I" ]
]
]
]
end
The monitors demonstrate the counterintuitive results that arise in complex system behaviour.
A naive approach would expect that the proportion of protected people becoming infected would
be lower than the proportion of unprotected people becoming infected, potentially by a factor
equivalent to the ecacy of the protective behaviour. With further reection, however, it is
apparent people near the epidemic front are more likely to have adopted protective behaviour
and also have greater exposure to the epidemic. Therefore, it is possible that incidence is actually
higher in the protected population, making it appear that the protective behaviour increases the
risk of becoming infected. Agent-based models can be used to understand such counterintuitive
results (Barbrook-Johnson et al., 2017).
The tutorial model is now complete. The nal version is displayed at Figure 6.1. Note that the
94 CHAPTER 6. MODELS 5-8: ENHANCEMENTS
widgets have been organised into related groups. The group headings are Note widgets.
Figure 6.1: Screenshot of the interface after completing version 8 of the model. Markers indicate
patches where at least 75% of the simulated people are protected.
7
Bringing it all Together
The main tutorial is now complete. This chapter summarises some of the key ideas presented and
points to further materials to improve your understanding of agent-based modelling and NetLogo.
It also brings together related ideas that are spread throughout the tutorial. The structure of
the tutorial, gradually building a model from start to nish, means that concepts are introduced
in the order that they are needed. This chapter, however, is structured thematically, linking
together pieces of information that may have been presented far apart.
There are three key skills needed to build an agent-based model. You need to be able to design
the model, to understand and describe the entities and behaviour to be represented. You need
to use good programming practices to implement the model, so that the model runs quickly
and accurately implements the design. Finally, you need to be familiar with the programming
language, in this case NetLogo, to translate the intent into instructions. The rst two of these
skills are required even if you are not personally writing the code, they are necessary to facilitate
communication with the programmer.
95
96 CHAPTER 7. BRINGING IT ALL TOGETHER
Some potential questions to stimulate a model design are listed at Table 7.1, together with how
they apply to the tutorial model. Many other considerations may also be relevant, but these
should be sucient to start any consideration or discussion.
This list of questions identies the key features of the model but signicant eort is needed to
create a full model design. In the tutorial, the design and operationalisation was presented as the
model was constructed, together with the NetLogo implementation of that operationalisation.
In a real project, a relatively detailed design should be specied before any coding. It is not
sucient to specify what is to be included in the model, but also how it is to be included. For
example, follow up questions could include:
• for agent attributes and spatial resources, what information is available about how the
attributes are distributed?
• for interactions, what is the specic rule or equation that governs the inuence and what
information and parameters are required to determine the outcome of that rule?
These questions focus on the process that is to be represented by the model. One important
element in model design is distinguishing between the intialisation and the actual simulation. A
model starts at a specic point in time, so the initialisation represents a static view of the world
7.2. GOOD PRACTICE IN PROGRAMMING 97
(as if time had been paused). Typical tasks in the initialisation include creating the agents and
allocating appropriate variable values. These are conceptually dierent than the simulation of
the process as time progresses.
The model design is agnostic with respect to the particular software in which the model is to be
implemented. That is, it should be expressed with an agent-centric representation and relevant
rules, but not with NetLogo keywords. One way to approach this is to imagine yourself as
the agent (each type separately) taking action and think about the choices facing you and the
information you require to decide an action. This consideration should be based on theory and
data, including narratives and other qualitative information. The goal of the thought experiment
is to encourage the agent-centric perspective required for the model specication instead of the
perspective of an observer.
Other aspects of the design concern the interface. The input widgets should allow the user
to control the primary features of dierent scenarios related to the research question. Outputs
provide the user with information that is relevant to the research question, but also communicate
what is occurring within the simulation.
Finally, the design should also consider broader aspects of how the model is to be used. This
includes the resolution and accuracy required to answer the research question, how to check
whether the model meets the accuracy requirements, and what experiments are to be conducted.
These issues are outside the scope of the tutorial, but are covered in other chapters.
Modularisation is common to many programming languages. Each block of code has a specic
task, and can call other blocks of code in a nested structure. In NetLogo, the blocks of code
are referred to as procedures, and are delimited with to and end or with to-report and end.
By convention, the main procedures are given the names `setup' and `go'. These are (usually)
triggered by a button, and the code section of the button settings simply calls the relevant main
procedure. Each procedure is comprised of calls to other procedures or primitives from the
NetLogo language. There is little conceptual dierence between a procedure and a primitive;
they are simply names for a set of computer instructions, but some are written by the NetLogo
developers and built into the language (primitives) while the others are written by the model
developer (primitives). Both procedures and primitives are able to use arguments as inputs.
Those arguments form the syntax that NetLogo expects when the procedure or primitive is
called in the model code.
Finally, good algorithm design is important in making the model ecient, so that it runs as
quickly as possible. This becomes critical as the number of agents increases. Using the model
will involve multiple simulations, and any delay in a single run has a substantial impact on the
model's long term usefulness.
patches-own [test?]
to testme
ask patches [set test? one-of [true false]]
ask patches
[ ifelse test?
[ set pcolor red ]
[ set pcolor blue ]
]
end
patches-own [test?]
to testme
ask patches [set test? one-of [true false]]
ask patches with [test?] [ set pcolor red ]
ask patches with [not test?] [ set pcolor blue ]
end
Figure 7.1: Each of these code snippets are complete models that set the colour of patches to red or
blue based on a randomly allocated patch variable. These demonstrate the two approaches to conditional
code with agentsets, testing each agent (ifelse within ask, upper) and selecting relevant agents in the
agentset construction (with, lower).
Link
Turtle
Patch
Figure 7.2: The three types of model entities available in NetLogo; patches for space, turtles for
individuals, and links for relationships between individuals.
There are multiple variables with the same name, each assigned to a particular model entity.
An entity is able to access its own variables automatically, and turtles can access the variables
belonging to the patch where it is located. Accessing a dierent entity's variables requires the
100 CHAPTER 7. BRINGING IT ALL TOGETHER
of reporter, to specify which entity's variable is to be accessed. Finally, local variables are
temporary storage that exist only within the code block in which they are created. They are
used, for example, to store the results of a short piece of code to make the model more ecient
by avoiding repeating that code or to make the model code more readable to humans. Local
variables are created with a let statement and the values of all types of variables are updated
with a set statement.
Interaction is an essential element of agent-based modelling, so any modelling platform must
allow agents to perceive characteristics of other agents. In turn, this requires a concept of `me'
and `them', as well as the capacity to access the variable values of other agents. In NetLogo,
self refers to the agent currently in focus, the one to which the instruction is being applied. In
contrast, myself refers to the agent issuing the instruction. The other key primitive in bridging
the agent perception gap is of, which is used to specify the information that is known to some
agent (or agentset) and is to be perceived by the instructing agent.
One of the reasons that NetLogo requires only a small language to implement agent-based models
is that many required features are built into the modelling environment, rather than requiring
explicit coding. These automatic features include time, space, and the mutual awareness of the
code and the interface widgets.
Time is managed by an internal time step counter. That counter is initialised with reset-ticks
(typically the nal command in the setup procedure) and advanced with tick (typically the nal
command in the go procedure). The tick counter can be observed by any model entity with the
ticks reporter.
Space is dealt with extensively in Chapter 8, as the coordinate system and related concepts such
as heading are more salient in models where turtles move. The key spatial concept in the tutorial
is neighbors, the agentset of patches surrounding the patch or turtle in focus. The in-radius
primitive extends this spatial neighbourhood further out.
A complete list of NetLogo keywords used in the book appears as a separate index. The following
list is the most important keywords that are used in the tutorial, which should become very
familiar for any NetLogo modeller:
• procedures: to to-report end
• creating entities: breed sprout
• variables: globals patches-own turtles-own let set
• agentsets: ask n-of max-n-of with
• time and space: tick neighbors
• interaction: myself of
• mathematical and logical operators
The next step is to design and construct your own model. During coding, try and follow the
sequencing of the tutorial. Create the agents and their physical world before trying to code the
interactions and behaviour. Remember to make the behaviour as simple as possible and then
amend it once the simple behaviour works correctly.
At this point, you can start working with some more advanced resources. Many of these are
listed at the NetLogo website. You should also dip into the remaining chapters of this book. The
most appropriate order will depend on your modelling project and your background.
There are two books that I would recommend to any agent-based modeller. Despite its name,
Agent-Based and Individual-Based Modeling: A Practical Introduction by Railsback and Grimm
(2011) is thorough and rigorous and comprehensively covers a range of important topics. While it
can be dicult for a complete novice, it uses NetLogo to build the example models and should be
accessible after completing this tutorial. A more theoretical perspective is taken in Agent-Based
Models by Gilbert (2008). If there is a strong spatial element to your model or you are intending
to work with GIS data, you are likely to nd Agent-Based Modelling & Geographical Information
Systems (Crooks et al., 2018) particularly useful.
A further two books are particularly good for stimulating ideas about what model to build: Mod-
eling Behavior in Complex Health Systems by Keane (2013), and An Introduction to Agent-Based
Modeling: Modeling natural, social and engineered complex systems with NetLogo by Wilensky
and Rand (2015). Both use NetLogo extensively and also have downloadable models available.
Finally, there are several resources that take a dierent approach, focusing on the NetLogo
language itself and how it is structured. The NetLogo Dictionary and the Programming Guide
are included in the NetLogo User Manual (online, linked from the Help menu). Once you are
reasonably comfortable with NetLogo, it is very useful to browse through the dictionary and to
read the Guide thoroughly. These resources will help you become aware of some of the other
primitives and gain a deeper understanding of how to think in NetLogo. This, more formal,
programming language approach is also take in NetLogo: A Modeling Tool by Garcia Vázquez
and Sancho Caparrini (2016).
102 CHAPTER 7. BRINGING IT ALL TOGETHER
CHAPTER
8
Turtles on the Move
An important part of many agent-based models is the mobility of turtle agents. For example,
livestock must move around grazing areas in land use models, cars or pedestrians must follow
routes and interact with each other in trac models, and random movement can be used to
control interactions for economic or social transactions. This chapter uses a mix of a small
tutorial model to introduce the main NetLogo concepts and primitives for mobile turtles and
examples drawn from the Library Models to demonstrate how to achieve some more advanced
model features.
103
104 CHAPTER 8. TURTLES ON THE MOVE
Table 8.1: Applying the broad design questions to the chasing game.
;--------------------------------------------------
; MAIN CONTROL PROCEDURES
;--------------------------------------------------
to setup
clear-all
reset-ticks
end
to go
tick
end
created without any content. The tutorial model approach is clearer because clear-all is added
when model entities are created, and reset-ticks and tick when time is introduced, so there is
a connection between the new code and the process being implemented. However, adding these
standard commands at the start of a new model can be a good habit.
The code can be tested by pressing the setup button and then either the step or go button. The
tick counter should advance. It's not a complete test as the clear-all could be missing without
aecting the model.
The next step is to create the physical environment. However, in the simple version of the
behaviour, without obstacles, there is nothing to create. The nal initialisation step is to create
players, but that rst requires an understanding of how NetLogo implements location.
8.2 Co-ordinates
The co-ordinate system within NetLogo was introduced at section 3.9. All locations are specied
with two co-ordinates (NetLogo 3D is outside the scope of this book) in the common cartesian
arrangement of an x-axis with values that increase to the right and a y -axis that increases
upwards. The intersection of these axes is referred to as the origin. Locations to the left or
below the origin have negative values for their x and y co-ordinates respectively.
Each turtle agent is located at some point in this two dimensional space. The co-ordinates
are stored in the variables xcor and ycor (x and y axes respectively), which are automatically
created for each turtle. These co-ordinates change as the turtle agent moves (for example, by
moving forward some amount). Similarly, setting these variables to specic values moves the
turtle agent to the specied location.
Each patch occupies one unit square in the two dimensional space, centred on integer values of
the co-ordinates. The patch boundaries are included in the patch on the left and bottom, and
are excluded at the top and right (see Figure 8.1). The patch co-ordinates are stored in the
106 CHAPTER 8. TURTLES ON THE MOVE
variables pxcor and pycor (x and y axes respectively). As patches do not move, these variables
can be accessed but not set. Those values are also used to identify patches, so patch 0 0 is the
patch centred on the origin.
y
4
3 Patch 2 2
(1.5, 2.5) (2.5, 1.5)
2
(1.5, 1.5) (2.5, 1.5)
1
0
−2 −1 0 1 2 3 4 x
−1
−2
Figure 8.1: Overlay of patches with the co-ordinates. The limits of the patch with pxcor of 2 and
pycor of 2 are displayed. Note that the solid lines at the bottom and left indicate that these co-ordinates
are within the patch (eg xcor = 1.5, ycor = 1.5) and the dashed line at the top and right indicate that
these are within the neighbouring patch (eg xcor = 2.5, ycor = 2.5).
Model settings (see Figure 2.1) control the number of patches in the World and the location of the
origin. The only requirement is that patch 0 0 is somewhere within the World. These settings
also control wrapping, whether the edges of the World are borders that cannot be traversed, or
whether turtles simply pass through the edge of the World and re-enter at the opposing edge.
At this point, the rst new primitives are required. The main tutorial model had each patch
sprout the turtle agents, creating the appropriate number of people in the centre of each patch.
For this model, the observer will create the turtle agents with create-turtles.
They will be randomly located throughout the world using setxy, which species the x and y
co-ordinates, and those co-ordinates are randomly selected with random-xcor and random-ycor.
Turtle agents have several built-in variables that are created automatically with the turtle. As
well as the variables for the co-ordinates (xcor and ycor), turtles have a color and size. As for
sprout, the code contained in the square brackets that is part of the create-turtles command
is run for each turtle as it is created. That code is used to set the in-built variables.
Note that the targets are not assigned until all players have been created. If you tried to
assign as each player is created, there would be two problems. The rst player would have no
potential targets, which would generate an error. Also, players created earlier would have more
opportunities to be selected as a target and therefore introduce a bias into the model.
Press the setup button to initialise the game. Open an inspect window for a player and check
that it has a target to chase and that the speed is some value up to the maximum speed on the
slider.
8.3. DIRECTION 107
;--------------------------------------------------
to setup-players
create-players num-players
[ setxy random-xcor random-ycor
set color blue
set size 1.5
set speed random-float max-speed
]
ask players
[ set target one-of other players
]
end
setxy
setxy <desired-x-co-ordinate> <desired-y-co-ordinate> sets the location of a tur-
tle by specifying the co-ordinates. It is a single primitive version of separately setting the
co-ordinates with a combination of set xcor <desired-x-co-ordinate> and set ycor
<desired-y-co-ordinate>. See also turtle built-in variables xcor and ycor.
8.3 Direction
Look at the model after running the setup procedure, each player (blue dart shape) is pointing
in some direction. This direction is stored in a built-in variable named `heading', which is the
number of degrees clockwise from pointing upwards.
In exactly the same way as other variables, a turtle's heading can be set to a specic number,
such as 90 to point to the right. But there are other ways to control direction, such as turning
right or left by a specic amount, or facing a model entity or specied co-ordinates. For
example, open an inspect window for one of the players and enter right 90 into the code area
at the bottom of the window, the value of the heading variable will increase by 90 and the player
will turn.
Note that the naming of these commands reects the agent-centric perspective of NetLogo and
agent-based modelling. Turning right or left is unambiguous from your own perspective. How-
ever, if somebody else asks you to turn right, the question then arises as to `whose right' to
turn. The reason that headings can be described as clockwise from pointing upwards is that the
NetLogo World has a xed perspective to a model user, a turtle with heading of 0 points upward
108 CHAPTER 8. TURTLES ON THE MOVE
and there is no way to get behind the computer screen and see the co-ordinate system from the
other side.
What happens if heading is increased to more than 360 or decreased to less than 0? The value
simply adjusts to the equivalent within that range by adding or subtracting 360 as required (that
is, heading is technically heading modulo 360).
to go
ask players
[ choose-direction
]
tick
end
;--------------------------------------------------
to choose-direction
set color blue
let targetme (players in-radius warning) with [target = myself]
ifelse any? targetme
[ set color red
face min-one-of targetme [ distance myself ]
set heading heading + 180
]
[ face target
]
end
The player rst checks whether there is any nearby player chasing them. If so, they face the
closest chaser and then add 180 to their heading, which faces them in the opposite direction. If
there is no close chaser, they face their target.
face
The primitive face instructs the turtle agent to change its heading so that it is facing
the specied model entity, a patch or turtle agent. See also facexy.
As well as face, this code introduces the distance primitive, which reports the distance between
the asking turtle agent and some other agent (in the ocial NetLogo sense, so it may be a patch).
8.4. MOVEMENT 109
It is commonly used with min-one-of to nd the closest turtle agent or patch that meets some
requirement. In this case, it nds the closest of all the turtles targeting the asker.
distance
The distance primitive reports the distance to the specied turtle agent or (centre of)
patch. See also distancexy to nd the distance to a specic location referenced by x and
y co-ordinates.
Turtle context procedures were shown in Figure 4.1, but were not required in the main tutorial.
Here, the go procedure has ask players calling choose-direction, which is a turtle procedure.
That is, NetLogo is already taking the player's perspective when the code enters the choose-
direction procedure. The reason that this approach is used in this model is to ensure that each
player makes its full move before moving on to the next player.
Consider what would happen if the go procedure called an observer context procedure to choose
directions and then an observer context procedure to move (with ask players for each proce-
dure). Every ask iterates through the agents. If a player chooses its direction, and then one
of the chasers moves within the warning distance before the target has moved, then the target
player may move toward a close chaser.
The code can be tested by pressing the setup then step buttons. Each player will initially choose
a random direction, but then rotate to point to its target. You should see this rotation, and may
see a turtle change to red. Inspect a player to identify its target and then check players that it
is facing to verify that one of them is the target.
8.4 Movement
The most common primitive used in moving is forward (sometimes abbreviated to fd), which
instructs the turtle to move in whatever direction it is facing. The distance it moves is given
in units of the co-ordinate system. For example, if a turtle with a heading of 90 turtle located
at the origin (given by xcor of 0 and ycor of 0) was asked to forward 1, it would move to the
location with xcor of 1 and ycor of 0. If, however, the turtle has a diagonal heading, then one
unit of distance is not enough to cross the patch.
Other primitives allow a turtle to look at the patch they would move onto if they either moved
forward to the next patch or moved some arbitrary heading and distance. Turtles are also able
to move in a direction that increases or decreases the value of a specied variable.
to move
let intended-move min (list speed distance target)
forward intended-move
end
forward
The primitive forward instructs the turtle agent to move in the direction it is heading by
the specied distance. If the World boundaries do not wrap and the requested forward
movement would take the agent past the boundary, it stops on an edge patch. It is
sometimes seen in code in its abbreviated form, fd.
Figure 8.2: Screenshot after implementing movement with Snippet M4 (page 110). The game settles
into a pattern of some clusters of players and other players following each other around the World.
The chase never ends because nothing happens when a player catches its target. One resolution
is that the caught player is removed from the game. Any players who were targeting that player
then need to choose a new target, but only the player who caught it should be given credit for
the capture.
Consider what is required to implement this behaviour before amending the code, as described in
Snippet M5 (page 111). Basic output widgets are also included, you could optionally add plots
over time or histograms instead of simply reporting current counts and averages.
The critical line in this snippet is if distance target < 0.005 [ ]. If a chaser gets very close
to its target then the target is considered to be captured. This is an example of using a tolerance
to avoid subtle errors arising from precision limits in the way that computers represent numbers
8.5. ADDING OBSTACLES 111
to capture
if distance target < 0.005
[ let my-target target
ask target [die]
ask players with [target = my-target]
[ set target one-of other players
]
set caught caught + 1
set size size + 0.5
]
end
die
A turtle or link that is asked to die removes itself from the model.
Now what happens when you run the model? It still doesn't end but that's because the last
two players are targeting each other. Any time one player gets close enough to almost catch the
other, the warning triggers and they run away instead. While a pair of nal players is the most
common outcome, some simulations will end with 3 players in a chase and others will have two
pairs in separate chases.
In a real situation, you would need to consider how to determine whether the simulation has
nished so it stops. One option is to add a global variable for the number of players still playing.
At regular intervals (such as 100 ticks), that variable is checked against the current number of
players. If it's the same, then stop the simulation and, if not, replace the variable value. For the
tutorial, manual stopping is ne. In addition, adding obstacles may change the outcome because
it will be harder for the target to move away.
At this point the model can be considered a full agent-based model, even though it is very simple.
Players are individually represented and are `doing something' through time. Players interact
with each other and those interactions inuence the behaviour, by chasing and running away.
Even without obstacles, the physical environment has an inuence because it represents distance.
There are several heterogeneous aspects of the players; location, target and speed.
without an obstacle. Eventually such random choices combined with the target moving should
allow the chaser to move around the obstacle.
The next step is to create these obstacles in the physical environment. This can be implemented
with a boolean variable indicating whether or not a patch is an obstacle, and the obstacles should
be visible. The density of the obstacles is to be controlled by the user. These requirements are
implemented in Snippet M6 (page 112).
patches-own
[ obstacle?
]
;--------------------------------------------------
to setup-patches
ask patches
[ ifelse random-float 1 < prop-obstacles
[ set obstacle? true
set pcolor yellow
]
[ set obstacle? false
set pcolor white
]
]
end
This snippet introduces the conditional code structure of while. The code inside the square
brackets runs repeatedly until the condition returns false. Randomly placing the players runs
the risk of having them start on a patch that is actually an obstacle. The while loop continues
to move the player to a new random location until it is on a patch that is not an obstacle.
while
The full syntax is while [<condition>] [<instructions>]. The instructions are re-
peated until the condition fails. Note that this repetition is conceptually dierent from
the repetition arising from repeated calls to the go procedure, because the ticks clock does
not advance.
You can test this code by pressing the setup button and observing the location of players. No
player should start on an obstacle (yellow patch). Find a player that appears to be on patch and
open an inspect window to check its co-ordinates.
The nal step is to have the player avoid an obstacle. This is more dicult than it seems as turtle
agents cannot actually `see' if there's an obstacle somewhere along their intended path. There
are several potentially helpful NetLogo primitives available, of which patch-ahead is the most
promising. This looks at the patch that is ahead of the asking turtle (that is, in the direction of
the turtle's heading) some specied distance.
8.5. ADDING OBSTACLES 113
What distance should be checked? The rst option is to check the distance intended to be moved,
but an obstacle may have ended before that distance. Another option is to check integer points
of distance, such as 1, 2 and so on, because each patch occupies one unit square of space. While
attractive, this option may not detect a patch whose corner crosses the intended path if that
corner is smaller than one unit across. But the idea is sensible, the resolution just needs to
be ner than a full spatial unit. The ner the resolution, the smaller the corners that can be
detected. This is the approach that is implemented with Snippet M7 (page 113).
I Sight lines
There is no concept of perception along a line but NetLogo can be instructed to examine
specic points either as absolute positions (x and y co-ordinates) or as a relative position
from some anchoring location (heading and distance, or change in x and y co-ordinates).
Perceiving along a path must be done by iteratively checking individual points on that
path.
If the player detects an obstacle, it instead randomly selects a neighbouring patch that is not an
obstacle and moves onto (or toward) that patch. To avoid potential problems of there being an
obstacle beyond this safe neighbour, the moved distance is limited to 1.
to move
let intended-move min (list speed distance target)
forward intended-move
ifelse check-path? intended-move 0.1
[ forward intended-move ]
[ face one-of neighbors with [not obstacle?]
forward min (list 1 intended-move)
]
end
The check-path? procedure implements checking at multiple points. If you can't remember the
dierence between a command (to) and reporter (to-report) procedure, review section 3.8, and
look at section 4.3 for a reminder about the square brackets following the procedure name. The
way it checks is that it looks the full distance rst and then gradually checks closer. As soon as
an obstacle is found, the while code block exits and the potential path is rejected.
The model is now complete. The nal version is shown at Figure 8.3. You can test the obstacle
avoidance by increasing the obstacle density and using the step button to move forward one
114 CHAPTER 8. TURTLES ON THE MOVE
tick at a time. Look at a player that is moving toward an obstacle to check that it does not
pass through. Alternatively, add a monitor that counts the number of players on patches with
obstacles and check that it remains 0.
Figure 8.3: Screenshot after completing the chasing game model. Players (blue darts) avoid obstacles
(yellow patches) while chasing each other. Player size indicates the number of captured targets.
8.6 Comments
NetLogo has many features built in to support mobile turtle agents. The most fundamental of
these is the x and y co-ordinate system, which denes all locations.
A turtle's location is specied by its xcor and ycor, the co-ordinate values. A turtle occupies a
point only, regardless of the size of the icon used to display the turtle agent. Further, co-ordinates
are essentially continuous numbers, so the probability of two turtles being at the same location
is negligible unless one turtle is explicitly moved to the other turtle.
One consequence of this arrangement is that NetLogo does not have any built in method to
detect that two turtles are colliding, overlapping icons is not equivalent to occupying the same
location. If you wish to check for overlaps, you will need to write your own code to calculate the
co-ordinates of the edges of the two icons and check whether the edge of one icon is inside the
space occupied by the other icon.
A patch occupies a unit square of the co-ordinate space, spanning from a half smaller (inclusive)
to a half larger (exclusive) of the integer co-ordinate value. NetLogo understands the concept of
`here' to mean `on this patch'.
With a co-ordinate system in place, directions can be dened by reference to that co-ordinate
system. Headings in NetLogo are given by a number from 0 to 360 (using modulo arithmetic)
with 0 pointing directly up the world and 90 pointing to the right. Headings can be specied
explicitly using a number, or indirectly by asking a turtle to face a model entity or to change
its heading by some value.
Distances and motion are also dened by reference to the co-ordinate system. The distance
between two points is simply the dierence between the co-ordinates. Motion is simply changing
location by some distance.
8.6. COMMENTS 115
The NetLogo Models Library contains several models that you can examine to help consolidate the
concepts and primitives involved in mobile turtle agents. The Ants model was briey discussed in
section 1.7 as an example of agents interacting with their environment. You can now revisit the
model to understand how the interaction is implemented. This model is particularly interesting
because it uses the uphill primitive to instruct ant agents to move in the direction that increases
the value of the specied patch variable. As trac simulation is a common use of mobile agents,
you may also wish to examine the Trac Grid model in the library, which uses the co-ordinate
system and headings extensively to restrict cars to roads. Note that library models may use the
abbreviated form of NetLogo commands, such as fd for forward.
The library also contains Code Examples to demonstrate coding techniques to achieve particular
objectives. This includes an alternative approach to the line of sight problem. Instead of standing
at one point and checking at other points along the path, the library model hatches a turtle to
move forward gradually, checking the patch where it is located and then dying when it reached
the required distance.
116 CHAPTER 8. TURTLES ON THE MOVE
Bibliography
Abdou, M., L. Hamill, and N. Gilbert (2012). Designing and Building an Agent-Based Model,
pp. 141165. Dordrecht: Springer.
Aristotle (2011). Aristotle's Metaphysics. Green Lion Press. Translated by Joe Sachs.
Badham, J., S. Elsawah, J. H. Guillaume, S. H. Hamilton, R. J. Hunt, A. J. Jakeman, S. A.
Pierce, V. O. Snow, M. Babbar-Sebens, B. Fu, P. Gober, M. C. Hill, T. Iwanaga, D. P. Loucks,
W. S. Merritt, S. D. Peckham, A. K. Richmond, F. Zare, D. Ames, and G. Bammer (2019, jun).
Eective modeling for integrated water resource management: A guide to contextual practices
by phases and steps and future opportunities. Environmental Modelling & Software 116, 4056.
Barbrook-Johnson, P., J. Badham, and N. Gilbert (2017). Uses of Agent-Based Modeling for
Health Communication: the TELL ME Case Study. Health Communication 32 (8), 939944.
PMID: 27435821.
Bass, F. M. (1969, jan). A new product growth for model consumer durables. Management
Science 15 (5), 215227.
Crooks, A., N. Malleson, E. Manley, and A. Heppenstall (2018). Agent-Based Modelling and
Geographical Information Systems. SAGE Publications Ltd.
Diekmann, O. and J. A. P. Heesterbeek (2000). Mathematical Epidemiology of Infectious Dis-
eases: Model Building, Analysis and Interpretation. Wiley.
García Vázquez, J. C. and F. Sancho Caparrini (2016). NetLogo: a modeling tool.
Gilbert, N. (2008). Agent-Based Models. Quantitative Applications in the Social Sciences. Los
Angeles: Sage Publications.
Hammond, R. A. and R. Axelrod (2006, dec). The evolution of ethnocentrism. Journal of
Conict Resolution 50 (6), 926936.
Hegselmann, R. (2017). Thomas C. Schelling and James M. Sakoda: The intellectual, technical,
and social history of a model. Journal of Articial Societies and Social Simulation 20 (3).
Keane, C. (2013).Modeling Behavior in Complex Public Health Systems: Simulation and Games
for Action and Evaluation. Springer.
Kermack, W. O. and A. G. McKendrick (1927). A contribution to the mathematical theory of
epidemics - i. Proceedings of the Royal Society A: Mathematical, Physical and Engineering
Sciences 115A(772), 700721.
Knuth, D. E. (1984, feb). Literate programming. The Computer Journal 27 (2), 97111.
Lotka, A. J. (1925). Elements of Physical Biology. Baltimore, MD: Williams & Wilkins Co.
Luke, D. A. and K. A. Stamatakis (2012, April). Systems science methods in public health:
Dynamics, networks, and agents. Annual Review of Public Health 33 (1), 357376.
117
118 BIBLIOGRAPHY
Macal, C. M. and M. J. North (2010, sep). Tutorial on agent-based modelling and simulation.
Journal of Simulation 4 (3), 151162.
Miller, J. H. and S. E. Page (2007). Complex Adaptive Systems. University Press Group Ltd.
Newman, M. (2010). Networks: an introduction. Oxford University Press.
Railsback, S. F. and V. Grimm (2011). Agent-based and Individual-based Modeling: A Practical
Introduction. New Jersey: Princeton University Press.
Rogers, E. M. (2003). Diusion of Innovations (5th ed.). Simon & Schuster.
Sakoda, J. M. (1971, jan). The checkerboard model of social interaction. The Journal of Math-
ematical Sociology 1 (1), 119132.
Schelling, T. C. (1971, jul). Dynamic models of segregation. The Journal of Mathematical
Sociology 1 (2), 143186.
Smith, J. M. (1964). Group selection and kin selection. Nature 201 (4924), 1145.
Volterra, V. (1926). Variazioni e uttuazioni del numero d'individui in specie animali conviventi.
Memoria della Reale Accademia Nazionale dei Lincei 2, 31113.
Weaver, W. (1948). Science and Complexity. American Scientist 36, 536544.
Wilensky, U. (1999). NetLogo http://ccl.northwestern.edu/netlogo/. Technical report, Center
for Connected Learning and Computer-Based Modeling, Northwestern University, Evanston,
IL.
Wilensky, U. and W. Rand (2015). An Introduction to Agent-Based Modeling: Modeling natural,
social and engineered complex systems with NetLogo. Cambridge, MA: MIT Press.
NetLogo Keywords
List of all the NetLogo commands, reporters and other keywords presented in this book. See
the NetLogo Dictionary for all available keywords, their denitions and short examples. Some
keywords also have short versions, but such abbreviations are not used in the tutorial. The full
words are easier to read and more natural to remember.
119
120 NETLOGO KEYWORDS
Index
debug patches, 19
context menu, 37 pop-up menu, see context menu
inspect, 34 position, see co-ordinates
sanity check, 2729, 35, 38, 47, 49, 55, precedence, 31
68, 69, 73, 83, 85 primitive, see keyword
syntax, 23, 24 probability, 70
design, 78 procedure, 21, 55, 69
call, 23, 28
epidemic, 11, 16, 43
SIR, see epidemic
false, see logic
oating-point, 111 time, 51
forever, 23 true, see logic
turtles, 31
initialise, 22, 32 attributes, 32
interface, 73 creating, 32
121
122 INDEX
note, 94 slider, 52
output, 85 switch, 74
plot, 61 World, 34
position, 62