Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

MASTER OF BUSINESS ANALYTICS

BA 3003 – Computational Social Science

8 – NetLogo Programming

Ruvan Weerasinghe
<arw@ucsc.cmb.ac.lk>

UNIVERSITY OF COLOMBO SCHOOL OF COMPUTING


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 2


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 3


Agents
• The NetLogo world is made up of agents
• Agents are beings that can follow instructions
• Four types of agents
• turtles, patches, links, and the observer
• Turtles are agents that move around in the world:
• i.e. a two dimensional grid of patches
• Links are agents that connect two turtles or patches
• The observer can look over the whole world
• can also give instructions to other agents (not just observe!)

Master of Business Analytics 26 September 2020 4


Agents (contd.)
• When NetLogo starts up, there are no turtles
• The observer can make new turtles
• Patches can also make new turtles
• Though they can’t move, they’re just as ‘alive’ as turtles
• They have coordinates pxcor and pycor
• The total number of patches is determined by min-pxcor, max-
pxcor, min-pycor and max-pycor (-16, 16, -16, 16 by default)
• i.e. 33x33 or 1089 patches in total
• Turtles also have coordinates xcor and ycor – but they can be
decimals – i.e. not necessarily at the center of the patch they’re on
• Links do not have coordinates but have two ends – if a turtle at
either end dies, the link dies too

Master of Business Analytics 26 September 2020 5


Agentsets
• This is a set of agents
• Of only one type: turtles, patches or links
• It has no order (as they are sets!)
• Each time it is used, it is in a different random order!
• turtles, patches and links are primitive agentsets!
• We can define subsets of these for solving problems
• e.g. all the red turtles, or the patches with pxcor evenly divisible by
five, or the turtles in the first quadrant that are on a green patch or the
links connected to turtle 0
• Using turtles-here, turtles-at or turtles-on to get the
set of turtles standing on a given patch or set of patches, or the set of
turtles standing on the same patch as a given turtle or set of turtles

Master of Business Analytics 26 September 2020 6


Agentsets (contd.)
NB: use of other to
exclude this agent
Examples of different types of agentsets

Master of Business Analytics 26 September 2020 7


Agentsets (contd.)
• Use of defined agentsets
• Use ask to make the agents in the agentset do something
• Use any? to see if the agentset is empty
• Use all? to see if every agent in an agentset satisfies a
condition
• Use count to find out how many agents are in the set
• Pick a random agent from the set using one-of
• e.g. ask one-of turtles [ set color green ]
• Tell a randomly chosen patch to sprout a new turtle
• e.g. ask one-of patches [ sprout 1 ]

Master of Business Analytics 26 September 2020 8


Agentsets (contd.)
• Use of defined agentsets (contd.)
• Use the max-one-of or min-one-of reporters to find
out which agent is the most or least along some scale
• e.g. ask max-one-of turtles [sum assets] [ die ]
• Make a histogram of the agentset using the histogram
command (in combination with of)
• Use of to make a list of values, one for each agent in the
agentset. Then use one of NetLogo’s list primitives to do
something with the list
• e.g. to find out how rich turtles are on the average:
show mean [sum assets] of turtles

Master of Business Analytics 26 September 2020 9


Agentsets (contd.)
• Use of defined agentsets (contd.)
• Use turtle-set, patch-set and link-set
reporters to make new agentsets by gathering together
agents from a variety of possible sources
• Use no-turtles, no-patches and no-links
reporters to make empty agentsets
• Check whether two agentsets are equal using = or !=
• Use member? to see whether a particular agent is a
member of an agentset

Master of Business Analytics 26 September 2020 10


Special agentsets
• The agentsets turtles
and links have special
behavior
• As they always hold the sets
of all turtles and all links
• See interaction shown (with
globals [g] defined)
• The turtles agentset grows
when new turtles are born, but other agentsets don’t grow. Writing
turtle-set turtles, gets a new, normal agentset containing
just the turtles that currently exist. Then new turtles don’t join when
they’re born

Master of Business Analytics 26 September 2020 11


Special agentsets (contd.)
• Breed agentsets are special in the same way as
turtles and links
• If you need agents in your agentset to do something
in a fixed order, you need to make a list of the
agents first
• Since otherwise the agentset will be in a random order

