NetLogo 6.0.4 User Manual Net Logo

NetLogo%20User%20Manual

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 436 [warning: Documents this large are best viewed by clicking the View PDF Link!]

TheNetLogo6.0.4UserManual
2
26
26
28
28
28
28
28
28
29
29
29
29
30
30
30
30
31
31
32
32
33
33
33
34
34
34
35
35
35
35
36
37
37
37
37
37
37
38
38
38
38
39
39
39
41
41
41
42
42
42
43
43
43
44
44
44
TableofContents
TableofContents
WhatisNetLogo?
Features
CopyrightandLicenseInformation
Howtoreference
Acknowledgments
NetLogolicense
Commerciallicenses
NetLogoUserManuallicense
Opensource
Thirdpartylicenses
Scala
MersenneTwisterFast
Colt
Config
ApacheCommonsCodec(TM)
Flexmark
JHotDraw
JOGL
Matrix3D
ASM
Log4j
PicoContainer
Parboiled
RSyntaxTextArea
JCodec
Java-Objective-CBridge
Webcam-capture
Guava
Gephi
RExtension
JNA
What'snew?
Version6.0.4(May2018)
FeatureChanges
Bugfixes
DocumentationChanges
ModelChanges
Version6.0.3(March2018)
FeatureChanges
DocumentationChanges
Bugfixes
ExtensionChanges
DocumentationChanges
ModelChanges
Version6.0.2(August2017)
FeatureChanges
Bugfixes
ExtensionChanges
DocumentationChanges
ModelChanges
Version6.0.1(March2017)
FeatureChanges
Bugfixes
ExtensionChanges
DocumentationChanges
Models
45
45
45
46
46
47
47
47
47
49
49
49
49
50
50
50
50
50
50
50
51
51
51
51
51
52
52
52
52
53
53
54
54
54
54
54
54
54
54
55
55
56
56
56
56
56
56
56
58
58
58
58
58
59
59
61
Version6.0(December2016)
FeatureChanges
Bugfixes
LanguageChanges
ExtensionChanges
OperatingSystemSupport
DocumentationChanges
InternationalizationChanges
Models
Version5.3.1(February2016)
FeatureChanges
ExtensionChanges
Bugfixes
Version5.3(December2015)
FeatureChanges
ExtensionChanges
Version5.2.1(September2015)
Extensions
Newfeatures
Bugfixes
Modelchanges
Version5.2.0(April2015)
Extensions
Newfeatures
Bugfixes
Modelchanges
Version5.1.0(July2014)
Version5.0.4(March2013)
Version5.0(February2012)
Version4.1.3(April2011)
Version4.1(December2009)
Version4.0(September2007)
Version3.1(April2006)
Version3.0(September2005)
Version2.1(December2004)
Version2.0.2(August2004)
Version2.0(December2003)
Version1.3(June2003)
Version1.2(March2003)
Version1.1(July2002)
Version1.0(April2002)
SystemRequirements
ApplicationRequirements
Windows
MacOSX
Linux
3DRequirements
32-bitor64-bit?
ContactingUs
Website
Feedback,questions,etc.
Reportingbugs
Opensource
SampleModel:Party
AtaParty
Challenge
61
62
63
63
64
64
65
67
67
67
67
71
71
71
71
72
72
73
73
73
76
77
81
82
82
82
84
84
85
85
86
87
88
89
90
91
92
92
93
95
95
95
99
99
99
100
100
101
101
101
102
104
106
106
Thinkingwithmodels
What’snext?
Tutorial#1:Models
SampleModel:WolfSheepPredation
ControllingtheModel:Buttons
Controllingspeed:SpeedSlider
AdjustingSettings:SlidersandSwitches
GatheringInformation:PlotsandMonitors
Plots
Monitors
ControllingtheView
ModelsLibrary
SampleModels
CurricularModels
CodeExamples
HubNetActivities
What’sNext?
Tutorial#2:Commands
SampleModel:TrafficBasic
CommandCenter
Workingwithcolors
AgentMonitorsandAgentCommanders
What’sNext?
Tutorial#3:Procedures
Agentsandprocedures
Makingthesetupbutton
Switchingtotick-basedviewupdates
Makingthegobutton
Experimentingwithcommands
Patchesandvariables
Turtlevariables
Monitors
Switchesandlabels
Moreprocedures
Plotting
Tickcounter
Somemoredetails
What’snext?
Appendix:Completecode
InterfaceGuide
Menus
Chart:NetLogomenus
Tabs
InternationalUsage
Charactersets
Languages
Supportfortranslators
InterfaceTabGuide
Workingwithinterfaceelements
Chart:InterfaceToolbar
The2Dand3Dviews
Manipulatingthe3DView
CommandCenter
Reporters
107
107
107
107
107
108
109
111
111
112
112
113
113
113
113
113
113
113
113
114
114
114
114
114
114
114
115
115
116
116
116
117
117
117
117
117
118
118
118
118
118
118
119
119
119
120
120
120
121
121
122
123
123
123
125
126
126
Accessingpreviouscommands
Clearing
Arranging
Plots
PlotPens
Sliders
AgentMonitors
InfoTab
Editing
Headings
Input
Paragraphs
Example
Formatted
Italicizedandboldtext
Example
Formatted
Orderedlists
Example
Formatted
Unorderedlists
Example
Formatted
Links
Automaticlinks
Linkswithtext
Locallinks
Images
Example
Formatted
Localimages
Blockquotations
Example
Formatted
Code
Example
Formatted
Codeblocks
Example
Formatted
Superscriptsandsubscripts
Example
Formatted
Notesonusage
Otherfeatures
CodeTabGuide
CheckingforErrors
Find&Replace
AutomaticIndentation
MoreEditingOptions
IncludedFilesMenu
ProgrammingGuide
Agents
Procedures
Variables
Tickcounter
Whentotick
126
127
129
130
132
132
132
133
134
135
139
141
142
142
142
142
143
143
143
144
144
145
145
145
146
146
147
147
147
147
147
148
148
149
149
150
151
152
152
153
156
158
158
158
158
159
159
159
159
159
160
160
160
162
162
162
162
163
163
Fractionalticks
Colors
Ask
Agentsets
Specialagentsets
Agentsetsandlists
Breeds
Linkbreeds
Buttons
Lists
Math
Randomnumbers
Auxiliarygenerator
Localrandomness
Turtleshapes
Linkshapes
Viewupdates
Continuousupdates
Tick-basedupdates
Choosingamode
Framerate
Plotting
Plottingpoints
Plotcommands
Otherkindsofplots
Histograms
Clearingandresetting
Rangesandautoscaling
UsingaLegend
Temporaryplotpens
set-current-plotandset-current-plot-pen
Conclusion
Strings
Output
HowOutputPrimitivesDiffer
FileI/O
Movies
Perspective
Drawing
Topology
Links
Anonymousprocedures
Anonymousprocedureprimitives
Anonymousprocedureinputs
Anonymousproceduresandstrings
Concisesyntax
Anonymousproceduresasclosures
Nonlocalexits
Anonymousproceduresandextensions
Limitations
WhatisOptional?
Codeexample
Ask-Concurrent
UserInteractionPrimitives
Whatdoes“Halt”mean?
Tie
Multiplesourcefiles
Syntax
Colors
163
163
163
163
163
164
164
164
166
166
166
166
166
166
167
168
169
169
169
169
170
170
170
171
171
171
171
171
171
172
173
174
174
174
174
175
175
176
176
176
177
177
177
178
179
179
180
181
182
182
182
183
183
183
183
183
185
185
185
187
187
Notice
Keywords
Identifiers
Scope
Comments
Structure
Commandsandreporters
ComparedtootherLogos
TransitionGuide
ChangesforNetLogo6.0.3
ArduinoExtensionChanges
CFExtensionChanges
ChangesforNetLogo6.0
TasksreplacedbyAnonymousProcedures
Linkreportersoverhauledtobemoreconsistentandflexible
RemovalofApplets
ChangestotheNetLogoUserInterface
NobodyNotPermittedasaChooserValue
Breedsmusthavesingularandpluralnames
Removalof“Movie”Prims
ImprovedNameCollisionDetection
Removalofhubnet-set-client-interface
Improved&UpdatedExtensionsAPI
Addrangeprimitive
ChangesforNetLogo5.2
hsbprimitives
GoGoextension
ChangesforNetLogo5.0
Plotting
Tickcounter
Unicodecharacters
Infotabs
Modelspeed
Listperformance
ExtensionsAPI
ChangesforNetLogo4.1
Combiningsetandof
ChangesforNetLogo4.0
Whonumbering
Turtlecreation:randomizedvs.“ordered”
Addingstringsandlists
The-atprimitives
Links
New“of”syntax
Serialask
Tickcounter
Viewupdatemodes
Speedslider
Numbers
Agentsetbuilding
RGBColors
Tie
ChangesforNetLogo3.1
Agentsets
Wrapping
Randomturtlecoordinates
ShapesEditorGuide
Gettingstarted
Importingshapes
Creatingandeditingturtleshapes
Tools
187
188
188
188
188
188
188
188
189
189
191
191
191
192
192
192
194
194
196
196
198
199
199
200
200
200
200
201
201
203
203
203
203
206
207
209
209
209
209
209
209
210
210
210
211
211
212
213
213
213
213
214
214
214
215
216
217
217
Previews
Overlappingshapes
Undo
Colors
Otherbuttons
Shapedesign
Keepingashape
Creatingandeditinglinkshapes
Changinglinkshapeproperties
Usingshapesinamodel
BehaviorSpaceGuide
WhatisBehaviorSpace?
WhyBehaviorSpace?
HowItWorks
Managingexperimentsetups
Creatinganexperimentsetup
SpecialprimitivesforBehaviorSpaceexperiments
Runninganexperiment
AdvancedUsage
Runningfromthecommandline
SettingupexperimentsinXML
AdjustingJVMParameters
ControllingAPI
SystemDynamicsGuide
WhatistheNetLogoSystemDynamicsModeler?
BasicConcepts
SampleModels
HowitWorks
DiagramTab
CodeTab
TheSystemDynamicsModelerandNetLogo
Tutorial:Wolf-SheepPredation
Step1:SheepReproduction
Step2:NetLogoIntegration
Step3:WolfPredation
HubNetGuide
UnderstandingHubNet
NetLogo
HubNetArchitecture
ComputerHubNet
Activities
Clients
Requirements
Startinganactivity
HubNetControlCenter
Troubleshooting
KnownLimitations
Teacherworkshops
HubNetAuthoringGuide
RunningHubNetinheadlessmode
Gettinghelp
HubNetAuthoringGuide
CodingHubNetactivities
Setup
Receivingmessagesfromclients
Sendingmessagestoclients
Examples
Howtomakeaclientinterface
218
218
218
219
220
220
220
220
221
222
222
224
224
224
224
224
224
226
227
228
229
229
229
230
231
231
231
232
232
232
233
233
234
234
236
237
239
239
239
239
239
240
240
241
241
241
241
241
242
242
243
243
243
243
244
244
244
Viewupdatesontheclients
Clickingintheviewonclients
Customizingtheclient’sview
Plotupdatesontheclients
ModelingCommonsGuide
Introduction
ModelingCommonsAccounts
UploadingModels
UploadANewModel
UploadAChildOfAnExistingModel(“forking”)
UpdatingAnExistingModel
Logging
Startinglogging
MacOSXorWindows
Linuxandothers
Usinglogging
Wherelogsarestored
Howtoconfiguretheloggingoutput
AdvancedConfiguration
ControllingGuide
MathematicaLink
WhatcanIdowithit?
Installation
Usage
KnownIssues
Sourcecode
Credits
NetLogo3D
Introduction
3DWorlds
Theobserverandthe3Dview
CustomShapes
Tutorial
Step1:Depth
Step2:TurtleMovement
Step3:ObserverMovement
Dictionary
CommandsandReporters
Built-InVariables
Primitives
at-points4.1
distancexyz4.1distancexyz-nowrap4.1
dz4.1
facefacexyz4.1
left4.1
link-pitch4.1.2
load-shapes-3d4.1
max-pzcor4.1min-pzcor4.1
neighbors4.1neighbors64.1
orbit-down4.1orbit-left4.1orbit-right4.1orbit-up4.1
__oxcor__oycor__ozcor
patch4.1
patch-at4.1
patch-at-heading-pitch-and-distance4.1
pitch
pzcor
random-pzcor4.1
245
245
245
246
246
246
246
247
247
247
248
248
248
249
249
249
250
250
250
251
251
251
251
251
251
251
252
252
252
252
252
252
252
253
253
253
253
253
253
254
254
254
254
255
255
255
255
255
255
255
256
256
256
256
256
256
256
256
257
257
random-zcor4.1
right4.1
roll
roll-left4.1
roll-right4.1
setxyz4.1
tilt-down4.1tilt-up4.1
towards-pitch4.1towards-pitch-nowrap4.1
towards-pitch-xyz4.1towards-pitch-xyz-nowrap4.1
turtles-at4.1<breeds>-at
world-depth4.1
zcor
zoom4.1
ExtensionsGuide
UsingExtensions
Whereextensionsarelocated
NetLogoArduinoExtension
Using
Notes
Compatibility
Questions
Primitives
arduino:primitives
arduino:ports
arduino:open
arduino:close
arduino:get
arduino:write-string
arduino:write-int
arduino:write-byte
arduino:is-open?
arduino:debug-to-arduino
arduino:debug-from-arduino
NetLogoArrayExtension
Using
WhentoUse
ExampleuseofArrayExtension
Primitives
array:from-list
array:item
array:set
array:length
array:to-list
NetLogoBitmapExtension
Using
WhatdoestheBitmapExtensiondo?
Gettingstarted
Primitives
bitmap:average-color
bitmap:channel
bitmap:copy-to-drawing
bitmap:copy-to-pcolors
bitmap:difference-rgb
bitmap:export
bitmap:from-view
bitmap:to-grayscale
bitmap:height
bitmap:import
bitmap:scaled
bitmap:width
258
258
258
258
260
260
260
260
260
260
260
260
260
260
261
261
262
262
262
264
264
264
265
265
265
265
265
265
266
266
266
266
267
267
267
268
268
268
269
269
269
270
270
270
270
270
270
271
271
271
271
271
271
272
272
272
272
272
273
273
273
NetLogoCfExtension
Primitives
cf:ifelse
cf:ifelse-value
NetLogoCsvExtension
Commonusecasesandexamples
Readafileallatonce
Readafileonelineatatime
Readafileonelinepertick
Writeafile
Primitives
FormattingNetLogodataasCSV
ParsingCSVinputtoNetLogodata
csv:from-row
csv:from-string
csv:from-file
csv:to-row
csv:to-string
csv:to-file
NetLogoGisExtension
Using
Howtouse
KnownIssues
Credits
Primitives
RasterDatasetPrimitives
DatasetPrimitives
VectorDatasetPrimitives
CoordinateSystemPrimitives
DrawingPrimitives
gis:set-transformation
gis:set-transformation-ds
gis:set-world-envelope
gis:set-world-envelope-ds
gis:world-envelope
gis:envelope-of
gis:envelope-union-of
gis:load-coordinate-system
gis:set-coordinate-system
gis:load-dataset
gis:store-dataset
gis:type-of
gis:patch-dataset
gis:turtle-dataset
gis:link-dataset
gis:shape-type-of
gis:property-names
gis:feature-list-of
gis:vertex-lists-of
gis:centroid-of
gis:location-of
gis:property-value
gis:find-features
gis:find-one-feature
gis:find-less-than
gis:find-greater-than
gis:find-range
gis:property-minimum
gis:property-maximum
gis:apply-coverage
gis:coverage-minimum-threshold
273
273
274
274
274
274
275
276
277
277
278
278
278
278
278
278
279
279
280
280
280
280
281
281
281
282
282
282
282
283
283
283
283
283
283
283
283
284
284
284
284
284
284
284
285
285
285
285
285
285
285
286
286
287
287
287
287
287
288
288
289
gis:set-coverage-minimum-threshold
gis:coverage-maximum-threshold
gis:set-coverage-maximum-threshold
gis:intersects?
gis:contains?
gis:contained-by?
gis:have-relationship?
gis:relationship-of
gis:intersecting
gis:width-of
gis:height-of
gis:raster-value
gis:set-raster-value
gis:minimum-of
gis:maximum-of
gis:sampling-method-of
gis:set-sampling-method
gis:raster-sample
gis:raster-world-envelope
gis:create-raster
gis:resample
gis:convolve
gis:apply-raster
gis:drawing-color
gis:set-drawing-color
gis:draw
gis:fill
gis:paint
gis:import-wms-drawing
NetLogoGogoExtension
Usage
Changes
Primitives
OtherOutputs
Utilities
General
Sensors
OutputsandServos
gogo:primitives
gogo:howmany-gogos
gogo:talk-to-output-ports
gogo:set-output-port-power
gogo:output-port-on
gogo:output-port-off
gogo:output-port-clockwise
gogo:output-port-counterclockwise
gogo:set-servo
gogo:led
gogo:beep
gogo:read-sensors
gogo:read-sensor
gogo:read-all
gogo:send-bytes
NetLogoLsExtension
LevelSpacefundamentals
HeadlessandInteractiveModels
KeepingTrackofModels
Ageneralusecase:AskingandReporting
Ageneralusecase:Inter-ModelInteractions
AgeneralUsecase:Tidyingup“Dead”ChildModels
CitingLevelSpaceinResearch
289
289
289
289
289
289
290
290
290
291
291
291
291
292
293
293
293
293
293
293
293
293
294
295
295
295
295
295
295
295
295
296
296
296
296
296
296
296
296
296
297
297
297
297
297
297
297
297
297
298
298
298
298
298
298
299
299
299
299
299
299
299
Primitives
CommandingandReporting
LogicandControl
OpeningandClosingModels
ls:create-models
ls:create-interactive-models
ls:close
ls:reset
ls:ask
ls:of
ls:report
ls:with
ls:let
ls:assign
ls:models
ls:show
ls:show-all
ls:hide
ls:hide-all
ls:path-of
ls:name-of
ls:model-exists?
ls:random-seed
NetLogoMatrixExtension
Using
WhentoUse
HowtoUse
Example
Primitives
Matrixcreationandconversionto/fromlists
Advancedfeatures
Matrixdataretrievalandmanipulation
Mathoperations
matrix:make-constant
matrix:make-identity
matrix:from-row-list
matrix:from-column-list
matrix:to-row-list
matrix:to-column-list
matrix:copy
matrix:pretty-print-text
matrix:get
matrix:get-row
matrix:get-column
matrix:set
matrix:set-row
matrix:set-column
matrix:swap-rows
matrix:swap-columns
matrix:set-and-report
matrix:dimensions
matrix:submatrix
matrix:map
matrix:times-scalar
matrix:times
matrix:*
matrix:times-element-wise
matrix:plus-scalar
matrix:plus
matrix:+
matrix:minus
matrix:-
300
300
300
300
300
300
300
300
300
301
301
301
302
303
303
303
305
305
305
305
305
305
305
305
305
305
306
306
307
307
308
308
308
308
309
309
309
310
310
310
311
311
311
311
311
312
312
312
312
313
313
313
313
314
314
314
314
315
315
315
315
316
matrix:inverse
matrix:transpose
matrix:real-eigenvalues
matrix:imaginary-eigenvalues
matrix:eigenvectors
matrix:det
matrix:rank
matrix:trace
matrix:solve
matrix:forecast-linear-growth
matrix:forecast-compound-growth
matrix:forecast-continuous-growth
matrix:regress
NetLogoNwExtension
Usage
Specialagentsetsvsnormalagentsets
Anoteregardingfloatingpointcalculations
Performance
Primitives
Generators
PathandDistance
Clusterer/CommunityDetection
ContextManagement
ImportandExport
CentralityMeasures
ClusteringMeasures
nw:set-context
nw:get-context
nw:with-context
nw:turtles-in-radius
nw:turtles-in-reverse-radius
nw:distance-to
nw:weighted-distance-to
nw:path-to
nw:turtles-on-path-to
nw:weighted-path-to
nw:turtles-on-weighted-path-to
nw:mean-path-length
nw:mean-weighted-path-length
nw:betweenness-centrality
nw:eigenvector-centrality
nw:page-rank
nw:closeness-centrality
nw:weighted-closeness-centrality
nw:clustering-coefficient
nw:modularity
nw:bicomponent-clusters
nw:weak-component-clusters
nw:louvain-communities
nw:maximal-cliques
nw:biggest-maximal-cliques
nw:generate-preferential-attachment
nw:generate-random
nw:generate-watts-strogatz
nw:generate-small-world
nw:generate-lattice-2d
nw:generate-ring
nw:generate-star
nw:generate-wheel
nw:save-matrix
nw:load-matrix
nw:save-graphml
317
318
319
320
320
320
320
320
320
320
321
321
321
321
322
322
323
323
323
323
323
323
323
324
324
324
324
324
326
326
326
328
328
328
329
329
329
329
330
330
330
330
330
331
331
331
332
332
332
332
332
333
333
333
333
333
333
333
335
nw:load-graphml
nw:load
nw:save
NetLogoPaletteExtension
UsingthePaletteExtension
GettingStarted
WhatcolorsshouldIuse?
ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?
ExampleModels
FurtherReading
Primitives
palette:scale-gradient
palette:scale-scheme
palette:scheme-colors
palette:scale-gradient
References
NetLogoProfilerExtension
UsingtheProfilerExtension
Howtouse
Example
Primitives
profiler:calls
profiler:exclusive-time
profiler:inclusive-time
profiler:start
profiler:stop
profiler:reset
profiler:report
NetLogoRExtension
Using
SomeTips
Installing
InstallingR
ConfiguringtheRextension
Determiningr.homeandjri.home.paths
Windows-SpecificInstallationSteps
Primitives
r:clear
r:clearLocal
r:eval
r:__evaldirect
r:gc
r:get
r:interactiveShell
r:put
r:putagent
r:putagentdf
r:putdataframe
r:putlist
r:putnamedlist
r:setPlotDevice
r:stop
Troubleshooting
LoadingRpackagesfails
AfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextension
Specificerrorcodelist
Citation
CopyrightandLicense
NetLogoRndExtension
335
335
336
336
336
336
336
337
337
338
338
340
340
340
340
340
340
341
341
341
341
341
342
344
344
344
344
344
344
344
345
345
345
345
345
345
345
345
345
345
345
346
346
346
346
347
347
347
347
347
347
347
347
348
348
348
349
349
349
349
Usage
Anoteaboutperformance
Primitives
AgentSetPrimitives
ListPrimitives
rnd:weighted-one-of
rnd:weighted-n-of
rnd:weighted-n-of-with-repeats
rnd:weighted-one-of-list
rnd:weighted-n-of-list
rnd:weighted-n-of-list-with-repeats
NetLogoSoundExtension
Using
HowtoUse
MIDIsupport
Primitives
sound:drums
sound:instruments
sound:play-drum
sound:play-note
sound:play-note-later
DrumNames
InstrumentNames
NetLogoTableExtension
Using
WhentoUse
Example
ManipulatingTables
KeyRestrictions
Primitives
table:clear
table:counts
table:group-agents
table:group-items
table:from-list
table:get
table:get-or-default
table:has-key?
table:keys
table:length
table:make
table:put
table:remove
table:to-list
table:values
NetLogoVidExtension
Concepts
VideoSource
SourceLifecycle
VideoRecorder
Primitives
vid:camera-names
vid:camera-open
vid:camera-select
vid:movie-select
vid:movie-open
vid:movie-open-remote
vid:close
vid:start
vid:stop
350
350
350
351
351
351
352
352
352
353
353
354
354
354
354
354
354
354
355
355
355
355
356
356
356
356
356
356
356
356
357
357
357
357
357
357
357
358
358
358
358
358
358
358
358
358
359
359
359
359
359
359
359
360
360
360
360
360
360
360
360
361
vid:status
vid:capture-image
vid:set-time
vid:show-player
vid:hide-player
vid:record-view
vid:record-interface
vid:record-source
vid:recorder-status
vid:start-recorder
vid:save-recording
NetLogoView2.5dExtension
HowtoUse
IncorporatingIntoModels
Feedback
Primitives
view2.5d:patch-view
view2.5d:decorate-patch-view
view2.5d:undecorate-patch-view
view2.5d:turtle-view
view2.5d:update-all-patch-views
view2.5d:update-patch-view
view2.5d:update-turtle-view
view2.5d:get-z-scale
view2.5d:set-z-scale
view2.5d:set-turtle-stem-thickness
view2.5d:get-observer-angles
view2.5d:set-observer-angles
view2.5d:get-observer-xy-focus
view2.5d:set-observer-xy-focus
view2.5d:get-observer-distance
view2.5d:set-observer-distance
view2.5d:remove-patch-view
view2.5d:remove-turtle-view
view2.5d:remove-all-patch-views
view2.5d:remove-all-turtle-views
view2.5d:count-windows
FAQ(FrequentlyAskedQuestions)
General
WhyisitcalledNetLogo?
HowdoIciteNetLogoorHubNetinapublication?
HowdoIciteamodelfromtheModelsLibraryinapublication?
WhereandwhenwasNetLogocreated?
WhatprogramminglanguagewasNetLogowrittenin?
What’stherelationshipbetweenStarLogoandNetLogo?
UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?
DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?
ArethereanyNetLogotextbooks?
IsNetLogoavailableinotherlanguagesbesidesEnglish?
IsNetLogocompiledorinterpreted?
Hasanyonebuiltamodelof<x>?
AreNetLogomodelsrunsscientificallyreproducible?
WillNetLogoandNetLogo3Dremainseparate?
CanIrunNetLogoonmyphoneortablet?
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?
I’monaUNIXsystemandIcan’tuntarthedownload.Why?
HowdoIinstallNetLogounattended?
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?
WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?
WhydoesNetLogobundleJava?
361
361
361
361
362
362
362
362
362
362
363
363
363
364
364
364
364
364
363
364
364
364
364
364
365
365
365
365
365
366
366
366
366
366
366
367
367
365
367
367
367
367
367
367
367
367
368
368
368
368
368
368
368
368
368
368
368
368
368
369
369
369
HowcomeNetLogowon’tstartuponmyLinuxmachine?
WhenItrytoinstallNetLogoonWindows,Isee“WindowsprotectedyourPC
WhenItrytostartNetLogoonWindowsIgetanerror“TheJVMcouldnotbestarted”.Help!
NetLogowon’tstartonMacOSSierra(orlater)
NetLogowon’tstartonWindowsorcrashessuddenlyonMacOSSierra
CanIrunNetLogofromthecommandline,withouttheGUI?
DoesNetLogotakeadvantageofmultipleprocessors?
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?
IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
WhyisHubNetDiscoveryNotWorking?
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?
CanIusethemouseto“paint”intheview?
Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmymodelcontain?
CanIuseGISdatainNetLogo?
Mymodelrunsslowly.HowcanIspeeditup?
CanIhavemorethanonemodelopenatatime?
CanIchangethechoicesinachooseronthefly?
CanIdividethecodeformymodelupintoseveralfiles?
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?
HowcomemymodelfromanearlierNetLogodoesn’tworkright?
HowdoItakethenegativeofanumber?
Myturtlemovedforward1,butit’sstillonthesamepatch.Why?
HowdoIkeepmyturtlesonpatchcenters?
patch-ahead1isreportingthesamepatchmyturtleisalreadystandingon.Why?
HowdoIgivemyturtles“vision”?
Canagentssensewhat’sinthedrawinglayer?
I’mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?
Thedocumentationsaysthatrandom-float1mightreturn0butwillneverreturn1.WhatifIwant1tobeincluded?
HowcanIkeeptwoturtlesfromoccupyingthesamepatch?
HowcanIfindoutifaturtleisdead?
DoesNetLogohavearrays?
DoesNetLogohavehashtablesorassociativearrays?
HowcanIusedifferentpatch“neighborhoods”(circular,VonNeumann,Moore,etc.)?
HowcanIconvertanagentsettoalistofagents,orviceversa?
HowdoIstopforeach?
I’mtryingtomakealist.WhydoIkeepgettingtheerror“Expectedaconstant”?
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?
HowdoImeasurerunseverynticks?
I’mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn’twork.Why?
NetLogo3D
DoesNetLogoworkwithmystereoscopicdevice?
Extensions
I’mwritinganextension.Whydoesthecompilersayitcan’tfindorg.nlogo.api?
NetLogoDictionary
Categories
Turtle-related
Patch-related
Link-related
Agentset
Color
Controlflowandlogic
AnonymousProcedures
World
Perspective
HubNet
Input/output
File
List
String
369
369
369
369
369
369
369
369
369
369
369
369
369
369
370
370
370
370
370
370
371
371
371
372
372
372
372
372
373
373
373
373
373
373
373
373
374
374
374
374
375
375
375
375
375
375
375
375
376
376
376
376
376
376
376
377
377
377
377
378
Mathematical
Plotting
BehaviorSpace
System
Built-InVariables
Turtles
Patches
Links
Other
Keywords
Constants
MathematicalConstants
BooleanConstants
ColorConstants
A
abs1.0
acos1.3
all?4.0
and1.0
any?2.0
approximate-hsb4.0
approximate-rgb4.0
ArithmeticOperators+1.0*1.0-1.0/1.0^1.0<1.0>1.0=1.0!=1.0<=1.0>=1.0
asin1.3
ask1.0
ask-concurrent4.0
at-points1.0
atan1.0
autoplot?1.0
auto-plot-off1.0auto-plot-on1.0
B
back1.0bk1.0
base-colors4.0
beep2.1
behaviorspace-experiment-name5.2
behaviorspace-run-number4.1.1
both-ends4.0
breed
breed
but-first1.0butfirst1.0bf1.0but-last1.0butlast1.0bl1.0
C
can-move?3.1
carefully2.1
ceiling1.0
clear-all1.0ca1.0
clear-all-plots1.0
clear-drawing3.0cd3.0
clear-globals5.2
clear-links4.0
clear-output1.0
clear-patches1.0cp1.0
clear-plot
clear-ticks5.0
clear-turtles1.0ct1.0
color
cos1.0
count1.0
create-ordered-turtles4.0cro4.0
create-<breed>-tocreate-<breeds>-tocreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-withcreate-
<breeds>-withcreate-link-to4.0create-links-to4.0create-link-from4.0create-links-from4.0create-link-with4.0
create-links-with4.0
create-turtles1.0crt1.0
378
379
379
379
379
379
379
380
380
380
381
381
381
381
381
381
381
382
382
382
382
382
383
383
383
383
383
384
384
384
384
384
384
384
385
385
385
385
386
386
386
386
386
386
387
387
387
387
387
388
388
388
388
388
388
388
389
389
389
389
389
389
389
create-temporary-plot-pen1.1
D
date-and-time3.0
die1.0
diffuse1.0
diffuse41.0
directed-link-breed
display1.0
distance1.0
distancexy1.0
downhill1.0downhill41.0
dx1.0dy1.0
E
empty?1.0
end
end14.0
end24.0
error5.0
error-message2.1
every1.0
exp1.0
export-view3.0export-interface2.0export-output1.0export-plot1.0export-all-plots1.2.1export-world1.0
extensions
extract-hsb1.0
extract-rgb1.0
F
face3.0
facexy3.0
file-at-end?2.0
file-close2.0
file-close-all2.0
file-delete2.0
file-exists?2.0
file-flush4.0
file-open2.0
file-print2.0
file-read2.0
file-read-characters2.0
file-read-line2.0
file-show2.0
file-type2.0
file-write2.0
filter1.3
first1.0
floor1.0
follow3.0
follow-me3.0
foreach1.3
forward1.0fd1.0
fput1.0
G
globals
H
hatch1.0
heading
hidden?
hide-link4.0
hide-turtle1.0ht1.0
histogram1.0
home1.0
hsb1.0
hubnet-broadcast1.1
hubnet-broadcast-clear-output4.1
390
390
390
390
390
390
390
390
390
391
391
391
391
391
391
391
391
392
392
392
392
392
392
392
393
393
393
393
393
394
394
394
394
395
395
395
395
395
396
396
396
396
396
396
397
397
397
397
398
398
398
398
398
399
399
399
399
399
399
400
400
hubnet-broadcast-message4.1
hubnet-clear-override4.1hubnet-clear-overrides4.1
hubnet-clients-list5.0
hubnet-enter-message?1.2.1
hubnet-exit-message?1.2.1
hubnet-fetch-message1.1
hubnet-kick-client5.0
hubnet-kick-all-clients5.0
hubnet-message1.1
hubnet-message-source1.1
hubnet-message-tag1.1
hubnet-message-waiting?1.1
hubnet-reset1.1
hubnet-reset-perspective4.1
hubnet-send1.1
hubnet-send-clear-output4.1
hubnet-send-follow4.1
hubnet-send-message4.1
hubnet-send-override4.1
hubnet-send-watch4.1
I
if1.0
ifelse1.0
ifelse-value2.0
import-drawing3.0
import-pcolors3.0
import-pcolors-rgb4.0
import-world1.0
in-cone3.0
in-<breed>-neighbor?in-link-neighbor?4.0
in-<breed>-neighborsin-link-neighbors4.0
in-<breed>-fromin-link-from4.0
__includes4.0
in-radius1.0
insert-item6.0.2
inspect1.1
int1.0
is-agent?1.2.1is-agentset?1.2.1is-anonymous-command?6.0is-anonymous-reporter?6.0is-boolean?1.2.1is-
directed-link?4.0is-link?4.0is-link-set?4.0is-list?1.0is-number?1.2.1is-patch?1.2.1is-patch-set?4.0is-string?1.0
is-turtle?1.2.1is-turtle-set?4.0is-undirected-link?4.0
item1.0
J
jump1.0
L
label
label-color
last1.0
layout-circle4.0
layout-radial4.0
layout-spring4.0
layout-tutte4.0
left1.0lt1.0
length1.0
let2.1
link4.0
link-heading4.0
link-length4.0
link-set4.0
link-shapes4.0
links4.0
links-own
list1.0
ln1.0
400
400
400
400
400
401
401
401
401
401
402
402
402
402
402
403
403
403
403
403
403
404
404
404
404
405
405
405
405
405
406
406
406
406
406
406
407
407
407
407
407
407
407
407
408
408
408
408
408
409
409
409
409
409
410
410
410
410
410
411
411
411
411
log1.0
loop1.0
lput1.0
M
map1.3
max1.0
max-n-of4.0
max-one-of1.0
max-pxcor3.1max-pycor3.1
mean1.0
median1.0
member?1.0
min1.0
min-n-of4.0
min-one-of1.0
min-pxcor3.1min-pycor3.1
mod1.0
modes2.0
mouse-down?1.0
mouse-inside?3.0
mouse-xcor1.0mouse-ycor1.0
move-to4.0
my-<breeds>my-links4.0
my-in-<breeds>my-in-links4.0
my-out-<breeds>my-out-links4.0
myself1.0
N
n-of3.1
n-values2.0
neighbors1.1neighbors41.1
<breed>-neighborslink-neighbors4.0
<breed>-neighbor?link-neighbor?4.0
netlogo-version3.0
netlogo-web?5.2
new-seed3.0
no-display1.0
nobody
no-links4.0
no-patches4.0
not1.0
no-turtles4.0
O
of4.0
one-of1.0
or1.0
other4.0
other-end4.0
out-<breed>-neighbor?out-link-neighbor?4.0
out-<breed>-neighborsout-link-neighbors4.0
out-<breed>-toout-link-to4.0
output-print2.1output-show2.1output-type2.1output-write2.1
P
patch1.0
patch-ahead2.0
patch-at1.0
patch-at-heading-and-distance2.0
patch-here1.0
patch-left-and-ahead2.0patch-right-and-ahead2.0
patch-set4.0
patch-size4.1
patches1.0
patches-own
pcolor
411
411
411
412
412
412
412
412
412
412
412
412
413
413
413
413
413
413
414
414
414
414
415
415
415
415
416
416
416
416
417
417
417
417
417
417
417
418
418
418
418
418
418
419
419
419
419
419
419
420
420
420
420
420
421
421
421
421
421
421
421
422
422
pen-down1.0pd1.0pen-erase3.0pe3.0pen-up1.0pu1.0
pen-mode
pen-size
plabel
plabel-color
plot1.0
plot-name1.0
plot-pen-exists?4.0
plot-pen-down1.0plot-pen-up1.0
plot-pen-reset1.0
plotxy1.0
plot-x-min1.0plot-x-max1.0plot-y-min1.0plot-y-max1.0
position1.0
precision1.0
print1.0
pxcorpycor
R
random1.0
random-float2.0
random-exponential1.2.1random-gamma2.0random-normal1.2.1random-poisson1.2.1
random-pxcor3.1random-pycor3.1
random-seed1.0
random-xcor3.1random-ycor3.1
range6.0
read-from-string1.1
reduce1.3
remainder1.2.1
remove1.0
remove-duplicates1.0
remove-item2.0
repeat1.0
replace-item1.0
report1.0
reset-perspective3.0rp3.0
reset-ticks4.0
reset-timer1.0
resize-world4.1
reverse1.0
rgb1.0
ride3.0
ride-me3.0
right1.0rt1.0
round1.0
run1.3runresult1.3
S
scale-color1.0
self1.3
;(semicolon)
sentence1.0se1.0
set1.0
set-current-directory2.0
set-current-plot1.0
set-current-plot-pen1.0
set-default-shape1.0
set-histogram-num-bars1.0
__set-line-thickness
set-patch-size4.1
set-plot-background-color6.0.2
set-plot-pen-color1.0
set-plot-pen-interval1.0
set-plot-pen-mode1.0
setup-plots5.0
set-plot-x-range1.0set-plot-y-range1.0
422
422
422
422
423
423
423
423
423
423
423
424
424
424
425
425
425
425
425
425
425
426
426
426
426
426
426
426
427
427
427
427
427
427
428
428
428
428
428
429
429
429
429
429
429
430
430
430
430
431
431
431
431
431
431
432
432
432
432
432
432
433
433
setxy1.0
shade-of?1.0
shape
shapes2.1
show1.0
show-turtle1.0st1.0
show-link4.0
shuffle2.0
sin1.0
size
sort1.0
sort-by1.3
sort-on5.0
sprout1.0
sqrt1.0
stamp1.0
stamp-erase3.1
standard-deviation1.0
startup
stop1.0
stop-inspecting5.2
stop-inspecting-dead-agents5.2
subject3.0
sublist2.1substring1.0
subtract-headings2.1
sum1.0
T
tan1.0
thickness
tick4.0
tick-advance4.0
ticks4.0
tie4.0
tie-mode
timer1.0
to
to-report
towards1.0
towardsxy1.0
turtle1.0
turtle-set4.0
turtles1.0
turtles-at1.0
turtles-here1.0
turtles-on2.0
turtles-own
type1.0
U
undirected-link-breed
untie4.0
update-plots5.0
uphill1.0uphill41.0
user-directory3.1
user-file3.1
user-new-file3.1
user-input1.1
user-message1.1
user-one-of3.1
user-yes-or-no?2.0
V
variance1.0
W
wait1.0
433
433
433
433
434
434
434
434
434
435
435
435
435
435
436
436
436
436
436
436
436
watch3.0
watch-me3.0
while1.0
who
with1.0
<breed>-withlink-with4.0
with-max2.1
with-min2.1
with-local-randomness4.0
without-interruption1.1
word1.0
world-width3.1world-height3.1
wrap-color1.0
write2.0
X
xcor
xor1.0
Y
ycor
->
->6.0
WhatisNetLogo?
NetLogoisaprogrammablemodelingenvironmentforsimulatingnaturalandsocial
phenomena.ItwasauthoredbyUriWilenskyin1999andhasbeenincontinuous
developmenteversinceattheCenterforConnectedLearningandComputer-Based
Modeling.
NetLogoisparticularlywellsuitedformodelingcomplexsystemsdevelopingovertime.
Modelerscangiveinstructionstohundredsorthousandsof“agents”alloperating
independently.Thismakesitpossibletoexploretheconnectionbetweenthemicro-level
behaviorofindividualsandthemacro-levelpatternsthatemergefromtheirinteraction.
NetLogoletsstudentsopensimulationsand“play”withthem,exploringtheirbehaviorunder
variousconditions.Itisalsoanauthoringenvironmentwhichenablesstudents,teachersand
curriculumdeveloperstocreatetheirownmodels.NetLogoissimpleenoughforstudentsand
teachers,yetadvancedenoughtoserveasapowerfultoolforresearchersinmanyfields.
NetLogohasextensivedocumentationandtutorials.ItalsocomeswiththeModelsLibrary,a
largecollectionofpre-writtensimulationsthatcanbeusedandmodified.Thesesimulations
addresscontentareasinthenaturalandsocialsciencesincludingbiologyandmedicine,
physicsandchemistry,mathematicsandcomputerscience,andeconomicsandsocial
psychology.Severalmodel-basedinquirycurriculausingNetLogoareavailableandmoreare
underdevelopment.
NetLogoisthenextgenerationoftheseriesofmulti-agentmodelinglanguagesincluding
StarLogoandStarLogoT.NetLogorunsontheJavaVirtualMachine,soitworksonallmajor
platforms(Mac,Windows,Linux,etal).Itisrunasadesktopapplication.Commandline
operationisalsosupported.
Features
System:
Free,opensource
Cross-platform:runsonMac,Windows,Linux,etal
Internationalcharactersetsupport
Programming:
Fullyprogrammable
Approachablesyntax
LanguageisLogodialectextendedtosupportagents
Mobileagents(turtles)moveoveragridofstationaryagents(patches)
Linkagentsconnectturtlestomakenetworks,graphs,andaggregates
Largevocabularyofbuilt-inlanguageprimitives
Doubleprecisionfloatingpointmath
First-classfunctionvalues(akaanonymousprocedures,closures,lambda)
Runsarereproduciblecross-platform
Environment:
Commandcenterforon-the-flyinteraction
Interfacebuilderw/buttons,sliders,switches,choosers,monitors,textboxes,
notes,outputarea
Infotabforannotatingyourmodelwithformattedtextandimages
HubNet:participatorysimulationsusingnetworkeddevices
Agentmonitorsforinspectingandcontrollingagents
Exportandimportfunctions(exportdata,saveandrestorestateofmodel,makea
movie)
BehaviorSpace,anopensourcetoolusedtocollectdatafrommultipleparallel
runsofamodel
SystemDynamicsModeler
NetLogo3Dformodeling3Dworlds
Headlessmodeallowsdoingbatchrunsfromthecommandline
Displayandvisualization:
Line,bar,andscatterplots
Speedsliderletsyoufastforwardyourmodelorseeitinslowmotion
Viewyourmodelineither2Dor3D
Scalableandrotatablevectorshapes
Turtleandpatchlabels
APIs:
controllingAPIallowsembeddingNetLogoinascriptorapplication
extensionsAPIallowsaddingnewcommandsandreporterstotheNetLogo
language;opensourceexampleextensionsareincluded
CopyrightandLicenseInformation
NetLogo6.0.4UserManual
Howtoreference
IfyouuseorrefertoNetLogoinapublication,weaskthatyouciteit.Thecorrectcitationis:
Wilensky,U.(1999).NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnected
LearningandComputer-BasedModeling,NorthwesternUniversity,Evanston,IL.
ForHubNet,cite:Wilensky,U.&Stroup,W.,1999.HubNet.
http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnectedLearningand
Computer-BasedModeling,NorthwesternUniversity.Evanston,IL.
FormodelsintheModelsLibrary,thecorrectcitationisincludedinthe"Creditsand
References"sectionofeachmodel'sInfotab.
Acknowledgments
TheCCLgratefullyacknowledgestwodecadesofsupportforourNetLogowork.Theoriginal
supportcamefromtheNationalScienceFoundation--grantnumbersREC-9814682and
REC-0126227.FurthersupporthascomefromREC-0003285,REC-0115699,DRL-0196044,
CCF-ITR-0326542,DRL-REC/ROLE-0440113,SBE-0624318,EEC-0648316,IIS-0713619,
DRL-RED-9552950,DRL-REC-9632612,andDRL-DRK12-1020101,IIS-1441552,CNS-
1441016,CNS-1441041,CNS-1138461,IIS-1438813,IIS-1147621,DRL-REC-1343873,IIS-
1438813,IIS-1441552,CNS-1441041,IIS-1546120,DRL-1546122,DRL-1614745andDRL-
1640201.AdditionalsupportcamefromtheSpencerFoundation,TexasInstruments,the
BradyFund,theMurphyfund,andtheNorthwesternInstituteonComplexSystems.
NetLogolicense
Copyright1999-2018byUriWilensky.
Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsofthe
GNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2
oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;
withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULAR
PURPOSE.SeetheGNUGeneralPublicLicenseformoredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwiththisprogram;
ifnot,writetotheFreeSoftwareFoundation,Inc.,51FranklinStreet,FifthFloor,Boston,MA
02110-1301,USA.
Commerciallicenses
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,pleasecontact
UriWilenskyaturi@northwestern.edu.
NetLogoUserManuallicense
Copyright1999-2018byUriWilensky.
TheNetLogoUserManualbyUriWilenskyislicensedunderaCreativeCommonsAttribution-
ShareAlike3.0UnportedLicense.
Opensource
TheNetLogosourcecodeishostedathttps://github.com/NetLogo/NetLogo.Contributions
frominterestedusersarewelcome.
Thirdpartylicenses
Scala
MuchofNetLogoiswrittenintheScalalanguageandusestheScalastandardlibraries.The
licenseforScalaisasfollows:
Copyright (c) 2002 - EPFL
Copyright (c) 2011 - Lightbend, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the EPFL nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
MersenneTwisterFast
Forrandomnumbergeneration,NetLogousestheMersenneTwisterFastclassbySeanLuke.
Thecopyrightforthatcodeisasfollows:
Copyright (c) 2003 by Sean Luke.
Portions copyright (c) 1993 by Michael Lecuyer.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the copyright owners, their employers, nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNERS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Colt
PartsofNetLogo(specifically,therandom-gammaprimitive)arebasedoncodefromtheColt
library(http://acs.lbl.gov/~hoschek/colt/).Thecopyrightforthatcodeisasfollows:
Copyright 1999 CERN - European Organization for Nuclear Research. Permission
to use, copy, modify, distribute and sell this software and its documentation
for any purpose is hereby granted without fee, provided that the above
copyright notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation. CERN makes no
representations about the suitability of this software for any purpose. It is
provided "as is" without expressed or implied warranty.
Config
NetLogousestheTypesafe"Config"library.Copyright(C)2011-2012TypesafeInc.
http://typesafe.comTheConfiglibraryislicensedundertheApache2.0License.Youmay
obtainacopyofthelicenseathttp://www.apache.org/licenses/LICENSE-2.0.
ApacheCommonsCodec(TM)
TheNetLogocompilerusesadigestmethodfromtheApacheCommonsCodec(TM)library.
ApacheCommonsCodec(TM)iscopyrightandtrademark2002-2014theApacheSoftware
Foundation.ItislicensedundertheApache2.0License.Youmayobtainacopyofthelicense
athttp://www.apache.org/licenses/LICENSE-2.0.
Flexmark
NetLogousestheFlexmarklibrary(andextensions)fortheinfotab.Thecopyrightandlicense
areasfollows:
Copyright (c) 2015-2016, Atlassian Pty Ltd All rights reserved. Copyright (c)
2016, Vladimir Schneider, All rights reserved. Redistribution and use in
source and binary forms, with or without modification, are permitted provided
that the following conditions are met: * Redistributions of source code must
retain the above copyright notice, this list of conditions and the following
disclaimer. * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution. THIS
SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
JHotDraw
Forthesystemdynamicsmodeler,NetLogousestheJHotDrawlibrary,whichisCopyright(c)
1996,1997byIFAInformatikandErichGamma.ThelibraryiscoveredbytheGNULGPL
(LesserGeneralPublicLicense).Thetextofthatlicenseisincludedinthe"docs"folderwhich
accompaniestheNetLogodownload,andisalsoavailablefrom
http://www.gnu.org/copyleft/lesser.html.
JOGL
For3Dgraphicsrendering,NetLogousesJOGL,aJavaAPIforOpenGL,andGluegen,an
automaticcodegenerationtool.FormoreinformationaboutJOGLandGluegen,see
jogamp.org/.BothlibrariesaredistributedundertheBSDlicense:
Copyright 2010 JogAmp Community. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL JogAmp Community OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of JogAmp Community.
You can address the JogAmp Community via: Web http://jogamp.org/
Forum/Mailinglist http://forum.jogamp.org Chatrooms IRC irc.freenode.net
#jogamp Jabber conference.jabber.org room: jogamp (deprecated!) Repository
http://jogamp.org/git/ Email mediastream _at_ jogamp _dot_ org
Matrix3D
For3Dmatrixoperations,NetLogousestheMatrix3Dclass.Itisdistributedunderthe
followinglicense:
Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
modify and redistribute this software in source and binary code form, provided
that i) this copyright notice and license appear on all copies of the
software; and ii) Licensee does not utilize the software in a manner which is
disparaging to Sun.
This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS
OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-
INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE
FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
This software is not designed or intended for use in on-line control of
aircraft, air traffic, aircraft navigation or aircraft communications; or in
the design, construction, operation or maintenance of any nuclear facility.
Licensee represents and warrants that it will not use or redistribute the
Software for such purposes.
ASM
ForJavabytecodegeneration,NetLogousestheASMlibrary.Itisdistributedunderthe
followinglicense:
Copyright (c) 2000-2011 INRIA, France Telecom. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Log4j
Forlogging,NetLogousestheLog4jlibrary.Thecopyrightandlicenseforthelibraryareas
follows:
Copyright 2007 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
PicoContainer
Fordependencyinjection,NetLogousesthePicoContainerlibrary.Thecopyrightandlicense
forthelibraryareasfollows:
Copyright (c) 2004-2011, PicoContainer Organization All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the PicoContainer Organization nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Parboiled
Forreadingmodels,NetLogousestheParboiledlibrary.Thecopyrightandlicensefor
Parboiledareasfollows:
This software is licensed under the Apache 2 license, quoted below. Copyright
© 2009-2013 Mathias Doenitz http://parboiled2.org Copyright © 2013 Alexander
Myltsev Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may obtain a
copy of the License at [http://www.apache.org/licenses/LICENSE-2.0] Unless
required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
RSyntaxTextArea
TheNetLogoeditorusestheRSyntaxTextArealibrary.Thecopyrightandlicenseareas
follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: *
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. * Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided
with the distribution. * Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission. THIS SOFTWARE IS PROVIDED
BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL &COPYRIGHT HOLDER& BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
JCodec
TheNetLogovidextensionmakesuseoftheJCodeclibrary.Thecopyrightandlicensefor
JCodecareasfollows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided
with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Java-Objective-CBridge
NetLogoonMacOSXmakesuseoftheJava-Objective-CBridgelibrary.Thislibrarywas
createdbySteveHannahandisdistributedundertheApache2.0license,availableat
https://www.apache.org/licenses/LICENSE-2.0.
Webcam-capture
TheNetLogovidextensionmakesuseoftheWebcam-capturelibrary.Thecopyrightand
licenseforWebcam-captureareasfollows:
The MIT License (MIT) Copyright (c) 2012 - 2015 Bartosz Firyn and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright
notice and this permission notice shall be included in all copies or
substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Guava
TheNetLogolsextensionmakesuseoftheGuavalibrary.Guavaisreleasedunderthe
ApacheLicense2.0(http://www.apache.org/licenses/LICENSE-2.0)
Gephi
ThenwextensionmakesuseoftheGephilibrary.Gephiislicensedunderthefollowingterms:
Gephi Dual License Header and License Notice
The Gephi Consortium elects to use only the GNU General Public License version
3 (GPL) for any software where a choice of GPL license versions are made
available with the language indicating that GPLv3 or any later version may be
used, or where a choice of which version of the GPL is applied is unspecified.
For more information on the license please see: the Gephi License FAQs.
License headers are available on http://www.opensource.org/licenses/CDDL-1.0
and http://www.gnu.org/licenses/gpl.html.
RExtension
TheNetLogoRExtensionislicensedunderthefollowingterms:
The R extension is Copyright (C) 2009-2016 Jan C. Thiele and Copyright (C)
2016 Uri Wilensky / The Center for Connected Learning. NetLogo-R-Extension is
free software; you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with
NetLogo-R-Extension (located in GPL.txt). If not, see
http://www.gnu.org/licenses.
JNA
TheNetLogoRExtensionmakesuseoftheJNAlibrary.TheJNAlibraryislicensedunderthe
followingterms:
This copy of JNA is licensed under the Apache (Software) License, version 2.0
("the License"). See the License for details about distribution rights, and
the specific rights regarding derivate works. You may obtain a copy of the
License at: http://www.apache.org/licenses/
What'snew?
NetLogo6.0.4UserManual
Thefollowingisacondensedhistory.DetailedreleasenotesareonGitHub.
Forhelprunningmodelsmadeinoldversions,seetheTransitionGuide.
Version6.0.4(May2018)
FeatureChanges
NetLogonowsupportsthePortugueselanguage.
BehaviorSpaceallowsoptionallydisablingplotsandtheviewwhenrunning
experiments.
Bugfixes
UpdatedthebundledJava8,whichshouldresolveanissuewithNetLogofailingtostart
onWindowscomputers.
Fixedanumericalerrorwiththerangeprimitive.
Fixedabugwithlinklookupwhenusingmorethantwolinkbreeds.
CommentanduncommentcodehotkeysshouldworkwithNetLogoincludesourcefiles.
Addedabettererrormessagewhenawebbrowsercouldn’tbelaunchedforanyreason.
DocumentationChanges
Documentthatresize-worldonlykillsallturtleswhencoordinatesreallychange.
ModelChanges
NewCurricularModels
MindtheGapCurriculum
MTG1EqualOpportunitiesHubNet
MTG2RandomAssignmentHubNet
MTG3FeedbackLoopHubNet
RevisedSampleModels
BloodSugarRegulation:Updatedstatisticalsamplingprocedures
Flocking:Changeddefaultvisionto5.0patches
RumorMill:Fixedaminorbugwiththespreadstatisticsinearlyticks
RevisedCodeExamples
Flocking(PerspectiveDemo):Changeddefaultvisionto5.0patches
RevisedCurricularModels
GenEvo-GenEvo1:Fixedsave screenshotbugonWindowsmachines
GenEvo-GenEvo2:Fixedsave screenshotbugonWindowsmachines
GenEvo-GenEvo3:Fixedsave screenshotbugonWindowsmachines
RevisedAlternativeVisualizations
Flocking(AlternativeVisualizations):Changeddefaultvisionto5.0patches
Version6.0.3(March2018)
FeatureChanges
Improvethelook&feelofAgentMonitorwindows.
Theproceduresmenuinthecodetabnowhasasearchfieldandactivelyfilters
procedurenamesastheusertypes.Thisshouldimprovenavigationspeedforlarge
modelswithlotsofprocedures.Thereisalsonowahotkeytoaccessthismenu:Ctrl-G
onWindowsandLinux,andCmd-GonMacOS.
Increasethespeedofthediffusionprimitiveandmakethediffusionoperation
symmetric.
NetLogoenforcesthatplotnamesareuniqueandthatpennamesareper-plotunique
withouttakingcapitalizationintoaccount.Thisavoidscertaincaseswhereset-current-
plotandset-current-plot-penprimitiveswouldsettheplotorpentosomething
differentthantheuserintendedbecausenamesdifferedincapitalizationonly.
Modelswithexistingplotsandpenswhichhavethesamenamewithouttaking
capitalizationintoaccountwillbeautomaticallyconvertedonfirstopenin6.0.3.
Weareplanningonaddingtheabilitytohavemultipleconditionalbranchestoifelse
andifelse-value.However,asthisisafairlysubstantialchangetothecorelanguage,
wehaveimplementeditinthecfextensionfortesting.Seethecfdocumentationfor
informationaboutthenewsyntax.
DocumentationChanges
AddatabletotheOutputsectionoftheProgrammingGuidespecifyinghowthevarious
outputprimitivesdifferinwhethertheyprintthecallingagent,whethertheyprinta
newline,andwhethertheycanbereadbackintoNetLogo.
Bugfixes
Anonymousproceduresappearinginsideaskblocksinsiderepeatblocksnowclose
overuniquecopiesoflet-variablesintroducedintherepeatblock.
FixalongstandingHubNetbuginwhichHubNetwouldsometimescrashasalarge
numberofusersjoined.
FixHubNetdiscoverywhentheHubNetserverisrunonaMac.
Whenswitchingfromthecodetabtotheinterfacetab,thecursorswitchestothe
commandcenter.Thispreventstypedcommandsorcopy/pastekeyboardshortcuts
fromaffectingthecodetab.
Turtlesdrawtrailswhenmovingbackwards(regressioninNetLogo6.0.1).
SmoothCodeTabscrolling.
BehaviorSpacenowonlyappliesstandardCSVstringescaping(doublingofdouble
quotes)tostringoutputsinresultfiles.ItusedtoapplyNetLogostylestringescaping
(backslashesinfrontofspecialcharacters)andthenapplyCSVescapingontopofthat.
ThenewbehaviorisconsistentwiththeRFC4180specificationandthecurrent
behaviorofthecsvextension.
TheBehaviorspacedialogappearscenteredintheNetLogowindow.
DuetochangesintroducedinJava,certaindialogsinNetLogo6.0.1wouldappear
underthedialogthatcreatedtheminsteadofontop.Thesedialogsnowappearontop
ofthedialogthatcreatedthem.
Non-codechangestotheSystemDynamicsmodelerarepulledinoneveryrecompile
(priortothis,changeslikenewly-disconnectedflowsweresometimesnottakeninto
accountonrecompiles).
Thesystemdynamicscodetabadjustsitselftomatchthesizeofthesystemdynamics
window.
NetLogo3Dloadsandsavessystemdynamics.
Fixesanerrorraisedin3Dwhentheworldwasclearedfollowingsettingapatch-color
toanRGBlist.
Miscellaneoussmallchangestotheformatofexportedworlds.NetLogo6.0.3shouldbe
abletoimportworldsexportedbyolderversionsofNetLogoandolderversionsof
NetLogoshouldbeabletoimportworldsexportedbyNetLogo6.0.3.
The“others”executebitissetforthenetlogo-headless.shscriptintheLinuxinstaller
package.
ExtensionChanges
nw:generate-preferential-attachmentacceptsamin-degreeparameter,specifyingthe
numberoflinkseachnewturtlepreferentiallycreatestoexistingturtles.
Thearduinoextension(andtherelatedsketchandmodelinthelibrary)havebeen
updatedtoallowthearduinotosendstringsbacktoNetLogo.Twonewdebug
primitiveshavealsobeenaddedtohelptroubleshootinteractionbetweenNetLogoand
thearduino.
Theverbosecfextensionconditionalsyntaxasbeenreplacedwithstraight-forward
generalizationsoftheifelseandifelse-valueprimitives.Thesyntaxismuchsimpler
andtheseprimitivesrunmuchfasterthantheoldconstructs.
Thelsextensionhasmuchlessoverheadforcallingouttosinglemodels,making
constructslikeask turtles [ ls:ask my-model [ run-something ] ] muchfaster.
ThelsextensionnowseedsthechildmodelRNGbasedontheparentmodelRNGat
modelcreation.Furthermore,andls:random-seedprimitivehasbeenintroduced,soan
entiremodelsystemcanbeseededsimultaneously.Thismakesitpossibletohave
reproduciblerunswhenusingLevelSpace.
Thels:letprimitivenowhandlesscopingproperly.
ls:assignhasbeenaddedtoLevelSpacetomakeassigningglobalsofchildmodels
easier.
DocumentationChanges
Clarifydocumentationaround__includesbyprovidingexamples.
Fixabrokenlinkinthedictionary.
UpdatetheWindowsunattendedinstallationdirectionsintheFAQ.
ModelChanges
NewSampleModels:
BiddingMarket
BloodSugarRegulation
RockPaperScissors
VisionEvolution
NewCurricularModels
NIELS-CurrentinaWireHubNet
NewHubNetActivities:
CurrentinaWireHubNet(sameasabove)
RevisedCodeExamples:
arduinoExtension:Theexamplemodelandsketchhavebeenupdatedtoreflectnew
featuresintheextension
soundExtension–SoundWorkbench:MinorGUIupdates
soundExtension–PercussionWorkbench:MinorGUIupdates
FileInputExample:Fixedabuginthesave-patch-datatemplateprocedure
LotteryExample:CorrectedRelatedModelsfromPreferentialAttachmenttotheRnd
ExampleModelintheInfoTab
InfoTabExample:CorrectedreferencefrompegdowntoflexmarkintheInfoTab
RevisedCurricularModels:
BEAGLEEvolution-FishTankGeneticDrift:Updateduplicateplot-pennamesand
resizeplots
GenEvo-GenEvo4:Replacedusageofcf:whenwithnestedifelses
LatticeLand-LatticeLandExplore:Fixedbugwhendeletingasegmentthatdidn’t
exist.
LatticeLand-LatticeLandTrianglesDissection:Fixedbugwhendeletingasegment
thatdidn’texist.
NIELS-Electrostatics:Allturtlesarenowparticlesandeachparticlehasacharge;
Changedparticlecoloring;UpdatedInfoTabandsomevariablenamestoreflectlater
NIELSmodels
UrbanSuite-TijuanaBordertowns:MinorInfoTabupdates.
RevisedSampleModels:
ArtificialAnasazi:UpdatebrokenURLsinInfoTab
Autumn:UpdatebrokenURLsinInfoTab
HIV:TheAIDSmodelhasbeenrenamedtoHIV
ColorFractions:RemoveddirectreferencetodeadwebpageinInfoTab
FairyCircles:UpdateURLsinInfoTab
Fur:UpdatebrokenURLsinInfoTab
HexCellAggregation:UpdatebrokenURLsinInfoTab
Ising:UpdatebrokenURLsinInfoTab
KickedRotators:UpdatebrokenURLsinInfoTab
LanguageChange:UpdateURLsinInfoTab
Lennard-Jones:AddedcitationintheInfotab
Lightning:UpdateURLsinInfoTab.
L-SystemFractals:UpdatebrokenURLsinInfoTab
MembraneFormation:UpdatebrokenURLsinInfoTab
Moth:UpdateURLsinInfoTab
Party:Fixincorrectcommentonturtleheadings.
PDBasic:MinorGUIupdates
Segregation:UpdatebrokenURLsinInfoTab.Updatecolorschemeforcolorblindness.
MinorGUIupdates.MinorInfoTabupdates.
Sugarscape1ImmediateGrowback:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
Sugarscape2ConstantGrowback:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
Sugarscape3WealthDistribution:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
RevisedIABMModels:
ArduinoExample:Theexamplemodelandsketchhavebeenupdatedtoreflectnew
featuresintheextension(sameasabove)
SegregationSimpleExtension1:UpdatebrokenURLsinInfoTab
SegregationSimpleExtension2:UpdatebrokenURLsinInfoTab
SegregationSimpleExtension3:UpdatebrokenURLsinInfoTab
SegregationSimple:UpdatebrokenURLsinInfoTab
†-ModelsUpdatedtoCorrectlyReferencetheHIVModel
AlternativeVisualizations
Virus-AlternativeVisualization
Virus-CircleVisualization
CurricularModels
epiDEMBasic
epiDEMTravelandControl
IABMModels
SpreadofDisease
SampleModels:
DiseaseSolo
Virus
RumorMill
Version6.0.2(August2017)
FeatureChanges
TheautosuggestfunctionalityintroducedinNetLogo6willnowdisplayextension
primitivenames.
Anewinsert-itemprimitivewasaddedtothelanguage.Itworkssimilarlytoreplace-
item,butwithoutremovingtheitematthespecifiedindex.
Anewset-plot-background-colorprimitivewasaddedtothelanguage.Itcanbeused
inplottingcodetosetthebackgroundcoloroftheplot.
Behaviorsearch’suserinterfacehasbeenupdated.ItnowusestheJavaFXUItoolkitfor
amoremodernlookandfeel.
Bugfixes
The6.0.1autoconverterwoulderrorwhenconvertingtaskswithexactlyoneargument
(from5.3.1andearliermodelsonly).Theconversionwouldbecorrect,butitwas
confusing.Thishasnowbeenremediedandtheautoconverterwillcorrectlyconvert
modelsfrom5.3.1andearlierwithouterroringonsingle-argumenttasks.
Fixabugwhereextensionsweren’tlocatedproperlywheninapathrelativetothe
model.
Helpbrowsernowopensin64-bitWindows.
Fixaspeedregressionfortheimport-worldprimitiveintroducedin6.0.
Ifanunexpectedreporterblockispassedtowithwhenusedwithother,theerrorwill
nowreflectthattheblockisunsuitableforwithinsteadofother.
Whensort-byreceivesanunsuitablereporterblockfromtheuseritnowshowsauseful
errorinsteadofacrypticstacktrace.
Stringrepresentationsofanonymousproceduresnowshowtheargumentsofthose
anonymousprocedures
Whenworkinginannlsfile,switchingtoadifferenttabwillcompilethenlsfile.
Displayerrorlabelonnlsfilewhenthecodeitcontainscausesanerror.
SomeuserswereunabletoopenNetLogo6and6.0.1inMacOSSierra.We’ve
changedoursigningprocessin6.0.2toattempttofixthisproblem.Wearecontinuingto
trackthisissuetodeterminewhetherourfixwaseffective.Moreinformation(includinga
partialworkaroundfortheproblem)isavailablehere.
ExtensionChanges
Fixedabugingis:patch-datasetintroducedinNetLogo6.
Thetableextensionhasnewtable:group-agentsandtable:group-itemsprimitives
whichcanbeusedtobuildatableofgroupedagentsanditemsbysupplyingan
anonymousreporter.
DocumentationChanges
Clarifywhenvariouspartsoftheanonymousproceduresyntaxareoptional.
Fixafewsmalldocumentationbugsaroundforeach.
Clarifyrelationshipbetweenspeedandupdatemodalityinthe“ViewUpdates”sectionof
theprogrammingguide.
ModelChanges
NewSampleModels:
ChaosinaBox
FairyCircles
SmoothLife
NewCurricularModels:
LatticeLandCurriculum
LatticeLand-TrianglesExplore
LatticeLand-TrianglesDissection
RevisedSampleModels:
Anisogamy:Newcolorscheme.AddsBehaviorSpaceexperiments.
Ethnocentrism:Nowcross-listedasanEvolutionarymodel.
Fireworks:Renamefireworkstomax-fireworksandenforceaminimumof1.
GenJam-Duple:Minorinfotabupdates.
WolfSheepPredation:Revisedtobetterclarifythegrass?constructandcode.
RevisedCurricularModels:
ConnectedChemistry:
ConnectedChemistry1:FixNetLogoWebincompatibility.
ConnectedChemistry3:Updateminimumnumberofparticlesto2.
ConnectedChemistry8:Minorcodeupdates.Smallchangetodefaultvalues.
RevisedHubNetActivities:
GridlockHubNet:Minorcodeupdates.
RevisedCodeExamples:
InfoTabExample:Correctedformattingofun/orderedlistsexample.
LSExtension–ModelVisualizerandPlotterExample:Updatedcodedependenciesfor
WSP.
LSExtension–ModelInteractionsExample:UpdatedcodedependenciesforWSP.
Version6.0.1(March2017)
FeatureChanges
Bracketsarerequiredaroundanonymousprocedurereportersonlywhentherearetwo
ormorearguments.Forinstance[ [x] -> x ]cannowbewritten[ x -> x ] .Notethis
changemakesitpossibletocreatemodelsinNetLogo6.0.1thatwillnotruninNetLogo
6.0.IfyouplantouseyourmodelinNetLogo6.0,besuretoincludebracketsaround
anonymousprocedurearguments.Forashortperiodaftertherelease,modelswhich
useunbracketedlambdaargumentsmaynotworkonnetlogoweb.org.
Bugfixes
TheNetLogocodeeditornavigatesandindentsmodelsmuchmorequicklyand
efficientlythaninNetLogo6.0.
TheNetLogo5-to-6autoconverternowignorescommented-outcode.
Thebehavioroflayout-radialinNetLogo6didnotmatchthe5.3.1behavior.Thishas
beencorrectedandlayout-radialshouldbeidenticalbetweenNetLogo6.0.1and
NetLogo5.3.1
NetLogo6raisedaNullPointerExceptionwhennumbersbecametoolargeforNetLogo
tohandle.Thisisnowproperlydisplayedtotheuserasanumberoutofboundserror.
Improvedperformanceofmodelswhichuseletandanonymousprocedurestogether.
Reloadingamodelnowclearsglobalvariables.
ClearerwarningdialogswhenopeninganolderversionofaNetLogo2DfileinNetLogo
3D.
UsingforeachimproperlyintheCommandCenterwilldisplaythesameerrorasitwould
ifusedimproperlyinthecodetab.
Extremelylonganonymousproceduresnolongercauseanexceptionwhencompiled.
in-radiusisnolongerpathologicallyslowonagentsetscreatedusingwith.
ExtensionChanges
Anewprimitive,table:valueshasbeenaddedtothetableextension.
TheRextensionhasbeenupdatedtotakefulladvantageoftheJavaGDRlibraryusing
r:setPlotDevice.
UserscannowsupplyapathtotheRextensionbyconfiguringthevalueofr.lib.pathsin
theuser.propertiesfile.
FixedaLevelSpacebugpreventinginteractivemodelsfromusingnlsfiles.
FixedaLevelSpacebugcausingNetLogotolockupwhentryingtoloadanonexistent
fileasaninteractivemodel.
DocumentationChanges
Thesystemdynamicstutorialnowinstructstheusertosetthedttoavaluewhichgives
stablebehavior
Thedocumentationforfollow,ride,andwatchhasbeenclarifiedtoindicatethatcalling
oneundoeshighlightsandperspectivechangescausedbytheother
Thedocumentationfor=and!=indicatesthattheyworkwithextensionobjects.
Severalexampleshavebeenaddedtosortclarifyingthebehaviorofsortonlists
featuringdifferenttypesofobjects.
AnewsectiononUserInterfaceprimitiveshasbeenaddedtotheprogrammingguide
whichdiscussesthebehaviorofthe“Halt”buttoninthevarioususerinteractiondialogs.
Incorrectexamplecodeforforeachandreducehasbeencorrected.
Models
Allmodelshavebeenupdatedtoreflectthenewoptionalnatureofbracketsforzero/one
argumentanonymousprocedures.Thisresultedinchangesto108models.
Allmodelshavebeenupdatedtoreflecttheavailabilityofthenewrangeprimitive.This
resultedinchangesto12models.
NewSampleModel
GenJam-Duple
NewCurricularModel
LatticeLandcurriculum:
LatticeLandExplore
RevisedSampleModels
PD2PersonIterated:infotabupdatesandextensivefixesforthecode.
Party:fixedbugwhereamonitorcoveredaplot.
SignalingGame:infotabupdates.
RevisedCurricularModels
GenEvocurriculum:
GenEvo1GeneticSwitch:infotabupdatesandnewgraduatedmethodof
displayinglacZconcentration.
GenEvo2GeneticDrift:infotabupdatesandinterfacetweaks.Newmodel
preview.
GenEvo3GeneticDriftandNaturalSelection:infotabupdatesandinterface
tweaks.
GenEvo4Competition:infotabupdates.
GeneticSwitch-SyntheticBiologyhasbeenrenamedandisnowSynthetic
Biology-GeneticSwitch.Italsoreceivedinfotabupdatesandafewinterface
changes.
Version6.0(December2016)
FeatureChanges
TheNetLogocodeeditornowoffersautocompletionsupport.SimplypresstheControl
keyandthespacebaratthesametimewhiletypingawordandyouwillseealistof
similarNetLogoprimitivesassuggestions.
TheNetLogocodeeditorofferstheoptionto“fold”procedurestomakenavigatinglarge
modelssimpler.
NetLogosupportsmulti-levelagent-basedmodelingwiththeLevelSpaceextension
LinenumberingcanbeenabledintheNetLogocodeeditorbychoosing“ShowLine
Numbers”fromthe“Preferences”dialog.Thisdialogcanbeopenedbyselecting
“NetLogo”>“Preferences”inMac,or“Tools”>“Preferences”onLinuxorWindows.
Theviewresizingarrowshavebeenremovedandthetickcounterhasbeenrelocated
underthespeedslider.
WheneditingNetLogocode,userscanright-clickavariablenameorprimitiveand
choose“ShowUsage”toseeallusagesofthatnameinthefile.
WheneditingNetLogocode,userscanright-clickavariablenameandchoose“Jumpto
Declaration”toseewhereinthefilethatvariableisdeclared.
TheNetLogointerfaceeditornowsupports“Undo”forwidgetaddition,deletion,and
movement.
NetLogocanexportcodetoHTMLwithcode-colorizationbychoosing“ExportCode”in
the“Export”sectionofthe“File”menu.
ThelookandfeelofNetLogoonMacOSXhaschangedsignificantly.NetLogoisnow
usingtheOracle-suppliedJavalookandfeelasopposedtoathird-partylookandfeel
usedinpriorversions.
Plotsusearandomnumbergeneratorindependentofthemain-modelrandomnumber
generator.
ModelPreviewCommandscanbeeditedthroughtheGUIbychoosing“Preview
CommandsEditor”inthe“Tools”menu.Thosecommandsgeneratethepreviewimage
thatappearswhenyouuploadyourmodeltotheModelingCommons.
NetLogodisplaysamorehelpfulerrormessagewhenaprogramfailsduetoan“outof
memory”error.
NetLogoanditsbundledextensionsarenowcompiledagainstJava8andScala2.12.
NetLogohasupgradedtheASMbytecodelibrarytoenablegenerationofJava8
bytecode.
Bugfixes
*-link-neighbor?primitivesnowworkthesamewayforbreededandunbreededlinks.
ResizingtheworldinNetLogo3Dnolongercausesablackview.
Fixederrorcausedbyright-clickingawidgetwhiledragging.
Improvederrormessagewhenauser-definedprocedureshadowsabreedprocedure.
neighbors4andneighborsnolongerreportagentsetscontainingthesamepatchmore
thanonce.
LanguageChanges
Supportforplural-onlybreednames(e.g.,breed [mice])hasbeenremoved.Writebreed
[mice mouse]instead.
Taskshavebeenreplacedbyanonymousprocedures.Tasksmadeuseof?variables
whichwereconfusingfornovicesanddifficulttoreadforexperts.Additionally,tasks
couldnotrefertothetaskvariablesofacontainingtask.Anonymousproceduresmay
havenamedargumentswhichcanbeaccessedbyinneranonymoustasks.Uponfirst
openingaNetLogo5modelinNetLogo6,tasksliketask [ ?1 + ?2 ] willbe
automaticallyconvertedto[ [?1 ?2] -> ?1 + ?2 ] .Seethethetransitionguidefor
moreinformation.
Linkreportershavebeenoverhauledtobemoreconsistentandflexible
Thetaskprimitiveisnolongersupported.
Breednamesthatconflictwithlanguageprimitivesarenowdisallowed.Forinstance,
breed [strings string]isnowdisallowedsinceitmakesis-string?ambiguous.
Thecompilererrorsonduplicatedbreedsingularnames.
Thecompilerdetectsagreaternumberoftypeerrors,forinstancenot pxcornowraises
acompilererrorinsteadoferroringatruntime.
set-plot-pen-colornowacceptsRGBlistsasarguments.
Thehubnet-set-client-interfaceprimitivehasbeenremoved.
Thevariousprimitivesstartingwithmovie-havebeenremoved,ashasthemovie
encoder.Theyhavebeenreplacedwiththenewvidextension.Thetransitionguide
providesmoredetailsandinformation.
The__change-languageprimitivehasbeenremoved.YoucannowchangetheUser
InterfaceLanguagethroughthepreferencesdialog,whichcanbefoundbychoosing
“Preferences…”inthe“NetLogo”menu(MacOSX)orinthe“Tools”menu(allother
platforms).
Thestringrepresentationofanonymousproceduresdisplaysthebodyofthe
anonymousprocedure.
ExtensionChanges
NetLogo6.0comeswiththreenew,bundledextensions:LevelSpacels,thevid
extensionforvideomanipulation,andtheenhancedvisualizationextensionview2.5d.
lsenablesmulti-levelagent-basedmodelinginNetLogo.
TheExtensionsAPIhasbeenupdatedfrom5.0to6.0.Thismeansthatallnon-bundled
extensionswillneedtobeupdatedtousethenewAPI.ExtensionswrittenforNetLogo
5willnotworkinNetLogo6.Ifyou’reanextensionauthor,seetheextensionauthor
transitionguidefor6.0formoreinformation.Ifyouregularlyuseextensionsyoumay
wanttocontacttheirauthorstoinformthemanewversionofNetLogoisonthewayand
theymaywanttoupdatetheirextensions.
arduino:get(inthearduinoextension)correctlyreportsvaluesfromWindows64-bit
machines.Inpriorversionsitwouldonlyreportsomevaluescorrectly.
Severalnewfeatureshavebeenaddedtothenwextension:
AddedcommunitydetectionusingtheLouvainmethod
Addedmodularitymeasurement
AddedWatts-Strogatzsmall-worldnetworkgeneration
Madeothernetworkgenerationalgorithmseasiertolayout
Weightedprimitivesnowtakesymbolicvariablenamesinsteadofstrings.Seethe
transitionguideformoreinformation.
TheqtjextensionisnolongerbundledwithNetLogo.Usersareencouragedtomake
useofthenewvidextension.
ThenewvidextensionisnowbundledwithNetLogo,combiningfeaturesofthelateqtj
extensionandthemovieprimitives.
ThenetworkextensionisnolongerbundledwithNetLogo.Usersareencouragedtouse
thenwextension(https://ccl.northwestern.edu/netlogo/docs/nw.html),whichhasbeen
bundledwithNetLogoforsometime.
Thegogo-serialextensionisnolongerbundledwithNetLogo.Usersareencouragedto
transitiontothenewergogoextension,whichusesHIDtocommunicatewiththeGoGo
board.
OperatingSystemSupport
NetLogowillnowbeusedtoopen.nlogolinksinPowerPointandotherprogramson
MicrosoftWindows.
TheNetLogobinariesonMacOSXareinstalledasrunnablebyanyuser.
NetLogoinMacOSXwillnotuse“AppNap”whilerunning.Thiskeepssimulations
runningatfullspeedwhenNetLogoisinthebackground.
TheNetLogocontrollingAPIhaschangedsinceNetLogo5.Programsthatrelyonthe
controllingAPI(suchasBehaviorSearch)willnotworkuntiltheyhavebeenchangedto
matchthenewAPI.
DocumentationChanges
Newdocumentationforanonymousprocedures
TheNetLogotutorialscreenshotshavebeenupdatedtocorrespondtothenewMacOS
XLookandFeel.
TheNetLogodictionarydisplaystheversioninwhicheachprimitivewasintroducednext
tothatprimitive.
ASpanishtranslationoftheNetLogodictionaryisavailablehere
InternationalizationChanges
AnewSpanishtranslationoftheNetLogodictionaryisavailableaspartoftheNetLogo
manual.
Languagepreferencescanbechangedbyusingthenew“Preferences”menuinsteadof
the__change-languageprimitive.
AJapaneselocalizationforNetLogoisnowavailableandincludedwiththestandard
download.
TheChinesetranslationforNetLogohasbeenupdated.
Models
NewSampleModels:
KickedRotator
KickedRotators
Mammoths,alegacyStarLogoTmodel,hasbeenconvertedtoNetLogo.
NewCurricularModels:
GenEvo1GeneticSwitch
GenEvo2GeneticDrift
GenEvo3GeneticDriftandNaturalSelection
GenEvo4Competition
NewCodeExamples:
MoviePlayingExample(vidextension)
MovieRecordingExample(vidextension)
VideoCameraExample(vidextension)
NetworkExtensionGeneralDemo(nwextension)
ModelInteractionsExample(lsextension)
ModelLoaderExample(lsextension)
ModelVisualizerandPlotterExample(lsextension)
PromotedModels(improvedandnolonger“unverified”):
ProbLabGenetics
Traffic2Lanes
RevisedSampleModels:
GiantComponent:addedtextintheinfotab.
TeamAssembly:removedunusedswitchwidget.
TrafficBasic,TrafficGrid,TrafficIntersection:revisedinfotab.
Voting:stoppedthemodelwhenvotingstabilizes.
WealthDistribution:fixedtyposininfotab,improvedcodeformatting.
RevisedHubNetActivities:
BugHuntersCompetitionHubNet,CritterDesignersHubNet,FishSpottersHubNet:
removedunnecessarycalltohubnet-set-client-interface.
GridlockHubNet,GridlockAlternateHubNet:revisedinfotab.
RevisedCurricularModels:
DNAReplicationFork:fixedaamonitorandruntimeerrorwhenusingatimelimit.
RevisedIABMmodels:
AgentsetEfficiency:clarifieddescriptionofgo-2ininfotab.
AgentsetOrdering:fixedtyposinintotab.
ArduinoExample:improvedmodeltodemonstratebothdirectionsofcommunication
withtheArduino.
HeroesandCowards:removedextratextininfotab.
PreferentialAttachmentSimple:removedextrapeninplotandextra“layout”button.
RandomNetwork:madesurethatthenumberoflinksisnevertoobigforthenumberof
nodes.
SegregationSimpleExtension1,2and3:fixednumber-of-ethnicitiesslidertoavoid
runtimeerrors.
TrafficBasicAdaptiveIndividuals,TrafficBasicUtility,TrafficGridGoal:revisedinfotab.
TrafficBasicAdaptive:revisedinfotab,clarifiedcommentinadaptive-goprocedure.
VotingComponentVerification:stoppedthemodelwhenvotingstabilizes.
VotingSensitivityAnalysis:improvedcodeforstoppingthemodelwhenvoting
stabilizes.
RevisedCodeExamples:
GoGoMonitorSerial,GoGoMonitorSimpleSerial:removedthemodels,asthegogo-
serialandqtjextensionsarenolongerbundled.
RandomNetworkExample:madesurethatthenumberoflinksisnevertoobigforthe
numberofnodes.
SincetheQuickTimeextension(qtj)hasbeenreplacedbythevidextension,the
followingmodelshavebeenconvertedtousethevidextension:
MovieExample,replacedbyMovieRecordingExample
QuickTimeMovieExample,replacedbyMoviePlayingExample
QuickTimeCameraExample,replacedbyVideoCameraExample
Demotedmodel:
ElFarolNetworkCongestion,apreviously“unverified”model,hasbeenmovedtothe
NetLogoUserCommunityModels
Version5.3.1(February2016)
FeatureChanges
MathematicaLinkisnowincludedandhasbeentestedtoworkwithMathematica10.
AlinktoIntroductiontoAgent-BasedModellinghasbeenaddedtothe“Help”menu.
ExtensionChanges
ThegogoextensionnowpromptstheuserforthelocationofJavauponopening.This
versionofJavaisusedtolaunchthegogohiddaemon.
Thecorrectversionofthenetworkextensionisnowbundled,whichwillopenproperly
Bundlesthecfextension,whichaddsmatch,case,andselectprimitives.
Bugfixes
Correctsabugwhereturtleswrappingaroundatorus-shapedworldwithpendown
wouldsometimescauseNetLogotoloopinfinitely.
FixesabugwherebuttonswouldappeartoremainpressedafterarightclickonMac.
Fixesabugwherepressingtherightmousebuttonwhiledraggingwouldconfusethe
mouse-down?primitive.
Fixesagenttype-checkingoftasks(bugappearedin5.2.1).
link-neighbor?nowreturnstrueifandonlyiftheneighborisconnectedthroughan
undirectedlink.
Documentationfixesformy-linksandmeanprimitives.
Version5.3(December2015)
FeatureChanges
Java8isnowbundledwithallversionsofNetLogo,thisremovestheneedfora
separateJava6installationonMacOSX
Separate32-bitand64-bitversionsareavailableforbothWindowsandLinux
TheWindowsinstallerisnowanmsiinsteadofanexe
javax.media.openglisnolongersupportedinJava8,ithasbeenreplacedby
com.jogamp.opengl
MathematicaLinkisnotdistributedduetoJavaversionchanges
ExtensionChanges
Aminorupdatetothenwextensionmakesnw:weighted-path-tobehaveas
documented.
Mostextensionsshouldcontinuetoworkwithoutchangeunlesstheyrelyon
javax.media.opengl,whichwasrenamedintheupdatedversionofJOGL.
Version5.2.1(September2015)
Extensions
AnincludedArduinoextensionforusewithArduinoboards
Newfeatures
NewfilemenuitemtoexportmodelstoNetLogoWeb
Bugfixes
BehaviorSpaceoutputtypepreferenceisnowremembered
Outputwidgetfontisnowsavedatthepropersizewhenzoomed
Reportertasksarenowevaluatedinvariablecontext
runresultargumentsnowonlygetevaluatedonce
ThelastuseddirectoryisnowrememberedonLinux
Whitespaceisnowstrippedfrommodelswhensaving
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,
BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,Bug
HuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-
Jones,Paths
Thereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,
AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4
ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheep
Extensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetwork
Example,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,
TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponent
Verification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroid
AvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,Simple
MachineLearning,SimpleViralMarketing,TicketSales,SandpileSimple
NewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-Alternative
Visualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternative
visualization,Virus-AlternativeVisualization,Virus-CircleVisualization
Promotedmodels:Honeycomb,MinorityGame
Manyotherbugfixesandupgrades
Modelchanges
ImprovedSampleModels:Altruism,AntLines,ArtificialAnasazi,Cooperation,
Daisyworld,DividetheCake,HeatDiffusion,HydrogenDiffusion3D,Lennard-Jones,N-
Bodies,PDBasicEvolutionary,Sandpile,RobbytheRobot,Segregation,Simple
Kinetics2and3,TrafficGrid,GridLockHubNet,GridLockHubNetAlternate
RevisedCurricularModels:4BlockStalagmites,4BlockTwoStalagmites,BugHunter
CompetitionHubNet,FishSpottersHubNet,Ising,TijuanaBordertowns,UrbanSuite-
TijuanaBordertowns,
RevisedCodeExamples:LotteryExample,selfExample,NetworkImportExample
RevisedIABMTextbookmodels:SimpleEconomy,FireSimpleExtension2and3,
SegregationSimple,1,2and3,AgentsetEfficiency,PreferentialAttachmentSimple,
RandomNetwork,TrafficBasicAdaptive,RunExample,TrafficGridGoal,
NewIABMTextbookmodel:TrafficBasicAdaptiveIndividuals
Version5.2.0(April2015)
Extensions
AnincludedCSVextensiontoreadandwriteCSVfiles
AnincludedPaletteextensiontomapdifferentvaluestocolors
Thepreviousgogoextensionhasbeenremoved.Ithasbeenreplacedwithtwodifferent
gogoextensions,gogoandgogo-serial.Theextensionsworkwithdifferenthardware.
ThegogoextensionworkswiththenewstyleHID-interfacegogoboardsandthegogo-
serialextensionworkswiththeold-styleserial-interfacegogoboards
Upgradetothenetworkextensionincludingthefollowingchanges:
Supportformanymorefiletypes,includingGEXF,GDF,GML,PajekNET,
UCINETDL,andNetdrawVNA
FixedbugswithGraphMLsupport
Improveddocumentation
Newfeatures
Newprimitivenetlogo-web?addedtotestwhetheryouarecurrentlyrunninginNetLogo
Web
Newprimitivebehaviorspace-experiment-nameaddedallowingyoutogetthenameof
thecurrentlyrunningexperiment
Newprimitivestop-inspectingtostopinspectingagents
Newprimitivestop-inspecting-dead-agentsandmenuitemtostopinspectingdead
agents
__includeskeywordnowenablestheIncludesbuttonwhengivenanempty
hooksaddedforextensionstowritecustomlogmessages
Bugfixes
user-one-ofwillnowsignalanerrorearlierwhenprovidedanemptylistofchoices
hsb,extract-hsb,andapproximate-hsbhavebeenupdatedtorepresenttruehsb
conventions
newdeprecatedprimitives__hsb-old,__extract-hsb-old,and__approximate-hsb-old
workastheoldhsbprimitivesdidwhenoldermodelsusingthehsbprimitivesare
openedinNetLogo5.2,theywillbeauto-convertedtousethedeprecatedprimitives
extract-hsb–fixedbugwhereitdidn’tworkcorrectlyonrgblists
Modelchanges
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,
BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,Bug
HuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-
Jones,Paths
Thereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,
AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4
ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheep
Extensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetwork
Example,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,
TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponent
Verification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroid
AvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,Simple
MachineLearning,SimpleViralMarketing,TicketSales,SandpileSimple
NewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-Alternative
Visualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternative
visualization,Virus-AlternativeVisualization,Virus-CircleVisualization
Promotedmodels:Honeycomb,MinorityGame
Manyotherbugfixesandupgrades
Version5.1.0(July2014)
bundlenewnetworkextension
Filemenuincludesrecentlyopenedfiles
deprecateapplets
supportretinadisplayonnewMacBooks
Version5.0.4(March2013)
uploadmodelstotheModelingCommons
Version5.0(February2012)
features:
opensource(GPLlicense;sourcecodeonlineat
https://github.com/NetLogo/NetLogo)
newlicenseforSampleModelsandCurricularModelsisCreativeCommons
Attribution-NonCommercial-ShareAlike
internationalcharacters(Unicode)supportedthroughoutapplication
GUIislocalizedinSpanish,Russian,andChinese(volunteertranslatorswanted)
richformattingandimagesinInfotabsusingMarkdown
plottingcodegoesinsideplotsinsteadofincodetab
authorablemodelspeed(targetframeratesetting)
buttonsoptionallydisableuntilticksstart
translucentcolorsin3DviewandNetLogo3D(forRGBcolorsonly)
languagechanges:
“tasks”storecodetoberunlater
akafirst-classfunctions,closures,lambda
newprimitives:task,is-command-task?,is-reporter-task?
theseprimitivesaccepttasks:run,runresult,foreach,map,reduce,filter,n-
values,sort-by
improvedoveralllistperformance(manyoperationstakenear-constanttime
insteadoflineartime)
youmustusereset-tickstostartthetickcounterbeforeusingtickortick-
advance
newprimitivessetup-plotsandupdate-plots
newprimitivesort-onletsyousaye.g.,sort-on [size] turtles
newprimitiveerrorcausesaruntimeerror
random-normalrejectsnegativestandarddeviations
HubNet:
activitiescanrunheadless
newprimitiveshubnet-clients-list,hubnet-kick-client,hubnet-kick-all-
clients
hubnet-set-client-interfacenolongerrequired
otherfixesandchanges:
tabsrenamedtoInterface/Info/Code
CommandCenterallowsreporters,addsshowcommandautomatically
NetLogo3Duses.nlogo3dsuffix,not.nlogo
import-worldismuchfaster
startupnolongerrunsheadlessorinbackgroundBehaviorSpaceruns
fixed3Drenderingbugwheresmallturtlesweretoobright
Macapprunsin64bitmodebydefault
upgradedWindowsinstaller
GoGoextensiongetting-startedexperiencenowsmootheronallplatforms
models:
newSampleModels:Sandpile,Lightning,OsmoticPressure,RobbytheRobot,
PreferentialAttachment3D
newCurricularModels:BugHuntConsumers,BugHuntPredatorsandInvasive
Species,PlantSpeciation,epiDEMBasic,epiDEMTravelandControl,Connected
ChemistryAtmosphere
newCodeExamples:InfoTabExample,GoGoMonitorSimple
Version4.1.3(April2011)
matrixextension
behaviorspace-run-number
Version4.1(December2009)
parallelBehaviorSpace
controllingAPIallowsembedding
automaticcodeindenter
searchableModelsLibrary
translucentcolors
mini-viewsinagentmonitors
resize-world,set-patch-size
bitmap,QuickTimeextensions
individualizedHubNetclientviews
browser-basedHubNetclient
Version4.0(September2007)
linkagents
tickcounter
viewupdatemodes(tick-based,continuous)
speedsliderfastforwards
inputboxesininterfacetab
includemultiplesourcefiles
RGBcolors
sliderboundsmaybereporters
HubNetclienteditor
Mathematica-NetLogolink
array,table,profiler,GISextensions
modelsrunfaster(partialcompilationtoJVMbytecode)
logging
Version3.1(April2006)
topologies(optionalwrappingatworldedges)
randomizedagentsetordering
Version3.0(September2005)
3Dview(for2Dmodels)
formattedInfotabs
SystemDynamicsModeler
follow,ride,watch
drawinglayer
GoGoextension
Version2.1(December2004)
“headless”modeforcommandlineoperation
“actionkeys”totriggerbuttonsbykeypresses
makesQuickTimemoviesofmodels
let,carefully
Version2.0.2(August2004)
extensionsandcontrollingAPIs
soundextension
Version2.0(December2003)
fast,flicker-free,non-grid-basedgraphics
Version1.3(June2003)
run,runresult,map,foreach,filter,reduce
Version1.2(March2003)
computersasHubNetclients
Version1.1(July2002)
Applets
Version1.0(April2002)
firstfullrelease(afteraseriesofbetas)
SystemRequirements
NetLogo6.0.4UserManual
NetLogorunsonalmostanycurrentcomputer.
IfyouhaveanytroublewithNetLogonotworking,seeContactingUs.
ApplicationRequirements
Windows
NetLogorunsonWindows10,Windows8,Windows7andVista.NetLogo5.2.1wasthelast
versiontosupportWindowsXPandWindows2000.
TheNetLogoinstallerforWindowsincludesJava8forNetLogo’sprivateuseonly.Other
programsonyourcomputerarenotaffected.
MacOSX
MacOSX10.8.3ornewerisrequired.(NetLogo5.1wasthelastversiontosupport10.5and
10.4;NetLogo5.2.1wasthelastversiontosupport10.6and10.7)
TheNetLogoapplicationcontainsadistributionoftheJava8runtimeforNetLogo’sprivate
useonly.Otherprogramsonyourcomputerwillnotbeaffected.
Linux
NetLogoshouldworkonstandardDebian-basedandRedHat-basedLinuxdistributions.The
NetLogotarballincludesacopyoftheJava8runtime.
StartNetLogobyrunningtheprovidedNetLogoexecutable.
3DRequirements
Occasionallyanolder,lesspowerfulsystemisnotabletousethe3DvieworNetLogo3D.
Tryitandsee.
Somesystemscanuse3Dbutcan’tswitchtofull-screenmode.Itdependsonthegraphics
cardorcontroller.(Forexample,theATIRadeonIGP345andIntel82845probablywillnot
work.)
32-bitor64-bit?
FormostusersonLinuxorWindows,the32-bitversionofNetLogoisthesimplestwaytoa
workingNetLogoinstallation.Advanceduserswillwanttounderstandtheadvantagesof64-
bitNetLogoaswellashowtodeterminewhethertheirmachinemeetstherequirements.
Theprimaryadvantageofthe64-bitversionistheabilitytoaddadditionalheapspaceby
changingthe“-Xmx”JVMoption.Formoreinformation,seeHowbigcanmymodelbe.You
mayalsofindithelpfultobrowseOracle’sdocumentationontheperformancecharacteristics
ofthe64-bitJVM
Torun64-bitNetLogo,youmustberunning64-bitWindows.Todeterminewhetheryour
versionofWindowsis64-bit,seeIsmyPCrunningthe32-bitor64-bitversionofWindowsif
you’reusingWindowsVista,orWindows7,orWhichWindowsoperatingsystemamI
running?ifyouarerunninganyotherversionofWindows.
ForLinuxusers,theeasiestwaytodeterminewhetheryouroperatingsystemis64-bitis
checkingtheoutputof
uname -m
Iftheoutputshows“x86_64”or“amd64”,youshouldbeabletorunthe64-bitversion.
ContactingUs
NetLogo6.0.4UserManual
FeedbackfromusersisessentialtousindesigningandimprovingNetLogo.We’dliketohear
fromyou.
Website
Ourwebsiteathttp://ccl.northwestern.edu/includesourmailingaddressandphonenumber.
Italsohasinformationaboutourstaffandourvariousresearchactivities.
Feedback,questions,etc.
ForhelpusingNetLogo,trythisgroup:http://groups.google.com/d/forum/netlogo-users.
Ifyouhavefeedback,suggestions,orquestions,youmaywriteusat
feedback@ccl.northwestern.edu.
Reportingbugs
OurpublicbugtrackerisonGitHubathttps://github.com/NetLogo/NetLogo/issues.Youcan
lookheretoreportanewbug,checkifabughasalreadybeenreported,andsoon.
Whensubmittingabugreport,pleasetrytoincludeasmuchofthefollowinginformationas
possible:
Acompletedescriptionoftheproblemandhowitoccurred.
TheNetLogomodelorcodeyouarehavingtroublewith.Ifpossible,attachacomplete
model.(It’sbestifyoucanreducetheamountofcodeinthemodeltotheminimum
necessarytodemonstratethebug.)
Yoursysteminformation:NetLogoversion,OSversion,Javaversion,andsoon.This
informationisavailablefromNetLogo’s“AboutNetLogo”menuitem,thenclickingthe
Systemtab.
Anyerrormessagesthatweredisplayed.Pleasecopyandpastetheentireerror
messageintoyouremail,ormakeascreencaptureifyouareunabletocopyandpaste.
Wealsoacceptbugreportsbyemailatbugs@ccl.northwestern.edu.
Opensource
NetLogoisfree,opensourcesoftware.Thesourcecodeishostedat
https://github.com/NetLogo/NetLogo.Contributionsfrominterestedusersarewelcome.
FordiscussionofNetLogoAPI’sandthedevelopmentofNetLogoitself,try
https://groups.google.com/group/netlogo-devel.
SampleModel:Party
NetLogo6.0.4UserManual
Thisactivitygetsyouthinkingaboutcomputermodelingandhowyoucanuseit.Italsogives
youinsightintoNetLogoitself.Weencouragebeginninguserstostarthere.
AtaParty
Haveyoueverbeenatapartyandnoticedhowpeopleclusteringroups?Youmayhavealso
noticedthatpeopledon’tjuststayinagroup.Astheycirculate,thegroupschange.Ifyou
watchedthesechangesovertime,youmightnoticepatterns.
Forexample,insocialsettings,peoplemayexhibitdifferentbehaviorthanatworkorhome.
Individualswhoareconfidentwithintheirworkenvironmentmaybecomeshyandtimidata
socialgathering.Andotherswhoarereservedatworkmaybethe“partystarter”withfriends.
Thesepatternscandependonthetypeofgathering.Insomesettings,peoplearetrainedto
organizethemselvesintomixedgroups;forexample,partygamesorschool-likeactivities.But
inanon-structuredatmosphere,peopletendtogroupinamorerandommanner.
Isthereanytypeofpatterntothiskindofgrouping?
Let’stakeacloserlookatthisquestionbyusingthecomputertomodelhumanbehaviorata
party.NetLogo’s“Party”modellooksspecificallyatthequestionofgroupingbygenderat
parties:whydogroupstendtoformthataremostlymen,ormostlywomen?
Let’suseNetLogotoexplorethisquestion.
Whattodo:
1. StartNetLogo.
2. Choose“ModelsLibrary”fromtheFilemenu.
3. Openthe“SocialScience”folder.
4. Clickonthemodelcalled“Party”.
5. Pressthe“open”button.
6. Pressthe“setup”button.
Intheviewofthemodel,youwillseepinkandbluegroupswithnumbers:
Theselinesrepresentminglinggroupsataparty.Menareshownasblue,womenpink.The
numbersarethesizesofthegroups.
Doallthegroupshaveaboutthesamenumberofpeople?
Doallthegroupshaveaboutthesamenumberofeachsex?
Let’ssayyouarehavingapartyandinvited150people.Youarewonderinghowpeoplewill
gathertogether.Suppose10groupsformattheparty.
Howdoyouthinktheywillgroup?
Insteadofasking150ofyourclosestfriendstogatherandrandomlygroup,let’shavethe
computersimulatethissituationforus.
Whattodo:
1. Pressthe“go”button.(Pressing“go”againwillstopthemodelmanually.)
2. Observethemovementofpeopleuntilthemodelstops.
3. Watchtheplotstoseewhat’shappeninginanotherway.
4. Usethespeedsliderifyouneedtoslowthemodeldown.
Nowhowmanypeopleareineachgroup?
Originally,youmayhavethought150peoplesplittinginto10groups,wouldresultinabout15
peopleineachgroup.Fromthemodel,weseethatpeopledidnotdivideupevenlyintothe10
groups.Instead,somegroupsbecameverysmall,whereasothergroupsbecameverylarge.
Also,thepartychangedovertimefromallmixedgroupsofmenandwomentoallsingle-sex
groups.
Whatcouldexplainthis?
Therearelotsofpossibleanswerstothisquestionaboutwhathappensatrealparties.The
designerofthissimulationthoughtthatgroupsatpartiesdon’tjustformrandomly.Thegroups
aredeterminedbyhowtheindividualsatthepartybehave.Thedesignerchosetofocusona
particularvariable,called“tolerance”:
Toleranceisdefinedhereasthepercentageofpeopleoftheoppositesexanindividualis
“comfortable”with.Iftheindividualisinagroupthathasahigherpercentageofpeopleofthe
oppositesexthantheirtoleranceallows,thentheybecome“uncomfortable”andleavethe
grouptofindanothergroup.
Forexample,ifthetolerancelevelissetat25%,thenmalesareonly“comfortable”ingroups
thatarelessthan25%female,andfemalesareonly“comfortable”ingroupsthatareless
than25%male.
Asindividualsbecome“uncomfortable”andleavegroups,theymoveintonewgroups,which
maycausesomepeopleinthatgrouptobecome“uncomfortable”inturn.Thischainreaction
continuesuntileveryoneatthepartyis“comfortable”intheirgroup.
Notethatinthemodel,“tolerance”isnotfixed.You,theuser,canusethetolerance“slider”to
trydifferenttolerancepercentagesandseewhattheoutcomeiswhenyoustartthemodel
overagain.
Howtostartover:
1. Ifthe“go”buttonispressed(black),thenthemodelisstillrunning.Pressthe
buttonagaintostopit.
2. Adjustthe“tolerance”slidertoanewvaluebydraggingitsredhandle.
3. Pressthe“setup”buttontoresetthemodel.
4. Pressthe“go”buttontostartthemodelrunningagain.
Challenge
Asthehostoftheparty,youwouldliketoseebothmenandwomenminglingwithinthe
groups.Adjustthetoleranceslideronthesideoftheviewtogetallgroupstobemixedasan
endresult.
Tomakesureallgroupsof10havebothsexes,atwhatlevelshouldwesetthe
tolerance?
Testyourpredictionsonthemodel.
Canyouseeanyotherfactorsorvariablesthatmightaffectthemaletofemale
ratiowithineachgroup?
Makepredictionsandtestyourideaswithinthismodel.
Asyouaretestingyourhypotheses,youwillnoticethatpatternsareemergingfromthedata.
Forexample,ifyoukeepthenumberofpeopleatthepartyconstantbutgraduallyincrease
thetolerancelevel,moremixedgroupsappear.
Howhighdoesthetolerancevaluehavetobebeforeyougetmixedgroups?
Whatpercenttolerancetendstoproducewhatpercentageofmixing?
Thinkingwithmodels
UsingNetLogotomodelasituationlikeapartyallowsyoutoexperimentwithasystemina
rapidandflexiblewaythatwouldbedifficulttodointherealworld.Modelingalsogivesyou
theopportunitytoobserveasituationorcircumstancewithlessprejudice,asyoucan
examinetheunderlyingdynamicsofasituation.Youmayfindthatasyoumodelmoreand
more,manyofyourpreconceivedideasaboutvariousphenomenawillbechallenged.For
example,asurprisingresultofthePartymodelisthateveniftoleranceisrelativelyhigh,a
greatdealofseparationbetweenthesexesoccurs.
Thisisaclassicexampleofan“emergent”phenomenon,whereagrouppatternresultsfrom
theinteractionofmanyindividuals.Thisideaof“emergent”phenomenacanbeappliedto
almostanysubject.
Whatotheremergentphenomenacanyouthinkof?
ToseemoreexamplesandgainadeeperunderstandingofthisconceptandhowNetLogo
helpslearnersexploreit,youmaywishtoexploreNetLogo’sModelsLibrary.Itcontains
modelsthatdemonstratetheseideasinsystemsofallkinds.
ForalongerdiscussionofemergenceandhowNetLogohelpslearnersexploreit,see
“ModelingNature’sEmergentPatternswithMulti-agentLanguages”(Wilensky,2001).
What’snext?
ThesectionoftheUserManualcalledTutorial#1:RunningModelsgoesintomoredetail
abouthowtousetheothermodelsintheModelsLibrary.
Ifyouwanttolearnhowtoexplorethemodelsatadeeperlevel,Tutorial#2:Commandswill
introduceyoutotheNetLogomodelinglanguage.
Eventually,you’llbereadyforTutorial#3:Procedures.Thereyoucanlearnhowtoalterand
extendexistingmodelstogivethemnewbehaviors,andyoucanstarttobuildyourown
models.
Tutorial#1:Models
NetLogo6.0.4UserManual
IfyoureadtheSampleModel:Partysection,yougotabriefintroductiontowhatit’sliketo
exploreaNetLogomodel.Thissectionwillgointomoredepthaboutthefeaturesthatare
availablewhileyou’reexploringthemodelsintheModelsLibrary.
Throughoutallofthetutorials,we’llbeaskingyoutomakepredictionsaboutwhattheeffects
ofmakingchangestothemodelswillbe.Keepinmindthattheeffectsareoftensurprising.
Wethinkthesesurprisesareexcitingandprovideexcellentopportunitiesforlearning.
Youmaywanttoprintoutthetutorialstomakethemeasiertorefertowhileyou’reusing
NetLogo.
SampleModel:WolfSheepPredation
We’llopenoneoftheSampleModelsandexploreitindetail.Let’stryabiologymodel:Wolf
SheepPredation,apredator-preypopulationmodel.
OpentheModelsLibraryfromtheFilemenu.
Choose“WolfSheepPredation”fromtheBiologysectionandpress“Open”.
TheInterfacetabwillfillupwithlotsofbuttons,switches,slidersandmonitors.These
interfaceelementsallowyoutointeractwiththemodel.Buttonsareblue;theysetup,start,
andstopthemodel.Slidersandswitchesaregreen;theyaltermodelsettings.Monitorsand
plotsarebeige;theydisplaydata.
Ifyou’dliketomakethewindowlargersothateverythingiseasiertosee,youcanusethe
Zoommenu.
Whenyoufirstopenthemodel,youwillnoticethatthe“view”(thegraphicaldisplayofthe
agentsinthemodel)isempty(allblack).Tobeginthemodel,youwillfirstneedtosetitup.
Pressthe“setup”button.
Whatdoyouseeappearintheview?
Pressthe“go”buttontostartthesimulation.
Asthemodelisrunning,whatishappeningtothewolfandsheep
populations?
Pressthe“go”buttontostopthemodel.
ControllingtheModel:Buttons
Whenabuttonispressed,themodelrespondswithanaction.Abuttoncanbea“once”
button,ora“forever”button.Youcantellthedifferencebetweenthesetwotypesofbuttons
byasymbolonthefaceofthebutton.Foreverbuttonshavetwoarrowsinthebottomright
corners,likethis:
Oncebuttonsdon’thavethearrows,likethis:
Oncebuttonsdooneactionandthenstop.Whentheactionisfinished,thebuttonpopsback
up.
Foreverbuttonsdoanactionoverandoveragain.Whenyouwanttheactiontostop,press
thebuttonagain.Itwillfinishthecurrentaction,thenpopbackup.
Mostmodels,includingWolfSheepPredation,haveaoncebuttoncalled“setup”anda
foreverbuttoncalled“go”.Manymodelsalsohaveaoncebuttoncalled“goonce”or“step
once”whichislike“go”exceptthatitadvancesthemodelbyonetick(timestep)insteadof
overandover.Usingaoncebuttonlikethisletsyouwatchtheprogressofthemodelmore
closely.
Stoppingaforeverbuttonisthenormalwaytopauseorstopamodel.Afterpausingyoucan
makeitresumebypressingthebuttonagain.(Youcanalsostopamodelwiththe“Halt”item
ontheToolsmenu,butyoushouldonlydothisifthemodelisstuckforsomereason.Using
“Halt”mayinterruptthemodelinthemiddleofanaction,andastheresultthemodelcould
getconfused.)
Ifyoulike,experimentwiththe“setup”and“go”buttonsintheWolfSheep
Predationmodel.
Doyouevergetdifferentresultsifyourunthemodelseveraltimeswith
thesamesettings?
Controllingspeed:SpeedSlider
Thespeedsliderallowsyoutocontrolthespeedofamodel,thatis,thespeedatwhichturtles
move,patcheschangecolor,andsoon.
Whenyoumovetheslidertotheleftthemodelslowsdownsotherearelongerpauses
betweeneachtick(timestep).Thatmakesiteasiertoseewhatishappening.Youmighteven
slowthemodeldownsofarastoseeexactlywhatasingleturtleisdoing.
Whenyoumovethespeedslidertotherightthemodelspeedsup.NetLogowillstartskipping
frames,thatis,itwon’tupdatetheviewattheendofeverytick,onlysometicks.Updating
takestime,sofewerviewupdatesmeansthemodelprogressesfaster.
Notethatifyoupushthespeedsliderwelltotheright,theviewmayupdatesoinfrequently
thatthemodelappearstohavesloweddown.Ithasn’t,asyoucanseebywatchingthetick
counterraceahead.Onlythefrequencyofviewupdateshaslessened.
AdjustingSettings:SlidersandSwitches
Amodel’ssettingsletyouexploredifferentscenariosorhypotheses.Alteringthesettingsand
thenrunningthemodeltoseehowitreactscangiveyouadeeperunderstandingofthe
phenomenabeingmodeled.
Switchesandslidersgiveyouaccesstoamodel’ssettings.Herearetheswitchesandsliders
inWolfSheepPredation:
Let’sexperimentwiththeireffectonthebehaviorofthemodel.
OpenWolfSheepPredationifit’snotopenalready.
Press“setup”and“go”andletthemodelrunforabout100ticks.(Thetick
countisshownabovetheview.)
Stopthemodelbypressingthe“go”button.
Whathappenedtothesheepovertime?
Let’stakealookandseewhatwouldhappentothesheepifwechangeasetting.
Turnthe“grass?”switchon.
Press“setup”and“go”andletthemodelrunforasimilaramountoftimeas
before.
Whatdidtheswitchdo?Wastheoutcomethesameasyourpreviousrun?
Turningthe“grass?”switchonaffectedtheoutcomeofthemodel.Withtheswitchoff,the
amountofgrassavailablealwaysstayedthesame.Thisisnotarealisticlookatthepredator-
preyrelationship;sobysettingandturningonagrassregrowthrate,wewereabletomodel
allthreefactors:sheep,wolfandgrasspopulations.
Anothertypeofsettingiscalledaslider.
Besidesswitches,amodelmayalsohavesliders.Whileaswitchhasonlytwovalues,onand
off,asliderhasawholerangeofnumericvalues.Forexample,the“initial-number-sheep”
sliderhasaminimumvalueof0andamaximumvalueof250.Themodelcouldrunwith0
sheeporitcouldrunwith250sheep,oranywhereinbetween.Trythisoutandseewhat
happens.Asyoumovethemarkerfromtheminimumtothemaximumvalue,thenumberon
therightsideofthesliderchanges;thisisthenumbertheslideriscurrentlysetto.
Let’sinvestigateWolfSheepPredation’ssliders.
ChangefromtheInterfacetotheInfotabtolearnwhateachofthismodels’
slidersrepresents.
TheInfotaboffersguidanceandinsightintothemodel.Withinthistabyouwillfindan
explanationofthemodel,suggestionsonthingstotry,andotherinformation.Youmaywant
toreadtheInfotabbeforerunningamodel,oryoumightwanttojuststartexperimenting,
thenlookattheInfotablater.
Whatwouldhappentothesheeppopulationifthereweremoresheepand
lesswolvesinitially?
Turnthe“grass?”switchoff.
Setthe“initial-number-sheep”sliderto100.
Setthe“initial-number-wolves”sliderto20.
Press“setup”andthen“go”.
Letthemodelrunforabout100ticks.
Tryrunningthemodelseveraltimeswiththesesettings.
Whathappenedtothesheeppopulation?
Didthisoutcomesurpriseyou?Whatotherslidersorswitchescanbe
adjustedtohelpoutthesheeppopulation?
Set“initial-number-sheep”to80and“initial-number-wolves”to50.(Thisis
closetohowtheywerewhenyoufirstopenedthemodel.)
Set“sheep-reproduce”to10.0%.
Press“setup”andthen“go”.
Letthemodelrunforabout100timeticks.
Whathappenedtothewolvesinthisrun?
Whenyouopenamodel,alltheslidersandswitchesareonadefaultsetting.Ifyouopena
newmodelorexittheprogram,yourchangedsettingswillnotbesaved,unlessyouchoose
tosavethem.
(Note:inadditiontoslidersandswitches,somemodelshavechoosersandinputboxes.The
WolfSheepPredationdoesn’thaveanyofthese,though.)
GatheringInformation:PlotsandMonitors
Theviewletsyouseewhat’sgoingoninamodel.NetLogoalsoprovideshasotherwaysof
givingyouinformationaboutmodelrun,suchasplotsandmonitors.
Plots
TheplotinWolfSheepPredationcontainsthreelines:sheep,wolves,andgrass/4.(The
grasscountisdividedbyfoursoitdoesn’tmaketheplottootall.)Thelinesshowwhat’s
happeninginthemodelovertime.Theplotlegendshowswhateachlineindicates.Inthis
case,it’sthepopulationcounts.
Whenaplotgetsclosetobecomingfilledup,thehorizontalaxisiscompressedandallofthe
datafrombeforegetssqueezedintoasmallerspace.Inthisway,moreroomismadeforthe
plottogrow.
Ifyouwanttosavethedatafromaplottovieworanalyzeitinanotherapplication,usethe
“ExportPlot”itemontheFilemenu.Itsavestheplotdatainaformatthatcanbyreadbackby
spreadsheetanddatabaseprogramssuchasExcel.Youcanalsoexportaplotbyright-
clickingitandchoosing“Export…”fromthepopupmenu.
Monitors
Monitorsareanothermeansofdisplayinginformationfromamodel.Herearethemonitorsin
WolfSheepPredation:
Themonitorsshowusthepopulationofsheepandwolves,andtheamountofgrass.
(Remember,theamountofgrassisdividedbyfourtokeeptheplotfromgettingtootall.)
Thenumbersdisplayedinthemonitorschangeasthemodelruns,whereastheplotsshow
youdatafromthewholecourseofthemodelrun.
ControllingtheView
IntheInterfacetab,you’llseeatoolbarofcontrols.Someofthesecontrolaspectsoftheview.
Let’sexperimentwiththeeffectofthesecontrols.
Press“setup”andthen“go”tostartthemodelrunning.
Asthemodelruns,movethespeedslidertotheleft.
Whathappens?
Thissliderishelpfulifamodelisrunningtoofastforyoutoseewhat’sgoingonin
detail.
Movethespeedslidertothemiddle.
Trymovingthespeedslidertotheright.
Nowtrycheckinganduncheckingthe“viewupdates”checkbox.
Whathappens?
Fastforwardingthemodelandturningoffviewupdatesareusefulifyou’reimpatientandwant
amodeltorunfaster.Fastforwarding(movingthespeedslidertotheright)dropsview
updatessothemodelcanrunfast,sinceupdatingtheviewtakestimethatcouldbeusedfor
runningthemodelitself.
Whenviewupdatesareoffcompletely,themodelcontinuestoruninthebackground,and
plotsandmonitorsstillupdate.Butifyouwanttoseewhat’shappening,youneedtoturnview
updatesbackonbyrecheckingthebox.Manymodelsrunmuchfasterwhenviewupdates
areoff.Forothers,itmakeslittledifference.
Thesizeoftheviewisdeterminedbyfiveseparatesettings:min-pxcor,max-pxcor,min-
pycor,max-pycor,andpatchsize.Let’stakealookatwhathappenswhenwechangethe
sizeoftheviewinthe“WolfSheepPredation”model.
Therearemoremodelsettingsthanthere’sroomforinthetoolbar.The“Settings…”button
letsyougettotherestofthesettings.
Pressthe“Settings…”buttoninthetoolbar.
Adialogwillopencontainingallthesettingsfortheview:
Whatarethecurrentsettingsformin-pxcor,max-pxcor,min-pycor,max-
pycor,andpatchsize?
Press“cancel”tomakethiswindowgoawaywithoutchangingthesettings.
Placeyourmousepointernextto,butstilloutsideof,theview.
Youwillnoticethatthepointerturnsintoacrosshair.
Holddownthemousebuttonanddragthecrosshairovertheview.
Theviewisnowselected,whichyouknowbecauseitisnowsurroundedbyagray
border.
Dragoneofthesquareblack“handles”.Thehandlesarefoundontheedges
andatthecornersoftheview.
Unselecttheviewbyclickinganywhereinthewhitebackgroundofthe
Interfacetab.
Pressthe“Settings…”buttonagainandlookatthesettings.
Whatnumberschanged?
Whatnumbersdidn’tchange?
TheNetLogoworldisatwodimensionalgridof“patches”.Patchesaretheindividualsquares
inthegrid.InWolfSheepPredation,whenthe“grass?”switchisontheindividualpatchesare
easilyseen,becausesomearegreen,othersbrown.
Thinkofthepatchesasbeinglikesquaretilesinaroomwithatilefloor.Bydefault,exactlyin
themiddleoftheroomisatilelabeled(0,0);meaningthatiftheroomwasdividedinhalfone
wayandthentheotherway,thesetwodividinglineswouldintersectonthistile.Wenowhave
acoordinatesystemthatwillhelpuslocateobjectswithintheroom:
Howmanytilesawayisthe(0,0)tilefromtherightsideoftheroom?
Howmanytilesawayisthe(0,0)tilefromtheleftsideoftheroom?
InNetLogo,thenumberoftilesfromrighttoleftiscalledworld-width.Andthenumberoftiles
fromtoptobottomisworld-height.Thesenumbersaredefinedbytop,bottom,leftandright
boundaries.
Inthesediagrams,max-pxcoris3,min-pxcoris-3,max-pycoris2andmin-pycoris-2.
Whenyouchangethepatchsize,thenumberofpatches(tiles)doesn’tchange,thepatches
onlygetlargerorsmallerintheview.
Let’slookattheeffectofchangingtheminimumandmaximumcoordinatesintheworld.
UsingtheSettingsdialogthatisstillopen,changemax-pxcorto30andmax-
pycorvalueto10.Noticethatmin-pxcorandmin-pycorchangetoo.That’s
becausebydefaulttheorigin(0,0)isinthecenteroftheworld.
Whathappenedtotheshapeoftheview?
Pressthe“setup”button.
Nowyoucanseethenewpatchesyouhavecreated.
Edittheviewbypressingthe“Settings…”buttonagain.
Changethepatchsizeto20andpress“OK”.
Whathappenedtothesizeoftheview?Diditsshapechange?
Editingtheviewalsoletsyouchangeothersettings.Feelfreetoexperimentwiththese.
OnceyouaredoneexploringtheWolfSheepPredationmodel,youmaywanttotakesome
timejusttoexploresomeoftheothermodelsavailableintheModelsLibrary.
ModelsLibrary
Thelibrarycontainsfoursections:SampleModels,CurricularModels,CodeExamples,and
HubNetActivities.
SampleModels
TheSampleModelssectionisorganizedbysubjectareaandcurrentlycontainsmorethan
200models.Wearecontinuouslyworkingonaddingnewmodelstoit,socomevisitthis
sectionatalaterdatetoviewthenewadditionstothelibrary.
SomeofthefoldersinSampleModelshavefoldersinsidethemlabeled“(unverified)”.These
modelsarecompleteandfunctional,butarestillintheprocessofbeingreviewedforcontent,
accuracy,andqualityofcode.
CurricularModels
Thesearemodelsdesignedtobeusedinschoolsinthecontextofcurriculadevelopedbythe
CCLatNorthwesternUniversity.SomeofthesearemodelsarealsolistedunderSample
Models;othersareuniquetothissection.SeetheInfotabsofthemodelsformore
informationonthecurriculatheygowith.
CodeExamples
ThesearesimpledemonstrationsofparticularfeaturesofNetLogo.They’llbeusefultoyou
laterwhenyou’reextendingexistingmodelsorbuildingnewones.Forexample,ifyouwanted
toaddahistogramtoyourmodel,you’dlookat“HistogramExample”tofindouthow.
HubNetActivities
Thissectioncontainsparticipatorysimulationsforusewithgroups.Formoreinformation
aboutHubNet,seetheHubNetGuide.
What’sNext?
Ifyouwanttolearnhowtoexploremodelsatadeeperlevel,Tutorial#2:Commandswill
introduceyoutotheNetLogomodelinglanguage.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuild
newones.
Tutorial#2:Commands
NetLogo6.0.4UserManual
Sofaryou’vesuccessfullynavigatedyourwaythroughopeningandrunningmodels,pressing
buttons,changingslidersandswitches,andgatheringinformationfromamodelusingplots
andmonitors.
Inthissection,thefocuswillstarttoshiftfromobservingmodelstomanipulatingmodels.You
willstarttoseetheinnerworkingsofthemodelsandbeabletochangehowtheylook.
SampleModel:TrafficBasic
OpentheModelsLibrary(fromtheFilemenu).
OpenTrafficBasic,foundinthe“SocialScience”section.
Runthemodelforawhiletogetafeelforit.
ConsulttheInfotabforanyquestionsyoumayhave.
Inthismodel,youwillnoticeoneredcarinastreamofbluecars.Thestreamofcarsareall
movinginthesamedirection.Everysooftenthey“pileup”andstopmoving.Thisismodeling
howtrafficjamscanformwithoutaspecificcauselikeanaccident.
Youmayalterthesettingsandobserveafewrunstogetafullerunderstandingofthemodel.
AsyouareusingtheTrafficBasicmodel,haveyounoticedanyadditions
youwouldliketomaketothemodel?
LookingattheTrafficBasicmodel,youmaynoticetheenvironmentisfairlysimple;ablack
backgroundwithawhitestreetandnumberofbluecarsandoneredcar.Changesthatcould
bemadetothemodelinclude:changingthecolorandshapeofthecars,addingahouseor
streetlight,creatingastoplight,orevencreatinganotherlaneoftraffic.Someofthese
suggestedchangesarevisual,toenhancethelookofthemodel,whileothersaremore
behavioral.Wewillbefocusingmoreonthesimplerorcosmeticchangesthroughoutmostof
thistutorial.(Tutorial#3willgointogreaterdetailaboutbehavioralchanges,whichrequire
changingtheCodetab.)
TomakethesesimplechangeswewillbeusingtheCommandCenter.
CommandCenter
TheCommandCenterisfoundintheInterfacetab.Itallowsyoutoentercommandsor
directionstoamodel.CommandsareinstructionsyoucangivetoNetLogo’sagents:turtles,
patches,links,andtheobserver.
InTrafficBasic:
Pressthe“setup”button.
LocatetheCommandCenter.
ClickthemouseinthewhiteboxatthebottomoftheCommandCenter.
Typethetextshownhere:
Pressthereturnkey.
WhathappenedtotheView?
YoumayhavenoticedthebackgroundoftheViewhasturnedallyellowandthe
streethasdisappeared.
Whydidn’tthecarsturnyellowtoo?
Lookingbackatthecommandthatwaswritten,weaskedonlythepatchesto
changetheircolor.Inthismodel,thecarsarerepresentedbyadifferentkindof
agent,called“turtles”.Therefore,thecarsdidnotreceivetheseinstructionsandthus
didnotchange.
WhathappenedintheCommandCenter?
Youmayhavenoticedthatthecommandyoujusttypedisnowdisplayedinthe
CommandCenterasshownbelow:
TypeinthebottomoftheCommandCenterthetextshownbelow:
Wastheresultwhatyouexpected?
Theviewshouldhaveayellowbackgroundwithalineofbrowncarsinthemiddle:
TheNetLogoworldisatwodimensionalworldthatismadeupofturtles,patches,links,and
anobserver.Thepatchesarethegroundoverwhichtheturtlesmove.Linksareconnections
betweenturtles.Andtheobserverisabeingthatoverseeseverythingthatisgoingon.(For
morespecifics,refertotheNetLogoProgrammingGuide.)
IntheCommandCenteryoucangivecommandstoanyofthesetypesofagents.Youchoose
whichtypetotalktobyusingthepopupmenulocatedinthebottomleftcorner.Youcanalso
usethetabkeyonyourkeyboardtocyclethroughthedifferenttypes.
IntheCommandCenter,clickonthe“observer>”inthebottomleftcorner:
Choose“turtles”fromthepopupmenu.
Typeset color pinkandpressreturn.
Pressthetabkeyuntilyousee“patches>”inthebottomleftcorner.
Typeset pcolor whiteandpressreturn.
WhatdoestheViewlooklikenow?
Doyounoticeanydifferencesbetweenthesetwocommandsandthe
observercommandsfromearlier?
Theobserveroverseestheworldandthereforecangiveacommandtothepatchesorturtles
usingask.Likeinthefirstexample(observer>ask patches [set pcolor yellow] ),the
observerhastoaskthepatchestosettheirpcolortoyellow.Butwhenacommandisdirectly
giventoagroupofagentslikeinthesecondexample(patches>set pcolor white),youonly
havetogivethecommanditself.
Press“setup”.
Whathappened?
WhydidtheViewrevertbacktotheoldversion,withtheblackbackgroundandwhiteroad?
Uponpressingthe“setup”button,themodelwillreconfigureitselfbacktothesettingsoutlined
intheCodetab.TheCommandCenterdoesn’tpermanentlychangethemodel.Itallowsyou
tomanipulatetheNetLogoworlddirectlytofurtheranswerthose“Whatif”questionsthatpop
upasyouareinvestigatingthemodels.(TheCodetabisexplainedinthenexttutorial,andin
theProgrammingGuide.)
NowthatwehavefamiliarizedourselveswiththeCommandCenter,let’slookatsomemore
detailsabouthowcolorsworkinNetLogo.
Workingwithcolors
Youmayhavenoticedintheprevioussectionthatweusedtwodifferentwordsforchanging
color:colorandpcolor.
Whatisthedifferencebetweencolorandpcolor?
Choose“turtles”fromthepopupmenuintheCommandCenter(orusethetab
key).
Typeset color blueandpressreturn.
Whathappenedtothecars?
Thinkaboutwhatyoudidtomakethecarsturnblue,andtrytomakethepatches
turnred.
Ifyoutrytoaskthepatchestoset color red,anerrormessageoccurs:
Typeset pcolor redinsteadandpressreturn.
Wecallcolorandpcolor“variables”.Somecommandsandvariablesarespecifictoturtles
andsomearespecifictopatches.Forexample,thecolorvariableisaturtlevariable,while
thepcolorvariableisapatchvariable.
Goaheadandpracticealteringthecolorsoftheturtlesandpatchesusingthesetcommand
andthesetwovariables.
Tobeabletomakemorechangestothecolorsofturtlesandpatches,orshallwesaycars
andbackgrounds,weneedtogainalittleinsightintohowNetLogodealswithcolors.
InNetLogo,colorshaveanumericvalue.Inalloftheexerciseswehavebeenusingthename
ofthecolor.ThisisbecauseNetLogorecognizes16differentcolornames.Thisdoesnot
meanthatNetLogoonlyrecognizes16colors.Therearemanyshadesinbetweenthese
colorsthatcanbeusedtoo.Here’sachartthatshowsthewholeNetLogocolorspace:
Togetanintermediateshade,yourefertoitbyanumberinstead,orbyaddingorsubtracting
anumberfromaname.Forexample,whenyoutypeset color red,thisdoesthesamething
asifyouhadtypedset color 15.Andyoucangetalighterordarkerversionofthesame
colorbyusinganumberthatisalittlelargeroralittlesmaller,asfollows.
Choose“patches”fromthepopupmenuintheCommandCenter(orusethe
tabkey).
Typeset pcolor red - 2(Thespacingaroundthe“-”isimportant.)
Bysubtractingfromred,youmakeitdarker.
Typeset pcolor red + 2
Byaddingtored,youmakeitlighter.
Youcanusethistechniqueonanyofthecolorslistedinthechart.
AgentMonitorsandAgentCommanders
Inthepreviousactivity,weusedthesetcommandtochangethecolorsofallthecars.Butif
yourecall,theoriginalmodelcontainedoneredcaramongstagroupofbluecars.Let’slook
athowtochangeonlyonecar’scolor.
Press“setup”togettheredcartoreappear.
Right-clickontheredcar.
Ifthereisanotherturtleclosetotheredturtleyou’llseemorethanoneturtle
listedatthebottomofthemenu.Moveyourmouseovertheturtleselections,
noticewhenyourmousehighlightsaturtlemenuitemthatturtleishighlighted
intheview.Select“inspectturtle”fromthesub-menufortheredturtle.
Aturtlemonitorforthatcarwillappear:
Themini-viewatthetopoftheagentmonitorwillalwaysstaycenteredonthisagent.Youcan
zoomtheviewinandoutusingthesliderbelowtheviewandyoucanwatchthisturtleinthe
mainviewbypressingthe“watch-me”button.
Takingacloserlookatthisturtlemonitor,wecanseeallofthevariablesthatbelongtothe
redcar.Avariableisalocationthatholdsavalue.
Let’stakeacloserlookattheturtlemonitor:
Whatisthisturtle’swhonumber?
Whatcoloristhisturtle?
Whatshapeisthisturtle?
Thisturtlemonitorisshowingaturtlewhothathasawhonumberof0,acolorof15(red–
seechartabove),andtheshapeofacar.
Therearetwootherwaystoopenaturtlemonitorbesidesright-clicking.Onewayisto
choose“TurtleMonitor”fromtheToolsmenu,thentypethewhonumberoftheturtleyou
wanttoinspectintothe“who”fieldandpressreturn.Theotherwayistotypeinspect turtle
0(orotherwhonumber)intotheCommandCenter.
Youcloseaturtlemonitorbyclickingthecloseboxintheupperlefthandcorner(Mac)or
upperrighthandcorner(otheroperatingsystems).
NowthatweknowmoreaboutAgentMonitors,wehavethreewaystochangeanindividual
turtle’scolor.
OnewayistousetheboxcalledanAgentCommanderfoundatthebottomofanAgent
Monitor.Youtypecommandshere,justlikeintheCommandCenter,butthecommandsyou
typehereareonlydonebythisparticularturtle.
IntheAgentCommanderoftheTurtleMonitorforturtle0,typeset color
pink.
WhathappensintheView?
DidanythingchangeintheTurtleMonitor?
Asecondwaytochangeoneturtle’scoloristogodirectlytothecolorvariableintheTurtle
Monitorandchangethevalue.
Selectthetexttotherightof“color”intheTurtleMonitor.
Typeinanewcolorsuchasgreen + 2.
Whathappened?
Thethirdwaytochangeanindividualturtle’sorpatch’scoloristousetheobserver.Since,
theobserveroverseestheNetLogoworld,itcangivecommandsthataffectindividualturtles,
aswellasgroupsofturtles.
IntheCommandCenter,select“observer”fromthepopupmenu(orusethe
tabkey).
Typeask turtle 0 [set color blue]andpressreturn.
Whathappens?
JustasthereareTurtleMonitors,therearealsoPatchMonitors,whichworkvery
similarly.
Canyoumakeapatchmonitoranduseittochangethecolorofasingle
patch?
Ifyoutrytohavetheobserverask patch 0 [set pcolor blue],you’llgetanerrormessage:
Toaskanindividualturtletodosomething,weuseitswhonumber.Butpatchesdon’thave
whonumbers,thereforeweneedtorefertothemsomeotherway.
Remember,patchesarearrangedonacoordinatesystem.Twonumbersareneededtoplota
pointonagraph:anx-axisvalueanday-axisvalue.Patchlocationsaredesignatedinthe
samewayasplottingapoint.
Openapatchmonitorforanypatch.
Themonitorshowsthatforthepatchinthepicture,itspxcorvariableis-19andits
pycorvariableis0.Ifwegobacktotheanalogyofthecoordinateplaneandwanted
toplotthispoint,thepointwouldbefoundonthexaxisleftoftheorigin,wherex=-
19andy=0.
Totellthisparticularpatchtochangecolor:
Inthebottomofthepatchmonitor,enterset pcolor blueandpressreturn.
Typingacommandinaturtleorpatchmonitoraddressesonlythatturtleorpatch.
YoucanalsotalktoasinglepatchfromtheCommandCenter:
IntheCommandCenter,enterask patch -19 0 [set pcolor green] and
pressreturn.
What’sNext?
Atthispoint,youmaywanttotakesometimetotryoutthetechniquesyou’velearnedon
someoftheothermodelsintheModelsLibrary.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuild
yourownmodels.
Tutorial#3:Procedures
NetLogo6.0.4UserManual
Thistutorialleadsyouthroughtheprocessofbuildingacompletemodel,builtupinstages,witheverystepexplainedalongtheway.
Agentsandprocedures
InTutorial#2,youlearnedhowtousethecommandcenterandagentmonitorstoinspectandmodifyagentsandmakethemdothings.
Nowyou’rereadytolearnabouttherealheartofaNetLogomodel:theCodetab.
You’veseenthatagentsinNetLogoaredividedintopatches,turtles,links,andtheobserver.Patchesarestationaryandarrangedina
grid.Turtlesmoveoverthatgrid.Linksconnecttwoturtles.Theobserveroverseeseverythingthat’sgoingonanddoeswhateverthe
turtles,patchesandlinkscan’tdoforthemselves.
AllfourtypesofagentscanrunNetLogocommands.Allfourcanalsorun“procedures”.AprocedurecombinesaseriesofNetLogo
commandsintoasinglenewcommandthatyoudefine.
Youwillnowlearntowriteproceduresthatmaketurtlesmove,eat,reproduce,anddie.Youwillalsolearnhowtomakemonitors,
sliders,andplots.Themodelwe’llbuildisasimpleecosystemmodelnotunlikeWolfSheepPredationfromTutorial#1.
Makingthesetupbutton
Tostartanewmodel,select“New”fromtheFilemenu.Thenbeginbycreatingasetupbutton:
Clickthe“Add”iconinthetoolbaratthetopoftheInterfacetab.
OnthemenunexttoAdd,selectButton(ifitisn’talreadyselected).
ClickwhereveryouwantthebuttontoappearintheemptywhiteareaoftheInterfacetab.
Adialogboxforeditingthebuttonopens.Typesetupintheboxlabeled“Commands”.
PresstheOKbuttonwhenyou’redone;thedialogboxcloses.
Nowyouhaveasetupbutton.Pressingthebuttonrunsaprocedurecalled“setup”.AprocedureisasequenceofNetLogocommands
thatweassignanewname.We’lldefinethatproceduresoon,butwehaven’tyet.Thebuttonreferstoaprocedurethatdoesn’texist,so
thebuttonturnsred:
Ifyouwanttoseetheactualerrormessage,clickthebutton.
Nowwe’llcreatethe“setup”procedure,sotheerrormessagewillgoaway:
SwitchtotheCodetab.
Typethefollowing:
to setup
clear-all
create-turtles 100 [ setxy random-xcor random-ycor ]
reset-ticks
end
Whenyou’redone,theCodetablookslikethis:
Notethatsomelinesareindented.Mostpeoplefindithelpfultoindenttheircode.Itisn’tmandatory,butitmakesthecodeeasiertoread
andchange.
Yourprocedurebeginswithtoandendswithend.Everyprocedurebeginsandendswiththesewords.
Let’slookatwhatyoutypedinandseewhateachlineofyourproceduredoes:
to setupbeginsdefiningaprocedurenamed“setup”.
clear-allresetstheworldtoaninitial,emptystate.Allthepatchesturnblackandanyturtlesyoumighthavecreateddisappear.
Basically,itwipestheslatecleanforanewmodelrun.
create-turtles 100creates100turtles.Theystartoutstandingattheorigin,thatis,thecenterofpatch0,0.
Aftercreate-turtleswecanputcommandsforthenewturtlestorun,enclosedbysquarebrackets.
setxy random-xcor random-ycorisacommandusing“reporters”.Areporter,asopposedtoacommand,reportsaresult.Firsteach
turtlerunsthereporterrandom-xcorwhichwillreportarandomnumberfromtheallowablerangeofturtlecoordinatesalongtheX
axis.Theneachturtlerunsthereporterrandom-ycor,samefortheYaxis.Finallyeachturtlerunsthesetxycommandwiththose
twonumbersasinputs.Thatmakestheturtlemovetothepointwiththosecoordinates.
reset-ticksstartsthetickcounter,nowthatsetupisotherwisecomplete.
endcompletesthedefinitionofthe“setup”procedure.
Whenyou’redonetyping,switchtotheInterfacetabandpressthesetupbuttonyoumadebefore.Youwillseetheturtlesscattered
aroundtheworld:
Presssetupacouplemoretimes,andseehowthearrangementofturtlesisdifferenteachtime.Notethatsometurtlesmayberighton
topofeachother.
Thinkabitaboutwhatyouneededtodotomakethishappen.Youneededtomakeabuttonintheinterfaceandmakeaprocedurethat
thebuttonuses.Thebuttononlyworkedonceyoucompletedbothoftheseseparatesteps.Intheremainderofthistutorial,youwill
oftenhavetocompletetwoormoresimilarstepstoaddanotherfeaturetothemodel.Ifsomethingdoesn’tappeartoworkafteryou
completedwhatyouthoughtisthefinalstepforthatnewfeature,continuetoreadaheadtoseeifthereisstillmoretodo.Afterreading
aheadforacoupleofparagraphs,youshouldthengobackoverthedirectionstoseeifthereisanystepyoumighthavemissed.
Switchingtotick-basedviewupdates
Nowthatwe’reusingthetickcounter(withreset-ticks),weshouldtellNetLogothatitonlyneedstoupdatetheviewoncepertick,
insteadofcontinuouslyupdatingit.
Findtheviewupdatesmenu.It’sabovetheviewandbydefaultsays“continuous”.
Choose“onticks”instead.
Thismakesyourmodelrunfasterandensuresaconsistentappearance(sincetheupdateswillhappenatconsistenttimes).Seethe
ProgrammingGuideforafullerdiscussionofviewupdates.
Makingthegobutton
Nowmakeabuttoncalled“go”.Followthesamestepsyouusedtomakethesetupbutton,except:
ForCommandsentergoinsteadofsetup.
Checkthe“Forever”checkboxintheeditdialog.
Checkthe“Disableuntilticksstart”checkboxtoo.
The“Forever”checkboxmakesthebuttonstaydownoncepressed,soitscommandsrunoverandoveragain,notjustonce.
The“Disableuntilticksstart”preventsyoufrompressinggobeforesetup.
ThenaddagoproceduretotheCodetab:
to go
move-turtles
tick
end
tickisaprimitivethatadvancesthetickcounterbyonetick.
Butwhatismove-turtles?Isitaprimitive(inotherwords,built-intoNetLogo)?No,it’sanotherprocedurethatyou’reabouttoadd.So
far,youhaveintroducedtwoproceduresthatyouaddedyourself:setupandgo.
Addthemove-turtlesprocedureafterthegoprocedure:
to go
move-turtles
tick
end
to move-turtles
ask turtles [
right random 360
forward 1
]
end
Notetherearenospacesaroundthehypheninmove-turtles.InTutorial#2weusedred - 2,withspaces,inordertosubtracttwo
numbers,butherewewantmove-turtles,withoutspaces.The“-”combines“move”and“turtles”intoasinglename.
Hereiswhateachcommandinthemove-turtlesproceduredoes:
ask turtles [ ... ]saysthateachturtleshouldrunthecommandsinthebrackets.
right random 360isanothercommandthatusesareporter.First,eachturtlepicksarandomwholenumberbetween0and359.
(randomdoesn’tincludethenumberyougiveitasapossibleresult.)Thentheturtleturnsrightthisnumberofdegrees.
forward 1makestheturtlemoveforwardonestep.
Whycouldn’twehavejustwrittenallofthesecommandsingoinsteadofinaseparateprocedure?Wecouldhave,butduringthe
courseofbuildingyourproject,it’slikelythatyou’lladdmanyotherparts.We’dliketokeepgoassimpleaspossible,sothatitiseasyto
understand.Eventually,itwillincludemanyotherthingsyouwanttohavehappenasthemodelruns,suchascalculatingsomethingor
plottingtheresults.Eachofthesethingstodowillhaveitsownprocedureandeachprocedurewillhaveitsownuniquename.
The‘go’buttonyoumadeintheInterfacetabisaforeverbutton,meaningthatitwillcontinuallyrunitscommandsuntilyoushutitoff(by
clickingonitagain).Afteryouhavepressed‘setup’once,tocreatetheturtles,pressthe‘go’button.Watchwhathappens.Turnitoff,
andyou’llseethatalltheturtlesstopintheirtracks.
Notethatifaturtlemovesofftheedgeoftheworld,it“wraps”,thatis,itappearsontheotherside.(Thisisthedefaultbehavior.Itcanbe
changed;seetheTopologysectionoftheProgrammingGuideformoreinformation.)
Experimentingwithcommands
Wesuggestyoustartexperimentingwithotherturtlecommands.
TypecommandsintotheCommandCenter(liketurtles> set color red),oraddcommandstosetup,go,ormove-turtles.
NotethatwhenyouentercommandsintheCommandCenter,youmustchooseturtles>,patches>,links>,orobserver>inthepopup
menuontheleft,dependingonwhichagentsaregoingtorunthecommands.It’sjustlikeusingask turtlesorask patches,butsaves
typing.Youcanalsousethetabkeytoswitchagenttypes,whichyoumightfindmoreconvenientthanusingthemenu.
Youmighttrytypingturtles>pen-downintotheCommandCenterandthenpressingthegobutton.
Also,insidethemove-turtlesprocedureyoucantrychangingright random 360toright random 45.
Playaround.It’seasyandtheresultsareimmediateandvisible–oneofNetLogo’smanystrengths.
Whenyoufeelyou’vedoneenoughexperimentingfornow,you’rereadytocontinueimprovingthemodelyouarebuilding.
Patchesandvariables
Nowwe’vegot100turtlesaimlesslymovingaround,completelyunawareofanythingelsearoundthem.Let’smakethingsalittlemore
interestingbygivingtheseturtlesanicebackgroundagainstwhichtomove.
Gobacktothesetupprocedure.Wecanrewriteitasfollows:
to setup
clear-all
setup-patches
setup-turtles
reset-ticks
end
Thenewdefinitionofsetupreferstotwonewprocedures.Todefinesetup-patches,addthis:
to setup-patches
ask patches [ set pcolor green ]
end
Thesetup-patchesproceduresetsthecolorofeverypatchtogreentostartwith.(Aturtle’scolorvariableiscolor;a
patch’sispcolor.)
Theonlypartremaininginournew‘setup’thatisstillundefinedissetup-turtles.
Addthisproceduretoo:
to setup-turtles
create-turtles 100
ask turtles [ setxy random-xcor random-ycor ]
end
Didyounoticethatthenewsetup-turtlesprocedurehasmostofthesamecommandsastheoldsetupprocedure?
SwitchbacktotheInterfacetab.
Pressthesetupbutton.
Voila!AlushNetLogolandscapecompletewithturtlesandgreenpatchesappears:
Afterseeingthenewsetupprocedureworkafewtimes,youmayfindithelpfultoreadthroughtheproceduredefinitionsagain.
Turtlevariables
Sowehavesometurtlesrunningaroundonalandscape,buttheyaren’tdoinganythingwithit.Let’saddsomeinteractionbetweenthe
turtlesandthepatches.
We’llmaketheturtleseat“grass”(thegreenpatches),reproduce,anddie.Thegrasswillgraduallygrowbackafteritiseaten.
We’llneedawayofcontrollingwhenaturtlereproducesanddies.We’lldeterminethatbykeepingtrackofhowmuch“energy”each
turtlehas.Todothatweneedtoaddanewturtlevariable.
You’vealreadyseenbuilt-inturtlevariableslikecolor.Tomakeanewturtlevariable,weaddaturtles-owndeclarationatthetopofthe
Codetab,beforealltheprocedures.Callitenergy:
turtles-own [energy]
to go
move-turtles
eat-grass
tick
end
Let’susethisnewlydefinedvariable(energy)toallowtheturtlestoeat.
SwitchtotheCodetab.
Rewritethegoprocedureasfollows:
to go
move-turtles
eat-grass
tick
end
Addaneweat-grassprocedure:
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
set energy energy + 10
]
]
end
Weareusingtheifcommandforthefirsttime.Lookatthecodecarefully.Eachturtle,whenitrunsthesecommands,comparesthe
valueofthepatchcoloritison(pcolor)tothevalueforgreen.(Aturtlehasdirectaccesstothevariablesofthepatchitisstandingon.)If
thepatchcolorisgreen,thecomparisonreportstrue,andonlythenwilltheturtlerunthecommandsinsidethebrackets(otherwiseit
skipsthem).Thecommandsmaketheturtlechangethepatchcolortoblackandincreaseitsownenergyby10.Thepatchturnsblack
tosignifythatthegrassatthatspothasbeeneaten.Andtheturtleisgivenmoreenergy,fromhavingjusteaten.
Next,let’smakethemovementofturtlesuseupsomeoftheturtle’senergy.
Rewritemove-turtlesasfollows:
to move-turtles
ask turtles [
right random 360
forward 1
set energy energy - 1
]
end
Aseachturtlewanders,itwillloseoneunitofenergyateachstep.
SwitchtotheInterfacetabnowandpressthesetupbuttonandthegobutton.
You’llseethepatchesturnblackasturtlestraveloverthem.
Monitors
NextyouwillcreatetwomonitorsintheInterfacetabwiththetoolbar.(Youmakethemjustlikebuttonsandsliders,usingtheAddicon
onthetoolbar.)Let’smakethefirstmonitornow.
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotin
theInterface.
Adialogboxwillappear.
Inthedialogtype:count turtles(seeimagebelow).
PresstheOKbuttontoclosethedialog.
turtlesisan“agentset”,thesetofallturtles.counttellsushowmanyagentsareinthatset.
Let’smakethesecondmonitornow:
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotin
theInterface.
Adialogboxwillappear.
IntheReportersectionofthedialogboxtype:count patches with [pcolor = green] (seeimagebelow).
IntheDisplaynamesectionofthedialogboxtype:green patches
PresstheOKbuttontoclosethedialogbox.
Herewe’reusingcountagaintoseehowmanyagentsareinanagentset.patchesisthesetofallthepatches,butwedon’tjustwantto
knowhowmanypatchestherearetotal,wewanttoknowhowmanyofthemaregreen.That’swhatwithdoes;itmakesasmaller
agentsetofjustthoseagentsforwhomtheconditioninthebracketsistrue.Theconditionispcolor = green,sothatgivesusjustthe
greenpatches.
Nowwehavetwomonitorsthatwillreporthowmanyturtlesandgreenpatcheswehave,tohelpustrackwhat’sgoingoninourmodel.
Asthemodelruns,thenumbersinthemonitorswillautomaticallychange.
Usethesetupandgobuttonsandwatchthenumbersinthemonitorschange.
Switchesandlabels
Theturtlesaren’tjustturningthepatchesblack.They’realsogainingandlosingenergy.Asthemodelruns,tryusingaturtlemonitorto
watchoneturtle’senergygoupanddown.
Itwouldbenicerifwecouldseeeveryturtle’senergyallthetime.Wewillnowdoexactlythat,andaddaswitchsowecanturntheextra
visualinformationonandoff.
ClickontheAddicononthetoolbar(intheInterfacetab).
SelectSwitchfromthemenunexttoAdd.
Clickonanopenspotintheinterface.
Adialogwillappear.
IntotheGlobalvariablefield,typeshow-energy?Don’tforgettoincludethequestionmarkinthename.(Seeimage
below.)
Nowgobacktothe‘go’procedureusingtheCodetabwiththeToolbar.
Rewritetheeat-grassprocedureasfollows:
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
set energy energy + 10
]
ifelse show-energy?
[ set label energy ]
[ set label "" ]
]
end
Theeat-grassprocedureintroducestheifelsecommand.Lookatthecodecarefully.Eachturtle,whenitrunsthesenewcommands,
checksthevalueofshow-energy?(determinedbytheswitch).Iftheswitchison,comparisonistrueandtheturtlewillrunthecommands
insidethefirstsetofbrackets.Inthiscase,itassignsthevaluefortheenergytothelabeloftheturtle.Ifthecomparisonisfalse(the
switchisoff)thentheturtlerunsthecommandsinsidethesecondsetofbrackets.Inthiscase,itremovesthetextlabels(bysettingthe
labeloftheturtletobenothing).
(InNetLogo,apieceoftextiscalleda“string”,shortforstringofcharacters.Astringisasequenceoflettersorothercharacters,written
betweendoublequotes.Herewehavetwodoublequotesrightnexttoeachother,withnothinginbetweenthem.That’sanemptystring.
Ifaturtle’slabelisanemptystring,notextisattachedtotheturtle.)
TestthisintheInterfacetab,byrunningthemodel(usingthesetupandgobuttons)switchingtheshow-energy?
switchbackandforth.
Whentheswitchison,you’llseetheenergyofeachturtlegoupeachtimeiteatsgrass.You’llalsoseeitsenergygoingdownwhenever
itmoves.
Moreprocedures
Nowourturtlesareeating.Let’smakethemreproduceanddie,too.Andlet’smakethegrassgrowback.We’lladdallthreeoftheseof
thesebehaviorsnow,bymakingthreeseparateprocedures,oneforeachbehavior.
GototheCodetab.
Rewritethegoprocedureasfollows:
to go
move-turtles
eat-grass
reproduce
check-death
regrow-grass
tick
end
Addtheproceduresforreproduce,check-death,andregrow-grassasshownbelow:
to reproduce
ask turtles [
if energy > 50 [
set energy energy - 50
hatch 1 [ set energy 50 ]
]
]
end
to check-death
ask turtles [
if energy <= 0 [ die ]
]
end
to regrow-grass
ask patches [
if random 100 < 3 [ set pcolor green ]
]
end
Eachoftheseproceduresusestheifcommand.Eachturtle,whenitrunscheck-deathitwillchecktoseeifitsenergyislessorequalto
0.Ifthisistrue,thentheturtleistoldtodie(dieisaNetLogoprimitive).
Wheneachturtlerunsreproduce,itchecksthevalueoftheturtle’senergyvariable.Ifitisgreaterthan50,thentheturtlerunsthe
commandsinsidethefirstsetofbrackets.Inthiscase,itdecreasestheturtle’senergyby50,then‘hatches’anewturtlewithanenergy
of50.ThehatchcommandisaNetLogoprimitivewhichlookslikethis:hatchnumber[commands].Thisturtlecreatesnumbernew
turtles,eachidenticaltoitsparent,andasksthenewturtle(s)thathavebeenhatchedtoruncommands.Youcanusethecommandsto
givethenewturtlesdifferentcolors,headings,orwhatever.Inourcasewerunonecommand.Wesettheenergyforthenewlyhatched
turtletobe50.
Wheneachpatchrunsregrow-grassitwillchecktoseeifarandomintegerfrom0to99islessthan3.Ifso,thepatchcolorissetto
green.Thiswillhappen3%ofthetime(onaverage)foreachpatch,sincetherearethreenumbers(0,1,and2)outof100possiblethat
arelessthan3.
SwitchtotheInterfacetabnowandpressthesetupandgobuttons.
Youshouldseesomeinterestingbehaviorinyourmodelnow.Someturtlesdieoff,somenewturtlesarecreated(hatched),andsome
grassgrowsback.Thisisexactlywhatwesetouttodo.
Ifyoucontinuetowatchyourmonitorsinyourmodel,youwillseethatthecountturtlesandgreenpatchesmonitorsbothfluctuate.Is
thispatternoffluctuationpredictable?Istherearelationshipbetweenthevariables?
It’dbeniceifwehadaeasierwaytotrackthechangesinthemodelbehaviorovertime.NetLogoallowsustoplotdataaswegoalong.
Thatwillbeournextstep.
Plotting
Tomakeplottingwork,we’llneedtocreateaplotintheInterfacetabandputsomecommandsinsideit.
Thecommandsweputintheplotswillrunautomaticallywhenoursetupprocedurecallsreset-ticksandwhenourgoprocedurecalls
tick.
CreateaplotbyclickingtheAddicononthetoolbar,selectingPlotnexttoit,andclickingonanopenspotinthe
Interface.
SetitsNameto“Totals”(seeimagebelow)
SettheXaxislabelto“time”
SettheYaxislabelto“totals”
Changethenameofthe“default”pento“turtles”.
Enterplot count turtlesunderPenUpdateCommands.
Pressthe“AddPen”button.
Changethenameofthenewpento“grass”.
Enterplot count patches with [pcolor = green] underPenUpdateCommands.
Whenyou’redone,thedialogshouldlooklikethis:
PressOKinthePlotdialogtofinishediting.
NotethatwhenyoucreatetheplotyoucanalsosettheminimumandmaximumvaluesontheXandYaxes.You’llwanttoleavethe
“AutoScale”checkboxchecked,sothatifanythingyouplotexceedstheminimumandmaximumvaluesfortheaxes,theaxeswill
automaticallygrowsoyoucanseeallthedata.
Notethatweusedtheplotcommandtoaddthenextpointtoaplot.Thiscommandmovesthecurrentplotpentothepointthathasan
Xcoordinateequalto1greaterthanthepreviouslyplottedXcoordinateandaYcoordinateequaltothevaluegivenintheplot
command(inthefirstcase,thenumberofturtles,andinthesecondcase,thenumberofgreenpatches).Asthepensmovetheyeach
drawaline.
Setupandrunthemodelagain.
Youcannowwatchtheplotbeingdrawnasthemodelisrunning.Yourplotshouldhavethegeneralshapeoftheonebelow,though
yourplotmightnotlookexactlythesame.
Rememberthatweleft“AutoScale?”on.Thisallowstheplottoreadjustitselfwhenitrunsoutofroom.
Ifyouforgetwhichpeniswhich,youcanedittheplotandcheckthe“Showlegend?”checkbox.
Youmighttryrunningthemodelseveraltimestoseewhataspectsoftheplotarethesameandwhicharedifferentfromruntorun.
Tickcounter
Tomakecomparisonsbetweenplotsfromonemodelrunandanother,itisoftenusefultodothecomparisonforthesamelengthof
modelrun.Learninghowtostoporstartanactionataspecifictimecanhelpmakethishappenbystoppingthemodelatthesamepoint
eachmodelrun.Keepingtrackofhowmanytimesthegoprocedureisrunisausefulwaytocuetheseactions.That’swhatthetick
counterdoes.
You’realreadyusingthetickcounterinyourmodel,withthereset-ticksandtickcommands,whichalsotriggerplotting.
Youcanalsousethetickcounterforotherthings,suchastosetalimitonthetotallengthofarun.
Changethegoprocedure:
to go
if ticks >= 500 [ stop ]
move-turtles
eat-grass
check-death
reproduce
regrow-grass
tick
end
Nowsetupandrunthemodel.
Thegraphandmodelwon’tkeeprunningforever.TheyshouldstopautomaticallywhenthetickcounterintheInterfacetab’stoolbar
reaches500.
Thetickcommandadvancesthetickcounterby1.ticksisareporterwhichreportsthecurrentvalueofthetickcounter.reset-ticks,in
yoursetupprocedure,takescareofrestartingthetickcounterat0whenanewrunissetupandreadytobegin.
Somemoredetails
First,insteadofalwaysusing100turtles,youcanhaveavaryingnumberofturtles.
Createaslidernamed“number”:clicktheAddicononthetoolbar,selectSlidernexttoit,andclickonanopenspot
intheinterface.
Trychangingtheminimumandmaximumvaluesintheslider.
Theninsideofsetup-turtles,insteadofcreate-turtles 100youcantype:
to setup-turtles
create-turtles number [ setxy random-xcor random-ycor ]
end
Testthischangeandcomparehowhavingmoreorfewerturtlesinitiallyaffecttheplotsovertime.
Second,wouldn’titbenicetoadjusttheenergytheturtlesgainandloseastheyeatgrassandreproduce?
Makeaslidercalledenergy-from-grass.
Makeanotherslidercalledbirth-energy.
Then,insideofeat-grass,makethischange:
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
set energy (energy + energy-from-grass)
]
ifelse show-energy?
[ set label energy ]
[ set label "" ]
]
end
And,insideofreproduce,makethischange:
to reproduce
ask turtles [
if energy > birth-energy [
set energy energy - birth-energy
hatch 1 [ set energy birth-energy ]
]
]
end
Finally,whatotherslidercouldyouaddtovaryhowoftengrassgrowsback?Arethererulesyoucanaddtothemovementoftheturtles
ortothenewlyhatchedturtlesthathappenonlyatcertaintimes?Trywritingthem.
What’snext?
Sonowyouhaveasimplemodelofanecosystem.Patchesgrowgrass.Turtleswander,eatthegrass,reproduce,anddie.
Youhavecreatedaninterfacecontainingbuttons,sliders,switches,monitors,andaplot.You’veevenwrittenaseriesofproceduresto
givetheturtlessomethingtodo.
That’swherethistutorialleavesoff.
Ifyou’dliketolookatsomemoredocumentationaboutNetLogo,theInterfaceGuidesectionofthemanualwalksyouthroughevery
elementoftheNetLogointerfaceinorderandexplainsitsfunction.Foradetaileddescriptionandspecificsaboutwritingprocedures,
refertotheProgrammingGuide.AlloftheprimitivesarelistedanddescribedintheNetLogoDictionary.
Also,youcancontinueexperimentingwithandexpandingthismodelifyou’dlike,experimentingwithdifferentvariablesandbehaviors
fortheagents.
Alternatively,youmaywanttorevisitthefirstmodelinthetutorial,WolfSheepPredation.ThisisthemodelyouusedinTutorial #1.In
theWolfSheepPredationmodel,yousawsheepmovearound,consumeresourcesthatarereplenishedoccasionally(grass),
reproduceundercertainconditions,anddieiftheyranoutofresources.Butthatmodelhadanothertypeofcreaturemovingaround–
wolves.Theadditionofwolvesrequiressomeadditionalproceduresandsomenewprimitives.Wolvesandsheeparetwodifferent
“breeds”ofturtle.Toseehowtousebreeds,studyWolfSheepPredation.
Alternatively,youcanlookatothermodels(includingthemanymodelsintheCodeExamplessectionoftheModelsLibrary)orevengo
aheadandbuildyourownmodel.Youdon’tevenhavetomodelanything.Itcanbeinterestingjusttowatchpatchesandturtlesforming
patterns,totrytocreateagametoplay,orwhatever.
Hopefullyyouhavelearnedsomethings,bothintermsoftheNetLogolanguageandabouthowtogoaboutbuildingamodel.Theentire
setofproceduresthatwascreatedaboveisshownbelow.
Appendix:Completecode
ThecompletemodelisalsoavailableinNetLogo’sModelsLibrary,intheCodeExamplessection.It’scalled“Tutorial3”.
Noticethatthislistingisfullof“comments”,whichbeginwithsemicolons.Commentsletyoumixanexplanationthecoderightinwiththe
codeitself.Youmightusecommentstohelpothersunderstandyourmodel,oryoumightusethemasnotestoyourself.
IntheCodetab,commentsaregray,soyoureyescanpickthemouteasily.
turtles-own [energy] ;; for keeping track of when the turtle is ready
;; to reproduce and when it will die
to setup
clear-all
setup-patches
setup-turtles
reset-ticks
end
to setup-patches
ask patches [ set pcolor green ]
end
to setup-turtles
create-turtles number ;; uses the value of the number slider to create turtles
ask turtles [ setxy random-xcor random-ycor ]
end
to go
if ticks >= 500 [ stop ] ;; stop after 500 ticks
move-turtles
eat-grass
check-death
reproduce
regrow-grass
tick ;; increase the tick counter by 1 each time through
end
to move-turtles
ask turtles [
right random 360
forward 1
set energy energy - 1 ;; when the turtle moves it looses one unit of energy
]
end
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
;; the value of energy-from-grass slider is added to energy
set energy energy + energy-from-grass
]
ifelse show-energy?
[ set label energy ] ;; the label is set to be the value of the energy
[ set label "" ] ;; the label is set to an empty text value
]
end
to reproduce
ask turtles [
if energy > birth-energy [
set energy energy - birth-energy ;; take away birth-energy to give birth
hatch 1 [ set energy birth-energy ] ;; give this birth-energy to the offspring
]
]
end
to check-death
ask turtles [
if energy <= 0 [ die ] ;; removes the turtle if it has no energy left
]
end
to regrow-grass
ask patches [ ;; 3 out of 100 times, the patch color is set to green
if random 100 < 3 [ set pcolor green ]
]
end
InterfaceGuide
NetLogo6.0.4UserManual
ThissectionofthemanualexplainsthefunctionofeachelementinNetLogo’suserinterface.
InNetLogo,youhavethechoiceofviewingmodelsfoundintheModelsLibrary,addingto
existingmodels,orcreatingyourownmodels.TheNetLogointerfacewasdesignedtomeetall
theseneeds.
Theinterfacecanbedividedintotwomainparts:NetLogomenus,andthemainNetLogo
window.Themainwindowisdividedintotabs.
Menus
OnaMac,ifyouarerunningtheNetLogoapplication,themenubarislocatedatthetopofthe
screen.Onotherplatforms,themenubarisfoundatthetopoftheNetLogowindow.
Thefunctionsavailablefromthemenusinthemenubararelistedinthefollowingchart.
Chart:NetLogomenus
File
New Startsanewmodel.
Open… OpensanyNetLogomodelonyourcomputer.
ModelsLibrary Acollectionofdemonstrationmodels.
RecentFiles Re-opensanypreviouslymodelopenedwith"File->Open"
Save Savethecurrentmodel,orthecurrentlyselectedsourcefile.
SaveAs… Savethecurrentmodel,orthecurrentlyselectedsourcefile,usinga
differentname.
SaveAll Savethecurrentmodelandallopensourcefiles.Thisoptionisonly
availablewhenoneormoresourcefilesareopen.
Uploadto
Modeling
Commons
UploadsthemodeltoModelingCommons.SeeModelingCommons
SaveAs
NetLogo
Web…
Savesawebpage,inHTMLformat,containingNetLogowebrunning
yourmodel.
ExportWorld… Savesallvariables,thecurrentstateofallturtlesandpatches,the
drawing,theplots,theoutputareaandtherandomstateinformation
toafile.
ExportPlot… Savesthedatainaplottoafile.
ExportAll
Plots… Savesthedatainalltheplotstoafile.
ExportViewSaveapictureofthecurrentview(2Dor3D)toafile(inPNG
format).
Export
Interface… SaveapictureofthecurrentInterfacetab.(inPNGformat)
Export
Output…
Savethecontentsoftheoutputareaortheoutputsectionofthe
commandcentertoafile.
ExportCode… Savethemodel'scodetoanHTMLfile,preservingcolors.
ImportWorld… LoadafilethatwassavedbyExportWorld.
ImportPatch
ColorsLoadanimageintothepatches;seetheimport-pcolorscommand.
ImportPatch
ColorsRGB
LoadanimageintothepatchesusingRGBcolors;seetheimport-
pcolors-rgbcommand.
Import
Drawing… Loadanimageintothedrawing,seetheimport-drawingcommand.
ImportHubNet
Client
Interface…
LoadtheinterfacefromanothermodelintotheHubNetClientEditor.
Print… Sendsthecontentsofthecurrentlyshowingtabtoyourprinter.
Quit ExitsNetLogo.OnaMac,thisitemisontheNetLogomenuinstead.
Edit
Undo Undolasttexteditingactionyouperformed.
Redo Redolastundoactionyouperformed.
Cut Cutsoutorremovestheselectedtextandtemporarilysavesittothe
clipboard.
Copy Copiestheselectedtext.
Paste Placestheclipboardtextwherecursoriscurrentlylocated.
Delete Deletesselectedtext.
SelectAll Selectallthetextintheactivewindow.
Find… FindsawordorsequenceofcharacterswithintheInfoorCodetabs.
FindNext FindthenextoccurrenceofthewordorsequenceyoulastusedFind
with.
Comment/
Uncomment
UsedintheCodetabtoaddorremovesemicolonsfromcode
(semicolonsareusedinNetLogocodetoindicatecomments).
ShiftLeft/Shift
Right UsedintheCodetabtochangetheindentationlevelofcode.
Format UsedintheCodetabtocorrecttheindentationofthecurrently
selectedcode.
SnaptoGrid
AvailableonlyintheInterfaceTab.Whenenablednewwidgetsstay
ona5pixelgridsoitiseasiertolinethemup.(Note:thisfeatureis
disabledwhenzoomedinorout.)
Convertfrom
5.3.1to6.0
Availableonlyinan".nls"codetab.Treatsthecodeinthistabas
thoughitwerewrittenin5.3.1andconvertsittoruninNetLogo6.
Notethatthiswillnottakeintoaccountcodedefinedinthemain
codetab."Undo"doesn'ttakethisoperationintoaccount,soyou
won'twanttosaveunlessyou'resatisfiedwiththechanges.
Tools
Preferences
Opensthepreferencesdialog,whereyoucancustomizevarious
NetLogosettings.OnaMac,thisitemisontheNetLogomenu
instead.
Halt
Stopsallrunningcode,includingbuttonsandthecommandcenter.
(Warning:sincethecodeisinterruptedinthemiddleofwhateverit
wasdoing,youmaygetunexpectedresultsifyoutrytocontinue
runningthemodelwithoutfirstpressing"setup"tostartthemodel
runover.)
Globals
Monitor Displaysthevaluesofallglobalvariables.
TurtleMonitor
Displaysthevaluesofallofthevariablesinaparticularturtle.You
cancanalsoeditthevaluesoftheturtle'svariablesandissue
commandstotheturtle.(Youcanalsoopenaturtlemonitorviathe
View;seetheViewsectionbelow.)
PatchMonitor
Displaysthevaluesofallofthevariablesinaparticularpatch.You
cancanalsoeditthevaluesofthepatch'svariablesandissue
commandstothepatch.(Youcanalsoopenapatchmonitorviathe
View;seetheViewsectionbelow.)
LinkMonitor
Displaysthevaluesofallofthevariablesinaparticularlink.Youcan
canalsoeditthevaluesofthelink'svariablesandissuecommands
tothelink.(YoucanalsoopenalinkmonitorviatheView;seethe
Viewsectionbelow.)
CloseAll
AgentMonitors Closesallopenagentmonitorwindows.
CloseMonitors
forDead
Agents
Closesallopenagentmonitorwindowstargetingdeadagents.
Hide/Show
Command
Center
Makesthecommandcentervisibleorinvisible.(Notethatthe
commandcentercanalsobeshownorhidden,orresized,withthe
mouse.)ThisoptionisonlyavailablewhentheInterfaceTabis
active
3DView Opensthe3Dview.SeetheViewssectionoftheInterfaceTab
Guideformoreinformation.
Color
Swatches
OpenstheColorSwatches.SeetheColorSectionofthe
ProgrammingGuidefordetails.
TurtleShapes
Editor
Drawturtleshapes.SeetheShapesEditorGuideformore
information.
LinkShapes
Editor Drawlinkshapes.SeetheShapesEditorGuideformoreinformation.
BehaviorSpace Runsthemodeloverandoverwithdifferentsettings.Seethe
BehaviorSpaceGuideformoreinformation.
System
Dynamics
Modeler
OpenstheSystemDynamicsModeler.SeetheSystemDynamics
ModelerGuideformoredetails.
Preview
Commands
Editor
Allowsforeasyeditingofthecommandssequenceusedtocreate
previewimagesformodels.Givesawaytospecifywhatcodewillbe
used(orspecifythattheimageismanuallymade)andpreviewthe
resultingimage.
HubNetClient
Editor
OpenstheHubNetClientEditor.SeetheHubNetAuthoringGuide
formoredetails.
HubNet
ControlCenter
DisabledifnoHubNetactivityisopen.SeetheHubNetGuidefor
moreinformation.
Zoom
Larger Increasetheoverallscreensizeofthemodel.Usefulonlarge
monitorsorwhenusingaprojectorinfrontofagroup.
NormalSize Resetthescreensizeofthemodeltothenormalsize.
Smaller Decreasetheoverallscreensizeofthemodel.
Tabs
Thismenuofferskeyboardshortcutsforeachofthetabs.OnaMac,
it'sCommand1throughCommand3.OnWindows,it'sControl1
throughControl3.Additionalnumbersareusedfortabscontaining
".nls"files.
Help
LookUpIn
Dictionary
Opensabrowserwiththedictionaryentryfortheselectedcommand
orreporter.(YoumayalsousetheF1keyforthis.)
NetLogoUser
Manual Opensthismanualinawebbrowser.
NetLogo
Dictionary OpenstheNetLogoDictionaryinawebbrowser.
NetLogoUsers
Group OpenstheNetLogoUsersGroupsiteinawebbrowser.
Introductionto
Agent-Based
Modeling
OpenstheMITPresspagefor"IntroductiontoAgent-Based
Modeling"(byUriWilenskyandWilliamRand)inawebbrowser.
Donate OpenstheNetLogodonationpageinawebbrowser.
AboutNetLogo
6.0.4…
InformationonthecurrentNetLogoversionyouarerunning.Ona
Mac,thismenuitemisontheNetLogomenuinstead.
Tabs
AtthetopofNetLogo’smainwindowarethreetabslabeled“Interface”,“Info”and“Code”.Only
onetabatatimecanbevisible,butyoucanswitchbetweenthembyclickingonthetabsatthe
topofthewindow.
Rightbelowtherowoftabsisatoolbarcontainingarowofcontrols.Thecontrolsavailablevary
fromtabtotab.
InternationalUsage
Charactersets
NetLogoalwayssavesandloadsmodelsintheUTF-8characterencoding,whichincludesa
widerangeofinternationalcharacters.
IfyouareinalocaleotherthanU.S.English,letusknowifyouhaveanytroubleusingyourlocal
characterset.
TheTransitionGuidehasadviceonconvertingmodelscontaininginternationalcharactersfrom
earlierNetLogoversions.
Languages
MostofNetLogo’sGUI,andsomeofitserrormessages,arenow“internationalized”.This
meansthatitisnowpossibletodisplayNetLogoindifferentlanguages.
Wesay“possible”herebecausethecurrentreleaseofNetLogoonlysupportsEnglish,Spanish,
Chinese,Russian,andJapanese.
Theworkoninternationalizationisnotcomplete.Weareaskingforhelpfromtheuser
communityinhelpinguslocalizeitemssuchasthemenusanderrormessages.
Defaultlanguage
Bydefault,NetLogousesthesamelanguageyouroperatingsystemissetto,ifavailable.(If
unavailable,yougetEnglish.)
Youcanrecordapreferenceforadifferentlanguagebychangingthe“UserInterfaceLanguage”
optioninthepreferencesdialog.Onceanewlanguageischosenyouwillhavetorestart
NetLogo.
Supportfortranslators
WehopeNetLogowillbecomeavailableinmanydifferentlanguages.Ifyouwouldliketo
translateNetLogotoyourlanguage,seethiswikipageforinstructions.
InterfaceTabGuide
NetLogo6.0.4UserManual
TheInterfacetabiswhereyouwatchyourmodelrun.Italsohastoolsyoucanusetoinspectandalter
what’sgoingoninsidethemodel.
WhenyoufirstopenNetLogo,theInterfacetabisemptyexceptfortheview,wheretheturtlesand
patchesappear,andtheCommandCenter,whichallowsyoutoissueNetLogocommands.
Workingwithinterfaceelements
ThetoolbarontheInterfacetabcontainsbuttonsthatletyouedit,delete,andcreateitemsinthe
Interfacetabandamenuthatletsyouselectdifferentinterfaceitems(suchasbuttonsandsliders).
Thebuttonsinthetoolbararedescribedbelow.
Adding:Toaddaninterfaceelement,selecttheelementfromthedropdownmenu.NotethattheAdd
buttonstaysdown.Thenclickonthewhiteareabelowthetoolbar.(Ifthemenuisalreadyshowingthe
righttype,youcanjustpresstheAddbuttoninsteadofusingthemenuagain.)
Selecting:Toselectaninterfaceelement,dragarectanglearounditwithyourmouse.Agrayborder
withblackhandleswillappeararoundtheelementtoshowitisselected.
Selectingmultipleitems:Youcanselectmultipleinterfaceelementsatthesametimebyincluding
themintherectangleyoudrag.Ifmultipleelementsareselected,oneofthemisthe“key”item,which
meansthatifyouusethe“Edit”or“Delete”buttonsontheInterfaceToolbar,onlythekeyitemis
affected.Thekeyitem’sborderisdarkergray.
Unselecting:Tounselectallinterfaceelements,clickthemouseonthewhitebackgroundofthe
Interfacetab.Tounselectanindividualelement,right-clicktheelementandchoose“Unselect”fromthe
popupmenu.
Editing:Tochangethecharacteristicsofaninterfaceelement,selecttheelement,thenpressthe“Edit”
buttonontheInterfacetoolbar.Youmayalsodoubleclicktheelementonceitisselected.Athirdwayto
editanelementistoright-clickitandchoose“Edit”fromthepopupmenu.Ifyouusethislastmethod,itis
notnecessarytoselecttheelementfirst.
Moving:Selecttheinterfaceelement,thendragitwithyourmousetoitsnewlocation.Ifyouholddown
theshiftkeywhiledragging,theelementwillmoveonlystraightupanddownorstraightleftandright.
Resizing:Selecttheinterfaceelement,thendragtheblack“handles”intheselectionborder.
Deleting:Selecttheelementorelementsyouwanttodelete,thenpressthe“Delete”buttononthe
Interfacetoolbar.Youmayalsodeleteanelementbyright-clickingitandchoosing“Delete”fromthe
popupmenu.Ifyouusethislattermethod,itisnotnecessarytoselecttheelementfirst.
Tolearnmoreaboutthedifferentkindsofinterfaceelements,refertothechartbelow.
Chart:InterfaceToolbar
Icon&Name Description
Abuttoniseitheronceorforever.Whenyouclickonaoncebutton,itexecutesits
instructionsonce.Theforeverbuttonexecutestheinstructionsoverandover,until
youclickonthebuttonagaintostoptheaction.Ifyouhaveassignedanactionkey
tothebutton,pressingthecorrespondingkeyboardkeywillactjustlikeabutton
presswhenthebuttonisinfocus.Buttonswithactionkeyshavealetterinthe
upperrightcornerofthebuttontoshowwhattheactionkeyis.Ifthekeyboard
focusisinanotherinterfaceelementsuchastheCommandCenter,pressingthe
actionkeywon'ttriggerthebutton.Theletterintheupperrighthandcornerofthe
buttonwillbedimmedinthissituation.Toenableactionkeys,clickinthewhite
backgroundoftheInterfacetab.
Slidersareglobalvariables,whichareaccessiblebyallagents.Theyareusedin
modelsasaquickwaytochangeavariablewithouthavingtorecodethe
procedureeverytime.Instead,theusermovestheslidertoavalueandobserves
whathappensinthemodel.
Switchesareavisualrepresentationforatrue/falseglobalvariable.Youmayset
thevariabletoeitheron(true)oroff(false)byflippingtheswitch.
Choosersletyouchooseavalueforaglobalvariablefromalistofchoices,
presentedinadropdownmenu.Thechoicesmaybestrings,numbers,booleans,
orlists.
InputBoxesareglobalvariablesthatcontainstringsornumbers.Themodelauthor
chooseswhattypesofvaluesyoucanenter.Inputboxescanbesettocheckthe
syntaxofastringforcommandsorreporters.Numberinputboxesreadanytypeof
constantnumberreporterwhichallowsamoreopenwaytoexpressnumbersthan
aslider.ColorinputboxesofferaNetLogocolorchooser.
Monitorsdisplaythevalueofanyreporter.Thereportercouldbeavariable,a
complexreporter,oracalltoareporterprocedure.Monitorsautomaticallyupdate
severaltimespersecond.
Plotsshowdatathemodelisgenerating.
Theoutputareaisascrollingareaoftextwhichcanbeusedtocreatealogof
activityinthemodel.Amodelmayonlyhaveoneoutputarea.
NotesletsyouaddinformativetextlabelstotheInterfacetab.Thecontentsofnotes
donotchangeasthemodelruns.
TheothercontrolsintheInterfacetoolbarallowyoutocontroltheviewupdatesandvariousothermodel
properties.
Thesliderletsyoucontrolhowfastthemodelruns.Slowercanbevaluablesincesomemodelsrun
sofastthey’rehardtofollow.Youcanalsofast-forwardthemodelbymovingtheslidertotheright,
reducingthefrequencyofviewupdates.
Theviewupdatescheckboxcontrolswhetherviewupdateshappenatall.
Theupdatemodemenuallowsyoutoswitchbetweencontinuousandtick-basedupdates.
The“Settings…”buttonallowsyoutochangemodelsettings.
“Continuous”updatesmeansthatNetLogoupdates(thatis,redraws)theviewmanytimesasecond,
regardlessofwhatisgoingoninthemodel.“Tick-based”updatesmeansthattheviewonlyupdates
whenthetickcounteradvances.(Forafullerdiscussionofviewupdates,seetheProgrammingGuide.)
The2Dand3Dviews
ThelargeblacksquareintheInterfacetabisthe2Dview.It’savisualrepresentationoftheNetLogo
worldofturtlesandpatches.Initiallyit’sallblackbecausethepatchesareblackandtherearenoturtles
yet.Youcanopenthe3DView,analternatevisualrepresentationoftheworld,byrightclicking(ctrl-
clickingonMac)ontheViewandchoosing“Switchto3DView”(thisoptionisalsoavailableinthe
“Tools”menu).
ThereareanumberofsettingsfortheView(accessiblebyeditingtheView,orbypressingthe
“Settings…”buttonintheInterfaceToolbar):
Noticethatthesettingsarebrokenupintothreegroups.Thereareworld,view,andtickscounter
settings.Worldsettingsaffectthepropertiesoftheworldthattheturtleslivein(changingthemmay
requireresettingtheworld).Viewandtickcountersettingsonlyaffecttheappearance,changingthem
willnotaffecttheoutcomeofthemodel.
Theworldsettingsallowyoutodefinetheboundariesandtopologyoftheworld.Atthetopoftheleft
sideoftheworldpanelyoucanchoosealocationfortheoriginoftheworldeither“Center”,“Corner”,
“Edge”,or“Custom”.Bydefaulttheworldhasacenterconfigurationwhere(0,0)isatthecenterofthe
worldandyoudefinethenumberofpatchesfromthecentertotherightandleftboundariesandthe
numberofpatchesfromthecentertothetopandbottomboundaries.Forexample:ifyousetMax-Pxcor
=10,thenMin-Pxcorwillautomaticallybesetto-10,thusthereare10patchestotheleftoftheorigin
and10patchestotherightofpatch00,foratotalof21patchesineachrow.
ACornerconfigurationallowsyoutodefinethelocationoftheoriginasoneofthecornersoftheworld,
upperleft,upperright,lowerleft,orlowerright.Thenyoudefinethefarboundaryinthexandy
directions.Forexampleifyouchoosetoputtheorigininthelowerleftcorneroftheworldyoudefinethe
rightandtop(positive)boundaries.
Edgemodeallowsyoutoplacetheoriginalongoneoftheedges(xory)thendefinethefarboundaryin
thatdirectionandbothboundariesintheother.Forexampleifyouselectedgemodealongthebottomof
theworld,youmustalsodefinethetopboundary,aswellastheleftandtheright.
Finally,Custommodeallowsyoutoplacetheoriginatanylocationintheworld,thoughpatch00must
stillexistintheworld.
Asyouchangethesettingsyouwillnoticethatthechangesyoumakearereflectedinthepreviewonthe
rightsideofthepanelwhichshowstheoriginandtheboundaries.Thewidthandheightoftheworldare
displayedbelowthepreview.
Alsobelowthepreviewtherearetwocheckboxes,theworldwrapsettings.Theseallowyoutocontrol
thetopologyoftheworld.Noticewhenyouclickthecheckboxesthepreviewindicateswhichdirections
allowwrapping,andthenameofthetopologyisdisplayednexttotheworlddimensions.Seethe
TopologysectionoftheProgrammingGuideformoreinformation.
Theviewsettingsallowyoutocustomizethelookoftheviewwithoutchangingtheworld.Changingview
settingswillneverforceaworldreset.Tochangethesizeofthe2DViewadjustthe“PatchSize”setting,
measuredinpixels.Thisdoesnotchangethenumberofpatches,onlyhowlargethepatchesappearin
the2DView.(Notethatthepatchsizedoesnotaffectthe3DView,asyoucansimplymakethe3D
Viewlargerbymakingthewindowlarger.)
Thefontsizesettingletsyoucontrolthesizeofturtle,patch,andlinklabels.
Theframeratecontrolshowoftentheviewgetsupdated.Thiscanhaveadramaticeffectonthedefault
speedatwhichamodelruns.Formoredetails,seetheviewupdatessectionoftheProgrammingGuide.
The“Smoothedges”checkboxcontrolstheuseofanti-aliasinginthe3Dviewonlyandonlyappears
wheneditingfromthe3Dview.Uncheckingitmakeslinesappearmorejaggedbutmayspeedup
rendering.
Tickcountersettingscontroltheappearanceofthetickcounterwhichisvisible(ornot)intheview
controlstrip.
Turtle,patchandlinkmonitorsareeasilyavailablethroughtheView,justright-clickontheturtleorpatch
youwanttoinspect,andchoose“inspectturtle…”or“inspectpatch…”fromthepopupmenu.Youcan
alsowatch,followorrideaturtlebyselectingtheappropriateitemintheturtlesub-menu.(Turtle,patch
andlinkmonitorscanalsobeopenedfromtheToolsmenuorbyusingtheinspectcommand.)
SomeNetLogomodelsletyouinteractwiththeturtlesandpatcheswithyourmousebyclickingand
draggingintheView.
Manipulatingthe3DView
Atthebottomofthewindowtherearebuttonstomovetheobserver,orchangetheperspectivefrom
whichyouarelookingattheworld.
Abluecrossappearsatthecurrentfocuspointasyouadjustthesesettings.Thelittlebluetrianglewill
alwayspointalongthey-axisinthepositivedirection,soyoucanorientyourselfincaseyougetlost.
Tolookattheworldfromadifferentangle,pressthe“rotate”button,thenclickanddragthemouse.The
observerwillcontinuetofacethesamepointasbefore(wherethebluecrossis)butitspositioninthe
relationtothexy-planewillchange.
Tomovecloserorfartherawayfromtheworldortheagentyouarewatching,followingorriding,press
the“zoom”buttonanddragupanddown.Notewhenyouareinfolloworridemodezoomingwillswitch
youbetweenrideandfollow,sincerideisjustaspecialcaseoffollowwherethedistanceatwhichyou
arefollowingis0.
Tochangethepositionoftheobserverwithoutchangingthedirectionitisfacingselectthe“move”
buttonanddragthemouseinsidethe3DViewwhileholdingdownthemousebutton.
Toallowthemousepositionandstatetobepassedtothemodelselectthe“interact”buttonanditwill
functionjustasthemousedoesinthe2Dview.
Toreturntheobserverandfocuspointtotheirdefaultpositionspressthe“ResetPerspective”button(or
usethereset-perspectivecommand).
FullscreenMode
Toenterfullscreenmode,pressthe“FullScreen”button,toexitfullscreenmode,presstheEsckey.
Note:Fullscreenmodedoesn’tworkoneverycomputer.Itdependsonyourgraphicscard.Seethe
SystemRequirementsfordetails.
3DShapes
Someshapesareautomaticallymappedtotrue3Dcounterpartsinthe3Dview.Forexample,the2D
circleshapebecomesasphereinthe3Dview.
Shapename 3Dshape
default 3Dturtleshape
circle sphere
dot smallsphere
square cube
triangle cone
line 3Dline
cylinder 3Dcylinder
line-half 3Dline-half
car 3Dcar
Allothershapesarebasedontheir2Dforms.Ifashapeisarotatableshape,itisassumedtobeatop
viewanditisextrudedasifthroughacookiecutterandorientedparalleltothexy-plane,asinAnts.
Or,ifashapeisnon-rotatable,itisassumedtobeasideview,anditisdrawnalwaysfacingthe
observer,asinWolfSheepPredation.
CommandCenter
TheCommandCenterallowsyoutoissuecommandsdirectly,withoutaddingthemtothemodel’s
procedures.Thisisusefulforinspectingandmanipulatingagentsonthefly.
(Tutorial#2:CommandsisanintroductiontousingcommandsintheCommandCenter.)
Let’stakealookatthedesignoftheCommandCenter.
Thesmallerbox,belowthelargebox,iswhereyoutypeacommand.AftertypingitpresstheReturnor
Enterkeytorunit.
Totheleftofwhereyoutypeisapopupmenuthatinitiallysays“observer>”.Youcanchooseeither
observer,turtles,orpatches,tospecifywhichagentsrunthecommandyoutype.
Tip:aquickerwaytochangeagenttypesistousetheTabkey.
Reporters
IfyouenterareporterintotheCommandCenter,theshowcommandwillbeinsertedbeforeit
automatically.
Accessingpreviouscommands
Afteryoutypeacommand,itappearsinthelargescrollingboxabovethecommandline.Youcanuse
CopyontheEditmenuinthisareatocopycommandsandthenpastethemelsewhere,suchasthe
Codetab.
Youcanalsoaccesspreviouscommandsusingthehistorypopup,whichisthesmalldownwardpointing
triangletotherightofwhereyoutypecommands.Clickonthetriangleandamenuofpreviouslytyped
commandsappears,soyoucanpickonetouseagain.
Tip:aquickerwaytoaccesspreviouscommandsiswiththeupanddownarrowkeysonyourkeyboard.
Clearing
Toclearthelargescrollingareacontainingpreviouscommandsandoutput,click“clear”inthetopright
corner.
Toclearthehistorypopupmenu,choose“ClearHistory”onthatmenu.
Arranging
YoucanhideandshowthecommandcenterusingtheHideCommandCenterandShowCommand
CenteritemsontheToolsmenu.
Toresizethecommandcenter,dragthebarthatseparatesitfromthemodelinterface.Or,clickoneof
thelittlearrowsontherightendofthebartomakethecommandcentereitherverybigorhidden
altogether.
Toswitchbetweenaverticalcommandcenterandahorizontalone,clickthebuttonwiththedouble-
headedarrow,justtotheleftof“Clear”.
Plots
Whenthemousepointerisoverthewhiteareaofaplot,thexandycoordinatesofthemouselocation
appear.(Notethatthemouselocationmightnotcorrespondexactlytoanyactualdatapointsintheplot.
Ifyouneedtoknowtheexactcoordinatesofplottedpoints,usetheExportPlotmenuitemandinspect
theresultingfileinanotherprogram.)
Whenyoucreateaplot,aswithallwidgets,theeditdialogautomaticallyappears.
Manyofthefieldsarefairlyself-explanatory,suchasthenameoftheplot,labelsforthexandyaxes,
rangesfortheaxes,andthe“Showlegend?”checkbox.
IfAutoScale?ischeckedthexandychangeswillautomaticallyreadjustaspointsareaddedtotheplot
iftheyareoutsidethecurrentrange.
Under“Plotsetupcommands”and“Plotupdatecommands”youcanentercommandsthatwill
automaticallyberunatappropriatetimes.Clickthelittletriangletoopenthetextboxforthecommands.
PlotcommandsareexplainedinmoredetailinthePlottingsectionoftheProgrammingGuide.
PlotPens
Intheplotpenssectionofthedialog,youcancreateandcustomizeyourplot’spens.Eachtablerow
representsapen.Bydefaultthereisonepennamed“default”.(Youmaywishtochangeittoaname
thathasmeaninginyourmodel.)
Toeditthecolorofapenclickthecoloredrectangletotheleftofthepen’sname.Thiswillbringupa
dialogthatallowsyoutosetthecolortooneoftheNetLogobasehuesoracustomcolorusingthecolor
swatches.
Toeditthepen’sname,doubleclickthename.
Inthe“PenUpdateCommands”columnyoucanentercommandsthatwillberunwhenreset-ticks,
tick,orupdate-plotscommandsarerun.ThisisexplainedinmoredetailinthePlottingsectionofthe
ProgrammingGuide.
Thelastcolumnhastwobuttons.Clickingthepenciliconwillbringupaneditdialogwithadditionalpen
settings.Thetrashcanbuttondeletesthepen.
PlotPenAdvancedSettings
Clickingapen’seditbuttonwillopenthisdialog:
Modeallowsyoutochangetheappearanceoftheplotpen:line,bar(forabarchart),orpoint(a
scatterplotofindividualpoints).
Intervalistheamountbywhichxadvanceseverytimeyouusetheplotcommand.
Ifthe“Showinlegend”checkboxischeckedtheselectedpenwillbeapartofthelegendinthe
upperrighthandcorneroftheplot.
Inthe“Setupcommands”fieldyoucanentercommandsthatwillberunwhenreset-ticksor
setup-plotsruns.
Inthe“Updatecommands”fieldyoucanentercommandsthatwillberunwhentickorupdate-
plotsruns.Thisfieldreappearsintheadvanceddialogtoprovidespaceforeditinglengthiersets
ofcommands.
FormoredetailedinformationonhoweachofthesefeaturesworksyoucanseethePlottingSectionof
theProgrammingGuide.
Sliders
Asliderhasanassociatedglobalvariable.Movingthesliderchangesthevariable’svalue.
WhenyouplaceasliderintheInterfacetabtheeditdialogautomaticallyopens,aswithallwidgets.Most
ofthefieldswillbefamiliar.However,itisimportanttonoticetheminimum,maximumandincrement
fieldswilltakeanyreporter,notjustconstants.So,forexample,youcouldmaketheminimummin-pxcor
andthemaximummax-pxcorandthesliderboundswillautomaticallyadjustwhenyouchangethesizeof
theworld.
AgentMonitors
Agentmonitorsdisplayboththevaluesofallthevariablesforaparticularagentandamini-viewthat
showstheagentandasmallareaaroundit.
YoucanopenagentmonitorsthroughtheToolsmenuortheinspectcommand.
Youcanzoominoroutusingthesliderbeneaththeviewandyoucanwatchtheagentinthemainview
usingthewatch-mebutton.
Belowthesliderthecurrentvalueofeachagentvariableisdisplayed.Youcanenteranewvalue.Itwill
beasif,forexample,thecodeset pcolor ...hadrun.
Belowtheagentvariableareathereisamini-commandcenter.Ratherthanrunningcodeasthe
observer,ortalkingtoalloftheturtles,patches,orlinks,thecodeenteredinthiscommandcenterisrun
onlybythisagent.
Youcancloseanagentmonitorbyclickingtheboxintheupperleftcorner,orbypressingtheEsckey.If
youholddownshiftwhileyouclicktheboxallopenagentmonitorswillcloseoryoucancloseallthe
agentmonitorsusingthe“CloseAllMonitors”optionintheToolsMenu.
InfoTab
NetLogo6.0.4UserManual
TheInfotabprovidesanintroductiontoamodel.Itexplainswhatsystemisbeingmodeled,how
themodelwascreated,andandhowtouseit.Itmayalsosuggestthingstoexploreandwaysto
extendthemodel,orcallyourattentiontoparticularNetLogofeaturesthemodeluses.
YoumaywishtoreadtheInfotabbeforestartingamodel.
Editing
Thenormal,formattedviewoftheInfotabisnoteditable.Tomakeedits,clickthe"Edit"button.
Whendoneediting,clickthe"Edit"buttonagain.
YouedittheInfotabasunformattedplaintext.Whenyou'redoneediting,theplaintextyou
enteredisdisplayedinamoreattractiveformat.
Tocontrolhowtheformatteddisplaylooks,youusea"markuplanguage"calledMarkdown.You
mayhaveencounteredMarkdownelsewhere;itisusedonanumberofwebsites.(Thereare
othermarkuplanguagesinuseontheweb;forexample,Wikipediausedamarkuplanguage
calledMediaWiki.Markuplanguagesdifferindetails.)
TheremainderofthisguideisatourofMarkdown.
Headings
Paragraphs
Italicizedandboldtext
Orderedlists
Unorderedlists
Links
Images
Blockquotations
Code
Codeblocks
Superscriptsandsubscripts
Notesonusage
Otherfeatures
Headings
Aheadingbeginswithoneormorehashmarks(#).Firstlevelheadingsgetonehash,second
levelheadingsgettwo,andsoonuptofourlevels.
Input
# First-level heading
## Second-level heading
### Third-level heading
#### Fourth-level heading
Paragraphs
Example
This is a paragraph. There are no spaces before the word 'This'.
This is another paragraph. The first line has two sentences.
The entire paragraph has two lines and three sentences.
Line breaks in the input,
Make line breaks in the output,
Like this.
Formatted
Thisisaparagraph.Therearenospacesbeforetheword‘This’.
Thisisanotherparagraph.Thefirstlinehastwosentences.Theentireparagraphhastwolines
andthreesentences.
Linebreaksintheinput,Makelinebreaksintheoutput,Likethis.
Italicizedandboldtext
Example
For italics, surround text with underscores:
_hello, world_.
For bold, surround text with two asterisks:
**hello, world**.
You can also combine them:
_**hello**_ and **_goodbye_**
Formatted
Foritalics,surroundtextwithunderscores:hello,world.
Forbold,surroundtextwithtwoasterisks:hello,world.
Youcanalsocombinethem:helloandgoodbye
Orderedlists
Example
We are about to start an ordered list.
1. Ordered lists are indented 2 spaces.
1. Subitems are indented 2 more spaces (4 in all).
2. The next item in the list starts with the next number.
3. And so on...
Formatted
Weareabouttostartanorderedlist.
1. Orderedlistsareindented2spaces.
1. Subitemsareindented2morespaces(4inallforasecondlevelitem).
2. Thenextitemintheliststartswiththenextnumber.
3. Andsoon…
Unorderedlists
Example
We are about to start an unordered list.
* Like ordered lists, unordered lists are also indented 2 spaces.
* Unlike ordered lists, unordered lists use stars instead of numbers.
* Sub items are indented 2 more spaces.
* Here's another sub item.
Formatted
Weareabouttostartanunorderedlist.
Likeorderedlists,unorderedlistsarealsoindented2spaces.
Unlikeorderedlists,unorderedlistsusestarsinsteadofnumbers.
Subitemsareindented2morespaces.
Here’sanothersubitem.
Links
Automaticlinks
Thesimplestwaytocreatealinkistojusttypeitin:
Example
http://ccl.northwestern.edu/netlogo/
Formatted
http://ccl.northwestern.edu/netlogo/
Linkswithtext
Ifyouwanttouseyourowntextforthelink,here’show:
[link text here](link.address.here)
Example
[NetLogo](http://ccl.northwestern.edu/netlogo/)
Formatted
NetLogo
Locallinks
Itisalsopossibletolinktoapageonyourcomputer,insteadofapagesomewhereonthe
Internet.
Locallinkshavethisform:
[alt text](file:path)
Anyspacesinthepathmustbeconvertedto%20.Forexample,this:
file:my page.html
mustbewrittenas:
file:my%20page.html
Thepathisrelativetothedirectorythatthemodelfileisin.
Example
Theeasiestwaytolinktofilesonyourcomputeristoputthemintothesamedirectoryasyour
model.Assumingyouhaveafilenamedindex.htmlinthesamedirectoryasyourmodel,thelink
wouldlooklikethis:
[Home](file:index.html)
Example
Hereisanotherexamplewherethefilelivesinadirectorycalleddocs,anddocsisinthesame
directoryasyourmodel:
[Home](file:docs/index.html)
Images
Imagesareverysimilartolinks,buthaveanexclamationpointinfront:
![alt text](http://location/of/image)
(Thealternatetextisthetextthatgetsdisplayediftheimageisnotfound.)
Example
![NetLogo](http://ccl.northwestern.edu/netlogo/images/netlogo-title-new.jpg)
Formatted
Localimages
Alsoverysimilartolinks,itispossibletodisplayanimageonyourcomputerinsteadofanimage
somewhereontheInternet.Assumingyouhaveanimagenamedimage.jpg,localimageslook
likethis:
![alt text](file:path)
Thepathisrelativetothedirectorythatthemodelfileisin.
Aswithlocallinks,anyspacesinthenameofthefileorthepathmustbeconvertedto%20.
Example
Likelocallinks,theeasiestwaytodisplayimagesonyourcomputeristoputthemintothesame
directoryasyourmodel.Thisexampledisplaystheimage“PerspectiveExample.png”,which
residesinthesamedirectoryasthismodel(InfoTabExample).
![Example](file:Perspective%20Example.png)
Formatted
Blockquotations
Consecutivelinesstartingwith>willbecomeblockquotations.Youcanputwhatevertextyoulike
insideofitandyoucanalsostyleit.
Example
> Let me see: four times five is twelve, and four times six is thirteen,
> and four times seven is --- _oh dear!_
> I shall never get to twenty at that rate!
Formatted
Letmesee:fourtimesfiveistwelve,andfourtimessixisthirteen,andfourtimesseven
is—ohdear!Ishallnevergettotwentyatthatrate!
Code
Toincludeashortpieceofcodeinasentence,surrounditwithbackticks(`).
Example
You can create a single turtle with the `crt 1` command.
Formatted
Youcancreateasingleturtlewiththecrt 1command.
Codeblocks
Itisalsopossibletohaveblocksofcode.Tocreateacodeblock,indenteverylineoftheblockby
4spaces.Anotherwayistosurrounditwithathreebacktickslinebeforeandaftertheblock.(If
youdon’twantyourcodetobecoloredasNetLogocode,addtextafterthefirstthreebackticks.)
Example
About to start the code block.
Leave a blank line after this one, and then put the code block:
; a typical go procedure
to go
ask turtles
[ fd 1 ]
tick
end
or:
About to start the code block.
Leave a blank line after this one, and then put the code block:
```
; a typical go procedure
to go
ask turtles
[ fd 1 ]
tick
end
```
Formatted
Abouttostartthecodeblock.Leaveablanklineafterthisone,andthenputthecodeblock:
; a typical go procedure
to go
ask turtles
[ fd 1 ]
tick
end
Superscriptsandsubscripts
Superscriptsandsubscriptsareusefulforwritingformulas,equations,footnotesandmore.
Subscriptsappearhalfacharacterbelowthebaseline,andarewrittenusingtheHTMLtag<sub>.
Superscriptsappearhalfacharacterabovethebaseline,andarewrittenusingtheHTMLtag
<sup>.
Example
H<sub>2</sub>O
2x<sup>4</sup> + x<sup>2</sup>
WWW<sup>[1]</sup>
Formatted
H2O
2x4+x2+42
WWW[1]
Notesonusage
Paragraphs,lists,codeblocksandotherfeaturesshouldbeseparatedfromeachotherwith
ablankline.Ifyoufindthatsomethingisn’tformattedthewayyouexpected,itmightbe
becauseyouneedtoaddablanklinebeforeit.
Topreventaspecialcharacterfrombeingtreatedasmarkup,putabackslash(\)beforeit.
WeuseGitHubflavorednewlines(https://github.github.com/github-flavored-markdown/)
insteadoftraditionalMarkdownhandlingofnewlines.Thismeansthatnewlinesaretreated
asreallinebreaks,insteadofbeingcombinedwiththepreviouslineintoasingleparagraph.
Otherfeatures
Markdownhasadditionalfeaturesthatwehavenotshownhere.
Wehavetestedthefeaturesshownaboveonavarietyofsystems.IfyouuseotherMarkdown
features,youmayfindthattheyworkonyourcomputer,ornot.Evenafeaturethatworksonyour
computermightworkdifferently,ornotworkatall,forsomeonewithadifferentoperatingsystem
orJavavirtualmachine.
IfyouwantallNetLogouserstobeabletoreadyourInfotab,useonlythefeaturesshownabove.
MoreinformationaboutMarkdownisathttps://daringfireball.net/projects/markdown/.For
renderingMarkdown,NetLogousestheFlexmark-javalibrary.
CodeTabGuide
NetLogo6.0.4UserManual
TheCodetabiswherethecodeforthemodelisstored.Commandsyouonlywanttouse
immediatelygointheCommandCenter;commandsyouwanttosaveanduselater,overand
overagain,arefoundintheCodetab.
CheckingforErrors
Todetermineifthecodehasanyerrors,youmaypressthe“Check”button.Ifthereareany
syntaxerrors,theCodetabwillturnred,thecodethatcontainstheerrorwillbehighlighted,
andanerrormessagewillappear.
Switchingtabsalsocausesthecodetobechecked,soifyoujustswitchtabs,pressingthe
Checkbuttonfirstisn’tnecessary.
Find&Replace
Tofindafragmentofcodeintheprocedures,clickonthe“Find”buttonintheCodetoolbar
andtheFinddialogwillappear.
Youmayenterawordorphrasetofind,andoptionallyalsoanewwordorphrasetoreplaceit
with.The“Ignorecase”checkboxcontrolswhetherthecapitalizationmustbethesameto
indicateamatch.
Ifthe“Wraparound”checkboxischecked,theentireCodetabwillbecheckedforthephrase,
startingatthecursorposition.Whenitreachestheenditwillreturntothetop,otherwiseonly
theareafromthecursorpositiontotheendoftheCodetabwillbesearched.The“Next”and
“Previous”buttonswillmovedownanduptofindanotheroccurrenceofthesearchphrase.
“Replace”changesthecurrentlyselectedphrasewiththereplacephraseand“Replace&
Find”changestheselectedphraseandmovestothenextoccurrence.“ReplaceAll”will
changeallinstancesofthefindphraseinthesearchareawiththereplacephrase.
AutomaticIndentation
WhentheIndentAutomaticallycheckboxisselected,NetLogowillautomaticallyattemptto
alignyourcodeinalogicallystructuredformat.Forexample,whenyouopenasetofsquare
brackets“[”(perhapsafteranifstatement),NetLogowillautomaticallyaddspacessothat
thefollowinglinesofcodearetwospacesfurtherindentedthanthebracket.Whenyouclose
thesquarebracketstheclosingbracketwillbelinedupwiththematchingopenbracket.
NetLogowilltrytoindentthecodeasyoutype,butyoucanalsopressthetabkeyanywhere
onanylinetoaskNetLogotoindentthelineimmediately.Or,youcanselectawholeregionof
codeandpressthetabkeytore-indentallofit.
MoreEditingOptions
Tofindaparticularproceduredefinitioninyourcode,usethe“Procedures”popupmenuinthe
Codetab.Themenulistsallproceduresintheordertheyappearinthefile.Tosearchfora
particularprocedure,usethesearchfieldatthetopofthepopup.Itwillfilterthelistof
proceduresusingfuzzymatchingasyoutype.Fuzzymatchwillincludeprocedureswhose
namescontainthecharactersthatyoutypeintheorderthattheyappearinthesearchfield,
butthecharactersdonothavetoberightnexttoeachother.Forinstance,“fnn”will
match"find-nearest-neighbors"and“wolf-down-neighbor”butnot“nearest-wolf-neighbor”.
Youmayusethearrowkeysormousetoselectaparticularprocedureandenterorclickto
jumptoit.Thiscanbeaveryconvenientwaytonavigateyourfile.Tofacilitatethis,youcan
usetheshortcutctrl-g(cmd+gonMacOS)toaccesstheproceduresmenu.
The“ShiftLeft”,“ShiftRight”,“Comment”,and“Uncomment”itemsontheEditmenuareused
intheCodetabtochangetheindentationlevelofyourcodeoraddandremovesemicolons,
whichmarkcomments,fromsectionsofcode.
Formoreinformationaboutwritingprocedures,readTutorial#3:Proceduresandthe
ProgrammingGuide.
IncludedFilesMenu
Caution:Theincludesfacilityisnewandexperimental.
Whenyouaddthe__includeskeywordtoamodelamenutotherightoftheproceduresmenu
appears.Thisisthe“IncludedFiles”menuwhichlistsalltheNetLogosourcefiles(.nls)
includedinthisfile.YoucanmakethismenualwaysvisibleusingthePreferencesdialog.
Youcanchooseafilenamefromthemenutoopenatabforthatfile,oryoucanopenanew
orexistingfileusingNewSourceFileandOpenSourceFile,respectively.
Onceyou’veopenednewtabstheybecomeaccessiblefromtheTabsmenu,andyoucanuse
thekeyboardtomovefromtabtotab(Command+numberonMac,Control+numberon
otheroperatingsystems).
TransitionGuide
NetLogo6.0.4UserManual
ManymodelscreatedinearlierversionsofNetLogoalsoworkinNetLogo5.0.However,
somemodelswillneedchanges.Ifanoldmodelisn’tworking,thissectionoftheUserManual
maybeabletohelpyou.
WhatissuesmayarisedependsonwhatversionofNetLogothemodelwascreatedwith.
Thisguideonlycoverschangesmostlikelytocauseissuesforusers.Seethereleasenotes
formorecompletedetailsondifferencesbetweenversions.
ChangesforNetLogo6.0.3
ArduinoExtensionChanges
ThearduinoextensionhassubstantiallychangedthewayitreceivesvaluesfromArduino
boards.Pleaseconsultthearduinoexamplesketch(includedwithinthe“models”folderunder
Chapter8oftheIABMtextbook)foranupdatedsketchcompatiblewiththeArduinoexample
model.Ifyouhaveanexistingarduinosketch,youwillneedtoadjusttheformatusedtosend
valuestoNetLogo.Oldsketcheswillhavecodewhichsendsbackmessageslike“;A,2.5;”.For
thenewversionofthearduinoextensiontoreceivethesamemessage,sketchesshould
send“;A,D,2.5;”instead.Theadded‘D,’informsNetlogothatthevaluebeingsentisa
numberandnotastring.
CFExtensionChanges
Allprimitiveshavebeenremovedfromthecfextensionandreplacedbythecf:ifelseand
cf:ifelse-valuemulti-branchprimitives.Weencourageexistingcfuserstoadjusttheircode
tousethesenewprimitives.Overtime,wehopetousetheseprimitivesasanexampleon
whichtoremodelNetLogo’sexistingifelseandifelse-valueprimitives.Becausethiswould
bearelativelylargelanguagechange,wewouldlovetohearanyfeedbackaddressyoumay
havefromusingthesecfextensionprimitives.
ChangesforNetLogo6.0
TasksreplacedbyAnonymousProcedures
InNetLogo6.0,taskshavebeenreplacedbyanonymousprocedures.Thismeansthattaskis
nolongeraprimitive,it’sbeenreplacedbythenewarrowsyntaxforcreatinganonymous
procedures.Similarly,questionmarkvariableslike?,?1,and?2arenowjustordinarynames
inNetLogoandcanbeusedtonameprocedurevariables,letvariables,oranonymous
procedurevariables.Finally,is-reporter-task?andis-command-task?havebeenreplacedby
is-anonymous-reporter?andis-anonymous-command?.
Tomakethistransitioneasier,we’veaddedanautomaticconversionstepwhichshouldallow
mostmodelssavedinNetLogo5tobeconvertedtousethenewsyntaxautomatically.The
autoconverterhasbeenasubstantialpieceofeffortandwe’vetesteditonallthemodelsin
themodelslibrary.Touseit,ensurethemodelcompilesandrunproperlyinNetLogo5or
later,thensaveitfromNetLogo5orlater.Then,simplyopenthemodelinNetLogo6.Ifall
goeswell,you’llseetheconverterhaschangedcodeliketask [?1 + ?2] to[ [?1 ?2] -> ?1
+ ?2 ].Thequestionmarksaremeanttoserveastemporaryplaceholdersforconversion.
Theyenableyourmodeltorun,butyoucan(andshould)replacethesevariableswith
meaningfulnames.Ifyouopenamodelwithtasksandithasnotbeenconverted,the
autoconverterwasn’tabletoconvertyourmodel.Ratherthanattempttoautoconvertyour
modelandbreaksomething,themodelwillopen,youwillbeshowntheappropriateerrors
andgivenachancetoedityourmodel.
Whilewehavetestedtheautoconverterthoroughly,weexpecttheretobesomecasesit
doesn’tcover.
Ifyoumakeuseofextensionsthataren’tyetcompiledforNetLogo6,theautoconverter
willnotworkuntilthoseextensionshavebeenupdated.
Ifyourcodeusesrunorrunresulttoevaluatestringscontainingtasks,the
autoconverterwillnotchangethosestringstobeanonymousprocedures.Tomakerun
andrunresultworkasexpected,lookatstringsinyourmodelandchangeanywhich
relyontaskor?-variablestoinsteadrelyonanonymousprocedures
Ifyourmodeldoesn’tfallintotheabovecategoriesanddoesn’tconvertorconverts
incorrectly,pleaseemailourfeedbackaddressandwe’llbehappytoofferwhatever
assistancewecan.
Linkreportersoverhauledtobemoreconsistentandflexible
InpreviousversionsofNetLogo,linkreportershavehadanumberofinconsistencies
regardingdirectedandundirectedlinks.Forexample,my-linkswouldreportalllinks
connectedtoaturtle,whereaslink-neighborswouldonlyreportneighborsconnectedby
undirectedlinks.Furthermore,itwasquitedifficulttoworkwithmodelswherethelinkscould
eitherbedirectedorundirected.
Toalleviatetheseissues,thelinkprimitiveshavebeenoverhauledin6.0.Thesechanges
onlyaffectexistingmodelsthatusebothdirectedandundirectedlinkswhilealsousingthe
unbreededlinkprimitives.
Thechangesareasfollows:
Linkreportersthatcontaintheword“out”nowutilizebothdirected,outgoinglinksand
undirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogetfromthecurrent
nodetoothernodes.Forexample,out-link-neighbor?willreporttrueifthecurrent
turtleisconnectedtothegiventurtlebyeitheranoutgoingdirectedlinkoranundirected
link.Ifyouonlywantdirected,outgoinglinks,youcanuseabreed-specificreporteror
my-out-links with [ is-directed? self ].Generally,whenworkingwithmodelsthat
havebothdirectedandundirectedlinks,youwillprobablywanttousethe“out
primitivesformostthingsnow.
Linkreportersthatcontaintheword“in”nowutilizebothdirected,incominglinksand
undirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogettothecurrent
nodefromothernodes.Forexample,in-link-neighbor?willreporttrueifthecurrent
turtleisconnectedtothegiventurtlebyeitheranincomingdirectedlinkoranundirected
link.Ifyouonlywantdirected,incominglinks,youcanuseabreed-specificreporteror
my-in-links with [ is-directed? self ].
Linkreportersthatdonotspecify“out”or“in”utilizealllinks.
Furthermore,therearenolongerrestrictionsregardingwhichreporterscanbeusedwith
whichbreeds.Forunbreededlinks,thismakesitpossibletousethesameprimitives
regardlessofwhetheryournetworkendsupbeingdirectedorundirected.
Thenewbehavior(includingallchangedprimitives)issummarizedbythefollowingtable,
where“un”referstoundirectedlinks,“out”referstodirected,outgoinglinks,and“in”refersto
directed,incominglinks.
Newlinkreporterbehavior
Oldlinkreporterbehavior
RemovalofApplets
Oracle,thecompanybehindJava,hasannouncedthatJavaappletsaredeprecated(seethis
blogpostformoreinformation).Thiscomesasthemajorbrowsershaveremovedsupportfor
plug-ins(likejavaapplets)orannouncedthattheyplantodoso.
Insteadofusingappletstodistributeyourmodel,NetLogoofferstheoptiontoexportto
NetLogoWeb.WhileNetLogoWebdoesn’tyetofferthefullfunctionalityofdesktopNetLogo
(inparticular,extensionsaren’tsupported),itisnowcapableofrunningmostofthemodelsin
theNetLogomodelslibraryandwehopethatmostmodeldistributorswillfindthatitmeets
theirneeds.ToexporttoNetLogoWeb,choosethe“SaveAsNetLogoWeb”optionfromthe
“File”menu.
ChangestotheNetLogoUserInterface
UserswillnoticeseveraltweakstotheNetLogoUserinterfacewhenopeningNetLogo6for
thefirsttime.We’veremovedthebarborderabovetheview.Toopenthe3DViewin6.0,you
canrightclickontheviewandchoose“Switchto3DView”,orchoosethesameoptionfrom
the“Tools”menu.Ticksarenowdisplayedintheinterfacetabtoolbarbeneaththespeed
slider.Toadjustthelabelusedfor“ticks”andotherviewproperties,youcanchoosethe
“Settings”buttonatthefarrightoftheinterfacetabtoolbarorright-clickontheviewand
choose“Edit…”fromthecontextmenuthatappears.
NobodyNotPermittedasaChooserValue
InNetLogo6.0,nobodyisnolongeravalidchooservalue.Justasyoucan’tputturtle 0or
turtles,nobodyreferstoanon-literalvaluewhichisn’tsupportedinchoosers.Aspartofthis
transition,chooserscontainingnobody(ornobodywithinanestedlist)willhaveallusesof
nobodychangedto"nobody"whenopenedinNetLogo6.0.
Breedsmusthavesingularandpluralnames
InNetLogo6.0,youmustspecifybothpluralandsingularbreednames.Inpriorversions,
declarationslikebreed [mice]werelegal,butthissupporthasbeenremovedin6.0.Ifyou
havemodelswhichuseonlypluralbreednames,itisrecommendedthatyouconvertthemto
specifybothnamesbeforeopeningin6.0sincedoingsowillpermittheNetLogoconverterto
workmosteffectivelyonanyothercodeinyourmodelwhichneedsconversion.
Removalof“Movie”Prims
TheNetLogomovieprimshadn’tbeenupdatedinquitesometimeandgeneratedinvalid
quicktimemoviefiles.Theyhavebeenreplacedbyprimsinthenewvidextension.Thefull
documentationforthevidextensionisavailableintheVidExtensionsectionofthemanual.
Aswithallextensions,userswillneedtoincludevidintheextensionssectionoftheir
NetLogomodel.
Manyofthemovieprimitiveshavedirectparallelsinthevidextensionwhichcanbefoundin
thefollowingtable:
movieprim vidprim
movie-cancel vid:reset-recorder
movie-close vid:save-recording *file-name*
movie-grab-view vid:record-view
movie-grab-interface vid:record-interface
movie-start *file-name* vid:start-recorder *optional-width* *optional-height*
movie-status vid:recorder-status
movieprim vidprim
WhenyoufirstopenafileinNetLogo6.0,yourfilewillbeautomaticallyconvertedtousethe
newprimitives.Thiswillincludeaddinganewglobalvariable-_recording-save-file-nameto
trackthenameoftheactiverecording,aswellasaddingthevidextensiontothemodel.You
shouldverifythattheconversiontookplacecorrectly.Thereisnoreplacementformovie-set-
frame-rate.Thevidextensionrecordsframesat25persecond,slightlymorethanthedefault
15frames-per-secondofthemovieprims.Ifyourrecordingissensitivetoframerate,consider
recordingeachexistingframetwice(2/25isfairlycloseto1/15)orconsiderusinga
postprocessingtool(likegstreamerorffmpeg)toadjustthevideoplaybackspeed.
ImprovedNameCollisionDetection
InNetLogo6.0,expandederror-checkingintheNetLogocompilercausesmodelswhich
defineundirected-link-breed [ undirected-links undirected-link ] and/ordirected-
link-breed [ directed-links directed-link ]toerrorforredefiningaprimitivereporter
(eitheris-directed-link?oris-undirected-link?).Ifyourmodeldoesn’tuseis-directed-
link?oris-undirected-link?atall,simplychangingthebreednamesshouldresolvethe
error.
Ifyouusedeitheroftheis-<directedness>-link?prim,thereareseveralwaysyoumight
modifyyourmodeltoaccountforthischange.Ifyourmodelhasnootherbreededlinks,
considerremovingthelinkbreedandusingthebuilt-inlinkprimitives.Ifyourmodelhasother
breededlinks,butonlyofdifferentdirectedness,simplychangingthebreedname(andall
relatedprimitivenames)shouldresolvetheproblem.Notethatinthiscaseis-directed-link?
and/oris-undirected-link?continuetobehavethesameasbefore.Ifyourmodelhasother
breededlinksofthesamedirectedness,thechangewillvarydependingonyourmodel.The
breedname(s)mustbechanged,butyoumustdecidewhetheryouusedis-directed-link?/
is-undirected-link?tochecklinkdirectednessortocheckthatlinkbreedmembership.Ifyou
usedittochecklinkdirectednessleavingitas-isshouldkeepthecurrentbehaviorofthe
model.Otherwise,itcansimplybereplacedbyis-<breed>?.
Removalofhubnet-set-client-interface
Thehubnet-set-client-interfaceprimitivewasrenderedobsoletebytheintroductionofthe
HubNetclienteditorandendofsupportforcalculatorHubNet.Wehavefounditusedinvery
fewmodelsandhavedecidedtoremoveitfromthelanguage.Onopeninganexistingmodel
in6.0,theautoconvertershouldremoveallusesofhubnet-set-client-interfacefromyour
code.
Improved&UpdatedExtensionsAPI
OneofourgoalsinNetLogo6.0hasbeentomakeiteasiertodevelopextensionsandeasy
todevelopmorepowerfulextensions.Tothatend,we’vebumpedtheextensionAPIfrom5.0
to6.0.Existingextensionswillneedtorecompilechangingthe“NetLogo-Extension-API-
Version”intheirjar’sMANIFEST.MFfrom5.0to6.0.
Someofthechangeswe’vemadetotheextensionsAPIinclude:
org.nlogo.api.Contextnowallowsaccesstothecurrentworldandworkspaceobjects
withoutrequiringacasttoanorg.nlogo.nvm.ExtensionContext.
org.nlogo.api.WorkspacehasbeenintroducedasastableAPIforextensionstodepend
on.
ANetLogojarisnowavailablefromBinTray.
Forafulllistofchangesbetween5.0and6.0,pleasevisitourExtensionTransitionGuideon
GitHub.
Inserviceofmakingiteasiertobuildextensions,we’veexpandedandimprovedtheNetLogo
ExtensionPluginforsbt,theScalaBuildTool.SbtisapowerfultoolforbuildingJVMprojects
andcanbeusedinprojectsthatuseScala,Java,oracombinationofthetwo.We’renow
usingtheExtensionPlugintobuildallofthebundledextensionsandwestronglyrecommend
extensionauthorstakeadvantageofthepluginasitmakesconfiguringaNetLogoextension
buildextremelystraightforward.ThepluginhandlesfetchingtheNetLogojarwhichextensions
compileagainstaswellasgenerationofajarfortheextensioncontainingtheappropriate
metadata.
Addrangeprimitive
AnewrangeprimitivewasaddedinNetLogo6.As“range”mayappearinexistingmodelsas
aprocedureorvariablename,wehaveaddedanautoconversionstepwhichwillensurethat
thesemodelscontinuetooperateimmediatelyuponopeninginNetLogo6.Existingusesof
rangeinmodelsauthoredbeforeNetLogo6willbeconvertedto_rangeuponfirstopeningin
NetLogo6.Oncethemodelopens,youcanrename_rangetosuityourmodel.
ChangesforNetLogo5.2
hsbprimitives
In5.2,thehsbprimitiveshavebeenchangedtoworkwiththestandardscalevaluesof360
forhue,and100forsaturationandbrightness.Thisaffectstheprimitiveshsb,extract-hsb
andapproximate-hsb.
Theoldprimitives,scaledto255,areautomaticallytransitionedtoandhavebeenrenamed
__hsb-old,__extract-hsb-oldand__approximate-hsb-old.
GoGoextension
TheGoGoextensionhasbeenupgradedtousenewerGoGoboardswiththeHIDinterface.
Manyoftheolderprimitivesnolongerwork,andwillalertyoutoupgradingyourGoGo
board’sfirmware.
Ifyouneedtocontinuetouseaserialinterface,youcanusethebundledgogo-serial
extension.Changeyourmodeltousegogo-serialasopposedtogogo.Moredetailshere.
IfyoucannotupgradetousethenewHIDextensionnorthenewserialextension,theoriginal
extensioncanbefoundathttps://github.com/NetLogo/GoGo-RXTX-Extension
ChangesforNetLogo5.0
Plotting
In5.0,youdon’thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanput
itinsidetheplotsthemselves,intheInterfacetab.
Nonetheless,theoldstyleandalloftheexistingplottingprimitivesarestillsupported.We
recommendchangingyourmodeltousethenewstyle,butifyoudon’t,itshouldstillwork.
Thefollowingexampleshowshowtochangeamodeltousethenewstyle.Supposeyou
haveatypicalNetLogo4.1modelwithoneplotcalled“populations”andtwopenscalled
“robots”and“humans”.Theoldcodemightlooklike:
to setup
clear-all
...
do-plotting
end
to go
...
tick
do-plotting
end
to do-plotting
set-current-plot "populations"
set-current-plot-pen "robots"
plot count robots
set-current-plot-pen "humans"
plot count humans
end
Herearethestepstomakethetransition:
Copytheplot count robotscommandandpasteitintotheUpdateCommandsfieldfor
therobotspenintheploteditdialog.Removeitfromthedo-plottingprocedure.
Theplot count humanscommandcanbemovedinthesamewayforthehumanspen.
Afterthoselinesareremovedfromthedo-plottingprocedure,itdoesn’tactuallydo
anythinganymore!Removeit.
Thefinalstepistoreplacethedo-plottingprocedurecallsinsetupandgo.Insetup,the
do-plottingcallshouldbechangedtoreset-ticks.Ingo,thedo-plottingcallshouldbe
changedtotick.reset-ticksandtickwillbothcauseplottingtohappenautomatically.
Theresulting(muchsimpler)codelookslikethis:
to setup
clear-all
...
reset-ticks
end
to go
...
tick
end
FormoredetailsonhowplottingworksinNetLogo5.0,seethePlottingSectionsofthe
ProgrammingGuideandtheInterfaceGuide.Fordetailsonhowplottinginteractswiththetick
counter,readon.
Tickcounter
Thewaythetickcounterworkshaschangedin5.0.Insteadofbeinginitiallysetto0,thetick
counterisinitiallyblank.
reset-ticks
Youmustusereset-tickstostartthetickcounterat0beforeusingticks,tickortick-
advanceforthefirsttime.
reset-ticksshouldgoattheendofyoursetupprocedure.Puttingittherewillallowyour
modeltoworkwith5.0’snewplottingfeatures.
reset-ticksandplotting
In5.0,youdon’thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanput
itinsidetheplotsthemselves,intheInterfacetab.Codeinsideplotsistriggeredbyreset-
ticksandtick.Resettingthetickcounterrunsplotsetupcode,andthenitalsorunsplot
updatecodetoplottheinitialstateofthemodel.Theinitialstateofthemodelwon’tbein
placeuntiltheendofsetup,sothat’swhyreset-ticksshouldgoattheend.
__clear-all-and-reset-ticks
InorderformodelsfrompreviousNetLogoversionstoworkin5.0withoutchanges,whenan
oldmodelisopenedin5.0,anyoccurrencesofclear-all(orca)areautomaticallychangedto
__clear-all-and-reset-ticks,whichcombinestheeffectsofclear-allandreset-ticks.The
twounderscoresonthenameindicatethatthisisnotanormalprimitive,butexistsonlyfor
backwardscompatibility.
Youshouldremove__clear-all-and-reset-ticksfromyourcode,replaceitwithclear-all,
andputreset-ticksattheendofyoursetupprocedure.(Thisdoesn’thappenautomatically
becausethestructureofNetLogomodelsistoofree-formforanautomaticconverterto
reliablymakethechangeforyou.)
Unicodecharacters
NetLogo5.0fullysupportsinternationalcharacterscross-platform,usingtheUnicode
characterset.NetLogo5.0modelfilesalwaysrepresentUnicodecharactersusingtheUTF-8
encoding.
PreviousversionsofNetLogoallowedUnicodecharacterstobeusedinsomecontexts.
However,modelfilesweresavedintheplatform’sdefaultencoding,whichonmostsystems
wassomethingotherthanUTF-8.Characterswerehandledcorrectlyonthesameplatform
(e.g.twoWindowsmachines),butcouldbealteredifthemodelwasmovedbetween
platforms(e.g.fromWindowstoMacorviceversa).
WhenopeninganexistingmodelinNetLogo5.0,ifthemodelcontainsinternationalorother
non-ASCIIcharacters,thecharactersmaybeinterpretedincorrectly,becausetheywere
originallywritteninaplatform-specificencoding,butthenreadbackininUTF-8.
Ifonlyafewcharactersareaffected,youmightfinditeasiestjusttofixthemmanually.
Butifyouexpectalargenumberofcharacterstobeaffected,andyouwantthemtranslated
automatically,youcanuseathirdpartyutilitytore-encodeyour.nlogofilefromitsoriginal
encodingintoUTF-8.Afterconversion,openthemodelinNetLogo5.0andallcharacters
shouldbecorrect.
Infotabs
NetLogo5.0usestheMarkdownmarkuplanguagetoallowyoutoformatyourInfotab,
includingheaders,boldanditalics,images,andsoforth.
EarlierversionsofNetLogousedacustommarkuplanguagewithmuchmorelimited
capabilities.
Whenopeningamodelfromanolderversion,NetLogo5.0translatesyouroldmarkupinto
Markdown.Mostofthetimethisproducesgoodresults,butyoumaywanttocheckthe
resultsyourselfandmakesurethatyourInfotabstilllooksgood.
Modelspeed
InNetLogo5.0everymodelhasa“targetframerate”whichaffectsthedefaultspeedatwhich
themodelruns,whenthespeedsliderisinthemiddle,onthe“normalspeed”setting.
Thedefaulttargetframeratefornewmodels,andformodelsthatwerecreatedinearlier
versionsofNetLogo,is30framespersecond.Ifyouareusingtick-basedupdates,aswe
recommendformostmodels,thenthattranslatesto30tickspersecond.
Ifyourmodelrunsslowerin5.0thanitranin4.1,it’sprobablyjustbecauseitsspeedisbeing
limitedbythisrate.Ifyouwant,youcanpresstheSettingsbuttonintheInterfacetaband
changetheframeratetoahighernumber.
Someoldmodelsusedtheeverycommandtosetadefaultspeed.Inmostcasethiscanbe
nowremovedfromthecode,andthetargetframeratesettingusedinstead.
Listperformance
TheunderlyingdatastructureforNetLogolistshaschanged.
InNetLogo4.1,aNetLogolistwasrepresentedinternallyasasinglylinkedlist.Some
operationsonsinglylinkedlistsarefast(suchasfirstandbutfirst)butothersareslow
becausetheycouldrequiretraversingthewholelist(suchasitemandlast).
InNetLogo5.0,listsarenowactuallytreesinternally.Asaresult,someoperationsarealittle
slower,butotheroperationsaredrasticallyfasteronlonglists.SeetheListssectionofthe
ProgrammingGuidefordetails.
Somemodelsmayrunalittleslowerwiththenewdatastructure,especiallyifyoumake
heavyuseofshortlists.Butothermodelswillrunfaster–perhapsdramaticallyfaster.
Somespecialwaysofwritinglist-processingcodethatwereusefulinNetLogo4.1areno
longerneededin5.0.Forexample,sincein4.1fputwasfastandlputwasslow,modelers
sometimesbuiltuplistsinreverseorderusingfput,perhapscallingreverselatertorestore
theintendedorder.InNetLogo5.0,youdon’tneedtocodethatwayanymore.fputandlput
arethesamespeed.
ExtensionsAPI
Ifyouaretheauthorofanextension,youwillneedtorecompileitagainstthe5.0NetLogo.jar
andlibdirectoryforittoworkwith5.0.
Youmayalsoneedtobeawareofthefollowingchanges:
Syntaxconstants
Thecodeforspecifyingthesyntaxofaprimitivehaschangedslightly,forexample
Syntax.TYPE_STRINGisnowSyntax.StringType().(FromJava,thepairofparenthesesatthe
endisrequired.InScala,youcanomitthem.)
LogoListconstruction
Onesignificantchangeisthatorg.nlogo.api.LogoListnolongerhasapublicconstructor.
Instead,therearetwonewwaystoconstructaLogoList.
Ifyouhaveajava.lang.Iterable,youcancopythecontentsintoafreshLogoListbypassing
ittothestaticmethodLogoList.fromJava().Seethearrayextensionsourcecodefora
sampleusage.
Or,tobuildupanewlistoneitematime,useorg.nlogo.api.LogoListBuilder.The
ExtensionsGuidehassamplecodeshowingtheuseofLogoListBuilder.
Primitiveclasses
InpriorNetLogoversions,theextensionsAPIrequiredthateachextensionprimitivehaveits
ownseparatetop-levelclasswithano-argumentconstructor.Theselimitationshavenow
beenlifted.Also,api.Primitiveobjectsarenowmadeonlyonce,whentheextensionis
loaded,insteadofeverytimetheCodetabwasrecompiled.
ChangesforNetLogo4.1
Combiningsetandof
Thefollowingsyntaxisnolongersupported:
set [<variable>] of <agent> <value>
Commandsofthisformmustberewrittenusingask:
ask <agent> [ set <variable> <value> ]
Or,ifthenewvaluemustbecomputedbytheaskingagentandnotbytheagentwhose
variableisbeingset:
;; OPTION #1 (using let):
let new-value <value>
ask <agent> [ set <variable> new-value ]
;; OPTION #2 (using myself):
ask <agent> [ set <variable> [value] of myself ]
Soforexample,this:
set [color] of turtle 0 red
Canberewrittenas:
ask turtle 0 [ set color red ]
Itisnotnecessarytouseletormyselfsinceredisredfromthepointofviewofbothagents.
However,this:
set [color] of turtle 0 color
Mustberewrittenas:
let new-color color
ask turtle 0 [ set color new-color ]
or
ask turtle 0 [ set color [color] of myself ]
inordernottochangethemeaning,sincethetwoagentsmayhavedifferentstartingvalues
forcolor.Theformusingmyselfisbriefer,buttheformerusingletmaybeconsidered
clearer,dependingoncontextandindividualpreference.
ChangesforNetLogo4.0
Whonumbering
PriortoNetLogo4.0,adeadturtle’swhonumber(storedinthewhoturtlevariable)couldbe
reassignedtoalaternewbornturtle.InNetLogo4.0,whonumbersareneverreuseduntilwho
numberingisresetto0bytheclear-allorclear-turtlescommand.Thischangeinbehavior
maybreakafewoldmodels.
Turtlecreation:randomizedvs.“ordered
NetLogo4.0providestwodifferentobservercommandsforcreatingturtles,create-turtles
(crt)andcreate-ordered-turtles(cro).
crtgivesthenewturtlesrandomcolorsandrandomintegerheadings.croassignscolors
sequentiallyandgivestheturtlessequentialequallyspacedheadings,withthefirstturtle
facingnorth(headingof0).
PriortoNetLogo4.0,thecrtcommandbehavedthewaycrodoesnow.Ifyouroldmodel
dependsonthe“ordered”behavior,youwillneedtochangeyourcodetousecroinsteadof
crt.
Itiscommonforoldmodelsthatusedcrttocontainextracommandstorandomizethenew
turtles’headings,forexamplert random 360orset heading random 360.Thesecommands
arenolongernecessarywhenusedinsidecrt.
Addingstringsandlists
PriortoNetLogo4.0,the+(addition)operatorcouldbeusedtoconcatenatestringsandjoin
lists.IncurrentNetLogo,+onlyworksonnumbers.Toconcatenatestrings,usetheword
primitive;tojoinliststogether,usethesentenceprimitive.Thislanguagechangewasmadeto
increasethespeedofcodethatuses+.
Oldcode:
print "There are " + count turtles + " turtles."
Newcode:
print (word "There are " count turtles " turtles.")
Likewise,ifyouneedtoconcatenatelists,useSENTENCE.
Thischangeisnothandledautomaticallywhenconvertingoldmodels;userswillneedto
changetheircodebyhand.
Weknowthischangewillbeawkwardforuserswhoareusedtotheoldsyntax.Wehave
madethischangeforefficiencyandconsistency.Wecanimplementanadditionoperatorthat
onlyaddsnumbersmuchmoreefficientlythanonethathandlesseveraldifferentdatatypes.
Becauseadditionissuchacommonoperation,NetLogo’soverallspeedisaffected.
The-atprimitives
Theobservermaynolongerusepatch-at,turtles-at,andBREEDS-at.Usepatch,turtles-on
patch,andBREEDS-onpatchinstead.Notethatpatchnowroundsitsinputs(beforeitonly
acceptedintegerinputs).
Links
NetLogo3.1hadsupportsforusinglinkstoconnectturtlestomakenetworks,graphs,and
geometricfigures.Thelinkswerethemselvesturtles.
InNetLogo4.0,insteadoflinksbeingturtles,linksarenowanindependentfourthagenttype,
rightalongsideobserver,turtles,patches.Theprimitivesinvolvinglinksarenolonger
consideredexperimental;theyarenowfullypartofthelanguage.
Modelsthatusetheold,experimentalturtle-basedlinkprimitiveswillneedtobeupdatedto
uselinkagents.Thedifferencesarenothuge,buthandupdatingisrequired.
LinksaredocumentedintheLinkssectionoftheProgrammingGuide,andintheNetLogo
Dictionaryentriesforthelinkprimitives.SeetheNetworkssectionoftheModelsLibraryfor
examplemodelsthatuselinks.Therearealsosomelink-basedCodeExamples.
Firstyouwillneedtoremoveanybreedscalled“links”ifyouareonlyusingonetypeoflinks
thenyouwillnothavetousebreedsatall.Ifyouareusingmultipletypesoflinkssee
undirected-link-breedanddirected-link-breed.Commandsandreportersthatcontainthe
word“links”(like__create-links-with,etc.)willautomaticallybeconvertedtothenewform
withoutunderscores(create-links-with).However,primitivesthatuseadifferentbreed
name(suchas“edges”)willnotbeconverted.Youwillneedtoremovetheunderscoresby
handandunlessyouaredeclaringalinkbreedwiththatnameyouwillneedtochangethe
breeddesignationto“links”.
Thecommandsremove-link(s)-with/from/tonolongerexist.Insteadyoushouldaskthe
linksinquestiontodie.
Forexample:
ask turtle 0 [ __remove-links-with link-neighbors ]
becomes
ask turtle 0 [ ask my-links [ die ] ]
Severalofthelayoutcommandshaveslightlydifferentinputs,thefirsttwoinputsare
generallyaturtleagentsetandalinkagentsettoperformthelayouton.Seethedictionary
entriesfordetails.layout-spring,layout-radialandlayout-tutte
Youmayalsoneedtorearrangethedeclarationofturtles-ownvariables,sincelinkswere
onceactuallyturtles.Anyvariablesthatapplytolinksshouldbemovedintoalinks-ownblock.
Sincelinksarenolongerturtlestheynolongerhavethebuilt-inturtlevariables(thoughsome
ofthelinkvariablesarethesamesuchascolorandlabel.Ifyouformerlyusedthelocationof
linkturtlesyouwillnowneedtocalculatethemidpointofthelink.Thisisfairlysimpleina
non-wrappingworld.
to-report link-xcor
report mean [xcor] of both-ends
end
to-report link-ycor
report mean [ycor] of both-ends
end
itisalittlebittrickierinawrappingworldbutstillfairlystraightforward.
to-report link-xcor
let other-guy end2
let x 0
ask end1
[
hatch 1
[
face other-guy
fd [distance other-guy] of myself / 2
set x xcor
die
]
]
report x
end
andsimilarlyforycor.
Ifyouusedeitherthesizeorheadingofthelinkturtlesyoucanusethereporterslink-length
andlink-headinginstead.
New“of”syntax
Wehavereplacedthreedifferentlanguageconstructs,-of(withhyphen),value-from,and
values-fromwithasingleofconstruct(nohyphen).
old new
`color-ofturtle0` `[color]ofturtle0`
`value-fromturtle0[size*size]` `[size*size]ofturtle
0`
`meanvalues-fromturtles[size]` `mean[size]ofturtles`
Whenofisusedwithasingleagent,itreportsasinglevalue.Whenusedwithanagentset,it
reportsalistofvalues(inrandomorder,sinceagentsetsarealwaysinrandomorder).
Notethatwhenopeningoldmodelsinthenewversion,-of,value-from,andvalues-fromwill
automaticallybeconvertedtouse“of”instead,butsomenestedusesoftheseconstructsare
toocomplexfortheconverterandmustbeconvertedbyhand.
Serialask
Theaskcommandisnowserialratherthanconcurrent.Inotherwords,theaskedagentswill
runoneatatime.Notuntiloneagentcompletelyfinishestheentirebodyoftheaskdoesthe
nextagentstart.
Notethateventheoldaskwasnevertrulyconcurrent;wesimulatedconcurrentexecutionby
interleavingexecutionamongtheagentsusingaturn-takingmechanismdescribedinthe
NetLogoFAQ.
Wehavemadethischangebecauseinourexperience,usersoftenwrotemodelsthat
behavedinunexpectedwaysduetothesimulatedconcurrency,butrarelywrotemodelsthat
benefitedfromthesimulatedconcurrency.Modelsexhibitingunexpectedbehaviorcould
usuallybefixedbyaddingthewithout-interruptioncommandintherightplaces,butitwas
difficultforuserstoknowwhetherthatcommandwasneededandifso,where.
InNetLogo4.0,without-interruptionisnolongernecessaryunlessyourmodelusesask-
concurrent(oraturtleorpatchforeverbuttoncontainingcodethatdependsonsimulated
concurrency).Inmostmodels,allusesofwithout-interruptioncanberemoved.
Thesimulatedconcurrencyformerlyemployedby“ask”isstillaccessibleinthreeways:
Youmayusetheask-concurrentprimitiveinsteadofasktogettheoldsimulated
concurrency.(Wedon’trecommendthis,though.)
CommandsissuedintheCommandCenterdirectlytoturtles,patches,orlinkshavean
impliedask-concurrent.
Turtle,patch,andlinkforeverbuttonshaveanimpliedask-concurrentaswell.
Notethataskitselfisalwaysserialregardlessofthecontextinwhichitisused,however.
InourownModelsLibrary,modelsthatmakeuseofthisconcurrencyarerare.Aprominent
example,though,isTermites,whichusesaconcurrentturtleforeverbutton.
Tickcounter
NetLogonowhasabuilt-intickcounterforrepresentingthepassageofsimulatedtime.
Youadvancethecounterbyoneusingthetickcommand.Ifyouneedtoreaditsvalue,
there’sareportercalledticks.Theclear-allcommandresetsthetickcounter;sodoes
reset-ticks.
Inmostmodelsthetickcounterwillbeinteger-valued,butifyouwanttousesmaller
incrementsoftime,youcanusethetick-advancecommandtoadvancethetickcounterby
anypositiveamount,includingfractionalamounts.SomeModelsLibrarymodelsthatuse
tick-advanceareVectorFieldsandtheGasLabmodels.
ThevalueofthetickcounterisdisplayedinthetoolbaratthetopoftheInterfacetab.(You
canusetheSettings…buttoninthetoolbartohidethetickcounter,orchangetheword
“ticks”tosomethingelse.)
Viewupdatemodes
Inthepast,NetLogoalwaystriedtoupdatetheviewabout20timesasecond.We’renow
callingthat“continuous”viewupdates.Thebiggestproblemwithitwasthatyouusuallywant
updatestohappenbetweenmodelticks,notinthemiddleofatick,sowehadacheckboxon
buttonsthat(bydefault)forcedadisplayupdateaftereverybuttoniteration.Thatmadesure
updateshappenedbetweenticks,butitdidn’tgetridoftheintermediateupdates.Youhadto
useno-displayanddisplaytolockthemout.
Westillsupportcontinuousupdates.TheyarethedefaultwhenyoustartupNetLogo.But
mostModelsLibrarymodelsnowusetick-basedupdates.Withtick-basedupdates,updates
happenonlywhenthetickcounteradvances.(Thedisplaycommandcanbeusedtoforce
additionalupdates;seebelow.)
Theadvantagesoftick-basedupdatesasweseethemareasfollows:
1. Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputerto
computerorfromruntorun.
2. Intermediateupdatescanconfusetheuserofyourmodelbylettingthemseethings
theyaren’tsupposedtosee,whichmaybemisleading.
3. Increasedspeed.Updatingtheviewtakestime,soifoneupdatepertickisenough,then
enforcingthanthereisonlyoneupdatepertickwillmakeyourmodelfaster.
4. Insteadofhavinga“forceviewupdate”checkboxineverybuttonlikeinNetLogo3.1,we
onlyneedonechoicewhichappliestotheentiremodel.
5. Usingthespeedslidertoslowdownamodelnowjustinsertspausesbetweenticks.So
withtick-basedupdates,setupbuttonsarenolongeraffectedbythespeedslider.This
wasarealannoyancewiththeoldspeedslider.(Theannoyancepersistsformodels
thatusecontinuousupdates,though.)
Asmentionedabove,mostmodelsinourModelsLibrarynowusetick-basedupdates.
Evenformodelsthatwouldnormallybesettotick-basedupdates,itmaybeusefultoswitch
tocontinuousupdatestemporarilyfordebuggingpurposes.Seeingwhat’sgoingonwithina
tick,insteadofonlyseeingtheendresultofatick,couldhelpwithtroubleshooting.
Ifyouswitchyourmodeltousetick-basedupdates,you’llalsoneedtoaddthetick
commandtoyourcode,otherwisetheviewwon’tupdate.(Notethattheviewstillalways
updateswhenabuttonpopsuporacommandenteredinthecommandcenterfinishes,
though.Soit’snotliketheviewwilljuststayfrozenindefinitely.)
Howtomakeamodeluseticksandtick-basedupdates
Herearethestepstofollowtoconvertyourmodeltouseticksandtick-basedupdatesin
NetLogo4.0:
1. IntheInterfacetabtoolbar,ontherighthandsidewhereitsays“updateview:”,change
thesettingfrom“continuously”to“onticks”.
2. Addthetickcommandtoyourgoprocedure,atorneartheend.InModelsLibrary
modelswealwaysputtickaftertheagentsmovebutbeforeanyplottingcommands.
That’sbecausetheplottingcommandsmightcontainsomethinglikeplotxy ticks ...
andwewantthenewvalueofthetickcounterused,nottheoldone.Mostmodelsdon’t
refertothetickcounterintheirplottingcommands,butnonetheless,forconsistencyand
toavoidmistakeswesuggestalwaysputtingtickbeforetheplottingcommands.
Somemodelswillrequiresomeadditionalchanges:
1. Ifyourmodelalreadyhasaglobal“ticks”or“clock”or“time”variable,getridofit.Use
thetickcommandandticksreporterinstead.(Ifyourmodelusesfractionalincrements
oftime,usetick-advanceinsteadoftick.)Ifyouhadamonitorforthatvariable,youcan
getridofit;there’snowatickcounterinthetoolbar.
2. clear-allresetsthetickcountertozero.Ifyoudon’tuseclear-allinyoursetup
procedure,thenyoumayneedtoaddreset-tickstoresetthecountertozero.
3. Ifyouusedno-displayanddisplaytopreventviewupdatesfromhappeninginthe
middleofgo,youcangetridofthem.
4. Ifyourmodelneedstoupdatetheviewwithoutadvancingthetickcounter(examples:
Party,DiceStalagmite,networkmodelswithanimatedlayout,modelswithmouse
interactionbuttons),usethedisplaycommandtoforceadditionalviewupdatessothe
usercanseewhatisgoingon.
Speedslider
PreviousversionsofNetLogohadaspeedsliderthatcouldbeusedtomakemodelsrun
slower,soyoucanseewhat’sgoingon.
InNetLogo4.0,theslidercanbeusedtospeedupmodelsaswell.Itdoesthisbyupdating
theviewlessfrequently.Updatingtheviewtakestime,sothefewerupdates,thefasterthe
modelruns.
Thedefaultpositionofthesliderisinthecenter.Whenyou’reatthecenter,theslidersays
“normalspeed”.
Asyoumovethesliderawayfromthecenterposition,themodelwillgraduallyrunfasteror
slower.
Atveryhighspeeds,viewupdatesbecomeveryinfrequentandmaybeseparatedbyseveral
seconds.Itmayfeellikethemodelisactuallyrunningslower,sincetheupdatesareso
infrequent.Butwatchthetickcounter,orotherindicatorssuchasplots,andyou’llseethat
yes,themodelreallyisrunningfaster.Iftheinfrequentupdatesaredisconcerting,don’tpush
theslidersofarover.
Whenusingtick-basedupdates,slowingthemodeldowndoesnotcauseadditionalview
updates.Rather,NetLogosimplypausesaftereachtick.
Whenusingcontinuousupdates,slowingthemodeldownmeansviewupdatesbecomemore
closelyspaced.Ifyoupushthespeedslidermorethanhalfwaytotheleft,themodelwillbe
runningsoslowlythatyoucanwatchturtlesmovingoneatatime!ThisisnewinNetLogo4.0;
inpreviousNetLogoversions,nomatterhowslowlyyouranamodel,youwouldneverseethe
agentsinanaskmovingoneatatime;alltheagentsinanaskalwaysappearedtomove
together.
Numbers
NetLogonolongermaintainsaninternaldistinctionbetweenintegersandfloatingpoint
numbers.Soforexample:
Old:
observer> print 3
3
observer> print 3.0
3.0
observer> print 1 + 2
3
observer> print 1.5 + 1.5
3.0
observer> print 3 = 3.0
true
(Thelastlineshowsthatalthoughthedistinctionbetweeninteger3andfloatingpoint3.0was
maintained,thetwonumberswerestillconsideredequal.)
New:
observer> print 3
3
observer> print 3.0
3
observer> print 1 + 2
3
observer> print 1.5 + 1.5
3
observer> print 3 = 3.0
true
Weexpectthatonlyraremodelswillbenegativelyimpactedbythischange.
AbenefitofthischangeisthatNetLogonowsupportsamuchlargerrangeofintegers.The
oldrangewas-2,147,483,648to2,147,483,647(around+/-2billion);thenewrangeis+/-
9,007,199,254,740,992(around+/-9quadrillion).
Agentsetbuilding
NetLogo3.1(andsomeearlierversions)includedprimitivescalledturtles-fromandpatches-
fromthatwereoccasionallyusefulforbuildingagentsets.InNetLogo4.0,theseprimitives
havebeenreplacedwithnewprimitivescalledturtle-setandpatch-setthataremuchmore
flexibleandpowerful.(link-setexistsaswell.)Seetheentriesfortheseprimitivesinthe
NetLogoDictionary.Modelsthatusetheoldturtles-fromandpatches-fromwillneedtobe
alteredbyhandtousethenewprimitives.
RGBColors
InNetLogo3.1RGBandHSBcolorscouldbeapproximatedasNetLogocolorsusingthergb
andhsbprimitives.Thesehavebeenrenamedtoapproximate-rgbandapproximate-hsband
nowexpectinputsintherange0-255,not0-1.
ThefullRGBspectrumisnowavailableinNetLogosoitmaynolongerbenecessarytouse
theseprimitivesatall.Youcansetanycolorvariabletoathree-itemRGBlist,withvaluesin
the0-255range,andgetthatexactcolor.SeetheColorsectionoftheProgrammingGuide
fordetails.
Tie
Inpreviousversions__tiewasprovidedasanexperimentalfeature.AsofNetLogo4.0links
haveatie-modevariablewhichcanbesetto"none","free",or"fixed".In4.0tieisnowa
link-onlyprimitive.Thismeansthattotieturtle1toturtle0youwrite:
ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
SeetheTiesectionoftheprogrammingguidefordetails.
ChangesforNetLogo3.1
Agentsets
Ifyourmodelisbehavingstrangelyorincorrectly,itmaybebecausesinceNetLogo3.1,
agentsetsarenowalwaysinrandomorder.InpriorversionsofNetLogo,agentsetswere
alwaysinafixedorder.Ifyourcodedependedonthatfixedorder,thenitwon’tworkanymore.
Howtofixyourmodeltoworkwithrandomizedagentsetsdependsonthedetailsofwhatyour
codeisdoing.Insomesituations,itishelpfultousethesortorsort-byprimitivestoconvert
anagentset(randomorder)intoalistofagents(fixedorder).See“Listsofagents”intheLists
sectionoftheProgrammingGuide.
Wrapping
Ifyouareseeingpiecesofturtleshapeswrappingaroundtheviewedges,it’sbecause
NetLogo3.0allowedyoutoturnoffsuchwrappingintheviewwithoutaffectingthebehavior
ofthemodel.SinceNetLogo3.1,ifyoudon’twanttheviewtowrapyoumustmakeitsothe
worlddoesn’twrap,usingthenewtopologyfeature.Makingthischangemayrequireother
changestoyourmodel,though.SeetheTopologysectionoftheProgrammingGuidefora
thoroughdiscussionofhowtoconvertyourmodeltotakeadvantageofthisnewfeature.
Randomturtlecoordinates
ManymodelsmadeinNetLogo3.0orearlierusesetxy random world-width random world-
heighttoscatterturtlesrandomly,usingeitherrandomorrandom-float.Itonlyworksifworld
wrappingison.
(Why?Becausewhenwrappingison,youcansetcoordinatesofturtlestonumbersbeyond
theedgeoftheworldandNetLogowillwraptheturtletotheotherside.Butinworldsthat
don’twrapsettingthexorycoordinatesofaturtletoapointoutsidetheboundsoftheworld
causesaruntimeerror.TheworldwrapsettingswereaddedinNetLogo3.1.Seethe
TopologysectionoftheProgrammingGuideformoreinformation.)
Tofixyourmodelsothatitworksregardlessofthewrappingsettings,useoneofthesetwo
commandsinstead:
setxy random-xcor random-ycor
setxy random-pxcor random-pycor
Thetwocommandsareabitdifferent.Thefirstcommandputstheturtleonarandompointin
theworld.Thesecondcommandputstheturtleonthecenterofarandompatch.Aneven
moreconcisewaytoputaturtleonthecenterofarandompatchis:
move-to one-of patches
ShapesEditorGuide
NetLogo6.0.4UserManual
TheTurtleandLinkShapeEditorsallowsyoutocreateandsaveturtleandlinkdesigns.
NetLogousesfullyscalableandrotatablevectorshapes,whichmeansyoucancreate
designsbycombiningbasicgeometricelements,whichcanappearon-screeninanysizeor
orientation.
Gettingstarted
Tobeginmakingshapes,chooseTurtleShapesEditororLinkShapesEditorintheTools
menu.Anewwindowwillopenlistingalltheshapescurrentlyinthemodel,beginningwith
default,thedefaultshape.TheShapesEditorallowsyoutoeditshapes,createnewshapes,
andborrowfromanothermodel.Youcanalsoimportturtleshapesfromalibraryofpre-
existingshapes.
Importingshapes
EverynewmodelinNetLogostartsoffcontainingasmallcoresetoffrequentlyusedshapes.
ManymoreturtleshapesareavailablebyusingtheImportfromlibrary…button.Thisbrings
upadialogwhereyoucanselectoneormoreshapesandbringthemintoyourmodel.Select
theshapes,thenpresstheImportbutton.
Similarly,youcanusetheImportfrommodelbuttontoborrowshapesfromanother
model.
Defaultshapes
HerearetheturtleshapesthatareincludedbydefaultineverynewNetLogomodel:
Firstrow:default,airplane,arrow,box,bug,butterfly,car
Secondrow:circle,circle2,cow,cylinder,dot,facehappy,faceneutral
Thirdrow:facesad,fish,flag,flower,house,leaf,line
Fourthrow:linehalf,pentagon,person,plant,sheep,square,square2
Fifthrow:star,target,tree,triangle,triangle2,truck,turtle
Sixthrow:wheel,x
Shapeslibrary
Andherearetheshapesintheshapeslibrary(includingallofthedefaultshapes,too):
BydefaultthereisonlyoneLinkshapeinamodel,thatis“default”.Thisshapeissimplya
singlestraightlinewithasimplearrowhead(ifthelinkhappenstobedirected).
Creatingandeditingturtleshapes
PressingtheNewbuttonwillmakeanewshape.Or,youmayselectanexistingshapeand
pressEdit.
Tools
Intheupperleftcorneroftheeditingwindowisagroupofdrawingtools.Thearrowisthe
selectiontool,whichselectsanalreadydrawnelement.
Todrawanewelement,useoneoftheotherseventools:
Thelinetooldrawslinesegments.
Thecircle,square,andpolygontoolscomeintwoversions,solidandoutline.
Whenusingthepolygontool,clickthemousetoaddanewsegmenttothepolygon.When
you’redoneaddingsegments,doubleclick.
Afteryoudrawanewelement,itisselected,soyoucanmove,delete,orreshapeitifyou
want:
Tomoveit,dragitwiththemouse
Todeleteit,presstheDeletebutton.
Toreshapeit,dragthesmall“handles”thatappearontheelementonlywhenitis
selected.
Tochangeitscolor,clickonthenewcolor.
Previews
Asyoudrawyourshape,youwillalsoseeitinfivesmallersizesinthefivepreviewareas
foundnearthebottomoftheeditingwindow.Thepreviewsshowyourshapeasitmight
appearinyourmodel,includinghowitlooksasitrotates.Thenumberbeloweachpreviewis
thesizeofthepreviewinpixels.Whenyouedittheview,patchsizeisalsomeasuredin
pixels.Soforexample,thepreviewwith“20”belowitshowsyouhowyourshapewouldlook
onaturtle(ofsize1)onpatchesofsize20pixels.
Therotatablefeaturecanbeturnedoffifyouwantashapethatalwaysfacesthesameway,
regardlessoftheturtle’sheading.
Overlappingshapes
Newelementsgoontopofpreviouselements.Youcanchangethelayeringorderby
selectinganelementandthenusingtheBringtofrontandSendtobackbuttons.
Undo
AtanypointyoucanusetheUndobuttontoundotheedityoujustperformed.
Colors
ElementswhosecolormatchestheColorthatchanges(selectedfromadrop-downmenu–
thedefaultisgray)willchangecoloraccordingtothevalueofeachturtle’scolorvariablein
yourmodel.Elementsofothercolorsdon’tchange.Forexample,youcouldcreatecarsthat
alwayshaveyellowheadlightsandblackwheels,butdifferentbodycolors.
Otherbuttons
The“RotateLeft”and“RotateRight”buttonsrotateelementsby90degrees.The“Flip
Horizontal”and“FlipVertical”buttonsreflectelementsacrosstheaxes.
Thesefourbuttonswillrotateorfliptheentireshape,unlessanelementisselected,inwhich
caseonlythatelementisaffected.
Thesebuttonsareespeciallyhandyinconjunctionwiththe“Duplicate”buttonifyouwantto
makeshapesthataresymmetrical.Forexample,ifyouweremakingabutterfly,youcould
drawthebutterfly’sleftwingwiththepolygontool,thenduplicatethewingwiththe“Duplicate”
button,thenturnthecopyintoarightwingwiththe“FlipHorizontal”button.
Shapedesign
It’stemptingtodrawcomplicated,interestingshapes,butrememberthatinmostmodels,the
patchsizeissosmallthatyouwon’tbeabletoseeverymuchdetail.Simple,bold,iconic
shapesareusuallybest.
Keepingashape
Whentheshapeisdone,giveitanameandpresstheDonebuttonatthebottomofthe
editingwindow.Theshapeanditsnamewillnowbeincludedinthelistofshapesalongwith
the“default”shape.
Creatingandeditinglinkshapes
Managinglinkshapesisverysimilartomanagingturtleshapes.So,youcancreateanew
shapebypressingtheNewbuttonoryoucaneditexistingshapes.Whenyouaredone
editingashapepressDoneifyouwanttokeepit.
Changinglinkshapeproperties
Thereareseveraldifferentpropertiesforeachlinkshapethatyouareallowedtochange:
Name-linkshapescanhavethesamenameasturtleshapesbutmustbeunique
amonglinkshapes.
DirectionIndicator-thedirectionindicator(thelittlearrowondirectedlinks)isjustlike
theturtlevectorshapes,youcanedititusingthesameeditorbypressingtheEdit
button.
Curviness-thisistheamountofbendinalinkexpressedinpatches(thisisparticularly
usefulifyouhavedirectedlinksgoinginbothdirectionssoyoucandiscernbothlinks)
Numberoflines:Youcanhave1,2,or3linesineachlinkshape,youcontrolthisby
selectinglinepatternsinthe“leftline”,“middleline”,and“rightline”selectionboxes.
Dashpatternoflines:Thereareseveraldashedlinepatternsavailableintheselection
boxessonotalllinesneedbesolid.
Herearesomelinkshapeswithvariousproperties:
Usingshapesinamodel
Inthemodel’scodeorinthecommandcenter,youcanuseanyoftheshapesthatareinthe
model(thoughonlyturtlescanhaveturtleshapesandonlylinkscanhavelinkshapes).For
example,supposeyouwanttocreate50turtleswiththeshape“rabbit”.Providedthereis
someturtleshapecalledrabbitinthismodel,givethiscommandtotheobserverinthe
commandcenter:
observer> crt 50
Andthengivethesecommandstotheturtlestospreadthemout,thenchangetheirshape:
turtles> fd random 15
turtles> set shape "rabbit"
Voila!Rabbits!Notetheuseofdoublequotesaroundtheshapename.Shapenamesare
strings.
Similarly,youcansettheshapevariableoflinks.Assumingthereisalinkshapecalled“road”
inthismodel:
observer> crt 5 [ create-links-with other turtles ]
turtles> fd 5
links> set shape "road"
Theset-default-shapecommandisalsousefulforassigningshapestoturtlesandlinks.
BehaviorSpaceGuide
NetLogo6.0.4UserManual
Thisguidehasthreeparts:
WhatisBehaviorSpace?:Ageneraldescriptionofthetool,includingtheideasand
principlesbehindit.
HowItWorks:Walksyouthroughhowtousethetoolandhighlightsitsmostcommonly
usedfeatures.
AdvancedUsage:HowtouseBehaviorSpacefromthecommandline,orfromyour
ownJavacode.
WhatisBehaviorSpace?
BehaviorSpaceisasoftwaretoolintegratedwithNetLogothatallowsyoutoperform
experimentswithmodels.
BehaviorSpacerunsamodelmanytimes,systematicallyvaryingthemodel’ssettingsand
recordingtheresultsofeachmodelrun.Thisprocessissometimescalled“parameter
sweeping”.Itletsyouexplorethemodel’s“space”ofpossiblebehaviorsanddeterminewhich
combinationsofsettingscausethebehaviorsofinterest.
Ifyourcomputerhasmultipleprocessorcores,thenbydefault,modelrunswillhappenin
parallel,onepercore.
WhyBehaviorSpace?
Theneedforthistypeofexperimentisrevealedbythefollowingobservations.Modelsoften
havemanysettings,eachofwhichcantakearangeofvalues.Togethertheyformwhatin
mathematicsiscalledaparameterspaceforthemodel,whosedimensionsarethenumberof
settings,andinwhicheverypointisaparticularcombinationofvalues.Runningamodelwith
differentsettings(andsometimeseventhesameones)canleadtodrasticallydifferent
behaviorinthesystembeingmodeled.So,howareyoutoknowwhichparticular
configurationofvalues,ortypesofconfigurations,willyieldthekindofbehavioryouare
interestedin?Thisamountstothequestionofwhereinitshuge,multi-dimensionparameter
spacedoesyourmodelperformbest?
Forexample,supposeyouwantspeedysynchronizationfromtheagentsintheFireflies
model.Themodelhasfoursliders–number,cycle-length,flash-lengthandnumber-flashes–
thathaveapproximately2000,100,10and3possiblevalues,respectively.Thatmeansthere
are2000*100*10*3=600,000possiblecombinationsofslidervalues!Tryingcombinations
oneatatimeishardlyanefficientwaytolearnwhichonewillevokethespeediest
synchronization.
BehaviorSpaceoffersyouamuchbetterwaytosolvethisproblem.Ifyouspecifyasubsetof
valuesfromtherangesofeachslider,itwillrunthemodelwitheachpossiblecombinationof
thosevaluesand,duringeachmodelrun,recordtheresults.Indoingso,itsamplesthe
model’sparameterspace–notexhaustively,butenoughsothatyouwillbeabletosee
relationshipsformbetweendifferentslidersandthebehaviorofthesystem.Afteralltheruns
areover,adatasetisgeneratedwhichyoucanopeninadifferenttool,suchasa
spreadsheet,database,orscientificvisualizationapplication,andexplore.
Byenablingyoutoexploretheentire“space”ofbehaviorsamodelcanexhibit,
BehaviorSpacecanbeapowerfulassistanttothemodeler.
HowItWorks
TobeginusingBehaviorSpace,openyourmodel,thenchoosetheBehaviorSpaceitemon
NetLogo’sToolsmenu.
Managingexperimentsetups
Thedialogthatopensletsyoucreate,edit,duplicate,delete,andrunexperimentsetups.
Experimentsarelistedbynameandhowbymodelrunstheexperimentwillconsistof.
ExperimentsetupsareconsideredpartofaNetLogomodelandaresavedaspartofthe
model.
Tocreateanewexperimentsetup,pressthe“New”button.
Creatinganexperimentsetup
Inthenewdialogthatappears,youcanspecifythefollowinginformation.Notethatyoudon’t
alwaysneedtospecifyeverything;somepartscanbeleftblank,orleftwiththeirdefault
values,dependingonyourneeds.
Experimentname:Ifyouhavemultipleexperiments,givingthemdifferentnameswillhelp
youkeepthemstraight.
Varyvariablesasfollows:Thisiswhereyouspecifywhichsettingsyouwantvaried,and
whatvaluesyouwantthemtotake.Variablescanincludesliders,switches,choosers,and
anyglobalvariablesinyourmodel.
Variablescanalsoincludemax-pxcor,min-pxcor,max-pycorandmin-pycor,world-width,
world-heightandrandom-seed.Thesearenot,strictlyspeaking,variables,butBehaviorSpace
letsyouvarythemasiftheywere.Varyingtheworlddimensionsletsyouexploretheeffectof
worldsizeuponyourmodel.Sincesettingworld-widthandworld-heightdoesnotnecessarily
definetheboundsoftheworldhowtheyarevarieddependsonthelocationoftheorigin.If
theoriginiscentered,BehaviorSpacewillkeepitcenteredsothevaluesworld-widthor
world-heightmustbeodd.Ifoneoftheboundsisatzerothatboundwillbekeptatzeroand
theotherboundwillmove,forexampleifyoustartwithaworldwithmin-pxcor = 0max-pxcor
= 10andyouvaryworld-widthlikethis:
["world-width" [11 1 14]]
min-pxcorwillstayatzeroandmax-pxcorwillsetto11,12,and13foreachoftheruns.If
neitheroftheseconditionsaretrue,theoriginisnotcentered,norattheedgeoftheworld
youcannotvaryworld-heightorworld-widthdirectlybutyoushouldvarymax-pxcor,max-
pycor,min-pxcorandmin-pycorinstead.
Varyingrandom-seedletsyourepeatrunsbyusingaknownseedfortheNetLogorandom
numbergenerator.Notethatyou’realsofreetousetherandom-seedcommandinyour
experiment’ssetupcommands.Formoreinformationonrandomseeds,seetheRandom
NumberssectionoftheProgrammingGuide.
Youmayspecifyvalueseitherbylistingthevaluesyouwantused,orbyspecifyingthatyou
wanttotryeveryvaluewithinagivenrange.Forexample,togiveaslidernamednumber
everyvaluefrom100to1000inincrementsof50,youwouldenter:
["number" [100 50 1000]]
Or,togiveitonlythevaluesof100,200,400,and800,youwouldenter:
["number" 100 200 400 800]
Becarefulwiththebracketshere.Notethattherearefewersquarebracketsinthesecond
example.IncludingornotincludingthisextrasetofbracketsishowyoutellBehaviorSpace
whetheryouarelistingindividualvalues,orspecifyingarange.
Alsonotethatthedoublequotesaroundthevariablenamesarerequired.
Youcanvaryasmanysettingsasyouwant,includingjustone,ornoneatall.Anysettings
thatyoudonotvarywillretaintheircurrentvalues.Notvaryinganysettingsisusefulifyou
justwanttodomanyrunswiththecurrentsettings.
Whatorderyoulistthevariablesindetermineswhatordertherunswillbedonein.Allvalues
foralatervariablewillbetriedbeforemovingtothenextvalueforanearliervariable.Sofor
exampleifyouvarybothxandyfrom1to3,andxislistedfirst,thentheorderofmodelruns
willbe:x=1y=1,x=1y=2,x=1y=3,x=2y=1,andsoon.
Repetitions:Sometimesthebehaviorofamodelcanvaryalotfromruntorunevenifthe
settingsdon’tchange,ifthemodelusesrandomnumbers.Ifyouwanttorunthemodelmore
thanonceateachcombinationofsettings,enterahighernumber.
Measurerunsusingthesereporters:Thisiswhereyouspecifywhatdatayouwantto
collectfromeachrun.Forexample,ifyouwantedtorecordhowthepopulationofturtlesrose
andfellduringeachrun,youwouldenter:
count turtles
Youcanenteronereporter,orseveral,ornoneatall.Ifyouenterseveral,eachreportermust
beonalinebyitself,forexample:
count frogs
count mice
count birds
Ifyoudon’tenteranyreporters,therunswillstilltakeplace.Thisisusefulifyouwantto
recordtheresultsyourselfyourownway,suchaswiththeexport-worldcommand.
Measurerunsateverystep:NormallyNetLogowillmeasuremodelrunsateverystep,
usingthereportersyouenteredinthepreviousbox.Ifyou’redoingverylongmodelruns,you
mightnotwantallthatdata.Uncheckthisboxifyouonlywanttomeasureeachrunafterit
ends.
Setupcommands:Thesecommandswillbeusedtobegineachmodelrun.Typically,you
willenterthenameofaprocedurethatsetsupthemodel,typicallysetup.Butitisalso
possibletoincludeothercommandsaswell.
Gocommands:Thesecommandswillberunoverandoveragaintoadvancetothemodel
tothenext“step”.Typically,thiswillbethenameofaprocedure,suchasgo,butyoumay
includeanycommandsyoulike.
Stopcondition:Thisletsyoudomodelrunsofvaryinglength,endingeachrunwhena
certainconditionbecomestrue.Forexample,supposeyouwantedeachruntolastuntilthere
werenomoreturtles.Thenyouwouldenter:
not any? turtles
Ifyouwantthelengthofrunstoallbeofafixedlength,justleavethisblank.
Therunmayalsostopbecausethegocommandsusethestopcommand,inthesameway
thatstopcanbeusedtostopaforeverbutton.Thestopcommandmaybeuseddirectlyinthe
gocommands,orinaprocedurecalleddirectlybythegocommands.(Theintentisthatthe
samegoprocedureshouldworkbothinabuttonandinaBehaviorSpaceexperiment.)Note
thatthestepinwhichstopisusedisconsideredtohavebeenaborted,sonoresultswillbe
recordedforthatstep.Therefore,thestoppingtestshouldbeatthebeginningofthego
commandsorprocedure,notattheend.
Finalcommands:Theseareanyextracommandsthatyouwantrunonce,whentherun
ends.Usuallythisisleftblank,butyoumightuseittocalltheexport-worldcommandor
recordtheresultsoftheruninsomeotherway.
Timelimit:Thisletsyousetafixedmaximumlengthforeachrun.Ifyoudon’twanttosetany
maximum,butwantthelengthoftherunstobecontrolledbythestopconditioninstead,enter
0.
SpecialprimitivesforBehaviorSpaceexperiments
Currentlythereareonlytwo,behaviorspace-run-numberandbehaviorspace-experiment-name.
Therunnumberreportedbytheformerprimitivematchestherunnumberusedintheresults
filesgeneratedbyBehaviorSpace.Theexperimentnamereportedbythelattermatchesthe
namewithwhichtheexperimentwassetup.
Runninganexperiment
Whenyou’redonesettingupyourexperiment,pressthe“OK”button,followedbythe“Run”
button.Adialogtitled“Runoptions”willappear.
Runoptions:formats
Therunoptionsdialogletsyouselecttheformatsyouwouldlikethedatafromyour
experimentsavedin.Dataiscollectedforeachrunorstep,accordingtothesettingof
Measurerunsateverystepoption.Ineithercase,theinitialstateofthesystemisrecorded,
afterthesetupcommandsrunbutbeforethegocommandsrunforthefirsttime.
Tableformatlistseachintervalinarow,witheachmetricinaseparatecolumn.Tabledatais
writtentotheoutputfileaseachruncompletes.Tableformatissuitableforautomated
processingofthedata,suchasimportingintoadatabaseorastatisticspackage.
Spreadsheetformatcalculatesthemin,mean,max,andfinalvaluesforeachmetric,andthen
listseachintervalinarow,witheachmetricinaseparatecolumn.Spreadsheetdataismore
human-readablethanTabledata,especiallyifimportedintoaspreadsheetapplication.
(Notehoweverthatspreadsheetdataisnotwrittentotheresultsfileuntiltheexperiment
finishes.Sincespreadsheetdataisstoredinmemoryuntiltheexperimentisdone,verylarge
experimentscouldrunoutofmemory.Soyoushoulddisablespreadsheetoutputunlessyou
reallywantit.Ifyoudowantspreadsheetoutput,notethatifanythinginterruptsthe
experiment,suchasaruntimeerror,runningoutofmemory,oracrashorpoweroutage,no
spreadsheetresultswillbewritten.Forlongexperiments,youmaywanttoalsoenabletable
formatasaprecautionsothatifsomethinghappensandyougetnospreadsheetoutputyou’ll
atleastgetpartialtableoutput.)
Afterselectingyouroutputformats,BehaviorSpacewillpromptyouforthenameofafileto
savetheresultsto.Thedefaultnameendsin“.csv”.Youcanchangeittoanynameyouwant,
butdon’tleaveoffthe“.csv”part;thatindicatesthefileisaCommaSeparatedValues(CSV)
file.Thisisaplain-textdataformatthatisreadablebyanytexteditoraswellasbymost
popularspreadsheetanddatabaseprograms.
Runoptions:parallelruns
Therunoptionsdialogalsoletsyouselectwhetheryouwantmultiplemodelrunstohappenin
parallel,andifso,howmanyareallowedtobesimultaneouslyactive.Thisnumberwilldefault
tothenumberofprocessorcoresinyourcomputer.
Thereareafewcautionsassociatedwithparallelruns.
First,ifmultiplerunsareactive,onlyoneofthemwillbeinthe“foreground”andcausethe
viewandplotstoupdate.Theotherrunswillhappeninvisiblyinthebackground.
Second,invisiblebackgroundrunscan’tuseprimitivesthatonlyworkintheGUI.For
example,abackgroundruncan’tmakeamovie.
Third,sinceparallelrunsprogressindependentlyofeachother,tableformatoutputmay
containinterleaved,out-of-orderresults.Whenyouanalyzeyourtabledata,youmaywishto
sortitbyrunnumberfirst.(Spreadsheetformatoutputisnotaffectedbythisissue,sinceitis
notwrittenuntiltheexperimentcompletesorisaborted.)
Fourth,usingallavailableprocessorcoresmaymakeyourcomputerslowtouseforother
taskswhiletheexperimentisrunning.
Fifth,doingrunsinparallelwillmultiplytheexperiment’smemoryrequirementsaccordingly.
YoumayneedtoincreaseNetLogo’smemoryceiling(seethisFAQentry).
Observingruns
Afteryoucompletetherunoptionsdialog,anotherdialogwillappear,titled“Running
Experiment”.Inthisdialog,you’llseeaprogressreportofhowmanyrunshavebeen
completedsofarandhowmuchtimehaspassed.Ifyouenteredanyreportersformeasuring
theruns,andifyouleftthe“Measurerunsateverystep”boxchecked,thenyou’llseeaplotof
howtheyvaryoverthecourseofeachrun.
YoucanalsowatchtherunsinthemainNetLogowindow.(Ifthe“RunningExperiment”dialog
isintheway,justmoveittoadifferentplaceonthescreen.)Theviewandplotswillupdateas
themodelruns.Ifyoudon’tneedtoseethemupdate,thenusethecheckboxesinthe
“RunningExperiment”dialogtoturntheupdatingoff.Thiswillmaketheexperimentgofaster.
Ifyouwanttostopyourexperimentbeforeit’sfinished,pressthe“Abort”button.Anyresults
generatedsofarwillstillbesaved.
Whenalltherunshavefinished,theexperimentiscomplete.
AdvancedUsage
Runningfromthecommandline
ItispossibletorunBehaviorSpaceexperiments“headless”,thatis,fromthecommandline,
withoutanygraphicaluserinterface(GUI).Thisisusefulforautomatingrunsonasingle
machineoraclusterofmachines.
NoJavaprogrammingisrequired.ExperimentsetupscanbecreatedintheGUIandthenrun
laterfromthecommandline,or,ifyouprefer,youcancreateoreditexperimentsetups
directlyusingXML.
Howtouseit
RunNetLogousingtheincludedcommandlinescript.Thisisfoundintherootdirectoryof
yourNetLogoinstallationandisnamednetlogo-headless.shonMacandLinuxandnetlogo-
headless.batonWindows.Thenetlogo-headlessscriptsupportsthefollowingarguments:
--model <path>:pathnameofmodeltoopen(required)
--setup-file <path>:readexperimentsetupsfromthisfileinsteadofthemodelfile
--experiment <name>:nameofexperimenttorun
--table <path>:pathnametosendtableoutputto(or-forstandardoutput)
--spreadsheet <path>:pathnametosendtableoutputto(or-forstandardoutput)
--threads <number>:usethismanythreadstodomodelrunsinparallel,or1todisable
parallelruns.defaultstoonethreadperprocessor.
--min-pxcor <number>:overrideworldsizesettinginmodelfile
--max-pxcor <number>:overrideworldsizesettinginmodelfile
--min-pycor <number>:overrideworldsizesettinginmodelfile
--max-pycor <number>:overrideworldsizesettinginmodelfile
--modelisrequired.Ifyoudon’tspecify--experiment,youmustspecify--setup-file.By
defaultnoresultsaregenerated,soyou’llusuallywanttospecifyeither--tableor--
spreadsheet,orboth.Ifyouspecifyanyoftheworlddimensions,youmustspecifyallfour.
Note:Theremainderofthisguideusesnetlogo-headless.shtorefertotheNetLogo
Headlesslaunchscript.IfyouareusingWindows,pleasesubstitutenetlogo-headless.batfor
netlogo-headless.shineachexample.
Examples
ItiseasiestifyoucreateyourexperimentsetupaheadoftimeintheGUI,soitissavedas
partofthemodel.Torunanexperimentsetupsavedinamodel,hereisanexample
commandline:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment1 \
--table -
Forthistowork,Java(version1.8orlater)mustbeavailable.YoucanmakeJavaavailableto
headlessineitheroftwoways
1. SettheJAVA_HOMEenvironmentvariabletothepathtotheJavainstallation.Thisisthe
directoryoftheJavainstallationwhichcontainsa“bin”directory.
2. AddthedirectorycontainingtheJavaexecutabletothePATHenvironmentvariable
IfJAVA_HOMEisdefined,netlogo-headlesswillrunNetLogousingtheJavathatitpointsto,
ignoringtheversionofJavaavailableonthepath.
Afterthenamedexperimenthasrun,theresultsaresenttostandardoutputintableformat,
asCSV.(“-”ishowyouspecifystandardoutputinsteadofoutputtoafile.)
Whenrunningnetlogoheadless,itforcesthesystempropertyjava.awt.headlesstobetrue.
ThistellsJavatoruninheadlessmode,allowingNetLogotorunonmachineswhena
graphicaldisplayisnotavailable.
Therequired--modelargumentisusedtospecifythemodelfileyouwanttoopen.
The--experimentargumentisusedtospecifythenameoftheexperimentyouwanttorun.
(AtthetimeyoucreateanexperimentsetupintheGUI,youassignitaname.)
Here’sanotherexamplethatshowssomeadditional,optionalarguments:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment2 \
--max-pxcor 100 \
--min-pxcor -100 \
--max-pycor 100 \
--min-pycor -100
Notetheuseoftheoptional--max-pxcor,--max-pycor,etc.argumentstospecifyadifferent
worldsizethanthatsavedinthemodel.(It’salsopossiblefortheexperimentsetuptospecify
valuesfortheworlddimensions;iftheyarespecifiedbytheexperimentsetup,thenthereis
noneedtospecifythemonthecommandline.)
Sinceneither--tablenor--spreadsheetisspecified,noresultswillbegenerated.Thisis
usefuliftheexperimentsetupgeneratesalltheoutputyouneedbysomeothermeans,such
asexportingworldfilesorwritingtoatextfile.
Yetanotherexample:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment2 \
--table table-output.csv \
--spreadsheet spreadsheet-output.csv
Theoptional--table <filename>argumentspecifiesthatoutputshouldbegeneratedina
tableformatandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,than
theoutputissenttothestandardsystemoutputstream.Tabledataiswrittenasitis
generated,witheachcompleterun.
Theoptional--spreadsheet <filename>argumentspecifiedthatspreadsheetoutputshould
begeneratedandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,than
theoutputissenttothestandardsystemoutputstream.Spreadsheetdataisnotwrittenout
untilallrunsintheexperimentarefinished.
Notethatitislegaltospecifyboth--tableand--spreadsheet,andifyoudo,bothkindsof
outputfilewillbegenerated.
Hereisonefinalexamplethatshowshowtorunanexperimentsetupwhichisstoredina
separateXMLfile,insteadofinthemodelfile:
netlogo-headless.sh \
--model Fire.nlogo \
--setup-file fire-setups.xml \
--experiment experiment3
IftheXMLfilecontainsmorethanoneexperimentsetup,itisnecessarytousethe--
experimentargumenttospecifythenameofthesetuptouse.
InordertorunaNetLogo3Dexperiment,runheadlesswiththe--3Dargument,forexample:
netlogo-headless.sh \
--3D \
--model "Mousetraps 3D.nlogo3d" \
--experiment experiment1 \
--table -
Notethatyoushouldsupplya3Dmodelandtherearealso3Darguments--max-pzcor
<number>and--min-pzcor <number>.
Thenextsectionhasinformationonhowtocreatestandaloneexperimentsetupfilesusing
XML.
SettingupexperimentsinXML
Wedon’tyethavedetaileddocumentationonauthoringexperimentsetupsinXML,butifyou
alreadyhavesomefamiliaritywithXML,thenthefollowingpointersmaybeenoughtogetyou
started.
ThestructureofBehaviorSpaceexperimentsetupsinXMLisdeterminedbyaDocument
TypeDefinition(DTD)file.TheDTDisstoredinNetLogo.jar,assystem/behaviorspace.dtd.
(JARfilesarealsozipfiles,soyoucanextracttheDTDfromtheJARusingJava’s“jar”utility
orwithanyprogramthatunderstandszipformat.)
TheeasiestwaytolearnwhatsetupslooklikeinXML,though,istoauthorafewofthemin
BehaviorSpace’sGUI,savethemodel,andthenexaminetheresulting.nlogofileinatext
editor.Theexperimentsetupsarestoredtowardstheendofthe.nlogofile,inasectionthat
beginsandendswithaexperimentstag.Example:
<experiments>
<experiment name="experiment" repetitions="10" runMetricsEveryStep="true">
<setup>setup</setup>
<go>go</go>
<exitCondition>not any? fires</exitCondition>
<metric>burned-trees</metric>
<enumeratedValueSet variable="density">
<value value="40"/>
<value value="0.1"/>
<value value="70"/>
</enumeratedValueSet>
</experiment>
</experiments>
Inthisexample,onlyoneexperimentsetupisgiven,butyoucanputasmanyasyouwant
betweenthebeginningandendingexperimentstags.
BetweenlookingattheDTD,andlookingatexamplesyoucreateintheGUI,itwillhopefully
beapparenthowtousethetagstospecifydifferentkindofexperiments.TheDTDspecifies
whichtagsarerequiredandwhichareoptional,whichmayberepeatedandwhichmaynot,
andsoforth.
WhenXMLforexperimentsetupsisincludedinamodelfile,itdoesnotbeginwithanyXML
headers,becausenotthewholefileisXML,onlypartofit.Ifyoukeepexperimentsetupsin
theirownfile,separatefromthemodelfile,thentheextensiononthefileshouldbe.xmlnot
.nlogo,andyou’llneedtobeginthefilewithproperXMLheaders,asfollows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE experiments SYSTEM "behaviorspace.dtd">
Thesecondlinemustbeincludedexactlyasshown.Inthefirstline,youmayspecifya
differentencodingthanUTF-8,suchasISO-8859-1.
AdjustingJVMParameters
OpeningtheNetLogoHeadlesslauncherscriptwillshowtheoptionsusedtolaunchjava
whenrunningNetLogoHeadless.YoucanadjustvariousJVMparametersinthisscript.You
mayalsopassinJavapropertiesstartingwith-Dtothelauncher.
Notetheuseof-Xmxtospecifyamaximumheapsizeofonegigabyte.Ifyoudon’tspecifya
maximumheapsize,youwillgetyourVM’sdefaultsize,whichmaybeunusablysmall.(One
gigabyteisanarbitrarysizewhichshouldbemorethanlargeenoughformostmodels;you
canspecifyadifferentlimitifyouwant.)
Notetheuseof-Dfile.encoding=UTF-8.ThisforcesallfileI/OtouseUTF-8encoding.Doing
soensuresthatNetLogocanloadallmodelsconsistently,andthatfile-*primitiveswork
consistentlyonallplatforms,includingmodelscontainingUnicodecharacters.
ControllingAPI
IfBehaviorSpaceisnotsufficientforyourneeds,apossiblealternativeistouseour
ControllingAPI,whichletsyouwriteJavacodethatcontrolsNetLogo.TheAPIletsyourun
BehaviorSpaceexperimentsfromJavacode,or,youcanwritecustomcodethatcontrols
NetLogomoredirectlytodoBehaviorSpace-likethings.SeetheControllingsectionofthe
UserManualforfurtherdetailsonbothpossibilities.
SystemDynamicsGuide
NetLogo6.0.4UserManual
Thisguidehasthreeparts:
WhatistheSystemDynamicsModeler?:Ageneraldescriptionofthetool,includingtheideasand
principlesbehindit.
HowItWorks:Describestheinterfaceandhowyouuseit.
Tutorial:Wolf-SheepPredation(aggregate):WalksyouthroughcreatingamodelwiththeSystem
DynamicsModeler.
WhatistheNetLogoSystemDynamicsModeler?
SystemDynamicsisatypeofmodelingwhereyoutrytounderstandhowthingsrelatetooneanother.Itisalittle
differentfromtheagent-basedapproachwenormallyuseinNetLogomodels.
Withtheagent-basedapproachweusuallyuseinNetLogo,youprogramthebehaviorofindividualagentsand
watchwhatemergesfromtheirinteraction.InamodelofWolf-SheepPredation,forexample,youproviderules
forhowwolves,sheepandgrassinteractwitheachother.Whenyourunthesimulation,youwatchtheemergent
aggregate-levelbehavior:forexample,howthepopulationsofwolvesandsheepchangeovertime.
WiththeSystemDynamicsModeler,youdon’tprogramthebehaviorofindividualagents.Instead,youprogram
howpopulationsofagentsbehaveasawhole.Forexample,usingSystemDynamicstomodelWolf-Sheep
Predation,youspecifyhowthetotalnumberofsheepwouldchangeasthetotalnumberofwolvesgoesupor
down,andviceversa.Youthenrunthesimulationtoseehowbothpopulationschangeovertime.
TheSystemDynamicsModelerallowsyoutodrawadiagramthatdefinesthesepopulations,or“stocks”,and
howtheyaffecteachother.TheModelerreadsyourdiagramandgeneratestheappropriateNetLogocode–
globalvariables,proceduresandreporters–torunyourSystemDynamicsmodelinsideofNetLogo.
BasicConcepts
ASystemDynamicsdiagramismadeoffourkindsofelements:Stocks,Variables,FlowsandLinks.
AStockisacollectionofstuff,anaggregate.Forexample,aStockcanrepresentapopulationofsheep,the
waterinalake,orthenumberofwidgetsinafactory.
AFlowbringsthingsinto,oroutofaStock.Flowslooklikepipeswithafaucetbecausethefaucetcontrolshow
muchstuffpassesthroughthepipe.
AVariableisavalueusedinthediagram.ItcanbeanequationthatdependsonotherVariables,oritcanbea
constant.
ALinkmakesavaluefromonepartofthediagramavailabletoanother.Alinktransmitsanumberfroma
VariableoraStockintoaStockoraFlow.
TheSystemDynamicsModelerfiguresouthowthevalueofyourStockschangeovertimebyestimatingthem
overandover.Theestimationisn’talwaysperfect,butyoucanaffectitsaccuracybychangingthevalueofdt.As
dtdecreases,youestimatethemodelmorefrequently,soitgetsmoreaccurate.However,decreasingdtalso
makesthemodelslower.
SampleModels
TherearefourbasicmodelsintheSampleModelssectionoftheNetLogoModelsLibrarythatdemonstratethe
useoftheSystemDynamicsModeler.Allfourbasicmodelsexplorepopulationgrowth(and,inmodelswith
predation,populationdecline).
ExponentialGrowthandLogisticGrowtharesimpleexamplesofgrowthinonestock.
WolfSheepPredation(SystemDynamics)isanexampleofasystemwithmultiplestocksinfluencingone
another.Itmodelsapredator-preyecosystemusingtheSystemDynamicsModeler.
WolfSheepPredation(DockedHybrid)isanexampleofamodelthatrunsboththeaSystemDynamicsmodel
andanagent-basedmodelside-by-side.ItrunstheSystemDynamicsimplementationofWolf-SheepPredation
nexttotheagent-basedWolfSheepPredationmodelfromtheBiologysectionofSampleModels.
HowitWorks
ToopentheSystemDynamicsModeler,choosetheSystemDynamicsModeleritemintheToolsmenu.The
SystemDynamicsModelerwindowwillappear.
DiagramTab
TheDiagramtabiswhereyoudrawyourSystemDynamicsdiagram.
Thetoolbarcontainsbuttonstoedit,deleteandcreateitemsinyourdiagram.
CreatingDiagramElements
ASystemDynamicsdiagramismadeupoffourkindsofcomponents:Stocks,Variables,FlowsandLinks.
Stock
TocreateaStock,presstheStockbuttoninthetoolbarandclickinthediagramareabelow.AnewStock
appears.EachStockrequiresauniquename,whichbecomesaglobalvariable.Stocksalsorequirean
**Initialvalue**.Itcanbeanumber,avariable,acomplexNetLogoexpression,oracalltoaNetLogo
reporter.
Variable
TocreateaVariable,presstheVariablebuttonandclickonthediagram.EachVariableintheSystem
DynamicsModelrequiresauniquename,whichbecomesthenameofaprocedure,oraglobalvariable.
Variablesalsorequirean**Expression**.Thisexpressioncanbeanumber,avariable,acomplexNetLogo
expression,oracalltoaNetLogoreporter.
Flow
TocreateaFlow,presstheFlowbutton.ClickandholdwhereyouwanttheFlowtobegin--eitherona
Stockorinanemptyarea--anddragthemousetowhereyouwanttheFlowtoend--onaStockorinan
emptyarea.EachFlowrequiresauniquename,whichbecomesaNetLogoreporter.Flowsrequirean
**Expression**,whichistherateofflowfromtheinputtotheoutput.Thisexpressioncanbeanumber,a
variable,acomplexNetLogoexpression,oracalltoaNetLogoreporter.Ifthevalueisnegative,theflowis
intheoppositedirection.
WhenmorethanoneFlowisconnectedtoaStock,itisimportanttoconsiderhowtheyshouldinteractwith
oneanother.NetLogowillnotenforcethattheFlowsoutofastockoccurinanyparticularorder.Also,
NetLogowillnotensurethatthesumofFlowsoutofaStockarelessthanorequaltothevalueofthe
Stock.ThesebehaviorscanbeimplementedexplicitlywhencreatingtheExpressionforaFlow.
Forexample,iftheFlowisdefinedasaconstantvalue,10,youcanensureitneverdrawsmorethanthe
valueoftheStockbyusingtheminprimitive:min (list stock 10).IfIwantFlowAtodepleteaStock
beforeFlowBiscalculated,IcanlinkFlowAtoFlowBandmodifyFlowBtosubtractFlowA’svaluefrom
thestock:min (list (max (list 0 (stock - flow-a))) 10).
Link
TocreateaLink,clickandholdonthestartingpointforthelink--aVariable,StockorFlow--anddragthe
mousetothedestinationVariableorFlow.
WorkingwithDiagramElements
WhenyoucreateaStock,Variable,orFlow,youseearedquestion-markontheelement.Thequestion-mark
indicatesthattheelementdoesn’thaveanameyet.TheredcolorindicatesthattheStockisincomplete:it’s
missingoneormorevaluesrequiredtogenerateaSystemDynamicsmodel.Whenadiagramelementis
complete,thenameturnsblack.
Selecting:Toselectadiagramelement,clickonit.Toselectmultipleelements,holdtheshiftkey.Youcanalso
selectoneormoreelementsbydraggingaselectionbox.
Editing:Toeditadiagramelement,selecttheelementandpressthe“Edit”buttononthetoolbar.Orjustdouble-
clicktheelement.(YoucaneditStocks,FlowsandVariables,butyoucan’teditLinks).
Moving:Tomoveadiagramelement,selectitanddragthemousetoanewlocation.
Editingdt
Ontherightsideofthetoolbaristhedefaultdt,theintervalusedtoapproximatetheresultsofyourSystem
Dynamicsmodel.Tochangethevalueofthedefaultdtforyouraggregatemodel,presstheEditbuttonnextto
thedtdisplayandenteranewvalue.
Errors
Whenyouclickthe“check”buttonorwhenyoueditastock,flow,orvariablethemodelerwillautomatically
generatetheNetLogocodethecorrespondstoyourdiagramandtrytocompilethatcode.Ifthereisanerrorthe
Codetabwillturnredandamessagewillappear,andtheportionofthegeneratedcodethatiscausingthe
troublewillbehighlighted.
Thisshouldgiveyouabetterideawhichelementinthediagramiscausingtheproblem.
CodeTab
TheSystemDynamicsModelergeneratesNetLogovariablesandproceduresbasedonthecontentsofyour
diagram.Theseproceduresarewhatmakethediagramactuallyperformcalculations.TheCodetabinthe
SystemDynamicsModelerwindowdisplaystheNetLogoproceduresgeneratedfromyourdiagram.
Youcan’teditthecontentsoftheCodetab.TomodifyyourSystemDynamicsmode,editthediagram.
Let’stakeacloserlookathowthegeneratedcoderelatestothediagram:
Stockscorrespondtoaglobalvariablethatisinitializedtothevalueorexpressionyouprovidedinthe
Initialvaluefield.EachStockwillbeupdatedeverystepbasedontheFlowsinandout.
FlowscorrespondtoaprocedurethatcontainstheexpressionyouprovidedintheExpressionfield.
Variablescaneitherbeglobalvariablesorprocedures.IftheExpressionyouprovidedisaconstantitwill
beaglobalvariableandinitializedtothatvalue.IfyouusedamorecomplicatedExpressiontodefinethe
VariableitwillcreateaprocedurelikeaFlow.
ThevariablesandproceduresdefinedinthistabareaccessibleinthemainNetLogowindow,justlikethe
variablesandproceduresyoudefineyourselfinthemainNetLogoCodetab.Youcancalltheproceduresfrom
themainCodetab,fromtheCommandCenter,orfrombuttonsintheInterfacetab.Youcanrefertotheglobal
variablesanywhere,includinginthemainCodetabandinmonitors.
Therearethreeimportantprocedurestonotice:system-dynamics-setup,system-dynamics-go,andsystem-
dynamics-do-plot.
system-dynamics-setupinitializestheaggregatemodel.Itsetsthevalueofdt,callsreset-ticks,andinitializes
yourstocksandyourconverters.Converterswithaconstantvalueareinitializedfirst,followedbythestockswith
constantvalues.Theremainingstocksareinitializedinalphabeticalorder.
system-dynamics-gorunstheaggregatemodelfordttimeunits.ItcomputesthevaluesofFlowsandVariables
andupdatesthevalueofStocks.Italsocallstick-advancewiththevalueofdt.ConvertersandFlowswithnon-
constantExpressionswillbecalculatedonlyoncewhenthisprocedureiscalled,however,theirorderof
evaluationisundefined
system-dynamics-do-plotplotsthevaluesofStocksintheaggregatemodel.Tousethis,firstcreateaplotinthe
mainNetLogowindow.YouthenneedtodefineaplotpenforeachStockyouwanttobeplotted.Thisprocedure
willusethecurrentplot,whichyoucanchangeusingtheset-current-plotcommand.
TheSystemDynamicsModelerandNetLogo
ThediagramyoucreatewiththeSystemDynamicsModeler,andtheproceduresgeneratedfromyourdiagram,
arepartofyourNetLogomodel.WhenyouasavetheNetLogomodel,yourdiagramissavedwithit,inthesame
file.
Tutorial:Wolf-SheepPredation
Let’screateamodelofWolf-SheepPredationwiththeSystemDynamicsModeler.
Step1:SheepReproduction
OpenanewmodelinNetLogo.
LaunchtheSystemDynamicsModelerintheToolsmenu.
Ourmodelwillhaveapopulationofwolvesandapopulationofsheep.Let’sstartwiththesheep.First,createa
StockthatholdsapopulationofSheep.
PresstheStockbuttoninthetoolbar.
Clickinthediagramarea.
YouseeaStockwitharedquestion-markinthemiddle.
Double-clicktheStocktoedit.
Namethestocksheep
Settheinitialvalueto100.
DeselecttheAllowNegativeValuescheckbox.Itdoesn’tmakesensetohavenegativesheep!
Oursheeppopulationcanincreaseifnewsheepareborn.Toaddthistoourdiagram,wecreateaFlowintothe
stockofsheep.
ClickontheFlowbuttoninthetoolbarandpressthemousebuttoninanemptyareatotheleft
ofthesheepStock.DragtheFlowtotherightuntilitconnectstothesheepStockandletgo.
EdittheFlowandnameitsheep-births.
Fornow,enteraconstant,suchas1,intotheExpressionfield.
Thenumberofsheepbornduringaperiodoftimedependsonthenumberofsheepthatarealive:moresheep
meansmorereproduction.
DrawaLinkfromthesheepStocktothesheep-birthsFlow.
Therateofsheepbirthsalsodependsonsomeconstantfactorsthatarebeyondthescopeofthismodel:the
rateofreproduction,etc.
CreateaVariableandnameitsheep-birth-rate.Setitsvalueto0.04.
DrawaLinkfromthesheep-birth-rateVariabletothesheep-births.
Yourdiagramshouldlooksomethinglikethis:
Ourdiagramhasthecorrectstructurebutwearen’tyetfinishedbecauseittheamountofsheepflowingintothe
stockdoesn’tdependuponthenumberofsheepandsheepbirthrate.
Editthesheep-birthsFlowandsettheexpressiontosheep-birth-rate * sheep.
Wenowhaveacompletediagram.ToseetheNetLogocodegeneratedbyourdiagram,youcanclickonthe
CodetaboftheSystemDynamicsModelerwindow.Itlookslikethis:
Step2:NetLogoIntegration
OnceyoucreateanaggregatemodelwiththeSystemDynamicsModeler,youcaninteractwiththemodel
throughthemainNetLogointerfacewindow.Let’sbuildourNetLogomodeltorunthecodegeneratedbyour
diagram.We’llneedasetupandgobuttonswhichcallthesystem-dynamics-setupandsystem-dynamics-go
procedurescreatedbytheSystemDynamicsModeler.Andwe’llwantamonitorandaplottowatchthechanges
insheeppopulation.
SelectthemainNetLogowindow
IntheCodetab,write:
to setup
ca
system-dynamics-setup
end
to go
system-dynamics-go
system-dynamics-do-plot
end
MovetotheInterfacetab
Createasetupbutton
Createagobutton(don’tforgettomakeitforever)
Createasheepmonitor.
Createaplotcalled“populations”withapennamed“sheep”.
Nowwe’rereadytorunourmodel.
Pressthesetupbutton.
Don’tpressthe“go”buttonyet.Instead,typegofourorfivetimesintotheCommandCenter.
Noticewhathappens.Thesheeppopulationincreasesexponentially.Afterfourorfiveiterations,wehavean
enormousnumberofsheep.That’sbecausewehavesheepreproduction,butoursheepneverdie.
Tofixthat,let’sfinishourdiagrambyintroducingapopulationofwolveswhicheatsheep.
Step3:WolfPredation
MovebacktotheSystemDynamicswindow
Addastockofwolves
AddFlows,VariablesandLinkstomakeyourdiagramlooklikethis:
AddonemoreFlowfromthewolvesStocktotheFlowthatgoesoutoftheSheepstock.
Fillinthenamesofthediagramelementssoitlookslikethis:
where
initial-valueofwolvesis30,
wolf-deathsiswolves * wolf-death-rate,
wolf-death-rateis0.15,
predator-efficiencyis.8,
wolf-birthsiswolves * predator-efficiency * predation-rate * sheep ,
predation-rateis3.0E-4,
andsheep-deathsissheep * predation-rate * wolves.
Adjustthedtofthesystemdynamicsmodelbyselecting“Edit”nexttodtinthetoolbarofthe
systemdynamicsmodeler.Inthedialogthatappears,enter0.01.
Nowwe’rereallydone.
GobacktothemainNetLogowindow
Addaplotpennamed“wolves”tothepopulationplot
PresssetupandgotoseeyourSystemDynamicsModelerdiagraminaction.
Youseeaplotofthepopulationsthatlookslikethis:
HubNetGuide
NetLogo6.0.4UserManual
ThissectionoftheUserManualintroducestheHubNetsystemandincludesinstructionsto
setupandrunaHubNetactivity.
HubNetisatechnologythatletsyouuseNetLogotorunparticipatorysimulationsinthe
classroom.Inaparticipatorysimulation,awholeclasstakespartinenactingthebehaviorofa
systemaseachstudentcontrolsapartofthesystembyusinganindividualdevice,suchasa
networkedcomputer.
Forexample,intheGridlocksimulation,eachstudentcontrolsatrafficlightinasimulatedcity.
Theclassasawholetriestomaketrafficflowefficientlythroughthecity.Asthesimulation
runs,dataiscollectedwhichcanafterwardsbeanalyzedonacomputer.
Formoreinformationonparticipatorysimulationsandtheirlearningpotential,pleasevisitthe
ParticipatorySimulationsProjectwebsite.
UnderstandingHubNet
NetLogo
NetLogoisaprogrammablemodelingenvironment.Itcomeswithalargelibraryofexisting
simulations,bothparticipatoryandtraditional,thatyoucanuseandmodify.Contentareas
includesocialscienceandeconomics,biologyandmedicine,physicsandchemistry,and
mathematicsandcomputerscience.Youandyourstudentscanalsouseittobuildyourown
simulations.
IntraditionalNetLogosimulations,thesimulationrunsaccordingtorulesthatthesimulation
authorspecifies.HubNetaddsanewdimensiontoNetLogobylettingsimulationsrunnotjust
accordingtorules,butbydirecthumanparticipation.
SinceHubNetbuildsuponNetLogo,werecommendthatbeforetryingHubNetforthefirst
time,youbecomefamiliarwiththebasicsofNetLogo.TogetstartedusingNetLogomodels,
seeTutorial#1:RunningModelsintheNetLogoUsersManual.
HubNetArchitecture
HubNetsimulationsarebasedonaclient/serverarchitecture.Theactivityleaderusesthe
NetLogoapplicationtorunaHubNetactivity.WhenNetLogoisrunningaHubNetactivity,we
refertoitasaHubNetserver.Participantsuseaclientapplicationtologinandinteractwith
theHubNetserver.
WhileHubNetisonlysupportedviatheJavaDesktopclientsatthemoment,wehopetoadd
supportforothertypesofclientssuchastabletsandphonesinthefuture.
ComputerHubNet
Activities
ThefollowingactivitiesareavailableintheModelsLibrary,intheHubNetActivitiesfolder.
InformationonhowtorunthemodelsandactivitiescanbefoundintheInfotabofeach
model.Additionaldiscussionofeducationalgoalsandwaystoincorporatemanyofthe
activitiesintoyourclassroomintheParticipatorySimulationsGuideontheParticipatory
SimulationsProjectwebsite.
BugHuntersCamouflage-studentshuntbugsandcamouflagingemerges.
DiceStalagmiteHubNet-studentsrolldiceandexplorethespaceofdependentand
independentevents.
Disease-Adiseasespreadsthroughthesimulatedpopulationofstudents.
DiseaseDoctors-AslightmodificationtotheDiseaseactivitywheresomestudentscan
recoverfromthedisease.
Gridlock-Studentsusetrafficlightstocontroltheflowoftrafficthroughacity.
Polling-Askstudentsquestionsandplottheiranswers.
RootBeerGame-AnadaptationofapopulargamecreatedatMITintheearly1960s
thatshowshowsmalldelaysinadistributionsystemcancreatebigproblems.
Sampler-Studentsengageinstatisticalanalysisasindividualsandasaclassroom.
Throughtheseactivities,studentsdiscoverthemeaninganduseofbasicconceptsin
statistics.
TragedyoftheCommons-Studentsworkasfarmerssharingacommonresource.
Clients
TousetheclientapplicationyousimplyneedtolaunchtheHubNetclientapplicationthatis
bundledwithNetLogo.
Requirements
TouseComputerHubNet,youneedanetworkedcomputerwithNetLogoinstalledforthe
server.Whenusingtheclientapplicationyouwillalsoneedanetworkedcomputerwith
NetLogoinstalledforeachparticipant.Whenusinginclassroomsettingswealsosuggestan
attachedprojectorfortheleadertoprojecttheentiresimulationtotheparticipants.
Startinganactivity
You’llfindtheHubNetactivitiesinNetLogo’sModelsLibrary,intheHubNetActivitiesfolder.
Wesuggestdoingafewpracticerunsofanactivitybeforetryingitinfrontofaclass.
OpenaComputerHubNetmodel.NetLogowillpromptyoutoenterthenameofyournew
HubNetsession.Thisisthenamethatparticipantswillusetoidentifythisactivity.Youmay
alsoseeabroadcastnetworkselectiondropdownforwhichmoreextensivedocumentationis
availableintheFAQ.Fornow,justenteranameandpressStart.
NetLogowillopentheHubNetControlCenter,whichletsyouinteractwiththeHubNetserver.
You,astheleader,shouldthennotifyeveryonethattheymayjoin.Tojointheactivity,
participantslaunchtheHubNetClientapplicationandentertheirname.Theyshouldseeyour
activitylistedandcanjoinyouractivitybyselectingitandpressingEnter.Iftheactivityyou
startedisnotlistedthestudentcanentertheserveraddressmanuallywhichcanbefoundin
theHubNetControlCenter.
HubNetControlCenter
TheHubNetControlCenterletsyouinteractwiththeHubNetserver.Itdisplaysthename,
activity,addressandportnumberofyourserver.The“Mirror2DViewonclients”checkbox
controlswhethertheHubNetparticipantscanseetheviewontheirclients,assumingthereis
aviewintheclientsetup.The“Mirrorplotsonclients”checkboxcontrolswhetherparticipants
willreceiveplotinformation.
Theclientlistontherightdisplaysthenamesofclientsthatarecurrentlyconnectedtoyou
activity.Toremoveaparticipantfromtheactivity,selecttheirnameinthelistandpressthe
Kickbutton.TolaunchyourownHubNetclientpresstheLocalbutton,thisisparticularly
usefulwhenyouaredebugginganactivity.The“Reset”buttonkicksoutallcurrentlyloggedin
clientsandreloadstheclientinterface.
ThelowerpartoftheControlCenterdisplaysmessageswhenaparticipantjoinsorleavesthe
activity.Tobroadcastamessagetoalltheparticipants,clickonthefieldatthebottom,type
yourmessageandpressBroadcastMessage.
Troubleshooting
IstartedaHubNetactivity,butwhenparticipantsopenaHubNetClient,my
activityisn’tlisted.
Onsomenetworks,theHubNetClientcannotautomaticallydetectaHubNetserver.Tellyour
participantstomanuallyentertheserveraddressandportofyourHubNetserver,which
appearintheHubNetControlCenter.
Note:Thetechnicaldetailsonthisareasfollows.Inorderfortheclienttodetecttheserver,
multicastroutingmustbeavailablebetweenthem.Notallnetworkssupportmulticastrouting.
Inparticular,networksthatusetheIPsecprotocoltypicallydonotsupportmulticast.The
IPsecprotocolisusedonmanyVirtualPrivateNetworks(VPNs).
Whenaparticipanttriestoconnecttoanactivity,nothinghappens(theclient
appearstohangorgivesanerrorsayingthatnoserverwasfound).
Ifyourcomputerornetworkhasafirewall,itmaybeimpedingtheHubNetserverfrom
communicating.Makesurethatyourcomputerandnetworkarenotblockingportsusedby
theHubNetserver(ports9173-9180).
TheviewontheHubNetclientisgray.
Verifythatthe“Mirror2Dviewonclients”checkboxintheHubNetControlCenteris
selected.
Makesurethatthedisplayswitchinthemodelison.
Ifyouhavemadechangestothesizeoftheviewontheserveryoumayneedtopress
the“Reset”buttonintheControlCentertoensuretheclientsgetthenewsize.
ThereisnoviewontheHubNetclient.
Someactivitiesdon’thaveaviewontheclient.Ifyouwanttoaddaviewsimplyselect
“HubNetClientEditor”fromtheToolsMenuandaddaviewlikeanyotherwidget.Makesure
topressthe“Reset”buttonbeforehavingclientslogin.
Ican’tquitaHubNetclient.
Youwillhavetoforcetheclienttoquit.OnOSX,forcequittheapplicationbyselectingForce
Quit…intheApplemenu.OnWindows,pressCtrl-Alt-DeletetoopentheTaskManager,
selectHubNetClientandpressEndTask.
MycomputerwenttosleepwhilerunningaHubNetactivity.WhenIwokethe
computerup,IgotanerrorandHubNetwouldn’tworkanymore.
TheHubNetservermaystopworkingifthecomputergoestosleep.Ifthishappens,quitthe
NetLogoapplicationandstartover.Changethesettingsonyourcomputersoitwon’tsleep
again.
Myproblemisnotaddressedonthispage.
SeeContactingUs.
KnownLimitations
IfHubNetmalfunctions,seethebugreportinginformationatContactingUs.
Pleasenotethat:
HubNethasnotyetbeenextensivelytestedwithlargenumbersofclients(i.e.more
thanabout25).Unexpectedresultsmayoccurwithmoreclients.
Out-of-memoryconditionsarenothandledgracefully
Sendinglargeamountsofplottingmessagestotheclientscantakealongtime.
NetLogodoesnothandlemaliciousclientsinarobustmanner(inotherwords,itislikely
vulnerabletodenial-of-servicetypeattacks).
Performancedoesnotdegradegracefullyoversloworunreliablenetworkconnections.
Ifyouareonawirelessnetworkorsub-LAN,theIPaddressintheHubNetControl
CenterisnotalwaystheentireIPaddressoftheserver.
ComputerHubNethasonlybeentestedonLANs,andnotondial-upconnectionsor
WANs.
Teacherworkshops
ForinformationonupcomingworkshopsandNetLogoandHubNetuseintheclassroom,
pleasecontactus.
HubNetAuthoringGuide
TolearnaboutauthoringormodifyingHubNetactivities,seetheHubNetAuthoringGuide.
RunningHubNetinheadlessmode
TolearnaboutrunningHubNetactivitiesfromthecommandline,withnoGUIontheserver,
seetheHubNetsectionintheControllingGuide.
Gettinghelp
IfyouhaveanyquestionsaboutHubNetorneedhelpgettingstarted,contactus.
HubNetAuthoringGuide
NetLogo6.0.4UserManual
ThisguideshowshowtounderstandandmodifythecodeofexistingHubNetactivitiesand
writeyourownnewones.ItassumesyouarefamiliarwithrunningHubNetactivities,basic
NetLogocodeandNetLogointerfaceelements.FormoregeneralinformationaboutHubNet
seetheHubNetGuide.
CodingHubNetactivities
ManyHubNetactivitieswillsharebitsofthesamecode.Thatisthecodethatitusedtosetup
thenetworkandthecodethatisusedtoreceiveinformationfromandsendinformationtothe
clients.Ifyouunderstandthiscodeyoushouldbeabletoeasilymakemodificationsto
existingactivitiesandyoushouldhaveagoodstartonwritingyourownactivities.Togetyou
startedwehaveprovidedaTemplatemodel(inHubNetActivities->CodeExamples)that
containsthemostbasiccomponentsthatwillbeinthemajorityofHubNetactivities.You
shouldbeabletousethisactivityasastartingpointformostprojects.
CodeExample:Template
Setup
TomakeaNetLogomodelintoaHubNetactivityyoumustfirstinitializethenetwork.Inmost
HubNetactivitiesyouwillusethestartupproceduretoinitializethenetwork.startupisa
specialprocedurethatNetLogorunsautomaticallywhenyouopenanymodel.Thatmakesita
goodplacetoputcodethatyouwanttorunonceandonlyonce(nomatterhowmanytimes
theuserrunsthemodel).ForHubNetweputthecommandthatinitializesthenetworkin
startupbecauseoncethenetworkissetupwedon’tneedtodosoagain.Weinitializethe
systemusinghubnet-reset,whichwillasktheuserforasessionnameandopenupthe
HubNetControlCenter.Hereisthestartupprocedureinthetemplatemodel:
to startup
hubnet-reset
end
Nowthatthenetworkisallsetupyoudon’tneedtoworryaboutcallinghubnet-resetagain.
Takealookatthesetupprocedureinthetemplatemodel:
to setup
cp
cd
clear-output
ask turtles
[
set step-size 1
hubnet-send user-id "step-size" step-size
]
end
Forthemostpartitlookslikemostothersetupprocedures,however,youshouldnoticethatit
doesnotcallclear-all.Inthismodel,andinthegreatmajorityofHubNetactivitiesinthe
ModelsLibrary,wehaveabreedofturtlesthatrepresentthecurrentlyloggedinclients.Inthis
casewe’vecalledthisbreedstudents.Wheneveraclientlogsinwecreateastudentand
recordanyinformationwemightneedlateraboutthatclientinaturtlevariable.Sincewedon’t
wanttorequireuserstologoutandlogbackineverytimewesetuptheactivitywedon’twant
tokillalltheturtles,instead,wewanttosetallthevariablesbacktoinitialvaluesandnotify
theclientsofanychangeswemake(moreonthatlater).
Receivingmessagesfromclients
DuringtheactivityyouwillbetransferringdatabetweentheHubNetclientsandtheserver.
MostHubNetactivitieswillcallaprocedureinthegoloopthatchecksfornewmessagesfrom
clientsinthiscaseit’scalledlistenclients:
to listen-clients
while [ hubnet-message-waiting? ]
[
hubnet-fetch-message
ifelse hubnet-enter-message?
[ create-new-student ]
[
ifelse hubnet-exit-message?
[ remove-student ]
[ execute-command hubnet-message-tag ]
]
]
end
Aslongastherearemessagesinthequeuethisloopfetcheseachmessageoneatatime.
hubnet-fetch-messagemakesthenextmessageinthequeuethecurrentmessageandsets
thereportershubnet-message-source,hubnet-message-tagandhubnet-messagetothe
appropriatevalues.Theclientssendmessageswhentheusersloginandlogoutanytimethe
usermanipulatesoneoftheinterfaceelements,thatis,pushesabutton,movesaslider,
clicksintheview,etc.Westepthrougheachmessageanddecidewhatactiontotake
dependingonthetypeofmessage(enter,exit,orother),thehubnet-message-tag(thename
oftheinterfaceelement),andthehubnet-message-sourceofthemessage(thenameofthe
clientthemessagecamefrom).
Onanentermessagewecreateaturtlewithauser-idthatmatchesthehubnet-message-
sourcewhichisthenamethateachuserentersuponenteringtheactivity,itisguaranteedto
beunique.
to create-new-student
create-students 1
[
set user-id hubnet-message-source
set label user-id
set step-size 1
send-info-to-clients
]
end
Atthispointwesetanyotherclientvariablestodefaultvaluesandsendthemtotheclientsif
appropriate.Wedeclaredastudents-ownvariableforeveryinterfaceelementontheclient
thatholdsstate,thatis,anythingthatwouldbeaglobalvariableontheserver,sliders,
choosers,switchesandinputboxes.Itisimportanttomakesurethatthesevariablesstay
synchronizedwiththevaluesvisibleontheclient.
Whentheclientslogouttheysendanexitmessagetotheserverwhichgivesyouachanceto
cleanupanyinformationyouhavebeenstoringabouttheclient,inthiscasewemerelyhave
toasktheappropriateturtletodie.
to remove-student
ask students with [user-id = hubnet-message-source]
[ die ]
end
Allothermessagesareinterfaceelementsidentifiedbythehubnet-message-tagwhichisthe
namethatappearsintheclientinterface.Everytimeaninterfaceelementchangesa
messageissenttotheserver.Unlessyoustorethestateofthevaluescurrentlydisplayedin
theclientinterfacewillnotbeaccessibleinotherpartsofthemodel.That’swhywe’ve
declaredastudents-ownvariableforeveryinterfaceelementthathasastate(sliders,
switches,etc).Whenwereceivethemessagefromtheclientwesettheturtlevariabletothe
contentofthemessage:
if hubnet-message-tag = "step-size"
[
ask students with [user-id = hubnet-message-source]
[ set step-size hubnet-message ]
]
Sincebuttonsdon’thaveanyassociateddatathereisgenerallynoassociatedturtlevariable,
insteadtheyindicateanactiontakenbytheclient,justaswitharegularbuttonthereisoften
procedureassociatedwitheachbuttonthatyoucallwheneveryoureceiveamessage
indicatingthebuttonhasbeenpressed.Thoughitiscertainlynotrequired,theprocedureis
oftenaturtleprocedure,thatis,somethingthatthestudentturtleassociatedwiththemessage
sourcecanexecute:
if command = "move left"
[ set heading 270
fd 1 ]
Sendingmessagestoclients
Asmentionedearlieryoucanalsosendvaluestoanyinterfaceelementsthatdisplay
information:monitors,sliders,switches,choosers,andinputboxes(notethatplotsandthe
viewarespecialcasesthathavetheirownsections).
Therearetwoprimitivesthatallowyoutosendinformationhubnet-sendandhubnet-
broadcast.Broadcastsendstheinformationtoalltheclients;sendsendstooneclient,ora
selectedgroup.
Assuggestedearlier,nothingontheclientupdatesautomatically.Ifavaluechangesonthe
server,itisyourresponsibilityastheactivityauthortoupdatemonitorsontheclient.
Forexample,sayyouhaveasliderontheclientcalledstep-sizeandamonitorcalledStep
Size(notethatthenamesmustbedifferent)youmightwriteupdatingcodelikethis:
if hubnet-message-tag = "step-size"
[
ask student with [ user-id = hubnet-message-source ]
[
set step-size hubnet-message
hubnet-send user-id "Step Size" step-size
]
]
Youcansendanytypeofdatayouwant,numbers,strings,lists,listsoflists,listsofstrings,
however,ifthedataisnotappropriateforthereceivinginterfaceelement(say,ifyouwereto
sendastringtoaslider)themessagewillbeignored.Hereareafewcodeexamplesfor
differenttypesofdata:
data
type hubnet-broadcastexample hubnet-sendexample
number hubnet-broadcast "A" 3.14 hubnet-send "jimmy" "A" 3.14
string hubnet-broadcast "STR1" "HI THERE" hubnet-send ["12" "15"] "STR1" "HI
THERE"
listof
numbers hubnet-broadcast "L2" [1 2 3] hubnet-send hubnet-message-source
"L2" [1 2 3]
matrixof
numbers
hubnet-broadcast "[A]" [[1 2] [3
4]]
hubnet-send "susie" "[A]" [[1 2] [3
4]]
listof
strings
hubnet-broadcast "user-names"
[["jimmy" "susie"] ["bob"
"george"]]
hubnet-send "teacher" "user-names"
[["jimmy" "susie"] ["bob" "george"]]
Examples
Studythemodelsinthe“HubNetActivities”sectionoftheModelsLibrarytoseehowthese
primitivesareusedinpracticeintheCodetab.Diseaseisagoodonetostartwith.
Howtomakeaclientinterface
OpentheHubNetClientEditor,foundintheToolsMenu.Addanybuttons,sliders,switches,
monitors,plots,choosers,ornotesthatyouwantjustasyouwouldintheinterfacetab.You’ll
noticethattheinformationyouenterforeachofthewidgetsisslightlydifferentthaninthe
Interfacepanel.Widgetsontheclientdon’tinteractwiththemodelinthesameway.Instead
ofadirectlinktocommandsandreportersthewidgetssendmessagesbacktotheserverand
themodelthendetermineshowthosemessagesaffectthemodel.Allwidgetsontheclient
haveatagwhichisanamethatuniquelyidentifiesthewidget.Whentheserverreceivesa
messagefromthatwidgetthetagisfoundinhubnet-message-tag.
Forexample,ifyouhaveabuttoncalled“moveleft”,aslidercalled“step-size”,aswitchcalled
“all-in-one-step?”,andamonitorcalled“Location:”,thetagsfortheseinterfaceelementswill
beasfollows:
interface
element tag
moveleft moveleft
step-size step-size
all-in-one-step? all-in-one-step?
Location: Location:
Notethatyoucanonlyhaveoneinterfaceelementwithaspecificname.Havingmorethan
oneinterfaceelementwiththesametagintheclientinterfacewillresultinunpredictable
behaviorsinceitisnotclearwhichelementyouintendedtosendtheinformationto.
Viewupdatesontheclients
Viewmirroringletsviewsoftheworldbedisplayedinclientsaswellontheserver.View
mirroringisenabledusingacheckboxintheHubNetControlCenter.
Whenmirroringisenabled,clientviewsupdatewhenevertheviewontheserverdoes.To
avoidexcessivenetworktraffic,theviewshouldnotupdatemoreoftenthannecessary.
Thereforewestronglyrecommendusingtick-basedupdates,ratherthancontinuousupdates.
SeetheViewUpdatessectionoftheProgrammingGuideforanexplanationofthetwotypes
ofupdates.
Withtick-basedupdates,updateshappenwhenatickordisplaycommandruns.We
recommendusingthesecommandsonlyinsideaneveryblock,tolimitthefrequencyofview
updatesandthusalsolimitnetworktraffic.Forexample:
every 0.1
[
display
]
IfthereisnoViewintheclientsoriftheMirror2DViewonClientscheckboxintheHubNet
ControlCenterisnotchecked,thennoviewupdatesaresenttotheclients.
Clickingintheviewonclients
IftheViewisincludedintheclient,twomessagesaresenttotheservereverytimetheuser
clicksintheview.Thefirstmessage,whentheuserpressesthemousebutton,hasthetag
“View”.Thesecondmessage,sentwhentheuserreleasesthemousebutton,hasthetag
“MouseUp”.Bothmessagesconsistofatwoitemlistofthexandycoordinates.Forexample,
toturnanypatchthatwasclickedonbytheclientred,youwouldusethefollowingNetLogo
code:
if hubnet-message-tag = "View"
[
ask patches with [ pxcor = (round item 0 hubnet-message) and
pycor = (round item 1 hubnet-message) ]
[ set pcolor red ]
]
Customizingtheclient’sview
Whenviewmirroringisenabled,bydefaultclientsseethesameviewtheactivityleadersees
ontheserver.Butyoucanchangethissothateachclientseessomethingdifferent,notjusta
literal“mirror”.
Youcanchangewhataclientseesintwodistinctways.Wecallthem“clientperspectives”
and“clientoverrides”.
Changingaclient’sperspectivemeansmakingit“watch”or“follow”aparticularagent,much
likethewatchandfollowcommandsthatworkwithordinaryNetLogomodels.Seethe
dictionaryentriesforhubnet-send-watch,hubnet-send-follow,andhubnet-reset-perspective.
CodeExample:ClientPerspectiveExample
Clientoverridesletyouchangetheappearanceofpatches,turtles,andlinksintheclient
views.Youcanoverrideanyofthevariablesaffectinganagent’sappearance,includingthe
hidden?variablecausingaturtleorlinktobevisibleorinvisible.Seethedictionaryentriesfor
hubnet-send-override,hubnet-clear-override,andhubnet-clear-overrides.
CodeExample:ClientOverridesExample
Plotupdatesontheclients
Ifplotmirroringisenabled(intheHubNetControlCenter)andaplotintheNetLogomodel
changesandaplotwiththeexactsamenameexistsontheclients,amessagewiththat
changeissenttotheclientscausingtheclient’splottomakethesamechange.Forexample,
let’spretendthereisaHubNetmodelthathasaplotcalledMilkSupplyinNetLogoandthe
clients.MilkSupplyisthecurrentplotinNetLogoandintheCommandCenteryoutype:
plot 5
Thiswillcauseamessagetobesenttoalltheclientstellingthemthattheyneedtoplota
pointwithayvalueof5inthenextpositionoftheplot.Notice,ifyouaredoingalotofplotting
allatonce,thiscangeneratealotofplottingmessagestobesenttotheclients.
ModelingCommonsGuide
NetLogo6.0.4UserManual
Introduction
TheModelingCommons(http://modelingcommons.org/)isaWeb-basedcollaborationsystemfor
NetLogomodelers.UsersoftheModelingCommonscanshare,download,modify,createvariations
of,commenton,andrunNetLogomodels–boththosethatareapartoftheNetLogomodels
library,andalsothosethathavebeenuploadedbyotherNetLogousers.
ByuploadingyourNetLogomodelstotheModelingCommons,youmakeiteasyforotherstosee,
review,andcommentonyourwork.Youcanoptionallykeepthemodelprivate,eithertoyourselfor
toagroupofyourchoice,ifyouaren’tcomfortablewithlettingeveryoneseethemodel.Youcan
alwayschangethepermissionsassociatedwithamodel,ifyouchangeyourmindlateron.
NetLogonowmakesitpossibletosavemodelstotheModelingCommons,justasyoucansave
themto.nlogofilesonyourowncomputer.Youcanaccessthisfunctionalitybyselecting“Uploadto
ModelingCommons”fromthe“File”menu.
UseoftheModelingCommonsisfreeofcharge.Youmayuseitforyourownpersonalwork,for
yourresearchgrouporcompany,orforaclassinwhichyouareastudentorteacher.TheModeling
CommonsissponsoredbytheCCL,thesamegroupthatdevelopsanddistributesNetLogo.
ModelingCommonsAccounts
InordertouploadmodelstotheModelingCommons,youmustfirstbearegistereduser.
Unregistereduserscanviewanddownloadmodels,butcannotupload,edit,orcommentonthem.
Thefirsttimethatyouinvoke“SavetoModelingCommons”inNetLogo,youwillbepromptedto
enteryoure-mailaddressandpassword.Ifyoualreadyhaveanaccount,thenyoucanenterthis
informationandclickonthe“Login”button.
Ifyoudon’tyethaveanaccountwiththeModelingCommons,thenyouwillneedtocreateone.
Clickonthe“CreateAccount”button,andentertherequestedinformation.Onceyouhavedoneso,
clickonthe“CreateAccount”button.Iftherearenoerrors,thenyouwillbepromptedtouploada
NetLogomodel.Alternatively,youmaygototheModelingCommonsitselfandregisterwithyour
Webbrowser.
UploadingModels
TherearethreewaystouploadamodeltotheModelingCommons:Uploading,updating,and
creatingachild(“forking”).Thefollowingsectionsdescribetheseindetail.
UploadANewModel
AnewmodelwillbecreatedintheModelingCommons,withitsownpage,description,andforum.
YoushouldusethisfunctionthefirsttimethatyousaveamodeltotheModelingCommons.
Youmustgiveyourmodelaname.Modelnamesarenotrequiredtobeunique;youcouldhave2or
moremodelswiththesamename,thoughwerecommendthatyounotdothis.
Bydefault,anyonecanview,fork,andupdateyourmodel.Youcanrestricttheabilitytoviewand
forkyourmodelbychangingthevisibilitypermission.Youcanrestricttheabilitytoupdateyour
modelbychangingthechangeabilitypermission.Inordertosetpermissionsformultiplepeople,
assignyourmodeltoagroup,andthenrestrictvisibilityorchangeabilitytomembersofthatgroup.
GroupscanbecreatedfromtheModelingCommons.Onceyouhaveuploadedyourmodel,youcan
editthepermissionsfromthemodel’sModelingCommonspage.
Youcanoptionallyuploadapreviewimagetoyourmodel.Thepreviewimagewillbedisplayed
alongsideyourmodelwheneveritisshownontheModelingCommons.Whileuploadingapreview
imageisoptional,wehighlyrecommendthatyoudoso,inoneofthefollowingthreeways:
The“Usecurrentimage”optiontellsNetLogotousethecurrentviewasyourpreview.We
recommendthatyoufirstrunthemodel,suchthatitshowsoffthekeyvisualfeatures.
The“Auto-generateimage”featureauto-generatesapreviewimagebyrunningrandom-seed 0
setup repeat 75 [ go ].Thisoptionwillonlybeenabledifyouhavedefinedsetupandgo
proceduresforNetLogotorun.
The“Imagefromfile”featureallowsyoutouploadanyPNGimage.Previewimagesworkbest
whentheyaresquare.
UploadAChildOfAnExistingModel(“forking”)
Savingamodelinthisway,sometimesknownas“forking,”doesnotchangeoroverwritethe
originalmodel.Rather,itcreatesanewmodelontheModelingCommons,muchasaplain“save”
woulddo,simultaneouslycreatingaparent-childrelationshipbetweentheoldmodelandthenew
one.Thisrelationshipcanbeseenonthe“family”tabforagivenmodel.Youmayforkanymodelfor
whichyouhave“view”permissions,includingonethatyoucannotchange.Youmaywish,for
example,tocreateavariationonamodelintheNetLogomodelslibrary.
Toforkamodel,youmustgiveyournewchildaname,aswellasselectanexistingmodeltofork.
Toindicatetheexistingmodel,starttypingthenameofthemodelthatyouwouldliketofork.Select
itsnamefromamongthesearchresults.
Finally,youmustenteradescriptionaboutwhatyouarechanginginyourchildmodel,andhowit
relatestoitsparent.
UpdatingAnExistingModel
UsethisoptionifyouhaveimprovedamodelthatalreadyexistsintheModelingCommons.Existing
attachments,discussions,andsocialtagswillbepreserved,butthemodelthatuserscandisplay,
run,anddownloadwillbeupdated.Youmayonlyupdateamodelforwhichyouhave“write”
permissions.
AllversionsofamodelaresavedintheModelingCommons,soyoushouldfeelfreetoexperiment
withnewideas.Ifsomethinggoeswrong,youcanalwaysrefertoanoldversionfromthe“history”
tabonamodel’spage.
Toindicatewhichmodelshouldbeupdated,starttypingthenameofthemodel.Selectthename
thatpopsupwiththesearchresults.Finally,enteradescriptionaboutwhatyouarechangingin
yournewversion.
Logging
NetLogo6.0.4UserManual
NetLogo’sloggingfacilityallowsresearcherstorecordstudentactionsforlateranalysis.
LogginginNetLogo,onceinitiated,isinvisibletothestudent.Theresearchercanchoosethe
typeofeventsloggedthroughaconfigurationfile.
NetLogousesthelog4jpackageforlogging.Ifyouhavepreviousexperiencewiththispackage
you’llfindlogginginNetLogofamiliar.
LoggingissupportedonlybythespecialNetLogoLoggingapplication.
Startinglogging
Thisdependsonwhatoperatingsystemyouareusing.
MacOSXorWindows
ThereisaspeciallogginglauncherintheNetLogodirectorycalledNetLogoLogging.Double
clickontheicon.
OnWindows,theNetLogodirectorycanbefoundatC:\Program Files,unlessyouchosea
differentlocationwhenyouinstalledNetLogo.
Linuxandothers
Toenablelogging,invokethenetlogo.shscriptasfollows:
netlogo.sh --logging netlogo_logging.xml
Youcouldalsomodifythescripttoincludetheseflags,orcopythescriptandmodifythecopy.
Youcanreplacenetlogo_logging.xmlwithanyvalidlog4jXMLconfigurationfile,whichwillbe
discussedinmoredetaillater.
Usinglogging
WhenNetLogostartsupitwillaskforausername.Thisnamewillappearinallthelogs
generatedduringthissession.
Wherelogsarestored
LogsarestoredintheOS-specifictempdirectory.OnmostUnix-likesystemsthatis/tmp.On
WindowsVistathelogscanbefoundinc:\Users\<user>\AppData\Local\Temp,where<user>is
theloggedinuser.OnMacOSX,thetempdirectoryvariesforeachuser.Youcandetermine
yourtempdirectorybyopeningtheTerminalapplicationandtypingecho $TMPDIR>atthe
prompt.
Therearetwoconveniencecommandsthatwillhelpyoumanagethelogs.__zip-log-files
filenamewillgatherallthelogsinthetempdirectoryandputtheminonezipfile,atthe
locationspecified.Afterdoing__zip-log-filestheexistinglogsarenotdeleted,youcando
soexplicitlybyusing__delete-log-files.
Thefollowingisachartdescribingthenameoftheloggersavailable,thetypeofeventseach
logs,atwhatlevel,andprovidesasampleoutputusingtheXMLLayout.Alltheloggersare
foundinorg.nlogo.log.Logger.Whenreferringtotheloggersintheconfigurationfileyou
shouldusethefullyqualifiedname.So,forexample,theloggerGLOBALSwouldactuallybe
org.nlogo.log.Logger.GLOBALS
Logger Events Level Example
GLOBALS aglobalvariable
changes
info,
debug
<event logger="org.nlogo.log.Logger.GLOBALS"
timestamp="1177341065988"
level="INFO"
type="globals">
<name>FOO</name>
<value>51.0</value>
</event>
GREENS
sliders,
switches,
choosers,input
boxesare
changed
throughthe
interface
info
<event logger="org.nlogo.log.Logger.GREENS"
timestamp="1177341065988"
level="INFO"
type="slider">
<action>changed</action>
<name>foo</name>
<value>51.0</value>
<parameters>
<min>0.0</min>
<max>100.0</max>
<inc>1.0</inc>
</parameters>
</event>
CODE
codeis
compiled,
including:
command
center,Code
tab,slider
bounds,and
buttons
info
<event logger="org.nlogo.log.Logger.CODE"
timestamp="1177341072208"
level="INFO"
type="command center">
<action>compiled</action>
<code>crt 1</code>
<agentType>O</agentType>
<errorMessage>success</errorMessage>
</event>
WIDGETS
awidgetis
addedor
removedfrom
theinterface
info
<event logger="org.nlogo.log.Logger.WIDGETS"
timestamp="1177341058351"
level="INFO"
type="slider">
<name></name>
<action>added</action>
</event>
BUTTONS
abuttonis
pressedor info
<event logger="org.nlogo.log.Logger.BUTTONS"
timestamp="1177341053679"
level="INFO"
type="button">
<name>show 1</name>
released <action>released</action>
<releaseType>once</releaseType>
</event>
SPEED thespeedslider
changes info
<event logger="org.nlogo.log.Logger.SPEED"
timestamp="1177341042202"
level="INFO"
type="speed">
<value>0.0</value>
</event>
TURTLES turtlesdieor
areborn info
<event logger="org.nlogo.log.Logger.TURTLES"
timestamp="1177341094342"
level="INFO"
type="turtle">
<name>turtle 1</name>
<action>born</action>
<breed>TURTLES</breed>
</event>
LINKS linksdieorare
born info
<event logger="org.nlogo.log.Logger.LINKS"
timestamp="1177341094342"
level="INFO"
type="link">
<name>link 2 7</name>
<action>born</action>
<breed>LINKS</breed>
</event>
Logger Events Level Example
Howtoconfiguretheloggingoutput
Thedefaultloggingconfiguration(netlogo_logging.xml)lookssomethinglikethis:
NetLogodefines8loggers,alldescenddirectlyfromtherootlogger,whichmeansunlessyou
explicitlysettheproperties(appender,layout,andoutputlevel)intheconfigurationtheywill
inheritthemfromtheroot.InthedefaultconfigurationtherootissettolevelINFO,the
appenderisorg.nlogo.log.XMLFileAppenderandlayoutisorg.nlogo.log.XMLLayout.Together
thesegenerateanicelyformattedXMLfileasdefinedinthenetlogo_logging.dtdwhichis
basedonthelog4jdtd.IftheappenderisaFileAppender(includingtheXMLFileAppender)a
newfileisstarteachtimetheuseropensamodel.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="false" xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="A1" class="org.nlogo.log.XMLFileAppender">
<layout class="org.nlogo.log.XMLLayout"/>
</appender>
<category name="org.nlogo.log.Logger.WIDGETS">
<priority value="off" />
</category>
<category name="org.nlogo.log.Logger.TURTLES">
<priority value="off" />
</category>
<category name="org.nlogo.log.Logger.LINKS">
<priority value="off" />
</category>
<root>
<priority value ="info" />
<appender-ref ref="A1" />
</root>
</log4j:configuration>
Thisconfiguration,firstdefinesanappendernamed“A1”oftypeXMLFileAppenderwithan
XMLLayout.Theappenderdefineswheretheloggingdatagoes,inthiscasethedatagoes
intoafile.Infact,ifNetLogoisgivenaFileAppenderitwillautomaticallystartanewfileevery
timetheuseropensanewmodel.TheXMLFileAppenderalsodoessomeformattingand
writestheappropriateheaderstothefile.Thelayoutdefineshowtowriteeachindividual
message.Unlessyouareanadvanceduserthereisnoneedchange(orworryabout)the
appenderorthelayout.
Attheendoftheconfigurationnoticethedefinitionoftherootlogger.Alloftheotherloggers
descendfromtherootloggerand,thus,inheritthepropertiesoftherootunlessexplicitlyset.
Thiscaseisfairlysimple,havingsetuptheappenderA1wemakethatthedefaultappender
fortheroot(andallotherloggers)andmakethedefaultpriority“INFO”.Messagesthatare
loggedattheINFOlevelorhigherwillbewritten,messagesloggedatlowerlevelswillnot.
NotethatwithonlyoneexceptionNetLogoalwayslogsatlevelINFO.Setstoglobalsthatdon’t
changethevalueoftheglobalareloggedatlevelDEBUG.Whichmeansthatthesemessages
aredisabledbydefault,sincedebugislowerlevelthaninfo.Therestofthebodyofthe
configurationfileoverridespropertiesoftherootloggerinafewspecificloggers(orcategories
astheyareknownintheconfigurationfile,thetermscanbeassumedtobesynonymousfor
theproposesofthisdocument).ThatisitturnsofftheWIDGET,TURTLES,andLINKS
loggers,bydefault.Tore-enablethemyoucanchangesthepriorityfromofftoinfo,likethis:
<category name="org.nlogo.log.Logger.TURTLES">
<priority value="info" />
</category>
oryoucansimplyremovetheentirereferencetothecategoryfromtheconfigurationfile,asit
isnotservinganyotherpurpose.
AdvancedConfiguration
ThisisonlyabasicintroductiontoconfigurationfilesforlogginginNetLogo.Therearemany
moreconfigurationoptionsavailablethroughthelog4jframework.Seethelog4j
documentation.
ControllingGuide
NetLogo6.0.4UserManual
NetLogocanbeinvokedandcontrolledbyanotherprogramrunningontheJavaVirtual
Machine.Forexample,youmightwanttocallNetLogofromasmallprogramthatdoes
somethingsimplelikeautomateaseriesofmodelruns.Or,youmightwanttoembed
NetLogomodelsinalargerapplication.
Formoreinformation,gohere.
MathematicaLink
NetLogo6.0.4UserManual
TheNetLogo-Mathematicalinkprovidesmodelerswithaneasytouse,real-timelinkbetween
NetLogoandMathematica.Together,thesetoolscanprovideuserswithahighlyinteractive,
self-documentingworkflowthatneithercanprovidealone.
Mathematicaincludesmanyofthetoolsthatagent-basedmodelersrelyonthroughoutthe
researchprocess:advancedimportcapabilities,statisticalfunctions,datavisualization,and
documentcreation.WiththeNetLogo-Mathematicalink,youcanrunallofthesetoolsside-by-
sidewithNetLogo.
BecauseallMathematicadocuments,ornotebooks,containcomments,code,images,
annotations,andinteractiveobjects,theintegrationofNetLogoandMathematicaprovidesa
morecompletesolutionforcomplexmodelexplorationforstudentsandresearchersalike.
ThebasicfunctionalityofthelinkismuchliketheNetLogoControllingAPI:youcanload
models,executecommands,andreportbackdatafromNetLogo.UnliketheControllingAPI,
whichisbasedonJava,allinteractionswiththelinkareinterpreted,makingitidealnotonly
forrapidlydesigningcustomBehaviorSpace-likeexperiments,butalsoasacompanionto
NetLogoindebuggingyourmodel.
FormoreinformationaboutMathematica,pleasevisittheWolframResearchwebsite.
WhatcanIdowithit?
HereareafewexamplesofwhatyoucandowiththeMathematica-NetLogolink.
Analyzeyourmodelinreal-timewithseamlesstwo-waydataconversion
Develophighquality,customvisualizationsofmodeldata
Collectdetailedsimulationdataacrosslargemulti-dimensionalparameterspaces
Rapidlydevelopinteractiveinterfacesforexploringmodelbehavior
Havedirectaccesstopatchesandnetworkdatawithbuilt-infunctions
Installation
TheNetLogo-MathematicalinksupportsMathematica10orgreater.ToinstalltheNetLogo-
Mathematicalink:
1. GotothemenubarinMathematica
2. ClickonFileandselectInstall…
3. IntheInstallMathematicaItemdialog
4. SelectPackageforTypeofitemtoinstall
5. ClickSource,andselectFromfile…
6. Inthefilebrowser,gotothelocationofyourNetLogoinstallation,
7. clickontheMathematicaLinksubfolder,andselectNetLogo.m.
8. ForInstallName,enterNetLogo.
YoucaneitherinstalltheNetLogolinkinyouruserbasedirectoryorinthesystem-wide
directory.IftheNetLogolinkisinstalledintheuserbasedirectory,otherusersonthesystem
mustalsogothroughtheNetLogo-Mathematicalinkinstallationprocesstouseit.Thisoption
mightbepreferableifyoudonothavepermissiontomodifyfilesoutsideofyourhome
directory.Otherwise,youcaninstallNetLogo-Mathematicalinkinthesystem-wide
Mathematicabasedirectory.
Usage
ThissectionwillverybrieflyintroducehowtousetheNetLogo-MathematicaLink.Itwillshow
youhowtoloadtheNetLogo-MathematicaLinkpackage,startNetLogo,executecommands,
andretrievedatafromNetLogo.
Loadingthepackage:OncetheNetLogo-Mathematicalinkisinstalled,youcanloadthe
packagebyenteringthefollowingintoyourMathematicanotebook:
<<NetLogo`
LaunchingNetLogofromMathematica:TobeginyourNetLogosessioninMathematica,
typethefollowingintoyournotebook:
NLStart[“your netlogo path”];
whereyournetlogopathisthedirectorythatnetlogoislocatedin.TypicallyonaMacthiswill
be“/Applications/NetLogo6.0.4/”
Loadingamodel:Toloadamodel,youmustspecifythefullpathofthemodel.Inthis
examplewewillloadtheForestFiremodel,andthepathwillbegivenusingthetypicalMac
installlocation.
NLLoadModel["/Applications/NetLogo 6.0.4/models/Sample Models/Earth
Science/Fire.nlogo"];
ExecutingaNetLogocommand:Commandscanbeexecutedbypassingastringof
commandstoNLCommand[].TheNLCommand[]functionautomaticallysplicescommon
MathematicadatatypesintostringssuitableforNetLogo.Thefollowingcommandssetthe
densityusingasinglestring,orsetthedensityusingaMathematicadefinedvariable,
myDensity.
NLCommand["set density 50"];
myDensity = 60;
NLCommand["set density", myDensity];
ReportinginformationfromNetLogo:NetLogodatacanbereportedbacktoMathematica
usingNLReport[].Thisincludesnumbers,strings,booleanvalues,andlists.
NLReport["count turtles"];
NLReport["[(list pxcor pycor)] of n-of 10 patches"]
Formoreinformation,seetheNetLogo-MathematicaTutorialnotebookincludedwith
NetLogo.Thenotebookwalksyouthroughtheprocessofusingthelink,withmanyexamples
alongtheway.IfyoudonothaveMathematica,butareconsideringusingthelink,youcan
findaPDFofthenotebookincludedwithNetLogointhe“MathematicaLink”directory.
KnownIssues
ANetLogosessioncannotbequitwithoutexitingJ/Link(theJava-Mathematicalink)
entirely.ThismaydisruptotherpackagesthatmakeuseofJ/Link.
IfamodelloadedwiththeNetLogo-MathematicalinkusesaNetLogoextension,the
extensionmustbelocatedinthesamedirectoryasthemodelitself.Iftheextensionis
locatedinNetLogo’sapplication-wideextensionsdirectory,itwillnotbefound.
CallstoNetLogo,suchasNLCommand[]andNLReport[],cannotbeaborted.
Sourcecode
ThesourcecodefortheNetLogo-Mathematicalinkisinthepublicdomain.Itishostedonline
athttps://github.com/NetLogo/Mathematica-Link.
Credits
TheprimarydeveloperoftheNetLogo-MathematicalinkwasEytanBakshy.
Torefertothispackageinacademicpublications,pleaseuse:Bakshy,E.,Wilensky,U.
(2007).NetLogo-MathematicaLink.http://ccl.northwestern.edu/netlogo/mathematica.html.
CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity,
Evanston,IL.
NetLogo3D
NetLogoincludestheNetLogo3Dapplicationthatallowsyoutocreate3Dworlds.
Notice:NetLogo'ssupportfor3DislessdevelopedthanNetLogo2D.Modelscreatedwith
thisreleasemaynotbecompatiblewithfutureversions.Whilewe'vemadeeffortsto
ensureaqualityproduct,NetLogo3Dhasnotbeensubjecttothesamelevelofquality
controlasthemainapplication.
Introduction
Tutorial
Dictionary
Introduction
TogetstartedusingNetLogo3D,launchtheNetLogo3Dapplicationandcheckoutthe
SampleModelsinthe3DsectionoftheModelsLibrary.
Whenyou'rereadytowriteyourown3Dmodel,lookattheCodeExamplesinthe3D
sectionoftheModelsLibrary.
CodeExample:TurtlePerspectiveExample3Dhelpsyoulearnaboutthedifferent
perspectives.
CodeExample:TurtleandObserverMotionExample3Dhelpsyouunderstandhow
turtlesandtheobservermovein3D.Youcanalsostepthroughthismodelwiththetutorial
below.
3DWorlds
Anunspeakablehorrorseizedme.Therewasadarkness;thenadizzy,sickening
sensationofsightthatwasnotlikeseeing;IsawaLinethatwasnoLine;Spacethatwas
notSpace:Iwasmyself,andnotmyself.WhenIcouldfindvoice,Ishriekedloudinagony,
"EitherthisismadnessoritisHell."
"Itisneither,"calmlyrepliedthevoiceoftheSphere,"itisKnowledge;itisThree
Dimensions:openyoureyeonceagainandtrytolooksteadily."
--EdwinA.Abbott,Flatland:Aromanceinmanydimensions
NetLogo3D'sworldhaswidth,heightanddepth.Patchesarecubes.Inadditiontopxcor
andpycor,patcheshavepzcor.
TurtleshavethreeCartesiancoordinates,insteadoftwo,todescribeposition.Inaddition
toxcorandycor,turtleshavezcor.
Aturtle'sorientationisdefinedbythreeturtlevariables,heading,pitchandroll.Youcan
imaginetheturtleashavingtwovectorstodefineitsorientationin3Dspace.Onevector
comesstraightoutofthenoseoftheturtle,thisisthedirectiontheturtlewilltravelwhenit
movesforward.Thesecondvectorisperpendiculartotheforwardvectorandcomesout
oftherightsideoftheturtle(asiftheturtleweretostickitsrightarmstraightoutfromits
body).Headingistheanglebetweentheforwardvectoroftheturtleprojectedontothexy-
planeandthevector[010].Pitchistheanglebetweentheforwardvectoroftheturtleand
thexy-planeandfinallyrollistheanglebetweentherightvectoroftheturtleandthexy-
plane.Whenturtleturnsrightorleftin3Dspaceitrotatesaroundthedownvector,thatis
thevectorthatisperpendiculartoboththeforwardandrightvectors.Dependingonthe
orientationoftheturtlemorethanoneoftheinternalturtlevariablesmaychangeasthe
resultofaturn.
Theobserverandthe3Dview
Thepointofviewthatyouseetheworldfromisconsideredthelocationandorientationof
theobserver.Thisissimilartothe3DviewinNetLogo2D.However,thereareafewmore
waystocontroltheobserver.Youcansetthepointthattheobserverisfacingbyusing
faceandfacexyzwhichworkthesamewayastheturtlecommands,theobserverturnsso
thecenteroftheviewisonthegivenpointorthelocationofthegivenagentatthetimeit
iscalled.Youcanchangethelocationoftheobserverusingsetxyz.Theobserverwill
movetoviewtheworldasifstandingonthegivenlocation,thepointtheobserverfaces
willstaythesame.Forexamplecreateanewmodelandobserverwillbelocatedat(0,0,
49.5),thatis,onthez-axis49.5patchunitsawayfromtheoriginandtheobserveris
facingtheorigin,(0,0,0).Ifyousetxyz 0 49.5 0theobserverwillmovesoitisonthe
positivey-axisbutitwillkeeptheoriginatthecenteroftheview.Youcanalsomovethe
observerusingtherotationprimitivesthatwillallowyoutomovetheobserveraroundthe
worldasifonthesurfaceofaspherewherethecenteristhelocationtheobserveris
facing.Youmaynoticefromtheaboveexamplesthattheobserverisnotconstrainedto
bewithintheboundsoftheworld.
CustomShapes
NetLogoautomaticallyinterprets2Dshapessotheyareextruded,likeacookiecutter
shapeinthe3Dview.Youcanalsousetheprimitiveload-shapes-3dtoloadshapes
describedinanexternalfileinacustomformatdescribedhere.Currentlywedonotimport
shapesinanystandardformats.
Foreachshapeinacustom3Dshapefile,a2Dshapeofthesamenamemustexistas
well.Youcancreatethe2DshapeintheTurtleShapesEditor.
Theinputfilemaycontainanynumberofshapeswithanynumberofrectangularor
triangularsurfaces.Theformatoftheinputfileshouldbeasfollows:
number of shapes in file
name of first shape
type of surface ( quads or tris )
surface1
surface2
.
.
.
stop
type of surface
surfaceA
.
.
.
stop
end-shape
Eachsurfaceisdefinedbyaunitnormalvectorandtheverticeslistedinclockwiseorder,
trisshouldhavethreeverticesandquadsshouldhavefour.
normal: xn yn zn
x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
Afiledeclaringjustatwodimensional,patch-sized,squareinthexy-planecenteredatthe
originwouldlooklikethis:
1
square
quads
normal: 0 0 1
0.15 0.15 0
-0.15 0.15 0
-0.15 -0.15 0
0.15 -0.15 0
normal: 0 0 -1
0.15 0.15 0
0.15 -0.15 0
-0.15 -0.15 0
-0.15 0.15 0
stop
end-shape
Tutorial
Step1:Depth
OneofthefirstthingsyouwillnoticewhenyouopenNetLogo3Disthattheworldisa
cubeinsteadofasquare.
YoucanopenuptheModelSettings,byclickingonthe"Settings..."buttonatthetopof
the3DView.You'llnoticeinadditiontomax-pxcor,min-pxcor,max-pycor,andmin-pycor,
thereisalsomax-pzcorandmin-pzcor.
Thez-axisisperpendiculartoboththex-axisandthey-axis,whenyoureset-perspective
itistheaxisthatcomesstraightoutofthescreen.Inthedefaultpositionmax-pzcoristhe
faceofthecubenearesttoyouandmin-pzcoristhefacefarthestfromyou.Asalways
min-pxcorisontheleft,max-pxcorontheright,min-pycoronthebottom,andmax-pycoron
thetop.
You'llalsonoticeontheleftsideoftheModelSettingsthatthereareoptionsforwrapping
inallthreedirections,however,theyareallcheckedandgrayedout.Topologiesarenot
yetsupportedinNetLogo3D,sotheworldalwayswrapsinalldimensions.
MovetotheCommandCenterandtypeprint count patches.
Isthenumbersmallerorlargerthanyouexpected?
Ina3Dworldthenumberofpatchesgrowsveryquicklysincecount patches = world-
width * world-height * world-depth.It'simportanttokeepthisinmindwhenyouare
buildingyourmodel.LotsofpatchescanslowyourmodeldownorevencauseNetLogoto
runoutofmemory.
Typeask patch 1 2 3 [ set pcolor red ] intotheCommandCenter.
Usethemouseinthe3Dviewtorotatetheworld.
Noticetheshapeofthepatchanditspositioninrelationtotheedgesoftheworld.You'll
alsonoticethatyounowneedthreecoordinatestoaddresspatchesina3Dworld.
Step2:TurtleMovement
OpentheModelsLibraryintheFilemenu.(IfyouareonaMacandyoudon'thavea
Filemenu,clickonthemainNetLogowindowfirstanditshouldreappear.)
OpenTurtleandObserverMotionExample3Din3D/CodeExamples
Takeamomenttolookforthecontrolsandmonitors.Inthebottomleftyou'llnoticea
groupofmonitorsthatdescribethelocationandorientationoftheturtle,thoughuntilyou
pressthesetupbuttonthey'llallsay"N/A".
Pressthe"setup"button
Heading,pitch,androllareturtlevariablesthatrepresenttheorientationoftheturtle.
Headingisabsoluteinrelationtothex/yplane;itistherotationoftheturtlearoundthez-
axis.
Pitchistheanglebetweenthenoseoftheturtleandthexy-plane.Itisrelativetoheading.
Rollistherotationaroundtheturtle'sforwardvector.Itisrelativetoheadingandpitch.
Whenturtlesarecreatedwithcreate-turtlesorcreate-ordered-turtles,theirinitial
headingsvarybuttheirinitialpitchandrollarealwayszero.
Takealookatthe"TurtleMovement"buttons.
Pressthe"left1"button.
Howdoestheturtlemove?Isisthesameordifferentfrom2DNetLogo?Whichof
theturtlevariableschange?
Pressthe"pitch-down1"button.
Howdoestheturtlemove?Whichoftheturtlevariableschange?
Pressthe"left1"buttonagain.
Howdoestheturtlemove?Isitdifferentthanthelasttimeyoupressedthe"left1"
button?
TakealittletimetoplaywiththeTurtleMovementbuttons,watchingbothhowtheturtle
movesandwhichoftheturtlevariableschange.
Youprobablynoticedthatoftenmorethanoneoftheturtlevariablesmaychangefora
singleturn.Forthisreasonwesuggestthatyouusetheturtlecommandsratherthan
settingtheorientationvariablesdirectly.
Step3:ObserverMovement
AtthebottomoftheinterfaceyouwillseeOrbit,Zoom,andMovebuttons.Ifyouhave
everusedthe3DviewinNetLogo2Dorifyouhavebeenusingthemousecontrolsinthe
3Dviewthroughthistutorialyouhavebeenmovingtheobserver.Changingthepointof
viewinthe3Dviewisactuallymovingandchangingtheorientationoftheobserver.The
observerhasx,yandzcoordinates,justlikeaturtleorpatch,whileturtlesandpatches
areconstrainedtobeinsidetheworldtheobservercanbeanywhere.Likeaturtlethe
observerhasaheading,pitchandroll,thesevariablescontrolwheretheobserveris
looking,thatis,whatyouseeintheview.
Movetothe3Dview,andmakesure"Orbit"isselectedinthebottomleftcornerofthe
view.
Clickandholdthemousebuttoninthemiddleoftheview,movethemouseleft,right,
up,anddown.
Howdoesthepositionandorientationoftheobserverchange?
Pressthereset-perspectivebuttoninthelowerrightcorneroftheviewandselect
"Zoom"inthelowerleftcorner.
Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseupand
down.
Whichoftheobservervariableschange?Whichstaythesame?
Tryrotatingtheworldabitandthenzoomagain.
Pressthe"Move"buttoninthelowerleftcorneroftheview.
Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseup,
down,leftandright.
Howdoestheviewchange?Howdotheobservervariableschange?
Afteryouaredoneexploringtheworldusingthemousecontrolsyoucantakealookatthe
observercontrolbuttonsinthelowerleftportionoftheinterface.
Youmayalreadybefamiliarwiththefirstthreebuttonsintheobservergroupfromyour
experiencewithNetLogo2D.Watch,follow,andride,arespecialmodesthatautomatically
updatethepositionandorientationoftheobserver.Wheninfolloworridemode,the
observerpositionandorientationarethesameastheturtle's.Notethatfollowandrideare
functionallyexactlythesame,thedifferenceisonlyvisualinthe3Dview.Wheninwatch
modetheobserverdoesnotmovebutupdatestofacethetargetagent.
Pressthe"setup"buttonagainsoyouarebacktothedefaultorientation.
Pressthe"orbit-right"button.
Howdidtheviewchange?Wasitwhatyouexpected?Howisitsimilarordifferent
fromusingthemousecontrols?
Takealittletimetoexperimentwithorbit,rollandzoombuttons;noticesimilaritiesand
differencestothemousecontrols.
Thedirectionoftheorbitcommandsrefertothedirectionthattheobservermoves.Thatis,
imaginethattheobserverisonthesurfaceofasphere,thecenterofthesphereisthe
pointthattheobserverisfacingrepresentedbythebluecross,bydefault(0,0,0).The
observerwillalwaysfacethecenterofthesphereandtheradiusofthespherewillremain
constant.Thedirections,up,down,left,andright,refertomovingalongthelinesof
latitudeandthelinesoflongitudeofthesphere.Whenyouzoomtheradiusofthesphere
changesbutthecenterandtheobserver'sorientationinrelationtothecenterofthe
spherewillremainthesame.
Pressoneofthe"setxyz"buttons.
Howdoestheviewchange?Howdotheobservervariableschange?
Pressthe"facexyz"button.
Howdoestheviewchange?Howdotheobservervariableschange?
Whenyousetxyzthecenterofthesphereremainsthesame(sotheobserver
automaticallykeepsthatpointinthecenteroftheview.)However,theradiusofthesphere
maychangeaswellastheobserver'sorientationinrelationtothecenter.Whenyou
facexyzorface,thecenterofthespherechangesbuttheobserverdoesnotmove.The
radiusofthespheremaychange,aswellastheorientationoftheobserver.
Since4.1
Dictionary
CommandsandReporters
Turtle-relatedprimitives
distancexyzdistancexyz-nowrapdzleftpatch-atpatch-at-heading-pitch-and-distancetilt-down
tilt-uprightroll-leftroll-rightsetxyztowards-pitchtowards-pitch-nowraptowards-pitch-xyz
towards-pitch-xyz-nowrapturtles-at
Patch-relatedprimitives
distancexyzdistancexyz-nowrapneighborsneighbors6patchpatch-atpatch-at-heading-pitch-
and-distance
Agentsetprimitives
at-pointsbreeds-atturtles-at
Worldprimitives
max-pzcormin-pzcorrandom-pzcorrandom-zcorworld-depthload-shapes-3d
Observerprimitives
facefacexyzorbit-downorbit-leftorbit-rightorbit-up__oxcor__oycor__ozcorsetxyzzoom
Linkprimitives
link-pitch
Built-InVariables
Turtles
zcorpitchroll
Patches
pzcor
Primitives
at-points
Since4.1
Since4.1
Since4.1
agentsetat-points[[x1y1z1][x2y2z2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesthe
givendistancesawayfromthisagent.Thedistancesarespecifiedasalistofthree-item
lists,wherethethreeitemsarethex,y,andzoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inother
words,thepointsaretakenasabsolutepatchcoordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,and
notfromthecenterofthepatchundertheturtle.
ask turtles at-points [[2 4 0] [1 2 1] [10 15 10]]
[ fd 1 ] ;; only the turtles on the patches at the
;; distances (2,4,0), (1,2,1) and (10,15,10),
;; relative to the caller, move
distancexyz
distancexyz-nowrap
distancexyzxcorycorzcor
distancexyz-nowrapxcorycorzcor
3Dversionsofdistancexy.
Reportsthedistancefromthisagenttothepoint(xcor,ycor,zcor).
Thedistancefromapatchismeasuredfromthecenterofthepatch.
distancexyz-nowrapalwaysreportstheinworlddistance,neveradistancethatwould
requirewrappingaroundtheedgesoftheworld.Withdistancexyzthewrappeddistance
(aroundtheedgesoftheworld)isusedifthatdistanceisshorterthantheinworld
distance.
if (distancexyz 0 0 0) < 10
[ set color green ]
;; all turtles less than 10 units from
;; the center of the screen turn green.
dz
dz
Reportsthez-increment(theamountbywhichtheturtle'szcorwouldchange)iftheturtle
weretotakeonestepforwardatitscurrentheadingandpitch.
NOTE:dzissimplythesineoftheturtle'spitch.Bothdxanddyhavechangedinthiscase.
So,dx=cos(pitch)*sin(heading)anddy=cos(pitch)*cos(heading).
Seealsodx,dy.
Since4.1
Since4.1
Since4.1.2
Since4.1
Since4.1
Since4.1
face
facexyz
faceagent
facexyzxyz
Setthecaller'sheadingandpitchtowardsagentortowardsthepoint(x,y,z).
Ifthecallerandthetargetareatthesamexandycoordinatesthecaller'sheadingwillnot
change.Ifthecallerandthetargetarealsoatthesamezcoordinatethepitchwillnot
changeeither.
left
leftnumber
Theturtleturnsleftbynumberdegrees,relativetoitscurrentorientation.Whileleftina2D
worldonlymodifiestheturtle'sheading,leftina3Dworldmayalsomodifytheturtle's
pitchandroll.
Seealsoleft,tilt-up,tilt-down
link-pitch
link-pitch
Reportsthepitchfromend1toend2ofthislink.
ask link 0 1 [ print link-pitch ]
;; prints [[towards-pitch other-end] of end1] of link 0 1
Seealsolink-heading,pitch
load-shapes-3d
load-shapes-3dfilename
Loadscustom3Dshapesfromthegivenfile.Seethe3Dguideformoredetails.Youmust
alsoadda2DshapeofthesamenametothemodelusingtheTurtleShapesEditor.
Customshapesoverridebuilt-in3Dshapesandconverted2Dshapes.
max-pzcor
min-pzcor
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
max-pzcor
min-pzcor
Thesereportersgivethemaximumandminimumz-coordinates(respectively)forpatches,
whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenterofthe
world.However,theminimumz-coordinatehastobelessthanorequalto0andthe
maximumz-coordinatehastobegreaterthanorequalto0.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporters
whichcannotbeset.
Seealsomax-pxcor,max-pycor,min-pxcor,min-pycor,andworld-depth.
neighbors
neighbors6
neighbors
neighbors6
3Dversionsofneighborsandneighbors4.
Reportsanagentsetcontainingthe26surroundingpatches(neighbors)or6surrounding
patches(neighbors6).
show sum values-from neighbors [count turtles-here]
;; prints the total number of turtles on the twenty-six
;; patches around this turtle or patch
ask neighbors6 [ set pcolor red ]
;; turns the six neighboring patches red
orbit-down
orbit-left
orbit-right
orbit-up
orbit-downnumber
orbit-leftnumber
orbit-rightnumber
orbit-upnumber
Rotatetheobserveraroundthelastpointfaced.Imaginetheobserverisonthesurfaceof
asphere,thelastpointfaceisthecenterofthatsphere.Upanddownorbitalongthelines
oflongitudeandrightandleftorbitalongthelinesoflatitude.Theobserverwillremain
facingthelastpointfacedsotheheadingandpitchmaychangeasresultoforbiting.
However,becauseweassumeanabsolutenorthpole(paralleltothepositivez-axis)the
rollwillneverchange.
Since4.1
Since4.1
Since4.1
Seealsosetxyz,faceandzoom
__oxcor
__oycor
__ozcor
__oxcor
__oycor
__ozcor
Reportsthex-,y-,orz-coordinateoftheobserver.
Seealsosetxyz
patch
patchpxcorpycorpzcor
3Dversionofpatch.
Giventhreeintegers,reportsthesinglepatchwiththegivenpxcor,pycorandpzcor.
pxcor,pycorandpzcormustbeintegers.
ask (patch 3 -4 2) [ set pcolor green ]
;; patch with pxcor of 3 and pycor of -4 and pzcor of 2 turns green
Seealsopatch
patch-at
patch-atdxdydz
3Dversionofpatch-at.
Reportsthesinglepatchat(dx,dy,dz)fromthecaller,thatis,dxpatcheseast,dypatches
northanddzpatchesupfromthecaller.
ask patch-at 1 -1 1 [ set pcolor green ]
;; turns the patch just southeast and up from the caller green
patch-at-heading-pitch-and-distance
patch-at-heading-pitch-and-distanceheadingpitchdistance
Since4.1
3Dversionofpatch-at-heading-and-distance.
patch-at-heading-pitch-and-distancereportsthesinglepatchthatisthegivendistance
fromthisturtleorpatch,alongthegivenabsoluteheadingandpitch.(Incontrasttopatch-
left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakeninto
account.)
ask patch-at-heading-pitch-and-distance 0 90 1 [ set pcolor green ]
;; turns the patch directly above the caller green.
pitch
pitch
Thisisabuilt-inturtlevariable.Pitchistheanglebetweenthe"nose"oftheturtleandthe
xy-plane.Headingandpitchtogetherdefinetheforwardvectoroftheturtleorthedirection
thattheturtleisfacing.
Thisisanumbergreaterthanorequalto0andlessthan360.0isparalleltothexy-plane,
90isparalleltothez-axis.Whileyoucansetpitchwerecommendthatyouusethe
primitivestoturntheturtle.Dependingonthepositionmorethanonerelativeangle
(heading,pitchandroll)maychangeatonce.
Example:
;; assume roll and heading are 0
set pitch 45 ;; turtle is now north and up
set heading heading + 10 ;; same effect as "tilt-up 10"
Seealsoheading,roll,tilt-up,tilt-down,right,left
pzcor
pzcor
Thisisabuilt-inpatchvariable.Itholdsthezcoordinateofthepatch.Itisalwaysan
integer.Youcannotsetthisvariable,becausepatchesdon'tmove.
pzcorisgreaterthanorequaltomin-pzcorandlessthanorequaltomax-pzcor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsopxcor,pycor,zcor.
random-pzcor
random-pzcor
Since4.1
Since4.1
Reportsarandomintegerrangingfrommin-pzcortomax-pzcorinclusive.
ask turtles [
;; move each turtle to the center of a random patch
setxyz random-pxcor random-pycor random-pzcor
]
Seealsorandom-pxcor,random-pycor.
random-zcor
random-zcor
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinates
alongthezaxis.
Turtlecoordinatesrangefrommin-pzcor-0.5(inclusive)tomax-pzcor+0.5(exclusive).
ask turtles [
;; move each turtle to a random point
setxyz random-xcor random-ycor random-zcor
]
Seealsorandom-xcor,random-ycor.
right
rightnumber
Theturtleturnsrightbynumberdegrees,relativetoitscurrentorientation.Whilerightina
2Dworldonlymodifiestheturtle'sheading,rightina3Dworldmayalsomodifytheturtle's
pitchandroll.
Seealsorightandleft
roll
roll
Thisisabuilt-inturtlevariable.Rollistheanglebetweenthe"wing-tip"oftheturtleandthe
xy-plane.
Thisisanumbergreaterthanorequalto0andlessthan360.Youcansetthisvariableto
makeaturtleroll.Sincerollisalwaysfromtheturtle'spointofview,rollingrightandleft
onlyonlychangerollregardlessofturtleorientation.
Example:
set roll 45 ;; turtle rotated right
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
set roll roll + 10 ;; same effect as "roll-right 10"
Seealsoheading,pitch,roll-left,roll-right.
roll-left
roll-leftnumber
Thewingtipoftheturtlerotatestotheleftnumberdegreeswithrespecttothecurrent
headingandpitch.
roll-right
roll-rightnumber
Thewingtipoftheturtlerotatestotherightnumberdegreeswithrespecttothecurrent
headingandpitch.
setxyz
setxyzxyz
3Dversionofsetxy.
Theagent,aturtleortheobserver,setsitsx-coordinatetox,itsy-coordinatetoyanditsz-
coordinatetoz.Whentheobserverusessetxyzitremainsfacingthesamepointsothe
heading,pitch,androll,mayalsochange.
Forturtlesequivalenttoset xcor x set ycor y set zcor z,exceptithappensinonetime
stepinsteadofthree.
setxyz 0 0 0
;; agent moves to the middle of the center patch
Seealsoface
tilt-down
tilt-up
tilt-downnumber
tilt-upnumber
Thenoseoftheturtlerotatesbynumberdegrees,relativetoitscurrentorientation.
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
Dependingontheorientationoftheturtlemorethanoneoftherelativeangles(heading,
pitch,androll)maychangewhenaturtleturns.
towards-pitch
towards-pitch-nowrap
towards-pitchagent
towards-pitch-nowrapagent
Reportsthepitchfromthisagenttothegivenagent.
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screen
distance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrap
neverusesthewrappedpath.
Note:Inordertogetoneturtletofaceanotheryouneedtousebothtowards-pitchand
towards.
Note:askingforthepitchfromanagenttoitself,oranagentonthesamelocation,will
causearuntimeerror.
Seealsotowards
towards-pitch-xyz
towards-pitch-xyz-nowrap
towards-pitch-xyzxyz
towards-pitch-xyz-no-wrapxyz
Reportsthepitchfromthisagenttothecoordinatesx,y,z
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screen
distance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrap
neverusesthewrappedpath.
Note:Inordertogetaturtletofaceagivenlocationyouneedtousebothtowards-pitch-
xyzandtowardsxy.
Note:askingforthepitchfromanagenttothelocationitisstandingonwillcausea
runtimeerror.
Seealsotowardsxy
turtles-at
<breeds>-at
turtles-atdxdydz
<breeds>-atdxdydz
Since4.1
Since4.1
3Dversionsofturtles-atandbreeds-at.
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy,dz)fromthecaller
(includingthecalleritselfifit'saturtle).
;; suppose I have 40 turtles at the origin
show [count turtles-at 0 0 0] of turtle 0
=> 40
world-depth
world-depth
ReportsthetotaldepthoftheNetLogoworld.
Thedepthoftheworldisthesameasmax-pzcor-min-pzcor+1.
Seealsomax-pzcor,min-pzcor,world-width,andworld-height
zcor
zcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentzcoordinateoftheturtle.Thisisa
floatingpointnumber,notaninteger.Youcansetthisvariabletochangetheturtle's
location.
Thisvariableisalwaysgreaterthanorequalto(-screen-edge-z)andstrictlylessthan
screen-edge-z.
Seealsosetxy,xcor,ycor,pxcor,pycor,pzcor
zoom
zoomnumber
Movetheobservertowardthepointitisfacing,numbersteps.Theobserverwillnever
movebeyondthepointitisfacingsoifnumberisgreaterthanthedistancetothatpointit
willonlymoveasfarasthepointitisfacing.
ExtensionsGuide
NetLogo6.0.4UserManual
NetLogoallowsuserstowritenewcommandsandreportersinJavaandotherlanguagesand
usethemintheirmodels.ThissectionoftheUserManualintroducesthisfacilityandshows
howtouseanextensioninyourmodelonceyouhaveobtainedormadeone.
ExtensionscreatedbymembersoftheNetLogocommunityareavailablefrom
https://github.com/NetLogo/NetLogo/wiki/Extensions.
Forinformationoncreatingyourownextensions,gohere.
UsingExtensions
Touseanextensioninamodel,addtheextensionskeywordatthebeginningoftheCode
tab,beforedeclaringanybreedsorvariables.
Afterextensionscomesalistofextensionnamesinsquarebrackets.Forexample:
extensions [sound speech]
UsingextensionstellsNetLogotofindandopenthespecifiedextensionandmakesthe
customcommandsandreportersfoundintheextensionavailabletothecurrentmodel.You
canusethesecommandsandreportersjustasiftheywerebuilt-inNetLogoprimitives.
Whereextensionsarelocated
NetLogowilllookforextensionsinseveralplaces:
1. Inthefolderofthecurrentmodel.
2. TheextensionsfolderlocatedwiththeNetLogoinstallation.FortypicalNetLogo
installations:
OnMacOSX:/Applications/NetLogo 6.0.4/extensions
On64-bitWindowswith64-bitNetLogoor32-bitWindowswith32-bitNetLogo:
C:\Program Files\NetLogo 6.0.4\app\extensions
On64-bitWindowswith32-bitNetLogo:C:\Program Files (x86)\NetLogo
6.0.4\app\extensions
OnLinux:theapp/extensionssubdirectoryoftheNetLogodirectoryextractedfrom
theinstallation.tgz
EachNetLogoextensionconsistsofafolderwiththesamenameastheextension,entirelyin
lowercase.ThisfoldermustcontainaJARfilewiththesamenameasthefolder.For
example,thesoundextensionisstoredinafoldercalledsoundwithafileinsidecalled
sound.jar.
ToinstallaNetLogoextensionforusebyanymodel,puttheextension’sfolderintheNetLogo
extensionsdirectory.Or,youcanjustkeeptheextension’sfolderinthesamefolderasthe
modelthatusesit.
Someextensionsdependonadditionalfiles.Thesefileswillbeintheextension’sfolderalong
withtheJARfile.Thefoldermayalsocontainotherfilessuchasdocumentationandexample
models.
NetLogoArduinoExtension
Using
Forafirstusewithoutcompilingcode,dothefollowing:
1. AcquiretheNetLogosoftware.TheArduinoextensioncomespre-installedwith
NetLogo5.2.1andlater.
2. AcquireanArduinoboardandinstallthearduinoIDE
3. UsetheArduinoIDEtoedittheSketch(ifdesired)andsendtotheboard.(See
elaboratecommentsinthesketchforrecommendationsaboutwhattocomment
out/leaveindependingonyoursetup&circuitontheboard.)
4. OncetheArduinohasthesketchloadedonit,itwillrunthatsketchwheneveritis
poweredon.
5. Openthetest“ArduinoExample”modelintheNetLogoModelslibrary(it’sinthe
“IABMTextbook”>“Chapter8”folder)
6. ConnecttheArduinotoaUSBportonthecomputerifitisnotstillconnectedfrom
step3.
7. PressOPENtochoosetheporttocommunicatewithandestablishtheconnection.
8. Usethebuttonstosendbytecommands;usetheinterfacetoinspectvariable
value(s)thatyoursketchissending.
9. Notethatbytypingarduino:primitivesyoucangetalistoftheavailablecommands
intheextension.
Notes
ANetLogomodelusingthisextensionmustworkinconjunctionwithanArduinoSketch.
Thesetwoendpointscommunicatebywayofanapplicationprotocolthattheydefine.For
example,iftheNetLogomodelsendsabyte‘1’overthewirethismaymeansomethingto
theArduinoSketch,whichwillrespondaccordingly.TheArduinoSketchforitsownpart
maysendname-valuepairsovertheserialport,whichthencanbelookedup
asynchronouslybytheNetLogomodel.
Themodelerisfreetobuildassimpleorascomplexanapplicationprotocolontopofthis
rawcommunicationmechanism.
Theasynchronousnatureoftheboard-to-computercommunicationshasonenotable
limitation.Ifyouchoosetotrytosimulateasynchronous,BLOCKINGREAD
communicationspattern,(e.g.,bysendingabyte-basedsignaltotheboard,whichtriggers
aresponseinaknownname-valuepair),thenyouarelikelytobe‘offbyone’response.
Thatis,ifyoudothefollowinginNetLogocode:
arduino:write-byte b
show arduino:get "varname"
YouarelikelytogetthevalueofvarnamefromthePRIORcommandrepresentedby
writingthebyteb.ThisisbecausethesecondlineofNetLogocodewillexecutewhilethe
Arduinoisoffgeneratinganewvalueforvarname.
Therearewaysofgettingaroundthis(simulatingablockinginterfacebypollingonavalue
toindicatefresh“news”onvarname).Butthisextensionworksbestinsettingswherethe
ArduinoSketchis“chatty”andtheNetLogomodelsamplesthisstreamwhenitneeds
data.
Compatibility
ThiscodehasbeentestedonWindows7and10with32-bitNetLogoandonMacOSX.
Youarelikelytoencounterissueswhenrunningthiswith64-bitNetLogoinWindows8or
Windows10,soifyouhaveWindows8or10,pleasedownloadthe32-Bitversionof
NetLogoifyouplanonusingtheArduinoextension.Westriveforcross-platform
compatibilityacrossMac,Win,andLinux.Soifyouhavetroubles,pleaseletusknow.
Questions
Ifyourunintoproblemsorhavequestionsabouttheextension,pleaseemailccl-feedback
orcbrady@inquirelearning.com.
Primitives
arduino:primitivesarduino:portsarduino:openarduino:closearduino:getarduino:write-
stringarduino:write-intarduino:write-bytearduino:is-open?arduino:debug-to-arduino
arduino:debug-from-arduino
arduino:primitives
arduino:primitives
Reportsalistofprimitivesavailableintheextension,withbasichintsabouttheirsyntax.
arduino:ports
arduino:ports
Reportsalistofportnames
arduino:open
arduino:openport-name
Openstheportnamedport-name.
arduino:close
arduino:close
Closesthecurrentlyopenport.
arduino:get
arduino:getvar-name
Readsandreportsthevalueassociatedwithvar-nameontheArduinoboard.Ifthereisno
valueassociatedwithvar-name,returnsfalse.Note:var-nameiscaseinsensitive.
arduino:write-string
arduino:write-stringstring-message
Writesastringmessagetothecurrentlyopenport.
arduino:write-int
arduino:write-intint-message
Writesaintegermessagetothecurrentlyopenport.
arduino:write-byte
arduino:write-bytebyte-message
Writesabytemessagetothecurrentlyopenport.
arduino:is-open?
arduino:is-open?
Reportsabooleanvalue(trueorfalse)indicatingifaportisopen.
arduino:debug-to-arduino
arduino:debug-to-arduino
ReportsalistofthelastmessagessentfromNetLogototheArduino,uptoamaximumof
5messages.Eachentryinthislistisastringbeginningwith“s:”ifthemessagesentwasa
string,“i:”ifthemessagesentwasanint,and“b:”ifthemessagesentwasabyte.
arduino:debug-from-arduino
arduino:debug-from-arduino
ReportsalistoflistscontaininganyerrantmessagessentfromNetLogototheArduino,up
toamaximumof10errantmessages.Eachsublistcontainstherawmessageasitsfirst
elementandamessagedescribingtheerrorasthesecondelement.
NetLogoArrayExtension
Using
Thearrayextensionispre-installedinNetLogo.
Tousethearrayextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [array]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddarraytothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithanarrayinNetLogo,youcouldalsojustusealistfor.
Butyoumaywanttoconsiderusinganarrayinsteadforspeedreasons.Listsandarrays
havedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrun
fasterbyselectingtheappropriatedatastructure.
Arraysareusefulwhenyouneedacollectionofvalueswhosesizeisfixed.Youcan
quicklyaccessoralteranyiteminanarrayifyouknowitsposition.
UnlikeNetLogo’slistsandstrings,arraysare“mutable”.Thatmeansthatyoucanactually
modifythemdirectly,ratherthanconstructinganalteredcopyaswithlists.Ifthearrayis
usedinmorethanoneplaceinyourcode,anychangesyoumakewillshowup
everywhere.It’strickytowritecodeinvolvingmutablestructuresandit’seasytomake
subtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunless
you’recertainyouwantandneedmutability.
ExampleuseofArrayExtension
let a array:from-list n-values 5 [0]
print a
=> {{array: 0 0 0 0 0}}
print array:length a
=> 5
foreach n-values 5 [ i -> i ] [ i -> array:set a i i * i ]
print a
=> {{array: 0 1 4 9 16}}
print array:item a 0
=> 0
print array:item a 3
=> 9
array:set a 3 50
print a
=> {{array: 0 1 4 50 16}}
Primitives
array:from-listarray:itemarray:setarray:lengtharray:to-list
array:from-list
array:from-list
array:from-listlist
Reportsanewarraycontainingthesameitemsinthesameorderastheinputlist.
array:item
array:itemarrayindex
Reportstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthof
thearrayminusone).
array:set
array:setarrayindexvalue
Setstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthof
thearrayminusone)tothegivenvalue.
Notethatunlikethereplace-itemprimitiveforlists,anewarrayisnotcreated.Thegiven
arrayisactuallymodified.
array:length
array:lengtharray
Reportsthelengthofthegivenarray,thatis,thenumberofitemsinthearray.
array:to-list
array:to-listarray
Reportsanewlistcontainingthesameitemsinthesameorderasthegivenarray.
NetLogoBitmapExtension
Using
Thebitmapextensionispre-installedinNetLogo.Forinstructionsonusingit,orformore
informationaboutNetLogoextensions,seetheNetLogoUserManual.
WhatdoestheBitmapExtensiondo?
TheBitmapExtensionallowsyoutomanipulateandimportimagesintothedrawingand
patches.ItoffersfeaturesnotprovidedbytheNetLogocoreprimitives,suchas:scaling,
manipulationofdifferentcolorchannels,andwidthandheightreporters.
Gettingstarted
Toimportandmanipulateimagesyouwillneedtoincludethebitmapextensioninyour
NetLogomodel.
extensions[ bitmap ]
TheimagefileformatssupportedaredeterminedbyyourJavavirtualmachine’simageio
library.TypicallythisisPNG,JPG,GIF,andBMP.PNGisagood,standardchoicethatis
likelytoworkeverywhere.
Iftheimageformatsupportstransparency(alpha),thatinformationwillbeimportedas
well.
Primitives
bitmap:average-colorbitmap:channelbitmap:copy-to-drawingbitmap:copy-to-pcolors
bitmap:difference-rgbbitmap:exportbitmap:from-viewbitmap:to-grayscalebitmap:height
bitmap:importbitmap:scaledbitmap:width
bitmap:average-color
bitmap:average-colorimage
Reportsa3-elementlistdescribingtheamountofR,G,andBinimage,bysumming
acrossallpixels,andnormalizingeachcomponentbythenumberofpixelsintheimage,
soeachcomponentrangesfrom0to255.
bitmap:channel
bitmap:channelimagechannel
Extractseitherthealpha,red,green,orbluechannelfromanimage.Theinputchannel
shouldbeaninteger0-3indicatingthechanneltoremove(alpha=0,red=1,green=2,
blue=3).Theresultingimageisagrayscaleimagerepresentingspecifiedchannel.
bitmap:copy-to-drawing
bitmap:copy-to-drawingimagexy
Importsthegivenimageintothedrawingwithoutscalingtheimageatthegivenpixel
coordinates.
bitmap:copy-to-pcolors
bitmap:copy-to-pcolorsimageboolean
Importsthegivenimageintothepcolors,scaledtofittheworld.Thesecondinput
indicateswhetherthecolorsshouldbeinterpretedasNetLogocolorsorleftasRGB
colors.falsemeansRGBcolors.
bitmap:difference-rgb
bitmap:difference-rgbimage1image2
Reportsanimagethatistheabsolutevalueofthepixel-wiseRGBdifferencebetweentwo
images.Notethatimage1andimage2MUSTbethesamewidthandheightaseachother,
orerrorswillensue.
bitmap:export
bitmap:exportimagefilename
Writesimagetofilename.
bitmap:from-view
bitmap:from-view
Reportsanimageofthecurrentview.
bitmap:to-grayscale
bitmap:to-grayscaleimage
Convertsthegivenimagetograyscale.
bitmap:height
bitmap:heightimage
Reportstheheightofgivenimage
bitmap:import
bitmap:importfilename
ReportsaLogoBitmapcontainingtheimageatfilename.
bitmap:scaled
bitmap:scaledimagewidthheight
Reportsanewimagethatisimagescaledtothegivenwidthandheight
bitmap:width
bitmap:widthimage
Reportsthewidthofthegivenimage
NetLogoCfExtension
Primitives
cf:ifelsecf:ifelse-value
cf:ifelse
cf:ifelseconditionconsequentconditions/consequentsoptional-else
Runsthefirstcommandblockfollowingatruecondition:
let x 3
(cf:ifelse
x < 2 [ print "x is less than 2!" ]
x < 4 [ print "x is less than 4!" ]
x < 6 [ print "x is less than 6!" ]
[ print "x is greater than or equal to 6!" ])
Theabovecodewillprintoutx is less than 4! sincethat’sthefirstcasewithatrue
condition.
Afinalcommandblockwithoutamatchingconditionmaybeprovided,inwhichcaseitwill
runifnoothercommandblocksdo.Ifnosuchcommandblockisprovidedandno
conditionsaretrue,nothingwillhappen.
Thedefaultnumberofargumentsis3,sothatifyouonlyhaveonecondition,a
consequent,andanelseblock(likearegularNetLogoifelse),youdonotneed
parentheses:
cf:ifelse 0 < 1 [ print "hi" ] [ print "bye" ]
cf:ifelse-value
cf:ifelse-valueconditionconsequentconditions/consequentselse-reporter
Runsthefirstreporterfollowingatrueconditionandreportsitsvalue:
(cf:ifelse-value
x < 2 [ "x is less than 2!" ]
x < 4 [ "x is less than 4!" ]
x < 6 [ "x is less than 6!" ]
[ "x is greater than or equal to 6!" ])
Theabovecodewillreportx is less than 4! sincethat’sthefirstcasewithatrue
condition.
Unlikecf:ifelse,theelse-blockisrequiredincf:ifelse-value.Ifnoconditionistrue,the
resultoftheelseblockwillbereported.
Notethatcf:ifelse-valuehassomewhatdifferentassociativitythanNetLogo’sifelse,
makingitsothatyoudon’tneedtoputparenthesesaroundtheconditions,asintheabove
example.
Thedefaultnumberofargumentsis3,sothatifyouonlyhaveonecondition,a
consequent,andanelseblock(likearegularNetLogoifelse-value),youdonotneed
parentheses:
cf:ifelse-value 0 < 1 [ "hi" ] [ "bye" ]
NetLogoCsvExtension
Commonusecasesandexamples
Readafileallatonce
Justusecsv:from-file "/path/to/myfile.csv"!Seefrom-fileformoreinformation.
Readafileonelineatatime
Forreallybigfiles,youmaynotwanttostoretheentirefileinmemory,butratherjustprocessitalineata
time.Forinstance,ifyouwanttosumeachofthecolumnsofanumericCSVfile,youcando:
to-report sum-columns [ file ]
file-open file
set result csv:from-row file-read-line
while [ not file-at-end? ] [
let row csv:from-row file-read-line
set result (map [?1 + ?2] result row)
]
file-close
report result
end
Youcanalsousethistechniqueto…
Readafileonelinepertick
Here’sanexamplemodelthatreadsinafileonelinepertick:
globals [ data ]
to setup
clear-all
file-close-all % Close any files open from last run
file-open "data.csv"
% other setup goes here
reset-ticks
end
to go
if file-at-end? [ stop ]
set data csv:from-row file-read-line
% model update goes here
tick
end
Writeafile
Justusecsv:to-file "/path/to/myfile.csv" my-data!Seeto-fileformoreinformation.
Primitives
FormattingNetLogodataasCSV
csv:to-rowcsv:to-stringcsv:to-file
ParsingCSVinputtoNetLogodata
csv:from-rowcsv:from-stringcsv:from-file
csv:from-row
csv:from-rowstring
csv:from-rowstringdelimiter
ParsesthegivenstringasthoughitwerearowfromaCSVfileandreturnsitasalistofvalues.Forexample:
observer> show csv:from-row "one,two,three"
observer: ["one" "two" "three"]
Quotescanbeusedwhenitemscontaincommas:
observer> show csv:from-row "there's,a,comma,\"in,here\""
observer: ["there's" "a" "comma" "in,here"]
Youcanputtwoquotesinarowtoputanactualquoteinanentry.Iftheentryisnotquoted,youcanjustuse
onequote:
observer> foreach (csv:from-row "he said \"hi there\",\"afterwards, she said \"\"hello\"\"\"") print
he said "hi there"
afterwards, she said "hello"
Number-like-entrieswillbeparsedasnumbers:
observer> show csv:from-row "1,-2.5,1e3"
observer: [1 -2.5 1000]
trueandfalsewithanycapitalizationwillbeparsedasbooleans:
observer> show csv:from-row "true,TRUE,False,falsE"
observer: [true true false false]
Touseadifferentdelimiter,youcanspecifyasecond,optionalargument.Onlysinglecharacterdelimitersare
supported:
observer> show (csv:from-row "1;2;3" ";")
observer: [1 2 3]
Differenttypesofvaluescanbemixedfreely:
observer> show csv:from-row "one,2,true"
observer: ["one" 2 true]
csv:from-string
csv:from-stringstring
csv:from-stringstringdelimiter
ParsesastringrepresentationofoneormoreCSVrowsandreturnsitasalistoflistsofvalues.Forexample:
observer> show csv:from-string "1,two,3\nfour,5,true"
observer: [[1 "two" 3] ["four" 5 true]]
csv:from-file
csv:from-filecsv-file
csv:from-filecsv-filedelimiter
ParsesanentireCSVfiletoalistoflistsofvalues.Forexample,ifwehaveafileexample.csvthatcontains:
1,2,3
4,5,6
7,8,9
10,11,12
Then,weget:
observer> show csv:from-file "example.csv"
observer: [[1 2 3] [4 5 6] [7 8 9] [10 11 12]]
Theparserdoesn’tcareiftherowshavedifferentnumbersofitemsonthem.Thenumberofitemsintherows
listwillalwaysbe<number of delimiters> + 1 ,thoughblanklinesareskipped.Thismakeshandlingfileswith
headersquiteeasy.Forinstance,ifwehaveheader.csvthatcontains:
My Data
2/1/2015
Parameters:
start,stop,resolution,population,birth?
0,4,1,100,true
Data:
time,x,y
0,0,0
1,1,1
2,4,8
3,9,27
Thisgives:
observer> foreach csv:from-file "header.csv" show
observer: ["My Data"]
observer: ["2/1/2015"]
observer: ["Parameters:"]
observer: ["start" "stop" "resolution" "population" "birth?"]
observer: [0 4 1 100 true]
observer: ["Data:"]
observer: ["time" "x" "y"]
observer: [0 0 0]
observer: [1 1 1]
observer: [2 4 8]
observer: [3 9 27]
csv:to-row
csv:to-rowlist
csv:to-rowlistdelimiter
ReportsthegivenlistasaCSVrow.Forexample:
observer> show csv:to-row ["one" 2 true]
observer: "one,2,true"
csv:to-string
csv:to-stringlist
csv:to-stringlistdelimiter
ReportsthegivenlistoflistsasaCSVstring.Forexample:
observer> show csv:to-string [[1 "two" 3] [4 5]]
observer: "1,two,3\n4,5"
csv:to-file
csv:to-filecsv-filelist
csv:to-filecsv-filelistdelimiter
WritesthegivenlistofliststoanewCSVfile.Forexample:
observer> csv:to-file "myfile.csv" [[1 "two" 3] [4 5]]
willresultinafilemyfile.csvcontaining:
1,two,3
4,5
NetLogoGisExtension
Using
ThisextensionaddsGIS(GeographicInformationSystems)supporttoNetLogo.It
providestheabilitytoloadvectorGISdata(points,lines,andpolygons),andrasterGIS
data(grids)intoyourmodel.
TheextensionsupportsvectordataintheformofESRIshapefiles.Theshapefile(.shp)
formatisthemostcommonformatforstoringandexchangingvectorGISdata.The
extensionsupportsrasterdataintheformofESRIASCIIGridfiles.TheASCIIgridfile
(.ascor.grd)isnotascommonastheshapefile,butissupportedasaninterchange
formatbymostGISplatforms.
Howtouse
Ingeneral,youfirstdefineatransformationbetweenGISdataspaceandNetLogospace,
thenloaddatasetsandperformvariousoperationsonthem.Theeasiestwaytodefinea
transformationbetweenGISspaceandNetLogospaceistotaketheunionofthe
“envelopes”orboundingrectanglesofallofyourdatasetsinGISspaceandmapthat
directlytotheboundsoftheNetLogoworld.SeeGISGeneralExamplesforanexampleof
thistechnique.
YoumayalsooptionallydefineaprojectionfortheGISspace,inwhichcasedatasetswill
bere-projectedtomatchthatprojectionastheyareloaded,aslongaseachofyourdata
fileshasanassociated.prjfilethatdescribestheprojectionorgeographiccoordinate
systemofthedata.Ifnoassociated.prjfileisfound,theextensionwillassumethatthe
datasetalreadyusesthecurrentprojection,regardlessofwhatthatprojectionis.
Oncethecoordinatesystemisdefined,youcanloaddatasetsusinggis:load-dataset.This
primitivereportseitheraVectorDatasetoraRasterDataset,dependingonwhattypeoffile
youpassit.
AVectorDatasetconsistsofacollectionofVectorFeatures,eachoneofwhichisapoint,
line,orpolygon,alongwithasetofpropertyvalues.AsingleVectorDatasetmaycontain
onlyoneofthethreepossibletypesoffeatures.
ThereareseveralthingsyoucandowithaVectorDataset:askitforthenamesofthe
propertiesofitsfeatures,askitforits“envelope”(boundingrectangle),askforalistofall
VectorFeaturesinthedataset,searchforasingleVectorFeatureorlistofVectorFeatures
whosevalueforaparticularpropertyislessthanorgreaterthanaparticularvalue,orlies
withinagivenrange,ormatchesagivenstringusingwildcardmatching(“*”,which
matchesanynumberofoccurrencesofanycharacters).IftheVectorFeaturesare
polygons,youcanalsoapplythevaluesofaparticularpropertyofthedataset’sfeaturesto
agivenpatchvariable.
TherearealsoseveralthingsyoucandowithaVectorFeaturefromaVectorDataset:ask
itforalistofvertexlists,askitforapropertyvaluebyname,askitforitscentroid(centerof
gravity),andaskforasubsetofagivenagentsetwhoseagentsintersectthegiven
VectorFeature.Forpointdata,eachvertexlistwillbeaone-elementlist.Forlinedata,
eachvertexlistwillrepresenttheverticesofalinethatmakesupthatfeature.Forpolygon
data,eachvertexlistwillrepresentone“ring”ofthepolygon,andthefirstandlastvertex
ofthelistwillbethesame.ThevertexlistsaremadeupofvaluesoftypeVertex,andthe
centroidwillbeavalueoftypeVertexaswell.
ThereareanumberofoperationsdefinedforRasterDatasetsaswell.Mostlytheseinvolve
samplingthevaluesinthedataset,orre-samplingarastertoadifferentresolution.You
canalsoapplyarastertoagivenpatchvariable,andconvolvearasterusinganarbitrary
convolutionmatrix.
CodeExample:GISGeneralExampleshasgeneralexamplesofhowtousethe
extension
CodeExample:GISGradientExampleisamoreadvancedexampleofraster
datasetanalysis.
KnownIssues
ValuesoftypeRasterDataset,VectorDataset,VectorFeature,andVertexarenothandled
properlybyexport-worldandimport-world.Tosavedatasets,youmustusethe
gis:store-datasetprimitive.
Thereiscurrentlynowaytodistinguishpositive-area“shell”polygonsfromnegative-area
“hole”polygons,ortodeterminewhichholesareassociatedwithwhichshells.
Credits
TheprimarydeveloperoftheGISextensionwasEricRussell.
TheGISextensionmakesuseofseveralopen-sourcesoftwarelibraries.Forcopyrightand
licenseinformationonthose,seethecopyrightsectionofthemanual.Theextensionalso
containselementsborrowedfromMyWorldGIS.
ThisdocumentationandtheexampleNetLogomodelsareinthepublicdomain.TheGIS
extensionitselfisfreeandopensourcesoftware.SeetheREADME.mdfileinthe
extension/gisdirectoryfordetails.
WewouldlovetohearyoursuggestionsonhowtoimprovetheGISextension,orjust
aboutwhatyou’reusingitfor.PostquestionsandcommentsattheNetLogoUsersGroup,
orwritedirectlytoEricRussellandtheNetLogoteamatccl-gis@ccl.northwestern.edu
Primitives
RasterDatasetPrimitives
gis:width-ofgis:height-ofgis:raster-valuegis:set-raster-valuegis:minimum-of
gis:maximum-ofgis:sampling-method-ofgis:set-sampling-methodgis:raster-sample
gis:raster-world-envelopegis:create-rastergis:resamplegis:convolvegis:apply-raster
DatasetPrimitives
gis:load-datasetgis:store-datasetgis:type-ofgis:patch-datasetgis:turtle-dataset
gis:link-dataset
VectorDatasetPrimitives
gis:shape-type-ofgis:property-namesgis:feature-list-ofgis:vertex-lists-of
gis:centroid-ofgis:location-ofgis:property-valuegis:find-featuresgis:find-one-
featuregis:find-less-thangis:find-greater-thangis:find-rangegis:property-minimum
gis:property-maximumgis:apply-coveragegis:coverage-minimum-thresholdgis:set-
coverage-minimum-thresholdgis:coverage-maximum-thresholdgis:set-coverage-maximum-
thresholdgis:intersects?gis:contains?gis:contained-by?gis:have-relationship?
gis:relationship-ofgis:intersecting
CoordinateSystemPrimitives
gis:set-transformationgis:set-transformation-dsgis:set-world-envelopegis:set-world-
envelope-dsgis:world-envelopegis:envelope-ofgis:envelope-union-ofgis:load-
coordinate-systemgis:set-coordinate-system
DrawingPrimitives
gis:drawing-colorgis:set-drawing-colorgis:drawgis:fillgis:paintgis:import-wms-
drawing
gis:set-transformation
gis:set-transformationgis-envelopenetlogo-envelope
DefinesamappingbetweenGIScoordinatesandNetLogocoordinates.Thegis-envelope
andnetlogo-envelopeparametersmusteachbefour-elementlistsconsistingof:
[minimum-x maximum-x minimum-y maximum-y]
Thescaleofthetransformationwillbeequaltotheminimumofthescalenecessaryto
makethemappingbetweentherangesofxvaluesandthescalenecessarytomakethe
mappingbetweentherangesofyvalues.TheGISspacewillbecenteredinNetLogo
space.
Forexample,thefollowingtwolistswouldmapallofgeographic(latitudeandlongitude)
spaceindegreestoNetLogoworldspace,regardlessofthecurrentdimensionsofthe
NetLogoworld:
(list -180 180 -90 90)
(list min-pxcor max-pxcor min-pycor max-pycor)
However,ifyou’resettingtheenvelopeoftheNetLogoworld,youshouldprobablybe
usingset-world-envelope.
gis:set-transformation-ds
gis:set-transformation-dsgis-envelopenetlogo-envelope
Doesthesamethingasset-transformationabove,exceptthatitallowsthescalefor
mappingtherangeofxvaluestobedifferentthanthescaleforyvalues.The“-ds”onthe
endstandsfor“differentscales”.Usingdifferentscaleswillcausedistortionoftheshape
ofGISfeatures,andsoitisgenerallynotrecommended,butitmaybeusefulforsome
models.
Hereisanexampleofthedifferencebetweenset-transformationandset-transformation-
ds:
Using[set-transformation]
(#gisset-transformation),the
scalealongthexandyaxisis
thesame,preservingtheround
shapeoftheEarthinthis
Orthographicprojection.
Using[set-transformation-ds](#gisset-
transformation-ds),thescalealong
thexaxisisstretchedsothatthe
earthcoverstheentireNetLogoView,
whichinthiscasedistortstheshape
oftheEarth.
gis:set-world-envelope
gis:set-world-envelopegis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworld
tothegivenenvelopeinGISspace,whilekeepingthescalesalongthexandyaxisthe
same.Itisequivalentto:
set-transformation gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Thisprimitiveissuppliedbecausemostofthetimeyou’llwanttosettheenvelopeofthe
entireNetLogoworld,ratherthanjustapartofit.
gis:set-world-envelope-ds
gis:set-world-envelope-dsgis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworld
tothegivenenvelopeinGISspace,usingdifferentscalesalongthexandyaxisif
necessary.Itisequivalentto:
set-transformation-ds gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Seethepicturesaboveforthedifferencebetweenusingequalscalesforxandy
coordinatesandusingdifferentscales.
gis:world-envelope
gis:world-envelope
Reportstheenvelope(boundingrectangle)oftheNetLogoworld,transformedintoGIS
space.Anenvelopeconsistsofafour-elementlistoftheform:
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-of
gis:envelope-ofthing
Reportstheenvelope(boundingrectangle)ofthinginGIScoordinates.Thethingmaybe
anAgent,anAgentSet,aRasterDataset,aVectorDataset,oraVectorFeature.An
envelopeconsistsofafour-elementlistoftheform:
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-union-of
gis:envelope-union-ofenvelope1envelope2
gis:envelope-union-ofenvelope1...
Reportsanenvelope(boundingrectangle)thatentirelycontainsthegivenenvelopes.An
envelopeconsistsofafour-elementlistoftheform
[minimum-x maximum-x minimum-y maximum-y]
Noassumptionismadeaboutthecoordinatesystemofthearguments,thoughiftheyare
notinthesamecoordinatesystem,resultswillbeunpredictable.
gis:load-coordinate-system
gis:load-coordinate-systemfile
Loadsanewglobalprojectionusedforprojectingorre-projectingGISdataasitisloaded
fromafile.ThefilemustcontainavalidWell-KnownText(WKT)projectiondescription.
WKTprojectionfilesarefrequentlydistributedalongsideGISdatafiles,andusuallyhavea
“.prj”filenameextension.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’s
homedirectoryifthecurrentmodelhasn’tbeensavedyet.
TheGISextensiondoesnotsupportallWKTcoordinatesystemsandprojections.Only
geographic("GEOGCS")andprojected("PROJCS")coordinatesystemsaresupported.For
projectedcoordinatesystems,onlythefollowingprojectionsaresupported:
Albers_Conic_Equal_Area
Lambert_Conformal_Conic_2SP
Polyconic
Lambert_Azimuthal_Equal_Area
Mercator_1SP
Robinson
Azimuthal_Equidistant
Miller
Stereographic
Cylindrical_Equal_Area
Oblique_Mercator
Transverse_Mercator
Equidistant_Conic
hotine_oblique_mercator
Gnomonic
Orthographic
Seeremotesensing.orgforacompletelistofWKTprojectionsandtheirparameters.
gis:set-coordinate-system
gis:set-coordinate-systemsystem
Setstheglobalprojectionusedforprojectingorre-projectingGISdataasitisloaded.The
systemmustbeeitherastringinWell-KnownText(WKT)format,oraNetLogolistthat
consistsofWKTconvertedtoalistbymovingeachkeywordinsideitsassociatedbrackets
andputtingquotesaroundit.Thelatterispreferredbecauseitmakesthecodemuchmore
readable.
ThesamelimitationsonWKTsupportapplyasdescribedaboveinthedocumentationfor
load-coordinate-system
gis:load-dataset
gis:load-datasetfile
Loadsthegivendatafile,re-projectingthedataasnecessaryifaglobalprojectionis
definedandifthedatafileitselfhasanassociated.prjfile,thenreportstheresulting
dataset.
Ifno“.prj”fileispresent,thenload-datasetassumesthattheprojectionofthedatabeing
loadedisthesameasthecurrentglobalcoordinatesystem.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’s
homedirectoryifthecurrentmodelhasn’tbeensavedyet.
Currently,twotypesofdatafilearesupported:
.shp”(ESRIshapefile):containsvectordata,consistingofpoints,lines,orpolygons.
Whenthetargetfileisashapefile,load-datasetreportsaVectorDataset.
.asc”or“.grd”(ESRIASCIIgrid):containsrasterdata,consistingofagridofvalues.
WhenthetargetfileisanASCIIgridfile,load-datasetreportsaRasterDataset.
gis:store-dataset
gis:store-datasetdatasetfile
Savesthegivendatasettothegivenfile.Ifthenameofthefiledoesnothavetheproper
fileextension,theextensionwillbeautomaticallyappendedtothename.Relativepaths
areresolvedrelativetothelocationofthecurrentmodel,ortheuser’shomedirectoryif
thecurrentmodelhasn’tbeensavedyet.
Currently,thisprimitiveonlyworksforRasterDatasets,anditcanonlysavethosedatasets
asESRIASCIIgridfiles.
gis:type-of
gis:type-ofdataset
ReportsthetypeofthegivenGISdataset:either“VECTOR”or“RASTER”
gis:patch-dataset
gis:patch-datasetpatch-variable
ReportsanewrasterwhosecellscorresponddirectlytoNetLogopatches,andwhosecell
valuesconsistofthevaluesofthegivenpatchvariable.Thisprimitiveisbasicallythe
inverseofapply-raster;apply-rastercopiesvaluesfromarasterdatasettoapatch
variable,whilethisprimitivecopiesvaluesfromapatchvariabletoarasterdataset.
gis:turtle-dataset
gis:turtle-datasetturtle-set
Reportsanew,pointVectorDatasetbuiltfromtheturtlesinthegivenagentset.Thepoints
arelocatedatlocationsoftheturtles,translatedfromNetLogospaceintoGISspaceusing
thecurrentcoordinatetransformation.Andthedataset’spropertiesconsistofallofthe
turtlevariablescommontoeveryturtleintheagentset.
gis:link-dataset
gis:link-datasetlink-set
Reportsanew,lineVectorDatasetbuiltfromthelinksinthegivenagentset.Theendpoints
ofeachlineareatthelocationoftheturtlesconnectedbyeachlink,translatedfrom
NetLogospaceintoGISspaceusingthecurrentcoordinatetransformation.Andthe
dataset’spropertiesconsistofallofthelinkvariablescommontoeverylinkinthe
agentset.
gis:shape-type-of
gis:shape-type-ofVectorDataset
Reportstheshapetypeofthegivendataset.Thepossibleoutputvaluesare“POINT”,
“LINE”,and“POLYGON”.
gis:property-names
gis:property-namesVectorDataset
Reportsalistofstringswhereeachstringisthenameofapropertypossessedbyeach
VectorFeatureinthegivenVectorDataset,suitableforuseingis:property-value.
gis:feature-list-of
gis:feature-list-ofVectorDataset
ReportsalistofallVectorFeaturesinthegivendataset.
gis:vertex-lists-of
gis:vertex-lists-ofVectorFeature
ReportsalistoflistsofVertexvalues.Forpointdatasets,eachvertexlistwillcontain
exactlyonevertex:thelocationofapoint.Forlinedatasets,eachvertexlistwillcontainat
leasttwopoints,andwillrepresenta“polyline”,connectingeachadjacentpairofvertices
inthelist.Forpolygondatasets,eachvertexlistwillcontainatleastthreepoints,
representingapolygonconnectingeachvertex,andthefirstandlastverticesinthelistwill
bethesame.
gis:centroid-of
gis:centroid-ofVectorFeature
ReportsasingleVertexrepresentingthecentroid(centerofgravity)ofthegivenfeature.
Forpointdatasets,thecentroidisdefinedastheaveragelocationofallpointsinthe
feature.Forlinedatasets,thecentroidisdefinedastheaverageofthelocationsofthe
midpointsofalllinesegmentsinthefeature,weightedbysegmentlength.Forpolygon
datasets,thecentroidisdefinedastheweightedsumofthecentroidsofadecomposition
oftheareainto(possiblyoverlapping)triangles.SeethisFAQformoredetailsonthe
polygoncentroidalgorithm.
gis:location-of
gis:location-ofVertex
Reportsatwo-elementlistcontainingthexandyvalues(inthatorder)ofthegivenvertex
translatedintoNetLogoworldspaceusingthecurrenttransformation,oranemptylistif
thegivenvertexliesoutsidetheNetLogoworld.
gis:property-value
gis:property-valueVectorFeatureproperty-name
ReportsthevalueofthepropertywiththegivennameforthegivenVectorDataset.The
reportedvaluemaybeanumber,astring,orabooleanvalue,dependingonthetypeof
thefieldintheunderlyingdatafile.
Forshapefiles,valuesfromdBaseCHARACTERandDATEfieldsarereturnedasstrings,
valuesfromNUMBERandFLOATfieldsarereturnedasnumbers,andvaluesfromLOGICAL
fieldsarereturnedasbooleanvalues.MEMOfieldsarenotsupported.DATEvaluesare
convertedtostringsusingISO8601format(YYYY-MM-DD).
gis:find-features
gis:find-featuresVectorDatasetproperty-namespecified-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-namematchesspecified-value(astring).Valuecomparisonisnotcasesensitive,
andthewildcardcharacter“*”willmatchanynumberofoccurrences(includingzero)of
anycharacter.
gis:find-one-feature
gis:find-one-featureVectorDatasetproperty-namespecified-value
ReportsthefirstVectorFeatureinthedatasetwhosevalueforthepropertyproperty-name
matchesthegivenstring.Valuecomparisonisnotcasesensitive,andthewildcard
character“*”willmatchanynumberofoccurrences(includingzero)ofanycharacter.
Featuresaresearchedintheorderthattheyappearinthedatafilethatwasthesourceof
thedataset,andsearchingstopsassoonasamatchisfound.Reportsnobodyifno
matchingVectorFeatureisfound.
gis:find-less-than
gis:find-less-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameislessthanthegivenvalue.Stringvaluesarecomparedusingcase-
sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalue
foranumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-greater-than
gis:find-greater-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameisgreaterthanthegivenvalue.Stringvaluesarecomparedusingcase-
sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalue
foranumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-range
gis:find-rangeVectorDatasetproperty-nameminimum-valuemaximum-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameisstrictlygreaterthanminimum-valueandstrictlylessthanmaximum-
value.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedin
theJavaDocumentation.Usingastringvalueforanumericpropertyoranumericvaluefor
astringpropertywillcauseanerror.
gis:property-minimum
gis:property-minimumVectorDatasetproperty-name
ReportsthesmallestvalueforthegivenpropertyoveralloftheVectorFeaturesinthe
givendataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderas
definedintheJavaDocumentation.
gis:property-maximum
gis:property-maximumVectorDatasetproperty-name
ReportsthelargestvalueforthegivenpropertyoveralloftheVectorFeaturesinthegiven
dataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefined
intheJavaDocumentation.
gis:apply-coverage
gis:apply-coverageVectorDatasetproperty-namepatch-variable
CopiesvaluesfromthegivenpropertyoftheVectorDataset’sfeaturestothegivenpatch
variable.Thedatasetmustbeapolygondataset;pointsandlinesarenotsupported.
Foreachpatch,itfindsallVectorFeaturesthatintersectthatpatch.Then,ifthepropertyis
astringproperty,itcomputesthemajorityvaluebycomputingthetotalareaofthepatch
coveredbyVectorFeatureshavingeachpossiblevalueoftheproperty,thenreturningthe
valuewhichrepresentsthelargestproportionofthepatcharea.Ifthepropertyisa
numericproperty,itcomputesaweightedaverageofpropertyvaluesfromall
VectorFeatureswhichintersectthepatch,weightedbytheproportionofthepatcharea
theycover.
Therearetwoexceptionstothisdefaultbehavior:
Ifapercentageofapatches’areagreaterthanthecoverage-maximum-thresholdis
coveredbyasingleVectorFeature,thenthepropertyvaluefromthatVectorFeature
iscopieddirectly.IfmorethanoneVectorFeaturecoversapercentageofarea
greaterthanthethreshold,onlythefirstwillbeused.
Ifthetotalpercentageofapatches’areacoveredbyVectorFeaturesislessthanthe
coverage-minimum-threshold,thetargetpatchvariableissettoNotANumber.
Bydefault,theminimumthresholdis10%andthemaximumthresholdis33%.These
valuesmaybemodifiedusingthefourprimitivesthatfollow.
gis:coverage-minimum-threshold
gis:coverage-minimum-threshold
Reportsthecurrentcoverageminimumthresholdusedbygis:apply-coverage.
gis:set-coverage-minimum-threshold
gis:set-coverage-minimum-thresholdnew-threshold
Setsthecurrentcoverageminimumthresholdtobeusedbygis:apply-coverage.
gis:coverage-maximum-threshold
gis:coverage-maximum-threshold
Reportsthecurrentcoveragemaximumthresholdusedbygis:apply-coverage.
gis:set-coverage-maximum-threshold
gis:set-coverage-maximum-thresholdnew-threshold
Setsthecurrentcoveragemaximumthresholdtobeusedbygis:apply-coverage.
gis:intersects?
gis:intersects?xy
Reportstrueifthegivenobjects’spatialrepresentationsshareatleastonepointin
common,andfalseotherwise.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contains?
gis:contains?xy
Reportstrueifeverypointofy’sspatialrepresentationisalsoapartofx’sspatial
representation.Notethatthismeansthatpolygonsdocontaintheirboundaries.The
objectsxandymaybeanyoneof
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contained-by?
gis:contained-by?xy
Reportstrueifeverypointofx’sspatialrepresentationisalsoapartofy’sspatial
representation.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:have-relationship?
gis:have-relationship?xy
Reportstrueifthespatialrepresentationsofthetwoobjectshavethegivenspatial
relationship,andfalseotherwise.Thespatialrelationshipisspecifiedusinga
DimensionallyExtendedNine-IntersectionModel(DE-9IM)matrix.Thematrixconsists
of9elements,eachofwhichspecifiestherequiredrelationshipbetweenthetwoobjects’
interiorspace,boundaryspace,orexteriorspace.Theelementsmusthaveoneofsix
possiblevalues:
“T”,meaningthespacesmustintersectinsomeway
“F”,meaningthespacesmustnotintersectinanyway
“0”,meaningthedimensionofthespaces’intersectionmustbezero(i.e.,itmustbea
pointornon-emptysetofpoints).
“1”,meaningthedimensionofthespaces’intersectionmustbeone(i.e.,itmustbea
lineornon-emptysetoflinesegments).
“2”,meaningthedimensionofthespaces’intersectionmustbetwo(i.e.,itmustbea
polygonorsetofpolygonswhoseareaisgreaterthanzero).
“*”,meaningthatthetwospacesmayhaveanyrelationship.
Forexample,thismatrix:
x
Interior Boundary Exterior
y
Interior T * *
Boundary * * *
Exterior F F *
wouldreturntrueifandonlyifsomepartofobjectx’sinteriorliesinsideobjecty’sinterior,
andnopartofobjectx’sinteriororboundaryintersectsobjecty’sexterior.Thisis
essentiallyamorerestrictiveformofthecontains?primitive;oneinwhichpolygonsare
notconsideredtocontaintheirboundaries.
Thematrixisgiventothehave-relationship?primitiveasastring,whoseelementsare
giveninthefollowingorder:
123
456
789
Sotousetheexamplematrixabove,youwouldwrite:
gis:have-relationship? x y "T*****FF*"
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociated
point-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:relationship-of
gis:relationship-ofxy
ReportstheDimensionallyExtendedNine-IntersectionModel(DE-9IM)matrixthat
describesthespatialrelationshipofthetwoobjects.Thematrixconsistsof9elements,
eachofwhichdescribestherelationshipbetweenthetwoobjects’interiorspace,boundary
space,orexteriorspace.Eachelementwilldescribethedimensionoftheintersectionof
twospaces,meaningthatitmayhaveoneoffourpossiblevalues:
“-1”,meaningthespacesdonotintersect
“0”,meaningthedimensionofthespaces’intersectioniszero(i.e.,theyintersectata
pointorsetofpoints).
“1”,meaningthedimensionofthespaces’intersectionisone(i.e.,theyintersectalong
oneormorelines).
“2”,meaningthedimensionofthespaces’intersectionistwo(i.e.,theirintersectionisa
non-emptypolygon).
Forexample,thetwopolygonsxandyshownhere:
havethefollowingDE-9IMmatrix:
x
Interior Boundary Exterior
y
Interior 2 1 2
Boundary 1 0 1
Exterior 2 1 2
Whichwouldbereportedbytherelationship-ofprimitiveasthestring“212101212”.
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociated
point-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:intersecting
patch-setgis:intersectingdata
Reportsanewagentsetcontainingonlythosemembersofthegivenagentsetwhich
intersectgivenGISdata,whichmaybeanyoneof:aVectorDataset,aVectorFeature,an
Agent,anAgentSet,oralistcontaininganyoftheabove.
gis:width-of
gis:width-ofRasterDataset
Reportsthenumberofcolumnsinthedataset.Notethatthisisthenumberofcellsfrom
lefttoright,notthewidthofthedatasetinGISspace.
gis:height-of
gis:height-ofRasterDataset
Reportsthenumberofrowsinthedataset.Notethatthisisthenumberofcellsfromtopto
bottom,nottheheightofthedatasetinGISspace.
gis:raster-value
gis:raster-valueRasterDatasetxy
Reportsthevalueofthegivenrasterdatasetinthegivencell.Cellcoordinatesare
numberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleft
cellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset
-1).
gis:set-raster-value
gis:set-raster-valueRasterDatasetxyvalue
Setsthevalueofthegivenrasterdatasetatthegivencelltoanewvalue.Cellcoordinates
arenumberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupper
leftcellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of
dataset-1).
gis:minimum-of
gis:minimum-ofRasterDataset
Reportsthehighestvalueinthegivenrasterdataset.
gis:maximum-of
gis:maximum-ofRasterDataset
Reportsthelowestvalueinthegivenrasterdataset.
gis:sampling-method-of
gis:sampling-method-ofRasterDataset
Reportsthesamplingmethodusedtocomputethevalueofthegivenrasterdatasetata
singlepoint,oroveranareasmallerthanasinglerastercell.Samplingisperformedbythe
GISextensionprimitivesraster-sample,resample,convolve,andapply-raster.The
samplingmethodwillbeoneofthefollowing:
"NEAREST_NEIGHBOR":thevalueofthecellnearestthesamplinglocationisused.
"BILINEAR":thevalueofthefournearestcellsaresampledbylinearweighting,
accordingtotheirproximitytothesamplingsite.
"BICUBIC":thevalueofthesixteennearestcellsaresampled,andtheirvaluesare
combinedbyweightaccordingtoapiecewisecubicpolynomialrecommendedby
Rifman(seeDigitalImageWarping,GeorgeWolberg,1990,pp129-131,IEEE
ComputerSocietyPress).
"BICUBIC_2":thevalueissampledusingthesameprocedureandthesamepolynomial
aswithBICUBICabove,butusingadifferentcoefficient.Thismethodmayproduce
somewhatsharperresultsthanBICUBIC,butthatresultisdatadependent.
Formoreinformationonthesesamplingmethodsandonrastersamplingingeneral,see
thiswikipediaarticle.
gis:set-sampling-method
gis:set-sampling-methodRasterDatasetsampling-method
Setsthesamplingmethodusedbythegivenrasterdatasetatasinglepoint,oroveran
areasmallerthanasinglerastercell.SamplingisperformedbytheGISextension
primitivesraster-sample,resample,convolve,andapply-raster.Thesamplingmethodmust
beoneofthefollowing:
"NEAREST_NEIGHBOR"
"BILINEAR"
"BICUBIC"
"BICUBIC_2"
Seesampling-method-ofaboveforamorespecificdescriptionofeachsamplingmethod.
gis:raster-sample
gis:raster-sampleRasterDatasetsample-location
Reportsthevalueofthegivenrasteroverthegivenlocation.Thelocationmaybeanyof
thefollowing:
Alistoflength2,whichistakentorepresentapointinnetlogospace([xcor ycor])of
thesortreportedbylocation-ofVertex.Therasterdatasetissampledatthepointofthat
location.
Alistoflength4,whichistakentorepresentanenvelopeinGISspace,ofthesort
reportedbyenvelope-of.Therasterdatasetissampledovertheareaofthatenvelope.
Apatch,inwhichcasetherasterdatasetissampledovertheareaofthepatch.
Aturtle,inwhichcasetherasterdatasetissampledatthelocationofthatturtle.
AVertex,inwhichcasetherasterdatasetissampledatthelocationofthatVertex.
Iftherequestedlocationisoutsidetheareacoveredbytherasterdataset,thisprimitive
reportsthespecialvaluerepresenting“notanumber”,whichisprintedbyNetLogoas
“NaN”.Usingthespecial“notanumber”valueasanargumenttoprimitivesthatexpecta
numbermaycauseanerror,butyoucantestthevaluereportedbythisprimitivetofilter
out“notanumber”values.Avaluethatisnotanumberwillbeneitherlessthannor
greaterthananumbervalue,soyoucandetect“notanumber”valuesusingthefollowing:
let value gis:raster-sample dataset turtle 0
; set color to blue if value is a number, red if value is "not a number"
ifelse (value <= 0) or (value >= 0)
[ set color blue ]
[ set color red ]
Iftherequestedlocationisapoint,thesampleisalwayscomputedusingthemethodset
byset-sampling-method.Iftherequestedlocationisanarea(i.e.,anenvelopeorpatch),
thesampleiscomputedbytakingtheaverageofallrastercellscoveredbytherequested
area.
gis:raster-world-envelope
gis:raster-world-envelopeRasterDatasetxy
ReportstheGISenvelopeneededtomatchtheboundariesofNetLogopatcheswiththe
boundariesofcellsinthegivenrasterdataset.Thisenvelopecouldthenbeusedasan
argumenttoset-transformation-ds.
TheremaybemorecellsinthedatasetthantherearepatchesintheNetLogoworld.In
thatcase,youwillneedtoselectasubsetofcellsinthedatasetbyspecifyingwhichcellin
thedatasetyouwanttomatchwiththeupper-leftcorneroftheNetLogoworld.Cellsare
numberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleft
cellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset
-1).
gis:create-raster
gis:create-rasterwidthheightenvelope
Createsandreportsanew,emptyrasterdatasetwiththegivennumberofcolumnsand
rows,coveringthegivenenvelope.
gis:resample
gis:resampleRasterDatasetenvelopewidthheight
ReportsanewdatasetthatconsistsofthegivenRasterDatasetresampledtocoverthe
givenenvelopeandtocontainthegivennumberofcolumnsandrows.Ifthenewraster’s
cellsaresmallerthantheexistingraster’scells,theywillberesampledusingthemethod
setbyset-sampling-method.Ifthenewcellsarelargerthantheoriginalcells,theywillbe
sampledusingthe"NEAREST_NEIGHBOR"method.
gis:convolve
gis:convolveRasterDatasetkernel-rowskernel-columnskernelkey-columnkey-row
Reportsanewrasterwhosedataconsistsofthegivenrasterconvolvedwiththegiven
kernel.
Aconvolutionisamathematicaloperationthatcomputeseachoutputcellbymultiplying
elementsofakernelwiththecellvaluessurroundingaparticularsourcecell.Akernelisa
matrixofvalues,withoneparticularvaluedefinedasthe“keyelement”,thevaluethatis
centeredoverthesourcecellcorrespondingtothedestinationcellwhosevalueisbeing
computed.
Thevaluesofthekernelmatrixaregivenasalist,whichenumeratestheelementsofthe
matrixfromlefttoright,toptobottom.Sotheelementsofa3-by-3matrixwouldbelisted
inthefollowingorder:
123
456
789
Thekeyelementisspecifiedbycolumnandrowwithinthematrix.Columnsarenumbered
fromlefttoright,beginningwithzero.Rowsarenumberedfromtoptobottom,also
beginningwithzero.So,forexample,thekernelforthehorizontalSobeloperator,which
lookslikethis:
1 0 -1
20
(key) -2
1 0 -1
wouldbespecifiedasfollows:
let horizontal-gradient gis:convolve dataset 3 3 [1 0 -1 2 0 -2 1 0 -1] 1 1
gis:apply-raster
gis:apply-rasterRasterDatasetpatch-variable
Copiesvaluesfromthegivenrasterdatasettothegivenpatchvariable,resamplingthe
rasterasnecessarysothatitscellboundariesmatchupwithNetLogopatchboundaries.
Thisresamplingisdoneasifusingresampleratherthanraster-sample,forthesakeof
efficiency.However,patchesnotcoveredbytherasterareassignedvaluesof“nota
number”inthesamewaythatraster-samplereportsvaluesforlocationsoutsidethe
raster.
gis:drawing-color
gis:drawing-color
ReportsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogo
drawinglayer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumber
betweenzeroand140)oranRGBcolor(alistof3numbers).SeedetailsintheColors
sectionoftheProgrammingGuide.
gis:set-drawing-color
gis:set-drawing-colorcolor
SetsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogodrawing
layer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumberbetweenzero
and140)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionofthe
ProgrammingGuide.
gis:draw
gis:drawvector-dataline-thickness
DrawsthegivenvectordatatotheNetLogodrawinglayer,usingthecurrentGISdrawing
color,withthegivenlinethickness.Thedatamayconsisteitherofanentire
VectorDataset,orasingleVectorFeature.Thisprimitivedrawsonlytheboundaryof
polygondata,andforpointdata,itfillsacirclewitharadiusequaltothelinethickness.
gis:fill
gis:fillvector-dataline-thickness
FillsthegivenvectordataintheNetLogodrawinglayerusingthecurrentGISdrawing
color,usingthegivenlinethicknessaroundtheedges.Thedatamayconsisteitherofan
entireVectorDataset,orasingleVectorFeature.Forpointdata,itfillsacirclewitharadius
equaltothelinethickness.
gis:paint
gis:paintRasterDatasettransparency
PaintsthegivenrasterdatatotheNetLogodrawinglayer.Thehighestvalueinthe
datasetispaintedwhite,thelowestispaintedinblack,andtheothervaluesarepaintedin
shadesofgrayscaledlinearlybetweenwhiteandblack.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.
Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
gis:import-wms-drawing
gis:import-wms-drawingserver-urlspatial-referencelayerstransparency
ImportsanimageintotheNetLogodrawinglayerusingtheWebMappingService
protocol,asdefinedbytheOpenGeospatialConsortium.
Thespatialreferenceandlayersinputsshouldbegivenasstrings.Thespatialreference
inputcorrespondstotheSRSparametertotheGetMaprequestasdefinedinsection
7.2.3.5ofversion1.1.1oftheWMSstandard.Thelayersinputcorrespondstothe
LAYERSparametertotheasdefinedin7.2.3.3ofversion1.1.1oftheWMSstandard.
Youcanfindthelistofvalidspatialreferencecodesandlayernamesbyexaminingthe
responsetoaGetCapabilitiesrequesttotheWMSserver.Consulttherelevantstandard
forinstructionsonhowtoissueaGetCapabilitiesrequesttotheserverandhowto
interprettheresults.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.
Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
NetLogoGogoExtension
Usage
TheGoGoExtensioncomespreinstalledwhenyoudownloadandinstallNetLogo.Touse
theextensioninyourmodel,addthislinetothetopofyourCodetab:
extensions [ gogo ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddgogotothelist.
Afterloadingtheextension,youcanseewhetheroneormoreHID-basedgogosareon
andattachedtothecomputerbytypingthefollowingintothecommandcenter:
gogo:howmany-gogos
Changes
ComparedtopreviousversionsoftheGoGoextension,thisversionoffers:
Improvedrobustness.WithpriorversionsoftheGoGoextension,crasheswerefairly
commonduetoproblemsintheUSB-Serialstackacrossplatforms.TheswitchtoHID
improvedrobustness,andthenewextensionalsousesa“daemon”architecturewhich
shieldsNetLogofromanyproblemsthatmayoccurindirectcommunicationwiththe
GoGoboard.TheresultisasubstantialreductioninthenumberofcrashesofNetLogo.
NoInstallationofDrivers.BecausethenewGoGofirmwarepresentstheboardasan
HIDdevice,theextensioncouldbewrittensoasnottorequireinstallingdrivers.This
meansthereisnoneedfortheusertohaveadministratorrightsonthecomputer.
DirectionalityforMotors.Theboardnowhaspolarity-ensuringoutputconnectors,so
that“counterclockwise”or“clockwise”cannowbespecifiedincode.
Primitives
OtherOutputs
gogo:ledgogo:beep
Utilities
gogo:read-all
General
gogo:primitivesgogo:howmany-gogos
Sensors
gogo:read-sensorsgogo:read-sensor
OutputsandServos
gogo:talk-to-output-portsgogo:set-output-port-powergogo:output-port-ongogo:output-
port-offgogo:output-port-clockwisegogo:output-port-counterclockwisegogo:set-servo
gogo:primitives
gogo:primitives
Returnsalistoftheprimitivesofthisextension.
gogo:howmany-gogos
gogo:howmany-gogos
ReportsthenumberofUSBHIDdevicesvisibletothecomputerandhavingthecorrect
vendorandproductIDtobeaGoGoboard.Aboardwillonlybedetectedifitisboth
connectedandpoweredon.Usingthisprimitiveisonewaytodeterminequicklywhethera
GoGoboardhastheHIDfirmwareloaded.(AUSB-Serialversionoftheboardwillnotbe
detected.).
gogo:talk-to-output-ports
gogo:talk-to-output-portslist-of-portnames
Establishesalistofoutputportsthatwillbecontrolledwithsubsequentoutput-port
commands.Seebelow…
gogo:set-output-port-power
gogo:set-output-port-powerpower-level
power-levelisanumberbetween0and100,reflectingthepercentageofmaximum
power.Setstheamountofpowerthatwillbefedtotheoutputportsindicatedintalk-to-
output-ports.Thiswillnotaffecttheon-offstateoftheoutputports.So,forexample,ifa
motorisalreadyconnectedtoanoutputportandrunning,changingitspowerwillchange
itsspeed.Ifthemotorisnotrunning,changingthepowerlevelwillnotturniton;instead,it
willaffectthespeedatwhichthemotorstartswhenitisturnedonwithoutput-port-on.
gogo:output-port-on
gogo:output-port-on
Turnsontheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehave
beensetwithtalk-to-output-ports,noportswillbeturnedon.
gogo:output-port-off
gogo:output-port-off
Turnsofftheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehave
beensetwithtalk-to-output-ports,noportswillbeturnedoff.
gogo:output-port-clockwise
gogo:output-port-clockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,so
thatamotorattachedtooneoftheseportswouldturnclockwise.
gogo:output-port-counterclockwise
gogo:output-port-counterclockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,
sothatamotorattachedtooneoftheseportswouldturncounterclockwise.
gogo:set-servo
gogo:set-servonumber
SetsthePulse-WidthModulation(PWM)proportionoftheoutputport(s)thathavebeen
specifiedwithtalk-to-output-ports.Notethattheservoconnectorsarethemalepinsnext
tothestandardmotorconnectors.DifferentservosrespondtodifferentPWMranges,but
allservosreadPWMproportionsandsetthepositionoftheirmaingearaccordingly.
gogo:led
gogo:ledon-or-off
Turnstheuser-LEDonoroff,dependingontheargument.gogo:led1turnstheLEDon;
gogo:led0turnsitoff.
gogo:beep
gogo:beep
CausestheGoGoboardtobeep.
gogo:read-sensors
gogo:read-sensors
ReportsalistcontainingthecurrentreadingsofalleightsensorsportsoftheGoGo.
gogo:read-sensor
gogo:read-sensorwhich-sensor
Reportsthevalueofsensornumberwhich-sensor,wherewhich-sensorisanumber
between0-7.
gogo:read-all
gogo:read-all
Reportsalldataavailablefromtheboard,inaraw-listformusefulfordebugging.
gogo:send-bytes
gogo:send-byteslist
SendsalistofbytestotheGoGoboard.Usefulfordebuggingorfortestinganynewor
futurefunctionalitythatisaddedtotheGoGoboardwithnewfirmwareupdates.
NetLogoLsExtension
LevelSpacefundamentals
LevelSpacemustbeloadedinamodelusingextensions [ls]atthetopofyourmodel.
Oncethisisdone,amodelwillbeabletoloadupothermodelsusingtheLevelSpace
primitives,runcommandsandreportersinthem,andclosethemdownwhentheyareno
longerneeded.
AskingandreportinginLevelSpaceisconceptuallyprettystraightforward:Youpassblocks
ofcodetochildmodels,andthechildmodelsrespondasifyouhadtypedthatcodeinto
theirCommandCenter.LevelSpaceallowsyoutoreportstrings,numbers,andlistsfroma
childtoitsparent.Itisnotpossibletodirectlyreportturtles,patches,links,oranyoftheir
respectivesets.Further,itisnotpossibletopushdatafromachildtoitsparent-parents
mustasktheirchildrentoreport.Thismimicksthewayinwhichturtlescannot“push”data
totheobserver,butrelyontheobservertoaskthemforit.
Ingeneral,theLevelSpacesyntaxhasbeendesignedtoalignwithexistingNetLogo
primitiveswheneverpossible.
HeadlessandInteractiveModels
LevelSpacehastwodifferentchildmodeltypes;headlessmodelsandinteractivemodels.
Theyeachhavetheirstrengthsandweaknesses:
Interactivemodels*arefull-fledgedmodelsthatgivefullaccesstotheirinterfaceand
widgets,*runabitslower,andusemorememory*arevisiblebydefault
HeadlessModels*onlygiveyouaccesstotheirviewandcommandcenter*arefasterand
uselessmemorythaninteractivemodels.*arehiddenbydefault
Typicallyyouwillwanttouseheadlessmodelswhenyouarerunningalargenumberof
models,orifyousimplywanttorunthemfaster.Interactivemodelsaregoodifyouruna
smallamountofmodels,ifyouarewritingaLevelSpacemodelandneedtobeableto
debug,orifyouneedaccesstowidgetsduringruntime.
KeepingTrackofModels
Childmodelsarekepttrackofintheextensionwithanidnumber,startingwith0,andall
communicationfromparenttochildisdonebyreferencingthisnumber,henceforthreferred
toasmodel-id.
Theeasiestwaytoworkwithmultiplemodelsistostoretheirmodel-idinalist,anduse
NetLogo’slistprimitivestosort,filter,etc.themduringruntime.
Keepingtrackofmodelsisimportant:MostLevelSpaceprimitiveswillfailandcausea
runtimeinterruptionifprovidedamodel-idtoanon-existingmodel.Youcanusels:model-
exists? model-idtocheckifmodel-idreferstoanexistingmodel.
Ageneralusecase:AskingandReporting
ThisusecaseisbasedontheModelVisualizerandPlotterExample-modelfromthe
NetLogoModelsLibrary.
Asimplethingwecandoistoopenupsomemodels,runthemconcurrently,andcalculate
theaverageofsomereporter.Let’ssaythatweareinterestedinfindingthemeannumber
ofsheepinabunchofWolfSheepPredationmodels.Firstwewouldopenupsomeof
thesemodels,andsetthemup:
to setup
ls:reset
ca
ls:create-models 30 "Wolf Sheep Predation.nlogo"
ls:ask ls:models [ set grass? true setup ]
reset-ticks
end
Wethenwanttorunallourchildmodels,andthenfindoutwhatthemeannumberof
sheepis:
to go
ls:ask ls:models [ go ]
show mean [ count sheep ] ls:of ls:models
end
Ageneralusecase:Inter-ModelInteractions
ThisusecaseisbasedontheModelInteractionsExample-modelfromtheNetLogoModels
Library.
Let’simaginethatwehavetwomodels:aWolfSheepPredation-modelcalledWSP,anda
ClimateChangemodelcalledCC.Nowlet’simaginethatwewanttheregrowthtimeinthe
wSPmodeltodependonthetemperatureintheCCmodel.UsingLevelSpace’sprimitives,
wecoulddosomethinglikethis:
; save new regrowth time in a temporary LevelSpace let-variable
ls:let new-regrowth-time 25 + ( abs [ temperature - 55 ] ls:of CC ) / 2
; remove decimals, pass it to the wolf sheep predation model and change the time
ls:ask WSP [
set grass-regrowth-time round new-regrowth-time
]
; finally ask both models to go
ls:ask ls:models [ go ]
AgeneralUsecase:Tidyingup“Dead”ChildModels
Aspreviouslymentioned,itisimportanttokeeptrackof“living”and“dead”modelswhen
youdynamicallycreateanddisposeofmodels.Letusimaginewehavesomelistsof
modelsofdifferentkinds,andwewanttomakesurethatweonlykeepthemodelsthatare
alive.Afterrunningcodethatkillschildmodelswecanusethels:model-exists?primitive
tocleanupourlistofmodelslikethis:
to-report remove-dead-models [list-of-models]
report filter [ [ model-id ] -> ls:model-exists model-id] list-of-models
end
Wethenreassigneachlistofmodelswiththis,e.g.
set a-list-of-models remove-dead-models a-list-of-models
set another-list-of-models remove-dead-models a-list-of-models
CitingLevelSpaceinResearch
IfyouuseLevelSpaceinresearch,weaskthatyouciteus,
Hjorth,A.Head,B.&Wilensky,U.(2015).“LevelSpaceNetLogoextension”.
http://ccl.northwestern.edu/rp/levelspace/index.shtmlEvanston,IL:CenterforConnected
LearningandComputerBasedModeling,NorthwesternUniversity.
Primitives
CommandingandReporting
ls:askls:ofls:reportls:withls:letls:assign
LogicandControl
ls:modelsls:showls:show-allls:hidels:hide-allls:path-ofls:name-ofls:model-exists?
OpeningandClosingModels
ls:create-modelsls:create-interactive-modelsls:closels:reset
ls:create-models
ls:create-modelsnumberpath
ls:create-modelsnumberpathanonymouscommand
Createthespecifiednumberofinstancesofthegiven.nlogomodel.Thepathcanbe
absolute,orrelativetothemainmodel.Comparedwithls:create-interactive-models,this
primitivecreateslightweightmodelsthatarehiddenbydefault.Youshouldusethis
primitiveifyouplanonhavingmanyinstancesofthegivenmodel.Themodelsmaybe
shownusingls:show;whenvisible,theywillhaveaviewandcommandcenter,butno
otherwidgets,e.g.plotsormonitors.
Ifgivenacommand,LevelSpacewillcallthecommandafterloadingeachinstanceofthe
modelwiththemodel-idastheargument.Thisallowsyoutoeasilystoremodelidsina
variableorlistwhenloadingmodels,ordootherinitialization.Forexample,tostorea
modelidinavariable,youcando:
let model-id 0
(ls:create-models "My-Model.nlogo" [ [id] -> set model-id id ])
ChildmodelRNGsareseededfromtheparentmodelsRNGwhentheyarecreated.Thus,
ifyouseedtheparent’smodelRNGbeforechildmodelbeforechildmodelsarecreated,
thesimulationasawholewillbereproducible.Usethels:random-seedprimitivetoseedthe
modelsystem’sRNGsafterchildmodelshavebeencreated.
ls:create-interactive-models
ls:create-interactive-modelsnumberpath
ls:create-interactive-modelsnumberpathanonymouscommand
Likels:create-models,createsthespecifiednumberofinstancesofthegiven.nlogo
model.Unlikels:create-models,ls:create-interactive-modelscreatesmodelsthatare
visiblebydefault,andhaveallwidgets.Youshouldusethisprimitiveifyouplanonhaving
onlyahandfulofinstancesofthegivenmodel,andwouldliketobeabletointeractwiththe
instancesthroughtheirinterfacesduringruntime.
ChildmodelRNGsareseededfromtheparentmodelsRNGwhentheyarecreated.Thus,
ifyouseedtheparent’smodelRNGbeforechildmodelbeforechildmodelsarecreated,
thesimulationasawholewillbereproducible.Usethels:random-seedprimitivetoseedthe
modelsystem’sRNGsafterchildmodelshavebeencreated.
ls:close
ls:closemodel-or-list-of-models
Closethemodelormodelswiththegivenmodel-id.
ls:reset
ls:reset
Closedownallchildmodels(and,recursively,theirchildmodels).You’lloftenwanttocall
thisinyoursetupprocedure.
Notethatclear-alldoesnotcloseLevelSpacemodels.
ls:ask
ls:askmodel-or-list-of-modelscommandargument
Askthegivenchildmodelorlistofchildmodelstorunthegivencommand.Thisisthe
primaryofdoingthingswithchildmodels.Forexample:
ls:ask model-id [ create-turtles 5 ]
Youcanalsoaskalistofmodelstoalldothesamething:
ls:ask ls:models [ create-turtles 5 ]
Youmaysupplythecommandwitharguments,justlikeyouwouldwithanonymous
commands:
let turtle-id 0
let speed 5
(ls:ask model-id [ [t s] -> ask turtle t [ fd s ] ] turtle-id speed)
Notethatthecommandscannotaccessvariablesintheparentmodeldirectly.Youmust
eitherpassinformationinthroughargumentsorusingls:let.
ls:of
reporterls:ofmodel-or-list-of-models
Runthegivenreporterinthegivenmodelandreporttheresult.
ls:ofisdesignedtoworklikeNetLogo’sinbuiltof:Ifyousendls:ofamodel-id,itwill
reportthevalueofthereporterfromthatmodel.Ifyousenditalistofmodel-ids,itwill
reportalistofvaluesofthereporterstringfromallmodels.Youcannotpassargumentsto
ls:of,butyoucanusels:let.
[ count turtles ] ls:of model-id
ls:report
ls:reportmodel-or-list-of-modelsreporterargument
Runthegivenreporterinthegivenmodelandreporttheresult.Thisformexiststoallow
youtopassargumentstothereporter.
let turtle-id 0
(ls:report model-id [ [a-turtle] -> [ color ] of turtle a-turtle ] turtle-id)
ls:with
list-of-modelsls:withreporter
Reportsanewlistofmodelscontainingonlythosemodelsthatreporttruewhentheyrun
thereporterblock.
ls:models ls:with [ count turtles > 100 ]
ls:let
ls:letvariable-namevalue
Createsavariablecontainingthegivendatathatcanbeaccessedbythechildmodels.
ask turtles [
ls:let my-color color
ls:ask my-model [
ask turtles [ set color my-color ]
]
]
ls:letworksquitesimilartoletinthatthevariableisonlylocallyaccessible:
ask turtles [
ls:let my-color color
]
;; my-color is innaccessible here
ls:letisverysimilartolet,exceptinafewcases.
ls:letwilloverwritepreviousvaluesinthevariable
Ifyoudo
ls:let my-var 5
ls:let my-var 6
my-varwillbesetequalto6.Thereisnols:set.
ls:letsupportsvariableshadowing
Ifyoudo
ls:let my-var 5
ask turtles [
ls:let my-var 6
ls:ask child-model [ show my-var ]
]
ls:ask child-model [ show my-var ]
child-modelwillshow6andthen5.Thisisknownasvariableshadowing.
Theparentmodelcannotdirectlyreadthevalueofanlsvariable
Forexample,thisdoesnotwork.
ls:let my-var 5
show my-var
Thisisintentional.lsvariablesaremeanttobeusedforsharingdatawithchildmodels.The
parentmodelalreadyhasaccesstothedata.
Furthermore,changingthevalueofanlsletvariableinachildmodelwillnotaffectitinany
othermodel.Forexample:
ls:let my-var 0
ls:ask ls:models [
set my-var my-var + 1
show my-var
]
Allmodelswillprint1.
ls:assign
ls:assignmodel-or-list-of-modelsglobal-variablevalue
Setsthegivenglobalvariableinchildmodeltogivenvalue.Forinstance
ls:assign ls:models glob1 count turtles
setstheglobalvariableglob1inallmodelstotheparent’smodelcount turtles.
ls:models
ls:models
Reportalistofmodel-idsforallexistingmodels.
ls:show
ls:showmodel-or-list-of-models
Makesallofthegivenmodelsvisible.
ls:show-all
ls:show-allmodel-or-list-of-models
Makesallofthegivenmodelsandtheirdescendentsvisible.
ls:hide
ls:hidemodel-or-list-of-models
Hideallofthegivenmodels.Hidingmodelsisagoodwayofmakingyoursimulationrun
faster.
ls:hide-all
ls:hide-allmodel-or-list-of-models
Hideallofthegivenmodelsandtheirdescendents.Hidingmodelsisagoodwayofmaking
yoursimulationrunfaster.
ls:path-of
ls:path-ofmodel-or-list-of-models
Reportthefullpath,includingthe.nlogofilename,ofthemodel.Ifalistofmodelsisgiven,
alistofpathsisreported.
ls:name-of
ls:name-ofmodel-or-list-of-models
Reportsthenameofthe.nlogofileofthemodel.Thisisthenameofthewindowinwhich
themodelappearswhenvisible.Ifalistofmodelsisgiven,alistofnamesisreported.
ls:model-exists?
ls:model-exists?model-or-list-of-models
Reportabooleanvalueforwhetherthereisamodelwiththatmodel-id.Thisisoftenuseful
whenyouaredynamicallygeneratingmodels,andwanttoensurethatyouarenotasking
modelsthatnolongerexisttodostuff.
ls:random-seed
ls:random-seedseed
BehavesexactlylikeNetLogo’sbuilt-inprimitiverandom-seed,exceptthatchildmodelshave
theirRNGsseededbasedonthegivenseedaswell(aswelltheirchildmodels,andtheir
childmodels’childmodels,andsoforth).Thisprimitiveshouldalmostalwaysbeused
insteadofNetLogo’sbuilt-inoneforseedingRNGwhenusingLevelSpace.
NetLogoMatrixExtension
Using
ThematrixextensionaddsanewmatrixdatastructuretoNetLogo.Amatrixisamutable2-dimensionalarraycontaining
onlynumbers.
WhentoUse
Althoughmatricesstorenumbers,muchlikealistoflists,oranarrayofarrays,theprimaryreasontousethematrixdata
typeistotakeadvantageofspecialmathematicaloperationsassociatedwithmatrices.Forinstance,matrixmultiplication
isaconvenientwaytoperformgeometrictransformations,andtherepeatedapplicationofmatrixmultiplicationcanalso
beusedtosimulateotherdynamicprocesses(forinstance,processesongraph/networkstructures).
Ifyou’dliketoknowmoreaboutmatricesandhowtheycanbeused,youmightconsideracourseonlinearalgebra,or
searchthewebfortutorials.Thematrixextensionalsoallowsyoutosolvelinearalgebraicequations(specifiedina
matrixformat),andeventoidentifytrendsinyourdataandperformlinear(ordinaryleastsquares)regressionsondata
setswithmultipleexplanatoryvariables.
HowtoUse
Thematrixextensioncomespreinstalled.
Tousethematrixextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [matrix]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddmatrixtothelist.
Example
let m matrix:from-row-list [[1 2 3] [4 5 6]]
print m
=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ] ]}}
print matrix:pretty-print-text m
=>
[[ 1 2 3 ]
[ 4 5 6 ]]
print matrix:dimensions m
=> [2 3]
;;(NOTE: row & column indexing starts at 0, not 1)
print matrix:get m 1 2 ;; what number is in row 1, column 2?
=> 6
matrix:set m 1 2 10 ;; change the 6 to a 10
print m
=> {{matrix: [ [ 1 2 3 ][ 4 5 10 ] ]}}
let m2 matrix:make-identity 3
print m2
=> {{matrix: [ [ 1 0 0 ][ 0 1 0 ][ 0 0 1 ] ]}}
print matrix:times m m2 ;; multiplying by the identity changes nothing
=> {{matrix: [ [ 1 2 3 ][ 4 5 10 ] ]}}
;; make a new matrix with the middle 1 changed to -1
let m3 (matrix:set-and-report m2 1 1 -1)
print m3
=> {{matrix: [ [ 1 0 0 ][ 0 -1 0 ][ 0 0 1 ] ]}}
print matrix:times m m3
=> {{matrix: [ [ 1 -2 3 ][ 4 -5 10 ] ]}}
print matrix:to-row-list (matrix:plus m2 m3)
=> [[2 0 0] [0 0 0] [0 0 2]]
Primitives
Matrixcreationandconversionto/fromlists
matrix:make-constantmatrix:make-identitymatrix:from-row-listmatrix:from-column-listmatrix:to-row-list
matrix:to-column-listmatrix:copymatrix:pretty-print-text
Advancedfeatures
matrix:solvematrix:forecast-linear-growthmatrix:forecast-compound-growthmatrix:forecast-continuous-growth
matrix:regress
Matrixdataretrievalandmanipulation
matrix:getmatrix:get-rowmatrix:get-columnmatrix:setmatrix:set-rowmatrix:set-columnmatrix:swap-rows
matrix:swap-columnsmatrix:set-and-reportmatrix:dimensionsmatrix:submatrixmatrix:map
Mathoperations
matrix:times-scalarmatrix:timesmatrix:*matrix:times-element-wisematrix:plus-scalarmatrix:plusmatrix:+
matrix:minusmatrix:-matrix:inversematrix:transposematrix:real-eigenvaluesmatrix:imaginary-eigenvalues
matrix:eigenvectorsmatrix:detmatrix:rankmatrix:trace
matrix:make-constant
matrix:make-constantn-rowsn-colsinitialValue
Reportsanewn-rowsbyn-colsmatrixobject,withallentriesinthematrixcontainingthesamevalue(number).
matrix:make-identity
matrix:make-identitysize
Reportsanewsquarematrixobject(withdimensionsn-sizexn-size),consistingoftheidentitymatrix(1salongthemain
diagonal,0selsewhere).
matrix:from-row-list
matrix:from-row-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolist,whereeachiteminthatlistisanotherlist(correspondingto
eachoftherowsofthematrix.)
print matrix:from-row-list [[1 2] [3 4]]
=> {{matrix: [ [ 1 2 ][ 3 4 ] ]}}
;; Corresponds to this matrix:
;; 1 2
;; 3 4
matrix:from-column-list
matrix:from-column-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolistcontainingeachofthecolumnsofthematrix.
matrix:to-row-list
matrix:to-row-listmatrix
Reportsalistoflists,containingeachrowofthematrix.
matrix:to-column-list
matrix:to-column-listmatrix
Reportsalistoflists,containingeachcolumnofthematrix.
matrix:copy
matrix:copymatrix
Reportsanewmatrixthatisanexactcopyofthegivenmatrix.Thisprimitiveisimportantbecausethematrixtypeis
mutable(changeable).Here’sacodeexample:
let m1 matrix:from-column-list [[1 4 7][2 5 8][3 6 9]] ; a 3x3 matrix
print m1
=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
let m2 m1 ;; m2 refers to the same matrix object as m1
let m3 matrix:copy m1 ;; m3 is a new copy containing m1's data
matrix:set m1 0 0 100 ;; now m1 is changed
print m1
=> {{matrix: [ [ 100 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
print m2
=> {{matrix: [ [ 100 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
;;Notice that m2 was also changed, when m1 was changed!
print m3
=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
matrix:pretty-print-text
matrix:pretty-print-textmatrix
Reportsastringthatisatextualrepresentationofthematrix,inaformatthatisreasonablyhuman-readablewhen
displayed.
matrix:get
matrix:getmatrixrow-icol-j
Reportsthe(numeric)valueatlocationrow-i(secondargument),col-j(thirdargument),inthegivenmatrixgiveninthe
firstargument
matrix:get-row
matrix:get-rowmatrixrow-i
Reportsasimple(notnested)NetLogolistcontainingtheelementsofrow-i(secondargument)ofthematrixsuppliedin
thefirstargument.
matrix:get-column
matrix:get-columnmatrixcol-j
Reportsasimple(notnested)NetLogolistcontainingtheelementsofcol-jofthematrixsuppliedinthefirstargument.
matrix:set
matrix:setmatrixrow-icol-jnew-value
Changesthegivenmatrixbysettingthevalueatlocationrow-i,col-jtonew-value
matrix:set-row
matrix:set-rowmatrixrow-isimple-list
Changesthegivenmatrixmatrixbyreplacingtherowatrow-iwiththecontentsofthesimple(notnested)NetLogolist
simple-list.Thesimple-listmusthavealengthequaltothenumberofcolumnsinthematrix,i.e.,thematrixrowlength.
matrix:set-column
matrix:set-columnmatrixcol-jsimple-list
Changesthegivenmatrixmatrixbyreplacingthecolumnatcol-jwiththecontentsofthesimple(notnested)NetLogolist
simple-list.Thesimple-listmusthavealengthequaltothenumberofrowsinthematrix,i.e.,thematrixcolumnlength
length.
matrix:swap-rows
matrix:swap-rowsmatrixrow1row2
Changesthegivenmatrixmatrixbyswappingtherowsatrow1androw2witheachother.
matrix:swap-columns
matrix:swap-columnsmatrixcol1col2
Changesthegivenmatrixmatrixbyswappingthecolumnsatcol1andcol2witheachother.
matrix:set-and-report
matrix:set-and-reportmatrixrow-icol-jnew-value
Reportsanewmatrix,whichisacopyofthegivenmatrixexceptthatthevalueatrow-i,col-jhasbeenchangedtonew-
value.ANetLogostatementsuchasset mat matrix:set-and-report mat 2 3 10willresultinmatpointingtothisnew
matrix,acopyoftheoldversionofmatwiththeelementatrow2,column3beingsetto10.Theoldversionofmatwillbe
“lost”.
matrix:dimensions
matrix:dimensionsmatrix
Reportsa2-elementlist([num-rows,num-cols]),containingthenumberofrowsandnumberofcolumnsinthegiven
matrix
matrix:submatrix
matrix:submatrixmatrixr1c1r2c2
Reportsanewmatrixobject,consistingofarectangularsubsectionofthegivenmatrix.Therectangularregionisfrom
rowr1upto(butnotincluding)rowr2,andfromcolumnc1upto(butnotincluding)columnc2.
Hereisanexample:
let m matrix:from-row-list [[1 2 3][4 5 6][7 8 9]]
print matrix:submatrix m 0 1 2 3 ; matrix, row-start, col-start, row-end, col-end
; rows from 0 (inclusive) to 2 (exclusive),
; columns from 1 (inclusive) to 3 (exclusive)
=> {{matrix: [ [ 2 3 ][ 5 6 ] ]}}
matrix:map
matrix:mapanonymousreportermatrix
matrix:mapanonymousreportermatrixanything
Reportsanewmatrixwhichresultsfromapplyingreporter(ananonymousreporterorthenameofareporter)toeachof
theelementsofthegivenmatrix.Forexample,
matrix:map sqrt matrix
wouldtakethesquarerootofeachelementofmatrix.Ifmorethanonematrixargumentisprovided,thereporterisgiven
theelementsofeachmatrixasarguments.Thus,
(matrix:map + matrix1 matrix2)
wouldaddmatrix1andmatrix2.
Thisreporterismeanttobethesameasmap,butformatricesinsteadoflists.
matrix:times-scalar
matrix:times-scalarmatrixfactor
AsofNetLogo5.1,matrix:timescanmultiplymatricesbyscalarsmakingthisfunctionobsolete.Usematrix:times
instead.
Reportsanewmatrix,whichistheresultofmultiplyingeveryentryintheoriginalmatrixbythegivenscalingfactor.
matrix:times
matrix:timesm1m2
matrix:timesm1m2...
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesandscalars(usingstandardmatrixmultiplication–
makesureyourmatrixdimensionsmatchup.)Withoutparentheses,ittakestwoarguments.Withparenthesesittakes
twoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:*
m1matrix:*m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesand/orscalars(usingstandardmatrixmultiplication
–makesureyourmatrixdimensionsmatchup.)Thisisexactlythesameasmatrix:times m1 m2
Takesprecedenceovermatrix:+andmatrix:-,sameasnormalmultiplication.
matrix:times-element-wise
matrix:times-element-wisem1m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricestogether,element-wise.Allelementsaremultiplied
byscalarargumentsaswell.Notethatallmatrixargumentsmusthavethesamedimensions.Withoutparentheses,it
takestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butat
leastonemustbeamatrix.
matrix:plus-scalar
matrix:plus-scalarmatrixnumber
AsofNetLogo5.1,matrix:pluscanaddmatricesandscalarsmakingthisfunctionobsolete.Usematrix:plusinstead.
Reportsamatrix,whichistheresultofaddingtheconstantnumbertoeachelementofthegivenmatrix.
matrix:plus
matrix:plusm1m2
matrix:plusm1m2...
Reportsamatrix,whichistheresultofaddingthegivenmatricesandscalars.Scalarsareaddedtoeachelement.
Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbe
numbersormatrices,butatleastonemustbeamatrix.
matrix:+
m1matrix:+m2
Reportsamatrix,whichistheresultofaddingthegivenmatricesand/orscalars.Thisisexactlythesameasmatrix:plus
m1 m2
Takesprecedenceaftermatrix:*,sameasnormaladdition.
matrix:minus
matrix:minusm1m2
matrix:minusm1m2...
Reportsamatrix,whichistheresultofsubtractingallargumentsbesidesm1fromm1.Scalarargumentsaretreatedas
matricesofthesamesizeasthematrixargumentswitheveryelementequaltothatscalar.Withoutparentheses,ittakes
twoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleast
onemustbeamatrix.
matrix:-
m1matrix:-m2
Reportsamatrix,whichistheresultofsubtractingthegivenmatricesand/orscalars.Thisisexactlythesameas
matrix:minus m1 m2
Takesprecedenceaftermatrix:*,sameasnormalsubtraction.
matrix:inverse
matrix:inversematrix
Reportstheinverseofthegivenmatrix,orresultsinanerrorifthematrixisnotinvertible.
matrix:transpose
matrix:transposematrix
Reportsthetransposeofthegivenmatrix.
matrix:real-eigenvalues
matrix:real-eigenvaluesmatrix
Reportsalistcontainingtherealeigenvaluesofthegivenmatrix.
matrix:imaginary-eigenvalues
matrix:imaginary-eigenvaluesmatrix
Reportsalistcontainingtheimaginaryeigenvaluesofthegivenmatrix.
matrix:eigenvectors
matrix:eigenvectorsmatrix
Reportsamatrixthatcontainstheeigenvectorsofthegivenmatrix.(Eacheigenvectorasacolumnoftheresulting
matrix.)
matrix:det
matrix:detmatrix
Reportsathedeterminantofthematrix.
matrix:rank
matrix:rankmatrix
Reportstheeffectivenumericalrankofthematrix,obtainedfromSVD(SingularValueDecomposition).
matrix:trace
matrix:tracematrix
Reportsthetraceofthematrix,whichissimplythesumofthemaindiagonalelements.
matrix:solve
matrix:solveAC
Reportsthesolutiontoalinearsystemofequations,specifiedbytheAandCmatrices.Ingeneral,solvingasetoflinear
equationsisakintomatrixdivision.Thatis,thegoalistofindamatrixBsuchthatA*B=C.(Forsimplelinearsystems,
CandBcanbothbe1-dimensionalmatrices–i.e.vectors).IfAisnotasquarematrix,thena“leastsquares”solutionis
returned.
;; To solve the set of equations x + 3y = 10 and 7x - 4y = 20
;; We make our A matrix [[1 3][7 -4]], and our C matrix [[10][20]]
let A matrix:from-row-list [[1 3][7 -4]]
let C matrix:from-row-list [[10][20]]
print matrix:solve A C
=> {{matrix: [ [ 4 ][ 2.0000000000000004 ] ]}}
;; NOTE: as you can see, the results may be only approximate
;; (In this case, the true solution should be x=4 and y=2.)
matrix:forecast-linear-growth
matrix:forecast-linear-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant slope R2 ]
Theforecastisthepredictednextvaluethatwouldfollowinthesequencegivenbythedata-listinput,basedonalinear
trend-line.Normallydata-listwillcontainobservationsonsomevariable,Y,fromtimet=0totimet=(n-1)wherenisthe
numberofobservations.TheforecastisthepredictedvalueofYatt=n.Theconstantandslopearetheparametersof
thetrend-line
Y = *constant* + *slope* * t.
TheR2valuemeasuresthegoodnessoffitofthetrend-linetothedata,withanR
2=1beingaperfectfitandanR
2of0
indicatingnodiscernibletrend.LineargrowthassumesthatthevariableYgrowsbyaconstantabsoluteamounteach
period.
;; a linear extrapolation of the next item in the list.
print matrix:forecast-linear-growth [20 25 28 32 35 39]
=> [42.733333333333334 20.619047619047638 3.6857142857142824 0.9953743395474031]
;; These results tell us:
;; * the next predicted value is roughly 42.7333
;; * the linear trend line is given by Y = 20.6190 + 3.6857 * t
;; * Y grows by approximately 3.6857 units each period
;; * the R^2 value is roughly 0.9954 (a good fit)
matrix:forecast-compound-growth
matrix:forecast-compound-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-proportion R2 ]
Whereasmatrix:forecast-linear-growthassumesgrowthbyaconstantabsoluteamounteachperiod,matrix:forecast-
compound-growthassumesthatYgrowsbyaconstantproportioneachperiod.Theconstantandgrowth-proportionare
theparametersofthetrend-line
Y = constant * growth-proportiont.
Notethatthegrowthproportionistypicallyinterpretedasgrowth-proportion=(1.0+growth-rate).Therefore,if
matrix:forecast-compound-growthreturnsagrowth-proportionof1.10,thatimpliesthatYgrowsby(1.10-1.0)=10%
eachperiod.Notethatifgrowthisnegative,matrix:forecast-compound-growthwillreturnagrowth-proportionoflessthan
one.E.g.,agrowth-proportionof0.90impliesagrowthrateof-10%.
NOTE:ThecompoundgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)Becauseitis
impossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-compound-growthwillresultinanerrorif
itfindsazeroornegativenumberindata-list.
;; a compound growth extrapolation of the next item in the list.
print matrix:forecast-compound-growth [20 25 28 32 35 39]
=> [45.60964465307147 21.15254147944863 1.136621034423892 0.9760867518334806]
;; These results tell us:
;; * the next predicted value is approximately 45.610
;; * the compound growth trend line is given by Y = 21.1525 * 1.1366 ^ t
;; * Y grows by approximately 13.66% each period
;; * the R^2 value is roughly 0.9761 (a good fit)
matrix:forecast-continuous-growth
matrix:forecast-continuous-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-rate R2 ].Whereasmatrix:forecast-compound-growthassumesdiscretetimewithY
growingbyagivenproportioneachfiniteperiodoftime(e.g.,amonthorayear),matrix:forecast-continuous-growth
assumesthatYiscompoundedcontinuously(e.g.,eachsecondorfractionofasecond).Theconstantandgrowth-rate
aretheparametersofthetrend-line
Y = constant * e(growth-rate * t)
matrix:forecast-continuous-growthisthe“calculus”analogofmatrix:forecast-compound-growth.Thetwowillnormally
yieldsimilar(butnotidentical)results,asshownintheexamplebelow.growth-ratemay,ofcourse,benegative.
NOTE:ThecontinuousgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)
Becauseitisimpossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-continuous-growth
willresultinanerrorifitfindsazeroornegativenumberindata-list.
;; a continuous growth extrapolation of the next item in the list.
print matrix:forecast-continuous-growth [20 25 28 32 35 39]
=> [45.60964465307146 21.15254147944863 0.12805985615332668 0.9760867518334806]
;; These results tell us:
;; * the next predicted value is approximately 45.610
;; * the compound growth trend line is given by Y = 21.1525 * e ^ (0.1281 * t)
;; * Y grows by approximately 12.81% each period if compounding takes place continuously
;; * the R^2 value is roughly 0.9761 (a good fit)
matrix:regress
matrix:regressdata-matrix
AllthreeoftheforecastprimitivesabovearejustspecialcasesofperforminganOLS(ordinary-least-squares)linear
regression–thematrix:regressprimitiveprovidesaflexible/general-purposeapproach.Theinputisamatrixdata-matrix,
withthefirstcolumnbeingtheobservationsonthedependentvariableandeachsubsequentcolumnbeingthe
observationsonthe(1ormore)independentvariables.Thuseachrowconsistsofanobservationofthedependent
variablefollowedbythecorrespondingobservationsforeachindependentvariable.
TheoutputisaLogonestedlistcomposedoftwoelements.Thefirstelementisalistcontainingtheregressionconstant
followedbythecoefficientsoneachoftheindependentvariables.Thesecondelementisa3-elementlistcontainingthe
R2statistic,thetotalsumofsquares,andtheresidualsumofsquares.Thefollowingcodeexampleshowshowthe
matrix:regressprimitivecanbeusedtoperformthesamefunctionasthecodeexamplesshowninthematrix:forecast-*-
growthprimitivesabove.(However,keepinmindthatthematrix:regressprimitiveismorepowerfulthanthis,andcan
havemanymoreindependentvariablesintheregression,asindicatedinthefourthexamplebelow.)
;; this is equivalent to what the matrix:forecast-linear-growth does
let data-list [20 25 28 32 35 39]
let indep-var (n-values length data-list [ x -> x ]) ; 0,1,2...,5
let lin-output matrix:regress matrix:from-column-list (list data-list indep-var)
let lincnst item 0 (item 0 lin-output)
let linslpe item 1 (item 0 lin-output)
let linR2 item 0 (item 1 lin-output)
;;Note the "6" here is because we want to forecast the value at time t=6.
print (list (lincnst + linslpe * 6) (lincnst) (linslpe) (linR2))
;; this is equivalent to what the matrix:forecast-compound-growth does
let com-log-data-list (map ln [20 25 28 32 35 39])
let com-indep-var2 (n-values length com-log-data-list [ x -> x ]) ; 0,1,2...,5
let com-output matrix:regress matrix:from-column-list (list com-log-data-list com-indep-var2)
let comcnst exp item 0 (item 0 com-output)
let comprop exp item 1 (item 0 com-output)
let comR2 item 0 (item 1 com-output)
;;Note the "6" here is because we want to forecast the value at time t=6.
print (list (comcnst * comprop ^ 6) (comcnst) (comprop) (comR2))
;; this is equivalent to what the matrix:forecast-continuous-growth does
let con-log-data-list (map ln [20 25 28 32 35 39])
let con-indep-var2 (n-values length con-log-data-list [ x -> x ]) ; 0,1,2...,5
let con-output matrix:regress matrix:from-column-list (list con-log-data-list con-indep-var2)
let concnst exp item 0 (item 0 con-output)
let conrate item 1 (item 0 con-output)
let conR2 item 0 (item 1 con-output)
print (list (concnst * exp (conrate * 6)) (concnst) (conrate) (conR2))
;; example of a regression with two independent variables:
;; Pretend we have a dataset, and we want to know how well happiness
;; is correlated to snack-food consumption and accomplishing goals.
let happiness [2 4 5 8 10]
let snack-food-consumed [3 4 3 7 8]
let goals-accomplished [2 3 5 8 9]
print matrix:regress matrix:from-column-list (list happiness snack-food-consumed goals-accomplished)
=> [[-0.14606741573033788 0.3033707865168543 0.8202247191011234] [0.9801718440185063 40.8 0.8089887640449439]]
;; linear regression: happiness = -0.146 + 0.303*snack-food-consumed + 0.820*goals-accomplished
;; (Since the 0.820 coefficient is higher than the 0.303 coefficient, it appears that each goal
;; accomplished yields more happiness than does each snack consumed, although both are positively
;; correlated with happiness.)
;; Also, we see that R^2 = 0.98, so the two factors together provide a good fit.
NetLogoNwExtension
Usage
Thefirstthingthatoneneedstounderstandinordertoworkwiththenetworkextensionishowtotelltheextension
whichnetworktoworkwith.Considerthefollowingexamplesituation:
breed [ bankers banker ]
breed [ clients client ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]
Basically,youhavebankersandclients.Clientscanhaveaccountswithbankers.Bankerscanprobablyhave
accountwithotherbankers,andanyonecanbefriendswithanyone.
Nowwemightwanttoconsiderthiswholethingasonebignetwork.Ifthatisthecase,thereisnothingspecialtodo:
bydefault,theNWextensionprimitivesconsiderallturtlesandalllinkstobepartofthecurrentnetwork.
Wecouldalso,however,beonlyinterestedinasubsetofthenetwork.Maybewewanttoconsideronlyfriendship
relations.Furthermore,maybewewanttoconsideronlythefriendshipsbetweenbankers.Afterall,havingavery
highcentralityinanetworkofbankerfriendshipsisverydifferentfromhavingahighcentralityinanetworkofclient
friendships.
Tospecifysuchnetworks,weneedtotelltheextensionbothwhichturtlesandwhichlinksweareinterestedin.All
theturtlesfromthespecifiedsetofturtleswillbeincludedinthenetwork,andonlythelinksfromthespecifiedsetof
linksthatarebetweenturtlesofthespecifiedsetwillbeincluded.Forexample,ifyouaskforbankersand
friendships,eventhelonelybankerswithnofriendswillbeincluded,butfriendshiplinksbetweenbankersand
clientswillnotbeincluded.Thewaytotelltheextensionaboutthisiswiththenw:set-contextprimitive,whichyou
mustcallpriortodoinganyoperationsonanetwork.
Someexamples:
nw:set-context turtles links willgiveyoueverything:bankersandclients,friendshipsandaccounts,asonebig
network.
nw:set-context turtles friendships willgiveyouallthebankersandclientsandfriendshipsbetweenanyof
them.
nw:set-context bankers friendships willgiveyouallthebankers,andonlyfriendshipsbetweenbankers.
nw:set-context bankers links willgiveyouallthebankers,andanylinksbetweenthem,whethertheselinksare
friendshipsoraccounts.
nw:set-context clients accountswillgiveyoualltheclients,andaccountsbetweeneachother,butsinceinour
fictionalexampleclientscanonlyhaveaccountswithbankers,thiswillbeacompletelydisconnectednetwork.
Specialagentsetsvsnormalagentsets
ItmustbenotedthatNetLogohastwotypesofagentsetsthatbehaveslightlydifferently,andthatthishasanimpact
onthewaynw:set-contextworks.Wewillsayafewwordsabouttheseconceptsherebut,forathorough
understanding,itishighlyrecommendedthatyoureadthesectiononagentsetsintheNetLogoprogrammingguide.
The“special”agentsetsinNetLogoareturtles,linksandthedifferent“breed”agentsets.Whatisspecialabout
themisthattheycangrow:ifyoucreateanewturtle,itwillbeaddedtotheturtlesagentset.Ifyouhaveabankers
breedandyoucreateanewbanker,itwillbeaddedtothebankersagentsetandtotheturtlesagentset.Samegoes
forlinks.Otheragentsets,suchasthosecreatedwiththewithprimitive(e.g.,turtles with [ color = red ] )orthe
turtle-setandlink-setprimitives)areneveraddedto.Thecontentofnormalagentsetswillonlychangeifthe
agentsthattheycontaindie.
Toshowhowdifferenttypesofagentsetsinteractwithnw:set-context,let’screateaverysimplenetwork:
clear-all
create-turtles 3 [ create-links-with other turtles ]
Let’ssetthecontexttoturtlesandlinks(whichisthedefaultanyway)andusenw:get-contexttoseewhatwe
have:
nw:set-context turtles links
show map sort nw:get-context
Wegetallthreeturtlesandallthreelinks:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Nowlet’skilloneturtle:
ask one-of turtles [ die ]
show map sort nw:get-context
Asexpected,thecontextisupdatedtoreflectthedeathoftheturtleandofthetwolinksthatdiedwithit:
[[(turtle 0) (turtle 1)] [(link 0 1)]]
Whatifwenowcreateanewturtle?
create-turtles 1
show map sort nw:get-context
Sinceourcontextisusingthespecialturtlesagentset,thenewturtleisautomaticallyadded:
[[(turtle 0) (turtle 1) (turtle 3)] [(link 0 1)]]
Nowlet’sdemonstratehowitworkswithnormalagentsets.Westartoverwithanewnetworkofredturtles:
clear-all
create-turtles 3 [
create-links-with other turtles
set color red
]
Andwesetthecontexttoturtles with [ color = red ]) andlinks
nw:set-context (turtles with [ color = red ]) links
show map sort nw:get-context
Sinceallturtlesarered,wegeteverythinginourcontext:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Butwhatifweaskoneofthemtoturnblue?
ask one-of turtles [ set color blue ]
show map sort nw:get-context
Nochange.Theagentsetusedinourcontextremainsunaffected:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Ifwekilloneofthem,however
ask one-of turtles [ die ]
show map sort nw:get-context
Itgetsremovedfromtheset:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
Whatifweaddanewredturtle?
create-turtles 1 [ set color red ]
show map sort nw:get-context
Nope:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
Anoteregardingfloatingpointcalculations
NeitherJGraphTnorJung,thetwonetworklibrariesthatweuseinternally,usestrictfpfloatingpointcalculations.
Thisdoesmeanthatexactreproducibilityofresultsinvolvingfloatingpointcalculationsbetweendifferenthardware
architecturesisnotfullyguaranteed.(NetLogoitselfalwaysusesstrictmathsothisonlyappliestosomeprimitivesof
theNWextension.)
Performance
Inordertobefastinasmanycircumstancesaspossible,theNWextensiontrieshardtonevercalculatethings
twice.Itremembersallpaths,distances,andcentralitiesthatitcalculates.So,whilethefirsttimeyouaskforthe
distancebetweenturtle 0andturtle 3782maytakesometime,afterthat,itshouldbealmostinstantaneous.
Furthermore,itkeepstrackofvaluesitjusthappenedtocalculatealongtheway.Forexample,ifturtle 297iscloser
toturtle 0thanturtle 3782is,itmayjusthappentofigureoutthedistancebetweenturtle 0andturtle 297while
itfiguresoutthedistancebetweenturtle 0andturtle 3782.Itwillrememberthisvalue,sothatifyouaskitforthe
distancebetweenturtle 0andturtle 297,itdoesn’thavetodoallthatworkagain.
ThereareafewcircumstanceswheretheNWextensionhastoforgetthings.Ifthenetworkchangesatall(youadd
turtlesorlinks,orremoveturtlesorlinks),ithastoforgeteverything.Forweightedprimitives,ifthevalueofthe
weightvariablechangesforanyofthelinksinthenetwork,itwillforgetthevaluesassociatedwiththatweight
variable.
Ifyou’reworkingonanetworkthatcanchangeregularly,trytodoallyournetworkcalculationsatonce,thenallyour
networkchangesatonce.Themoreyourinterweavenetworkcalculationsandnetworkchanges,themoretheNW
extensionwillhavetorecalculatethings.Forexample,ifyouhaveatrafficmodel,andcarsneedtofigureoutthe
shortestpathtotheirdestinationbasedonthetrafficeachtick,haveallthecarsfindtheirshortestpaths,then
changethenetworkweightstoaccountforhowtraffichaschanged.
Theremayberareoccasionsinwhichyoudon’twanttheNWextensiontoremembervalues.Forexample,ifyou’re
workingonanextremelylargenetwork,rememberingallthosevaluesmaytakemorememorythanyouhave.Inthat
case,youcanjustcallnw:set-context (first nw:get-context) (last nw:get-context) toforcetheNWextensionto
immediatelyforgeteverything.
Primitives
Generators
nw:generate-preferential-attachmentnw:generate-randomnw:generate-watts-strogatznw:generate-small-world
nw:generate-lattice-2dnw:generate-ringnw:generate-starnw:generate-wheel
PathandDistance
nw:turtles-in-radiusnw:turtles-in-reverse-radiusnw:distance-tonw:weighted-distance-tonw:path-tonw:turtles-
on-path-tonw:weighted-path-tonw:turtles-on-weighted-path-tonw:mean-path-lengthnw:mean-weighted-path-length
Clusterer/CommunityDetection
nw:bicomponent-clustersnw:weak-component-clustersnw:louvain-communitiesnw:maximal-cliquesnw:biggest-
maximal-cliques
ContextManagement
nw:set-contextnw:get-contextnw:with-context
ImportandExport
nw:save-matrixnw:load-matrixnw:save-graphmlnw:load-graphmlnw:loadnw:save
CentralityMeasures
nw:betweenness-centralitynw:eigenvector-centralitynw:page-ranknw:closeness-centralitynw:weighted-closeness-
centrality
ClusteringMeasures
nw:clustering-coefficientnw:modularity
nw:set-context
nw:set-contextturtlesetlinkset
Specifiesthesetofturtlesandthesetoflinksthattheextensionwillconsidertobethecurrentgraph.Alltheturtles
fromturtlesetandallthelinksfromlinksetthatconnecttwoturtlesfromturtlesetwillbeincluded.
Thiscontextisusedbyallotherprimitives(unlessspecifiedotherwise)untilanewcontextisspecified.(Atthe
moment,onlythegeneratorprimitivesandthefileinputprimitivesareexceptionstothisrule.)
Seetheusagesectionforamuchmoredetailedexplanationofnw:set-context.
nw:get-context
nw:get-context
Reportsthecontentofthecurrentgraphcontextasalistcontainingtwoagentsets:theagentsetofturtlesthatare
partofthecontextandtheagentsetoflinksthatarepartofthecontext.
Let’ssaywestartwithablankslateandthedefaultcontextconsistingofturtlesandlinks,nw:get-contextwill
reportalistthespecialturtlesandlinksbreedagentsets:
observer> clear-all
observer> show nw:get-context
observer: [turtles links]
Ifweaddsometurtlesandlinkstoourcontext,we’llstillseethesamething,eventhoughturtlesandlinkshave
internallygrown:
observer> crt 2 [ create-links-with other turtles ]
observer> show nw:get-context
observer: [turtles links]
Ifyouhadsetyourcontexttonormalagentsetsinstead(builtwithturtle-set,link-setorwith)hereiswhatyou
wouldsee:
observer> clear-all
observer> nw:set-context turtle-set turtles link-set links
observer> show nw:get-context
observer: [(agentset, 0 turtles) (agentset, 0 links)]
Ifyouthencreatenewturtlesandlinks,theyarenotaddedtothecontextbecausenormalagentsetsdon’tgrow(see
Specialagentsetsvsnormalagentsets):
observer> crt 2 [ create-links-with other turtles ]
observer> show nw:get-context
observer: [(agentset, 0 turtles) (agentset, 0 links)]
Butifyouconstructnewagentsetsandsetthecontexttothem,yournewagentswillbethere:
observer> nw:set-context turtle-set turtles link-set links
observer> show nw:get-context
observer: [(agentset, 2 turtles) (agentset, 1 link)]
Ifyouwanttoseetheactualcontentofyourcontext,itiseasytoturnyouragentsetsintoliststhatcanbenicely
displayed.Justuseacombinationofmapandsort:
observer> show map sort nw:get-context
observer: [[(turtle 0) (turtle 1)] [(link 0 1)]]
Finally,youcanusenw:get-contexttostoreacontextthatyoueventuallywanttorestore:
extensions [ nw ]
to store-and-restore-context
clear-all
crt 2 [
set color red
create-links-with other turtles with [ color = red ] [
set color yellow
]
]
crt 2 [
set color blue
create-links-with other turtles with [ color = blue ] [
set color green
]
]
nw:set-context turtles with [ color = red ] links with [ color = yellow ]
show map sort nw:get-context
let old-turtles item 0 nw:get-context
let old-links item 1 nw:get-context
nw:set-context turtles with [ color = blue ] links with [ color = green ]
show map sort nw:get-context
nw:set-context old-turtles old-links
show map sort nw:get-context
end
Hereistheresult:
observer> store-and-restore-context
observer: [[(turtle 0) (turtle 1)] [(link 0 1)]]
observer: [[(turtle 2) (turtle 3)] [(link 2 3)]]
observer: [[(turtle 0) (turtle 1)] [(link 0 1)]]
nw:with-context
nw:with-contextturtlesetlinksetcommand-block
Executesthecommand-blockwiththecontexttemporarilysettoturtlesetandlinkset.Aftercommand-blockfinishes
running,thepreviouscontextwillberestored.
Forexample:
observer> create-turtles 3 [ create-links-with other turtles ]
observer> nw:with-context (turtle-set turtle 0 turtle 1) (link-set link 0 1) [ show nw:get-context ]
observer: [(agentset, 2 turtles) (agentset, 1 link)
observer> show nw:get-context
observer: [turtles links]
IfyouhaveNWextensioncoderunningintwoforeverbuttonsorloopblocksthateachneedtousedifferent
contexts,youshouldusenw:with-contextineachtomakesuretheyareoperatinginthecorrectcontext.
nw:turtles-in-radius
nw:turtles-in-radiusradius
Returnsthesetofturtleswithinthegivendistance(numberoflinksfollowed)ofthecallingturtleinthecurrent
context,includingthecallingturtle.
nw:turtles-in-radiusformwillfollowbothundirectedlinksanddirectedoutlinks.Youcanthinkofturtles-in-
radiusas“turtleswhoIcangettoinradiussteps”.
Ifyouwanttheprimitivetofollowonlyundirectedlinksoronlydirectedlinks,youcandoitbysettingthecontext
appropriately.Forexample:nw:set-context turtles undir-links (assumingundir-linksisanundirectedlink
breed)ornw:set-context turtles dir-links(assumingdir-linksisadirectedlinkbreed).
Example:
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 ]
ask turtle 0 [ create-link-with turtle 2 ]
ask turtle 1 [ create-link-with turtle 3 ]
ask turtle 2 [ create-link-with turtle 4 ]
ask turtle 0 [
show sort nw:turtles-in-radius 1
]
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
Asyoumayhavenoticed,theresultincludesthecallingturtle.ThismimicsthebehavioroftheregularNetLogoin-
radiusprimitive.
nw:turtles-in-reverse-radius
nw:turtles-in-reverse-radiusradius
Likenw:turtles-in-radius,butfollowsin-linksinsteadofout-links.Alsofollowundirectedlinks.Youcanthinkof
turtles-in-reverse-radiusas“turtleswhocangettomeinradiussteps”.
nw:distance-to
nw:distance-totarget-turtle
Findstheshortestpathtothetargetturtleandreportsthetotaldistanceforthispath,orfalseifnopathexistsinthe
currentcontext.Eachlinkcountsforadistanceofone.
Example:
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 ]
ask turtle 1 [ create-link-with turtle 2 ]
ask turtle 0 [ create-link-with turtle 3 ]
ask turtle 3 [ create-link-with turtle 4 ]
ask turtle 4 [ create-link-with turtle 2 ]
ask turtle 0 [ show nw:distance-to turtle 2 ]
end
Willoutput:
(turtle 0): 2
nw:weighted-distance-to
nw:weighted-distance-totarget-turtleweight-variable
Likenw:distance-to,buttakeslinkweightintoaccount.Theweightscannotbenegativenumbers.
Example:
links-own [ weight ]
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ]
ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ]
ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ]
ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ]
ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ]
ask turtle 0 [ show nw:weighted-distance-to turtle 2 weight ]
end
Willoutput:
(turtle 0): 1.5
nw:path-to
nw:path-totarget-turtle
Findstheshortestpathtothetargetturtleandreportstheactualpathbetweenthesourceandthetargetturtle.The
pathisreportedasthelistoflinksthatconstitutethepath.
Ifnopathexistbetweenthesourceandthetargetturtles,falsewillbereportedinstead.
NotethattheNW-Extensionrememberspathsthatitscalculatedpreviouslyunlessthenetworkchanges.Thus,you
don’tneedtostorepathstoefficientlymoveacrossthenetwork;youcanjustkeepre-callingoneofthepath
primitives.Ifthenetworkchanges,however,thestoredanswersareforgotten.Example:
links-own [ weight ]
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 ]
ask turtle 1 [ create-link-with turtle 2 ]
ask turtle 0 [ create-link-with turtle 3 ]
ask turtle 3 [ create-link-with turtle 4 ]
ask turtle 4 [ create-link-with turtle 2 ]
ask turtle 0 [ show nw:path-to turtle 2 ]
end
Willoutput:
(turtle 0): [(link 0 1) (link 1 2)]
nw:turtles-on-path-to
nw:turtles-on-path-totarget-turtle
Likenw:path-to,buttheturtlesonthepatharereported,insteadofthelinks,includingthesourceturtleandtarget
turtle.
Example:
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 ]
ask turtle 1 [ create-link-with turtle 2 ]
ask turtle 0 [ create-link-with turtle 3 ]
ask turtle 3 [ create-link-with turtle 4 ]
ask turtle 4 [ create-link-with turtle 2 ]
ask turtle 0 [ show nw:turtles-on-path-to turtle 2 ]
end
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
nw:weighted-path-to
nw:weighted-path-totarget-turtleweight-variable
Likenw:path-to,buttakeslinkweightintoaccount.
Example:
links-own [ weight ]
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ]
ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ]
ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ]
ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ]
ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ]
ask turtle 0 [ show nw:weighted-path-to turtle 2 weight ]
end
Willoutput:
(turtle 0): [(link 0 3) (link 3 4) (link 2 4)]
nw:turtles-on-weighted-path-to
nw:turtles-on-weighted-path-totarget-turtleweight-variable
Likenw:turtles-on-path-to,buttakeslinkweightintoaccount.
Example:
links-own [ weight ]
to go
clear-all
create-turtles 5
ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ]
ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ]
ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ]
ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ]
ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ]
ask turtle 0 [ show nw:weighted-path-to turtle 2 weight ]
end
Willoutput:
(turtle 0): [(turtle 0) (turtle 3) (turtle 4) (turtle 2)]
nw:mean-path-length
nw:mean-path-length
Reportstheaverageshortest-pathlengthbetweenalldistinctpairsofnodesinthecurrentcontext.
Reportsfalseunlesspathsexistbetweenallpairs.
Example:
links-own [ weight ]
to go
clear-all
create-turtles 3
ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ]
ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ]
show nw:mean-path-length
create-turtles 1 ; create a new, disconnected turtle
show nw:mean-path-length
end
Willouput:
observer: 1.3333333333333333
observer: false
nw:mean-weighted-path-length
nw:mean-weighted-path-lengthweight-variable
Likenw:mean-path-length,buttakesintoaccountlinkweights.
Example:
links-own [ weight ]
to go
clear-all
create-turtles 3
ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ]
ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ]
show nw:mean-path-length
show nw:mean-weighted-path-length weight
create-turtles 1 ; create a new, disconnected turtle
show nw:mean-path-length
show nw:mean-weighted-path-length weight
end
Willouput:
observer: 2.6666666666666665
observer: false
nw:betweenness-centrality
nw:betweenness-centrality
Tocalculatethebetweennesscentralityofaturtle,youtakeeveryotherpossiblepairsofturtlesand,foreachpair,
youcalculatetheproportionofshortestpathsbetweenmembersofthepairthatpassesthroughthecurrentturtle.
Thebetweennesscentralityofaturtleisthesumofthese.
Asofnow,linkweightsarenottakenintoaccount.
nw:eigenvector-centrality
nw:eigenvector-centrality
TheEigenvectorcentralityofanodecanbethoughtofastheamountofinfluenceanodehasonanetwork.In
practice,turtlesthatareconnectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)geta
higherEigenvectorcentralityscore.
Inthisimplementation,theeigenvectorcentralityisnormalizedsuchthatthehighesteigenvectorcentralityanode
canhaveis1.ThisimplementationisdesignedtoagreewithGephi’simplementationouttoatleast3decimal
places.IfyoudiscoverthatitdisagreeswithGephionaparticularnetwork,pleasereportit.
Theprimitiverespectslinkdirection,eveninmixed-directednetworks.Thisistheoneplacewhereitshoulddisagree
withGephi;Gephirefusestotreatdirectedlinksasdirectedinmixed-networks.
Asofnow,linkweightsarenottakenintoaccount.
nw:page-rank
nw:page-rank
Thepagerankofanodecanbethoughtofastheproportionoftimethatanagentwalkingforeveratrandomonthe
networkwouldspendatthisnode.Theagenthasanequalchanceoftakinganyofanodesedges,andwilljump
aroundthenetworkcompletelyrandomly15%ofthetime.Inpractice,likewitheigenvectorcentrality,turtlesthatare
connectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)getahigherpagerank.
Pagerankisoneoftheseveralalgorithmsthatsearchenginesusetodeterminetheimportanceofawebsite.
Thesumofallpagerankvaluesshouldbeapproximatelyone.Unlikeeigenvectorcentrality,pagerankisdefinedfor
allnetworks,nomattertheconnectivity.Currently,ittreatsalllinksasundirectedlinks.
Asofnow,linkweightsarenottakenintoaccount.
nw:closeness-centrality
nw:closeness-centrality
Theclosenesscentralityofaturtleisdefinedastheinverseoftheaverageofit’sdistancestoallotherturtles.(Some
peopleusethesumofdistancesinsteadoftheaverage,buttheextensionusestheaverage.)
Notethatthisprimitivereportstheintra-componentclosenessofaturtle,thatis,ittakesintoaccountonlythe
distancestotheturtlesthatarepartofthesamecomponentasthecurrentturtle,sincedistancetoturtlesinother
componentsisundefined.Theclosenesscentralityofanisolatedturtleisdefinedtobezero.
nw:weighted-closeness-centrality
nw:weighted-closeness-centralitylink-weight-variable
Thisisidenticaltonw:closeness-centrality,exceptthatweightsprovidedbythegivenvariablearetreatedasthe
distancesoflinks.
nw:clustering-coefficient
nw:clustering-coefficient
Reportsthelocalclusteringcoefficientoftheturtle.Theclusteringcoefficientofanodemeasureshowconnectedits
neighborsare.Itisdefinedasthenumberoflinksbetweenthenode’sneighborsdividedbythetotalnumberof
possiblelinksbetweenitsneighbors.
nw:clustering-coefficienttakesthedirectednessoflinksintoaccount.Adirectedlinkcountsasasinglelink
whereasanundirectedlinkcountsastwolinks(onegoingone-way,onegoingtheother).
Theglobalclusteringcoefficientmeasureshowmuchnodestendtoclustertogetherinthenetworkingeneral.Itis
definedbasedonthetypesoftripletsinthenetwork.Atripletconsistsofacentralnodeandtwoofitsneighbors.Ifits
neighborsarealsoconnected,it’saclosedtriplet.Ifitsneighborsarenotconnected,it’sanopentriplet.Theglobal
clusteringcoefficientissimplythenumberofclosedtripletsinanetworkdividedbythetotalnumberoftriplets.Itcan
becalculatedfromthelocalclusteringcoefficientquiteeasilywiththefollowingcode
to-report global-clustering-coefficient
let closed-triplets sum [ nw:clustering-coefficient * count my-links * (count my-links - 1) ] of turtles
let triplets sum [ count my-links * (count my-links - 1) ] of turtles
report closed-triplets / triplets
end
Notethattheabovewillonlyworkwiththedefaultcontext,andmayneedtotweakedifyou’vesettheturtlesorlinks
inthenetworktosomethingotherthanturtlesandlinks.
Theaveragelocalclusteringcoefficientisanotherpopularmethodformeasuringtheamountofclusteringinthe
networkasawhole.Itmaybecalculatedwith
mean [ nw:clustering-coefficient ] of turtles
nw:modularity
nw:modularity
Modularityisameasurementofcommunitystructureinthenetwork.Itisdefinedbasedonthenumberofin-
communitylinksversusthenumberofbetween-communitylinks.Thisprimitivetakesasinputalistofagentsets,
whereeachoftheagentsetsisonethecommunitiesthatyou’reseparatingthenetworkinto.
Thismeasurementworksonundirected,directed,andmixed-directednessnetworks.Inthecaseofmixed-
directedness,undirectedlinksaretreatedessentiallythesameastwoopposingdirectedlinks.Itdoesnottake
weightintoaccount.
Example:
nw:modularity (list (turtles with [ color = blue ]) (turtles with [ color = red ]))
nw:bicomponent-clusters
nw:bicomponent-clusters
Reportsthelistofbicomponentclustersinthecurrentnetworkcontext.Abicomponent(alsoknownasamaximal
biconnectedsubgraph)isapartofanetworkthatcannotbedisconnectedbyremovingonlyonenode(i.e.youneed
toremoveatleasttwotodisconnectit).Theresultisreportedasalistofagentsets,inrandomorder.Notethatone
turtlecanbeamemberofmorethanonebicomponentatonce.
nw:weak-component-clusters
nw:weak-component-clusters
Reportsthelistof“weakly”connectedcomponentsinthecurrentnetworkcontext.Aweaklyconnectedcomponentis
simplyagroupofnodeswherethereisapathfromeachnodetoeveryothernode.A“strongly”connected
componentwouldbeonewherethereisadirectedpathfromeachnodetoeveryother.Theextensiondoesnot
supporttheidentificationofstronglyconnectedcomponentsatthemoment.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecannotbeamemberofmorethan
oneweaklyconnectedcomponentatonce.
nw:louvain-communities
nw:louvain-communities
Detectscommunitystructurepresentinthenetwork.ItdoesthisbymaximizingmodularityusingtheLouvainmethod.
Thecommunitiesarereportedasalistofturtle-sets.
Oftenyou’llwanttotellturtlesaboutthecommunitythattheyarein.Youcandothislikeso:
turtles-own [ community ]
...
foreach nw:louvain-communities [ [comm] ->
ask comm [ set community comm ]
]
Youcangiveeachcommunityitsowncolorwithsomethinglikethis:
let communities nw:louvain-communities
let colors sublist 0 (length communities) base-colors
(foreach communities colors [ [community col] ->
ask community [ set color col ]
])
nw:maximal-cliques
nw:maximal-cliques
Acliqueisasubsetofanetworkinwhicheverynodehasadirectlinktoeveryothernode.Amaximalcliqueisa
cliquethatisnot,itself,containedinabiggerclique.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecanbeamemberofmorethanone
maximalcliqueatonce.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:biggest-maximal-cliques
nw:biggest-maximal-cliques
Thebiggestmaximalcliquesare,asthenameimplies,thebiggestcliquesinthecurrentcontext.Often,morethan
onecliquearetiedforthetitleofbiggestclique,sotheresultisreportedasalistofagentsets,inrandomorder.Ifyou
wantonlyoneclique,useone-of nw:biggest-maximal-cliques.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:generate-preferential-attachment
nw:generate-preferential-attachmentturtle-breedlink-breednum-nodesmin-degreeoptional-command-
block
GeneratesanewnetworkusingaversionoftheBarabási–Albertalgorithm.Thisnetworkwillhavethepropertyof
being“scalefree”:thedistributionofdegrees(i.e.thenumberoflinksforeachturtle)shouldfollowapowerlaw.
Generationworksasfollowsturtlesareadded,onebyone,eachformingmin-degreelinkstoapreviouslyadded
turtles,untilnum-nodesisreached.Themorelinksaturtlealreadyhas,thegreatertheprobabilitythatnewturtles
formlinkswithitwhentheyareadded.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-preferential-attachment turtles links 100 1 [ set color red ]
nw:generate-random
nw:generate-randomturtle-breedlink-breednum-nodesconnection-probabilityoptional-command-block
Generatesanewrandomnetworkofnum-nodesturtlesinwhicheachonehasaconnection-probability(between0
and1)ofbeingconnectedtoeachotherturtles.ThealgorithmusestheG(n,p)variantoftheErdős–Rényimodel.
ThealgorithmisO(n²)fordirectednetworksandO(n²/2)forundirectednetworks,sogeneratingmorethanacouple
thousandnodeswilllikelytakeaverylongtime.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-random turtles links 100 0.5 [ set color red ]
nw:generate-watts-strogatz
nw:generate-watts-strogatzturtle-breedlink-breednum-nodesneighborhood-sizerewire-probability
optional-command-block
GeneratesanewWatts-Strogatzsmall-worldnetwork.
Thealgorithmbeginsbycreatingaringofnodes,whereeachnodeisconnectedtoneighborhood-sizenodeson
eitherside.Then,eachlinkisrewiredwithprobabilityrewire-prob.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Furthermore,
theturtlesaregeneratedintheordertheyappearasincreate-ordered-turtles.So,inordertolaytheringoutasa
ring,youcandosomethinglike:
nw:generate-watts-strogatz turtles links 50 2 0.1 [ fd 10 ]
nw:generate-small-world
nw:generate-small-worldturtle-breedlink-breedrow-countcolumn-countclustering-exponentis-toroidal
optional-command-block
Generatesanewsmall-worldnetworkusingtheKleinbergModel.Notethatnw:generate-watts-strogatzgeneratesa
moretraditionalsmall-worldnetwork.
Thealgorithmproceedsbygeneratingalatticeofthegivennumberofrowsandcolumns(thelatticewillwraparound
itselfifis-toroidalistrue).The“smallworldeffect”iscreatedbyaddingadditionallinksbetweenthenodesinthe
lattice.Thehighertheclustering-exponent,themorethealgorithmwillfavoralreadyclose-bynodeswhenadding
newlinks.Aclusteringexponentof2.0istypicallyused.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-small-world turtles links 10 10 2.0 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togenerateakleinberglattice
accrosstheentireworld,andlayitoutaccordingly,trythefollowing:
nw:generate-small-world turtles links world-width world-height 2.0 false
(foreach (sort turtles) (sort patches) [ [t p] -> ask t [ move-to p ] ])
nw:generate-lattice-2d
nw:generate-lattice-2dturtle-breedlink-breedrow-countcolumn-countis-toroidaloptional-command-block
Generatesanew2Dlatticenetwork(basically,agrid)ofrow-countrowsandcolumn-countcolumns.Thegridwill
wraparounditselfifis-toroidalistrue.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-lattice-2d turtles links 10 10 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togeneratealatticeaccross
theentireworld,andlayitoutaccordingly,trythefollowing:
nw:generate-lattice-2d turtles links world-width world-height false
(foreach (sort turtles) (sort patches) [ [t p] -> ask t [ move-to p ] ])
nw:generate-ring
nw:generate-ringturtle-breedlink-breednum-nodesoptional-command-block
Generatesaringnetworkofnum-nodesturtles,inwhicheachturtleisconnectedtoexactlytwootherturtles.
Thenumberofnodesmustbeatleastthree.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-ring turtles links 100 [ set color red ]
nw:generate-star
nw:generate-starturtle-breedlink-breednum-nodesoptional-command-block
Generatesastarnetworkinwhichthereisonecentralturtleandeveryotherturtleisconnectedonlytothiscentral
node.Thenumberofturtlescanbeaslowasone,butitwon’tlookmuchlikeastar.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-star turtles links 100 [ set color red ]
nw:generate-wheel
nw:generate-wheelturtle-breedlink-breednum-nodesoptional-command-block
Variants:
nw:generate-wheel-inward
nw:generate-wheel-outward
Generatesawheelnetwork,whichisbasicallyaringnetworkwithanadditional“central”turtlethatisconnectedto
everyotherturtle.
Thenumberofnodesmustbeatleastfour.
Thenw:generate-wheelonlyworkswithundirectedlinkbreeds.Thenw:generate-wheel-inwardandnw:generate-
wheel-outwardversionsonlyworkwithdirectedlink-breed.Theinwardandoutwardpartoftheprimitivenamesrefer
tothedirectionthatthe“spokes”ofthewheelpointtorelativetothecentralturtle.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-wheel turtles links 100 [ set color red ]
nw:save-matrix
nw:save-matrixfile-name
Savesthecurrentnetwork,asdefinedbynw:set-context,tofile-name,asatextfile,intheformofasimple
connectionmatrix.
Hereis,forexample,aundirectedringnetworkwithfournodes:
0.00 1.00 0.00 1.00
1.00 0.00 1.00 0.00
0.00 1.00 0.00 1.00
1.00 0.00 1.00 0.00
Andhereisthedirectedversion:
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00
1.00 0.00 0.00 0.00
Atthemoment,nw:save-matrixdoesnotsupportlinkweights.Everylinkisrepresentedasa“1.00”intheconnection
matrix.Thiswillchangeinafutureversionoftheextension.
nw:load-matrix
nw:load-matrixfile-nameoptional-command-block
Generatesanewnetworkaccordingtotheconnectionmatrixsavedinfile-name,usingturtle-breedandlink-breedto
createthenewturtlesandlinks.
Atthemoment,nw:load-matrixdoesnotsupportlinkweights.
Pleasebeawarethatthebreedsthatuseusetoloadthematrixmaybedifferentfromthosethatyouusedwhenyou
savedit.
Forexample:
extensions [ nw ]
directed-link-breed [ dirlinks dirlink ]
to go
clear-all
crt 5 [ create-dirlinks-to other turtles ]
nw:set-context turtles dirlinks
nw:save-matrix "matrix.txt"
clear-all
nw:load-matrix "matrix.txt" turtles links
layout-circle turtles 10
end
willgiveyoubackundirectedlinks,evenifyousaveddirectedlinksintothematrix.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-matrix "matrix.txt" turtles links [ set color red ]
nw:save-graphml
nw:save-graphmlfile-name
YoucansavethecurrentgraphtoGraphML.ThefollowingNetLogocode:
extensions [ nw ]
breed [ bankers banker ]
bankers-own [ bank-name ]
breed [ clients client ]
clients-own [ hometown ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]
accounts-own [ amount ]
to go
clear-all
create-bankers 1 [
set bank-name "The Bank"
]
create-clients 1 [
set hometown "Turtle City"
create-friendship-with banker 0
create-account-to banker 0 [
set amount 9999.99
]
]
nw:set-context turtles links
nw:save-graphml "example.graphml"
end
WillproducethefollowingGraphMLfile:
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns/graphml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns/graphml">
<key id="PEN-MODE" for="node" attr.name="PEN-MODE" attr.type="string"/>
<key id="YCOR" for="node" attr.name="YCOR" attr.type="double"/>
<key id="PEN-SIZE" for="node" attr.name="PEN-SIZE" attr.type="double"/>
<key id="LABEL" for="node" attr.name="LABEL" attr.type="string"/>
<key id="SHAPE" for="node" attr.name="SHAPE" attr.type="string"/>
<key id="BREED" for="node" attr.name="BREED" attr.type="string"/>
<key id="WHO" for="node" attr.name="WHO" attr.type="double"/>
<key id="HIDDEN?" for="node" attr.name="HIDDEN?" attr.type="boolean"/>
<key id="LABEL-COLOR" for="node" attr.name="LABEL-COLOR" attr.type="double"/>
<key id="HEADING" for="node" attr.name="HEADING" attr.type="double"/>
<key id="BANK-NAME" for="node" attr.name="BANK-NAME" attr.type="string"/>
<key id="HOMETOWN" for="node" attr.name="HOMETOWN" attr.type="string"/>
<key id="COLOR" for="node" attr.name="COLOR" attr.type="double"/>
<key id="XCOR" for="node" attr.name="XCOR" attr.type="double"/>
<key id="SIZE" for="node" attr.name="SIZE" attr.type="double"/>
<key id="END1" for="edge" attr.name="END1" attr.type="string"/>
<key id="TIE-MODE" for="edge" attr.name="TIE-MODE" attr.type="string"/>
<key id="END2" for="edge" attr.name="END2" attr.type="string"/>
<key id="LABEL-COLOR" for="edge" attr.name="LABEL-COLOR" attr.type="double"/>
<key id="THICKNESS" for="edge" attr.name="THICKNESS" attr.type="double"/>
<key id="LABEL" for="edge" attr.name="LABEL" attr.type="string"/>
<key id="SHAPE" for="edge" attr.name="SHAPE" attr.type="string"/>
<key id="BREED" for="edge" attr.name="BREED" attr.type="string"/>
<key id="COLOR" for="edge" attr.name="COLOR" attr.type="double"/>
<key id="AMOUNT" for="edge" attr.name="AMOUNT" attr.type="double"/>
<key id="HIDDEN?" for="edge" attr.name="HIDDEN?" attr.type="boolean"/>
<graph edgedefault="undirected">
<node id="client 1">
<data key="PEN-MODE">up</data>
<data key="YCOR">0</data>
<data key="PEN-SIZE">1</data>
<data key="LABEL"></data>
<data key="SHAPE">default</data>
<data key="BREED">clients</data>
<data key="WHO">1</data>
<data key="HIDDEN?">false</data>
<data key="LABEL-COLOR">9.9</data>
<data key="HEADING">356</data>
<data key="HOMETOWN">Turtle City</data>
<data key="COLOR">115</data>
<data key="XCOR">0</data>
<data key="SIZE">1</data>
</node>
<node id="banker 0">
<data key="PEN-MODE">up</data>
<data key="YCOR">0</data>
<data key="PEN-SIZE">1</data>
<data key="LABEL"></data>
<data key="SHAPE">default</data>
<data key="BREED">bankers</data>
<data key="WHO">0</data>
<data key="HIDDEN?">false</data>
<data key="LABEL-COLOR">9.9</data>
<data key="HEADING">32</data>
<data key="BANK-NAME">The Bank</data>
<data key="COLOR">85</data>
<data key="XCOR">0</data>
<data key="SIZE">1</data>
</node>
<edge source="client 1" target="banker 0">
<data key="END1">(client 1)</data>
<data key="TIE-MODE">none</data>
<data key="END2">(banker 0)</data>
<data key="LABEL-COLOR">9.9</data>
<data key="THICKNESS">0</data>
<data key="LABEL"></data>
<data key="SHAPE">default</data>
<data key="BREED">accounts</data>
<data key="COLOR">5</data>
<data key="AMOUNT">9999.99</data>
<data key="HIDDEN?">false</data>
</edge>
<edge source="banker 0" target="client 1">
<data key="END1">(banker 0)</data>
<data key="TIE-MODE">none</data>
<data key="END2">(client 1)</data>
<data key="LABEL-COLOR">9.9</data>
<data key="THICKNESS">0</data>
<data key="LABEL"></data>
<data key="SHAPE">default</data>
<data key="BREED">friendships</data>
<data key="COLOR">5</data>
<data key="HIDDEN?">false</data>
</edge>
</graph>
</graphml>
Afewthingstonotice:
Thebreedisstoredasdatafield,bothfornodesandedges.
ThedataincludesbothNetLogo’sinternalvariablesandthevariablesthatweredefinedaseitherbreeds-own,
turtles-own,linkbreeds-ownorlinks-own.
Eachkeygetsanattr.typebasedontheactualtypesofthevaluescontainedintheagentvariables.Thethree
possibletypesare"string","double"and"boolean".Todeterminetheattributetypeofaparticularagentvariable,
theextensionwilllookatthefirstagentinthegraph.Toseewhichagentisfirst,youcanlookattheresultof
nw:get-context.Notethatvariablescontainingothertypesofvalues,suchasturtles,patches,lists,etc.,willbe
storedasstrings.
Thisexampleonlyhasadirectedlink,andyouwillnoticethe<graph edgedefault="directed">element.Ifwehad
onlyundirectedlinks,wewouldhave<graph edgedefault="undirected">.Whatifwetrytomixbothkindsoflink?
Atthemoment,theextensionwillsavesucha“mixed”graphasifitwereanundirectedgraph(seethisissuefor
moredetails).Theorderofthesourceandtargetwillberespected,however,soifyouknowwhichbreeds
representdirectedlinks,youcanfigureitoutaposteriori.
nw:load-graphml
nw:load-graphmlfile-nameoptional-command-block
LoadingaGraphMLfileintoNetLogowiththenetworkextensionshouldbeassimpleascallingnw:load-graphml
"example.graphml",butthereisabitofpreparationinvolved.
Thekeyideaisthatnw:load-graphmlwilltrytoassigntheattributevaluesdefinedintheGraphMLfiletoNetLogo
agentvariablesofthesamenames(thisisnotcasesensitive).Thefirstoneittriestosetisbreedifitisthere,sothe
turtleorlinkwillgettherightbreedand,hence,therightbreedvariables.
Onespecialcaseisthewhonumber,whichisignoredbytheimporterifitispresentasaGraphMLattribute:NetLogo
doesnotallowyoutomodifythisnumberonceaturtleiscreatedand,besides,therecouldalreadybeanexisting
turtlewiththatnumber.
ThesimplestcasetohandleiswhentheoriginalGraphMLfilehasbeensavedfromNetLogobyusingnw:save-
graphml.Inthiscase,allyoushouldhavetodoistomakesurethatyouhavethesamebreedandvariables
definitionaswhenyousavedthefileandyoushouldgetbackyouroriginalgraph.Forexample,ifyouwanttoload
thefilefromthenw:save-graphmlexampleabove,youshouldhavethefollowingdefinitions:
breed [ bankers banker ]
bankers-own [ bank-name ]
breed [ clients client ]
clients-own [ hometown ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]
accounts-own [ amount ]
LoadingagraphthatwassavedfromadifferentprogramthanNetLogoisquitepossibleaswell,butitmaytakeabit
oftinkeringtogetalltheattribute-variablematchupright.Ifyouencountermajorproblems,pleasedonothesitateto
openanissue.
Theextensionwilltrytoassignthetypedefinedbyattr.typetoeachvariablethatitloads.Ifit’sunabletoconvertit
tothattype,itwillloaditasastring.Ifattr.typeisnotdefined,orissettoanunknownvalue,theextensionwillfirst
trytoloadthevalueasadouble,thentryitasaboolean,andfinallyfallbackonastring.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-graphml "example.graphml" [ set color red ]
Notethatthiscommandblockcanbeusedtobuildalistoranagentsetcontainingthenewlycreatednodes:
let node-list []
nw:load-graphml "example.graphml" [
set node-list lput self node-list
]
let node-set turtle-set node-list
nw:load
nw:loadfile-namedefault-turtle-breeddefault-link-breedoptional-command-block
Filetypespecificvariants:
nw:load
nw:load-dl
nw:load-gdf
nw:load-gexf
nw:load-gml
nw:load-vna
ImportthegivenfileintoNetLogo.Likenw:load-graphml,theimporterwilldoitsbesttomatchnodeandedge
attributesinthefilewithturtleandlinkvariablesinNetLogo.Ifbreedisspecifiedfornodesandedgesinthefileand
existsinNetLogo,itwillbeused.Otherwise,thedefaultturtleandlinkbreedsareused.
Limitations:
Multigraphsarenotsupportedinimporting.Evenifthefileformatsupportsit(andmanydon’t),onlythefirstlink
willbeusedonimport.ThisisduetoalimitationintheparsinglibrariesNWuses.nw:load-graphmldoessupport
multigraphswiththenormalNetLogolimitationthattwoturtlescansharemorethanonelinkonlyifallthelinksare
ofdifferentbreeds.
nw:loaddeterminesthefile-typeofgivenfilebasedontheextensionandcallsthecorrespondingload-*primitiveon
it.NotethatGraphMLmustbeimportedwithnw:load-graphml.
nw:save
nw:savefile-name
Filetypespecificvariants:
nw:save-dl
nw:save-gdf
nw:save-gexf
nw:save-gml
nw:save-vna
Exportthenetworkcontextinthegivenformattothegivenfile.Turtleandlinkattributeswillbeexportedtoformats
thatsupportnodeandedgeproperties.
Limitations:
xandy(notxcorandycor)canonlybenumbers.xandyarecommonlyusedinformatspertainingtopositionand
behindthescenesNWusesGephi’slibrariesforexporting.Furthermore,xandywillbeaddedeveniftheydidn’t
existinthemodel.Again,thisisbecauseNWusesGephi’slibrarieswhichassumethatnodeshavepositions
storedinxandy.IfyouwishtoexporttoGephispecifically,werecommendcreatingxandyturtlesvariablesand
settingthemtoxcorandycorbeforeexport.
ColorwillbeexportedinastandardRGBformat.Thisshouldhopefullyincreasecompatibilitywithotherprograms.
Turtleandlinkvariablesthatcontainvaluesofdifferenttypeswillbestoredasstrings.Unfortunately,mostnetwork
formatsrequirethatnodeandattributeshaveasingletype.
Manyprogramsuselabeltostoretheidofnodes.Thus,ifyou’rehavingtroubleimportingdataexportedfrom
NetLogointoanotherprogram,youmighttrysettingturtles’labelstotheirwhonumber.
Multigraphsarenotsupported.Thus,twoturtlescanshareatmostonelink.nw:save-graphmldoessupport
multigraphs,sousethatifturtlescanhavemorethanonetypeoflinkconnectingthem.
nw:savedeterminesthefile-typeofthegivenfilebasedontheextensionandcallsthecorrespondingsave-*primitive
onit.NotethatGraphMLmustbeexportedwithnw:save-graphml.
NetLogoPaletteExtension
UsingthePaletteExtension
TheNetLogopaletteextensionallowstomapvaluestocolors.ThecolorsgobeyondNetLogocolors,including
ColorBrewercolorschemesorarbitraryRGBcolors.Additionally,itprovidesaprimitivetomaptocolorgradientsanda
primitivetolaunchaColorBrewerdialogforeasyschemeselection.
GettingStarted
TogetstartedwithpalettesaddtothetopofyourCodetab:
extensions [palette]
youcanthencallanyoftheprimitivesbyaddingpalette:beforetheprimitive:
palette:scale-gradient
palette:scale-scheme
palette:scheme-color
palette:scheme-dialog
ThepaletteextensionprimitivesreturnalistcontainingRGBcolors[[r g b][r g b]...[r g b]] ,exceptfor
palette:scheme-dialogwhichopensadialog.
WhatcolorsshouldIuse?
ColorBrewerhasmanycolorswheretostart.ColorBrewerhasthreeschemesSequential,DivergentandQualitative.The
useofColorBrewerformapsisdiscussedatlengthinthispaper(Harrower,Brewer2003).Choosingtherightcolorsisa
designproblem,thus,therearemanyacceptablesolution.However,theseguidelinesmightbeusefulforchoosingcolors
inAgentBasedModels:
Sequentialcolorsarebestforcontinuousnaturalphenomenamodelssuchasasheatdiffusioninphysicsorfirein
earthsciences.
Divergentcolorsareusefulforhighlightingamiddlevalueinamodel.Itcanbealsoappliedtotheheatdiffusionmodel
ifthegoalistohighlightthemiddletemperature.
Qualitativecolorsarebestforchoosingcolorsinmodelswherecolordenotescategoryandnotvalue.
Foragentsthatcoverlargeareasavoidstrongcolorsandtrytousepastelcolors.However,foralownumberofsmall
isolatedagentstrytousestrongcolorssuchassuchaaccent.
Themaingoalistoavoidhavingalargeareacoveredwithagentswithabrightcolorandorhavingsmallareashaving
amutedpastelcolor.
Ifyouarecoloringbothturtlesandpatches,makesuretheyhavedifferentrangesofhue,saturationandvalue.E.g.
Usedifferenthuesofpastelforpatchesandaccentforturtles
ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?
Theanswerdependsonthetaskthatyourwillbeaskingfromyouruser.
Forexample,gradientsaremoreaestheticthusaremorememorablethandiscretecolors.Consequently,agradientcan
beabetterchoiceforpresentationswherethemaingoaloftheimageistobeattractiveandmemorable.However,
binningvaluesinadiscretesetofcolorssimplifiestaskssuchasestimationandcountingbyremovingunnecessary
detailtodisplaythebigpicture.Thus,discretecolorscanbeabetterchoiceforapaperwheretheuserwillhavethetime
andinteresttostudythevisualization.
InordertoseethedifferenceyoucanturnonandoffthegradientintheHeatDiffusionmodel.Youcanobservethat
turninggradientonmakesthemodelmoreaesthetic,butitbecomeshardertoestimatethevalueofapatchatagiven
position.
ExampleModels
ThereisanexampleofusingthepaletteprimitivesintheCodeExamplessectionofthemodelslibrary:
PaletteExample
AndoneSampleModelthatusestheextension:
HeatDiffusion-AlternativeGradient
FurtherReading
BesuretochecktheColorBrewerwebpage
TogetadeeperunderstandingofhowtousethecolorschemesreadtheColorBrewerpaper(Harrower,Brewer2003)
Primitives
palette:scale-gradientpalette:scale-schemepalette:scheme-colorspalette:scale-gradient
palette:scale-gradient
palette:scale-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofa
listcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,the
colorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
Example:
ask patches
[
set pcolor palette:scale-gradient [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor
]
;; colors each patch with a color proportional to the gradient
palette:scale-scheme
palette:scale-schemescheme-typescheme-colornumber-of-classesrange1range2
ReportsanRGBcolorproportionaltonumberusingthecolorbrewerschemes.Ittakessixargumentsthefirstthree
argumentsdefinetheColorBrewerlegend.Firtheusershouldselectascheme-typewhichcanbe“Sequential”,
“Divergent,Qualitative”.Thenitshouldselectavarietyofscheme-colorswhichdependingonthescheme-colorcanhave
namessuchas“Reds”,“Divergent”,“Set1”.Finallytheusershouldselectthenumberofclasseswithaminimumof3and
amaximumbetween9and11.Formoreinformationgotohttp://www.colorbrewer.orgorconsultthescheme-dialog
primitive.
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtoschemecolors.While,ifrange2islessthanrange1,the
colorschemeselectionisinverted.
Ifnumberislessthanrange1,thenthefirstcoloroftheresultingColorBrewerlegendischosen.
Ifnumberisgraterthanrange2,thenthelastcoloroftheresultingColorBrewerlegendischosen.
Example:
ask patches
[
set pcolor palette:scale-scheme [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor
]
;; colors each patch with a color from the Color Brewer Schemes
palette:scheme-colors
palette:scheme-colorsscheme-typescheme-colornumber-of-classes
reportalistofRGBcolorswiththesizespecifiedintheanumberofclasses
Example:
show palette:scheme-colors "Divergent" "Spectral" 3
=> [[252 141 89] [255 255 191] [153 213 148]]
; The schemes-color primitive can be used with the scale-gradient primitive
ask patches
[set pcolor palette:scale-gradient palette:scheme-colors "Divergent" "Spectral" 9 pxcor min-pxcor max-pxcor]
palette:scale-gradient
palette:scale-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofa
listcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,the
colorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
Example:
ask patches
[
set pcolor palette:scale-gradient [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor
]
;; colors each patch with a color proportional to the gradient
References
ColorBrewerwww.colorbrewer.org
HARROWER,M.andC.BREWER(2003).ColorBrewer:Anonlinetoolforselectingcolorschemesformaps.The
CartographicJournal40(1):27-37.)
HEALEY,CG(2006)PerceptioninVisualization,(comprehensivereviewupdatedregularly).
HEALEY,CG,BOOTHKS,andENNS,JT(1995).VisualizingReal-TimeMultivariateDataUsingPreattentive
ProcessingACMTransactionsonModelingandComputerSimulation5,3,190-221.
TUFTE,E(1983)TheVisualDisplayofQuantitativeInformation,GraphicsPress.
WARE,C(2004)InformationVisualization,2ndEd.,MorganKaufmann.Feedback
NetLogoProfilerExtension
UsingtheProfilerExtension
Ifyou’dlikeyourmodeltorunfaster,theprofilerextensionmaybeusefultoyou.It
includesprimitivesthatmeasurehowmanytimestheproceduresinyourmodelarecalled
duringarunandhowlongeachcalltakes.Youcanusethisinformationtowheretofocus
yourspeedupefforts.
Caution:
Theprofilerextensionisexperimental.Itisnotyetwelltestedoruserfriendly.
Nonetheless,wethinksomeuserswillfindituseful.
Howtouse
Theprofilerextensioncomespreinstalled.Tousetheextensioninyourmodel,addaline
tothetopofyourCodetab:
extensions [profiler]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddprofilertothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
Example
setup ;; set up the model
profiler:start ;; start profiling
repeat 20 [ go ] ;; run something you want to measure
profiler:stop ;; stop profiling
print profiler:report ;; view the results
profiler:reset ;; clear the data
ThankstoRogerPeppeforhiscontributionstothecode.
Primitives
profiler:callsprofiler:exclusive-timeprofiler:inclusive-timeprofiler:start
profiler:stopprofiler:resetprofiler:report
profiler:calls
profiler:callsprocedure-name
Reportsthenumberoftimesthatprocedure-namewascalled.Ifprocedure-nameisnot
defined,thenreports0.
profiler:exclusive-time
profiler:exclusive-timeprocedure-name
Reportstheexclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.
Exclusivetimeisthetimefromwhentheprocedurewasentered,untilitfinishes,butdoes
notincludeanytimespentinotheruser-definedprocedureswhichitcalls.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:inclusive-time
profiler:inclusive-timeprocedure-name
Reportstheinclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.Inclusive
timeisthetimefromwhentheprocedurewasentered,untilitfinishes.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:start
profiler:start
Instructstheprofilertobeginrecordinguser-definedprocedurecalls.
profiler:stop
profiler:stop
Instructstheprofilertostoprecordinguser-definedprocedurecalls.
profiler:reset
profiler:reset
Instructstheprofilertoeraseallcollecteddata.
profiler:report
profiler:report
Reportsastringcontainingabreakdownofalluser-definedprocedurecalls.TheCalls
columncontainsthenumberoftimesauser-definedprocedurewascalled.TheIncl
T(ms)columnisthetotaltime,inmilliseconds,ittookforthecalltocomplete,includingthe
timespentinotheruser-definedprocedures.TheExcl T(ms)columnisthetotaltime,in
milliseconds,spentwithinthatuser-definedprocedure,notcountingotheruser-define
proceduresitcalled.TheExcl/callscolumnisanestimateofthetime,inmilliseconds,
spentinthatuser-definedprocedureforeachcall.
Hereisexampleoutput:
Sorted by Exclusive Time
Name Calls Incl T(ms) Excl T(ms) Excl/calls
CALLTHEM 13 26.066 19.476 1.498
CALLME 13 6.413 6.413 0.493
REPORTME 13 0.177 0.177 0.014
Sorted by Inclusive Time
Name Calls Incl T(ms) Excl T(ms) Excl/calls
CALLTHEM 13 26.066 19.476 1.498
CALLME 13 6.413 6.413 0.493
REPORTME 13 0.177 0.177 0.014
Sorted by Number of Calls
Name Calls Incl T(ms) Excl T(ms) Excl/calls
CALLTHEM 13 26.066 19.476 1.498
NetLogoRExtension
TheR-ExtensionofNetLogoprovidesprimitivestousethestatisticalsoftwareR(GnuS)(seetheRProjectwebsite)withina
NetLogomodel.ThereareprimitivestocreateR-VariableswithvaluesfromNetLogovariablesoragentsandothersto
evaluatecommandsinRwithandwithoutreturnvalues.
Using
Tousetheextensioninyourmodel,addalinetothetopofyourprocedurestab:
extensions [ r ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddrtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide.
ForexamplesoftheusageoftheR-Extension,modelscanbedownloadedfromtheprojectrepository.Thesemodelsare
installedwithNetLogointhe“models”directoryoftheRextension.Pleasenotethat(asofNetLogo6.0)thesemodelsare
notincludedintheNetLogomodelslibrary.
SomeTips
Plotting
IfyouwanttousetheplotfunctionofR,youcouldactivatetheJavaGDplotdeviceviar:setPlotDevice,seethe“plot-
example1.nlogo”model.Thisisthepreferedmethod!
ButyoucanalsousethestandardRdevice,butthen,youhavetogiveRsomecputime,e.g.byrunanevalulationof
sys.sleep(0.01)withaforeverbutton.Seethe“plot-example2.nlogo”.(ManythankstoThomasPetzold!).Thecreationof
plotsintofilesisalsopossible.Seethe“plot-into-file-example.nlogo”intheexamplesfolder.
LoadandSavedatafrom/intofile(s)
It’spossibletoloadandsavedatafromfiledirectlyinR.Thiscodesnippetillustrates:
r:eval "dataname <- read.table('<path to file>')" ; read file
r:eval "write.table(dataname, file='<filename>')" ; write file
Data.framewithvectorincells
Normally,adata.framecellcontainsonlyasinglevalue.Eachcolumnisrepresentedasavectorandifyouwouldputa
vectorofvectorstoadata.frame,itwouldbesplittedintoseveralcolumns.WiththeR-Extensionitispossibletoputavector
intoadata.framecell,whenyouassignaNetLogoListtoacolumnwhichcontainsnestedNetLogoListsforeachrow.Ifyou
want,forexample,tousewrite.tableonthisdata.frame,youhavetomarkthiscolumnasclass="AsIs".Youcandothisby
usingtheI(x)-function.
Example:Ifthecolumnofinteresthasthename“col1”ofthedata.frame“df1”youcouldexecuter:eval "df1$col1 <-
I(df1$col1)".Callhelp(I)fromwithinanRterminalforfurtherdetails.
LoadanR-Script
Furthermore,youcandefinefunctionsinanR-Script,loadit,andusethefunctions.LoadR-filesviar:eval "source('<path
to r-file>')".
LoadaPackage
It’salsopossibletoloadRpackagesviar:eval "library(<name of package>)".
Whenyoucompileyourcodecontainingextensions [r]youwillcreateanewRworkspace.Untilyoureloadtheextension,
openanewmodelorsubmittheprimitive[r:clear](#rclear),allRvariablesassignedinthissessionwillbeavailablelike
youwoulduseRfromthecommandlineorintheRConsole.
InteractiveShell
YoucanopenanInteractiveRShellviar:interactiveShell.ThisshellisaporttotheunderlayingRinstance.Thisshell
worksontheglobalenvironment(seeEnvironmentsintheRExtensionbelow)whiletheextensionitselfworkonacustom
localenvironment.Butthereisoneautomaticvariable“nl.env”intheglobalenvironment,whichisareferencetothelocal
environmentoftheextension.Don’tdeletethisvariable!
Youcanaccessavariablecreatedbytheextensionviaget("<variable name>",nl.env),forexamplemyvar <-
get("myvar",nl.env).IfyouwanttoplotfromtheInteractiveShellyoushouldusetheincludedJavaGDplotdevice(see
r:setPlotDevice).YoucansaveandloadthehistoryofenteredRcommandsviaaright-mousebuttoncontextmenu.
Pleasereadthenotesatthetopoftheoutputtextareaafteropeningtheshell!OnLinuxOSitcanhappenthatyouseean
errormessagefromX11.Pleasecheck,ifeverythingworkedcorrecly.Ifso,youcanignorethesemessages.Ifnot,please
writeareporttobugs@ccl.northwestern.eduoropenanissue.
EnvironmentsIntheRExtension
WhenyouloadamodeltheR-ExtensioncreatesanewRenvironment.WhenyoucreateanRvariableusingtheR-
Extension,thisvariableiscreatedinthelocalRenvironment.Furthermore,allcallsfromtheR-Extensionworkonthislocal
environment.ThisnewenvironmentconceptenablesyoutousetheextensioninBehaviorSpaceExperiments.Therefore,
youdon’thavetocareabouttheenvironmentwhileyou’renotusingtheInteractiveShellorothertools,whichworkonthe
globalenvironment.Youcanexplicitlyassignavariabletotheglobalenvironmentbyusingthe<-operatororbyexecuting
assign(<name>,<value>,envir=.GlobalEnv).IfyouworkwiththeInteractiveShell,seethenotesatthetopoftheoutputtext
areaafteropeningtheshell.
Typehelp(environment)inanRshelltolearnmoreaboutenvironments.
Youcan/shouldclear(i.e.removeallvariableandfreememory)thelocalenvironmentviar:clearLocal.Ifyouwanttoclear
alsotheglobalenvironment(thewholeworkspace),callr:clear.
Memory
WiththeR-ExtensionyoucanloadRintotheprocessofNetLogo.BecauseofthearchitectureofR,bothsoftwareshareone
systemprocessandthereforethememorygiventoNetLogo.
InsomecircumstancesitcanhappenthatyoureceiveanoutofmemoryerrorduetoJava’sheapspace.Youcanincrease
theheapspacebeforestartingNetLogobyadaptingthe-XmxJVM-parameter(seealsotheNetLogomanualsectionon
Windowsmemory).Buton32-bitsystems,thisisverylimited.Therefore,itisagoodideatousea64-bitsystemifyou
want/needtousehighamountofRAM.YoucanseethememoryusageofRbystartingtheinteractiveshell
(r:interactiveShell)andtypethere:memory.size(max=F)andmemory.size(max=T).Furthermore,youcancheckthememory
limitbytyping:memory.limit().
Seealso:
Rmanualpageformemory.profile
Rmanualpageforobject.size
Rmanualpageformemory.size
Ifyoucallthegarbagecollectorintheinteractiveshellbytypinggc(),youwillgetsomeinformationaboutthecurrent
memoryusage(seealsohttp://stat.ethz.ch/R-manual/R-patched/library/base/html/gc.html).
Ifyoutypegc(nl.env)youwillseethepercentageofmemoryusedforconscellsandvectors.
Don’tforgettocallther:gcprimitiveafterremovinganRvariableanddon’tforgettoremoveRvariableyoudon’tneed
anymore!Seehowthememoryusagechangesafterremovingvariableandcallingr:gc.
Ifyouusetoomuchmemory,itcanhappen,thatNetLogowillcloseabruptly.Insuchacase,checkifthereisawayto
reducethememoryused.Ifnot,trytoswitchovertotheRserve-extension.WiththeRserve-Extensionbothsoftware,
NetLogoandR,runindependently.Thereis,ofcause,alsoalimitoftransferabledataamountwithonerequest,butitisless
restrictive.
Onelastnotetothistopic:KeepinmindthatRisavector-orientedlanguage.Preventmasscallswithsinglevalues
wheneverpossibleandreplacethembyvectoroperations.Thisismuchfasterandmorestable.
Headless
SinceR-Extensionversion1.1itispossibleusetheextensionwhenNetLogoisrunninginheadlessmode.Thisisfor
examplethecase,whenyourunBehaviorSpaceexperimentsfromthecommandline(seehere).Thedifferenceis,thatthe
interactiveShellisnotinitialized/instanciated.YoucanusetheextensionasyouknowitfromGUImode,butitisnot
possibletoopentheinteractiveShell(r:interactiveShell)andtosettheplotdevice(r:setPlotDevice).Butoneadditional
thingshastobedone:Youhavetocallr:stopfinallywhenrunningNetLogoheadlesstostoptheRengine.Otherwise
NetLogowillnotbeclosedandyouwillnotgetbacktothecommandlineprompt.WhensettingupaBehaviorSpace
experiment,thereistheoptiontosetfinalcommands.Thisisagoodplacetoaddther:stopcommand(seeimage).
Installing
TheRExtensionisbundledwithNetLogo6.Touseit,youwillneedacompatibleRinstallationandyoumayneedto
configuretheextension.
InstallingR
StandardR3installationsshouldwork(sometimeswithoutconfiguration).AsofNetLogo6.0.2,thefollowingoperating
system/Rversionsweretested:
MacOSX,R3.3.3
Windows10,R3.3.2
Ubuntu14.04(64-bit),R3.0.2
OnceRisinstalled,youwillneedtoinstalltherJavapackage.CertainfeaturesoftheRextensionrelyontheJavaGD
package.
Toinstall,starttheRGuifromyourprogramlist,clickontheitem“Packages”inthemenubarandthenon“Install
Package(s)”.Selectyourfavoriteserverandfind“rJava”,aswellas“JavaGD”and/or“CommonJavaJars”(bothoptional)in
thelistofpackages.
Ifyoupreferusingtheconsole,youcaninstallthesamepackagesbyrunningthefollowingcommandsintheconsole(and
followingthepromptstheygenerate,asappropriate).
install.packages("rJava")
install.packages("JavaGD") # Optional
install.packages("CommonJavaJars") # Optional
ConfiguringtheRextension
IfyouareusingLinuxorMacOSandoneoftheaboveRversions,youmaynotneedtoperformanyfurtherconfiguration.
AneasywaytodeterminewhetheryouneedtoconfiguretheextensionittoopenanewNetLogomodel,addextensions [
r ]tothecodetabandpress“Check.”Ifyouseeanerror,youneedtoconfiguretheRextension.TheRextensioncanbe
configuredbyeditingthe“user.properties”fileinatexteditor(“user.properties”islocatedintherextensiondirectoryaspart
oftheNetLogoinstallation).Thefollowingkeysareusedtoconfiguretheextension:
r.home:Controlswhichinstallationofrisused.
jri.home.paths:ControlsthepathtothejrisubdirectoryoftherJavalibrary.
NotethatyouwillhavetoexitNetLogoandrestarttoseeconfigurationchangestakeeffect,astheconfigurationfileisonly
loadedonceperNetLogoinstance.Seebelowonhowtodeterminetheappropriatevaluestoforr.homeand
jri.home.paths.
Determiningr.homeandjri.home.paths
r.homeisthepathtothe“R”installationdirectorywhichcontainsthe“bin”directory.Ifyou’rehavingtroublefindingthis,you
canrunR.home(component = "home")inR,orR RHOMEonthecommandline(ifRisonyourpath).
R.home(component = "home")
# Returns "C:/PROGRA~1/R/R-33~1.2/bin/x64" on Windows.
# Will return other results on other platforms or configurations
jri.home.pathsisalistofdirectoriestocheckforjri.It’sinthejridirectoryundertherJavalibraryinstallation.Youcanfind
thejridirectoryintherJavapackagebyrunningthefollowinginR:
system.file("jri", package = "rJava")
# Returns "C:/Users/username/Documents/R/win-library/3.3/rJava/jri" on Windows.
# Will return other results on other platforms or configurations
Takethepathandedittheuser.propertiesfile,uncommentingandeditingonesetofr.homeandjri.home.pathstomatch
thevaluesobtainedinR.Whenyou’redone,theuser.propertiesfileshouldhavethefollowinglines(giventheabove
results):
r.home=C:/PROGRA~1/R/R-33~1.2/bin/x64
jri.home.paths=C:/Users/username/Documents/R/win-library/3.3/rJava/jri
Saveuser.propertiesandloadamodelusingtheRextension.Youshouldseeitstartandrunproperly.
Windows-SpecificInstallationSteps
WindowsrequirestheadditionalconfigurationstepofconfiguringthePATHenvironmentvariable.Additionally,editingthe
user.propertiesfileonWindowsisslightlymoredifficultthanonotherplatforms.
ConfiguringthePATH
Tobegin,determinetheappropriatedirectoryfromyourRinstallationtoaddtoyourPATH.Todothis,determinewhere
yourRinstallationislocated(herewe’llusethelocationC:\ProgramFiles\R\R-),thenfollowthesesteps.
1. OpentheSystemPropertiesdialog.Youcantype“EnvironmentVariable”intoCortanaornavigatetherethrough“Control
Panel”>System>“Advancedsystemsettings”.
2. Clickthe“Environmentvariables…”buttoninthelowerrightofthedialog.
3. Clickthe“Path”variableinthelowerpanel,thenclickthelower“Edit…”button.
4. Windows10allowsyoutochoose“New”andenteraseparatepath.Ifyou’reusingWindows7,appendthevalue,usinga
semicolontoseparateitfromtheentrybefore.
Ifyou’reusing32-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\i386\
Ifyou’reusing64-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\x64\
1. ChooseOK,andOKagain
2. LogoutofyouruserandbackinorrestartWindowstoletthesettingtakeaffect.
NotethatyouwillneedtoupdatethissettingifyouwishtoupgradetheversionofRusedbyNetLogo.
Notesonediting“user.properties”onWindows
“user.properties”isanewline-delimitedfile.Thismeansifitisopenedin“Notepad”itwilllooklikeallthetextisonasingle
line.Forthisreason,itisrecommendedtoopenfirstin“WordPad”andresavebeforeeditinginNotepad.Alternatively,ifyou
haveafull-featuredtexteditor(likeNotepad++,Vim,orEmacs)installed,youcanusethattoeditthefile.
Toreiterateawarninggiveninthe“user.properties”file,thedirectoryseparatorforWindowsmustbeenteredin
user.propertiesasdouble-backslash(“\”)orsingle-forward-slash(“/”).
Primitives
r:clearr:clearLocalr:evalr:__evaldirectr:gcr:getr:interactiveShellr:putr:putagentr:putagentdfr:putdataframe
r:putlistr:putnamedlistr:setPlotDevicer:stop
r:clear
r:clear
ClearstheR-Workspace.AllvariablesinRwillbedeleted.ItevaluatestheRcommandrm(list=ls())and
rm(list=ls(nl.env)).Thisdeletesvariablescreatedinglobalaswellaslocalenvironment(seeREnvironmentsfordetails
aboutenvironments).It’salwaysagoodideatoaddthiscommandtoyoursetupprocedureunderyour“clear-all”call.
;; clear the R workspace
r:clear
r:clearLocal
r:clearLocal
ItclearsthelocalRenvironment,whichisusedbytheextension.Allvariableswhichhavebeencreatedinthelocal
environmentwillbedeleted.ItevaluatestheRcommandrm(list=ls(nl.env)).SeeREnvironmentsfordetailsabout
environments.Seer:clearfordeletingallvariables,i.e.theglobalsaswell.
;; delete the local variables
r:clearLocal
r:eval
r:evalR-command
ItevaluatesthesubmittedRcommand.TheRcommandshouldn’treturnavalue.
;; creates a new vector in R with a sequence from 1 to 10
r:eval "x <- seq(1,10)"
show r:get "x"
r:__evaldirect
r:__evaldirectR-command
EvaluatesthesubmittedRcommandintheglobalenvironment(notinthelocalenvironmentliker:evaldoes)andwithouta
check(notusingtry-functioninternally).ThiscanbenecessaryforsomeRpackages,likegglopt2.Pleasenote,thatyoucan
producenameclasheswhencreatingnewvariablesusingthisprimitive.Thevariablewillbecreatedintotheglobal
environmentandwillnotoverwritevariablewiththesamenamethathavebeencreatedintothelocalenvironment.Ifyou
requestavariablewithr:getitwillsearchinthelocalenvironmentfirst.Therefore,iftherearevariableswiththesamename
inthelocalandtheglobalenvironment,itwillreportthevariablefromthelocalenvironmentandnotthevariablecreatedvia
r:__evaldirect.Ifthereisonlyavariablewiththerequestednameintheglobalenvironment,everythingwillbefine-r:get
willreportthevalueofthisvariable.Ifyouwanttoremoveavariablecreatedviar:__evaldirect,i.e.intheglobal
environment,callr:eval "rm(myvar, envir=.GlobalEnv)",replacemyvarbythenameofyourvariable.TheRcommand
shouldn’treturnavalue.Thisprimitiveisexperimental.
;; creates a new vector in R with a sequence from 1 to 10
r:__evaldirect "x <- seq(1,10)"
show r:get "x"
r:gc
r:gc
CallsthegarbagecollectorofJava(i.e.theR-Extension)andR.CallthisprimitiveafterremovinganRvariabletofreethe
memory.
;; create a variable
r:eval "x <- 1:10"
;; remove the variable
r:eval "rm(x)"
;; call the garbage collector
r:gc
r:get
r:getR-command
ReportsthereturnvalueofthesubmittedRcommand.ReturntypecouldbeaString,Number,Boolean,NetLogoListora
NetLogoListofLists.
RlistswillbeconvertedintoaNetLogoList.IftheRlistitselfcontainsfurtherlists,itwillbeconvertedintoaNetLogoList
withnestedNetLogolists.Listscontainingvaluesofdifferentdatatypesarealsosupported(e.g.mixedStrings,Numbers
andBooleans/Logicals).
Data.frameswillbeconvertedintoaNetLogoListwithnestedListforeachcolumn,butthecolumnnameswillbelost(same
fornamedRlists).
Rmatricescanbereceived,buttheyareconvertedintooneNetLogolist.NULLandNAvaluesarenotconvertedandwill
throwanerror,becauseNetLogohasnocorrespondingvalue.
;; returns a list with 10 variables
show r:get "rnorm(10)"
r:interactiveShell
r:interactiveShell
Opensawindowwithtwotextareas.TheupperoneistheRoutputstreamandintheloweroneyoucantypeRcommands.
ThisistheaccesstotheunderlayingRsession.Youcantypemulti-linecommands.TosubmitcommandspressCtrl+Enter.
With“PageUp”and“PageDown”intheinputareayoucanbrowsethroughthehistroyofsubmittedcommands.Withright-
mouseclickcontextmenu,youcansaveandloadanRHistory(interchangeablewithRterminalandotherRGUIs).
Pleasenote,thattheInteractiveShellworksontheglobalenvironment,whilecommandssubmittedfromNetLogolivesinan
localenvironment.Areferencetothislocalenvironmentisautomaticallyaddedtotheglobalenvironment(namednl.env,
pleasedonotdeletethisvariable.Withacallofr:clearyoucanrestoreitbutthiswillemptyyourworkspace).Youcanuse
thistohaveaccesstovariableswhichyouhavecreatedfromNetLogobyget("<variable name>",nl.env).Tocopyfor
exampleanvariablewiththenamevar1fromthelocalenvironmenttotheglobalenvironment,typevar <-
get("var",nl.env).SeesectionREnvironmentsfordetails.Ifyoujustwanttoseethecontentsofavariablewhichlivesin
thelocalenvironment,youcouldsubmityourcommand,forexampleintheNetLogoCommandCenter,andtheresultwillbe
shownintheoutputareaoftheInteractiveShell.Forexample:
r:put "test" (list world-width world-height)
r:interactiveShell
r:eval "print(test)"
r:eval "str(test)"
VariableswhichhavebeencreatedintheInteractiveShellareavailablefromNetLogo,eveniftheyarecreatedintheglobal
environment.Butifthereisavariablewiththesamenameinthelocalenvironment,youwillgetthisvariableinNetLogo
insteadtheonefromtheglobalenvironment.
IfyouwanttoexecuteplotcommandsfromtheInteractiveShellyoushouldactivatetheintegratedJavaGDplotdevicevia
r:setPlotDevicefirst.
;; opens Interactive Shell
r:interactiveShell
r:put
r:putnamevalue
CreatesanewvariableinRwiththenamename.ThevaluecanbeaString,Number,BooleanorList.
NetLogoListsareconvertedtoRvectors,ifallentriesareofthesamedatatype.IfaNetLogolistcontainsdifferentdata
types(mixedStrings,NumbersofBooleans),itwillbeconvertedintoanRlist.IfaNetLogoListcontainsother/nested
NetLogoListsitwillbeconvertedintoanRlistandthenestedListsarehandledbythesamerule(Vectorsifallitemsareof
thesamedatatype,…).
;; creates an R variable "testvar" with the size of turtle 0
r:put "testvar" [size] of turtle 0
show r:get "testvar"
r:putagent
r:putagentnameagentvariables
r:putagentnameagentsetvariables
CreatesanewnamedlistinRwiththenamename.Theargumentvariablesisanynumberofstringswhichlistand
variable(s)oftheagent|agentset.NamesoftheelementsoftheRlistwillbethesameasthenamesoftheagentvariables.
Turtleswillbeassignedinascendingorderoftheirwho-variable.Patcheswillbeassignedinlinesfromupperlefttolower
right.Sincetheargumentsofthisprimitivearerepeatable,don’tforgettheparenthesesaroundthestatement.
;; creates an R-list "agentlist1" with the size and the id of turtles, don't forget the parentheses
(r:putagent "agentlist1" turtles "size" "who")
show r:get "agentlist1$who"
;; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches
(r:putagent "agentlist2" patches "pcolor" "pxcor" "pycor")
show r:get "agentlist2$pcolor"
r:putagentdf
r:putagentdfnameagentvariables
r:putagentdfnameagentsetvariables
Sameasr:putagentbutcreatesanRdata.frameinsteadalist.Pleasereadthenotesaboutdata.framesifoneofyour
agentvariablescontainsNetLogoLists.
;; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches, don't forget the parentheses
(r:putagentdf "df1" patches "pcolor" "pxcor" "pycor")
show r:get "class(df1)"
r:putdataframe
r:putdataframenamevarnamevalue
r:putdataframenamevarnamevaluevarname2value2...
Sameasr:putnamedlistbutcreatesanRdata.frameinsteadofalist.IfyousendmorethanonelisttoNetLogoandthe
listsareofdifferentlength,thesmalleroneswillbefilledwithNAvalues.
IfyousendnestedLogoLists(e.g.oftype:[[][]…])toonecolumnpleasereadthenotesaboutdataframeswithvectorsin
cells.
;; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches, don't forget the parentheses
(r:putdataframe "df1" "v1" [12 13 14 15 16] "v2" ["foo1" "foo2" "foo3" "foo4" "foo5"] "v3" [1.1 2.2 3.3 4.4 5.5])
show r:get "df1$v3"
r:putlist
r:putlistnamevalue
CreatesanewlistinRwiththenamename.VariableisrepeatableandcanbeaNumber,BooleanorList.Each“Variable”
willgetthenameofitsposition(1,2,3,…).Sincetheargumentsofthisprimitivearerepeatable,don’tforgetthe
parenthesesaroundthestatement.
;; creates an R-list "list1", don't forget the parentheses
(r:putlist "list1" 25.5 [25 43 32 53] "testvalue" [44.3 32.32 321.2 4.2])
show r:get "class(list1)"
show r:get "list1[[1]]"
show r:get "list1$'0'"
show r:get "list1[[2]]"
r:putnamedlist
r:putnamedlistnamevarnamevalue
r:putnamedlistnamevarnamevaluevarname2value2...
CreatesanewnamedlistinRwiththenamename.Variablenamesandvaluesfollowinalternatingsequenceandmaybe
repeatedasmanytimesasdesired.ValuescanbeaNumber,BooleanorList.Eachvaluewillgetthenamevarname.Since
theargumentsofthisprimitivearerepeatable,don’tforgettoputthestatementintoparentheses.
;; creates an R-list "list1" , don't forget the parentheses
(r:putnamedlist "list1" "v1" 25.5 "v2" [25 43 32 53] "v3" "testvalue" "v4" [44.3 32.32 321.2 4.2])
show r:get "class(list1)"
show r:get "list1[[1]]"
show r:get "list1$v1"
r:setPlotDevice
r:setPlotDevice
ToopenanRplotinawindowyoucanusetheJavaGDplotdevice.Withthisprimitiveyoucanactivatethisdeviceandall
followingcallsofRplotswillbeprintedwiththisdevice.
Tousethisdevice,youhavetoinstalltheJavaGDpackageinR.OpenanRterminalortheInteractiveShell(see
r:interactiveShell)andtypeinstall.packages("JavaGD").
Withthisplotwindowyoucansavetheplottoanfileofdifferentgraphictypeandyoucancopytheplottotheclipboard.
Pleasenote,thatonLinuxOSitcanbenecessarytoallowtoaddimagestotheclipboard(e.g.inKDEyouhavetoconfigure
KLIPPERtoallowimages).Theresolutionforrasterimagesdependsonthesizeoftheplotwindow.Ifyouneedhigh
resolutionmaximazethewindow(anddon’tusejpeg,becausethedriverisbad)orbetteruseavectorimageformat.
Pleaseseethenotesaboutplottingforotherdetails.
;; activate the JavaGD plot device
r:setPlotDevice
r:stop
r:stop
StopstheRengine.Thisisneeded(only)ifNetLogoisrunninginheadlessmode,forexamplewhenrunning
BehaviorSpaceexperimentsfromthecommandlinewithsomethinglikethis:
java -cp NetLogo.jar org.nlogo.headless.Main --model mymodel.nlogo --experiment exp1 --table outtab1.csv
Shouldbethelastcallinheadlesssimulation.Seeusagenotesabovefordetails.
r:stop
Troubleshooting
Belowaresomecommonproblemsandsomeideasonhowtoremedythem.Pleasekeepinmindthatweplantocontinue
toimprovetheRextensionfollowingthereleaseofNetLogo6.Wewelcomefeedbackonhowtoimprovetheextensionas
wellasbugreportspointingustoanynewproblemsyouencounter.
LoadingRpackagesfails
See,forexample,thispost.
AfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextension
ChangingworkingdirectoryinRdoesn’tworkbecauseitchangesalsoJava’slibrarypaththatNetLogoneedstofindits
extensions.PleaseuseabsolutepathtoanyfilesinRinsteadofchangingtheworkingdirectory.
Specificerrorcodelist
Error#01.InvalidRHome.RhomeisspecifiedviatheR_HOMEenvironmentvariableorapropertiesfile,butcouldn’tbe
foundatthespecifiedpath.SeeaboveforhowtospecifyRhome.
Error#02:CannotfindrJava/JRI.TheRExtensionwasunabletolocateyourinstallationofrJava.Somestepstoresolve:
EnsurethatrJava(0.9-8orlater)isinstalledinR.Ensurethatit’sinstalledeithersystem-wideorforyouasauser
EnsurethatyourconfigurationpointstotheproperrJavalocation.Ifyouhaveauser.propertiesfile,ensurethat
jri.home.pathsincludesthepathgivenbyRwhenyourunsystem.file("jri",package="rJava")
Error#03:CannotloadrJavalibraries.ThismayindicateacorruptedrJavainstallation.TryreinstallingrJava.
Error#04:ErrorinR-Extension.Thisisanunknowninitializationerror.EnsurethatyouarerunningR3.0.0orlaterand
havetherJavaextensioninstalled(version0.9-8orlater).Pleasereportthiserrortobugs@ccl.northwestern.eduoropen
anewissueontheR-Extensionissuetracker.
Error#05:TherewasanerrorsettingR_HOME.Checkyouruser.propertiesfiletoensurethatr.homespecifiesavalidpath
totheRextension.YoumayalsobeabletoworkaroundthiserrorbysettingtheR_HOMEenvironmentvariable.Ifthiserror
persists,pleasereportit!
Error#06:CannotloadRlibraries.ThismayindicateacorruptedorimproperlyconfiguredRinstallation.Ifyou’recertain
thatyourRinstallationisfine,pleasereportthisasanissue.
Citation
Thiele,JC;Grimm,V(2010).NetLogomeetsR:Linkingagent-basedmodelswithatoolboxfortheiranalysis.Environmental
ModellingandSoftware,Volume25,Issue8:972-974[DOI:10.1016/j.envsoft.2010.02.008]
CopyrightandLicense
TheRextensionisCopyright(C)2009-2016JanC.ThieleandCopyright(C)2016UriWilensky/TheCenterforConnected
Learning.
NetLogo-R-Extensionisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNUGeneralPublic
LicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimplied
warrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwithNetLogo-R-Extension(locatedinGPL.txt).
Ifnot,seehttp://www.gnu.org/licenses/.
NetLogoRndExtension
ThisextensionaddstheabilitytodoroulettewheelselectioninNetLogo.Itprovidesasimpler
waytoaccomplishthesamethingastheLotteryExamplefromtheNetLogoModelsLibrary.
Usage
Whichprimitivetousedependsonwhetheryouwanttoselectanitemfromalistorfroman
agenset.Italsodependsonwhetheryouwantoneormanyitemsand,ifyouwantmany,if
repeatsareallowedornot.Thefollowingtablesummarizesthesituation:
FromanAgentSet FromaList
Oneitem rnd:weighted-one-of rnd:weighted-one-of-list
Manyitems,without
repeats rnd:weighted-n-of rnd:weighted-n-of-list
Manyitems,withrepeats rnd:weighted-n-of-with-
repeats
rnd:weighted-n-of-list-with-
repeats
(Note:theinitialversionoftheextensionhadasinglesetofprimitivesforbothlistsand
agentsets,butitturnedouttobeconfusing,sowechangedit.Ifyouwereusingtheold
versionoftheextension,youwillneedtomodifyyourcodetousethenewprimitives.)
Inallcases,youwillneedtoprovidetwothingstotheprimitive:
The“candidates”:theitemsthattheprimitivewillselectfrom.
The“weight”:howlikelyitisforeachcandidatetobeselected.
Ifyouwanttoselectmorethanoneitems,youwillalsoneedtotellit:
Howmanyitemstoselect.
Anoteaboutperformance
TheextensionusesKeithSchwarz’simplementationofVose’sAliasMethod(seeSchwarz’s
Darts,Dice,andCoinspage).Assumingyouarechoosingncandidatesforacollectionofsize
mwithrepeats,thismethodhasaninitializationcostofO(m)followedbyacostofO(1)for
eachitemyoupick,soO(m+n)overall.
Forexample,inthefollowingcode:
let candidates n-values 500 [ [n] -> n ]
rnd:weighted-n-of-list-with-repeats 100 candidates [ [w] -> w ]
n-values 100 [ rnd:weighted-one-of-list candidates [ [w] -> w ] ]
…thelineusingrnd:weighted-n-of-list-with-repeatswilllikelyrun100timesfasterthanthe
lineusingacombinationofn-valuesandrnd:weighted-one-of-list.Thisisbecause
rnd:weighted-n-of-list-with-repeatsonlyinitializesthealgorithmonceandrnd:weighted-
one-ofdoesiteachtimeitiscalled.
(Notethatcomposingn-valueswithrnd:weighted-one-of-listdoesnotpreservetheorderof
theoriginalcandidatelist,whilernd:weighted-n-of-list-with-repeatsdoes.)
Thingsareabitmorecomplicatedifyouarechoosingwithoutrepeats,however.Inthiscase,
thealgorithmmayhavetodiscardsomepicksbecausethecandidateshavealreadybeen
selected.Whenthisstartshappeningtoooften(maybebecausesomeweightsaremuch
biggerthanothers),theextensionre-initializesthealgorithmwiththealready-picked
candidatesexcluded.Thisshouldnothappentoooften,however,sowhilepickingwithout
repeatshasanupperboundofO(m*n)intheory,itshouldusuallynotbemuchmorethan
O(m+n)inpractice.
Thepreviousremarksapplytoagentsetprimitivesasmuchastheyapplytolistprimitives.
Primitives
AgentSetPrimitives
rnd:weighted-one-ofrnd:weighted-n-ofrnd:weighted-n-of-with-repeats
ListPrimitives
rnd:weighted-one-of-listrnd:weighted-n-of-listrnd:weighted-n-of-list-with-repeats
rnd:weighted-one-of
rnd:weighted-one-ofagentsetreporter
Reportsarandomagentfromagentset.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustnotbenegative.
Iftheagentsetisempty,itreportsnobody.
HereisafullrewriteoftheLotteryExamplemodelusingthernd:weighted-one-ofprimitive:
extensions [ rnd ]
to setup
clear-all
; create a turtle on every fifth patch
ask patches with [ pxcor mod 5 = 0 and pycor mod 5 = 0 ] [
sprout 1 [
set size 2 + random 6 ; vary the size of the turtles
set label 0 ; start them out with no wins
set color color - 2 ; make turtles darker so the labels stand out
]
]
reset-ticks
end
to go
ask rnd:weighted-one-of turtles [ size ] [
set label label + 1
]
tick
end
rnd:weighted-n-of
rnd:weighted-n-ofsizeagentset[reporter]
Reportsanagentsetofthegivensizerandomlychosenfromtheagentset,withnorepeats.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustbenon-negativenumbers.
Itisanerrorforsizetobegreaterthanthesizeoftheagentset.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
rnd:weighted-n-of-with-repeats
rnd:weighted-n-of-with-repeatssizeagentset[reporter]
Reportsalistofthegivensizerandomlychosenfromtheagentset,withrepeats.(Whyalist
insteadofanagentset?Becauseanagentsetcannotcontainthesameagentmorethan
once.)
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustbenon-negativenumbers.
Itisnotanerrorforsizetobegreaterthanthesizeoftheagentset,buttherehastobeat
leastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
rnd:weighted-one-of-list
rnd:weighted-one-of-listlistanonymous-reporter
Reportsarandomitemfromlist.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisanerrorforthelisttobeempty.
Acommonwaytousetheprimitiveistohavealistoflists,wherethefirstitemofeachsublist
isthethingyouwanttochooseandtheseconditemistheweight.Hereisashortexample:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]
repeat 25 [
; report the first item of the pair selected using
; the second item (i.e., `last p`) as the weight
type first rnd:weighted-one-of-list pairs [ [p] -> last p ]
]
ThisshouldprintBroughlyfourtimesmoreoftenthanitprintsA.
Ifyouhappentohaveyouritemsandyourweightsintwoseparatelists,youcancombine
themintopairsbyusingacombinationofmapandlist:
let items [ "A" "B" "C" ]
let weights [ 0.1 0.2 0.7 ]
let pairs (map list items weights)
Sinceweapplymaptoboththeitemslistandtheweightslist,theparenthesesareneededin
(map list items weights).Wealsousetheconciseanonymousproceduresyntax(seethe
programmingguide)topasslistasthereporterformap.Thesamethingcouldhavebeen
written(map [ [a b] -> list a b ] items weights) .
rnd:weighted-n-of-list
rnd:weighted-n-of-listsizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withnorepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisanerrorforsizetobegreaterthanthesizeofthelist of candidates.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistof
candidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
Example:
let candidates n-values 8 [ [n] -> 2 ^ (n + 1) ] ; make a list with the powers of two
print rnd:weighted-n-of-list 4 candidates [ [w] -> w ]
Thisshouldprintalistoffournumbers,wherethebiggernumbers(32,64,128,256)havea
muchbetterchancetoshowupthanthesmallerones(2,4,8,16).
rnd:weighted-n-of-list-with-repeats
rnd:weighted-n-of-list-with-repeatssizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withrepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisnotanerrorforsizetobegreaterthanthesizeofthelistofcandidates,buttherehasto
beatleastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistof
candidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
Example:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]
print map first rnd:weighted-n-of-list-with-repeats 25 pairs [ [p] -> last p ]
Thisshouldprintalistof25AsandBs,withroughlyfourtimesasmanyBsthanAs.
NetLogoSoundExtension
Using
TheSoundExtensionletsNetLogomodelsmaketwokindsofsounds:MIDIsoundsand
playbackofpre-recordedsoundfiles.
TheJavaAPIsusedarejavax.sound.midiandjava.applet.AudioClip.
HowtoUse
Thesoundextensioncomespreinstalled.Tousetheextensioninyourmodel,addthisat
thetopofyourCodetab:
extensions [sound]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddsoundtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
Forexamplesthatusethesoundextension,seetheSoundsectionunderCodeExamples
intheNetLogoModelsLibrary.
MIDIsupport
TheMIDIpartoftheextensionsimulatesa128-keyelectronickeyboardwith47drumsand
128melodicinstruments,asprovidedbyGeneralMIDILevel1specification.
Itsupports15polyphonicinstrumentchannelsandasinglepercussionchannel.Using
morethan15differentmelodicinstrumentssimultaneouslyinamodelwillcausesome
soundstobelostorcutoff.
Thepitchofamelodicinstrumentisspecifiedbyakeynumber.Thekeysonthekeyboard
arenumberedconsecutivelyfrom0to127,where0istheleft-mostkey.MiddleCiskey
number60.
Theloudnessofaninstrumentisspecifiedbyavelocity,whichrepresentstheforcewith
whichthekeyboardkeyisdepressed.Velocityrangesfrom0to127,where64isthe
standardvelocity.Ahighervelocityresultsinaloudersound.
Primitives
sound:drumssound:instrumentssound:play-drumsound:play-notesound:play-note-later
sound:drums
sound:drums
Reportsalistofthenamesofthe47drumsforusewithsound:play-drum.
sound:instruments
sound:instruments
Reportsalistofthenamesofthe128instrumentsforusewithsound:play-note,
sound:play-note-later,sound:start-noteandsound:stop-note.
sound:play-drum
sound:play-drumdrumvelocity
Playsadrum.
Example:
sound:play-drum "ACOUSTIC SNARE" 64
sound:play-note
sound:play-noteinstrumentkeynumbervelocityduration
Playsanoteforaspecifiedduration,inseconds.Theagentdoesnotwaitforthenoteto
finishbeforecontinuingtonextcommand.
;; play a trumpet at middle C for two seconds
sound:play-note "TRUMPET" 60 64 2
sound:play-note-later
sound:play-note-laterdelayinstrumentkeynumbervelocityduration
Waitsforthespecifieddelaybeforeplayingthenoteforaspecifiedduration,inseconds.
Theagentdoesnotwaitforthenotetofinishbeforecontinuingtonextcommand.
Example:
;; in one second, play a trumpet at middle C for two seconds
sound:play-note-later 1 "TRUMPET" 60 64 2
DrumNames
35. Acoustic Bass Drum 59. Ride Cymbal 2
36. Bass Drum 1 60. Hi Bongo
37. Side Stick 61. Low Bongo
38. Acoustic Snare 62. Mute Hi Conga
39. Hand Clap 63. Open Hi Conga
40. Electric Snare 64. Low Conga
41. Low Floor Tom 65. Hi Timbale
42. Closed Hi Hat 66. Low Timbale
43. Hi Floor Tom 67. Hi Agogo
44. Pedal Hi Hat 68. Low Agogo
45. Low Tom 69. Cabasa
47. Open Hi Hat 70. Maracas
47. Low Mid Tom 71. Short Whistle
48. Hi Mid Tom 72. Long Whistle
49. Crash Cymbal 1 73. Short Guiro
50. Hi Tom 74. Long Guiro
51. Ride Cymbal 1 75. Claves
52. Chinese Cymbal 76. Hi Wood Block
53. Ride Bell 77. Low Wood Block
54. Tambourine 78. Mute Cuica
55. Splash Cymbal 79. Open Cuica
56. Cowbell 80. Mute Triangle
57. Crash Cymbal 2 81. Open Triangle
58. Vibraslap
InstrumentNames
*Piano* *Reed*
1. Acoustic Grand Piano 65. Soprano Sax
2. Bright Acoustic Piano 66. Alto Sax
3. Electric Grand Piano 67. Tenor Sax
4. Honky-tonk Piano 68. Baritone Sax
5. Electric Piano 1 69. Oboe
6. Electric Piano 2 70. English Horn
7. Harpsichord 71. Bassoon
8. Clavi 72. Clarinet
*Chromatic Percussion* *Pipe*
9. Celesta 73. Piccolo
10. Glockenspiel 74. Flute
11. Music Box 75. Recorder
12. Vibraphone 76. Pan Flute
13. Marimba 77. Blown Bottle
14. Xylophone 78. Shakuhachi
15. Tubular Bells 79. Whistle
16. Dulcimer 80. Ocarina
*Organ* *Synth Lead*
17. Drawbar Organ 81. Square Wave
18. Percussive Organ 82. Sawtooth Wave
19. Rock Organ 83. Calliope
20. Church Organ 84. Chiff
21. Reed Organ 85. Charang
22. Accordion 86. Voice
23. Harmonica 87. Fifths
24. Tango Accordion 88. Bass and Lead
*Guitar* *Synth Pad*
25. Nylon String Guitar 89. New Age
26. Steel Acoustic Guitar 90. Warm
27. Jazz Electric Guitar 91. Polysynth
28. Clean Electric Guitar 92. Choir
29. Muted Electric Guitar 93. Bowed
30. Overdriven Guitar 94. Metal
31. Distortion Guitar 95. Halo
32. Guitar harmonics 96. Sweep
*Bass* *Synth Effects*
33. Acoustic Bass 97. Rain
34. Fingered Electric Bass 98. Soundtrack
35. Picked Electric Bass 99. Crystal
36. Fretless Bass 100. Atmosphere
37. Slap Bass 1 101. Brightness
38. Slap Bass 2 102. Goblins
39. Synth Bass 1 103. Echoes
40. Synth Bass 2 104. Sci-fi
*Strings* *Ethnic*
41. Violin 105. Sitar
42. Viola 106. Banjo
43. Cello 107. Shamisen
44. Contrabass 108. Koto
45. Tremolo Strings 109. Kalimba
47. Pizzicato Strings 110. Bag pipe
47. Orchestral Harp 111. Fiddle
48. Timpani 112. Shanai
*Ensemble* *Percussive*
49. String Ensemble 1 113. Tinkle Bell
50. String Ensemble 2 114. Agogo
51. Synth Strings 1 115. Steel Drums
52. Synth Strings 2 116. Woodblock
53. Choir Aahs 117. Taiko Drum
54. Voice Oohs 118. Melodic Tom
55. Synth Voice 119. Synth Drum
56. Orchestra Hit 120. Reverse Cymbal
*Brass* *Sound Effects*
57. Trumpet 121. Guitar Fret Noise
58. Trombone 122. Breath Noise
59. Tuba 123. Seashore
60. Muted Trumpet 124. Bird Tweet
61. French Horn 125. Telephone Ring
62. Brass Section 126. Helicopter
63. Synth Brass 1 127. Applause
64. Synth Brass 2 128. Gunshot
NetLogoTableExtension
Using
Thetableextensionispre-installedinNetLogo.
Tousethetableextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [table]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddtabletothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithantableinNetLogo,youcouldalsojustusealistfor.Butyoumaywanttoconsiderusingantableinsteadfor
speedreasons.Listsandtableshavedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrunfasterbyselectingthe
appropriatedatastructure.
Tablesareusefulwhenyouneedtodoassociatevalueswithothervalues.Forexample,youmightmakeatableofwordsandtheirdefinitions.
Thenyoucanlookupthedefinitionofanyword.Here,thewordsarethe"keys".Youcaneasilyretrievethevalueforanykeyinthetable,butnot
viceversa.
UnlikeNetLogo’slistsandstrings,tablesare“mutable”.Thatmeansthatyoucanactuallymodifythemdirectly,ratherthanconstructinganaltered
copyaswithlists.Ifthetableisusedinmorethanoneplaceinyourcode,anychangesyoumakewillshowupeverywhere.It’strickytowritecode
involvingmutablestructuresandit’seasytomakesubtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunlessyou’re
certainyouwantandneedmutability.
Example
let dict table:make
table:put dict "turtle" "cute"
table:put dict "bunny" "cutest"
print dict
=> {{table: "turtle" -> "cute", "bunny" -> "cutest" }}
print table:length dict
=> 2
print table:get dict "turtle"
=> "cute"
print table:get dict "leopard"
=> (error)
print table:keys dict
=> ["turtle" "bunny"]
ManipulatingTables
Ifthesamekeyisusedwithtable:putmorethanonceforthesametable,thevalueprovidedtolastcalloftable:putwillbethevalueshownwhen
table:getisused.Hereisanexample:
let dict table:make
table:put dict "a" 5
table:put dict "a" 3
print table:get dict "a"
=> 3
Becausetablesaremutable,manipulatingexistingvaluesshouldbedonebycallingtable:getortable:get-or-defaultonakey,transformingthe
returnedvalue,andthencallingtable:puttoupdatethetransformedvalueinthetable.Hereisanexampleprocedurewhichincrementsavaluein
atableatagivenkey.Ifthekeydoesn’texist,itputsa1atthatkeyinstead.
to increment-table-value [ dict key ]
let i table:get-or-default dict key 0
table:put dict key i + 1
end
KeyRestrictions
TablekeysarelimitedtothefollowingNetLogotypes:
Numbers
Strings
Booleans
Listscontainingonlyelementswhicharethemselvesvalidkeys
Ifyouattempttouseanillegalvalue,thetableextensionwillraiseanexception,asshowninthefollowingexample.
crt 1
let dict table:make
table:put dict (one-of turtles) 10
;; Errors with the following message:
;; (turtle 0) is not a valid table key (a table key may only be a number, a string, true or false, or a list whose items are valid keys)
Primitives
table:cleartable:countstable:group-agentstable:group-itemstable:from-listtable:gettable:get-or-defaulttable:has-key?table:keys
table:lengthtable:maketable:puttable:removetable:to-listtable:values
table:clear
table:cleartable
Removesallkey-valuepairsfromtable.
table:counts
table:countslist
Countstheoccurrencesofeachelementofthegivenlistandreportsthecountsinatable.
table:group-agents
table:group-agentsagentsetanonymousreporter
Groupstheagentsintheagentsetbasedonthegivenreporter.Agentsthatreportthesamethingforreporterwillbegroupedtogether.Theresults
ofthereporterwillbeusedasthekeysintheresultingtableandthegroupswillbeagentsets.
Forexample:
observer> create-turtles 100 [ set color one-of [ red green blue ] ]
observer> show table:group-by turtles [ color ]
observer: {{table: [[105 (agentset, 38 turtles)] [55 (agentset, 32 turtles)] [15 (agentset, 30 turtles)]]}}
table:group-items
table:group-itemslistanonymous-reporter
Groupstheitemsofthelistbasedonthegivenreporter.Thereportershouldtakeasingleargument,whichwillbetheitemsofthelist.Itemsthat
reportthesamethingwhenpassedtothereporterwillbegroupedtogether.Theresultsofthereporterwillbeusedasthekeysintheresulting
tableandthegroupswillbelists.
Forexample:
observer> show table:group-by range 10 [ num -> num mod 3 ]
observer: {{table: [[0 [0 3 6 9]] [1 [1 4 7]] [2 [2 5 8]]]}}
table:from-list
table:from-listlist
Reportsanewtablewiththecontentsoflist.listmustbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecond
elementisthevalue.
table:get
table:gettablekey
Reportsthevaluethatkeyismappedtointhetable.Causesanerrorifthereisnoentryforthekey.
table:get-or-default
table:get-or-defaulttablekeydefault-value
Reportsthevaluethatkeyismappedtointhetable.Reportsthedefault-valueifthereisnoentryforthekey.
table:has-key?
table:has-key?tablekey
Reportstrueifkeyhasanentryintable.
table:keys
table:keystable
Reportsalistofallthekeysintable,inthesameorderthekeyswereinserted.
table:length
table:lengthtable
Reportsthenumberofentriesintable.
table:make
table:make
Reportsanew,emptytable.
table:put
table:puttablekeyvalue
Mapskeytovalueintable.Ifanentryalreadyexistsinthetableforthegivenkey,itisreplaced.
table:remove
table:removetablekey
Removesthemappingintableforkey.
table:to-list
table:to-listtable
Reportsalistwiththecontentoftable.Thelistwillbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecond
elementisthevalue.Thekeysappearinthesameordertheywereinserted.
table:values
table:valuestable
Reportsalistwiththeentriesoftable.Theentrieswillappearinthesameordertheywereinserted,withduplicatesincluded.
NetLogoVidExtension
Concepts
VideoSource
Thevidextensionhasabuilt-inconceptofavideosource.Atthemoment,theonlyvideosources
availablearemoviesinthedirectorythemodellivesinandcamerasattachedtothecomputer.The
vidextensionopensanewvideosourcewiththevid:<source>-openandvid:<source>-select.
Theseprimitiveschangethesourcetotheselectedsource.Ifasourceisalreadyopen,itclosesit
beforeopeninganewone.
SourceLifecycle
Moviesourcesare“stopped”afterbeingcreatedbyvid:movie-selectorvid:movie-open.Camera
sourcesstartoffas“playing”afterbeingcreatedbyvid:camera-selectorvid:camera-open.Ifa
sourceisinstatus“stopped”itcanbestartedwithvid:start.Conversely,ifthesourceis“playing”it
canbestoppedwithvid:stop.Whenasourceis“stopped”,eachcalltovid:capture-imagewill
returnthesameimage.
VideoRecorder
Thevidextensionalsohastheconceptofarecording,aseriesofframeswhichcanbesewninto
an“mp4”movie.Therecorderstatuscanbequeriedusingvid:recorder-status.Therecorder
statusis“inactive”untilstartedwithvid:start-recorder,whichsetsitto“recording”.Whilethe
recorderis“recording”thevid:record-view,vid:record-interface,andvid:record-sourcecanbe
usedtosaveframestotherecording.Youcanchoosetosavetherecordingwhilerecordingusing
vid:save-recordingwhichsavesthemovietothespecifiedfileandresettherecordingstatusto
“inactive”.Ifyouwouldprefertothrowawaytherecordedframeswithoutsaving,usevid:reset-
recorder.
Primitives
vid:camera-namesvid:camera-openvid:camera-selectvid:movie-selectvid:movie-openvid:movie-
open-remotevid:closevid:startvid:stopvid:statusvid:capture-imagevid:set-timevid:show-
playervid:hide-playervid:record-viewvid:record-interfacevid:record-sourcevid:recorder-
statusvid:start-recordervid:save-recording
vid:camera-names
vid:camera-names
Providesalistofallavailablecameras.
Example:
vid:camera-names => []
vid:camera-names => ["Mac Camera"]
vid:camera-names => ["Logitech Camera"]
vid:camera-open
vid:camera-open
Opensthenamedcameraasavideosource.Ifnonameisprovided,opensthefirstcamerathat
wouldbelistedbycamera-names.
Example:
vid:camera-open ; opens first camera
(vid:camera-open "Logitech Camera")
Errors:
Message"vid: no cameras found" :nocamerasareavailable.
Message"vid: camera "\<name\>" not found":ifthenamedcameraisnotavailable.
vid:camera-select
vid:camera-select
Promptstheusertoselectacameraasvideosource.Thiscommanddoesnoterroriftheuser
cancels.Usevid:statustoseeifauserselectedacamera.
Example:
vid:camera-select
Errors:
Message“vid:nocamerasfound”:nocamerasareavailable.
vid:movie-select
vid:movie-select
Promptstheusertoselectamovietouseasavideosource.Theformatssupportedarethose
supportedbyJavaFX2.Thiscommanddoesnoterroriftheusercancels.Usevid:statustoseeif
theuserselectedamovie.
Example:
vid:movie-select
Errors:
Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open
vid:movie-openfilename
Opensavideofromthefilesystem.Iftheprovidedpathisnotabsolutetheextensionsearchesfor
thegivenpathrelativetothecurrentmodeldirectory.Iftheprovidedpathisabsolutetheextension
opensthefile.
Example:
vid:movie-open "foo.mp4" ; Opens foo.mp4 in the directory containing the model
vid:movie-open user-file ; Opens a dialog for the user to select a movie
vid:movie-open "/tmp/foo.mp4" ; Opens a movie from the "/tmp" directory
Errors:
Message"vid: no movie found":themoviecouldnotbefound.
Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open-remote
vid:movie-open-remoteurl
Opensaremotevideofromawebsiteorftpserver.
Example:
vid:movie-open-remote "http://example.org/foo.mp4"
Errors:
Message"vid: no movie found":ThespecifiedURLcouldnotbeloadedorerroredwhile
loading.
Message"vid: format not supported":Thefiletypeoftheremotemovieisnotsupported.
Message"vid: protocol not supported":ThemoviewasatanunsupportedURLprotocol.
Supportedprotocolsareftpandhttp.
vid:close
vid:close
Closesthecurrentlyselectedvideosource.Hasnoeffectifthereisnoactivevideosource.
Example:
vid:close
vid:start
vid:start
Startstheselectedvideosource.Avideosourcemusthavebeenselectedbeforecallingvid:start.
Example:
vid:start
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:stop
vid:stop
Stopsthecurrentlyrunningvideosource.
Example:
vid:stop
vid:status
vid:status
Reportsthecurrentstatusofanactivevideo.Notethataftercallingvid:movie-openorvid:movie-
selectthestatuswillbesetto“stopped”,whileaftercallingvid:camera-openorvid:camera-select
thestatuswillbe“playing”.
Example:
vid:status ; => "inactive"
vid:movie-open "foobar.mp4"
vid:status ; => "stopped"
vid:movie-start
vid:status ; => "playing"
vid:capture-image
vid:capture-imagewidthheight
Capturesanimagefromthecurrentlyselectedactivesource.
Ifwidthandheightarenotspecified,theimageiscapturedatthecurrentsourceresolution.
Example:
extensions [ vid bitmap ]
to capture
; capture an image if a video source is open,
; have the user select a camera if no video source found
carefully [
; when camera open, take an image
let image vid:capture-image ; returns image suitable for use with bitmap extension
bitmap:copy-to-drawing image 0 0
] [
if error-message = "Extension exception: vid: no selected source" [
vid:camera-select
vid:start
let image vid:capture-image
bitmap:copy-to-drawing image 0 0
]
]
end
Ifyouwanttocaptureimagesatadifferentresolution,simplyreplacevid:capture-imagewith,e.g.,
(vid:capture-image 640 480).
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:set-time
vid:set-timeseconds
Setsthetimeofthecurrentvideosourceto*seconds*.Thishasnoeffectwhenthecurrentvideo
sourceisacamera.
Example:
vid:set-time 100
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
Message"vid: invalid time":Thecurrentlyactivevideodoesnotcontainthespecifiedsecond.
Thesecondmaybenegative,orgreaterthanthelengthofthevideo.
vid:show-player
vid:show-playerwidthheight
Showsaplayerinaseparatewindow.Ifthereisnovideosource,thewindowwillbeanemptyblack
frame.Ifthereisanactivevideosource,itwillbedisplayedinthewindowwiththespecifiedwidth
andheight.Ifthereisaplayingvideosource,itwillbedisplayedinthewindowatitsspecifiedwidth
andheight.Ifwidthandheightareomitted,thevideowillbedisplayedinitsnativeresolution.
Examplewithnativeresolution:
vid:show-player
Examplewithcustomresolution:
(vid:show-player 640 480)
Errors:
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:hide-player
vid:hide-player
Hidestheplayerifopen.Doesnothingifthereisnoplayerwindow.
Example:
vid:hide-player
vid:record-view
vid:record-view
RecordsthecurrentimageshownintheNetLogoviewtotheactiverecording.
Example:
vid:record-view
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
vid:record-interface
vid:record-interface
RecordstheNetLogointerfaceviewtotheactiverecording.
Example:
vid:record-interface
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: export interface not supported":ThecallingNetLogoversiondoesnotsupport
interfaceexports.ThiswilloccurwhenrunningNetLogoheadlessly.
vid:record-source
vid:record-source
Recordsaframetotheactiverecordingfromthecurrentlyactivesource.
Example:
vid:record-source
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:recorder-status
vid:recorder-status
Reportsthecurrentstatusoftherecorder.Initiallyandaftertherecorderissaved(viavid:save-
recording)orreset(viavid:reset-recorder)therecorderstatusis“inactive”.Aftercalling
vid:start-recorderthestatuswillbe“recording”.
Example:
vid:recorder-status ; => "inactive"
vid:start-recorder
vid:recorder-status ; => "recording"
vid:reset-recorder
vid:recorder-status ; => "inactive"
vid:start-recorder
vid:start-recorder
Startstherecorder.Iftherecorderisalreadyrunningthiswillcauseanerrortoberaised.Ifdesired,
arecordingwidthandheightcanbesupplied.Ifwidthandheightarenotsupplied,theywillbe
determinedfromthefirstframerecorded.
Example:
vid:start-recorder
(vid:start-recorder 640 480)
Errors:
Message"vid: recorder already started":Therecorderhasalreadybeenstarted.Theexisting
recordingshouldbesavedorresetbeforestartingtherecording.
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:save-recording
vid:save-recordingfilename
Savestherecordingtothespecifiedpath.Iftherecorderisnotrunningthiswillcauseanerrortobe
raised.Notethatatpresenttherecordingwillalwaysbesavedinthe“mp4”format.Ifthesupplied
filenamedoesnotendin“.mp4”,the“.mp4”suffixwillbeadded.Notethatvid:save-recordingwill
overwriteexistingfilesofthesamename.vid:save-recordingwillerroriftherecorderhasnotbeen
startedorifthefilecannotbewrittensincethecontainingdirectorydoesnotexist.
Example:
vid:save-recording "foo.mp4" ; Saves to foo.mp4 in the directory containing the model
vid:save-recording user-new-file ; Opens a dialog for the user to select a save path
vid:save-recording "/tmp/foo.mp4" ; Saves the recording to the "/tmp" directory
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: no such directory":Thedirectorycontainingthespecifiedsavefiledoesnot
exist.
Message"vid: no frames recorded":Youtriedtosavearecordingwithnoframesrecorded.
Checkthatyouarerecordingproperlyorusevid:reset-recordingtotochangetherecording
formatwithoutsaving.
NetLogoView2.5dExtension
TheView2.5DextensionoffersvisualizationforPatchandTurtlereporters,inrealtime,ina
simulation’scontext.
HowtoUse
Theview2.5dextensionispre-installedinNetLogo.
Tousetheview2.5dextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [view2.5d]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustadd
view2.5dtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
IncorporatingIntoModels
openawindowusingeithertheview2.5d:patch-vieworview2.5d:turtle-viewcommands(itcanbea
goodideatoputtheseinyour‘SETUP’procedureoraseparatebutton).
updateyourwindow’sviewusingoneoftheupdatecommands(puttheseinyour‘GO’procedure).
SeetheView2.5dCodeExamplesintheNetLogomodelslibrary.
Feedback
Sendcomments,bugs,orotherfeedbacktoCCLFeedbackand/orCoreyBrady.
Primitives
view2.5d:patch-viewview2.5d:decorate-patch-viewview2.5d:undecorate-patch-viewview2.5d:turtle-
viewview2.5d:update-all-patch-viewsview2.5d:update-patch-viewview2.5d:update-turtle-view
view2.5d:get-z-scaleview2.5d:set-z-scaleview2.5d:set-turtle-stem-thicknessview2.5d:get-
observer-anglesview2.5d:set-observer-anglesview2.5d:get-observer-xy-focusview2.5d:set-observer-
xy-focusview2.5d:get-observer-distanceview2.5d:set-observer-distanceview2.5d:remove-patch-view
view2.5d:remove-turtle-viewview2.5d:remove-all-patch-viewsview2.5d:remove-all-turtle-views
view2.5d:count-windows
view2.5d:patch-view
view2.5d:patch-viewTitleReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallfor
subsequentupdatesandmodifications.SpecificationoftheReporterusestheNetLogoanonymous
proceduresyntax,fromtheObserverperspective.
Example:
view2.5d:patch-view "Test" [ [the-turtle] -> [pxcor] of the-turtle]
view2.5d:decorate-patch-view
view2.5d:decorate-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:drawsthe
turtlesofthemodelattheircurrentlocation,ontopofthePatchviewdisplay
NOTE:onlyhasaneffectinthe“structures”patchview(intheothers,thepatchvalueis
inclinedbasedonneighbors&gradient)
NOTE:fornegativepatchvalues,theturtleshapesaredrawnbelow(orbitunderneathto
seethem)
Example:
view2.5d:decorate-patch-view "Test"
view2.5d:undecorate-patch-view
view2.5d:undecorate-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)
TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:STOPSdrawingtheturtlesof
themodelattheircurrentlocation,ontopofthePatchviewdisplay
Example:
view2.5d:undecorate-patch-view "Test"
view2.5d:turtle-view
view2.5d:turtle-viewTitleAgentsReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallfor
subsequentupdates.Theturtle-setisanyselectorforturtles.SpecificationoftheReporterusesthe
NetLogotasksyntax,fromtheObserverperspective.
Example:
view2.5d:turtle-view "Test" turtles with [color = red] [[energy] of ?1]
; This would create a new 2.5d window, plotting the ENERGY value of all turtles that are red.
view2.5d:update-all-patch-views
view2.5d:update-all-patch-views
ThiscommandmustbecalledfromtheObservercontext.Updatesallexistingpatch-viewwindows
accordingtothelatestvalues.
view2.5d:update-patch-view
view2.5d:update-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.Updatesonlythepatch-viewwindowwiththe
specifiedtitle(ifany).
view2.5d:update-turtle-view
view2.5d:update-turtle-viewTitleAgents
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Theturtle-setselectormustbesuppliedtorefreshthesetofturtles.
view2.5d:get-z-scale
view2.5d:get-z-scaletitle
ThisreportermustbecalledfromtheObservercontext.Returnsthecurrentz-scaleoftheturtle-viewor
patch-viewwindowwiththespecifiedtitle(ifany).
view2.5d:set-z-scale
view2.5d:set-z-scaleTitlenew-z-scale
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-vieworpatch-view
windowwiththespecifiedtitle(ifany).Theviewisnowdisplayedwiththenewz-scale.
view2.5d:set-turtle-stem-thickness
view2.5d:set-turtle-stem-thicknessTitlethickness
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Turtlesarenowdrawnwith“pins”or“stems”thathavethespecifiedthickness
(insteadofthehairlinedefault)
view2.5d:get-observer-angles
view2.5d:get-observer-anglesTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingtheobserver’sangular
perspective{headingpitch}(theplaceonanimaginarysphereatthezoomdistanceisupdatedto
obeyheading&pitchgiven)
view2.5d:set-observer-angles
view2.5d:set-observer-anglesTitleheadingpitch
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setstheobserver’sangularperspective(theplaceonanimaginarysphereatthe
zoomdistanceisupdatedtoobeyheading&pitchgiven)
view2.5d:get-observer-xy-focus
view2.5d:get-observer-xy-focusTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingthexandycoordinates
theobserveris“lookingat”inthepatchplane.
view2.5d:set-observer-xy-focus
view2.5d:set-observer-xy-focusTitlenumberycor
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setsthexandycoordinatestheobserverthatis“lookingat”inthepatchplane.
view2.5d:get-observer-distance
view2.5d:get-observer-distanceTitle
ThisreportermustbecalledfromtheObservercontext.Returnstheobserver’sdistancefromits“focus
point”
view2.5d:set-observer-distance
view2.5d:set-observer-distanceTitlenew-distance
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setstheobserver’sdistancefromits“focuspoint”
view2.5d:remove-patch-view
view2.5d:remove-patch-viewTitle
Thiscommandclosesandremovesthespecifiedpatchviewprogrammatically(equivalenttoclosing
thewindowmanually).
view2.5d:remove-turtle-view
view2.5d:remove-turtle-viewTitle
Thiscommandclosesandremovesthespecifiedturtleviewprogrammatically(equivalenttoclosing
thewindowmanually).
view2.5d:remove-all-patch-views
view2.5d:remove-all-patch-views
Thiscommandclosesandremovesallpatchviewsprogrammatically(equivalenttoclosingthe
windowsmanually).
view2.5d:remove-all-turtle-views
view2.5d:remove-all-turtle-views
Thiscommandclosesandremovesallturtleviewsprogrammatically(equivalenttoclosingthe
windowsmanually).
view2.5d:count-windows
view2.5d:count-windows
Thisreporterreturnsthenumberofturtleandpatchviewsthatarecurrentlyactive.
FAQ(FrequentlyAskedQuestions)
NetLogo6.0.4UserManual
FeedbackfromusersisveryvaluabletousindesigningandimprovingNetLogo.We’dliketohearfromyou.(SeeContacting
Us.)
General
WhyisitcalledNetLogo?
The“Logo”partisbecauseNetLogoisadialectoftheLogolanguage.
“Net”ismeanttoevokethedecentralized,interconnectednatureofthephenomenayoucanmodelwithNetLogo,including
networkphenomena.ItalsoreferstoHubNet,themultiuserparticipatorysimulationenvironmentincludedinNetLogo.
HowdoIciteNetLogoorHubNetinapublication?
IfyouuseorrefertoNetLogo,HubNetoramodelfromtheNetLogomodelslibrary,weaskthatyouciteitasfollows:
NetLogoitself:Wilensky,U.1999.NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnectedLearningandComputer-
BasedModeling,NorthwesternUniversity.Evanston,IL.
HubNet:Wilensky,U.&Stroup,W.,1999.HubNet.http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnected
LearningandComputer-BasedModeling,NorthwesternUniversity.Evanston,IL.
HowdoIciteamodelfromtheModelsLibraryinapublication?
Thecorrectcitationisincludedinthe“CreditsandReferences”sectionofeachmodel’sInfotab.
WhereandwhenwasNetLogocreated?
NetLogowasfirstcreatedin1999byUriWilenskyattheCenterforConnectedLearningandComputer-BasedModeling,thenat
TuftsUniversityintheBostonarea.NetLogogrewoutofStarLogoT,whichwasauthoredbyWilenskyin1997.In2000,theCCL
movedtoNorthwesternUniversity,intheChicagoarea.NetLogo1.0cameoutin2002,2.0in2003,3.0in2005,4.0in2007,4.1
in2009,and5.0in2012.
WhatprogramminglanguagewasNetLogowrittenin?
NetLogoiswrittenmostlyinScala,withsomepartsinJava.(ScalacodecompilestoJavabytecodeandisfullyinteroperable
withJavaandotherJVMlanguages.)
What’stherelationshipbetweenStarLogoandNetLogo?
TheoriginalStarLogobeganattheMITMediaLabin1989andranontheConnectionMachine.Laterversionsweredeveloped
forMacintoshcomputers:MacStarLogo(1994,MIT)andStarLogoT(1997,Tufts).
TodaytherearetwoStarLogodescendantsunderactivedevelopment:NetLogo(fromtheCCLatNorthwesternUniversity)and
StarLogoTNG(fromMIT).NetLogoisthemostwidelyusedagent-basedmodelingenvironmentinbotheducationandresearch.
StarLogoTNGisdistinguishedbyitsprogramminginterfacebasedoncoloredblocks.
UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?
NetLogoisfree,opensourcesoftwareundertheGPL(GNUGeneralPublicLicense),version2,or(atyouroption)anylater
version.
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,pleasecontactUriWilenskyat
uri@northwestern.edu.
ThesourcecodeisonGitHub,here.Developmentdiscussionisonthenetlogo-develgroup.
TheUserManualispublishedunderaCreativeCommonsAttribution-ShareAlikelicense(CCBY-SA3.0).
SourcecodeforalloftheextensionsbundledwithNetLogoisonGitHub,here.Mostoftheextensionsareinthepublicdomain
(CC0notice).Otherextensionsarereleasedunderopensourcelicenses.Seeeachextension’sREADMEfordetails.
TheCodeExamplesintheModelsLibraryareinthepublicdomain(CC0notice).
TherestofthemodelsintheModelsLibraryareprovidedunderavarietyoflicenses.Somearepublicdomainandsomeare
opensource,butmostareundertheCreativeCommonsAttribution-ShareAlikelicense(CCBY-NC-SA),whichisnotanopen
sourcelicense,thoughthemodelsarefreefornoncommercialdistributionanduse.
Seeeachmodel’sInfotabtocheckitsparticularlicense.
ThemodelsareinapublicGitrepositoryhere.
DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?
Weofferworkshopsfromtimetotime.Ifaworkshophasbeenscheduled,wewillannounceitontheNetLogoUsersGroup.
ArethereanyNetLogotextbooks?
TheCCLhaspublishedatextbook(writtenbytheauthorofNetLogo)thatgivesanintroductiontoagent-basedmodeling
methodsusingNetLogo.Itgoesstepbystepwithcodingexampleshowtodesign,build,revise,andanalyzemodels.Andit
presentssomeadvancedtechniques.
Seewww.intro-to-abm.comformoreinformationonthattextbook.
SeetheTextbookssectionofourResourcespage.
WeattheCCLhavehopedtowriteseveralmoreNetLogotextbooks.Thesecouldbeaimedatdifferentaudiences,suchas:
middleschool,highschool,undergraduatecourseinmodelingorcomplexity,practicalguideforinterestedadults.
Unfortunately,wehavenotyetbeenabletofindthetimetomakethesehappen.Ifanyonefromtheusercommunitywouldlike
tocollaborateonsuchaventure,pleaseletusknow.Wewouldwelcomeit.
IsNetLogoavailableinotherlanguagesbesidesEnglish?
VolunteershavetranslatedtheusermanualintoChineseandCzech.ThetranslatedversionsareavailablefromtheNetLogo
website.
Sofar,theNetLogouserinterfacehasbeenlocalizedinEnglish,Spanish,Chinese,Russian,andJapanese.Allfivelanguages
areincludedinthestandarddownload.
WeareseekingvolunteerstocompleteandimprovetheselocalizationsandtotranslatetheNetLogosoftwareandmanualinto
asmanyotherlanguagesaspossible.Ifyou’reabletohelpinthisendeavor,pleasecontactus.
IsNetLogocompiledorinterpreted?
Shortanswer:someofboth.
Longanswer:NetLogodoesincludeacompilerthatgeneratesJavabytecode.However,thiscompilerdoesnotyetsupportthe
entirelanguage,sosomepartsofusercoderemaininterpreted.NotethatourcompilergeneratesJavabytecode,andJava
virtualmachineshave“just-in-time”compilersthatinturncompileJavabytecodeallthewaytonativecode,somuchusercode
isultimatelytranslatedtonativecode.
Hasanyonebuiltamodelof<x>?
TrylookingattheNetLogoModelsLibrary,theNetLogoModelingCommons,ourCommunityModelspage,andourlistof
referencestoNetLogoinoutsideworks.
YoumightalsoaskthequestionontheNetLogoUsersGroupand/orsearchpastmessagesonthegroup.
AreNetLogomodelsrunsscientificallyreproducible?
Yes.NetLogo’spseudorandomnumbergeneratorandagentschedulingalgorithmsaredeterministic,andNetLogoalwaysuses
Java’s“strictmath”library,whichgivesbit-for-bitidenticalresultsregardlessofplatform.Butkeepthefollowingcautionsinmind:
Ifyourmodelusesrandomnumbers,theninordertogetreproduciblebehavior,youmustusetherandom-seedcommand
tosettherandomseedinadvance,sothatyourmodelwillreceivetheexactsamesequenceofrandomnumbersevery
time.Rememberthatagentsetsarealwaysinrandomorder,soanythingyoudowithagentsetsusesrandomnumbers.
Ifyourmodelusestheeveryorwaitcommandsinsuchawaythataffectstheoutcomeofthemodel,thenyoumayget
differentresultsondifferentcomputers,orevenonthesamecomputer,sincethemodelmayrunatadifferentspeed.
Inordertoreproducemodelrunsexactly,youmustbeusingtheexactsameversionofNetLogo.Thedetailsoftheagent
schedulingmechanismandtherandomnumbergeneratormaychangebetweenNetLogoversions,andotherchanges
(bugfixesintheengine,languagechanges,andsoforth)mayalsoaffectthebehaviorofyourmodel.(Thenagain,they
maynot.)
WehaveexpendedeveryefforttomakeNetLogomodelrunsfullyreproducible,butofcoursethiscannevertrulybean
iron-cladguarantee,duenotonlytothepossibilityofrandomhardwarefailure,butalsothepossibilityofhumanerrorinthe
designof:yourmodel,NetLogo,yourJavaVM,yourhardware,andsoon.
WillNetLogoandNetLogo3Dremainseparate?
Fornow,yes.NetLogo3DisincludedwithNetLogo,butitisstillaseparateapplication.
Ideallyasingleunifiedapplicationwouldsupportboth2Dand3Dmodeling.Wewoulddesignthe3Dworldsupportsoitdoesn’t
getinthewaywhenyouarebuilding2Dmodels.ModelsbuiltinNetLogo3Dmightrequirechangesinordertoruninthe
hypotheticalunifiedapplication.
CanIrunNetLogoonmyphoneortablet?
No.NeitheriOS,norAndroid,norWindowsRTsupportsrunningJavaapplicationssuchasNetLogo.
WeareworkingonanalternateimplementationofNetLogoonaJavaScriptandHTML5base,insteadofJava.Itwillworkona
varietyoftabletsandphones.Wedon’tknowyetwhenitwillbeready,andweexpectthatforalongtimeitwillonlysupporta
subsetofthefeaturesindesktopNetLogo.Themanyperson-yearsofdevelopmenteffortthathavegoneintotheJavaversion
can’tcheaplyoreasilybereplicatedonanotherplatform.
Fortechnicaldetailsonthisnewproject,gohere.
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?
Yes.WhenyouinstallNetLogo,thefolderthatiscreatedcontainshastheversionnumberinitsname,somultipleversionscan
coexist.
OnWindowssystems,whicheverversionyouinstalledlastwillbetheversionthatopenswhenyoudoubleclickamodelfilein
WindowsExplorer.OnMacs,youcancontrolwhatversionopensvia“GetInfo”intheFinder.
I’monaUNIXsystemandIcan’tuntarthedownload.Why?
Someofthefilesinthetarballhavelongpathnames,toolongforthestandardtarformat.YoumustusetheGNUversionoftar
instead(oranotherprogramwhichunderstandstheGNUtarextensions).Onsomesystems,theGNUversionoftarisavailable
underthename“gnutar”.YoucanfindoutifyouarealreadyusingtheGNUversionbytypingtar --versionandseeingifthe
outputsays“tar(GNUtar)”.
HowdoIinstallNetLogounattended?
Itdependsonwhichplatformyouareusing.
Linux:UntarNetLogointotheappropriateplace.
Mac:CopytheNetLogodirectoryfromthediskimageintotheApplicationsfolder.
Windows:TheinstallerisanMSIwhichcanberunusingoneofthefollowingcommands(thesemayrequireadmin
privileges):
msiexec.exe /i C:\Path\to\NetLogo.msi ALLUSERS=1 ADDLOCAL=Shortcuts :: To install with desktop shortcuts
msiexec.exe /i C:\Path\to\NetLogo.msi ALLUSERS=1 ADDLOCAL=BaseInstall :: To install without desktop shortcuts
Wealsomaintainanadvancedinstallationwikipagewhichmayhaveadditionaltipsandtricks.Weencourageuserswhohave
problemswithunattendedinstallationorideasonhowitcouldbeimprovedtoemailfeedback@ccl.northwestern.edu.
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?
Yes.NetLogorunsfinefromanyfilesystem,includingread-onlyfilesystems.
WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?
Yourcomputerisswitchingtopowersavingmodewhenunplugged.It’snormalforthistoreducespeedalittle,butunfortunately
thereisabuginJavathatdrasticallyslowsdownSwingapplications,includingNetLogo.
Oneworkaroundistochangethepowersettingsonyourcomputersoitdoesn’tgointopowersavingmodewhenyouunplugit.
(Ifyoudothis,yourbatterywon’tlastaslong.)
AnotherworkaroundistorunNetLogowithanoptionrecommendedbyOracle,byeditingtheNetLogo6.0.4.vmoptionsfile,
foundintheNetLogodirectory(underProgramFilesonyourharddrive,unlessyouinstalledNetLogoinadifferentlocation).Add
onanewline:
-Dsun.java2d.ddoffscreen=false
YoucanseethedetailsoftheJavabugandvoteforOracletofixithere.
WhydoesNetLogobundleJava?
SinceMacOSXLion,ApplehaveencouragedMacapplicationdeveloperstobundleJava.NetLogobundlesJavabecauseit
allowsustodeliveraconsistent,convenientexperiencetoourusers.BundlingJavaallowsustotestforcompatibilityonceand
avoidanybugscausedbyversionmismatchesorJavaconfigurationincompatibilities.
IfusersareinterestedinusingJavaontheirsysteminsteadoftheversionofJavabundledwithNetLogo,theycanconfigure
NetLogotouseadifferentJavaruntime.Pleasenotethatthischangeisdoneatyourownrisk.Weareunabletooffersupport
forproblemscausedbyrunningNetLogowithanalternateJavaRuntime.TochangetheJavaruntimeusedbyNetLogo,open
theNetLogo.cfgfileandmodifytheapp.runtimepropertytothepathofyourpreferredJavaRuntime.
HowcomeNetLogowon’tstartuponmyLinuxmachine?
WebundleOracle’sJavaruntimewhenusingNetLogoonLinux.Ifyouwouldliketochangetheversionoflinuxused,youcan
modifythe.cfgfilestopointtoadifferentversionofjava(seeHowbigcanmymodelbe?formoreinformation).
Intheory,anyJava8orlaterruntimewillrunNetLogo.Inpractice,someJavaimplementationsaren’thighenoughquality.
RecentversionsofOpenJDKshouldwork;olderonesmaynot.GNUlibgcjdoesnotwork.
Ubuntuusersshouldconsulthttps://help.ubuntu.com/community/Java.
WhenItrytoinstallNetLogoonWindows,Isee“WindowsprotectedyourPC”
Windowsattemptstoprotectusersfromdownloadingmalicioussoftwarebymaintainingalistof“good”and“malicious”software.
ThefirstuserstoinstallanyNetLogoreleasewillseethiswarning.Laterusersmayormaynotseethiswarning.Beforegoing
anyfurther,ensureyouareprotected.TheCCLcanonlyvouchforNetLogodownloadshostedontheCCLWebsite.NetLogo
canbefreelydownloadedfromtheofficialNetLogodownloadpage.IfyouobtainNetLogofromanywhereelse,youinstallitat
yourownrisk!
YoucancontinuepasttheWindowspromptbytakingthefollowingsteps:
Inthe“WindowsprotectedyourPC”prompt,click“MoreInfo”,thepromptwillchange
Inthechangedprompt,click“RunAnyway”andcontinuewithinstallationasnormal
Noteinordertoseethe“MoreInfo”or“RunAnyway”options,youwillneedtoruntheinstallerasanadministrator.Ifyoudonot
seethoseoptions,right-clickandchoose“Runasadministrator”and/orchangeyouruseraccounttoanadministratoraccount
beforeinstalling.
WeattheCCLareworkingonsolvingthisproblemandhopetofreeourusersoftheaddedinstallationdifficultysoon!
WhenItrytostartNetLogoonWindowsIgetanerror“TheJVMcouldnotbestarted”.Help!
AnearlycertainfixistouseatexteditortoedittheNetLogo.cfgfile,changing1024mtoasmallernumber,like512m.This
shouldpermitNetLogotostart,althoughthelowerheapsizelimitmayaffectyourabilitytorunmodelswithmanyagents.See
Howbigcanmymodelbe?forinformationonmodelsizeandhowtoeditthecfgfile.
Ifrunningwiththelowerheapsizelimitisunacceptable,readon.
SomeWindowssystemshavetroubleallocatinglargeamountsofcontiguousvirtualmemory.Upgradingtoanewerversionof
Windowsmayhelp.
RunningWindowsin64-bitmodeinsteadof32-bitmodemayalsohelp.DoublecheckthatWindowsisactuallyrunningin64-bit
mode;seeMicrosoft’sFAQpageon64-bitWindows.
NetLogowon’tstartonMacOSSierra(orlater)
SomeusershavereportedproblemsopeningNetLogo6onMacOSSierra.We’vebeenunabletodeterminearootcausefor
thisproblem,butwe’recontinuingtoinvestigate.We’relookingforassistancefromyouifyourunintothisproblem.Itwouldbe
extremelyhelpfulifyoucouldrunthefollowingcommandinthe“Terminal”applicationandsendtheoutputinanemailto
bugs@ccl.northwestern.edu.
xattr -pl com.apple.quarantine /Applications/NetLogo\ 6.0.4/NetLogo\ 6.0.4.app
runningitshouldgiveyouasinglelineofoutput(somethinglikecom.apple.quarantine: 01e1;58ac6af2;Firefox;F2E0B1E2-D203-
4B05-8DF9-ABA58B52EFEA,butyourswillhavedifferentnumbers,letters,andwords).Pleasecopyandpastethisstringintothe
emailyousendus.
Thereisalsoapartialworkaround!RunningthefollowingcommandintheTerminalwillenableuserstorunNetLogowithout
turningGatekeepercompletelyoff.Thecommandis:
sudo xattr -dr com.apple.quarantine /Applications/NetLogo\ 6.0.4/NetLogo\ 6.0.4.app
NotethatifyouplantorunNetLogo3D,HubNetClient,orNetLogoLogging,youmayalsoneedtore-runthatcommandonce
foreachofthoseapplications.Iftheworkaroundwasnoteffectiveforyou,pleasesendusanemailandletusknow.
NetLogowon’tstartonWindowsorcrashessuddenlyonMacOSSierra
SomeusersonMacOSwithdiscretegraphicscardsexperiencesuddencrashesofNetLogowhenswitchingbetweenintegrated
anddiscretegraphics.It’spossibletopreventthesecrashesbydisablingautomaticgraphicsswitchinginSystemPreferences.
SomeWindowsusersmayalsobeunabletoopenNetLogoduetographicscardsettingsordrivers.Ifyouareunabletoopen
NetLogoonWindows,youmightbeabletofixthisbyupdatingorreinstallingyourgraphicsdriverand/ordisablinganygraphics
cardutilities.BecauseNetLogomightbeunabletostartforanumberofreasons,weencourageyoutocontactusifthesesteps
aren’teffectiveinresolvingtheproblem.
CanIrunNetLogofromthecommandline,withouttheGUI?
Yes.TheeasiestwayistosetupyourmodelrunorrunsasaBehaviorSpaceexperiment.Noadditionalprogrammingis
required.SeetheBehaviorSpaceGuidefordetails.
AnotheroptionistouseourControllingAPI.SomelightJavaprogrammingisrequired.SeetheControllingAPIGuidefordetails
andsamplecode.
DoesNetLogotakeadvantageofmultipleprocessors?
OnlywhenusingBehaviorSpace.BehaviorSpacedoesparallelruns,oneperprocessor.
Forasinglemodelrun,onlyoneprocessorisused.
Weareseekingfundingtomakeitpossibletosplitasinglemodelrunacrossmultipleprocessorsormultiplecomputers.
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?
Manyofthesamecommentsinthepreviousanswerapply.Itisnotpossibletosplitasinglemodelrunacrossmultiple
computers,butyoucanhaveeachmachineinaclusterdoingoneormoreseparate,independentmodelruns,usingeither
BehaviorSpaceorourControllingAPI.Wedon’thaveautomatedsupportforsplittingtherunsacrossclusters,soyou’llneedto
arrangethatyourself.
VarioususersarealreadyusingNetLogoonclusters,withavarietyofhardwareandsoftware.Youcanseekthemoutonthe
NetLogoUsersGroup.
IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
Yes.NetLogoauto-savesfilesasyouareworkingonthem.Thepathtotheauto-savefiledependsonwhetherornotthe
NetLogomodelhasbeensaved.
ForNetLogomodelswhichhavebeensaved,ahiddenfilewiththename“.filename.tmp.nlogo”willbecreatedinthesame
directoryastheNetLogomodel.
ForunsavedNetLogomodels,autosavefilescanbefoundinyourOS-specificjavatemporarydirectory.Thefilesarenamed
accordingtothefollowingformat:autosave_yyyy-MM-dd.HH_mm_ss.nlogowherethetimeanddatearethetimeanddatethe
modelwasopened.Theexactpathwilldependonyouroperatingsystem:
OnMacOS,thetemporarydirectoryis/var/folders/68/<30-character-alphanumeric-sequence>/T/.The30-character-
alphanumeric-sequenceisuniquetoeachmachine.
OnWindowsthelogscanbefoundinC:\Users\<user>\AppData\Local\Temp,where<user>istheloggedinuser.
Onmostnon-MacUnix-likesystemsthetempdirectoryis/tmp.
WhyisHubNetDiscoveryNotWorking?
HubNetdiscoveryprovidestheabilityforHubNetclientsrunningonthesamelocalnetworkastheHubNetserverto
automaticallydisplaytheIPaddressandcurrentactivityoftheserver.ThisusesIPv4multicastoveralocalareanetwork-it
won’tidentifyHubNetserversontheinternetorondifferentnetworks.Somenetworksalsodonotsupportmulticasttrafficandit
willsimplynotworkonthosenetworks.ForHubNetDiscoverytowork,theservermustbebroadcastingtothesamenetwork
thattheclientispollingformessages.Often,boththeclientandserverareonlyconnectedtoasinglenetworkandthereisno
needforfurtherconfiguration.
SinceNetLogo6.0.3,wehavetoolsinplacetoallowclientsand/orserversconnectedtomultiplenetworkstoselectthenetwork
onwhichtheywillbroadcast/listen.WhenrunningaHubNetserver,thisisdonebyselectingtheappropriate“broadcastnetwork”
viaselectiondropdownwhenstartingaHubNetserver.ThispreferencewillberemembereduntilNetLogoisrestarted,soifyou
endupneedingtobroadcastonadifferentnetwork,restartNetLogo.HubNetclientsalsoseeasimilardropdownwhenselecting
whichactivitytojoin.UnlikeHubNetserver,clientsmaychangethenetworkonwhichtheylistenatanytime.HubNetdiscovery
willonlyworkwhenbothclientandserverarelistening/broadcastingonthesamenetwork,sosometrialanderrormaybe
requiredtofigureoutaworkingconfiguration.Generallyspeaking,thesharednetworkistheoneonwhichtheclientandthe
serverhavethemostsimilarIPaddressprefixes.Forinstance,iftheserverselectstobroadcastonanetworkwhereithasIP
address192.168.0.101,aclientshouldpreferlisteningonanetworkwhereithasanIPlike192.167.0.203overanetworkwhere
ithasanIPlike10.5.0.101.Evenwhenthesamenetworkisselected,itispossiblethatthatnetworkmaynotsupportIPv4
multicast,inwhichcasediscoverywillnotworkandclientsmustenterIPaddressesmanually.
Notethatthechangemadein6.0.3simplyenableselectionofthenetworkonwhichclientsandserversbroadcast/listenon.The
HubNetserverstilllistensonallnetworkconnections,soalllistedIPaddressesgivenintheserverbroadcastnetworkselection
dropdownarepotentiallyvalidforaHubNetclient(evenaclientonadifferentnetwork)toconnectto.SimilarlyHubNetclients
mayconnecttoanyHubNetserverreachablefromtheircomputer.
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?
TheonlywayNetLogocanmakeyourmodelrunfasterisbyupdatingtheviewlessfrequently.Asyoumovethespeedsliderto
theright,viewupdatesbecomelessandlessfrequent.Sinceviewupdatestaketime,thatmeansmorespeed.
However,fewerupdatesalsomeansthattheupdatescomefartherapart.Whenseveralsecondspassbetweenupdates,itmay
seemlikeyourmodelhasstopped.Ithasn’t.It’srunningatfullspeed.Watchthetickcounter!(Ifyourmodelusesit.Ifitdoesn’t,
watchsomethingelse,likeaplot.)
Togetafeelforwhat’sgoingon,trymovingtheslidertotherightgraduallyratherthansuddenly.Ifyoufindtheupdatestoo
infrequentattherightmostposition,justdon’tpushthesliderthatfar.
CanIusethemouseto“paint”intheview?
NetLogodoesnothaveabuilt-insetofpaintingtoolsforpaintingintheview.Butwithonlyafewlinesofcode,youcanadd
paintingcapabilitytoyourmodel.Toseehowit’sdone,lookatMouseExample,intheCodeExamplessectionoftheModels
Library.Thesametechniquescanbeusedtolettheuserinteractwithyourmodelusingthemouseinotherways,too.
AnotherpossibilityistocreateanimageinanotherprogramandimportitusingtheimportitemsontheFilemenuortheimport-
*primitives.
Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmy
modelcontain?
WehavetestedNetLogowithmodelsthatusehundredsofmegabytesofRAMandtheyworkfine.Wehaven’ttestedmodels
thatusegigabytesofRAM,though.Theoreticallyitshouldwork,butyoumighthitsomelimitsthatareinherentintheunderlying
JavaVMand/oroperatingsystem(eitherdesigned-inlimits,orbugs).
TheNetLogoenginehasnofixedlimitsonsize.Bydefault,though,NetLogoshipswithaone-gigabyteceilingonhowmuchtotal
RAMitcanuse.Ifyourmodelexceedsthatlimit,you’llgetanOutOfMemoryErrordialog.
IfyouareusingBehaviorSpace,notethatdoingrunsinparallelwillmultiplyyourRAMusageaccordingly.
Eachplatformcontains“.cfg”filescontainingJVMsettings.Thereisonecfgfileforeachsub-application(NetLogo,NetLogo3D,
HubNetClient,etc.)Althoughthefilelocationvariesbyplatform,theprocessforchangingitisthesame.Locatethesectionof
thefilethatlookslikethefollowing:
[JVMOptions]
# there may be one or more lines, leave them unchanged
-Xmx1024m
# there may be one or more lines, leave them unchanged
Modifythevalueimmediatelyfollowing-Xmx,changingittotheamountofspaceyouneed,savethefile,andrestartNetLogo.
Platformspecificnotesfollow:
Windows:ThecfgfileswillbeinC:\Program Files (x86)\NetLogo 6.0.4\appifyouarerunning64-bitwindows,and
C:\Program Files\NetLogo 6.0.4\appotherwise.
MacOSX:ThefileforNetLogowillbelocatedat:/Application/NetLogo 6.0.4/NetLogo.app/Contents/Java/NetLogo.cfg
ForNetLogo3Dandtheotherapplications,youwillfindthefileinthecorrespondinglocationforeachapplicationpackage.
Youcanreachthecfgfilebycontrol-clickingtheapplicationintheFinderandchoosing“ShowPackageContents”fromthe
popupmenu.
PleasenotethatdependingonyourversionofMacOSX,changingthecfgfilemaybreakapplicationsigning.Ifthis
happens,followApple’sdirectionsonthispagetotemporarilyallowappsfrom“Anywhere”,runNetLogoonce,thenrestore
thesettingto“MacAppStoreandIdentifiedDevelopers”.
Other:Thecfgfileswillbelocatedinthenetlogo-6.0.4/appfolderafteruntarring.
Bydefault,MacbuildsofNetLogobundlea64-bitJVM,whichshouldbeabletomakeuseofasmuchmemoryasthelesserof
availablesystemmemoryandthevaluefollowing-Xmx.WindowsandLinuxwillbundlea32-bitor64-bitJVM,dependingon
whichversionyouhavedownloaded.Itisrecommendedthatyouinstall64-bitNetLogoonall64-bitoperatingsystemsforbest
performance.
CanIuseGISdatainNetLogo?
Yes,manyusersareusingGISdatawithNetLogo.ThemostcompletewaytodothatiswiththeGISextension.SeetheGIS
ExtensionGuide.
Asimplerwayistouseimport-pcolors,butthatonlyworksforimportingmapsthatareimages,notmapsinotherformats.
ItisalsopossibletowriteNetLogocodethatreadsGISdatausingourfileI/Oprimitivessuchasfile-open.Forexample,seethe
GrandCanyonmodelintheEarthSciencesectionofSampleModels.
Mymodelrunsslowly.HowcanIspeeditup?
Here’ssomewaystomakeitrunfasterwithoutchangingthestructureofthecode:
Usetick-basedviewupdates,notcontinuousupdates.
Decreasethefrequencyofviewupdatesbypushingthespeedslidertotheright,orturnupdatesoffusingthecheckbox.
IfyourmodelisusingallavailableRAMonyourcomputer,theninstallingmoreRAMshouldhelp.Ifyourharddrivemakes
alotofnoisewhileyourmodelisrunning,youprobablyneedmoreRAM.
Useturtlesize1,1.5,or2,asthe2DrenderingsforthesesizesarecachedbyNetLogo.(Thisonlyaffectsgraphicsspeed
inthe2Dview,notcomputationspeed.)
Inmanycases,though,ifyouwantyourmodeltorunfaster,youmayneedtomakesomechangestothecode.Usuallythe
mostobviousopportunityforspeedupisthatyou’redoingtoomanycomputationsthatinvolvealltheturtlesorallthepatches.
Oftenthiscanbereducedbyreworkingthemodelsothatitdoeslesscomputationpertimestep.ThemembersoftheNetLogo
UsersGroupmaybeabletohelpwiththis.
Theprofilerextensionisusefulforidentifyingwhichpartsofyourcodearetakingthemosttime.
Unlessyouarerunningtheexactsamestringsoverandover,usingrunandrunresultaremuchslowerthanrunningcode
directly;youshouldavoidusingtheseprimitivesonfreshstringsinperformance-criticalcode.
CanIhavemorethanonemodelopenatatime?
OneinstanceofNetLogocanonlyhaveonemodelopenatatime.(Unfortunately,itisunlikelythatthiswillchangeinafuture
version,duetotheengineeringdifficultiesinvolved.)
YoucanhavemultiplemodelsopenbyopeningmultipleinstancesofNetLogo,though.OnWindowsandLinux,simplystartthe
applicationagain.OnaMac,you’llneedtoduplicatetheapplication(notthewholefolder,justtheapplicationitself)intheFinder,
thenopenthecopy.(Thecopytakesuponlyaverysmallamountofadditionaldiskspace.)
CanIchangethechoicesinachooseronthefly?
No.
CanIdividethecodeformymodelupintoseveralfiles?
Onanexperimentalbasis,thisisavailableusingthe__includeskeyword.
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?
ThisisansweredindetailattheendoftheProgrammingGuide.
HowcomemymodelfromanearlierNetLogodoesn’tworkright?
SeetheTransitionGuideforhelp.
HowdoItakethenegativeofanumber?
Anyoftheseways:
(- x)
-1 * x
0 - x
Withthefirstway,theparenthesesarerequired.
Myturtlemovedforward1,butit’sstillonthesamepatch.Why?
Ifyouhavedisabledwrappingattheworldedgesinyourmodel,thentheturtlemightbeataworldedgeandunabletomoveany
further.Youcantestforthisusingcan-move?.
Assumingtheturtleisn’thittingaworldedge,movingforward1isonlyguaranteedtotakeaturtletoanewpatchiftheturtle’s
headingisamultipleof90(thatis,exactlynorth,south,east,orwest).
It’sbecausetheturtlemightnotbestandinginthecenterofapatch.Itmightbenearthecornerofapatch.Forexample,
supposeyourturtleisclosetothesouthwestcornerofapatchandisfacingnortheast.Thelengthofthepatchdiagonalis
1.414…(thesquarerootoftwo),sofd 1willleavetheturtlenearthenortheastcornerofthesamepatch.
Ifyoudon’twanttohavetothinkabouttheseissues,onepossibilityistowriteyourmodelinsuchawaythatyourturtlesalways
cometorestonpatchcenters.Seenextquestion.
HowdoIkeepmyturtlesonpatchcenters?
Aturtleisonapatchcenterwhenitsxcorandycorareintegers.
Youcanmoveaturtletothecenterofitscurrentpatchwitheitherofthesetwoequivalentcommands:
move-to patch-here
setxy pxcor pycor
Butyou’llneverneedtodothatifyouneverallowturtlesoffofpatchcentersinthefirstplace.
Thesproutcommandcreatesturtlesonpatchcenters.Forexample:
ask n-of 50 patches [ sprout 1 [ face one-of neighbors4 ] ]
Anotherwayforaturtletostartonapatchcenteriswithacommandsuchasthislineofturtlecode,whichmovesittothecenter
ofarandompatch:
move-to one-of patches
Onceaturtleisonapatchcenter,aslongasitsheadingalwaysstaysanexactmultipleof90(thatistosay,duenorth,east,
south,orwest),andasitlongasitmovesforwardorbackbyintegeramounts,itwillalwayslandonpatchcenters.
SeeRandomGridWalkExample,intheCodeExamplessectionoftheModelsLibrary,toseethesecodesnippetsinuse.
patch-ahead 1isreportingthesamepatchmyturtleisalreadystandingon.Why?
Seetheanswertwoanswersup.It’sthesameissue.
Thismightnotbethemeaningof“ahead”youwereexpecting.Withpatch-ahead,youmustspecifythedistanceaheadthatyou
wanttolook.Ifyouwanttoknowthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously,itispossibletofindthat
out.SeeNextPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowdoIgivemyturtles“vision”?
Youcanusein-radiustoletaturtleseeacircularareaaroundit.
Severalprimitiveslettheturtle“look”atspecificpoints.Thepatch-aheadprimitiveisusefulforlettingaturtleseewhatisdirectly
infrontofit.Ifyouwanttheturtletolookinanotherdirectionbesidesstraightahead,trypatch-left-and-aheadandpatch-right-
and-ahead.
Ifyouwanttheturtletohaveafull“cone”ofvision,usethein-coneprimitive.
Youcanalsofindoutthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously.SeeNextPatchExample,inthe
CodeExamplessectionoftheModelsLibrary.
Canagentssensewhat’sinthedrawinglayer?
No.Ifyouwanttomakemarksthatagentscansense,usepatchcolors.
I’mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?
Seethe“Math”sectionoftheProgrammingGuideforadiscussionofthisissue.
Thedocumentationsaysthat random-float 1mightreturn0butwillneverreturn1.WhatifI
want1tobeincluded?
Itreallydoesn’tmatter.Evenif1wereapossibleresult,itwouldonlycomeupapproximately1in2^64tries,whichmeansyou’d
bewaitinghundredsofyearsbeforeitevercameupexactly1.
Nonetheless,ifyouareconvincedthatitreallymustbepossibletoget1,youcanuseprecisiontoroundyouranswertoa
certainnumberofdecimalplaces.Forexample:
print precision (random-float 1) 10
0.2745173723
(Ifyouusethismethod,notethat0and1areonlyhalfaslikelytocomeupasotheranswers.Toseewhythisisso,considerthe
casewhereyouonlykeeponedigitafterthedecimalpoint.Resultsbetween0and0.5getroundedto0,butresultsbetween0.5
and1.5getroundedto1;thelatterrangeistwiceaslarge.Ifyouwant0,0.1,0.2,…,0.9,and1toallbeequallylikely,an
alternativeistowriterandom 11 / 10 ;thisgivesall11answerswithequalprobability.)
HowcanIkeeptwoturtlesfromoccupyingthesamepatch?
SeeOneTurtlePerPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowcanIfindoutifaturtleisdead?
Whenaturtledies,itturnsintonobody.nobodyisaspecialvalueusedinNetLogousedtoindicatetheabsenceofaturtleor
patch.Soforexample:
if turtle 0 != nobody [ ... ]
Youcouldalsouseis-turtle?:
if is-turtle? turtle 0 [ ... ]
DoesNetLogohavearrays?
Nearlyallmodelsshouldjustuselistsforthis.
Theusualmotivationforusingarraysinotherprogramminglanguagesisthattheyprovidefastrandomaccess(item)and
mutation(replace-item).ButNetLogo’slists,eventhoughtheyareimmutable,nowprovidenearconstanttimeperformanceon
theseoperations.
ListsinearlierversionsofNetLogo(4.1and4.0)weresimplesingly-linkedlistsandthereforetheseoperationstooklineartime.
ThedatastructureunderlyingNetLogo’slistsnowistheimmutableVectorclassfromtheScalacollectionslibrary.Ituses32-
widehasharraymappedtries,asimplementedbyTiarkRompf,basedinpartonworkbyPhilBagwellandRichHickey.
Ifyouarecertainyouwanttouseraw,mutableJVMarraysinyourmodel,theyareprovidedbythearrayextension.Seethe
Arrays&TablessectionoftheUserManual.
DoesNetLogohavehashtablesorassociativearrays?
Yes,usingthetableextension.SeetheArrays&TablessectionoftheUserManual.
HowcanIusedifferentpatch“neighborhoods”(circular,VonNeumann,Moore,etc.)?
Thein-radiusprimitivesletsyouaccesscircularneighborhoodsofanyradius.
TheneighborsprimitivegivesyouaMooreneighborhoodofradius1,andtheneighbors4primitivegivesyouaVonNeumann
neighborhoodofradius1.
ForMooreorVonNeumannneighborhoodsofalargerradius,seeMoore&VonNeumannExampleintheCodeExamples
sectionoftheModelsLibrary.
HowcanIconvertanagentsettoalistofagents,orviceversa?
Ifyouwantthelistinaparticularorder,usethesortorsort-byprimitives.TheListssectionoftheProgrammingGuideexplains
howtodothis.SeealsoAskOrderingExample,intheCodeExamplessectionoftheModelsLibrary.
Ifyouwantthelistinarandomorder,here’show:
[self] of <agentset>
Becausealloperationsonagentsetsareinrandomorder,theresultinglistisinrandomorder.
Toconvertalistofagentstoanagentset,usetheturtle-set,patch-set,orlink-setprimitives.
HowdoIstopforeach?
Tostopaforeachfromexecutingyouneedtodefineaseparateprocedurethatcontainsonlytheforeach,forexample:
to test
foreach [1 2 3] [ i ->
if i = 2 [ stop ]
print i
]
end
Thiscodewillonlyprintthenumber1.Thestopreturnsfromthecurrentproceduresonothingaftertheforeachwillbeexecuted
either.(Iftheprocedureisareporterprocedure,usereportinsteadofstop.)
I’mtryingtomakealist.WhydoIkeepgettingtheerror“Expectedaconstant”?
Ifalistcontainsonlyconstants,youcanwriteitdownjustbyputtingsquarebracketsaroundit,like[1 2 3].
Ifyouwantyourlisttocontainitemsthatmayvaryatruntime,thelistcannotbewrittendowndirectly.Instead,youbuilditusing
thelistprimitive.
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?
Thisisnormalwhendoingmultiplerunsinparallel.Foradiscussionoftheissue,seethesectiononparallelrunsinthe
BehaviorSpaceGuidesectionoftheUserManual.
HowdoImeasurerunseverynticks?
Userepeatinyourexperiment’sgocommands,e.g.:
repeat 10 [ go ]
tomeasuretherunafterevery10ticks.Essentiallyyouaremakingoneexperimentstepequal10ticks.
I’mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn’twork.Why?
It’sprobablybecauseyoursetupcommandsorsetupprocedureareusingclear-all,causingthevaluessetbyBehaviorSpace
tobecleared.
Onepossibleworkaroundistochangeyourexperiment’ssetupcommandstopreservethevalueofthevariable,e.g.:
let old-var1 var1
setup
set var1 old-var1
Thisworksbecauseevenclear-alldoesn’tclearthevaluesoflocalvariablesmadewithlet
Anotherpossibleworkaroundistochangeyourmodel’ssetupproceduretousemorespecificclearingcommandstoclearonly
whatyouwantcleared.
NetLogo3D
DoesNetLogoworkwithmystereoscopicdevice?
NetLogosupportsfullscreenexclusivemode.Ifthatisallyourdeviceneedsthen,possiblyyes.However,itcanbetrickytogetit
working.Wedon’thaveanysuchdevicessoitisdifficultforustomaketheprocesseasier.Ifyourdeviceneedssomethingelse,
forexample,quadbuffersenabled,theanswerisprobablyno.
Extensions
I’mwritinganextension.Whydoesthecompilersayitcan’tfind org.nlogo.api?
YouneedtoaddNetLogo.jartoyourclasspathwhencompiling.NetLogo.jarisincludedwithNetLogo.
NetLogoDictionary
NetLogo6.0.4UserManual
Alphabetical:ABCDEFGHIJLMNOPRSTUVWXY->
Categories:Turtle-Patch-Links-Agentset-Color-AnonymousProcedures-Control/Logic-World
Perspective-Input/Output-File-List-String-Math-Plotting-System-HubNet
Special:Variables-Keywords-Constants
Categories
Thisisanapproximategrouping.Rememberthataturtle-relatedprimitivemightstillbeusedbypatchesortheobserver,andviceversa.To
seewhichagents(turtles,patches,links,observer)canactuallyrunaprimitive,consultitsdictionaryentry.
Turtle-related
back(bk)<breeds>-at<breeds>-here<breeds>-oncan-move?clear-turtles(ct)create-<breeds>create-ordered-<breeds>create-ordered-
turtles(cro)create-turtles(crt)diedistancedistancexydownhilldownhill4dxdyfacefacexyforward(fd)hatchhatch-<breeds>hide-turtle(ht)
homeinspectis-<breed>?is-turtle?jumplayout-circleleft(lt)move-tomyselfnobodyno-turtlesofotherpatch-aheadpatch-atpatch-at-
heading-and-distancepatch-herepatch-left-and-aheadpatch-right-and-aheadpen-down(pd)pen-erase(pe)pen-up(pu)random-xcor
random-ycorright(rt)selfset-default-shape__set-line-thicknesssetxyshapesshow-turtle(st)sproutsprout-<breeds>stampstamp-erase
stop-inspectingsubjectsubtract-headingstietowardstowardsxyturtleturtle-setturtlesturtles-atturtles-hereturtles-onturtles-ownuntieuphill
uphill4
Patch-related
clear-patches(cp)diffusediffuse4distancedistancexyimport-pcolorsimport-pcolors-rgbinspectis-patch?myselfneighborsneighbors4
nobodyno-patchesofotherpatchpatch-atpatch-aheadpatch-at-heading-and-distancepatch-herepatch-left-and-aheadpatch-right-and-
aheadpatch-setpatchespatches-ownrandom-pxcorrandom-pycorselfsproutsprout-<breeds>stop-inspectingsubjectturtles-here
Link-related
both-endsclear-linkscreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-tocreate-<breeds>-tocreate-<breed>-withcreate-
<breeds>-withcreate-link-fromcreate-links-fromcreate-link-tocreate-links-tocreate-link-withcreate-links-withdiehide-linkin-<breed>-
neighbor?in-<breed>-neighborsin-<breed>-fromin-link-neighbor?in-link-neighborsin-link-fromis-directed-link?is-link?is-link-set?is-<link-
breed>?is-undirected-link?layout-radiallayout-springlayout-tutte<breed>-neighbor?<breed>-neighbors<breed>-withlink-headinglink-
lengthlink-neighbor?linklinkslinks-own<link-breeds>-ownlink-neighborslink-withmy-<breeds>my-in-<breeds>my-in-linksmy-linksmy-
out-<breeds>my-out-linksno-linksother-endout-<breed>-neighbor?out-<breed>-neighborsout-<breed>-toout-link-neighbor?out-link-
neighborsout-link-toshow-linktieuntie
Agentset
all?any?askask-concurrentat-points<breeds>-at<breeds>-here<breeds>-oncountin-conein-radiusis-agent?is-agentset?is-patch-set?
is-turtle-set?link-setmax-n-ofmax-one-ofmember?min-n-ofmin-one-ofn-ofneighborsneighbors4no-linksno-patchesno-turtlesofone-of
otherpatch-setpatchessortsort-bysort-onturtle-setturtlesturtles-atturtles-hereturtles-onwithwith-maxwith-min
Color
approximate-hsbapproximate-rgbbase-colorscolorextract-hsbextract-rgbhsbimport-pcolorsimport-pcolors-rgbpcolorrgbscale-color
shade-of?wrap-color
Controlflowandlogic
andaskask-concurrentcarefullyenderrorerror-messageeveryififelseifelse-valueletloopnotorrepeatreportrunrunresult;(semicolon)set
stopstartuptoto-reportwaitwhilewith-local-randomnesswithout-interruptionxor
AnonymousProcedures
->(anonymousprocedure)filterforeachis-anonymous-command?is-anonymous-reporter?mapn-valuesreducerunrunresultsort-by
World
clear-all(ca)clear-drawing(cd)clear-globalsclear-patches(cp)clear-ticksclear-turtles(ct)displayimport-drawingimport-pcolorsimport-
pcolors-rgbno-displaymax-pxcormax-pycormin-pxcormin-pycorpatch-sizereset-ticksresize-worldset-patch-sizestop-inspecting-dead-
agentsticktick-advanceticksworld-widthworld-height
Perspective
followfollow-mereset-perspective(rp)rideride-mesubjectwatchwatch-me
HubNet
hubnet-broadcasthubnet-broadcast-clear-outputhubnet-broadcast-messagehubnet-clear-overridehubnet-clear-overrideshubnet-clients-list
hubnet-enter-message?hubnet-exit-message?hubnet-kick-all-clientshubnet-kick-clienthubnet-fetch-messagehubnet-messagehubnet-
message-sourcehubnet-message-taghubnet-message-waiting?hubnet-resethubnet-reset-perspectivehubnet-sendhubnet-send-clear-
outputhubnet-send-followhubnet-send-messagehubnet-send-overridehubnet-send-watch
Input/output
beepclear-outputdate-and-timeexport-viewexport-interfaceexport-outputexport-plotexport-all-plotsexport-worldimport-drawingimport-
pcolorsimport-pcolors-rgbimport-worldmouse-down?mouse-inside?mouse-xcormouse-ycoroutput-printoutput-showoutput-typeoutput-
writeprintread-from-stringreset-timerset-current-directoryshowtimertypeuser-directoryuser-fileuser-new-fileuser-inputuser-message
user-one-ofuser-yes-or-no?write
File
file-at-end?file-closefile-close-allfile-deletefile-exists?file-flushfile-openfile-printfile-readfile-read-charactersfile-read-linefile-showfile-
typefile-writeuser-directoryuser-fileuser-new-file
List
but-firstbut-lastempty?filterfirstforeachfputhistograminsert-itemis-list?itemlastlengthlistlputmapmaxmember?minmodesn-ofn-
valuesofpositionone-ofrangereduceremoveremove-duplicatesremove-itemreplace-itemreversesentenceshufflesortsort-bysort-on
sublist
String
Operators(<,>,=,!=,<=,>=)but-firstbut-lastempty?firstinsert-itemis-string?itemlastlengthmember?positionremoveremove-itemread-
from-stringreplace-itemreversesubstringword
Mathematical
ArithmeticOperators(+,*,-,/,^,<,>,=,!=,<=,>=)absacosasinatanceilingcoseexpfloorintis-number?lnlogmaxmeanmedianminmod
modesnew-seedpiprecisionrandomrandom-exponentialrandom-floatrandom-gammarandom-normalrandom-poissonrandom-seed
remainderroundsinsqrtstandard-deviationsubtract-headingssumtanvariance
Plotting
autoplot?auto-plot-offauto-plot-onclear-all-plotsclear-plotcreate-temporary-plot-penexport-plotexport-all-plotshistogramplotplot-name
plot-pen-exists?plot-pen-downplot-pen-resetplot-pen-upplot-x-maxplot-x-minplot-y-maxplot-y-minplotxyset-current-plotset-current-plot-
penset-histogram-num-barsset-plot-background-colorset-plot-pen-colorset-plot-pen-intervalset-plot-pen-modeset-plot-x-rangeset-plot-y-
rangesetup-plotsupdate-plots
BehaviorSpace
behaviorspace-experiment-namebehaviorspace-run-number
System
netlogo-versionnetlogo-web?
Built-InVariables
Turtles
breedcolorheadinghidden?labellabel-colorpen-modepen-sizeshapesizewhoxcorycor
Patches
pcolorplabelplabel-colorpxcorpycor
Links
breedcolorend1end2hidden?labellabel-colorshapethicknesstie-mode
Other
->
Keywords
breeddirected-link-breedendextensionsglobals__includeslinks-ownpatches-owntoto-reportturtles-ownundirected-link-breed
Constants
MathematicalConstants
e=2.718281828459045
pi=3.141592653589793
BooleanConstants
false
true
ColorConstants
Since1.0
Since1.3
Since4.0
Since1.0
Since2.0
black=0
gray=5
white=9.9
red=15
orange=25
brown=35
yellow=45
green=55
lime=65
turquoise=75
cyan=85
sky=95
blue=105
violet=115
magenta=125
pink=135
SeetheColorssectionoftheProgrammingGuideformoredetails.
A
abs
absnumber
Reportstheabsolutevalueofnumber.
show abs -7
=> 7
show abs 5
=> 5
acos
acosnumber
Reportsthearccosine(inversecosine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesinthe
range0to180.
all?
all?agentset[reporter]
Reportstrueifalloftheagentsintheagentsetreporttrueforthegivenreporter.Otherwisereportsfalseassoonasacounterexampleis
found.
Iftheagentsetisempty,reportstrue.
Thereportermustreportabooleanvalueforeveryagent(eithertrueorfalse),otherwiseanerroroccurs.
if all? turtles [color = red]
[ show "every turtle is red!" ]
Seealsoany?.
and
condition1andcondition2
Reportstrueifbothcondition1andcondition2aretrue.
Notethatifcondition1isfalse,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) and (pycor > 0)
[ set pcolor blue ] ;; the upper-right quadrant of
;; patches turn blue
any?
any?agentset
Reportstrueifthegivenagentsetisnon-empty,falseotherwise.
Equivalentto"countagentset>0",butmoreefficient(andarguablymorereadable).
if any? turtles with [color = red]
[ show "at least one turtle is red!" ]
Note:nobodyisnotanagentset.Youonlygetnobodybackinsituationswhereyouwereexpectingasingleagent,notawholeagentset.If
Since4.0
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
any?getsnobodyasinput,anerrorresults.
Seealsoall?,nobody.
approximate-hsb
approximate-hsbhuesaturationbrightness
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheHSBspectrum,inNetLogo's
colorspace.
Thefirstvalue(hue)shouldbeintherangeof0to360,thesecondandthird(saturationandbrightness)intherangebetween0and100.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.
show approximate-hsb 0 0 0
=> 0 ;; (black)
show approximate-hsb 180 57.143 76.863
=> 85 ;; (cyan)
Seealsoextract-hsb,approximate-rgb,extract-rgb.
approximate-rgb
approximate-rgbredgreenblue
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheRGBspectrum,inNetLogo's
colorspace.
Allthreeinputsshouldbeintherange0to255.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.(Seeapproximate-hsb
foradescriptionofwhatpartsoftheHSBcolorspaceNetLogocolorscover;thisisdifficulttocharacterizeinRGBterms.)
show approximate-rgb 0 0 0
=> 0 ;; black
show approximate-rgb 0 255 255
=> 85.2 ;; cyan
Seealsoextract-rgb,approximate-hsb,andextract-hsb.
ArithmeticOperators
+
*
-
/
^
<
>
=
!=
<=
>=
Alloftheseoperatorstaketwoinputs,andallactas"infixoperators"(goingbetweenthetwoinputs,asinstandardmathematicaluse).
NetLogocorrectlysupportsorderofoperationsforinfixoperators.
Theoperatorsworkasfollows:+isaddition,*ismultiplication,-issubtraction,/isdivision,^isexponentiation,<islessthan,>isgreater
than,=isequalto,!=isnotequalto,<=islessthanorequal,>=isgreaterthanorequal.
Notethatthesubtractionoperator(-)alwaystakestwoinputsunlessyouputparenthesesaroundit,inwhichcaseitcantakeoneinput.For
example,totakethenegativeofx,write(-x),withtheparentheses.
Allofthecomparisonoperatorsalsoworkonstrings.
Allofthecomparisonoperatorsworkonagents.Turtlesarecomparedbywhonumber.Patchesarecomparedtoptobottomlefttoright,so
patch010islessthanpatch09andpatch90islessthanpatch100.Linksareorderedbyendpointsandincaseofatiebybreed.Solink
09isbeforelink110astheend1issmaller,andlink08islessthanlink09.Iftherearemultiplebreedsoflinksunbreededlinkswillcome
beforebreededlinksofthesameendpointsandbreededlinkswillbesortedintheordertheyaredeclaredintheCodetab.
Agentsetscanbetestedforequalityorinequality.Twoagentsetsareequaliftheyarethesametype(turtleorpatch)andcontainthesame
agents.
IfyouarenotsurehowNetLogowillinterpretyourcode,youshouldaddparentheses.
show 5 * 6 + 6 / 3
=> 32
show 5 * (6 + 6) / 3
=> 20
Manyextensionobjectsmaybetestedforequalityandinequalityusing=and!=.Forinstance,thearray,matrix,andtableobjectsreturnedby
theirrespectiveextensionsmaybecomparedforequality/inequality.Extensionobjectsmaynotbetestedusing<,>,<=,or>=.
Since1.3
Since1.0
Since4.0
Since1.0
Since1.0
asin
asinnumber
Reportsthearcsine(inversesine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesintherange
-90to90.
ask
askagentset[commands]
askagent[commands]
Thespecifiedagentoragentsetrunsthegivencommands.
ask turtles [ fd 1 ]
;; all turtles move forward one step
ask patches [ set pcolor red ]
;; all patches turn red
ask turtle 4 [ rt 90 ]
;; only the turtle with id 4 turns right
Note:onlytheobservercanaskallturtlesorallpatches.Thispreventsyoufrominadvertentlyhavingallturtlesaskallturtlesorallpatches
askallpatches,whichisacommonmistaketomakeifyou'renotcarefulaboutwhichagentswillrunthecodeyouarewriting.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
ask-concurrent
ask-concurrentagentset[commands]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitnewmodels.
Theagentsinthegivenagentsetrunthegivencommands,usingaturn-takingmechanismtoproducesimulatedconcurrency.SeetheAsk-
ConcurrentsectionoftheProgrammingGuidefordetailsonhowthisworks.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
Seealsowithout-interruption.
at-points
agentsetat-points[[x1y1][x2y2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesatthegivencoordinates(relativetothisagent).The
coordinatesarespecifiedasalistoftwo-itemlists,wherethetwoitemsarethexandyoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inotherwords,thepointsaretakenasabsolutepatch
coordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,andnotfromthecenterofthepatchundertheturtle.
ask turtles at-points [[2 4] [1 2] [10 15]]
[ fd 1 ] ;; only the turtles on the patches at the
;; coordinates (2,4), (1,2) and (10,15),
;; relative to the caller, move
atan
atanxy
Convertsxandyoffsetstoaturtleheadingindegrees(from0to360).
NotethatthisversionofatanisdesignedtoconformtothegeometryoftheNetLogoworld,whereaheadingof0isstraightup,90istothe
right,andsoonclockwisearoundthecircle.(Normallyingeometryanangleof0isright,90isup,andsoon,counterclockwisearoundthe
circle,andatanwouldbedefinedaccordingly.)
Whenyis0:ifxispositive,itreports90;ifxisnegative,itreports270;ifxiszero,yougetanerror.
show atan 1 -1
=> 135
show atan -1 1
=> 315
crt 1 [ set heading 30 fd 1 print atan xcor ycor ]
=> 30
Inthefinalexample,notethattheresultofatanequalstheturtle'sheading.
Ifyoueverneedtoconvertaturtleheading(obtainedwithatanorotherwise)toanormalmathematicalangle,thefollowingshouldbehelpful:
to-report heading-to-angle [ h ]
report (90 - h) mod 360
end
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since4.0
Since2.1
Since5.2
Since4.1.1
autoplot?
autoplot?
Reportstrueifauto-plottingisonforthecurrentplot,falseotherwise.
auto-plot-off
auto-plot-on
auto-plot-off
auto-plot-on
ThispairofcommandsisusedtocontroltheNetLogofeatureofauto-plottinginthecurrentplot.Auto-plottingwillautomaticallyupdatethex
andyaxesoftheplotwheneverthecurrentpenexceedstheseboundaries.Itisusefulwhenwantingtoshowallplottedvaluesinthecurrent
plot,regardlessofthecurrentplotranges.
B
back
bk
backnumber
Theturtlemovesbackwardbynumbersteps.(Ifnumberisnegative,theturtlemovesforward.)
Turtlesusingthisprimitivecanmoveamaximumofoneunitpertimeincrement.Sobk 0.5andbk 1bothtakeoneunitoftime,butbk 3
takesthree.
Iftheturtlecannotmovebackwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof
1asitcanandstop.
Seealsoforward,jump,can-move?.
base-colors
base-colors
Reportsalistofthe14basicNetLogohues.
print base-colors
=> [5 15 25 35 45 55 65 75 85 95 105 115 125 135]
ask turtles [ set color one-of base-colors ]
;; each turtle turns a random base color
ask turtles [ set color one-of remove gray base-colors ]
;; each turtle turns a random base color except for gray
beep
beep
Emitsabeep.Notethatthebeepsoundsimmediately,soseveralbeepcommandsinclosesuccessionmayproduceonlyoneaudiblesound.
Example:
beep ;; emits one beep
repeat 3 [ beep ] ;; emits 3 beeps at once,
;; so you only hear one sound
repeat 3 [ beep wait 0.1 ] ;; produces 3 beeps in succession,
;; separated by 1/10th of a second
Whenrunningheadless,thiscommandhasnoeffect.
behaviorspace-experiment-name
behaviorspace-experiment-name
Reportsthecurrentexperimentnameinthecurrentexperiment.
IfnoBehaviorSpaceexperimentisrunning,reports"".
behaviorspace-run-number
behaviorspace-run-number
ReportsthecurrentrunnumberinthecurrentBehaviorSpaceexperiment,startingat1.
IfnoBehaviorSpaceexperimentisrunning,reports0.
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
both-ends
both-ends
Reportstheagentsetofthe2nodesconnectedbythislink.
crt 2
ask turtle 0 [ create-link-with turtle 1 ]
ask link 0 1 [
ask both-ends [ set color red ] ;; turtles 0 and 1 both turn red
]
breed
breed
Thisisabuilt-inturtleandlinkvariable.Itholdstheagentsetofallturtlesorlinksofthesamebreedasthisturtleorlink.(Forturtlesorlinks
thatdonothaveanyparticularbreed,thisistheturtlesagentsetofallturtlesorthelinksagentsetofalllinksrespectively.)
Youcansetthisvariabletochangeaturtleorlink'sbreed.(Whenaturtlechangesbreeds,itsshapeisresettothedefaultshapeforthat
breed.Seeset-default-shape.)
Seealsobreed,directed-link-breed,undirected-link-breed
Example:
breed [cats cat]
breed [dogs dog]
;; turtle code:
if breed = cats [ show "meow!" ]
set breed dogs
show "woof!"
directed-link-breed [ roads road ]
;; link code
if breed = roads [ set color gray ]
breed
breed[<breeds><breed>]
Thiskeyword,liketheglobals,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningoftheCodetab,beforeany
proceduredefinitions.Itdefinesabreed.Thefirstinputdefinesthenameoftheagentsetassociatedwiththebreed.Thesecondinputdefines
thenameofasinglememberofthebreed.
Anyturtleofthegivenbreed:
ispartoftheagentsetnamedbythebreedname
hasitsbreedbuilt-invariablesettothatagentset
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlytheturtlesofaparticularbreed.
breed [mice mouse]
breed [frogs frog]
to setup
clear-all
create-mice 50
ask mice [ set color white ]
create-frogs 50
ask frogs [ set color green ]
show [breed] of one-of mice ;; prints mice
show [breed] of one-of frogs ;; prints frogs
end
show mouse 1
;; prints (mouse 1)
show frog 51
;; prints (frog 51)
show turtle 51
;; prints (frog 51)
Seealsoglobals,patches-own,turtles-own,<breeds>-own,create-<breeds>,<breeds>-at,<breeds>-here.
but-first
butfirst
bf
but-last
butlast
bl
but-firstlist
but-firststring
but-lastlist
but-laststring
Since3.1
Since2.1
Since1.0
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since5.2
Whenusedonalist,but-firstreportsallofthelistitemsoflistexceptthefirst,andbut-lastreportsallofthelistitemsoflistexceptthelast.
Onstrings,but-firstandbut-lastreportashorterstringomittingthefirstorlastcharacteroftheoriginalstring.
;; mylist is [2 4 6 5 8 12]
set mylist but-first mylist
;; mylist is now [4 6 5 8 12]
set mylist but-last mylist
;; mylist is now [4 6 5 8]
show but-first "string"
;; prints "tring"
show but-last "string"
;; prints "strin"
C
can-move?
can-move?distance
Reportstrueifthisturtlecanmovedistanceinthedirectionitisfacingwithoutviolatingthetopology;reportsfalseotherwise.
Itisequivalentto:
patch-ahead distance != nobody
carefully
carefully[commands1][commands2]
Runscommands1.Ifaruntimeerroroccursinsidecommands1,NetLogowon'tstopandalerttheuserthatanerroroccurred.Itwillsuppress
theerrorandruncommands2instead.
Theerror-messagereportercanbeusedincommands2tofindoutwhaterrorwassuppressedincommands1.Seeerror-message.
carefully [ print one-of [1 2 3] ] [ print error-message ]
=> 3
observer> carefully [ print one-of [] ] [ print error-message ]
=> ONE-OF got an empty list as input.
ceiling
ceilingnumber
Reportsthesmallestintegergreaterthanorequaltonumber.
show ceiling 4.5
=> 5
show ceiling -4.5
=> -4
Seealsofloor,round,precision.
clear-all
ca
clear-all
Combinestheeffectsofclear-globals,clear-ticks,clear-turtles,clear-patches,clear-drawing,clear-all-plots,andclear-output.
clear-all-plots
clear-all-plots
Clearseveryplotinthemodel.Seeclear-plotformoreinformation.
clear-drawing
cd
clear-drawing
Clearsalllinesandstampsdrawnbyturtles.
clear-globals
Since4.0
Since1.0
Since1.0
Since1.0
Since5.0
Since1.0
Since1.0
clear-globals
Setsallglobalvariablesto0.
clear-links
clear-links
Killsalllinks.
Seealsodie.
clear-output
clear-output
Clearsalltextfromthemodel'soutputarea,ifithasone.Otherwisedoesnothing.
clear-patches
cp
clear-patches
Clearsthepatchesbyresettingallpatchvariablestotheirdefaultinitialvalues,includingsettingtheircolortoblack.
clear-plot
clear-plot
Inthecurrentplotonly,resetsallplotpens,deletesalltemporaryplotpens,resetstheplottoitsdefaultvalues(forxrange,yrange,etc.),and
resetsallpermanentplotpenstotheirdefaultvalues.ThedefaultvaluesfortheplotandforthepermanentplotpensaresetintheplotEdit
dialog,whichisdisplayedwhenyouedittheplot.Iftherearenoplotpensafterdeletingalltemporarypens,thatistosayifthereareno
permanentplotpens,adefaultplotpenwillbecreatedwiththefollowinginitialsettings:
Pen:down
Color:black
Mode:0(linemode)
Name:"default"
Interval:1
Seealsoclear-all-plots.
clear-ticks
clear-ticks
Clearsthetickcounter.
Doesnotsetthecountertozero.Afterthiscommandruns,thetickcounterhasnovalue.Attemptingtoaccessorupdateitisanerroruntil
reset-ticksiscalled.
Seealsoreset-ticks.
clear-turtles
ct
clear-turtles
Killsallturtles.
Alsoresetsthewhonumbering,sothenextturtlecreatedwillbeturtle0.
Seealsodie.
color
color
Thisisabuilt-inturtleorlinkvariable.Itholdsthecoloroftheturtleorlink.Youcansetthisvariabletomaketheturtleorlinkchangecolor.
ColorcanberepresentedeitherasaNetLogocolor(asinglenumber),oranRGBcolor(alistof3numbers).SeedetailsintheColorssection
oftheProgrammingGuide.
Since1.0
Since1.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Seealsopcolor.
cos
cosnumber
Reportsthecosineofthegivenangle.Assumestheangleisgivenindegrees.
show cos 180
=> -1
count
countagentset
Reportsthenumberofagentsinthegivenagentset.
show count turtles
;; prints the total number of turtles
show count patches with [pcolor = red]
;; prints the total number of red patches
create-ordered-turtles
cro
create-ordered-turtlesnumber
create-ordered-turtlesnumber[commands]
create-ordered<breeds>number
create-ordered<breeds>number[commands]
Createsnumbernewturtles.Newturtlesstartatposition(0,0),arecreatedwiththe14primarycolors,andhaveheadingsfrom0to360,
evenlyspaced.
Ifthecreate-ordered-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,or
whatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
cro 100 [ fd 10 ] ;; makes an evenly spaced circle
create-<breed>-to
create-<breeds>-to
create-<breed>-from
create-<breeds>-from
create-<breed>-with
create-<breeds>-with
create-link-to
create-links-to
create-link-from
create-links-from
create-link-with
create-links-with
create-<breed>-toturtle
create-<breed>-toturtle[commands]
create-<breed>-fromturtle
create-<breed>-fromturtle[commands]
create-<breed>-withturtle
create-<breed>-withturtle[commands]
create-<breeds>-toturtleset
create-<breeds>-toturtleset[commands]
create-<breeds>-fromturtleset
create-<breeds>-fromturtleset[commands]
create-<breeds>-withturtleset
create-<breeds>-withturtleset[commands]
create-link-toturtle
create-link-toturtle[commands]
create-link-fromturtle
create-link-fromturtle[commands]
create-link-withturtle
create-link-withturtle[commands]
create-links-toturtleset
create-links-toturtleset[commands]
create-links-fromturtleset
create-links-fromturtleset[commands]
create-links-withturtleset
create-links-withturtleset[commands]
Since1.0
Since1.0
Since1.1
Usedforcreatingbreededandunbreededlinksbetweenturtles.
create-link-withcreatesanundirectedlinkbetweenthecallerandagent.create-link-tocreatesadirectedlinkfromthecallertoagent.
create-link-fromcreatesadirectedlinkfromagenttothecaller.
Whenthepluralformofthebreednameisused,anagentsetisexpectedinsteadofanagentandlinksarecreatedbetweenthecallerandall
agentsintheagentset.
Theoptionalcommandblockisthesetofcommandseachnewlyformedlinkruns.(Thelinksarecreatedallatoncethenrunoneatatime,in
randomorder.)
Anodecannotbelinkedtoitself.Also,youcannothavemorethanoneundirectedlinkofthesamebreedbetweenthesametwonodes,nor
canyouhavemorethanonedirectedlinkofthesamebreedgoinginthesamedirectionbetweentwonodes.
Ifyoutrytocreatealinkwhereone(ofthesamebreed)alreadyexists,nothinghappens.Ifyoutrytocreatealinkfromaturtletoitselfyouget
aruntimeerror.
to setup
clear-all
create-turtles 5
;; turtle 1 creates links with all other turtles
;; the link between the turtle and itself is ignored
ask turtle 0 [ create-links-with other turtles ]
show count links ;; shows 4
;; this does nothing since the link already exists
ask turtle 0 [ create-link-with turtle 1 ]
show count links ;; shows 4 since the previous link already existed
ask turtle 2 [ create-link-with turtle 1 ]
show count links ;; shows 5
end
directed-link-breed [red-links red-link]
undirected-link-breed [blue-links blue-link]
to setup
clear-all
create-turtles 5
;; create links in both directions between turtle 0
;; and all other turtles
ask turtle 0 [ create-red-links-to other turtles ]
ask turtle 0 [ create-red-links-from other turtles ]
show count links ;; shows 8
;; now create undirected links between turtle 0 and other turtles
ask turtle 0 [ create-blue-links-with other turtles ]
show count links ;; shows 12
end
create-turtles
crt
create-turtlesnumber
create-turtlesnumber[commands]
create-<breeds>number
create-<breeds>number[commands]
Createsnumbernewturtlesattheorigin.Newturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe14primary
colors.
Ifthecreate-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,or
whatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
crt 100 [ fd 10 ] ;; makes a randomly spaced circle
breed [canaries canary]
breed [snakes snake]
to setup
clear-all
create-canaries 50 [ set color yellow ]
create-snakes 50 [ set color green ]
end
Seealsohatch,sprout.
create-temporary-plot-pen
create-temporary-plot-penstring
Anewtemporaryplotpenwiththegivennameiscreatedinthecurrentplotandsettobethecurrentpen.
Fewmodelswillwanttousethisprimitive,becausealltemporarypensdisappearwhenclear-plotorclear-all-plotsarecalled.Thenormalway
tomakeapenistomakeapermanentpenintheplot'sEditdialog.
Ifapenwiththatnamealreadyexistsinthecurrentplot,nonewpeniscreated,andtheexistingpenissettothecurrentpen.
Thenewtemporaryplotpenhasthefollowinginitialsettings:
Since3.0
Since1.0
Since1.0
Since1.0
Pen:down
Color:black
Mode:0(linemode)
Interval:1
See:clear-plot,clear-all-plots,andset-current-plot-pen.
D
date-and-time
date-and-time
Reportsastringcontainingthecurrentdateandtime.Theformatisshownbelow.Allfieldsarefixedwidth,sotheyarealwaysatthesame
locationsinthestring.Thepotentialresolutionoftheclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfrom
systemtosystem,dependingonthecapabilitiesoftheunderlyingJavaVirtualMachine.)
show date-and-time
=> "01:19:36.685 PM 19-Sep-2002"
die
die
Theturtleorlinkdies.
if xcor > 20 [ die ]
;; all turtles with xcor greater than 20 die
ask links with [color = blue] [ die ]
;; all the blue links will die
Adeadagentceasestoexist.Theeffectsofthisinclude:
Theagentwillnotexecuteanyfurthercode.Soifyouwriteask turtles [ die print "last words?" ] ,nolastwordswillbeprinted,
becausetheturtlesarealreadydeadbeforetheyhaveachancetoprintanything.
Theagentwilldisappearfromanyagentsetsitwasin,reducingthesizeofthoseagentsetsbyone.
Anyvariablethatwasstoringtheagentwillnowinsteadhavenobodyinit.Soforexamplelet x one-of turtles ask x [ die ] print x
printsnobody.
Ifthedeadagentwasaturtle,everylinkconnectedtoitalsodies.
Iftheobserverwaswatchingorfollowingtheagent,theobserver'sperspectiveresets,asifreset-perspectivehadbeenrun.
Seealso:clear-turtlesclear-links
diffuse
diffusepatch-variablenumber
Tellseachpatchtogiveequalsharesof(number*100)percentofthevalueofpatch-variabletoitseightneighboringpatches.number
shouldbebetween0and1.Regardlessoftopologythesumofpatch-variablewillbeconservedacrosstheworld.(Ifapatchhasfewerthan
eightneighbors,eachneighborstillgetsaneighthshare;thepatchkeepsanyleftovershares.)
Notethatthisisanobservercommandonly,eventhoughyoumightexpectittobeapatchcommand.(Thereasonisthatitactsonallthe
patchesatonce--patchcommandsactonindividualpatches.)
diffuse chemical 0.5
;; each patch diffuses 50% of its variable
;; chemical to its neighboring 8 patches. Thus,
;; each patch gets 1/8 of 50% of the chemical
;; from each neighboring patch.)
diffuse4
diffuse4patch-variablenumber
Likediffuse,butonlydiffusestothefourneighboringpatches(tothenorth,south,east,andwest),nottothediagonalneighbors.
diffuse4 chemical 0.5
;; each patch diffuses 50% of its variable
;; chemical to its neighboring 4 patches. Thus,
;; each patch gets 1/4 of 50% of the chemical
;; from each neighboring patch.)
directed-link-breed
directed-link-breed[<link-breeds><link-breed>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.It
Since1.0
Since1.0
Since1.0
definesadirectedlinkbreed.LinksofaparticularbreedarealwaysalldirectedorallundirectedThefirstinputdefinesthenameofthe
agentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.Directedlinkscanbecreated
usingcreate-link(s)-to,andcreate-link(s)-from,butnotcreate-link(s)-with
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreedname
hasitsbuilt-invariablebreedsettothatagentset
isdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
directed-link-breed [streets street]
directed-link-breed [highways highway]
to setup
clear-all
crt 2
;; create a link from turtle 0 to turtle 1
ask turtle 0 [ create-street-to turtle 1 ]
;; create a link from turtle 1 to turtle 0
ask turtle 0 [ create-highway-from turtle 1 ]
end
ask turtle 0 [ show one-of my-in-links ]
;; prints (street 0 1)
ask turtle 0 [ show one-of my-out-links ]
;; prints (highway 1 0)
Seealsobreed,undirected-link-breed
display
display
Causestheviewtobeupdatedimmediately.(Exception:iftheuserisusingthespeedslidertofast-forwardthemodel,thentheupdatemay
beskipped.)
Alsoundoestheeffectoftheno-displaycommand,sothatifviewupdatesweresuspendedbythatcommand,theywillresume.
no-display
ask turtles [ jump 10 set color blue set size 5 ]
display
;; turtles move, change color, and grow, with none of
;; their intermediate states visible to the user, only
;; their final state
Evenifno-displaywasnotused,"display"canstillbeuseful,becauseordinarilyNetLogoisfreetoskipsomeviewupdates,sothatfewer
totalupdatestakeplace,sothatmodelsrunfaster.Thiscommandletsyouforceaviewupdate,sowhateverchangeshavetakenplaceinthe
worldarevisibletotheuser.
ask turtles [ set color red ]
display
ask turtles [ set color blue]
;; turtles turn red, then blue; use of "display" forces
;; red turtles to appear briefly
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsono-display.
distance
distanceagent
Reportsthedistancefromthisagenttothegiventurtleorpatch.
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedges
oftheworld)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
ask turtles [ show max-one-of turtles [distance myself] ]
;; each turtle prints the turtle farthest from itself
distancexy
distancexyxy
Reportsthedistancefromthisagenttothepoint(x,y).
Thedistancefromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedgesofthe
world)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
if (distancexy 0 0) > 10
[ set color green ]
;; all turtles more than 10 units from
;; the center of the world turn green.
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since4.0
Since4.0
downhill
downhill4
downhillpatch-variable
downhill4patch-variable
Movestheturtletotheneighboringpatchwiththelowestvalueforpatch-variable.Ifnoneighboringpatchhasasmallervaluethanthe
currentpatch,theturtlestaysput.Iftherearemultiplepatcheswiththesamelowestvalue,theturtlepicksonerandomly.Non-numeric
valuesareignored.
downhillconsiderstheeightneighboringpatches;downhill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
move-to patch-here ;; go to patch center
let p min-one-of neighbors [patch-variable] ;; or neighbors4
if [patch-variable] of p < patch-variable [
face p
move-to p
]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(downhill)or90(downhill4).
Seealsouphill,uphill4.
dx
dy
dx
dy
Reportsthex-incrementory-increment(theamountbywhichtheturtle'sxcororycorwouldchange)iftheturtleweretotakeonestep
forwardinitscurrentheading.
Note:dxissimplythesineoftheturtle'sheading,anddyissimplythecosine.(Ifthisisthereverseofwhatyouexpected,it'sbecausein
NetLogoaheadingof0isnorthand90iseast,whichisthereverseofhowanglesareusuallydefinedingeometry.)
Note:InearlierversionsofNetLogo,theseprimitiveswereusedinmanysituationswherethenewpatch-aheadprimitiveisnowmore
appropriate.
E
empty?
empty?list
empty?string
Reportstrueifthegivenlistorstringisempty,falseotherwise.
Note:theemptylistiswritten[].Theemptystringiswritten"".
end
end
Usedtoconcludeaprocedure.Seetoandto-report.
end1
end1
Thisisabuilt-inlinkvariable.Itindicatesthefirstendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethesourceforundirectedlinks
itwillalwaysbetheturtlewiththelowerwhonumber.Youcannotsetend1.
crt 2
ask turtle 0
[ create-link-to turtle 1 ]
ask links
[ show end1 ] ;; shows turtle 0
end2
end2
Thisisabuilt-inlinkvariable.Itindicatesthesecondendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethedestinationfor
undirectedlinksitwillalwaysbetheturtlewiththehigherwhonumber.Youcannotsetend2.
Since5.0
Since2.1
Since1.0
Since1.0
Since3.0
Since2.0
Since1.0
Since1.0
Since1.2.1
Since1.0
crt 2
ask turtle 1
[ create-link-with turtle 0 ]
ask links
[ show end2 ] ;; shows turtle 1
error
errorvalue
Causesaruntimeerrortooccur.
Thegivenvalueisconvertedtoastring(ifitisn'tonealready)andusedastheerrormessage.
Seealsoerror-message,carefully.
error-message
error-message
Reportsastringdescribingtheerrorthatwassuppressedbycarefully.
Thisreportercanonlybeusedinthesecondblockofacarefullycommand.
Seealsoerror,carefully.
every
everynumber[commands]
Runsthegivencommandsonlyifit'sbeenmorethannumbersecondssincethelasttimethisagentrantheminthiscontext.Otherwise,the
commandsareskipped.
Byitself,everydoesn'tmakecommandsrunoverandoveragain.Youneedtouseeveryinsidealoop,orinsideaforeverbutton,ifyouwant
thecommandsrunoverandoveragain.everyonlylimitshowoftenthecommandsrun.
Above,"inthiscontext"meansduringthesameask(orbuttonpressorcommandtypedintheCommandCenter).Soitdoesn'tmakesense
towriteask turtles [ every 0.5 [ ... ] ],becausewhentheaskfinishestheturtleswillalldiscardtheirtimersforthe"every".Thecorrect
usageisshownbelow.
every 0.5 [ ask turtles [ fd 1 ] ]
;; twice a second the turtles will move forward 1
every 2 [ set index index + 1 ]
;; every 2 seconds index is incremented
Seealsowait.
exp
expnumber
Reportsthevalueoferaisedtothenumberpower.
Note:Thisisthesamease^number.
export-view
export-interface
export-output
export-plot
export-all-plots
export-world
export-viewfilename
export-interfacefilename
export-outputfilename
export-plotplotnamefilename
export-all-plotsfilename
export-worldfilename
export-viewwritesthecurrentcontentsofthecurrentviewtoanexternalfilegivenbythestringfilename.ThefileissavedinPNG(Portable
NetworkGraphics)format,soitisrecommendedtosupplyafilenameendingin".png".
export-interfaceissimilar,butforthewholeinterfacetab.
Notethatexport-viewstillworkswhenrunningNetLogoinheadlessmode,butexport-interfacedoesn't.
export-outputwritesthecontentsofthemodel'soutputareatoanexternalfilegivenbythestringfilename.(Ifthemodeldoesnothavea
separateoutputarea,theoutputportionoftheCommandCenterisused.)
export-plotwritesthexandyvaluesofallpointsplottedbyalltheplotpensintheplotgivenbythestringplotnametoanexternalfilegivenby
thestringfilename.Ifapenisinbarmode(mode0)andtheyvalueofthepointplottedisgreaterthan0,theupper-leftcornerpointofthebar
Since1.0
Since1.0
Since3.0
willbeexported.Iftheyvalueislessthan0,thenthelower-leftcornerpointofthebarwillbeexported.
export-all-plotswriteseveryplotinthecurrentmodeltoanexternalfilegivenbythestringfilename.Eachplotisidenticalinformattothe
outputofexport-plot.
export-worldwritesthevaluesofallvariables,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,thedrawing,
thecontentsoftheoutputareaifoneexists,thecontentsofanyplotsandthestateoftherandomnumbergenerator,toanexternalfilegiven
bythestringfilename.(TheresultfilecanbereadbackintoNetLogowiththeimport-worldprimitive.)export-worlddoesnotsavethestateof
openfiles.
export-plot,export-all-plotsandexport-worldsavefilesininplain-text,"comma-separatedvalues"(.csv)format.CSVfilescanbereadby
mostpopularspreadsheetanddatabaseprogramsaswellasanytexteditor.
Ifyouwishtoexporttoafileinalocationotherthanthemodel'slocation,youshouldincludethefullpathtothefileyouwishtoexport.(Use
theforward-slash"/"asthefolderseparator.)
NotethatthefunctionalityoftheseprimitivesisalsoavailabledirectlyfromNetLogo'sFilemenu.
export-world "fire.csv"
;; exports the state of the model to the file fire.csv
;; located in the NetLogo folder
export-plot "Temperature" "c:/My Documents/plot.csv"
;; exports the plot named
;; "Temperature" to the file plot.csv located in
;; the C:\My Documents folder
export-all-plots "c:/My Documents/plots.csv"
;; exports all plots to the file plots.csv
;; located in the C:\My Documents folder
Ifthefilealreadyexists,itisoverwritten.Toavoidthisyoumaywishtousesomemethodofgeneratingfreshnames.Examples:
export-world user-new-file
export-world (word "results " date-and-time ".csv") ;; Colon characters in the time cause errors on Windows
export-world (word "results " random-float 1.0 ".csv")
extensions
extensions[name...]
Allowsthemodeltouseprimitivesfromtheextensionswiththegivennames.SeetheExtensionsguideformoreinformation.
extract-hsb
extract-hsbcolor
Reportsalistofthreevalues,thefirst(hue)intherangeof0to360,thesecondandthird(brightnessandsaturation)intherangeof0to100.
ThegivencolorcaneitherbeaNetLogocolorintherange0to140,notincluding140itself,oranRGBlistofthreevaluesintherange0to
255representingthelevelsofred,green,andblue.
show extract-hsb cyan
=> [180 57.143 76.863]
show extract-hsb red
=> [3.103 80.93 84.314]
show extract-hsb [255 0 0]
=> [0 100 100]
Seealsoapproximate-hsb,approximate-rgb,extract-rgb.
extract-rgb
extract-rgbcolor
Reportsalistofthreevaluesintherange0to255representingthelevelsofred,green,andblue,respectively,ofthegivenNetLogocolorin
therange0to140,notincluding140itself.
show extract-rgb red
=> [215 50 41]
show extract-rgb cyan
=> [84 196 196]
Seealsoapproximate-rgb,approximate-hsb,extract-hsb.
F
face
faceagent
Setthecaller'sheadingtowardsagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,facewillusethewrappedpath.
Since3.0
Since2.0
Since2.0
Since2.0
Since2.0
Since2.0
Since4.0
Ifthecallerandtheagentareattheexactsameposition,thecaller'sheadingwon'tchange.
facexy
facexyxy
Setthecaller'sheadingtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorterandwrappingisallowed,facexy
willusethewrappedpath.
Ifthecallerisonthepoint(x,y),thecaller'sheadingwon'tchange.
file-at-end?
file-at-end?
Reportstruewhentherearenomorecharacterslefttoreadinfromthecurrentfile(thatwasopenedpreviouslywithfile-open).Otherwise,
reportsfalse.
file-open "my-file.txt"
print file-at-end?
=> false ;; Can still read in more characters
print file-read-line
=> This is the last line in file
print file-at-end?
=> true ;; We reached the end of the file
Seealsofile-open,file-close-all.
file-close
file-close
Closesafilethathasbeenopenedpreviouslywithfile-open.
Notethatthisandfile-close-allaretheonlywaystorestarttothebeginningofanopenedfileortoswitchbetweenfilemodes.
Ifnofileisopen,doesnothing.
Seealsofile-close-all,file-open.
file-close-all
file-close-all
Closesallfiles(ifany)thathavebeenopenedpreviouslywithfile-open.
Seealsofile-close,file-open.
file-delete
file-deletestring
Deletesthefilespecifiedasstring
stringmustbeanexistingfilewithwritablepermissionbytheuser.Also,thefilecannotbeopen.Usethecommandfile-closetoclosean
openedfilebeforedeletion.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
file-exists?
file-exists?string
Reportstrueifstringisthenameofanexistingfileonthesystem.Otherwiseitreportsfalse.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itdefaultstotothemodel'sdirectory.
file-flush
file-flush
Forcesfileupdatestobewrittentodisk.Whenyouusefile-writeorotheroutputcommands,thevaluesmaynotbeimmediatelywrittento
disk.Thisimprovestheperformanceofthefileoutputcommands.Closingafileensuresthatalloutputiswrittentodisk.
Sometimesyouneedtoensurethatdataiswrittentodiskwithoutclosingthefile.Forexample,youcouldbeusingafiletocommunicatewith
anotherprogramonyourmachineandwanttheotherprogramtobeabletoseetheoutputimmediately.
Since2.0
Since2.0
Since2.0
Since2.0
file-open
file-openstring
Thiscommandwillinterpretstringasapathnametoafileandopenthefile.Youmaythenusethereportersfile-read,file-read-line,andfile-
read-characterstoreadinfromthefile,orfile-write,file-print,file-type,orfile-showtowriteouttothefile.
Notethatyoucanonlyopenafileforreadingorwritingbutnotboth.Thenextfilei/oprimitiveyouuseafterthiscommanddictateswhich
modethefileisopenedin.Toswitchmodes,youneedtoclosethefileusingfile-close.
Also,thefilemustalreadyexistifopeningafileinreadingmode.
Whenopeningafileinwritingmode,allnewdatawillbeappendedtotheendoftheoriginalfile.Ifthereisnooriginalfile,anewblankfilewill
becreatedinitsplace.(Youmusthavewritepermissioninthefile'sdirectory.)(Ifyoudon'twanttoappend,butwanttoreplacethefile's
existingcontents,usefile-deletetodeleteitfirst,perhapsinsideacarefullyifyou'renotsurewhetheritalreadyexists.)
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
file-open "my-file-in.txt"
print file-read-line
=> First line in file ;; File is in reading mode
file-open "C:\\NetLogo\\my-file-out.txt"
;; assuming Windows machine
file-print "Hello World" ;; File is in writing mode
Openingafiledoesnotclosepreviouslyopenedfiles.Youcanusefile-opentoswitchbackandforthbetweenmultipleopenfiles.
Seealsofile-closeSeealsofile-close-all.
file-print
file-printvalue
Printsvaluetoanopenedfile,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikefile-show.
Notethatthiscommandisthefilei/oequivalentofprint,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-show,file-type,file-write,andOutput(programmingguide).
file-read
file-read
ThisreporterwillreadinthenextconstantfromtheopenedfileandinterpretitasifithadbeentypedintheCommandCenter.Itreportsthe
resultingvalue.Theresultmaybeanumber,list,string,boolean,orthespecialvaluenobody.
Whitespaceseparatestheconstants.Eachcalltofile-readwillskippastbothleadingandtrailingwhitespace.
Notethatstringsneedtohavequotesaroundthem.Usethecommandfile-writetohavequotesincluded.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.data"
print file-read + 5
;; Next value is the number 1
=> 6
print length file-read
;; Next value is the list [1 2 3 4]
=> 4
Seealsofile-openandfile-write.
file-read-characters
file-read-charactersnumber
Reportsthegivennumberofcharactersfromanopenedfileasastring.Iftherearefewerthanthatmanycharactersleft,itwillreportallofthe
remainingcharacters.
Notethatitwillreturneverycharacterincludingnewlinesandspaces.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"
print file-read-characters 5
;; Current line in file is "Hello World"
=> Hello
Seealsofile-open.
Since2.0
Since2.0
Since2.0
Since2.0
Since1.3
Since1.0
file-read-line
file-read-line
Readsthenextlineinthefileandreportsitasastring.Itdeterminestheendofthefilebyacarriagereturn,anendoffilecharacterorbothin
arow.Itdoesnotreturnthelineterminatorcharacters.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"
print file-read-line
=> Hello World
Seealsofile-open.
file-show
file-showvalue
Printsvaluetoanopenedfile,precededbythisagentagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrack
ofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartofile-write.
Notethatthiscommandisthefilei/oequivalentofshow,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-type,file-write,andOutput(programmingguide).
file-type
file-typevalue
Printsvaluetoanopenedfile,notfollowedbyacarriagereturn(unlikefile-printandfile-show).Thelackofacarriagereturnallowsyoutoprint
severalvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikefile-show.
Notethatthiscommandisthefilei/oequivalentoftype,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-show,file-write,andOutput(programmingguide).
file-write
file-writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytoanopenedfile,notfollowedbyacarriagereturn
(unlikefile-printandfile-show).
Thisagentisnotprintedbeforethevalue,unlikefile-show.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.It
willoutputthevalueinsuchamannerthatfile-readwillbeabletointerpretit.
Notethatthiscommandisthefilei/oequivalentofwrite,andfile-openneedstobecalledbeforethiscommandcanbeused.
file-open "locations.txt"
ask turtles
[ file-write xcor file-write ycor ]
Seealsofile-print,file-show,file-type,andOutput(programmingguide).
filter
filterreporterlist
Reportsalistcontainingonlythoseitemsoflistforwhichthereporterreportstrue--inotherwords,theitemssatisfyingthegivencondition.
reportermaybeananonymousreporterorthenameofareporter.
show filter is-number? [1 "2" 3]
=> [1 3]
show filter [ i -> i < 3 ] [1 3 2]
=> [1 2]
show filter [ s -> first s != "t" ] ["hi" "there" "everyone"]
=> ["hi" "everyone"]
Seealsomap,reduce,->(anonymousprocedure).
first
firstlist
firststring
Onalist,reportsthefirst(0th)iteminthelist.
Since1.0
Since3.0
Since3.0
Since1.3
Since1.0
Since1.0
Onastring,reportsaone-characterstringcontainingonlythefirstcharacteroftheoriginalstring.
floor
floornumber
Reportsthelargestintegerlessthanorequaltonumber.
show floor 4.5
=> 4
show floor -4.5
=> -5
Seealsoceiling,round,precision.
follow
followturtle
Similartoride,but,inthe3Dview,theobserver'svantagepointisbehindandaboveturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollowwillalterthehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingthefollowedturtleinstead.
Seealsofollow-me,ride,reset-perspective,watch,subject.
follow-me
follow-me
Askstheobservertofollowthisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollow-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-
me,highlightingthisturtleinstead.
Seealsofollow.
foreach
foreachlistcommand
(foreachlist1...command)
Withasinglelist,runsthecommandforeachitemoflist.commandmaybethenameofacommand,orananonymouscommandcreated
with->.
foreach [1.1 2.2 2.6] show
=> 1.1
=> 2.2
=> 2.6
foreach [1.1 2.2 2.6] [ x -> show (word x " -> " round x) ]
=> 1.1 -> 1
=> 2.2 -> 2
=> 2.6 -> 3
Withmultiplelists,runscommandforeachgroupofitemsfromeachlist.So,theyarerunonceforthefirstitems,oncefortheseconditems,
andsoon.Allthelistsmustbethesamelength.
Someexamplesmakethisclearer:
(foreach [1 2 3] [2 4 6]
[ [a b] -> show word "the sum is: " (a + b) ])
=> "the sum is: 3"
=> "the sum is: 6"
=> "the sum is: 9"
(foreach list (turtle 1) (turtle 2) [3 4]
[ [the-turtle num-steps] -> ask the-turtle [ fd num-steps ] ])
;; turtle 1 moves forward 3 patches
;; turtle 2 moves forward 4 patches
Seealsomap,->(anonymousprocedure).
forward
fd
forwardnumber
Theturtlemovesforwardbynumbersteps,onestepatatime.(Ifnumberisnegative,theturtlemovesbackward.)
fd 10isequivalenttorepeat 10 [ jump 1 ] .fd 10.5isequivalenttorepeat 10 [ jump 1 ] jump 0.5.
Iftheturtlecannotmoveforwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof1
Since1.0
Since1.0
asitcan,thenstop.
Seealsojump,can-move?.
fput
fputitemlist
Addsitemtothebeginningofalistandreportsthenewlist.
;; suppose mylist is [5 7 10]
set mylist fput 2 mylist
;; mylist is now [2 5 7 10]
G
globals
globals[var1...]
Thiskeyword,likethebreed,<breeds>-own,patches-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,before
anyfunctiondefinitions.Itdefinesnewglobalvariables.Globalvariablesare"global"becausetheyareaccessiblebyallagentsandcanbe
usedanywhereinamodel.
Mostoften,globalsisusedtodefinevariablesorconstantsthatneedtobeusedinmanypartsoftheprogram.
H
hatch
hatchnumber[commands]
hatch-<breeds>number[commands]
Thisturtlecreatesnumbernewturtles.Eachnewturtleinheritsofallitsvariables,includingitslocation,fromitsparent.(Exceptions:each
newturtlewillhaveanewwhonumber,anditmaybeofadifferentbreedthanitsparentifthehatch-<breeds>formisused.)
Thenewturtlesthenruncommands.Youcanusethecommandstogivethenewturtlesdifferentcolors,headings,locations,orwhatever.
(Thenewturtlesarecreatedallatonce,thenrunoneatatime,inrandomorder.)
Ifthehatch-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.Otherwise,thenewturtlesarethesame
breedastheirparent.
hatch 1 [ lt 45 fd 1 ]
;; this turtle creates one new turtle,
;; and the child turns and moves away
hatch-sheep 1 [ set color black ]
;; this turtle creates a new turtle
;; of the sheep breed
Seealsocreate-turtles,sprout.
heading
heading
Thisisabuilt-inturtlevariable.Itindicatesthedirectiontheturtleisfacing.Thisisanumbergreaterthanorequalto0andlessthan360.0is
north,90iseast,andsoon.Youcansetthisvariabletomakeaturtleturn.
Seealsoright,left,dx,dy.
Example:
set heading 45 ;; turtle is now facing northeast
set heading heading + 10 ;; same effect as "rt 10"
hidden?
hidden?
Thisisabuilt-inturtleorlinkvariable.Itholdsaboolean(trueorfalse)valueindicatingwhethertheturtleorlinkiscurrentlyhidden(i.e.,
invisible).Youcansetthisvariabletomakeaturtleorlinkdisappearorreappear.
Seealsohide-turtle,show-turtle,hide-link,show-link
Example:
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.1
Since4.1
set hidden? not hidden?
;; if turtle was showing, it hides, and if it was hiding,
;; it reappears
hide-link
hide-link
Thelinkmakesitselfinvisible.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"totrue.
Seealsoshow-link.
hide-turtle
ht
hide-turtle
Theturtlemakesitselfinvisible.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"totrue.
Seealsoshow-turtle.
histogram
histogramlist
Histogramsthevaluesinthegivenlist
Drawsahistogramshowingthefrequencydistributionofthevaluesinthelist.Theheightsofthebarsinthehistogramrepresentthe
numbersofvaluesineachsubrange.
Beforethehistogramisdrawn,firstanypreviouspointsdrawnbythecurrentplotpenareremoved.
Anynon-numericvaluesinthelistareignored.
Thehistogramisdrawnonthecurrentplotusingthecurrentplotpenandpencolor.Autoscalingdoesnotaffectahistogram'shorizontal
range,soset-plot-x-rangeshouldbeusedtocontroltherange,andthepenintervalcanthenbeset(eitherdirectlywithset-plot-pen-interval,
orindirectlyviaset-histogram-num-bars)tocontrolhowmanybarsthatrangeissplitupinto.
Besurethatifyouwantthehistogramdrawnwithbarsthatthecurrentpenisinbarmode(mode1).
Forhistogrammingpurposestheplot'sXrangeisnotconsideredtoincludethemaximumXvalue.ValuesequaltothemaximumXwillfall
outsideofthehistogram'srange.
histogram [color] of turtles
;; draws a histogram showing how many turtles there are
;; of each color
home
home
Thisturtlemovestotheorigin(0,0).Equivalenttosetxy 0 0.
hsb
hsbhuesaturationbrightness
ReportsaRGBlistwhengiventhreenumbersdescribinganHSBcolor.Hue,saturation,andbrightnessareintegersintherange0-360,0-
100,0-100respectively.TheRGBlistcontainsthreeintegersintherangeof0-255.
Seealsorgb
hubnet-broadcast
hubnet-broadcasttag-namevalue
ThisbroadcastsvaluefromNetLogototheinterfaceelementwiththenametag-nameontheclients.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-broadcast-clear-output
Since4.1
Since4.1
Since4.1
Since5.0
Since1.2.1
Since1.2.1
Since1.1
Since5.0
Since5.0
Since1.1
hubnet-broadcast-clear-output
Thisclearsallmessagesprintedtothetextareaoneveryclient.
Seealso:hubnet-broadcast-message,hubnet-send-clear-output
hubnet-broadcast-message
hubnet-broadcast-messagevalue
Thisprintsthevalueinthetextareaoneachclient.Thisisthesamefunctionalityasthe"BroadcastMessage"buttonintheHubNetControl
Center.
Seealso:hubnet-send-message
hubnet-clear-override
hubnet-clear-overrides
hubnet-clear-overrideclientagent-or-setvariable-name
hubnet-clear-overridesclient
Removeoverridesfromtheoverridelistonclient.hubnet-clear-overrideremovesonlytheoverrideforthespecifiedvariableforthespecified
agentoragentset.hubnet-clear-overridesremovesalloverridesfromthespecifiedclient.
Seealso:hubnet-send-override
hubnet-clients-list
hubnet-clients-list
ReportsalistcontainingthenamesofalltheclientscurrentlyconnectedtotheHubNetserver.
hubnet-enter-message?
hubnet-enter-message?
Reportstrueifanewclientjustenteredthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameofthe
clientthatjustloggedon.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-exit-message?
hubnet-exit-message?
Reportstrueifaclientjustexitedthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameoftheclientthat
justloggedoff.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-fetch-message
hubnet-fetch-message
Ifthereisanynewdatasentbytheclients,thisretrievesthenextpieceofdata,sothatitcanbeaccessedbyhubnet-message,hubnet-
message-source,andhubnet-message-tag.Thiswillcauseanerrorifthereisnonewdatafromtheclients.
SeetheHubNetAuthoringGuidefordetails.
hubnet-kick-client
hubnet-kick-clientclient-name
Kickstheclientwiththegivenclient-name.ThisisequivalenttoclickingtheclientnameintheHubNetControlCenterandpressingtheKick
button.
hubnet-kick-all-clients
hubnet-kick-all-clients
KicksoutallcurrentlyconnectedHubNetclients.ThisisequivalenttoselectingallclientsintheHubNetControlCenterandpressingtheKick
button.
hubnet-message
hubnet-message
Since1.1
Since1.1
Since1.1
Since1.1
Since4.1
Since1.1
Since4.1
Since4.1
Reportsthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-source
hubnet-message-source
Reportsthenameoftheclientthatsentthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-tag
hubnet-message-tag
Reportsthetagthatisassociatedwiththedatathatwasretrievedbyhubnet-fetch-message.ThetagwillbeoneoftheDisplayNamesofthe
interfaceelementsintheclientinterface.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-waiting?
hubnet-message-waiting?
Thislooksforanewmessagesentbytheclients.Itreportstrueifthereisone,andfalseifthereisnot.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset
hubnet-reset
StartsuptheHubNetsystem.HubNetmustbestartedtouseanyoftheotherhubnetprimitives.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset-perspective
hubnet-reset-perspectivetag-name
Clearswatchorfollowsentdirectlytotheclient.Theviewperspectivewillreverttotheserverperspective.
Seealso:hubnet-send-watchhubnet-send-follow
hubnet-send
hubnet-sendstringtag-namevalue
hubnet-sendlist-of-stringstag-namevalue
Forastring,thissendsvaluefromNetLogotothetagtag-nameontheclientthathasstringforitsusername.
Foralist-of-strings,thissendsvaluefromNetLogotothetagtag-nameonalltheclientsthathaveausernamethatisinthelist-of-strings.
Sendingamessagetoanon-existentclient,usinghubnet-send,generatesahubnet-exit-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-send-clear-output
hubnet-send-clear-outputstring
hubnet-send-clear-outputlist-of-strings
Thisclearsallmessagesprintedtothetextareaonthegivenclientorclients(specifiedinthestringorlist-of-strings.
Seealso:hubnet-send-message,hubnet-broadcast-clear-output
hubnet-send-follow
hubnet-send-followclient-nameagentradius
Tellstheclientassociatedwithclient-nametofollowagentshowingaradiussizedMooreneighborhoodaroundtheagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-followwillalterthehighlightcreatedbypriorcallstohubnet-send-
watch,highlightingthefollowedagentinstead.
Seealso:hubnet-send-watch,hubnet-reset-perspective
Since4.1
Since4.1
Since4.1
Since1.0
Since1.0
Since2.0
hubnet-send-message
hubnet-send-messagestringvalue
Thisprintsvalueinthetextareaontheclientspecifiedbystring.
Seealso:hubnet-broadcast-message
hubnet-send-override
hubnet-send-overrideclient-nameagent-or-setvariable-name
[reporter]
Evaluatesreporterfortheagentoragentsetindicatedthensendsthevaluestotheclientto"override"thevalueofvariable-nameonlyon
client-name.Thisisusedtochangetheappearanceofagentsintheclientview,hence,onlybuilt-invariablesthataffecttheappearanceof
theagentmaybeselected.Forexample,youcanoverridethecolorvariableofaturtle:
ask turtles [ hubnet-send-override client-name self "color" [ red ] ]
Inthisexampleassumethatthereisaturtles-ownvariableclient-namewhichisassociatedwithaloggedinclient,andalltheturtlesareblue.
Thiscodemakestheturtleassociatedwitheachclientappearredinhisorherownviewbutnotonanyoneelse'sorontheserver.
Seealso:hubnet-clear-overrides
hubnet-send-watch
hubnet-send-watchclient-nameagent
Tellstheclientassociatedwithclient-nametowatchagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-watchwillundoperspectivechangescausedbypriorcallstohubnet-
send-follow.
Seealso:hubnet-send-follow,hubnet-reset-perspective
I
if
ifcondition[commands]
Reportermustreportaboolean(trueorfalse)value.
Ifconditionreportstrue,runscommands.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommandsandothersdon't.
if xcor > 0[ set color blue ]
;; turtles in the right half of the world
;; turn blue
Seealsoifelse,ifelse-value.
ifelse
ifelsereporter[commands1][commands2]
Reportermustreportaboolean(trueorfalse)value.
Ifreporterreportstrue,runscommands1.
Ifreporterreportsfalse,runscommands2.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommands1whileothersruncommands2.
ask patches
[ ifelse pxcor > 0
[ set pcolor blue ]
[ set pcolor red ] ]
;; the left half of the world turns red and
;; the right half turns blue
Seealsoif,ifelse-value.
ifelse-value
ifelse-valuereporter[reporter1][reporter2]
Reportermustreportaboolean(trueorfalse)value.
Since3.0
Since3.0
Since4.0
Since1.0
Since3.0
Ifreporterreportstrue,theresultisthevalueofreporter1.
Ifreporterreportsfalse,theresultisthevalueofreporter2.
Thiscanbeusedwhenaconditionalisneededinthecontextofareporter,wherecommands(suchasifelse)arenotallowed.
ask patches [
set pcolor ifelse-value (pxcor > 0) [blue] [red]
]
;; the left half of the world turns red and
;; the right half turns blue
show n-values 10 [ifelse-value (? < 5) [0] [1]]
=> [0 0 0 0 0 1 1 1 1 1]
show reduce [ [a b] -> ifelse-value (a > b) [a] [b] ]
[1 3 2 5 3 8 3 2 1]
=> 8
Seealsoif,ifelse.
import-drawing
import-drawingfilename
Readsanimagefileintothedrawing,scalingittothesizeoftheworld,whileretainingtheoriginalaspectratiooftheimage.Theimageis
centeredinthedrawing.Theolddrawingisnotclearedfirst.
Agentscannotsensethedrawing,sotheycannotinteractwithorprocessimagesimportedbyimport-drawing.Ifyouneedagentstosensean
image,useimport-pcolorsorimport-pcolors-rgb.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),that
informationwillbeimportedaswell.
import-pcolors
import-pcolorsfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransfers
theresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Theresultingpatchcolorsmaybedistorted,sincethe
NetLogocolorspacedoesnotincludeallpossiblecolors.(SeetheColorsectionoftheProgrammingGuide.)import-pcolorsmaybeslowfor
someimages,particularlywhenyouhavemanypatchesandalargeimagewithmanydifferentcolors.
Sinceimport-pcolorssetsthepcolorofpatches,agentscansensetheimage.Thisisusefulifagentsneedtoanalyze,process,orotherwise
interactwiththeimage.Ifyouwanttosimplydisplayastaticbackdrop,withoutcolordistortion,seeimport-drawing.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfully
transparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-pcolors-rgb
import-pcolors-rgbfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransfers
theresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Unlikeimport-pcolorstheexactcolorsintheoriginalimage
areretained.ThepcolorvariableofallthepatcheswillbeanRGBlistratherthanan(approximated)NetLogocolor.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfully
transparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-world
import-worldfilename
Readsthevaluesofallvariablesforamodel,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,froman
externalfilenamedbythegivenstring.Thefileshouldbeintheformatusedbytheexport-worldprimitive.
NotethatthefunctionalityofthisprimitiveisalsodirectlyavailablefromNetLogo'sFilemenu.
Whenusingimport-world,toavoiderrors,performthesestepsinthefollowingorder:
1. Openthemodelfromwhichyoucreatedtheexportfile.
2. PresstheSetupbutton,togetthemodelinastatefromwhichitcanberun.
3. Importthefile.
4. Re-openanyfilesthatthemodelhadopenedwiththefile-opencommand.
5. Ifyouwant,pressGobuttontocontinuerunningthemodelfromthepointwhereitleftoff.
Ifyouwishtoimportafilefromalocationotherthanthemodel'slocation,youmayincludethefullpathtothefileyouwishtoimport.See
export-worldforanexample.
in-cone
Since4.0
Since4.0
Since4.0
Since4.0
agentsetin-conedistanceangle
Thisreporterletsyougiveaturtlea"coneofvision"infrontofitself.Theconeisdefinedbythetwoinputs,thevisiondistance(radius)and
theviewingangle.Theviewinganglemayrangefrom0to360andiscenteredaroundtheturtle'scurrentheading.(Iftheangleis360,then
in-coneisequivalenttoin-radius.)
in-conereportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetthatfallinthecone.(Thiscanincludetheagentitself.)
Thedistancetoapatchismeasuredfromthecenterofthepatch.
ask turtles
[ ask patches in-cone 3 60
[ set pcolor red ] ]
;; each turtle makes a red "splotch" of patches in a 60 degree
;; cone of radius 3 ahead of itself
in-<breed>-neighbor?
in-link-neighbor?
in-<breed>-neighbor?agent
in-link-neighbor?turtle
Reportstrueifthereisadirectedlinkgoingfromturtletothecalleroranundirectedlinkconnectingturtletothecaller.Youcanthinkofthisas
"istherealinkIcanusetogetfromturtletothecaller?"
crt 2
ask turtle 0 [
create-link-to turtle 1
show in-link-neighbor? turtle 1 ;; prints false
show out-link-neighbor? turtle 1 ;; prints true
]
ask turtle 1 [
show in-link-neighbor? turtle 0 ;; prints true
show out-link-neighbor? turtle 0 ;; prints false
]
in-<breed>-neighbors
in-link-neighbors
in-<breed>-neighbors
in-link-neighbors
Reportstheagentsetofalltheturtlesthathavedirectedlinkscomingfromthemtothecalleraswellasallturtlesthathaveanundirectedlink
connectingthemwiththecaller.Youcanthinkofthisas"alltheturtlesthatcangettothecallerusingalink."
crt 4
ask turtle 0 [ create-links-to other turtles ]
ask turtle 1 [ ask in-link-neighbors [ set color blue ] ] ;; turtle 0 turns blue
in-<breed>-from
in-link-from
in-<breed>-fromturtle
in-link-fromturtle
Reportsadirectedlinkfromturtletothecalleroranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromturtletothecaller."
crt 2
ask turtle 0 [ create-link-to turtle 1 ]
ask turtle 1 [ show in-link-from turtle 0 ] ;; shows link 0 1
ask turtle 0 [ show in-link-from turtle 1 ] ;; shows nobody
Seealso:out-link-tolink-with
__includes
__includes[filename...]
CausesexternalNetLogosourcefiles(withthe.nlssuffix)tobeincludedinthismodel.Includedfilesmaycontainbreed,variable,and
proceduredefinitions.__includescanonlybeusedonceperfile.
Thefilenamesmustbestrings,forexample:
__includes [ "utils.nls" ]
Or,formultiplefiles:
Since1.0
Since6.0.2
Since1.1
Since1.0
Since1.2.1
Since1.2.1
Since6.0
Since6.0
Since1.2.1
Since4.0
Since4.0
Since4.0
Since1.0
Since1.2.1
Since1.2.1
Since4.0
Since1.0
Since1.2.1
Since4.0
Since4.0
__includes [ "utils1.nls" "utils2.nls" ]
in-radius
agentsetin-radiusnumber
Reportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetwhosedistancefromthecallerislessthanorequalto
number.(Thiscanincludetheagentitself.)
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.
ask turtles
[ ask patches in-radius 3
[ set pcolor red ] ]
;; each turtle makes a red "splotch" around itself
insert-item
insert-itemindexlistvalue
insert-itemindexstring1string2
Onalist,insertsaniteminthatlist.indexistheindexwheretheitemwillbeinserted.Thefirstitemhasanindexof0.(The6thiteminalist
wouldhaveanindexof5.)
Likewiseforastring,butallcharactersinamultiple-characterstring2areinsertedatindex.
show insert-item 2 [2 7 4 5] 15
=> [2 7 15 4 5]
show insert-item 2 "cat" "re"
=> "caret"
inspect
inspectagent
Opensanagentmonitorforthegivenagent(turtleorpatch).
inspect patch 2 4
;; an agent monitor opens for that patch
inspect one-of sheep
;; an agent monitor opens for a random turtle from
;; the "sheep" breed
Seestop-inspectingandstop-inspecting-dead-agents
int
intnumber
Reportstheintegerpartofnumber--anyfractionalpartisdiscarded.
show int 4.7
=> 4
show int -3.5
=> -3
is-agent?
is-agentset?
is-anonymous-command?
is-anonymous-reporter?
is-boolean?
is-directed-link?
is-link?
is-link-set?
is-list?
is-number?
is-patch?
is-patch-set?
is-string?
is-turtle?
is-turtle-set?
is-undirected-link?
is-agent?value
Since1.0
Since1.0
is-agentset?value
is-anonymous-command?value
is-anonymous-reporter?value
is-boolean?value
is-<breed>?value
is-<link-breed>?value
is-directed-link?value
is-link?value
is-link-set?value
is-list?value
is-number?value
is-patch?value
is-patch-set?value
is-string?value
is-turtle?value
is-turtle-set?value
is-undirected-link?value
Reportstrueifvalueisofthegiventype,falseotherwise.
item
itemindexlist
itemindexstring
Onlists,reportsthevalueoftheiteminthegivenlistwiththegivenindex.
Onstrings,reportsthecharacterinthegivenstringatthegivenindex.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
;; suppose mylist is [2 4 6 8 10]
show item 2 mylist
=> 6
show item 3 "my-shoe"
=> "s"
J
jump
jumpnumber
Theturtlemovesforwardbynumberunitsallatonce(ratherthanonestepatatimeaswiththeforwardcommand).
Iftheturtlecannotjumpnumberunitsbecauseitisnotpermittedbythecurrenttopologytheturtledoesnotmoveatall.
Seealsoforward,can-move?.
L
label
label
Thisisabuilt-inturtleorlinkvariable.Itmayholdavalueofanytype.Theturtleorlinkappearsintheviewwiththegivenvalue"attached"to
itastext.Youcansetthisvariabletoadd,change,orremoveaturtleorlink'slabel.
Seealsolabel-color,plabel,plabel-color.
Example:
ask turtles [ set label who ]
;; all the turtles now are labeled with their
;; who numbers
ask turtles [ set label "" ]
;; all turtles now are not labeled
label-color
label-color
Thisisabuilt-inturtleorlinkvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolorthe
turtleorlink'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofaturtleorlink'slabel.
Seealsolabel,plabel,plabel-color.
Example:
Since1.0
Since4.0
Since4.0
Since4.0
ask turtles [ set label-color red ]
;; all the turtles now have red labels
last
lastlist
laststring
Onalist,reportsthelastiteminthelist.
Onastring,reportsaone-characterstringcontainingonlythelastcharacteroftheoriginalstring.
layout-circle
layout-circleagentsetradius
layout-circlelist-of-turtlesradius
Arrangesthegiventurtlesinacirclecenteredonthepatchatthecenteroftheworldwiththegivenradius.(Iftheworldhasanevensizethe
centerofthecircleisroundeddowntothenearestpatch.)Theturtlespointoutwards.
Ifthefirstinputisanagentset,theturtlesarearrangedinrandomorder.
Ifthefirstinputisalist,theturtlesarearrangedclockwiseinthegivenorder,startingatthetopofthecircle.(Anynon-turtlesinthelistare
ignored.)
;; in random order
layout-circle turtles 10
;; in order by who number
layout-circle sort turtles 10
;; in order by size
layout-circle sort-by [ [a b] -> [size] of a < [size] of b ] turtles 10
layout-radial
layout-radialturtle-setlink-setroot-agent
Arrangestheturtlesinturtle-setconnectedbylinksinlink-set,inaradialtreelayout,centeredaroundtheroot-agentwhichismovedtothe
centeroftheworldview.
Onlylinksinthelink-setwillbeusedtodeterminethelayout.Iflinksconnectturtlesthatarenotinturtle-setthoseturtleswillremain
stationary.
Evenifthenetworkdoescontaincycles,andisnotatruetreestructure,thislayoutwillstillwork,althoughtheresultswillnotalwaysbe
pretty.
to make-a-tree
set-default-shape turtles "circle"
crt 6
ask turtle 0 [
create-link-with turtle 1
create-link-with turtle 2
create-link-with turtle 3
]
ask turtle 1 [
create-link-with turtle 4
create-link-with turtle 5
]
; do a radial tree layout, centered on turtle 0
layout-radial turtles links (turtle 0)
end
layout-spring
layout-springturtle-setlink-setspring-constantspring-lengthrepulsion-constant
Arrangestheturtlesinturtle-set,asifthelinksinlink-setarespringsandtheturtlesarerepellingeachother.Turtlesthatareconnectedby
linksinlink-setbutnotincludedinturtle-setaretreatedasanchorsandarenotmoved.
spring-constantisameasureofthe"tautness"ofthespring.Itisthe"resistance"tochangeintheirlength.spring-constantistheforcethe
springwouldexertifit'slengthwerechangedby1unit.
spring-lengthisthe"zero-force"lengthorthenaturallengthofthesprings.Thisisthelengthwhichallspringstrytoachieveeitherbypushing
outtheirnodesorpullingthemin.
repulsion-constantisameasureofrepulsionbetweenthenodes.Itistheforcethat2nodesatadistanceof1unitwillexertoneachother.
Therepulsioneffecttriestogetthenodesasfaraspossiblefromeachother,inordertoavoidcrowdingandthespringeffecttriestokeep
themat"about"acertaindistancefromthenodestheyareconnectedto.Theresultisthelayingoutofthewholenetworkinawaywhich
highlightsrelationshipsamongthenodesandatthesametimeiscrowdedlessandisvisuallypleasing.
ThelayoutalgorithmisbasedontheFruchterman-Reingoldlayoutalgorithm.Moreinformationaboutthisalgorithmcanbeobtainedhere.
to make-a-triangle
set-default-shape turtles "circle"
crt 3
ask turtle 0
[
Since4.0
Since1.0
Since1.0
Since1.0
Since2.1
Since4.0
create-links-with other turtles
]
ask turtle 1
[
create-link-with turtle 2
]
repeat 30 [ layout-spring turtles links 0.2 5 1 ] ;; lays the nodes in a triangle
end
layout-tutte
layout-tutteturtle-setlink-setradius
Theturtlesthatareconnectedbylinksinlink-setbutnotincludedinturtle-setareplacedinacirclelayoutwiththegivenradius.Thereshould
beatleast3agentsinthisagentset.
Theturtlesinturtle-setarethenlaidoutinthefollowingmanner:Eachturtleisplacedatcentroid(orbarycenter)ofthepolygonformedbyits
linkedneighbors.(Thecentroidislikea2-dimensionalaverageofthecoordinatesoftheneighbors.)
(Thepurposeofthecircleof"anchoragents"istopreventalltheturtlesfromcollapsingdowntoonepoint.)
Afterafewiterationsofthis,thelayoutwillstabilize.
ThislayoutisnamedafterthemathematicianWilliamThomasTutte,whoproposeditasamethodforgraphlayout.
to make-a-tree
set-default-shape turtles "circle"
crt 6
ask turtle 0 [
create-link-with turtle 1
create-link-with turtle 2
create-link-with turtle 3
]
ask turtle 1 [
create-link-with turtle 4
create-link-with turtle 5
]
; place all the turtles with just one
; neighbor on the perimeter of a circle
; and then place the remaining turtles inside
; this circle, spread between their neighbors.
repeat 10 [ layout-tutte (turtles with [link-neighbors = 1]) links 12 ]
end
left
lt
leftnumber
Theturtleturnsleftbynumberdegrees.(Ifnumberisnegative,itturnsright.)
length
lengthlist
lengthstring
Reportsthenumberofitemsinthegivenlist,orthenumberofcharactersinthegivenstring.
let
letvariablevalue
Createsanewlocalvariableandgivesitthegivenvalue.Alocalvariableisonethatexistsonlywithintheenclosingblockofcommands.
Ifyouwanttochangethevalueafterwards,useset.
Example:
let prey one-of sheep-here
if prey != nobody
[ ask prey [ die ] ]
link
linkend1end2
<breed>end1end2
Giventhewhonumbersoftheendpoints,reportsthelinkconnectingtheturtles.Ifthereisnosuchlinkreportsnobody.Torefertobreeded
linksyoumustusethesingularbreedformwiththeendpoints.
ask link 0 1 [ set color green ]
;; unbreeded link connecting turtle 0 and turtle 1 will turn green
ask directed-link 0 1 [ set color red ]
;; directed link connecting turtle 0 and turtle 1 will turn red
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Seealsopatch-at.
link-heading
link-heading
Reportstheheadingindegrees(atleast0,lessthan360)fromend1toend2ofthelink.Throwsaruntimeerroriftheendpointsareatthe
samelocation.
ask link 0 1 [ print link-heading ]
;; prints [[towards other-end] of end1] of link 0 1
Seealsolink-length
link-length
link-length
Reportsthedistancebetweentheendpointsofthelink.
ask link 0 1 [ print link-length ]
;; prints [[distance other-end] of end1] of link 0 1
Seealsolink-heading
link-set
link-setvalue
(link-setvalue1value2...)
Reportsanagentsetcontainingallofthelinksanywhereinanyoftheinputs.Theinputsmaybeindividuallinks,linkagentsets,nobody,or
lists(ornestedlists)containinganyoftheabove.
link-set self
link-set [my-links] of nodes with [color = red]
Seealsoturtle-set,patch-set.
link-shapes
link-shapes
Reportsalistofstringscontainingallofthelinkshapesinthemodel.
Newshapescanbecreated,orimportedfromothermodels,intheLinkShapesEditor.
show link-shapes
=> ["default"]
links
links
Reportstheagentsetconsistingofalllinks.Thisisaspecialagentsetthatcangrowasturtlesareaddedtotheworld,seetheprogramming
guideformoreinfo.
show count links
;; prints the number of links
links-own
links-own[var1...]
<link-breeds>-own[var1...]
Thelinks-ownkeyword,liketheglobals,breed,<breeds>-own,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningof
aprogram,beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachlink.
Ifyouspecifyabreedinsteadof"links",onlylinksofthatbreedhavethelistedvariables.(Morethanonelinkbreedmaylistthesame
variable.)
undirected-link-breed [sidewalks sidewalk]
directed-link-breed [streets street]
links-own [traffic] ;; applies to all breeds
sidewalks-own [pedestrians]
streets-own [cars bikes]
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.3
list
listvalue1value2
(listvalue1...)
Reportsalistcontainingthegivenitems.Theitemscanbeofanytype,producedbyanykindofreporter.
show list (random 10) (random 10)
=> [4 9] ;; or similar list
show (list 5)
=> [5]
show (list (random 10) 1 2 3 (random 10))
=> [4 1 2 3 9] ;; or similar list
ln
lnnumber
Reportsthenaturallogarithmofnumber,thatis,thelogarithmtothebasee(2.71828...).
Seealsoe,log.
log
lognumberbase
Reportsthelogarithmofnumberinbasebase.
show log 64 2
=> 6
Seealsoln.
loop
loop[commands]
Repeatsthecommandsforever,oruntiltheenclosingprocedureexitsthroughuseofthestoporreportcommands.
to move-to-world-edge ;; turtle procedure
loop [
if not can-move? 1 [ stop ]
fd 1
]
end
Inthisexample,stopexitsnotjusttheloop,buttheentireprocedure.
Note:inmanycircumstances,itismoreappropriatetouseaforeverbuttontorepeatsomethingindefinitely.SeeButtonsintheProgramming
Guide.
lput
lputvaluelist
Addsvaluetotheendofalistandreportsthenewlist.
;; suppose mylist is [2 7 10 "Bob"]
set mylist lput 42 mylist
;; mylist now is [2 7 10 "Bob" 42]
M
map
mapreporterlist
(mapreporterlist1...)
Withasinglelist,thegivenreporterisrunforeachiteminthelist,andalistoftheresultsiscollectedandreported.reportermaybean
anonymousreporterorthenameofareporter.
show map round [1.1 2.2 2.7]
=> [1 2 3]
show map [ i -> i * i ] [1 2 3]
=> [1 4 9]
Withmultiplelists,thegivenreporterisrunforeachgroupofitemsfromeachlist.So,itisrunonceforthefirstitems,onceforthesecond
items,andsoon.Allthelistsmustbethesamelength.
Since1.0
Since4.0
Since1.0
Since3.1
Since3.1
Since1.0
Someexamplesmakethisclearer:
show (map + [1 2 3] [2 4 6])
=> [3 6 9]
show (map [ [a b c] -> a + b = c ] [1 2 3] [2 4 6] [3 5 9])
=> [true false true]
Seealsoforeach,->(anonymousprocedure).
max
maxlist
Reportsthemaximumnumbervalueinthelist.Itignoresothertypesofitems.
show max [xcor] of turtles
;; prints the x coordinate of the turtle which is
;; farthest right in the world
show max list a b
;; prints the larger of the two variables a and b
show max (list a b c)
;; prints the largest of the three variables a, b, and c
max-n-of
max-n-ofnumberagentset[reporter]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththehighestvaluesofreporter.Theagentsetisbuiltbyfindingallthe
agentswiththehighestvalueofreporter,iftherearenotnumberagentswiththatvaluethenagentswiththesecondhighestvaluearefound,
andsoon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; assume the world is 11 x 11
show max-n-of 5 patches [pxcor]
;; shows 5 patches with pxcor = max-pxcor
show max-n-of 5 patches with [pycor = 0] [pxcor]
;; shows an agentset containing:
;; (patch 1 0) (patch 2 0) (patch 3 0) (patch 4 0) (patch 5 0)
Seealsomax-one-of,with-max.
max-one-of
max-one-ofagentset[reporter]
Reportstheagentintheagentsetthathasthehighestvalueforthegivenreporter.Ifthereisatiethiscommandreportsonerandomagent
withthehighestvalue.Ifyouwantallsuchagents,usewith-maxinstead.
show max-one-of patches [count turtles-here]
;; prints the first patch with the most turtles on it
Seealsomax-n-of,with-max.
max-pxcor
max-pycor
max-pxcor
max-pycor
Thesereportersgivethemaximumx-coordinateandmaximumy-coordinate,(respectively)forpatches,whichdeterminesthesizeofthe
world.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,themaximumx-andy-coordinates
mustbegreaterthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
crt 100 [ setxy random-float max-pxcor
random-float max-pycor ]
;; distributes 100 turtles randomly in the
;; first quadrant
Seealsomin-pxcor,min-pycor,world-width,andworld-height
mean
meanlist
Reportsthestatisticalmeanofthenumericitemsinthegivenlist.Errorsonnon-numericitems.Themeanistheaverage,i.e.,thesumofthe
itemsdividedbythetotalnumberofitems.
Since1.0
Since1.0
Since1.0
Since4.0
Since1.0
show mean [xcor] of turtles
;; prints the average of all the turtles' x coordinates
median
medianlist
Reportsthestatisticalmedianofthenumericitemsofthegivenlist.Ignoresnon-numericitems.Themedianistheitemthatwouldbeinthe
middleifalltheitemswerearrangedinorder.(Iftwoitemswouldbeinthemiddle,themedianistheaverageofthetwo.)
show median [xcor] of turtles
;; prints the median of all the turtles' x coordinates
member?
member?valuelist
member?string1string2
member?agentagentset
Foralist,reportstrueifthegivenvalueappearsinthegivenlist,otherwisereportsfalse.
Forastring,reportstrueorfalsedependingonwhetherstring1appearsanywhereinsidestring2asasubstring.
Foranagentset,reportstrueifthegivenagentisappearsinthegivenagentset,otherwisereportsfalse.
show member? 2 [1 2 3]
=> true
show member? 4 [1 2 3]
=> false
show member? "bat" "abate"
=> true
show member? turtle 0 turtles
=> true
show member? turtle 0 patches
=> false
Seealsoposition.
min
minlist
Reportstheminimumnumbervalueinthelist.Itignoresothertypesofitems.
show min [xcor] of turtles
;; prints the lowest x-coordinate of all the turtles
show min list a b
;; prints the smaller of the two variables a and b
show min (list a b c)
;; prints the smallest of the three variables a, b, and c
min-n-of
min-n-ofnumberagentset[reporter]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththelowestvaluesofreporter.Theagentsetisbuiltbyfindingalltheagents
withthelowestvalueofreporter,iftherearenotnumberagentswiththatvaluethentheagentswiththesecondlowestvaluearefound,and
soon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; assume the world is 11 x 11
show min-n-of 5 patches [pxcor]
;; shows 5 patches with pxcor = min-pxcor
show min-n-of 5 patches with [pycor = 0] [pxcor]
;; shows an agentset containing:
;; (patch -5 0) (patch -4 0) (patch -3 0) (patch -2 0) (patch -1 0)
Seealsomin-one-of,with-min.
min-one-of
min-one-ofagentset[reporter]
Reportsarandomagentintheagentsetthatreportsthelowestvalueforthegivenreporter.Ifthereisatie,thiscommandreportsone
randomagentthatmeetsthecondition.Ifyouwantallsuchagentsusewith-mininstead.
show min-one-of turtles [xcor + ycor]
;; reports the first turtle with the smallest sum of
;; coordinates
Seealsowith-min,min-n-of.
Since3.1
Since3.1
Since1.0
Since2.0
Since1.0
Since3.0
Since1.0
Since1.0
min-pxcor
min-pycor
min-pxcor
min-pycor
Thesereportersgivetheminimumx-coordinateandminimumy-coordinate,(respectively)forpatches,whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,theminimumx-andy-coordinates
mustbelessthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
crt 100 [ setxy random-float min-pxcor
random-float min-pycor ]
;; distributes 100 turtles randomly in the
;; third quadrant
Seealsomax-pxcor,max-pycor,world-width,andworld-height
mod
number1modnumber2
Reportsnumber1modulonumber2:thatis,theresidueofnumber1(modnumber2).modisisequivalenttothefollowingNetLogocode:
number1 - (floor (number1 / number2)) * number2
Notethatmodis"infix",thatis,itcomesbetweenitstwoinputs.
show 62 mod 5
=> 2
show -8 mod 3
=> 1
Seealsoremainder.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
modes
modeslist
Reportsalistofthemostcommonitemoritemsinlist.
TheinputlistmaycontainanyNetLogovalues.
Iftheinputisanemptylist,reportsanemptylist.
show modes [1 2 2 3 4]
=> [2]
show modes [1 2 2 3 3 4]
=> [2 3]
show modes [ [1 2 [3]] [1 2 [3]] [2 3 4] ]
=> [[1 2 [3]]]
show modes [pxcor] of turtles
;; shows which columns of patches have the most
;; turtles on them
mouse-down?
mouse-down?
Reportstrueifthemousebuttonisdown,falseotherwise.
Note:Ifthemousepointerisoutsideofthecurrentview,mouse-down?willalwaysreportfalse.
mouse-inside?
mouse-inside?
Reportstrueifthemousepointerisinsidethecurrentview,falseotherwise.
mouse-xcor
mouse-ycor
mouse-xcor
mouse-ycor
Reportsthexorycoordinateofthemouseinthe2Dview.Thevalueisintermsofturtlecoordinates,soitmightnotbeaninteger.Ifyouwant
patchcoordinates,useround mouse-xcorandround mouse-ycor.
Note:Ifthemouseisoutsideofthe2Dview,reportsthevaluefromthelasttimeitwasinside.
Since4.0
Since4.0
Since4.0
Since4.0
;; to make the mouse "draw" in red:
if mouse-down?
[ ask patch mouse-xcor mouse-ycor [ set pcolor red ] ]
move-to
move-toagent
Theturtlesetsitsxandycoordinatestobethesameasthegivenagent's.
(Ifthatagentisapatch,theeffectistomovetheturtletothecenterofthatpatch.)
move-to turtle 5
;; turtle moves to same point as turtle 5
move-to one-of patches
;; turtle moves to the center of a random patch
move-to max-one-of turtles [size]
;; turtle moves to same point as biggest turtle
Notethattheturtle'sheadingisunaltered.Youmaywanttousethefacecommandfirsttoorienttheturtleinthedirectionofmotion.
Seealsosetxy.
my-<breeds>
my-links
my-<breeds>
my-links
Reportsanagentsetofalllinksconnectedtothecallerofthecorrespondingbreed,regardlessofdirectedness.Generally,youmightconsider
usingmy-out-linksinsteadofthisprimitive,asitworkswellforeitherdirectedorundirectednetworks(sinceitexcludesdirected,incoming
links).
crt 5
ask turtle 0
[
create-links-with other turtles
show my-links ;; prints the agentset containing all links
;; (since all the links we created were with turtle 0 )
]
ask turtle 1
[
show my-links ;; shows an agentset containing the link 0 1
]
end
Ifyouonlywanttheundirectedlinksconnectedtoanode,youcandomy-links with [ not is-directed-link? self ].
my-in-<breeds>
my-in-links
my-in-<breeds>
my-in-links
Reportsanagentsetofallthedirectedlinkscominginfromothernodestothecalleraswellasallundirectedlinksconnectedtothecaller.
Youcanthinkofthisas"alllinksthatyoucanusetotraveltothisnode".
crt 5
ask turtle 0
[
create-links-to other turtles
show my-in-links ;; shows an empty agentset
]
ask turtle 1
[
show my-in-links ;; shows an agentset containing the link 0 1
]
my-out-<breeds>
my-out-links
my-out-<breeds>
my-out-links
Reportsanagentsetofallthedirectedlinksgoingoutfromthecallertoothernodesaswellasundirectedlinksconnectedtothecaller.You
canthinkofthisas"alllinksyoucanusetotravelfromthisnode".
crt 5
ask turtle 0
[
create-links-to other turtles
show my-out-links ;; shows agentset containing all the links
Since1.0
Since3.1
Since2.0
Since1.1
Since1.1
]
ask turtle 1
[
show my-out-links ;; shows an empty agentset
]
myself
myself
 
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theturtle,patchorlinkwhoaskedmetodowhatI'm
doingrightnow."
Whenanagenthasbeenaskedtorunsomecode,usingmyselfinthatcodereportstheagent(turtle,patchorlink)thatdidtheasking.
myselfismostoftenusedinconjunctionwithoftoreadorsetvariablesintheaskingagent.
myselfcanbeusedwithinblocksofcodenotjustintheaskcommand,butalsohatch,sprout,of,with,all?,with-min,with-max,min-one-of,
max-one-of,min-n-of,max-n-of.
ask turtles
[ ask patches in-radius 3
[ set pcolor [color] of myself ] ]
;; each turtle makes a colored "splotch" around itself
Seethe"MyselfExample"codeexampleformoreexamples.
Seealsoself.
N
n-of
n-ofsizeagentset
n-ofsizelist
Fromanagentset,reportsanagentsetofsizesizerandomlychosenfromtheinputset,withnorepeats.
Fromalist,reportsalistofsizesizerandomlychosenfromtheinputset,withnorepeats.Theitemsintheresultappearinthesameorder
thattheyappearedintheinputlist.(Ifyouwanttheminrandomorder,useshuffleontheresult.)
Itisanerrorforsizetobegreaterthanthesizeoftheinput.
ask n-of 50 patches [ set pcolor green ]
;; 50 randomly chosen patches turn green
Seealsoone-of.
n-values
n-valuessizereporter
Reportsalistoflengthsizecontainingvaluescomputedbyrepeatedlyrunningthereporter.reportermaybeananonymousreporterorthe
nameofareporter.
Ifthereporteracceptsinputs,theinputwillbethenumberoftheitemcurrentlybeingcomputed,startingfromzero.
show n-values 5 [1]
=> [1 1 1 1 1]
show n-values 5 [ i -> i ]
=> [0 1 2 3 4]
show n-values 3 turtle
=> [(turtle 0) (turtle 1) (turtle 2)]
show n-values 5 [ x -> x * x ]
=> [0 1 4 9 16]
Seealsoreduce,filter,->(anonymousprocedure),range.
neighbors
neighbors4
neighbors
neighbors4
Reportsanagentsetcontainingthe8surroundingpatches(neighbors)or4surroundingpatches(neighbors4).
show sum [count turtles-here] of neighbors
;; prints the total number of turtles on the eight
;; patches around this turtle or patch
show count turtles-on neighbors
;; a shorter way to say the same thing
ask neighbors4 [ set pcolor red ]
Since4.0
Since4.0
Since3.0
Since5.2
Since3.0
Since1.0
;; turns the four neighboring patches red
<breed>-neighbors
link-neighbors
<breed>-neighbors
link-neighbors
Reportstheagentsetofallturtlesfoundattheotherendofanylinks(undirectedordirected,incomingoroutgoing)connectedtothisturtle.
crt 3
ask turtle 0
[
create-links-with other turtles
ask link-neighbors [ set color red ] ;; turtles 1 and 2 turn red
]
ask turtle 1
[
ask link-neighbors [ set color blue ] ;; turtle 0 turns blue
]
end
<breed>-neighbor?
link-neighbor?
<breed>-neighbor?turtle
link-neighbor?turtle
Reportstrueifthereisalink(eitherdirectedorundirected,incomingoroutgoing)betweenturtleandthecaller.
crt 2
ask turtle 0
[
create-link-with turtle 1
show link-neighbor? turtle 1 ;; prints true
]
ask turtle 1
[
show link-neighbor? turtle 0 ;; prints true
]
netlogo-version
netlogo-version
ReportsastringcontainingtheversionnumberoftheNetLogoyouarerunning.
show netlogo-version
=> "6.0.4"
netlogo-web?
netlogo-web?
ReportstrueifthemodelisrunninginNetLogoWeb.
new-seed
new-seed
Reportsanumbersuitableforseedingtherandomnumbergenerator.
Thenumbersreportedbynew-seedarebasedonthecurrentdateandtimeinmillisecondsandlieinthegenerator'susablerangeofseeds,-
2147483648to2147483647.
new-seedneverreportsthesamenumbertwiceinsuccession,evenacrossparallelBehaviorSpaceruns.(Thisisaccomplishedbywaitinga
millisecondiftheseedforthecurrentmillisecondwasalreadyused.)
Seealsorandom-seed.
no-display
no-display
Turnsoffallupdatestothecurrentviewuntilthedisplaycommandisissued.Thishastwomajoruses.
One,youcancontrolwhentheuserseesviewupdates.Youmightwanttochangelotsofthingsontheviewbehindtheuser'sback,soto
speak,thenmakethemvisibletotheuserallatonce.
Two,yourmodelwillrunfasterwhenviewupdatingisoff,soifyou'reinahurry,thiscommandwillletyougetresultsfaster.(Notethat
Since4.0
Since4.0
Since1.0
Since4.0
Since4.0
Since1.0
normallyyoudon'tneedtouseno-displayforthis,sinceyoucanalsousetheon/offswitchinviewcontrolstriptofreezetheview.)
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsodisplay.
nobody
nobody
Thisisaspecialvaluewhichsomeprimitivessuchasturtle,one-of,max-one-of,etc.reporttoindicatethatnoagentwasfound.Also,whena
turtledies,itbecomesequaltonobody.
Note:Emptyagentsetsarenotequaltonobody.Ifyouwanttotestforanemptyagentset,useany?.Youonlygetnobodybackinsituations
whereyouwereexpectingasingleagent,notawholeagentset.
set target one-of other turtles-here
if target != nobody
[ ask target [ set color red ] ]
no-links
no-links
Reportsanemptylinkagentset.
no-patches
no-patches
Reportsanemptypatchagentset.
not
notboolean
Reportstrueifbooleanisfalse,otherwisereportsfalse.
if not any? turtles [ crt 10 ]
no-turtles
no-turtles
Reportsanemptyturtleagentset.
O
of
[reporter]ofagent
[reporter]ofagentset
Foranagent,reportsthevalueofthereporterforthatagent(turtleorpatch).
show [pxcor] of patch 3 5
;; prints 3
show [pxcor] of one-of patches
;; prints the value of a random patch's pxcor variable
show [who * who] of turtle 5
=> 25
show [count turtles in-radius 3] of patch 0 0
;; prints the number of turtles located within a
;; three-patch radius of the origin
Foranagentset,reportsalistthatcontainsthevalueofthereporterforeachagentintheagentset(inrandomorder).
crt 4
show sort [who] of turtles
=> [0 1 2 3]
show sort [who * who] of turtles
=> [0 1 4 9]
one-of
one-ofagentset
one-oflist
Fromanagentset,reportsarandomagent.Iftheagentsetisempty,reportsnobody.
Since1.0
Since4.0
Since4.0
Since4.0
Since4.0
Fromalist,reportsarandomlistitem.Itisanerrorforthelisttobeempty.
ask one-of patches [ set pcolor green ]
;; a random patch turns green
ask patches with [any? turtles-here]
[ show one-of turtles-here ]
;; for each patch containing turtles, prints one of
;; those turtles
;; suppose mylist is [1 2 3 4 5 6]
show one-of mylist
;; prints a value randomly chosen from the list
Seealson-of.
or
boolean1orboolean2
Reportstrueifeitherboolean1orboolean2,orboth,istrue.
Notethatifcondition1istrue,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) or (pycor > 0) [ set pcolor red ]
;; patches turn red except in lower-left quadrant
other
otheragentset
Reportsanagentsetwhichisthesameastheinputagentsetbutomitsthisagent.
show count turtles-here
=> 10
show count other turtles-here
=> 9
other-end
other-end
Ifrunbyaturtle,reportstheturtleattheotherendoftheaskinglink.
Ifrunbyalink,reportstheturtleattheendofthelinkthatisn'ttheaskingturtle.
Thesedefinitionsaredifficulttounderstandintheabstract,butthefollowingexamplesshouldhelp:
ask turtle 0 [ create-link-with turtle 1 ]
ask turtle 0 [ ask link 0 1 [ show other-end ] ] ;; prints turtle 1
ask turtle 1 [ ask link 0 1 [ show other-end ] ] ;; prints turtle 0
ask link 0 1 [ ask turtle 0 [ show other-end ] ] ;; prints turtle 1
Astheseexampleshopefullymakeplain,the"other"endistheendthatisneitheraskingnorbeingasked.
out-<breed>-neighbor?
out-link-neighbor?
out-<breed>-neighbor?turtle
out-link-neighbor?turtle
Reportstrueifthereisadirectedlinkgoingfromthecallertoturtleorifthereisanundirectedlinkconnectingthecallerwithturtle.Youcan
thinkofthisas"canIgetfromthecallertoturtleusingalink?"
crt 2
ask turtle 0 [
create-link-to turtle 1
show in-link-neighbor? turtle 1 ;; prints false
show out-link-neighbor? turtle 1 ;; prints true
]
ask turtle 1 [
show in-link-neighbor? turtle 0 ;; prints true
show out-link-neighbor? turtle 0 ;; prints false
]
out-<breed>-neighbors
out-link-neighbors
out-<breed>-neighbors
out-link-neighbors
Since4.0
Since2.1
Since2.1
Since2.1
Since2.1
Since1.0
Since2.0
Reportstheagentsetofalltheturtlesthathavedirectedlinksfromthecaller,orundirectedlinkswiththecaller.Youcanthinkofthisas"who
canIgettofromthecallerusingalink?"
crt 4
ask turtle 0
[
create-links-to other turtles
ask out-link-neighbors [ set color pink ] ;; turtles 1-3 turn pink
]
ask turtle 1
[
ask out-link-neighbors [ set color orange ] ;; no turtles change colors
;; since turtle 1 only has in-links
]
end
out-<breed>-to
out-link-to
out-<breed>-toturtle
out-link-toturtle
Reportsadirectedlinkfromthecallertoturtleoranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromthecallertoturtle."
crt 2
ask turtle 0 [
create-link-to turtle 1
show out-link-to turtle 1 ;; shows link 0 1
]
ask turtle 1
[
show out-link-to turtle 0 ;; shows nobody
]
Seealso:in-link-fromlink-with
output-print
output-show
output-type
output-write
output-printvalue
output-showvalue
output-typevalue
output-writevalue
Thesecommandsarethesameastheprint,show,type,andwritecommandsexceptthatvalueisprintedinthemodel'soutputarea,instead
ofintheCommandCenter.(Ifthemodeldoesnothaveaseparateoutputarea,thentheCommandCenterisused.)SeealsoOutput
(programmingguide).
P
patch
patchxcorycor
Giventhexandycoordinatesofapoint,reportsthepatchcontainingthatpoint.(Thecoordinatesareabsolutecoordinates;theyarenot
computedrelativetothisagent,aswithpatch-at.)
Ifxandyareintegers,thepointisthecenterofapatch.Ifxoryisnotaninteger,roundingtothenearestintegerisusedtodeterminewhich
patchcontainsthepoint.
Ifwrappingisallowedbythetopology,thegivencoordinateswillbewrappedtobewithintheworld.Ifwrappingisnotallowedandthegiven
coordinatesareoutsidetheworld,reportsnobody.
ask patch 3 -4 [ set pcolor green ]
;; patch with pxcor of 3 and pycor of -4 turns green
show patch 1.2 3.7
;; prints (patch 1 4); note rounding
show patch 18 19
;; supposing min-pxcor and min-pycor are -17
;; and max-pxcor and max-pycor are 17,
;; in a wrapping topology, prints (patch -17 -16);
;; in a non-wrapping topology, prints nobody
Seealsopatch-at.
patch-ahead
patch-aheaddistance
Since1.0
Since2.0
Since1.0
Since2.0
Since2.0
Since4.0
Reportsthesinglepatchthatisthegivendistance"ahead"ofthisturtle,thatis,alongtheturtle'scurrentheading.Reportsnobodyifthepatch
doesnotexistbecauseitisoutsidetheworld.
ask patch-ahead 1 [ set pcolor green ]
;; turns the patch 1 in front of this turtle
;; green; note that this might be the same patch
;; the turtle is standing on
Seealsopatch-at,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at
patch-atdxdy
Reportsthepatchat(dx,dy)fromthecaller,thatis,thepatchcontainingthepointdxeastanddypatchesnorthofthisagent.
Reportsnobodyifthereisnosuchpatchbecausethatpointisbeyondanon-wrappingworldboundary.
ask patch-at 1 -1 [ set pcolor green ]
;; if caller is a turtle or patch, turns the
;; patch just southeast of the caller green
Seealsopatch,patch-ahead,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at-heading-and-distance
patch-at-heading-and-distanceheadingdistance
patch-at-heading-and-distancereportsthesinglepatchthatisthegivendistancefromthisturtleorpatch,alongthegivenabsoluteheading.
(Incontrasttopatch-left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakenintoaccount.)Reportsnobodyifthe
patchdoesnotexistbecauseitisoutsidetheworld.
ask patch-at-heading-and-distance -90 1 [ set pcolor green ]
;; turns the patch 1 to the west of this patch green
Seealsopatch,patch-at,patch-left-and-ahead,patch-right-and-ahead.
patch-here
patch-here
patch-herereportsthepatchundertheturtle.
Notethatthisreporterisn'tavailabletoapatchbecauseapatchcanjustsay"self".
patch-left-and-ahead
patch-right-and-ahead
patch-left-and-aheadangledistance
patch-right-and-aheadangledistance
Reportsthesinglepatchthatisthegivendistancefromthisturtle,inthedirectionturnedleftorrightthegivenangle(indegrees)fromthe
turtle'scurrentheading.Reportsnobodyifthepatchdoesnotexistbecauseitisoutsidetheworld.
(Ifyouwanttofindapatchinagivenabsoluteheading,ratherthanonerelativetothecurrentturtle'sheading,usepatch-at-heading-and-
distanceinstead.)
ask patch-right-and-ahead 30 1 [ set pcolor green ]
;; this turtle "looks" 30 degrees right of its
;; current heading at the patch 1 unit away, and turns
;; that patch green; note that this might be the same
;; patch the turtle is standing on
Seealsopatch,patch-at,patch-at-heading-and-distance.
patch-set
patch-setvalue1
(patch-setvalue1value2...)
Reportsanagentsetcontainingallofthepatchesanywhereinanyoftheinputs.Theinputsmaybeindividualpatches,patchagentsets,
nobody,orlists(ornestedlists)containinganyoftheabove.
patch-set self
patch-set patch-here
(patch-set self neighbors)
Since4.1
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since1.0
Since1.0
(patch-set patch-here neighbors)
(patch-set patch 0 0 patch 1 3 patch 4 -2)
(patch-set patch-at -1 1 patch-at 0 1 patch-at 1 1)
patch-set [patch-here] of turtles
patch-set [neighbors] of turtles
Seealsoturtle-set,link-set.
patch-size
patch-size
Reportsthesizeofthepatchesintheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsoset-patch-size.
patches
patches
Reportstheagentsetconsistingofallpatches.
patches-own
patches-own[var1...]
Thiskeyword,liketheglobals,breed,<breed>-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeany
functiondefinitions.Itdefinesthevariablesthatallpatchescanuse.
Allpatcheswillthenhavethegivenvariablesandbeabletousethem.
Allpatchvariablescanalsobedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoglobals,turtles-own,breed,<breeds>-own.
pcolor
pcolor
Thisisabuilt-inpatchvariable.Itholdsthecolorofthepatch.Youcansetthisvariabletomakethepatchchangecolor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.ColorcanberepresentedeitherasaNetLogocolor(asingle
number)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
Seealsocolor.
pen-down
pd
pen-erase
pe
pen-up
pu
pen-down
pen-erase
pen-up
Theturtlechangesmodesbetweendrawinglines,removinglinesorneither.Thelineswillalwaysbedisplayedontopofthepatchesand
belowtheturtles.Tochangethecolorofthepensetthecoloroftheturtleusingset color.
Note:Whenaturtle'spenisdown,allmovementcommandscauselinestobedrawn,includingjump,setxy,andmove-to.
Note:Thesecommandsareequivalenttosettingtheturtlevariable"pen-mode"to"down","up",and"erase".
Note:OnWindowsdrawinganderasingalinemightnoteraseeverypixel.
pen-mode
Thisisabuilt-inturtlevariable.Itholdsthestateoftheturtle'spen.Yousetthevariabletodrawlines,eraselinesorstopeitherofthese
actions.Possiblevaluesare"up","down",and"erase".
pen-size
Since1.0
Since1.0
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Thisisabuilt-inturtlevariable.Itholdsthewidthoftheline,inpixels,thattheturtlewilldraw(orerase)whenthepenisdown(orerasing).
plabel
plabel
Thisisabuilt-inpatchvariable.Itmayholdavalueofanytype.Thepatchappearsintheviewwiththegivenvalue"attached"toitastext.
Youcansetthisvariabletoadd,change,orremoveapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel-color,label,label-color.
plabel-color
plabel-color
Thisisabuilt-inpatchvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolorthe
patch'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel,label,label-color.
plot
plotnumber
Incrementsthex-valueoftheplotpenbyplot-pen-interval,thenplotsapointattheupdatedx-valueanday-valueofnumber.(Thefirsttime
thecommandisusedonaplot,thepointplottedhasanx-valueof0.)
plot-name
plot-name
Reportsthenameofthecurrentplot(astring)
plot-pen-exists?
plot-pen-exists?string
Reportstrueifaplotpenwiththegivennameisdefinedinthecurrentplot.Otherwisereportsfalse.
plot-pen-down
plot-pen-up
plot-pen-down
plot-pen-up
Putsdown(orup)thecurrentplot-pen,sothatitdraws(ordoesn't).(Bydefault,allpensaredowninitially.)
plot-pen-reset
plot-pen-reset
Clearseverythingthecurrentplotpenhasdrawn,movesitto(0,0),andputsitdown.Ifthepenisapermanentpen,thecolor,mode,and
intervalareresettothedefaultvaluesfromtheplotEditdialog.
plotxy
plotxynumber1number2
Movesthecurrentplotpentothepointwithcoordinates(number1,number2).Ifthepenisdown,aline,bar,orpointwillbedrawn(depending
onthepen'smode).
plot-x-min
plot-x-max
plot-y-min
plot-y-max
plot-x-min
plot-x-max
plot-y-min
plot-y-max
Since1.0
Since1.0
Since1.0
Since1.0
Reportstheminimumormaximumvalueonthexoryaxisofthecurrentplot.
Thesevaluescanbesetwiththecommandsset-plot-x-rangeandset-plot-y-range.(TheirdefaultvaluesaresetfromtheplotEditdialog.)
position
positionitemlist
positionstring1string2
Onalist,reportsthefirstpositionofiteminlist,orfalseifitdoesnotappear.
Onstrings,reportsthepositionofthefirstappearancestring1asasubstringofstring2,orfalseifitdoesnotappear.
Note:Thepositionsarenumberedbeginningwith0,notwith1.
;; suppose mylist is [2 7 4 7 "Bob"]
show position 7 mylist
=> 1
show position 10 mylist
=> false
show position "in" "string"
=> 3
Seealsomember?.
precision
precisionnumberplaces
Reportsnumberroundedtoplacesdecimalplaces.
Ifplacesisnegative,theroundingtakesplacetotheleftofthedecimalpoint.
show precision 1.23456789 3
=> 1.235
show precision 3834 -3
=> 4000
Seealsoround,ceiling,floor.
print
printvalue
PrintsvalueintheCommandCenter,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikeshow.
Seealsoshow,type,write,output-print,andOutput(programmingguide).
pxcor
pycor
pxcor
pycor
Thesearebuilt-inpatchvariables.Theyholdthexandycoordinateofthepatch.Theyarealwaysintegers.Youcannotsetthesevariables,
becausepatchesdon'tmove.
pxcorisgreaterthanorequaltomin-pxcorandlessthanorequaltomax-pxcor;similarlyforpycorandmin-pycorandmax-pycor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoxcor,ycor.
R
random
randomnumber
Ifnumberispositive,reportsarandomintegergreaterthanorequalto0,butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomintegerlessthanorequalto0,butstrictlygreaterthannumber.
Ifnumberiszero,theresultisalways0aswell.
Note:InversionsofNetLogopriortoversion2.0,thisprimitivereportedafloatingpointnumberifgivenanon-integerinput.Thisisnolonger
thecase.Ifyouwantafloatingpointanswer,youmustnowuserandom-floatinstead.
show random 3
Since2.0
Since1.2.1
Since2.0
Since1.2.1
Since1.2.1
Since3.1
Since3.1
Since1.0
;; prints 0, 1, or 2
show random -3
;; prints 0, -1, or -2
show random 3.5
;; prints 0, 1, 2, or 3
Seealsorandom-float.
random-float
random-floatnumber
Ifnumberispositive,reportsarandomfloatingpointnumbergreaterthanorequalto0butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomfloatingpointnumberlessthanorequalto0,butstrictlygreaterthannumber.
Ifnumberiszero,theresultisalways0.
show random-float 3
;; prints a number at least 0 but less than 3,
;; for example 2.589444906014774
show random-float 2.5
;; prints a number at least 0 but less than 2.5,
;; for example 1.0897423196760796
random-exponential
random-gamma
random-normal
random-poisson
random-exponentialmean
random-gammaalphalambda
random-normalmeanstandard-deviation
random-poissonmean
Reportsanaccordinglydistributedrandomnumberwiththemeanand,inthecaseofthenormaldistribution,thestandard-deviation.(The
standarddeviationmaynotbenegative.)
random-exponentialreportsanexponentiallydistributedrandomfloatingpointnumber.Itisequivalentto(- mean) * ln random-float 1.0.
random-gammareportsagamma-distributedrandomfloatingpointnumberascontrolledbythefloatingpointalphaandlambdaparameters.
Bothinputsmustbegreaterthanzero.(Note:forresultswithagivenmeanandvariance,useinputsasfollows:alpha=mean*mean/
variance;lambda=1/(variance/mean).)
random-normalreportsanormallydistributedrandomfloatingpointnumber.
random-poissonreportsaPoisson-distributedrandominteger.
show random-exponential 2
;; prints an exponentially distributed random floating
;; point number with a mean of 2
show random-normal 10.1 5.2
;; prints a normally distributed random floating point
;; number with a mean of 10.1 and a standard deviation
;; of 5.2
show random-poisson 3.4
;; prints a Poisson-distributed random integer with a
;; mean of 3.4
random-pxcor
random-pycor
random-pxcor
random-pycor
Reportsarandomintegerrangingfrommin-pxcor(or-y)tomax-pxcor(or-y)inclusive.
ask turtles [
;; move each turtle to the center of a random patch
setxy random-pxcor random-pycor
]
Seealsorandom-xcor,random-ycor.
random-seed
random-seednumber
Setstheseedofthepseudo-randomnumbergeneratortotheintegerpartofnumber.Theseedmustbeintherange-2147483648to
2147483647;notethatthisissmallerthanthefullrangeofintegerssupportedbyNetLogo(-9007199254740992to9007199254740992).
SeetheRandomNumberssectionoftheProgrammingGuideformoredetails.
random-seed 47822
Since3.1
Since3.1
Since6.0
Since1.1
Since1.3
show random 100
=> 50
show random 100
=> 35
random-seed 47822
show random 100
=> 50
show random 100
=> 35
random-xcor
random-ycor
random-xcor
random-ycor
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinatesalongthegivenaxis,xory.
Turtlecoordinatesrangefrommin-pxcor-0.5(inclusive)tomax-pxcor+0.5(exclusive)horizontally;vertically,substitute-yfor-x.
ask turtles [
;; move each turtle to a random point
setxy random-xcor random-ycor
]
Seealsorandom-pxcor,random-pycor.
range
rangestop
(rangestartstop)
(rangestartstopstep)
Generatesalistofnumbers,startingatstart,endingbeforestop,countingbystep.startdefaultsto0andstepdefaultsto1.
show range 5
=> [0 1 2 3 4]
show (range 2 5)
=> [2 3 4]
show (range 2 5 0.5)
=> [2 2.5 3 3.5 4 4.5]
show (range 10 0 -1)
=> [10 9 8 7 6 5 4 3 2 1]
Seealson-values
read-from-string
read-from-stringstring
InterpretsthegivenstringasifithadbeentypedintheCommandCenter,andreportstheresultingvalue.Theresultmaybeanumber,list,
string,orbooleanvalue,orthespecialvalue"nobody".
Usefulinconjunctionwiththeuser-inputprimitiveforconvertingtheuser'sinputintousableform.
show read-from-string "3" + read-from-string "5"
=> 8
show length read-from-string "[1 2 3]"
=> 3
crt read-from-string user-input "Make how many turtles?"
;; the number of turtles input by the user
;; are created
reduce
reducereporterlist
Reducesalistfromlefttorightusingthegivenreporter,resultinginasinglevalue.Thismeans,forexample,thatreduce [ [a b] -> a + b]
[1 2 3 4]isequivalentto(((1+2)+3)+4).Iflisthasasingleitem,thatitemisreported.Itisanerrortoreduceanemptylist.reportermay
beananonymousreporterorthenameofareporter.
Thefirstinputpassedtothereporteristheresultsofar,andthesecondinputisthenextiteminthelist.
Sinceitcanbedifficulttodevelopanintuitionaboutwhatreducedoes,herearesomesimpleexampleswhich,whilenotusefulinthemselves,
maygiveyouabetterunderstandingofthisprimitive:
show reduce + [1 2 3]
=> 6
show reduce - [1 2 3]
=> -4
show reduce [ [result-so-far next-item] -> next-item - result-so-far ] [1 2 3]
=> 2
show reduce [ [result-so-far ignored-item] -> result-so-far ] [1 2 3]
=> 1
show reduce [ [ignored next-item] -> next-item ] [1 2 3]
=> 3
show reduce sentence [[1 2] [3 [4]] 5]
=> [1 2 3 [4] 5]
show reduce [ [result-so-far next-item] -> fput next-item result-so-far ] (fput [] [1 2 3 4 5])
Since1.2.1
Since1.0
Since1.0
Since2.0
=> [5 4 3 2 1]
Herearesomemoreusefulexamples:
;; find the longest string in a list
to-report longest-string [strings]
report reduce
[ [longest-so-far next-string] -> ifelse-value (length longest-so-far >= length next-string) [longest-so-far] [next-string] ]
strings
end
show longest-string ["hi" "there" "!"]
=> "there"
;; count the number of occurrences of an item in a list
to-report occurrences [x the-list]
report reduce
[ [occurrence-count next-item] -> ifelse-value (next-item = x) [occurrence-count + 1] [occurrence-count] ] (fput 0 the-list)
end
show occurrences 1 [1 2 1 3 1 2 3 1 1 4 5 1]
=> 6
;; evaluate the polynomial, with given coefficients, at x
to-report evaluate-polynomial [coefficients x]
report reduce [ [value coefficient] -> (x * value) + coefficient ] coefficients
end
;; evaluate 3x^2 + 2x + 1 at x = 4
show evaluate-polynomial [3 2 1] 4
=> 57
Seealsofilter,->(anonymousprocedure.
remainder
remaindernumber1number2
Reportstheremainderwhennumber1isdividedbynumber2.ThisisequivalenttothefollowingNetLogocode:
number1 - (int (number1 / number2)) * number2
show remainder 62 5
=> 2
show remainder -8 3
=> -2
Seealsomod.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
remove
removeitemlist
removestring1string2
Foralist,reportsacopyoflistwithallinstancesofitemremoved.
Forstrings,reportsacopyofstring2withalltheappearancesofstring1asasubstringremoved.
set mylist [2 7 4 7 "Bob"]
set mylist remove 7 mylist
;; mylist is now [2 4 "Bob"]
show remove "to" "phototonic"
=> "phonic"
remove-duplicates
remove-duplicateslist
Reportsacopyoflistwithallduplicateitemsremoved.Thefirstofeachitemremainsinplace.
set mylist [2 7 4 7 "Bob" 7]
set mylist remove-duplicates mylist
;; mylist is now [2 7 4 "Bob"]
remove-item
remove-itemindexlist
remove-itemindexstring
Foralist,reportsacopyoflistwiththeitematthegivenindexremoved.
Forstrings,reportsacopyofstringwiththecharacteratthegivenindexremoved.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
set mylist [2 7 4 7 "Bob"]
set mylist remove-item 2 mylist
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since4.0
Since1.0
Since4.1
;; mylist is now [2 7 7 "Bob"]
show remove-item 2 "string"
=> "sting"
repeat
repeatnumber[commands]
Runscommandsnumbertimes.
pd repeat 36 [ fd 1 rt 10 ]
;; the turtle draws a circle
replace-item
replace-itemindexlistvalue
replace-itemindexstring1string2
Onalist,replacesaniteminthatlist.indexistheindexoftheitemtobereplaced,startingwith0.(The6thiteminalistwouldhaveanindex
of5.)Notethat"replace-item"isusedinconjunctionwith"set"tochangealist.
Likewiseforastring,butthegivencharacterofstring1removedandthecontentsofstring2splicedininstead.
show replace-item 2 [2 7 4 5] 15
=> [2 7 15 5]
show replace-item 1 "cat" "are"
=> "caret"
report
reportvalue
Immediatelyexitsfromthecurrentto-reportprocedureandreportsvalueastheresultofthatprocedure.reportandto-reportarealwaysused
inconjunctionwitheachother.Seeto-reportforadiscussionofhowtousethem.
reset-perspective
rp
reset-perspective
Theobserverstopswatching,following,orridinganyturtles(orpatches).(Ifitwasn'twatching,following,orridinganybody,nothing
happens.)Inthe3Dview,theobserveralsoreturnstoitsdefaultposition(abovetheorigin,lookingstraightdown).
Seealsofollow,ride,watch.
reset-ticks
reset-ticks
Resetsthetickcountertozero,setsupallplots,thenupdatesallplots(sothattheinitialstateoftheworldisplotted).
Normallyreset-ticksgoesattheendofasetupprocedure.
Seealsoclear-ticks,tick,ticks,tick-advance,setup-plots,update-plots.
reset-timer
reset-timer
Resetsthetimertozeroseconds.Seealsotimer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsed
modeltimeinticks.
resize-world
resize-worldmin-pxcormax-pxcormin-pycormax-pycor
Changesthesizeofthepatchgrid.
Ifthegivenpatchgridcoordinatesaredifferentthantheonesinuse,allturtlesandlinksdie,andtheexistingpatchgridisdiscardedandnew
patchescreated.Otherwise,existingturtlesandlinkswillliveifthegridcoordinatesareunchanged.
Retainingreferencestooldpatchesorpatchsetsisinadvisableandmaysubsequentlycauseruntimeerrorsorotherunexpectedbehavior.
Since1.0
Since1.0
Since3.0
Since3.0
Since1.0
Since1.0
Since1.0
Seealsoset-patch-size.
reverse
reverselist
reversestring
Reportsareversedcopyofthegivenlistorstring.
show mylist
;; mylist is [2 7 4 "Bob"]
set mylist reverse mylist
;; mylist now is ["Bob" 4 7 2]
show reverse "live"
=> "evil"
rgb
rgbredgreenblue
ReportsaRGBlistwhengiventhreenumbersdescribinganRGBcolor.Thenumbersarerangecheckedtobebetween0and255.
Seealsohsb
ride
rideturtle
Settheperspectivetoturtle.
Everytimeturtlemovestheobserveralsomoves.Thus,inthe2DViewtheturtlewillstayatthecenteroftheview.Inthe3Dviewitisasif
lookingthroughtheeyesoftheturtle.Iftheturtledies,theperspectiveresetstothedefault.
Theobservermayonlywatchorfollowasinglesubject.Callingridewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingtheriddenturtleinstead.
Seealsoreset-perspective,watch,follow,subject.
ride-me
ride-me
Askstheobservertoridethisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingride-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingthisturtleinstead.
Seealsoride.
right
rt
rightnumber
Theturtleturnsrightbynumberdegrees.(Ifnumberisnegative,itturnsleft.)
round
roundnumber
Reportstheintegernearesttonumber.
Ifthedecimalportionofnumberisexactly.5,thenumberisroundedinthepositivedirection.
Notethatroundinginthepositivedirectionisnotalwayshowroundingisdoneinothersoftwareprograms.(Inparticular,itdoesnotmatch
thebehaviorofStarLogoT,whichalwaysroundednumbersendingin0.5tothenearesteveninteger.)Therationaleforthisbehavioristhatit
matcheshowturtlecoordinatesrelatetopatchcoordinatesinNetLogo.Forexample,ifaturtle'sxcoris-4.5,thenitisontheboundary
betweenapatchwhosepxcoris-4andapatchwhosepxcoris-5,buttheturtlemustbeconsideredtobeinonepatchortheother,sothe
turtleisconsideredtobeinthepatchwhosepxcoris-4,becauseweroundtowardsthepositivenumbers.
show round 4.2
=> 4
show round 4.5
=> 5
show round -4.5
=> -4
Seealsoprecision,ceiling,floor.
Since1.3
Since1.3
Since1.0
Since1.3
Since1.0
Since1.0
run
runresult
runcommand
(runcommandinput1...)
runstring
runresultreporter
(runresultreporterinput1...)
runresultstring
Therunformexpectsthenameofacommand,ananonymouscommand,orastringcontainingcommands.Thisagentthenrunsthem.
Therunresultformexpectsthenameofareporter,ananonymousreporter,orastringcontainingareporter.Thisagentrunsitandreports
theresult.
Notethatyoucan'tuseruntodefineorredefineprocedures.Ifyoucareaboutperformance,notethatthecodemustbecompiledfirstwhich
takestime.However,compiledbitsofcodearecachedbyNetLogoandthususingrunonthesamestringoverandoverismuchfasterthan
runningdifferentstrings.Thefirstrun,though,willbemanytimesslowerthanrunningthesamecodedirectly,orinananonymouscommand.
Anonymousproceduresarerecommendedoverstringswheneverpossible.(Anexampleofwhenyoumustusestringsisifyouaccept
piecesofcodefromtheuserofyourmodel.)
Anonymousproceduresmayfreelyreadand/orsetlocalvariablesandprocedureinputs.Tryingtodothesamewithstringsmayormaynot
workandshouldnotbereliedon.
Whenusinganonymousprocedures,youcanprovidethemwithinputs,ifyousurroundtheentirecallwithparentheses.Forexample:
(run [ [turtle-count step-count] -> crt turtle-count [ fd step-count ] ] 10 5)
;; creates 10 turtles and move them forward 5 steps
show (runresult [ [a b] -> a + b ] 10 5)
=> 15
;; adds 10 and 5
Seealsoforeach,->(anonymousprocedure).
S
scale-color
scale-colorcolornumberrange1range2
Reportsashadeofcolorproportionaltothevalueofnumber.
Ifrange1islessthanrange2,thenthelargerthenumber,thelightertheshadeofcolor.Butifrange2islessthanrange1,thecolorscalingis
inverted.
Ifnumberislessthanrange1,thenthedarkestshadeofcolorischosen.
Ifnumberisgreaterthanrange2,thenthelightestshadeofcolorischosen.
Note:forcolorshadeisirrelevant,e.g.greenandgreen+2areequivalent,andthesamespectrumofcolorswillbeused.
ask turtles [ set color scale-color red age 0 50 ]
;; colors each turtle a shade of red proportional
;; to its value for the age variable
self
self
 
Reportsthisturtle,patch,orlink.
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theagentwhoaskedmetodowhatI'mdoingright
now."
Notethatitisalwaysredundanttowrite[foo] of self.Thisisalwaysequivalenttosimplywritingfoo.
Seealsomyself.
;(semicolon)
;comments
Afterasemicolon,therestofthelineisignored.Thisisusefulforadding"comments"toyourcode--textthatexplainsthecodetohuman
readers.Extrasemicolonscanbeaddedforvisualeffect.
NetLogo'sEditmenuhasitemsthatletyoucommentoruncommentwholesectionsofcode.
sentence
se
Since1.0
Since2.0
Since1.0
Since1.0
Since1.0
sentencevalue1value2
(sentencevalue1...)
Makesalistoutofthevalues.Ifanyvalueisalist,itsitemsareincludedintheresultdirectly,ratherthanbeingincludedasasublist.
Examplesmakethisclearer:
show sentence 1 2
=> [1 2]
show sentence [1 2] 3
=> [1 2 3]
show sentence 1 [2 3]
=> [1 2 3]
show sentence [1 2] [3 4]
=> [1 2 3 4]
show sentence [[1 2]] [[3 4]]
=> [[1 2] [3 4]]
show (sentence [1 2] 3 [4 5] (3 + 3) 7)
=> [1 2 3 4 5 6 7]
set
setvariablevalue
Setsvariabletothegivenvalue.
Variablecanbeanyofthefollowing:
Aglobalvariabledeclaredusing"globals"
Theglobalvariableassociatedwithaslider,switch,chooser,orinputbox.
Avariablebelongingtothisagent
Ifthisagentisaturtle,avariablebelongingtothepatchundertheturtle.
Alocalvariablecreatedbytheletcommand.
Aninputtothecurrentprocedure.
set-current-directory
set-current-directorystring
Setsthecurrentdirectorythatisusedbytheprimitivesfile-delete,file-exists?,andfile-open.
Thecurrentdirectoryisnotusediftheabovecommandsaregivenanabsolutefilepath.Thisisdefaultedtotheuser'shomedirectoryfor
newmodels,andischangedtothemodel'sdirectorywhenamodelisopened.
NotethatinWindowsfilepathsthebackslashneedstobeescapedwithinastringbyusinganotherbackslash"C:\\"
Thechangeistemporaryandisnotsavedwiththemodel.
set-current-directory "C:\\NetLogo"
;; Assume it is a Windows Machine
file-open "my-file.txt"
;; Opens file "C:\\NetLogo\\my-file.txt"
set-current-plot
set-current-plotplotname
Setsthecurrentplottotheplotwiththegivenname(astring).Subsequentplottingcommandswillaffectthecurrentplot.
set-current-plot-pen
set-current-plot-penpenname
Thecurrentplot'scurrentpenissettothepennamedpenname(astring).Ifnosuchpenexistsinthecurrentplot,aruntimeerroroccurs.
set-default-shape
set-default-shapeturtlesstring
set-default-shapelinksstring
set-default-shapebreedstring
Specifiesadefaultinitialshapeforallturtlesorlinks,orforaparticularbreedofturtlesorlinks.Whenaturtleorlinkiscreated,oritchanges
breeds,itshapeissettothegivenshape.
Thiscommanddoesn'taffectexistingagents,onlyagentsyoucreateafterwards.
Thegivenbreedmustbeeitherturtles,links,orthenameofabreed.Thegivenstringmustbethenameofacurrentlydefinedshape.
Innewmodels,thedefaultshapeforallturtlesis"default".
Notethatspecifyingadefaultshapedoesnotpreventyoufromchanginganagent'sshapelater.Agentsdon'thavetobestuckwiththeir
breed'sdefaultshape.
Since1.0
Since4.1
Since6.0.2
Since1.0
Since1.0
Since1.0
create-turtles 1 ;; new turtle's shape is "default"
create-cats 1 ;; new turtle's shape is "default"
set-default-shape turtles "circle"
create-turtles 1 ;; new turtle's shape is "circle"
create-cats 1 ;; new turtle's shape is "circle"
set-default-shape cats "cat"
set-default-shape dogs "dog"
create-cats 1 ;; new turtle's shape is "cat"
ask cats [ set breed dogs ]
;; all cats become dogs, and automatically
;; change their shape to "dog"
Seealsoshape.
set-histogram-num-bars
set-histogram-num-barsnumber
Setthecurrentplotpen'splotintervalsothat,giventhecurrentxrangefortheplot,therewouldbenumbernumberofbarsdrawnifthe
histogramcommandiscalled.
Seealsohistogram.
__set-line-thickness
__set-line-thicknessnumber
Specifiesthethicknessoflinesandoutlinedelementsintheturtle'sshape.
Thedefaultvalueis0.Thisalwaysproduceslinesonepixelthick.
Non-zerovaluesareinterpretedasthicknessinpatches.Athicknessof1,forexample,produceslineswhichappearonepatchthick.(It's
commontouseasmallervaluesuchas0.5or0.2.)
Linesarealwaysatleastonepixelthick.
Thiscommandisexperimentalandmaychangeinlaterreleases.
set-patch-size
set-patch-sizesize
Setsthesizeofthepatchesoftheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsopatch-size,resize-world.
set-plot-background-color
set-plot-background-colorcolor
Setsthebackgroundcolorofthecurrentplot.Thecolormaybespecifiedasanumberoralist.SeetheColorssectionoftheprogramming
guideformoredetails.Thischangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,thebackgroundcolorwillrevertto
white.
Note:Plotbackgroundsdonotsupporttransparency.Ifalistisusedtosetthecolor,thealphacomponentwillbeignored.
set-plot-pen-color
set-plot-pen-colorcolor
Setsthecolorofthecurrentplotpentocolor.
set-plot-pen-interval
set-plot-pen-intervalnumber
Tellsthecurrentplotpentomoveadistanceofnumberinthexdirectionduringeachuseoftheplotcommand.(Theplotpenintervalalso
affectsthebehaviorofthehistogramcommand.)
set-plot-pen-mode
set-plot-pen-modenumber
Setsthemodethecurrentplotpendrawsintonumber.Theallowedplotpenmodesare:
0(linemode)theplotpendrawsalineconnectingtwopointstogether.
1(barmode):theplotpendrawsabarofwidthplot-pen-intervalwiththepointplottedastheupper(orlower,ifyouareplottinganegative
number)leftcornerofthebar.
Since5.0
Since1.0
Since1.0
Since1.0
Since1.0
Since2.1
2(pointmode):theplotpendrawsapointatthepointplotted.Pointsarenotconnected.
Thedefaultmodefornewpensis0(linemode).
setup-plots
setup-plots
Foreachplot,runsthatplot'ssetupcommands,includingthesetupcodeforanypensintheplot.
reset-tickshasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsoupdate-plots.
set-plot-x-range
set-plot-y-range
set-plot-x-rangeminmax
set-plot-y-rangeminmax
Setstheminimumandmaximumvaluesofthexoryaxisofthecurrentplot.
Thechangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,therangeswillreverttotheirdefaultvaluesassetinthe
plot'sEditdialog.
setxy
setxyxy
Theturtlesetsitsx-coordinatetoxanditsy-coordinatetoy.
Equivalenttoset xcor x set ycor y,exceptithappensinonetimestepinsteadoftwo.
Ifxoryisoutsidetheworld,NetLogowillthrowaruntimeerror,unlesswrappingisturnedonintherelevantdimensions.Forexample,with
wrappingturnedoninbothdimensionsandthedefaultworldsizewheremin-pxcor = -16,max-pxcor = 16,min-pycor = -16andmax-pycor =
16,askingaturtletosetxy 17 17willmoveittothecenterofpatch(-16,-16).
setxy 0 0
;; turtle moves to the middle of the center patch
setxy random-xcor random-ycor
;; turtle moves to a random point
setxy random-pxcor random-pycor
;; turtle moves to the center of a random patch
Seealsomove-to.
shade-of?
shade-of?color1color2
Reportstrueifbothcolorsareshadesofoneanother,falseotherwise.
show shade-of? blue red
=> false
show shade-of? blue (blue + 1)
=> true
show shade-of? gray white
=> true
shape
shape
Thisisabuilt-inturtleandlinkvariable.Itholdsastringthatisthenameoftheturtleorlink'scurrentshape.Youcansetthisvariableto
changetheshape.Newturtlesandlinkshavetheshape"default"unlesstheadifferentshapehasbeenspecifiedusingset-default-shape.
Example:
ask turtles [ set shape "wolf" ]
;; assumes you have made a "wolf"
;; shape in NetLogo's Turtle Shapes Editor
ask links [ set shape "link 1" ]
;; assumes you have made a "link 1" shape in
;; the Link Shapes Editor
Seealsoset-default-shape,shapes.
shapes
Since1.0
Since1.0
Since1.0
Since4.0
Since2.0
Since1.0
Since1.0
shapes
Reportsalistofstringscontainingalloftheturtleshapesinthemodel.
Newshapescanbecreated,orimportedfromtheshapeslibraryorfromothermodels,intheShapesEditor.
show shapes
=> ["default" "airplane" "arrow" "box" "bug" ...
ask turtles [ set shape one-of shapes ]
show
showvalue
PrintsvalueintheCommandCenter,precededbythisagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrack
ofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartowrite.
Seealsoprint,type,write,output-show,andOutput(programmingguide).
show-turtle
st
show-turtle
Theturtlebecomesvisibleagain.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"tofalse.
Seealsohide-turtle.
show-link
show-link
Thelinkbecomesvisibleagain.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"tofalse.
Seealsohide-link.
shuffle
shufflelist
Reportsanewlistcontainingthesameitemsastheinputlist,butinrandomizedorder.
show shuffle [1 2 3 4 5]
=> [5 2 4 1 3]
show shuffle [1 2 3 4 5]
=> [1 3 5 2 4]
sin
sinnumber
Reportsthesineofthegivenangle.Assumesangleisgivenindegrees.
show sin 270
=> -1
size
size
Thisisabuilt-inturtlevariable.Itholdsanumberthatistheturtle'sapparentsize.Thedefaultsizeis1,whichmeansthattheturtleisthe
samesizeasapatch.Youcansetthisvariabletochangeaturtle'ssize.
sort
sortlist
sortagentset
Reportsasortedlistofnumbers,strings,oragents.
Iftheinputcontainsnonumbers,strings,oragents,theresultistheemptylist.
Since1.3
Since5.0
Since1.0
Iftheinputcontainsatleastonenumber,thenumbersinthelistaresortedinascendingorderandanewlistreported;non-numbersare
ignored.
Or,iftheinputcontainsatleastonestring,thestringsinthelistaresortedinascendingorderandanewlistreported;non-stringsare
ignored.
Or,iftheinputisanagentsetoralistcontainingatleastoneagent,asortedlistofagents(neveranagentset)isreported;non-agentsare
ignored.Agentsaresortedinthesameorderthe<operatoruses.(Patchesaresortedwiththetopleft-mostpatchfirstandthebottomright-
mostpatchlast,turtlesaresortedbywhonumber).
show sort [3 1 4 2]
=> [1 2 3 4]
show sort [2 1 "a"]
=> [1 2]
show sort (list "a" "c" "b" (patch 0 0))
=> ["a" "b" "c"]
show sort (list (patch 0 0) (patch 0 1) (patch 1 0))
=> [(patch 0 1) (patch 0 0) (patch 1 0)]
;; label patches with numbers in left-to-right, top-to-bottom order
let n 0
foreach sort patches [ the-patch ->
ask the-patch [
set plabel n
set n n + 1
]
]
;; some additional examples to clarify behavior in strange cases
show sort (list patch 0 0 patch 0 1 patch 1 0 turtle 0 turtle 1) ; turtles are always sorted lower than patches
=> [(turtle 0) (turtle 1) (patch 0 1) (patch 0 0) (patch 1 0)]
show sort (list nobody false true) ; booleans and nobody cannot be sorted
=> []
show sort (list [1 2 3] turtles) ; lists and agentsets are not included if they are inside a list passed to sort
=> []
Seealsosort-by,sort-on.
sort-by
sort-byreporterlist
sort-byreporteragentset
Iftheinputisalist,reportsanewlistcontainingthesameitemsastheinputlist,inasortedorderdefinedbythebooleanreporter.reporter
maybeananonymousreporterorthenameofareporter.
Thetwoinputstoreporterarethevaluesbeingcompared.Thereportershouldreporttrueifthefirstargumentcomesstrictlybeforethe
secondinthedesiredsortorder,andfalseotherwise.
Iftheinputisanagentsetoralistofagents,reportsalist(neveranagentset)ofagents.
Iftheinputisalist,thesortisstable,thatis,theorderofitemsconsideredequalbythereporterisnotdisturbed.Iftheinputisanagentset,
tiesarebrokenrandomly.
show sort-by < [3 1 4 2]
=> [1 2 3 4]
show sort-by > [3 1 4 2]
=> [4 3 2 1]
show sort-by [ [string1 string2] -> length string1 < length string2 ] ["Grumpy" "Doc" "Happy"]
=> ["Doc" "Happy" "Grumpy"]
Seealsosort,sort-on,->(anonymousprocedure).
sort-on
sort-on[reporter]agentset
Reportsalistofagents,sortedaccordingtoeachagent'svalueforreporter.Tiesarebrokenrandomly.
Thevaluesmustbeallnumbers,allstrings,orallagentsofthesametype.
crt 3
show sort-on [who] turtles
=> [(turtle 0) (turtle 1) (turtle 2)]
show sort-on [(- who)] turtles
=> [(turtle 2) (turtle 1) (turtle 0)]
foreach sort-on [size] turtles
[ the-turtle -> ask the-turtle [ do-something ] ]
;; turtles run "do-something" one at a time, in
;; ascending order by size
Seealsosort,sort-by.
sprout
sproutnumber[commands]
sprout-<breeds>number[commands]
Createsnumbernewturtlesonthecurrentpatch.Thenewturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe
14primarycolors.Theturtlesimmediatelyruncommands.Thisisusefulforgivingthenewturtlesdifferentcolors,headings,orwhatever.
Since1.0
Since1.0
Since3.1
Since1.0
Since1.0
Since5.2
(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
Ifthesprout-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
sprout 5
sprout-wolves 10
sprout 1 [ set color red ]
sprout-sheep 1 [ set color black ]
Seealsocreate-turtles,hatch.
sqrt
sqrtnumber
Reportsthesquarerootofnumber.
stamp
stamp
Thisturtleorlinkleavesanimageofitsshapeinthedrawingatitscurrentlocation.
Note:Theshapesmadebystampmaynotbepixel-for-pixelidenticalfromcomputertocomputer.
stamp-erase
stamp-erase
Thisturtleorlinkremovesanypixelsbelowitinthedrawinginsidetheboundsofitsshape.
Note:Theshapesmadebystamp-erasemaynotbepixel-for-pixelidenticalfromcomputertocomputer.
standard-deviation
standard-deviationlist
Reportsthesamplestandarddeviationofalistofnumbers.Ignoresothertypesofitems.
(Notethatthisestimatesthestandarddeviationforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
show standard-deviation [1 2 3 4 5 6]
=> 1.8708286933869707
show standard-deviation [energy] of turtles
;; prints the standard deviation of the variable "energy"
;; from all the turtles
startup
startup
User-definedprocedurewhich,ifitexists,willbecalledwhenamodelisfirstloadedintheNetLogoapplication.
to startup
setup
end
startupdoesnotrunwhenamodelisrunheadlessfromthecommandline,orbyparallelBehaviorSpace.
stop
stop
Thisagentexitsimmediatelyfromtheenclosingprocedure,ask,orask-likeconstruct(e.g.crt,hatch,sprout).Onlytheenclosingprocedureor
constructstops,notallexecutionfortheagent.
if not any? turtles [ stop ]
;; exits if there are no more turtles
Note:stopcanalsobeusedtostopaforeverbutton.SeeButtonsintheProgrammingGuidefordetails.
stopcanalsobeusedtostopaBehaviorSpacemodelrun.Ifthegocommandsdirectlycallaprocedure,thenwhenthatprocedurecallsstop,
therunends.
stop-inspecting
Since5.2
Since3.0
Since2.1
Since1.0
Since2.1
Since1.0
Since1.0
stop-inspectingagent
Closestheagentmonitorforthegivenagent(turtleorpatch).Inthecasethatnoagentmonitorisopen,stop-inspectingdoesnothing.
stop-inspecting patch 2 4
;; the agent monitor for that patch closes
ask sheep [ stop-inspecting self ]
;; close all agent monitors for sheep
Seeinspectandstop-inspecting-dead-agents.
stop-inspecting-dead-agents
stop-inspecting-dead-agents
Closesallagentmonitorsfordeadagents.Seeinspectandstop-inspecting.
subject
subject
Reportstheturtle(orpatch)thattheobserveriscurrentlywatching,following,orriding.Reportsnobodyifthereisnosuchturtle(orpatch).
Seealsowatch,follow,ride.
sublist
substring
sublistlistposition1position2
substringstringposition1position2
Reportsjustasectionofthegivenlistorstring,rangingbetweenthefirstposition(inclusive)andthesecondposition(exclusive).
Note:Thepositionsarenumberedbeginningwith0,notwith1.
show sublist [99 88 77 66] 1 3
=> [88 77]
show substring "apartment" 1 5
=> "part"
subtract-headings
subtract-headingsheading1heading2
Computesthedifferencebetweenthegivenheadings,thatis,thenumberofdegreesinthesmallestanglebywhichheading2couldbe
rotatedtoproduceheading1.Apositiveanswermeansaclockwiserotation,anegativeanswercounterclockwise.Theresultisalwaysinthe
range-180to180,butisneverexactly-180.
Notethatsimplysubtractingthetwoheadingsusingthe-(minus)operatorwouldn'twork.Justsubtractingcorrespondstoalwaysrotating
clockwisefromheading2toheading1;butsometimesthecounterclockwiserotationisshorter.Forexample,thedifferencebetween5
degreesand355degreesis10degrees,not-350degrees.
show subtract-headings 80 60
=> 20
show subtract-headings 60 80
=> -20
show subtract-headings 5 355
=> 10
show subtract-headings 355 5
=> -10
show subtract-headings 180 0
=> 180
show subtract-headings 0 180
=> 180
sum
sumlist
Reportsthesumoftheitemsinthelist.
show sum [energy] of turtles
;; prints the total of the variable "energy"
;; from all the turtles
T
tan
tannumber
Since4.0
Since4.0
Since4.0
Since4.0
Reportsthetangentofthegivenangle.Assumestheangleisgivenindegrees.
thickness
thickness
Thisisabuilt-inlinkvariable.Itholdsanumberthatisthelink'sapparentsizeasafractionofthepatchsize.Thedefaultthicknessis0,which
meansthatregardlessofpatch-sizethelinkswillalwaysappear1pixelwide.Youcansetthisvariabletochangealink'sthickness.
tick
tick
Advancesthetickcounterbyoneandupdatesallplots.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Normallytickgoesattheendofagoprocedure.
Seealsoticks,tick-advance,reset-ticks,clear-ticks,update-plots.
tick-advance
tick-advancenumber
Advancesthetickcounterbynumber.Theinputmaybeanintegerorafloatingpointnumber.(Somemodelsdivideticksmorefinelythanby
ones.)Theinputmaynotbenegative.
Whenusingtick-basedviewupdates,theviewisnormallyupdatedevery1.0ticks,sousingtick-advancewithanumberlessthen1.0may
notalwaystriggeranupdate.Ifyouwanttomakesurethattheviewisupdated,youcanusethedisplaycommand.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Doesnotupdateplots.
Seealsotick,ticks,reset-ticks,clear-ticks.
ticks
ticks
Reportsthecurrentvalueofthetickcounter.Theresultisalwaysanumberandnevernegative.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Mostmodelsusethetickcommandtoadvancethetickcounter,inwhichcasetickswillalwaysreportaninteger.Ifthetick-advance
commandisused,thenticksmayreportafloatingpointnumber.
Seealsotick,tick-advance,reset-ticks,clear-ticks.
tie
tie
Tiesend1andend2ofthelinktogether.Ifthelinkisadirectedlinkend1istherootturtleandend2istheleafturtle.Themovementoftheroot
turtleaffectsthelocationandheadingoftheleafturtle.Ifthelinkisundirectedthetieisreciprocalsobothturtlescanbeconsideredroot
turtlesandleafturtles.Movementorchangeinheadingofeitherturtleaffectsthelocationandheadingoftheotherturtle.
Whentherootturtlemoves,theleafturtlesmovesthesamedistance,inthesamedirection.Theheadingoftheleafturtleisnotaffected.
Thisworkswithforward,jump,andsettingthexcororycoroftherootturtle.
Whentherootturtleturnsrightorleft,theleafturtleisrotatedaroundtherootturtlethesameamount.Theheadingoftheleafturtleisalso
changedbythesameamount.
Ifthelinkdies,thetierelationisremoved.
crt 2 [ fd 3 ]
;; creates a link and ties turtle 1 to turtle 0
ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
Seealsountie
tie-mode
tie-mode
Since1.0
Since1.0
Since1.0
Thisisabuilt-inlinkvariable.Itholdsastringthatisthenameofthetiemodethelinkiscurrentlyin.Usingthetieanduntiecommands
changesthemodeofthelink.Youcanalsosettie-modeto"free"tocreateanon-rigidjointbetweentwoturtles(seetheTiesectionofthe
ProgrammingGuidefordetails).Bydefaultlinksarenottied.
Seealso:tie,untie
timer
timer
Reportshowmanysecondshavepassedsincethecommandreset-timerwaslastrun(orsinceNetLogostarted).Thepotentialresolutionof
theclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfromsystemtosystem,dependingonthecapabilitiesof
theunderlyingJavaVirtualMachine.)
Seealsoreset-timer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsed
modeltimeinticks.
to
toprocedure-name
toprocedure-name[input1...]
Usedtobeginacommandprocedure.
to setup
clear-all
crt 500
end
to circle [radius]
crt 100 [ fd radius ]
end
to-report
to-reportprocedure-name
to-reportprocedure-name[input1...]
Usedtobeginareporterprocedure.
Thebodyoftheprocedureshouldusereporttoreportavaluefortheprocedure.Seereport.
to-report average [a b]
report (a + b) / 2
end
to-report absolute-value [number]
ifelse number >= 0
[ report number ]
[ report (- number) ]
end
to-report first-turtle?
report who = 0 ;; reports true or false
end
towards
towardsagent
Reportstheheadingfromthisagenttothegivenagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardswillusethewrapped
path.
Note:askingfortheheadingfromanagenttoitself,oranagentonthesamelocation,willcausearuntimeerror.
set heading towards turtle 1
;; same as "face turtle 1"
Seealsoface.
towardsxy
towardsxyxy
Reportstheheadingfromtheturtleorpatchtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardsxywillusethewrapped
path.
Since1.0
Since4.0
Since1.0
Since1.0
Since1.0
Since2.0
Note:askingfortheheadingtothepointtheagentisalreadystandingonwillcausearuntimeerror.
Seealsofacexy.
turtle
turtlenumber
<breed>number
Reportstheturtlewiththegivenwhonumber,ornobodyifthereisnosuchturtle.Forbreededturtlesyoumayalsousethesinglebreedform
torefertothem.
ask turtle 5 [ set color red ]
;; turtle with who number 5 turns red
turtle-set
turtle-setvalue1
(turtle-setvalue1value2...)
Reportsanagentsetcontainingalloftheturtlesanywhereinanyoftheinputs.Theinputsmaybeindividualturtles,turtleagentsets,nobody,
orlists(ornestedlists)containinganyoftheabove.
turtle-set self
(turtle-set self turtles-on neighbors)
(turtle-set turtle 0 turtle 2 turtle 9)
(turtle-set frogs mice)
Seealsopatch-set,link-set.
turtles
turtles
Reportstheagentsetconsistingofallturtles.Thisisaspecialagentsetthatcangrowasturtlesareaddedtotheworld,seetheprogramming
guideformoreinfo.
show count turtles
;; prints the number of turtles
turtles-at
turtles-atdxdy
<breeds>-atdxdy
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy)fromthecaller.(Theresultmayincludethecalleritselfifthecallerisaturtle.)
create-turtles 5 [ setxy 2 3 ]
show count [turtles-at 1 1] of patch 1 2
=> 5
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
turtles-here
turtles-here
<breeds>-here
Reportsanagentsetcontainingalltheturtlesonthecaller'spatch(includingthecalleritselfifit'saturtle).
crt 10
ask turtle 0 [ show count turtles-here ]
=> 10
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
breed [cats cat]
breed [dogs dog]
create-cats 5
create-dogs 1
ask dogs [ show count cats-here ]
=> 5
turtles-on
turtles-onagent
Since1.0
turtles-onagentset
<breeds>-onagent
<breeds>-onagentset
Reportsanagentsetcontainingalltheturtlesthatareonthegivenpatchorpatches,orstandingonthesamepatchasthegiventurtleor
turtles.
ask turtles [
if not any? turtles-on patch-ahead 1
[ fd 1 ]
]
ask turtles [
if not any? turtles-on neighbors [
die-of-loneliness
]
]
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
turtles-own
turtles-own[var1...]
<breeds>-own[var1...]
Theturtles-ownkeyword,liketheglobals,breed,<breeds>-own,andpatches-ownkeywords,canonlybeusedatthebeginningofaprogram,
beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachturtle.
Ifyouspecifyabreedinsteadof"turtles",onlyturtlesofthatbreedhavethelistedvariables.(Morethanoneturtlebreedmaylistthesame
variable.)
breed [cats cat ]
breed [dogs dog]
breed [hamsters hamster]
turtles-own [eyes legs] ;; applies to all breeds
cats-own [fur kittens]
hamsters-own [fur cage]
dogs-own [hair puppies]
Seealsoglobals,patches-own,breed,<breeds>-own.
type
typevalue
PrintsvalueintheCommandCenter,notfollowedbyacarriagereturn(unlikeprintandshow).Thelackofacarriagereturnallowsyoutoprint
severalvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikeshow.
type 3 type " " print 4
=> 3 4
Seealsoprint,show,write,output-type,andOutput(programmingguide).
U
undirected-link-breed
undirected-link-breed[<link-breeds><link-breed>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.It
definesanundirectedlinkbreed.Linksofaparticularbreedarealwayseitheralldirectedorallundirected.Thefirstinputdefinesthenameof
theagentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreedname
hasitsbuilt-invariablebreedsettothatagentset
isdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
undirected-link-breed [streets street]
undirected-link-breed [highways highway]
to setup
clear-all
crt 2
ask turtle 0 [ create-street-with turtle 1 ]
ask turtle 0 [ create-highway-with turtle 1 ]
end
ask turtle 0 [ show sort my-links ]
;; prints [(street 0 1) (highway 0 1)]
Seealsobreed,directed-link-breed
Since4.0
Since5.0
Since1.0
Since1.0
Since3.1
Since3.1
Since3.1
untie
untie
Untiesend2fromend1(setstie-modeto"none")iftheywerepreviouslytiedtogether.Ifthelinkisanundirectedlink,thenitwilluntieend1
fromend2aswell.Itdoesnotremovethelinkbetweenthetwoturtles.
Seealsotie
SeetheTiesectionoftheProgrammingGuideformoredetails.
update-plots
update-plots
Foreachplot,runsthatplot'supdatecommands,includingtheupdatecodeforanypensintheplot.
tickhasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.Modelsthatusefractionalticksmayneed
update-plots,sincetick-advancedoesnotupdatetheplots.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsosetup-plots.
uphill
uphill4
uphillpatch-variable
uphill4patch-variable
Movestheturtletotheneighboringpatchwiththehighestvalueforpatch-variable.Ifnoneighboringpatchhasahighervaluethanthecurrent
patch,theturtlestaysput.Iftherearemultiplepatcheswiththesamehighestvalue,theturtlepicksonerandomly.Non-numericvaluesare
ignored.
uphillconsiderstheeightneighboringpatches;uphill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
move-to patch-here ;; go to patch center
let p max-one-of neighbors [patch-variable] ;; or neighbors4
if [patch-variable] of p > patch-variable [
face p
move-to p
]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(uphill)or90(uphill4).
Seealsodownhill,downhill4.
user-directory
user-directory
Opensadialogthatallowstheusertochooseanexistingdirectoryonthesystem.
Itreportsastringwiththeabsolutepathorfalseiftheusercancels.
set-current-directory user-directory
;; Assumes the user will choose a directory
user-file
user-file
Opensadialogthatallowstheusertochooseanexistingfileonthesystem.
Itreportsastringwiththeabsolutefilepathorfalseiftheusercancels.
file-open user-file
;; Assumes the user will choose a file
user-new-file
user-new-file
Opensadialogthatallowstheusertochoosealocationandnameofanewfiletobecreated.Itreportsastringwiththeabsolutefilepathor
falseiftheusercancels.
Since1.1
Since1.1
Since3.1
Since2.0
Since1.0
file-open user-new-file
;; Assumes the user will choose a file
Notethatthisreporterdoesn'tactuallycreatethefile;normallyyouwouldcreatethefileusingfile-open,asintheexample.
Iftheuserchoosesanexistingfile,theywillbeaskediftheywishtoreplaceitornot,butthereporteritselfdoesn'tcausethefiletobe
replaced.Todothatyouwouldusefile-delete.
user-input
user-inputvalue
Reportsthestringthatausertypesintoanentryfieldinadialogwithtitlevalue.
valuemaybeofanytype,butistypicallyastring.
show user-input "What is your name?"
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-message
user-messagevalue
Opensadialogwithvaluedisplayedasthemessagetotheuser.
valuemaybeofanytype,butistypicallyastring.
user-message (word "There are " count turtles " turtles.")
Notethatifauserclosestheuser-messagedialogwiththe"X"inthecorner,thebehaviorwillbethesameasiftheyhadclicked"OK".
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-one-of
user-one-ofvaluelist-of-choices
Opensadialogwithvaluedisplayedasthemessageandlist-of-choicesdisplayedasapopupmenufortheusertoselectfrom.
Reportstheiteminlist-of-choicesselectedbytheuser.
valuemaybeofanytype,butistypicallyastring.
if "yes" = user-one-of "Set up the model?" ["yes" "no"]
[ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-yes-or-no?
user-yes-or-no?value
Reportstrueorfalsebasedontheuser'sresponsetovalue.
valuemaybeofanytype,butistypicallyastring.
if user-yes-or-no? "Set up the model?"
[ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
V
variance
variancelist
Reportsthesamplevarianceofalistofnumbers.Ignoresothertypesofitems.
(Notethatthiscomputesanunbiasedestimateofthevarianceforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
Thesamplevarianceisthesumofthesquaresofthedeviationsofthenumbersfromtheirmean,dividedbyonelessthanthenumberof
numbersinthelist.
show variance [2 7 4 3 5]
=> 3.7
Since1.0
Since3.0
Since3.0
Since1.0
W
wait
waitnumber
Waitthegivennumberofseconds.(Thisneedn'tbeaninteger;youcanspecifyfractionsofseconds.)Notethatyoucan'texpectcomplete
precision;theagentwillneverwaitlessthanthegivenamount,butmightwaitslightlymore.
repeat 10 [ fd 1 wait 0.5 ]
Whiletheagentiswaiting,nootheragentscandoanything.Everythingstopsuntiltheagentisdone.
Seealsoevery.
watch
watchagent
Putsaspotlightonagent.Inthe3Dviewtheobserverwillalsoturntofacethesubject.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-
me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch-me.
watch-me
watch-me
Askstheobservertowatchthisagent.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-
me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch.
while
while[reporter][commands]
Ifreporterreportsfalse,exittheloop.Otherwiseruncommandsandrepeat.
Thereportermayhavedifferentvaluesfordifferentagents,sosomeagentsmayruncommandsadifferentnumberoftimesthanother
agents.
while [any? other turtles-here]
[ fd 1 ]
;; turtle moves until it finds a patch that has
;; no other turtles on it
who
who
Thisisabuilt-inturtlevariable.Itholdstheturtle's"whonumber"orIDnumber,anintegergreaterthanorequaltozero.Youcannotsetthis
variable;aturtle'swhonumberneverchanges.
Whonumbersstartat0.Adeadturtle'snumberwillnotbereassignedtoanewturtleuntilyouusetheclear-turtlesorclear-allcommands,at
whichtimewhonumberingstartsoveragainat0.
Example:
show [who] of turtles with [color = red]
;; prints a list of the who numbers of all red turtles
;; in the Command Center, in random order
crt 100
[ ifelse who < 50
[ set color red ]
[ set color blue ] ]
;; turtles 0 through 49 are red, turtles 50
;; through 99 are blue
Youcanusetheturtlereportertoretrieveaturtlewithagivenwhonumber.Seealsoturtle.
Notethatwhonumbersaren'tbreed-specific.Notwoturtlescanhavethesamewhonumber,eveniftheyaredifferentbreeds:
clear-turtles
Since1.0
Since4.0
Since2.1
Since2.1
Since4.0
create-frogs 1
create-mice 1
ask turtles [ print who ]
;; prints (in some random order):
;; (frog 0): 0
;; (mouse 1): 1
Eventhoughweonlyhaveonemouse,itismouse 1notmouse 0,becausethewhonumber0wasalreadytakenbythefrog.
with
agentsetwith[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,abooleanreporter.Reportsanewagentsetcontaining
onlythoseagentsthatreportedtrue--inotherwords,theagentssatisfyingthegivencondition.
show count patches with [pcolor = red]
;; prints the number of red patches
<breed>-with
link-with
<breed>-withturtle
link-withturtle
Reportsalinkbetweenturtleandthecaller(directedorundirected,incomingoroutgoing).Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.
crt 2
ask turtle 0 [
create-link-with turtle 1
show link-with turtle 1 ;; prints link 0 1
]
Seealso:in-link-from,out-link-to
with-max
agentsetwith-max[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingall
agentsreportingthemaximumvalueofthegivenreporter.
show count patches with-max [pxcor]
;; prints the number of patches on the right edge
Seealsomax-one-of,max-n-of.
with-min
agentsetwith-min[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingonly
thoseagentsthathavetheminimumvalueofthegivenreporter.
show count patches with-min [pycor]
;; prints the number of patches on the bottom edge
Seealsomin-one-of,min-n-of.
with-local-randomness
with-local-randomness[commands]
Thecommandsarerunwithoutaffectingsubsequentrandomevents.Thisisusefulforperformingextraoperations(suchasoutput)without
changingtheoutcomeofamodel.
Example:
;; Run #1:
random-seed 50 setup repeat 10 [ go ]
;; Run #2:
random-seed 50 setup
with-local-randomness [ watch one-of turtles ]
repeat 10 [ go ]
Sinceone-ofisusedinsidewith-local-randomness,bothrunswillbeidentical.
Specificallyhowitworksis,thestateoftherandomnumbergeneratorisrememberedbeforethecommandsrun,thenrestoredafterwards.(If
youwanttorunthecommandswithafreshrandomstateinsteadofthesamerandomstatethatwillberestoredlater,youcanbeginthe
Since1.1
Since1.0
Since3.1
Since3.1
Since1.0
Since2.0
commandswithrandom-seed new-seed.)
Thefollowingexampledemonstratesthattherandomnumbergeneratorstateisthesamebothbeforethecommandsrunandafterwards.
random-seed 10
with-local-randomness [ print n-values 10 [random 10] ]
;; prints [8 9 8 4 2 4 5 4 7 9]
print n-values 10 [random 10]
;; prints [8 9 8 4 2 4 5 4 7 9]
without-interruption
without-interruption[commands]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitinnewmodels.
Theagentrunsallthecommandsintheblockwithoutallowingotheragentsusingask-concurrentto"interrupt".Thatis,otheragentsareput
"onhold"anddonotrunanycommandsuntilthecommandsintheblockarefinished.
Note:Thiscommandisonlyusefulinconjunctionwithask-concurrent.
Seealsoask-concurrent.
word
wordvalue1value2
(wordvalue1...)
Concatenatestheinputstogetherandreportstheresultasastring.
show word "tur" "tle"
=> "turtle"
word "a" 6
=> "a6"
set directory "c:\\foo\\fish\\"
show word directory "bar.txt"
=> "c:\foo\fish\bar.txt"
show word [1 54 8] "fishy"
=> "[1 54 8]fishy"
show (word 3)
=> "3"
show (word "a" "b" "c" 1 23)
=> "abc123"
world-width
world-height
world-width
world-height
ThesereportersgivethetotalwidthandheightoftheNetLogoworld.
Thewidthequalsmax-pxcor-min-pxcor+1andtheheightequalsmax-pycor-min-pycor+1.
Seealsomax-pxcor,max-pycor,min-pxcor,andmin-pycor
wrap-color
wrap-colornumber
wrap-colorcheckswhethernumberisintheNetLogocolorrangeof0to140(notincluding140itself).Ifitisnot,wrap-color"wraps"the
numericinputtothe0to140range.
Thewrappingisdonebyrepeatedlyaddingorsubtracting140fromthegivennumberuntilitisinthe0to140range.(Thisisthesame
wrappingthatisdoneautomaticallyifyouassignanout-of-rangenumbertothecolorturtlevariableorpcolorpatchvariable.)
show wrap-color 150
=> 10
show wrap-color -10
=> 130
write
writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytotheCommandCenter,notfollowedbyacarriage
return(unlikeprintandshow).
Thisagentisnotprintedbeforethevalue,unlikeshow.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.
write "hello world"
=> "hello world"
Since1.0
Since6.0
Seealsoprint,show,type,output-write,andOutput(programmingguide).
X
xcor
xcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentxcoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pxcor-0.5)andstrictlylessthan(max-pxcor+0.5).
Seealsosetxy,ycor,pxcor,pycor,
xor
boolean1xorboolean2
Reportstrueifeitherboolean1orboolean2istrue,butnotwhenbotharetrue.
if (pxcor > 0) xor (pycor > 0)
[ set pcolor blue ]
;; upper-left and lower-right quadrants turn blue
Y
ycor
ycor
Thisisabuilt-inturtlevariable.Itholdsthecurrentycoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pycor-0.5)andstrictlylessthan(max-pycor+0.5).
Seealsosetxy,xcor,pxcor,pycor,
->
->
[[args]->commands]
[[args]->reporter]
Createsandreportsananonymousprocedure-acommandorreporter-dependingontheinput.Withincommandsorreporterthelistedargs
maybeusedjustasyouwoulduseletorprocedurevariables.Thevariablenamesinargshavethesamerestrictionsasvariablenamesof
commandsandreporters.Inaddition,theymustnotmatchthenameofanyletorprocedurevariableintheirprocedure.
Anonymousproceduresarecommonlyusedwiththeprimitivesforeach,map,reduce,filter,sort-by,andn-values.Seethoseentriesfor
exampleusage.
SeetheAnonymousProceduressectionoftheProgrammingGuidefordetails.

Navigation menu