Sei sulla pagina 1di 52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

ProgrammingGuide
NetLogo5.3.1UserManual

ThissectiondescribestheNetLogoprogramminglanguageindetail.
TheCodeExamplemodelsmentionedthroughoutcanbefoundintheCodeExamples
sectionoftheModelsLibrary.
Agents
Procedures
Variables
Tickcounter
Colors
Ask
Agentsets
Breeds
Buttons
Lists
Math
Randomnumbers
Turtleshapes
Linkshapes
Viewupdates
Plotting
Strings
Output
FileI/O
Movies
Perspective
Drawing
Topology
Links
Tasks
AskConcurrent
Tie
Multiplesourcefiles
Syntax

Agents
TheNetLogoworldismadeupofagents.Agentsarebeingsthatcanfollowinstructions.
InNetLogo,therearefourtypesofagents:turtles,patches,links,andtheobserver.
Turtlesareagentsthatmovearoundintheworld.Theworldistwodimensionalandis
dividedupintoagridofpatches.Eachpatchisasquarepieceof"ground"overwhich
turtlescanmove.Linksareagentsthatconnecttwoturtles.Theobserverdoesn'thavea
locationyoucanimagineitaslookingoutovertheworldofturtlesandpatches.
Theobserverdoesn'tobservepassivelyitgivesinstructionstotheotheragents.
WhenNetLogostartsup,therearenoturtles.Theobservercanmakenewturtles.
https://ccl.northwestern.edu/netlogo/docs/programming.html

1/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Patchescanmakenewturtlestoo.(Patchescan'tmove,butotherwisethey'rejustas
"alive"asturtles.)
Patcheshavecoordinates.Thepatchatcoordinates(0,0)iscalledtheoriginandthe
coordinatesoftheotherpatchesarethehorizontalandverticaldistancesfromthisone.
Wecallthepatch'scoordinatespxcorandpycor.Justlikeinthestandardmathematical
coordinateplane,pxcorincreasesasyoumovetotherightandpycorincreasesasyou
moveup.
Thetotalnumberofpatchesisdeterminedbythesettingsmin-pxcor,max-pxcor,minpycor,andmax-pycorWhenNetLogostartsup,min-pxcor,max-pxcor,min-pycor,andmaxpycorare16,16,16,and16respectively.Thismeansthatpxcorandpycorbothrange
from16to16,sothereare33times33,or1089patchestotal.(Youcanchangethe
numberofpatcheswiththeSettingsbutton.)
Turtleshavecoordinatestoo:xcorandycor.Apatch'scoordinatesarealwaysintegers,
butaturtle'scoordinatescanhavedecimals.Thismeansthataturtlecanbepositionedat
anypointwithinitspatchitdoesn'thavetobeinthecenterofthepatch.
Linksdonothavecoordinates.Everylinkhastwoends,andeachendisaturtle.Ifeither
turtledies,thelinkdiestoo.Alinkisrepresentedvisuallyasalineconnectingthetwo
turtles.

Procedures
InNetLogo,commandsandreporterstellagentswhattodo.Acommandisanactionfor
anagenttocarryout,resultinginsomeeffect.Areporterisinstructionsforcomputinga
value,whichtheagentthen"reports"towhoeveraskedit.
Typically,acommandnamebeginswithaverb,suchas"create","die","jump","inspect",
or"clear".Mostreporternamesarenounsornounphrases.
CommandsandreportersbuiltintoNetLogoarecalledprimitives.TheNetLogo
Dictionaryhasacompletelistofbuiltincommandsandreporters.
Commandsandreportersyoudefineyourselfarecalledprocedures.Eachprocedurehas
aname,precededbythekeywordtoorto-report,dependingonwhetheritisa
commandprocedureorareporterprocedure.Thekeywordendmarkstheendofthe
commandsintheprocedure.Onceyoudefineaprocedure,youcanuseitelsewherein
yourprogram.
Manycommandsandreporterstakeinputsvaluesthatthecommandorreporteruses
incarryingoutitsactionsorcomputingitsresult.
Herearetwocommandprocedures:
to setup
clear-all
create-turtles 10
reset-ticks
end
to go
ask turtles [
fd 1

;; forward 1 step

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

2/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

rt random 10
lt random 10

]
tick
end

;; turn right
;; turn left

Notetheuseofsemicolonstoadd"comments"totheprogram.Commentscanmakeyour
codeeasiertoreadandunderstand,buttheydon'taffectitsbehavior.
Inthisprogram,
setupandgoareuserdefinedcommands.
clear-all,create-turtles,reset-ticks,ask,lt("leftturn"),rt("rightturn")and
tick,areallprimitivecommands.
randomandturtlesareprimitivereporters.randomtakesasinglenumberasaninput

andreportsarandomintegerthatislessthantheinput(inthiscase,between0and
9).turtlesreportstheagentsetconsistingofalltheturtles.(We'llexplainabout
agentsetslater.)
setupandgocanbecalledbyotherprocedures,orbybuttons,orfromtheCommand

Center.
ManyNetLogomodelshaveaoncebuttonthatcallsaprocedurecalledsetupanda
foreverbuttonthatcallsaprocedurecalledgo.
InNetLogo,youmayspecifywhichagentsturtles,patches,orlinksaretoruneach
command.Ifyoudon'tspecify,thecodeisrunbytheobserver.Inthecodeabove,the
observerusesasktomakethesetofallturtlesrunthecommandsbetweenthesquare
brackets.
clear-allandcreate-turtlescanonlyberunbytheobserver.fd,ontheotherhand,can
onlyberunbyturtles.Someothercommandsandreporters,suchassetandticks,can

berunbydifferentagenttypes.
Herearesomemoreadvancedfeaturesyoucantakeadvantageofwhendefiningyour
ownprocedures.
Procedureswithinputs
Procedurescantakeinputs,justlikemanyprimitivesdo.Tocreateaprocedurethat
acceptsinputs,puttheirnamesinsquarebracketsaftertheprocedurename.For
example:
to draw-polygon [num-sides len] ;; turtle procedure
pen-down
repeat num-sides [
fd len
rt 360 / num-sides
]
end

Elsewhereintheprogram,youmightusetheprocedurebyaskingtheturtlestoeachdraw
anoctagonwithasidelengthequaltoitswhonumber:
ask turtles [ draw-polygon 8 who ]
https://ccl.northwestern.edu/netlogo/docs/programming.html

3/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Reporterprocedures
Justlikeyoucandefineyourowncommands,youcandefineyourownreporters.You
mustdotwospecialthings.First,useto-reportinsteadoftotobeginyourprocedure.
Then,inthebodyoftheprocedure,usereporttoreportthevalueyouwanttoreport.
to-report absolute-value [number]
ifelse number >= 0
[ report number ]
[ report (- number) ]
end

Variables
Agentvariables
Agentvariablesareplacestostorevalues(suchasnumbers)inanagent.Anagent
variablecanbeaglobalvariable,aturtlevariable,apatchvariable,oralinkvariable.
Ifavariableisaglobalvariable,thereisonlyonevalueforthevariable,andeveryagent
canaccessit.Youcanthinkofglobalvariablesasbelongingtotheobserver.
Turtle,patch,andlinkvariablesaredifferent.Eachturtlehasitsownvalueforeveryturtle
variable.Thesamegoesforpatchesandlinks.
SomevariablesarebuiltintoNetLogo.Forexample,allturtlesandlinkshaveacolor
variable,andallpatcheshaveapcolorvariable.(Thepatchvariablebeginswith"p"soit
doesn'tgetconfusedwiththeturtlevariable,sinceturtleshavedirectaccesstopatch
variables.)Ifyousetthevariable,theturtleorpatchchangescolor.(Seenextsectionfor
details.)
Otherbuiltinturtlevariablesincludingxcor,ycor,andheading.Otherbuiltinpatch
variablesincludepxcorandpycor.(Thereisacompletelisthere.)
Youcanalsodefineyourownvariables.Youcanmakeaglobalvariablebyaddinga
switch,slider,chooser,orinputboxtoyourmodel,orbyusingtheglobalskeywordatthe
beginningofyourcode,likethis:
globals [score]

Youcanalsodefinenewturtle,patchandlinkvariablesusingtheturtles-own,patchesownandlinks-ownkeywords,likethis:
turtles-own [energy speed]
patches-own [friction]
links-own [strength]