Master of Business Analytics 26 September 2020 12


Breeds
• Can create agent types using breeds keyword
• Only turtle and link types
• Then give them different behaviors
• Breeds defined later appear on top of those defined earlier
• When defined a new agentset with its capabilities is created
• e.g. for a new breed called sheep, the following primitives are
automatically available: create-sheep, hatch-sheep,
sprout-sheep, sheep-here, sheep-at, sheep-on, and
is-a-sheep?.
• Can also define new sheep variables using sheep-own
• Can test a breeds type using the
breed turtle variable
Master of Business Analytics 26 September 2020 13
Breeds (contd.)
• Who numbers are assigned
irrespective of breeds
• If you already have a frog 0,
the first mouse will be mouse 1,
not mouse 0, since the who
number 0 is already taken
• Try this code out and inspect the
who numbers of the resulting
mice and frogs

Master of Business Analytics 26 September 2020 14


Link Breeds
• When you declare a link breed you must declare
whether it is a breed of directed or undirected
• e.g. directed-link-breed [streets street]
undirected-link-breed [friendships friendship]
• The following primitives become available for directed breeds:
create-street-from, create-streets-from, create-
street-to, create-streets-to, in-street-neighbor? , in-
street-neighbors, in-street-from, my-in-streets, my-
out-streets, out-street-neighbor? , out-street-
neighbors and out-street-to
• For undirected breeds the following become available:
create-friendship-with , create-friendships-with ,
friendship-neighbor?, friendship-neighbors ,
friendship-with and my-friendships

Master of Business Analytics 26 September 2020 15


Links
• Link primitive names indicate what kind of links they
deal with
• Primitives that have ‘out’ in their name utilize outgoing and
undirected links
• Primitives that have ‘in’ in their name utilize incoming and
undirected links
• Primitives that do not specify ‘in’ or ‘out’, or have ‘with’ in
their name utilize all links, both undirected and directed,
incoming and outgoing

Master of Business Analytics 26 September 2020 16


Links (contd.)
• If the link is directed, it goes from end1 to end2
• If the link is undirected, end1 is always the older of the two
turtles, that is, the turtle with the smaller who number
• Links most importantly support the
representation of networks
• The simplest primitive is layout-
circle which evenly spaces the
agents around the center of the world
given a radius

Master of Business Analytics 26 September 2020 17


Links (contd.)
• The layout-radial is a good layout if you have
something like a tree structure (can have cycles too)
• Takes a root agent to be in the center
at (0,0)
• Nodes one degree away from the root
will be arranged in a circular pattern
around the central node and the next
level around those nodes and so on

Master of Business Analytics 26 September 2020 18


Links (contd.)
• Given a set of anchor nodes layout-tutte
places all the other nodes at the center of
mass of the nodes it is linked to
• The anchor set is automatically arranged
in a circle layout with a user defined radius
and the other nodes will converge into place

Master of Business Analytics 26 September 2020 19


Patch Topology
• By default the world is a torus – which means it isn’t
bounded, but ‘wraps’ at the edges
• i.e. when a turtle moves past the edge of the world, it
disappears and reappears on the opposite edge
• Can change the wrap settings with the Settings button
• If wrapping is not allowed in a given direction then in that
direction (x or y) the world is bounded
• Patches along that boundary will have fewer than 8 neighbors
• Turtles will not move beyond the edge of the world

Master of Business Analytics 26 September 2020 20


Patch Topology (contd.)
• Four topologies available:
• torus, box, vertical cylinder, or horizontal
cylinder
• Torus – wraps in both directions
• Box – doesn’t wrap in either direction
• Horizontal and vertical cylinders wrap in one direction but
not the other
• A horizontal cylinder wraps vertically, so the top of the world is
connected to the bottom
• A vertical cylinder is the opposite; it wraps horizontally so the left
and right edges are connected, but the top and bottom edges are
bounded

Master of Business Analytics 26 September 2020 21


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 22


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 23


Procedures
• There are 2 types of procedures
• Commands and Reporters
• Commands are actions for agents to carry out
• They result in some effect
• They are named using verbs such as ‘create’, ‘die’, ‘jump’,
‘inspect’, or ‘clear’
• Reporters are instructions for computing some value
• An agent reports such values to whoever who asked
• Reporter names are nouns or noun phrases

