View
220
Download
0
Category
Preview:
Citation preview
Transitioningto
NetLogo
Assignment:let x 5 ; Creates a new local variable and
; gives it the given value.
; If you want to change the value afterwards,
; use set. set x 5
Control:if x <=5 [ do this ]ifelse x <=5 [ do this ][ else ...do this ]
Iteration:repeat 10[ do this ]while [x <=5] [ do this ]
Procedure:to HelloThere [s]
; print se "Hello there, " stype "Hello there, "print s
end
observer> hellothere "Ron"Hello there, Ron
Functions:to-report avg [x y]
report (x + y) / 2end
observer> print avg 7 87.5
I/O:
print show type write
Random Numbers:
random random-float random-exponentialrandom-normal random-poisson random-gamma
Statistics:
histogram max min mean medianmodes standard-deviation variance
List Processing:
first last butfirst butlast removeitem length sumsort shuffle reversesentence word listrun
Files:
file-open file-closefile-read file-read-line file-read-charactersfile-print file-show file-type file-print
to tryMe [n] let c 0
let comma ”,”file-open "/Users/rpryor/Desktop/my-file-out.csv"
while [c < n] [file-write (random-normal 3 1) file-type comma set c c + 1]
file-type random-normal 3 1 file-close
end
NetLogo
ProgrammingAN INTRODUCTION
Author: Alan G. Isaac
Organization: American University
NetLogo Basics
BACKGROUND
PRELIMINARIES
First read the NetLogo Basics
GOALS
After mastering this section, you will be able to:
use NetLogo’s branching and looping constructs
create procedures and reporters
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
1 of 26 7/20/12 4:14 PM
find NetLogo “Code examples” to simplify your own programming task
modify an existing NetLogo model
build a new NetLogo model
CODE EXAMPLES
The NetLogo Models Library includes a collection of code examples. Be sure to look at
these for hints whenever you get stuck.
PROGRAM STRUCTURE
THE CCOODDEE TAB: GLOBAL VARIABLES
comments:
a semicolon (;;) begins a comment for remainder of line
global variables
each global variable must be declared in the declarations section
every agent can access a global variable. (Roughly, they belong to the
observer.)
values are assigned (or reassigned) with the sseett command
THE CCOODDEE TAB: DECLARATIONS AND PROCEDURES
declarations section
gglloobbaallss [[......]]
declares a list of global variables
other global variables declared in sliders
may be thought of as oobbsseerrvveerr--oowwnnss
ttuurrttlleess--oowwnn [[......]], ppaattcchheess--oowwnn [[......]],
lliinnkkss--oowwnn [[......]]
declare a list of instance attributes for each agent type
procedures section (only contains procedures and reporters)
ttoo mmyy--pprroocceedduurree ...... eenndd
ttoo--rreeppoorrtt mmyy--rreeppoorrtteerr ...... eenndd
a procedure that returns a value is called a “reporter”
reporters must use rreeppoorrtt
KEYWORDS
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
2 of 26 7/20/12 4:14 PM
In the Code tab, outside of code blocks, we should only find:
comments
NetLogo keywords
<<iinnssttaanncceess>>--oowwnn (see below)
Comment: many of the NetLogo documentation examples are slightly misleading on this
score. E.g., http://ccl.northwestern.edu/netlogo/docs/dictionary.html#breed
KEYWORDS
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#Keywords
extensions http://ccl.northwestern.edu/netlogo/docs/extensions.html
__includes http://ccl.northwestern.edu/netlogo
/docs/dictionary.html#includes
globals
breed, directed-link-breed, undirected-link-breed
patches-own, turtles-own, <breeds>-own, links-own, <link-breeds>-own
to, to-report, end
EXTENSIONS
See: Help > NetLogoUser Manual > Extensions
standard extensions
array, table, GoGo, Profiler, GIS, Sample, and Sound are in the standard
installation
sound (MIDI sounds and sound file playback)
located in Extensions subfolder of NetLogo installation folder
Some (GIS, Table) come with existing models
NetLogo 3D
NetLogo can locate agents in 3d spaces
patches becomes cubes
see examples in Models Library
other important extensions
R extension: http://netlogo-r-ext.berlios.de/
MORE EXTENSIONS (3RD PARTY)
There are many third-party extensions for NetLogo. Here are a couple of examples:
graphics extension http://evolve.lse.ac.uk/NetLogo/extensions/Simulations-
NetLogo%20Extensions.php
shell extension https://github.com/NetLogo/Shell-Extension/
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
3 of 26 7/20/12 4:14 PM
BASIC PROGRAM STRUCTURE
Even the simplest NetLogo programs traditionally include the following structure:
globals
declaration of global variables using the gglloobbaallss keyword
setup
a procedure named sseettuupp that initializes the global varaibles and does other
setup operations
go
a procedure that runs one iteration of the model; this holds the “schedule” for your
program
EXAMPLE: MINIMAL PROGRAM STRUCTURE
globals [ gvar01 gvar02 ]
to setup
clear-all
end
to go
do-stuff
end
to do-stuff
...
end
APPLICATION: MINIMAL PROGRAM STRUCTURE
globals [ n-heads n-tails ]
to setup
clear-all
end
to go
repeat 50 [ flip-coin ]
end
to flip-coin
;; fill in procedure body
end
PARAMETERS FOR PROCEDURES
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
4 of 26 7/20/12 4:14 PM
Procedures and reporters can specifiy formal parmeters in brackets after the name. As a
convention, we will begin formal parameter names with a hash mark. (These names are
strictly local to the procedure.)
to-report is-equal? [#x #y]
ifelse #x = #y [report true] [report false]
end
See: http://ccl.northwestern.edu/netlogo/2.0/docs/programming.html#procedures2
PLOTTING: FIRST STEPS
PLOTTING
Plots are added through the GUI. (In your program you can refer to them by the name you
give them at creation.)
http://ccl.northwestern.edu/netlogo/docs/programming.html#plotting
In the NetLogo Models Library, under Code Examples, see PPlloottttiinngg EExxaammppllee.
BASIC CONCEPTS: PLOTS
You can add plots to the IInntteerrffaaccee window. Just right click where you want it
located, and fill in the resulting dialogue.
For the moment, we will only change the ppeenn uuppddaattee ccoommmmaannddss.
pen update commands
commands to be executed when the plot updates
update-plots
NetLogo primitive that we will call in our ggoo procedure
EXERCISE: BASIC PLOT
In the CCooddee window, create a coin-flipping program that has the following ggoo
procedure:
to go
set n-heads 0
repeat 50 [ flip-coin ]
update-plots
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
5 of 26 7/20/12 4:14 PM
end
Add a plot with the pen update command pplloott nn--hheeaaddss.
In the Command Center, run your sseettuupp procedure, and then run your ggoo procedure
100 times.
EEXXPPOORRTT--PPLLOOTT
export-plot writes a comma-separated values file. There data written includes the x and y
values of all points plotted by all the plot pens in the plot.
Specify the plotname as a string: it is the same as whatever you entered as the name in the
plot dialogue (which is used as the title of your plot).
The data is written to an external file. You specify the filename as a string. Use forward
slashes.
See: http://ccl.northwestern.edu/netlogo/docs/dictionary.html#export-plot
PLOT COMMANDS
most-used plot commands:
histogram, plot, plotxy, set-current-plot, set-current-plot-pen, set-plot-pen-mode
often-used plot commands:
set-histogram-num-bars set-plot-pen-color set-plot-x-range set-plot-y-range
autoplot (automatic axes range adjustemnts):
autoplot? auto-plot-off auto-plot-on
clear-plot related commands:
clear-all-plots clear-plot plot-pen-reset
other plot commands:
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#plottinggroup
SIMPLE HISTOGRAM
Suppose we have turtles classified by color: red, green, or blue. After using the GUI to
create a plot titled "Class Histogram", we can:
to update-class-histogram
set-current-plot "Class Histogram"
histogram map [position ? [red green blue]] ([color] of turtles)
end
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
6 of 26 7/20/12 4:14 PM
CUSTOM HISTOGRAM
If we would like to color-code our bars, we cannot use hhiissttooggrraamm. Instead we plot a
bar for each value.
to update-class-histogram
set-current-plot "Class Histogram"
plot-pen-reset
set plot-pen-mode 1 ;; bar mode
set-plot-pen-color red
plot count turtles with [color = red]
set-plot-pen-color green
plot count turtles with [color = green]
set-plot-pen-color blue
plot count turtles with [color = blue]
end
PLOTTING GINI COEFFICIENT AND LORENZ CURVE
let cumsum-sorted-wealths
partial-sums sort [wealth] of turtles
let total-wealth last cumsum-sorted-wealths
let normalized-wealths
map [? / total-wealth] cumsum-sorted-wealths
PLOTTING GINI COEFFICIENT AND LORENZ CURVE
...
let n length normalized-wealths
let gaps n-values n
[((? + 1) / n) - item ? normalized-wealths]
set gini (2 * sum gaps / n) ;; Gini = A/(A+B) = 2*A
set-current-plot "Gini Dynamics" plot gini
PLOTTING GINI COEFFICIENT AND LORENZ CURVE
...
set-current-plot "Dynamic Lorenz Curve"
set-current-plot-pen "lorenz01a" plot-pen-reset
set-plot-pen-interval 1 / n
plot 0
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
7 of 26 7/20/12 4:14 PM
foreach normalized-wealths [plot ?]
Building NetLogo Models
FIRST STEPS
STEPS TOWARD MAKING YOUR OWN MODELS
Experiment with existing models via GUI
Models Library downloads with installation (File > Models Library)
http://ccl.northwestern.edu/netlogo/models/
other publicly available models on the web http://www.openabm.org/
1.
Modify existing models2.
Roll your own3.
MODIFYING MODELS
find a model that does something close to what you want
save it under a new name
modify it to suit your needs
update the model information to match your changes
make sure to appropriately attribute all code (i.e., honor the copyrights)
structured and commented code
– helpful to others who read your code – helpful to you in both writing and
understanding your code
SIMPLE MODIFICATIONS
You might want to change the World settings
size
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
8 of 26 7/20/12 4:14 PM
location of 0, 0
torus or rectangle
patch size (this and size determine size of world screen)
MODEL DECISIONS
system to be modeled
what do the agents represent?
what are the rules of action and interaction?
how will you approximate these rules for entry into the modeling environment?
what does a tick (cycle) represent?
SIMPLE MODEL
A basic model will have:
sseettuupp procedure1.
ggoo procedure2.
For example:
sseettuupp procedure
create turtles (ccrrtt or sspprroouutt)
random headings? (the default)
random positions? (origin is the default)
ggoo procedure
move the turtles with random distance and headings
randomly change speed (jump size) and headings
SIMPLE MODEL ...
A basic model may have:
ssttaarrttuupp procedure
If you name a procedue ssttaarrttuupp, it will be run when your model first
loads.
sliders
sliders let users control model parameters, e.g., the speed range and the
angle range for heading changes
easy to add in NetLogo GUI
graphs
graphs can dynamically monitor a single value (plot), pairs of values
(plotxy), or collections of values (histogram)
easy to add in NetLogo GUI
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
9 of 26 7/20/12 4:14 PM
NetLogo Programming
Language
PROGRAMMING IN NETLOGO
CONTEXT IN NETLOGO
context: who is acting
the default actor/agent is the observer, but ...
aasskk ttuurrttlleess sets context to turtles
aasskk ttuurrttllee 00 sets context to turtle 0
agents can ask other agents to do things
aasskk ttuurrttlleess [[ aasskk lliinnkkss [[ …… ]]…… ]]
only the agent that “owns” an attribute can find the value or change the value
BREEDS
new breeds can be declared in the declarations section of a script:
breed [ thieves thief ]
a breed is like a “subtype” of turtle: it has all the attributes of turtle, plus any new
attributes declared for the breed. E.g.,
thieves-own [ skill known? ]
Turtles and links come with a bbrreeeedd attribute, which can be reset.
show [ breed ] of turtle 0
ask turtle 0 [ set breed thieves ]
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
10 of 26 7/20/12 4:14 PM
LINKS
create-link-with
create an undirected link between the caller and agent
create-link-to
create a directed link from the caller to agent
create-link-from
creates a directed link from agent to the caller
LINK BREEDS
Link breeds must be declared as either directed or undirected. These breeds may own
variables. (See the Link Breeds Example in the Model Library.)
directed-link-breed [unis uni]
undirected-link-breed [bis bi]
bis-own [weight]
...
ask turtule 0 [create-uni-to turtle 1]
ask turtule 0 [create-bis-with other turtles]
LANGUAGE BASICS
LANGUAGE BASICS
reassignment: set a b
use parentheses to control order of operations
use brackets [[ ]] for code blocks
white space ignored after initial space
procedures and reporters (see above)
BASIC DATA TYPES
numbers
all numbers are floating point
lists
immutable
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
11 of 26 7/20/12 4:14 PM
System Message: WARNING/2 (nneettllooggoo--iinnttrroo..rrsstt, line 583)
Definition list ends without a blank line; unexpected unindent.
strings
booleans (true or false)
AGENTSETS
turtlesets
patchsets
linksets
EXTENSION DATA TYPES
tables
arrays
LANGUAGE SURPRISES
use ((-- nnuummbbeerrnnaammee)), not --nnuummbbeerrnnaammee
case-insensitive
necessary white space: set a (3 * b)
RECENT CHANGES
see the Transition Guide: http://ccl.northwestern.edu/netlogo
/docs/transition.html
rreesseett--ttiicckkss: as of version 5, you must explicitly call rreesseett--ttiicckkss
to initialize the ticks counter; it is no longer called by cclleeaarr--aallll
NetLogo 5: can no longer concatenate strings with ++; use wwoorrdd
rraannddoomm--oonnee--ooff was renamed oonnee--ooff
LANGUAGE CONVENTIONS
Logical variables end in ??
procedure body indented
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
12 of 26 7/20/12 4:14 PM
two semicolons to start comment ;;;;
TICKS
NetLogo includes a built-in tick counter:
print ticks ;; display current value of ticks
tick ;; increment ticks (by 1)
print ticks ;; display current value of ticks
reset-ticks ;; reset ticks to 0
print ticks ;; display current value of ticks
CONTROL FLOW: BRANCHING
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#controlgroup
if (condition) [commands]
ifelse (condition) [commands4true] [commands4false]
ifelse-value (condition) [reporter4true] [reporter4false]
BOOLEANS AND CONDITIONAL BRANCHING
NetLogo has boolean primitives, ttrruuee and ffaallssee. Comparisons (e.g., >> or <<)
produce a boolean result, which can be used for conditional code execution. E.g., noting
that rraannddoomm--ffllooaatt 11 is between zero and one:
if (random-float 1 < 0.5) [show "heads"]
We might also like the observer to print “tails” for larger outcomes. We can use the
iiffeellssee construct to do this.:
ifelse (random-float 1 < 0.5)
[show "heads"]
[show "tails"]
Note that to create a string, we bracket a sequence of characters with double quotes.
IIFFEELLSSEE--VVAALLUUEE
NetLogo also provides the unusual iiffeellssee--vvaalluuee primitive, which allows
condition determination of a value.
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
13 of 26 7/20/12 4:14 PM
ask turtles [
set color ifelse-value (wealth < 0) [red] [blue]
]
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#ifelse
CONTROL FLOW: LOOPING
foreach list [commands]
repeat
stop
while
loop (forever!)
other: ask ask-concurrent carefully error-message every run runresult to
to-report wait with-local-randomness without-interruption
OPERATORS: MATH, LOGIC AND COMPARISON
math
+, -, /, ^
white space delimited (e.g., 33 ++ 22 not 33++22)
all are binary, but can write ((-- xx)) for 00 -- xx
logical operators (operate on booleans)
and, not, or, xor
comparison (http://ccl.northwestern.edu/netlogo/docs/dictionary.html#Symbols)
>, >=, <, <=, =, !=
GLOBAL VARIABLES
have global scope (i.e., are available anywhere in the program)
must be declared before used
in the declarations section, or
by adding a button
use sseett aa bb to change the value of variable aa
LOCAL VARIABLES
lleett aa bb declares a new local variable aa and assigns it the value of bb
scope restricted to code block in which declared
cannot be declared with global scope
sseett aa bb changes the value of aa to the value of bb
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
14 of 26 7/20/12 4:14 PM
LISTS
AGENTSETS VS. LISTS
agentset
an unordered collection of agents
traverse with aasskk
aasskk aaggeennttsseett [[ lliisstt ooff ccoommmmaannddss ]]
list
an ordered, immutable collection of objects
traverse the list items sequentially with ffoorreeaacchh
?? is special name for current list item in the ffoorreeaacchh sequence
E.g., ffoorreeaacchh [[11..11 22..22 22..66]] [[ pprriinntt rroouunndd ?? ]]
will print 1, 2, 3.
CREATING LISTS
list constants between brackets:
lleett mmyylliisstt [[00 11 22 33]]
use lliisstt to make a list from variables:
lleett aa 00 lleett bb 11 lleett mmyylliisstt ((lliisstt aa bb))
use the sseenntteennccee primitive (to append to or concatenate):
sseenntteennccee [[00 11]] 22
sseenntteennccee [[00 11]] [[22 33]]
use ooff with an agentset:
[[ccoolloorr]] ooff ttuurrttlleess
OPERATING ON LISTS
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#listsgroup
sublists
sublist, remove-duplicates
remove item list, remove-item int list
but-first, but-last
new lists
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
15 of 26 7/20/12 4:14 PM
replace-item int list
fput, lput, sentence
n-of int list, n-values int [reporter]
reverse, shuffle
sort, sort-by
membership
member?
IMMUTABILITY
NetLogo lists are immutable: you construct new lists based on old lists.
if you want an extant variable to refer to a new list, use sseett.
set mylist replace-item 0 mylist 99
; mylist's first element is now 99
set mylist lput 100 mylist
; appends the value 100 to mylst
set mylist fput -1 mylist
; mylist now has a new first element
OPERATING ON LISTS ...
zero based indexing:
iitteemm 00 [[00 11 22]]
list items
first mylst, last mylst, item int mylst, one-of list
member? value list, position item list
other
empty?, length
INTRODUCTION TO FUNCTIONAL PROGRAMMING
mmaapp
apply a reporter to a list and produce a new list.
The current item is represented by ??.
E.g., mmaapp [[?? ** ??]] [[00 11 22]] reports [[00 11 44]].
ffiilltteerr
report a new list with only some of the members of the given list:
E.g., ffiilltteerr [[?? << 22]] [[11 22 11 22]] reports [[11 11]].
rreedduuccee
combine the items of a list into a single result:
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
16 of 26 7/20/12 4:14 PM
E.g., rreedduuccee [[??11 ++ ??22]] [[11 22 33]] reports 66.
ssoorrtt--bbyy
sort a list based on a comparions.
E.g., ssoorrtt--bbyy [[??11 >> ??22]] [[33 11 44 22]] reports [[44 33 22 11]]
FFOORREEAACCHH
run commands for each item of a list
syntax: ffoorreeaacchh **lliisstt** [[**ccoommmmaannddss**]]
simple example:
let range n-values 10 [?]
foreach range [show ? * ?]
or equivalently:
foreach n-values 10 [?] [show ? * ?]
FFOORREEAACCHH WITH MULTIPLE LISTS
The ffoorreeaacchh command can be used with multiple lists of identical length. The first
result is computed from the first elements of the arguments. The second result is computed
from the second elements of the arguments. For example:
(foreach [1 2] [3 4] [5 6] [print ?1 + ?2 + ?3])
Note the required parentheses.
NESTED FFOORREEAACCHH
to-report moore-offsets [radius]
let dxdy (list ) ;; empty list
let offsets n-values (2 * radius + 1) [? - radius]
foreach offsets [
let xoff ?
foreach offsets [
let yoff ?
set dxdy lput (list xoff yoff) dxdy
]
]
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
17 of 26 7/20/12 4:14 PM
report dxdy
end
RREEDDUUCCEE
reduce [reporter] list
reduce a list from left to right using reporter, resulting in a single value.
use ?1 and ?2 in your reporter to refer to the two objects being
combined.
example: reduce [?1 + ?2] [1 2 3]
→ 6
CUMULATIVE SUM VIA RREEDDUUCCEE
Written by Seth Tisue
to-report partial-sums [nums]
let total 0
let result []
foreach nums [
set total total + ?
set result lput total result
]
report result
end
CUMULATIVE SUM VIA RREEDDUUCCEE (V.2)
to-report partial-sums [lst] ;; written by Seth Tisue
report butfirst reduce [lput (?2 + last ?1) ?1] fput [0] lst
end
OUTPUT
BEHAVIORSPACE
parameter sweep
systematic variation of scenarios
standard method for exploring the parameter space
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
18 of 26 7/20/12 4:14 PM
BehaviorSpace
a NetLogo tool for easily implementing a parameter sweep
USING BEHAVIORSPACE
Tools > Behavior Space > New
give your experiment a name
specify multiple values of parameters for your experiment
list the values explicitly, or use a range [[ssttaarrtt iinnccrreemmeenntt
eenndd]]
[[""mmyyppaarraamm"" 00 11 22 33]], or [[""mmyyppaarraamm"" [[00 11 33]]]]
you can vary the world size! (not a parameter in an ordinary sense)
fill in the experiment information
click “ok” when you are done
save your NetLogo model (this will save your experiment settings)
run the experiment by pressing the RRuunn button
you will be prompted for how to save your data before the experiment
runs
it runs much more quickly if you uncheck “update graphics” and “update
plots and monitors”.
BEHAVIOR SPACE ...
Repetitions
the number of repetitions for each parameter combination
reporters
one per line, for each variable you want to record
Setup commands:
usually just your sseettuupp procedure
Go commands:
the procedure that runs one step of your model, usually named ggoo
Stop condition:
a reporter that reports ttrruuee when the run should stop (or just set the number of
iterations as a TTiimmee LLiimmiitt)
OPEN A FILE
Unlike many languages, NetLogo does not allow you to specify upon opening whether
you will read from or write to the file. That is determined by the next file primitive you
use (e.g., ffiillee--rreeaadd or ffiillee--wwrriittee).
If you open an existing file and write to it, you will append to that file. If you want to
replace the content of an existing file, you will have start with a ffiillee--ddeelleettee.
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
19 of 26 7/20/12 4:14 PM
Once you are done with an open file, you should close it with ffiillee--cclloossee.
OPEN A FILE FOR WRITING
In order to open a file for writing and close it afterwards, you need the following
commands:
ffiillee--ddeelleettee string
delete the file designated by string
ffiillee--ooppeenn string
open a file for reading or appending (but not both)
ffiillee--cclloossee:
close an open file
USING CCAARREEFFUULLLLYY WITH FFIILLEE--DDEELLEETTEE
If you want to replace the content of a file, say tteemmpp..ttxxtt, you should begin by
deleting the existing file. But suppose you do not know ahead of time whether the file
exists: deleting a file that does not exist is a runtime error. To work around this issue, use
ccaarreeffuullllyy. http://ccl.northwestern.edu/netlogo/docs/dictionary.html#carefully
carefully [file-delete "c:/temp/temp.txt"] []
file-open "c:/temp/temp.txt"
file-print "test 01"
file-close
FILE OUTPUT
In order to write information to external files, you may find the following commands to be
useful.
ffiillee--pprriinntt value
write value to open file, followed by carriage return
ffiillee--sshhooww value
first write the agent to file, then write value to open file, followed by carriage
return
ffiillee--ttyyppee value
write value to open file, not followed by carriage return (strings are written
without quotes; backslashes escape control characters)
ffiillee--wwrriittee value
write a space and then write value to open file, not followed by carriage return
(strings are written quote delimited; backslahses are literal)
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
20 of 26 7/20/12 4:14 PM
EXAMPLE
Try this in the command center:
file-delete "c:/temp/temp.txt"
file-open "c:/temp/temp.txt"
file-print "Minimum mean maximum"
file-type 10 file-write 15 file-write 20
file-print ""
file-close
Note use forward slashes in your paths.
FILE-BASED INPUT
In order to read external information into your program, you may find the following
commands to be useful.
ffiillee--ooppeenn string:
open a file for reading or appending (but not both)
ffiillee--cclloossee:
close an open file
ffiillee--rreeaadd--lliinnee:
read the next line and return it as a string (without terminators)
ffiillee--rreeaadd:
read the next "constant" (e.g., number, list, or string) and return it
ffiillee--aatt--eenndd??:
report true if last character of file has been read
EXAMPLE
Try this in the command center:
file-open "c:/temp/temp.txt"
print file-read-line
file-close
Note use forward slashes in your paths.
EXAMPLE: FILE-BASED INPUT
Suppose the nnllddaattaa0011..ttxxtt looks like:
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
21 of 26 7/20/12 4:14 PM
pxcor pycor n-turtles
0 0 5
1 0 3
You could handle this as follows:
file-open "nldata01.txt"
let trash file-read-line ;; discard header line
while [not file-at-end?] [
ask patch file-read file-read [sprout file-read]
]
file-close
EXAMPLE: FILE-BASED INPUT (PYTHON)
fin = open('nldata01.txt', 'r')
trash = next(fin)
data = dict()
for line in fin:
x, y, n = map(int, line.split())
data[(x,y)] = n
fin.close()
BEHAVIORSPACE AND FILE OUTPUT
If you want to make your own output files during BehaviorSpace runs, use the
bbeehhaavviioorrssppaaccee--rruunn--nnuummbbeerr primitive. Alternatively, produce filenames
based on parameter values.
["globalA" 1 2 3]
["gloablB" 4 5 6]
file-open (word "myfile-" globalA "-" globalB ".txt")
Of course you can combine these two approaches.
If you needs even more flexibility, consider Charles Staelin's ppaatthhddiirr extension. It
might still be here: http://sophia.smith.edu/~cstaelin/NetLogo/pathdir.html
NetLogo Resources
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
22 of 26 7/20/12 4:14 PM
MANUAL
USER MANUAL
http://ccl.northwestern.edu/netlogo/docs/ includes tutorials and the following:
Interface Guide
Programming Guid
NetLogo Dictionary
GUIDES
Interface Guide
http://ccl.northwestern.edu/netlogo/docs/interface.html
world settings: size, topology (wrapping vs. reflecting)
menu items, controls
Programming Guide
http://ccl.northwestern.edu/netlogo/docs/programming.html
NetLogo Dictionary
http://ccl.northwestern.edu/netlogo/docs/dictionary.html
alphabetical list
also grouped by type
DOWNLOAD, INSTALL, AND RUN (WINDOWS
VERSION)
Download
Go to: http://ccl.northwestern.edu/netlogo/
Download link on the left
Save to desktop or accept the default
Install
Double-click on downloaded file to install (NetLogo4.1Installer.exe)
Accept all defaults
Run (Windows version)
Start > All Programs > NetLogo > NetLogo 4.1
PUTTING NETLOGO MODELS ON THE WEB
http://ccl.northwestern.edu/netlogo/docs/applet.html
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
23 of 26 7/20/12 4:14 PM
SaveAs > Applet
Java Virtual Machine (JVM) included (solves problems: old versions
work!)
applet can read and write files on your computer, but not on your users’
computers
OTHER NETLOGO RESOURCES
discussion group: http://groups.yahoo.com/group/netlogo-users/
homepage includes mail lists, documentation, and example models
http://ccl.northwestern.edu/netlogo/
onlines articles and papers, e.g.,
http://ccl.northwestern.edu/papers/
http://ccl.northwestern.edu/papers/netlogo-outside.html
MODELS LIBRARY: LIFE
MODELS LIBRARY: LIFE
Models Library
Computer Science > Cellular Automata > Life
use of patches to implement cellular automaton
just patches (cells); no turtles
cells have two states: alive and dead
Dark = cell alive, background color = dead
Transition rule
dead cell with 3 or more live neighbors comes to life
live cell with 2 live neighbors continues to live
live cell with less than 2 live neighbors dies
MODELS LIBRARY: HEAT BUGS
FFiillee >> MMooddeellss LLiibbrraarryy >> BBiioollooggyy >> HHeeaattbbuuggss
famous biological model
each bug radiates a little heat
bugs move if they are too hot or cold
Compare to the 'Collectivities' model.
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
24 of 26 7/20/12 4:14 PM
MODELS LIBRARY: PARTY
Models Library
Social Science > Party (famous in another form)
implements the Schelling segregation model
two types of people (e.g., men and women)
otherwise the same attributes
Key parameter:
how “comfortable” are these agents being in a local minoriy
adjustable parameter (slider)
Discovery
Even a slight preference can lead to complete segregation
MODELS LIBRARY: SMALL WORLD
Models Library > Networks > Small Worlds
famous: six degrees of separation
new tools
uses links
path along links from one agent to another
Setup
initalize links in a ring (each agent links to an agent each side)
key outcome concerns the average path length for all pairs of agents
even a few random new links substantially reduces the average path
length
potentially significant for organizational design
potentially significant for disease transmission
MODELS LIBRARY: EL FAROL
Models Library > Social Science > ElFarol
another version: http://www.markgarofalo.com/ABS/ElFarol
/ElFarolBarProblem.html
Readings: [garofalo-2006-wp], [wilensky.rand-2007-jasss]
MODELS LIBRARY: PREDATION
File > Models Library > Biology > Wolf Sheep Predation
use of breeds (wolves, sheep)
more interesting variant: patches grow grass that sheep eat (click grass?
Switch to On)
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
25 of 26 7/20/12 4:14 PM
boom-and-bust cycles common (with sheep and wolves negatively
correlated)
MODELS ON NETLOGO SITE
URL: ccl.northwestern.edu/netlogo/ > Community
possible problems if models are written for earlier versions of NetLogo
MODELS ON NETLOGO SITE
Miller & Page Applause Model
http://luis.izqui.org/models/standingovation/
Readings: [miller.page-2004-complexity]
REFERENCES
Axtell, R., Axelrod, R., Epstien, J. M., and Cohen, M. D. (1996). Aligning simulation
models: A case study and results. Computational and Mathematical Organization Theory,
1:123–141.
Resnick, M. (1997). Turtles, Termites, and Traffic Jams: Explorations in Massively
Parallel Microworlds. MIT Press.
[garofalo-
2006-wp]
Garofalo, Mark. (2006) "Modeling the 'El Farol Bar Problem' in
NetLogo". Dexia Bank Belgium . http://ccl.northwestern.edu
/papers/netlogo-outside.html
[miller.page-
2004-complexity]
Miller, John H, and Scott E Page. 2004. The Standing
Ovation Problem. Complexity 9, 8--16.
[wilensky.rand-
2007-jasss]
Wilensky, Uri, and William Rand. 2007. Making Models Match:
Replicating an Agent-Based Model. Journal of Artificial
Societies and Social Simulation 10, Article 2.
http://jasss.soc.surrey.ac.uk/10/4/2.html
LEGALITIES
Copyright © 2012 Alan G. Isaac. Some rights reserved. This document is
licensed under a Creative Commons Attribution License.
NetLogo Programming https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml
26 of 26 7/20/12 4:14 PM
First Steps with NetLogoLets take a few first steps with our modeling frameworks. We will be fairly brief , limiting ourselves to simple "kicking thetires" and writing a hello world in each ABM system (here is the RePast First Steps). Our goal is to gain a feel for what eachsystem is capable of so that we can make intelligent decisions on which one to use for a given task. Note: most imagesbelow can be clicked on for a full size image.
Introducing NetLogo
To download NetLogo, go to their web site, downloading the package for your system. As of thiswriting, the version is 1.2. During the download you can join the mail list, which I recommend.
The package will include considerable browser-based documentation in the docs/ directory for fastviewing. I show the results of downloading "Other Java-enabled platform" to the right. TheNetLogo.jar is double clickable, starting the application. Specific downloads are available for Macand Windows.
The NetLogoLite.jar file is used for exporting your models to the web, like this example.
When NetLogo starts, you are presented with an empty model, left, whichyou can modify. You also can browse the Model Library, right. Start byselecting the Segregation model from the Social Science collection.
To run the model, click "Setup", then "go". The model runs until each agent(called turtles) is "satisfied" .. i.e. has neighbors of at least "%-similar-wanted" as himself. You can experiment with number of turtles and the %setting by changing the sliders.
Note the surprising result with the initial settings: wanting 30% similar neighbors generally results in over 70% similar! Thissuggests very minor desire for similarity among residents of a neighborhood results in segregation. Click on the tabs on thetop of the window to see more information about the model, and to see the source code itself. The code is surprisinglysimple for what it does.
Now lets try a few simple commands. To do this, we'll select New in the File menu to get an empty new model. Thispresents just two items: the graphics window and the command center. The graphics window shows the patches and turtles,while the command center lets you type in commands, helpful for experimenting to see how they work.
Kicking The Tires: The Command Center
The command center accepts commands in three contexts: commands for the global Observer, or for commands sent to all ofthe individual Turtles or Patches as a group. You choose which sort of command you want via the small drop down menu. In the image below left we show the patches being selected. The center image shows the result of one command: "setpcolor (pxcor + pycor)" which simply sets the color (a number between 0 and 140) to the sum of the x and ycoordinates. Note that, because the command is going to all of the patches, the entire Graphics Window is changed. Sillybut illustrative! We then switch to Observer mode and reset the display and create 36 turtles with these two commands:"clear-patches" and "create-turtles 36". We then switch to Turtle mode, and do "set heading who *10" and "forward 15" which turns the turtles in all directions ("who" is the number of the turtle from 0 to 35) and thenhas them move forward 15 units, resulting in the image on the right.
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
1 of 8 7/20/12 1:33 AM
Programs are run using a very simple Logo-like language, along with an easy to use GUI forbuilding sliders, buttons, and graphs. To understand this a bit further, we'll use the (excellent!)documentation that came with the download. The index page is to the right. Use your browser tolook at the doc/index.html that came with your system.
Take some time to browse through the documentation. The three tutorial modules are quite good asare the three reference sections. Look at the Interface Guide .. it will show you all the visiblecomponents in a model, and explain how they are used. Then look at the Programming Guide .. itwill guide you through all of the NetLogo language features. Finally, the Primitives Dictionarygives detailed information on every language primitive. It will be your constant companion as youwrite models!
Buttons: A "Hello World" Model
In Stuart Kauffman's wonderful book "At Home in the Universe", he presents an exampleof a rapid "phase transition". This is modeled by a set of buttons which, during each turn,a random pair are chosen to be tied together.
Initially there are lots of isolated pairs tied together. Later threes, fours and abruptly thereis a steep transition to most of the buttons being tied together .. an emergent giant cluster. In the example shown here, there are 500 buttons and we plot 1000 turns. The rapidchange occurs at around the 1/4 mark where the number of threads is about half thenumber of buttons.
We can model this in NetLogo by having the buttons be turtles placed randomly on the graphicwindow. Each tick we will chose a pair of buttons, connecting them together and changingtheir color to be the same. At the end of each turn we will find the largest cluster, posting itssize.
Before we start, you can try the model in your browser, and browse the source code.
As we begin programming, use your "Open File" menu to open the docs/index.html that camewith your NetLogo download, and click on the Primitives Dictionary, so that you can look upthe NetLogo language keywords as we use them. On my system, it looks like this.
We will build our model in four phases, in order to make learning a simple, step-by-step process.
Initialization: Building the "button" agents and randomly placing them on the display1.Behavior: Building the procedure that ties a pair of buttons together, merging their two sets of buttons.2.Control: Building the GUI elements that control the setup and execution of the simulation3.Data: Building the GUI elements that show the data gathered by the simulation4.
The majority of the programming is done in steps 1 and 2, while the buttons and graphs are added in steps 3 and 4.
Buttons Phase 1: The Button Turtles and the setup Procedure
From the File menu chose "New". This will give us a "blank" new model with an empty graphics window and a commandcenter. Use the File menu's Save command to save the model on your disk in a convenient place. We'll use the nameButtons, which is stored with the extension ".nlogo" automatically. Ours looks like this.
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
2 of 8 7/20/12 1:33 AM
Click on the Procedures tab where the model program is built. It will look like this. It has one line:
; add model procedures here
The ";" begins a comment which goes to the end of the line. We'll delete this and begin by building the buttons agents. Ourfirst phase simply builds 500 turtles (buttons) and randomly places them on the screen. The source file is here and looks likethis, where we've added line numbers for reference:
1 globals [buttons] ; Global variables
2 to setup ; Initializes model for new run.3 set-default-shape turtles "circle" ; Turtles are circles4 clear-all ; Reset turtles and patches5 set buttons 500 ; Set number of buttons to 5006 create-turtles (buttons) ; Create "buttons" number of turtles7 ask turtles [setup-turtles] ; Initialize each turtle8 end
9 to setup-turtles ; Called for each turtle during setup10 setxy random screen-size-x random screen-size-y ; Set our x,y randomly11 end
Cut and paste the source into the (empty) procedures tab. It will look like the image on the rightwhen your are done. Note the color coding used to make it easier to understand the elements ofthe Logo language. In this case, language commands, like "set" or "ask" are blue, built-invariables are purple, literal numbers and strings are red, our variables and procedures are blackand structural keywords (globals, to, end) are dark green.
To compile the code, click on the Compile icon, or simply click on the Interface tab where we aregoing next. Anytime you exit the Procedures tab, it will automatically compile if needed.
To run the current code, click on the Interface tab. We have not built a GUI yet so will have to use theCommand Center like we did in the "Kicking the Tires" introduction above. Make sure the type-in area ofthe Command Center is in "Observer" mode (i.e. the left of the type-in area shows "O >"). A smalldrop-down menu is used to change between Observer, Turtle, and Patches, see the introduction above.
Click in the type-in area to the right of the "O >" symbol and type "setup". You can do this several times,getting a new random set of buttons each time.
Line 1 declares the global variable, "buttons", the number of buttons for this run of the model. Note that it is not declared asan integer variable, which it happens to be. NetLogo dynamically types variables as needed. And indeed, you can have thesame variable be a string, a list, an integer and so on during the execution of the program. Look up "globals" in the NetLogoPrimitives Dictionary by clicking on the "G" Alphabetical index, or by scrolling primitives frame, or by searching to theword "globals" using your browser's "Find". Also note the comments at the end of the line: everything past a ";" is acomment, just like C/C++ "//" comments or the shell's "#" comments.
Lines 2 and 8 ("to" and "end") enclose the definition of the procedure "setup". Line 3 sets theshape of the turtles to be circles rather than the default arrow-like shape. Line 4 initializes thesystem by killing all existing turtles, resetting all globals, and clearing the patches and plots. This lets us re-run the model multiple times. Line 5 sets the global "buttons" to be 500. Line6 creates that number of turtles. Line 7 then causes the procedure on line 9 to be called foreach turtle.
For each of the commands above, there is an entry in the Primitives Dictionary in thedocumentation. To the right we show the "clear-all" entry. The "ca" in the banner tells us thatwe can use ca as an abbreviation for clear-all. The eye-ball tells us that it executes in theobserver context (as discussed in the Command Center above). If you have any doubt how acommand works, just look it up!
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
3 of 8 7/20/12 1:33 AM
The "ask" command is special: it executes the command in each individual turtle's context. Thisexposes variables like "color, xcor" which can be set, and "who", which cannot be changed.
The documentation contains special entries for these variables. To the right we show the entryfor turtles. You can also check the variables for patches. There are also predefined variablesfor constants like "red" , "pi", and so on.
Just as Lines 2 and 8 enclose the procedure "setup", lines 9 and 11 enclose the procedure "setup-turtles". Line 10 is our firstcompound command which contains three simple commands, two instances of the "random" command and one instance ofthe "setxy" command. Calling "random integer-variable" returns a number between 0 and (integer-variable - 1). The "setxy"command takes two variables and sets the turtle's xcor and ycor (coordinate) values to these two numbers. Note that Logotypically uses these compound commands, much like Lisp and other sophisticated recursive languages.
The "setxy" statement introduces us to the coordinate system used by the turtlesand patches. This is discussed in Tutorial #1 in the Changing Graphics WindowSettings section. The origin, x=0, y=0, is in the center of the patches. This causesNetLogo to have the screen-size-x and screen-size-y to be an odd number of cells.
But in the setxy command, we use screen-size which is twice the edge length plusone for the center! This works because NetLogo wraps the coordinates around theedges. So when an X coordinate is one greater than the right edge, it really on thefar left edge. This means the NetLogo modeling space is actually a torus. This iscommon in modeling frameworks.
A similar style is applied to colors. Colors go from 0-140 as discussed in Tutorial#2 in the Working With Colors section. If you set a color beyond the 140 colors,they wrap as well. Thus color 150 is the same as color 10. This lets us use colorsequal to the "who" number of the turtles without error.
Buttons Phase 2: Adding Behavior, the "Go" procedure
Our first phase simply let us initialize our Buttons model. This phase adds the model's behavior of selecting pairs of buttonsand tying them together, one pair each step of the model. The "go" and "joinClusters" procedures contain the new code weneed. This phase completes most of the programming, the additional phases are primarily GUI building. Here is the newsource code, again shown below with reference line numbers:
1 globals [buttons] ; Global variables2 turtles-own [group] ; Each turtle has "group" as a variable
3 to setup ; Initializes model for new run.4 set-default-shape turtles "circle" ; Turtles are circles5 clear-all ; Reset turtles and patches6 set buttons 500 ; Set number of buttons to 5007 create-turtles (buttons) ; Create "buttons" number of turtles8 ask turtles [setup-turtles] ; Initialize each turtle9 end
10 to setup-turtles ; Called for each turtle during setup11 set group who ; Initialize "group" ins var to ID built-in12 setxy random screen-size-x random screen-size-y ; Set our x,y randomly13 end
14 to go ; Step the model once15 locals [g1 g2] ; This procedure has some temp local variables16 set g1 group-of turtle random buttons ; g1 & g2 are two group values17 set g2 group-of turtle random buttons ; chosen from two random turtles18 ask turtles [joinClusters g1 g2] ; Merge group g1 with group g219 end
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
4 of 8 7/20/12 1:33 AM
20 to joinClusters [g1 g2] ; Convert group g1 turtles into g2 turtles21 if (group = g1) [set group g2 set color color-of turtle g2]22 end
As we did before, lets start with your placing the new source code in the Procedures tab,as shown on the right (replacing all the earlier code). Click on the Interface tab (whichauto-compiles the code) which lets us use the Command Center. As before, enter"setup" to initialize the model. You can also run "go" a couple of times. But note thismakes little in the way of change.
To run the model several times, use the "repeat" command which takes a count and aprocedure. We'll use "repeat buttons [go]" to run it the number of times we havebuttons. On the left we have the results of such a run. Note that a considerable numberof the buttons now belong to a large cluster.
Line 2 adds a new variable, "group", to each turtle, using the "turtles-own" command. This is initialized in line 11, inside ourearlier "setup-turtles" procedure, to be the value of the turtle's "who" variable. Recall "who" is automatically assigned toturtles and cannot be changed. Thus each turtle starts out in a group of one, itself. This means there are no threads yet tiedbetween any of the turtles. These two lines are the only changes to our earlier procedures. The other changes are to add the"go" and "joinClusters" procedures.
As before, lines 14, 19, 20 and 22 enclose our two new procedures using "to" and "end" pairs. At line 15, the "go" procedureuses the "locals" primitive to declare two local variables. Local variables are only "visible" within the defining procedureand are thus temporary to the execution of the procedure. Line 16 is a compound command, using the "set", "-of", "turtle",and "random" primitives. The execution is from right to left. First, "random buttons" returns an integer between 0 andbuttons-1. Next, the "turtle" primitive uses this to return the turtle who's ID ("who" value) is equal to that random number. Next, the "group-of" command returns the "group" variable's value of that particular turtle. (Look at the -of primitive in thePrimitives Dictionary, under "O".) Finally, the "set" command stores the result in the "g1" local variable. Line 17 simplyrepeats this for a second time to get a second group value, "g2", to use.
Whew! These three lines could have been written:
locals [g1 who1 t1 g2 who2 t2] set who1 random buttons set t1 turtle who1 set g1 group-of t1 set who2 random buttons set t2 turtle who2 set g2 group-of t2
But as you become more adapt at NetLogo, you'll find the terse form far easier to read and understand.
Line 18 in the "go" procedure asks each turtle to execute the command: "joinClusters g1 g2". JoinClusters is the firstprocedure we have created with arguments passed to it (g1 & g2). The task of "joinClusters" is to make every turtle in groupg1 become a g2 member by setting its group value to g2 and its color to be the same as all the turtles of g2. It does this witha single line with several parts. It is easier to understand rewritten as follows:
if (group = g1) [ set group g2 set color color-of turtle g2 ]
The "if" primitive takes a boolean (true/false) expression and if it evaluates to true, executes the supplied procedure. The ()'sare not necessary but improve readability. Note that "a = b" does not mean "set a to b" but "does a equal b". The first line ofthe if statement's procedure simply sets the group variable of the turtle to be g2. The second statement is a compoundstatement: turtle g2 returns the turtle who's ID ("who" value) is g2. We then set the color of the current turtle to be the colorof turtle g2. This is a bit subtle: "turtle g2" is guaranteed to be in the g2 group because of the way we initialized the groupsto be turtle IDs. Thus its color is the color of the g2 group. Actually, we could just as simply set the merged group colors tobe "red" or some other value. We are simply trying to make all the turtles in groups g1 and g2 to look alike.
Buttons Phase 3: Graphic Controls
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
5 of 8 7/20/12 1:33 AM
By now, we've done all the hard programming parts: built a set of randombuttons and built the procedure to pick up a pair of buttons and join theirgroups. Phase 3 and 4 are the graphic parts: providing controls and inputparameters, and providing outputs showing the results of the model.
You'll be delighted to hear that for this phase, we actually take two linesof code out of the program! We do this by placing a ";" in front of lines 1and 6 above, see the Procedures window to the left. Go ahead and dothis.
Initially this will cause an error, see Error window, right. Don't panic! Itsimportant to see how NetLogo handles errors, so lets dwell on this a bit.
When you commented out the two lines above, it left NetLogo not knowing about the"buttons" variable which tells us how many buttons to use. When you click to leave theProcedures tab, or you click the compile icon, NetLogo finds the error, and automaticallyopens the Error tab, with the error highlighted in blue, and explained in yellow. You can stillgo the Interface tab, but to help you remember you're in an error state, both the Procedurestab and Errors tab will be highlighted red.
So how do we fix the error? NetLogo's sliders both declare a global variable and set its value ..exactly the two lines we commented out. To make our own slider, go to the Interface tab andclick the slider control as shown on the right.
When we click on the slider control button, we are presented with a cross-hair cursor, askingwhere on the window to place the slider. After we click, we get an "empty" slider and anediting window.
On the right we show our entering "buttons" as the global variable name associated with thisslider, thus fixing the error. We also set 100, 100, 1000 as the Minimum, Increment, andMaximum values for the slider, and 500 for its current value. Go ahead and do this now. Afteryou are done, you can compile the program without error by entering the Procedures tab andclicking on the compile icon.
After creating the slider, it can be moved and resized by selecting it: click in the white part of the window and drag over theslider. By then clicking on the edit icon, you can also edit the parameters you set up when you made the slider initially.
At this point, you can run the program as you did in Phase 2: using the Command Center for entering "setup" and "go"commands, while using the slider to control the number of buttons used. The rest of this section will add two buttons toreplace this use of the Command Center
First, we'll add a NetLogo button to call "setup". To do this, in the Interface Tab, click the Button icon,and with the cross-hair cursor, click where you want to place the "setup" button. Put "setup" in theresulting dialog's code box. This will default to being the display name as well. Each click willre-initialize the buttons.
Similarly, create a "go" button, with the additional step of checking the "Forever" check box, causing it torepeat indefinitely (until the stop command above). We can now run the model easily without thecommand center.
Next, we'll generate graphical data for the simulation.
Buttons Phase 4: Graphical Results
To complete the simulation, we'll add three graphical data outputs: a plot of the number of buttons in the largest group, thecurrent tick count, and the current largest cluster. Here is the new source code which contains just 9 new lines. Save yourPhase 3 model and then cut and paste the new source into the Procedures window.
1 globals [ClusterSz ticks] ; Global variables2 turtles-own [group] ; Each turtle has "group" as a variable
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
6 of 8 7/20/12 1:33 AM
3 to setup ; Initializes model for new run.4 set-default-shape turtles "circle" ; Turtles are circles5 clear-all ; Reset turtles and patches6 set ticks 0 ; Initialize ticks global to 07 set ClusterSz 1 ; Initialize ClusterSz global to 18 set-plot-y-range 0 buttons ; Set Y axis to be 0 .. "buttons" tall9 create-turtles (buttons) ; Create "buttons" number of turtles10 ask turtles [setup-turtles] ; Initialize each turtle11 end
12 to setup-turtles ; Called for each turtle during setup13 set group who ; Initialize "group" ins var to ID built-in14 setxy random screen-size-x random screen-size-y ; Set our x,y randomly15 end
16 to go ; Step the model once17 locals [g1 g2 thisClusterSz] ; This procedure has some temp local variables18 set g1 group-of turtle random buttons ; g1 & g2 are two group values19 set g2 group-of turtle random buttons ; chosen from two random turtles20 ask turtles [joinClusters g1 g2] ; Merge group g1 with group g2
21 set thisClusterSz (count turtles with [group = g2]) ; Calculate merged size22 set ClusterSz (max list ClusterSz thisClusterSz) ; Update global max size23 plot ClusterSz ; Plot current max cluster size24 set ticks (ticks + 1) ; Keep track of number of steps25 if (ClusterSz = buttons) [stop] ; Stop if we have one huge cluster26 end
27 to joinClusters [g1 g2] ; Convert group g1 turtles into g2 turtles28 if (group = g1) [set group g2 set color color-of turtle g2]29 end
Compiling this code will not create an error. But when the "setup" button is clicked, we get a run-timeerror.
This is caused by our not yet having a plot window, thus the "set-plot-y-range" command fails. We'llsolve this by adding the NetLogo plot GUI item.
But first, lets look at the changes in the final version of the program's source code.
Line 1 adds two global variables we will use to monitor the simulation: "clusterSz" and "ticks". ClusterSz is the number ofbuttons in the largest group of buttons. We initialize this to 1 in line 7. Ticks is the number of times we've run the "go"procedure. We initialize this to 0 in line 6. Line 8 initializes the plot we are about to build to have the Y axis go from 0 tobuttons, the size of the largest cluster when all buttons are connected to each other.
Lines 21-25 manage clusterSz and ticks in the go procedure. Line 21 sets a local variable, "thisClusterSz", to be the size ofthe newly merged two groups of buttons. The phrase "turtles with [group = g2] returns the set of turtles who's group variableis g2. The "count" primitive returns the number of turtles in this set, which is used to set the value of thisClusterSz. Theglobal variable clusterSz is then set to the maximum value of itself and the local thisClusterSz. Line 23 adds the new value ofClusterSz to the plot. Line 24 simply increments the "ticks" global variable. Finally, line 25 halts the program when we'vereached the point where all the buttons are in the same group.
Just as with the slider, we click on the Plot icon, get a cross-hair cursor for placing theplot, and a plot editing window appears for setting the plot parameters.
We make four changes: fill in the Name to Cluster Size, X Axis Label to Steps, Y AxisLabel to Cluster and set the X Max Value to 1000.
To use the new plot item, click setup, then go, and watch the plot grow over time.
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
7 of 8 7/20/12 1:33 AM
To create the ClusterSz display, click on the Monitor icon, then clicking where you want to place thedisplay. In the resulting dialog, enter "ClusterSz" in the "reporter" box. (A Reporter in NetLogo is anyvalue or procedure returning a value).
Similarly create the "ticks" monitor which shows how many times the simulation "go" procedure hasbeen run.
To make the model clearer for the user, we'll clean up the layout a bit mymoving and resizing our GUI items, and adding two text items.
First, select and drag the buttons and slider down enough to leave a whitespace for a text label. Repeat for the two monitors and the plot, resizing theplot as shown. This separates the controls from the data items, leaving spacefor labels. Create two Text items describing the new layout, see details onthe right.
The final results appear like the image to the left.
Summary and Home Work!
In this fairly elementary (only 29 lines of code, after all!) NetLogo tutorial, we've tried several things:
Downloaded and installed the NetLogo system from the web.Ran two NetLogo simulations (Peer Net and Buttons) as applets from a web site.Used the Command Center to "kick the tires" .. exercise simple patch and turtle commands.Used the (excellent!) NetLogo documentation to learn the language and how models work.Created the Buttons simulation in four phasesLearned about both compile and run-time errors and how to solve them
Here are a few explorations you can try for your next steps into NetLogo
Add a "step" button which calls the "go" procedure, but only once rather than continuously.1.Look at the Information tab. Fill it out for this model. This will appear in the model if you send it to someone thereforeis very useful! And it will be included in the web page you are going to make in 5 below.
2.
Create the initial plot with an X axis length of 2*buttons. Thus if buttons is set to 700, the X axis will go from 0 to1400.
3.
Our current model lets multiple buttons exist on a single patch. Change the program to allow only one turtle to exist ona given patch (x, y location). Hint: use the "turtles-at" or "turtles-here" style commands. Or simply ask a randomnumber of patches to create the initial turtles. This is the "best practice" method.
4.
Use "Save as Applet" from the file menu. This will create an html file that will include the current model in the webpage as an applet, along with explanatory information as to how to deploy it. It will include the information from theInformation tab. Make sure you copy the NetLogoLite.jar file to where you put your applet! It contains the reducedNetLogo jar file appropriate for a web based model.
5.
Our current model can pick up the same button and connect it to itself! Change the program so that this does nothappen.
6.
Our current model randomly merges two groups of buttons. Change the model to merge the smaller group into thelarger one. Hint: use "count turtles with [..]" twice to figure out which of g1 or g2 is larger.
7.
Extra Credit: Most models have the agents move during the simulation. Using many of the above explorations, I've addedmotion to the model. In this version of the model, the two groups being joined together move towards each other if there isan empty space available. For your extra credit asignment, try using this version of the model, and read the code tounderstand how the motion was achieved.
Feel free to contact me if you run into difficulties or have suggestions for improving the tutorial!
First Steps with NetLogo http://complexityworkshop.com/cw/tutorial/NetLogo/
8 of 8 7/20/12 1:33 AM
Recommended