Thesevariablescanthenbeusedfreelyinyourmodel.Usethesetcommandtoset
them.(Anyvariableyoudon'tsethasastartingvalueofzero.)
https://ccl.northwestern.edu/netlogo/docs/programming.html

4/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Globalvariablescanbereadandsetatanytimebyanyagent.Aswell,aturtlecanread
andsetpatchvariablesofthepatchitisstandingon.Forexample,thiscode:
ask turtles [ set pcolor red ]

causeseveryturtletomakethepatchitisstandingonred.(Becausepatchvariablesare
sharedbyturtlesinthisway,youcan'thaveaturtlevariableandapatchvariablewiththe
samename.)
Inothersituationswhereyouwantanagenttoreadadifferentagent'svariable,youcan
useof.Example:
show [color] of turtle 5
;; prints current color of turtle with who number 5

Youcanalsouseofwithamorecomplicatedexpressionthanjustavariablename,for
example:
show [xcor + ycor] of turtle 5
;; prints the sum of the x and y coordinates of
;; turtle with who number 5

Localvariables
Alocalvariableisdefinedandusedonlyinthecontextofaparticularprocedureorpartof
aprocedure.Tocreatealocalvariable,usetheletcommand.Ifyouuseletatthetopof
aprocedure,thevariablewillexistthroughouttheprocedure.Ifyouuseitinsideasetof
squarebrackets,forexampleinsidean"ask",thenitwillexistonlyinsidethosebrackets.
to swap-colors [turtle1 turtle2]
let temp [color] of turtle1
ask turtle1 [ set color [color] of turtle2 ]
ask turtle2 [ set color temp ]
end

Tickcounter
InmanyNetLogomodels,timepassesindiscretesteps,called"ticks".NetLogoincludesa
builtintickcountersoyoucankeeptrackofhowmanytickshavepassed.
Thecurrentvalueofthetickcounterisshownabovetheview.(YoucanusetheSettings
buttontohidethetickcounter,orchangetheword"ticks"tosomethingelse.)
Incode,toretrievethecurrentvalueofthetickcounter,usetheticksreporter.Thetick
commandadvancesthetickcounterby1.Theclear-allcommandclearsthetickcounter
alongwitheverythingelse.
Whenthetickcounterisclear,it'sanerrortotrytoreadormodifyit.Usethereset-ticks
commandwhenyourmodelisdonesettingup,tostartthetickcounter.
Ifyourmodelissettousetickbasedupdates,thenthetickcommandwillusuallyalso
https://ccl.northwestern.edu/netlogo/docs/programming.html

5/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

updatetheview.Seethelatersection,ViewUpdates.

Whentotick
Usereset-ticksattheendofyoursetupprocedure.
Usetickattheendofyourgoprocedure.
to setup
clear-all
create-turtles 10
reset-ticks
end
to go
ask turtles [ fd 1 ]
tick
end

Fractionalticks
Inmostmodels,thetickcounterstartsat0andgoesup1atatime,fromintegerto
integer.Butit'salsopossibleforthetickcountertotakeoninbetweenfloatingpoint
values.
Toadvancethetickcounterbyafractionalamount,usethetick-advancecommand.This
commandtakesanumericinputspecifyinghowfartoadvancethetickcounter.
Atypicaluseoffractionalticksistoapproximatecontinuousorcurvedmotion.See,for
example,theGasLabmodelsintheModelsLibrary(underChemistry&Physics).These
modelscalculatetheexacttimeatwhichafutureeventistooccur,thenadvancethetick
countertoexactlythattime.

Colors
NetLogorepresentscolorsindifferentways.Acolorcanbenumberintherange0to140,
withtheexceptionof140itself.Belowisachartshowingtherangeofsuchcolorsyoucan
useinNetLogo.

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

6/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Thechartshowsthat:
Someofthecolorshavenames.(Youcanusethesenamesinyourcode.)
Everynamedcolorexceptblackandwhitehasanumberendingin5.
Oneithersideofeachnamedcoloraredarkerandlightershadesofthecolor.
0ispureblack.9.9ispurewhite.
10,20,andsoonareallsodarktheyareverynearlyblack.
19.9,29.9andsoonareallsolighttheyareverynearlywhite.
CodeExample:ThecolorchartwasmadeinNetLogowiththeColorChart
Examplemodel.
Ifyouuseanumberoutsidethe0to140range,NetLogowillrepeatedlyaddorsubtract
140fromthenumberuntilitisinthe0to140range.Forexample,25isorange,so165,
305,445,andsoonareorangetoo,andsoare115,255,395,etc.Thiscalculationis
doneautomaticallywheneveryousettheturtlevariablecolororthepatchvariable
pcolor.Shouldyouneedtoperformthiscalculationinsomeothercontext,usethewrapcolorprimitive.
Ifyouwantacolorthat'snotonthechart,moreexistbetweentheintegers.Forexample,
26.5isashadeoforangehalfwaybetween26and27.Thisdoesn'tmeanyoucanmake
anycolorinNetLogotheNetLogocolorspaceisonlyasubsetofallpossiblecolors.It
containsonlyafixedsetofdiscretehues(onehueperrowofthechart).Startingfromone
ofthosehues,youcaneitherdecreaseitsbrightness(darkenit)ordecreaseitssaturation
(lightenit),butyoucannotdecreasebothbrightnessandsaturation.Also,onlythefirst
digitafterthedecimalpointissignificant.Thus,colorvaluesareroundeddowntothenext
https://ccl.northwestern.edu/netlogo/docs/programming.html

7/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

0.1,soforexample,there'snovisibledifferencebetween26.5and26.52or26.58.
Colorprimitives
Thereareafewprimitivesthatarehelpfulforworkingwithcolors.
Wehavealreadymentionedthewrap-colorprimitive.
Thescale-colorprimitiveisusefulforconvertingnumericdataintocolors.
shade-of?willtellyouiftwocolorsareboth"shades"ofthesamebasichue.Forexample,
shade-of? orange 27istrue,because27isalightershadeoforange.

CodeExample:ScalecolorExampledemonstratesthescalecolorreporter.
RGBandRGBAColors
NetLogoalsorepresentscolorsasRGB(red/green/blue)listsandRGBA
(red/green/blue/alpha)lists.WhenusingRGBcolorsthefullrangeofcolorsisavailableto
you.RGBAcolorsallowallthecolorsthatRGBallowsandyoucanalsovarythe
transparencyofacolor.RGBandRGBAlistsaremadeupofthreeorfourintegers,
respectively,between0and255ifanumberisoutsidethatrange255isrepeatedly
subtracteduntilitisintherange.YoucansetanycolorvariablesinNetLogo(colorfor
turtlesandlinksandpcolorforpatches)toanRGBlistandthatagentwillberendered
appropriately.Soyoucansetthecolorofpatch00topureredusingthefollowingcode:
set pcolor [255 0 0]

Turtles,links,andlabelscanallcontainRGBAlistsastheircolorvariables,however,
patchescannothaveRGBApcolorsYoucansetthecolorofaturtletobeapproximately
halftransparentpureredwiththefollowingcode:
set color [255 0 0 125]

YoucanconvertfromaNetLogocolortoRGBorHSB(hue/saturation/brightness)using
extract-hsbandextract-rgb.Youcanusergbtogeneratergblistsandhsbtoconvert
fromanHSBcolortoRGB.
SincemanycolorsaremissingfromtheNetLogocolorspace,approximate-hsband
approximate-rgboftencan'tgiveyoutheexactcoloryouaskfor,buttheytrytocomeas
closeaspossible.
Example:youcanchangeanyturtlefromit'sexistingNetLogocolortoahalftransparent
versionofthatcolorusing:
set color lput 125 extract-rgb color

CodeExamples:HSBandRGBExample(letsyouexperimentwiththeHSB
andRGBcolorsystems),TransparencyExample
https://ccl.northwestern.edu/netlogo/docs/programming.html

8/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

ColorSwatchesdialog
TheColorSwatchesdialoghelpsyouexperimentwithandchoosecolors.Openitby
choosingColorSwatchesontheToolsMenu.

Whenyouclickonacolorswatch(oracolorbutton),thatcolorwillbeshownagainst
othercolors.Inthebottomleft,thecodeforthecurrentlyselectedcolorisdisplayed(for
example,red + 2)soyoucancopyandpasteitintoyourcode.Onthebottomrightthere
arethreeincrementoptions,1,0.5,and0.1.Thesenumbersindicatethedifference
betweentwoadjacentswatches.Whentheincrementis1thereare10differentshadesin
eachrowwhentheincrementis0.1thereare100differentshadesineachrow.0.5isan
intermediatesetting.

Ask
NetLogousestheaskcommandtogivecommandstoturtles,patches,andlinks.Allcode
toberunbyturtlesmustbelocatedinaturtle"context".Youcanestablishaturtlecontext
inanyofthreeways:
Inabutton,bychoosing"Turtles"fromthepopupmenu.Anycodeyouputinthe
buttonwillberunbyallturtles.
IntheCommandCenter,bychoosing"Turtles"fromthepopupmenu.Any
commandsyouenterwillberunbyalltheturtles.
Byusingask turtles,hatch,orothercommandswhichestablishaturtlecontext.
Thesamegoesforpatches,links,andtheobserver,exceptthatyoucannotaskthe
observer.Anycodethatisnotinsideanyaskisbydefaultobservercode.
Here'sanexampleoftheuseofaskinaNetLogoprocedure:
https://ccl.northwestern.edu/netlogo/docs/programming.html

9/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

to setup
clear-all
create-turtles 100 ;; create 100 turtles with random headings
ask turtles
[ set color red
;; turn them red
fd 50 ]
;; spread them around
ask patches
[ if pxcor > 0
;; patches on the right side
[ set pcolor green ] ] ;; of the view turn green
reset-ticks
end

ThemodelsintheModelsLibraryarefullofotherexamples.Agoodplacetostartlooking
isintheCodeExamplessection.
Usually,theobserverusesasktoaskallturtles,allpatchesoralllinkstoruncommands.
Youcanalsouseasktohaveanindividualturtle,patchorlinkruncommands.The
reportersturtle,patch,linkandpatch-atareusefulforthistechnique.Forexample:
to setup
clear-all
crt 3
;; make 3 turtles
ask turtle 0
;; tell the first one...
[ fd 1 ]
;; ...to go forward
ask turtle 1
;; tell the second one...
[ set color green ]
;; ...to become green
ask turtle 2
;; tell the third one...
[ rt 90 ]
;; ...to turn right
ask patch 2 -2
;; ask the patch at (2,-2)
[ set pcolor blue ]
;; ...to become blue
ask turtle 0
;; ask the first turtle
[ ask patch-at 1 0
;; ...to ask patch to the east
[ set pcolor red ] ]
;; ...to become red
ask turtle 0
;; tell the first turtle...
[ create-link-with turtle 1 ] ;; ...make a link with the second
ask link 0 1
;; tell the link between turtle 0 and 1
[ set color blue ]
;; ...to become blue
reset-ticks
end

Everyturtlecreatedhasawhonumber.Thefirstturtlecreatedisnumber0,thesecond
turtlenumber1,andsoforth.
Theturtleprimitivereportertakesawhonumberasaninput,andreportstheturtlewith
thatwhonumber.Thepatchprimitivereportertakesvaluesforpxcorandpycorand
reportsthepatchwiththosecoordinates.Thelinkprimitivetakestwoinputs,thewho
numbersofthetwoturtlesitconnects.Andthepatch-atprimitivereportertakesoffsets:
distances,inthexandydirections,fromthefirstagent.Intheexampleabove,theturtle
withwhonumber0isaskedtogetthepatcheast(andnopatchesnorth)ofitself.
Youcanalsoselectasubsetofturtles,orasubsetofpatches,orasubsetoflinksand
askthemtodosomething.Thisinvolvesusingagentsets.Thenextsectionexplainsthem
indetail.
Whenyouaskasetofagentstorunmorethanonecommand,eachagentmustfinish
beforethenextagentstarts.Oneagentrunsallofthecommands,thenthenextagent
runsallofthem,andsoon.Forexample,ifyouwrite:
https://ccl.northwestern.edu/netlogo/docs/programming.html

10/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

ask turtles
[ fd 1
set color red ]

firstoneturtlemovesandturnsred,thenanotherturtlemovesandturnsred,andsoon.
Butifyouwriteitthisway:
ask turtles [ fd 1 ]
ask turtles [ set color red ]

firstalltheturtlesmove,thentheyallturnred.

Agentsets
Anagentsetisexactlywhatitsnameimplies,asetofagents.Anagentsetcancontain
eitherturtles,patchesorlinks,butnotmorethanonetypeatonce.
Anagentsetisnotinanyparticularorder.Infact,it'salwaysinarandomorder.Andevery
timeyouuseit,theagentsetisinadifferentrandomorder.Thishelpsyoukeepyour
modelfromtreatinganyparticularturtles,patchesorlinksdifferentlyfromanyothers
(unlessyouwantthemtobe).Sincetheorderisrandomeverytime,nooneagentalways
getstogofirst.
You'veseentheturtlesprimitive,whichreportstheagentsetofallturtles,thepatches
primitive,whichreportstheagentsetofallpatchesandthelinksprimitivewhichreports
theagentsetofalllinks.
Butwhat'spowerfulabouttheagentsetconceptisthatyoucanconstructagentsetsthat
containonlysometurtles,somepatchesorsomelinks.Forexample,alltheredturtles,or
thepatcheswithpxcorevenlydivisiblebyfive,ortheturtlesinthefirstquadrantthatare
onagreenpatchorthelinksconnectedtoturtle0.Theseagentsetscanthenbeusedby
askorbyvariousreportersthattakeagentsetsasinputs.
Onewayistouseturtles-hereorturtles-at,tomakeanagentsetcontainingonlythe
turtlesonmypatch,oronlytheturtlesonsomeotherpatchatsomexandyoffsets.
There'salsoturtles-onsoyoucangetthesetofturtlesstandingonagivenpatchorset
ofpatches,orthesetofturtlesstandingonthesamepatchasagiventurtleorsetof
turtles.
Herearesomemoreexamplesofhowtomakeagentsets:
;; all other turtles:
other turtles
;; all other turtles on this patch:
other turtles-here
;; all red turtles:
turtles with [color = red]
;; all red turtles on my patch
turtles-here with [color = red]
;; patches on right side of view
patches with [pxcor > 0]
;; all turtles less than 3 patches away
https://ccl.northwestern.edu/netlogo/docs/programming.html

11/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

turtles in-radius 3
;; the four patches to the east, north, west, and south
patches at-points [[1 0] [0 1] [-1 0] [0 -1]]
;; shorthand for those four patches
neighbors4
;; turtles in the first quadrant that are on a green patch
turtles with [(xcor > 0) and (ycor > 0)
and (pcolor = green)]
;; turtles standing on my neighboring four patches
turtles-on neighbors4
;; all the links connected to turtle 0
[my-links] of turtle 0

Notetheuseofothertoexcludethisagent.Thisiscommon.
Onceyouhavecreatedanagentset,herearesomesimplethingsyoucando:
Useasktomaketheagentsintheagentsetdosomething
Useany?toseeiftheagentsetisempty
Useall?toseeifeveryagentinanagentsetsatisfiesacondition.
Usecounttofindoutexactlyhowmanyagentsareintheset
Andherearesomemorecomplexthingsyoucando:
Pickarandomagentfromthesetusingone-of.Forexample,wecanmakea
randomlychosenturtleturngreen:
ask one-of turtles [ set color green ]

Ortellarandomlychosenpatchtosproutanewturtle:
ask one-of patches [ sprout 1 ]

Usethemax-one-oformin-one-ofreporterstofindoutwhichagentisthemostor
leastalongsomescale.Forexample,toremovetherichestturtle,youcouldsay
ask max-one-of turtles [sum assets] [ die ]

Makeahistogramoftheagentsetusingthehistogramcommand(incombination
withof).
Useoftomakealistofvalues,oneforeachagentintheagentset.Thenuseoneof
NetLogo'slistprimitivestodosomethingwiththelist.(Seethe"Lists"section
below.)Forexample,tofindouthowrichturtlesareontheaverage,youcouldsay
show mean [sum assets] of turtles

Useturtle-set,patch-setandlink-setreporterstomakenewagentsetsby
gatheringtogetheragentsfromavarietyofpossiblesources.
Useno-turtles,no-patchesandno-linksreporterstomakeemptyagentsets.
Checkwhethertwoagentsetsareequalusing=or!=.
Usemember?toseewhetheraparticularagentisamemberofanagentset.
Thisonlyscratchesthesurface.SeetheModelsLibraryformanymoreexamples,and
https://ccl.northwestern.edu/netlogo/docs/programming.html

12/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

consulttheNetLogoDictionaryformoreinformationaboutalloftheagentsetprimitives.
Moreexamplesofusingagentsetsareprovidedintheindividualentriesforthese
primitivesintheNetLogoDictionary.

Specialagentsets
Theagentsetsturtlesandlinkshavespecialbehaviorbecausetheyalwaysholdthe
setsofallturtlesandalllinks.Therefore,theseagentsetscangrow.
Thefollowinginteractionshowsthespecialbehavior.AssumetheCodetabhasglobals
[g].Then:
observer> clear-all
observer> create-turtles 5
observer> set g turtles
observer> print count g
5
observer> create-turtles 5
observer> print count g
10
observer> set g turtle-set turtles
observer> print count g
10
observer> create-turtles 5
observer> print count g
10
observer> print count turtles
15

Theturtlesagentsetgrowswhennewturtlesareborn,butotheragentsetsdon'tgrow.If
Iwriteturtle-set turtles,Igetanew,normalagentsetcontainingjusttheturtlesthat
currentlyexist.Newturtlesdon'tjoinwhenthey'reborn.
Breedagentsetsarespecialinthesamewayasturtlesandlinks.Breedsare
introducedandexplainedbelow.

Agentsetsandlists
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomorderevery
time.Ifyouneedyouragentstodosomethinginafixedorder,youneedtomakealistof
theagentsinstead.SeetheListssectionbelow.
CodeExample:AskOrderingExample

Breeds
NetLogoallowsyoutodefinedifferent"breeds"ofturtlesandbreedsoflinks.Onceyou
havedefinedbreeds,youcangoonandmakethedifferentbreedsbehavedifferently.For
example,youcouldhavebreedscalledsheepandwolves,andhavethewolvestrytoeat
thesheeporyoucouldhavelinkbreedscalledstreetsandsidewalkswherefoottrafficis
https://ccl.northwestern.edu/netlogo/docs/programming.html

13/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

routedonsidewalksandcartrafficisroutedonstreets.
Youdefineturtlebreedsusingthebreedkeyword,atthetopoftheCodetab,beforeany
procedures:
breed [wolves wolf]
breed [sheep a-sheep]