Master of Business Analytics 26 September 2020 24


Procedures (contd.)
• Built-in procedures are called primitives
• Full list: https://ccl.northwestern.edu/netlogo/docs/dictionary.html
• User-defined commands and reporters are called
procedures
• They have names that are preceded by the keyword to or
to-report depending on their type
• Both types are ended using the keyword end
• Many commands and reporters take inputs (arguments)

Master of Business Analytics 26 September 2020 25


Procedures (contd.)
• Exercise
• What are setup and go?
• Procedures
• What are clear-all,
create-turtles,
reset-ticks, ask, lt,
rt and tick?
• Primitive commands
• What are random and turtles?
• Primitive reporters
• NB: setup and go can be called by other procedures, by
buttons on the UI or from the Command Center

Master of Business Analytics 26 September 2020 26


Procedures (contd.)
• You may specify which agents – turtles, patches, or
links – are to run each command
• If not, the code is run by the observer
• In the example code, the observer uses ask to make the set
of all turtles run the commands between the square brackets
• clear-all and create-turtles can only be run by
the observer
• fd can only be run by turtles
• set and ticks can be run by different agent types

Master of Business Analytics 26 September 2020 27


Procedures (contd.)
• Procedures can take input by specifying them within
square brackets
• This example turtle procedure
can be called elsewhere as:
ask turtles [ draw-polygon 8 who ]

• Which draws an octagon with a side length of its who


number
• Reporters behave similarly
• But are defined using
to-report instead of just to
• Need to specify value to return using report keyword
Master of Business Analytics 26 September 2020 28
Anonymous Procedures
• Anonymous procedures store code to be run later
• Can be (anonymous) command or (anonymous) reporter
• They are values, so they may be passed as input, reported
as a result, or stored in a variable
• Known as lambda functions or closures in other langauges
• Primitive anonymous procedures include:
• ->, is-anonymous-command?, and is-
anonymous-reporter?
• -> creates an anonymous procedure: command or reporter

Master of Business Analytics 26 September 2020 29


Anonymous Procedures (contd.)
• Anonymous commands and reporters
• [ -> fd 1 ] is an anonymous command, while
[ -> count turtles ] is an anonymous reporter
• They require anonymous procedures as input: foreach,
map, reduce, filter, n-values, sort-by
• Using -> is optional if anonymous procedure contains a single
primitive which requires no more inputs than are are provided by
the primitive
• e.g. foreach mylist [[x] -> print x] can be replaced by
foreach mylist print (but both forms are accepted)
• The run command and runresult reporter accept
anonymous commands and reporters as well as strings
Master of Business Analytics 26 September 2020 30
Anonymous Procedures (contd.)
• An anonymous procedure may take zero or more inputs
• The inputs are referenced the variables declared before the
arrow
• e.g. in anon reporter [[a b] -> a + b], a and b are inputs

New syntax

Old syntax

Master of Business Analytics 26 September 2020 31


Anonymous Procedures (contd.)
• Omitting parts of anonymous procedure syntax

Master of Business Analytics 26 September 2020 32


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 33


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 34


Variables
• Two main types: agent and local
• An agent variable can be:
• global variable, a turtle variable, a patch variable, or a link
variable
• A global agent variable has only 1 value for all agents
• Each turtle, patch or link has its own value for every non-
global agent variable
• Built-in variables exist and for patches begin with ‘p’
• e.g. color, xcor, ycor, pcolor, pxcor, pycor etc.
• Complete list: https://ccl.northwestern.edu/netlogo/docs/dictionary.html#builtinvariables

Master of Business Analytics 26 September 2020 35


Variables (contd.)
• User-defined variables need to be declared
• You can define a global variable by adding a switch, slider,
chooser, or input box to your model, or by using the
globals keyword in your code
• e.g. globals [score]
• You can define new turtle, patch and link variables using
the turtles-own, patches-own and links-own
keywords
• e.g. turtles-own [energy speed]
patches-own [friction]
links-own [strength]

Master of Business Analytics 26 September 2020 36


Variables (contd.)
• These variables can be used throughout your code
• Use the set command to set them
• Any variable you don’t set has a starting value of zero
• Global variables can be read and set at any time by any
agent
• A turtle can read and set patch variables of the patch it is
standing on
• e.g. ask turtles [ set pcolor red ]
• To read a different agent’s variable, you can use of:
• e.g. show [color] of turtle 5
Other turtle’s
who number

Master of Business Analytics 26 September 2020 37


Variables (contd.)
• A more complicated
use of the of keyword
• Local variables are only defined within a particular
procedure
• Define using let keyword
• Exists only within the
procedure or within the
context of a square bracket
within which it is defined
• e.g. ask turtle [ let color [color] of turtle 5]

Master of Business Analytics 26 September 2020 38


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 39


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 40


Lists
• Lists let you store multiple pieces of information in a
single variable
• Can be a number, a string, an agent or agentset, or even
another list
• If your agents carry out a repetitive calculation on multiple
variables, it might be easier to have a list variable, instead
of multiple number variables
• Simplest type are constant lists
• e.g. set mylist1 [2 4 6 8]
set mylist2 [[2 4] [3 5]]
• An empty list is given by [ ]

Master of Business Analytics 26 September 2020 41


Lists (contd.)
• To make a list in which the values are built on the fly (as
opposed to being constants), use the list reporter
• It accepts two other reporters, runs them, and reports the results as a
list: e.g. set random-list list (random 10) (random 20)
- this will create a new list of two random integers each time it runs
• For longer lists you can use list within parenthesis:
(list random 10 random 20 random 30)
• Some kinds of lists are best built using the n-values
reporter, which allows you to construct a list of a specific
length by repeatedly running a given reporter
• e.g. n-values 5 [ i -> i ] creates a list of [0 1 2 3 4] while
n-values 5 [ x -> x * x ] creates a list of [0 1 4 9 16]

Master of Business Analytics 26 September 2020 42


Lists (contd.)
• Can combine two or more lists using the sentence
reporter for concatenation
• e.g. sentence 1 2 gives [ 1 2 ]
sentence 1 [2 3] gives [ 1 2 3 ]
sentence [1 2] [3 4] gives [ 1 2 3 4 ]
sentence [[1 2]] [[3 4]] gives [[1 2] [3 4]]
(sentence [1 2] 3 [4 5] (3 + 3)) gives [1 2 3 4 5 6]
• Lists can’t be modified (immutable), but you can construct
new lists based on old lists
The replace-item reporter
takes three inputs: pos of item
to be replaced, the list name
and the value of replacement

Master of Business Analytics 26 September 2020 43


Lists (contd.)
• To add an item, say 42, to the end of a list, use the lput
reporter (fput adds an item to the beginning of a list)
• e.g. set mylist lput 42 mylist gives the new mylist as
[2 7 10 Bob [3 0 -2] 42]
• The but-last (bl for short) reporter reports all the list
items but the last
• e.g. set mylist but-last mylist gives back the new
mylist as [2 7 10 Bob [3 0 -2]]
• Try but-first as an exercise!
• Can also replace nested items:
• e.g. what does the following do: set mylist (replace-item 3
mylist (replace-item 2 (item 3 mylist) 9))

Master of Business Analytics 26 September 2020 44


Lists (contd.)
• To run some operation on each item in a list in turn we use
• e.g. foreach [1 2 3] show

• foreach [1 2 3] [steps -> ask turtles [fd steps]]


will make the turtles move forward 6 patches
• foreach [true false true true] [ should-move? ->
ask turtles [ if should-move? [ fd 1 ] ] ] will make
turtles move forward 3 patches

Master of Business Analytics 26 September 2020 45


Lists (contd.)
• map is like foreach but is a reporter and takes an input list
and a reporter name or reporter block
• e.g. set mylist map round [1.2 2.2 2.7] gives
mylist the value [ 1 2 3 ]
• Using anonymous procedures as before we can do

• Other primitive procedures for handling lists include:


• filter, reduce, and sort-by
• In addition you can use control flow with repeat or while

Master of Business Analytics 26 September 2020 46