Youcanrefertoamemberofthebreedusingthesingularform,justliketheturtle
reporter.Whenprinted,membersofthebreedwillbelabeledwiththesingularname.
Somecommandsandreportershavethepluralnameofthebreedinthem,suchas
create-<breeds>.Othershavethesingularnameofthebreedinthem,suchas<breed>
Theorderinwhichbreedsaredeclaredisalsotheorderinwhichtheyarelayeredinthe
view.Sobreedsdefinedlaterwillappearontopofbreedsdefinedearlierinthisexample,
sheepwillbedrawnoverwolves.
Whenyoudefineabreedsuchassheep,anagentsetforthatbreedisautomatically
created,sothatalloftheagentsetcapabilitiesdescribedaboveareimmediatelyavailable
withthesheepagentset.
Thefollowingnewprimitivesarealsoautomaticallyavailableonceyoudefineabreed:
create-sheep,hatch-sheep,sprout-sheep,sheep-here,sheep-at,sheep-on,andis-asheep?.
Also,youcanusesheep-owntodefinenewturtlevariablesthatonlyturtlesofthegiven
breedhave.(It'sallowedformorethanonebreedtoownthesamevariable.)
Aturtle'sbreedagentsetisstoredinthebreedturtlevariable.Soyoucantestaturtle's
breed,likethis:
if breed = wolves [ ... ]

Notealsothatturtlescanchangebreeds.Awolfdoesn'thavetoremainawolfitswhole
life.Let'schangearandomwolfintoasheep:
ask one-of wolves [ set breed sheep ]

Theset-default-shapeprimitiveisusefulforassociatingcertainturtleshapeswithcertain
breeds.Seethesectiononshapesbelow.
Whonumbersareassignedirrespectiveofbreeds.Ifyoualreadyhaveafrog 0,thenthe
firstmousewillbemouse 1,notmouse 0,sincethewhonumber0isalreadytaken.
Hereisaquickexampleofusingbreeds:
breed [mice mouse]
breed [frogs frog]
mice-own [cheese]
to setup
clear-all
https://ccl.northwestern.edu/netlogo/docs/programming.html

14/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

create-mice 50
[ set color white
set cheese random 10 ]
create-frogs 50
[ set color green ]
reset-ticks
end

CodeExample:BreedsandShapesExample

Linkbreeds
Linkbreedsareverysimilartoturtlebreeds,however,thereareafewdifferences.
Whenyoudeclarealinkbreedyoumustdeclarewhetheritisabreedofdirectedor
undirectedlinksbyusingthedirected-link-breedandundirected-link-breedkeywords.
directed-link-breed [streets street]
undirected-link-breed [friendships friendship]

Onceyouhavecreatedabreededlinkyoucannotcreateunbreededlinksandviceversa.
(Youcan,however,havedirectedandundirectedlinksinthesameworld,justnotinthe
samebreed)
Unlikewithturtlebreedsthesingularbreednameisrequiredforlinkbreeds,asmanyof
thelinkcommandsandreportsusethesingularname,suchas<link-breed>-neighbor?.
Thefollowingprimitivesarealsoautomaticallyavailableonceyoudefineadirectedlink
breed:create-street-fromcreate-streets-fromcreate-street-tocreate-streets-to
in-street-neighbor?in-street-neighborsin-street-frommy-in-streetsmy-out-streets
out-street-neighbor?out-street-neighborsout-street-to
Andthefollowingareautomaticallyavailablewhenyoudefineanundirectedlinkbreed:
create-friendship-withcreate-friendships-withfriendship-neighbor?friendshipneighborsfriendship-withmy-friendships
Multiplelinkbreedsmaydeclarethesame-ownvariable,butavariablemaynotbeshared
betweenaturtlebreedandalinkbreed.
Justaswithturtlebreedstheorderinwhichlinkbreedsaredeclareddefinestheorderin
whichthelinksaredrawn,sothefriendshipswillalwaysbeontopofstreets(ifforsome
reasonthesebreedswereinthesamemodel).Youcanalsouse<link-breeds>-ownto
declarevariablesofeachlinkbreedseparately.
Youcanchangethebreedofalinkwithset breed.(However,youcannotchangea
breededlinktoanunbreededone,topreventhavingbreededandunbreededlinksinthe
sameworld.)
ask one-of friendships [ set breed streets ]
ask one-of friendships [ set breed links ] ;; produces a runtime error

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

15/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

set-default-shapemayalsobeusedwithlinkbreedstoassociateitwithaparticularlink

shape.
CodeExample:LinkBreedsExample

Buttons
Buttonsintheinterfacetabprovideaneasywaytocontrolthemodel.Typicallyamodel
willhaveatleasta"setup"button,tosetuptheinitialstateoftheworld,anda"go"button
tomakethemodelruncontinuously.Somemodelswillhaveadditionalbuttonsthat
performotheractions.
AbuttoncontainssomeNetLogocode.Thatcodeisrunwhenyoupressthebutton.
Abuttonmaybeeithera"oncebutton",ora"foreverbutton".Youcancontrolthisby
editingthebuttonandcheckingoruncheckingthe"Forever"checkbox.Oncebuttonsrun
theircodeonce,thenstopandpopbackup.Foreverbuttonskeeprunningtheircodeover
andoveragain.
Aforeverbuttonstopsiftheuserpressesthebuttonagaintostopit.Thebuttonwaitsuntil
thecurrentiterationhasfinished,thenpopsup.
Aforeverbuttoncanalsobestoppedfromcode.Iftheforeverbuttondirectlycallsa
procedure,thenwhenthatprocedurestops,thebuttonstops.(Inaturtleorpatchforever
button,thebuttonwon'tstopuntileveryturtleorpatchstopsasingleturtleorpatch
doesn'thavethepowertostopthewholebutton.)
Normally,abuttonislabeledwiththecodethatitruns.Forexample,abuttonthatsays
"go"onitusuallycontainsthecode"go",whichmeans"runthegoprocedure".
(ProceduresaredefinedintheCodetabseebelow.)Butyoucanalsoeditabuttonand
entera"displayname"forthebutton,whichisatextthatappearsonthebuttoninsteadof
thecode.Youmightusethisfeatureifyouthinktheactualcodewouldbeconfusingto
yourusers.
Whenyouputcodeinabutton,youmustalsospecifywhichagentsyouwanttorunthat
code.Youcanchoosetohavetheobserverrunthecode,orallturtles,orallpatches,or
alllinks.(Ifyouwantthecodetoberunbyonlysometurtlesorsomepatches,youcould
makeanobserverbutton,andthenhavetheobserverusetheaskcommandtoaskonly
someoftheturtlesorpatchestodosomething.)
Whenyoueditabutton,youhavetheoptiontoassignan"actionkey".Thismakesthat
keyonthekeyboardbehavejustlikeabuttonpress.Ifthebuttonisaforeverbutton,itwill
staydownuntilthekeyispressedagain(orthebuttonisclicked).Actionkeysare
particularlyusefulforgamesoranymodelwhererapidtriggeringofbuttonsisneeded.
Buttonstaketurns
Morethanonebuttoncanbepressedatatime.Ifthishappens,thebuttons"taketurns",
whichmeansthatonlyonebuttonrunsatatime.Eachbuttonrunsitscodealltheway
throughoncewhiletheotherbuttonswait,thenthenextbuttongetsitsturn.
Inthefollowingexamples,"setup"isaoncebuttonand"go"isaforeverbutton.
https://ccl.northwestern.edu/netlogo/docs/programming.html

16/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Example#1:Theuserpresses"setup",thenpresses"go"immediately,beforethe"setup"
haspoppedbackup.Result:"setup"finishesbefore"go"starts.
Example#2:Whilethe"go"buttonisdown,theuserpresses"setup".Result:the"go"
buttonfinishesitscurrentiteration.Thenthe"setup"buttonruns.Then"go"startsrunning
again.
Example#3:Theuserhastwoforeverbuttonsdownatthesametime.Result:firstone
buttonrunsitscodeallthewaythrough,thentheotherrunsitscodeallthewaythrough,
andsoon,alternating.
Notethatifonebuttongetsstuckinaninfiniteloop,thennootherbuttonswillrun.
Turtle,patch,andlinkforeverbuttons
Thereisasubtledifferencebetweenputtingcommandsinaturtle,patchorlinkforever
button,andputtingthesamecommandsinanobserverbuttonthatdoesask turtles,ask
patchesorask links.An"ask"doesn'tcompleteuntilalloftheagentshavefinished
runningallofthecommandsinthe"ask".Sotheagents,astheyallrunthecommands
concurrently,canbeoutofsyncwitheachother,buttheyallsyncupagainattheendof
theask.Thesameisn'ttrueofturtle,patchandlinkforeverbuttons.Sinceaskwasnot
used,eachturtleorpatchrunsthegivencodeoverandoveragain,sotheycanbecome
(andremain)outofsyncwitheachother.
Atpresent,thiscapabilityisveryrarelyusedinthemodelsinourModelsLibrary.Amodel
thatdoesusethecapabilityistheTermitesmodel,intheBiologysectionofSample
Models.The"go"buttonisaturtleforeverbutton,soeachtermiteproceedsindependently
ofeveryothertermite,andtheobserverisnotinvolvedatall.Thismeansthatif,for
example,youwantedtoaddticksand/oraplottothemodel,youwouldneedtoadda
secondforeverbutton(anobserverforeverbutton),andrunbothforeverbuttonsatthe
sametime.NotealsothatamodellikethiscannotbeusedwithBehaviorSpace.
CodeExample:StateMachineExampleshowshowTermitescanberecodedin
atickbasedway,withoutusingaturtleforeverbutton.
Atpresent,NetLogohasnowayforoneforeverbuttontostartanother.Buttonsareonly
startedwhenyoupressthem.

Lists
Inthesimplestmodels,eachvariableholdsonlyonepieceofinformation,usuallya
numberorastring.Listsletyoustoremultiplepiecesofinformationinasinglevalueby
collectingthatinformationinalist.Eachvalueinthelistcanbeanytypeofvalue:a
number,orastring,anagentoragentset,orevenanotherlist.
ListsallowfortheconvenientpackagingofinformationinNetLogo.Ifyouragentscarry
outarepetitivecalculationonmultiplevariables,itmightbeeasiertohavealistvariable,
insteadofmultiplenumbervariables.Severalprimitivessimplifytheprocessofperforming
thesamecomputationoneachvalueinalist.
TheNetLogoDictionaryhasasectionthatlistsallofthelistrelatedprimitives.

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

17/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Constantlists
Youcanmakealistbysimplyputtingthevaluesyouwantinthelistbetweenbrackets,
likethis:set mylist [2 4 6 8].Notethattheindividualvaluesareseparatedbyspaces.
Youcanmakeliststhatcontainnumbersandstringsthisway,aswellaslistswithinlists,
forexample[[2 4] [3 5]].
Theemptylistiswrittenbyputtingnothingbetweenthebrackets,likethis:[].
Buildinglistsonthefly
Ifyouwanttomakealistinwhichthevaluesaredeterminedbyreporters,asopposedto
beingaseriesofconstants,usethelistreporter.Thelistreporteracceptstwoother
reporters,runsthem,andreportstheresultsasalist.
IfIwantedalisttocontaintworandomvalues,Imightusethefollowingcode:
set random-list list (random 10) (random 20)

Thiswillsetrandom-listtoanewlistoftworandomintegerseachtimeitruns.
Tomakelongerorshorterlists,youcanusethelistreporterwithfewerormorethantwo
inputs,butinordertodoso,youmustenclosetheentirecallinparentheses,e.g.:
(list random 10)
(list random 10 random 20 random 30)

Formoreinformation,seeVaryingnumberofinputs.
Somekindsoflistsaremosteasilybuiltusingthen-valuesreporter,whichallowsyouto
constructalistofaspecificlengthbyrepeatedlyrunningagivenreporter.Youcanmake
alistofthesamevaluerepeated,orallthenumbersinarange,oralotofrandom
numbers,ormanyotherpossibilities.Seedictionaryentryfordetailsandexamples.
Theofprimitiveletsyouconstructalistfromanagentset.Itreportsalistcontainingeach
agent'svalueforthegivenreporter.(Thereportercouldbeasimplevariablename,ora
morecomplexexpressionevenacalltoaproceduredefinedusingto-report.)A
commonidiomis
max [...] of turtles
sum [...] of turtles

andsoon.
Youcancombinetwoormorelistsusingthesentencereporter,whichconcatenateslists
bycombiningtheircontentsintoasingle,largerlist.Likelist,sentencenormallytakes
twoinputs,butcanacceptanynumberofinputsifthecallissurroundedbyparentheses.
Changinglistitems
Technically,listscan'tbemodified,butyoucanconstructnewlistsbasedonoldlists.If
youwantthenewlisttoreplacetheoldlist,useset.Forexample:
https://ccl.northwestern.edu/netlogo/docs/programming.html

18/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

set mylist [2 7 5 Bob [3 0 -2]]


; mylist is now [2 7 5 Bob [3 0 -2]]
set mylist replace-item 2 mylist 10
; mylist is now [2 7 10 Bob [3 0 -2]]

Thereplace-itemreportertakesthreeinputs.Thefirstinputspecifieswhichiteminthelist
istobechanged.0meansthefirstitem,1meanstheseconditem,andsoforth.
Toaddanitem,say42,totheendofalist,usethelputreporter.(fputaddsanitemto
thebeginningofalist.)
set mylist lput 42 mylist
; mylist is now [2 7 10 Bob [3 0 -2] 42]

Butwhatifyouchangedyourmind?Thebut-last(blforshort)reporterreportsallthelist
itemsbutthelast.
set mylist but-last mylist
; mylist is now [2 7 10 Bob [3 0 -2]]

Supposeyouwanttogetridofitem0,the2atthebeginningofthelist.
set mylist but-first mylist
; mylist is now [7 10 Bob [3 0 -2]]

Supposeyouwantedtochangethethirditemthat'snestedinsideitem3from2to9?The
keyistorealizethatthenamethatcanbeusedtocallthenestedlist[302]isitem 3
mylist.Thenthereplace-itemreportercanbenestedtochangethelistwithinalist.The
parenthesesareaddedforclarity.
set mylist (replace-item 3 mylist
(replace-item 2 (item 3 mylist) 9))
; mylist is now [7 10 Bob [3 0 9]]

Iteratingoverlists
Ifyouwanttodosomeoperationoneachiteminalistinturn,theforeachcommandand
themapreportermaybehelpful.
foreachisusedtorunacommandorcommandsoneachiteminalist.Ittakesaninput

listandacommandnameorblockofcommands,likethis:
foreach [1 2 3] show
=> 1
=> 2
=> 3
foreach [2 4 6]
[ crt ?
show (word "created " ? " turtles") ]
=> created 2 turtles
=> created 4 turtles
https://ccl.northwestern.edu/netlogo/docs/programming.html

19/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

=> created 6 turtles

Intheblock,thevariable?holdsthecurrentvaluefromtheinputlist.
Herearesomemoreexamplesofforeach:
foreach [1 2 3] [ ask turtles [ fd ? ] ]
;; turtles move forward 6 patches
foreach [true false true true] [ ask turtles [ if ? [ fd 1 ] ] ]
;; turtles move forward 3 patches
mapissimilartoforeach,butitisareporter.Ittakesaninputlistandareporternameor
reporterblock.Notethatunlikeforeach,thereportercomesfirst,likethis:
show map round [1.2 2.2 2.7]
;; prints [1 2 3]
mapreportsalistcontainingtheresultsofapplyingthereportertoeachitemintheinput
list.Again,use?torefertothecurrentiteminthelist.

Hereareacouplemoreexamplesofmap:
show map [? < 0] [1 -1 3 4 -2 -10]
;; prints [false true false false true true]
show map [? * ?] [1 2 3]
;; prints [1 4 9]

Besidesmapandforeach,otherprimitivesforprocessingwholelistsinaconfigurableway
includefilter,reduce,andsort-by.
Theseprimitivesaren'talwaysthesolutionforeverysituationinwhichyouwanttooperate
onanentirelist.Insomesituations,youmayneedtousesomeothertechniquesuchasa
loopusingrepeatorwhile,orarecursiveprocedure.
Theblocksofcodewe'regivingtomapandforeachintheseexamplesareactuallytasks.
TasksareexplainedinmoredetailinTasks,below.
Varyingnumberofinputs
Somecommandsandreportersinvolvinglistsandstringsmaytakeavaryingnumberof
inputs.Inthesecases,inordertopassthemanumberofinputsotherthantheirdefault,
theprimitiveanditsinputsmustbesurroundedbyparentheses.Herearesomeexamples:
show list 1 2
=> [1 2]
show (list 1 2 3 4)
=> [1 2 3 4]
show (list)
=> []

Notethateachofthesespecialprimitiveshasadefaultnumberofinputsforwhichno
parenthesesarerequired.Theprimitiveswhichhavethiscapabilityarelist,word,
https://ccl.northwestern.edu/netlogo/docs/programming.html

20/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

sentence,map,foreach,run,andrunresult.

Listsofagents
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomorderevery
time.Ifyouneedyouragentstodosomethinginafixedorder,youneedtomakealistof
theagentsinstead.
Therearetwoprimitivesthathelpyoudothis,sortandsort-by.
Bothsortandsort-bycantakeanagentsetasinput.Theresultisalwaysanewlist,
containingthesameagentsastheagentsetdid,butinaparticularorder.
Ifyouusesortonanagentsetofturtles,theresultisalistofturtlessortedinascending
orderbywhonumber.
Ifyouusesortonanagentsetofpatches,theresultisalistofpatchessortedlefttoright,
toptobottom.
Ifyouusesortonanagentsetoflinks,theresultisalistoflinks,sortedinascending
orderfirstbyend1thenbyend2anyremainingtiesareresolvedbybreedintheorderthey
aredeclaredintheCodetab.
Ifyouneeddescendingorderinstead,youcancombinereversewithsort,forexample
reverse sort turtles.
Ifyouwantyouragentstobeorderedbysomeothercriterionthanthestandardonessort
uses,you'llneedtousesort-byinstead.
Here'sanexample:
sort-by [[size] of ?1 < [size] of ?2] turtles

Thisreturnsalistofturtlessortedinascendingorderbytheirturtlevariablesize.
There'sacommonpatterntogetalistofagentsinarandomorder,usingacombinationof
ofandself,intherarecasethatyoucannotjustuseask:
[self] of my-agentset

Askingalistofagents
Onceyouhavealistofagents,youmightwanttoaskthemeachtodosomething.Todo
this,usetheforeachandaskcommandsincombination,likethis:
foreach sort turtles [
ask ? [
...
]
]

Thiswillaskeachturtleinascendingorderbywhonumber.Substitute"patches"for
"turtles"toaskpatchesinlefttoright,toptobottomorder.
https://ccl.northwestern.edu/netlogo/docs/programming.html

21/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Notethatyoucan'tuseaskdirectlyonalistofturtles.askonlyworkswithagentsetsand
singleagents.
Performanceoflists
ThedatastructureunderlyingNetLogo'slistsisasophisticatedtreebaseddatastructure
onwhichmostoperationsruninnearconstanttime.Thatincludesfput,lput,butfirst,
butlast,length,item,andreplace-item.
Oneexceptiontothefastperformanceruleisthatconcatenatingtwolistswithsentence
requirestraversingandcopyingthewholesecondlist.(Thismaybefixedinafuture
version.)
Technically,"nearconstanttime"isactuallylogarithmictime,proportionaltothedepthof
theunderlyingtree,butthesetreeshavelargenodesandahighbranchingfactor,sothey
arenevermorethanafewlevelsdeep.Thismeansthatchangescanbemadeinatmost
afewsteps.Thetreesareimmutable,buttheysharestructurewitheachother,sothe
wholetreedoesn'tneedtobecopiedtomakeachangedversion.
TheactualdatastructureusedistheimmutableVectorclassfromtheScalacollections
library.Theseare32widehasharraymappedtries,asimplementedbyTiarkRompf,
basedinpartonworkbyPhilBagwellandRichHickey.

Math
AllnumbersinNetLogoarestoredinternallyasdoubleprecisionfloatingpointnumbers,
asdefinedintheIEEE754standard.Theyare64bitnumbersconsistingofonesignbit,
an11bitexponent,anda52bitmantissa.SeetheIEEE754standardfordetails.
An"integer"inNetLogoissimplyanumberthathappenstohavenofractionalpart.No
distinctionismadebetween3and3.0theyarethesamenumber.(Thisisthesameas
howmostpeopleusenumbersineverydaycontexts,butdifferentfromsome
programminglanguages.Somelanguagestreatintegersandfloatingpointnumbersas
distincttypes.)
IntegersarealwaysprintedbyNetLogowithoutthetrailing".0":
show 1.5 + 1.5
observer: 3

Ifanumberwithafractionalpartissuppliedinacontextwhereanintegerisexpected,the
fractionalpartissimplydiscarded.Soforexample,crt 3.5createsthreeturtlestheextra
0.5isignored.
Therangeofintegersis+/9007199254740992(2^53,about9quadrillion).Calculations
thatexceedthisrangewillnotcauseruntimeerrors,butprecisionwillbelostwhenthe
leastsignificant(binary)digitsareroundedoffinorderfitthenumberinto64bits.With
verylargenumbers,thisroundingcanresultinimpreciseanswerswhichmaybe
surprising:
show 2 ^ 60 + 1 = 2 ^ 60
=> true
https://ccl.northwestern.edu/netlogo/docs/programming.html

22/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Calculationswithsmallernumberscanalsoproducesurprisingresultsiftheyinvolve
fractionalquantities,sincenotallfractionscanbepreciselyrepresentedandroundoffmay
occur.Forexample:
show 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6
=> 0.9999999999999999
show 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9
=> 1.0000000000000002

Anyoperationwhichproducesthespecialquantities"infinity"or"notanumber"willcause
aruntimeerror.
Scientificnotation
VerylargeorverysmallfloatingpointnumbersaredisplayedbyNetLogousing"scientific
notation".Examples:
show 0.000000000001
=> 1.0E-12
show 50000000000000000000
=> 5.0E19

NumbersinscientificnotationaredistinguishedbythepresenceoftheletterE(for
"exponent").Itmeans"timestentothepowerof",soforexample,1.0E12means1.0
times10tothe12power:
show 1.0 * 10 ^ -12
=> 1.0E-12

YoucanalsousescientificnotationyourselfinNetLogocode:
show 3.0E6
=> 3000000
show 8.123456789E6
=> 8123456.789
show 8.123456789E7
=> 8.123456789E7
show 3.0E16
=> 3.0E16
show 8.0E-3
=> 0.0080
show 8.0E-4
=> 8.0E-4

Theseexamplesshowthatnumberswithfractionalpartsaredisplayedusingscientific
notationiftheexponentislessthan3orgreaterthan6.NumbersoutsideofNetLogo's
integerrangeof9007199254740992to9007199254740992(+/2^53)arealsoalways
showninscientificnotation:
show 2 ^ 60
=> 1.15292150460684698E18

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

23/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Whenenteringanumber,theletterEmaybeeitherupperorlowercase.Whenprintinga
number,NetLogoalwaysusesanuppercaseE:
show 4.5e20
=> 4.5E20

Floatingpointaccuracy
BecausenumbersinNetLogoaresubjecttothelimitationsofhowfloatingpointnumbers
arerepresentedinbinary,youmaygetanswersthatareslightlyinaccurate.Forexample:
show 0.1 + 0.1 + 0.1
=> 0.30000000000000004
show cos 90
=> 6.123233995736766E-17

Thisisaninherentissuewithfloatingpointarithmeticitoccursinallprogramming
languagesthatusefloatingpointnumbers.
Ifyouaredealingwithfixedprecisionquantities,forexampledollarsandcents,acommon
techniqueistouseonlyintegers(cents)internally,thendivideby100togetaresultin
dollarsfordisplay.
Ifyoumustusefloatingpointnumbers,theninsomesituationsyoumayneedtoreplacea
straightforwardequalitytestsuchasif x = 1 [ ... ]withatestthattoleratesslight
imprecision,forexampleif abs (x - 1) < 0.0001 [ ... ].
Also,theprecisionprimitiveishandyforroundingoffnumbersfordisplaypurposes.
NetLogomonitorsroundthenumberstheydisplaytoaconfigurablenumberofdecimal
places,too.

Randomnumbers
TherandomnumbersusedbyNetLogoarewhatiscalled"pseudorandom".(Thisis
typicalincomputerprogramming.)Thatmeanstheyappearrandom,butareinfact
generatedbyadeterministicprocess."Deterministic"meansthatyougetthesameresults
everytime,ifyoustartwiththesamerandom"seed".We'llexplaininaminutewhatwe
meanby"seed".
Inthecontextofscientificmodeling,pseudorandomnumbersareactuallydesirable.
That'sbecauseit'simportantthatascientificexperimentbereproduciblesoanyonecan
tryitthemselvesandgetthesameresultthatyougot.SinceNetLogousespseudo
randomnumbers,the"experiments"thatyoudowithitcanbereproducedbyothers.
Here'showitworks.NetLogo'srandomnumbergeneratorcanbestartedwithacertain
seedvalue,whichmustbeanintegerintherange2147483648to2147483647.Oncethe
generatorhasbeen"seeded"withtherandom-seedcommand,italwaysgeneratesthe
samesequenceofrandomnumbersfromthenon.Forexample,ifyourunthese
commands:
random-seed 137
show random 100
https://ccl.northwestern.edu/netlogo/docs/programming.html

24/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

show random 100


show random 100

Youwillalwaysgetthenumbers79,89,and61inthatorder.
Note,however,thatyou'reonlyguaranteedtogetthosesamenumbersifyou'reusingthe
sameversionofNetLogo.SometimeswhenwemakeanewversionofNetLogothe
randomnumbergeneratorchanges.(Presently,weuseageneratorknownasthe
MersenneTwister.)
Tocreateanumbersuitableforseedingtherandomnumbergenerator,usethenew-seed
reporter.new-seedcreatesaseed,evenlydistributedoverthespaceofpossibleseeds,
basedonthecurrentdateandtime.Itneverreportsthesameseedtwiceinarow.
CodeExample:RandomSeedExample
Ifyoudon'tsettherandomseedyourself,NetLogosetsittoavaluebasedonthecurrent
dateandtime.Thereisnowaytofindoutwhatrandomseeditchose,soifyouwantyour
modelruntobereproducible,youmustsettherandomseedyourselfaheadoftime.
TheNetLogoprimitiveswith"random"intheirnames(random,randomfloat,andsoon)
aren'ttheonlyonesthatusepseudorandomnumbers.Manyotheroperationsalsomake
randomchoices.Forexample,agentsetsarealwaysinrandomorder,one-ofandn-of
chooseagentsrandomly,thesproutcommandcreatesturtleswithrandomcolorsand
headings,andthedownhillreporterchoosesarandompatchwhenthere'satie.Allof
theserandomchoicesaregovernedbytherandomseedaswell,somodelrunscanbe
reproducible.
Inadditiontotheuniformlydistributedrandomintegersandfloatingpointnumbers
generatedbyrandomandrandom-float,NetLogoalsooffersseveralotherrandom
distributions.Seethedictionaryentriesforrandom-normal,random-poisson,randomexponential,andrandom-gamma.

Auxiliarygenerator
Coderunbybuttonsorfromthecommandcenterusesthemainrandomnumber
generator.
Codeinmonitorsusesanauxiliaryrandomgenerator,soevenifamonitordoesa
calculationthatusesrandomnumbers,theoutcomeofthemodelisnotaffected.The
sameistrueofcodeinsliders.

Localrandomness
Youmaywanttoexplicitlyspecifythatasectionofcodedoesnotaffectthestateofthe
mainrandomgenerator,sotheoutcomeofthemodelisnotaffected.Thewith-localrandomnesscommandisprovidedforthispurpose.SeeitsentryintheNetLogoDictionary
formoreinformation.

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

25/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

InNetLogo,turtleshapesarevectorshapes.Theyarebuiltupfrombasicgeometric
shapessquares,circles,andlines,ratherthanagridofpixels.Vectorshapesarefully
scalableandrotatable.NetLogocachesbitmapimagesofvectorshapessize1,1.5,and2
inordertospeedupexecution.
Aturtle'sshapeisstoredinitsshapevariableandcanbesetusingthesetcommand.
Newturtleshaveashapeof"default".Theset-default-shapeprimitiveisusefulfor
changingthedefaultturtleshapetoadifferentshape,orhavingadifferentdefaultturtle
shapeforeachbreedofturtle.
Theshapesprimitivereportsalistofcurrentlyavailableturtleshapesinthemodel.Thisis
usefulif,forexample,youwanttoassignarandomshapetoaturtle:
ask turtles [ set shape one-of shapes ]

UsetheTurtleShapesEditortocreateyourownturtleshapes,ortoaddshapestoyour
modelfromourshapeslibrary,ortotransfershapesbetweenmodels.Formore
information,seetheShapesEditorsectionofthismanual.
Thethicknessofthelinesusedtodrawthevectorshapescanbecontrolledbythe__setline-thicknessprimitive.
CodeExamples:BreedsandShapesExample,ShapeAnimationExample

Linkshapes
LinkShapesaresimilartoturtleshapes,onlyyouusetheLinkShapeEditortocreateand
editthem.Linkshapesconsistofbetween0and3lineswhichcanhavedifferentpatterns
andadirectionindicatorthatiscomposedofthesameelementsasturtleshapes.Links
alsohaveashapevariablethatcanbesettoanylinkshapethatisinthemodel.By
defaultlinkshavethe"default"shape,thoughyoucanchangethatusingset-defaultshape.Thelink-shapesreporterreportsallthelinkshapesincludedinthecurrentmodel.
Thethicknessofthelinesinthelinkshapeiscontrolledbythethicknesslinkvariable.

Viewupdates
The"view"inNetLogoletsyouseetheagentsinyourmodelonyourcomputer'sscreen.
Asyouragentsmoveandchange,youseethemmovingandchangingintheview.
Ofcourse,youcan'treallyseeyouragentsdirectly.TheviewisapicturethatNetLogo
paints,showingyouhowyouragentslookataparticularinstant.Oncethatinstantpasses
andyouragentsmoveandchangesomemore,thatpictureneedstoberepaintedto
reflectthenewstateoftheworld.Repaintingthepictureiscalled"updating"theview.
Whendoestheviewgetupdated?ThissectiondiscusseshowNetLogodecideswhento
updatetheview,andhowyoucaninfluencewhenitgetsupdated.
NetLogoofferstwoupdatesmodes,"continuous"updatesand"tickbased"updates.You
https://ccl.northwestern.edu/netlogo/docs/programming.html

26/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

canswitchbetweenNetLogo'stwoviewupdatemodesusingapopupmenuatthetopof
theInterfacetab.
ContinuousupdatesarethedefaultwhenyoustartupNetLogoorstartanewmodel.
NearlyeverymodelinourModelsLibrary,however,usestickbasedupdates.
Continuousupdatesaresimplest,buttickbasedupdatesgiveyoumorecontrolover
whenandhowoftenupdateshappen.
It'simportantexactlywhenanupdatehappens,becausewhenupdateshappen
determineswhatyouseeonthescreen.Ifanupdatecomesatanunexpectedtime,you
mayseesomethingunexpectedperhapssomethingconfusingormisleading.
It'salsoimportanthowoftenupdateshappen,becauseupdatestaketime.Themoretime
NetLogospendsupdatingtheview,thesloweryourmodelwillrun.Withfewerupdates,
yourmodelrunsfaster.

Continuousupdates
Continuousupdatesareverysimple.Withcontinuousupdates,NetLogoupdatestheview
acertainnumberoftimespersecondbydefault,30timesasecondwhenthespeed
sliderisinthedefault,middlesetting.
Ifyoumovethespeedslidertoaslowersetting,NetLogowillupdatemorethan30timesa
second,effectivelyslowingdownthemodel.Onafastersetting,NetLogowillupdateless
than30timesasecond.Onthefastestsetting,updateswillbeseparatedbyseveral
seconds.
Atextremelyslowsettings,NetLogowillbeupdatingsooftenthatyouwillseeyouragents
moving(orchangingcolor,etc.)oneatatime.
Ifyouneedtotemporarilyshutoffcontinuousupdates,usetheno-displaycommand.The
displaycommandturnsupdatesbackon,andalsoforcesanimmediateupdate(unless
theuserisfastforwardingthemodelusingthespeedslider).

Tickbasedupdates
AsdiscussedaboveintheTickCountersection,inmanyNetLogomodels,timepassesin
discretesteps,called"ticks".Typically,youwanttheviewtoupdateoncepertick,
betweenticks.That'sthedefaultbehaviorwithtickbasedupdates.
Ifyouwantadditionalviewupdates,youcanforceanupdateusingthedisplaycommand.
(Theupdatemaybeskippediftheuserisfastforwardingthemodelusingthespeed
slider.)
Youdon'thavetousethetickcountertousetickbasedupdates.Ifthetickcounternever
advances,theviewwillupdateonlywhenyouusethedisplaycommand.
Ifyoumovethespeedslidertoafastenoughsetting,eventuallyNetLogowillskipsomeof
theupdatesthatwouldordinarilyhavehappened.Movingthespeedslidertoaslower
settingdoesn'tcauseadditionalupdatesrather,itmakesNetLogopauseaftereach
update.Theslowerthesetting,thelongerthepause.
https://ccl.northwestern.edu/netlogo/docs/programming.html

27/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Evenundertickbasedupdates,theviewalsoupdateswheneverabuttonintheinterface
popsup(bothonceandforeverbuttons)andwhenacommandenteredintheCommand
Centerfinishes.Soit'snotnecessarytoaddthedisplaycommandtooncebuttonsthat
don'tadvancethetickcounter.Manyforeverbuttonsthatdon'tadvancethetickcounter
doneedtousethedisplaycommand.AnexampleintheModelsLibraryistheLifemodel
(underComputerScience>CellularAutomata).Theforeverbuttonsthatlettheuser
drawintheviewusethedisplaycommandsotheusercanseewhattheyaredrawing,
eventhoughthetickcounterisnotadvancing.

Choosingamode
Advantagesoftickbasedupdatesovercontinuousupdatesinclude:
1.Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputerto
computerorfromruntorun.
2.Continuousupdatescanconfusetheuserofyourmodelbylettingthemseemodel
statestheyaren'tsupposedtosee,whichmaybemisleading.
3.Increasedspeed.Updatingtheviewtakestime,soifoneupdatepertickisenough,
thenenforcingthereisonlyoneupdatepertickwillmakeyourmodelfaster.
4.Sincesetupbuttonsdon'tadvancethetickcounter,theyareunaffectedbythe
speedsliderthisisnormallythedesiredbehavior.
NearlyeverymodelinourModelsLibraryusestickbasedupdates.
Continuousupdatesareoccasionallyusefulforthoseraremodelsinwhichexecutionis
notdividedintoshort,discretephases.AnexampleintheModelsLibraryisTermites.
(Seealso,however,theStateMachineExamplemodel,whichshowshowtorecode
Termitesusingticks.)
Evenformodelsthatwouldnormallybesettotickbasedupdates,itmaybeusefulto
switchtocontinuousupdatestemporarilyfordebuggingpurposes.Seeingwhat'sgoingon
withinatick,insteadofonlyseeingtheendresultofatick,couldhelpwith
troubleshooting.Afterswitchingtocontinuousupdates,youmaywanttousethespeed
slidertoslowthemodeldownuntilyouseeyouragentsmovingoneatatime.Don'tforget
tochangebacktotickbasedupdateswhenyouaredone,asthechoiceofupdatemode
issavedwiththemodel.

Framerate
OneofthemodelsettingsinNetLogo's"Settings..."dialogis"Framerate"whichdefaults
to30framespersecond.
Theframeratesettingaffectsbothcontinuousupdatesandtickbasedupdates.
Withcontinuousupdates,thesettingdirectlydeterminesthefrequencyofupdates.
Withtickbasedupdates,thesettingisaceilingonhowmanyupdatespersecondyou
get.Iftheframerateis30,thenNetLogowillensurethatthemodelneverrunsfasterthan
thatwhenthespeedsliderisinthedefaultposition.Ifanyframetakeslessthan1/30ofa
secondtocomputeanddisplay,NetLogowillpauseandwaituntilthefull1/30ofasecond
haspassedbeforecontinuing.
Theframeratesettingsletsyousetwhatyouconsidertobeanormalspeedforyour
https://ccl.northwestern.edu/netlogo/docs/programming.html

28/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

model.Thenyou,ortheuserofyourmodel,canusethespeedslidertotemporarilygeta
fasterorslowerspeed.

Plotting
NetLogo'splottingfeaturesletyoucreateplotstohelpyouunderstandwhat'sgoingonin
yourmodel.
Beforeyoucanplot,youneedtocreateoneormoreplotsintheInterfacetab.Formore
informationonusingandeditingplotsintheInterfacetab,seetheInterfaceGuide.

Plottingpoints
Thetwobasiccommandsforactuallyplottingthingsareplotandplotxy.
Withplotyouneedonlyspecifytheyvalueyouwantplotted.Thexvaluewill
automaticallybe0forthefirstpointyouplot,1forthesecond,andsoon.(That'siftheplot
pen's"interval"isthedefaultvalueof1youcanchangetheinterval.)
Theplotcommandisespeciallyhandywhenyouwantyourmodeltoplotanewpointat
everytimestep.Example:
plot count turtles

Ifyouneedtospecifyboththexandyvaluesofthepointyouwantplotted,thenuse
plotxyinstead.Thisexampleassumesthataglobalvariablecalledtimeexists:
plotxy time count-turtles

Plotcommands
Eachplotanditspenshavesetupandupdatecodefieldsthatmaycontaincommands
(usuallycontainingplotorplotxy).Thesecommandsarerunautomaticallytriggeredby
othercommandsinNetLogo.
Plotsetupcommandsandpensetupcommandsarerunwhentheeitherreset-ticksor
setup-plotscommandsarerun.Ifthestopcommandisruninthebodyoftheplotsetup
commandsthenthepensetupcommandswillnotrun.
Plotupdatecommandsandpenupdatecommandsarerunwhentheeitherreset-ticks,
tickorupdate-plotscommandsarerun.Ifthestopcommandisruninthebodyofthe
plotupdatecommandsthenthepenupdatecommandswillnotrun.
Herearethefourcommandsthattriggerplottingexplainedinmoredetail.
setup-plotsexecutescommandsforoneplotatatime.Foreachplot,theplot's

setupcommandsareexecuted.Ifthestopcommandisnotencounteredwhile
runningthosecommands,theneachoftheplot'spenswillhavetheirsetupcode
executed.
update-plotsisverysimilartosetup-plots.Foreachplot,theplot'supdate
https://ccl.northwestern.edu/netlogo/docs/programming.html

29/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

commandsareexecuted.Ifthestopcommandisnotencounteredwhilerunning
thosecommands,theneachoftheplot'spenswillhavetheirupdatecodeexecuted.
tickisexactlythesameasupdate-plotsexceptthatthetickcounterisincremented
beforetheplotcommandsareexecuted.
reset-ticksfirstresetsthetickcounterto0,andthendoestheequivalentofsetupplotsfollowedbyupdate-plots.
Atypicalmodelwillusereset-ticksandticklikeso:
to setup
clear-all
...
reset-ticks
end
to go
...
tick
end

Notethatinthisexampleweplotfromboththesetupandgoprocedures(becauseresetticksrunsplotsetupandplotupdatecommands).Wedothisbecausewewantourplot
toincludetheinitialstateofthesystemattheendofsetup.Weplotattheendofthego
procedure,notthebeginning,becausewewanttheplotalwaystobeuptodateafterthe
gobuttonstops.
Modelsthatdon'tuseticksbutstillwanttodoplottingwillinsteadusesetup-plotsand
update-plots.Inthepreviouscode,replacereset-tickswithsetup-plots update-plots
andreplacetickwithupdate-plots.
CodeExample:PlottingExample

Otherkindsofplots
Bydefault,NetLogoplotpensplotinlinemode,sothatthepointsyouplotareconnected
byaline.
Ifyouwanttomovethepenwithoutplotting,youcanusetheplot-pen-upcommand.After
thiscommandisissued,theplotandplotxycommandsmovethepenbutdonotactually
drawanything.Oncethepeniswhereyouwantit,useplot-pen-downtoputthepenback
down.
Ifyouwanttoplotindividualpointsinsteadoflines,oryouwanttodrawbarsinsteadof
linesorpoints,youneedtochangetheplotpen's"mode".Threemodesareavailable:
line,bar,andpoint.Lineisthedefaultmode.
Normally,youchangeapen'smodebyeditingtheplot.Thischangesthepen'sdefault
mode.It'salsopossibletochangethepen'smodetemporarilyusingtheset-plot-penmode command.Thatcommandtakesanumberasinput:0forline,1forbar,2forpoint.

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

30/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Ahistogramisaspecialkindofplotthatmeasureshowfrequentlycertainvalues,or
valuesincertainranges,occurinacollectionofnumbersthatariseinyourmodel.
Forexample,supposetheturtlesinyourmodelhaveanagevariable.Youcouldcreatea
histogramofthedistributionofagesamongyourturtleswiththehistogramcommand,like
this:
histogram [age] of turtles

Thenumbersyouwanttohistogramdon'thavetocomefromanagentsettheycouldbe
anylistofnumbers.
Notethatusingthehistogramcommanddoesn'tautomaticallyswitchthecurrentplotpen
tobarmode.Ifyouwantbars,youhavetosettheplotpentobarmodeyourself.(Aswe
saidbefore,youcanchangeapen'sdefaultmodebyeditingtheplotintheInterfacetab.)
Likeothertypesofplots,histogramscanbesettoautoscale.However,autoscaled
histogramsdonotautomaticallyresizethemselveshorizontallylikeotherplottypesdo.To
settherangeprogrammatically,youcanusetheset-plot-x-rangeprimitive.
Thewidthofthebarsinahistogramiscontrolledbytheplotpen'sinterval.Youcanseta
plotpen'sdefaultintervalbyeditingtheplotintheInterfacetab.Youcanalsochangethe
intervaltemporarilywiththeset-plot-pen-intervalcommandortheset-histogram-numbars.Ifyouusethelattercommand,NetLogowillsettheintervalappropriatelysoastofit
thespecifiednumberofbarswithintheplot'scurrentxrange.
CodeExample:HistogramExample

Clearingandresetting
Youcanclearthecurrentplotwiththeclear-plotcommand,orcleareveryplotinyour
modelwithclear-all-plots.Theclear-all commandalsoclearsallplots,inadditionto
clearingeverythingelseinyourmodel.
Ifyouwanttoremoveonlythepointsthataparticularpenhasdrawn,useplot-pen-reset.
Whenawholeplotiscleared,orwhenapenisreset,thatdoesn'tjustremovethedata
thathasbeenplotted.Italsorestorestheplotorpentoitsdefaultsettings,astheywere
specifiedintheInterfacetabwhentheplotwascreatedorlastedited.Therefore,the
effectsofsuchcommandsasset-plot-x-rangeandset-plot-pen-colorareonly
temporary.

Rangesandautoscaling
Thedefaultxandyrangesforaplotarefixednumbers,buttheycanbechangedatsetup
timeorasthemodelruns.
Tochangetherangesatanytime,useset-plot-x-rangeandset-plot-y-range.Or,you
canlettherangesgrowautomatically.Eitherway,whentheplotisclearedtherangeswill
returntotheirdefaultvalues.
https://ccl.northwestern.edu/netlogo/docs/programming.html

31/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Bydefault,allNetLogoplotshavetheautoscalingfeatureenabled.Thismeansthatifthe
modeltriestoplotapointwhichisoutsidethecurrentdisplayedrange,therangeofthe
plotwillgrowalongoneorbothaxessothatthenewpointisvisible.Histogramplots,
however,donotautoscalehorizontally.
Inthehopethattherangeswon'thavetochangeeverytimeanewpointisadded,when
therangesgrowtheyleavesomeextraroom:25%ifgrowinghorizontally,10%ifgrowing
vertically.
Ifyouwanttoturnoffthisfeature,edittheplotandunchecktheAutoScale?checkbox.At
present,itisnotpossibletoenableordisablethisfeatureonlyononeaxisitalways
appliestobothaxes.

UsingaLegend
Youcanshowthelegendofaplotbycheckingthe"Showlegend"checkboxintheedit
dialog.Ifyoudon'twantaparticularpentoshowupinthelegendyoucanuncheckthe
"ShowinLegend"checkboxforthatpenalsointheadvancedplotpensettings(the
advancedplotpensettingscanbeopenedbyclickingthepencilbuttonforthatpeninthe
plotpenstableintheploteditdialog).

Temporaryplotpens
Mostplotscangetalongwithafixednumberofpens.Butsomeplotshavemorecomplex
needstheymayneedtohavethenumberofpensvarydependingonconditions.Insuch
cases,youcanmake"temporary"plotpensfromcodeandthenplotwiththem.These
pensarecalled"temporary"becausetheyvanishwhentheplotiscleared(bytheclearplot,clear-all-plots,orclear-allcommands).
Tocreateatemporaryplotpen,usethecreate-temporary-plot-pencommand.Typically,
thiswouldbedoneintheCodetab,butitisalsopossibletousethiscommandfromplot
setuporplotupdatecode(intheeditdialog).Bydefault,thenewpenisdown,isblackin
color,hasanintervalof1,andplotsinlinemode.Commandsareavailabletochangeall
ofthesesettingsseethePlottingsectionoftheNetLogoDictionary.
Beforeyoucanusethepen,you'llhavetousetheusetheset-current-plotandsetcurrent-plot-pencommands.Theseareexplainedinthenextsection.

setcurrentplotandsetcurrentplotpen
BeforeNetLogo5,itwasnotpossibletoputplotcommandsintheplotitself.Alloftheplot
codewaswrittenintheCodetabwiththerestofthecode.Forbackwardscompatibility,
andfortemporaryplotpens,thisisstillsupported.ModelsinpreviousversionsofNetLogo
(andthoseusingtemporaryplotpens)havetoexplicitlystatewhichplotisthecurrentplot
withtheset-current-plotcommandandwhichpenisthecurrentpenwiththesetcurrent-plot-pencommand.
Tosetthecurrentplotusetheset-current-plotcommandwiththenameoftheplot
enclosedindoublequotes,likethis:
set-current-plot "Distance vs. Time"
https://ccl.northwestern.edu/netlogo/docs/programming.html

32/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Thenameoftheplotmustbeexactlyasyoutypeditwhenyoucreatedtheplot.Notethat
laterifyouchangethenameoftheplot,you'llalsohavetoupdatetheset-current-plot
callsinyourmodeltousethenewname.(Copyandpastecanbehelpfulhere.)
Foraplotwithmultiplepens,youcanmanuallyspecifywhichpenyouwanttoplotwith.If
youdon'tspecifyapen,plottingwilltakeplacewiththefirstpenintheplot.Toplotwitha
differentpen,theset-current-plot-pencommandwasusedwiththenameofthepen
enclosedindoublequotes,likethis:
set-current-plot-pen "distance"

Oncethecurrentpenisset,thencommandslikeplot count turtlescanbeexecutedfor


thatpen.
Oldermodelswithplotsusuallyhadtheirowndo-plottingprocedurethatlooked
somethinglikethis:
to do-plotting
set-current-plot "populations"
set-current-plot-pen "sheep"
plot count sheep
set-current-plot-pen "wolves"
plot count wolves
set-current-plot "next plot"
...
end

Onceagain,thisisnolongernecessaryinNetLogo5,unlessyouareusingtemporaryplot
pens.

Conclusion
NoteveryaspectofNetLogo'splottingsystemhasbeenexplainedhere.SeethePlotting
sectionoftheNetLogoDictionaryforinformationonadditionalcommandsandreporters
relatedtoplotting.
ManyoftheSampleModelsintheModelsLibraryillustratevariousadvancedplotting
techniques.Alsocheckoutthefollowingcodeexamples:
CodeExamples:PlotAxisExample,PlotSmoothingExample,RollingPlot
Example

Strings
StringsmaycontainanyUnicodecharacters.
ToinputaconstantstringinNetLogo,surrounditwithdoublequotes.
https://ccl.northwestern.edu/netlogo/docs/programming.html

33/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Theemptystringiswrittenbyputtingnothingbetweenthequotes,likethis:"".
Mostofthelistprimitivesworkonstringsaswell:
but-first "string" => "tring"
but-last "string" => "strin"
empty? "" => true
empty? "string" => false
first "string" => "s"
item 2 "string" => "r"
last "string" => "g"
length "string" => 6
member? "s" "string" => true
member? "rin" "string" => true
member? "ron" "string" => false
position "s" "string" => 0
position "rin" "string" => 2
position "ron" "string" => false
remove "r" "string" => "sting"
remove "s" "strings" => "tring"
replace-item 3 "string" "o" => "strong"
reverse "string" => "gnirts"

Afewprimitivesarespecifictostrings,suchasis-string?,substring,andword:
is-string? "string" => true
is-string? 37 => false
substring "string" 2 5 => "rin"
word "tur" "tle" => "turtle"

Stringscanbecomparedusingthe=,!=,<,>,<=,and>=operators.
Ifyouneedtoembedaspecialcharacterinastring,usethefollowingescapesequences:
\n=newline
\t=tab
\"=doublequote
\\=backslash

Output
Thissectionisaboutoutputtothescreen.Outputtothescreencanalsobelatersavedto
afileusingtheexport-outputcommand.Ifyouneedamoreflexiblemethodofwriting
datatoexternalfiles,seethenextsection,FileI/O.
ThebasiccommandsforgeneratingoutputtothescreeninNetLogoareprint,show,
type,andwrite.ThesecommandssendtheiroutputtotheCommandCenter.
Forfulldetailsonthesefourcommands,seetheirentriesintheNetLogoDictionary.Here
ishowtheyaretypicallyused:
printisusefulinmostsituations.
showletsyouseewhichagentisprintingwhat.
typeletsyouprintseveralthingsonthesameline.
writeletsyouprintvaluesinaformatwhichcanbereadbackinusingfile-read.
https://ccl.northwestern.edu/netlogo/docs/programming.html

34/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

ANetLogomodelmayoptionallyhavean"outputarea"initsInterfacetab,separatefrom
theCommandCenter.TosendoutputthereinsteadoftheCommandCenter,usethe
output-print,output-show,output-type,andoutput-writecommands.
Theoutputareacanbeclearedwiththeclear-outputcommandandsavedtoafilewith
export-output.Thecontentsoftheoutputareawillbesavedbytheexport-world
command.Theimport-worldcommandwillcleartheoutputareaandsetitscontentsto
thevalueinimportedworldfile.Itshouldbenotedthatlargeamountsofdatabeingsent
totheoutputareacanincreasethesizeofyourexportedworlds.
Ifyouuseoutput-print,output-show,output-type,output-write,clear-output,or
export-outputinamodelwhichdoesnothaveaseparateoutputarea,thenthe
commandsapplytotheoutputportionoftheCommandCenter.

FileI/O
InNetLogo,thereisasetofprimitivesthatgiveyouthepowertointeractwithoutside
files.Theyallbeginwiththeprefixfile.
Therearetwomainmodeswhendealingwithfiles:readingandwriting.Thedifferenceis
thedirectionoftheflowofdata.Whenyouarereadingininformationfromafile,datathat
isstoredinthefileflowsintoyourmodel.Ontheotherhand,writingallowsdatatoflow
outofyourmodelandintoafile.
Whenworkingwithfiles,alwaysbeginbyusingtheprimitivefile-open.Thisspecifies
whichfileyouwillbeinteractingwith.Noneoftheotherprimitivesworkunlessyouopena
filefirst.
Thenextfileprimitiveyouusedictateswhichmodethefilewillbeinuntilthefileis
closed,readingorwriting.Toswitchmodes,closeandthenreopenthefile.
Thereadingprimitivesincludefile-read,file-read-line,file-read-characters,and
file-at-end?Notethatthefilemustexistalreadybeforeyoucanopenitforreading.
CodeExamples:FileInputExample
TheprimitivesforwritingaresimilartotheprimitivesthatprintthingsintheCommand
Center,exceptthattheoutputgetssavedtoafile.Theyincludefile-print,file-show,
file-type,andfile-write.Notethatyoucannever"overwrite"data.Inotherwords,if
youattempttowritetoafilewithexistingdata,allnewdatawillbeappendedtotheendof
thefile.(Ifyouwanttooverwriteafile,usefile-deletetodeleteit,thenopenitfor
writing.)
CodeExamples:FileOutputExample
Whenyouarefinishedusingafile,youcanusethecommandfile-closetoendyour
sessionwiththefile.Ifyouwishtoremovethefileafterwards,usetheprimitivefiledeletetodeleteit.Toclosemultipleopenedfiles,oneneedstofirstselectthefileby
usingfile-openbeforeclosingit.

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

35/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

;; Open 3 files
file-open "myfile1.txt"
file-open "myfile2.txt"
file-open "myfile3.txt"
;; Now close the 3 files
file-close
file-open "myfile2.txt"
file-close
file-open "myfile1.txt"
file-close

Or,ifyouknowyoujustwanttocloseeveryfile,youcanusefile-close-all.
Twoprimitivesworthnotingarefile-writeandfile-read.Theseprimitivesaredesigned
toeasilysaveandretrieveNetLogoconstantssuchasnumbers,lists,booleans,and
strings.filewritewillalwaysoutputthevariableinsuchamannerthatfilereadwillbeable
tointerpretitcorrectly.
file-open "myfile.txt" ;; Opening file for writing
ask turtles
[ file-write xcor file-write ycor ]
file-close
file-open "myfile.txt" ;; Opening file for reading
ask turtles
[ setxy file-read file-read ]
file-close

CodeExamples:FileInputExampleandFileOutputExample
Lettingtheuserchoose
Theuser-directory,user-file,anduser-new-fileprimitivesareusefulwhenyouwant
theusertochooseafileordirectoryforyourcodetooperateon.

Movies
ThissectiondescribeshowtocaptureaQuickTimemovieofaNetLogomodel.
First,usethemovie-startcommandtostartanewmovie.Thefilenameyouprovide
shouldendwith.mov,theextensionforQuickTimemovies.
Toaddaframetoyourmovie,useeithermovie-grab-viewormovie-grab-interface,
dependingonwhetheryouwantthemovietoshowjustthecurrentview,ortheentire
Interfacetab.Inasinglemovie,youmustuseonlyonemoviegrabprimitiveortheother
youcan'tmixthem.
Whenyou'redoneaddingframes,usemovie-close.
;; export a 30 frame movie of the view
setup
movie-start "out.mov"
https://ccl.northwestern.edu/netlogo/docs/programming.html

36/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

movie-grab-view ;; show the initial state


repeat 30
[ go
movie-grab-view ]
movie-close

Bydefault,amoviewillplaybackat15framespersecond.Tomakeamoviewitha
differentframerate,callmovie-set-frame-ratewithadifferentnumberofframesper
second.Youmustsettheframerateaftermovie-startbutbeforegrabbinganyframes.
Tochecktheframerateofyourmovie,ortoseehowmanyframesyou'vegrabbed,call
movie-status,whichreportsastringthatdescribesthestateofthecurrentmovie.
Tothrowawayamovieanddeletethemoviefile,callmovie-cancel.
CodeExample:MovieExample
MoviescanonlybegeneratedfromtheNetLogoGUI,notwhenrunningheadless,orby
backgroundrunsinaparallelBehaviorSpaceexperiment.
NetLogomoviesareexportedasuncompressedQuickTimefiles.ToplayaQuickTime
movie,youcanuseQuickTimePlayer,afreedownloadfromApple.
Sincethemoviesarenotcompressed,theycantakeupalotofdiskspace.Youwill
probablywanttocompressyourmovieswiththirdpartysoftware.Thesoftwaremaygive
youachoiceofdifferentkindsofcompression.Somekindsofcompressionarelossless,
whileothersarelossy."Lossy"meansthatinordertomakethefilessmaller,someofthe
detailinthemovieislost.Dependingonthenatureofyourmodel,youmaywanttoavoid
usinglossycompression,forexampleiftheviewcontainsfinepixelleveldetail.
OnesoftwarepackagethatcancompressQuickTimemoviesonboththeMacand
WindowsplatformsisQuickTimePro.OnMacs,iMovieworksaswell.PNGcompression
isagoodchoiceforlosslesscompression.

Perspective
The2Dandthe3Dviewshowtheworldfromtheperspectiveoftheobserver.Bydefault
theobserverislookingdownontheworldfromthepositivezaxisattheorigin.Youcan
changetheperspectiveoftheobserverbyusingthefollow,rideandwatchobserver
commandsandfollow-me,ride-meandwatch-meturtlecommands.Wheninfolloworride
modetheobservermoveswiththesubjectagentaroundtheworld.Thedifference
betweenfollowandrideisonlyvisibleinthe3Dview.Inthe3Dviewtheusercanchange
thedistancebehindtheagentusingthemouse.Whentheobserverisfollowingatzero
distancefromtheagentitisactuallyridingtheagent.Whentheobserverisinwatchmode
ittracksthemovementsofoneturtlewithoutmoving.Inbothviewsyouwillseeaspotlight
appearonthesubjectandinthe3Dviewtheobserverwillturntofacethesubject.To
determinewhichagentisthefocusyoucanusethesubjectreporter.
CodeExample:PerspectiveExample

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

37/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Drawing
Thedrawingisalayerwhereturtlescanmakevisiblemarks.
Intheview,thedrawingappearsontopofthepatchesbutunderneaththeturtles.Initially,
thedrawingisemptyandtransparent.
Youcanseethedrawing,buttheturtles(andpatches)can't.Theycan'tsensethe
drawingorreacttoit.Thedrawingisjustforpeopletolookat.
Turtlescandrawanderaselinesinthedrawingusingthepen-downandpen-erase
commands.Whenaturtle'spenisdown(orerasing),theturtledraws(orerases)aline
behinditwheneveritmoves.Thelinesarethesamecolorastheturtle.Tostopdrawing
(orerasing),usepen-up.
Linesdrawnbyturtlesarenormallyonepixelthick.Ifyouwantadifferentthickness,set
thepen-sizeturtlevariabletoadifferentnumberbeforedrawing(orerasing).Innew
turtles,thevariableissetto1.
Linesmadewhenaturtlemovesinawaythatdoesn'tfixadirection,suchaswithsetxyor
move-to,theshortestpathlinethatobeysthetopologywillbedrawn.
Here'ssometurtleswhichhavemadeadrawingoveragridofrandomlyshadedpatches.
Noticehowtheturtlescoverthelinesandthelinescoverthepatchcolors.Thepen-size
usedherewas2:

Thestampcommandletsaturtleleaveanimageofitselfbehindinthedrawingandstamperaseletsitremovethepixelsbelowitinthedrawing.
Toerasethewholedrawing,usetheobservercommmandclear-drawing.(Youcanalso
useclear-all,whichclearseverythingelsetoo.)
Importinganimage
Theobservercommandimport-drawingcommandallowsyoutoimportanimagefilefrom
diskintothedrawing.
import-drawingisusefulonlyforprovidingabackdropforpeopletolookat.Ifyouwant
turtlesandpatchestoreacttotheimage,youshoulduseimport-pcolorsorimporthttps://ccl.northwestern.edu/netlogo/docs/programming.html

38/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

pcolors-rgbinstead.

ComparisontootherLogos
DrawingworkssomewhatdifferentlyinNetLogothansomeotherLogos.
Notabledifferencesinclude:
Newturtles'pensareup,notdown.
Insteadofusingafencecommandtoconfinetheturtleinsideboundaries,in
NetLogoyouedittheworldandturnwrappingoff.
Thereisnoscreen-color,bgcolor,orsetbg.Youcanmakeasolidbackgroundby
coloringthepatches,e.g.ask patches [ set pcolor blue ].
DrawingfeaturesnotsupportedbyNetLogo:
Thereisnowindowcommand.ThisisusedinsomeotherLogostolettheturtleroam
overaninfiniteplane.
Thereisnofloodorfillcommandtofillanenclosedareawithcolor.

Topology
Thewaytheworldofpatchesisconnectedcanchange.Bydefaulttheworldisatorus
whichmeansitisn'tbounded,but"wraps"sowhenaturtlemovespasttheedgeofthe
world,itdisappearsandreappearsontheoppositeedgeandeverypatchhasthesame
numberof"neighbor"patches.Ifyou'reapatchontheedgeoftheworld,someofyour
"neighbors"areontheoppositeedge.
However,youcanchangethewrapsettingswiththeSettingsbutton.Ifwrappingisnot
allowedinagivendirectiontheninthatdirection(xory)theworldisbounded.Patches
alongthatboundarywillhavefewerthan8neighborsandturtleswillnotmovebeyondthe
edgeoftheworld.
ThetopologyoftheNetLogoworldhasfourpotentialvalues,torus,box,verticalcylinder,
orhorizontalcylinder.Thetopologyiscontrolledbyenablingordisablingwrappinginthex
orydirections.Thedefaultworldisatorus.
Atoruswrapsinbothdirections,meaningthatthetopandbottomedgesoftheworldare
connectedandtheleftandrightedgesareconnected.Soifaturtlemovesbeyondthe
rightedgeoftheworlditappearsagainontheleftandthesameforthetopandbottom.
Aboxdoesnotwrapineitherdirection.Theworldisboundedsoturtlesthattrytomove
offtheedgeoftheworldcannot.Notethatthepatchesaroundedgeoftheworldhave
fewerthaneightneighborsthecornershavethreeandtheresthavefive.
Horizontalandverticalcylinderswrapinonedirectionbutnottheother.Ahorizontal
cylinderwrapsvertically,sothetopoftheworldisconnectedtothebottom.buttheleft
andrightedgesarebounded.Averticalcylinderistheoppositeitwrapshorizontallyso
theleftandrightedgesareconnected,butthetopandbottomedgesarebounded.
CodeExample:NeighborsExample
Whencoordinateswrap,turtlesandlinkswrapvisuallyintheview,too.Ifaturtleshapeor
https://ccl.northwestern.edu/netlogo/docs/programming.html

39/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

linkextendspastanedge,partofitwillappearattheotheredge.(Turtlesthemselvesare
pointsthattakeupnospace,sotheycannotbeonbothsidesoftheworldatonce,butin
theview,theyappeartotakeupspacebecausetheyhaveashape.)
Wrappingalsoaffectshowtheviewlookswhenyouarefollowingaturtle.Onatorus,
wherevertheturtlegoes,youwillalwaysseethewholeworldaroundit:

Whereasinaboxorcylindertheworldhasedges,sotheareaspastthoseedgesshowup
intheviewasgray:

CodeExample:TermitesPerspectiveDemo(torus),AntsPerspectiveDemo
(box)
Thetopologysettingsalsocontrolthebehaviorofthedistance(xy),inradius,incone,
face(xy),andtowards(xy)primitives.Thetopologycontrolswhethertheprimitiveswrapor
not.Theyalwaysusetheshortestpathallowedbythetopology.Forexample,the
distancefromthecenterofthepatchesinthebottomrightcorner(minpxcor,minpycor)
https://ccl.northwestern.edu/netlogo/docs/programming.html

40/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

andtheupperleftcorner(maxpxcor,maxpycor)willbeasfollowsforeachtopology
giventhattheminandmaxpxcorandpycorare+/2:
Torussqrt(2)~1.414(thiswillbethesameforallworldsizessincethepatchesare
directlydiagonaltoeachotherinatorus.)
Boxsqrt(worldwidth^2+worldheight^2)~7.07
VerticalCylindersqrt(worldheight^2+1)~5.099
HorizontalCylindersqrt(worldwidth^2+1)~5.099
Alltheotherprimitiveswillactsimilarlytodistance.Ifyouformerlyused-nowrapprimitives
inyourmodelwerecommendremovingthemandchangingthetopologyoftheworld
instead.
Ifyourmodelhasturtlesthatmovearoundyou'llneedtothinkaboutwhathappensto
themwhentheyreachtheedgeoftheworld,ifthetopologyyou'reusinghassomenon
wrappingedges.Thereareafewcommonoptions:theturtleisreflectedbackintothe
world(eithersystematicallyorrandomly),theturtleexitsthesystem(dies),ortheturtleis
hidden.Itisnolongernecessarytochecktheboundsusingturtlecoordinates,insteadwe
canjustaskNetLogoifaturtleisattheedgeoftheworld.Thereareacouplewaysof
doingthis,thesimplestistousethecan-move?primitive.
if not can-move? distance [ rt 180 ]

canmove?merelyreturnstrueifthepositiondistanceinfrontoftheturtleisinsidethe
NetLogoworld,falseotherwise.Inthiscase,iftheturtleisattheedgeoftheworldit
simplegoesbackthewayitcame.Youcanalsousepatch-ahead 1 != nobodyinplaceof
can-move?.Ifyouneedtodosomethingsmarterthatsimplyturningarounditmaybe
usefultousepatch-atwithdxanddy.
if patch-at dx 0 = nobody [
set heading (- heading)
]
if patch-at 0 dy = nobody [
set heading (180 - heading)
]

Thistestswhethertheturtleishittingahorizontalorverticalwallandbouncesoffthat
wall.
Insomemodelsifaturtlecan'tmoveforwarditsimplydies(exitsthesystem,likein
ConductororMousetraps).
if not can-move? distance[ die ]

Ifyouaremovingturtlesusingsetxyratherthanforwardyoushouldtesttomakesurethe
patchyouareabouttomovetoexistssincesetxythrowsaruntimeerrorifitisgiven
coordinatesoutsidetheworld.Thisisacommonsituationwhenthemodelissimulating
aninfiniteplaneandturtlesoutsidetheviewshouldsimplybehidden.
let new-x new-value-of-xcor
let new-y new-value-of-ycor
https://ccl.northwestern.edu/netlogo/docs/programming.html

41/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

ifelse patch-at (new-x - xcor) (new-y - ycor) = nobody


[ hide-turtle ]
[ setxy new-x new-y
show-turtle ]

SeveralmodelsintheModelsLibraryusethistechnique,Gravitation,NBodies,and
Electrostaticsaregoodexamples.
Thediffuseanddiffuse4commandsbehavecorrectlyinalltopologies.Eachpatch
diffusesandequalamountofthediffusevariabletoeachofitsneighbors,ifithasfewer
than8neighbors(or4ifyouareusingdiffuse4),theremainderstaysonthediffusing
patch.Thismeansthattheoverallsumofpatchvariableacrosstheworldremains
constant.However,ifyouwantthediffusemattertostillfallofftheedgesoftheworldasit
wouldonaninfiniteplaneyoustillneedtocleartheedgeseachstepasintheDiffuseOff
EdgesExample.

Links
Alinkisanagentthatconnectstwoturtles.Theseturtlesaresometimesalsocalled
nodes.
Thelinkisalwaysdrawnasalinebetweenthetwoturtles.Linksdonothavealocationas
turtlesdo,theyarenotconsideredtobeonanypatchandyoucannotfindthedistance
fromalinktoanotherpoint.
Therearetwoflavorsoflinks,undirectedanddirected.Adirectedlinkisoutof,orfrom,
onenodeandinto,orto,anothernode.Therelationshipofaparenttoachildcouldbe
modeledasadirectedlink.Anundirectedlinkappearsthesametobothnodes,each
nodehasalinkwithanothernode.Therelationshipbetweenspouses,orsiblings,could
bemodeledasanundirectedlink.
Thereisaglobalagentsetofalllinks,justaswithturtlesandpatches.Youcancreate
undirectedlinksusingthecreate-link-withandcreate-links-withcommandsand
directedlinksusingthecreate-link-to,create-links-to,create-link-from,andcreatelinks-fromcommands.Oncethefirstlinkhasbeencreateddirectedorundirected,all
unbreededlinksmustmatch(linksalsosupportbreeds,muchliketurtles,whichwillbe
discussedshortly)it'simpossibletohavetwounbreededlinkswhereoneisdirectedand
theotherisundirected.Aruntimeerroroccursifyoutrytodoit.(Ifallunbreededlinksdie,
thenyoucancreatelinksofthatbreedthataredifferentinflavorfromthepreviouslinks.)
Ingeneral,primitivesthatworkwithdirectedlinkshave"in","out","to",and"from"intheir
names.Undirectedoneseitheromittheseoruse"with".
Alink'send1andend2variablescontainthetwoturtlesthelinkconnects.Ifthelinkis
directed,itgoesfromend1toend2.Ifthelinkisundirected,end1isalwaystheolderof
thetwoturtles,thatis,theturtlewiththesmallerwhonumber.
Linkbreeds,liketurtlebreeds,allowyoutodefinedifferenttypesoflinksinyourmodel.
Linkbreedsmusteitherbedirectedorundirected,unlikeunbreededlinksthisisdefinedat
compiletimeratherthanruntime.Youdeclarelinkbreedsusingthekeywords
undirected-link-breedanddirected-link-breed.Breededlinkscanbecreatedusingthe
commandscreate-<breed>-withandcreate-<breeds>-withforundirectedbreedsandthe
commandscreate-<breed>-to,create-<breeds>-to,create-<breed>-from,andcreate<breeds>-fromfordirectedlinks.
https://ccl.northwestern.edu/netlogo/docs/programming.html

42/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Therecannotbemorethanoneundirectedlinkofthesamebreed(ormorethanone
unbreededundirectedlink)betweenapairofagents,normorethanonedirectedlinkof
thesamebreedinthesamedirectionbetweenapairofagents.Youcanhavetwo
directedlinksofthesamebreed(ortwounbreededdirectedlinks)betweenapairifthey
areinoppositedirections.
Layouts
Aspartofournetworksupportwehavealsoaddedseveraldifferentprimitivesthatwill
helpyoutovisualizethenetworks.Thesimplestislayout-circlewhichevenlyspaces
theagentsaroundthecenteroftheworldgivenaradius.

layout-radialisagoodlayoutifyouhavesomethinglikeatreestructure,thoughevenif

therearesomecyclesinthetreeitwillstillwork,thoughastherearemoreandmore
cyclesitwillprobablynotlookasgood.layout-radialtakesarootagenttobethecentral
nodeplacesitat(0,0)andarrangesthenodesconnectedtoitinaconcentricpattern.
Nodesonedegreeawayfromtherootwillbearrangedinacircularpatternaroundthe
centralnodeandthenextlevelaroundthosenodesandsoon.layout-radialwillattempt
toaccountforasymmetricalgraphsandgivemorespacetobranchesthatarewider.
layout-radialalsotakesabreedasaninputsoyouuseonebreedoflinkstolayoutthe
networkandnotanother.

Givenasetofanchornodeslayout-tutteplacesalltheothernodesatthecenterof
massofthenodesitislinkedto.Theanchorsetisautomaticallyarrangedinacircle
layoutwithauserdefinedradiusandtheothernodeswillconvergeintoplace(thisof
https://ccl.northwestern.edu/netlogo/docs/programming.html

43/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

coursemeansthatyoumayhavetorunitseveraltimesbeforethelayoutisstable.)

layout-springisusefulformanykindsofnetworks.Thedrawbackisthatisrelativelyslow

sinceittakesmanyiterationstoconverge.Inthislayoutthelinksactasspringsthatpull
thenodestheyconnecttowardeachotherandthenodesrepeleachother.Thestrength
oftheforcesiscontrolledbyinputstotheprimitives.Theseinputswillalwayshavea
valuebetween0and1keepinmindthatverysmallchangescanstillaffectthe
appearanceofthenetwork.Thespringsalsohavealength(inpatchunits),however,
becauseofalltheforcesinvolvedthenodeswillnotendupexactlythatdistancefrom
eachother.
CodeExamples:NetworkExample,NetworkImportExample,GiantComponent,
SmallWorlds,PreferentialAttachment

Tasks
Tasksletyoustorecodetoberunlater.Therearetwokinds,commandtasksand
reportertasks.
Tasksarevalues,whichmeansthatataskmaybepassedasinput,reportedasaresult,
orstoredinavariable.
Agiventaskmightberunonce,multipletimes,ornotatall.
Inotherprogramminglanguagestasksareknownasfirstclassfunctions,closures,or
lambda.

Taskprimitives
Primitivesspecifictotasksaretask,is-command-task?,andis-reporter-task?.
Thetaskprimitivecreatesatask.Thetaskitreportsmightbeacommandtaskora
reportertask,dependingonwhatkindofblockyoupassit.Forexampletask [ fd 1 ]
reportsacommandtask,becausefdisacommand,whiletask [ count turtles ]
reportsareportertask,becausecountisareporter.
https://ccl.northwestern.edu/netlogo/docs/programming.html

44/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Theseprimitivesrequiretasksasinput:foreach,map,reduce,filter,n-values,sort-by.
Whencallingtheseprimitives,thetaskprimitiveisoptional,soforexampleonemaywrite
simplyforeach mylist [ print ? ]insteadofforeach mylist task [ print ? ],though
thelatterisalsoaccepted.(Becausetaskisoptional,thesyntaxfortheseprimitivesis
backwardcompatiblewithexistingcodefrompreviousNetLogoversions.)
Theruncommandacceptscommandtasksaswellasstrings.
Therunresultreporteracceptsreportertasksaswellasstrings.
runandrunresultallowpassinginputstoatask.Aswithallprimitivesacceptingvarying

numberofinputs,thewholecallmustbesurroundedwithparentheses,soforexample
(run my-command-task 5)or(runresult my-reporter-task "foo" 2).Whennotpassing
input,noparenthesesarerequired.

Taskinputs
Ataskmaytakezeroormoreinputs.Theinputsarereferencedusingthespecial
variables?(aka?1),?2,?3,etc.Anyextrainputsareignored.

Tasksandstrings
Creatingandrunningtasksisfast.Touserunorrunresultonanewstringforthefirst
timeisabout100xslowerthanrunningatask.Modelersshouldnormallyusetasks
insteadofrunningstrings,exceptwhenrunningstringsenteredbytheuser.

Concisesyntax
Simpleusesofforeach,map,reduce,filter,n-values,andsort-bycanbewrittenwithan
especiallyconcisesyntax.Youcanwrite:
map abs [1 -2 3 -4] => [1 2 3 4]
reduce + [1 2 3 4] => 10
filter is-number? [1 "x" 3] => [1 3]
foreach [1 2 3 4] print

InolderNetLogoversions,thesehadtobewritten:
map [abs ?] [1 -2 3 -4] => [1 2 3 4]
reduce [?1 + ?2] [1 2 3 4] => 10
filter [is-number? ?] [1 "x" 3] => [1 3]
foreach [1 2 3 4] [ print ? ]

Theoldsyntaxremainsvalid.
Theconcisesyntaxcanalsobeusedwiththetaskprimitive.Soforexampletask dieis
shortfortask [ die ],task fdisshortfortask [fd ?],andtask +isshortfortask [?1
+ ?2].

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

45/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Tasksare"closures"thatmeanstheycaptureor"closeover"thebindings(notjustthe
currentvalues)oflocalvariablesandprocedureinputs.Theydonotcaptureagent
variablesanddonotcapturetheidentity(oreventheagenttype)ofthecurrentagent.

Nonlocalexits
Thestopandreportcommandsexitfromthedynamicallyenclosingprocedure,notthe
enclosingtask.(ThisisbackwardcompatiblewitholderNetLogoversions.)

Tasksandextensions
TheextensionsAPIsupportswritingprimitivesthataccepttasksasinput.Writeusfor
samplecode.

Limitations
WehopetoaddressatleastsomeofthefollowinglimitationsinfutureNetLogoversions:
import-worlddoesnotsupporttasks.

Taskinputscan'tbegivennames.Thiscanmakenestingreportertasksdifficult.
(Commandtaskscanuselettogivetheirinputsnames,ifneeded.)
Taskscan'tbevariadic(acceptavaryingnumberofinputs).
Reportertaskscan'tcontaincommands,onlyasinglereporterexpression.Sofor
exampleyoumustuseifelse-valuenotif,andyoudon'tusereportatall.Ifyour
codeistoocomplextobewrittenasonereporter,you'llneedtomovethecodetoa
separatereporterprocedure,andthencallthatprocedurefromyourtask,passingit
anyneededinputs.
Tasksarenotinterchangeablewithcommandblocksandreporterblocks.Onlythe
primitiveslistedaboveaccepttasksasinput.Controlprimitivessuchasifelseand
whileandagentprimitivessuchasofandwithdon'taccepttasks.Soforexampleif
Ihaveareportertaskrandtwocommandtasksc1andc2,Ican'twriteifelse r c1
c2,Imustwriteifelse runresult r [ run c1 ] [ run c2 ].
Theconcisesyntaxwheretaskmaybeomittedisonlyavailabletoprimitivesand
extensionprimitives,notordinaryprocedures.SoforexampleifIhaveaprocedurep
thatacceptsataskasinput,itmustbecalledase.g.p task [ ... ]notp [ ... ].

Codeexample
CodeExample:StateMachineExample

AskConcurrent
NOTE:Thefollowinginformationisincludedonlyforbackwardscompatibility.Wedon't
recommendusingtheask-concurrentprimitiveatallinnewmodels.
InveryoldversionsofNetLogo,askhadsimulatedconcurrentbehaviorbydefault.Since
NetLogo4.0(2007),askisserial,thatis,theagentsrunthecommandsinsidetheaskone
atatime.
https://ccl.northwestern.edu/netlogo/docs/programming.html

46/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Thefollowinginformationdescribesthebehavioroftheask-concurrentcommand,which
behavesthewaytheoldaskbehaved.
ask-concurrentproducessimulatedconcurrencyviaamechanismofturntaking.Thefirst

agenttakesaturn,thenthesecondagenttakesaturn,andsoonuntileveryagentinthe
askedagentsethashadaturn.Thenwegobacktothefirstagent.Thiscontinuesuntilall
oftheagentshavefinishedrunningallofthecommands.
Anagent's"turn"endswhenitperformsanactionthataffectsthestateoftheworld,such
asmoving,orcreatingaturtle,orchangingthevalueofaglobal,turtle,patch,orlink
variable.(Settingalocalvariabledoesn'tcount.)
Theforward(fd)andback(bk)commandsaretreatedspecially.Whenusedinsideaskconcurrent,thesecommandscantakemultipleturnstoexecute.Duringitsturn,theturtle
canonlymovebyonestep.Thus,forexample,fd 20isequivalenttorepeat 20 [ fd 1 ],
wheretheturtle'sturnendsaftereachrunoffd.Ifthedistancespecifiedisn'taninteger,
thelastfractionofsteptakesafullturn.Soforexamplefd 20.3isequivalenttorepeat 20
[ fd 1 ] fd 0.3.
Thejumpcommandalwaystakesexactlyoneturn,regardlessofdistance.
Tounderstandthedifferencebetweenaskandask-concurrent,considerthefollowingtwo
commands:
ask turtles [ fd 5 ]
ask-concurrent turtles [ fd 5 ]

Withask,thefirstturtletakesfivestepsforward,thenthesecondturtletakesfivesteps
forward,andsoon.
Withask-concurrent,alloftheturtlestakeonestepforward.Thentheyalltakeasecond
step,andsoon.Thus,thelattercommandisequivalentto:
repeat 5 [ ask turtles [ fd 1 ] ]

CodeExample:AskConcurrentExampleshowsthedifferencebetweenaskand
ask-concurrent.
Thebehaviorofask-concurrentcannotalwaysbesosimplyreproducedusingask,asin
thisexample.Considerthiscommand:
ask-concurrent turtles [ fd random 10 ]

Inordertogetthesamebehaviorusingask,wewouldhavetowrite:
turtles-own [steps]
ask turtles [ set steps random 10 ]
while [any? turtles with [steps > 0]] [
ask turtles with [steps > 0] [
fd 1
https://ccl.northwestern.edu/netlogo/docs/programming.html

47/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

set steps steps - 1

Toprolonganagent's"turn",usethewithout-interruptioncommand.(Thecommand
blocksinsidesomecommands,suchascreate-turtlesandhatch,haveanimplied
without-interruptionaroundthem.)
Notethatthebehaviorofask-concurrentiscompletelydeterministic.Giventhesame
codeandthesameinitialconditions,thesamethingwillalwayshappen(ifyouareusing
thesameversionofNetLogoandbeginyourmodelrunwiththesamerandomseed).
Ingeneral,wesuggestyounotuseask-concurrentatall.Ifyoudo,wesuggestyouwrite
yourmodelsothatitdoesnotdependontheexactdetailsofhowask-concurrentworks.
Wemakenoguaranteesthatitssemanticswillremainthesameinfutureversionsof
NetLogo,orthatitwillcontinuetobesupportedatall.

Tie
Tieconnectstwoturtlessothatthemovementofoneturtlesaffectsthelocationand
headingofanother.Tieisapropertyoflinkssotheremustbealinkbetweentwoturtlesto
createatierelationship.
Whenalink'stie-modeissetto"fixed"or"free"end1andend2aretiedtogether.Ifthelink
isdirectedend1isthe"rootagent"andend2isthe"leafagent".Thatiswhenend1moves
(usingfd,jump,setxy,etc.)end2alsomovesthesamedistanceanddirection.However
whenend2movesitdoesnotaffectend1.
Ifthelinkisundirecteditisareciprocaltierelationship,meaning,ifeitherturtlemovesthe
otherturtlewillalsomove.Sodependingonwhichturtleismovingeitherturtlecanbe
consideredtherootortheleaf.Therootturtleisalwaystheturtlethatinitiatesthe
movement.
Whentherootturtleturnsrightorleft,theleafturtlerotatesaroundtherootturtlethe
sameamountasifastiffwereattachingtheturtles.Whentie-modeissetto"fixed"the
headingoftheleafturtlechangesbythesameamount.Ifthetie-modeissetto"free"the
headingoftheleafturtleisunchanged.
Thetie-modeofalinkcanbesetto"fixed"usingthetiecommandandsetto"none"
(meaningtheturtlesarenolongertied)usinguntietosetthemodeto"free"youneedto:
set tie-mode "free".
CodeExample:TieSystemExample

Multiplesourcefiles
The__includeskeywordallowsyoutousemultiplesourcefilesinasingleNetLogo
model.
Thekeywordbeginswithtwounderscorestoindicatethatthefeatureisexperimentaland
maychangeinfutureNetLogoreleases.
https://ccl.northwestern.edu/netlogo/docs/programming.html

48/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Whenyouopenamodelthatusesthe__includeskeyword,orifyouaddittothetopofa
modelandhittheCheckbutton,theincludesmenuwillappearinthetoolbar.Fromthe
includesmenuyoucanselectfromthefilesincludedinthismodel.
Whenyouopenincludedfilestheyappearinadditionaltabs.SeetheInterfaceGuidefor
moredetails.
Youcanhaveanythinginexternalsourcefiles(.nls)thatyouwouldnormallyputinthe
Codetab:globals,breed,turtles-own,patches-own,breeds-own,proceduredefinitions,
etc.Notethoughthatthesedeclarationsallsharethesamenamespace.Thatis,ifyou
declareaglobalmy-globalintheCodetabyoucannotdeclareaglobal(oranythingelse)
withthenamemy-globalinanyfilethatisincludedinthemodel.my-globalwillbe
accessiblefromalltheincludedfiles.Thesamewouldbetrueifmy-globalweredeclared
inoneoftheincludedfiles.

Syntax
Colors
IntheCodetabandelsewhereintheNetLogouserinterface,programcodeiscolor
codedbythefollowingscheme:
Keywordsaregreen
Constantsareorange
Commentsaregray
Primitivecommandsareblue
Primitivereportersarepurple
Everythingelseisblack

Notice
Theremainderofthissectioncontainstechnicalterminologywhichwillbeunfamiliarto
somereaders.

Keywords
Theonlykeywordsinthelanguageareglobals,breed,turtles-own,patches-own,to,toreport,andend,plusextensionsandtheexperimental__includeskeyword.(Builtin
primitivenamesmaynotbeshadowedorredefined,sotheyareeffectivelyakindof
keywordaswell.)

Identifiers
Allprimitives,globalandagentvariablenames,andprocedurenamesshareasingle
globalcaseinsensitivenamespacelocalnames(letvariablesandthenamesof
procedureinputs)maynotshadowglobalnamesoreachother.Identifiersmaycontain
anyUnicodeletterordigitandthefollowingASCIIcharacters:
.?=*!<>:#+/%$_^'&https://ccl.northwestern.edu/netlogo/docs/programming.html

49/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Someprimitivenamesbeginwithtwounderscorestoindicatethattheyareexperimental
andareespeciallylikelytochangeorberemovedinfutureNetLogoreleases.
Identifiersbeginningwithaquestionmarkarereserved.

Scope
NetLogoislexicallyscoped.Localvariables(includinginputstoprocedures)are
accessiblewithintheblockofcommandsinwhichtheyaredeclared,butnotaccessibleby
procedurescalledbythosecommands.

Comments
Thesemicoloncharacterintroducesacomment,whichlastsuntiltheendoftheline.
Thereisnomultilinecommentsyntax.

Structure
Aprogramconsistsofoptionaldeclarations(globals,breed,turtles-own,patches-own,
<BREED>-own,extensions)inanyorder,followedbyzeroormoreproceduredefinitions.
Multiplebreedsmaybedeclaredwithseparatebreeddeclarationstheotherdeclarations
mayappearonceonly.
Everyproceduredefinitionbeginswithtoorto-report,theprocedurename,andan
optionalbracketedlistofinputnames.Everyproceduredefinitionendswithend.In
betweenarezeroormorecommands.

Commandsandreporters
Commandstakezeroormoreinputstheinputsarereporters,whichmayalsotakezero
ormoreinputs.Nopunctuationseparatesorterminatescommandsnopunctuation
separatesinputs.Identifiersmustbeseparatedbywhitespaceorbyparenthesesor
squarebrackets.(Soforexample,a+bisasingleidentifier,buta(b[c]d)econtainsfive
identifiers.)
Allcommandsareprefix.Alluserdefinedreportersareprefix.Mostprimitivereportersare
prefix,butsome(arithmeticoperators,booleanoperators,andsomeagentsetoperators
likewithandinpoints)areinfix.
Allcommandsandreporters,bothprimitiveanduserdefined,takeafixednumberof
inputsbydefault.(That'swhythelanguagecanbeparsedthoughthereisnopunctuation
toseparateorterminatecommandsand/orinputs.)Someprimitivesarevariadic,thatis,
mayoptionallytakeadifferentnumberofinputsthanthedefaultparenthesesareusedto
indicatethis,e.g.(list 1 2 3)(sincethelistprimitiveonlytakestwoinputsbydefault).
Parenthesesarealsousedtooverridethedefaultoperatorprecedence,e.g.(1 + 2) * 3,
asinotherprogramminglanguages.
Sometimesaninputtoaprimitiveisacommandblock(zeroormorecommandsinside
squarebrackets)orareporterblock(asinglereporterexpressioninsidesquarebrackets).
Userdefinedproceduresmaynottakeacommandorreporterblockasinput.
https://ccl.northwestern.edu/netlogo/docs/programming.html

50/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

Operatorprecedencesareasfollows,hightolow:
with,at-points,in-radius,in-cone

(allotherprimitivesanduserdefinedprocedures)
^
*,/,mod
+,<,>,<=,>=
=,!=
and,or,xor

ComparedtootherLogos
ThereisnoagreeduponstandarddefinitionofLogoitisaloosefamilyoflanguages.We
believethatNetLogohasenoughincommonwithotherLogostoearntheLogoname.
Still,NetLogodiffersinsomerespectsfrommostotherLogos.Themostimportant
differencesareasfollows.

Surfacedifferences
Theprecedenceofmathematicaloperatorsisdifferent.Infixmathoperators(like+,
*,etc.)havelowerprecedencethanreporterswithnames.Forexample,inmany
Logos,ifyouwritesin x + 1,itwillbeinterpretedassin (x + 1).NetLogo,onthe
otherhand,interpretsitthewaymostotherprogramminglanguageswould,andthe
waythesameexpressionwouldbeinterpretedinstandardmathematicalnotation,
namelyas(sin x) + 1.
Theandandorreportersarespecialforms,notordinaryfunctions,andthey"short
circuit",thatis,theyonlyevaluatetheirsecondinputifnecessary.
ProcedurescanonlybedefinedintheCodetab,notinteractivelyintheCommand
Center.
Reporterprocedures,thatis,proceduresthat"report"(return)avalue,mustbe
definedwithto-reportinsteadofto.Thecommandtoreportavaluefromareporter
procedureisreport,notoutput.
Whendefiningaprocedure,theinputstotheproceduremustbeenclosedinsquare
brackets,e.g.to square [x].
Variablenamesarealwaysusedwithoutanypunctuation:alwaysfoo,never:fooor
"foo.(Tomakethiswork,insteadofamakecommandtakingaquotedargumentwe
supplyasetspecialformwhichdoesnotevaluateitsfirstinput.)Asaresult,
proceduresandvariablesoccupyasinglesharednamespace.
Thelastthreedifferencesareillustratedinthefollowingproceduredefinitions:
mostLogos
to square :x
output :x * :x
end

NetLogo
to-report square [x]
report x * x
end

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

51/52

7/26/2016

NetLogo 5.3.1 User Manual: Programming Guide

NetLogo'slocalvariablesandinputstoproceduresarelexicallyscoped,not
dynamicallyscoped.
NetLogohasno"word"datatype(whatLispcalls"symbols").Eventually,wemay
addone,butsinceitisseldomrequested,itmaybethattheneeddoesn'tarise
muchinagentbasedmodeling.Wedohavestrings.Inmostsituationswhere
traditionalLogowouldusewords,wesimplyusestringsinstead.Forexamplein
Logoyoucouldwrite[see spot run](alistofwords),butinNetLogoyoumustwrite
"see spot run"(astring)or["see" "spot" "run"](alistofstrings)instead.
NetLogo'sruncommandworksontasksandstrings,notlists(sincewehaveno
"word"datatype),anddoesnotpermitthedefinitionorredefinitionofprocedures.
Controlstructuressuchasifandwhilearespecialforms,notordinaryfunctions.
Youcan'tdefineyourownspecialforms,soyoucan'tdefineyourowncontrol
structures.(Youcandosomethingsimilarusingtasks,butyoumustusethetask,
run,andrunresultprimitivesforthat,youcannotmakethemimplicit.)
Tasks(akafunctionvaluesorlambda)aretruelexicallyscopedclosures.This
featureisavailableinNetLogoandinmodernLisps,butnotinstandardLogo.
Ofcourse,theNetLogolanguagealsocontainsotherfeaturesnotfoundinmostLogos,
mostimportantlyagentsandagentsets.

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

52/52

Potrebbero piacerti anche