Lists (contd.)
• Since agentsets are randomly ordered we can use lists to
order them if needed using sort and sort-by
• If you use sort on an agentset of turtles, the result is a list of
turtles sorted in ascending order by who number
• If you use sort on an agentset of patches, the result is a list of
patches sorted left-to-right, top-to-bottom
• If you use sort on an agentset of links, the result is a list of links,
sorted in ascending order first by end1 then by end2 any
remaining ties are resolved by breed in the order they are declared
in the Code tab
• If you need descending order instead, you can combine reverse
with sort, for example reverse sort turtles

Master of Business Analytics 26 September 2020 47


Lists (contd.)
• Since agentsets are randomly ordered we can use lists to
order them if needed using sort and sort-by (contd.)
• To sort by something other than the who number it needs to be
explicitly specified – e.g.
sort-by [[a b] -> [size] of a < [size] of b]
turtles
• This returns a list of turtles sorted in ascending order by their turtle
variable size
• Once you have a list of
agents, you might want to ask
them each to do something
• Use the foreach and ask commands in combination
• This will ask each turtle in ascending order by who number
Master of Business Analytics 26 September 2020 48
Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 49


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 50


Ask
• NetLogo uses the ask command to give commands
to turtles, patches, and links
• All code to be run by turtles must be located in a
turtle ‘context’, established by:
• a button, by choosing ‘Turtles’ from the popup menu: any
code you put in the button will be run by all turtles
• the Command Center, by choosing ‘Turtles’ from popup:
any commands you enter will be run by all the turtles
• using ask turtles, hatch, or other commands which
establish a turtle context

Master of Business Analytics 26 September 2020 51


Ask (contd.)
• Any code that is not inside any ask is by default
observer code
• When ask is used with an agentset each agent will
take its turn in a random order

Master of Business Analytics 26 September 2020 52


Ask (contd.)
• Usually the observer uses
ask to ask all turtles, all
patches or all links to run
commands
• Can also use ask to have an
individual turtle, patch or
link run commands
What do these ask
commands achieve?

Master of Business Analytics 26 September 2020 53


Ask (contd.)
• The turtle primitive reporter takes a who number as an
input, and reports the turtle with that who number
• The patch primitive reporter takes values for pxcor and
pycor and reports the patch with those coordinates
• The link primitive takes two inputs, the who numbers of the
two turtles it connects
• And the patch-at primitive reporter takes offsets: distances,
in the x and y directions, from the first agent
• You can also select a subset of turtles, or a subset of patches,
or a subset of links and ask them to do something

Master of Business Analytics 26 September 2020 54


Ask (contd.)
• When you ask a set of agents to run more than one command,
each agent must finish before the next agent starts
• In this example, first one turtle
moves and turns red, then another
turtle moves and turns red, and so on

• In this example first all the turtles


move, then they all turn red

Master of Business Analytics 26 September 2020 55


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 56


Main concepts and constructs
• Agents

• Procedures

• Variables

• Lists

• Ask

• Output/Files

Master of Business Analytics 26 September 2020 57


Output
• The main output in NetLogo is to the screen
• Output to the screen can also be later saved to a file
using the export-output command
• Basic output commands are:
• print, show, type, and write
• print is useful in most situations
• show lets you see which agent is printing what
• type lets you print several things on the same line
• write lets you print values in a format which can be read back in
using file-read

Master of Business Analytics 26 September 2020 58


Output (contd.)
• The print, show, type, and write primitives
differ on the following facets:
• What types of values does the primitive accept?
• Does the primitive output a newline at the end?
• Are strings output with quotes surrounding them?
• Does the primitive output the agent which printed it?

Master of Business Analytics 26 September 2020 59


File I/O
• Primitives for interacting with outside files
• Begin with the prefix file-
• Two modes: read and write
• Start with file-open
• Then use file-read, file-read-line, file-read-
characters, and file-at-end?
• Writing primitives are: file-print, file-show, file-
type, and file-write
• Files will never be overwritten but always appended to
• After use need to give command file-close
• Files can be deleted using the command file-delete

Master of Business Analytics 26 September 2020 60


File I/O
• Typical usage example

• The user-directory, user-file, and user-new-


file primitives are useful when you want the user to
choose a file or directory for your code to operate on

Master of Business Analytics 26 September 2020 61


Programming in NetLogo

• Full syntax available at:


https://ccl.northwestern.edu/netlogo/docs/programming.html

Master of Business Analytics 26 September 2020 62

You might also like