NetLogo 6.0.4 User Manual Net Logo
NetLogo%20User%20Manual
User Manual:
Open the PDF directly: View PDF .
Page Count: 436 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Table of Contents
- What is NetLogo?
- Copyright and License Information
- What's new?
- Version 6.0.4 (May 2018)
- Version 6.0.3 (March 2018)
- Version 6.0.2 (August 2017)
- Version 6.0.1 (March 2017)
- Version 6.0 (December 2016)
- Version 5.3.1 (February 2016)
- Version 5.3 (December 2015)
- Version 5.2.1 (September 2015)
- Version 5.2.0 (April 2015)
- 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
- Contacting Us
- Sample Model: Party
- Tutorial #1: Models
- Tutorial #2: Commands
- Tutorial #3: Procedures
- Interface Guide
- Interface Tab Guide
- Info Tab
- Code Tab Guide
- Programming Guide
- Transition Guide
- Changes for NetLogo 6.0.3
- 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
- Changes for NetLogo 5.0
- Changes for NetLogo 4.1
- Changes for NetLogo 4.0
- Changes for NetLogo 3.1
- Shapes Editor Guide
- BehaviorSpace Guide
- System Dynamics Guide
- HubNet Guide
- Understanding HubNet
- Computer HubNet
- Activities
- Clients
- Requirements
- Starting an activity
- HubNet Control Center
- Troubleshooting
- I started a HubNet activity, but when participants open a HubNet Client, my activity isn’t listed.
- 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).
- The view on the HubNet client is gray.
- There is no view on the HubNet client.
- I can’t quit a HubNet client.
- 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.
- My problem is not addressed on this page.
- Known Limitations
- Teacher workshops
- HubNet Authoring Guide
- Running HubNet in headless mode
- Getting help
- HubNet Authoring Guide
- Modeling Commons Guide
- Logging
- Controlling Guide
- Mathematica Link
- NetLogo 3D
- Introduction
- Tutorial
- 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
- 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
- NetLogo Arduino Extension
- NetLogo Array Extension
- NetLogo Bitmap Extension
- NetLogo Cf Extension
- NetLogo Csv Extension
- NetLogo Gis Extension
- Using
- 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
- 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
- Citing LevelSpace in Research
- Primitives
- NetLogo Matrix Extension
- Using
- 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:-
- 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
- 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
- nw:load-graphml
- nw:load
- nw:save
- NetLogo Palette Extension
- NetLogo Profiler Extension
- NetLogo R Extension
- NetLogo Rnd Extension
- NetLogo Sound Extension
- NetLogo Table Extension
- NetLogo Vid Extension
- Concepts
- 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
- 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
- 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
- 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?
- 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
- NetLogo 3D
- Extensions
- General
- NetLogo Dictionary
- Categories
- Built-In Variables
- Keywords
- Constants
- A
- B
- 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
- create-temporary-plot-pen1.1
- D
- E
- F
- G
- 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
- 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
- L
- 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
- O
- 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
- 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
- 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
- U
- V
- W
- X
- Y
- ->
TheNetLogo6.0.4UserManual
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
TableofContents
TableofContents
WhatisNetLogo?
Features
CopyrightandLicenseInformation
Howtoreference
Acknowledgments
NetLogolicense
Commerciallicenses
NetLogoUserManuallicense
Opensource
Thirdpartylicenses
Scala
MersenneTwisterFast
Colt
Config
ApacheCommonsCodec(TM)
Flexmark
JHotDraw
JOGL
Matrix3D
ASM
Log4j
PicoContainer
Parboiled
RSyntaxTextArea
JCodec
Java-Objective-CBridge
Webcam-capture
Guava
Gephi
RExtension
JNA
What'snew?
Version6.0.4(May2018)
FeatureChanges
Bugfixes
DocumentationChanges
ModelChanges
Version6.0.3(March2018)
FeatureChanges
DocumentationChanges
Bugfixes
ExtensionChanges
DocumentationChanges
ModelChanges
Version6.0.2(August2017)
FeatureChanges
Bugfixes
ExtensionChanges
DocumentationChanges
ModelChanges
Version6.0.1(March2017)
FeatureChanges
Bugfixes
ExtensionChanges
DocumentationChanges
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
Version6.0(December2016)
FeatureChanges
Bugfixes
LanguageChanges
ExtensionChanges
OperatingSystemSupport
DocumentationChanges
InternationalizationChanges
Models
Version5.3.1(February2016)
FeatureChanges
ExtensionChanges
Bugfixes
Version5.3(December2015)
FeatureChanges
ExtensionChanges
Version5.2.1(September2015)
Extensions
Newfeatures
Bugfixes
Modelchanges
Version5.2.0(April2015)
Extensions
Newfeatures
Bugfixes
Modelchanges
Version5.1.0(July2014)
Version5.0.4(March2013)
Version5.0(February2012)
Version4.1.3(April2011)
Version4.1(December2009)
Version4.0(September2007)
Version3.1(April2006)
Version3.0(September2005)
Version2.1(December2004)
Version2.0.2(August2004)
Version2.0(December2003)
Version1.3(June2003)
Version1.2(March2003)
Version1.1(July2002)
Version1.0(April2002)
SystemRequirements
ApplicationRequirements
Windows
MacOSX
Linux
3DRequirements
32-bitor64-bit?
ContactingUs
Website
Feedback,questions,etc.
Reportingbugs
Opensource
SampleModel:Party
AtaParty
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
Thinkingwithmodels
What’snext?
Tutorial#1:Models
SampleModel:WolfSheepPredation
ControllingtheModel:Buttons
Controllingspeed:SpeedSlider
AdjustingSettings:SlidersandSwitches
GatheringInformation:PlotsandMonitors
Plots
Monitors
ControllingtheView
ModelsLibrary
SampleModels
CurricularModels
CodeExamples
HubNetActivities
What’sNext?
Tutorial#2:Commands
SampleModel:TrafficBasic
CommandCenter
Workingwithcolors
AgentMonitorsandAgentCommanders
What’sNext?
Tutorial#3:Procedures
Agentsandprocedures
Makingthesetupbutton
Switchingtotick-basedviewupdates
Makingthegobutton
Experimentingwithcommands
Patchesandvariables
Turtlevariables
Monitors
Switchesandlabels
Moreprocedures
Plotting
Tickcounter
Somemoredetails
What’snext?
Appendix:Completecode
InterfaceGuide
Menus
Chart:NetLogomenus
Tabs
InternationalUsage
Charactersets
Languages
Supportfortranslators
InterfaceTabGuide
Workingwithinterfaceelements
Chart:InterfaceToolbar
The2Dand3Dviews
Manipulatingthe3DView
CommandCenter
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
Accessingpreviouscommands
Clearing
Arranging
Plots
PlotPens
Sliders
AgentMonitors
InfoTab
Editing
Headings
Input
Paragraphs
Example
Formatted
Italicizedandboldtext
Example
Formatted
Orderedlists
Example
Formatted
Unorderedlists
Example
Formatted
Links
Automaticlinks
Linkswithtext
Locallinks
Images
Example
Formatted
Localimages
Blockquotations
Example
Formatted
Code
Example
Formatted
Codeblocks
Example
Formatted
Superscriptsandsubscripts
Example
Formatted
Notesonusage
Otherfeatures
CodeTabGuide
CheckingforErrors
Find&Replace
AutomaticIndentation
MoreEditingOptions
IncludedFilesMenu
ProgrammingGuide
Agents
Procedures
Variables
Tickcounter
Whentotick
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
Fractionalticks
Colors
Ask
Agentsets
Specialagentsets
Agentsetsandlists
Breeds
Linkbreeds
Buttons
Lists
Math
Randomnumbers
Auxiliarygenerator
Localrandomness
Turtleshapes
Linkshapes
Viewupdates
Continuousupdates
Tick-basedupdates
Choosingamode
Framerate
Plotting
Plottingpoints
Plotcommands
Otherkindsofplots
Histograms
Clearingandresetting
Rangesandautoscaling
UsingaLegend
Temporaryplotpens
set-current-plotandset-current-plot-pen
Conclusion
Strings
Output
HowOutputPrimitivesDiffer
FileI/O
Movies
Perspective
Drawing
Topology
Links
Anonymousprocedures
Anonymousprocedureprimitives
Anonymousprocedureinputs
Anonymousproceduresandstrings
Concisesyntax
Anonymousproceduresasclosures
Nonlocalexits
Anonymousproceduresandextensions
Limitations
WhatisOptional?
Codeexample
Ask-Concurrent
UserInteractionPrimitives
Whatdoes“Halt”mean?
Tie
Multiplesourcefiles
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
Commandsandreporters
ComparedtootherLogos
TransitionGuide
ChangesforNetLogo6.0.3
ArduinoExtensionChanges
CFExtensionChanges
ChangesforNetLogo6.0
TasksreplacedbyAnonymousProcedures
Linkreportersoverhauledtobemoreconsistentandflexible
RemovalofApplets
ChangestotheNetLogoUserInterface
NobodyNotPermittedasaChooserValue
Breedsmusthavesingularandpluralnames
Removalof“Movie”Prims
ImprovedNameCollisionDetection
Removalofhubnet-set-client-interface
Improved&UpdatedExtensionsAPI
Addrangeprimitive
ChangesforNetLogo5.2
hsbprimitives
GoGoextension
ChangesforNetLogo5.0
Plotting
Tickcounter
Unicodecharacters
Infotabs
Modelspeed
Listperformance
ExtensionsAPI
ChangesforNetLogo4.1
Combiningsetandof
ChangesforNetLogo4.0
Whonumbering
Turtlecreation:randomizedvs.“ordered”
Addingstringsandlists
The-atprimitives
Links
New“of”syntax
Serialask
Tickcounter
Viewupdatemodes
Speedslider
Numbers
Agentsetbuilding
RGBColors
Tie
ChangesforNetLogo3.1
Agentsets
Wrapping
Randomturtlecoordinates
ShapesEditorGuide
Gettingstarted
Importingshapes
Creatingandeditingturtleshapes
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
Overlappingshapes
Undo
Colors
Otherbuttons
Shapedesign
Keepingashape
Creatingandeditinglinkshapes
Changinglinkshapeproperties
Usingshapesinamodel
BehaviorSpaceGuide
WhatisBehaviorSpace?
WhyBehaviorSpace?
HowItWorks
Managingexperimentsetups
Creatinganexperimentsetup
SpecialprimitivesforBehaviorSpaceexperiments
Runninganexperiment
AdvancedUsage
Runningfromthecommandline
SettingupexperimentsinXML
AdjustingJVMParameters
ControllingAPI
SystemDynamicsGuide
WhatistheNetLogoSystemDynamicsModeler?
BasicConcepts
SampleModels
HowitWorks
DiagramTab
CodeTab
TheSystemDynamicsModelerandNetLogo
Tutorial:Wolf-SheepPredation
Step1:SheepReproduction
Step2:NetLogoIntegration
Step3:WolfPredation
HubNetGuide
UnderstandingHubNet
NetLogo
HubNetArchitecture
ComputerHubNet
Activities
Clients
Requirements
Startinganactivity
HubNetControlCenter
Troubleshooting
KnownLimitations
Teacherworkshops
HubNetAuthoringGuide
RunningHubNetinheadlessmode
Gettinghelp
HubNetAuthoringGuide
CodingHubNetactivities
Setup
Receivingmessagesfromclients
Sendingmessagestoclients
Examples
Howtomakeaclientinterface
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
Viewupdatesontheclients
Clickingintheviewonclients
Customizingtheclient’sview
Plotupdatesontheclients
ModelingCommonsGuide
Introduction
ModelingCommonsAccounts
UploadingModels
UploadANewModel
UploadAChildOfAnExistingModel(“forking”)
UpdatingAnExistingModel
Logging
Startinglogging
MacOSXorWindows
Linuxandothers
Usinglogging
Wherelogsarestored
Howtoconfiguretheloggingoutput
AdvancedConfiguration
ControllingGuide
MathematicaLink
WhatcanIdowithit?
Installation
Usage
KnownIssues
Sourcecode
Credits
NetLogo3D
Introduction
3DWorlds
Theobserverandthe3Dview
CustomShapes
Tutorial
Step1:Depth
Step2:TurtleMovement
Step3:ObserverMovement
Dictionary
CommandsandReporters
Built-InVariables
Primitives
at-points4.1
distancexyz4.1distancexyz-nowrap4.1
dz4.1
facefacexyz4.1
left4.1
link-pitch4.1.2
load-shapes-3d4.1
max-pzcor4.1min-pzcor4.1
neighbors4.1neighbors64.1
orbit-down4.1orbit-left4.1orbit-right4.1orbit-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.1tilt-up4.1
towards-pitch4.1towards-pitch-nowrap4.1
towards-pitch-xyz4.1towards-pitch-xyz-nowrap4.1
turtles-at4.1<breeds>-at
world-depth4.1
zcor
zoom4.1
ExtensionsGuide
UsingExtensions
Whereextensionsarelocated
NetLogoArduinoExtension
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
NetLogoArrayExtension
Using
WhentoUse
ExampleuseofArrayExtension
Primitives
array:from-list
array:item
array:set
array:length
array:to-list
NetLogoBitmapExtension
Using
WhatdoestheBitmapExtensiondo?
Gettingstarted
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
NetLogoCfExtension
Primitives
cf:ifelse
cf:ifelse-value
NetLogoCsvExtension
Commonusecasesandexamples
Readafileallatonce
Readafileonelineatatime
Readafileonelinepertick
Writeafile
Primitives
FormattingNetLogodataasCSV
ParsingCSVinputtoNetLogodata
csv:from-row
csv:from-string
csv:from-file
csv:to-row
csv:to-string
csv:to-file
NetLogoGisExtension
Using
Howtouse
KnownIssues
Credits
Primitives
RasterDatasetPrimitives
DatasetPrimitives
VectorDatasetPrimitives
CoordinateSystemPrimitives
DrawingPrimitives
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
NetLogoGogoExtension
Usage
Changes
Primitives
OtherOutputs
Utilities
General
Sensors
OutputsandServos
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
NetLogoLsExtension
LevelSpacefundamentals
HeadlessandInteractiveModels
KeepingTrackofModels
Ageneralusecase:AskingandReporting
Ageneralusecase:Inter-ModelInteractions
AgeneralUsecase:Tidyingup“Dead”ChildModels
CitingLevelSpaceinResearch
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
CommandingandReporting
LogicandControl
OpeningandClosingModels
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
NetLogoMatrixExtension
Using
WhentoUse
HowtoUse
Example
Primitives
Matrixcreationandconversionto/fromlists
Advancedfeatures
Matrixdataretrievalandmanipulation
Mathoperations
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
NetLogoNwExtension
Usage
Specialagentsetsvsnormalagentsets
Anoteregardingfloatingpointcalculations
Performance
Primitives
Generators
PathandDistance
Clusterer/CommunityDetection
ContextManagement
ImportandExport
CentralityMeasures
ClusteringMeasures
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
NetLogoPaletteExtension
UsingthePaletteExtension
GettingStarted
WhatcolorsshouldIuse?
ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?
ExampleModels
FurtherReading
Primitives
palette:scale-gradient
palette:scale-scheme
palette:scheme-colors
palette:scale-gradient
References
NetLogoProfilerExtension
UsingtheProfilerExtension
Howtouse
Example
Primitives
profiler:calls
profiler:exclusive-time
profiler:inclusive-time
profiler:start
profiler:stop
profiler:reset
profiler:report
NetLogoRExtension
Using
SomeTips
Installing
InstallingR
ConfiguringtheRextension
Determiningr.homeandjri.home.paths
Windows-SpecificInstallationSteps
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
LoadingRpackagesfails
AfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextension
Specificerrorcodelist
Citation
CopyrightandLicense
NetLogoRndExtension
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
Anoteaboutperformance
Primitives
AgentSetPrimitives
ListPrimitives
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
NetLogoSoundExtension
Using
HowtoUse
MIDIsupport
Primitives
sound:drums
sound:instruments
sound:play-drum
sound:play-note
sound:play-note-later
DrumNames
InstrumentNames
NetLogoTableExtension
Using
WhentoUse
Example
ManipulatingTables
KeyRestrictions
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
NetLogoVidExtension
Concepts
VideoSource
SourceLifecycle
VideoRecorder
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
NetLogoView2.5dExtension
HowtoUse
IncorporatingIntoModels
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(FrequentlyAskedQuestions)
General
WhyisitcalledNetLogo?
HowdoIciteNetLogoorHubNetinapublication?
HowdoIciteamodelfromtheModelsLibraryinapublication?
WhereandwhenwasNetLogocreated?
WhatprogramminglanguagewasNetLogowrittenin?
What’stherelationshipbetweenStarLogoandNetLogo?
UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?
DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?
ArethereanyNetLogotextbooks?
IsNetLogoavailableinotherlanguagesbesidesEnglish?
IsNetLogocompiledorinterpreted?
Hasanyonebuiltamodelof<x>?
AreNetLogomodelsrunsscientificallyreproducible?
WillNetLogoandNetLogo3Dremainseparate?
CanIrunNetLogoonmyphoneortablet?
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?
I’monaUNIXsystemandIcan’tuntarthedownload.Why?
HowdoIinstallNetLogounattended?
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?
WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?
WhydoesNetLogobundleJava?
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
HowcomeNetLogowon’tstartuponmyLinuxmachine?
WhenItrytoinstallNetLogoonWindows,Isee“WindowsprotectedyourPC”
WhenItrytostartNetLogoonWindowsIgetanerror“TheJVMcouldnotbestarted”.Help!
NetLogowon’tstartonMacOSSierra(orlater)
NetLogowon’tstartonWindowsorcrashessuddenlyonMacOSSierra
CanIrunNetLogofromthecommandline,withouttheGUI?
DoesNetLogotakeadvantageofmultipleprocessors?
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?
IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
WhyisHubNetDiscoveryNotWorking?
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?
CanIusethemouseto“paint”intheview?
Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmymodelcontain?
CanIuseGISdatainNetLogo?
Mymodelrunsslowly.HowcanIspeeditup?
CanIhavemorethanonemodelopenatatime?
CanIchangethechoicesinachooseronthefly?
CanIdividethecodeformymodelupintoseveralfiles?
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?
HowcomemymodelfromanearlierNetLogodoesn’tworkright?
HowdoItakethenegativeofanumber?
Myturtlemovedforward1,butit’sstillonthesamepatch.Why?
HowdoIkeepmyturtlesonpatchcenters?
patch-ahead1isreportingthesamepatchmyturtleisalreadystandingon.Why?
HowdoIgivemyturtles“vision”?
Canagentssensewhat’sinthedrawinglayer?
I’mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?
Thedocumentationsaysthatrandom-float1mightreturn0butwillneverreturn1.WhatifIwant1tobeincluded?
HowcanIkeeptwoturtlesfromoccupyingthesamepatch?
HowcanIfindoutifaturtleisdead?
DoesNetLogohavearrays?
DoesNetLogohavehashtablesorassociativearrays?
HowcanIusedifferentpatch“neighborhoods”(circular,VonNeumann,Moore,etc.)?
HowcanIconvertanagentsettoalistofagents,orviceversa?
HowdoIstopforeach?
I’mtryingtomakealist.WhydoIkeepgettingtheerror“Expectedaconstant”?
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?
HowdoImeasurerunseverynticks?
I’mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn’twork.Why?
NetLogo3D
DoesNetLogoworkwithmystereoscopicdevice?
Extensions
I’mwritinganextension.Whydoesthecompilersayitcan’tfindorg.nlogo.api?
NetLogoDictionary
Categories
Turtle-related
Patch-related
Link-related
Agentset
Color
Controlflowandlogic
AnonymousProcedures
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-InVariables
Turtles
Patches
Links
Other
Keywords
Constants
MathematicalConstants
BooleanConstants
ColorConstants
A
abs1.0
acos1.3
all?4.0
and1.0
any?2.0
approximate-hsb4.0
approximate-rgb4.0
ArithmeticOperators+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.0auto-plot-on1.0
B
back1.0bk1.0
base-colors4.0
beep2.1
behaviorspace-experiment-name5.2
behaviorspace-run-number4.1.1
both-ends4.0
breed
breed
but-first1.0butfirst1.0bf1.0but-last1.0butlast1.0bl1.0
C
can-move?3.1
carefully2.1
ceiling1.0
clear-all1.0ca1.0
clear-all-plots1.0
clear-drawing3.0cd3.0
clear-globals5.2
clear-links4.0
clear-output1.0
clear-patches1.0cp1.0
clear-plot
clear-ticks5.0
clear-turtles1.0ct1.0
color
cos1.0
count1.0
create-ordered-turtles4.0cro4.0
create-<breed>-tocreate-<breeds>-tocreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-withcreate-
<breeds>-withcreate-link-to4.0create-links-to4.0create-link-from4.0create-links-from4.0create-link-with4.0
create-links-with4.0
create-turtles1.0crt1.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.0downhill41.0
dx1.0dy1.0
E
empty?1.0
end
end14.0
end24.0
error5.0
error-message2.1
every1.0
exp1.0
export-view3.0export-interface2.0export-output1.0export-plot1.0export-all-plots1.2.1export-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.0fd1.0
fput1.0
G
globals
H
hatch1.0
heading
hidden?
hide-link4.0
hide-turtle1.0ht1.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.1hubnet-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>-neighborsin-link-neighbors4.0
in-<breed>-fromin-link-from4.0
__includes4.0
in-radius1.0
insert-item6.0.2
inspect1.1
int1.0
is-agent?1.2.1is-agentset?1.2.1is-anonymous-command?6.0is-anonymous-reporter?6.0is-boolean?1.2.1is-
directed-link?4.0is-link?4.0is-link-set?4.0is-list?1.0is-number?1.2.1is-patch?1.2.1is-patch-set?4.0is-string?1.0
is-turtle?1.2.1is-turtle-set?4.0is-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.0lt1.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.1max-pycor3.1
mean1.0
median1.0
member?1.0
min1.0
min-n-of4.0
min-one-of1.0
min-pxcor3.1min-pycor3.1
mod1.0
modes2.0
mouse-down?1.0
mouse-inside?3.0
mouse-xcor1.0mouse-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.1neighbors41.1
<breed>-neighborslink-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>-neighborsout-link-neighbors4.0
out-<breed>-toout-link-to4.0
output-print2.1output-show2.1output-type2.1output-write2.1
P
patch1.0
patch-ahead2.0
patch-at1.0
patch-at-heading-and-distance2.0
patch-here1.0
patch-left-and-ahead2.0patch-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.0pd1.0pen-erase3.0pe3.0pen-up1.0pu1.0
pen-mode
pen-size
plabel
plabel-color
plot1.0
plot-name1.0
plot-pen-exists?4.0
plot-pen-down1.0plot-pen-up1.0
plot-pen-reset1.0
plotxy1.0
plot-x-min1.0plot-x-max1.0plot-y-min1.0plot-y-max1.0
position1.0
precision1.0
print1.0
pxcorpycor
R
random1.0
random-float2.0
random-exponential1.2.1random-gamma2.0random-normal1.2.1random-poisson1.2.1
random-pxcor3.1random-pycor3.1
random-seed1.0
random-xcor3.1random-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.0rp3.0
reset-ticks4.0
reset-timer1.0
resize-world4.1
reverse1.0
rgb1.0
ride3.0
ride-me3.0
right1.0rt1.0
round1.0
run1.3runresult1.3
S
scale-color1.0
self1.3
;(semicolon)
sentence1.0se1.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.0set-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.0st1.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.1substring1.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.0uphill41.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
WhatisNetLogo?
NetLogoisaprogrammablemodelingenvironmentforsimulatingnaturalandsocial
phenomena.ItwasauthoredbyUriWilenskyin1999andhasbeenincontinuous
developmenteversinceattheCenterforConnectedLearningandComputer-Based
Modeling.
NetLogoisparticularlywellsuitedformodelingcomplexsystemsdevelopingovertime.
Modelerscangiveinstructionstohundredsorthousandsof“agents”alloperating
independently.Thismakesitpossibletoexploretheconnectionbetweenthemicro-level
behaviorofindividualsandthemacro-levelpatternsthatemergefromtheirinteraction.
NetLogoletsstudentsopensimulationsand“play”withthem,exploringtheirbehaviorunder
variousconditions.Itisalsoanauthoringenvironmentwhichenablesstudents,teachersand
curriculumdeveloperstocreatetheirownmodels.NetLogoissimpleenoughforstudentsand
teachers,yetadvancedenoughtoserveasapowerfultoolforresearchersinmanyfields.
NetLogohasextensivedocumentationandtutorials.ItalsocomeswiththeModelsLibrary,a
largecollectionofpre-writtensimulationsthatcanbeusedandmodified.Thesesimulations
addresscontentareasinthenaturalandsocialsciencesincludingbiologyandmedicine,
physicsandchemistry,mathematicsandcomputerscience,andeconomicsandsocial
psychology.Severalmodel-basedinquirycurriculausingNetLogoareavailableandmoreare
underdevelopment.
NetLogoisthenextgenerationoftheseriesofmulti-agentmodelinglanguagesincluding
StarLogoandStarLogoT.NetLogorunsontheJavaVirtualMachine,soitworksonallmajor
platforms(Mac,Windows,Linux,etal).Itisrunasadesktopapplication.Commandline
operationisalsosupported.
Features
System:
Free,opensource
Cross-platform:runsonMac,Windows,Linux,etal
Internationalcharactersetsupport
Programming:
Fullyprogrammable
Approachablesyntax
LanguageisLogodialectextendedtosupportagents
Mobileagents(turtles)moveoveragridofstationaryagents(patches)
Linkagentsconnectturtlestomakenetworks,graphs,andaggregates
Largevocabularyofbuilt-inlanguageprimitives
Doubleprecisionfloatingpointmath
First-classfunctionvalues(akaanonymousprocedures,closures,lambda)
Runsarereproduciblecross-platform
Environment:
Commandcenterforon-the-flyinteraction
Interfacebuilderw/buttons,sliders,switches,choosers,monitors,textboxes,
notes,outputarea
Infotabforannotatingyourmodelwithformattedtextandimages
HubNet:participatorysimulationsusingnetworkeddevices
Agentmonitorsforinspectingandcontrollingagents
Exportandimportfunctions(exportdata,saveandrestorestateofmodel,makea
movie)
BehaviorSpace,anopensourcetoolusedtocollectdatafrommultipleparallel
runsofamodel
SystemDynamicsModeler
NetLogo3Dformodeling3Dworlds
Headlessmodeallowsdoingbatchrunsfromthecommandline
Displayandvisualization:
Line,bar,andscatterplots
Speedsliderletsyoufastforwardyourmodelorseeitinslowmotion
Viewyourmodelineither2Dor3D
Scalableandrotatablevectorshapes
Turtleandpatchlabels
APIs:
controllingAPIallowsembeddingNetLogoinascriptorapplication
extensionsAPIallowsaddingnewcommandsandreporterstotheNetLogo
language;opensourceexampleextensionsareincluded
CopyrightandLicenseInformation
NetLogo6.0.4UserManual
Howtoreference
IfyouuseorrefertoNetLogoinapublication,weaskthatyouciteit.Thecorrectcitationis:
Wilensky,U.(1999).NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnected
LearningandComputer-BasedModeling,NorthwesternUniversity,Evanston,IL.
ForHubNet,cite:Wilensky,U.&Stroup,W.,1999.HubNet.
http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnectedLearningand
Computer-BasedModeling,NorthwesternUniversity.Evanston,IL.
FormodelsintheModelsLibrary,thecorrectcitationisincludedinthe"Creditsand
References"sectionofeachmodel'sInfotab.
Acknowledgments
TheCCLgratefullyacknowledgestwodecadesofsupportforourNetLogowork.Theoriginal
supportcamefromtheNationalScienceFoundation--grantnumbersREC-9814682and
REC-0126227.FurthersupporthascomefromREC-0003285,REC-0115699,DRL-0196044,
CCF-ITR-0326542,DRL-REC/ROLE-0440113,SBE-0624318,EEC-0648316,IIS-0713619,
DRL-RED-9552950,DRL-REC-9632612,andDRL-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-1614745andDRL-
1640201.AdditionalsupportcamefromtheSpencerFoundation,TexasInstruments,the
BradyFund,theMurphyfund,andtheNorthwesternInstituteonComplexSystems.
NetLogolicense
Copyright1999-2018byUriWilensky.
Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsofthe
GNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2
oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;
withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULAR
PURPOSE.SeetheGNUGeneralPublicLicenseformoredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwiththisprogram;
ifnot,writetotheFreeSoftwareFoundation,Inc.,51FranklinStreet,FifthFloor,Boston,MA
02110-1301,USA.
Commerciallicenses
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,pleasecontact
UriWilenskyaturi@northwestern.edu.
NetLogoUserManuallicense
Copyright1999-2018byUriWilensky.
TheNetLogoUserManualbyUriWilenskyislicensedunderaCreativeCommonsAttribution-
ShareAlike3.0UnportedLicense.
Opensource
TheNetLogosourcecodeishostedathttps://github.com/NetLogo/NetLogo.Contributions
frominterestedusersarewelcome.
Thirdpartylicenses
Scala
MuchofNetLogoiswrittenintheScalalanguageandusestheScalastandardlibraries.The
licenseforScalaisasfollows:
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
Forrandomnumbergeneration,NetLogousestheMersenneTwisterFastclassbySeanLuke.
Thecopyrightforthatcodeisasfollows:
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
PartsofNetLogo(specifically,therandom-gammaprimitive)arebasedoncodefromtheColt
library(http://acs.lbl.gov/~hoschek/colt/).Thecopyrightforthatcodeisasfollows:
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
NetLogousestheTypesafe"Config"library.Copyright(C)2011-2012TypesafeInc.
http://typesafe.comTheConfiglibraryislicensedundertheApache2.0License.Youmay
obtainacopyofthelicenseathttp://www.apache.org/licenses/LICENSE-2.0.
ApacheCommonsCodec(TM)
TheNetLogocompilerusesadigestmethodfromtheApacheCommonsCodec(TM)library.
ApacheCommonsCodec(TM)iscopyrightandtrademark2002-2014theApacheSoftware
Foundation.ItislicensedundertheApache2.0License.Youmayobtainacopyofthelicense
athttp://www.apache.org/licenses/LICENSE-2.0.
Flexmark
NetLogousestheFlexmarklibrary(andextensions)fortheinfotab.Thecopyrightandlicense
areasfollows:
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
Forthesystemdynamicsmodeler,NetLogousestheJHotDrawlibrary,whichisCopyright(c)
1996,1997byIFAInformatikandErichGamma.ThelibraryiscoveredbytheGNULGPL
(LesserGeneralPublicLicense).Thetextofthatlicenseisincludedinthe"docs"folderwhich
accompaniestheNetLogodownload,andisalsoavailablefrom
http://www.gnu.org/copyleft/lesser.html.
JOGL
For3Dgraphicsrendering,NetLogousesJOGL,aJavaAPIforOpenGL,andGluegen,an
automaticcodegenerationtool.FormoreinformationaboutJOGLandGluegen,see
jogamp.org/.BothlibrariesaredistributedundertheBSDlicense:
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
For3Dmatrixoperations,NetLogousestheMatrix3Dclass.Itisdistributedunderthe
followinglicense:
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
ForJavabytecodegeneration,NetLogousestheASMlibrary.Itisdistributedunderthe
followinglicense:
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
Forlogging,NetLogousestheLog4jlibrary.Thecopyrightandlicenseforthelibraryareas
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
Fordependencyinjection,NetLogousesthePicoContainerlibrary.Thecopyrightandlicense
forthelibraryareasfollows:
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
Forreadingmodels,NetLogousestheParboiledlibrary.Thecopyrightandlicensefor
Parboiledareasfollows:
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
TheNetLogoeditorusestheRSyntaxTextArealibrary.Thecopyrightandlicenseareas
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 ©RIGHT 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
TheNetLogovidextensionmakesuseoftheJCodeclibrary.Thecopyrightandlicensefor
JCodecareasfollows:
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-CBridge
NetLogoonMacOSXmakesuseoftheJava-Objective-CBridgelibrary.Thislibrarywas
createdbySteveHannahandisdistributedundertheApache2.0license,availableat
https://www.apache.org/licenses/LICENSE-2.0.
Webcam-capture
TheNetLogovidextensionmakesuseoftheWebcam-capturelibrary.Thecopyrightand
licenseforWebcam-captureareasfollows:
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
TheNetLogolsextensionmakesuseoftheGuavalibrary.Guavaisreleasedunderthe
ApacheLicense2.0(http://www.apache.org/licenses/LICENSE-2.0)
Gephi
ThenwextensionmakesuseoftheGephilibrary.Gephiislicensedunderthefollowingterms:
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.
RExtension
TheNetLogoRExtensionislicensedunderthefollowingterms:
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
TheNetLogoRExtensionmakesuseoftheJNAlibrary.TheJNAlibraryislicensedunderthe
followingterms:
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'snew?
NetLogo6.0.4UserManual
Thefollowingisacondensedhistory.DetailedreleasenotesareonGitHub.
Forhelprunningmodelsmadeinoldversions,seetheTransitionGuide.
Version6.0.4(May2018)
FeatureChanges
NetLogonowsupportsthePortugueselanguage.
BehaviorSpaceallowsoptionallydisablingplotsandtheviewwhenrunning
experiments.
Bugfixes
UpdatedthebundledJava8,whichshouldresolveanissuewithNetLogofailingtostart
onWindowscomputers.
Fixedanumericalerrorwiththerangeprimitive.
Fixedabugwithlinklookupwhenusingmorethantwolinkbreeds.
CommentanduncommentcodehotkeysshouldworkwithNetLogoincludesourcefiles.
Addedabettererrormessagewhenawebbrowsercouldn’tbelaunchedforanyreason.
DocumentationChanges
Documentthatresize-worldonlykillsallturtleswhencoordinatesreallychange.
ModelChanges
NewCurricularModels
MindtheGapCurriculum
MTG1EqualOpportunitiesHubNet
MTG2RandomAssignmentHubNet
MTG3FeedbackLoopHubNet
RevisedSampleModels
BloodSugarRegulation:Updatedstatisticalsamplingprocedures
Flocking:Changeddefaultvisionto5.0patches
RumorMill:Fixedaminorbugwiththespreadstatisticsinearlyticks
RevisedCodeExamples
Flocking(PerspectiveDemo):Changeddefaultvisionto5.0patches
RevisedCurricularModels
GenEvo-GenEvo1:Fixedsave screenshotbugonWindowsmachines
GenEvo-GenEvo2:Fixedsave screenshotbugonWindowsmachines
GenEvo-GenEvo3:Fixedsave screenshotbugonWindowsmachines
RevisedAlternativeVisualizations
Flocking(AlternativeVisualizations):Changeddefaultvisionto5.0patches
Version6.0.3(March2018)
FeatureChanges
Improvethelook&feelofAgentMonitorwindows.
Theproceduresmenuinthecodetabnowhasasearchfieldandactivelyfilters
procedurenamesastheusertypes.Thisshouldimprovenavigationspeedforlarge
modelswithlotsofprocedures.Thereisalsonowahotkeytoaccessthismenu:Ctrl-G
onWindowsandLinux,andCmd-GonMacOS.
Increasethespeedofthediffusionprimitiveandmakethediffusionoperation
symmetric.
NetLogoenforcesthatplotnamesareuniqueandthatpennamesareper-plotunique
withouttakingcapitalizationintoaccount.Thisavoidscertaincaseswhereset-current-
plotandset-current-plot-penprimitiveswouldsettheplotorpentosomething
differentthantheuserintendedbecausenamesdifferedincapitalizationonly.
Modelswithexistingplotsandpenswhichhavethesamenamewithouttaking
capitalizationintoaccountwillbeautomaticallyconvertedonfirstopenin6.0.3.
Weareplanningonaddingtheabilitytohavemultipleconditionalbranchestoifelse
andifelse-value.However,asthisisafairlysubstantialchangetothecorelanguage,
wehaveimplementeditinthecfextensionfortesting.Seethecfdocumentationfor
informationaboutthenewsyntax.
DocumentationChanges
AddatabletotheOutputsectionoftheProgrammingGuidespecifyinghowthevarious
outputprimitivesdifferinwhethertheyprintthecallingagent,whethertheyprinta
newline,andwhethertheycanbereadbackintoNetLogo.
Bugfixes
Anonymousproceduresappearinginsideaskblocksinsiderepeatblocksnowclose
overuniquecopiesoflet-variablesintroducedintherepeatblock.
FixalongstandingHubNetbuginwhichHubNetwouldsometimescrashasalarge
numberofusersjoined.
FixHubNetdiscoverywhentheHubNetserverisrunonaMac.
Whenswitchingfromthecodetabtotheinterfacetab,thecursorswitchestothe
commandcenter.Thispreventstypedcommandsorcopy/pastekeyboardshortcuts
fromaffectingthecodetab.
Turtlesdrawtrailswhenmovingbackwards(regressioninNetLogo6.0.1).
SmoothCodeTabscrolling.
BehaviorSpacenowonlyappliesstandardCSVstringescaping(doublingofdouble
quotes)tostringoutputsinresultfiles.ItusedtoapplyNetLogostylestringescaping
(backslashesinfrontofspecialcharacters)andthenapplyCSVescapingontopofthat.
ThenewbehaviorisconsistentwiththeRFC4180specificationandthecurrent
behaviorofthecsvextension.
TheBehaviorspacedialogappearscenteredintheNetLogowindow.
DuetochangesintroducedinJava,certaindialogsinNetLogo6.0.1wouldappear
underthedialogthatcreatedtheminsteadofontop.Thesedialogsnowappearontop
ofthedialogthatcreatedthem.
Non-codechangestotheSystemDynamicsmodelerarepulledinoneveryrecompile
(priortothis,changeslikenewly-disconnectedflowsweresometimesnottakeninto
accountonrecompiles).
Thesystemdynamicscodetabadjustsitselftomatchthesizeofthesystemdynamics
window.
NetLogo3Dloadsandsavessystemdynamics.
Fixesanerrorraisedin3Dwhentheworldwasclearedfollowingsettingapatch-color
toanRGBlist.
Miscellaneoussmallchangestotheformatofexportedworlds.NetLogo6.0.3shouldbe
abletoimportworldsexportedbyolderversionsofNetLogoandolderversionsof
NetLogoshouldbeabletoimportworldsexportedbyNetLogo6.0.3.
The“others”executebitissetforthenetlogo-headless.shscriptintheLinuxinstaller
package.
ExtensionChanges
nw:generate-preferential-attachmentacceptsamin-degreeparameter,specifyingthe
numberoflinkseachnewturtlepreferentiallycreatestoexistingturtles.
Thearduinoextension(andtherelatedsketchandmodelinthelibrary)havebeen
updatedtoallowthearduinotosendstringsbacktoNetLogo.Twonewdebug
primitiveshavealsobeenaddedtohelptroubleshootinteractionbetweenNetLogoand
thearduino.
Theverbosecfextensionconditionalsyntaxasbeenreplacedwithstraight-forward
generalizationsoftheifelseandifelse-valueprimitives.Thesyntaxismuchsimpler
andtheseprimitivesrunmuchfasterthantheoldconstructs.
Thelsextensionhasmuchlessoverheadforcallingouttosinglemodels,making
constructslikeask turtles [ ls:ask my-model [ run-something ] ] muchfaster.
ThelsextensionnowseedsthechildmodelRNGbasedontheparentmodelRNGat
modelcreation.Furthermore,andls:random-seedprimitivehasbeenintroduced,soan
entiremodelsystemcanbeseededsimultaneously.Thismakesitpossibletohave
reproduciblerunswhenusingLevelSpace.
Thels:letprimitivenowhandlesscopingproperly.
ls:assignhasbeenaddedtoLevelSpacetomakeassigningglobalsofchildmodels
easier.
DocumentationChanges
Clarifydocumentationaround__includesbyprovidingexamples.
Fixabrokenlinkinthedictionary.
UpdatetheWindowsunattendedinstallationdirectionsintheFAQ.
ModelChanges
NewSampleModels:
BiddingMarket
BloodSugarRegulation
RockPaperScissors
VisionEvolution
NewCurricularModels
NIELS-CurrentinaWireHubNet
NewHubNetActivities:
CurrentinaWireHubNet(sameasabove)
RevisedCodeExamples:
arduinoExtension:Theexamplemodelandsketchhavebeenupdatedtoreflectnew
featuresintheextension
soundExtension–SoundWorkbench:MinorGUIupdates
soundExtension–PercussionWorkbench:MinorGUIupdates
FileInputExample:Fixedabuginthesave-patch-datatemplateprocedure
LotteryExample:CorrectedRelatedModelsfromPreferentialAttachmenttotheRnd
ExampleModelintheInfoTab
InfoTabExample:CorrectedreferencefrompegdowntoflexmarkintheInfoTab
RevisedCurricularModels:
BEAGLEEvolution-FishTankGeneticDrift:Updateduplicateplot-pennamesand
resizeplots
GenEvo-GenEvo4:Replacedusageofcf:whenwithnestedifelses
LatticeLand-LatticeLandExplore:Fixedbugwhendeletingasegmentthatdidn’t
exist.
LatticeLand-LatticeLandTrianglesDissection:Fixedbugwhendeletingasegment
thatdidn’texist.
NIELS-Electrostatics:Allturtlesarenowparticlesandeachparticlehasacharge;
Changedparticlecoloring;UpdatedInfoTabandsomevariablenamestoreflectlater
NIELSmodels
UrbanSuite-TijuanaBordertowns:MinorInfoTabupdates.
RevisedSampleModels:
ArtificialAnasazi:UpdatebrokenURLsinInfoTab
Autumn:UpdatebrokenURLsinInfoTab
HIV:TheAIDSmodelhasbeenrenamedtoHIV†
ColorFractions:RemoveddirectreferencetodeadwebpageinInfoTab
FairyCircles:UpdateURLsinInfoTab
Fur:UpdatebrokenURLsinInfoTab
HexCellAggregation:UpdatebrokenURLsinInfoTab
Ising:UpdatebrokenURLsinInfoTab
KickedRotators:UpdatebrokenURLsinInfoTab
LanguageChange:UpdateURLsinInfoTab
Lennard-Jones:AddedcitationintheInfotab
Lightning:UpdateURLsinInfoTab.
L-SystemFractals:UpdatebrokenURLsinInfoTab
MembraneFormation:UpdatebrokenURLsinInfoTab
Moth:UpdateURLsinInfoTab
Party:Fixincorrectcommentonturtleheadings.
PDBasic:MinorGUIupdates
Segregation:UpdatebrokenURLsinInfoTab.Updatecolorschemeforcolorblindness.
MinorGUIupdates.MinorInfoTabupdates.
Sugarscape1ImmediateGrowback:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
Sugarscape2ConstantGrowback:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
Sugarscape3WealthDistribution:Fixed“Wealthdistribution”histogrambug(turtle
withmaxsugarwasnotdisplayed)
RevisedIABMModels:
ArduinoExample:Theexamplemodelandsketchhavebeenupdatedtoreflectnew
featuresintheextension(sameasabove)
SegregationSimpleExtension1:UpdatebrokenURLsinInfoTab
SegregationSimpleExtension2:UpdatebrokenURLsinInfoTab
SegregationSimpleExtension3:UpdatebrokenURLsinInfoTab
SegregationSimple:UpdatebrokenURLsinInfoTab
†-ModelsUpdatedtoCorrectlyReferencetheHIVModel
AlternativeVisualizations
Virus-AlternativeVisualization
Virus-CircleVisualization
CurricularModels
epiDEMBasic
epiDEMTravelandControl
IABMModels
SpreadofDisease
SampleModels:
DiseaseSolo
Virus
RumorMill
Version6.0.2(August2017)
FeatureChanges
TheautosuggestfunctionalityintroducedinNetLogo6willnowdisplayextension
primitivenames.
Anewinsert-itemprimitivewasaddedtothelanguage.Itworkssimilarlytoreplace-
item,butwithoutremovingtheitematthespecifiedindex.
Anewset-plot-background-colorprimitivewasaddedtothelanguage.Itcanbeused
inplottingcodetosetthebackgroundcoloroftheplot.
Behaviorsearch’suserinterfacehasbeenupdated.ItnowusestheJavaFXUItoolkitfor
amoremodernlookandfeel.
Bugfixes
The6.0.1autoconverterwoulderrorwhenconvertingtaskswithexactlyoneargument
(from5.3.1andearliermodelsonly).Theconversionwouldbecorrect,butitwas
confusing.Thishasnowbeenremediedandtheautoconverterwillcorrectlyconvert
modelsfrom5.3.1andearlierwithouterroringonsingle-argumenttasks.
Fixabugwhereextensionsweren’tlocatedproperlywheninapathrelativetothe
model.
Helpbrowsernowopensin64-bitWindows.
Fixaspeedregressionfortheimport-worldprimitiveintroducedin6.0.
Ifanunexpectedreporterblockispassedtowithwhenusedwithother,theerrorwill
nowreflectthattheblockisunsuitableforwithinsteadofother.
Whensort-byreceivesanunsuitablereporterblockfromtheuseritnowshowsauseful
errorinsteadofacrypticstacktrace.
Stringrepresentationsofanonymousproceduresnowshowtheargumentsofthose
anonymousprocedures
Whenworkinginannlsfile,switchingtoadifferenttabwillcompilethenlsfile.
Displayerrorlabelonnlsfilewhenthecodeitcontainscausesanerror.
SomeuserswereunabletoopenNetLogo6and6.0.1inMacOSSierra.We’ve
changedoursigningprocessin6.0.2toattempttofixthisproblem.Wearecontinuingto
trackthisissuetodeterminewhetherourfixwaseffective.Moreinformation(includinga
partialworkaroundfortheproblem)isavailablehere.
ExtensionChanges
Fixedabugingis:patch-datasetintroducedinNetLogo6.
Thetableextensionhasnewtable:group-agentsandtable:group-itemsprimitives
whichcanbeusedtobuildatableofgroupedagentsanditemsbysupplyingan
anonymousreporter.
DocumentationChanges
Clarifywhenvariouspartsoftheanonymousproceduresyntaxareoptional.
Fixafewsmalldocumentationbugsaroundforeach.
Clarifyrelationshipbetweenspeedandupdatemodalityinthe“ViewUpdates”sectionof
theprogrammingguide.
ModelChanges
NewSampleModels:
ChaosinaBox
FairyCircles
SmoothLife
NewCurricularModels:
LatticeLandCurriculum
LatticeLand-TrianglesExplore
LatticeLand-TrianglesDissection
RevisedSampleModels:
Anisogamy:Newcolorscheme.AddsBehaviorSpaceexperiments.
Ethnocentrism:Nowcross-listedasanEvolutionarymodel.
Fireworks:Renamefireworkstomax-fireworksandenforceaminimumof1.
GenJam-Duple:Minorinfotabupdates.
WolfSheepPredation:Revisedtobetterclarifythegrass?constructandcode.
RevisedCurricularModels:
ConnectedChemistry:
ConnectedChemistry1:FixNetLogoWebincompatibility.
ConnectedChemistry3:Updateminimumnumberofparticlesto2.
ConnectedChemistry8:Minorcodeupdates.Smallchangetodefaultvalues.
RevisedHubNetActivities:
GridlockHubNet:Minorcodeupdates.
RevisedCodeExamples:
InfoTabExample:Correctedformattingofun/orderedlistsexample.
LSExtension–ModelVisualizerandPlotterExample:Updatedcodedependenciesfor
WSP.
LSExtension–ModelInteractionsExample:UpdatedcodedependenciesforWSP.
Version6.0.1(March2017)
FeatureChanges
Bracketsarerequiredaroundanonymousprocedurereportersonlywhentherearetwo
ormorearguments.Forinstance[ [x] -> x ]cannowbewritten[ x -> x ] .Notethis
changemakesitpossibletocreatemodelsinNetLogo6.0.1thatwillnotruninNetLogo
6.0.IfyouplantouseyourmodelinNetLogo6.0,besuretoincludebracketsaround
anonymousprocedurearguments.Forashortperiodaftertherelease,modelswhich
useunbracketedlambdaargumentsmaynotworkonnetlogoweb.org.
Bugfixes
TheNetLogocodeeditornavigatesandindentsmodelsmuchmorequicklyand
efficientlythaninNetLogo6.0.
TheNetLogo5-to-6autoconverternowignorescommented-outcode.
Thebehavioroflayout-radialinNetLogo6didnotmatchthe5.3.1behavior.Thishas
beencorrectedandlayout-radialshouldbeidenticalbetweenNetLogo6.0.1and
NetLogo5.3.1
NetLogo6raisedaNullPointerExceptionwhennumbersbecametoolargeforNetLogo
tohandle.Thisisnowproperlydisplayedtotheuserasanumberoutofboundserror.
Improvedperformanceofmodelswhichuseletandanonymousprocedurestogether.
Reloadingamodelnowclearsglobalvariables.
ClearerwarningdialogswhenopeninganolderversionofaNetLogo2DfileinNetLogo
3D.
UsingforeachimproperlyintheCommandCenterwilldisplaythesameerrorasitwould
ifusedimproperlyinthecodetab.
Extremelylonganonymousproceduresnolongercauseanexceptionwhencompiled.
in-radiusisnolongerpathologicallyslowonagentsetscreatedusingwith.
ExtensionChanges
Anewprimitive,table:valueshasbeenaddedtothetableextension.
TheRextensionhasbeenupdatedtotakefulladvantageoftheJavaGDRlibraryusing
r:setPlotDevice.
UserscannowsupplyapathtotheRextensionbyconfiguringthevalueofr.lib.pathsin
theuser.propertiesfile.
FixedaLevelSpacebugpreventinginteractivemodelsfromusingnlsfiles.
FixedaLevelSpacebugcausingNetLogotolockupwhentryingtoloadanonexistent
fileasaninteractivemodel.
DocumentationChanges
Thesystemdynamicstutorialnowinstructstheusertosetthedttoavaluewhichgives
stablebehavior
Thedocumentationforfollow,ride,andwatchhasbeenclarifiedtoindicatethatcalling
oneundoeshighlightsandperspectivechangescausedbytheother
Thedocumentationfor=and!=indicatesthattheyworkwithextensionobjects.
Severalexampleshavebeenaddedtosortclarifyingthebehaviorofsortonlists
featuringdifferenttypesofobjects.
AnewsectiononUserInterfaceprimitiveshasbeenaddedtotheprogrammingguide
whichdiscussesthebehaviorofthe“Halt”buttoninthevarioususerinteractiondialogs.
Incorrectexamplecodeforforeachandreducehasbeencorrected.
Models
Allmodelshavebeenupdatedtoreflectthenewoptionalnatureofbracketsforzero/one
argumentanonymousprocedures.Thisresultedinchangesto108models.
Allmodelshavebeenupdatedtoreflecttheavailabilityofthenewrangeprimitive.This
resultedinchangesto12models.
NewSampleModel
GenJam-Duple
NewCurricularModel
LatticeLandcurriculum:
LatticeLandExplore
RevisedSampleModels
PD2PersonIterated:infotabupdatesandextensivefixesforthecode.
Party:fixedbugwhereamonitorcoveredaplot.
SignalingGame:infotabupdates.
RevisedCurricularModels
GenEvocurriculum:
GenEvo1GeneticSwitch:infotabupdatesandnewgraduatedmethodof
displayinglacZconcentration.
GenEvo2GeneticDrift:infotabupdatesandinterfacetweaks.Newmodel
preview.
GenEvo3GeneticDriftandNaturalSelection:infotabupdatesandinterface
tweaks.
GenEvo4Competition:infotabupdates.
GeneticSwitch-SyntheticBiologyhasbeenrenamedandisnowSynthetic
Biology-GeneticSwitch.Italsoreceivedinfotabupdatesandafewinterface
changes.
Version6.0(December2016)
FeatureChanges
TheNetLogocodeeditornowoffersautocompletionsupport.SimplypresstheControl
keyandthespacebaratthesametimewhiletypingawordandyouwillseealistof
similarNetLogoprimitivesassuggestions.
TheNetLogocodeeditorofferstheoptionto“fold”procedurestomakenavigatinglarge
modelssimpler.
NetLogosupportsmulti-levelagent-basedmodelingwiththeLevelSpaceextension
LinenumberingcanbeenabledintheNetLogocodeeditorbychoosing“ShowLine
Numbers”fromthe“Preferences”dialog.Thisdialogcanbeopenedbyselecting
“NetLogo”>“Preferences”inMac,or“Tools”>“Preferences”onLinuxorWindows.
Theviewresizingarrowshavebeenremovedandthetickcounterhasbeenrelocated
underthespeedslider.
WheneditingNetLogocode,userscanright-clickavariablenameorprimitiveand
choose“ShowUsage”toseeallusagesofthatnameinthefile.
WheneditingNetLogocode,userscanright-clickavariablenameandchoose“Jumpto
Declaration”toseewhereinthefilethatvariableisdeclared.
TheNetLogointerfaceeditornowsupports“Undo”forwidgetaddition,deletion,and
movement.
NetLogocanexportcodetoHTMLwithcode-colorizationbychoosing“ExportCode”in
the“Export”sectionofthe“File”menu.
ThelookandfeelofNetLogoonMacOSXhaschangedsignificantly.NetLogoisnow
usingtheOracle-suppliedJavalookandfeelasopposedtoathird-partylookandfeel
usedinpriorversions.
Plotsusearandomnumbergeneratorindependentofthemain-modelrandomnumber
generator.
ModelPreviewCommandscanbeeditedthroughtheGUIbychoosing“Preview
CommandsEditor”inthe“Tools”menu.Thosecommandsgeneratethepreviewimage
thatappearswhenyouuploadyourmodeltotheModelingCommons.
NetLogodisplaysamorehelpfulerrormessagewhenaprogramfailsduetoan“outof
memory”error.
NetLogoanditsbundledextensionsarenowcompiledagainstJava8andScala2.12.
NetLogohasupgradedtheASMbytecodelibrarytoenablegenerationofJava8
bytecode.
Bugfixes
*-link-neighbor?primitivesnowworkthesamewayforbreededandunbreededlinks.
ResizingtheworldinNetLogo3Dnolongercausesablackview.
Fixederrorcausedbyright-clickingawidgetwhiledragging.
Improvederrormessagewhenauser-definedprocedureshadowsabreedprocedure.
neighbors4andneighborsnolongerreportagentsetscontainingthesamepatchmore
thanonce.
LanguageChanges
Supportforplural-onlybreednames(e.g.,breed [mice])hasbeenremoved.Writebreed
[mice mouse]instead.
Taskshavebeenreplacedbyanonymousprocedures.Tasksmadeuseof?variables
whichwereconfusingfornovicesanddifficulttoreadforexperts.Additionally,tasks
couldnotrefertothetaskvariablesofacontainingtask.Anonymousproceduresmay
havenamedargumentswhichcanbeaccessedbyinneranonymoustasks.Uponfirst
openingaNetLogo5modelinNetLogo6,tasksliketask [ ?1 + ?2 ] willbe
automaticallyconvertedto[ [?1 ?2] -> ?1 + ?2 ] .Seethethetransitionguidefor
moreinformation.
Linkreportershavebeenoverhauledtobemoreconsistentandflexible
Thetaskprimitiveisnolongersupported.
Breednamesthatconflictwithlanguageprimitivesarenowdisallowed.Forinstance,
breed [strings string]isnowdisallowedsinceitmakesis-string?ambiguous.
Thecompilererrorsonduplicatedbreedsingularnames.
Thecompilerdetectsagreaternumberoftypeerrors,forinstancenot pxcornowraises
acompilererrorinsteadoferroringatruntime.
set-plot-pen-colornowacceptsRGBlistsasarguments.
Thehubnet-set-client-interfaceprimitivehasbeenremoved.
Thevariousprimitivesstartingwithmovie-havebeenremoved,ashasthemovie
encoder.Theyhavebeenreplacedwiththenewvidextension.Thetransitionguide
providesmoredetailsandinformation.
The__change-languageprimitivehasbeenremoved.YoucannowchangetheUser
InterfaceLanguagethroughthepreferencesdialog,whichcanbefoundbychoosing
“Preferences…”inthe“NetLogo”menu(MacOSX)orinthe“Tools”menu(allother
platforms).
Thestringrepresentationofanonymousproceduresdisplaysthebodyofthe
anonymousprocedure.
ExtensionChanges
NetLogo6.0comeswiththreenew,bundledextensions:LevelSpacels,thevid
extensionforvideomanipulation,andtheenhancedvisualizationextensionview2.5d.
lsenablesmulti-levelagent-basedmodelinginNetLogo.
TheExtensionsAPIhasbeenupdatedfrom5.0to6.0.Thismeansthatallnon-bundled
extensionswillneedtobeupdatedtousethenewAPI.ExtensionswrittenforNetLogo
5willnotworkinNetLogo6.Ifyou’reanextensionauthor,seetheextensionauthor
transitionguidefor6.0formoreinformation.Ifyouregularlyuseextensionsyoumay
wanttocontacttheirauthorstoinformthemanewversionofNetLogoisonthewayand
theymaywanttoupdatetheirextensions.
arduino:get(inthearduinoextension)correctlyreportsvaluesfromWindows64-bit
machines.Inpriorversionsitwouldonlyreportsomevaluescorrectly.
Severalnewfeatureshavebeenaddedtothenwextension:
AddedcommunitydetectionusingtheLouvainmethod
Addedmodularitymeasurement
AddedWatts-Strogatzsmall-worldnetworkgeneration
Madeothernetworkgenerationalgorithmseasiertolayout
Weightedprimitivesnowtakesymbolicvariablenamesinsteadofstrings.Seethe
transitionguideformoreinformation.
TheqtjextensionisnolongerbundledwithNetLogo.Usersareencouragedtomake
useofthenewvidextension.
ThenewvidextensionisnowbundledwithNetLogo,combiningfeaturesofthelateqtj
extensionandthemovieprimitives.
ThenetworkextensionisnolongerbundledwithNetLogo.Usersareencouragedtouse
thenwextension(https://ccl.northwestern.edu/netlogo/docs/nw.html),whichhasbeen
bundledwithNetLogoforsometime.
Thegogo-serialextensionisnolongerbundledwithNetLogo.Usersareencouragedto
transitiontothenewergogoextension,whichusesHIDtocommunicatewiththeGoGo
board.
OperatingSystemSupport
NetLogowillnowbeusedtoopen.nlogolinksinPowerPointandotherprogramson
MicrosoftWindows.
TheNetLogobinariesonMacOSXareinstalledasrunnablebyanyuser.
NetLogoinMacOSXwillnotuse“AppNap”whilerunning.Thiskeepssimulations
runningatfullspeedwhenNetLogoisinthebackground.
TheNetLogocontrollingAPIhaschangedsinceNetLogo5.Programsthatrelyonthe
controllingAPI(suchasBehaviorSearch)willnotworkuntiltheyhavebeenchangedto
matchthenewAPI.
DocumentationChanges
Newdocumentationforanonymousprocedures
TheNetLogotutorialscreenshotshavebeenupdatedtocorrespondtothenewMacOS
XLookandFeel.
TheNetLogodictionarydisplaystheversioninwhicheachprimitivewasintroducednext
tothatprimitive.
ASpanishtranslationoftheNetLogodictionaryisavailablehere
InternationalizationChanges
AnewSpanishtranslationoftheNetLogodictionaryisavailableaspartoftheNetLogo
manual.
Languagepreferencescanbechangedbyusingthenew“Preferences”menuinsteadof
the__change-languageprimitive.
AJapaneselocalizationforNetLogoisnowavailableandincludedwiththestandard
download.
TheChinesetranslationforNetLogohasbeenupdated.
Models
NewSampleModels:
KickedRotator
KickedRotators
Mammoths,alegacyStarLogoTmodel,hasbeenconvertedtoNetLogo.
NewCurricularModels:
GenEvo1GeneticSwitch
GenEvo2GeneticDrift
GenEvo3GeneticDriftandNaturalSelection
GenEvo4Competition
NewCodeExamples:
MoviePlayingExample(vidextension)
MovieRecordingExample(vidextension)
VideoCameraExample(vidextension)
NetworkExtensionGeneralDemo(nwextension)
ModelInteractionsExample(lsextension)
ModelLoaderExample(lsextension)
ModelVisualizerandPlotterExample(lsextension)
PromotedModels(improvedandnolonger“unverified”):
ProbLabGenetics
Traffic2Lanes
RevisedSampleModels:
GiantComponent:addedtextintheinfotab.
TeamAssembly:removedunusedswitchwidget.
TrafficBasic,TrafficGrid,TrafficIntersection:revisedinfotab.
Voting:stoppedthemodelwhenvotingstabilizes.
WealthDistribution:fixedtyposininfotab,improvedcodeformatting.
RevisedHubNetActivities:
BugHuntersCompetitionHubNet,CritterDesignersHubNet,FishSpottersHubNet:
removedunnecessarycalltohubnet-set-client-interface.
GridlockHubNet,GridlockAlternateHubNet:revisedinfotab.
RevisedCurricularModels:
DNAReplicationFork:fixedaamonitorandruntimeerrorwhenusingatimelimit.
RevisedIABMmodels:
AgentsetEfficiency:clarifieddescriptionofgo-2ininfotab.
AgentsetOrdering:fixedtyposinintotab.
ArduinoExample:improvedmodeltodemonstratebothdirectionsofcommunication
withtheArduino.
HeroesandCowards:removedextratextininfotab.
PreferentialAttachmentSimple:removedextrapeninplotandextra“layout”button.
RandomNetwork:madesurethatthenumberoflinksisnevertoobigforthenumberof
nodes.
SegregationSimpleExtension1,2and3:fixednumber-of-ethnicitiesslidertoavoid
runtimeerrors.
TrafficBasicAdaptiveIndividuals,TrafficBasicUtility,TrafficGridGoal:revisedinfotab.
TrafficBasicAdaptive:revisedinfotab,clarifiedcommentinadaptive-goprocedure.
VotingComponentVerification:stoppedthemodelwhenvotingstabilizes.
VotingSensitivityAnalysis:improvedcodeforstoppingthemodelwhenvoting
stabilizes.
RevisedCodeExamples:
GoGoMonitorSerial,GoGoMonitorSimpleSerial:removedthemodels,asthegogo-
serialandqtjextensionsarenolongerbundled.
RandomNetworkExample:madesurethatthenumberoflinksisnevertoobigforthe
numberofnodes.
SincetheQuickTimeextension(qtj)hasbeenreplacedbythevidextension,the
followingmodelshavebeenconvertedtousethevidextension:
MovieExample,replacedbyMovieRecordingExample
QuickTimeMovieExample,replacedbyMoviePlayingExample
QuickTimeCameraExample,replacedbyVideoCameraExample
Demotedmodel:
ElFarolNetworkCongestion,apreviously“unverified”model,hasbeenmovedtothe
NetLogoUserCommunityModels
Version5.3.1(February2016)
FeatureChanges
MathematicaLinkisnowincludedandhasbeentestedtoworkwithMathematica10.
AlinktoIntroductiontoAgent-BasedModellinghasbeenaddedtothe“Help”menu.
ExtensionChanges
ThegogoextensionnowpromptstheuserforthelocationofJavauponopening.This
versionofJavaisusedtolaunchthegogohiddaemon.
Thecorrectversionofthenetworkextensionisnowbundled,whichwillopenproperly
Bundlesthecfextension,whichaddsmatch,case,andselectprimitives.
Bugfixes
Correctsabugwhereturtleswrappingaroundatorus-shapedworldwithpendown
wouldsometimescauseNetLogotoloopinfinitely.
FixesabugwherebuttonswouldappeartoremainpressedafterarightclickonMac.
Fixesabugwherepressingtherightmousebuttonwhiledraggingwouldconfusethe
mouse-down?primitive.
Fixesagenttype-checkingoftasks(bugappearedin5.2.1).
link-neighbor?nowreturnstrueifandonlyiftheneighborisconnectedthroughan
undirectedlink.
Documentationfixesformy-linksandmeanprimitives.
Version5.3(December2015)
FeatureChanges
Java8isnowbundledwithallversionsofNetLogo,thisremovestheneedfora
separateJava6installationonMacOSX
Separate32-bitand64-bitversionsareavailableforbothWindowsandLinux
TheWindowsinstallerisnowanmsiinsteadofanexe
javax.media.openglisnolongersupportedinJava8,ithasbeenreplacedby
com.jogamp.opengl
MathematicaLinkisnotdistributedduetoJavaversionchanges
ExtensionChanges
Aminorupdatetothenwextensionmakesnw:weighted-path-tobehaveas
documented.
Mostextensionsshouldcontinuetoworkwithoutchangeunlesstheyrelyon
javax.media.opengl,whichwasrenamedintheupdatedversionofJOGL.
Version5.2.1(September2015)
Extensions
AnincludedArduinoextensionforusewithArduinoboards
Newfeatures
NewfilemenuitemtoexportmodelstoNetLogoWeb
Bugfixes
BehaviorSpaceoutputtypepreferenceisnowremembered
Outputwidgetfontisnowsavedatthepropersizewhenzoomed
Reportertasksarenowevaluatedinvariablecontext
runresultargumentsnowonlygetevaluatedonce
ThelastuseddirectoryisnowrememberedonLinux
Whitespaceisnowstrippedfrommodelswhensaving
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,
BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,Bug
HuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-
Jones,Paths
Thereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,
AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4
ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheep
Extensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetwork
Example,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,
TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponent
Verification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroid
AvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,Simple
MachineLearning,SimpleViralMarketing,TicketSales,SandpileSimple
NewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-Alternative
Visualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternative
visualization,Virus-AlternativeVisualization,Virus-CircleVisualization
Promotedmodels:Honeycomb,MinorityGame
Manyotherbugfixesandupgrades
Modelchanges
ImprovedSampleModels:Altruism,AntLines,ArtificialAnasazi,Cooperation,
Daisyworld,DividetheCake,HeatDiffusion,HydrogenDiffusion3D,Lennard-Jones,N-
Bodies,PDBasicEvolutionary,Sandpile,RobbytheRobot,Segregation,Simple
Kinetics2and3,TrafficGrid,GridLockHubNet,GridLockHubNetAlternate
RevisedCurricularModels:4BlockStalagmites,4BlockTwoStalagmites,BugHunter
CompetitionHubNet,FishSpottersHubNet,Ising,TijuanaBordertowns,UrbanSuite-
TijuanaBordertowns,
RevisedCodeExamples:LotteryExample,selfExample,NetworkImportExample
RevisedIABMTextbookmodels:SimpleEconomy,FireSimpleExtension2and3,
SegregationSimple,1,2and3,AgentsetEfficiency,PreferentialAttachmentSimple,
RandomNetwork,TrafficBasicAdaptive,RunExample,TrafficGridGoal,
NewIABMTextbookmodel:TrafficBasicAdaptiveIndividuals
Version5.2.0(April2015)
Extensions
AnincludedCSVextensiontoreadandwriteCSVfiles
AnincludedPaletteextensiontomapdifferentvaluestocolors
Thepreviousgogoextensionhasbeenremoved.Ithasbeenreplacedwithtwodifferent
gogoextensions,gogoandgogo-serial.Theextensionsworkwithdifferenthardware.
ThegogoextensionworkswiththenewstyleHID-interfacegogoboardsandthegogo-
serialextensionworkswiththeold-styleserial-interfacegogoboards
Upgradetothenetworkextensionincludingthefollowingchanges:
Supportformanymorefiletypes,includingGEXF,GDF,GML,PajekNET,
UCINETDL,andNetdrawVNA
FixedbugswithGraphMLsupport
Improveddocumentation
Newfeatures
Newprimitivenetlogo-web?addedtotestwhetheryouarecurrentlyrunninginNetLogo
Web
Newprimitivebehaviorspace-experiment-nameaddedallowingyoutogetthenameof
thecurrentlyrunningexperiment
Newprimitivestop-inspectingtostopinspectingagents
Newprimitivestop-inspecting-dead-agentsandmenuitemtostopinspectingdead
agents
__includeskeywordnowenablestheIncludesbuttonwhengivenanempty
hooksaddedforextensionstowritecustomlogmessages
Bugfixes
user-one-ofwillnowsignalanerrorearlierwhenprovidedanemptylistofchoices
hsb,extract-hsb,andapproximate-hsbhavebeenupdatedtorepresenttruehsb
conventions
newdeprecatedprimitives__hsb-old,__extract-hsb-old,and__approximate-hsb-old
workastheoldhsbprimitivesdidwhenoldermodelsusingthehsbprimitivesare
openedinNetLogo5.2,theywillbeauto-convertedtousethedeprecatedprimitives
extract-hsb–fixedbugwhereitdidn’tworkcorrectlyonrgblists
Modelchanges
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,
BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,Bug
HuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-
Jones,Paths
Thereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,
AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4
ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheep
Extensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetwork
Example,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,
TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponent
Verification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroid
AvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,Simple
MachineLearning,SimpleViralMarketing,TicketSales,SandpileSimple
NewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-Alternative
Visualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternative
visualization,Virus-AlternativeVisualization,Virus-CircleVisualization
Promotedmodels:Honeycomb,MinorityGame
Manyotherbugfixesandupgrades
Version5.1.0(July2014)
bundlenewnetworkextension
Filemenuincludesrecentlyopenedfiles
deprecateapplets
supportretinadisplayonnewMacBooks
Version5.0.4(March2013)
uploadmodelstotheModelingCommons
Version5.0(February2012)
features:
opensource(GPLlicense;sourcecodeonlineat
https://github.com/NetLogo/NetLogo)
newlicenseforSampleModelsandCurricularModelsisCreativeCommons
Attribution-NonCommercial-ShareAlike
internationalcharacters(Unicode)supportedthroughoutapplication
GUIislocalizedinSpanish,Russian,andChinese(volunteertranslatorswanted)
richformattingandimagesinInfotabsusingMarkdown
plottingcodegoesinsideplotsinsteadofincodetab
authorablemodelspeed(targetframeratesetting)
buttonsoptionallydisableuntilticksstart
translucentcolorsin3DviewandNetLogo3D(forRGBcolorsonly)
languagechanges:
“tasks”storecodetoberunlater
akafirst-classfunctions,closures,lambda
newprimitives:task,is-command-task?,is-reporter-task?
theseprimitivesaccepttasks:run,runresult,foreach,map,reduce,filter,n-
values,sort-by
improvedoveralllistperformance(manyoperationstakenear-constanttime
insteadoflineartime)
youmustusereset-tickstostartthetickcounterbeforeusingtickortick-
advance
newprimitivessetup-plotsandupdate-plots
newprimitivesort-onletsyousaye.g.,sort-on [size] turtles
newprimitiveerrorcausesaruntimeerror
random-normalrejectsnegativestandarddeviations
HubNet:
activitiescanrunheadless
newprimitiveshubnet-clients-list,hubnet-kick-client,hubnet-kick-all-
clients
hubnet-set-client-interfacenolongerrequired
otherfixesandchanges:
tabsrenamedtoInterface/Info/Code
CommandCenterallowsreporters,addsshowcommandautomatically
NetLogo3Duses.nlogo3dsuffix,not.nlogo
import-worldismuchfaster
startupnolongerrunsheadlessorinbackgroundBehaviorSpaceruns
fixed3Drenderingbugwheresmallturtlesweretoobright
Macapprunsin64bitmodebydefault
upgradedWindowsinstaller
GoGoextensiongetting-startedexperiencenowsmootheronallplatforms
models:
newSampleModels:Sandpile,Lightning,OsmoticPressure,RobbytheRobot,
PreferentialAttachment3D
newCurricularModels:BugHuntConsumers,BugHuntPredatorsandInvasive
Species,PlantSpeciation,epiDEMBasic,epiDEMTravelandControl,Connected
ChemistryAtmosphere
newCodeExamples:InfoTabExample,GoGoMonitorSimple
Version4.1.3(April2011)
matrixextension
behaviorspace-run-number
Version4.1(December2009)
parallelBehaviorSpace
controllingAPIallowsembedding
automaticcodeindenter
searchableModelsLibrary
translucentcolors
mini-viewsinagentmonitors
resize-world,set-patch-size
bitmap,QuickTimeextensions
individualizedHubNetclientviews
browser-basedHubNetclient
Version4.0(September2007)
linkagents
tickcounter
viewupdatemodes(tick-based,continuous)
speedsliderfastforwards
inputboxesininterfacetab
includemultiplesourcefiles
RGBcolors
sliderboundsmaybereporters
HubNetclienteditor
Mathematica-NetLogolink
array,table,profiler,GISextensions
modelsrunfaster(partialcompilationtoJVMbytecode)
logging
Version3.1(April2006)
topologies(optionalwrappingatworldedges)
randomizedagentsetordering
Version3.0(September2005)
3Dview(for2Dmodels)
formattedInfotabs
SystemDynamicsModeler
follow,ride,watch
drawinglayer
GoGoextension
Version2.1(December2004)
“headless”modeforcommandlineoperation
“actionkeys”totriggerbuttonsbykeypresses
makesQuickTimemoviesofmodels
let,carefully
Version2.0.2(August2004)
extensionsandcontrollingAPIs
soundextension
Version2.0(December2003)
fast,flicker-free,non-grid-basedgraphics
Version1.3(June2003)
run,runresult,map,foreach,filter,reduce
Version1.2(March2003)
SystemRequirements
NetLogo6.0.4UserManual
NetLogorunsonalmostanycurrentcomputer.
IfyouhaveanytroublewithNetLogonotworking,seeContactingUs.
ApplicationRequirements
Windows
NetLogorunsonWindows10,Windows8,Windows7andVista.NetLogo5.2.1wasthelast
versiontosupportWindowsXPandWindows2000.
TheNetLogoinstallerforWindowsincludesJava8forNetLogo’sprivateuseonly.Other
programsonyourcomputerarenotaffected.
MacOSX
MacOSX10.8.3ornewerisrequired.(NetLogo5.1wasthelastversiontosupport10.5and
10.4;NetLogo5.2.1wasthelastversiontosupport10.6and10.7)
TheNetLogoapplicationcontainsadistributionoftheJava8runtimeforNetLogo’sprivate
useonly.Otherprogramsonyourcomputerwillnotbeaffected.
Linux
NetLogoshouldworkonstandardDebian-basedandRedHat-basedLinuxdistributions.The
NetLogotarballincludesacopyoftheJava8runtime.
StartNetLogobyrunningtheprovidedNetLogoexecutable.
3DRequirements
Occasionallyanolder,lesspowerfulsystemisnotabletousethe3DvieworNetLogo3D.
Tryitandsee.
Somesystemscanuse3Dbutcan’tswitchtofull-screenmode.Itdependsonthegraphics
cardorcontroller.(Forexample,theATIRadeonIGP345andIntel82845probablywillnot
work.)
32-bitor64-bit?
FormostusersonLinuxorWindows,the32-bitversionofNetLogoisthesimplestwaytoa
workingNetLogoinstallation.Advanceduserswillwanttounderstandtheadvantagesof64-
bitNetLogoaswellashowtodeterminewhethertheirmachinemeetstherequirements.
Theprimaryadvantageofthe64-bitversionistheabilitytoaddadditionalheapspaceby
changingthe“-Xmx”JVMoption.Formoreinformation,seeHowbigcanmymodelbe.You
mayalsofindithelpfultobrowseOracle’sdocumentationontheperformancecharacteristics
ofthe64-bitJVM
Torun64-bitNetLogo,youmustberunning64-bitWindows.Todeterminewhetheryour
versionofWindowsis64-bit,seeIsmyPCrunningthe32-bitor64-bitversionofWindowsif
you’reusingWindowsVista,orWindows7,orWhichWindowsoperatingsystemamI
running?ifyouarerunninganyotherversionofWindows.
ForLinuxusers,theeasiestwaytodeterminewhetheryouroperatingsystemis64-bitis
checkingtheoutputof
uname -m
Iftheoutputshows“x86_64”or“amd64”,youshouldbeabletorunthe64-bitversion.
ContactingUs
NetLogo6.0.4UserManual
FeedbackfromusersisessentialtousindesigningandimprovingNetLogo.We’dliketohear
fromyou.
Website
Ourwebsiteathttp://ccl.northwestern.edu/includesourmailingaddressandphonenumber.
Italsohasinformationaboutourstaffandourvariousresearchactivities.
Feedback,questions,etc.
ForhelpusingNetLogo,trythisgroup:http://groups.google.com/d/forum/netlogo-users.
Ifyouhavefeedback,suggestions,orquestions,youmaywriteusat
feedback@ccl.northwestern.edu.
Reportingbugs
OurpublicbugtrackerisonGitHubathttps://github.com/NetLogo/NetLogo/issues.Youcan
lookheretoreportanewbug,checkifabughasalreadybeenreported,andsoon.
Whensubmittingabugreport,pleasetrytoincludeasmuchofthefollowinginformationas
possible:
Acompletedescriptionoftheproblemandhowitoccurred.
TheNetLogomodelorcodeyouarehavingtroublewith.Ifpossible,attachacomplete
model.(It’sbestifyoucanreducetheamountofcodeinthemodeltotheminimum
necessarytodemonstratethebug.)
Yoursysteminformation:NetLogoversion,OSversion,Javaversion,andsoon.This
informationisavailablefromNetLogo’s“AboutNetLogo”menuitem,thenclickingthe
Systemtab.
Anyerrormessagesthatweredisplayed.Pleasecopyandpastetheentireerror
messageintoyouremail,ormakeascreencaptureifyouareunabletocopyandpaste.
Wealsoacceptbugreportsbyemailatbugs@ccl.northwestern.edu.
Opensource
NetLogoisfree,opensourcesoftware.Thesourcecodeishostedat
https://github.com/NetLogo/NetLogo.Contributionsfrominterestedusersarewelcome.
FordiscussionofNetLogoAPI’sandthedevelopmentofNetLogoitself,try
https://groups.google.com/group/netlogo-devel.
SampleModel:Party
NetLogo6.0.4UserManual
Thisactivitygetsyouthinkingaboutcomputermodelingandhowyoucanuseit.Italsogives
youinsightintoNetLogoitself.Weencouragebeginninguserstostarthere.
AtaParty
Haveyoueverbeenatapartyandnoticedhowpeopleclusteringroups?Youmayhavealso
noticedthatpeopledon’tjuststayinagroup.Astheycirculate,thegroupschange.Ifyou
watchedthesechangesovertime,youmightnoticepatterns.
Forexample,insocialsettings,peoplemayexhibitdifferentbehaviorthanatworkorhome.
Individualswhoareconfidentwithintheirworkenvironmentmaybecomeshyandtimidata
socialgathering.Andotherswhoarereservedatworkmaybethe“partystarter”withfriends.
Thesepatternscandependonthetypeofgathering.Insomesettings,peoplearetrainedto
organizethemselvesintomixedgroups;forexample,partygamesorschool-likeactivities.But
inanon-structuredatmosphere,peopletendtogroupinamorerandommanner.
Isthereanytypeofpatterntothiskindofgrouping?
Let’stakeacloserlookatthisquestionbyusingthecomputertomodelhumanbehaviorata
party.NetLogo’s“Party”modellooksspecificallyatthequestionofgroupingbygenderat
parties:whydogroupstendtoformthataremostlymen,ormostlywomen?
Let’suseNetLogotoexplorethisquestion.
Whattodo:
1. StartNetLogo.
2. Choose“ModelsLibrary”fromtheFilemenu.
3. Openthe“SocialScience”folder.
4. Clickonthemodelcalled“Party”.
5. Pressthe“open”button.
6. Pressthe“setup”button.
Intheviewofthemodel,youwillseepinkandbluegroupswithnumbers:
Theselinesrepresentminglinggroupsataparty.Menareshownasblue,womenpink.The
numbersarethesizesofthegroups.
Doallthegroupshaveaboutthesamenumberofpeople?
Doallthegroupshaveaboutthesamenumberofeachsex?
Let’ssayyouarehavingapartyandinvited150people.Youarewonderinghowpeoplewill
gathertogether.Suppose10groupsformattheparty.
Howdoyouthinktheywillgroup?
Insteadofasking150ofyourclosestfriendstogatherandrandomlygroup,let’shavethe
computersimulatethissituationforus.
Whattodo:
1. Pressthe“go”button.(Pressing“go”againwillstopthemodelmanually.)
2. Observethemovementofpeopleuntilthemodelstops.
3. Watchtheplotstoseewhat’shappeninginanotherway.
4. Usethespeedsliderifyouneedtoslowthemodeldown.
Nowhowmanypeopleareineachgroup?
Originally,youmayhavethought150peoplesplittinginto10groups,wouldresultinabout15
peopleineachgroup.Fromthemodel,weseethatpeopledidnotdivideupevenlyintothe10
groups.Instead,somegroupsbecameverysmall,whereasothergroupsbecameverylarge.
Also,thepartychangedovertimefromallmixedgroupsofmenandwomentoallsingle-sex
groups.
Whatcouldexplainthis?
Therearelotsofpossibleanswerstothisquestionaboutwhathappensatrealparties.The
designerofthissimulationthoughtthatgroupsatpartiesdon’tjustformrandomly.Thegroups
aredeterminedbyhowtheindividualsatthepartybehave.Thedesignerchosetofocusona
particularvariable,called“tolerance”:
Toleranceisdefinedhereasthepercentageofpeopleoftheoppositesexanindividualis
“comfortable”with.Iftheindividualisinagroupthathasahigherpercentageofpeopleofthe
oppositesexthantheirtoleranceallows,thentheybecome“uncomfortable”andleavethe
grouptofindanothergroup.
Forexample,ifthetolerancelevelissetat25%,thenmalesareonly“comfortable”ingroups
thatarelessthan25%female,andfemalesareonly“comfortable”ingroupsthatareless
than25%male.
Asindividualsbecome“uncomfortable”andleavegroups,theymoveintonewgroups,which
maycausesomepeopleinthatgrouptobecome“uncomfortable”inturn.Thischainreaction
continuesuntileveryoneatthepartyis“comfortable”intheirgroup.
Notethatinthemodel,“tolerance”isnotfixed.You,theuser,canusethetolerance“slider”to
trydifferenttolerancepercentagesandseewhattheoutcomeiswhenyoustartthemodel
overagain.
Howtostartover:
1. Ifthe“go”buttonispressed(black),thenthemodelisstillrunning.Pressthe
buttonagaintostopit.
2. Adjustthe“tolerance”slidertoanewvaluebydraggingitsredhandle.
3. Pressthe“setup”buttontoresetthemodel.
4. Pressthe“go”buttontostartthemodelrunningagain.
Challenge
Asthehostoftheparty,youwouldliketoseebothmenandwomenminglingwithinthe
groups.Adjustthetoleranceslideronthesideoftheviewtogetallgroupstobemixedasan
endresult.
Tomakesureallgroupsof10havebothsexes,atwhatlevelshouldwesetthe
tolerance?
Testyourpredictionsonthemodel.
Canyouseeanyotherfactorsorvariablesthatmightaffectthemaletofemale
ratiowithineachgroup?
Makepredictionsandtestyourideaswithinthismodel.
Asyouaretestingyourhypotheses,youwillnoticethatpatternsareemergingfromthedata.
Forexample,ifyoukeepthenumberofpeopleatthepartyconstantbutgraduallyincrease
thetolerancelevel,moremixedgroupsappear.
Howhighdoesthetolerancevaluehavetobebeforeyougetmixedgroups?
Whatpercenttolerancetendstoproducewhatpercentageofmixing?
Thinkingwithmodels
UsingNetLogotomodelasituationlikeapartyallowsyoutoexperimentwithasystemina
rapidandflexiblewaythatwouldbedifficulttodointherealworld.Modelingalsogivesyou
theopportunitytoobserveasituationorcircumstancewithlessprejudice,asyoucan
examinetheunderlyingdynamicsofasituation.Youmayfindthatasyoumodelmoreand
more,manyofyourpreconceivedideasaboutvariousphenomenawillbechallenged.For
example,asurprisingresultofthePartymodelisthateveniftoleranceisrelativelyhigh,a
greatdealofseparationbetweenthesexesoccurs.
Thisisaclassicexampleofan“emergent”phenomenon,whereagrouppatternresultsfrom
theinteractionofmanyindividuals.Thisideaof“emergent”phenomenacanbeappliedto
almostanysubject.
Whatotheremergentphenomenacanyouthinkof?
ToseemoreexamplesandgainadeeperunderstandingofthisconceptandhowNetLogo
helpslearnersexploreit,youmaywishtoexploreNetLogo’sModelsLibrary.Itcontains
modelsthatdemonstratetheseideasinsystemsofallkinds.
ForalongerdiscussionofemergenceandhowNetLogohelpslearnersexploreit,see
“ModelingNature’sEmergentPatternswithMulti-agentLanguages”(Wilensky,2001).
What’snext?
ThesectionoftheUserManualcalledTutorial#1:RunningModelsgoesintomoredetail
abouthowtousetheothermodelsintheModelsLibrary.
Ifyouwanttolearnhowtoexplorethemodelsatadeeperlevel,Tutorial#2:Commandswill
introduceyoutotheNetLogomodelinglanguage.
Eventually,you’llbereadyforTutorial#3:Procedures.Thereyoucanlearnhowtoalterand
extendexistingmodelstogivethemnewbehaviors,andyoucanstarttobuildyourown
models.
Tutorial#1:Models
NetLogo6.0.4UserManual
IfyoureadtheSampleModel:Partysection,yougotabriefintroductiontowhatit’sliketo
exploreaNetLogomodel.Thissectionwillgointomoredepthaboutthefeaturesthatare
availablewhileyou’reexploringthemodelsintheModelsLibrary.
Throughoutallofthetutorials,we’llbeaskingyoutomakepredictionsaboutwhattheeffects
ofmakingchangestothemodelswillbe.Keepinmindthattheeffectsareoftensurprising.
Wethinkthesesurprisesareexcitingandprovideexcellentopportunitiesforlearning.
Youmaywanttoprintoutthetutorialstomakethemeasiertorefertowhileyou’reusing
NetLogo.
SampleModel:WolfSheepPredation
We’llopenoneoftheSampleModelsandexploreitindetail.Let’stryabiologymodel:Wolf
SheepPredation,apredator-preypopulationmodel.
OpentheModelsLibraryfromtheFilemenu.
Choose“WolfSheepPredation”fromtheBiologysectionandpress“Open”.
TheInterfacetabwillfillupwithlotsofbuttons,switches,slidersandmonitors.These
interfaceelementsallowyoutointeractwiththemodel.Buttonsareblue;theysetup,start,
andstopthemodel.Slidersandswitchesaregreen;theyaltermodelsettings.Monitorsand
plotsarebeige;theydisplaydata.
Ifyou’dliketomakethewindowlargersothateverythingiseasiertosee,youcanusethe
Zoommenu.
Whenyoufirstopenthemodel,youwillnoticethatthe“view”(thegraphicaldisplayofthe
agentsinthemodel)isempty(allblack).Tobeginthemodel,youwillfirstneedtosetitup.
Pressthe“setup”button.
Whatdoyouseeappearintheview?
Pressthe“go”buttontostartthesimulation.
Asthemodelisrunning,whatishappeningtothewolfandsheep
populations?
Pressthe“go”buttontostopthemodel.
ControllingtheModel:Buttons
Whenabuttonispressed,themodelrespondswithanaction.Abuttoncanbea“once”
button,ora“forever”button.Youcantellthedifferencebetweenthesetwotypesofbuttons
byasymbolonthefaceofthebutton.Foreverbuttonshavetwoarrowsinthebottomright
corners,likethis:
Oncebuttonsdon’thavethearrows,likethis:
Oncebuttonsdooneactionandthenstop.Whentheactionisfinished,thebuttonpopsback
up.
Foreverbuttonsdoanactionoverandoveragain.Whenyouwanttheactiontostop,press
thebuttonagain.Itwillfinishthecurrentaction,thenpopbackup.
Mostmodels,includingWolfSheepPredation,haveaoncebuttoncalled“setup”anda
foreverbuttoncalled“go”.Manymodelsalsohaveaoncebuttoncalled“goonce”or“step
once”whichislike“go”exceptthatitadvancesthemodelbyonetick(timestep)insteadof
overandover.Usingaoncebuttonlikethisletsyouwatchtheprogressofthemodelmore
closely.
Stoppingaforeverbuttonisthenormalwaytopauseorstopamodel.Afterpausingyoucan
makeitresumebypressingthebuttonagain.(Youcanalsostopamodelwiththe“Halt”item
ontheToolsmenu,butyoushouldonlydothisifthemodelisstuckforsomereason.Using
“Halt”mayinterruptthemodelinthemiddleofanaction,andastheresultthemodelcould
getconfused.)
Ifyoulike,experimentwiththe“setup”and“go”buttonsintheWolfSheep
Predationmodel.
Doyouevergetdifferentresultsifyourunthemodelseveraltimeswith
thesamesettings?
Controllingspeed:SpeedSlider
Thespeedsliderallowsyoutocontrolthespeedofamodel,thatis,thespeedatwhichturtles
move,patcheschangecolor,andsoon.
Whenyoumovetheslidertotheleftthemodelslowsdownsotherearelongerpauses
betweeneachtick(timestep).Thatmakesiteasiertoseewhatishappening.Youmighteven
slowthemodeldownsofarastoseeexactlywhatasingleturtleisdoing.
Whenyoumovethespeedslidertotherightthemodelspeedsup.NetLogowillstartskipping
frames,thatis,itwon’tupdatetheviewattheendofeverytick,onlysometicks.Updating
takestime,sofewerviewupdatesmeansthemodelprogressesfaster.
Notethatifyoupushthespeedsliderwelltotheright,theviewmayupdatesoinfrequently
thatthemodelappearstohavesloweddown.Ithasn’t,asyoucanseebywatchingthetick
counterraceahead.Onlythefrequencyofviewupdateshaslessened.
AdjustingSettings:SlidersandSwitches
Amodel’ssettingsletyouexploredifferentscenariosorhypotheses.Alteringthesettingsand
thenrunningthemodeltoseehowitreactscangiveyouadeeperunderstandingofthe
phenomenabeingmodeled.
Switchesandslidersgiveyouaccesstoamodel’ssettings.Herearetheswitchesandsliders
inWolfSheepPredation:
Let’sexperimentwiththeireffectonthebehaviorofthemodel.
OpenWolfSheepPredationifit’snotopenalready.
Press“setup”and“go”andletthemodelrunforabout100ticks.(Thetick
countisshownabovetheview.)
Stopthemodelbypressingthe“go”button.
Whathappenedtothesheepovertime?
Let’stakealookandseewhatwouldhappentothesheepifwechangeasetting.
Turnthe“grass?”switchon.
Press“setup”and“go”andletthemodelrunforasimilaramountoftimeas
before.
Whatdidtheswitchdo?Wastheoutcomethesameasyourpreviousrun?
Turningthe“grass?”switchonaffectedtheoutcomeofthemodel.Withtheswitchoff,the
amountofgrassavailablealwaysstayedthesame.Thisisnotarealisticlookatthepredator-
preyrelationship;sobysettingandturningonagrassregrowthrate,wewereabletomodel
allthreefactors:sheep,wolfandgrasspopulations.
Anothertypeofsettingiscalledaslider.
Besidesswitches,amodelmayalsohavesliders.Whileaswitchhasonlytwovalues,onand
off,asliderhasawholerangeofnumericvalues.Forexample,the“initial-number-sheep”
sliderhasaminimumvalueof0andamaximumvalueof250.Themodelcouldrunwith0
sheeporitcouldrunwith250sheep,oranywhereinbetween.Trythisoutandseewhat
happens.Asyoumovethemarkerfromtheminimumtothemaximumvalue,thenumberon
therightsideofthesliderchanges;thisisthenumbertheslideriscurrentlysetto.
Let’sinvestigateWolfSheepPredation’ssliders.
ChangefromtheInterfacetotheInfotabtolearnwhateachofthismodels’
slidersrepresents.
TheInfotaboffersguidanceandinsightintothemodel.Withinthistabyouwillfindan
explanationofthemodel,suggestionsonthingstotry,andotherinformation.Youmaywant
toreadtheInfotabbeforerunningamodel,oryoumightwanttojuststartexperimenting,
thenlookattheInfotablater.
Whatwouldhappentothesheeppopulationifthereweremoresheepand
lesswolvesinitially?
Turnthe“grass?”switchoff.
Setthe“initial-number-sheep”sliderto100.
Setthe“initial-number-wolves”sliderto20.
Press“setup”andthen“go”.
Letthemodelrunforabout100ticks.
Tryrunningthemodelseveraltimeswiththesesettings.
Whathappenedtothesheeppopulation?
Didthisoutcomesurpriseyou?Whatotherslidersorswitchescanbe
adjustedtohelpoutthesheeppopulation?
Set“initial-number-sheep”to80and“initial-number-wolves”to50.(Thisis
closetohowtheywerewhenyoufirstopenedthemodel.)
Set“sheep-reproduce”to10.0%.
Press“setup”andthen“go”.
Letthemodelrunforabout100timeticks.
Whathappenedtothewolvesinthisrun?
Whenyouopenamodel,alltheslidersandswitchesareonadefaultsetting.Ifyouopena
newmodelorexittheprogram,yourchangedsettingswillnotbesaved,unlessyouchoose
tosavethem.
(Note:inadditiontoslidersandswitches,somemodelshavechoosersandinputboxes.The
WolfSheepPredationdoesn’thaveanyofthese,though.)
GatheringInformation:PlotsandMonitors
Theviewletsyouseewhat’sgoingoninamodel.NetLogoalsoprovideshasotherwaysof
givingyouinformationaboutmodelrun,suchasplotsandmonitors.
Plots
TheplotinWolfSheepPredationcontainsthreelines:sheep,wolves,andgrass/4.(The
grasscountisdividedbyfoursoitdoesn’tmaketheplottootall.)Thelinesshowwhat’s
happeninginthemodelovertime.Theplotlegendshowswhateachlineindicates.Inthis
case,it’sthepopulationcounts.
Whenaplotgetsclosetobecomingfilledup,thehorizontalaxisiscompressedandallofthe
datafrombeforegetssqueezedintoasmallerspace.Inthisway,moreroomismadeforthe
plottogrow.
Ifyouwanttosavethedatafromaplottovieworanalyzeitinanotherapplication,usethe
“ExportPlot”itemontheFilemenu.Itsavestheplotdatainaformatthatcanbyreadbackby
spreadsheetanddatabaseprogramssuchasExcel.Youcanalsoexportaplotbyright-
clickingitandchoosing“Export…”fromthepopupmenu.
Monitors
Monitorsareanothermeansofdisplayinginformationfromamodel.Herearethemonitorsin
WolfSheepPredation:
Themonitorsshowusthepopulationofsheepandwolves,andtheamountofgrass.
(Remember,theamountofgrassisdividedbyfourtokeeptheplotfromgettingtootall.)
Thenumbersdisplayedinthemonitorschangeasthemodelruns,whereastheplotsshow
youdatafromthewholecourseofthemodelrun.
ControllingtheView
IntheInterfacetab,you’llseeatoolbarofcontrols.Someofthesecontrolaspectsoftheview.
Let’sexperimentwiththeeffectofthesecontrols.
Press“setup”andthen“go”tostartthemodelrunning.
Asthemodelruns,movethespeedslidertotheleft.
Whathappens?
Thissliderishelpfulifamodelisrunningtoofastforyoutoseewhat’sgoingonin
detail.
Movethespeedslidertothemiddle.
Trymovingthespeedslidertotheright.
Nowtrycheckinganduncheckingthe“viewupdates”checkbox.
Whathappens?
Fastforwardingthemodelandturningoffviewupdatesareusefulifyou’reimpatientandwant
amodeltorunfaster.Fastforwarding(movingthespeedslidertotheright)dropsview
updatessothemodelcanrunfast,sinceupdatingtheviewtakestimethatcouldbeusedfor
runningthemodelitself.
Whenviewupdatesareoffcompletely,themodelcontinuestoruninthebackground,and
plotsandmonitorsstillupdate.Butifyouwanttoseewhat’shappening,youneedtoturnview
updatesbackonbyrecheckingthebox.Manymodelsrunmuchfasterwhenviewupdates
areoff.Forothers,itmakeslittledifference.
Thesizeoftheviewisdeterminedbyfiveseparatesettings:min-pxcor,max-pxcor,min-
pycor,max-pycor,andpatchsize.Let’stakealookatwhathappenswhenwechangethe
sizeoftheviewinthe“WolfSheepPredation”model.
Therearemoremodelsettingsthanthere’sroomforinthetoolbar.The“Settings…”button
letsyougettotherestofthesettings.
Pressthe“Settings…”buttoninthetoolbar.
Adialogwillopencontainingallthesettingsfortheview:
Whatarethecurrentsettingsformin-pxcor,max-pxcor,min-pycor,max-
pycor,andpatchsize?
Press“cancel”tomakethiswindowgoawaywithoutchangingthesettings.
Placeyourmousepointernextto,butstilloutsideof,theview.
Youwillnoticethatthepointerturnsintoacrosshair.
Holddownthemousebuttonanddragthecrosshairovertheview.
Theviewisnowselected,whichyouknowbecauseitisnowsurroundedbyagray
border.
Dragoneofthesquareblack“handles”.Thehandlesarefoundontheedges
andatthecornersoftheview.
Unselecttheviewbyclickinganywhereinthewhitebackgroundofthe
Interfacetab.
Pressthe“Settings…”buttonagainandlookatthesettings.
Whatnumberschanged?
Whatnumbersdidn’tchange?
TheNetLogoworldisatwodimensionalgridof“patches”.Patchesaretheindividualsquares
inthegrid.InWolfSheepPredation,whenthe“grass?”switchisontheindividualpatchesare
easilyseen,becausesomearegreen,othersbrown.
Thinkofthepatchesasbeinglikesquaretilesinaroomwithatilefloor.Bydefault,exactlyin
themiddleoftheroomisatilelabeled(0,0);meaningthatiftheroomwasdividedinhalfone
wayandthentheotherway,thesetwodividinglineswouldintersectonthistile.Wenowhave
acoordinatesystemthatwillhelpuslocateobjectswithintheroom:
Howmanytilesawayisthe(0,0)tilefromtherightsideoftheroom?
Howmanytilesawayisthe(0,0)tilefromtheleftsideoftheroom?
InNetLogo,thenumberoftilesfromrighttoleftiscalledworld-width.Andthenumberoftiles
fromtoptobottomisworld-height.Thesenumbersaredefinedbytop,bottom,leftandright
boundaries.
Inthesediagrams,max-pxcoris3,min-pxcoris-3,max-pycoris2andmin-pycoris-2.
Whenyouchangethepatchsize,thenumberofpatches(tiles)doesn’tchange,thepatches
onlygetlargerorsmallerintheview.
Let’slookattheeffectofchangingtheminimumandmaximumcoordinatesintheworld.
UsingtheSettingsdialogthatisstillopen,changemax-pxcorto30andmax-
pycorvalueto10.Noticethatmin-pxcorandmin-pycorchangetoo.That’s
becausebydefaulttheorigin(0,0)isinthecenteroftheworld.
Whathappenedtotheshapeoftheview?
Pressthe“setup”button.
Nowyoucanseethenewpatchesyouhavecreated.
Edittheviewbypressingthe“Settings…”buttonagain.
Changethepatchsizeto20andpress“OK”.
Whathappenedtothesizeoftheview?Diditsshapechange?
Editingtheviewalsoletsyouchangeothersettings.Feelfreetoexperimentwiththese.
OnceyouaredoneexploringtheWolfSheepPredationmodel,youmaywanttotakesome
timejusttoexploresomeoftheothermodelsavailableintheModelsLibrary.
ModelsLibrary
Thelibrarycontainsfoursections:SampleModels,CurricularModels,CodeExamples,and
HubNetActivities.
SampleModels
TheSampleModelssectionisorganizedbysubjectareaandcurrentlycontainsmorethan
200models.Wearecontinuouslyworkingonaddingnewmodelstoit,socomevisitthis
sectionatalaterdatetoviewthenewadditionstothelibrary.
SomeofthefoldersinSampleModelshavefoldersinsidethemlabeled“(unverified)”.These
modelsarecompleteandfunctional,butarestillintheprocessofbeingreviewedforcontent,
accuracy,andqualityofcode.
CurricularModels
Thesearemodelsdesignedtobeusedinschoolsinthecontextofcurriculadevelopedbythe
CCLatNorthwesternUniversity.SomeofthesearemodelsarealsolistedunderSample
Models;othersareuniquetothissection.SeetheInfotabsofthemodelsformore
informationonthecurriculatheygowith.
CodeExamples
ThesearesimpledemonstrationsofparticularfeaturesofNetLogo.They’llbeusefultoyou
laterwhenyou’reextendingexistingmodelsorbuildingnewones.Forexample,ifyouwanted
toaddahistogramtoyourmodel,you’dlookat“HistogramExample”tofindouthow.
HubNetActivities
Thissectioncontainsparticipatorysimulationsforusewithgroups.Formoreinformation
aboutHubNet,seetheHubNetGuide.
What’sNext?
Ifyouwanttolearnhowtoexploremodelsatadeeperlevel,Tutorial#2:Commandswill
introduceyoutotheNetLogomodelinglanguage.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuild
newones.
Tutorial#2:Commands
NetLogo6.0.4UserManual
Sofaryou’vesuccessfullynavigatedyourwaythroughopeningandrunningmodels,pressing
buttons,changingslidersandswitches,andgatheringinformationfromamodelusingplots
andmonitors.
Inthissection,thefocuswillstarttoshiftfromobservingmodelstomanipulatingmodels.You
willstarttoseetheinnerworkingsofthemodelsandbeabletochangehowtheylook.
SampleModel:TrafficBasic
OpentheModelsLibrary(fromtheFilemenu).
OpenTrafficBasic,foundinthe“SocialScience”section.
Runthemodelforawhiletogetafeelforit.
ConsulttheInfotabforanyquestionsyoumayhave.
Inthismodel,youwillnoticeoneredcarinastreamofbluecars.Thestreamofcarsareall
movinginthesamedirection.Everysooftenthey“pileup”andstopmoving.Thisismodeling
howtrafficjamscanformwithoutaspecificcauselikeanaccident.
Youmayalterthesettingsandobserveafewrunstogetafullerunderstandingofthemodel.
AsyouareusingtheTrafficBasicmodel,haveyounoticedanyadditions
youwouldliketomaketothemodel?
LookingattheTrafficBasicmodel,youmaynoticetheenvironmentisfairlysimple;ablack
backgroundwithawhitestreetandnumberofbluecarsandoneredcar.Changesthatcould
bemadetothemodelinclude:changingthecolorandshapeofthecars,addingahouseor
streetlight,creatingastoplight,orevencreatinganotherlaneoftraffic.Someofthese
suggestedchangesarevisual,toenhancethelookofthemodel,whileothersaremore
behavioral.Wewillbefocusingmoreonthesimplerorcosmeticchangesthroughoutmostof
thistutorial.(Tutorial#3willgointogreaterdetailaboutbehavioralchanges,whichrequire
changingtheCodetab.)
TomakethesesimplechangeswewillbeusingtheCommandCenter.
CommandCenter
TheCommandCenterisfoundintheInterfacetab.Itallowsyoutoentercommandsor
directionstoamodel.CommandsareinstructionsyoucangivetoNetLogo’sagents:turtles,
patches,links,andtheobserver.
InTrafficBasic:
Pressthe“setup”button.
LocatetheCommandCenter.
ClickthemouseinthewhiteboxatthebottomoftheCommandCenter.
Typethetextshownhere:
Pressthereturnkey.
WhathappenedtotheView?
YoumayhavenoticedthebackgroundoftheViewhasturnedallyellowandthe
streethasdisappeared.
Whydidn’tthecarsturnyellowtoo?
Lookingbackatthecommandthatwaswritten,weaskedonlythepatchesto
changetheircolor.Inthismodel,thecarsarerepresentedbyadifferentkindof
agent,called“turtles”.Therefore,thecarsdidnotreceivetheseinstructionsandthus
didnotchange.
WhathappenedintheCommandCenter?
Youmayhavenoticedthatthecommandyoujusttypedisnowdisplayedinthe
CommandCenterasshownbelow:
TypeinthebottomoftheCommandCenterthetextshownbelow:
Wastheresultwhatyouexpected?
Theviewshouldhaveayellowbackgroundwithalineofbrowncarsinthemiddle:
TheNetLogoworldisatwodimensionalworldthatismadeupofturtles,patches,links,and
anobserver.Thepatchesarethegroundoverwhichtheturtlesmove.Linksareconnections
betweenturtles.Andtheobserverisabeingthatoverseeseverythingthatisgoingon.(For
morespecifics,refertotheNetLogoProgrammingGuide.)
IntheCommandCenteryoucangivecommandstoanyofthesetypesofagents.Youchoose
whichtypetotalktobyusingthepopupmenulocatedinthebottomleftcorner.Youcanalso
usethetabkeyonyourkeyboardtocyclethroughthedifferenttypes.
IntheCommandCenter,clickonthe“observer>”inthebottomleftcorner:
Choose“turtles”fromthepopupmenu.
Typeset color pinkandpressreturn.
Pressthetabkeyuntilyousee“patches>”inthebottomleftcorner.
Typeset pcolor whiteandpressreturn.
WhatdoestheViewlooklikenow?
Doyounoticeanydifferencesbetweenthesetwocommandsandthe
observercommandsfromearlier?
Theobserveroverseestheworldandthereforecangiveacommandtothepatchesorturtles
usingask.Likeinthefirstexample(observer>ask patches [set pcolor yellow] ),the
observerhastoaskthepatchestosettheirpcolortoyellow.Butwhenacommandisdirectly
giventoagroupofagentslikeinthesecondexample(patches>set pcolor white),youonly
havetogivethecommanditself.
Press“setup”.
Whathappened?
WhydidtheViewrevertbacktotheoldversion,withtheblackbackgroundandwhiteroad?
Uponpressingthe“setup”button,themodelwillreconfigureitselfbacktothesettingsoutlined
intheCodetab.TheCommandCenterdoesn’tpermanentlychangethemodel.Itallowsyou
tomanipulatetheNetLogoworlddirectlytofurtheranswerthose“Whatif”questionsthatpop
upasyouareinvestigatingthemodels.(TheCodetabisexplainedinthenexttutorial,andin
theProgrammingGuide.)
NowthatwehavefamiliarizedourselveswiththeCommandCenter,let’slookatsomemore
detailsabouthowcolorsworkinNetLogo.
Workingwithcolors
Youmayhavenoticedintheprevioussectionthatweusedtwodifferentwordsforchanging
color:colorandpcolor.
Whatisthedifferencebetweencolorandpcolor?
Choose“turtles”fromthepopupmenuintheCommandCenter(orusethetab
key).
Typeset color blueandpressreturn.
Whathappenedtothecars?
Thinkaboutwhatyoudidtomakethecarsturnblue,andtrytomakethepatches
turnred.
Ifyoutrytoaskthepatchestoset color red,anerrormessageoccurs:
Typeset pcolor redinsteadandpressreturn.
Wecallcolorandpcolor“variables”.Somecommandsandvariablesarespecifictoturtles
andsomearespecifictopatches.Forexample,thecolorvariableisaturtlevariable,while
thepcolorvariableisapatchvariable.
Goaheadandpracticealteringthecolorsoftheturtlesandpatchesusingthesetcommand
andthesetwovariables.
Tobeabletomakemorechangestothecolorsofturtlesandpatches,orshallwesaycars
andbackgrounds,weneedtogainalittleinsightintohowNetLogodealswithcolors.
InNetLogo,colorshaveanumericvalue.Inalloftheexerciseswehavebeenusingthename
ofthecolor.ThisisbecauseNetLogorecognizes16differentcolornames.Thisdoesnot
meanthatNetLogoonlyrecognizes16colors.Therearemanyshadesinbetweenthese
colorsthatcanbeusedtoo.Here’sachartthatshowsthewholeNetLogocolorspace:
Togetanintermediateshade,yourefertoitbyanumberinstead,orbyaddingorsubtracting
anumberfromaname.Forexample,whenyoutypeset color red,thisdoesthesamething
asifyouhadtypedset color 15.Andyoucangetalighterordarkerversionofthesame
colorbyusinganumberthatisalittlelargeroralittlesmaller,asfollows.
Choose“patches”fromthepopupmenuintheCommandCenter(orusethe
tabkey).
Typeset pcolor red - 2(Thespacingaroundthe“-”isimportant.)
Bysubtractingfromred,youmakeitdarker.
Typeset pcolor red + 2
Byaddingtored,youmakeitlighter.
Youcanusethistechniqueonanyofthecolorslistedinthechart.
AgentMonitorsandAgentCommanders
Inthepreviousactivity,weusedthesetcommandtochangethecolorsofallthecars.Butif
yourecall,theoriginalmodelcontainedoneredcaramongstagroupofbluecars.Let’slook
athowtochangeonlyonecar’scolor.
Press“setup”togettheredcartoreappear.
Right-clickontheredcar.
Ifthereisanotherturtleclosetotheredturtleyou’llseemorethanoneturtle
listedatthebottomofthemenu.Moveyourmouseovertheturtleselections,
noticewhenyourmousehighlightsaturtlemenuitemthatturtleishighlighted
intheview.Select“inspectturtle”fromthesub-menufortheredturtle.
Aturtlemonitorforthatcarwillappear:
Themini-viewatthetopoftheagentmonitorwillalwaysstaycenteredonthisagent.Youcan
zoomtheviewinandoutusingthesliderbelowtheviewandyoucanwatchthisturtleinthe
mainviewbypressingthe“watch-me”button.
Takingacloserlookatthisturtlemonitor,wecanseeallofthevariablesthatbelongtothe
redcar.Avariableisalocationthatholdsavalue.
Let’stakeacloserlookattheturtlemonitor:
Whatisthisturtle’swhonumber?
Whatcoloristhisturtle?
Whatshapeisthisturtle?
Thisturtlemonitorisshowingaturtlewhothathasawhonumberof0,acolorof15(red–
seechartabove),andtheshapeofacar.
Therearetwootherwaystoopenaturtlemonitorbesidesright-clicking.Onewayisto
choose“TurtleMonitor”fromtheToolsmenu,thentypethewhonumberoftheturtleyou
wanttoinspectintothe“who”fieldandpressreturn.Theotherwayistotypeinspect turtle
0(orotherwhonumber)intotheCommandCenter.
Youcloseaturtlemonitorbyclickingthecloseboxintheupperlefthandcorner(Mac)or
upperrighthandcorner(otheroperatingsystems).
NowthatweknowmoreaboutAgentMonitors,wehavethreewaystochangeanindividual
turtle’scolor.
OnewayistousetheboxcalledanAgentCommanderfoundatthebottomofanAgent
Monitor.Youtypecommandshere,justlikeintheCommandCenter,butthecommandsyou
typehereareonlydonebythisparticularturtle.
IntheAgentCommanderoftheTurtleMonitorforturtle0,typeset color
pink.
WhathappensintheView?
DidanythingchangeintheTurtleMonitor?
Asecondwaytochangeoneturtle’scoloristogodirectlytothecolorvariableintheTurtle
Monitorandchangethevalue.
Selectthetexttotherightof“color”intheTurtleMonitor.
Typeinanewcolorsuchasgreen + 2.
Whathappened?
Thethirdwaytochangeanindividualturtle’sorpatch’scoloristousetheobserver.Since,
theobserveroverseestheNetLogoworld,itcangivecommandsthataffectindividualturtles,
aswellasgroupsofturtles.
IntheCommandCenter,select“observer”fromthepopupmenu(orusethe
tabkey).
Typeask turtle 0 [set color blue]andpressreturn.
Whathappens?
JustasthereareTurtleMonitors,therearealsoPatchMonitors,whichworkvery
similarly.
Canyoumakeapatchmonitoranduseittochangethecolorofasingle
patch?
Ifyoutrytohavetheobserverask patch 0 [set pcolor blue],you’llgetanerrormessage:
Toaskanindividualturtletodosomething,weuseitswhonumber.Butpatchesdon’thave
whonumbers,thereforeweneedtorefertothemsomeotherway.
Remember,patchesarearrangedonacoordinatesystem.Twonumbersareneededtoplota
pointonagraph:anx-axisvalueanday-axisvalue.Patchlocationsaredesignatedinthe
samewayasplottingapoint.
Openapatchmonitorforanypatch.
Themonitorshowsthatforthepatchinthepicture,itspxcorvariableis-19andits
pycorvariableis0.Ifwegobacktotheanalogyofthecoordinateplaneandwanted
toplotthispoint,thepointwouldbefoundonthexaxisleftoftheorigin,wherex=-
19andy=0.
Totellthisparticularpatchtochangecolor:
Inthebottomofthepatchmonitor,enterset pcolor blueandpressreturn.
Typingacommandinaturtleorpatchmonitoraddressesonlythatturtleorpatch.
YoucanalsotalktoasinglepatchfromtheCommandCenter:
IntheCommandCenter,enterask patch -19 0 [set pcolor green] and
pressreturn.
What’sNext?
Atthispoint,youmaywanttotakesometimetotryoutthetechniquesyou’velearnedon
someoftheothermodelsintheModelsLibrary.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuild
yourownmodels.
Tutorial#3:Procedures
NetLogo6.0.4UserManual
Thistutorialleadsyouthroughtheprocessofbuildingacompletemodel,builtupinstages,witheverystepexplainedalongtheway.
Agentsandprocedures
InTutorial#2,youlearnedhowtousethecommandcenterandagentmonitorstoinspectandmodifyagentsandmakethemdothings.
Nowyou’rereadytolearnabouttherealheartofaNetLogomodel:theCodetab.
You’veseenthatagentsinNetLogoaredividedintopatches,turtles,links,andtheobserver.Patchesarestationaryandarrangedina
grid.Turtlesmoveoverthatgrid.Linksconnecttwoturtles.Theobserveroverseeseverythingthat’sgoingonanddoeswhateverthe
turtles,patchesandlinkscan’tdoforthemselves.
AllfourtypesofagentscanrunNetLogocommands.Allfourcanalsorun“procedures”.AprocedurecombinesaseriesofNetLogo
commandsintoasinglenewcommandthatyoudefine.
Youwillnowlearntowriteproceduresthatmaketurtlesmove,eat,reproduce,anddie.Youwillalsolearnhowtomakemonitors,
sliders,andplots.Themodelwe’llbuildisasimpleecosystemmodelnotunlikeWolfSheepPredationfromTutorial#1.
Makingthesetupbutton
Tostartanewmodel,select“New”fromtheFilemenu.Thenbeginbycreatingasetupbutton:
Clickthe“Add”iconinthetoolbaratthetopoftheInterfacetab.
OnthemenunexttoAdd,selectButton(ifitisn’talreadyselected).
ClickwhereveryouwantthebuttontoappearintheemptywhiteareaoftheInterfacetab.
Adialogboxforeditingthebuttonopens.Typesetupintheboxlabeled“Commands”.
PresstheOKbuttonwhenyou’redone;thedialogboxcloses.
Nowyouhaveasetupbutton.Pressingthebuttonrunsaprocedurecalled“setup”.AprocedureisasequenceofNetLogocommands
thatweassignanewname.We’lldefinethatproceduresoon,butwehaven’tyet.Thebuttonreferstoaprocedurethatdoesn’texist,so
thebuttonturnsred:
Ifyouwanttoseetheactualerrormessage,clickthebutton.
Nowwe’llcreatethe“setup”procedure,sotheerrormessagewillgoaway:
SwitchtotheCodetab.
Typethefollowing:
to setup
clear-all
create-turtles 100 [ setxy random-xcor random-ycor ]
reset-ticks
end
Whenyou’redone,theCodetablookslikethis:
Notethatsomelinesareindented.Mostpeoplefindithelpfultoindenttheircode.Itisn’tmandatory,butitmakesthecodeeasiertoread
andchange.
Yourprocedurebeginswithtoandendswithend.Everyprocedurebeginsandendswiththesewords.
Let’slookatwhatyoutypedinandseewhateachlineofyourproceduredoes:
to setupbeginsdefiningaprocedurenamed“setup”.
clear-allresetstheworldtoaninitial,emptystate.Allthepatchesturnblackandanyturtlesyoumighthavecreateddisappear.
Basically,itwipestheslatecleanforanewmodelrun.
create-turtles 100creates100turtles.Theystartoutstandingattheorigin,thatis,thecenterofpatch0,0.
Aftercreate-turtleswecanputcommandsforthenewturtlestorun,enclosedbysquarebrackets.
setxy random-xcor random-ycorisacommandusing“reporters”.Areporter,asopposedtoacommand,reportsaresult.Firsteach
turtlerunsthereporterrandom-xcorwhichwillreportarandomnumberfromtheallowablerangeofturtlecoordinatesalongtheX
axis.Theneachturtlerunsthereporterrandom-ycor,samefortheYaxis.Finallyeachturtlerunsthesetxycommandwiththose
twonumbersasinputs.Thatmakestheturtlemovetothepointwiththosecoordinates.
reset-ticksstartsthetickcounter,nowthatsetupisotherwisecomplete.
endcompletesthedefinitionofthe“setup”procedure.
Whenyou’redonetyping,switchtotheInterfacetabandpressthesetupbuttonyoumadebefore.Youwillseetheturtlesscattered
aroundtheworld:
Presssetupacouplemoretimes,andseehowthearrangementofturtlesisdifferenteachtime.Notethatsometurtlesmayberighton
topofeachother.
Thinkabitaboutwhatyouneededtodotomakethishappen.Youneededtomakeabuttonintheinterfaceandmakeaprocedurethat
thebuttonuses.Thebuttononlyworkedonceyoucompletedbothoftheseseparatesteps.Intheremainderofthistutorial,youwill
oftenhavetocompletetwoormoresimilarstepstoaddanotherfeaturetothemodel.Ifsomethingdoesn’tappeartoworkafteryou
completedwhatyouthoughtisthefinalstepforthatnewfeature,continuetoreadaheadtoseeifthereisstillmoretodo.Afterreading
aheadforacoupleofparagraphs,youshouldthengobackoverthedirectionstoseeifthereisanystepyoumighthavemissed.
Switchingtotick-basedviewupdates
Nowthatwe’reusingthetickcounter(withreset-ticks),weshouldtellNetLogothatitonlyneedstoupdatetheviewoncepertick,
insteadofcontinuouslyupdatingit.
Findtheviewupdatesmenu.It’sabovetheviewandbydefaultsays“continuous”.
Choose“onticks”instead.
Thismakesyourmodelrunfasterandensuresaconsistentappearance(sincetheupdateswillhappenatconsistenttimes).Seethe
ProgrammingGuideforafullerdiscussionofviewupdates.
Makingthegobutton
Nowmakeabuttoncalled“go”.Followthesamestepsyouusedtomakethesetupbutton,except:
ForCommandsentergoinsteadofsetup.
Checkthe“Forever”checkboxintheeditdialog.
Checkthe“Disableuntilticksstart”checkboxtoo.
The“Forever”checkboxmakesthebuttonstaydownoncepressed,soitscommandsrunoverandoveragain,notjustonce.
The“Disableuntilticksstart”preventsyoufrompressinggobeforesetup.
ThenaddagoproceduretotheCodetab:
to go
move-turtles
tick
end
tickisaprimitivethatadvancesthetickcounterbyonetick.
Butwhatismove-turtles?Isitaprimitive(inotherwords,built-intoNetLogo)?No,it’sanotherprocedurethatyou’reabouttoadd.So
far,youhaveintroducedtwoproceduresthatyouaddedyourself:setupandgo.
Addthemove-turtlesprocedureafterthegoprocedure:
to go
move-turtles
tick
end
to move-turtles
ask turtles [
right random 360
forward 1
]
end
Notetherearenospacesaroundthehypheninmove-turtles.InTutorial#2weusedred - 2,withspaces,inordertosubtracttwo
numbers,butherewewantmove-turtles,withoutspaces.The“-”combines“move”and“turtles”intoasinglename.
Hereiswhateachcommandinthemove-turtlesproceduredoes:
ask turtles [ ... ]saysthateachturtleshouldrunthecommandsinthebrackets.
right random 360isanothercommandthatusesareporter.First,eachturtlepicksarandomwholenumberbetween0and359.
(randomdoesn’tincludethenumberyougiveitasapossibleresult.)Thentheturtleturnsrightthisnumberofdegrees.
forward 1makestheturtlemoveforwardonestep.
Whycouldn’twehavejustwrittenallofthesecommandsingoinsteadofinaseparateprocedure?Wecouldhave,butduringthe
courseofbuildingyourproject,it’slikelythatyou’lladdmanyotherparts.We’dliketokeepgoassimpleaspossible,sothatitiseasyto
understand.Eventually,itwillincludemanyotherthingsyouwanttohavehappenasthemodelruns,suchascalculatingsomethingor
plottingtheresults.Eachofthesethingstodowillhaveitsownprocedureandeachprocedurewillhaveitsownuniquename.
The‘go’buttonyoumadeintheInterfacetabisaforeverbutton,meaningthatitwillcontinuallyrunitscommandsuntilyoushutitoff(by
clickingonitagain).Afteryouhavepressed‘setup’once,tocreatetheturtles,pressthe‘go’button.Watchwhathappens.Turnitoff,
andyou’llseethatalltheturtlesstopintheirtracks.
Notethatifaturtlemovesofftheedgeoftheworld,it“wraps”,thatis,itappearsontheotherside.(Thisisthedefaultbehavior.Itcanbe
changed;seetheTopologysectionoftheProgrammingGuideformoreinformation.)
Experimentingwithcommands
Wesuggestyoustartexperimentingwithotherturtlecommands.
TypecommandsintotheCommandCenter(liketurtles> set color red),oraddcommandstosetup,go,ormove-turtles.
NotethatwhenyouentercommandsintheCommandCenter,youmustchooseturtles>,patches>,links>,orobserver>inthepopup
menuontheleft,dependingonwhichagentsaregoingtorunthecommands.It’sjustlikeusingask turtlesorask patches,butsaves
typing.Youcanalsousethetabkeytoswitchagenttypes,whichyoumightfindmoreconvenientthanusingthemenu.
Youmighttrytypingturtles>pen-downintotheCommandCenterandthenpressingthegobutton.
Also,insidethemove-turtlesprocedureyoucantrychangingright random 360toright random 45.
Playaround.It’seasyandtheresultsareimmediateandvisible–oneofNetLogo’smanystrengths.
Whenyoufeelyou’vedoneenoughexperimentingfornow,you’rereadytocontinueimprovingthemodelyouarebuilding.
Patchesandvariables
Nowwe’vegot100turtlesaimlesslymovingaround,completelyunawareofanythingelsearoundthem.Let’smakethingsalittlemore
interestingbygivingtheseturtlesanicebackgroundagainstwhichtomove.
Gobacktothesetupprocedure.Wecanrewriteitasfollows:
to setup
clear-all
setup-patches
setup-turtles
reset-ticks
end
Thenewdefinitionofsetupreferstotwonewprocedures.Todefinesetup-patches,addthis:
to setup-patches
ask patches [ set pcolor green ]
end
Thesetup-patchesproceduresetsthecolorofeverypatchtogreentostartwith.(Aturtle’scolorvariableiscolor;a
patch’sispcolor.)
Theonlypartremaininginournew‘setup’thatisstillundefinedissetup-turtles.
Addthisproceduretoo:
to setup-turtles
create-turtles 100
ask turtles [ setxy random-xcor random-ycor ]
end
Didyounoticethatthenewsetup-turtlesprocedurehasmostofthesamecommandsastheoldsetupprocedure?
SwitchbacktotheInterfacetab.
Pressthesetupbutton.
Voila!AlushNetLogolandscapecompletewithturtlesandgreenpatchesappears:
Afterseeingthenewsetupprocedureworkafewtimes,youmayfindithelpfultoreadthroughtheproceduredefinitionsagain.
Turtlevariables
Sowehavesometurtlesrunningaroundonalandscape,buttheyaren’tdoinganythingwithit.Let’saddsomeinteractionbetweenthe
turtlesandthepatches.
We’llmaketheturtleseat“grass”(thegreenpatches),reproduce,anddie.Thegrasswillgraduallygrowbackafteritiseaten.
We’llneedawayofcontrollingwhenaturtlereproducesanddies.We’lldeterminethatbykeepingtrackofhowmuch“energy”each
turtlehas.Todothatweneedtoaddanewturtlevariable.
You’vealreadyseenbuilt-inturtlevariableslikecolor.Tomakeanewturtlevariable,weaddaturtles-owndeclarationatthetopofthe
Codetab,beforealltheprocedures.Callitenergy:
turtles-own [energy]
to go
move-turtles
eat-grass
tick
end
Let’susethisnewlydefinedvariable(energy)toallowtheturtlestoeat.
SwitchtotheCodetab.
Rewritethegoprocedureasfollows:
to go
move-turtles
eat-grass
tick
end
Addaneweat-grassprocedure:
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
set energy energy + 10
]
]
end
Weareusingtheifcommandforthefirsttime.Lookatthecodecarefully.Eachturtle,whenitrunsthesecommands,comparesthe
valueofthepatchcoloritison(pcolor)tothevalueforgreen.(Aturtlehasdirectaccesstothevariablesofthepatchitisstandingon.)If
thepatchcolorisgreen,thecomparisonreportstrue,andonlythenwilltheturtlerunthecommandsinsidethebrackets(otherwiseit
skipsthem).Thecommandsmaketheturtlechangethepatchcolortoblackandincreaseitsownenergyby10.Thepatchturnsblack
tosignifythatthegrassatthatspothasbeeneaten.Andtheturtleisgivenmoreenergy,fromhavingjusteaten.
Next,let’smakethemovementofturtlesuseupsomeoftheturtle’senergy.
Rewritemove-turtlesasfollows:
to move-turtles
ask turtles [
right random 360
forward 1
set energy energy - 1
]
end
Aseachturtlewanders,itwillloseoneunitofenergyateachstep.
SwitchtotheInterfacetabnowandpressthesetupbuttonandthegobutton.
You’llseethepatchesturnblackasturtlestraveloverthem.
Monitors
NextyouwillcreatetwomonitorsintheInterfacetabwiththetoolbar.(Youmakethemjustlikebuttonsandsliders,usingtheAddicon
onthetoolbar.)Let’smakethefirstmonitornow.
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotin
theInterface.
Adialogboxwillappear.
Inthedialogtype:count turtles(seeimagebelow).
PresstheOKbuttontoclosethedialog.
turtlesisan“agentset”,thesetofallturtles.counttellsushowmanyagentsareinthatset.
Let’smakethesecondmonitornow:
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotin
theInterface.
Adialogboxwillappear.
IntheReportersectionofthedialogboxtype:count patches with [pcolor = green] (seeimagebelow).
IntheDisplaynamesectionofthedialogboxtype:green patches
PresstheOKbuttontoclosethedialogbox.
Herewe’reusingcountagaintoseehowmanyagentsareinanagentset.patchesisthesetofallthepatches,butwedon’tjustwantto
knowhowmanypatchestherearetotal,wewanttoknowhowmanyofthemaregreen.That’swhatwithdoes;itmakesasmaller
agentsetofjustthoseagentsforwhomtheconditioninthebracketsistrue.Theconditionispcolor = green,sothatgivesusjustthe
greenpatches.
Nowwehavetwomonitorsthatwillreporthowmanyturtlesandgreenpatcheswehave,tohelpustrackwhat’sgoingoninourmodel.
Asthemodelruns,thenumbersinthemonitorswillautomaticallychange.
Usethesetupandgobuttonsandwatchthenumbersinthemonitorschange.
Switchesandlabels
Theturtlesaren’tjustturningthepatchesblack.They’realsogainingandlosingenergy.Asthemodelruns,tryusingaturtlemonitorto
watchoneturtle’senergygoupanddown.
Itwouldbenicerifwecouldseeeveryturtle’senergyallthetime.Wewillnowdoexactlythat,andaddaswitchsowecanturntheextra
visualinformationonandoff.
ClickontheAddicononthetoolbar(intheInterfacetab).
SelectSwitchfromthemenunexttoAdd.
Clickonanopenspotintheinterface.
Adialogwillappear.
IntotheGlobalvariablefield,typeshow-energy?Don’tforgettoincludethequestionmarkinthename.(Seeimage
below.)
Nowgobacktothe‘go’procedureusingtheCodetabwiththeToolbar.
Rewritetheeat-grassprocedureasfollows:
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
set energy energy + 10
]
ifelse show-energy?
[ set label energy ]
[ set label "" ]
]
end
Theeat-grassprocedureintroducestheifelsecommand.Lookatthecodecarefully.Eachturtle,whenitrunsthesenewcommands,
checksthevalueofshow-energy?(determinedbytheswitch).Iftheswitchison,comparisonistrueandtheturtlewillrunthecommands
insidethefirstsetofbrackets.Inthiscase,itassignsthevaluefortheenergytothelabeloftheturtle.Ifthecomparisonisfalse(the
switchisoff)thentheturtlerunsthecommandsinsidethesecondsetofbrackets.Inthiscase,itremovesthetextlabels(bysettingthe
labeloftheturtletobenothing).
(InNetLogo,apieceoftextiscalleda“string”,shortforstringofcharacters.Astringisasequenceoflettersorothercharacters,written
betweendoublequotes.Herewehavetwodoublequotesrightnexttoeachother,withnothinginbetweenthem.That’sanemptystring.
Ifaturtle’slabelisanemptystring,notextisattachedtotheturtle.)
TestthisintheInterfacetab,byrunningthemodel(usingthesetupandgobuttons)switchingtheshow-energy?
switchbackandforth.
Whentheswitchison,you’llseetheenergyofeachturtlegoupeachtimeiteatsgrass.You’llalsoseeitsenergygoingdownwhenever
itmoves.
Moreprocedures
Nowourturtlesareeating.Let’smakethemreproduceanddie,too.Andlet’smakethegrassgrowback.We’lladdallthreeoftheseof
thesebehaviorsnow,bymakingthreeseparateprocedures,oneforeachbehavior.
GototheCodetab.
Rewritethegoprocedureasfollows:
to go
move-turtles
eat-grass
reproduce
check-death
regrow-grass
tick
end
Addtheproceduresforreproduce,check-death,andregrow-grassasshownbelow:
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
Eachoftheseproceduresusestheifcommand.Eachturtle,whenitrunscheck-deathitwillchecktoseeifitsenergyislessorequalto
0.Ifthisistrue,thentheturtleistoldtodie(dieisaNetLogoprimitive).
Wheneachturtlerunsreproduce,itchecksthevalueoftheturtle’senergyvariable.Ifitisgreaterthan50,thentheturtlerunsthe
commandsinsidethefirstsetofbrackets.Inthiscase,itdecreasestheturtle’senergyby50,then‘hatches’anewturtlewithanenergy
of50.ThehatchcommandisaNetLogoprimitivewhichlookslikethis:hatchnumber[commands].Thisturtlecreatesnumbernew
turtles,eachidenticaltoitsparent,andasksthenewturtle(s)thathavebeenhatchedtoruncommands.Youcanusethecommandsto
givethenewturtlesdifferentcolors,headings,orwhatever.Inourcasewerunonecommand.Wesettheenergyforthenewlyhatched
turtletobe50.
Wheneachpatchrunsregrow-grassitwillchecktoseeifarandomintegerfrom0to99islessthan3.Ifso,thepatchcolorissetto
green.Thiswillhappen3%ofthetime(onaverage)foreachpatch,sincetherearethreenumbers(0,1,and2)outof100possiblethat
arelessthan3.
SwitchtotheInterfacetabnowandpressthesetupandgobuttons.
Youshouldseesomeinterestingbehaviorinyourmodelnow.Someturtlesdieoff,somenewturtlesarecreated(hatched),andsome
grassgrowsback.Thisisexactlywhatwesetouttodo.
Ifyoucontinuetowatchyourmonitorsinyourmodel,youwillseethatthecountturtlesandgreenpatchesmonitorsbothfluctuate.Is
thispatternoffluctuationpredictable?Istherearelationshipbetweenthevariables?
It’dbeniceifwehadaeasierwaytotrackthechangesinthemodelbehaviorovertime.NetLogoallowsustoplotdataaswegoalong.
Thatwillbeournextstep.
Plotting
Tomakeplottingwork,we’llneedtocreateaplotintheInterfacetabandputsomecommandsinsideit.
Thecommandsweputintheplotswillrunautomaticallywhenoursetupprocedurecallsreset-ticksandwhenourgoprocedurecalls
tick.
CreateaplotbyclickingtheAddicononthetoolbar,selectingPlotnexttoit,andclickingonanopenspotinthe
Interface.
SetitsNameto“Totals”(seeimagebelow)
SettheXaxislabelto“time”
SettheYaxislabelto“totals”
Changethenameofthe“default”pento“turtles”.
Enterplot count turtlesunderPenUpdateCommands.
Pressthe“AddPen”button.
Changethenameofthenewpento“grass”.
Enterplot count patches with [pcolor = green] underPenUpdateCommands.
Whenyou’redone,thedialogshouldlooklikethis:
PressOKinthePlotdialogtofinishediting.
NotethatwhenyoucreatetheplotyoucanalsosettheminimumandmaximumvaluesontheXandYaxes.You’llwanttoleavethe
“AutoScale”checkboxchecked,sothatifanythingyouplotexceedstheminimumandmaximumvaluesfortheaxes,theaxeswill
automaticallygrowsoyoucanseeallthedata.
Notethatweusedtheplotcommandtoaddthenextpointtoaplot.Thiscommandmovesthecurrentplotpentothepointthathasan
Xcoordinateequalto1greaterthanthepreviouslyplottedXcoordinateandaYcoordinateequaltothevaluegivenintheplot
command(inthefirstcase,thenumberofturtles,andinthesecondcase,thenumberofgreenpatches).Asthepensmovetheyeach
drawaline.
Setupandrunthemodelagain.
Youcannowwatchtheplotbeingdrawnasthemodelisrunning.Yourplotshouldhavethegeneralshapeoftheonebelow,though
yourplotmightnotlookexactlythesame.
Rememberthatweleft“AutoScale?”on.Thisallowstheplottoreadjustitselfwhenitrunsoutofroom.
Ifyouforgetwhichpeniswhich,youcanedittheplotandcheckthe“Showlegend?”checkbox.
Youmighttryrunningthemodelseveraltimestoseewhataspectsoftheplotarethesameandwhicharedifferentfromruntorun.
Tickcounter
Tomakecomparisonsbetweenplotsfromonemodelrunandanother,itisoftenusefultodothecomparisonforthesamelengthof
modelrun.Learninghowtostoporstartanactionataspecifictimecanhelpmakethishappenbystoppingthemodelatthesamepoint
eachmodelrun.Keepingtrackofhowmanytimesthegoprocedureisrunisausefulwaytocuetheseactions.That’swhatthetick
counterdoes.
You’realreadyusingthetickcounterinyourmodel,withthereset-ticksandtickcommands,whichalsotriggerplotting.
Youcanalsousethetickcounterforotherthings,suchastosetalimitonthetotallengthofarun.
Changethegoprocedure:
to go
if ticks >= 500 [ stop ]
move-turtles
eat-grass
check-death
reproduce
regrow-grass
tick
end
Nowsetupandrunthemodel.
Thegraphandmodelwon’tkeeprunningforever.TheyshouldstopautomaticallywhenthetickcounterintheInterfacetab’stoolbar
reaches500.
Thetickcommandadvancesthetickcounterby1.ticksisareporterwhichreportsthecurrentvalueofthetickcounter.reset-ticks,in
yoursetupprocedure,takescareofrestartingthetickcounterat0whenanewrunissetupandreadytobegin.
Somemoredetails
First,insteadofalwaysusing100turtles,youcanhaveavaryingnumberofturtles.
Createaslidernamed“number”:clicktheAddicononthetoolbar,selectSlidernexttoit,andclickonanopenspot
intheinterface.
Trychangingtheminimumandmaximumvaluesintheslider.
Theninsideofsetup-turtles,insteadofcreate-turtles 100youcantype:
to setup-turtles
create-turtles number [ setxy random-xcor random-ycor ]
end
Testthischangeandcomparehowhavingmoreorfewerturtlesinitiallyaffecttheplotsovertime.
Second,wouldn’titbenicetoadjusttheenergytheturtlesgainandloseastheyeatgrassandreproduce?
Makeaslidercalledenergy-from-grass.
Makeanotherslidercalledbirth-energy.
Then,insideofeat-grass,makethischange:
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,insideofreproduce,makethischange:
to reproduce
ask turtles [
if energy > birth-energy [
set energy energy - birth-energy
hatch 1 [ set energy birth-energy ]
]
]
end
Finally,whatotherslidercouldyouaddtovaryhowoftengrassgrowsback?Arethererulesyoucanaddtothemovementoftheturtles
ortothenewlyhatchedturtlesthathappenonlyatcertaintimes?Trywritingthem.
What’snext?
Sonowyouhaveasimplemodelofanecosystem.Patchesgrowgrass.Turtleswander,eatthegrass,reproduce,anddie.
Youhavecreatedaninterfacecontainingbuttons,sliders,switches,monitors,andaplot.You’veevenwrittenaseriesofproceduresto
givetheturtlessomethingtodo.
That’swherethistutorialleavesoff.
Ifyou’dliketolookatsomemoredocumentationaboutNetLogo,theInterfaceGuidesectionofthemanualwalksyouthroughevery
elementoftheNetLogointerfaceinorderandexplainsitsfunction.Foradetaileddescriptionandspecificsaboutwritingprocedures,
refertotheProgrammingGuide.AlloftheprimitivesarelistedanddescribedintheNetLogoDictionary.
Also,youcancontinueexperimentingwithandexpandingthismodelifyou’dlike,experimentingwithdifferentvariablesandbehaviors
fortheagents.
Alternatively,youmaywanttorevisitthefirstmodelinthetutorial,WolfSheepPredation.ThisisthemodelyouusedinTutorial #1.In
theWolfSheepPredationmodel,yousawsheepmovearound,consumeresourcesthatarereplenishedoccasionally(grass),
reproduceundercertainconditions,anddieiftheyranoutofresources.Butthatmodelhadanothertypeofcreaturemovingaround–
wolves.Theadditionofwolvesrequiressomeadditionalproceduresandsomenewprimitives.Wolvesandsheeparetwodifferent
“breeds”ofturtle.Toseehowtousebreeds,studyWolfSheepPredation.
Alternatively,youcanlookatothermodels(includingthemanymodelsintheCodeExamplessectionoftheModelsLibrary)orevengo
aheadandbuildyourownmodel.Youdon’tevenhavetomodelanything.Itcanbeinterestingjusttowatchpatchesandturtlesforming
patterns,totrytocreateagametoplay,orwhatever.
Hopefullyyouhavelearnedsomethings,bothintermsoftheNetLogolanguageandabouthowtogoaboutbuildingamodel.Theentire
setofproceduresthatwascreatedaboveisshownbelow.
Appendix:Completecode
ThecompletemodelisalsoavailableinNetLogo’sModelsLibrary,intheCodeExamplessection.It’scalled“Tutorial3”.
Noticethatthislistingisfullof“comments”,whichbeginwithsemicolons.Commentsletyoumixanexplanationthecoderightinwiththe
codeitself.Youmightusecommentstohelpothersunderstandyourmodel,oryoumightusethemasnotestoyourself.
IntheCodetab,commentsaregray,soyoureyescanpickthemouteasily.
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
InterfaceGuide
NetLogo6.0.4UserManual
ThissectionofthemanualexplainsthefunctionofeachelementinNetLogo’suserinterface.
InNetLogo,youhavethechoiceofviewingmodelsfoundintheModelsLibrary,addingto
existingmodels,orcreatingyourownmodels.TheNetLogointerfacewasdesignedtomeetall
theseneeds.
Theinterfacecanbedividedintotwomainparts:NetLogomenus,andthemainNetLogo
window.Themainwindowisdividedintotabs.
Menus
OnaMac,ifyouarerunningtheNetLogoapplication,themenubarislocatedatthetopofthe
screen.Onotherplatforms,themenubarisfoundatthetopoftheNetLogowindow.
Thefunctionsavailablefromthemenusinthemenubararelistedinthefollowingchart.
Chart:NetLogomenus
File
New Startsanewmodel.
Open… OpensanyNetLogomodelonyourcomputer.
ModelsLibrary Acollectionofdemonstrationmodels.
RecentFiles Re-opensanypreviouslymodelopenedwith"File->Open"
Save Savethecurrentmodel,orthecurrentlyselectedsourcefile.
SaveAs… Savethecurrentmodel,orthecurrentlyselectedsourcefile,usinga
differentname.
SaveAll Savethecurrentmodelandallopensourcefiles.Thisoptionisonly
availablewhenoneormoresourcefilesareopen.
Uploadto
Modeling
Commons
UploadsthemodeltoModelingCommons.SeeModelingCommons
SaveAs
NetLogo
Web…
Savesawebpage,inHTMLformat,containingNetLogowebrunning
yourmodel.
ExportWorld… Savesallvariables,thecurrentstateofallturtlesandpatches,the
drawing,theplots,theoutputareaandtherandomstateinformation
toafile.
ExportPlot… Savesthedatainaplottoafile.
ExportAll
Plots… Savesthedatainalltheplotstoafile.
ExportView… Saveapictureofthecurrentview(2Dor3D)toafile(inPNG
format).
Export
Interface… SaveapictureofthecurrentInterfacetab.(inPNGformat)
Export
Output…
Savethecontentsoftheoutputareaortheoutputsectionofthe
commandcentertoafile.
ExportCode… Savethemodel'scodetoanHTMLfile,preservingcolors.
ImportWorld… LoadafilethatwassavedbyExportWorld.
ImportPatch
Colors… Loadanimageintothepatches;seetheimport-pcolorscommand.
ImportPatch
ColorsRGB…
LoadanimageintothepatchesusingRGBcolors;seetheimport-
pcolors-rgbcommand.
Import
Drawing… Loadanimageintothedrawing,seetheimport-drawingcommand.
ImportHubNet
Client
Interface…
LoadtheinterfacefromanothermodelintotheHubNetClientEditor.
Print… Sendsthecontentsofthecurrentlyshowingtabtoyourprinter.
Quit ExitsNetLogo.OnaMac,thisitemisontheNetLogomenuinstead.
Edit
Undo Undolasttexteditingactionyouperformed.
Redo Redolastundoactionyouperformed.
Cut Cutsoutorremovestheselectedtextandtemporarilysavesittothe
clipboard.
Copy Copiestheselectedtext.
Paste Placestheclipboardtextwherecursoriscurrentlylocated.
Delete Deletesselectedtext.
SelectAll Selectallthetextintheactivewindow.
Find… FindsawordorsequenceofcharacterswithintheInfoorCodetabs.
FindNext FindthenextoccurrenceofthewordorsequenceyoulastusedFind
with.
Comment/
Uncomment
UsedintheCodetabtoaddorremovesemicolonsfromcode
(semicolonsareusedinNetLogocodetoindicatecomments).
ShiftLeft/Shift
Right UsedintheCodetabtochangetheindentationlevelofcode.
Format UsedintheCodetabtocorrecttheindentationofthecurrently
selectedcode.
SnaptoGrid
AvailableonlyintheInterfaceTab.Whenenablednewwidgetsstay
ona5pixelgridsoitiseasiertolinethemup.(Note:thisfeatureis
disabledwhenzoomedinorout.)
Convertfrom
5.3.1to6.0
Availableonlyinan".nls"codetab.Treatsthecodeinthistabas
thoughitwerewrittenin5.3.1andconvertsittoruninNetLogo6.
Notethatthiswillnottakeintoaccountcodedefinedinthemain
codetab."Undo"doesn'ttakethisoperationintoaccount,soyou
won'twanttosaveunlessyou'resatisfiedwiththechanges.
Tools
Preferences…
Opensthepreferencesdialog,whereyoucancustomizevarious
NetLogosettings.OnaMac,thisitemisontheNetLogomenu
instead.
Halt
Stopsallrunningcode,includingbuttonsandthecommandcenter.
(Warning:sincethecodeisinterruptedinthemiddleofwhateverit
wasdoing,youmaygetunexpectedresultsifyoutrytocontinue
runningthemodelwithoutfirstpressing"setup"tostartthemodel
runover.)
Globals
Monitor Displaysthevaluesofallglobalvariables.
TurtleMonitor
Displaysthevaluesofallofthevariablesinaparticularturtle.You
cancanalsoeditthevaluesoftheturtle'svariablesandissue
commandstotheturtle.(Youcanalsoopenaturtlemonitorviathe
View;seetheViewsectionbelow.)
PatchMonitor
Displaysthevaluesofallofthevariablesinaparticularpatch.You
cancanalsoeditthevaluesofthepatch'svariablesandissue
commandstothepatch.(Youcanalsoopenapatchmonitorviathe
View;seetheViewsectionbelow.)
LinkMonitor
Displaysthevaluesofallofthevariablesinaparticularlink.Youcan
canalsoeditthevaluesofthelink'svariablesandissuecommands
tothelink.(YoucanalsoopenalinkmonitorviatheView;seethe
Viewsectionbelow.)
CloseAll
AgentMonitors Closesallopenagentmonitorwindows.
CloseMonitors
forDead
Agents
Closesallopenagentmonitorwindowstargetingdeadagents.
Hide/Show
Command
Center
Makesthecommandcentervisibleorinvisible.(Notethatthe
commandcentercanalsobeshownorhidden,orresized,withthe
mouse.)ThisoptionisonlyavailablewhentheInterfaceTabis
active
3DView Opensthe3Dview.SeetheViewssectionoftheInterfaceTab
Guideformoreinformation.
Color
Swatches
OpenstheColorSwatches.SeetheColorSectionofthe
ProgrammingGuidefordetails.
TurtleShapes
Editor
Drawturtleshapes.SeetheShapesEditorGuideformore
information.
LinkShapes
Editor Drawlinkshapes.SeetheShapesEditorGuideformoreinformation.
BehaviorSpace Runsthemodeloverandoverwithdifferentsettings.Seethe
BehaviorSpaceGuideformoreinformation.
System
Dynamics
Modeler
OpenstheSystemDynamicsModeler.SeetheSystemDynamics
ModelerGuideformoredetails.
Preview
Commands
Editor
Allowsforeasyeditingofthecommandssequenceusedtocreate
previewimagesformodels.Givesawaytospecifywhatcodewillbe
used(orspecifythattheimageismanuallymade)andpreviewthe
resultingimage.
HubNetClient
Editor
OpenstheHubNetClientEditor.SeetheHubNetAuthoringGuide
formoredetails.
HubNet
ControlCenter
DisabledifnoHubNetactivityisopen.SeetheHubNetGuidefor
moreinformation.
Zoom
Larger Increasetheoverallscreensizeofthemodel.Usefulonlarge
monitorsorwhenusingaprojectorinfrontofagroup.
NormalSize Resetthescreensizeofthemodeltothenormalsize.
Smaller Decreasetheoverallscreensizeofthemodel.
Tabs
Thismenuofferskeyboardshortcutsforeachofthetabs.OnaMac,
it'sCommand1throughCommand3.OnWindows,it'sControl1
throughControl3.Additionalnumbersareusedfortabscontaining
".nls"files.
Help
LookUpIn
Dictionary
Opensabrowserwiththedictionaryentryfortheselectedcommand
orreporter.(YoumayalsousetheF1keyforthis.)
NetLogoUser
Manual Opensthismanualinawebbrowser.
NetLogo
Dictionary OpenstheNetLogoDictionaryinawebbrowser.
NetLogoUsers
Group OpenstheNetLogoUsersGroupsiteinawebbrowser.
Introductionto
Agent-Based
Modeling
OpenstheMITPresspagefor"IntroductiontoAgent-Based
Modeling"(byUriWilenskyandWilliamRand)inawebbrowser.
Donate OpenstheNetLogodonationpageinawebbrowser.
AboutNetLogo
6.0.4…
InformationonthecurrentNetLogoversionyouarerunning.Ona
Mac,thismenuitemisontheNetLogomenuinstead.
Tabs
AtthetopofNetLogo’smainwindowarethreetabslabeled“Interface”,“Info”and“Code”.Only
onetabatatimecanbevisible,butyoucanswitchbetweenthembyclickingonthetabsatthe
topofthewindow.
Rightbelowtherowoftabsisatoolbarcontainingarowofcontrols.Thecontrolsavailablevary
fromtabtotab.
InternationalUsage
Charactersets
NetLogoalwayssavesandloadsmodelsintheUTF-8characterencoding,whichincludesa
widerangeofinternationalcharacters.
IfyouareinalocaleotherthanU.S.English,letusknowifyouhaveanytroubleusingyourlocal
characterset.
TheTransitionGuidehasadviceonconvertingmodelscontaininginternationalcharactersfrom
earlierNetLogoversions.
Languages
MostofNetLogo’sGUI,andsomeofitserrormessages,arenow“internationalized”.This
meansthatitisnowpossibletodisplayNetLogoindifferentlanguages.
Wesay“possible”herebecausethecurrentreleaseofNetLogoonlysupportsEnglish,Spanish,
Chinese,Russian,andJapanese.
Theworkoninternationalizationisnotcomplete.Weareaskingforhelpfromtheuser
communityinhelpinguslocalizeitemssuchasthemenusanderrormessages.
Defaultlanguage
Bydefault,NetLogousesthesamelanguageyouroperatingsystemissetto,ifavailable.(If
unavailable,yougetEnglish.)
Youcanrecordapreferenceforadifferentlanguagebychangingthe“UserInterfaceLanguage”
optioninthepreferencesdialog.Onceanewlanguageischosenyouwillhavetorestart
NetLogo.
Supportfortranslators
WehopeNetLogowillbecomeavailableinmanydifferentlanguages.Ifyouwouldliketo
translateNetLogotoyourlanguage,seethiswikipageforinstructions.
InterfaceTabGuide
NetLogo6.0.4UserManual
TheInterfacetabiswhereyouwatchyourmodelrun.Italsohastoolsyoucanusetoinspectandalter
what’sgoingoninsidethemodel.
WhenyoufirstopenNetLogo,theInterfacetabisemptyexceptfortheview,wheretheturtlesand
patchesappear,andtheCommandCenter,whichallowsyoutoissueNetLogocommands.
Workingwithinterfaceelements
ThetoolbarontheInterfacetabcontainsbuttonsthatletyouedit,delete,andcreateitemsinthe
Interfacetabandamenuthatletsyouselectdifferentinterfaceitems(suchasbuttonsandsliders).
Thebuttonsinthetoolbararedescribedbelow.
Adding:Toaddaninterfaceelement,selecttheelementfromthedropdownmenu.NotethattheAdd
buttonstaysdown.Thenclickonthewhiteareabelowthetoolbar.(Ifthemenuisalreadyshowingthe
righttype,youcanjustpresstheAddbuttoninsteadofusingthemenuagain.)
Selecting:Toselectaninterfaceelement,dragarectanglearounditwithyourmouse.Agrayborder
withblackhandleswillappeararoundtheelementtoshowitisselected.
Selectingmultipleitems:Youcanselectmultipleinterfaceelementsatthesametimebyincluding
themintherectangleyoudrag.Ifmultipleelementsareselected,oneofthemisthe“key”item,which
meansthatifyouusethe“Edit”or“Delete”buttonsontheInterfaceToolbar,onlythekeyitemis
affected.Thekeyitem’sborderisdarkergray.
Unselecting:Tounselectallinterfaceelements,clickthemouseonthewhitebackgroundofthe
Interfacetab.Tounselectanindividualelement,right-clicktheelementandchoose“Unselect”fromthe
popupmenu.
Editing:Tochangethecharacteristicsofaninterfaceelement,selecttheelement,thenpressthe“Edit”
buttonontheInterfacetoolbar.Youmayalsodoubleclicktheelementonceitisselected.Athirdwayto
editanelementistoright-clickitandchoose“Edit”fromthepopupmenu.Ifyouusethislastmethod,itis
notnecessarytoselecttheelementfirst.
Moving:Selecttheinterfaceelement,thendragitwithyourmousetoitsnewlocation.Ifyouholddown
theshiftkeywhiledragging,theelementwillmoveonlystraightupanddownorstraightleftandright.
Resizing:Selecttheinterfaceelement,thendragtheblack“handles”intheselectionborder.
Deleting:Selecttheelementorelementsyouwanttodelete,thenpressthe“Delete”buttononthe
Interfacetoolbar.Youmayalsodeleteanelementbyright-clickingitandchoosing“Delete”fromthe
popupmenu.Ifyouusethislattermethod,itisnotnecessarytoselecttheelementfirst.
Tolearnmoreaboutthedifferentkindsofinterfaceelements,refertothechartbelow.
Chart:InterfaceToolbar
Icon&Name Description
Abuttoniseitheronceorforever.Whenyouclickonaoncebutton,itexecutesits
instructionsonce.Theforeverbuttonexecutestheinstructionsoverandover,until
youclickonthebuttonagaintostoptheaction.Ifyouhaveassignedanactionkey
tothebutton,pressingthecorrespondingkeyboardkeywillactjustlikeabutton
presswhenthebuttonisinfocus.Buttonswithactionkeyshavealetterinthe
upperrightcornerofthebuttontoshowwhattheactionkeyis.Ifthekeyboard
focusisinanotherinterfaceelementsuchastheCommandCenter,pressingthe
actionkeywon'ttriggerthebutton.Theletterintheupperrighthandcornerofthe
buttonwillbedimmedinthissituation.Toenableactionkeys,clickinthewhite
backgroundoftheInterfacetab.
Slidersareglobalvariables,whichareaccessiblebyallagents.Theyareusedin
modelsasaquickwaytochangeavariablewithouthavingtorecodethe
procedureeverytime.Instead,theusermovestheslidertoavalueandobserves
whathappensinthemodel.
Switchesareavisualrepresentationforatrue/falseglobalvariable.Youmayset
thevariabletoeitheron(true)oroff(false)byflippingtheswitch.
Choosersletyouchooseavalueforaglobalvariablefromalistofchoices,
presentedinadropdownmenu.Thechoicesmaybestrings,numbers,booleans,
orlists.
InputBoxesareglobalvariablesthatcontainstringsornumbers.Themodelauthor
chooseswhattypesofvaluesyoucanenter.Inputboxescanbesettocheckthe
syntaxofastringforcommandsorreporters.Numberinputboxesreadanytypeof
constantnumberreporterwhichallowsamoreopenwaytoexpressnumbersthan
aslider.ColorinputboxesofferaNetLogocolorchooser.
Monitorsdisplaythevalueofanyreporter.Thereportercouldbeavariable,a
complexreporter,oracalltoareporterprocedure.Monitorsautomaticallyupdate
severaltimespersecond.
Plotsshowdatathemodelisgenerating.
Theoutputareaisascrollingareaoftextwhichcanbeusedtocreatealogof
activityinthemodel.Amodelmayonlyhaveoneoutputarea.
NotesletsyouaddinformativetextlabelstotheInterfacetab.Thecontentsofnotes
donotchangeasthemodelruns.
TheothercontrolsintheInterfacetoolbarallowyoutocontroltheviewupdatesandvariousothermodel
properties.
Thesliderletsyoucontrolhowfastthemodelruns.Slowercanbevaluablesincesomemodelsrun
sofastthey’rehardtofollow.Youcanalsofast-forwardthemodelbymovingtheslidertotheright,
reducingthefrequencyofviewupdates.
Theviewupdatescheckboxcontrolswhetherviewupdateshappenatall.
Theupdatemodemenuallowsyoutoswitchbetweencontinuousandtick-basedupdates.
The“Settings…”buttonallowsyoutochangemodelsettings.
“Continuous”updatesmeansthatNetLogoupdates(thatis,redraws)theviewmanytimesasecond,
regardlessofwhatisgoingoninthemodel.“Tick-based”updatesmeansthattheviewonlyupdates
whenthetickcounteradvances.(Forafullerdiscussionofviewupdates,seetheProgrammingGuide.)
The2Dand3Dviews
ThelargeblacksquareintheInterfacetabisthe2Dview.It’savisualrepresentationoftheNetLogo
worldofturtlesandpatches.Initiallyit’sallblackbecausethepatchesareblackandtherearenoturtles
yet.Youcanopenthe3DView,analternatevisualrepresentationoftheworld,byrightclicking(ctrl-
clickingonMac)ontheViewandchoosing“Switchto3DView”(thisoptionisalsoavailableinthe
“Tools”menu).
ThereareanumberofsettingsfortheView(accessiblebyeditingtheView,orbypressingthe
“Settings…”buttonintheInterfaceToolbar):
Noticethatthesettingsarebrokenupintothreegroups.Thereareworld,view,andtickscounter
settings.Worldsettingsaffectthepropertiesoftheworldthattheturtleslivein(changingthemmay
requireresettingtheworld).Viewandtickcountersettingsonlyaffecttheappearance,changingthem
willnotaffecttheoutcomeofthemodel.
Theworldsettingsallowyoutodefinetheboundariesandtopologyoftheworld.Atthetopoftheleft
sideoftheworldpanelyoucanchoosealocationfortheoriginoftheworldeither“Center”,“Corner”,
“Edge”,or“Custom”.Bydefaulttheworldhasacenterconfigurationwhere(0,0)isatthecenterofthe
worldandyoudefinethenumberofpatchesfromthecentertotherightandleftboundariesandthe
numberofpatchesfromthecentertothetopandbottomboundaries.Forexample:ifyousetMax-Pxcor
=10,thenMin-Pxcorwillautomaticallybesetto-10,thusthereare10patchestotheleftoftheorigin
and10patchestotherightofpatch00,foratotalof21patchesineachrow.
ACornerconfigurationallowsyoutodefinethelocationoftheoriginasoneofthecornersoftheworld,
upperleft,upperright,lowerleft,orlowerright.Thenyoudefinethefarboundaryinthexandy
directions.Forexampleifyouchoosetoputtheorigininthelowerleftcorneroftheworldyoudefinethe
rightandtop(positive)boundaries.
Edgemodeallowsyoutoplacetheoriginalongoneoftheedges(xory)thendefinethefarboundaryin
thatdirectionandbothboundariesintheother.Forexampleifyouselectedgemodealongthebottomof
theworld,youmustalsodefinethetopboundary,aswellastheleftandtheright.
Finally,Custommodeallowsyoutoplacetheoriginatanylocationintheworld,thoughpatch00must
stillexistintheworld.
Asyouchangethesettingsyouwillnoticethatthechangesyoumakearereflectedinthepreviewonthe
rightsideofthepanelwhichshowstheoriginandtheboundaries.Thewidthandheightoftheworldare
displayedbelowthepreview.
Alsobelowthepreviewtherearetwocheckboxes,theworldwrapsettings.Theseallowyoutocontrol
thetopologyoftheworld.Noticewhenyouclickthecheckboxesthepreviewindicateswhichdirections
allowwrapping,andthenameofthetopologyisdisplayednexttotheworlddimensions.Seethe
TopologysectionoftheProgrammingGuideformoreinformation.
Theviewsettingsallowyoutocustomizethelookoftheviewwithoutchangingtheworld.Changingview
settingswillneverforceaworldreset.Tochangethesizeofthe2DViewadjustthe“PatchSize”setting,
measuredinpixels.Thisdoesnotchangethenumberofpatches,onlyhowlargethepatchesappearin
the2DView.(Notethatthepatchsizedoesnotaffectthe3DView,asyoucansimplymakethe3D
Viewlargerbymakingthewindowlarger.)
Thefontsizesettingletsyoucontrolthesizeofturtle,patch,andlinklabels.
Theframeratecontrolshowoftentheviewgetsupdated.Thiscanhaveadramaticeffectonthedefault
speedatwhichamodelruns.Formoredetails,seetheviewupdatessectionoftheProgrammingGuide.
The“Smoothedges”checkboxcontrolstheuseofanti-aliasinginthe3Dviewonlyandonlyappears
wheneditingfromthe3Dview.Uncheckingitmakeslinesappearmorejaggedbutmayspeedup
rendering.
Tickcountersettingscontroltheappearanceofthetickcounterwhichisvisible(ornot)intheview
controlstrip.
Turtle,patchandlinkmonitorsareeasilyavailablethroughtheView,justright-clickontheturtleorpatch
youwanttoinspect,andchoose“inspectturtle…”or“inspectpatch…”fromthepopupmenu.Youcan
alsowatch,followorrideaturtlebyselectingtheappropriateitemintheturtlesub-menu.(Turtle,patch
andlinkmonitorscanalsobeopenedfromtheToolsmenuorbyusingtheinspectcommand.)
SomeNetLogomodelsletyouinteractwiththeturtlesandpatcheswithyourmousebyclickingand
draggingintheView.
Manipulatingthe3DView
Atthebottomofthewindowtherearebuttonstomovetheobserver,orchangetheperspectivefrom
whichyouarelookingattheworld.
Abluecrossappearsatthecurrentfocuspointasyouadjustthesesettings.Thelittlebluetrianglewill
alwayspointalongthey-axisinthepositivedirection,soyoucanorientyourselfincaseyougetlost.
Tolookattheworldfromadifferentangle,pressthe“rotate”button,thenclickanddragthemouse.The
observerwillcontinuetofacethesamepointasbefore(wherethebluecrossis)butitspositioninthe
relationtothexy-planewillchange.
Tomovecloserorfartherawayfromtheworldortheagentyouarewatching,followingorriding,press
the“zoom”buttonanddragupanddown.Notewhenyouareinfolloworridemodezoomingwillswitch
youbetweenrideandfollow,sincerideisjustaspecialcaseoffollowwherethedistanceatwhichyou
arefollowingis0.
Tochangethepositionoftheobserverwithoutchangingthedirectionitisfacingselectthe“move”
buttonanddragthemouseinsidethe3DViewwhileholdingdownthemousebutton.
Toallowthemousepositionandstatetobepassedtothemodelselectthe“interact”buttonanditwill
functionjustasthemousedoesinthe2Dview.
Toreturntheobserverandfocuspointtotheirdefaultpositionspressthe“ResetPerspective”button(or
usethereset-perspectivecommand).
FullscreenMode
Toenterfullscreenmode,pressthe“FullScreen”button,toexitfullscreenmode,presstheEsckey.
Note:Fullscreenmodedoesn’tworkoneverycomputer.Itdependsonyourgraphicscard.Seethe
SystemRequirementsfordetails.
3DShapes
Someshapesareautomaticallymappedtotrue3Dcounterpartsinthe3Dview.Forexample,the2D
circleshapebecomesasphereinthe3Dview.
Shapename 3Dshape
default 3Dturtleshape
circle sphere
dot smallsphere
square cube
triangle cone
line 3Dline
cylinder 3Dcylinder
line-half 3Dline-half
car 3Dcar
Allothershapesarebasedontheir2Dforms.Ifashapeisarotatableshape,itisassumedtobeatop
viewanditisextrudedasifthroughacookiecutterandorientedparalleltothexy-plane,asinAnts.
Or,ifashapeisnon-rotatable,itisassumedtobeasideview,anditisdrawnalwaysfacingthe
observer,asinWolfSheepPredation.
CommandCenter
TheCommandCenterallowsyoutoissuecommandsdirectly,withoutaddingthemtothemodel’s
procedures.Thisisusefulforinspectingandmanipulatingagentsonthefly.
(Tutorial#2:CommandsisanintroductiontousingcommandsintheCommandCenter.)
Let’stakealookatthedesignoftheCommandCenter.
Thesmallerbox,belowthelargebox,iswhereyoutypeacommand.AftertypingitpresstheReturnor
Enterkeytorunit.
Totheleftofwhereyoutypeisapopupmenuthatinitiallysays“observer>”.Youcanchooseeither
observer,turtles,orpatches,tospecifywhichagentsrunthecommandyoutype.
Tip:aquickerwaytochangeagenttypesistousetheTabkey.
Reporters
IfyouenterareporterintotheCommandCenter,theshowcommandwillbeinsertedbeforeit
automatically.
Accessingpreviouscommands
Afteryoutypeacommand,itappearsinthelargescrollingboxabovethecommandline.Youcanuse
CopyontheEditmenuinthisareatocopycommandsandthenpastethemelsewhere,suchasthe
Codetab.
Youcanalsoaccesspreviouscommandsusingthehistorypopup,whichisthesmalldownwardpointing
triangletotherightofwhereyoutypecommands.Clickonthetriangleandamenuofpreviouslytyped
commandsappears,soyoucanpickonetouseagain.
Tip:aquickerwaytoaccesspreviouscommandsiswiththeupanddownarrowkeysonyourkeyboard.
Clearing
Toclearthelargescrollingareacontainingpreviouscommandsandoutput,click“clear”inthetopright
corner.
Toclearthehistorypopupmenu,choose“ClearHistory”onthatmenu.
Arranging
YoucanhideandshowthecommandcenterusingtheHideCommandCenterandShowCommand
CenteritemsontheToolsmenu.
Toresizethecommandcenter,dragthebarthatseparatesitfromthemodelinterface.Or,clickoneof
thelittlearrowsontherightendofthebartomakethecommandcentereitherverybigorhidden
altogether.
Toswitchbetweenaverticalcommandcenterandahorizontalone,clickthebuttonwiththedouble-
headedarrow,justtotheleftof“Clear”.
Plots
Whenthemousepointerisoverthewhiteareaofaplot,thexandycoordinatesofthemouselocation
appear.(Notethatthemouselocationmightnotcorrespondexactlytoanyactualdatapointsintheplot.
Ifyouneedtoknowtheexactcoordinatesofplottedpoints,usetheExportPlotmenuitemandinspect
theresultingfileinanotherprogram.)
Whenyoucreateaplot,aswithallwidgets,theeditdialogautomaticallyappears.
Manyofthefieldsarefairlyself-explanatory,suchasthenameoftheplot,labelsforthexandyaxes,
rangesfortheaxes,andthe“Showlegend?”checkbox.
IfAutoScale?ischeckedthexandychangeswillautomaticallyreadjustaspointsareaddedtotheplot
iftheyareoutsidethecurrentrange.
Under“Plotsetupcommands”and“Plotupdatecommands”youcanentercommandsthatwill
automaticallyberunatappropriatetimes.Clickthelittletriangletoopenthetextboxforthecommands.
PlotcommandsareexplainedinmoredetailinthePlottingsectionoftheProgrammingGuide.
PlotPens
Intheplotpenssectionofthedialog,youcancreateandcustomizeyourplot’spens.Eachtablerow
representsapen.Bydefaultthereisonepennamed“default”.(Youmaywishtochangeittoaname
thathasmeaninginyourmodel.)
Toeditthecolorofapenclickthecoloredrectangletotheleftofthepen’sname.Thiswillbringupa
dialogthatallowsyoutosetthecolortooneoftheNetLogobasehuesoracustomcolorusingthecolor
swatches.
Toeditthepen’sname,doubleclickthename.
Inthe“PenUpdateCommands”columnyoucanentercommandsthatwillberunwhenreset-ticks,
tick,orupdate-plotscommandsarerun.ThisisexplainedinmoredetailinthePlottingsectionofthe
ProgrammingGuide.
Thelastcolumnhastwobuttons.Clickingthepenciliconwillbringupaneditdialogwithadditionalpen
settings.Thetrashcanbuttondeletesthepen.
PlotPenAdvancedSettings
Clickingapen’seditbuttonwillopenthisdialog:
Modeallowsyoutochangetheappearanceoftheplotpen:line,bar(forabarchart),orpoint(a
scatterplotofindividualpoints).
Intervalistheamountbywhichxadvanceseverytimeyouusetheplotcommand.
Ifthe“Showinlegend”checkboxischeckedtheselectedpenwillbeapartofthelegendinthe
upperrighthandcorneroftheplot.
Inthe“Setupcommands”fieldyoucanentercommandsthatwillberunwhenreset-ticksor
setup-plotsruns.
Inthe“Updatecommands”fieldyoucanentercommandsthatwillberunwhentickorupdate-
plotsruns.Thisfieldreappearsintheadvanceddialogtoprovidespaceforeditinglengthiersets
ofcommands.
FormoredetailedinformationonhoweachofthesefeaturesworksyoucanseethePlottingSectionof
theProgrammingGuide.
Sliders
Asliderhasanassociatedglobalvariable.Movingthesliderchangesthevariable’svalue.
WhenyouplaceasliderintheInterfacetabtheeditdialogautomaticallyopens,aswithallwidgets.Most
ofthefieldswillbefamiliar.However,itisimportanttonoticetheminimum,maximumandincrement
fieldswilltakeanyreporter,notjustconstants.So,forexample,youcouldmaketheminimummin-pxcor
andthemaximummax-pxcorandthesliderboundswillautomaticallyadjustwhenyouchangethesizeof
theworld.
AgentMonitors
Agentmonitorsdisplayboththevaluesofallthevariablesforaparticularagentandamini-viewthat
showstheagentandasmallareaaroundit.
YoucanopenagentmonitorsthroughtheToolsmenuortheinspectcommand.
Youcanzoominoroutusingthesliderbeneaththeviewandyoucanwatchtheagentinthemainview
usingthewatch-mebutton.
Belowthesliderthecurrentvalueofeachagentvariableisdisplayed.Youcanenteranewvalue.Itwill
beasif,forexample,thecodeset pcolor ...hadrun.
Belowtheagentvariableareathereisamini-commandcenter.Ratherthanrunningcodeasthe
observer,ortalkingtoalloftheturtles,patches,orlinks,thecodeenteredinthiscommandcenterisrun
onlybythisagent.
Youcancloseanagentmonitorbyclickingtheboxintheupperleftcorner,orbypressingtheEsckey.If
youholddownshiftwhileyouclicktheboxallopenagentmonitorswillcloseoryoucancloseallthe
agentmonitorsusingthe“CloseAllMonitors”optionintheToolsMenu.
InfoTab
NetLogo6.0.4UserManual
TheInfotabprovidesanintroductiontoamodel.Itexplainswhatsystemisbeingmodeled,how
themodelwascreated,andandhowtouseit.Itmayalsosuggestthingstoexploreandwaysto
extendthemodel,orcallyourattentiontoparticularNetLogofeaturesthemodeluses.
YoumaywishtoreadtheInfotabbeforestartingamodel.
Editing
Thenormal,formattedviewoftheInfotabisnoteditable.Tomakeedits,clickthe"Edit"button.
Whendoneediting,clickthe"Edit"buttonagain.
YouedittheInfotabasunformattedplaintext.Whenyou'redoneediting,theplaintextyou
enteredisdisplayedinamoreattractiveformat.
Tocontrolhowtheformatteddisplaylooks,youusea"markuplanguage"calledMarkdown.You
mayhaveencounteredMarkdownelsewhere;itisusedonanumberofwebsites.(Thereare
othermarkuplanguagesinuseontheweb;forexample,Wikipediausedamarkuplanguage
calledMediaWiki.Markuplanguagesdifferindetails.)
TheremainderofthisguideisatourofMarkdown.
Headings
Paragraphs
Italicizedandboldtext
Orderedlists
Unorderedlists
Links
Images
Blockquotations
Code
Codeblocks
Superscriptsandsubscripts
Notesonusage
Otherfeatures
Headings
Aheadingbeginswithoneormorehashmarks(#).Firstlevelheadingsgetonehash,second
levelheadingsgettwo,andsoonuptofourlevels.
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
Thisisaparagraph.Therearenospacesbeforetheword‘This’.
Thisisanotherparagraph.Thefirstlinehastwosentences.Theentireparagraphhastwolines
andthreesentences.
Linebreaksintheinput,Makelinebreaksintheoutput,Likethis.
Italicizedandboldtext
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
Foritalics,surroundtextwithunderscores:hello,world.
Forbold,surroundtextwithtwoasterisks:hello,world.
Youcanalsocombinethem:helloandgoodbye
Orderedlists
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
Weareabouttostartanorderedlist.
1. Orderedlistsareindented2spaces.
1. Subitemsareindented2morespaces(4inallforasecondlevelitem).
2. Thenextitemintheliststartswiththenextnumber.
3. Andsoon…
Unorderedlists
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
Weareabouttostartanunorderedlist.
Likeorderedlists,unorderedlistsarealsoindented2spaces.
Unlikeorderedlists,unorderedlistsusestarsinsteadofnumbers.
Subitemsareindented2morespaces.
Here’sanothersubitem.
Links
Automaticlinks
Thesimplestwaytocreatealinkistojusttypeitin:
Example
http://ccl.northwestern.edu/netlogo/
Formatted
http://ccl.northwestern.edu/netlogo/
Linkswithtext
Ifyouwanttouseyourowntextforthelink,here’show:
[link text here](link.address.here)
Example
[NetLogo](http://ccl.northwestern.edu/netlogo/)
Formatted
NetLogo
Locallinks
Itisalsopossibletolinktoapageonyourcomputer,insteadofapagesomewhereonthe
Internet.
Locallinkshavethisform:
[alt text](file:path)
Anyspacesinthepathmustbeconvertedto%20.Forexample,this:
file:my page.html
mustbewrittenas:
file:my%20page.html
Thepathisrelativetothedirectorythatthemodelfileisin.
Example
Theeasiestwaytolinktofilesonyourcomputeristoputthemintothesamedirectoryasyour
model.Assumingyouhaveafilenamedindex.htmlinthesamedirectoryasyourmodel,thelink
wouldlooklikethis:
[Home](file:index.html)
Example
Hereisanotherexamplewherethefilelivesinadirectorycalleddocs,anddocsisinthesame
directoryasyourmodel:
[Home](file:docs/index.html)
Images
Imagesareverysimilartolinks,buthaveanexclamationpointinfront:
![alt text](http://location/of/image)
(Thealternatetextisthetextthatgetsdisplayediftheimageisnotfound.)
Example
![NetLogo](http://ccl.northwestern.edu/netlogo/images/netlogo-title-new.jpg)
Formatted
Localimages
Alsoverysimilartolinks,itispossibletodisplayanimageonyourcomputerinsteadofanimage
somewhereontheInternet.Assumingyouhaveanimagenamedimage.jpg,localimageslook
likethis:
![alt text](file:path)
Thepathisrelativetothedirectorythatthemodelfileisin.
Aswithlocallinks,anyspacesinthenameofthefileorthepathmustbeconvertedto%20.
Example
Likelocallinks,theeasiestwaytodisplayimagesonyourcomputeristoputthemintothesame
directoryasyourmodel.Thisexampledisplaystheimage“PerspectiveExample.png”,which
residesinthesamedirectoryasthismodel(InfoTabExample).
![Example](file:Perspective%20Example.png)
Formatted
Blockquotations
Consecutivelinesstartingwith>willbecomeblockquotations.Youcanputwhatevertextyoulike
insideofitandyoucanalsostyleit.
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
Letmesee:fourtimesfiveistwelve,andfourtimessixisthirteen,andfourtimesseven
is—ohdear!Ishallnevergettotwentyatthatrate!
Code
Toincludeashortpieceofcodeinasentence,surrounditwithbackticks(`).
Example
You can create a single turtle with the `crt 1` command.
Formatted
Youcancreateasingleturtlewiththecrt 1command.
Codeblocks
Itisalsopossibletohaveblocksofcode.Tocreateacodeblock,indenteverylineoftheblockby
4spaces.Anotherwayistosurrounditwithathreebacktickslinebeforeandaftertheblock.(If
youdon’twantyourcodetobecoloredasNetLogocode,addtextafterthefirstthreebackticks.)
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
Abouttostartthecodeblock.Leaveablanklineafterthisone,andthenputthecodeblock:
; a typical go procedure
to go
ask turtles
[ fd 1 ]
tick
end
Superscriptsandsubscripts
Superscriptsandsubscriptsareusefulforwritingformulas,equations,footnotesandmore.
Subscriptsappearhalfacharacterbelowthebaseline,andarewrittenusingtheHTMLtag<sub>.
Superscriptsappearhalfacharacterabovethebaseline,andarewrittenusingtheHTMLtag
<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]
Notesonusage
Paragraphs,lists,codeblocksandotherfeaturesshouldbeseparatedfromeachotherwith
ablankline.Ifyoufindthatsomethingisn’tformattedthewayyouexpected,itmightbe
becauseyouneedtoaddablanklinebeforeit.
Topreventaspecialcharacterfrombeingtreatedasmarkup,putabackslash(\)beforeit.
WeuseGitHubflavorednewlines(https://github.github.com/github-flavored-markdown/)
insteadoftraditionalMarkdownhandlingofnewlines.Thismeansthatnewlinesaretreated
asreallinebreaks,insteadofbeingcombinedwiththepreviouslineintoasingleparagraph.
Otherfeatures
Markdownhasadditionalfeaturesthatwehavenotshownhere.
Wehavetestedthefeaturesshownaboveonavarietyofsystems.IfyouuseotherMarkdown
features,youmayfindthattheyworkonyourcomputer,ornot.Evenafeaturethatworksonyour
computermightworkdifferently,ornotworkatall,forsomeonewithadifferentoperatingsystem
orJavavirtualmachine.
IfyouwantallNetLogouserstobeabletoreadyourInfotab,useonlythefeaturesshownabove.
MoreinformationaboutMarkdownisathttps://daringfireball.net/projects/markdown/.For
renderingMarkdown,NetLogousestheFlexmark-javalibrary.
CodeTabGuide
NetLogo6.0.4UserManual
TheCodetabiswherethecodeforthemodelisstored.Commandsyouonlywanttouse
immediatelygointheCommandCenter;commandsyouwanttosaveanduselater,overand
overagain,arefoundintheCodetab.
CheckingforErrors
Todetermineifthecodehasanyerrors,youmaypressthe“Check”button.Ifthereareany
syntaxerrors,theCodetabwillturnred,thecodethatcontainstheerrorwillbehighlighted,
andanerrormessagewillappear.
Switchingtabsalsocausesthecodetobechecked,soifyoujustswitchtabs,pressingthe
Checkbuttonfirstisn’tnecessary.
Find&Replace
Tofindafragmentofcodeintheprocedures,clickonthe“Find”buttonintheCodetoolbar
andtheFinddialogwillappear.
Youmayenterawordorphrasetofind,andoptionallyalsoanewwordorphrasetoreplaceit
with.The“Ignorecase”checkboxcontrolswhetherthecapitalizationmustbethesameto
indicateamatch.
Ifthe“Wraparound”checkboxischecked,theentireCodetabwillbecheckedforthephrase,
startingatthecursorposition.Whenitreachestheenditwillreturntothetop,otherwiseonly
theareafromthecursorpositiontotheendoftheCodetabwillbesearched.The“Next”and
“Previous”buttonswillmovedownanduptofindanotheroccurrenceofthesearchphrase.
“Replace”changesthecurrentlyselectedphrasewiththereplacephraseand“Replace&
Find”changestheselectedphraseandmovestothenextoccurrence.“ReplaceAll”will
changeallinstancesofthefindphraseinthesearchareawiththereplacephrase.
AutomaticIndentation
WhentheIndentAutomaticallycheckboxisselected,NetLogowillautomaticallyattemptto
alignyourcodeinalogicallystructuredformat.Forexample,whenyouopenasetofsquare
brackets“[”(perhapsafteranifstatement),NetLogowillautomaticallyaddspacessothat
thefollowinglinesofcodearetwospacesfurtherindentedthanthebracket.Whenyouclose
thesquarebracketstheclosingbracketwillbelinedupwiththematchingopenbracket.
NetLogowilltrytoindentthecodeasyoutype,butyoucanalsopressthetabkeyanywhere
onanylinetoaskNetLogotoindentthelineimmediately.Or,youcanselectawholeregionof
codeandpressthetabkeytore-indentallofit.
MoreEditingOptions
Tofindaparticularproceduredefinitioninyourcode,usethe“Procedures”popupmenuinthe
Codetab.Themenulistsallproceduresintheordertheyappearinthefile.Tosearchfora
particularprocedure,usethesearchfieldatthetopofthepopup.Itwillfilterthelistof
proceduresusingfuzzymatchingasyoutype.Fuzzymatchwillincludeprocedureswhose
namescontainthecharactersthatyoutypeintheorderthattheyappearinthesearchfield,
butthecharactersdonothavetoberightnexttoeachother.Forinstance,“fnn”will
match"find-nearest-neighbors"and“wolf-down-neighbor”butnot“nearest-wolf-neighbor”.
Youmayusethearrowkeysormousetoselectaparticularprocedureandenterorclickto
jumptoit.Thiscanbeaveryconvenientwaytonavigateyourfile.Tofacilitatethis,youcan
usetheshortcutctrl-g(cmd+gonMacOS)toaccesstheproceduresmenu.
The“ShiftLeft”,“ShiftRight”,“Comment”,and“Uncomment”itemsontheEditmenuareused
intheCodetabtochangetheindentationlevelofyourcodeoraddandremovesemicolons,
whichmarkcomments,fromsectionsofcode.
Formoreinformationaboutwritingprocedures,readTutorial#3:Proceduresandthe
ProgrammingGuide.
IncludedFilesMenu
Caution:Theincludesfacilityisnewandexperimental.
Whenyouaddthe__includeskeywordtoamodelamenutotherightoftheproceduresmenu
appears.Thisisthe“IncludedFiles”menuwhichlistsalltheNetLogosourcefiles(.nls)
includedinthisfile.YoucanmakethismenualwaysvisibleusingthePreferencesdialog.
Youcanchooseafilenamefromthemenutoopenatabforthatfile,oryoucanopenanew
orexistingfileusingNewSourceFileandOpenSourceFile,respectively.
Onceyou’veopenednewtabstheybecomeaccessiblefromtheTabsmenu,andyoucanuse
thekeyboardtomovefromtabtotab(Command+numberonMac,Control+numberon
otheroperatingsystems).
ProgrammingGuide
NetLogo6.0.4UserManual
ThissectiondescribestheNetLogoprogramminglanguageindetail.
TheCodeExamplemodelsmentionedthroughoutcanbefoundintheCodeExamplessectionofthe
ModelsLibrary.
Agents
TheNetLogoworldismadeupofagents.Agentsarebeingsthatcanfollowinstructions.
InNetLogo,therearefourtypesofagents:turtles,patches,links,andtheobserver.
Turtlesareagentsthatmovearoundintheworld.Theworldistwodimensionalandisdividedupintoa
gridofpatches.Eachpatchisasquarepieceof“ground”overwhichturtlescanmove.Linksareagents
thatconnecttwoturtles.Theobserverdoesn’thavealocation–youcanimagineitaslookingoutover
theworldofturtlesandpatches.
Theobserverdoesn’tobservepassively–itgivesinstructionstotheotheragents.
WhenNetLogostartsup,therearenoturtles.Theobservercanmakenewturtles.Patchescanmake
newturtlestoo.(Patchescan’tmove,butotherwisethey’rejustas“alive”asturtles.)
Patcheshavecoordinates.Thepatchatcoordinates(0,0)iscalledtheoriginandthecoordinatesofthe
otherpatchesarethehorizontalandverticaldistancesfromthisone.Wecallthepatch’scoordinates
pxcorandpycor.Justlikeinthestandardmathematicalcoordinateplane,pxcorincreasesasyoumove
totherightandpycorincreasesasyoumoveup.
Thetotalnumberofpatchesisdeterminedbythesettingsmin-pxcor,max-pxcor,min-pycorandmax-
pycor.WhenNetLogostartsup,min-pxcor,max-pxcor,min-pycorandmax-pycorare-16,16,-16,and16
respectively.Thismeansthatpxcorandpycorbothrangefrom-16to16,sothereare33times33,or
1089patchestotal.(YoucanchangethenumberofpatcheswiththeSettingsbutton.)
Turtleshavecoordinatestoo:xcorandycor.Apatch’scoordinatesarealwaysintegers,butaturtle’s
coordinatescanhavedecimals.Thismeansthataturtlecanbepositionedatanypointwithinitspatch;it
doesn’thavetobeinthecenterofthepatch.
Linksdonothavecoordinates.Everylinkhastwoends,andeachendisaturtle.Ifeitherturtledies,the
linkdiestoo.Alinkisrepresentedvisuallyasalineconnectingthetwoturtles.
Procedures
InNetLogo,commandsandreporterstellagentswhattodo.Acommandisanactionforanagentto
carryout,resultinginsomeeffect.Areporterisinstructionsforcomputingavalue,whichtheagentthen
“reports”towhoeveraskedit.
Typically,acommandnamebeginswithaverb,suchas“create”,“die”,“jump”,“inspect”,or“clear”.Most
reporternamesarenounsornounphrases.
CommandsandreportersbuiltintoNetLogoarecalledprimitives.TheNetLogoDictionaryhasa
completelistofbuilt-incommandsandreporters.
Commandsandreportersyoudefineyourselfarecalledprocedures.Eachprocedurehasaname,
precededbythekeywordtoorto-report,dependingonwhetheritisacommandprocedureora
reporterprocedure.Thekeywordendmarkstheendofthecommandsintheprocedure.Onceyou
defineaprocedure,youcanuseitelsewhereinyourprogram.
Manycommandsandreporterstakeinputs–valuesthatthecommandorreporterusesincarryingout
itsactionsorcomputingitsresult.
Herearetwocommandprocedures:
to setup
clear-all
create-turtles 10
reset-ticks
end
to go
ask turtles [
fd 1 ;; forward 1 step
rt random 10 ;; turn right
lt random 10 ;; turn left
]
tick
end
Notetheuseofsemicolonstoadd“comments”totheprogram.Commentscanmakeyourcodeeasier
toreadandunderstand,buttheydon’taffectitsbehavior.
Inthisprogram,
setupandgoareuser-definedcommands.
clear-all,create-turtles,reset-ticks,ask,lt(“leftturn”),rt(“rightturn”)andtick,areall
primitivecommands.
randomandturtlesareprimitivereporters.randomtakesasinglenumberasaninputandreportsa
randomintegerthatislessthantheinput(inthiscase,between0and9).turtlesreportsthe
agentsetconsistingofalltheturtles.(We’llexplainaboutagentsetslater.)
setupandgocanbecalledbyotherprocedures,orbybuttons,orfromtheCommandCenter.
ManyNetLogomodelshaveaoncebuttonthatcallsaprocedurecalledsetupandaforeverbuttonthat
callsaprocedurecalledgo.
InNetLogo,youmayspecifywhichagents–turtles,patches,orlinks–aretoruneachcommand.Ifyou
don’tspecify,thecodeisrunbytheobserver.Inthecodeabove,theobserverusesasktomaketheset
ofallturtlesrunthecommandsbetweenthesquarebrackets.
clear-allandcreate-turtlescanonlyberunbytheobserver.fd,ontheotherhand,canonlyberun
byturtles.Someothercommandsandreporters,suchassetandticks,canberunbydifferentagent
types.
Herearesomemoreadvancedfeaturesyoucantakeadvantageofwhendefiningyourownprocedures.
Procedureswithinputs
Procedurescantakeinputs,justlikemanyprimitivesdo.Tocreateaprocedurethatacceptsinputs,put
theirnamesinsquarebracketsaftertheprocedurename.Forexample:
to draw-polygon [num-sides len] ;; turtle procedure
pen-down
repeat num-sides [
fd len
rt 360 / num-sides
]
end
Elsewhereintheprogram,youmightusetheprocedurebyaskingtheturtlestoeachdrawanoctagon
withasidelengthequaltoitswhonumber:
ask turtles [ draw-polygon 8 who ]
Reporterprocedures
Justlikeyoucandefineyourowncommands,youcandefineyourownreporters.Youmustdotwo
specialthings.First,useto-reportinsteadoftotobeginyourprocedure.Then,inthebodyofthe
procedure,usereporttoreportthevalueyouwanttoreport.
to-report absolute-value [number]
ifelse number >= 0
[ report number ]
[ report (- number) ]
end
Variables
Agentvariables
Agentvariablesareplacestostorevalues(suchasnumbers)inanagent.Anagentvariablecanbea
globalvariable,aturtlevariable,apatchvariable,oralinkvariable.
Ifavariableisaglobalvariable,thereisonlyonevalueforthevariable,andeveryagentcanaccessit.
Youcanthinkofglobalvariablesasbelongingtotheobserver.
Turtle,patch,andlinkvariablesaredifferent.Eachturtlehasitsownvalueforeveryturtlevariable.The
samegoesforpatchesandlinks.
SomevariablesarebuiltintoNetLogo.Forexample,allturtlesandlinkshaveacolorvariable,andall
patcheshaveapcolorvariable.(Thepatchvariablebeginswith“p”soitdoesn’tgetconfusedwiththe
turtlevariable,sinceturtleshavedirectaccesstopatchvariables.)Ifyousetthevariable,theturtleor
patchchangescolor.(Seenextsectionfordetails.)
Otherbuilt-inturtlevariablesincludingxcor,ycor,andheading.Otherbuilt-inpatchvariablesinclude
pxcorandpycor.(Thereisacompletelisthere.)
Youcanalsodefineyourownvariables.Youcanmakeaglobalvariablebyaddingaswitch,slider,
chooser,orinputboxtoyourmodel,orbyusingtheglobalskeywordatthebeginningofyourcode,like
this:
globals [score]
Youcanalsodefinenewturtle,patchandlinkvariablesusingtheturtles-own,patches-ownandlinks-
ownkeywords,likethis:
turtles-own [energy speed]
patches-own [friction]
links-own [strength]
Thesevariablescanthenbeusedfreelyinyourmodel.Usethesetcommandtosetthem.(Anyvariable
youdon’tsethasastartingvalueofzero.)
Globalvariablescanbereadandsetatanytimebyanyagent.Aswell,aturtlecanreadandsetpatch
variablesofthepatchitisstandingon.Forexample,thiscode:
ask turtles [ set pcolor red ]
causeseveryturtletomakethepatchitisstandingonred.(Becausepatchvariablesaresharedby
turtlesinthisway,youcan’thaveaturtlevariableandapatchvariablewiththesamename.)
Inothersituationswhereyouwantanagenttoreadadifferentagent’svariable,youcanuseof.
Example:
show [color] of turtle 5
;; prints current color of turtle with who number 5
Youcanalsouseofwithamorecomplicatedexpressionthanjustavariablename,forexample:
show [xcor + ycor] of turtle 5
;; prints the sum of the x and y coordinates of
;; turtle with who number 5
Localvariables
Alocalvariableisdefinedandusedonlyinthecontextofaparticularprocedureorpartofaprocedure.
Tocreatealocalvariable,usetheletcommand.Ifyouuseletatthetopofaprocedure,thevariable
willexistthroughouttheprocedure.Ifyouuseitinsideasetofsquarebrackets,forexampleinsidean
“ask”,thenitwillexistonlyinsidethosebrackets.
to swap-colors [turtle1 turtle2]
let temp [color] of turtle1
ask turtle1 [ set color [color] of turtle2 ]
ask turtle2 [ set color temp ]
end
Tickcounter
InmanyNetLogomodels,timepassesindiscretesteps,called“ticks”.NetLogoincludesabuilt-intick
countersoyoucankeeptrackofhowmanytickshavepassed.
Thecurrentvalueofthetickcounterisshownabovetheview.(YoucanusetheSettingsbuttontohide
thetickcounter,orchangetheword“ticks”tosomethingelse.)
Incode,toretrievethecurrentvalueofthetickcounter,usetheticksreporter.Thetickcommand
advancesthetickcounterby1.Theclear-allcommandclearsthetickcounteralongwitheverything
else.
Whenthetickcounterisclear,it’sanerrortotrytoreadormodifyit.Usethereset-tickscommand
whenyourmodelisdonesettingup,tostartthetickcounter.
Ifyourmodelissettousetick-basedupdates,thenthetickcommandwillusuallyalsoupdatetheview.
Seethelatersection,ViewUpdates.
Whentotick
Usereset-ticksattheendofyoursetupprocedure.
Usetickattheendofyourgoprocedure.
to setup
clear-all
create-turtles 10
reset-ticks
end
to go
ask turtles [ fd 1 ]
tick
end
Fractionalticks
Inmostmodels,thetickcounterstartsat0andgoesup1atatime,fromintegertointeger.Butit’salso
possibleforthetickcountertotakeonin-betweenfloatingpointvalues.
Toadvancethetickcounterbyafractionalamount,usethetick-advancecommand.Thiscommand
takesanumericinputspecifyinghowfartoadvancethetickcounter.
Atypicaluseoffractionalticksistoapproximatecontinuousorcurvedmotion.See,forexample,the
GasLabmodelsintheModelsLibrary(underChemistry&Physics).Thesemodelscalculatetheexact
timeatwhichafutureeventistooccur,thenadvancethetickcountertoexactlythattime.
Colors
NetLogorepresentscolorsindifferentways.Acolorcanbenumberintherange0to140,withthe
exceptionof140itself.BelowisachartshowingtherangeofsuchcolorsyoucanuseinNetLogo.
Thechartshowsthat:
Someofthecolorshavenames.(Youcanusethesenamesinyourcode.)
Everynamedcolorexceptblackandwhitehasanumberendingin5.
Oneithersideofeachnamedcoloraredarkerandlightershadesofthecolor.
0ispureblack.9.9ispurewhite.
10,20,andsoonareallsodarktheyareverynearlyblack.
19.9,29.9andsoonareallsolighttheyareverynearlywhite.
CodeExample:ThecolorchartwasmadeinNetLogowiththeColorChartExamplemodel.
Ifyouuseanumberoutsidethe0to140range,NetLogowillrepeatedlyaddorsubtract140fromthe
numberuntilitisinthe0to140range.Forexample,25isorange,so165,305,445,andsoonare
orangetoo,andsoare-115,-255,-395,etc.Thiscalculationisdoneautomaticallywheneveryouset
theturtlevariablecolororthepatchvariablepcolor.Shouldyouneedtoperformthiscalculationin
someothercontext,usethewrap-colorprimitive.
Ifyouwantacolorthat’snotonthechart,moreexistbetweentheintegers.Forexample,26.5isashade
oforangehalfwaybetween26and27.Thisdoesn’tmeanyoucanmakeanycolorinNetLogo;the
NetLogocolorspaceisonlyasubsetofallpossiblecolors.Itcontainsonlyafixedsetofdiscretehues
(onehueperrowofthechart).Startingfromoneofthosehues,youcaneitherdecreaseitsbrightness
(darkenit)ordecreaseitssaturation(lightenit),butyoucannotdecreasebothbrightnessandsaturation.
Also,onlythefirstdigitafterthedecimalpointissignificant.Thus,colorvaluesareroundeddowntothe
next0.1,soforexample,there’snovisibledifferencebetween26.5and26.52or26.58.
Colorprimitives
Thereareafewprimitivesthatarehelpfulforworkingwithcolors.
Wehavealreadymentionedthewrap-colorprimitive.
Thescale-colorprimitiveisusefulforconvertingnumericdataintocolors.
shade-of?willtellyouiftwocolorsareboth“shades”ofthesamebasichue.Forexample,shade-of?
orange 27istrue,because27isalightershadeoforange.
CodeExample:Scale-colorExampledemonstratesthescale-colorreporter.
RGBandRGBAColors
NetLogoalsorepresentscolorsasRGB(red/green/blue)listsandRGBA(red/green/blue/alpha)lists.
WhenusingRGBcolorsthefullrangeofcolorsisavailabletoyou.RGBAcolorsallowallthecolorsthat
RGBallowsandyoucanalsovarythetransparencyofacolor.RGBandRGBAlistsaremadeupof
threeorfourintegers,respectively,between0and255ifanumberisoutsidethatrange255is
repeatedlysubtracteduntilitisintherange.YoucansetanycolorvariablesinNetLogo(colorforturtles
andlinksandpcolorforpatches)toanRGBlistandthatagentwillberenderedappropriately.Soyou
cansetthecolorofpatch00topureredusingthefollowingcode:
set pcolor [255 0 0]
Turtles,links,andlabelscanallcontainRGBAlistsastheircolorvariables,however,patchescannot
haveRGBApcolorsYoucansetthecolorofaturtletobeapproximatelyhalftransparentpureredwith
thefollowingcode:
set color [255 0 0 125]
YoucanconvertfromaNetLogocolortoRGBorHSB(hue/saturation/brightness)usingextract-hsb
andextract-rgb.YoucanusergbtogeneratergblistsandhsbtoconvertfromanHSBcolortoRGB.
SincemanycolorsaremissingfromtheNetLogocolorspace,approximate-hsbandapproximate-rgb
oftencan’tgiveyoutheexactcoloryouaskfor,buttheytrytocomeascloseaspossible.
Example:youcanchangeanyturtlefromit’sexistingNetLogocolortoahalftransparentversionofthat
colorusing:
set color lput 125 extract-rgb color
CodeExamples:HSBandRGBExample(letsyouexperimentwiththeHSBandRGBcolor
systems),TransparencyExample
ColorSwatchesdialog
TheColorSwatchesdialoghelpsyouexperimentwithandchoosecolors.OpenitbychoosingColor
SwatchesontheToolsMenu.
Whenyouclickonacolorswatch(oracolorbutton),thatcolorwillbeshownagainstothercolors.Inthe
bottomleft,thecodeforthecurrentlyselectedcolorisdisplayed(forexample,red + 2)soyoucancopy
andpasteitintoyourcode.Onthebottomrighttherearethreeincrementoptions,1,0.5,and0.1.
Thesenumbersindicatethedifferencebetweentwoadjacentswatches.Whentheincrementis1there
are10differentshadesineachrow;whentheincrementis0.1thereare100differentshadesineach
row.0.5isanintermediatesetting.
Ask
NetLogousestheaskcommandtogivecommandstoturtles,patches,andlinks.Allcodetoberunby
turtlesmustbelocatedinaturtle“context”.Youcanestablishaturtlecontextinanyofthreeways:
Inabutton,bychoosing“Turtles”fromthepopupmenu.Anycodeyouputinthebuttonwillberun
byallturtles.
IntheCommandCenter,bychoosing“Turtles”fromthepopupmenu.Anycommandsyouenter
willberunbyalltheturtles.
Byusingask turtles,hatch,orothercommandswhichestablishaturtlecontext.
Thesamegoesforpatches,links,andtheobserver,exceptthatyoucannotasktheobserver.Anycode
thatisnotinsideanyaskisbydefaultobservercode.
Here’sanexampleoftheuseofaskinaNetLogoprocedure:
to setup
clear-all
create-turtles 100 ;; create 100 turtles with random headings
ask turtles
[ set color red ;; turn them red
fd 50 ] ;; spread them around
ask patches
[ if pxcor > 0 ;; patches on the right side
[ set pcolor green ] ] ;; of the view turn green
reset-ticks
end
ThemodelsintheModelsLibraryarefullofotherexamples.AgoodplacetostartlookingisintheCode
Examplessection.
Usually,theobserverusesasktoaskallturtles,allpatchesoralllinkstoruncommands.Youcanalso
useasktohaveanindividualturtle,patchorlinkruncommands.Thereportersturtle,patch,linkand
patch-atareusefulforthistechnique.Forexample:
to setup
clear-all
crt 3 ;; make 3 turtles
ask turtle 0 ;; tell the first one...
[ fd 1 ] ;; ...to go forward
ask turtle 1 ;; tell the second one...
[ set color green ] ;; ...to become green
ask turtle 2 ;; tell the third one...
[ rt 90 ] ;; ...to turn right
ask patch 2 -2 ;; ask the patch at (2,-2)
[ set pcolor blue ] ;; ...to become blue
ask turtle 0 ;; ask the first turtle
[ ask patch-at 1 0 ;; ...to ask patch to the east
[ set pcolor red ] ] ;; ...to become red
ask turtle 0 ;; tell the first turtle...
[ create-link-with turtle 1 ] ;; ...make a link with the second
ask link 0 1 ;; tell the link between turtle 0 and 1
[ set color blue ] ;; ...to become blue
reset-ticks
end
Everyturtlecreatedhasawhonumber.Thefirstturtlecreatedisnumber0,thesecondturtlenumber1,
andsoforth.
Theturtleprimitivereportertakesawhonumberasaninput,andreportstheturtlewiththatwho
number.Thepatchprimitivereportertakesvaluesforpxcorandpycorandreportsthepatchwiththose
coordinates.Thelinkprimitivetakestwoinputs,thewhonumbersofthetwoturtlesitconnects.Andthe
patch-atprimitivereportertakesoffsets:distances,inthexandydirections,fromthefirstagent.Inthe
exampleabove,theturtlewithwhonumber0isaskedtogetthepatcheast(andnopatchesnorth)of
itself.
Youcanalsoselectasubsetofturtles,orasubsetofpatches,orasubsetoflinksandaskthemtodo
something.Thisinvolvesusingagentsets.Thenextsectionexplainsthemindetail.
Whenyouaskasetofagentstorunmorethanonecommand,eachagentmustfinishbeforethenext
agentstarts.Oneagentrunsallofthecommands,thenthenextagentrunsallofthem,andsoon.For
example,ifyouwrite:
ask turtles
[ fd 1
set color red ]
firstoneturtlemovesandturnsred,thenanotherturtlemovesandturnsred,andsoon.
Butifyouwriteitthisway:
ask turtles [ fd 1 ]
ask turtles [ set color red ]
firstalltheturtlesmove,thentheyallturnred.
Agentsets
Anagentsetisexactlywhatitsnameimplies,asetofagents.Anagentsetcancontaineitherturtles,
patchesorlinks,butnotmorethanonetypeatonce.
Anagentsetisnotinanyparticularorder.Infact,it’salwaysinarandomorder.Andeverytimeyouuse
it,theagentsetisinadifferentrandomorder.Thishelpsyoukeepyourmodelfromtreatingany
particularturtles,patchesorlinksdifferentlyfromanyothers(unlessyouwantthemtobe).Sincethe
orderisrandomeverytime,nooneagentalwaysgetstogofirst.
You’veseentheturtlesprimitive,whichreportstheagentsetofallturtles,thepatchesprimitive,which
reportstheagentsetofallpatchesandthelinksprimitivewhichreportstheagentsetofalllinks.
Butwhat’spowerfulabouttheagentsetconceptisthatyoucanconstructagentsetsthatcontainonly
someturtles,somepatchesorsomelinks.Forexample,alltheredturtles,orthepatcheswithpxcor
evenlydivisiblebyfive,ortheturtlesinthefirstquadrantthatareonagreenpatchorthelinks
connectedtoturtle0.Theseagentsetscanthenbeusedbyaskorbyvariousreportersthattake
agentsetsasinputs.
Onewayistouseturtles-hereorturtles-at,tomakeanagentsetcontainingonlytheturtlesonmy
patch,oronlytheturtlesonsomeotherpatchatsomexandyoffsets.There’salsoturtles-onsoyou
cangetthesetofturtlesstandingonagivenpatchorsetofpatches,orthesetofturtlesstandingon
thesamepatchasagiventurtleorsetofturtles.
Herearesomemoreexamplesofhowtomakeagentsets:
;; all other turtles:
other turtles
;; all other turtles on this patch:
other turtles-here
;; all red turtles:
turtles with [color = red]
;; all red turtles on my patch
turtles-here with [color = red]
;; patches on right side of view
patches with [pxcor > 0]
;; all turtles less than 3 patches away
turtles in-radius 3
;; the four patches to the east, north, west, and south
patches at-points [[1 0] [0 1] [-1 0] [0 -1]]
;; shorthand for those four patches
neighbors4
;; turtles in the first quadrant that are on a green patch
turtles with [(xcor > 0) and (ycor > 0)
and (pcolor = green)]
;; turtles standing on my neighboring four patches
turtles-on neighbors4
;; all the links connected to turtle 0
[my-links] of turtle 0
Notetheuseofothertoexcludethisagent.Thisiscommon.
Onceyouhavecreatedanagentset,herearesomesimplethingsyoucando:
Useasktomaketheagentsintheagentsetdosomething
Useany?toseeiftheagentsetisempty
Useall?toseeifeveryagentinanagentsetsatisfiesacondition.
Usecounttofindoutexactlyhowmanyagentsareintheset
Andherearesomemorecomplexthingsyoucando:
Pickarandomagentfromthesetusingone-of.Forexample,wecanmakearandomlychosen
turtleturngreen:
ask one-of turtles [ set color green ]
Ortellarandomlychosenpatchtosproutanewturtle:
ask one-of patches [ sprout 1 ]
Usethemax-one-oformin-one-ofreporterstofindoutwhichagentisthemostorleastalongsome
scale.Forexample,toremovetherichestturtle,youcouldsay
ask max-one-of turtles [sum assets] [ die ]
Makeahistogramoftheagentsetusingthehistogramcommand(incombinationwithof).
Useoftomakealistofvalues,oneforeachagentintheagentset.ThenuseoneofNetLogo’slist
primitivestodosomethingwiththelist.(Seethe“Lists”sectionbelow.)Forexample,tofindout
howrichturtlesareontheaverage,youcouldsay
show mean [sum assets] of turtles
Useturtle-set,patch-setandlink-setreporterstomakenewagentsetsbygatheringtogether
agentsfromavarietyofpossiblesources.
Useno-turtles,no-patchesandno-linksreporterstomakeemptyagentsets.
Checkwhethertwoagentsetsareequalusing=or!=.
Usemember?toseewhetheraparticularagentisamemberofanagentset.
Thisonlyscratchesthesurface.SeetheModelsLibraryformanymoreexamples,andconsultthe
NetLogoDictionaryformoreinformationaboutalloftheagentsetprimitives.
Moreexamplesofusingagentsetsareprovidedintheindividualentriesfortheseprimitivesinthe
NetLogoDictionary.
Specialagentsets
Theagentsetsturtlesandlinkshavespecialbehaviorbecausetheyalwaysholdthesetsofallturtles
andalllinks.Therefore,theseagentsetscangrow.
Thefollowinginteractionshowsthespecialbehavior.AssumetheCodetabhasglobals [g].Then:
observer> clear-all
observer> create-turtles 5
observer> set g turtles
observer> print count g
5
observer> create-turtles 5
observer> print count g
10
observer> set g turtle-set turtles
observer> print count g
10
observer> create-turtles 5
observer> print count g
10
observer> print count turtles
15
Theturtlesagentsetgrowswhennewturtlesareborn,butotheragentsetsdon’tgrow.IfIwriteturtle-
set turtles,Igetanew,normalagentsetcontainingjusttheturtlesthatcurrentlyexist.Newturtlesdon’t
joinwhenthey’reborn.
Breedagentsetsarespecialinthesamewayasturtlesandlinks.Breedsareintroducedand
explainedbelow.
Agentsetsandlists
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomordereverytime.Ifyou
needyouragentstodosomethinginafixedorder,youneedtomakealistoftheagentsinstead.See
theListssectionbelow.
CodeExample:AskOrderingExample
Breeds
NetLogoallowsyoutodefinedifferent“breeds”ofturtlesandbreedsoflinks.Onceyouhavedefined
breeds,youcangoonandmakethedifferentbreedsbehavedifferently.Forexample,youcouldhave
breedscalledsheepandwolves,andhavethewolvestrytoeatthesheeporyoucouldhavelinkbreeds
calledstreetsandsidewalkswherefoottrafficisroutedonsidewalksandcartrafficisroutedonstreets.
Youdefineturtlebreedsusingthebreedkeyword,atthetopoftheCodetab,beforeanyprocedures:
breed [wolves wolf]
breed [sheep a-sheep]
Youcanrefertoamemberofthebreedusingthesingularform,justliketheturtlereporter.When
printed,membersofthebreedwillbelabeledwiththesingularname.
Somecommandsandreportershavethepluralnameofthebreedinthem,suchascreate-<breeds>.
Othershavethesingularnameofthebreedinthem,suchas<breed>.
Theorderinwhichbreedsaredeclaredisalsotheorderinwhichtheyarelayeredintheview.So
breedsdefinedlaterwillappearontopofbreedsdefinedearlier;inthisexample,sheepwillbedrawn
overwolves.
Whenyoudefineabreedsuchassheep,anagentsetforthatbreedisautomaticallycreated,sothatallof
theagentsetcapabilitiesdescribedaboveareimmediatelyavailablewiththesheepagentset.
Thefollowingnewprimitivesarealsoautomaticallyavailableonceyoudefineabreed:create-sheep,
hatch-sheep,sprout-sheep,sheep-here,sheep-at,sheep-on,andis-a-sheep?.
Also,youcanusesheep-owntodefinenewturtlevariablesthatonlyturtlesofthegivenbreedhave.(It’s
allowedformorethanonebreedtoownthesamevariable.)
Aturtle’sbreedagentsetisstoredinthebreedturtlevariable.Soyoucantestaturtle’sbreed,likethis:
if breed = wolves [ ... ]
Notealsothatturtlescanchangebreeds.Awolfdoesn’thavetoremainawolfitswholelife.Let’s
changearandomwolfintoasheep:
ask one-of wolves [ set breed sheep ]
Theset-default-shapeprimitiveisusefulforassociatingcertainturtleshapeswithcertainbreeds.See
thesectiononshapesbelow.
Whonumbersareassignedirrespectiveofbreeds.Ifyoualreadyhaveafrog 0,thenthefirstmousewill
bemouse 1,notmouse 0,sincethewhonumber0isalreadytaken.
Hereisaquickexampleofusingbreeds:
breed [mice mouse]
breed [frogs frog]
mice-own [cheese]
to setup
clear-all
create-mice 50
[ set color white
set cheese random 10 ]
create-frogs 50
[ set color green ]
reset-ticks
end
CodeExample:BreedsandShapesExample
Linkbreeds
Linkbreedsareverysimilartoturtlebreeds,however,thereareafewdifferences.
Whenyoudeclarealinkbreedyoumustdeclarewhetheritisabreedofdirectedorundirectedlinksby
usingthedirected-link-breedandundirected-link-breedkeywords.
directed-link-breed [streets street]
undirected-link-breed [friendships friendship]
Onceyouhavecreatedabreededlinkyoucannotcreateunbreededlinksandviceversa.(Youcan,
however,havedirectedandundirectedlinksinthesameworld,justnotinthesamebreed)
Unlikewithturtlebreedsthesingularbreednameisrequiredforlinkbreeds,asmanyofthelink
commandsandreportsusethesingularname,suchas<link-breed>-neighbor?.
Thefollowingprimitivesarealsoautomaticallyavailableonceyoudefineadirectedlinkbreed:create-
street-fromcreate-streets-fromcreate-street-tocreate-streets-toin-street-neighbor?in-
street-neighborsin-street-frommy-in-streetsmy-out-streetsout-street-neighbor?out-street-
neighborsout-street-to
Andthefollowingareautomaticallyavailablewhenyoudefineanundirectedlinkbreed:create-
friendship-withcreate-friendships-withfriendship-neighbor?friendship-neighborsfriendship-
withmy-friendships
Multiplelinkbreedsmaydeclarethesame-ownvariable,butavariablemaynotbesharedbetweena
turtlebreedandalinkbreed.
Justaswithturtlebreedstheorderinwhichlinkbreedsaredeclareddefinestheorderinwhichthelinks
aredrawn,sothefriendshipswillalwaysbeontopofstreets(ifforsomereasonthesebreedswerein
thesamemodel).Youcanalsouse<link-breeds>-owntodeclarevariablesofeachlinkbreed
separately.
Youcanchangethebreedofalinkwithset breed.(However,youcannotchangeabreededlinktoan
unbreededone,topreventhavingbreededandunbreededlinksinthesameworld.)
ask one-of friendships [ set breed streets ]
ask one-of friendships [ set breed links ] ;; produces a runtime error
set-default-shapemayalsobeusedwithlinkbreedstoassociateitwithaparticularlinkshape.
CodeExample:LinkBreedsExample
Buttons
Buttonsintheinterfacetabprovideaneasywaytocontrolthemodel.Typicallyamodelwillhaveat
leasta“setup”button,tosetuptheinitialstateoftheworld,anda“go”buttontomakethemodelrun
continuously.Somemodelswillhaveadditionalbuttonsthatperformotheractions.
AbuttoncontainssomeNetLogocode.Thatcodeisrunwhenyoupressthebutton.
Abuttonmaybeeithera“oncebutton”,ora“foreverbutton”.Youcancontrolthisbyeditingthebutton
andcheckingoruncheckingthe“Forever”checkbox.Oncebuttonsruntheircodeonce,thenstopand
popbackup.Foreverbuttonskeeprunningtheircodeoverandoveragain.
Aforeverbuttonstopsiftheuserpressesthebuttonagaintostopit.Thebuttonwaitsuntilthecurrent
iterationhasfinished,thenpopsup.
Aforeverbuttoncanalsobestoppedfromcode.Iftheforeverbuttondirectlycallsaprocedure,then
whenthatprocedurestops,thebuttonstops.(Inaturtleorpatchforeverbutton,thebuttonwon’tstop
untileveryturtleorpatchstops–asingleturtleorpatchdoesn’thavethepowertostopthewhole
button.)
Normally,abuttonislabeledwiththecodethatitruns.Forexample,abuttonthatsays“go”onitusually
containsthecode“go”,whichmeans“runthegoprocedure”.(ProceduresaredefinedintheCodetab;
seebelow.)Butyoucanalsoeditabuttonandentera“displayname”forthebutton,whichisatextthat
appearsonthebuttoninsteadofthecode.Youmightusethisfeatureifyouthinktheactualcodewould
beconfusingtoyourusers.
Whenyouputcodeinabutton,youmustalsospecifywhichagentsyouwanttorunthatcode.Youcan
choosetohavetheobserverrunthecode,orallturtles,orallpatches,oralllinks.(Ifyouwantthecode
toberunbyonlysometurtlesorsomepatches,youcouldmakeanobserverbutton,andthenhavethe
observerusetheaskcommandtoaskonlysomeoftheturtlesorpatchestodosomething.)
Whenyoueditabutton,youhavetheoptiontoassignan“actionkey”.Thismakesthatkeyonthe
keyboardbehavejustlikeabuttonpress.Ifthebuttonisaforeverbutton,itwillstaydownuntilthekeyis
pressedagain(orthebuttonisclicked).Actionkeysareparticularlyusefulforgamesoranymodel
whererapidtriggeringofbuttonsisneeded.
Buttonstaketurns
Morethanonebuttoncanbepressedatatime.Ifthishappens,thebuttons“taketurns”,whichmeans
thatonlyonebuttonrunsatatime.Eachbuttonrunsitscodeallthewaythroughoncewhiletheother
buttonswait,thenthenextbuttongetsitsturn.
Inthefollowingexamples,“setup”isaoncebuttonand“go”isaforeverbutton.
Example#1:Theuserpresses“setup”,thenpresses“go”immediately,beforethe“setup”haspopped
backup.Result:“setup”finishesbefore“go”starts.
Example#2:Whilethe“go”buttonisdown,theuserpresses“setup”.Result:the“go”buttonfinishesits
currentiteration.Thenthe“setup”buttonruns.Then“go”startsrunningagain.
Example#3:Theuserhastwoforeverbuttonsdownatthesametime.Result:firstonebuttonrunsits
codeallthewaythrough,thentheotherrunsitscodeallthewaythrough,andsoon,alternating.
Notethatifonebuttongetsstuckinaninfiniteloop,thennootherbuttonswillrun.
Turtle,patch,andlinkforeverbuttons
Thereisasubtledifferencebetweenputtingcommandsinaturtle,patchorlinkforeverbutton,and
puttingthesamecommandsinanobserverbuttonthatdoesask turtles,ask patchesorask links.An
“ask”doesn’tcompleteuntilalloftheagentshavefinishedrunningallofthecommandsinthe“ask”.So
theagents,astheyallrunthecommandsconcurrently,canbeoutofsyncwitheachother,buttheyall
syncupagainattheendoftheask.Thesameisn’ttrueofturtle,patchandlinkforeverbuttons.Since
askwasnotused,eachturtleorpatchrunsthegivencodeoverandoveragain,sotheycanbecome
(andremain)outofsyncwitheachother.
Atpresent,thiscapabilityisveryrarelyusedinthemodelsinourModelsLibrary.Amodelthatdoesuse
thecapabilityistheTermitesmodel,intheBiologysectionofSampleModels.The“go”buttonisaturtle
foreverbutton,soeachtermiteproceedsindependentlyofeveryothertermite,andtheobserverisnot
involvedatall.Thismeansthatif,forexample,youwantedtoaddticksand/oraplottothemodel,you
wouldneedtoaddasecondforeverbutton(anobserverforeverbutton),andrunbothforeverbuttonsat
thesametime.NotealsothatamodellikethiscannotbeusedwithBehaviorSpace.
CodeExample:StateMachineExampleshowshowTermitescanberecodedinatick-based
way,withoutusingaturtleforeverbutton.
Atpresent,NetLogohasnowayforoneforeverbuttontostartanother.Buttonsareonlystartedwhen
youpressthem.
Lists
Inthesimplestmodels,eachvariableholdsonlyonepieceofinformation,usuallyanumberorastring.
Listsletyoustoremultiplepiecesofinformationinasinglevaluebycollectingthatinformationinalist.
Eachvalueinthelistcanbeanytypeofvalue:anumber,orastring,anagentoragentset,oreven
anotherlist.
ListsallowfortheconvenientpackagingofinformationinNetLogo.Ifyouragentscarryoutarepetitive
calculationonmultiplevariables,itmightbeeasiertohavealistvariable,insteadofmultiplenumber
variables.Severalprimitivessimplifytheprocessofperformingthesamecomputationoneachvaluein
alist.
TheNetLogoDictionaryhasasectionthatlistsallofthelist-relatedprimitives.
Constantlists
Youcanmakealistbysimplyputtingthevaluesyouwantinthelistbetweenbrackets,likethis:set
mylist [2 4 6 8].Notethattheindividualvaluesareseparatedbyspaces.Youcanmakeliststhat
containnumbersandstringsthisway,aswellaslistswithinlists,forexample[[2 4] [3 5]].
Theemptylistiswrittenbyputtingnothingbetweenthebrackets,likethis:[].
Buildinglistsonthefly
Ifyouwanttomakealistinwhichthevaluesaredeterminedbyreporters,asopposedtobeingaseries
ofconstants,usethelistreporter.Thelistreporteracceptstwootherreporters,runsthem,and
reportstheresultsasalist.
IfIwantedalisttocontaintworandomvalues,Imightusethefollowingcode:
set random-list list (random 10) (random 20)
Thiswillsetrandom-listtoanewlistoftworandomintegerseachtimeitruns.
Tomakelongerorshorterlists,youcanusethelistreporterwithfewerormorethantwoinputs,butin
ordertodoso,youmustenclosetheentirecallinparentheses,e.g.:
(list random 10)
(list random 10 random 20 random 30)
Formoreinformation,seeVaryingnumberofinputs.
Somekindsoflistsaremosteasilybuiltusingthen-valuesreporter,whichallowsyoutoconstructalist
ofaspecificlengthbyrepeatedlyrunningagivenreporter.Youcanmakealistofthesamevalue
repeated,orallthenumbersinarange,oralotofrandomnumbers,ormanyotherpossibilities.See
dictionaryentryfordetailsandexamples.
Theofprimitiveletsyouconstructalistfromanagentset.Itreportsalistcontainingeachagent’svalue
forthegivenreporter.(Thereportercouldbeasimplevariablename,oramorecomplexexpression–
evenacalltoaproceduredefinedusingto-report.)Acommonidiomis
max [...] of turtles
sum [...] of turtles
andsoon.
Youcancombinetwoormorelistsusingthesentencereporter,whichconcatenateslistsbycombining
theircontentsintoasingle,largerlist.Likelist,sentencenormallytakestwoinputs,butcanacceptany
numberofinputsifthecallissurroundedbyparentheses.
Changinglistitems
Technically,listscan’tbemodified,butyoucanconstructnewlistsbasedonoldlists.Ifyouwantthe
newlisttoreplacetheoldlist,useset.Forexample:
set mylist [2 7 5 Bob [3 0 -2]]
; mylist is now [2 7 5 Bob [3 0 -2]]
set mylist replace-item 2 mylist 10
; mylist is now [2 7 10 Bob [3 0 -2]]
Thereplace-itemreportertakesthreeinputs.Thefirstinputspecifieswhichiteminthelististobe
changed.0meansthefirstitem,1meanstheseconditem,andsoforth.
Toaddanitem,say42,totheendofalist,usethelputreporter.(fputaddsanitemtothebeginningof
alist.)
set mylist lput 42 mylist
; mylist is now [2 7 10 Bob [3 0 -2] 42]
Butwhatifyouchangedyourmind?Thebut-last(blforshort)reporterreportsallthelistitemsbutthe
last.
set mylist but-last mylist
; mylist is now [2 7 10 Bob [3 0 -2]]
Supposeyouwanttogetridofitem0,the2atthebeginningofthelist.
set mylist but-first mylist
; mylist is now [7 10 Bob [3 0 -2]]
Supposeyouwantedtochangethethirditemthat’snestedinsideitem3from-2to9?Thekeyisto
realizethatthenamethatcanbeusedtocallthenestedlist[30-2]isitem 3 mylist.Thenthereplace-
itemreportercanbenestedtochangethelist-within-a-list.Theparenthesesareaddedforclarity.
set mylist (replace-item 3 mylist
(replace-item 2 (item 3 mylist) 9))
; mylist is now [7 10 Bob [3 0 9]]
Iteratingoverlists
Ifyouwanttodosomeoperationoneachiteminalistinturn,theforeachcommandandthemap
reportermaybehelpful.
foreachisusedtorunacommandorcommandsoneachiteminalist.Ittakesaninputlistanda
commandnameorblockofcommands,likethis:
foreach [1 2 3] show
=> 1
=> 2
=> 3
foreach [2 4 6]
[ n -> crt n
show (word "created " n " turtles") ]
=> created 2 turtles
=> created 4 turtles
=> created 6 turtles
Intheblock,thevariablenholdsthecurrentvaluefromtheinputlist.
Herearesomemoreexamplesofforeach:
foreach [1 2 3] [ steps -> ask turtles [ fd steps ] ]
;; turtles move forward 6 patches
foreach [true false true true] [ should-move? -> ask turtles [ if should-move? [ fd 1 ] ] ]
;; turtles move forward 3 patches
mapissimilartoforeach,butitisareporter.Ittakesaninputlistandareporternameorreporterblock.
Notethatunlikeforeach,thereportercomesfirst,likethis:
show map round [1.2 2.2 2.7]
;; prints [1 2 3]
mapreportsalistcontainingtheresultsofapplyingthereportertoeachitemintheinputlist.Again,use
thevariablenamedintheanonymousprocedure(xintheexamplesbelow)torefertothecurrentitemin
thelist.
Hereareacouplemoreexamplesofmap:
show map [ x -> x < 0 ] [1 -1 3 4 -2 -10]
;; prints [false true false false true true]
show map [ x -> x * x ] [1 2 3]
;; prints [1 4 9]
Besidesmapandforeach,otherprimitivesforprocessingwholelistsinaconfigurablewayinclude
filter,reduce,andsort-by.
Theseprimitivesaren’talwaysthesolutionforeverysituationinwhichyouwanttooperateonanentire
list.Insomesituations,youmayneedtousesomeothertechniquesuchasaloopusingrepeator
while,orarecursiveprocedure.
Theblocksofcodewe’regivingtomapandforeachintheseexamplesareactuallyanonymous
procedures.AnonymousproceduresareexplainedinmoredetailinAnonymousprocedures,below.
Varyingnumberofinputs
Somecommandsandreportersinvolvinglistsandstringsmaytakeavaryingnumberofinputs.Inthese
cases,inordertopassthemanumberofinputsotherthantheirdefault,theprimitiveanditsinputsmust
besurroundedbyparentheses.Herearesomeexamples:
show list 1 2
=> [1 2]
show (list 1 2 3 4)
=> [1 2 3 4]
show (list)
=> []
Notethateachofthesespecialprimitiveshasadefaultnumberofinputsforwhichnoparenthesesare
required.Theprimitiveswhichhavethiscapabilityarelist,word,sentence,map,foreach,run,and
runresult.
Listsofagents
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomordereverytime.Ifyou
needyouragentstodosomethinginafixedorder,youneedtomakealistoftheagentsinstead.
Therearetwoprimitivesthathelpyoudothis,sortandsort-by.
Bothsortandsort-bycantakeanagentsetasinput.Theresultisalwaysanewlist,containingthe
sameagentsastheagentsetdid,butinaparticularorder.
Ifyouusesortonanagentsetofturtles,theresultisalistofturtlessortedinascendingorderbywho
number.
Ifyouusesortonanagentsetofpatches,theresultisalistofpatchessortedleft-to-right,top-to-bottom.
Ifyouusesortonanagentsetoflinks,theresultisalistoflinks,sortedinascendingorderfirstbyend1
thenbyend2anyremainingtiesareresolvedbybreedintheordertheyaredeclaredintheCodetab.
Ifyouneeddescendingorderinstead,youcancombinereversewithsort,forexamplereverse sort
turtles.
Ifyouwantyouragentstobeorderedbysomeothercriterionthanthestandardonessortuses,you’ll
needtousesort-byinstead.
Here’sanexample:
sort-by [ [a b] -> [size] of a < [size] of b ] turtles
Thisreturnsalistofturtlessortedinascendingorderbytheirturtlevariablesize.
There’sacommonpatterntogetalistofagentsinarandomorder,usingacombinationofofandself,
intherarecasethatyoucannotjustuseask:
[self] of my-agentset
Askingalistofagents
Onceyouhavealistofagents,youmightwanttoaskthemeachtodosomething.Todothis,usethe
foreachandaskcommandsincombination,likethis:
foreach sort turtles [ the-turtle ->
ask the-turtle [
...
]
]
Thiswillaskeachturtleinascendingorderbywhonumber.Substitute“patches”for“turtles”toask
patchesinleft-to-right,top-to-bottomorder.
Notethatyoucan’tuseaskdirectlyonalistofturtles.askonlyworkswithagentsetsandsingleagents.
Performanceoflists
ThedatastructureunderlyingNetLogo’slistsisasophisticatedtree-baseddatastructureonwhichmost
operationsruninnear-constanttime.Thatincludesfput,lput,butfirst,butlast,length,item,and
replace-item.
Oneexceptiontothefast-performanceruleisthatconcatenatingtwolistswithsentencerequires
traversingandcopyingthewholesecondlist.(Thismaybefixedinafutureversion.)
Technically,“near-constanttime”isactuallylogarithmictime,proportionaltothedepthoftheunderlying
tree,butthesetreeshavelargenodesandahighbranchingfactor,sotheyarenevermorethanafew
levelsdeep.Thismeansthatchangescanbemadeinatmostafewsteps.Thetreesareimmutable,but
theysharestructurewitheachother,sothewholetreedoesn’tneedtobecopiedtomakeachanged
version.
TheactualdatastructureusedistheimmutableVectorclassfromtheScalacollectionslibrary.These
are32-widehasharraymappedtries,asimplementedbyTiarkRompf,basedinpartonworkbyPhil
BagwellandRichHickey.
Math
AllnumbersinNetLogoarestoredinternallyasdoubleprecisionfloatingpointnumbers,asdefinedin
theIEEE754standard.Theyare64bitnumbersconsistingofonesignbit,an11-bitexponent,anda
52-bitmantissa.SeetheIEEE754standardfordetails.
An“integer”inNetLogoissimplyanumberthathappenstohavenofractionalpart.Nodistinctionis
madebetween3and3.0;theyarethesamenumber.(Thisisthesameashowmostpeopleuse
numbersineverydaycontexts,butdifferentfromsomeprogramminglanguages.Somelanguagestreat
integersandfloatingpointnumbersasdistincttypes.)
IntegersarealwaysprintedbyNetLogowithoutthetrailing“.0”:
show 1.5 + 1.5
observer: 3
Ifanumberwithafractionalpartissuppliedinacontextwhereanintegerisexpected,thefractionalpart
issimplydiscarded.Soforexample,crt 3.5createsthreeturtles;theextra0.5isignored.
Therangeofintegersis+/-9007199254740992(2^53,about9quadrillion).Calculationsthatexceedthis
rangewillnotcauseruntimeerrors,butprecisionwillbelostwhentheleastsignificant(binary)digitsare
roundedoffinorderfitthenumberinto64bits.Withverylargenumbers,thisroundingcanresultin
impreciseanswerswhichmaybesurprising:
show 2 ^ 60 + 1 = 2 ^ 60
=> true
Calculationswithsmallernumberscanalsoproducesurprisingresultsiftheyinvolvefractional
quantities,sincenotallfractionscanbepreciselyrepresentedandroundoffmayoccur.Forexample:
show 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6
=> 0.9999999999999999
show 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9
=> 1.0000000000000002
Anyoperationwhichproducesthespecialquantities“infinity”or“notanumber”willcausearuntime
error.
Scientificnotation
VerylargeorverysmallfloatingpointnumbersaredisplayedbyNetLogousing“scientificnotation”.
Examples:
show 0.000000000001
=> 1.0E-12
show 50000000000000000000
=> 5.0E19
NumbersinscientificnotationaredistinguishedbythepresenceoftheletterE(for“exponent”).Itmeans
“timestentothepowerof”,soforexample,1.0E-12means1.0times10tothe-12power:
show 1.0 * 10 ^ -12
=> 1.0E-12
YoucanalsousescientificnotationyourselfinNetLogocode:
show 3.0E6
=> 3000000
show 8.123456789E6
=> 8123456.789
show 8.123456789E7
=> 8.123456789E7
show 3.0E16
=> 3.0E16
show 8.0E-3
=> 0.0080
show 8.0E-4
=> 8.0E-4
Theseexamplesshowthatnumberswithfractionalpartsaredisplayedusingscientificnotationifthe
exponentislessthan-3orgreaterthan6.NumbersoutsideofNetLogo’sintegerrangeof-
9007199254740992to9007199254740992(+/-2^53)arealsoalwaysshowninscientificnotation:
show 2 ^ 60
=> 1.15292150460684698E18
Whenenteringanumber,theletterEmaybeeitherupperorlowercase.Whenprintinganumber,
NetLogoalwaysusesanuppercaseE:
show 4.5e20
=> 4.5E20
Floatingpointaccuracy
BecausenumbersinNetLogoaresubjecttothelimitationsofhowfloatingpointnumbersare
representedinbinary,youmaygetanswersthatareslightlyinaccurate.Forexample:
show 0.1 + 0.1 + 0.1
=> 0.30000000000000004
show cos 90
=> 6.123233995736766E-17
Thisisaninherentissuewithfloatingpointarithmetic;itoccursinallprogramminglanguagesthatuse
floatingpointnumbers.
Ifyouaredealingwithfixedprecisionquantities,forexampledollarsandcents,acommontechniqueis
touseonlyintegers(cents)internally,thendivideby100togetaresultindollarsfordisplay.
Ifyoumustusefloatingpointnumbers,theninsomesituationsyoumayneedtoreplacea
straightforwardequalitytestsuchasif x = 1 [ ... ] withatestthattoleratesslightimprecision,for
exampleif abs (x - 1) < 0.0001 [ ... ] .
Also,theprecisionprimitiveishandyforroundingoffnumbersfordisplaypurposes.NetLogomonitors
roundthenumberstheydisplaytoaconfigurablenumberofdecimalplaces,too.
Randomnumbers
TherandomnumbersusedbyNetLogoarewhatiscalled“pseudo-random”.(Thisistypicalincomputer
programming.)Thatmeanstheyappearrandom,butareinfactgeneratedbyadeterministicprocess.
“Deterministic”meansthatyougetthesameresultseverytime,ifyoustartwiththesamerandom
“seed”.We’llexplaininaminutewhatwemeanby“seed”.
Inthecontextofscientificmodeling,pseudo-randomnumbersareactuallydesirable.That’sbecauseit’s
importantthatascientificexperimentbereproducible–soanyonecantryitthemselvesandgetthe
sameresultthatyougot.SinceNetLogousespseudo-randomnumbers,the“experiments”thatyoudo
withitcanbereproducedbyothers.
Here’showitworks.NetLogo’srandomnumbergeneratorcanbestartedwithacertainseedvalue,
whichmustbeanintegerintherange-2147483648to2147483647.Oncethegeneratorhasbeen
“seeded”withtherandom-seedcommand,italwaysgeneratesthesamesequenceofrandomnumbers
fromthenon.Forexample,ifyourunthesecommands:
random-seed 137
show random 100
show random 100
show random 100
Youwillalwaysgetthenumbers79,89,and61inthatorder.
Note,however,thatyou’reonlyguaranteedtogetthosesamenumbersifyou’reusingthesameversion
ofNetLogo.SometimeswhenwemakeanewversionofNetLogotherandomnumbergenerator
changes.(Presently,weuseageneratorknownastheMersenneTwister.)
Tocreateanumbersuitableforseedingtherandomnumbergenerator,usethenew-seedreporter.new-
seedcreatesaseed,evenlydistributedoverthespaceofpossibleseeds,basedonthecurrentdateand
time.Itneverreportsthesameseedtwiceinarow.
CodeExample:RandomSeedExample
Ifyoudon’tsettherandomseedyourself,NetLogosetsittoavaluebasedonthecurrentdateandtime.
Thereisnowaytofindoutwhatrandomseeditchose,soifyouwantyourmodelruntobereproducible,
youmustsettherandomseedyourselfaheadoftime.
TheNetLogoprimitiveswith“random”intheirnames(random,random-float,andsoon)aren’ttheonly
onesthatusepseudo-randomnumbers.Manyotheroperationsalsomakerandomchoices.For
example,agentsetsarealwaysinrandomorder,one-ofandn-ofchooseagentsrandomly,thesprout
commandcreatesturtleswithrandomcolorsandheadings,andthedownhillreporterchoosesa
randompatchwhenthere’satie.Alloftheserandomchoicesaregovernedbytherandomseedaswell,
somodelrunscanbereproducible.
Inadditiontotheuniformlydistributedrandomintegersandfloatingpointnumbersgeneratedbyrandom
andrandom-float,NetLogoalsooffersseveralotherrandomdistributions.Seethedictionaryentriesfor
random-normal,random-poisson,random-exponential,andrandom-gamma.
Auxiliarygenerator
Coderunbybuttonsorfromthecommandcenterusesthemainrandomnumbergenerator.
Codeinmonitorsusesanauxiliaryrandomgenerator,soevenifamonitordoesacalculationthatuses
randomnumbers,theoutcomeofthemodelisnotaffected.Thesameistrueofcodeinsliders.
Localrandomness
Youmaywanttoexplicitlyspecifythatasectionofcodedoesnotaffectthestateofthemainrandom
generator,sotheoutcomeofthemodelisnotaffected.Thewith-local-randomnesscommandis
providedforthispurpose.SeeitsentryintheNetLogoDictionaryformoreinformation.
Turtleshapes
InNetLogo,turtleshapesarevectorshapes.Theyarebuiltupfrombasicgeometricshapes;squares,
circles,andlines,ratherthanagridofpixels.Vectorshapesarefullyscalableandrotatable.NetLogo
cachesbitmapimagesofvectorshapessize1,1.5,and2inordertospeedupexecution.
Aturtle’sshapeisstoredinitsshapevariableandcanbesetusingthesetcommand.
Newturtleshaveashapeof“default”.Theset-default-shapeprimitiveisusefulforchangingthedefault
turtleshapetoadifferentshape,orhavingadifferentdefaultturtleshapeforeachbreedofturtle.
Theshapesprimitivereportsalistofcurrentlyavailableturtleshapesinthemodel.Thisisusefulif,for
example,youwanttoassignarandomshapetoaturtle:
ask turtles [ set shape one-of shapes ]
UsetheTurtleShapesEditortocreateyourownturtleshapes,ortoaddshapestoyourmodelfromour
shapeslibrary,ortotransfershapesbetweenmodels.Formoreinformation,seetheShapesEditor
sectionofthismanual.
Thethicknessofthelinesusedtodrawthevectorshapescanbecontrolledbythe__set-line-
thicknessprimitive.
CodeExamples:BreedsandShapesExample,ShapeAnimationExample
Linkshapes
LinkShapesaresimilartoturtleshapes,onlyyouusetheLinkShapeEditortocreateandeditthem.
Linkshapesconsistofbetween0and3lineswhichcanhavedifferentpatternsandadirectionindicator
thatiscomposedofthesameelementsasturtleshapes.Linksalsohaveashapevariablethatcanbe
settoanylinkshapethatisinthemodel.Bydefaultlinkshavethe“default”shape,thoughyoucan
changethatusingset-default-shape.Thelink-shapesreporterreportsallthelinkshapesincludedin
thecurrentmodel.
Thethicknessofthelinesinthelinkshapeiscontrolledbythethicknesslinkvariable.
Viewupdates
The“view”inNetLogoletsyouseetheagentsinyourmodelonyourcomputer’sscreen.Asyouragents
moveandchange,youseethemmovingandchangingintheview.
Ofcourse,youcan’treallyseeyouragentsdirectly.TheviewisapicturethatNetLogopaints,showing
youhowyouragentslookataparticularinstant.Oncethatinstantpassesandyouragentsmoveand
changesomemore,thatpictureneedstoberepaintedtoreflectthenewstateoftheworld.Repainting
thepictureiscalled“updating”theview.
Whendoestheviewgetupdated?ThissectiondiscusseshowNetLogodecideswhentoupdatethe
view,andhowyoucaninfluencewhenitgetsupdated.
NetLogoofferstwoupdatesmodes,“continuous”updatesand“tick-based”updates.Youcanswitch
betweenNetLogo’stwoviewupdatemodesusingapopupmenuatthetopoftheInterfacetab.
ContinuousupdatesarethedefaultwhenyoustartupNetLogoorstartanewmodel.Nearlyevery
modelinourModelsLibrary,however,usestick-basedupdates.
Continuousupdatesaresimplest,buttick-basedupdatesgiveyoumorecontroloverwhenandhow
oftenupdateshappen.
It’simportantexactlywhenanupdatehappens,becausewhenupdateshappendetermineswhatyou
seeonthescreen.Ifanupdatecomesatanunexpectedtime,youmayseesomethingunexpected–
perhapssomethingconfusingormisleading.
It’salsoimportanthowoftenupdateshappen,becauseupdatestaketime.ThemoretimeNetLogo
spendsupdatingtheview,thesloweryourmodelwillrun.Withfewerupdates,yourmodelrunsfaster.
Continuousupdates
Continuousupdatesareverysimple.Withcontinuousupdates,NetLogoupdatestheviewacertain
numberoftimespersecond–bydefault,30timesasecondwhenthespeedsliderisinthedefault,
middlesetting.
Ifyoumovethespeedslidertoaslowersetting,NetLogowillupdatemorethan30timesasecond,
effectivelyslowingdownthemodel.Onafastersetting,NetLogowillupdatelessthan30timesa
second.Onthefastestsetting,updateswillbeseparatedbyseveralseconds.
Atextremelyslowsettings,NetLogowillbeupdatingsooftenthatyouwillseeyouragentsmoving(or
changingcolor,etc.)oneatatime.
Ifyouneedtotemporarilyshutoffcontinuousupdates,usetheno-displaycommand.Thedisplay
commandturnsupdatesbackon,andalsoforcesanimmediateupdate(unlesstheuserisfast-
forwardingthemodelusingthespeedslider).
Tick-basedupdates
AsdiscussedaboveintheTickCountersection,inmanyNetLogomodels,timepassesindiscrete
steps,called“ticks”.Typically,youwanttheviewtoupdateoncepertick,betweenticks.That’sthe
defaultbehaviorwithtick-basedupdates.
Ifyouwantadditionalviewupdates,youcanforceanupdateusingthedisplaycommand.(Theupdate
maybeskippediftheuserisfast-forwardingthemodelusingthespeedslider.)
Youdon’thavetousethetickcountertousetick-basedupdates.Ifthetickcounterneveradvances,the
viewwillupdateonlywhenyouusethedisplaycommand.
Ifyoumovethespeedslidertoafastenoughsetting,eventuallyNetLogowillskipsomeoftheupdates
thatwouldordinarilyhavehappened.Movingthespeedslidertoaslowersettingdoesn’tcause
additionalupdates;rather,itmakesNetLogopauseaftereachupdate.Theslowerthesetting,thelonger
thepause.
Evenundertick-basedupdates,theviewalsoupdateswheneverabuttonintheinterfacepopsup(both
onceandforeverbuttons)andwhenacommandenteredintheCommandCenterfinishes.Soit’snot
necessarytoaddthedisplaycommandtooncebuttonsthatdon’tadvancethetickcounter.Many
foreverbuttonsthatdon’tadvancethetickcounterdoneedtousethedisplaycommand.Anexamplein
theModelsLibraryistheLifemodel(underComputerScience->CellularAutomata).Theforever
buttonsthatlettheuserdrawintheviewusethedisplaycommandsotheusercanseewhattheyare
drawing,eventhoughthetickcounterisnotadvancing.
Choosingamode
Advantagesoftick-basedupdatesovercontinuousupdatesinclude:
1. Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputertocomputeror
fromruntorun.
2. Continuousupdatescanconfusetheuserofyourmodelbylettingthemseemodelstatesthey
aren’tsupposedtosee,whichmaybemisleading.
3. Sincesetupbuttonsdon’tadvancethetickcounter,theyareunaffectedbythespeedslider;thisis
normallythedesiredbehavior.
NearlyeverymodelinourModelsLibraryusestick-basedupdates.
Continuousupdatesareoccasionallyusefulforthoseraremodelsinwhichexecutionisnotdividedinto
short,discretephases.AnexampleintheModelsLibraryisTermites.(Seealso,however,theState
MachineExamplemodel,whichshowshowtore-codeTermitesusingticks.)
Evenformodelsthatwouldnormallybesettotick-basedupdates,itmaybeusefultoswitchto
continuousupdatestemporarilyfordebuggingpurposes.Seeingwhat’sgoingonwithinatick,insteadof
onlyseeingtheendresultofatick,couldhelpwithtroubleshooting.Afterswitchingtocontinuous
updates,youmaywanttousethespeedslidertoslowthemodeldownuntilyouseeyouragents
movingoneatatime.Don’tforgettochangebacktotick-basedupdateswhenyouaredone,asthe
choiceofupdatemodeissavedwiththemodel.
Changingtheupdatemodealsoaffectsmodelspeed.Updatingtheviewtakestime;oftenenforcinga
singleupdatepertick(byusingtick-basedupdates)willmakeyourmodelfaster.Ontheotherhand,
continuousupdateswillbefasterwhenrunningasingletickisfasterthandrawingaframeofthemodel.
Mostmodelsrunfasterundertick-basedupdates,butforanexampleofamodelwhichisfasterwith
continuousupdatesseethe“HeroesandCowards”librarymodel.
Framerate
OneofthemodelsettingsinNetLogo’s“Settings…”dialogis“Framerate”whichdefaultsto30frames
persecond.
Theframeratesettingaffectsbothcontinuousupdatesandtick-basedupdates.
Withcontinuousupdates,thesettingdirectlydeterminesthefrequencyofupdates.
Withtick-basedupdates,thesettingisaceilingonhowmanyupdatespersecondyouget.Iftheframe
rateis30,thenNetLogowillensurethatthemodelneverrunsfasterthanthatwhenthespeedslideris
inthedefaultposition.Ifanyframetakeslessthan1/30ofasecondtocomputeanddisplay,NetLogo
willpauseandwaituntilthefull1/30ofasecondhaspassedbeforecontinuing.
Theframeratesettingsletsyousetwhatyouconsidertobeanormalspeedforyourmodel.Thenyou,
ortheuserofyourmodel,canusethespeedslidertotemporarilygetafasterorslowerspeed.
Plotting
NetLogo’splottingfeaturesletyoucreateplotstohelpyouunderstandwhat’sgoingoninyourmodel.
Beforeyoucanplot,youneedtocreateoneormoreplotsintheInterfacetab.Formoreinformationon
usingandeditingplotsintheInterfacetab,seetheInterfaceGuide.
Plottingpoints
Thetwobasiccommandsforactuallyplottingthingsareplotandplotxy.
Withplotyouneedonlyspecifytheyvalueyouwantplotted.Thexvaluewillautomaticallybe0forthe
firstpointyouplot,1forthesecond,andsoon.(That’siftheplotpen’s“interval”isthedefaultvalueof1;
youcanchangetheinterval.)
Theplotcommandisespeciallyhandywhenyouwantyourmodeltoplotanewpointateverytime
step.Example:
plot count turtles
Ifyouneedtospecifyboththexandyvaluesofthepointyouwantplotted,thenuseplotxyinstead.
Thisexampleassumesthataglobalvariablecalledtimeexists:
plotxy time count-turtles
Plotcommands
Eachplotanditspenshavesetupandupdatecodefieldsthatmaycontaincommands(usually
containingplotorplotxy).Thesecommandsarerunautomaticallytriggeredbyothercommandsin
NetLogo.
Plotsetupcommandsandpensetupcommandsarerunwhentheeitherreset-ticksorsetup-plots
commandsarerun.Ifthestopcommandisruninthebodyoftheplotsetupcommandsthenthepen
setupcommandswillnotrun.
Plotupdatecommandsandpenupdatecommandsarerunwhentheeitherreset-ticks,tickor
update-plotscommandsarerun.Ifthestopcommandisruninthebodyoftheplotupdatecommands
thenthepenupdatecommandswillnotrun.
Herearethefourcommandsthattriggerplottingexplainedinmoredetail.
setup-plotsexecutescommandsforoneplotatatime.Foreachplot,theplot’ssetupcommands
areexecuted.Ifthestopcommandisnotencounteredwhilerunningthosecommands,theneach
oftheplot’spenswillhavetheirsetupcodeexecuted.
update-plotsisverysimilartosetup-plots.Foreachplot,theplot’supdatecommandsare
executed.Ifthestopcommandisnotencounteredwhilerunningthosecommands,theneachof
theplot’spenswillhavetheirupdatecodeexecuted.
tickisexactlythesameasupdate-plotsexceptthatthetickcounterisincrementedbeforethe
plotcommandsareexecuted.
reset-ticksfirstresetsthetickcounterto0,andthendoestheequivalentofsetup-plotsfollowed
byupdate-plots.
Atypicalmodelwillusereset-ticksandticklikeso:
to setup
clear-all
...
reset-ticks
end
to go
...
tick
end
Notethatinthisexampleweplotfromboththesetupandgoprocedures(becausereset-ticksrunsplot
setupandplotupdatecommands).Wedothisbecausewewantourplottoincludetheinitialstateofthe
systemattheendofsetup.Weplotattheendofthegoprocedure,notthebeginning,becausewewant
theplotalwaystobeuptodateafterthegobuttonstops.
Modelsthatdon’tuseticksbutstillwanttodoplottingwillinsteadusesetup-plotsandupdate-plots.In
thepreviouscode,replacereset-tickswithsetup-plots update-plotsandreplacetickwithupdate-
plots.
CodeExample:PlottingExample
Otherkindsofplots
Bydefault,NetLogoplotpensplotinlinemode,sothatthepointsyouplotareconnectedbyaline.
Ifyouwanttomovethepenwithoutplotting,youcanusetheplot-pen-upcommand.Afterthis
commandisissued,theplotandplotxycommandsmovethepenbutdonotactuallydrawanything.
Oncethepeniswhereyouwantit,useplot-pen-downtoputthepenbackdown.
Ifyouwanttoplotindividualpointsinsteadoflines,oryouwanttodrawbarsinsteadoflinesorpoints,
youneedtochangetheplotpen’s“mode”.Threemodesareavailable:line,bar,andpoint.Lineisthe
defaultmode.
Normally,youchangeapen’smodebyeditingtheplot.Thischangesthepen’sdefaultmode.It’salso
possibletochangethepen’smodetemporarilyusingtheset-plot-pen-modecommand.Thatcommand
takesanumberasinput:0forline,1forbar,2forpoint.
Histograms
Ahistogramisaspecialkindofplotthatmeasureshowfrequentlycertainvalues,orvaluesincertain
ranges,occurinacollectionofnumbersthatariseinyourmodel.
Forexample,supposetheturtlesinyourmodelhaveanagevariable.Youcouldcreateahistogramof
thedistributionofagesamongyourturtleswiththehistogramcommand,likethis:
histogram [age] of turtles
Thenumbersyouwanttohistogramdon’thavetocomefromanagentset;theycouldbeanylistof
numbers.
Notethatusingthehistogramcommanddoesn’tautomaticallyswitchthecurrentplotpentobarmode.If
youwantbars,youhavetosettheplotpentobarmodeyourself.(Aswesaidbefore,youcanchangea
pen’sdefaultmodebyeditingtheplotintheInterfacetab.)
Likeothertypesofplots,histogramscanbesettoautoscale.However,autoscaledhistogramsdonot
automaticallyresizethemselveshorizontallylikeotherplottypesdo.Tosettherangeprogrammatically,
youcanusetheset-plot-x-rangeprimitive.
Thewidthofthebarsinahistogramiscontrolledbytheplotpen’sinterval.Youcansetaplotpen’s
defaultintervalbyeditingtheplotintheInterfacetab.Youcanalsochangetheintervaltemporarilywith
theset-plot-pen-intervalcommandortheset-histogram-num-bars.Ifyouusethelattercommand,
NetLogowillsettheintervalappropriatelysoastofitthespecifiednumberofbarswithintheplot’s
currentxrange.
CodeExample:HistogramExample
Clearingandresetting
Youcanclearthecurrentplotwiththeclear-plotcommand,orcleareveryplotinyourmodelwith
clear-all-plots.Theclear-all commandalsoclearsallplots,inadditiontoclearingeverythingelsein
yourmodel.
Ifyouwanttoremoveonlythepointsthataparticularpenhasdrawn,useplot-pen-reset.
Whenawholeplotiscleared,orwhenapenisreset,thatdoesn’tjustremovethedatathathasbeen
plotted.Italsorestorestheplotorpentoitsdefaultsettings,astheywerespecifiedintheInterfacetab
whentheplotwascreatedorlastedited.Therefore,theeffectsofsuchcommandsasset-plot-
background-color,set-plot-x-rangeandset-plot-pen-colorareonlytemporary.
Rangesandautoscaling
Thedefaultxandyrangesforaplotarefixednumbers,buttheycanbechangedatsetuptimeorasthe
modelruns.
Tochangetherangesatanytime,useset-plot-x-rangeandset-plot-y-range.Or,youcanletthe
rangesgrowautomatically.Eitherway,whentheplotisclearedtherangeswillreturntotheirdefault
values.
Bydefault,allNetLogoplotshavetheautoscalingfeatureenabled.Thismeansthatifthemodeltriesto
plotapointwhichisoutsidethecurrentdisplayedrange,therangeoftheplotwillgrowalongoneor
bothaxessothatthenewpointisvisible.Histogramplots,however,donotautoscalehorizontally.
Inthehopethattherangeswon’thavetochangeeverytimeanewpointisadded,whentheranges
growtheyleavesomeextraroom:25%ifgrowinghorizontally,10%ifgrowingvertically.
Ifyouwanttoturnoffthisfeature,edittheplotanduncheckthe“AutoScale?”checkbox.Atpresent,itis
notpossibletoenableordisablethisfeatureonlyononeaxis;italwaysappliestobothaxes.
UsingaLegend
Youcanshowthelegendofaplotbycheckingthe“Showlegend”checkboxintheeditdialog.Ifyou
don’twantaparticularpentoshowupinthelegendyoucanuncheckthe“ShowinLegend”checkbox
forthatpenalsointheadvancedplotpensettings(theadvancedplotpensettingscanbeopenedby
clickingthepencilbuttonforthatpenintheplotpenstableintheploteditdialog).
Temporaryplotpens
Mostplotscangetalongwithafixednumberofpens.Butsomeplotshavemorecomplexneeds;they
mayneedtohavethenumberofpensvarydependingonconditions.Insuchcases,youcanmake
“temporary”plotpensfromcodeandthenplotwiththem.Thesepensarecalled“temporary”because
theyvanishwhentheplotiscleared(bytheclear-plot,clear-all-plots,orclear-allcommands).
Tocreateatemporaryplotpen,usethecreate-temporary-plot-pencommand.Typically,thiswouldbe
doneintheCodetab,butitisalsopossibletousethiscommandfromplotsetuporplotupdatecode(in
theeditdialog).Bydefault,thenewpenisdown,isblackincolor,hasanintervalof1,andplotsinline
mode.Commandsareavailabletochangeallofthesesettings;seethePlottingsectionoftheNetLogo
Dictionary.
Beforeyoucanusethepen,you’llhavetousetheusetheset-current-plotandset-current-plot-pen
commands.Theseareexplainedinthenextsection.
set-current-plotandset-current-plot-pen
BeforeNetLogo5,itwasnotpossibletoputplotcommandsintheplotitself.Alloftheplotcodewas
writtenintheCodetabwiththerestofthecode.Forbackwardscompatibility,andfortemporaryplot
pens,thisisstillsupported.ModelsinpreviousversionsofNetLogo(andthoseusingtemporaryplot
pens)havetoexplicitlystatewhichplotisthecurrentplotwiththeset-current-plotcommandand
whichpenisthecurrentpenwiththeset-current-plot-pencommand.
Tosetthecurrentplotusetheset-current-plotcommandwiththenameoftheplotenclosedindouble
quotes,likethis:
set-current-plot "Distance vs. Time"
Thenameoftheplotmustbeexactlyasyoutypeditwhenyoucreatedtheplot.Notethatlaterifyou
changethenameoftheplot,you’llalsohavetoupdatetheset-current-plotcallsinyourmodeltouse
thenewname.(Copyandpastecanbehelpfulhere.)
Foraplotwithmultiplepens,youcanmanuallyspecifywhichpenyouwanttoplotwith.Ifyoudon’t
specifyapen,plottingwilltakeplacewiththefirstpenintheplot.Toplotwithadifferentpen,theset-
current-plot-pencommandwasusedwiththenameofthepenenclosedindoublequotes,likethis:
set-current-plot-pen "distance"
Oncethecurrentpenisset,thencommandslikeplot count turtlescanbeexecutedforthatpen.
Oldermodelswithplotsusuallyhadtheirowndo-plottingprocedurethatlookedsomethinglikethis:
to do-plotting
set-current-plot "populations"
set-current-plot-pen "sheep"
plot count sheep
set-current-plot-pen "wolves"
plot count wolves
set-current-plot "next plot"
...
end
Onceagain,thisisnolongernecessaryinNetLogo5,unlessyouareusingtemporaryplotpens.
Conclusion
NoteveryaspectofNetLogo’splottingsystemhasbeenexplainedhere.SeethePlottingsectionofthe
NetLogoDictionaryforinformationonadditionalcommandsandreportersrelatedtoplotting.
ManyoftheSampleModelsintheModelsLibraryillustratevariousadvancedplottingtechniques.Also
checkoutthefollowingcodeexamples:
CodeExamples:PlotAxisExample,PlotSmoothingExample,RollingPlotExample
Strings
StringsmaycontainanyUnicodecharacters.
ToinputaconstantstringinNetLogo,surrounditwithdoublequotes.
Theemptystringiswrittenbyputtingnothingbetweenthequotes,likethis:"".
Mostofthelistprimitivesworkonstringsaswell:
but-first "string" => "tring"
but-last "string" => "strin"
empty? "" => true
empty? "string" => false
first "string" => "s"
item 2 "string" => "r"
last "string" => "g"
length "string" => 6
member? "s" "string" => true
member? "rin" "string" => true
member? "ron" "string" => false
position "s" "string" => 0
position "rin" "string" => 2
position "ron" "string" => false
remove "r" "string" => "sting"
remove "s" "strings" => "tring"
replace-item 3 "string" "o" => "strong"
reverse "string" => "gnirts"
Afewprimitivesarespecifictostrings,suchasis-string?,substring,andword:
is-string? "string" => true
is-string? 37 => false
substring "string" 2 5 => "rin"
word "tur" "tle" => "turtle"
Stringscanbecomparedusingthe=,!=,<,>,<=,and>=operators.
Ifyouneedtoembedaspecialcharacterinastring,usethefollowingescapesequences:
\n=newline
\t=tab
\"=doublequote
\\=backslash
Output
Thissectionisaboutoutputtothescreen.Outputtothescreencanalsobelatersavedtoafileusing
theexport-outputcommand.Ifyouneedamoreflexiblemethodofwritingdatatoexternalfiles,seethe
nextsection,FileI/O.
ThebasiccommandsforgeneratingoutputtothescreeninNetLogoareprint,show,type,andwrite.
ThesecommandssendtheiroutputtotheCommandCenter.
Forfulldetailsonthesefourcommands,seetheirentriesintheNetLogoDictionary.Hereishowthey
aretypicallyused:
printisusefulinmostsituations.
showletsyouseewhichagentisprintingwhat.
typeletsyouprintseveralthingsonthesameline.
writeletsyouprintvaluesinaformatwhichcanbereadbackinusingfile-read.
ANetLogomodelmayoptionallyhavean“outputarea”initsInterfacetab,separatefromtheCommand
Center.TosendoutputthereinsteadoftheCommandCenter,usetheoutput-print,output-show,
output-type,andoutput-writecommands.
Theoutputareacanbeclearedwiththeclear-outputcommandandsavedtoafilewithexport-output.
Thecontentsoftheoutputareawillbesavedbytheexport-worldcommand.Theimport-world
commandwillcleartheoutputareaandsetitscontentstothevalueinimportedworldfile.Itshouldbe
notedthatlargeamountsofdatabeingsenttotheoutputareacanincreasethesizeofyourexported
worlds.
Ifyouuseoutput-print,output-show,output-type,output-write,clear-output,orexport-outputina
modelwhichdoesnothaveaseparateoutputarea,thenthecommandsapplytotheoutputportionof
theCommandCenter.
HowOutputPrimitivesDiffer
Thisinformationisaquickreferenceformoreadvancedusers.
Theprint,show,type,andwriteprimitivesdifferonthefollowingfacets:
Whattypesofvaluesdoestheprimitiveaccept?
Doestheprimitiveoutputanewlineattheend?
Arestringsoutputwithquotessurroundingthem?
Doestheprimitiveoutputtheagentwhichprintedit?
Thefollowingtablesummarizesthebehaviorofeachprimitive.
Primitive Acceptablevalues Adds
newline?
Strings
quoted?
Outputs
self?
print anyNetLogovalue yes no no
show anyNetLogovalue yes yes yes
type anyNetLogovalue no no no
write boolean,number,string,listscontainingonly
thesetypes no yes no
FileI/O
InNetLogo,thereisasetofprimitivesthatgiveyouthepowertointeractwithoutsidefiles.Theyall
beginwiththeprefixfile-.
Therearetwomainmodeswhendealingwithfiles:readingandwriting.Thedifferenceisthedirectionof
theflowofdata.Whenyouarereadingininformationfromafile,datathatisstoredinthefileflowsinto
yourmodel.Ontheotherhand,writingallowsdatatoflowoutofyourmodelandintoafile.
Whenworkingwithfiles,alwaysbeginbyusingtheprimitivefile-open.Thisspecifieswhichfileyouwill
beinteractingwith.Noneoftheotherprimitivesworkunlessyouopenafilefirst.
Thenextfile-primitiveyouusedictateswhichmodethefilewillbeinuntilthefileisclosed,readingor
writing.Toswitchmodes,closeandthenreopenthefile.
Thereadingprimitivesincludefile-read,file-read-line,file-read-characters,andfile-at-end?.
Notethatthefilemustexistalreadybeforeyoucanopenitforreading.
CodeExamples:FileInputExample
TheprimitivesforwritingaresimilartotheprimitivesthatprintthingsintheCommandCenter,except
thattheoutputgetssavedtoafile.Theyincludefile-print,file-show,file-type,andfile-write.Note
thatyoucannever“overwrite”data.Inotherwords,ifyouattempttowritetoafilewithexistingdata,all
newdatawillbeappendedtotheendofthefile.(Ifyouwanttooverwriteafile,usefile-deleteto
deleteit,thenopenitforwriting.)
CodeExamples:FileOutputExample
Whenyouarefinishedusingafile,youcanusethecommandfile-closetoendyoursessionwiththe
file.Ifyouwishtoremovethefileafterwards,usetheprimitivefile-deletetodeleteit.Toclosemultiple
openedfiles,oneneedstofirstselectthefilebyusingfile-openbeforeclosingit.
;; Open 3 files
file-open "myfile1.txt"
file-open "myfile2.txt"
file-open "myfile3.txt"
;; Now close the 3 files
file-close
file-open "myfile2.txt"
file-close
file-open "myfile1.txt"
file-close
Or,ifyouknowyoujustwanttocloseeveryfile,youcanusefile-close-all.
Twoprimitivesworthnotingarefile-writeandfile-read.Theseprimitivesaredesignedtoeasilysave
andretrieveNetLogoconstantssuchasnumbers,lists,booleans,andstrings.file-writewillalways
outputthevariableinsuchamannerthatfile-readwillbeabletointerpretitcorrectly.
file-open "myfile.txt" ;; Opening file for writing
ask turtles
[ file-write xcor file-write ycor ]
file-close
file-open "myfile.txt" ;; Opening file for reading
ask turtles
[ setxy file-read file-read ]
file-close
CodeExamples:FileInputExampleandFileOutputExample
Lettingtheuserchoose
Theuser-directory,user-file,anduser-new-fileprimitivesareusefulwhenyouwanttheuserto
chooseafileordirectoryforyourcodetooperateon.
Movies
Thissectiondescribeshowtocapturean“.mp4”movieofaNetLogomodel.
First,usethevid:start-recordercommandtostartthevideorecorder.
Toaddaframetoyourmovie,useeithervid:record-vieworvid:record-interface,dependingon
whetheryouwantthemovietoshowjustthecurrentview,ortheentireInterfacetab.Inasinglemovie,
theresolutionwillbeoneofthefollowing:
Theresolutionspecifiedinthecalltovid:start-recorderwidth heightifyouspecifiedthe
resolution.Theseareoptionalparameters.
Theresolutionoftheviewifyoudidnotspecifyaresolutioninthecalltovid:start-recorderand
callvid:record-viewbeforecallingvid:record-interface
Theresolutionoftheinterfaceifyoudidnotspecifyaresolutioninthecalltovid:start-recorder
andcallvid:record-interfacebeforecallingvid:record-view
Notethatiftheresolutionofarecordedimagedoesn’tmatchtheresolutionoftherecordingitwillbe
scaledtofitwhichcanresultinimageswhichlookblurryorout-of-focus.
Whenyou’redoneaddingframes,usevid:save-recording.Thefilenameyouprovideshouldendwith
.mp4,theextensionforMP4-encodedmovies(playableinQuickTimeandotherprograms).
;; export a 30 frame movie of the view
extensions [vid]
;...
setup
vid:start-recorder
vid:record-view ;; show the initial state
repeat 30
[ go
vid:record-view ]
vid:save-recording "out.mp4"
Amoviewillplaybackat25framespersecond.Tomakethemovieplaybackfasterorslower,consider
usingavideopostprocessingtool.
Tocheckwhetherornotyouarerecording,callvid:recorder-status,whichreportsastringthat
describesthestateofthecurrentrecorder.
Tothrowawaythemoviecurrentlybeingrecorded,callvid:reset-recorder.
CodeExample:MovieExample
Moviesgeneratedwhenrunningheadless,orbybackgroundrunsinaparallelBehaviorSpace
experimentmayuseonlyvid:record-viewprimitive.MoviesgeneratedinNetLogoGUImayalsouse
vid:record-interfaceandvid:record-source.
NetLogomoviesareexportedasH.264-encodedMP4files.ToplayanMP4movie,youcanusetheVLC
Player,afreedownloadfromtheVideoLANorganization.
Moviescantakeupalotofdiskspace.Youwillprobablywanttocompressyourmovieswiththird-party
software.Thesoftwaremaygiveyouachoiceofdifferentkindsofcompression.Somekindsof
compressionarelossless,whileothersarelossy.“Lossy”meansthatinordertomakethefilessmaller,
someofthedetailinthemovieislost.Dependingonthenatureofyourmodel,youmaywanttoavoid
usinglossycompression,forexampleiftheviewcontainsfinepixel-leveldetail.
Perspective
The2Dandthe3Dviewshowtheworldfromtheperspectiveoftheobserver.Bydefaulttheobserveris
lookingdownontheworldfromthepositivez-axisattheorigin.Youcanchangetheperspectiveofthe
observerbyusingthefollow,rideandwatchobservercommandsandfollow-me,ride-meandwatch-me
turtlecommands.Wheninfolloworridemodetheobservermoveswiththesubjectagentaroundthe
world.Thedifferencebetweenfollowandrideisonlyvisibleinthe3Dview.Inthe3Dviewtheusercan
changethedistancebehindtheagentusingthemouse.Whentheobserverisfollowingatzerodistance
fromtheagentitisactuallyridingtheagent.Whentheobserverisinwatchmodeittracksthe
movementsofoneturtlewithoutmoving.Inbothviewsyouwillseeaspotlightappearonthesubjectand
inthe3Dviewtheobserverwillturntofacethesubject.Todeterminewhichagentisthefocusyoucan
usethesubjectreporter.
CodeExample:PerspectiveExample
Drawing
Thedrawingisalayerwhereturtlescanmakevisiblemarks.
Intheview,thedrawingappearsontopofthepatchesbutunderneaththeturtles.Initially,thedrawingis
emptyandtransparent.
Youcanseethedrawing,buttheturtles(andpatches)can’t.Theycan’tsensethedrawingorreacttoit.
Thedrawingisjustforpeopletolookat.
Turtlescandrawanderaselinesinthedrawingusingthepen-downandpen-erasecommands.Whena
turtle’spenisdown(orerasing),theturtledraws(orerases)alinebehinditwheneveritmoves.The
linesarethesamecolorastheturtle.Tostopdrawing(orerasing),usepen-up.
Linesdrawnbyturtlesarenormallyonepixelthick.Ifyouwantadifferentthickness,setthepen-size
turtlevariabletoadifferentnumberbeforedrawing(orerasing).Innewturtles,thevariableissetto1.
Linesmadewhenaturtlemovesinawaythatdoesn’tfixadirection,suchaswithsetxyormove-to,the
shortestpathlinethatobeysthetopologywillbedrawn.
Here’ssometurtleswhichhavemadeadrawingoveragridofrandomlyshadedpatches.Noticehow
theturtlescoverthelinesandthelinescoverthepatchcolors.Thepen-sizeusedherewas2:
Thestampcommandletsaturtleleaveanimageofitselfbehindinthedrawingandstamp-eraseletsit
removethepixelsbelowitinthedrawing.
Toerasethewholedrawing,usetheobservercommmandclear-drawing.(Youcanalsouseclear-all,
whichclearseverythingelsetoo.)
Importinganimage
Theobservercommandimport-drawingcommandallowsyoutoimportanimagefilefromdiskintothe
drawing.
import-drawingisusefulonlyforprovidingabackdropforpeopletolookat.Ifyouwantturtlesand
patchestoreacttotheimage,youshoulduseimport-pcolorsorimport-pcolors-rgbinstead.
ComparisontootherLogos
DrawingworkssomewhatdifferentlyinNetLogothansomeotherLogos.
Notabledifferencesinclude:
Newturtles’pensareup,notdown.
Insteadofusingafencecommandtoconfinetheturtleinsideboundaries,inNetLogoyoueditthe
worldandturnwrappingoff.
Thereisnoscreen-color,bgcolor,orsetbg.Youcanmakeasolidbackgroundbycoloringthe
patches,e.g.ask patches [ set pcolor blue ].
DrawingfeaturesnotsupportedbyNetLogo:
Thereisnowindowcommand.ThisisusedinsomeotherLogostolettheturtleroamoveran
infiniteplane.
Thereisnofloodorfillcommandtofillanenclosedareawithcolor.
Topology
Thewaytheworldofpatchesisconnectedcanchange.Bydefaulttheworldisatoruswhichmeansit
isn’tbounded,but“wraps”–sowhenaturtlemovespasttheedgeoftheworld,itdisappearsand
reappearsontheoppositeedgeandeverypatchhasthesamenumberof“neighbor”patches.Ifyou’re
apatchontheedgeoftheworld,someofyour“neighbors”areontheoppositeedge.
However,youcanchangethewrapsettingswiththeSettingsbutton.Ifwrappingisnotallowedina
givendirectiontheninthatdirection(xory)theworldisbounded.Patchesalongthatboundarywillhave
fewerthan8neighborsandturtleswillnotmovebeyondtheedgeoftheworld.
ThetopologyoftheNetLogoworldhasfourpotentialvalues,torus,box,verticalcylinder,orhorizontal
cylinder.Thetopologyiscontrolledbyenablingordisablingwrappinginthexorydirections.Thedefault
worldisatorus.
Atoruswrapsinbothdirections,meaningthatthetopandbottomedgesoftheworldareconnectedand
theleftandrightedgesareconnected.Soifaturtlemovesbeyondtherightedgeoftheworlditappears
againontheleftandthesameforthetopandbottom.
Aboxdoesnotwrapineitherdirection.Theworldisboundedsoturtlesthattrytomoveofftheedgeof
theworldcannot.Notethatthepatchesaroundedgeoftheworldhavefewerthaneightneighbors;the
cornershavethreeandtheresthavefive.
Horizontalandverticalcylinderswrapinonedirectionbutnottheother.Ahorizontalcylinderwraps
vertically,sothetopoftheworldisconnectedtothebottom.buttheleftandrightedgesarebounded.A
verticalcylinderistheopposite;itwrapshorizontallysotheleftandrightedgesareconnected,butthe
topandbottomedgesarebounded.
CodeExample:NeighborsExample
Whencoordinateswrap,turtlesandlinkswrapvisuallyintheview,too.Ifaturtleshapeorlinkextends
pastanedge,partofitwillappearattheotheredge.(Turtlesthemselvesarepointsthattakeupno
space,sotheycannotbeonbothsidesoftheworldatonce,butintheview,theyappeartotakeup
spacebecausetheyhaveashape.)
Wrappingalsoaffectshowtheviewlookswhenyouarefollowingaturtle.Onatorus,wherevertheturtle
goes,youwillalwaysseethewholeworldaroundit:
Whereasinaboxorcylindertheworldhasedges,sotheareaspastthoseedgesshowupintheview
asgray:
CodeExample:TermitesPerspectiveDemo(torus),AntsPerspectiveDemo(box)
Thetopologysettingsalsocontrolthebehaviorofthedistance(xy),in-radius,in-cone,face(xy),and
towards(xy)primitives.Thetopologycontrolswhethertheprimitiveswrapornot.Theyalwaysusethe
shortestpathallowedbythetopology.Forexample,thedistancefromthecenterofthepatchesinthe
bottomrightcorner(min-pxcor,min-pycor)andtheupperleftcorner(max-pxcor,max-pycor)willbeas
followsforeachtopologygiventhattheminandmaxpxcorandpycorare+/-2:
Torus-sqrt(2)~1.414(thiswillbethesameforallworldsizessincethepatchesaredirectly
diagonaltoeachotherinatorus.)
Box-sqrt(world-width^2+world-height^2)~7.07
VerticalCylinder-sqrt(world-height^2+1)~5.099
HorizontalCylinder-sqrt(world-width^2+1)~5.099
Alltheotherprimitiveswillactsimilarlytodistance.Ifyouformerlyused-nowrapprimitivesinyourmodel
werecommendremovingthemandchangingthetopologyoftheworldinstead.
Ifyourmodelhasturtlesthatmovearoundyou’llneedtothinkaboutwhathappenstothemwhenthey
reachtheedgeoftheworld,ifthetopologyyou’reusinghassomenon-wrappingedges.Thereareafew
commonoptions:theturtleisreflectedbackintotheworld(eithersystematicallyorrandomly),theturtle
exitsthesystem(dies),ortheturtleishidden.Itisnolongernecessarytochecktheboundsusingturtle
coordinates,insteadwecanjustaskNetLogoifaturtleisattheedgeoftheworld.Thereareacouple
waysofdoingthis,thesimplestistousethecan-move?primitive.
if not can-move? distance [ rt 180 ]
can-move?merelyreturnstrueifthepositiondistanceinfrontoftheturtleisinsidetheNetLogoworld,
falseotherwise.Inthiscase,iftheturtleisattheedgeoftheworlditsimplegoesbackthewayitcame.
Youcanalsousepatch-ahead 1 != nobody inplaceofcan-move?.Ifyouneedtodosomethingsmarter
thatsimplyturningarounditmaybeusefultousepatch-atwithdxanddy.
if patch-at dx 0 = nobody [
set heading (- heading)
]
if patch-at 0 dy = nobody [
set heading (180 - heading)
]
Thistestswhethertheturtleishittingahorizontalorverticalwallandbouncesoffthatwall.
Insomemodelsifaturtlecan’tmoveforwarditsimplydies(exitsthesystem,likeinConductoror
Mousetraps).
if not can-move? distance[ die ]
Ifyouaremovingturtlesusingsetxyratherthanforwardyoushouldtesttomakesurethepatchyouare
abouttomovetoexistssincesetxythrowsaruntimeerrorifitisgivencoordinatesoutsidetheworld.
Thisisacommonsituationwhenthemodelissimulatinganinfiniteplaneandturtlesoutsidetheview
shouldsimplybehidden.
let new-x new-value-of-xcor
let new-y new-value-of-ycor
ifelse patch-at (new-x - xcor) (new-y - ycor) = nobody
[ hide-turtle ]
[ setxy new-x new-y
show-turtle ]
SeveralmodelsintheModelsLibraryusethistechnique,Gravitation,N-Bodies,andElectrostaticsare
goodexamples.
Thediffuseanddiffuse4commandsbehavecorrectlyinalltopologies.Eachpatchdiffusesandequal
amountofthediffusevariabletoeachofitsneighbors,ifithasfewerthan8neighbors(or4ifyouare
usingdiffuse4),theremainderstaysonthediffusingpatch.Thismeansthattheoverallsumofpatch-
variableacrosstheworldremainsconstant.However,ifyouwantthediffusemattertostillfalloffthe
edgesoftheworldasitwouldonaninfiniteplaneyoustillneedtocleartheedgeseachstepasinthe
DiffuseOffEdgesExample.
Links
Alinkisanagentthatconnectstwoturtles.Theseturtlesaresometimesalsocallednodes.
Thelinkisalwaysdrawnasalinebetweenthetwoturtles.Linksdonothavealocationasturtlesdo,
theyarenotconsideredtobeonanypatchandyoucannotfindthedistancefromalinktoanotherpoint.
Therearetwolinkdesignations:undirectedanddirected.Adirectedlinkisoutof,orfrom,onenodeand
into,orto,anothernode.Therelationshipofaparenttoachildcouldbemodeledasadirectedlink.An
undirectedlinkappearsthesametobothnodes,eachnodehasalinkwithanothernode.The
relationshipbetweenspouses,orsiblings,couldbemodeledasanundirectedlink.
Thereisaglobalagentsetofalllinks,justaswithturtlesandpatches.Youcancreateundirectedlinks
usingthecreate-link-withandcreate-links-withcommands;anddirectedlinksusingthecreate-
link-to,create-links-to,create-link-from,andcreate-links-fromcommands.Oncethefirstlinkhas
beencreateddirectedorundirected,allunbreededlinksmustmatch(linksalsosupportbreeds,much
liketurtles,whichwillbediscussedshortly);it’simpossibletohavetwounbreededlinkswhereoneis
directedandtheotherisundirected.Aruntimeerroroccursifyoutrytodoit.(Ifallunbreededlinksdie,
thenyoucancreatelinksofthatbreedthataredifferentindesignationfromthepreviouslinks.)
Ingeneral,linkprimitivenamesindicatewhatkindoflinkstheydealwith:
Primitivesthathave“out”intheirnameutilizeoutgoingandundirectedlinks.Youcanthinkofthese
as“thelinksIcanusetogetfromthecurrentnodetoothernodes.”Ingeneral,theseareprobably
theprimitivesyouwanttouse.
Primitivesthathave“in”intheirnameutilizeincomingandundirectedlinks.Youcanthinkofthese
as“thelinksIcanusetogettothecurrentnodefromothernodes.”
Primtivesthatdonotspecify“in”or“out”,orhave“with”intheirnameutilizealllinks,both
undirectedanddirected,incomingandoutgoing.
Alink’send1andend2variablescontainthetwoturtlesthelinkconnects.Ifthelinkisdirected,itgoes
fromend1toend2.Ifthelinkisundirected,end1isalwaystheolderofthetwoturtles,thatis,theturtle
withthesmallerwhonumber.
Linkbreeds,liketurtlebreeds,allowyoutodefinedifferenttypesoflinksinyourmodel.Linkbreeds
musteitherbedirectedorundirected,unlikeunbreededlinksthisisdefinedatcompiletimeratherthan
runtime.Youdeclarelinkbreedsusingthekeywordsundirected-link-breedanddirected-link-breed.
Breededlinkscanbecreatedusingthecommandscreate-<breed>-withandcreate-<breeds>-withfor
undirectedbreedsandthecommandscreate-<breed>-to,create-<breeds>-to,create-<breed>-from,
andcreate-<breeds>-fromfordirectedlinks.
Therecannotbemorethanoneundirectedlinkofthesamebreed(ormorethanoneunbreeded
undirectedlink)betweenapairofagents,normorethanonedirectedlinkofthesamebreedinthe
samedirectionbetweenapairofagents.Youcanhavetwodirectedlinksofthesamebreed(ortwo
unbreededdirectedlinks)betweenapairiftheyareinoppositedirections.
Layouts
Aspartofournetworksupportwehavealsoaddedseveraldifferentprimitivesthatwillhelpyouto
visualizethenetworks.Thesimplestislayout-circlewhichevenlyspacestheagentsaroundthecenter
oftheworldgivenaradius.
layout-radialisagoodlayoutifyouhavesomethinglikeatreestructure,thougheveniftherearesome
cyclesinthetreeitwillstillwork,thoughastherearemoreandmorecyclesitwillprobablynotlookas
good.layout-radialtakesarootagenttobethecentralnodeplacesitat(0,0)andarrangesthenodes
connectedtoitinaconcentricpattern.Nodesonedegreeawayfromtherootwillbearrangedina
circularpatternaroundthecentralnodeandthenextlevelaroundthosenodesandsoon.layout-
radialwillattempttoaccountforasymmetricalgraphsandgivemorespacetobranchesthatarewider.
layout-radialalsotakesabreedasaninputsoyouuseonebreedoflinkstolayoutthenetworkand
notanother.
Givenasetofanchornodeslayout-tutteplacesalltheothernodesatthecenterofmassofthenodes
itislinkedto.Theanchorsetisautomaticallyarrangedinacirclelayoutwithauserdefinedradiusand
theothernodeswillconvergeintoplace(thisofcoursemeansthatyoumayhavetorunitseveraltimes
beforethelayoutisstable.)
layout-springisusefulformanykindsofnetworks.Thedrawbackisthatisrelativelyslowsinceittakes
manyiterationstoconverge.Inthislayoutthelinksactasspringsthatpullthenodestheyconnect
towardeachotherandthenodesrepeleachother.Thestrengthoftheforcesiscontrolledbyinputsto
theprimitives.Theseinputswillalwayshaveavaluebetween0and1;keepinmindthatverysmall
changescanstillaffecttheappearanceofthenetwork.Thespringsalsohavealength(inpatchunits),
however,becauseofalltheforcesinvolvedthenodeswillnotendupexactlythatdistancefromeach
other.
**CodeExamples:**NetworkExample,NetworkImportExample,GiantComponent,Small
Worlds,PreferentialAttachment
Anonymousprocedures
Anonymousproceduresletyoustorecodetoberunlater.JustlikeregularNetLogoprocedures,an
anonymousprocedurescanbeeitheracommand(anonymouscommand)orareporter(anonymous
reporter).
Anonymousproceduresarevalues,whichmeanstheymaybepassedasinput,reportedasaresult,or
storedinavariable.
Ananonymousproceduremightberunonce,multipletimes,ornotatall.
Inotherprogramminglanguagesanonymousproceduresareknownasfirst-classfunctions,closures,or
lambda.
Anonymousprocedureprimitives
Primitivesspecifictoanonymousproceduresare->,is-anonymous-command?,andis-anonymous-
reporter?.
The->createsananonymousprocedure.Theanonymousprocedureitreportsmightbeacommandor
areporter,dependingonwhatkindofblockyoupassit.Forexample[ -> fd 1 ] reportsan
anonymouscommand,becausefdisacommand,while[ -> count turtles ] reportsananonymous
reporter,becausecountisareporter.
Theseprimitivesrequireanonymousproceduresasinput:foreach,map,reduce,filter,n-values,sort-
by.Whencallingtheseprimitives,usingan->isoptionalifyouranonymousprocedurecontainsasingle
primitivewhichhasrequiresnomoreinputsthanareareprovidedbytheprimitive.Forexampleone
maywritesimplyforeach mylist printinsteadofforeach mylist [ [x] -> print x ] ,thoughthe
latterisalsoaccepted.Dependingontheanonymousprocedure,variouspartsoftheanonymous
proceduresyntaxcanbeomitted.Forasummaryofoptionalsyntax,seethetablebelow.
Theruncommandacceptsanonymouscommandsaswellasstrings.
Therunresultreporteracceptsanonymousreportersaswellasstrings.
runandrunresultallowpassinginputstoananonymousprocedure.Aswithallprimitivesaccepting
varyingnumberofinputs,thewholecallmustbesurroundedwithparentheses,soforexample(run my-
anonymous-command 5)or(runresult my-anonymous-reporter "foo" 2).Whennotpassinginput,no
parenthesesarerequired.
Anonymousprocedureinputs
Ananonymousproceduremaytakezeroormoreinputs.Theinputsarereferencedthevariables
declaredbeforethearrow.Forinstance,intheanonymousreporter[ [a b] -> a + b ] ,aandbare
inputs.
Anonymousproceduresandstrings
Creatingandrunninganonymousproceduresisfast.Touserunorrunresultonanewstringforthefirst
timeisabout100xslowerthanrunningananonymousprocedure.Modelersshouldnormallyuse
anonymousproceduresinsteadofrunningstrings,exceptwhenrunningstringsenteredbytheuser.
Concisesyntax
Simpleusesofforeach,map,reduce,filter,n-values,andsort-bycanbewrittenwithanespecially
concisesyntax.Youcanwrite:
map abs [1 -2 3 -4]
;; => [1 2 3 4]
reduce + [1 2 3 4]
;; => 10
filter is-number? [1 "x" 3]
;; => [1 3]
foreach [1 2 3 4] print
;; prints 1 through 4
InolderNetLogoversions(4andearlier),thesehadtobewritten:
map [abs ?] [1 -2 3 -4]
;; => [1 2 3 4]
reduce [?1 + ?2] [1 2 3 4]
;; => 10
filter [is-number? ?] [1 "x" 3]
;; => [1 3]
foreach [1 2 3 4] [ print ? ]
;; prints 1 through 4
Anonymousproceduresasclosures
Anonymousproceduresare“closures”;thatmeanstheycaptureor“closeover”thebindings(notjustthe
currentvalues)oflocalvariablesandprocedureinputs.Theydonotcaptureagentvariablesanddonot
capturetheidentity(oreventheagenttype)ofthecurrentagent.
Nonlocalexits
Thestopandreportcommandsexitfromthedynamicallyenclosingprocedure,nottheenclosing
anonymousprocedure.(Thisisbackward-compatiblewitholderNetLogoversions.)
Anonymousproceduresandextensions
TheextensionsAPIsupportswritingprimitivesthatacceptanonymousproceduresasinput.Writeusfor
samplecode.
Limitations
WehopetoaddressatleastsomeofthefollowinglimitationsinfutureNetLogoversions:
import-worlddoesnotsupportanonymousprocedures.
Anonymousprocedurescan’tbevariadic(acceptavaryingnumberofinputs).
Anonymousreporterscan’tcontaincommands,onlyasinglereporterexpression.Soforexample
youmustuseifelse-valuenotif,andyoudon’tusereportatall.Ifyourcodeistoocomplexto
bewrittenasonereporter,you’llneedtomovethecodetoaseparatereporterprocedure,and
thencallthatprocedurefromyouranonymousreporter,passingitanyneededinputs.
Anonymousproceduresarenotinterchangeablewithcommandblocksandreporterblocks.Only
theprimitiveslistedaboveacceptanonymousproceduresasinput.Controlprimitivessuchas
ifelseandwhileandagentprimitivessuchasofandwithdon’tacceptanonymousprocedures.
SoforexampleifIhaveananonymousreporterlet r [ -> if random 2 == 0 ] andtwo
anonymouscommandslet c1 [ -> tick ] andlet c2 [ -> stop ] ,Ican’twriteifelse r c1 c2 ,
Imustwriteifelse runresult r [ run c1 ] [ run c2 ] .
Theconcisesyntaxwhere->maybeomittedisonlyavailabletoprimitivesandextension
primitives,notordinaryprocedures.SoforexampleifIhaveaprocedurepthatacceptsan
anonymousprocedureasinput,itmustbecalledase.g.p [ -> ... ]notp [ ... ].
WhatisOptional?
Thereareseveraldifferentwaysofwritinganonymousprocedureswhichallowuserstoomitpartorall
oftheanonymousproceduresyntax.Thesearesummarizedinthetablebelow.
Whatistheanonymous
procedurelike?
Whatcanbeleft
out? Examples
Theanonymousprocedure
isasingleprimitive
inputnames
arrow
block
brackets
foreach mylist stamp ; no inputs
foreach mylist print ; single input
(foreach xs ys setxy) ; multiple
inputs
map round [1.3 2.4 3.5] ; reporter,
single input
(map + [1 2 3] [4 5 6]) ; reporter,
multiple inputs
Theanonymousprocedure
takesnoinputs
inputnames
arrow
foreach mylist [ print "abc" ]
map [ 4 ] mylist
Theanonymousprocedure
haszerooroneinput(s)
brackets
aroundinput
names
foreach mylist [ -> stamp ] ; no
inputs
foreach mylist [ x -> print x ] ;
single input
foreach mylist [ x -> rt x fd x ] ;
multiple primitives, single input
map [ -> world-width ] mylist ;
reporter, no inputs
map [ x -> x ^ 2 ] mylist ; reporter,
single input
Anonymousproceduretakes
morethanoneinput nothing
(foreach xs ys [ [ x y ] -> setx x +
y ])
(map [ [ x y ] -> x mod round y ] xs
ys)
Note:bracketsaroundinputnameswerealwaysrequiredinNetLogo6.0.0.Ifyoucopyandpastecode
intoNetLogo6.0.0usinganonymousprocedureswithunbracketedinputnames,thecodewillnot
compileuntilyouaddthebrackets.
Codeexample
CodeExample:StateMachineExample
Ask-Concurrent
NOTE:Thefollowinginformationisincludedonlyforbackwardscompatibility.Wedon’trecommend
usingtheask-concurrentprimitiveatallinnewmodels.
InveryoldversionsofNetLogo,askhadsimulatedconcurrentbehaviorbydefault.SinceNetLogo4.0
(2007),askisserial,thatis,theagentsrunthecommandsinsidetheaskoneatatime.
Thefollowinginformationdescribesthebehavioroftheask-concurrentcommand,whichbehavesthe
waytheoldaskbehaved.
ask-concurrentproducessimulatedconcurrencyviaamechanismofturn-taking.Thefirstagenttakesa
turn,thenthesecondagenttakesaturn,andsoonuntileveryagentintheaskedagentsethashada
turn.Thenwegobacktothefirstagent.Thiscontinuesuntilalloftheagentshavefinishedrunningallof
thecommands.
Anagent’s“turn”endswhenitperformsanactionthataffectsthestateoftheworld,suchasmoving,or
creatingaturtle,orchangingthevalueofaglobal,turtle,patch,orlinkvariable.(Settingalocalvariable
doesn’tcount.)
Theforward(fd)andback(bk)commandsaretreatedspecially.Whenusedinsideask-concurrent,
thesecommandscantakemultipleturnstoexecute.Duringitsturn,theturtlecanonlymovebyone
step.Thus,forexample,fd 20isequivalenttorepeat 20 [ fd 1 ] ,wheretheturtle’sturnendsafter
eachrunoffd.Ifthedistancespecifiedisn’taninteger,thelastfractionofsteptakesafullturn.Sofor
examplefd 20.3isequivalenttorepeat 20 [ fd 1 ] fd 0.3 .
Thejumpcommandalwaystakesexactlyoneturn,regardlessofdistance.
Tounderstandthedifferencebetweenaskandask-concurrent,considerthefollowingtwocommands:
ask turtles [ fd 5 ]
ask-concurrent turtles [ fd 5 ]
Withask,thefirstturtletakesfivestepsforward,thenthesecondturtletakesfivestepsforward,andso
on.
Withask-concurrent,alloftheturtlestakeonestepforward.Thentheyalltakeasecondstep,andso
on.Thus,thelattercommandisequivalentto:
repeat 5 [ ask turtles [ fd 1 ] ]
CodeExample:Ask-ConcurrentExampleshowsthedifferencebetweenaskandask-
concurrent.
Thebehaviorofask-concurrentcannotalwaysbesosimplyreproducedusingask,asinthisexample.
Considerthiscommand:
ask-concurrent turtles [ fd random 10 ]
Inordertogetthesamebehaviorusingask,wewouldhavetowrite:
turtles-own [steps]
ask turtles [ set steps random 10 ]
while [any? turtles with [steps > 0]] [
ask turtles with [steps > 0] [
fd 1
set steps steps - 1
]
]
Toprolonganagent’s“turn”,usethewithout-interruptioncommand.(Thecommandblocksinside
somecommands,suchascreate-turtlesandhatch,haveanimpliedwithout-interruptionaround
them.)
Notethatthebehaviorofask-concurrentiscompletelydeterministic.Giventhesamecodeandthe
sameinitialconditions,thesamethingwillalwayshappen(ifyouareusingthesameversionofNetLogo
andbeginyourmodelrunwiththesamerandomseed).
Ingeneral,wesuggestyounotuseask-concurrentatall.Ifyoudo,wesuggestyouwriteyourmodelso
thatitdoesnotdependontheexactdetailsofhowask-concurrentworks.Wemakenoguaranteesthat
itssemanticswillremainthesameinfutureversionsofNetLogo,orthatitwillcontinuetobesupported
atall.
UserInteractionPrimitives
NetLogofeaturesseveralprimitiveswhichallowamodeltointeractwiththeuser.Theseprimitives
includeuser-directory,user-file,user-new-file,user-input,user-message,user-one-of,anduser-yes-or-
no?.
Theseprimitivesdifferinpreciselywhatinteractiontheytakewiththeuser.user-directory,user-file,
anduser-new-fileareallreporterswhichprompttheusertoselectanitemfromthefilesystemand
reportthepathoftheselecteditemtoNetLogo.user-yes-or-no?,user-one-of,anduser-inputall
prompttheusertoprovideinputintheformoftextoraselection.user-messagesimplypresentsa
messagetotheuser.
Notethatallactiveforeverbuttonswillpausewhenoneoftheseprimitivesisusedandwillresumeonly
whentheusercompletestheinteractionwiththebutton.
Whatdoes“Halt”mean?
Theprimitiveswhichprompttheuserforinput,aswellasuser-messageallprovidea“Halt”button.The
effectofthisbuttonisthesameforalloftheseprimitives-ithaltsthemodel.Whenthemodelishalted
allrunningcodeisstopped,includingbuttonsandthecommandcenter.Sincehaltingstopscodeinthe
middleofwhateverithappenedtobedoingatthetimeitwashalted,youmayseestrangeresultsifyou
continuetorunthemodelafterahaltwithoutsettingitupagain.
Tie
Tieconnectstwoturtlessothatthemovementofoneturtlesaffectsthelocationandheadingofanother.
Tieisapropertyoflinkssotheremustbealinkbetweentwoturtlestocreateatierelationship.
Whenalink’stie-modeissetto“fixed”or“free”end1andend2aretiedtogether.Ifthelinkisdirected
end1isthe“rootagent”andend2isthe“leafagent”.Thatiswhenend1moves(usingfd,jump,setxy,etc.)
end2alsomovesthesamedistanceanddirection.Howeverwhenend2movesitdoesnotaffectend1.
Ifthelinkisundirecteditisareciprocaltierelationship,meaning,ifeitherturtlemovestheotherturtle
willalsomove.Sodependingonwhichturtleismovingeitherturtlecanbeconsideredtherootorthe
leaf.Therootturtleisalwaystheturtlethatinitiatesthemovement.
Whentherootturtleturnsrightorleft,theleafturtlerotatesaroundtherootturtlethesameamountasif
astiffwereattachingtheturtles.Whentie-modeissetto“fixed”theheadingoftheleafturtlechangesby
thesameamount.Ifthetie-modeissetto“free”theheadingoftheleafturtleisunchanged.
Thetie-modeofalinkcanbesetto“fixed”usingthetiecommandandsetto“none”(meaningthe
turtlesarenolongertied)usinguntietosetthemodeto“free”youneedto:set tie-mode "free".
CodeExample:TieSystemExample
Multiplesourcefiles
The__includeskeywordallowsyoutousemultiplesourcefilesinasingleNetLogomodel.
Thekeywordbeginswithtwounderscorestoindicatethatthefeatureisexperimentalandmaychange
infutureNetLogoreleases.
Whenyouopenamodelthatusesthe__includeskeyword,orifyouaddittothetopofamodelandhit
theCheckbutton,theincludesmenuwillappearinthetoolbar.Fromtheincludesmenuyoucanselect
fromthefilesincludedinthismodel.
Whenyouopenincludedfilestheyappearinadditionaltabs.SeetheInterfaceGuideformoredetails.
Youcanhaveanythinginexternalsourcefiles(.nls)thatyouwouldnormallyputintheCodetab:
globals,breed,turtles-own,patches-own,breeds-own,proceduredefinitions,etc.Notethoughthatthese
declarationsallsharethesamenamespace.Thatis,ifyoudeclareaglobalmy-globalintheCodetab
youcannotdeclareaglobal(oranythingelse)withthenamemy-globalinanyfilethatisincludedinthe
model.my-globalwillbeaccessiblefromalltheincludedfiles.Thesamewouldbetrueifmy-globalwere
declaredinoneoftheincludedfiles.
Syntax
Colors
IntheCodetabandelsewhereintheNetLogouserinterface,programcodeiscolor-codedbythe
followingscheme:
Keywordsaregreen
Constantsareorange
Commentsaregray
Primitivecommandsareblue
Primitivereportersarepurple
Everythingelseisblack
Notice
Theremainderofthissectioncontainstechnicalterminologywhichwillbeunfamiliartosomereaders.
Keywords
Theonlykeywordsinthelanguageareglobals,breed,turtles-own,patches-own,to,to-report,andend,
plusextensionsandtheexperimental__includeskeyword.(Built-inprimitivenamesmaynotbe
shadowedorredefined,sotheyareeffectivelyakindofkeywordaswell.)
Identifiers
Allprimitives,globalandagentvariablenames,andprocedurenamesshareasingleglobalcase-
insensitivenamespace;localnames(letvariablesandthenamesofprocedureinputs)maynotshadow
globalnamesoreachother.IdentifiersmaycontainanyUnicodeletterordigitandthefollowingASCII
characters:
.?=*!<>:#+/%$_^'&-
Someprimitivenamesbeginwithtwounderscorestoindicatethattheyareexperimentalandare
especiallylikelytochangeorberemovedinfutureNetLogoreleases.
Scope
NetLogoislexicallyscoped.Localvariables(includinginputstoprocedures)areaccessiblewithinthe
blockofcommandsinwhichtheyaredeclared,butnotaccessiblebyprocedurescalledbythose
commands.
Comments
Thesemicoloncharacterintroducesacomment,whichlastsuntiltheendoftheline.Thereisnomulti-
linecommentsyntax.
Structure
Aprogramconsistsofoptionaldeclarations(globals,breed,turtles-own,patches-own,<BREED>-own,
extensions)inanyorder,followedbyzeroormoreproceduredefinitions.Multiplebreedsmaybe
declaredwithseparatebreeddeclarations;theotherdeclarationsmayappearonceonly.
Everyproceduredefinitionbeginswithtoorto-report,theprocedurename,andanoptionalbracketed
listofinputnames.Everyproceduredefinitionendswithend.Inbetweenarezeroormorecommands.
Commandsandreporters
Commandstakezeroormoreinputs;theinputsarereporters,whichmayalsotakezeroormoreinputs.
Nopunctuationseparatesorterminatescommands;nopunctuationseparatesinputs.Identifiersmustbe
separatedbywhitespaceorbyparenthesesorsquarebrackets.(Soforexample,a+bisasingle
identifier,buta(b[c]d)econtainsfiveidentifiers.)
Allcommandsareprefix.Alluser-definedreportersareprefix.Mostprimitivereportersareprefix,but
some(arithmeticoperators,booleanoperators,andsomeagentsetoperatorslikewithandin-points)are
infix.
Allcommandsandreporters,bothprimitiveanduser-defined,takeafixednumberofinputsbydefault.
(That’swhythelanguagecanbeparsedthoughthereisnopunctuationtoseparateorterminate
commandsand/orinputs.)Someprimitivesarevariadic,thatis,mayoptionallytakeadifferentnumber
ofinputsthanthedefault;parenthesesareusedtoindicatethis,e.g.(list 1 2 3)(sincethelist
primitiveonlytakestwoinputsbydefault).Parenthesesarealsousedtooverridethedefaultoperator
precedence,e.g.(1 + 2) * 3 ,asinotherprogramminglanguages.
Sometimesaninputtoaprimitiveisacommandblock(zeroormorecommandsinsidesquarebrackets)
orareporterblock(asinglereporterexpressioninsidesquarebrackets).User-definedproceduresmay
nottakeacommandorreporterblockasinput.
Operatorprecedencesareasfollows,hightolow:
with,at-points,in-radius,in-cone
(allotherprimitivesanduser-definedprocedures)
^
*,/,mod
+,-
<,>,<=,>=
=,!=
and,or,xor
ComparedtootherLogos
Thereisnoagreed-uponstandarddefinitionofLogo;itisaloosefamilyoflanguages.Webelievethat
NetLogohasenoughincommonwithotherLogostoearntheLogoname.Still,NetLogodiffersinsome
respectsfrommostotherLogos.Themostimportantdifferencesareasfollows.
Surfacedifferences
Theprecedenceofmathematicaloperatorsisdifferent.Infixmathoperators(like+,*,etc.)have
lowerprecedencethanreporterswithnames.Forexample,inmanyLogos,ifyouwritesin x + 1,
itwillbeinterpretedassin (x + 1).NetLogo,ontheotherhand,interpretsitthewaymostother
programminglanguageswould,andthewaythesameexpressionwouldbeinterpretedin
standardmathematicalnotation,namelyas(sin x) + 1.
Theandandorreportersarespecialforms,notordinaryfunctions,andthey“shortcircuit”,thatis,
theyonlyevaluatetheirsecondinputifnecessary.
ProcedurescanonlybedefinedintheCodetab,notinteractivelyintheCommandCenter.
Reporterprocedures,thatis,proceduresthat“report”(return)avalue,mustbedefinedwithto-
reportinsteadofto.Thecommandtoreportavaluefromareporterprocedureisreport,not
output.
Whendefiningaprocedure,theinputstotheproceduremustbeenclosedinsquarebrackets,e.g.
to square [x].
Variablenamesarealwaysusedwithoutanypunctuation:alwaysfoo,never:fooor"foo.(To
makethiswork,insteadofamakecommandtakingaquotedargumentwesupplyasetspecial
formwhichdoesnotevaluateitsfirstinput.)Asaresult,proceduresandvariablesoccupyasingle
sharednamespace.
Thelastthreedifferencesareillustratedinthefollowingproceduredefinitions:
mostLogos NetLogo
to square :x
output :x * :x
end
to-report square [x]
report x * x
end
Deeperdifferences
NetLogo’slocalvariablesandinputstoproceduresarelexicallyscoped,notdynamicallyscoped.
NetLogohasno“word”datatype(whatLispcalls“symbols”).Eventually,wemayaddone,but
sinceitisseldomrequested,itmaybethattheneeddoesn’tarisemuchinagent-basedmodeling.
Wedohavestrings.InmostsituationswheretraditionalLogowouldusewords,wesimplyuse
stringsinstead.ForexampleinLogoyoucouldwrite[see spot run](alistofwords),butin
NetLogoyoumustwrite"see spot run"(astring)or["see" "spot" "run"](alistofstrings)
instead.
NetLogo’sruncommandworksonanonymousproceduresandstrings,notlists(sincewehaveno
“word”datatype),anddoesnotpermitthedefinitionorredefinitionofprocedures.
Controlstructuressuchasifandwhilearespecialforms,notordinaryfunctions.Youcan’tdefine
yourownspecialforms,soyoucan’tdefineyourowncontrolstructures.(Youcandosomething
similarusinganonymousprocedures,butyoumustusethe->,run,andrunresultprimitivesfor
that,youcannotmakethemimplicit.)
Anonymousprocedures(akafunctionvaluesorlambda)aretruelexically-scopedclosures.This
featureisavailableinNetLogoandinmodernLisps,butnotinstandardLogo.
Ofcourse,theNetLogolanguagealsocontainsotherfeaturesnotfoundinmostLogos,mostimportantly
agentsandagentsets.
TransitionGuide
NetLogo6.0.4UserManual
ManymodelscreatedinearlierversionsofNetLogoalsoworkinNetLogo5.0.However,
somemodelswillneedchanges.Ifanoldmodelisn’tworking,thissectionoftheUserManual
maybeabletohelpyou.
WhatissuesmayarisedependsonwhatversionofNetLogothemodelwascreatedwith.
Thisguideonlycoverschangesmostlikelytocauseissuesforusers.Seethereleasenotes
formorecompletedetailsondifferencesbetweenversions.
ChangesforNetLogo6.0.3
ArduinoExtensionChanges
ThearduinoextensionhassubstantiallychangedthewayitreceivesvaluesfromArduino
boards.Pleaseconsultthearduinoexamplesketch(includedwithinthe“models”folderunder
Chapter8oftheIABMtextbook)foranupdatedsketchcompatiblewiththeArduinoexample
model.Ifyouhaveanexistingarduinosketch,youwillneedtoadjusttheformatusedtosend
valuestoNetLogo.Oldsketcheswillhavecodewhichsendsbackmessageslike“;A,2.5;”.For
thenewversionofthearduinoextensiontoreceivethesamemessage,sketchesshould
send“;A,D,2.5;”instead.Theadded‘D,’informsNetlogothatthevaluebeingsentisa
numberandnotastring.
CFExtensionChanges
Allprimitiveshavebeenremovedfromthecfextensionandreplacedbythecf:ifelseand
cf:ifelse-valuemulti-branchprimitives.Weencourageexistingcfuserstoadjusttheircode
tousethesenewprimitives.Overtime,wehopetousetheseprimitivesasanexampleon
whichtoremodelNetLogo’sexistingifelseandifelse-valueprimitives.Becausethiswould
bearelativelylargelanguagechange,wewouldlovetohearanyfeedbackaddressyoumay
havefromusingthesecfextensionprimitives.
ChangesforNetLogo6.0
TasksreplacedbyAnonymousProcedures
InNetLogo6.0,taskshavebeenreplacedbyanonymousprocedures.Thismeansthattaskis
nolongeraprimitive,it’sbeenreplacedbythenewarrowsyntaxforcreatinganonymous
procedures.Similarly,questionmarkvariableslike?,?1,and?2arenowjustordinarynames
inNetLogoandcanbeusedtonameprocedurevariables,letvariables,oranonymous
procedurevariables.Finally,is-reporter-task?andis-command-task?havebeenreplacedby
is-anonymous-reporter?andis-anonymous-command?.
Tomakethistransitioneasier,we’veaddedanautomaticconversionstepwhichshouldallow
mostmodelssavedinNetLogo5tobeconvertedtousethenewsyntaxautomatically.The
autoconverterhasbeenasubstantialpieceofeffortandwe’vetesteditonallthemodelsin
themodelslibrary.Touseit,ensurethemodelcompilesandrunproperlyinNetLogo5or
later,thensaveitfromNetLogo5orlater.Then,simplyopenthemodelinNetLogo6.Ifall
goeswell,you’llseetheconverterhaschangedcodeliketask [?1 + ?2] to[ [?1 ?2] -> ?1
+ ?2 ].Thequestionmarksaremeanttoserveastemporaryplaceholdersforconversion.
Theyenableyourmodeltorun,butyoucan(andshould)replacethesevariableswith
meaningfulnames.Ifyouopenamodelwithtasksandithasnotbeenconverted,the
autoconverterwasn’tabletoconvertyourmodel.Ratherthanattempttoautoconvertyour
modelandbreaksomething,themodelwillopen,youwillbeshowntheappropriateerrors
andgivenachancetoedityourmodel.
Whilewehavetestedtheautoconverterthoroughly,weexpecttheretobesomecasesit
doesn’tcover.
Ifyoumakeuseofextensionsthataren’tyetcompiledforNetLogo6,theautoconverter
willnotworkuntilthoseextensionshavebeenupdated.
Ifyourcodeusesrunorrunresulttoevaluatestringscontainingtasks,the
autoconverterwillnotchangethosestringstobeanonymousprocedures.Tomakerun
andrunresultworkasexpected,lookatstringsinyourmodelandchangeanywhich
relyontaskor?-variablestoinsteadrelyonanonymousprocedures
Ifyourmodeldoesn’tfallintotheabovecategoriesanddoesn’tconvertorconverts
incorrectly,pleaseemailourfeedbackaddressandwe’llbehappytoofferwhatever
assistancewecan.
Linkreportersoverhauledtobemoreconsistentandflexible
InpreviousversionsofNetLogo,linkreportershavehadanumberofinconsistencies
regardingdirectedandundirectedlinks.Forexample,my-linkswouldreportalllinks
connectedtoaturtle,whereaslink-neighborswouldonlyreportneighborsconnectedby
undirectedlinks.Furthermore,itwasquitedifficulttoworkwithmodelswherethelinkscould
eitherbedirectedorundirected.
Toalleviatetheseissues,thelinkprimitiveshavebeenoverhauledin6.0.Thesechanges
onlyaffectexistingmodelsthatusebothdirectedandundirectedlinkswhilealsousingthe
unbreededlinkprimitives.
Thechangesareasfollows:
Linkreportersthatcontaintheword“out”nowutilizebothdirected,outgoinglinksand
undirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogetfromthecurrent
nodetoothernodes.Forexample,out-link-neighbor?willreporttrueifthecurrent
turtleisconnectedtothegiventurtlebyeitheranoutgoingdirectedlinkoranundirected
link.Ifyouonlywantdirected,outgoinglinks,youcanuseabreed-specificreporteror
my-out-links with [ is-directed? self ].Generally,whenworkingwithmodelsthat
havebothdirectedandundirectedlinks,youwillprobablywanttousethe“out”
primitivesformostthingsnow.
Linkreportersthatcontaintheword“in”nowutilizebothdirected,incominglinksand
undirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogettothecurrent
nodefromothernodes.Forexample,in-link-neighbor?willreporttrueifthecurrent
turtleisconnectedtothegiventurtlebyeitheranincomingdirectedlinkoranundirected
link.Ifyouonlywantdirected,incominglinks,youcanuseabreed-specificreporteror
my-in-links with [ is-directed? self ].
Linkreportersthatdonotspecify“out”or“in”utilizealllinks.
Furthermore,therearenolongerrestrictionsregardingwhichreporterscanbeusedwith
whichbreeds.Forunbreededlinks,thismakesitpossibletousethesameprimitives
regardlessofwhetheryournetworkendsupbeingdirectedorundirected.
Thenewbehavior(includingallchangedprimitives)issummarizedbythefollowingtable,
Oracle,thecompanybehindJava,hasannouncedthatJavaappletsaredeprecated(seethis
blogpostformoreinformation).Thiscomesasthemajorbrowsershaveremovedsupportfor
plug-ins(likejavaapplets)orannouncedthattheyplantodoso.
Insteadofusingappletstodistributeyourmodel,NetLogoofferstheoptiontoexportto
NetLogoWeb.WhileNetLogoWebdoesn’tyetofferthefullfunctionalityofdesktopNetLogo
(inparticular,extensionsaren’tsupported),itisnowcapableofrunningmostofthemodelsin
theNetLogomodelslibraryandwehopethatmostmodeldistributorswillfindthatitmeets
theirneeds.ToexporttoNetLogoWeb,choosethe“SaveAsNetLogoWeb”optionfromthe
“File”menu.
ChangestotheNetLogoUserInterface
UserswillnoticeseveraltweakstotheNetLogoUserinterfacewhenopeningNetLogo6for
thefirsttime.We’veremovedthebarborderabovetheview.Toopenthe3DViewin6.0,you
canrightclickontheviewandchoose“Switchto3DView”,orchoosethesameoptionfrom
the“Tools”menu.Ticksarenowdisplayedintheinterfacetabtoolbarbeneaththespeed
slider.Toadjustthelabelusedfor“ticks”andotherviewproperties,youcanchoosethe
“Settings”buttonatthefarrightoftheinterfacetabtoolbarorright-clickontheviewand
choose“Edit…”fromthecontextmenuthatappears.
NobodyNotPermittedasaChooserValue
InNetLogo6.0,nobodyisnolongeravalidchooservalue.Justasyoucan’tputturtle 0or
turtles,nobodyreferstoanon-literalvaluewhichisn’tsupportedinchoosers.Aspartofthis
transition,chooserscontainingnobody(ornobodywithinanestedlist)willhaveallusesof
nobodychangedto"nobody"whenopenedinNetLogo6.0.
Breedsmusthavesingularandpluralnames
InNetLogo6.0,youmustspecifybothpluralandsingularbreednames.Inpriorversions,
declarationslikebreed [mice]werelegal,butthissupporthasbeenremovedin6.0.Ifyou
havemodelswhichuseonlypluralbreednames,itisrecommendedthatyouconvertthemto
specifybothnamesbeforeopeningin6.0sincedoingsowillpermittheNetLogoconverterto
workmosteffectivelyonanyothercodeinyourmodelwhichneedsconversion.
Removalof“Movie”Prims
TheNetLogomovieprimshadn’tbeenupdatedinquitesometimeandgeneratedinvalid
quicktimemoviefiles.Theyhavebeenreplacedbyprimsinthenewvidextension.Thefull
documentationforthevidextensionisavailableintheVidExtensionsectionofthemanual.
Aswithallextensions,userswillneedtoincludevidintheextensionssectionoftheir
NetLogomodel.
Manyofthemovieprimitiveshavedirectparallelsinthevidextensionwhichcanbefoundin
thefollowingtable:
movieprim vidprim
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
movieprim vidprim
WhenyoufirstopenafileinNetLogo6.0,yourfilewillbeautomaticallyconvertedtousethe
newprimitives.Thiswillincludeaddinganewglobalvariable-_recording-save-file-nameto
trackthenameoftheactiverecording,aswellasaddingthevidextensiontothemodel.You
shouldverifythattheconversiontookplacecorrectly.Thereisnoreplacementformovie-set-
frame-rate.Thevidextensionrecordsframesat25persecond,slightlymorethanthedefault
15frames-per-secondofthemovieprims.Ifyourrecordingissensitivetoframerate,consider
recordingeachexistingframetwice(2/25isfairlycloseto1/15)orconsiderusinga
postprocessingtool(likegstreamerorffmpeg)toadjustthevideoplaybackspeed.
ImprovedNameCollisionDetection
InNetLogo6.0,expandederror-checkingintheNetLogocompilercausesmodelswhich
defineundirected-link-breed [ undirected-links undirected-link ] and/ordirected-
link-breed [ directed-links directed-link ]toerrorforredefiningaprimitivereporter
(eitheris-directed-link?oris-undirected-link?).Ifyourmodeldoesn’tuseis-directed-
link?oris-undirected-link?atall,simplychangingthebreednamesshouldresolvethe
error.
Ifyouusedeitheroftheis-<directedness>-link?prim,thereareseveralwaysyoumight
modifyyourmodeltoaccountforthischange.Ifyourmodelhasnootherbreededlinks,
considerremovingthelinkbreedandusingthebuilt-inlinkprimitives.Ifyourmodelhasother
breededlinks,butonlyofdifferentdirectedness,simplychangingthebreedname(andall
relatedprimitivenames)shouldresolvetheproblem.Notethatinthiscaseis-directed-link?
and/oris-undirected-link?continuetobehavethesameasbefore.Ifyourmodelhasother
breededlinksofthesamedirectedness,thechangewillvarydependingonyourmodel.The
breedname(s)mustbechanged,butyoumustdecidewhetheryouusedis-directed-link?/
is-undirected-link?tochecklinkdirectednessortocheckthatlinkbreedmembership.Ifyou
usedittochecklinkdirectednessleavingitas-isshouldkeepthecurrentbehaviorofthe
model.Otherwise,itcansimplybereplacedbyis-<breed>?.
Removalofhubnet-set-client-interface
Thehubnet-set-client-interfaceprimitivewasrenderedobsoletebytheintroductionofthe
HubNetclienteditorandendofsupportforcalculatorHubNet.Wehavefounditusedinvery
fewmodelsandhavedecidedtoremoveitfromthelanguage.Onopeninganexistingmodel
in6.0,theautoconvertershouldremoveallusesofhubnet-set-client-interfacefromyour
code.
Improved&UpdatedExtensionsAPI
OneofourgoalsinNetLogo6.0hasbeentomakeiteasiertodevelopextensionsandeasy
todevelopmorepowerfulextensions.Tothatend,we’vebumpedtheextensionAPIfrom5.0
to6.0.Existingextensionswillneedtorecompilechangingthe“NetLogo-Extension-API-
Version”intheirjar’sMANIFEST.MFfrom5.0to6.0.
Someofthechangeswe’vemadetotheextensionsAPIinclude:
org.nlogo.api.Contextnowallowsaccesstothecurrentworldandworkspaceobjects
withoutrequiringacasttoanorg.nlogo.nvm.ExtensionContext.
org.nlogo.api.WorkspacehasbeenintroducedasastableAPIforextensionstodepend
on.
ANetLogojarisnowavailablefromBinTray.
Forafulllistofchangesbetween5.0and6.0,pleasevisitourExtensionTransitionGuideon
GitHub.
Inserviceofmakingiteasiertobuildextensions,we’veexpandedandimprovedtheNetLogo
ExtensionPluginforsbt,theScalaBuildTool.SbtisapowerfultoolforbuildingJVMprojects
andcanbeusedinprojectsthatuseScala,Java,oracombinationofthetwo.We’renow
usingtheExtensionPlugintobuildallofthebundledextensionsandwestronglyrecommend
extensionauthorstakeadvantageofthepluginasitmakesconfiguringaNetLogoextension
buildextremelystraightforward.ThepluginhandlesfetchingtheNetLogojarwhichextensions
compileagainstaswellasgenerationofajarfortheextensioncontainingtheappropriate
metadata.
Addrangeprimitive
AnewrangeprimitivewasaddedinNetLogo6.As“range”mayappearinexistingmodelsas
aprocedureorvariablename,wehaveaddedanautoconversionstepwhichwillensurethat
thesemodelscontinuetooperateimmediatelyuponopeninginNetLogo6.Existingusesof
rangeinmodelsauthoredbeforeNetLogo6willbeconvertedto_rangeuponfirstopeningin
NetLogo6.Oncethemodelopens,youcanrename_rangetosuityourmodel.
ChangesforNetLogo5.2
hsbprimitives
In5.2,thehsbprimitiveshavebeenchangedtoworkwiththestandardscalevaluesof360
forhue,and100forsaturationandbrightness.Thisaffectstheprimitiveshsb,extract-hsb
andapproximate-hsb.
Theoldprimitives,scaledto255,areautomaticallytransitionedtoandhavebeenrenamed
__hsb-old,__extract-hsb-oldand__approximate-hsb-old.
GoGoextension
TheGoGoextensionhasbeenupgradedtousenewerGoGoboardswiththeHIDinterface.
Manyoftheolderprimitivesnolongerwork,andwillalertyoutoupgradingyourGoGo
board’sfirmware.
Ifyouneedtocontinuetouseaserialinterface,youcanusethebundledgogo-serial
extension.Changeyourmodeltousegogo-serialasopposedtogogo.Moredetailshere.
IfyoucannotupgradetousethenewHIDextensionnorthenewserialextension,theoriginal
extensioncanbefoundathttps://github.com/NetLogo/GoGo-RXTX-Extension
ChangesforNetLogo5.0
Plotting
In5.0,youdon’thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanput
itinsidetheplotsthemselves,intheInterfacetab.
Nonetheless,theoldstyleandalloftheexistingplottingprimitivesarestillsupported.We
recommendchangingyourmodeltousethenewstyle,butifyoudon’t,itshouldstillwork.
Thefollowingexampleshowshowtochangeamodeltousethenewstyle.Supposeyou
haveatypicalNetLogo4.1modelwithoneplotcalled“populations”andtwopenscalled
“robots”and“humans”.Theoldcodemightlooklike:
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
Herearethestepstomakethetransition:
Copytheplot count robotscommandandpasteitintotheUpdateCommandsfieldfor
therobotspenintheploteditdialog.Removeitfromthedo-plottingprocedure.
Theplot count humanscommandcanbemovedinthesamewayforthehumanspen.
Afterthoselinesareremovedfromthedo-plottingprocedure,itdoesn’tactuallydo
anythinganymore!Removeit.
Thefinalstepistoreplacethedo-plottingprocedurecallsinsetupandgo.Insetup,the
do-plottingcallshouldbechangedtoreset-ticks.Ingo,thedo-plottingcallshouldbe
changedtotick.reset-ticksandtickwillbothcauseplottingtohappenautomatically.
Theresulting(muchsimpler)codelookslikethis:
to setup
clear-all
...
reset-ticks
end
to go
...
tick
end
FormoredetailsonhowplottingworksinNetLogo5.0,seethePlottingSectionsofthe
ProgrammingGuideandtheInterfaceGuide.Fordetailsonhowplottinginteractswiththetick
counter,readon.
Tickcounter
Thewaythetickcounterworkshaschangedin5.0.Insteadofbeinginitiallysetto0,thetick
counterisinitiallyblank.
reset-ticks
Youmustusereset-tickstostartthetickcounterat0beforeusingticks,tickortick-
advanceforthefirsttime.
reset-ticksshouldgoattheendofyoursetupprocedure.Puttingittherewillallowyour
modeltoworkwith5.0’snewplottingfeatures.
reset-ticksandplotting
In5.0,youdon’thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanput
itinsidetheplotsthemselves,intheInterfacetab.Codeinsideplotsistriggeredbyreset-
ticksandtick.Resettingthetickcounterrunsplotsetupcode,andthenitalsorunsplot
updatecodetoplottheinitialstateofthemodel.Theinitialstateofthemodelwon’tbein
placeuntiltheendofsetup,sothat’swhyreset-ticksshouldgoattheend.
__clear-all-and-reset-ticks
InorderformodelsfrompreviousNetLogoversionstoworkin5.0withoutchanges,whenan
oldmodelisopenedin5.0,anyoccurrencesofclear-all(orca)areautomaticallychangedto
__clear-all-and-reset-ticks,whichcombinestheeffectsofclear-allandreset-ticks.The
twounderscoresonthenameindicatethatthisisnotanormalprimitive,butexistsonlyfor
backwardscompatibility.
Youshouldremove__clear-all-and-reset-ticksfromyourcode,replaceitwithclear-all,
andputreset-ticksattheendofyoursetupprocedure.(Thisdoesn’thappenautomatically
becausethestructureofNetLogomodelsistoofree-formforanautomaticconverterto
reliablymakethechangeforyou.)
Unicodecharacters
NetLogo5.0fullysupportsinternationalcharacterscross-platform,usingtheUnicode
characterset.NetLogo5.0modelfilesalwaysrepresentUnicodecharactersusingtheUTF-8
encoding.
PreviousversionsofNetLogoallowedUnicodecharacterstobeusedinsomecontexts.
However,modelfilesweresavedintheplatform’sdefaultencoding,whichonmostsystems
wassomethingotherthanUTF-8.Characterswerehandledcorrectlyonthesameplatform
(e.g.twoWindowsmachines),butcouldbealteredifthemodelwasmovedbetween
platforms(e.g.fromWindowstoMacorviceversa).
WhenopeninganexistingmodelinNetLogo5.0,ifthemodelcontainsinternationalorother
non-ASCIIcharacters,thecharactersmaybeinterpretedincorrectly,becausetheywere
originallywritteninaplatform-specificencoding,butthenreadbackininUTF-8.
Ifonlyafewcharactersareaffected,youmightfinditeasiestjusttofixthemmanually.
Butifyouexpectalargenumberofcharacterstobeaffected,andyouwantthemtranslated
automatically,youcanuseathirdpartyutilitytore-encodeyour.nlogofilefromitsoriginal
encodingintoUTF-8.Afterconversion,openthemodelinNetLogo5.0andallcharacters
shouldbecorrect.
Infotabs
NetLogo5.0usestheMarkdownmarkuplanguagetoallowyoutoformatyourInfotab,
includingheaders,boldanditalics,images,andsoforth.
EarlierversionsofNetLogousedacustommarkuplanguagewithmuchmorelimited
capabilities.
Whenopeningamodelfromanolderversion,NetLogo5.0translatesyouroldmarkupinto
Markdown.Mostofthetimethisproducesgoodresults,butyoumaywanttocheckthe
resultsyourselfandmakesurethatyourInfotabstilllooksgood.
Modelspeed
InNetLogo5.0everymodelhasa“targetframerate”whichaffectsthedefaultspeedatwhich
themodelruns,whenthespeedsliderisinthemiddle,onthe“normalspeed”setting.
Thedefaulttargetframeratefornewmodels,andformodelsthatwerecreatedinearlier
versionsofNetLogo,is30framespersecond.Ifyouareusingtick-basedupdates,aswe
recommendformostmodels,thenthattranslatesto30tickspersecond.
Ifyourmodelrunsslowerin5.0thanitranin4.1,it’sprobablyjustbecauseitsspeedisbeing
limitedbythisrate.Ifyouwant,youcanpresstheSettingsbuttonintheInterfacetaband
changetheframeratetoahighernumber.
Someoldmodelsusedtheeverycommandtosetadefaultspeed.Inmostcasethiscanbe
nowremovedfromthecode,andthetargetframeratesettingusedinstead.
Listperformance
TheunderlyingdatastructureforNetLogolistshaschanged.
InNetLogo4.1,aNetLogolistwasrepresentedinternallyasasinglylinkedlist.Some
operationsonsinglylinkedlistsarefast(suchasfirstandbutfirst)butothersareslow
becausetheycouldrequiretraversingthewholelist(suchasitemandlast).
InNetLogo5.0,listsarenowactuallytreesinternally.Asaresult,someoperationsarealittle
slower,butotheroperationsaredrasticallyfasteronlonglists.SeetheListssectionofthe
ProgrammingGuidefordetails.
Somemodelsmayrunalittleslowerwiththenewdatastructure,especiallyifyoumake
heavyuseofshortlists.Butothermodelswillrunfaster–perhapsdramaticallyfaster.
Somespecialwaysofwritinglist-processingcodethatwereusefulinNetLogo4.1areno
longerneededin5.0.Forexample,sincein4.1fputwasfastandlputwasslow,modelers
sometimesbuiltuplistsinreverseorderusingfput,perhapscallingreverselatertorestore
theintendedorder.InNetLogo5.0,youdon’tneedtocodethatwayanymore.fputandlput
arethesamespeed.
ExtensionsAPI
Ifyouaretheauthorofanextension,youwillneedtorecompileitagainstthe5.0NetLogo.jar
andlibdirectoryforittoworkwith5.0.
Youmayalsoneedtobeawareofthefollowingchanges:
Syntaxconstants
Thecodeforspecifyingthesyntaxofaprimitivehaschangedslightly,forexample
Syntax.TYPE_STRINGisnowSyntax.StringType().(FromJava,thepairofparenthesesatthe
endisrequired.InScala,youcanomitthem.)
LogoListconstruction
Onesignificantchangeisthatorg.nlogo.api.LogoListnolongerhasapublicconstructor.
Instead,therearetwonewwaystoconstructaLogoList.
Ifyouhaveajava.lang.Iterable,youcancopythecontentsintoafreshLogoListbypassing
ittothestaticmethodLogoList.fromJava().Seethearrayextensionsourcecodefora
sampleusage.
Or,tobuildupanewlistoneitematime,useorg.nlogo.api.LogoListBuilder.The
ExtensionsGuidehassamplecodeshowingtheuseofLogoListBuilder.
Primitiveclasses
InpriorNetLogoversions,theextensionsAPIrequiredthateachextensionprimitivehaveits
ownseparatetop-levelclasswithano-argumentconstructor.Theselimitationshavenow
beenlifted.Also,api.Primitiveobjectsarenowmadeonlyonce,whentheextensionis
loaded,insteadofeverytimetheCodetabwasrecompiled.
ChangesforNetLogo4.1
Combiningsetandof
Thefollowingsyntaxisnolongersupported:
set [<variable>] of <agent> <value>
Commandsofthisformmustberewrittenusingask:
ask <agent> [ set <variable> <value> ]
Or,ifthenewvaluemustbecomputedbytheaskingagentandnotbytheagentwhose
variableisbeingset:
;; 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 ]
Soforexample,this:
set [color] of turtle 0 red
Canberewrittenas:
ask turtle 0 [ set color red ]
Itisnotnecessarytouseletormyselfsinceredisredfromthepointofviewofbothagents.
However,this:
set [color] of turtle 0 color
Mustberewrittenas:
let new-color color
ask turtle 0 [ set color new-color ]
or
ask turtle 0 [ set color [color] of myself ]
inordernottochangethemeaning,sincethetwoagentsmayhavedifferentstartingvalues
forcolor.Theformusingmyselfisbriefer,buttheformerusingletmaybeconsidered
clearer,dependingoncontextandindividualpreference.
ChangesforNetLogo4.0
Whonumbering
PriortoNetLogo4.0,adeadturtle’swhonumber(storedinthewhoturtlevariable)couldbe
reassignedtoalaternewbornturtle.InNetLogo4.0,whonumbersareneverreuseduntilwho
numberingisresetto0bytheclear-allorclear-turtlescommand.Thischangeinbehavior
maybreakafewoldmodels.
Turtlecreation:randomizedvs.“ordered”
NetLogo4.0providestwodifferentobservercommandsforcreatingturtles,create-turtles
(crt)andcreate-ordered-turtles(cro).
crtgivesthenewturtlesrandomcolorsandrandomintegerheadings.croassignscolors
sequentiallyandgivestheturtlessequentialequallyspacedheadings,withthefirstturtle
facingnorth(headingof0).
PriortoNetLogo4.0,thecrtcommandbehavedthewaycrodoesnow.Ifyouroldmodel
dependsonthe“ordered”behavior,youwillneedtochangeyourcodetousecroinsteadof
crt.
Itiscommonforoldmodelsthatusedcrttocontainextracommandstorandomizethenew
turtles’headings,forexamplert random 360orset heading random 360.Thesecommands
arenolongernecessarywhenusedinsidecrt.
Addingstringsandlists
PriortoNetLogo4.0,the+(addition)operatorcouldbeusedtoconcatenatestringsandjoin
lists.IncurrentNetLogo,+onlyworksonnumbers.Toconcatenatestrings,usetheword
primitive;tojoinliststogether,usethesentenceprimitive.Thislanguagechangewasmadeto
increasethespeedofcodethatuses+.
Oldcode:
print "There are " + count turtles + " turtles."
Newcode:
print (word "There are " count turtles " turtles.")
Likewise,ifyouneedtoconcatenatelists,useSENTENCE.
Thischangeisnothandledautomaticallywhenconvertingoldmodels;userswillneedto
changetheircodebyhand.
Weknowthischangewillbeawkwardforuserswhoareusedtotheoldsyntax.Wehave
madethischangeforefficiencyandconsistency.Wecanimplementanadditionoperatorthat
onlyaddsnumbersmuchmoreefficientlythanonethathandlesseveraldifferentdatatypes.
Becauseadditionissuchacommonoperation,NetLogo’soverallspeedisaffected.
The-atprimitives
Theobservermaynolongerusepatch-at,turtles-at,andBREEDS-at.Usepatch,turtles-on
patch,andBREEDS-onpatchinstead.Notethatpatchnowroundsitsinputs(beforeitonly
acceptedintegerinputs).
Links
NetLogo3.1hadsupportsforusinglinkstoconnectturtlestomakenetworks,graphs,and
geometricfigures.Thelinkswerethemselvesturtles.
InNetLogo4.0,insteadoflinksbeingturtles,linksarenowanindependentfourthagenttype,
rightalongsideobserver,turtles,patches.Theprimitivesinvolvinglinksarenolonger
consideredexperimental;theyarenowfullypartofthelanguage.
Modelsthatusetheold,experimentalturtle-basedlinkprimitiveswillneedtobeupdatedto
uselinkagents.Thedifferencesarenothuge,buthandupdatingisrequired.
LinksaredocumentedintheLinkssectionoftheProgrammingGuide,andintheNetLogo
Dictionaryentriesforthelinkprimitives.SeetheNetworkssectionoftheModelsLibraryfor
examplemodelsthatuselinks.Therearealsosomelink-basedCodeExamples.
Firstyouwillneedtoremoveanybreedscalled“links”ifyouareonlyusingonetypeoflinks
thenyouwillnothavetousebreedsatall.Ifyouareusingmultipletypesoflinkssee
undirected-link-breedanddirected-link-breed.Commandsandreportersthatcontainthe
word“links”(like__create-links-with,etc.)willautomaticallybeconvertedtothenewform
withoutunderscores(create-links-with).However,primitivesthatuseadifferentbreed
name(suchas“edges”)willnotbeconverted.Youwillneedtoremovetheunderscoresby
handandunlessyouaredeclaringalinkbreedwiththatnameyouwillneedtochangethe
breeddesignationto“links”.
Thecommandsremove-link(s)-with/from/tonolongerexist.Insteadyoushouldaskthe
linksinquestiontodie.
Forexample:
ask turtle 0 [ __remove-links-with link-neighbors ]
becomes
ask turtle 0 [ ask my-links [ die ] ]
Severalofthelayoutcommandshaveslightlydifferentinputs,thefirsttwoinputsare
generallyaturtleagentsetandalinkagentsettoperformthelayouton.Seethedictionary
entriesfordetails.layout-spring,layout-radialandlayout-tutte
Youmayalsoneedtorearrangethedeclarationofturtles-ownvariables,sincelinkswere
onceactuallyturtles.Anyvariablesthatapplytolinksshouldbemovedintoalinks-ownblock.
Sincelinksarenolongerturtlestheynolongerhavethebuilt-inturtlevariables(thoughsome
ofthelinkvariablesarethesamesuchascolorandlabel.Ifyouformerlyusedthelocationof
linkturtlesyouwillnowneedtocalculatethemidpointofthelink.Thisisfairlysimpleina
non-wrappingworld.
to-report link-xcor
report mean [xcor] of both-ends
end
to-report link-ycor
report mean [ycor] of both-ends
end
itisalittlebittrickierinawrappingworldbutstillfairlystraightforward.
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
andsimilarlyforycor.
Ifyouusedeitherthesizeorheadingofthelinkturtlesyoucanusethereporterslink-length
andlink-headinginstead.
New“of”syntax
Wehavereplacedthreedifferentlanguageconstructs,-of(withhyphen),value-from,and
values-fromwithasingleofconstruct(nohyphen).
old new
`color-ofturtle0` `[color]ofturtle0`
`value-fromturtle0[size*size]` `[size*size]ofturtle
0`
`meanvalues-fromturtles[size]` `mean[size]ofturtles`
Whenofisusedwithasingleagent,itreportsasinglevalue.Whenusedwithanagentset,it
reportsalistofvalues(inrandomorder,sinceagentsetsarealwaysinrandomorder).
Notethatwhenopeningoldmodelsinthenewversion,-of,value-from,andvalues-fromwill
automaticallybeconvertedtouse“of”instead,butsomenestedusesoftheseconstructsare
toocomplexfortheconverterandmustbeconvertedbyhand.
Serialask
Theaskcommandisnowserialratherthanconcurrent.Inotherwords,theaskedagentswill
runoneatatime.Notuntiloneagentcompletelyfinishestheentirebodyoftheaskdoesthe
nextagentstart.
Notethateventheoldaskwasnevertrulyconcurrent;wesimulatedconcurrentexecutionby
interleavingexecutionamongtheagentsusingaturn-takingmechanismdescribedinthe
NetLogoFAQ.
Wehavemadethischangebecauseinourexperience,usersoftenwrotemodelsthat
behavedinunexpectedwaysduetothesimulatedconcurrency,butrarelywrotemodelsthat
benefitedfromthesimulatedconcurrency.Modelsexhibitingunexpectedbehaviorcould
usuallybefixedbyaddingthewithout-interruptioncommandintherightplaces,butitwas
difficultforuserstoknowwhetherthatcommandwasneededandifso,where.
InNetLogo4.0,without-interruptionisnolongernecessaryunlessyourmodelusesask-
concurrent(oraturtleorpatchforeverbuttoncontainingcodethatdependsonsimulated
concurrency).Inmostmodels,allusesofwithout-interruptioncanberemoved.
Thesimulatedconcurrencyformerlyemployedby“ask”isstillaccessibleinthreeways:
Youmayusetheask-concurrentprimitiveinsteadofasktogettheoldsimulated
concurrency.(Wedon’trecommendthis,though.)
CommandsissuedintheCommandCenterdirectlytoturtles,patches,orlinkshavean
impliedask-concurrent.
Turtle,patch,andlinkforeverbuttonshaveanimpliedask-concurrentaswell.
Notethataskitselfisalwaysserialregardlessofthecontextinwhichitisused,however.
InourownModelsLibrary,modelsthatmakeuseofthisconcurrencyarerare.Aprominent
example,though,isTermites,whichusesaconcurrentturtleforeverbutton.
Tickcounter
NetLogonowhasabuilt-intickcounterforrepresentingthepassageofsimulatedtime.
Youadvancethecounterbyoneusingthetickcommand.Ifyouneedtoreaditsvalue,
there’sareportercalledticks.Theclear-allcommandresetsthetickcounter;sodoes
reset-ticks.
Inmostmodelsthetickcounterwillbeinteger-valued,butifyouwanttousesmaller
incrementsoftime,youcanusethetick-advancecommandtoadvancethetickcounterby
anypositiveamount,includingfractionalamounts.SomeModelsLibrarymodelsthatuse
tick-advanceareVectorFieldsandtheGasLabmodels.
ThevalueofthetickcounterisdisplayedinthetoolbaratthetopoftheInterfacetab.(You
canusetheSettings…buttoninthetoolbartohidethetickcounter,orchangetheword
“ticks”tosomethingelse.)
Viewupdatemodes
Inthepast,NetLogoalwaystriedtoupdatetheviewabout20timesasecond.We’renow
callingthat“continuous”viewupdates.Thebiggestproblemwithitwasthatyouusuallywant
updatestohappenbetweenmodelticks,notinthemiddleofatick,sowehadacheckboxon
buttonsthat(bydefault)forcedadisplayupdateaftereverybuttoniteration.Thatmadesure
updateshappenedbetweenticks,butitdidn’tgetridoftheintermediateupdates.Youhadto
useno-displayanddisplaytolockthemout.
Westillsupportcontinuousupdates.TheyarethedefaultwhenyoustartupNetLogo.But
mostModelsLibrarymodelsnowusetick-basedupdates.Withtick-basedupdates,updates
happenonlywhenthetickcounteradvances.(Thedisplaycommandcanbeusedtoforce
additionalupdates;seebelow.)
Theadvantagesoftick-basedupdatesasweseethemareasfollows:
1. Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputerto
computerorfromruntorun.
2. Intermediateupdatescanconfusetheuserofyourmodelbylettingthemseethings
theyaren’tsupposedtosee,whichmaybemisleading.
3. Increasedspeed.Updatingtheviewtakestime,soifoneupdatepertickisenough,then
enforcingthanthereisonlyoneupdatepertickwillmakeyourmodelfaster.
4. Insteadofhavinga“forceviewupdate”checkboxineverybuttonlikeinNetLogo3.1,we
onlyneedonechoicewhichappliestotheentiremodel.
5. Usingthespeedslidertoslowdownamodelnowjustinsertspausesbetweenticks.So
withtick-basedupdates,setupbuttonsarenolongeraffectedbythespeedslider.This
wasarealannoyancewiththeoldspeedslider.(Theannoyancepersistsformodels
thatusecontinuousupdates,though.)
Asmentionedabove,mostmodelsinourModelsLibrarynowusetick-basedupdates.
Evenformodelsthatwouldnormallybesettotick-basedupdates,itmaybeusefultoswitch
tocontinuousupdatestemporarilyfordebuggingpurposes.Seeingwhat’sgoingonwithina
tick,insteadofonlyseeingtheendresultofatick,couldhelpwithtroubleshooting.
Ifyouswitchyourmodeltousetick-basedupdates,you’llalsoneedtoaddthetick
commandtoyourcode,otherwisetheviewwon’tupdate.(Notethattheviewstillalways
updateswhenabuttonpopsuporacommandenteredinthecommandcenterfinishes,
though.Soit’snotliketheviewwilljuststayfrozenindefinitely.)
Howtomakeamodeluseticksandtick-basedupdates
Herearethestepstofollowtoconvertyourmodeltouseticksandtick-basedupdatesin
NetLogo4.0:
1. IntheInterfacetabtoolbar,ontherighthandsidewhereitsays“updateview:”,change
thesettingfrom“continuously”to“onticks”.
2. Addthetickcommandtoyourgoprocedure,atorneartheend.InModelsLibrary
modelswealwaysputtickaftertheagentsmovebutbeforeanyplottingcommands.
That’sbecausetheplottingcommandsmightcontainsomethinglikeplotxy ticks ...
andwewantthenewvalueofthetickcounterused,nottheoldone.Mostmodelsdon’t
refertothetickcounterintheirplottingcommands,butnonetheless,forconsistencyand
toavoidmistakeswesuggestalwaysputtingtickbeforetheplottingcommands.
Somemodelswillrequiresomeadditionalchanges:
1. Ifyourmodelalreadyhasaglobal“ticks”or“clock”or“time”variable,getridofit.Use
thetickcommandandticksreporterinstead.(Ifyourmodelusesfractionalincrements
oftime,usetick-advanceinsteadoftick.)Ifyouhadamonitorforthatvariable,youcan
getridofit;there’snowatickcounterinthetoolbar.
2. clear-allresetsthetickcountertozero.Ifyoudon’tuseclear-allinyoursetup
procedure,thenyoumayneedtoaddreset-tickstoresetthecountertozero.
3. Ifyouusedno-displayanddisplaytopreventviewupdatesfromhappeninginthe
middleofgo,youcangetridofthem.
4. Ifyourmodelneedstoupdatetheviewwithoutadvancingthetickcounter(examples:
Party,DiceStalagmite,networkmodelswithanimatedlayout,modelswithmouse
interactionbuttons),usethedisplaycommandtoforceadditionalviewupdatessothe
usercanseewhatisgoingon.
Speedslider
PreviousversionsofNetLogohadaspeedsliderthatcouldbeusedtomakemodelsrun
slower,soyoucanseewhat’sgoingon.
InNetLogo4.0,theslidercanbeusedtospeedupmodelsaswell.Itdoesthisbyupdating
theviewlessfrequently.Updatingtheviewtakestime,sothefewerupdates,thefasterthe
modelruns.
Thedefaultpositionofthesliderisinthecenter.Whenyou’reatthecenter,theslidersays
“normalspeed”.
Asyoumovethesliderawayfromthecenterposition,themodelwillgraduallyrunfasteror
slower.
Atveryhighspeeds,viewupdatesbecomeveryinfrequentandmaybeseparatedbyseveral
seconds.Itmayfeellikethemodelisactuallyrunningslower,sincetheupdatesareso
infrequent.Butwatchthetickcounter,orotherindicatorssuchasplots,andyou’llseethat
yes,themodelreallyisrunningfaster.Iftheinfrequentupdatesaredisconcerting,don’tpush
theslidersofarover.
Whenusingtick-basedupdates,slowingthemodeldowndoesnotcauseadditionalview
updates.Rather,NetLogosimplypausesaftereachtick.
Whenusingcontinuousupdates,slowingthemodeldownmeansviewupdatesbecomemore
closelyspaced.Ifyoupushthespeedslidermorethanhalfwaytotheleft,themodelwillbe
runningsoslowlythatyoucanwatchturtlesmovingoneatatime!ThisisnewinNetLogo4.0;
inpreviousNetLogoversions,nomatterhowslowlyyouranamodel,youwouldneverseethe
agentsinanaskmovingoneatatime;alltheagentsinanaskalwaysappearedtomove
together.
Numbers
NetLogonolongermaintainsaninternaldistinctionbetweenintegersandfloatingpoint
numbers.Soforexample:
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
(Thelastlineshowsthatalthoughthedistinctionbetweeninteger3andfloatingpoint3.0was
maintained,thetwonumberswerestillconsideredequal.)
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
Weexpectthatonlyraremodelswillbenegativelyimpactedbythischange.
AbenefitofthischangeisthatNetLogonowsupportsamuchlargerrangeofintegers.The
oldrangewas-2,147,483,648to2,147,483,647(around+/-2billion);thenewrangeis+/-
9,007,199,254,740,992(around+/-9quadrillion).
Agentsetbuilding
NetLogo3.1(andsomeearlierversions)includedprimitivescalledturtles-fromandpatches-
fromthatwereoccasionallyusefulforbuildingagentsets.InNetLogo4.0,theseprimitives
havebeenreplacedwithnewprimitivescalledturtle-setandpatch-setthataremuchmore
flexibleandpowerful.(link-setexistsaswell.)Seetheentriesfortheseprimitivesinthe
NetLogoDictionary.Modelsthatusetheoldturtles-fromandpatches-fromwillneedtobe
alteredbyhandtousethenewprimitives.
RGBColors
InNetLogo3.1RGBandHSBcolorscouldbeapproximatedasNetLogocolorsusingthergb
andhsbprimitives.Thesehavebeenrenamedtoapproximate-rgbandapproximate-hsband
nowexpectinputsintherange0-255,not0-1.
ThefullRGBspectrumisnowavailableinNetLogosoitmaynolongerbenecessarytouse
theseprimitivesatall.Youcansetanycolorvariabletoathree-itemRGBlist,withvaluesin
the0-255range,andgetthatexactcolor.SeetheColorsectionoftheProgrammingGuide
fordetails.
Tie
Inpreviousversions__tiewasprovidedasanexperimentalfeature.AsofNetLogo4.0links
haveatie-modevariablewhichcanbesetto"none","free",or"fixed".In4.0tieisnowa
link-onlyprimitive.Thismeansthattotieturtle1toturtle0youwrite:
ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
SeetheTiesectionoftheprogrammingguidefordetails.
ChangesforNetLogo3.1
Agentsets
Ifyourmodelisbehavingstrangelyorincorrectly,itmaybebecausesinceNetLogo3.1,
agentsetsarenowalwaysinrandomorder.InpriorversionsofNetLogo,agentsetswere
alwaysinafixedorder.Ifyourcodedependedonthatfixedorder,thenitwon’tworkanymore.
Howtofixyourmodeltoworkwithrandomizedagentsetsdependsonthedetailsofwhatyour
codeisdoing.Insomesituations,itishelpfultousethesortorsort-byprimitivestoconvert
anagentset(randomorder)intoalistofagents(fixedorder).See“Listsofagents”intheLists
sectionoftheProgrammingGuide.
Wrapping
Ifyouareseeingpiecesofturtleshapeswrappingaroundtheviewedges,it’sbecause
NetLogo3.0allowedyoutoturnoffsuchwrappingintheviewwithoutaffectingthebehavior
ofthemodel.SinceNetLogo3.1,ifyoudon’twanttheviewtowrapyoumustmakeitsothe
worlddoesn’twrap,usingthenewtopologyfeature.Makingthischangemayrequireother
changestoyourmodel,though.SeetheTopologysectionoftheProgrammingGuidefora
thoroughdiscussionofhowtoconvertyourmodeltotakeadvantageofthisnewfeature.
Randomturtlecoordinates
ManymodelsmadeinNetLogo3.0orearlierusesetxy random world-width random world-
heighttoscatterturtlesrandomly,usingeitherrandomorrandom-float.Itonlyworksifworld
wrappingison.
(Why?Becausewhenwrappingison,youcansetcoordinatesofturtlestonumbersbeyond
theedgeoftheworldandNetLogowillwraptheturtletotheotherside.Butinworldsthat
don’twrapsettingthexorycoordinatesofaturtletoapointoutsidetheboundsoftheworld
causesaruntimeerror.TheworldwrapsettingswereaddedinNetLogo3.1.Seethe
TopologysectionoftheProgrammingGuideformoreinformation.)
Tofixyourmodelsothatitworksregardlessofthewrappingsettings,useoneofthesetwo
commandsinstead:
setxy random-xcor random-ycor
setxy random-pxcor random-pycor
Thetwocommandsareabitdifferent.Thefirstcommandputstheturtleonarandompointin
theworld.Thesecondcommandputstheturtleonthecenterofarandompatch.Aneven
moreconcisewaytoputaturtleonthecenterofarandompatchis:
move-to one-of patches
ShapesEditorGuide
NetLogo6.0.4UserManual
TheTurtleandLinkShapeEditorsallowsyoutocreateandsaveturtleandlinkdesigns.
NetLogousesfullyscalableandrotatablevectorshapes,whichmeansyoucancreate
designsbycombiningbasicgeometricelements,whichcanappearon-screeninanysizeor
orientation.
Gettingstarted
Tobeginmakingshapes,chooseTurtleShapesEditororLinkShapesEditorintheTools
menu.Anewwindowwillopenlistingalltheshapescurrentlyinthemodel,beginningwith
default,thedefaultshape.TheShapesEditorallowsyoutoeditshapes,createnewshapes,
andborrowfromanothermodel.Youcanalsoimportturtleshapesfromalibraryofpre-
existingshapes.
Importingshapes
EverynewmodelinNetLogostartsoffcontainingasmallcoresetoffrequentlyusedshapes.
ManymoreturtleshapesareavailablebyusingtheImportfromlibrary…button.Thisbrings
upadialogwhereyoucanselectoneormoreshapesandbringthemintoyourmodel.Select
theshapes,thenpresstheImportbutton.
Similarly,youcanusetheImportfrommodel…buttontoborrowshapesfromanother
model.
Defaultshapes
HerearetheturtleshapesthatareincludedbydefaultineverynewNetLogomodel:
Firstrow:default,airplane,arrow,box,bug,butterfly,car
Secondrow:circle,circle2,cow,cylinder,dot,facehappy,faceneutral
Thirdrow:facesad,fish,flag,flower,house,leaf,line
Fourthrow:linehalf,pentagon,person,plant,sheep,square,square2
Fifthrow:star,target,tree,triangle,triangle2,truck,turtle
Sixthrow:wheel,x
Shapeslibrary
Andherearetheshapesintheshapeslibrary(includingallofthedefaultshapes,too):
BydefaultthereisonlyoneLinkshapeinamodel,thatis“default”.Thisshapeissimplya
singlestraightlinewithasimplearrowhead(ifthelinkhappenstobedirected).
Creatingandeditingturtleshapes
PressingtheNewbuttonwillmakeanewshape.Or,youmayselectanexistingshapeand
pressEdit.
Tools
Intheupperleftcorneroftheeditingwindowisagroupofdrawingtools.Thearrowisthe
selectiontool,whichselectsanalreadydrawnelement.
Todrawanewelement,useoneoftheotherseventools:
Thelinetooldrawslinesegments.
Thecircle,square,andpolygontoolscomeintwoversions,solidandoutline.
Whenusingthepolygontool,clickthemousetoaddanewsegmenttothepolygon.When
you’redoneaddingsegments,doubleclick.
Afteryoudrawanewelement,itisselected,soyoucanmove,delete,orreshapeitifyou
want:
Tomoveit,dragitwiththemouse
Todeleteit,presstheDeletebutton.
Toreshapeit,dragthesmall“handles”thatappearontheelementonlywhenitis
selected.
Tochangeitscolor,clickonthenewcolor.
Previews
Asyoudrawyourshape,youwillalsoseeitinfivesmallersizesinthefivepreviewareas
foundnearthebottomoftheeditingwindow.Thepreviewsshowyourshapeasitmight
appearinyourmodel,includinghowitlooksasitrotates.Thenumberbeloweachpreviewis
thesizeofthepreviewinpixels.Whenyouedittheview,patchsizeisalsomeasuredin
pixels.Soforexample,thepreviewwith“20”belowitshowsyouhowyourshapewouldlook
onaturtle(ofsize1)onpatchesofsize20pixels.
Therotatablefeaturecanbeturnedoffifyouwantashapethatalwaysfacesthesameway,
regardlessoftheturtle’sheading.
Overlappingshapes
Newelementsgoontopofpreviouselements.Youcanchangethelayeringorderby
selectinganelementandthenusingtheBringtofrontandSendtobackbuttons.
Undo
AtanypointyoucanusetheUndobuttontoundotheedityoujustperformed.
Colors
ElementswhosecolormatchestheColorthatchanges(selectedfromadrop-downmenu–
thedefaultisgray)willchangecoloraccordingtothevalueofeachturtle’scolorvariablein
yourmodel.Elementsofothercolorsdon’tchange.Forexample,youcouldcreatecarsthat
alwayshaveyellowheadlightsandblackwheels,butdifferentbodycolors.
Otherbuttons
The“RotateLeft”and“RotateRight”buttonsrotateelementsby90degrees.The“Flip
Horizontal”and“FlipVertical”buttonsreflectelementsacrosstheaxes.
Thesefourbuttonswillrotateorfliptheentireshape,unlessanelementisselected,inwhich
caseonlythatelementisaffected.
Thesebuttonsareespeciallyhandyinconjunctionwiththe“Duplicate”buttonifyouwantto
makeshapesthataresymmetrical.Forexample,ifyouweremakingabutterfly,youcould
drawthebutterfly’sleftwingwiththepolygontool,thenduplicatethewingwiththe“Duplicate”
button,thenturnthecopyintoarightwingwiththe“FlipHorizontal”button.
Shapedesign
It’stemptingtodrawcomplicated,interestingshapes,butrememberthatinmostmodels,the
patchsizeissosmallthatyouwon’tbeabletoseeverymuchdetail.Simple,bold,iconic
shapesareusuallybest.
Keepingashape
Whentheshapeisdone,giveitanameandpresstheDonebuttonatthebottomofthe
editingwindow.Theshapeanditsnamewillnowbeincludedinthelistofshapesalongwith
the“default”shape.
Creatingandeditinglinkshapes
Managinglinkshapesisverysimilartomanagingturtleshapes.So,youcancreateanew
shapebypressingtheNewbuttonoryoucaneditexistingshapes.Whenyouaredone
editingashapepressDoneifyouwanttokeepit.
Changinglinkshapeproperties
Thereareseveraldifferentpropertiesforeachlinkshapethatyouareallowedtochange:
Name-linkshapescanhavethesamenameasturtleshapesbutmustbeunique
amonglinkshapes.
DirectionIndicator-thedirectionindicator(thelittlearrowondirectedlinks)isjustlike
theturtlevectorshapes,youcanedititusingthesameeditorbypressingtheEdit
button.
Curviness-thisistheamountofbendinalinkexpressedinpatches(thisisparticularly
usefulifyouhavedirectedlinksgoinginbothdirectionssoyoucandiscernbothlinks)
Numberoflines:Youcanhave1,2,or3linesineachlinkshape,youcontrolthisby
selectinglinepatternsinthe“leftline”,“middleline”,and“rightline”selectionboxes.
Dashpatternoflines:Thereareseveraldashedlinepatternsavailableintheselection
boxessonotalllinesneedbesolid.
Herearesomelinkshapeswithvariousproperties:
Usingshapesinamodel
Inthemodel’scodeorinthecommandcenter,youcanuseanyoftheshapesthatareinthe
model(thoughonlyturtlescanhaveturtleshapesandonlylinkscanhavelinkshapes).For
example,supposeyouwanttocreate50turtleswiththeshape“rabbit”.Providedthereis
someturtleshapecalledrabbitinthismodel,givethiscommandtotheobserverinthe
commandcenter:
observer> crt 50
Andthengivethesecommandstotheturtlestospreadthemout,thenchangetheirshape:
turtles> fd random 15
turtles> set shape "rabbit"
Voila!Rabbits!Notetheuseofdoublequotesaroundtheshapename.Shapenamesare
strings.
Similarly,youcansettheshapevariableoflinks.Assumingthereisalinkshapecalled“road”
inthismodel:
observer> crt 5 [ create-links-with other turtles ]
turtles> fd 5
links> set shape "road"
Theset-default-shapecommandisalsousefulforassigningshapestoturtlesandlinks.
BehaviorSpaceGuide
NetLogo6.0.4UserManual
Thisguidehasthreeparts:
WhatisBehaviorSpace?:Ageneraldescriptionofthetool,includingtheideasand
principlesbehindit.
HowItWorks:Walksyouthroughhowtousethetoolandhighlightsitsmostcommonly
usedfeatures.
AdvancedUsage:HowtouseBehaviorSpacefromthecommandline,orfromyour
ownJavacode.
WhatisBehaviorSpace?
BehaviorSpaceisasoftwaretoolintegratedwithNetLogothatallowsyoutoperform
experimentswithmodels.
BehaviorSpacerunsamodelmanytimes,systematicallyvaryingthemodel’ssettingsand
recordingtheresultsofeachmodelrun.Thisprocessissometimescalled“parameter
sweeping”.Itletsyouexplorethemodel’s“space”ofpossiblebehaviorsanddeterminewhich
combinationsofsettingscausethebehaviorsofinterest.
Ifyourcomputerhasmultipleprocessorcores,thenbydefault,modelrunswillhappenin
parallel,onepercore.
WhyBehaviorSpace?
Theneedforthistypeofexperimentisrevealedbythefollowingobservations.Modelsoften
havemanysettings,eachofwhichcantakearangeofvalues.Togethertheyformwhatin
mathematicsiscalledaparameterspaceforthemodel,whosedimensionsarethenumberof
settings,andinwhicheverypointisaparticularcombinationofvalues.Runningamodelwith
differentsettings(andsometimeseventhesameones)canleadtodrasticallydifferent
behaviorinthesystembeingmodeled.So,howareyoutoknowwhichparticular
configurationofvalues,ortypesofconfigurations,willyieldthekindofbehavioryouare
interestedin?Thisamountstothequestionofwhereinitshuge,multi-dimensionparameter
spacedoesyourmodelperformbest?
Forexample,supposeyouwantspeedysynchronizationfromtheagentsintheFireflies
model.Themodelhasfoursliders–number,cycle-length,flash-lengthandnumber-flashes–
thathaveapproximately2000,100,10and3possiblevalues,respectively.Thatmeansthere
are2000*100*10*3=600,000possiblecombinationsofslidervalues!Tryingcombinations
oneatatimeishardlyanefficientwaytolearnwhichonewillevokethespeediest
synchronization.
BehaviorSpaceoffersyouamuchbetterwaytosolvethisproblem.Ifyouspecifyasubsetof
valuesfromtherangesofeachslider,itwillrunthemodelwitheachpossiblecombinationof
thosevaluesand,duringeachmodelrun,recordtheresults.Indoingso,itsamplesthe
model’sparameterspace–notexhaustively,butenoughsothatyouwillbeabletosee
relationshipsformbetweendifferentslidersandthebehaviorofthesystem.Afteralltheruns
areover,adatasetisgeneratedwhichyoucanopeninadifferenttool,suchasa
spreadsheet,database,orscientificvisualizationapplication,andexplore.
Byenablingyoutoexploretheentire“space”ofbehaviorsamodelcanexhibit,
BehaviorSpacecanbeapowerfulassistanttothemodeler.
HowItWorks
TobeginusingBehaviorSpace,openyourmodel,thenchoosetheBehaviorSpaceitemon
NetLogo’sToolsmenu.
Managingexperimentsetups
Thedialogthatopensletsyoucreate,edit,duplicate,delete,andrunexperimentsetups.
Experimentsarelistedbynameandhowbymodelrunstheexperimentwillconsistof.
ExperimentsetupsareconsideredpartofaNetLogomodelandaresavedaspartofthe
model.
Tocreateanewexperimentsetup,pressthe“New”button.
Creatinganexperimentsetup
Inthenewdialogthatappears,youcanspecifythefollowinginformation.Notethatyoudon’t
alwaysneedtospecifyeverything;somepartscanbeleftblank,orleftwiththeirdefault
values,dependingonyourneeds.
Experimentname:Ifyouhavemultipleexperiments,givingthemdifferentnameswillhelp
youkeepthemstraight.
Varyvariablesasfollows:Thisiswhereyouspecifywhichsettingsyouwantvaried,and
whatvaluesyouwantthemtotake.Variablescanincludesliders,switches,choosers,and
anyglobalvariablesinyourmodel.
Variablescanalsoincludemax-pxcor,min-pxcor,max-pycorandmin-pycor,world-width,
world-heightandrandom-seed.Thesearenot,strictlyspeaking,variables,butBehaviorSpace
letsyouvarythemasiftheywere.Varyingtheworlddimensionsletsyouexploretheeffectof
worldsizeuponyourmodel.Sincesettingworld-widthandworld-heightdoesnotnecessarily
definetheboundsoftheworldhowtheyarevarieddependsonthelocationoftheorigin.If
theoriginiscentered,BehaviorSpacewillkeepitcenteredsothevaluesworld-widthor
world-heightmustbeodd.Ifoneoftheboundsisatzerothatboundwillbekeptatzeroand
theotherboundwillmove,forexampleifyoustartwithaworldwithmin-pxcor = 0max-pxcor
= 10andyouvaryworld-widthlikethis:
["world-width" [11 1 14]]
min-pxcorwillstayatzeroandmax-pxcorwillsetto11,12,and13foreachoftheruns.If
neitheroftheseconditionsaretrue,theoriginisnotcentered,norattheedgeoftheworld
youcannotvaryworld-heightorworld-widthdirectlybutyoushouldvarymax-pxcor,max-
pycor,min-pxcorandmin-pycorinstead.
Varyingrandom-seedletsyourepeatrunsbyusingaknownseedfortheNetLogorandom
numbergenerator.Notethatyou’realsofreetousetherandom-seedcommandinyour
experiment’ssetupcommands.Formoreinformationonrandomseeds,seetheRandom
NumberssectionoftheProgrammingGuide.
Youmayspecifyvalueseitherbylistingthevaluesyouwantused,orbyspecifyingthatyou
wanttotryeveryvaluewithinagivenrange.Forexample,togiveaslidernamednumber
everyvaluefrom100to1000inincrementsof50,youwouldenter:
["number" [100 50 1000]]
Or,togiveitonlythevaluesof100,200,400,and800,youwouldenter:
["number" 100 200 400 800]
Becarefulwiththebracketshere.Notethattherearefewersquarebracketsinthesecond
example.IncludingornotincludingthisextrasetofbracketsishowyoutellBehaviorSpace
whetheryouarelistingindividualvalues,orspecifyingarange.
Alsonotethatthedoublequotesaroundthevariablenamesarerequired.
Youcanvaryasmanysettingsasyouwant,includingjustone,ornoneatall.Anysettings
thatyoudonotvarywillretaintheircurrentvalues.Notvaryinganysettingsisusefulifyou
justwanttodomanyrunswiththecurrentsettings.
Whatorderyoulistthevariablesindetermineswhatordertherunswillbedonein.Allvalues
foralatervariablewillbetriedbeforemovingtothenextvalueforanearliervariable.Sofor
exampleifyouvarybothxandyfrom1to3,andxislistedfirst,thentheorderofmodelruns
willbe:x=1y=1,x=1y=2,x=1y=3,x=2y=1,andsoon.
Repetitions:Sometimesthebehaviorofamodelcanvaryalotfromruntorunevenifthe
settingsdon’tchange,ifthemodelusesrandomnumbers.Ifyouwanttorunthemodelmore
thanonceateachcombinationofsettings,enterahighernumber.
Measurerunsusingthesereporters:Thisiswhereyouspecifywhatdatayouwantto
collectfromeachrun.Forexample,ifyouwantedtorecordhowthepopulationofturtlesrose
andfellduringeachrun,youwouldenter:
count turtles
Youcanenteronereporter,orseveral,ornoneatall.Ifyouenterseveral,eachreportermust
beonalinebyitself,forexample:
count frogs
count mice
count birds
Ifyoudon’tenteranyreporters,therunswillstilltakeplace.Thisisusefulifyouwantto
recordtheresultsyourselfyourownway,suchaswiththeexport-worldcommand.
Measurerunsateverystep:NormallyNetLogowillmeasuremodelrunsateverystep,
usingthereportersyouenteredinthepreviousbox.Ifyou’redoingverylongmodelruns,you
mightnotwantallthatdata.Uncheckthisboxifyouonlywanttomeasureeachrunafterit
ends.
Setupcommands:Thesecommandswillbeusedtobegineachmodelrun.Typically,you
willenterthenameofaprocedurethatsetsupthemodel,typicallysetup.Butitisalso
possibletoincludeothercommandsaswell.
Gocommands:Thesecommandswillberunoverandoveragaintoadvancetothemodel
tothenext“step”.Typically,thiswillbethenameofaprocedure,suchasgo,butyoumay
includeanycommandsyoulike.
Stopcondition:Thisletsyoudomodelrunsofvaryinglength,endingeachrunwhena
certainconditionbecomestrue.Forexample,supposeyouwantedeachruntolastuntilthere
werenomoreturtles.Thenyouwouldenter:
not any? turtles
Ifyouwantthelengthofrunstoallbeofafixedlength,justleavethisblank.
Therunmayalsostopbecausethegocommandsusethestopcommand,inthesameway
thatstopcanbeusedtostopaforeverbutton.Thestopcommandmaybeuseddirectlyinthe
gocommands,orinaprocedurecalleddirectlybythegocommands.(Theintentisthatthe
samegoprocedureshouldworkbothinabuttonandinaBehaviorSpaceexperiment.)Note
thatthestepinwhichstopisusedisconsideredtohavebeenaborted,sonoresultswillbe
recordedforthatstep.Therefore,thestoppingtestshouldbeatthebeginningofthego
commandsorprocedure,notattheend.
Finalcommands:Theseareanyextracommandsthatyouwantrunonce,whentherun
ends.Usuallythisisleftblank,butyoumightuseittocalltheexport-worldcommandor
recordtheresultsoftheruninsomeotherway.
Timelimit:Thisletsyousetafixedmaximumlengthforeachrun.Ifyoudon’twanttosetany
maximum,butwantthelengthoftherunstobecontrolledbythestopconditioninstead,enter
0.
SpecialprimitivesforBehaviorSpaceexperiments
Currentlythereareonlytwo,behaviorspace-run-numberandbehaviorspace-experiment-name.
Therunnumberreportedbytheformerprimitivematchestherunnumberusedintheresults
filesgeneratedbyBehaviorSpace.Theexperimentnamereportedbythelattermatchesthe
namewithwhichtheexperimentwassetup.
Runninganexperiment
Whenyou’redonesettingupyourexperiment,pressthe“OK”button,followedbythe“Run”
button.Adialogtitled“Runoptions”willappear.
Runoptions:formats
Therunoptionsdialogletsyouselecttheformatsyouwouldlikethedatafromyour
experimentsavedin.Dataiscollectedforeachrunorstep,accordingtothesettingof
Measurerunsateverystepoption.Ineithercase,theinitialstateofthesystemisrecorded,
afterthesetupcommandsrunbutbeforethegocommandsrunforthefirsttime.
Tableformatlistseachintervalinarow,witheachmetricinaseparatecolumn.Tabledatais
writtentotheoutputfileaseachruncompletes.Tableformatissuitableforautomated
processingofthedata,suchasimportingintoadatabaseorastatisticspackage.
Spreadsheetformatcalculatesthemin,mean,max,andfinalvaluesforeachmetric,andthen
listseachintervalinarow,witheachmetricinaseparatecolumn.Spreadsheetdataismore
human-readablethanTabledata,especiallyifimportedintoaspreadsheetapplication.
(Notehoweverthatspreadsheetdataisnotwrittentotheresultsfileuntiltheexperiment
finishes.Sincespreadsheetdataisstoredinmemoryuntiltheexperimentisdone,verylarge
experimentscouldrunoutofmemory.Soyoushoulddisablespreadsheetoutputunlessyou
reallywantit.Ifyoudowantspreadsheetoutput,notethatifanythinginterruptsthe
experiment,suchasaruntimeerror,runningoutofmemory,oracrashorpoweroutage,no
spreadsheetresultswillbewritten.Forlongexperiments,youmaywanttoalsoenabletable
formatasaprecautionsothatifsomethinghappensandyougetnospreadsheetoutputyou’ll
atleastgetpartialtableoutput.)
Afterselectingyouroutputformats,BehaviorSpacewillpromptyouforthenameofafileto
savetheresultsto.Thedefaultnameendsin“.csv”.Youcanchangeittoanynameyouwant,
butdon’tleaveoffthe“.csv”part;thatindicatesthefileisaCommaSeparatedValues(CSV)
file.Thisisaplain-textdataformatthatisreadablebyanytexteditoraswellasbymost
popularspreadsheetanddatabaseprograms.
Runoptions:parallelruns
Therunoptionsdialogalsoletsyouselectwhetheryouwantmultiplemodelrunstohappenin
parallel,andifso,howmanyareallowedtobesimultaneouslyactive.Thisnumberwilldefault
tothenumberofprocessorcoresinyourcomputer.
Thereareafewcautionsassociatedwithparallelruns.
First,ifmultiplerunsareactive,onlyoneofthemwillbeinthe“foreground”andcausethe
viewandplotstoupdate.Theotherrunswillhappeninvisiblyinthebackground.
Second,invisiblebackgroundrunscan’tuseprimitivesthatonlyworkintheGUI.For
example,abackgroundruncan’tmakeamovie.
Third,sinceparallelrunsprogressindependentlyofeachother,tableformatoutputmay
containinterleaved,out-of-orderresults.Whenyouanalyzeyourtabledata,youmaywishto
sortitbyrunnumberfirst.(Spreadsheetformatoutputisnotaffectedbythisissue,sinceitis
notwrittenuntiltheexperimentcompletesorisaborted.)
Fourth,usingallavailableprocessorcoresmaymakeyourcomputerslowtouseforother
taskswhiletheexperimentisrunning.
Fifth,doingrunsinparallelwillmultiplytheexperiment’smemoryrequirementsaccordingly.
YoumayneedtoincreaseNetLogo’smemoryceiling(seethisFAQentry).
Observingruns
Afteryoucompletetherunoptionsdialog,anotherdialogwillappear,titled“Running
Experiment”.Inthisdialog,you’llseeaprogressreportofhowmanyrunshavebeen
completedsofarandhowmuchtimehaspassed.Ifyouenteredanyreportersformeasuring
theruns,andifyouleftthe“Measurerunsateverystep”boxchecked,thenyou’llseeaplotof
howtheyvaryoverthecourseofeachrun.
YoucanalsowatchtherunsinthemainNetLogowindow.(Ifthe“RunningExperiment”dialog
isintheway,justmoveittoadifferentplaceonthescreen.)Theviewandplotswillupdateas
themodelruns.Ifyoudon’tneedtoseethemupdate,thenusethecheckboxesinthe
“RunningExperiment”dialogtoturntheupdatingoff.Thiswillmaketheexperimentgofaster.
Ifyouwanttostopyourexperimentbeforeit’sfinished,pressthe“Abort”button.Anyresults
generatedsofarwillstillbesaved.
Whenalltherunshavefinished,theexperimentiscomplete.
AdvancedUsage
Runningfromthecommandline
ItispossibletorunBehaviorSpaceexperiments“headless”,thatis,fromthecommandline,
withoutanygraphicaluserinterface(GUI).Thisisusefulforautomatingrunsonasingle
machineoraclusterofmachines.
NoJavaprogrammingisrequired.ExperimentsetupscanbecreatedintheGUIandthenrun
laterfromthecommandline,or,ifyouprefer,youcancreateoreditexperimentsetups
directlyusingXML.
Howtouseit
RunNetLogousingtheincludedcommandlinescript.Thisisfoundintherootdirectoryof
yourNetLogoinstallationandisnamednetlogo-headless.shonMacandLinuxandnetlogo-
headless.batonWindows.Thenetlogo-headlessscriptsupportsthefollowingarguments:
--model <path>:pathnameofmodeltoopen(required)
--setup-file <path>:readexperimentsetupsfromthisfileinsteadofthemodelfile
--experiment <name>:nameofexperimenttorun
--table <path>:pathnametosendtableoutputto(or-forstandardoutput)
--spreadsheet <path>:pathnametosendtableoutputto(or-forstandardoutput)
--threads <number>:usethismanythreadstodomodelrunsinparallel,or1todisable
parallelruns.defaultstoonethreadperprocessor.
--min-pxcor <number>:overrideworldsizesettinginmodelfile
--max-pxcor <number>:overrideworldsizesettinginmodelfile
--min-pycor <number>:overrideworldsizesettinginmodelfile
--max-pycor <number>:overrideworldsizesettinginmodelfile
--modelisrequired.Ifyoudon’tspecify--experiment,youmustspecify--setup-file.By
defaultnoresultsaregenerated,soyou’llusuallywanttospecifyeither--tableor--
spreadsheet,orboth.Ifyouspecifyanyoftheworlddimensions,youmustspecifyallfour.
Note:Theremainderofthisguideusesnetlogo-headless.shtorefertotheNetLogo
Headlesslaunchscript.IfyouareusingWindows,pleasesubstitutenetlogo-headless.batfor
netlogo-headless.shineachexample.
Examples
ItiseasiestifyoucreateyourexperimentsetupaheadoftimeintheGUI,soitissavedas
partofthemodel.Torunanexperimentsetupsavedinamodel,hereisanexample
commandline:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment1 \
--table -
Forthistowork,Java(version1.8orlater)mustbeavailable.YoucanmakeJavaavailableto
headlessineitheroftwoways
1. SettheJAVA_HOMEenvironmentvariabletothepathtotheJavainstallation.Thisisthe
directoryoftheJavainstallationwhichcontainsa“bin”directory.
2. AddthedirectorycontainingtheJavaexecutabletothePATHenvironmentvariable
IfJAVA_HOMEisdefined,netlogo-headlesswillrunNetLogousingtheJavathatitpointsto,
ignoringtheversionofJavaavailableonthepath.
Afterthenamedexperimenthasrun,theresultsaresenttostandardoutputintableformat,
asCSV.(“-”ishowyouspecifystandardoutputinsteadofoutputtoafile.)
Whenrunningnetlogoheadless,itforcesthesystempropertyjava.awt.headlesstobetrue.
ThistellsJavatoruninheadlessmode,allowingNetLogotorunonmachineswhena
graphicaldisplayisnotavailable.
Therequired--modelargumentisusedtospecifythemodelfileyouwanttoopen.
The--experimentargumentisusedtospecifythenameoftheexperimentyouwanttorun.
(AtthetimeyoucreateanexperimentsetupintheGUI,youassignitaname.)
Here’sanotherexamplethatshowssomeadditional,optionalarguments:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment2 \
--max-pxcor 100 \
--min-pxcor -100 \
--max-pycor 100 \
--min-pycor -100
Notetheuseoftheoptional--max-pxcor,--max-pycor,etc.argumentstospecifyadifferent
worldsizethanthatsavedinthemodel.(It’salsopossiblefortheexperimentsetuptospecify
valuesfortheworlddimensions;iftheyarespecifiedbytheexperimentsetup,thenthereis
noneedtospecifythemonthecommandline.)
Sinceneither--tablenor--spreadsheetisspecified,noresultswillbegenerated.Thisis
usefuliftheexperimentsetupgeneratesalltheoutputyouneedbysomeothermeans,such
asexportingworldfilesorwritingtoatextfile.
Yetanotherexample:
netlogo-headless.sh \
--model Fire.nlogo \
--experiment experiment2 \
--table table-output.csv \
--spreadsheet spreadsheet-output.csv
Theoptional--table <filename>argumentspecifiesthatoutputshouldbegeneratedina
tableformatandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,than
theoutputissenttothestandardsystemoutputstream.Tabledataiswrittenasitis
generated,witheachcompleterun.
Theoptional--spreadsheet <filename>argumentspecifiedthatspreadsheetoutputshould
begeneratedandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,than
theoutputissenttothestandardsystemoutputstream.Spreadsheetdataisnotwrittenout
untilallrunsintheexperimentarefinished.
Notethatitislegaltospecifyboth--tableand--spreadsheet,andifyoudo,bothkindsof
outputfilewillbegenerated.
Hereisonefinalexamplethatshowshowtorunanexperimentsetupwhichisstoredina
separateXMLfile,insteadofinthemodelfile:
netlogo-headless.sh \
--model Fire.nlogo \
--setup-file fire-setups.xml \
--experiment experiment3
IftheXMLfilecontainsmorethanoneexperimentsetup,itisnecessarytousethe--
experimentargumenttospecifythenameofthesetuptouse.
InordertorunaNetLogo3Dexperiment,runheadlesswiththe--3Dargument,forexample:
netlogo-headless.sh \
--3D \
--model "Mousetraps 3D.nlogo3d" \
--experiment experiment1 \
--table -
Notethatyoushouldsupplya3Dmodelandtherearealso3Darguments--max-pzcor
<number>and--min-pzcor <number>.
Thenextsectionhasinformationonhowtocreatestandaloneexperimentsetupfilesusing
XML.
SettingupexperimentsinXML
Wedon’tyethavedetaileddocumentationonauthoringexperimentsetupsinXML,butifyou
alreadyhavesomefamiliaritywithXML,thenthefollowingpointersmaybeenoughtogetyou
started.
ThestructureofBehaviorSpaceexperimentsetupsinXMLisdeterminedbyaDocument
TypeDefinition(DTD)file.TheDTDisstoredinNetLogo.jar,assystem/behaviorspace.dtd.
(JARfilesarealsozipfiles,soyoucanextracttheDTDfromtheJARusingJava’s“jar”utility
orwithanyprogramthatunderstandszipformat.)
TheeasiestwaytolearnwhatsetupslooklikeinXML,though,istoauthorafewofthemin
BehaviorSpace’sGUI,savethemodel,andthenexaminetheresulting.nlogofileinatext
editor.Theexperimentsetupsarestoredtowardstheendofthe.nlogofile,inasectionthat
beginsandendswithaexperimentstag.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>
Inthisexample,onlyoneexperimentsetupisgiven,butyoucanputasmanyasyouwant
betweenthebeginningandendingexperimentstags.
BetweenlookingattheDTD,andlookingatexamplesyoucreateintheGUI,itwillhopefully
beapparenthowtousethetagstospecifydifferentkindofexperiments.TheDTDspecifies
whichtagsarerequiredandwhichareoptional,whichmayberepeatedandwhichmaynot,
andsoforth.
WhenXMLforexperimentsetupsisincludedinamodelfile,itdoesnotbeginwithanyXML
headers,becausenotthewholefileisXML,onlypartofit.Ifyoukeepexperimentsetupsin
theirownfile,separatefromthemodelfile,thentheextensiononthefileshouldbe.xmlnot
.nlogo,andyou’llneedtobeginthefilewithproperXMLheaders,asfollows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE experiments SYSTEM "behaviorspace.dtd">
Thesecondlinemustbeincludedexactlyasshown.Inthefirstline,youmayspecifya
differentencodingthanUTF-8,suchasISO-8859-1.
AdjustingJVMParameters
OpeningtheNetLogoHeadlesslauncherscriptwillshowtheoptionsusedtolaunchjava
whenrunningNetLogoHeadless.YoucanadjustvariousJVMparametersinthisscript.You
mayalsopassinJavapropertiesstartingwith-Dtothelauncher.
Notetheuseof-Xmxtospecifyamaximumheapsizeofonegigabyte.Ifyoudon’tspecifya
maximumheapsize,youwillgetyourVM’sdefaultsize,whichmaybeunusablysmall.(One
gigabyteisanarbitrarysizewhichshouldbemorethanlargeenoughformostmodels;you
canspecifyadifferentlimitifyouwant.)
Notetheuseof-Dfile.encoding=UTF-8.ThisforcesallfileI/OtouseUTF-8encoding.Doing
soensuresthatNetLogocanloadallmodelsconsistently,andthatfile-*primitiveswork
consistentlyonallplatforms,includingmodelscontainingUnicodecharacters.
ControllingAPI
IfBehaviorSpaceisnotsufficientforyourneeds,apossiblealternativeistouseour
ControllingAPI,whichletsyouwriteJavacodethatcontrolsNetLogo.TheAPIletsyourun
BehaviorSpaceexperimentsfromJavacode,or,youcanwritecustomcodethatcontrols
NetLogomoredirectlytodoBehaviorSpace-likethings.SeetheControllingsectionofthe
UserManualforfurtherdetailsonbothpossibilities.
SystemDynamicsGuide
NetLogo6.0.4UserManual
Thisguidehasthreeparts:
WhatistheSystemDynamicsModeler?:Ageneraldescriptionofthetool,includingtheideasand
principlesbehindit.
HowItWorks:Describestheinterfaceandhowyouuseit.
Tutorial:Wolf-SheepPredation(aggregate):WalksyouthroughcreatingamodelwiththeSystem
DynamicsModeler.
WhatistheNetLogoSystemDynamicsModeler?
SystemDynamicsisatypeofmodelingwhereyoutrytounderstandhowthingsrelatetooneanother.Itisalittle
differentfromtheagent-basedapproachwenormallyuseinNetLogomodels.
Withtheagent-basedapproachweusuallyuseinNetLogo,youprogramthebehaviorofindividualagentsand
watchwhatemergesfromtheirinteraction.InamodelofWolf-SheepPredation,forexample,youproviderules
forhowwolves,sheepandgrassinteractwitheachother.Whenyourunthesimulation,youwatchtheemergent
aggregate-levelbehavior:forexample,howthepopulationsofwolvesandsheepchangeovertime.
WiththeSystemDynamicsModeler,youdon’tprogramthebehaviorofindividualagents.Instead,youprogram
howpopulationsofagentsbehaveasawhole.Forexample,usingSystemDynamicstomodelWolf-Sheep
Predation,youspecifyhowthetotalnumberofsheepwouldchangeasthetotalnumberofwolvesgoesupor
down,andviceversa.Youthenrunthesimulationtoseehowbothpopulationschangeovertime.
TheSystemDynamicsModelerallowsyoutodrawadiagramthatdefinesthesepopulations,or“stocks”,and
howtheyaffecteachother.TheModelerreadsyourdiagramandgeneratestheappropriateNetLogocode–
globalvariables,proceduresandreporters–torunyourSystemDynamicsmodelinsideofNetLogo.
BasicConcepts
ASystemDynamicsdiagramismadeoffourkindsofelements:Stocks,Variables,FlowsandLinks.
AStockisacollectionofstuff,anaggregate.Forexample,aStockcanrepresentapopulationofsheep,the
waterinalake,orthenumberofwidgetsinafactory.
AFlowbringsthingsinto,oroutofaStock.Flowslooklikepipeswithafaucetbecausethefaucetcontrolshow
muchstuffpassesthroughthepipe.
AVariableisavalueusedinthediagram.ItcanbeanequationthatdependsonotherVariables,oritcanbea
constant.
ALinkmakesavaluefromonepartofthediagramavailabletoanother.Alinktransmitsanumberfroma
VariableoraStockintoaStockoraFlow.
TheSystemDynamicsModelerfiguresouthowthevalueofyourStockschangeovertimebyestimatingthem
overandover.Theestimationisn’talwaysperfect,butyoucanaffectitsaccuracybychangingthevalueofdt.As
dtdecreases,youestimatethemodelmorefrequently,soitgetsmoreaccurate.However,decreasingdtalso
makesthemodelslower.
SampleModels
TherearefourbasicmodelsintheSampleModelssectionoftheNetLogoModelsLibrarythatdemonstratethe
useoftheSystemDynamicsModeler.Allfourbasicmodelsexplorepopulationgrowth(and,inmodelswith
predation,populationdecline).
ExponentialGrowthandLogisticGrowtharesimpleexamplesofgrowthinonestock.
WolfSheepPredation(SystemDynamics)isanexampleofasystemwithmultiplestocksinfluencingone
another.Itmodelsapredator-preyecosystemusingtheSystemDynamicsModeler.
WolfSheepPredation(DockedHybrid)isanexampleofamodelthatrunsboththeaSystemDynamicsmodel
andanagent-basedmodelside-by-side.ItrunstheSystemDynamicsimplementationofWolf-SheepPredation
nexttotheagent-basedWolfSheepPredationmodelfromtheBiologysectionofSampleModels.
HowitWorks
ToopentheSystemDynamicsModeler,choosetheSystemDynamicsModeleritemintheToolsmenu.The
SystemDynamicsModelerwindowwillappear.
DiagramTab
TheDiagramtabiswhereyoudrawyourSystemDynamicsdiagram.
Thetoolbarcontainsbuttonstoedit,deleteandcreateitemsinyourdiagram.
CreatingDiagramElements
ASystemDynamicsdiagramismadeupoffourkindsofcomponents:Stocks,Variables,FlowsandLinks.
Stock
TocreateaStock,presstheStockbuttoninthetoolbarandclickinthediagramareabelow.AnewStock
appears.EachStockrequiresauniquename,whichbecomesaglobalvariable.Stocksalsorequirean
**Initialvalue**.Itcanbeanumber,avariable,acomplexNetLogoexpression,oracalltoaNetLogo
reporter.
Variable
TocreateaVariable,presstheVariablebuttonandclickonthediagram.EachVariableintheSystem
DynamicsModelrequiresauniquename,whichbecomesthenameofaprocedure,oraglobalvariable.
Variablesalsorequirean**Expression**.Thisexpressioncanbeanumber,avariable,acomplexNetLogo
expression,oracalltoaNetLogoreporter.
Flow
TocreateaFlow,presstheFlowbutton.ClickandholdwhereyouwanttheFlowtobegin--eitherona
Stockorinanemptyarea--anddragthemousetowhereyouwanttheFlowtoend--onaStockorinan
emptyarea.EachFlowrequiresauniquename,whichbecomesaNetLogoreporter.Flowsrequirean
**Expression**,whichistherateofflowfromtheinputtotheoutput.Thisexpressioncanbeanumber,a
variable,acomplexNetLogoexpression,oracalltoaNetLogoreporter.Ifthevalueisnegative,theflowis
intheoppositedirection.
WhenmorethanoneFlowisconnectedtoaStock,itisimportanttoconsiderhowtheyshouldinteractwith
oneanother.NetLogowillnotenforcethattheFlowsoutofastockoccurinanyparticularorder.Also,
NetLogowillnotensurethatthesumofFlowsoutofaStockarelessthanorequaltothevalueofthe
Stock.ThesebehaviorscanbeimplementedexplicitlywhencreatingtheExpressionforaFlow.
Forexample,iftheFlowisdefinedasaconstantvalue,10,youcanensureitneverdrawsmorethanthe
valueoftheStockbyusingtheminprimitive:min (list stock 10).IfIwantFlowAtodepleteaStock
beforeFlowBiscalculated,IcanlinkFlowAtoFlowBandmodifyFlowBtosubtractFlowA’svaluefrom
thestock:min (list (max (list 0 (stock - flow-a))) 10).
Link
TocreateaLink,clickandholdonthestartingpointforthelink--aVariable,StockorFlow--anddragthe
mousetothedestinationVariableorFlow.
WorkingwithDiagramElements
WhenyoucreateaStock,Variable,orFlow,youseearedquestion-markontheelement.Thequestion-mark
indicatesthattheelementdoesn’thaveanameyet.TheredcolorindicatesthattheStockisincomplete:it’s
missingoneormorevaluesrequiredtogenerateaSystemDynamicsmodel.Whenadiagramelementis
complete,thenameturnsblack.
Selecting:Toselectadiagramelement,clickonit.Toselectmultipleelements,holdtheshiftkey.Youcanalso
selectoneormoreelementsbydraggingaselectionbox.
Editing:Toeditadiagramelement,selecttheelementandpressthe“Edit”buttononthetoolbar.Orjustdouble-
clicktheelement.(YoucaneditStocks,FlowsandVariables,butyoucan’teditLinks).
Moving:Tomoveadiagramelement,selectitanddragthemousetoanewlocation.
Editingdt
Ontherightsideofthetoolbaristhedefaultdt,theintervalusedtoapproximatetheresultsofyourSystem
Dynamicsmodel.Tochangethevalueofthedefaultdtforyouraggregatemodel,presstheEditbuttonnextto
thedtdisplayandenteranewvalue.
Errors
Whenyouclickthe“check”buttonorwhenyoueditastock,flow,orvariablethemodelerwillautomatically
generatetheNetLogocodethecorrespondstoyourdiagramandtrytocompilethatcode.Ifthereisanerrorthe
Codetabwillturnredandamessagewillappear,andtheportionofthegeneratedcodethatiscausingthe
troublewillbehighlighted.
Thisshouldgiveyouabetterideawhichelementinthediagramiscausingtheproblem.
CodeTab
TheSystemDynamicsModelergeneratesNetLogovariablesandproceduresbasedonthecontentsofyour
diagram.Theseproceduresarewhatmakethediagramactuallyperformcalculations.TheCodetabinthe
SystemDynamicsModelerwindowdisplaystheNetLogoproceduresgeneratedfromyourdiagram.
Youcan’teditthecontentsoftheCodetab.TomodifyyourSystemDynamicsmode,editthediagram.
Let’stakeacloserlookathowthegeneratedcoderelatestothediagram:
Stockscorrespondtoaglobalvariablethatisinitializedtothevalueorexpressionyouprovidedinthe
Initialvaluefield.EachStockwillbeupdatedeverystepbasedontheFlowsinandout.
FlowscorrespondtoaprocedurethatcontainstheexpressionyouprovidedintheExpressionfield.
Variablescaneitherbeglobalvariablesorprocedures.IftheExpressionyouprovidedisaconstantitwill
beaglobalvariableandinitializedtothatvalue.IfyouusedamorecomplicatedExpressiontodefinethe
VariableitwillcreateaprocedurelikeaFlow.
ThevariablesandproceduresdefinedinthistabareaccessibleinthemainNetLogowindow,justlikethe
variablesandproceduresyoudefineyourselfinthemainNetLogoCodetab.Youcancalltheproceduresfrom
themainCodetab,fromtheCommandCenter,orfrombuttonsintheInterfacetab.Youcanrefertotheglobal
variablesanywhere,includinginthemainCodetabandinmonitors.
Therearethreeimportantprocedurestonotice:system-dynamics-setup,system-dynamics-go,andsystem-
dynamics-do-plot.
system-dynamics-setupinitializestheaggregatemodel.Itsetsthevalueofdt,callsreset-ticks,andinitializes
yourstocksandyourconverters.Converterswithaconstantvalueareinitializedfirst,followedbythestockswith
constantvalues.Theremainingstocksareinitializedinalphabeticalorder.
system-dynamics-gorunstheaggregatemodelfordttimeunits.ItcomputesthevaluesofFlowsandVariables
andupdatesthevalueofStocks.Italsocallstick-advancewiththevalueofdt.ConvertersandFlowswithnon-
constantExpressionswillbecalculatedonlyoncewhenthisprocedureiscalled,however,theirorderof
evaluationisundefined
system-dynamics-do-plotplotsthevaluesofStocksintheaggregatemodel.Tousethis,firstcreateaplotinthe
mainNetLogowindow.YouthenneedtodefineaplotpenforeachStockyouwanttobeplotted.Thisprocedure
willusethecurrentplot,whichyoucanchangeusingtheset-current-plotcommand.
TheSystemDynamicsModelerandNetLogo
ThediagramyoucreatewiththeSystemDynamicsModeler,andtheproceduresgeneratedfromyourdiagram,
arepartofyourNetLogomodel.WhenyouasavetheNetLogomodel,yourdiagramissavedwithit,inthesame
file.
Tutorial:Wolf-SheepPredation
Let’screateamodelofWolf-SheepPredationwiththeSystemDynamicsModeler.
Step1:SheepReproduction
OpenanewmodelinNetLogo.
LaunchtheSystemDynamicsModelerintheToolsmenu.
Ourmodelwillhaveapopulationofwolvesandapopulationofsheep.Let’sstartwiththesheep.First,createa
StockthatholdsapopulationofSheep.
PresstheStockbuttoninthetoolbar.
Clickinthediagramarea.
YouseeaStockwitharedquestion-markinthemiddle.
Double-clicktheStocktoedit.
Namethestocksheep
Settheinitialvalueto100.
DeselecttheAllowNegativeValuescheckbox.Itdoesn’tmakesensetohavenegativesheep!
Oursheeppopulationcanincreaseifnewsheepareborn.Toaddthistoourdiagram,wecreateaFlowintothe
stockofsheep.
ClickontheFlowbuttoninthetoolbarandpressthemousebuttoninanemptyareatotheleft
ofthesheepStock.DragtheFlowtotherightuntilitconnectstothesheepStockandletgo.
EdittheFlowandnameitsheep-births.
Fornow,enteraconstant,suchas1,intotheExpressionfield.
Thenumberofsheepbornduringaperiodoftimedependsonthenumberofsheepthatarealive:moresheep
meansmorereproduction.
DrawaLinkfromthesheepStocktothesheep-birthsFlow.
Therateofsheepbirthsalsodependsonsomeconstantfactorsthatarebeyondthescopeofthismodel:the
rateofreproduction,etc.
CreateaVariableandnameitsheep-birth-rate.Setitsvalueto0.04.
DrawaLinkfromthesheep-birth-rateVariabletothesheep-births.
Yourdiagramshouldlooksomethinglikethis:
Ourdiagramhasthecorrectstructurebutwearen’tyetfinishedbecauseittheamountofsheepflowingintothe
stockdoesn’tdependuponthenumberofsheepandsheepbirthrate.
Editthesheep-birthsFlowandsettheexpressiontosheep-birth-rate * sheep.
Wenowhaveacompletediagram.ToseetheNetLogocodegeneratedbyourdiagram,youcanclickonthe
CodetaboftheSystemDynamicsModelerwindow.Itlookslikethis:
Step2:NetLogoIntegration
OnceyoucreateanaggregatemodelwiththeSystemDynamicsModeler,youcaninteractwiththemodel
throughthemainNetLogointerfacewindow.Let’sbuildourNetLogomodeltorunthecodegeneratedbyour
diagram.We’llneedasetupandgobuttonswhichcallthesystem-dynamics-setupandsystem-dynamics-go
procedurescreatedbytheSystemDynamicsModeler.Andwe’llwantamonitorandaplottowatchthechanges
insheeppopulation.
SelectthemainNetLogowindow
IntheCodetab,write:
to setup
ca
system-dynamics-setup
end
to go
system-dynamics-go
system-dynamics-do-plot
end
MovetotheInterfacetab
Createasetupbutton
Createagobutton(don’tforgettomakeitforever)
Createasheepmonitor.
Createaplotcalled“populations”withapennamed“sheep”.
Nowwe’rereadytorunourmodel.
Pressthesetupbutton.
Don’tpressthe“go”buttonyet.Instead,typegofourorfivetimesintotheCommandCenter.
Noticewhathappens.Thesheeppopulationincreasesexponentially.Afterfourorfiveiterations,wehavean
enormousnumberofsheep.That’sbecausewehavesheepreproduction,butoursheepneverdie.
Tofixthat,let’sfinishourdiagrambyintroducingapopulationofwolveswhicheatsheep.
Step3:WolfPredation
MovebacktotheSystemDynamicswindow
Addastockofwolves
AddFlows,VariablesandLinkstomakeyourdiagramlooklikethis:
AddonemoreFlowfromthewolvesStocktotheFlowthatgoesoutoftheSheepstock.
Fillinthenamesofthediagramelementssoitlookslikethis:
where
initial-valueofwolvesis30,
wolf-deathsiswolves * wolf-death-rate,
wolf-death-rateis0.15,
predator-efficiencyis.8,
wolf-birthsiswolves * predator-efficiency * predation-rate * sheep ,
predation-rateis3.0E-4,
andsheep-deathsissheep * predation-rate * wolves.
Adjustthedtofthesystemdynamicsmodelbyselecting“Edit”nexttodtinthetoolbarofthe
systemdynamicsmodeler.Inthedialogthatappears,enter0.01.
Nowwe’rereallydone.
GobacktothemainNetLogowindow
Addaplotpennamed“wolves”tothepopulationplot
PresssetupandgotoseeyourSystemDynamicsModelerdiagraminaction.
Youseeaplotofthepopulationsthatlookslikethis:
HubNetGuide
NetLogo6.0.4UserManual
ThissectionoftheUserManualintroducestheHubNetsystemandincludesinstructionsto
setupandrunaHubNetactivity.
HubNetisatechnologythatletsyouuseNetLogotorunparticipatorysimulationsinthe
classroom.Inaparticipatorysimulation,awholeclasstakespartinenactingthebehaviorofa
systemaseachstudentcontrolsapartofthesystembyusinganindividualdevice,suchasa
networkedcomputer.
Forexample,intheGridlocksimulation,eachstudentcontrolsatrafficlightinasimulatedcity.
Theclassasawholetriestomaketrafficflowefficientlythroughthecity.Asthesimulation
runs,dataiscollectedwhichcanafterwardsbeanalyzedonacomputer.
Formoreinformationonparticipatorysimulationsandtheirlearningpotential,pleasevisitthe
ParticipatorySimulationsProjectwebsite.
UnderstandingHubNet
NetLogo
NetLogoisaprogrammablemodelingenvironment.Itcomeswithalargelibraryofexisting
simulations,bothparticipatoryandtraditional,thatyoucanuseandmodify.Contentareas
includesocialscienceandeconomics,biologyandmedicine,physicsandchemistry,and
mathematicsandcomputerscience.Youandyourstudentscanalsouseittobuildyourown
simulations.
IntraditionalNetLogosimulations,thesimulationrunsaccordingtorulesthatthesimulation
authorspecifies.HubNetaddsanewdimensiontoNetLogobylettingsimulationsrunnotjust
accordingtorules,butbydirecthumanparticipation.
SinceHubNetbuildsuponNetLogo,werecommendthatbeforetryingHubNetforthefirst
time,youbecomefamiliarwiththebasicsofNetLogo.TogetstartedusingNetLogomodels,
seeTutorial#1:RunningModelsintheNetLogoUsersManual.
HubNetArchitecture
HubNetsimulationsarebasedonaclient/serverarchitecture.Theactivityleaderusesthe
NetLogoapplicationtorunaHubNetactivity.WhenNetLogoisrunningaHubNetactivity,we
refertoitasaHubNetserver.Participantsuseaclientapplicationtologinandinteractwith
theHubNetserver.
WhileHubNetisonlysupportedviatheJavaDesktopclientsatthemoment,wehopetoadd
supportforothertypesofclientssuchastabletsandphonesinthefuture.
ComputerHubNet
Activities
ThefollowingactivitiesareavailableintheModelsLibrary,intheHubNetActivitiesfolder.
InformationonhowtorunthemodelsandactivitiescanbefoundintheInfotabofeach
model.Additionaldiscussionofeducationalgoalsandwaystoincorporatemanyofthe
activitiesintoyourclassroomintheParticipatorySimulationsGuideontheParticipatory
SimulationsProjectwebsite.
BugHuntersCamouflage-studentshuntbugsandcamouflagingemerges.
DiceStalagmiteHubNet-studentsrolldiceandexplorethespaceofdependentand
independentevents.
Disease-Adiseasespreadsthroughthesimulatedpopulationofstudents.
DiseaseDoctors-AslightmodificationtotheDiseaseactivitywheresomestudentscan
recoverfromthedisease.
Gridlock-Studentsusetrafficlightstocontroltheflowoftrafficthroughacity.
Polling-Askstudentsquestionsandplottheiranswers.
RootBeerGame-AnadaptationofapopulargamecreatedatMITintheearly1960s
thatshowshowsmalldelaysinadistributionsystemcancreatebigproblems.
Sampler-Studentsengageinstatisticalanalysisasindividualsandasaclassroom.
Throughtheseactivities,studentsdiscoverthemeaninganduseofbasicconceptsin
statistics.
TragedyoftheCommons-Studentsworkasfarmerssharingacommonresource.
Clients
TousetheclientapplicationyousimplyneedtolaunchtheHubNetclientapplicationthatis
bundledwithNetLogo.
Requirements
TouseComputerHubNet,youneedanetworkedcomputerwithNetLogoinstalledforthe
server.Whenusingtheclientapplicationyouwillalsoneedanetworkedcomputerwith
NetLogoinstalledforeachparticipant.Whenusinginclassroomsettingswealsosuggestan
attachedprojectorfortheleadertoprojecttheentiresimulationtotheparticipants.
Startinganactivity
You’llfindtheHubNetactivitiesinNetLogo’sModelsLibrary,intheHubNetActivitiesfolder.
Wesuggestdoingafewpracticerunsofanactivitybeforetryingitinfrontofaclass.
OpenaComputerHubNetmodel.NetLogowillpromptyoutoenterthenameofyournew
HubNetsession.Thisisthenamethatparticipantswillusetoidentifythisactivity.Youmay
alsoseeabroadcastnetworkselectiondropdownforwhichmoreextensivedocumentationis
availableintheFAQ.Fornow,justenteranameandpressStart.
NetLogowillopentheHubNetControlCenter,whichletsyouinteractwiththeHubNetserver.
You,astheleader,shouldthennotifyeveryonethattheymayjoin.Tojointheactivity,
participantslaunchtheHubNetClientapplicationandentertheirname.Theyshouldseeyour
activitylistedandcanjoinyouractivitybyselectingitandpressingEnter.Iftheactivityyou
startedisnotlistedthestudentcanentertheserveraddressmanuallywhichcanbefoundin
theHubNetControlCenter.
HubNetControlCenter
TheHubNetControlCenterletsyouinteractwiththeHubNetserver.Itdisplaysthename,
activity,addressandportnumberofyourserver.The“Mirror2DViewonclients”checkbox
controlswhethertheHubNetparticipantscanseetheviewontheirclients,assumingthereis
aviewintheclientsetup.The“Mirrorplotsonclients”checkboxcontrolswhetherparticipants
willreceiveplotinformation.
Theclientlistontherightdisplaysthenamesofclientsthatarecurrentlyconnectedtoyou
activity.Toremoveaparticipantfromtheactivity,selecttheirnameinthelistandpressthe
Kickbutton.TolaunchyourownHubNetclientpresstheLocalbutton,thisisparticularly
usefulwhenyouaredebugginganactivity.The“Reset”buttonkicksoutallcurrentlyloggedin
clientsandreloadstheclientinterface.
ThelowerpartoftheControlCenterdisplaysmessageswhenaparticipantjoinsorleavesthe
activity.Tobroadcastamessagetoalltheparticipants,clickonthefieldatthebottom,type
yourmessageandpressBroadcastMessage.
Troubleshooting
IstartedaHubNetactivity,butwhenparticipantsopenaHubNetClient,my
activityisn’tlisted.
Onsomenetworks,theHubNetClientcannotautomaticallydetectaHubNetserver.Tellyour
participantstomanuallyentertheserveraddressandportofyourHubNetserver,which
appearintheHubNetControlCenter.
Note:Thetechnicaldetailsonthisareasfollows.Inorderfortheclienttodetecttheserver,
multicastroutingmustbeavailablebetweenthem.Notallnetworkssupportmulticastrouting.
Inparticular,networksthatusetheIPsecprotocoltypicallydonotsupportmulticast.The
IPsecprotocolisusedonmanyVirtualPrivateNetworks(VPNs).
Whenaparticipanttriestoconnecttoanactivity,nothinghappens(theclient
appearstohangorgivesanerrorsayingthatnoserverwasfound).
Ifyourcomputerornetworkhasafirewall,itmaybeimpedingtheHubNetserverfrom
communicating.Makesurethatyourcomputerandnetworkarenotblockingportsusedby
theHubNetserver(ports9173-9180).
TheviewontheHubNetclientisgray.
Verifythatthe“Mirror2Dviewonclients”checkboxintheHubNetControlCenteris
selected.
Makesurethatthedisplayswitchinthemodelison.
Ifyouhavemadechangestothesizeoftheviewontheserveryoumayneedtopress
the“Reset”buttonintheControlCentertoensuretheclientsgetthenewsize.
ThereisnoviewontheHubNetclient.
Someactivitiesdon’thaveaviewontheclient.Ifyouwanttoaddaviewsimplyselect
“HubNetClientEditor”fromtheToolsMenuandaddaviewlikeanyotherwidget.Makesure
topressthe“Reset”buttonbeforehavingclientslogin.
Ican’tquitaHubNetclient.
Youwillhavetoforcetheclienttoquit.OnOSX,forcequittheapplicationbyselectingForce
Quit…intheApplemenu.OnWindows,pressCtrl-Alt-DeletetoopentheTaskManager,
selectHubNetClientandpressEndTask.
MycomputerwenttosleepwhilerunningaHubNetactivity.WhenIwokethe
computerup,IgotanerrorandHubNetwouldn’tworkanymore.
TheHubNetservermaystopworkingifthecomputergoestosleep.Ifthishappens,quitthe
NetLogoapplicationandstartover.Changethesettingsonyourcomputersoitwon’tsleep
again.
Myproblemisnotaddressedonthispage.
SeeContactingUs.
KnownLimitations
IfHubNetmalfunctions,seethebugreportinginformationatContactingUs.
Pleasenotethat:
HubNethasnotyetbeenextensivelytestedwithlargenumbersofclients(i.e.more
thanabout25).Unexpectedresultsmayoccurwithmoreclients.
Out-of-memoryconditionsarenothandledgracefully
Sendinglargeamountsofplottingmessagestotheclientscantakealongtime.
NetLogodoesnothandlemaliciousclientsinarobustmanner(inotherwords,itislikely
vulnerabletodenial-of-servicetypeattacks).
Performancedoesnotdegradegracefullyoversloworunreliablenetworkconnections.
Ifyouareonawirelessnetworkorsub-LAN,theIPaddressintheHubNetControl
CenterisnotalwaystheentireIPaddressoftheserver.
ComputerHubNethasonlybeentestedonLANs,andnotondial-upconnectionsor
WANs.
Teacherworkshops
ForinformationonupcomingworkshopsandNetLogoandHubNetuseintheclassroom,
pleasecontactus.
HubNetAuthoringGuide
TolearnaboutauthoringormodifyingHubNetactivities,seetheHubNetAuthoringGuide.
RunningHubNetinheadlessmode
TolearnaboutrunningHubNetactivitiesfromthecommandline,withnoGUIontheserver,
seetheHubNetsectionintheControllingGuide.
Gettinghelp
IfyouhaveanyquestionsaboutHubNetorneedhelpgettingstarted,contactus.
HubNetAuthoringGuide
NetLogo6.0.4UserManual
ThisguideshowshowtounderstandandmodifythecodeofexistingHubNetactivitiesand
writeyourownnewones.ItassumesyouarefamiliarwithrunningHubNetactivities,basic
NetLogocodeandNetLogointerfaceelements.FormoregeneralinformationaboutHubNet
seetheHubNetGuide.
CodingHubNetactivities
ManyHubNetactivitieswillsharebitsofthesamecode.Thatisthecodethatitusedtosetup
thenetworkandthecodethatisusedtoreceiveinformationfromandsendinformationtothe
clients.Ifyouunderstandthiscodeyoushouldbeabletoeasilymakemodificationsto
existingactivitiesandyoushouldhaveagoodstartonwritingyourownactivities.Togetyou
startedwehaveprovidedaTemplatemodel(inHubNetActivities->CodeExamples)that
containsthemostbasiccomponentsthatwillbeinthemajorityofHubNetactivities.You
shouldbeabletousethisactivityasastartingpointformostprojects.
CodeExample:Template
Setup
TomakeaNetLogomodelintoaHubNetactivityyoumustfirstinitializethenetwork.Inmost
HubNetactivitiesyouwillusethestartupproceduretoinitializethenetwork.startupisa
specialprocedurethatNetLogorunsautomaticallywhenyouopenanymodel.Thatmakesita
goodplacetoputcodethatyouwanttorunonceandonlyonce(nomatterhowmanytimes
theuserrunsthemodel).ForHubNetweputthecommandthatinitializesthenetworkin
startupbecauseoncethenetworkissetupwedon’tneedtodosoagain.Weinitializethe
systemusinghubnet-reset,whichwillasktheuserforasessionnameandopenupthe
HubNetControlCenter.Hereisthestartupprocedureinthetemplatemodel:
to startup
hubnet-reset
end
Nowthatthenetworkisallsetupyoudon’tneedtoworryaboutcallinghubnet-resetagain.
Takealookatthesetupprocedureinthetemplatemodel:
to setup
cp
cd
clear-output
ask turtles
[
set step-size 1
hubnet-send user-id "step-size" step-size
]
end
Forthemostpartitlookslikemostothersetupprocedures,however,youshouldnoticethatit
doesnotcallclear-all.Inthismodel,andinthegreatmajorityofHubNetactivitiesinthe
ModelsLibrary,wehaveabreedofturtlesthatrepresentthecurrentlyloggedinclients.Inthis
casewe’vecalledthisbreedstudents.Wheneveraclientlogsinwecreateastudentand
recordanyinformationwemightneedlateraboutthatclientinaturtlevariable.Sincewedon’t
wanttorequireuserstologoutandlogbackineverytimewesetuptheactivitywedon’twant
tokillalltheturtles,instead,wewanttosetallthevariablesbacktoinitialvaluesandnotify
theclientsofanychangeswemake(moreonthatlater).
Receivingmessagesfromclients
DuringtheactivityyouwillbetransferringdatabetweentheHubNetclientsandtheserver.
MostHubNetactivitieswillcallaprocedureinthegoloopthatchecksfornewmessagesfrom
clientsinthiscaseit’scalledlistenclients:
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
Aslongastherearemessagesinthequeuethisloopfetcheseachmessageoneatatime.
hubnet-fetch-messagemakesthenextmessageinthequeuethecurrentmessageandsets
thereportershubnet-message-source,hubnet-message-tagandhubnet-messagetothe
appropriatevalues.Theclientssendmessageswhentheusersloginandlogoutanytimethe
usermanipulatesoneoftheinterfaceelements,thatis,pushesabutton,movesaslider,
clicksintheview,etc.Westepthrougheachmessageanddecidewhatactiontotake
dependingonthetypeofmessage(enter,exit,orother),thehubnet-message-tag(thename
oftheinterfaceelement),andthehubnet-message-sourceofthemessage(thenameofthe
clientthemessagecamefrom).
Onanentermessagewecreateaturtlewithauser-idthatmatchesthehubnet-message-
sourcewhichisthenamethateachuserentersuponenteringtheactivity,itisguaranteedto
beunique.
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
Atthispointwesetanyotherclientvariablestodefaultvaluesandsendthemtotheclientsif
appropriate.Wedeclaredastudents-ownvariableforeveryinterfaceelementontheclient
thatholdsstate,thatis,anythingthatwouldbeaglobalvariableontheserver,sliders,
choosers,switchesandinputboxes.Itisimportanttomakesurethatthesevariablesstay
synchronizedwiththevaluesvisibleontheclient.
Whentheclientslogouttheysendanexitmessagetotheserverwhichgivesyouachanceto
cleanupanyinformationyouhavebeenstoringabouttheclient,inthiscasewemerelyhave
toasktheappropriateturtletodie.
to remove-student
ask students with [user-id = hubnet-message-source]
[ die ]
end
Allothermessagesareinterfaceelementsidentifiedbythehubnet-message-tagwhichisthe
namethatappearsintheclientinterface.Everytimeaninterfaceelementchangesa
messageissenttotheserver.Unlessyoustorethestateofthevaluescurrentlydisplayedin
theclientinterfacewillnotbeaccessibleinotherpartsofthemodel.That’swhywe’ve
declaredastudents-ownvariableforeveryinterfaceelementthathasastate(sliders,
switches,etc).Whenwereceivethemessagefromtheclientwesettheturtlevariabletothe
contentofthemessage:
if hubnet-message-tag = "step-size"
[
ask students with [user-id = hubnet-message-source]
[ set step-size hubnet-message ]
]
Sincebuttonsdon’thaveanyassociateddatathereisgenerallynoassociatedturtlevariable,
insteadtheyindicateanactiontakenbytheclient,justaswitharegularbuttonthereisoften
procedureassociatedwitheachbuttonthatyoucallwheneveryoureceiveamessage
indicatingthebuttonhasbeenpressed.Thoughitiscertainlynotrequired,theprocedureis
oftenaturtleprocedure,thatis,somethingthatthestudentturtleassociatedwiththemessage
sourcecanexecute:
if command = "move left"
[ set heading 270
fd 1 ]
Sendingmessagestoclients
Asmentionedearlieryoucanalsosendvaluestoanyinterfaceelementsthatdisplay
information:monitors,sliders,switches,choosers,andinputboxes(notethatplotsandthe
viewarespecialcasesthathavetheirownsections).
Therearetwoprimitivesthatallowyoutosendinformationhubnet-sendandhubnet-
broadcast.Broadcastsendstheinformationtoalltheclients;sendsendstooneclient,ora
selectedgroup.
Assuggestedearlier,nothingontheclientupdatesautomatically.Ifavaluechangesonthe
server,itisyourresponsibilityastheactivityauthortoupdatemonitorsontheclient.
Forexample,sayyouhaveasliderontheclientcalledstep-sizeandamonitorcalledStep
Size(notethatthenamesmustbedifferent)youmightwriteupdatingcodelikethis:
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
]
]
Youcansendanytypeofdatayouwant,numbers,strings,lists,listsoflists,listsofstrings,
however,ifthedataisnotappropriateforthereceivinginterfaceelement(say,ifyouwereto
sendastringtoaslider)themessagewillbeignored.Hereareafewcodeexamplesfor
differenttypesofdata:
data
type hubnet-broadcastexample hubnet-sendexample
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"
listof
numbers hubnet-broadcast "L2" [1 2 3] hubnet-send hubnet-message-source
"L2" [1 2 3]
matrixof
numbers
hubnet-broadcast "[A]" [[1 2] [3
4]]
hubnet-send "susie" "[A]" [[1 2] [3
4]]
listof
strings
hubnet-broadcast "user-names"
[["jimmy" "susie"] ["bob"
"george"]]
hubnet-send "teacher" "user-names"
[["jimmy" "susie"] ["bob" "george"]]
Examples
Studythemodelsinthe“HubNetActivities”sectionoftheModelsLibrarytoseehowthese
primitivesareusedinpracticeintheCodetab.Diseaseisagoodonetostartwith.
Howtomakeaclientinterface
OpentheHubNetClientEditor,foundintheToolsMenu.Addanybuttons,sliders,switches,
monitors,plots,choosers,ornotesthatyouwantjustasyouwouldintheinterfacetab.You’ll
noticethattheinformationyouenterforeachofthewidgetsisslightlydifferentthaninthe
Interfacepanel.Widgetsontheclientdon’tinteractwiththemodelinthesameway.Instead
ofadirectlinktocommandsandreportersthewidgetssendmessagesbacktotheserverand
themodelthendetermineshowthosemessagesaffectthemodel.Allwidgetsontheclient
haveatagwhichisanamethatuniquelyidentifiesthewidget.Whentheserverreceivesa
messagefromthatwidgetthetagisfoundinhubnet-message-tag.
Forexample,ifyouhaveabuttoncalled“moveleft”,aslidercalled“step-size”,aswitchcalled
“all-in-one-step?”,andamonitorcalled“Location:”,thetagsfortheseinterfaceelementswill
beasfollows:
interface
element tag
moveleft moveleft
step-size step-size
all-in-one-step? all-in-one-step?
Location: Location:
Notethatyoucanonlyhaveoneinterfaceelementwithaspecificname.Havingmorethan
oneinterfaceelementwiththesametagintheclientinterfacewillresultinunpredictable
behaviorsinceitisnotclearwhichelementyouintendedtosendtheinformationto.
Viewupdatesontheclients
Viewmirroringletsviewsoftheworldbedisplayedinclientsaswellontheserver.View
mirroringisenabledusingacheckboxintheHubNetControlCenter.
Whenmirroringisenabled,clientviewsupdatewhenevertheviewontheserverdoes.To
avoidexcessivenetworktraffic,theviewshouldnotupdatemoreoftenthannecessary.
Thereforewestronglyrecommendusingtick-basedupdates,ratherthancontinuousupdates.
SeetheViewUpdatessectionoftheProgrammingGuideforanexplanationofthetwotypes
ofupdates.
Withtick-basedupdates,updateshappenwhenatickordisplaycommandruns.We
recommendusingthesecommandsonlyinsideaneveryblock,tolimitthefrequencyofview
updatesandthusalsolimitnetworktraffic.Forexample:
every 0.1
[
display
]
IfthereisnoViewintheclientsoriftheMirror2DViewonClientscheckboxintheHubNet
ControlCenterisnotchecked,thennoviewupdatesaresenttotheclients.
Clickingintheviewonclients
IftheViewisincludedintheclient,twomessagesaresenttotheservereverytimetheuser
clicksintheview.Thefirstmessage,whentheuserpressesthemousebutton,hasthetag
“View”.Thesecondmessage,sentwhentheuserreleasesthemousebutton,hasthetag
“MouseUp”.Bothmessagesconsistofatwoitemlistofthexandycoordinates.Forexample,
toturnanypatchthatwasclickedonbytheclientred,youwouldusethefollowingNetLogo
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 ]
]
Customizingtheclient’sview
Whenviewmirroringisenabled,bydefaultclientsseethesameviewtheactivityleadersees
ontheserver.Butyoucanchangethissothateachclientseessomethingdifferent,notjusta
literal“mirror”.
Youcanchangewhataclientseesintwodistinctways.Wecallthem“clientperspectives”
and“clientoverrides”.
Changingaclient’sperspectivemeansmakingit“watch”or“follow”aparticularagent,much
likethewatchandfollowcommandsthatworkwithordinaryNetLogomodels.Seethe
dictionaryentriesforhubnet-send-watch,hubnet-send-follow,andhubnet-reset-perspective.
CodeExample:ClientPerspectiveExample
Clientoverridesletyouchangetheappearanceofpatches,turtles,andlinksintheclient
views.Youcanoverrideanyofthevariablesaffectinganagent’sappearance,includingthe
hidden?variablecausingaturtleorlinktobevisibleorinvisible.Seethedictionaryentriesfor
hubnet-send-override,hubnet-clear-override,andhubnet-clear-overrides.
CodeExample:ClientOverridesExample
Plotupdatesontheclients
Ifplotmirroringisenabled(intheHubNetControlCenter)andaplotintheNetLogomodel
changesandaplotwiththeexactsamenameexistsontheclients,amessagewiththat
changeissenttotheclientscausingtheclient’splottomakethesamechange.Forexample,
let’spretendthereisaHubNetmodelthathasaplotcalledMilkSupplyinNetLogoandthe
clients.MilkSupplyisthecurrentplotinNetLogoandintheCommandCenteryoutype:
plot 5
Thiswillcauseamessagetobesenttoalltheclientstellingthemthattheyneedtoplota
pointwithayvalueof5inthenextpositionoftheplot.Notice,ifyouaredoingalotofplotting
allatonce,thiscangeneratealotofplottingmessagestobesenttotheclients.
ModelingCommonsGuide
NetLogo6.0.4UserManual
Introduction
TheModelingCommons(http://modelingcommons.org/)isaWeb-basedcollaborationsystemfor
NetLogomodelers.UsersoftheModelingCommonscanshare,download,modify,createvariations
of,commenton,andrunNetLogomodels–boththosethatareapartoftheNetLogomodels
library,andalsothosethathavebeenuploadedbyotherNetLogousers.
ByuploadingyourNetLogomodelstotheModelingCommons,youmakeiteasyforotherstosee,
review,andcommentonyourwork.Youcanoptionallykeepthemodelprivate,eithertoyourselfor
toagroupofyourchoice,ifyouaren’tcomfortablewithlettingeveryoneseethemodel.Youcan
alwayschangethepermissionsassociatedwithamodel,ifyouchangeyourmindlateron.
NetLogonowmakesitpossibletosavemodelstotheModelingCommons,justasyoucansave
themto.nlogofilesonyourowncomputer.Youcanaccessthisfunctionalitybyselecting“Uploadto
ModelingCommons”fromthe“File”menu.
UseoftheModelingCommonsisfreeofcharge.Youmayuseitforyourownpersonalwork,for
yourresearchgrouporcompany,orforaclassinwhichyouareastudentorteacher.TheModeling
CommonsissponsoredbytheCCL,thesamegroupthatdevelopsanddistributesNetLogo.
ModelingCommonsAccounts
InordertouploadmodelstotheModelingCommons,youmustfirstbearegistereduser.
Unregistereduserscanviewanddownloadmodels,butcannotupload,edit,orcommentonthem.
Thefirsttimethatyouinvoke“SavetoModelingCommons”inNetLogo,youwillbepromptedto
enteryoure-mailaddressandpassword.Ifyoualreadyhaveanaccount,thenyoucanenterthis
informationandclickonthe“Login”button.
Ifyoudon’tyethaveanaccountwiththeModelingCommons,thenyouwillneedtocreateone.
Clickonthe“CreateAccount”button,andentertherequestedinformation.Onceyouhavedoneso,
clickonthe“CreateAccount”button.Iftherearenoerrors,thenyouwillbepromptedtouploada
NetLogomodel.Alternatively,youmaygototheModelingCommonsitselfandregisterwithyour
Webbrowser.
UploadingModels
TherearethreewaystouploadamodeltotheModelingCommons:Uploading,updating,and
creatingachild(“forking”).Thefollowingsectionsdescribetheseindetail.
UploadANewModel
AnewmodelwillbecreatedintheModelingCommons,withitsownpage,description,andforum.
YoushouldusethisfunctionthefirsttimethatyousaveamodeltotheModelingCommons.
Youmustgiveyourmodelaname.Modelnamesarenotrequiredtobeunique;youcouldhave2or
moremodelswiththesamename,thoughwerecommendthatyounotdothis.
Bydefault,anyonecanview,fork,andupdateyourmodel.Youcanrestricttheabilitytoviewand
forkyourmodelbychangingthevisibilitypermission.Youcanrestricttheabilitytoupdateyour
modelbychangingthechangeabilitypermission.Inordertosetpermissionsformultiplepeople,
assignyourmodeltoagroup,andthenrestrictvisibilityorchangeabilitytomembersofthatgroup.
GroupscanbecreatedfromtheModelingCommons.Onceyouhaveuploadedyourmodel,youcan
editthepermissionsfromthemodel’sModelingCommonspage.
Youcanoptionallyuploadapreviewimagetoyourmodel.Thepreviewimagewillbedisplayed
alongsideyourmodelwheneveritisshownontheModelingCommons.Whileuploadingapreview
imageisoptional,wehighlyrecommendthatyoudoso,inoneofthefollowingthreeways:
The“Usecurrentimage”optiontellsNetLogotousethecurrentviewasyourpreview.We
recommendthatyoufirstrunthemodel,suchthatitshowsoffthekeyvisualfeatures.
The“Auto-generateimage”featureauto-generatesapreviewimagebyrunningrandom-seed 0
setup repeat 75 [ go ].Thisoptionwillonlybeenabledifyouhavedefinedsetupandgo
proceduresforNetLogotorun.
The“Imagefromfile”featureallowsyoutouploadanyPNGimage.Previewimagesworkbest
whentheyaresquare.
UploadAChildOfAnExistingModel(“forking”)
Savingamodelinthisway,sometimesknownas“forking,”doesnotchangeoroverwritethe
originalmodel.Rather,itcreatesanewmodelontheModelingCommons,muchasaplain“save”
woulddo,simultaneouslycreatingaparent-childrelationshipbetweentheoldmodelandthenew
one.Thisrelationshipcanbeseenonthe“family”tabforagivenmodel.Youmayforkanymodelfor
whichyouhave“view”permissions,includingonethatyoucannotchange.Youmaywish,for
example,tocreateavariationonamodelintheNetLogomodelslibrary.
Toforkamodel,youmustgiveyournewchildaname,aswellasselectanexistingmodeltofork.
Toindicatetheexistingmodel,starttypingthenameofthemodelthatyouwouldliketofork.Select
itsnamefromamongthesearchresults.
Finally,youmustenteradescriptionaboutwhatyouarechanginginyourchildmodel,andhowit
relatestoitsparent.
UpdatingAnExistingModel
UsethisoptionifyouhaveimprovedamodelthatalreadyexistsintheModelingCommons.Existing
attachments,discussions,andsocialtagswillbepreserved,butthemodelthatuserscandisplay,
run,anddownloadwillbeupdated.Youmayonlyupdateamodelforwhichyouhave“write”
permissions.
AllversionsofamodelaresavedintheModelingCommons,soyoushouldfeelfreetoexperiment
withnewideas.Ifsomethinggoeswrong,youcanalwaysrefertoanoldversionfromthe“history”
tabonamodel’spage.
Toindicatewhichmodelshouldbeupdated,starttypingthenameofthemodel.Selectthename
thatpopsupwiththesearchresults.Finally,enteradescriptionaboutwhatyouarechangingin
yournewversion.
Logging
NetLogo6.0.4UserManual
NetLogo’sloggingfacilityallowsresearcherstorecordstudentactionsforlateranalysis.
LogginginNetLogo,onceinitiated,isinvisibletothestudent.Theresearchercanchoosethe
typeofeventsloggedthroughaconfigurationfile.
NetLogousesthelog4jpackageforlogging.Ifyouhavepreviousexperiencewiththispackage
you’llfindlogginginNetLogofamiliar.
LoggingissupportedonlybythespecialNetLogoLoggingapplication.
Startinglogging
Thisdependsonwhatoperatingsystemyouareusing.
MacOSXorWindows
ThereisaspeciallogginglauncherintheNetLogodirectorycalledNetLogoLogging.Double
clickontheicon.
OnWindows,theNetLogodirectorycanbefoundatC:\Program Files,unlessyouchosea
differentlocationwhenyouinstalledNetLogo.
Linuxandothers
Toenablelogging,invokethenetlogo.shscriptasfollows:
netlogo.sh --logging netlogo_logging.xml
Youcouldalsomodifythescripttoincludetheseflags,orcopythescriptandmodifythecopy.
Youcanreplacenetlogo_logging.xmlwithanyvalidlog4jXMLconfigurationfile,whichwillbe
discussedinmoredetaillater.
Usinglogging
WhenNetLogostartsupitwillaskforausername.Thisnamewillappearinallthelogs
generatedduringthissession.
Wherelogsarestored
LogsarestoredintheOS-specifictempdirectory.OnmostUnix-likesystemsthatis/tmp.On
WindowsVistathelogscanbefoundinc:\Users\<user>\AppData\Local\Temp,where<user>is
theloggedinuser.OnMacOSX,thetempdirectoryvariesforeachuser.Youcandetermine
yourtempdirectorybyopeningtheTerminalapplicationandtypingecho $TMPDIR>atthe
prompt.
Therearetwoconveniencecommandsthatwillhelpyoumanagethelogs.__zip-log-files
filenamewillgatherallthelogsinthetempdirectoryandputtheminonezipfile,atthe
locationspecified.Afterdoing__zip-log-filestheexistinglogsarenotdeleted,youcando
soexplicitlybyusing__delete-log-files.
Thefollowingisachartdescribingthenameoftheloggersavailable,thetypeofeventseach
logs,atwhatlevel,andprovidesasampleoutputusingtheXMLLayout.Alltheloggersare
foundinorg.nlogo.log.Logger.Whenreferringtotheloggersintheconfigurationfileyou
shouldusethefullyqualifiedname.So,forexample,theloggerGLOBALSwouldactuallybe
org.nlogo.log.Logger.GLOBALS
Logger Events Level Example
GLOBALS aglobalvariable
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
boxesare
changed
throughthe
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
codeis
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
awidgetis
addedor
removedfrom
theinterface
info
<event logger="org.nlogo.log.Logger.WIDGETS"
timestamp="1177341058351"
level="INFO"
type="slider">
<name></name>
<action>added</action>
</event>
BUTTONS
abuttonis
pressedor 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 thespeedslider
changes info
<event logger="org.nlogo.log.Logger.SPEED"
timestamp="1177341042202"
level="INFO"
type="speed">
<value>0.0</value>
</event>
TURTLES turtlesdieor
areborn 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 linksdieorare
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
Howtoconfiguretheloggingoutput
Thedefaultloggingconfiguration(netlogo_logging.xml)lookssomethinglikethis:
NetLogodefines8loggers,alldescenddirectlyfromtherootlogger,whichmeansunlessyou
explicitlysettheproperties(appender,layout,andoutputlevel)intheconfigurationtheywill
inheritthemfromtheroot.InthedefaultconfigurationtherootissettolevelINFO,the
appenderisorg.nlogo.log.XMLFileAppenderandlayoutisorg.nlogo.log.XMLLayout.Together
thesegenerateanicelyformattedXMLfileasdefinedinthenetlogo_logging.dtdwhichis
basedonthelog4jdtd.IftheappenderisaFileAppender(includingtheXMLFileAppender)a
newfileisstarteachtimetheuseropensamodel.
<?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>
Thisconfiguration,firstdefinesanappendernamed“A1”oftypeXMLFileAppenderwithan
XMLLayout.Theappenderdefineswheretheloggingdatagoes,inthiscasethedatagoes
intoafile.Infact,ifNetLogoisgivenaFileAppenderitwillautomaticallystartanewfileevery
timetheuseropensanewmodel.TheXMLFileAppenderalsodoessomeformattingand
writestheappropriateheaderstothefile.Thelayoutdefineshowtowriteeachindividual
message.Unlessyouareanadvanceduserthereisnoneedchange(orworryabout)the
appenderorthelayout.
Attheendoftheconfigurationnoticethedefinitionoftherootlogger.Alloftheotherloggers
descendfromtherootloggerand,thus,inheritthepropertiesoftherootunlessexplicitlyset.
Thiscaseisfairlysimple,havingsetuptheappenderA1wemakethatthedefaultappender
fortheroot(andallotherloggers)andmakethedefaultpriority“INFO”.Messagesthatare
loggedattheINFOlevelorhigherwillbewritten,messagesloggedatlowerlevelswillnot.
NotethatwithonlyoneexceptionNetLogoalwayslogsatlevelINFO.Setstoglobalsthatdon’t
changethevalueoftheglobalareloggedatlevelDEBUG.Whichmeansthatthesemessages
aredisabledbydefault,sincedebugislowerlevelthaninfo.Therestofthebodyofthe
configurationfileoverridespropertiesoftherootloggerinafewspecificloggers(orcategories
astheyareknownintheconfigurationfile,thetermscanbeassumedtobesynonymousfor
theproposesofthisdocument).ThatisitturnsofftheWIDGET,TURTLES,andLINKS
loggers,bydefault.Tore-enablethemyoucanchangesthepriorityfromofftoinfo,likethis:
<category name="org.nlogo.log.Logger.TURTLES">
<priority value="info" />
</category>
oryoucansimplyremovetheentirereferencetothecategoryfromtheconfigurationfile,asit
isnotservinganyotherpurpose.
AdvancedConfiguration
ThisisonlyabasicintroductiontoconfigurationfilesforlogginginNetLogo.Therearemany
moreconfigurationoptionsavailablethroughthelog4jframework.Seethelog4j
documentation.
ControllingGuide
NetLogo6.0.4UserManual
NetLogocanbeinvokedandcontrolledbyanotherprogramrunningontheJavaVirtual
Machine.Forexample,youmightwanttocallNetLogofromasmallprogramthatdoes
somethingsimplelikeautomateaseriesofmodelruns.Or,youmightwanttoembed
NetLogomodelsinalargerapplication.
Formoreinformation,gohere.
MathematicaLink
NetLogo6.0.4UserManual
TheNetLogo-Mathematicalinkprovidesmodelerswithaneasytouse,real-timelinkbetween
NetLogoandMathematica.Together,thesetoolscanprovideuserswithahighlyinteractive,
self-documentingworkflowthatneithercanprovidealone.
Mathematicaincludesmanyofthetoolsthatagent-basedmodelersrelyonthroughoutthe
researchprocess:advancedimportcapabilities,statisticalfunctions,datavisualization,and
documentcreation.WiththeNetLogo-Mathematicalink,youcanrunallofthesetoolsside-by-
sidewithNetLogo.
BecauseallMathematicadocuments,ornotebooks,containcomments,code,images,
annotations,andinteractiveobjects,theintegrationofNetLogoandMathematicaprovidesa
morecompletesolutionforcomplexmodelexplorationforstudentsandresearchersalike.
ThebasicfunctionalityofthelinkismuchliketheNetLogoControllingAPI:youcanload
models,executecommands,andreportbackdatafromNetLogo.UnliketheControllingAPI,
whichisbasedonJava,allinteractionswiththelinkareinterpreted,makingitidealnotonly
forrapidlydesigningcustomBehaviorSpace-likeexperiments,butalsoasacompanionto
NetLogoindebuggingyourmodel.
FormoreinformationaboutMathematica,pleasevisittheWolframResearchwebsite.
WhatcanIdowithit?
HereareafewexamplesofwhatyoucandowiththeMathematica-NetLogolink.
Analyzeyourmodelinreal-timewithseamlesstwo-waydataconversion
Develophighquality,customvisualizationsofmodeldata
Collectdetailedsimulationdataacrosslargemulti-dimensionalparameterspaces
Rapidlydevelopinteractiveinterfacesforexploringmodelbehavior
Havedirectaccesstopatchesandnetworkdatawithbuilt-infunctions
Installation
TheNetLogo-MathematicalinksupportsMathematica10orgreater.ToinstalltheNetLogo-
Mathematicalink:
1. GotothemenubarinMathematica
2. ClickonFileandselectInstall…
3. IntheInstallMathematicaItemdialog
4. SelectPackageforTypeofitemtoinstall
5. ClickSource,andselectFromfile…
6. Inthefilebrowser,gotothelocationofyourNetLogoinstallation,
7. clickontheMathematicaLinksubfolder,andselectNetLogo.m.
8. ForInstallName,enterNetLogo.
YoucaneitherinstalltheNetLogolinkinyouruserbasedirectoryorinthesystem-wide
directory.IftheNetLogolinkisinstalledintheuserbasedirectory,otherusersonthesystem
mustalsogothroughtheNetLogo-Mathematicalinkinstallationprocesstouseit.Thisoption
mightbepreferableifyoudonothavepermissiontomodifyfilesoutsideofyourhome
directory.Otherwise,youcaninstallNetLogo-Mathematicalinkinthesystem-wide
Mathematicabasedirectory.
Usage
ThissectionwillverybrieflyintroducehowtousetheNetLogo-MathematicaLink.Itwillshow
youhowtoloadtheNetLogo-MathematicaLinkpackage,startNetLogo,executecommands,
andretrievedatafromNetLogo.
Loadingthepackage:OncetheNetLogo-Mathematicalinkisinstalled,youcanloadthe
packagebyenteringthefollowingintoyourMathematicanotebook:
<<NetLogo`
LaunchingNetLogofromMathematica:TobeginyourNetLogosessioninMathematica,
typethefollowingintoyournotebook:
NLStart[“your netlogo path”];
whereyournetlogopathisthedirectorythatnetlogoislocatedin.TypicallyonaMacthiswill
be“/Applications/NetLogo6.0.4/”
Loadingamodel:Toloadamodel,youmustspecifythefullpathofthemodel.Inthis
examplewewillloadtheForestFiremodel,andthepathwillbegivenusingthetypicalMac
installlocation.
NLLoadModel["/Applications/NetLogo 6.0.4/models/Sample Models/Earth
Science/Fire.nlogo"];
ExecutingaNetLogocommand:Commandscanbeexecutedbypassingastringof
commandstoNLCommand[].TheNLCommand[]functionautomaticallysplicescommon
MathematicadatatypesintostringssuitableforNetLogo.Thefollowingcommandssetthe
densityusingasinglestring,orsetthedensityusingaMathematicadefinedvariable,
myDensity.
NLCommand["set density 50"];
myDensity = 60;
NLCommand["set density", myDensity];
ReportinginformationfromNetLogo:NetLogodatacanbereportedbacktoMathematica
usingNLReport[].Thisincludesnumbers,strings,booleanvalues,andlists.
NLReport["count turtles"];
NLReport["[(list pxcor pycor)] of n-of 10 patches"]
Formoreinformation,seetheNetLogo-MathematicaTutorialnotebookincludedwith
NetLogo.Thenotebookwalksyouthroughtheprocessofusingthelink,withmanyexamples
alongtheway.IfyoudonothaveMathematica,butareconsideringusingthelink,youcan
findaPDFofthenotebookincludedwithNetLogointhe“MathematicaLink”directory.
KnownIssues
ANetLogosessioncannotbequitwithoutexitingJ/Link(theJava-Mathematicalink)
entirely.ThismaydisruptotherpackagesthatmakeuseofJ/Link.
IfamodelloadedwiththeNetLogo-MathematicalinkusesaNetLogoextension,the
extensionmustbelocatedinthesamedirectoryasthemodelitself.Iftheextensionis
locatedinNetLogo’sapplication-wideextensionsdirectory,itwillnotbefound.
CallstoNetLogo,suchasNLCommand[]andNLReport[],cannotbeaborted.
Sourcecode
ThesourcecodefortheNetLogo-Mathematicalinkisinthepublicdomain.Itishostedonline
athttps://github.com/NetLogo/Mathematica-Link.
Credits
TheprimarydeveloperoftheNetLogo-MathematicalinkwasEytanBakshy.
Torefertothispackageinacademicpublications,pleaseuse:Bakshy,E.,Wilensky,U.
(2007).NetLogo-MathematicaLink.http://ccl.northwestern.edu/netlogo/mathematica.html.
CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity,
Evanston,IL.
NetLogo3D
NetLogoincludestheNetLogo3Dapplicationthatallowsyoutocreate3Dworlds.
Notice:NetLogo'ssupportfor3DislessdevelopedthanNetLogo2D.Modelscreatedwith
thisreleasemaynotbecompatiblewithfutureversions.Whilewe'vemadeeffortsto
ensureaqualityproduct,NetLogo3Dhasnotbeensubjecttothesamelevelofquality
controlasthemainapplication.
Introduction
Tutorial
Dictionary
Introduction
TogetstartedusingNetLogo3D,launchtheNetLogo3Dapplicationandcheckoutthe
SampleModelsinthe3DsectionoftheModelsLibrary.
Whenyou'rereadytowriteyourown3Dmodel,lookattheCodeExamplesinthe3D
sectionoftheModelsLibrary.
CodeExample:TurtlePerspectiveExample3Dhelpsyoulearnaboutthedifferent
perspectives.
CodeExample:TurtleandObserverMotionExample3Dhelpsyouunderstandhow
turtlesandtheobservermovein3D.Youcanalsostepthroughthismodelwiththetutorial
below.
3DWorlds
Anunspeakablehorrorseizedme.Therewasadarkness;thenadizzy,sickening
sensationofsightthatwasnotlikeseeing;IsawaLinethatwasnoLine;Spacethatwas
notSpace:Iwasmyself,andnotmyself.WhenIcouldfindvoice,Ishriekedloudinagony,
"EitherthisismadnessoritisHell."
"Itisneither,"calmlyrepliedthevoiceoftheSphere,"itisKnowledge;itisThree
Dimensions:openyoureyeonceagainandtrytolooksteadily."
--EdwinA.Abbott,Flatland:Aromanceinmanydimensions
NetLogo3D'sworldhaswidth,heightanddepth.Patchesarecubes.Inadditiontopxcor
andpycor,patcheshavepzcor.
TurtleshavethreeCartesiancoordinates,insteadoftwo,todescribeposition.Inaddition
toxcorandycor,turtleshavezcor.
Aturtle'sorientationisdefinedbythreeturtlevariables,heading,pitchandroll.Youcan
imaginetheturtleashavingtwovectorstodefineitsorientationin3Dspace.Onevector
comesstraightoutofthenoseoftheturtle,thisisthedirectiontheturtlewilltravelwhenit
movesforward.Thesecondvectorisperpendiculartotheforwardvectorandcomesout
oftherightsideoftheturtle(asiftheturtleweretostickitsrightarmstraightoutfromits
body).Headingistheanglebetweentheforwardvectoroftheturtleprojectedontothexy-
planeandthevector[010].Pitchistheanglebetweentheforwardvectoroftheturtleand
thexy-planeandfinallyrollistheanglebetweentherightvectoroftheturtleandthexy-
plane.Whenturtleturnsrightorleftin3Dspaceitrotatesaroundthedownvector,thatis
thevectorthatisperpendiculartoboththeforwardandrightvectors.Dependingonthe
orientationoftheturtlemorethanoneoftheinternalturtlevariablesmaychangeasthe
resultofaturn.
Theobserverandthe3Dview
Thepointofviewthatyouseetheworldfromisconsideredthelocationandorientationof
theobserver.Thisissimilartothe3DviewinNetLogo2D.However,thereareafewmore
waystocontroltheobserver.Youcansetthepointthattheobserverisfacingbyusing
faceandfacexyzwhichworkthesamewayastheturtlecommands,theobserverturnsso
thecenteroftheviewisonthegivenpointorthelocationofthegivenagentatthetimeit
iscalled.Youcanchangethelocationoftheobserverusingsetxyz.Theobserverwill
movetoviewtheworldasifstandingonthegivenlocation,thepointtheobserverfaces
willstaythesame.Forexamplecreateanewmodelandobserverwillbelocatedat(0,0,
49.5),thatis,onthez-axis49.5patchunitsawayfromtheoriginandtheobserveris
facingtheorigin,(0,0,0).Ifyousetxyz 0 49.5 0theobserverwillmovesoitisonthe
positivey-axisbutitwillkeeptheoriginatthecenteroftheview.Youcanalsomovethe
observerusingtherotationprimitivesthatwillallowyoutomovetheobserveraroundthe
worldasifonthesurfaceofaspherewherethecenteristhelocationtheobserveris
facing.Youmaynoticefromtheaboveexamplesthattheobserverisnotconstrainedto
bewithintheboundsoftheworld.
CustomShapes
NetLogoautomaticallyinterprets2Dshapessotheyareextruded,likeacookiecutter
shapeinthe3Dview.Youcanalsousetheprimitiveload-shapes-3dtoloadshapes
describedinanexternalfileinacustomformatdescribedhere.Currentlywedonotimport
shapesinanystandardformats.
Foreachshapeinacustom3Dshapefile,a2Dshapeofthesamenamemustexistas
well.Youcancreatethe2DshapeintheTurtleShapesEditor.
Theinputfilemaycontainanynumberofshapeswithanynumberofrectangularor
triangularsurfaces.Theformatoftheinputfileshouldbeasfollows:
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
Eachsurfaceisdefinedbyaunitnormalvectorandtheverticeslistedinclockwiseorder,
trisshouldhavethreeverticesandquadsshouldhavefour.
normal: xn yn zn
x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
Afiledeclaringjustatwodimensional,patch-sized,squareinthexy-planecenteredatthe
originwouldlooklikethis:
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
Step1:Depth
OneofthefirstthingsyouwillnoticewhenyouopenNetLogo3Disthattheworldisa
cubeinsteadofasquare.
YoucanopenuptheModelSettings,byclickingonthe"Settings..."buttonatthetopof
the3DView.You'llnoticeinadditiontomax-pxcor,min-pxcor,max-pycor,andmin-pycor,
thereisalsomax-pzcorandmin-pzcor.
Thez-axisisperpendiculartoboththex-axisandthey-axis,whenyoureset-perspective
itistheaxisthatcomesstraightoutofthescreen.Inthedefaultpositionmax-pzcoristhe
faceofthecubenearesttoyouandmin-pzcoristhefacefarthestfromyou.Asalways
min-pxcorisontheleft,max-pxcorontheright,min-pycoronthebottom,andmax-pycoron
thetop.
You'llalsonoticeontheleftsideoftheModelSettingsthatthereareoptionsforwrapping
inallthreedirections,however,theyareallcheckedandgrayedout.Topologiesarenot
yetsupportedinNetLogo3D,sotheworldalwayswrapsinalldimensions.
MovetotheCommandCenterandtypeprint count patches.
Isthenumbersmallerorlargerthanyouexpected?
Ina3Dworldthenumberofpatchesgrowsveryquicklysincecount patches = world-
width * world-height * world-depth.It'simportanttokeepthisinmindwhenyouare
buildingyourmodel.LotsofpatchescanslowyourmodeldownorevencauseNetLogoto
runoutofmemory.
Typeask patch 1 2 3 [ set pcolor red ] intotheCommandCenter.
Usethemouseinthe3Dviewtorotatetheworld.
Noticetheshapeofthepatchanditspositioninrelationtotheedgesoftheworld.You'll
alsonoticethatyounowneedthreecoordinatestoaddresspatchesina3Dworld.
Step2:TurtleMovement
OpentheModelsLibraryintheFilemenu.(IfyouareonaMacandyoudon'thavea
Filemenu,clickonthemainNetLogowindowfirstanditshouldreappear.)
OpenTurtleandObserverMotionExample3Din3D/CodeExamples
Takeamomenttolookforthecontrolsandmonitors.Inthebottomleftyou'llnoticea
groupofmonitorsthatdescribethelocationandorientationoftheturtle,thoughuntilyou
pressthesetupbuttonthey'llallsay"N/A".
Pressthe"setup"button
Heading,pitch,androllareturtlevariablesthatrepresenttheorientationoftheturtle.
Headingisabsoluteinrelationtothex/yplane;itistherotationoftheturtlearoundthez-
axis.
Pitchistheanglebetweenthenoseoftheturtleandthexy-plane.Itisrelativetoheading.
Rollistherotationaroundtheturtle'sforwardvector.Itisrelativetoheadingandpitch.
Whenturtlesarecreatedwithcreate-turtlesorcreate-ordered-turtles,theirinitial
headingsvarybuttheirinitialpitchandrollarealwayszero.
Takealookatthe"TurtleMovement"buttons.
Pressthe"left1"button.
Howdoestheturtlemove?Isisthesameordifferentfrom2DNetLogo?Whichof
theturtlevariableschange?
Pressthe"pitch-down1"button.
Howdoestheturtlemove?Whichoftheturtlevariableschange?
Pressthe"left1"buttonagain.
Howdoestheturtlemove?Isitdifferentthanthelasttimeyoupressedthe"left1"
button?
TakealittletimetoplaywiththeTurtleMovementbuttons,watchingbothhowtheturtle
movesandwhichoftheturtlevariableschange.
Youprobablynoticedthatoftenmorethanoneoftheturtlevariablesmaychangefora
singleturn.Forthisreasonwesuggestthatyouusetheturtlecommandsratherthan
settingtheorientationvariablesdirectly.
Step3:ObserverMovement
AtthebottomoftheinterfaceyouwillseeOrbit,Zoom,andMovebuttons.Ifyouhave
everusedthe3DviewinNetLogo2Dorifyouhavebeenusingthemousecontrolsinthe
3Dviewthroughthistutorialyouhavebeenmovingtheobserver.Changingthepointof
viewinthe3Dviewisactuallymovingandchangingtheorientationoftheobserver.The
observerhasx,yandzcoordinates,justlikeaturtleorpatch,whileturtlesandpatches
areconstrainedtobeinsidetheworldtheobservercanbeanywhere.Likeaturtlethe
observerhasaheading,pitchandroll,thesevariablescontrolwheretheobserveris
looking,thatis,whatyouseeintheview.
Movetothe3Dview,andmakesure"Orbit"isselectedinthebottomleftcornerofthe
view.
Clickandholdthemousebuttoninthemiddleoftheview,movethemouseleft,right,
up,anddown.
Howdoesthepositionandorientationoftheobserverchange?
Pressthereset-perspectivebuttoninthelowerrightcorneroftheviewandselect
"Zoom"inthelowerleftcorner.
Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseupand
down.
Whichoftheobservervariableschange?Whichstaythesame?
Tryrotatingtheworldabitandthenzoomagain.
Pressthe"Move"buttoninthelowerleftcorneroftheview.
Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseup,
down,leftandright.
Howdoestheviewchange?Howdotheobservervariableschange?
Afteryouaredoneexploringtheworldusingthemousecontrolsyoucantakealookatthe
observercontrolbuttonsinthelowerleftportionoftheinterface.
Youmayalreadybefamiliarwiththefirstthreebuttonsintheobservergroupfromyour
experiencewithNetLogo2D.Watch,follow,andride,arespecialmodesthatautomatically
updatethepositionandorientationoftheobserver.Wheninfolloworridemode,the
observerpositionandorientationarethesameastheturtle's.Notethatfollowandrideare
functionallyexactlythesame,thedifferenceisonlyvisualinthe3Dview.Wheninwatch
modetheobserverdoesnotmovebutupdatestofacethetargetagent.
Pressthe"setup"buttonagainsoyouarebacktothedefaultorientation.
Pressthe"orbit-right"button.
Howdidtheviewchange?Wasitwhatyouexpected?Howisitsimilarordifferent
fromusingthemousecontrols?
Takealittletimetoexperimentwithorbit,rollandzoombuttons;noticesimilaritiesand
differencestothemousecontrols.
Thedirectionoftheorbitcommandsrefertothedirectionthattheobservermoves.Thatis,
imaginethattheobserverisonthesurfaceofasphere,thecenterofthesphereisthe
pointthattheobserverisfacingrepresentedbythebluecross,bydefault(0,0,0).The
observerwillalwaysfacethecenterofthesphereandtheradiusofthespherewillremain
constant.Thedirections,up,down,left,andright,refertomovingalongthelinesof
latitudeandthelinesoflongitudeofthesphere.Whenyouzoomtheradiusofthesphere
changesbutthecenterandtheobserver'sorientationinrelationtothecenterofthe
spherewillremainthesame.
Pressoneofthe"setxyz"buttons.
Howdoestheviewchange?Howdotheobservervariableschange?
Pressthe"facexyz"button.
Howdoestheviewchange?Howdotheobservervariableschange?
Whenyousetxyzthecenterofthesphereremainsthesame(sotheobserver
automaticallykeepsthatpointinthecenteroftheview.)However,theradiusofthesphere
maychangeaswellastheobserver'sorientationinrelationtothecenter.Whenyou
facexyzorface,thecenterofthespherechangesbuttheobserverdoesnotmove.The
radiusofthespheremaychange,aswellastheorientationoftheobserver.
Since4.1
Dictionary
CommandsandReporters
Turtle-relatedprimitives
distancexyzdistancexyz-nowrapdzleftpatch-atpatch-at-heading-pitch-and-distancetilt-down
tilt-uprightroll-leftroll-rightsetxyztowards-pitchtowards-pitch-nowraptowards-pitch-xyz
towards-pitch-xyz-nowrapturtles-at
Patch-relatedprimitives
distancexyzdistancexyz-nowrapneighborsneighbors6patchpatch-atpatch-at-heading-pitch-
and-distance
Agentsetprimitives
at-pointsbreeds-atturtles-at
Worldprimitives
max-pzcormin-pzcorrandom-pzcorrandom-zcorworld-depthload-shapes-3d
Observerprimitives
facefacexyzorbit-downorbit-leftorbit-rightorbit-up__oxcor__oycor__ozcorsetxyzzoom
Linkprimitives
link-pitch
Built-InVariables
Turtles
zcorpitchroll
Patches
pzcor
Primitives
at-points
Since4.1
Since4.1
Since4.1
agentsetat-points[[x1y1z1][x2y2z2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesthe
givendistancesawayfromthisagent.Thedistancesarespecifiedasalistofthree-item
lists,wherethethreeitemsarethex,y,andzoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inother
words,thepointsaretakenasabsolutepatchcoordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,and
notfromthecenterofthepatchundertheturtle.
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
distancexyzxcorycorzcor
distancexyz-nowrapxcorycorzcor
3Dversionsofdistancexy.
Reportsthedistancefromthisagenttothepoint(xcor,ycor,zcor).
Thedistancefromapatchismeasuredfromthecenterofthepatch.
distancexyz-nowrapalwaysreportstheinworlddistance,neveradistancethatwould
requirewrappingaroundtheedgesoftheworld.Withdistancexyzthewrappeddistance
(aroundtheedgesoftheworld)isusedifthatdistanceisshorterthantheinworld
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
Reportsthez-increment(theamountbywhichtheturtle'szcorwouldchange)iftheturtle
weretotakeonestepforwardatitscurrentheadingandpitch.
NOTE:dzissimplythesineoftheturtle'spitch.Bothdxanddyhavechangedinthiscase.
So,dx=cos(pitch)*sin(heading)anddy=cos(pitch)*cos(heading).
Seealsodx,dy.
Since4.1
Since4.1
Since4.1.2
Since4.1
Since4.1
Since4.1
face
facexyz
faceagent
facexyzxyz
Setthecaller'sheadingandpitchtowardsagentortowardsthepoint(x,y,z).
Ifthecallerandthetargetareatthesamexandycoordinatesthecaller'sheadingwillnot
change.Ifthecallerandthetargetarealsoatthesamezcoordinatethepitchwillnot
changeeither.
left
leftnumber
Theturtleturnsleftbynumberdegrees,relativetoitscurrentorientation.Whileleftina2D
worldonlymodifiestheturtle'sheading,leftina3Dworldmayalsomodifytheturtle's
pitchandroll.
Seealsoleft,tilt-up,tilt-down
link-pitch
link-pitch
Reportsthepitchfromend1toend2ofthislink.
ask link 0 1 [ print link-pitch ]
;; prints [[towards-pitch other-end] of end1] of link 0 1
Seealsolink-heading,pitch
load-shapes-3d
load-shapes-3dfilename
Loadscustom3Dshapesfromthegivenfile.Seethe3Dguideformoredetails.Youmust
alsoadda2DshapeofthesamenametothemodelusingtheTurtleShapesEditor.
Customshapesoverridebuilt-in3Dshapesandconverted2Dshapes.
max-pzcor
min-pzcor
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
max-pzcor
min-pzcor
Thesereportersgivethemaximumandminimumz-coordinates(respectively)forpatches,
whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenterofthe
world.However,theminimumz-coordinatehastobelessthanorequalto0andthe
maximumz-coordinatehastobegreaterthanorequalto0.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporters
whichcannotbeset.
Seealsomax-pxcor,max-pycor,min-pxcor,min-pycor,andworld-depth.
neighbors
neighbors6
neighbors
neighbors6
3Dversionsofneighborsandneighbors4.
Reportsanagentsetcontainingthe26surroundingpatches(neighbors)or6surrounding
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-downnumber
orbit-leftnumber
orbit-rightnumber
orbit-upnumber
Rotatetheobserveraroundthelastpointfaced.Imaginetheobserverisonthesurfaceof
asphere,thelastpointfaceisthecenterofthatsphere.Upanddownorbitalongthelines
oflongitudeandrightandleftorbitalongthelinesoflatitude.Theobserverwillremain
facingthelastpointfacedsotheheadingandpitchmaychangeasresultoforbiting.
However,becauseweassumeanabsolutenorthpole(paralleltothepositivez-axis)the
rollwillneverchange.
Since4.1
Since4.1
Since4.1
Seealsosetxyz,faceandzoom
__oxcor
__oycor
__ozcor
__oxcor
__oycor
__ozcor
Reportsthex-,y-,orz-coordinateoftheobserver.
Seealsosetxyz
patch
patchpxcorpycorpzcor
3Dversionofpatch.
Giventhreeintegers,reportsthesinglepatchwiththegivenpxcor,pycorandpzcor.
pxcor,pycorandpzcormustbeintegers.
ask (patch 3 -4 2) [ set pcolor green ]
;; patch with pxcor of 3 and pycor of -4 and pzcor of 2 turns green
Seealsopatch
patch-at
patch-atdxdydz
3Dversionofpatch-at.
Reportsthesinglepatchat(dx,dy,dz)fromthecaller,thatis,dxpatcheseast,dypatches
northanddzpatchesupfromthecaller.
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-distanceheadingpitchdistance
Since4.1
3Dversionofpatch-at-heading-and-distance.
patch-at-heading-pitch-and-distancereportsthesinglepatchthatisthegivendistance
fromthisturtleorpatch,alongthegivenabsoluteheadingandpitch.(Incontrasttopatch-
left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakeninto
account.)
ask patch-at-heading-pitch-and-distance 0 90 1 [ set pcolor green ]
;; turns the patch directly above the caller green.
pitch
pitch
Thisisabuilt-inturtlevariable.Pitchistheanglebetweenthe"nose"oftheturtleandthe
xy-plane.Headingandpitchtogetherdefinetheforwardvectoroftheturtleorthedirection
thattheturtleisfacing.
Thisisanumbergreaterthanorequalto0andlessthan360.0isparalleltothexy-plane,
90isparalleltothez-axis.Whileyoucansetpitchwerecommendthatyouusethe
primitivestoturntheturtle.Dependingonthepositionmorethanonerelativeangle
(heading,pitchandroll)maychangeatonce.
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"
Seealsoheading,roll,tilt-up,tilt-down,right,left
pzcor
pzcor
Thisisabuilt-inpatchvariable.Itholdsthezcoordinateofthepatch.Itisalwaysan
integer.Youcannotsetthisvariable,becausepatchesdon'tmove.
pzcorisgreaterthanorequaltomin-pzcorandlessthanorequaltomax-pzcor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsopxcor,pycor,zcor.
random-pzcor
random-pzcor
Since4.1
Since4.1
Reportsarandomintegerrangingfrommin-pzcortomax-pzcorinclusive.
ask turtles [
;; move each turtle to the center of a random patch
setxyz random-pxcor random-pycor random-pzcor
]
Seealsorandom-pxcor,random-pycor.
random-zcor
random-zcor
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinates
alongthezaxis.
Turtlecoordinatesrangefrommin-pzcor-0.5(inclusive)tomax-pzcor+0.5(exclusive).
ask turtles [
;; move each turtle to a random point
setxyz random-xcor random-ycor random-zcor
]
Seealsorandom-xcor,random-ycor.
right
rightnumber
Theturtleturnsrightbynumberdegrees,relativetoitscurrentorientation.Whilerightina
2Dworldonlymodifiestheturtle'sheading,rightina3Dworldmayalsomodifytheturtle's
pitchandroll.
Seealsorightandleft
roll
roll
Thisisabuilt-inturtlevariable.Rollistheanglebetweenthe"wing-tip"oftheturtleandthe
xy-plane.
Thisisanumbergreaterthanorequalto0andlessthan360.Youcansetthisvariableto
makeaturtleroll.Sincerollisalwaysfromtheturtle'spointofview,rollingrightandleft
onlyonlychangerollregardlessofturtleorientation.
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"
Seealsoheading,pitch,roll-left,roll-right.
roll-left
roll-leftnumber
Thewingtipoftheturtlerotatestotheleftnumberdegreeswithrespecttothecurrent
headingandpitch.
roll-right
roll-rightnumber
Thewingtipoftheturtlerotatestotherightnumberdegreeswithrespecttothecurrent
headingandpitch.
setxyz
setxyzxyz
3Dversionofsetxy.
Theagent,aturtleortheobserver,setsitsx-coordinatetox,itsy-coordinatetoyanditsz-
coordinatetoz.Whentheobserverusessetxyzitremainsfacingthesamepointsothe
heading,pitch,androll,mayalsochange.
Forturtlesequivalenttoset xcor x set ycor y set zcor z,exceptithappensinonetime
stepinsteadofthree.
setxyz 0 0 0
;; agent moves to the middle of the center patch
Seealsoface
tilt-down
tilt-up
tilt-downnumber
tilt-upnumber
Thenoseoftheturtlerotatesbynumberdegrees,relativetoitscurrentorientation.
Since4.1
Since4.1
Since4.1
Since4.1
Since4.1
Dependingontheorientationoftheturtlemorethanoneoftherelativeangles(heading,
pitch,androll)maychangewhenaturtleturns.
towards-pitch
towards-pitch-nowrap
towards-pitchagent
towards-pitch-nowrapagent
Reportsthepitchfromthisagenttothegivenagent.
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screen
distance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrap
neverusesthewrappedpath.
Note:Inordertogetoneturtletofaceanotheryouneedtousebothtowards-pitchand
towards.
Note:askingforthepitchfromanagenttoitself,oranagentonthesamelocation,will
causearuntimeerror.
Seealsotowards
towards-pitch-xyz
towards-pitch-xyz-nowrap
towards-pitch-xyzxyz
towards-pitch-xyz-no-wrapxyz
Reportsthepitchfromthisagenttothecoordinatesx,y,z
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screen
distance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrap
neverusesthewrappedpath.
Note:Inordertogetaturtletofaceagivenlocationyouneedtousebothtowards-pitch-
xyzandtowardsxy.
Note:askingforthepitchfromanagenttothelocationitisstandingonwillcausea
runtimeerror.
Seealsotowardsxy
turtles-at
<breeds>-at
turtles-atdxdydz
<breeds>-atdxdydz
Since4.1
Since4.1
3Dversionsofturtles-atandbreeds-at.
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy,dz)fromthecaller
(includingthecalleritselfifit'saturtle).
;; suppose I have 40 turtles at the origin
show [count turtles-at 0 0 0] of turtle 0
=> 40
world-depth
world-depth
ReportsthetotaldepthoftheNetLogoworld.
Thedepthoftheworldisthesameasmax-pzcor-min-pzcor+1.
Seealsomax-pzcor,min-pzcor,world-width,andworld-height
zcor
zcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentzcoordinateoftheturtle.Thisisa
floatingpointnumber,notaninteger.Youcansetthisvariabletochangetheturtle's
location.
Thisvariableisalwaysgreaterthanorequalto(-screen-edge-z)andstrictlylessthan
screen-edge-z.
Seealsosetxy,xcor,ycor,pxcor,pycor,pzcor
zoom
zoomnumber
Movetheobservertowardthepointitisfacing,numbersteps.Theobserverwillnever
movebeyondthepointitisfacingsoifnumberisgreaterthanthedistancetothatpointit
willonlymoveasfarasthepointitisfacing.
ExtensionsGuide
NetLogo6.0.4UserManual
NetLogoallowsuserstowritenewcommandsandreportersinJavaandotherlanguagesand
usethemintheirmodels.ThissectionoftheUserManualintroducesthisfacilityandshows
howtouseanextensioninyourmodelonceyouhaveobtainedormadeone.
ExtensionscreatedbymembersoftheNetLogocommunityareavailablefrom
https://github.com/NetLogo/NetLogo/wiki/Extensions.
Forinformationoncreatingyourownextensions,gohere.
UsingExtensions
Touseanextensioninamodel,addtheextensionskeywordatthebeginningoftheCode
tab,beforedeclaringanybreedsorvariables.
Afterextensionscomesalistofextensionnamesinsquarebrackets.Forexample:
extensions [sound speech]
UsingextensionstellsNetLogotofindandopenthespecifiedextensionandmakesthe
customcommandsandreportersfoundintheextensionavailabletothecurrentmodel.You
canusethesecommandsandreportersjustasiftheywerebuilt-inNetLogoprimitives.
Whereextensionsarelocated
NetLogowilllookforextensionsinseveralplaces:
1. Inthefolderofthecurrentmodel.
2. TheextensionsfolderlocatedwiththeNetLogoinstallation.FortypicalNetLogo
installations:
OnMacOSX:/Applications/NetLogo 6.0.4/extensions
On64-bitWindowswith64-bitNetLogoor32-bitWindowswith32-bitNetLogo:
C:\Program Files\NetLogo 6.0.4\app\extensions
On64-bitWindowswith32-bitNetLogo:C:\Program Files (x86)\NetLogo
6.0.4\app\extensions
OnLinux:theapp/extensionssubdirectoryoftheNetLogodirectoryextractedfrom
theinstallation.tgz
EachNetLogoextensionconsistsofafolderwiththesamenameastheextension,entirelyin
lowercase.ThisfoldermustcontainaJARfilewiththesamenameasthefolder.For
example,thesoundextensionisstoredinafoldercalledsoundwithafileinsidecalled
sound.jar.
ToinstallaNetLogoextensionforusebyanymodel,puttheextension’sfolderintheNetLogo
extensionsdirectory.Or,youcanjustkeeptheextension’sfolderinthesamefolderasthe
modelthatusesit.
Someextensionsdependonadditionalfiles.Thesefileswillbeintheextension’sfolderalong
withtheJARfile.Thefoldermayalsocontainotherfilessuchasdocumentationandexample
models.
NetLogoArduinoExtension
Using
Forafirstusewithoutcompilingcode,dothefollowing:
1. AcquiretheNetLogosoftware.TheArduinoextensioncomespre-installedwith
NetLogo5.2.1andlater.
2. AcquireanArduinoboardandinstallthearduinoIDE
3. UsetheArduinoIDEtoedittheSketch(ifdesired)andsendtotheboard.(See
elaboratecommentsinthesketchforrecommendationsaboutwhattocomment
out/leaveindependingonyoursetup&circuitontheboard.)
4. OncetheArduinohasthesketchloadedonit,itwillrunthatsketchwheneveritis
poweredon.
5. Openthetest“ArduinoExample”modelintheNetLogoModelslibrary(it’sinthe
“IABMTextbook”>“Chapter8”folder)
6. ConnecttheArduinotoaUSBportonthecomputerifitisnotstillconnectedfrom
step3.
7. PressOPENtochoosetheporttocommunicatewithandestablishtheconnection.
8. Usethebuttonstosendbytecommands;usetheinterfacetoinspectvariable
value(s)thatyoursketchissending.
9. Notethatbytypingarduino:primitivesyoucangetalistoftheavailablecommands
intheextension.
Notes
ANetLogomodelusingthisextensionmustworkinconjunctionwithanArduinoSketch.
Thesetwoendpointscommunicatebywayofanapplicationprotocolthattheydefine.For
example,iftheNetLogomodelsendsabyte‘1’overthewirethismaymeansomethingto
theArduinoSketch,whichwillrespondaccordingly.TheArduinoSketchforitsownpart
maysendname-valuepairsovertheserialport,whichthencanbelookedup
asynchronouslybytheNetLogomodel.
Themodelerisfreetobuildassimpleorascomplexanapplicationprotocolontopofthis
rawcommunicationmechanism.
Theasynchronousnatureoftheboard-to-computercommunicationshasonenotable
limitation.Ifyouchoosetotrytosimulateasynchronous,BLOCKINGREAD
communicationspattern,(e.g.,bysendingabyte-basedsignaltotheboard,whichtriggers
aresponseinaknownname-valuepair),thenyouarelikelytobe‘offbyone’response.
Thatis,ifyoudothefollowinginNetLogocode:
arduino:write-byte b
show arduino:get "varname"
YouarelikelytogetthevalueofvarnamefromthePRIORcommandrepresentedby
writingthebyteb.ThisisbecausethesecondlineofNetLogocodewillexecutewhilethe
Arduinoisoffgeneratinganewvalueforvarname.
Therearewaysofgettingaroundthis(simulatingablockinginterfacebypollingonavalue
toindicatefresh“news”onvarname).Butthisextensionworksbestinsettingswherethe
ArduinoSketchis“chatty”andtheNetLogomodelsamplesthisstreamwhenitneeds
data.
Compatibility
ThiscodehasbeentestedonWindows7and10with32-bitNetLogoandonMacOSX.
Youarelikelytoencounterissueswhenrunningthiswith64-bitNetLogoinWindows8or
Windows10,soifyouhaveWindows8or10,pleasedownloadthe32-Bitversionof
NetLogoifyouplanonusingtheArduinoextension.Westriveforcross-platform
compatibilityacrossMac,Win,andLinux.Soifyouhavetroubles,pleaseletusknow.
Questions
Ifyourunintoproblemsorhavequestionsabouttheextension,pleaseemailccl-feedback
orcbrady@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
Reportsalistofprimitivesavailableintheextension,withbasichintsabouttheirsyntax.
arduino:ports
arduino:ports
Reportsalistofportnames
arduino:open
arduino:openport-name
Openstheportnamedport-name.
arduino:close
arduino:close
Closesthecurrentlyopenport.
arduino:get
arduino:getvar-name
Readsandreportsthevalueassociatedwithvar-nameontheArduinoboard.Ifthereisno
valueassociatedwithvar-name,returnsfalse.Note:var-nameiscaseinsensitive.
arduino:write-string
arduino:write-stringstring-message
Writesastringmessagetothecurrentlyopenport.
arduino:write-int
arduino:write-intint-message
Writesaintegermessagetothecurrentlyopenport.
arduino:write-byte
arduino:write-bytebyte-message
Writesabytemessagetothecurrentlyopenport.
arduino:is-open?
arduino:is-open?
Reportsabooleanvalue(trueorfalse)indicatingifaportisopen.
arduino:debug-to-arduino
arduino:debug-to-arduino
ReportsalistofthelastmessagessentfromNetLogototheArduino,uptoamaximumof
5messages.Eachentryinthislistisastringbeginningwith“s:”ifthemessagesentwasa
string,“i:”ifthemessagesentwasanint,and“b:”ifthemessagesentwasabyte.
arduino:debug-from-arduino
arduino:debug-from-arduino
ReportsalistoflistscontaininganyerrantmessagessentfromNetLogototheArduino,up
toamaximumof10errantmessages.Eachsublistcontainstherawmessageasitsfirst
elementandamessagedescribingtheerrorasthesecondelement.
NetLogoArrayExtension
Using
Thearrayextensionispre-installedinNetLogo.
Tousethearrayextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [array]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddarraytothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithanarrayinNetLogo,youcouldalsojustusealistfor.
Butyoumaywanttoconsiderusinganarrayinsteadforspeedreasons.Listsandarrays
havedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrun
fasterbyselectingtheappropriatedatastructure.
Arraysareusefulwhenyouneedacollectionofvalueswhosesizeisfixed.Youcan
quicklyaccessoralteranyiteminanarrayifyouknowitsposition.
UnlikeNetLogo’slistsandstrings,arraysare“mutable”.Thatmeansthatyoucanactually
modifythemdirectly,ratherthanconstructinganalteredcopyaswithlists.Ifthearrayis
usedinmorethanoneplaceinyourcode,anychangesyoumakewillshowup
everywhere.It’strickytowritecodeinvolvingmutablestructuresandit’seasytomake
subtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunless
you’recertainyouwantandneedmutability.
ExampleuseofArrayExtension
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-listlist
Reportsanewarraycontainingthesameitemsinthesameorderastheinputlist.
array:item
array:itemarrayindex
Reportstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthof
thearrayminusone).
array:set
array:setarrayindexvalue
Setstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthof
thearrayminusone)tothegivenvalue.
Notethatunlikethereplace-itemprimitiveforlists,anewarrayisnotcreated.Thegiven
arrayisactuallymodified.
array:length
array:lengtharray
Reportsthelengthofthegivenarray,thatis,thenumberofitemsinthearray.
array:to-list
array:to-listarray
Reportsanewlistcontainingthesameitemsinthesameorderasthegivenarray.
NetLogoBitmapExtension
Using
Thebitmapextensionispre-installedinNetLogo.Forinstructionsonusingit,orformore
informationaboutNetLogoextensions,seetheNetLogoUserManual.
WhatdoestheBitmapExtensiondo?
TheBitmapExtensionallowsyoutomanipulateandimportimagesintothedrawingand
patches.ItoffersfeaturesnotprovidedbytheNetLogocoreprimitives,suchas:scaling,
manipulationofdifferentcolorchannels,andwidthandheightreporters.
Gettingstarted
Toimportandmanipulateimagesyouwillneedtoincludethebitmapextensioninyour
NetLogomodel.
extensions[ bitmap ]
TheimagefileformatssupportedaredeterminedbyyourJavavirtualmachine’simageio
library.TypicallythisisPNG,JPG,GIF,andBMP.PNGisagood,standardchoicethatis
likelytoworkeverywhere.
Iftheimageformatsupportstransparency(alpha),thatinformationwillbeimportedas
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-colorimage
Reportsa3-elementlistdescribingtheamountofR,G,andBinimage,bysumming
acrossallpixels,andnormalizingeachcomponentbythenumberofpixelsintheimage,
soeachcomponentrangesfrom0to255.
bitmap:channel
bitmap:channelimagechannel
Extractseitherthealpha,red,green,orbluechannelfromanimage.Theinputchannel
shouldbeaninteger0-3indicatingthechanneltoremove(alpha=0,red=1,green=2,
blue=3).Theresultingimageisagrayscaleimagerepresentingspecifiedchannel.
bitmap:copy-to-drawing
bitmap:copy-to-drawingimagexy
Importsthegivenimageintothedrawingwithoutscalingtheimageatthegivenpixel
coordinates.
bitmap:copy-to-pcolors
bitmap:copy-to-pcolorsimageboolean
Importsthegivenimageintothepcolors,scaledtofittheworld.Thesecondinput
indicateswhetherthecolorsshouldbeinterpretedasNetLogocolorsorleftasRGB
colors.falsemeansRGBcolors.
bitmap:difference-rgb
bitmap:difference-rgbimage1image2
Reportsanimagethatistheabsolutevalueofthepixel-wiseRGBdifferencebetweentwo
images.Notethatimage1andimage2MUSTbethesamewidthandheightaseachother,
orerrorswillensue.
bitmap:export
bitmap:exportimagefilename
Writesimagetofilename.
bitmap:from-view
bitmap:from-view
Reportsanimageofthecurrentview.
bitmap:to-grayscale
bitmap:to-grayscaleimage
Convertsthegivenimagetograyscale.
bitmap:height
bitmap:heightimage
Reportstheheightofgivenimage
bitmap:import
bitmap:importfilename
ReportsaLogoBitmapcontainingtheimageatfilename.
bitmap:scaled
bitmap:scaledimagewidthheight
Reportsanewimagethatisimagescaledtothegivenwidthandheight
bitmap:width
bitmap:widthimage
Reportsthewidthofthegivenimage
NetLogoCfExtension
Primitives
cf:ifelsecf:ifelse-value
cf:ifelse
cf:ifelseconditionconsequentconditions/consequentsoptional-else
Runsthefirstcommandblockfollowingatruecondition:
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!" ])
Theabovecodewillprintoutx is less than 4! sincethat’sthefirstcasewithatrue
condition.
Afinalcommandblockwithoutamatchingconditionmaybeprovided,inwhichcaseitwill
runifnoothercommandblocksdo.Ifnosuchcommandblockisprovidedandno
conditionsaretrue,nothingwillhappen.
Thedefaultnumberofargumentsis3,sothatifyouonlyhaveonecondition,a
consequent,andanelseblock(likearegularNetLogoifelse),youdonotneed
parentheses:
cf:ifelse 0 < 1 [ print "hi" ] [ print "bye" ]
cf:ifelse-value
cf:ifelse-valueconditionconsequentconditions/consequentselse-reporter
Runsthefirstreporterfollowingatrueconditionandreportsitsvalue:
(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!" ])
Theabovecodewillreportx is less than 4! sincethat’sthefirstcasewithatrue
condition.
Unlikecf:ifelse,theelse-blockisrequiredincf:ifelse-value.Ifnoconditionistrue,the
resultoftheelseblockwillbereported.
Notethatcf:ifelse-valuehassomewhatdifferentassociativitythanNetLogo’sifelse,
makingitsothatyoudon’tneedtoputparenthesesaroundtheconditions,asintheabove
example.
Thedefaultnumberofargumentsis3,sothatifyouonlyhaveonecondition,a
consequent,andanelseblock(likearegularNetLogoifelse-value),youdonotneed
parentheses:
cf:ifelse-value 0 < 1 [ "hi" ] [ "bye" ]
NetLogoCsvExtension
Commonusecasesandexamples
Readafileallatonce
Justusecsv:from-file "/path/to/myfile.csv"!Seefrom-fileformoreinformation.
Readafileonelineatatime
Forreallybigfiles,youmaynotwanttostoretheentirefileinmemory,butratherjustprocessitalineata
time.Forinstance,ifyouwanttosumeachofthecolumnsofanumericCSVfile,youcando:
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
Youcanalsousethistechniqueto…
Readafileonelinepertick
Here’sanexamplemodelthatreadsinafileonelinepertick:
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
Writeafile
Justusecsv:to-file "/path/to/myfile.csv" my-data!Seeto-fileformoreinformation.
Primitives
FormattingNetLogodataasCSV
csv:to-rowcsv:to-stringcsv:to-file
ParsingCSVinputtoNetLogodata
csv:from-rowcsv:from-stringcsv:from-file
csv:from-row
csv:from-rowstring
csv:from-rowstringdelimiter
ParsesthegivenstringasthoughitwerearowfromaCSVfileandreturnsitasalistofvalues.Forexample:
observer> show csv:from-row "one,two,three"
observer: ["one" "two" "three"]
Quotescanbeusedwhenitemscontaincommas:
observer> show csv:from-row "there's,a,comma,\"in,here\""
observer: ["there's" "a" "comma" "in,here"]
Youcanputtwoquotesinarowtoputanactualquoteinanentry.Iftheentryisnotquoted,youcanjustuse
onequote:
observer> foreach (csv:from-row "he said \"hi there\",\"afterwards, she said \"\"hello\"\"\"") print
he said "hi there"
afterwards, she said "hello"
Number-like-entrieswillbeparsedasnumbers:
observer> show csv:from-row "1,-2.5,1e3"
observer: [1 -2.5 1000]
trueandfalsewithanycapitalizationwillbeparsedasbooleans:
observer> show csv:from-row "true,TRUE,False,falsE"
observer: [true true false false]
Touseadifferentdelimiter,youcanspecifyasecond,optionalargument.Onlysinglecharacterdelimitersare
supported:
observer> show (csv:from-row "1;2;3" ";")
observer: [1 2 3]
Differenttypesofvaluescanbemixedfreely:
observer> show csv:from-row "one,2,true"
observer: ["one" 2 true]
csv:from-string
csv:from-stringstring
csv:from-stringstringdelimiter
ParsesastringrepresentationofoneormoreCSVrowsandreturnsitasalistoflistsofvalues.Forexample:
observer> show csv:from-string "1,two,3\nfour,5,true"
observer: [[1 "two" 3] ["four" 5 true]]
csv:from-file
csv:from-filecsv-file
csv:from-filecsv-filedelimiter
ParsesanentireCSVfiletoalistoflistsofvalues.Forexample,ifwehaveafileexample.csvthatcontains:
1,2,3
4,5,6
7,8,9
10,11,12
Then,weget:
observer> show csv:from-file "example.csv"
observer: [[1 2 3] [4 5 6] [7 8 9] [10 11 12]]
Theparserdoesn’tcareiftherowshavedifferentnumbersofitemsonthem.Thenumberofitemsintherows
listwillalwaysbe<number of delimiters> + 1 ,thoughblanklinesareskipped.Thismakeshandlingfileswith
headersquiteeasy.Forinstance,ifwehaveheader.csvthatcontains:
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
Thisgives:
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-rowlist
csv:to-rowlistdelimiter
ReportsthegivenlistasaCSVrow.Forexample:
observer> show csv:to-row ["one" 2 true]
observer: "one,2,true"
csv:to-string
csv:to-stringlist
csv:to-stringlistdelimiter
ReportsthegivenlistoflistsasaCSVstring.Forexample:
observer> show csv:to-string [[1 "two" 3] [4 5]]
observer: "1,two,3\n4,5"
csv:to-file
csv:to-filecsv-filelist
csv:to-filecsv-filelistdelimiter
WritesthegivenlistofliststoanewCSVfile.Forexample:
observer> csv:to-file "myfile.csv" [[1 "two" 3] [4 5]]
willresultinafilemyfile.csvcontaining:
1,two,3
4,5
NetLogoGisExtension
Using
ThisextensionaddsGIS(GeographicInformationSystems)supporttoNetLogo.It
providestheabilitytoloadvectorGISdata(points,lines,andpolygons),andrasterGIS
data(grids)intoyourmodel.
TheextensionsupportsvectordataintheformofESRIshapefiles.Theshapefile(.shp)
formatisthemostcommonformatforstoringandexchangingvectorGISdata.The
extensionsupportsrasterdataintheformofESRIASCIIGridfiles.TheASCIIgridfile
(.ascor.grd)isnotascommonastheshapefile,butissupportedasaninterchange
formatbymostGISplatforms.
Howtouse
Ingeneral,youfirstdefineatransformationbetweenGISdataspaceandNetLogospace,
thenloaddatasetsandperformvariousoperationsonthem.Theeasiestwaytodefinea
transformationbetweenGISspaceandNetLogospaceistotaketheunionofthe
“envelopes”orboundingrectanglesofallofyourdatasetsinGISspaceandmapthat
directlytotheboundsoftheNetLogoworld.SeeGISGeneralExamplesforanexampleof
thistechnique.
YoumayalsooptionallydefineaprojectionfortheGISspace,inwhichcasedatasetswill
bere-projectedtomatchthatprojectionastheyareloaded,aslongaseachofyourdata
fileshasanassociated.prjfilethatdescribestheprojectionorgeographiccoordinate
systemofthedata.Ifnoassociated.prjfileisfound,theextensionwillassumethatthe
datasetalreadyusesthecurrentprojection,regardlessofwhatthatprojectionis.
Oncethecoordinatesystemisdefined,youcanloaddatasetsusinggis:load-dataset.This
primitivereportseitheraVectorDatasetoraRasterDataset,dependingonwhattypeoffile
youpassit.
AVectorDatasetconsistsofacollectionofVectorFeatures,eachoneofwhichisapoint,
line,orpolygon,alongwithasetofpropertyvalues.AsingleVectorDatasetmaycontain
onlyoneofthethreepossibletypesoffeatures.
ThereareseveralthingsyoucandowithaVectorDataset:askitforthenamesofthe
propertiesofitsfeatures,askitforits“envelope”(boundingrectangle),askforalistofall
VectorFeaturesinthedataset,searchforasingleVectorFeatureorlistofVectorFeatures
whosevalueforaparticularpropertyislessthanorgreaterthanaparticularvalue,orlies
withinagivenrange,ormatchesagivenstringusingwildcardmatching(“*”,which
matchesanynumberofoccurrencesofanycharacters).IftheVectorFeaturesare
polygons,youcanalsoapplythevaluesofaparticularpropertyofthedataset’sfeaturesto
agivenpatchvariable.
TherearealsoseveralthingsyoucandowithaVectorFeaturefromaVectorDataset:ask
itforalistofvertexlists,askitforapropertyvaluebyname,askitforitscentroid(centerof
gravity),andaskforasubsetofagivenagentsetwhoseagentsintersectthegiven
VectorFeature.Forpointdata,eachvertexlistwillbeaone-elementlist.Forlinedata,
eachvertexlistwillrepresenttheverticesofalinethatmakesupthatfeature.Forpolygon
data,eachvertexlistwillrepresentone“ring”ofthepolygon,andthefirstandlastvertex
ofthelistwillbethesame.ThevertexlistsaremadeupofvaluesoftypeVertex,andthe
centroidwillbeavalueoftypeVertexaswell.
ThereareanumberofoperationsdefinedforRasterDatasetsaswell.Mostlytheseinvolve
samplingthevaluesinthedataset,orre-samplingarastertoadifferentresolution.You
canalsoapplyarastertoagivenpatchvariable,andconvolvearasterusinganarbitrary
convolutionmatrix.
CodeExample:GISGeneralExampleshasgeneralexamplesofhowtousethe
extension
CodeExample:GISGradientExampleisamoreadvancedexampleofraster
datasetanalysis.
KnownIssues
ValuesoftypeRasterDataset,VectorDataset,VectorFeature,andVertexarenothandled
properlybyexport-worldandimport-world.Tosavedatasets,youmustusethe
gis:store-datasetprimitive.
Thereiscurrentlynowaytodistinguishpositive-area“shell”polygonsfromnegative-area
“hole”polygons,ortodeterminewhichholesareassociatedwithwhichshells.
Credits
TheprimarydeveloperoftheGISextensionwasEricRussell.
TheGISextensionmakesuseofseveralopen-sourcesoftwarelibraries.Forcopyrightand
licenseinformationonthose,seethecopyrightsectionofthemanual.Theextensionalso
containselementsborrowedfromMyWorldGIS.
ThisdocumentationandtheexampleNetLogomodelsareinthepublicdomain.TheGIS
extensionitselfisfreeandopensourcesoftware.SeetheREADME.mdfileinthe
extension/gisdirectoryfordetails.
WewouldlovetohearyoursuggestionsonhowtoimprovetheGISextension,orjust
aboutwhatyou’reusingitfor.PostquestionsandcommentsattheNetLogoUsersGroup,
orwritedirectlytoEricRussellandtheNetLogoteamatccl-gis@ccl.northwestern.edu
Primitives
RasterDatasetPrimitives
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
DatasetPrimitives
gis:load-datasetgis:store-datasetgis:type-ofgis:patch-datasetgis:turtle-dataset
gis:link-dataset
VectorDatasetPrimitives
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
CoordinateSystemPrimitives
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
DrawingPrimitives
gis:drawing-colorgis:set-drawing-colorgis:drawgis:fillgis:paintgis:import-wms-
drawing
gis:set-transformation
gis:set-transformationgis-envelopenetlogo-envelope
DefinesamappingbetweenGIScoordinatesandNetLogocoordinates.Thegis-envelope
andnetlogo-envelopeparametersmusteachbefour-elementlistsconsistingof:
[minimum-x maximum-x minimum-y maximum-y]
Thescaleofthetransformationwillbeequaltotheminimumofthescalenecessaryto
makethemappingbetweentherangesofxvaluesandthescalenecessarytomakethe
mappingbetweentherangesofyvalues.TheGISspacewillbecenteredinNetLogo
space.
Forexample,thefollowingtwolistswouldmapallofgeographic(latitudeandlongitude)
spaceindegreestoNetLogoworldspace,regardlessofthecurrentdimensionsofthe
NetLogoworld:
(list -180 180 -90 90)
(list min-pxcor max-pxcor min-pycor max-pycor)
However,ifyou’resettingtheenvelopeoftheNetLogoworld,youshouldprobablybe
usingset-world-envelope.
gis:set-transformation-ds
gis:set-transformation-dsgis-envelopenetlogo-envelope
Doesthesamethingasset-transformationabove,exceptthatitallowsthescalefor
mappingtherangeofxvaluestobedifferentthanthescaleforyvalues.The“-ds”onthe
endstandsfor“differentscales”.Usingdifferentscaleswillcausedistortionoftheshape
ofGISfeatures,andsoitisgenerallynotrecommended,butitmaybeusefulforsome
models.
Hereisanexampleofthedifferencebetweenset-transformationandset-transformation-
ds:
Using[set-transformation]
(#gisset-transformation),the
scalealongthexandyaxisis
thesame,preservingtheround
shapeoftheEarthinthis
Orthographicprojection.
Using[set-transformation-ds](#gisset-
transformation-ds),thescalealong
thexaxisisstretchedsothatthe
earthcoverstheentireNetLogoView,
whichinthiscasedistortstheshape
oftheEarth.
gis:set-world-envelope
gis:set-world-envelopegis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworld
tothegivenenvelopeinGISspace,whilekeepingthescalesalongthexandyaxisthe
same.Itisequivalentto:
set-transformation gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Thisprimitiveissuppliedbecausemostofthetimeyou’llwanttosettheenvelopeofthe
entireNetLogoworld,ratherthanjustapartofit.
gis:set-world-envelope-ds
gis:set-world-envelope-dsgis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworld
tothegivenenvelopeinGISspace,usingdifferentscalesalongthexandyaxisif
necessary.Itisequivalentto:
set-transformation-ds gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Seethepicturesaboveforthedifferencebetweenusingequalscalesforxandy
coordinatesandusingdifferentscales.
gis:world-envelope
gis:world-envelope
Reportstheenvelope(boundingrectangle)oftheNetLogoworld,transformedintoGIS
space.Anenvelopeconsistsofafour-elementlistoftheform:
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-of
gis:envelope-ofthing
Reportstheenvelope(boundingrectangle)ofthinginGIScoordinates.Thethingmaybe
anAgent,anAgentSet,aRasterDataset,aVectorDataset,oraVectorFeature.An
envelopeconsistsofafour-elementlistoftheform:
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-union-of
gis:envelope-union-ofenvelope1envelope2
gis:envelope-union-ofenvelope1...
Reportsanenvelope(boundingrectangle)thatentirelycontainsthegivenenvelopes.An
envelopeconsistsofafour-elementlistoftheform
[minimum-x maximum-x minimum-y maximum-y]
Noassumptionismadeaboutthecoordinatesystemofthearguments,thoughiftheyare
notinthesamecoordinatesystem,resultswillbeunpredictable.
gis:load-coordinate-system
gis:load-coordinate-systemfile
Loadsanewglobalprojectionusedforprojectingorre-projectingGISdataasitisloaded
fromafile.ThefilemustcontainavalidWell-KnownText(WKT)projectiondescription.
WKTprojectionfilesarefrequentlydistributedalongsideGISdatafiles,andusuallyhavea
“.prj”filenameextension.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’s
homedirectoryifthecurrentmodelhasn’tbeensavedyet.
TheGISextensiondoesnotsupportallWKTcoordinatesystemsandprojections.Only
geographic("GEOGCS")andprojected("PROJCS")coordinatesystemsaresupported.For
projectedcoordinatesystems,onlythefollowingprojectionsaresupported:
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
Seeremotesensing.orgforacompletelistofWKTprojectionsandtheirparameters.
gis:set-coordinate-system
gis:set-coordinate-systemsystem
Setstheglobalprojectionusedforprojectingorre-projectingGISdataasitisloaded.The
systemmustbeeitherastringinWell-KnownText(WKT)format,oraNetLogolistthat
consistsofWKTconvertedtoalistbymovingeachkeywordinsideitsassociatedbrackets
andputtingquotesaroundit.Thelatterispreferredbecauseitmakesthecodemuchmore
readable.
ThesamelimitationsonWKTsupportapplyasdescribedaboveinthedocumentationfor
load-coordinate-system
gis:load-dataset
gis:load-datasetfile
Loadsthegivendatafile,re-projectingthedataasnecessaryifaglobalprojectionis
definedandifthedatafileitselfhasanassociated.prjfile,thenreportstheresulting
dataset.
Ifno“.prj”fileispresent,thenload-datasetassumesthattheprojectionofthedatabeing
loadedisthesameasthecurrentglobalcoordinatesystem.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’s
homedirectoryifthecurrentmodelhasn’tbeensavedyet.
Currently,twotypesofdatafilearesupported:
“.shp”(ESRIshapefile):containsvectordata,consistingofpoints,lines,orpolygons.
Whenthetargetfileisashapefile,load-datasetreportsaVectorDataset.
“.asc”or“.grd”(ESRIASCIIgrid):containsrasterdata,consistingofagridofvalues.
WhenthetargetfileisanASCIIgridfile,load-datasetreportsaRasterDataset.
gis:store-dataset
gis:store-datasetdatasetfile
Savesthegivendatasettothegivenfile.Ifthenameofthefiledoesnothavetheproper
fileextension,theextensionwillbeautomaticallyappendedtothename.Relativepaths
areresolvedrelativetothelocationofthecurrentmodel,ortheuser’shomedirectoryif
thecurrentmodelhasn’tbeensavedyet.
Currently,thisprimitiveonlyworksforRasterDatasets,anditcanonlysavethosedatasets
asESRIASCIIgridfiles.
gis:type-of
gis:type-ofdataset
ReportsthetypeofthegivenGISdataset:either“VECTOR”or“RASTER”
gis:patch-dataset
gis:patch-datasetpatch-variable
ReportsanewrasterwhosecellscorresponddirectlytoNetLogopatches,andwhosecell
valuesconsistofthevaluesofthegivenpatchvariable.Thisprimitiveisbasicallythe
inverseofapply-raster;apply-rastercopiesvaluesfromarasterdatasettoapatch
variable,whilethisprimitivecopiesvaluesfromapatchvariabletoarasterdataset.
gis:turtle-dataset
gis:turtle-datasetturtle-set
Reportsanew,pointVectorDatasetbuiltfromtheturtlesinthegivenagentset.Thepoints
arelocatedatlocationsoftheturtles,translatedfromNetLogospaceintoGISspaceusing
thecurrentcoordinatetransformation.Andthedataset’spropertiesconsistofallofthe
turtlevariablescommontoeveryturtleintheagentset.
gis:link-dataset
gis:link-datasetlink-set
Reportsanew,lineVectorDatasetbuiltfromthelinksinthegivenagentset.Theendpoints
ofeachlineareatthelocationoftheturtlesconnectedbyeachlink,translatedfrom
NetLogospaceintoGISspaceusingthecurrentcoordinatetransformation.Andthe
dataset’spropertiesconsistofallofthelinkvariablescommontoeverylinkinthe
agentset.
gis:shape-type-of
gis:shape-type-ofVectorDataset
Reportstheshapetypeofthegivendataset.Thepossibleoutputvaluesare“POINT”,
“LINE”,and“POLYGON”.
gis:property-names
gis:property-namesVectorDataset
Reportsalistofstringswhereeachstringisthenameofapropertypossessedbyeach
VectorFeatureinthegivenVectorDataset,suitableforuseingis:property-value.
gis:feature-list-of
gis:feature-list-ofVectorDataset
ReportsalistofallVectorFeaturesinthegivendataset.
gis:vertex-lists-of
gis:vertex-lists-ofVectorFeature
ReportsalistoflistsofVertexvalues.Forpointdatasets,eachvertexlistwillcontain
exactlyonevertex:thelocationofapoint.Forlinedatasets,eachvertexlistwillcontainat
leasttwopoints,andwillrepresenta“polyline”,connectingeachadjacentpairofvertices
inthelist.Forpolygondatasets,eachvertexlistwillcontainatleastthreepoints,
representingapolygonconnectingeachvertex,andthefirstandlastverticesinthelistwill
bethesame.
gis:centroid-of
gis:centroid-ofVectorFeature
ReportsasingleVertexrepresentingthecentroid(centerofgravity)ofthegivenfeature.
Forpointdatasets,thecentroidisdefinedastheaveragelocationofallpointsinthe
feature.Forlinedatasets,thecentroidisdefinedastheaverageofthelocationsofthe
midpointsofalllinesegmentsinthefeature,weightedbysegmentlength.Forpolygon
datasets,thecentroidisdefinedastheweightedsumofthecentroidsofadecomposition
oftheareainto(possiblyoverlapping)triangles.SeethisFAQformoredetailsonthe
polygoncentroidalgorithm.
gis:location-of
gis:location-ofVertex
Reportsatwo-elementlistcontainingthexandyvalues(inthatorder)ofthegivenvertex
translatedintoNetLogoworldspaceusingthecurrenttransformation,oranemptylistif
thegivenvertexliesoutsidetheNetLogoworld.
gis:property-value
gis:property-valueVectorFeatureproperty-name
ReportsthevalueofthepropertywiththegivennameforthegivenVectorDataset.The
reportedvaluemaybeanumber,astring,orabooleanvalue,dependingonthetypeof
thefieldintheunderlyingdatafile.
Forshapefiles,valuesfromdBaseCHARACTERandDATEfieldsarereturnedasstrings,
valuesfromNUMBERandFLOATfieldsarereturnedasnumbers,andvaluesfromLOGICAL
fieldsarereturnedasbooleanvalues.MEMOfieldsarenotsupported.DATEvaluesare
convertedtostringsusingISO8601format(YYYY-MM-DD).
gis:find-features
gis:find-featuresVectorDatasetproperty-namespecified-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-namematchesspecified-value(astring).Valuecomparisonisnotcasesensitive,
andthewildcardcharacter“*”willmatchanynumberofoccurrences(includingzero)of
anycharacter.
gis:find-one-feature
gis:find-one-featureVectorDatasetproperty-namespecified-value
ReportsthefirstVectorFeatureinthedatasetwhosevalueforthepropertyproperty-name
matchesthegivenstring.Valuecomparisonisnotcasesensitive,andthewildcard
character“*”willmatchanynumberofoccurrences(includingzero)ofanycharacter.
Featuresaresearchedintheorderthattheyappearinthedatafilethatwasthesourceof
thedataset,andsearchingstopsassoonasamatchisfound.Reportsnobodyifno
matchingVectorFeatureisfound.
gis:find-less-than
gis:find-less-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameislessthanthegivenvalue.Stringvaluesarecomparedusingcase-
sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalue
foranumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-greater-than
gis:find-greater-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameisgreaterthanthegivenvalue.Stringvaluesarecomparedusingcase-
sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalue
foranumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-range
gis:find-rangeVectorDatasetproperty-nameminimum-valuemaximum-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevaluefortheproperty
property-nameisstrictlygreaterthanminimum-valueandstrictlylessthanmaximum-
value.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedin
theJavaDocumentation.Usingastringvalueforanumericpropertyoranumericvaluefor
astringpropertywillcauseanerror.
gis:property-minimum
gis:property-minimumVectorDatasetproperty-name
ReportsthesmallestvalueforthegivenpropertyoveralloftheVectorFeaturesinthe
givendataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderas
definedintheJavaDocumentation.
gis:property-maximum
gis:property-maximumVectorDatasetproperty-name
ReportsthelargestvalueforthegivenpropertyoveralloftheVectorFeaturesinthegiven
dataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefined
intheJavaDocumentation.
gis:apply-coverage
gis:apply-coverageVectorDatasetproperty-namepatch-variable
CopiesvaluesfromthegivenpropertyoftheVectorDataset’sfeaturestothegivenpatch
variable.Thedatasetmustbeapolygondataset;pointsandlinesarenotsupported.
Foreachpatch,itfindsallVectorFeaturesthatintersectthatpatch.Then,ifthepropertyis
astringproperty,itcomputesthemajorityvaluebycomputingthetotalareaofthepatch
coveredbyVectorFeatureshavingeachpossiblevalueoftheproperty,thenreturningthe
valuewhichrepresentsthelargestproportionofthepatcharea.Ifthepropertyisa
numericproperty,itcomputesaweightedaverageofpropertyvaluesfromall
VectorFeatureswhichintersectthepatch,weightedbytheproportionofthepatcharea
theycover.
Therearetwoexceptionstothisdefaultbehavior:
Ifapercentageofapatches’areagreaterthanthecoverage-maximum-thresholdis
coveredbyasingleVectorFeature,thenthepropertyvaluefromthatVectorFeature
iscopieddirectly.IfmorethanoneVectorFeaturecoversapercentageofarea
greaterthanthethreshold,onlythefirstwillbeused.
Ifthetotalpercentageofapatches’areacoveredbyVectorFeaturesislessthanthe
coverage-minimum-threshold,thetargetpatchvariableissettoNotANumber.
Bydefault,theminimumthresholdis10%andthemaximumthresholdis33%.These
valuesmaybemodifiedusingthefourprimitivesthatfollow.
gis:coverage-minimum-threshold
gis:coverage-minimum-threshold
Reportsthecurrentcoverageminimumthresholdusedbygis:apply-coverage.
gis:set-coverage-minimum-threshold
gis:set-coverage-minimum-thresholdnew-threshold
Setsthecurrentcoverageminimumthresholdtobeusedbygis:apply-coverage.
gis:coverage-maximum-threshold
gis:coverage-maximum-threshold
Reportsthecurrentcoveragemaximumthresholdusedbygis:apply-coverage.
gis:set-coverage-maximum-threshold
gis:set-coverage-maximum-thresholdnew-threshold
Setsthecurrentcoveragemaximumthresholdtobeusedbygis:apply-coverage.
gis:intersects?
gis:intersects?xy
Reportstrueifthegivenobjects’spatialrepresentationsshareatleastonepointin
common,andfalseotherwise.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contains?
gis:contains?xy
Reportstrueifeverypointofy’sspatialrepresentationisalsoapartofx’sspatial
representation.Notethatthismeansthatpolygonsdocontaintheirboundaries.The
objectsxandymaybeanyoneof
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contained-by?
gis:contained-by?xy
Reportstrueifeverypointofx’sspatialrepresentationisalsoapartofy’sspatial
representation.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:have-relationship?
gis:have-relationship?xy
Reportstrueifthespatialrepresentationsofthetwoobjectshavethegivenspatial
relationship,andfalseotherwise.Thespatialrelationshipisspecifiedusinga
DimensionallyExtendedNine-IntersectionModel(DE-9IM)matrix.Thematrixconsists
of9elements,eachofwhichspecifiestherequiredrelationshipbetweenthetwoobjects’
interiorspace,boundaryspace,orexteriorspace.Theelementsmusthaveoneofsix
possiblevalues:
“T”,meaningthespacesmustintersectinsomeway
“F”,meaningthespacesmustnotintersectinanyway
“0”,meaningthedimensionofthespaces’intersectionmustbezero(i.e.,itmustbea
pointornon-emptysetofpoints).
“1”,meaningthedimensionofthespaces’intersectionmustbeone(i.e.,itmustbea
lineornon-emptysetoflinesegments).
“2”,meaningthedimensionofthespaces’intersectionmustbetwo(i.e.,itmustbea
polygonorsetofpolygonswhoseareaisgreaterthanzero).
“*”,meaningthatthetwospacesmayhaveanyrelationship.
Forexample,thismatrix:
x
Interior Boundary Exterior
y
Interior T * *
Boundary * * *
Exterior F F *
wouldreturntrueifandonlyifsomepartofobjectx’sinteriorliesinsideobjecty’sinterior,
andnopartofobjectx’sinteriororboundaryintersectsobjecty’sexterior.Thisis
essentiallyamorerestrictiveformofthecontains?primitive;oneinwhichpolygonsare
notconsideredtocontaintheirboundaries.
Thematrixisgiventothehave-relationship?primitiveasastring,whoseelementsare
giveninthefollowingorder:
123
456
789
Sotousetheexamplematrixabove,youwouldwrite:
gis:have-relationship? x y "T*****FF*"
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociated
point-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:relationship-of
gis:relationship-ofxy
ReportstheDimensionallyExtendedNine-IntersectionModel(DE-9IM)matrixthat
describesthespatialrelationshipofthetwoobjects.Thematrixconsistsof9elements,
eachofwhichdescribestherelationshipbetweenthetwoobjects’interiorspace,boundary
space,orexteriorspace.Eachelementwilldescribethedimensionoftheintersectionof
twospaces,meaningthatitmayhaveoneoffourpossiblevalues:
“-1”,meaningthespacesdonotintersect
“0”,meaningthedimensionofthespaces’intersectioniszero(i.e.,theyintersectata
pointorsetofpoints).
“1”,meaningthedimensionofthespaces’intersectionisone(i.e.,theyintersectalong
oneormorelines).
“2”,meaningthedimensionofthespaces’intersectionistwo(i.e.,theirintersectionisa
non-emptypolygon).
Forexample,thetwopolygonsxandyshownhere:
havethefollowingDE-9IMmatrix:
x
Interior Boundary Exterior
y
Interior 2 1 2
Boundary 1 0 1
Exterior 2 1 2
Whichwouldbereportedbytherelationship-ofprimitiveasthestring“212101212”.
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociated
point-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthe
points,lines,orpolygonsthedatasetcontains.
aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythe
point,line,orpolygonthefeaturecontains.
Aturtle,inwhichcasethespatialrepresentationisapoint.
Alink,whosespatialrepresentationisalinesegmentconnectingthetwopoints
representedbytheturtlesthelinkisconnecting.
Apatch,whosespatialrepresentationisarectangularpolygon.
Anagentset,whosespatialrepresentationistheunionoftherepresentationsofallof
theagentsitcontains.
Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatial
representationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:intersecting
patch-setgis:intersectingdata
Reportsanewagentsetcontainingonlythosemembersofthegivenagentsetwhich
intersectgivenGISdata,whichmaybeanyoneof:aVectorDataset,aVectorFeature,an
Agent,anAgentSet,oralistcontaininganyoftheabove.
gis:width-of
gis:width-ofRasterDataset
Reportsthenumberofcolumnsinthedataset.Notethatthisisthenumberofcellsfrom
lefttoright,notthewidthofthedatasetinGISspace.
gis:height-of
gis:height-ofRasterDataset
Reportsthenumberofrowsinthedataset.Notethatthisisthenumberofcellsfromtopto
bottom,nottheheightofthedatasetinGISspace.
gis:raster-value
gis:raster-valueRasterDatasetxy
Reportsthevalueofthegivenrasterdatasetinthegivencell.Cellcoordinatesare
numberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleft
cellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset
-1).
gis:set-raster-value
gis:set-raster-valueRasterDatasetxyvalue
Setsthevalueofthegivenrasterdatasetatthegivencelltoanewvalue.Cellcoordinates
arenumberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupper
leftcellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of
dataset-1).
gis:minimum-of
gis:minimum-ofRasterDataset
Reportsthehighestvalueinthegivenrasterdataset.
gis:maximum-of
gis:maximum-ofRasterDataset
Reportsthelowestvalueinthegivenrasterdataset.
gis:sampling-method-of
gis:sampling-method-ofRasterDataset
Reportsthesamplingmethodusedtocomputethevalueofthegivenrasterdatasetata
singlepoint,oroveranareasmallerthanasinglerastercell.Samplingisperformedbythe
GISextensionprimitivesraster-sample,resample,convolve,andapply-raster.The
samplingmethodwillbeoneofthefollowing:
"NEAREST_NEIGHBOR":thevalueofthecellnearestthesamplinglocationisused.
"BILINEAR":thevalueofthefournearestcellsaresampledbylinearweighting,
accordingtotheirproximitytothesamplingsite.
"BICUBIC":thevalueofthesixteennearestcellsaresampled,andtheirvaluesare
combinedbyweightaccordingtoapiecewisecubicpolynomialrecommendedby
Rifman(seeDigitalImageWarping,GeorgeWolberg,1990,pp129-131,IEEE
ComputerSocietyPress).
"BICUBIC_2":thevalueissampledusingthesameprocedureandthesamepolynomial
aswithBICUBICabove,butusingadifferentcoefficient.Thismethodmayproduce
somewhatsharperresultsthanBICUBIC,butthatresultisdatadependent.
Formoreinformationonthesesamplingmethodsandonrastersamplingingeneral,see
thiswikipediaarticle.
gis:set-sampling-method
gis:set-sampling-methodRasterDatasetsampling-method
Setsthesamplingmethodusedbythegivenrasterdatasetatasinglepoint,oroveran
areasmallerthanasinglerastercell.SamplingisperformedbytheGISextension
primitivesraster-sample,resample,convolve,andapply-raster.Thesamplingmethodmust
beoneofthefollowing:
"NEAREST_NEIGHBOR"
"BILINEAR"
"BICUBIC"
"BICUBIC_2"
Seesampling-method-ofaboveforamorespecificdescriptionofeachsamplingmethod.
gis:raster-sample
gis:raster-sampleRasterDatasetsample-location
Reportsthevalueofthegivenrasteroverthegivenlocation.Thelocationmaybeanyof
thefollowing:
Alistoflength2,whichistakentorepresentapointinnetlogospace([xcor ycor])of
thesortreportedbylocation-ofVertex.Therasterdatasetissampledatthepointofthat
location.
Alistoflength4,whichistakentorepresentanenvelopeinGISspace,ofthesort
reportedbyenvelope-of.Therasterdatasetissampledovertheareaofthatenvelope.
Apatch,inwhichcasetherasterdatasetissampledovertheareaofthepatch.
Aturtle,inwhichcasetherasterdatasetissampledatthelocationofthatturtle.
AVertex,inwhichcasetherasterdatasetissampledatthelocationofthatVertex.
Iftherequestedlocationisoutsidetheareacoveredbytherasterdataset,thisprimitive
reportsthespecialvaluerepresenting“notanumber”,whichisprintedbyNetLogoas
“NaN”.Usingthespecial“notanumber”valueasanargumenttoprimitivesthatexpecta
numbermaycauseanerror,butyoucantestthevaluereportedbythisprimitivetofilter
out“notanumber”values.Avaluethatisnotanumberwillbeneitherlessthannor
greaterthananumbervalue,soyoucandetect“notanumber”valuesusingthefollowing:
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 ]
Iftherequestedlocationisapoint,thesampleisalwayscomputedusingthemethodset
byset-sampling-method.Iftherequestedlocationisanarea(i.e.,anenvelopeorpatch),
thesampleiscomputedbytakingtheaverageofallrastercellscoveredbytherequested
area.
gis:raster-world-envelope
gis:raster-world-envelopeRasterDatasetxy
ReportstheGISenvelopeneededtomatchtheboundariesofNetLogopatcheswiththe
boundariesofcellsinthegivenrasterdataset.Thisenvelopecouldthenbeusedasan
argumenttoset-transformation-ds.
TheremaybemorecellsinthedatasetthantherearepatchesintheNetLogoworld.In
thatcase,youwillneedtoselectasubsetofcellsinthedatasetbyspecifyingwhichcellin
thedatasetyouwanttomatchwiththeupper-leftcorneroftheNetLogoworld.Cellsare
numberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleft
cellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset
-1).
gis:create-raster
gis:create-rasterwidthheightenvelope
Createsandreportsanew,emptyrasterdatasetwiththegivennumberofcolumnsand
rows,coveringthegivenenvelope.
gis:resample
gis:resampleRasterDatasetenvelopewidthheight
ReportsanewdatasetthatconsistsofthegivenRasterDatasetresampledtocoverthe
givenenvelopeandtocontainthegivennumberofcolumnsandrows.Ifthenewraster’s
cellsaresmallerthantheexistingraster’scells,theywillberesampledusingthemethod
setbyset-sampling-method.Ifthenewcellsarelargerthantheoriginalcells,theywillbe
sampledusingthe"NEAREST_NEIGHBOR"method.
gis:convolve
gis:convolveRasterDatasetkernel-rowskernel-columnskernelkey-columnkey-row
Reportsanewrasterwhosedataconsistsofthegivenrasterconvolvedwiththegiven
kernel.
Aconvolutionisamathematicaloperationthatcomputeseachoutputcellbymultiplying
elementsofakernelwiththecellvaluessurroundingaparticularsourcecell.Akernelisa
matrixofvalues,withoneparticularvaluedefinedasthe“keyelement”,thevaluethatis
centeredoverthesourcecellcorrespondingtothedestinationcellwhosevalueisbeing
computed.
Thevaluesofthekernelmatrixaregivenasalist,whichenumeratestheelementsofthe
matrixfromlefttoright,toptobottom.Sotheelementsofa3-by-3matrixwouldbelisted
inthefollowingorder:
123
456
789
Thekeyelementisspecifiedbycolumnandrowwithinthematrix.Columnsarenumbered
fromlefttoright,beginningwithzero.Rowsarenumberedfromtoptobottom,also
beginningwithzero.So,forexample,thekernelforthehorizontalSobeloperator,which
lookslikethis:
1 0 -1
20
(key) -2
1 0 -1
wouldbespecifiedasfollows:
let horizontal-gradient gis:convolve dataset 3 3 [1 0 -1 2 0 -2 1 0 -1] 1 1
gis:apply-raster
gis:apply-rasterRasterDatasetpatch-variable
Copiesvaluesfromthegivenrasterdatasettothegivenpatchvariable,resamplingthe
rasterasnecessarysothatitscellboundariesmatchupwithNetLogopatchboundaries.
Thisresamplingisdoneasifusingresampleratherthanraster-sample,forthesakeof
efficiency.However,patchesnotcoveredbytherasterareassignedvaluesof“nota
number”inthesamewaythatraster-samplereportsvaluesforlocationsoutsidethe
raster.
gis:drawing-color
gis:drawing-color
ReportsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogo
drawinglayer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumber
betweenzeroand140)oranRGBcolor(alistof3numbers).SeedetailsintheColors
sectionoftheProgrammingGuide.
gis:set-drawing-color
gis:set-drawing-colorcolor
SetsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogodrawing
layer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumberbetweenzero
and140)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionofthe
ProgrammingGuide.
gis:draw
gis:drawvector-dataline-thickness
DrawsthegivenvectordatatotheNetLogodrawinglayer,usingthecurrentGISdrawing
color,withthegivenlinethickness.Thedatamayconsisteitherofanentire
VectorDataset,orasingleVectorFeature.Thisprimitivedrawsonlytheboundaryof
polygondata,andforpointdata,itfillsacirclewitharadiusequaltothelinethickness.
gis:fill
gis:fillvector-dataline-thickness
FillsthegivenvectordataintheNetLogodrawinglayerusingthecurrentGISdrawing
color,usingthegivenlinethicknessaroundtheedges.Thedatamayconsisteitherofan
entireVectorDataset,orasingleVectorFeature.Forpointdata,itfillsacirclewitharadius
equaltothelinethickness.
gis:paint
gis:paintRasterDatasettransparency
PaintsthegivenrasterdatatotheNetLogodrawinglayer.Thehighestvalueinthe
datasetispaintedwhite,thelowestispaintedinblack,andtheothervaluesarepaintedin
shadesofgrayscaledlinearlybetweenwhiteandblack.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.
Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
gis:import-wms-drawing
gis:import-wms-drawingserver-urlspatial-referencelayerstransparency
ImportsanimageintotheNetLogodrawinglayerusingtheWebMappingService
protocol,asdefinedbytheOpenGeospatialConsortium.
Thespatialreferenceandlayersinputsshouldbegivenasstrings.Thespatialreference
inputcorrespondstotheSRSparametertotheGetMaprequestasdefinedinsection
7.2.3.5ofversion1.1.1oftheWMSstandard.Thelayersinputcorrespondstothe
LAYERSparametertotheasdefinedin7.2.3.3ofversion1.1.1oftheWMSstandard.
Youcanfindthelistofvalidspatialreferencecodesandlayernamesbyexaminingthe
responsetoaGetCapabilitiesrequesttotheWMSserver.Consulttherelevantstandard
forinstructionsonhowtoissueaGetCapabilitiesrequesttotheserverandhowto
interprettheresults.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.
Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
NetLogoGogoExtension
Usage
TheGoGoExtensioncomespreinstalledwhenyoudownloadandinstallNetLogo.Touse
theextensioninyourmodel,addthislinetothetopofyourCodetab:
extensions [ gogo ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddgogotothelist.
Afterloadingtheextension,youcanseewhetheroneormoreHID-basedgogosareon
andattachedtothecomputerbytypingthefollowingintothecommandcenter:
gogo:howmany-gogos
Changes
ComparedtopreviousversionsoftheGoGoextension,thisversionoffers:
Improvedrobustness.WithpriorversionsoftheGoGoextension,crasheswerefairly
commonduetoproblemsintheUSB-Serialstackacrossplatforms.TheswitchtoHID
improvedrobustness,andthenewextensionalsousesa“daemon”architecturewhich
shieldsNetLogofromanyproblemsthatmayoccurindirectcommunicationwiththe
GoGoboard.TheresultisasubstantialreductioninthenumberofcrashesofNetLogo.
NoInstallationofDrivers.BecausethenewGoGofirmwarepresentstheboardasan
HIDdevice,theextensioncouldbewrittensoasnottorequireinstallingdrivers.This
meansthereisnoneedfortheusertohaveadministratorrightsonthecomputer.
DirectionalityforMotors.Theboardnowhaspolarity-ensuringoutputconnectors,so
that“counterclockwise”or“clockwise”cannowbespecifiedincode.
Primitives
OtherOutputs
gogo:ledgogo:beep
Utilities
gogo:read-all
General
gogo:primitivesgogo:howmany-gogos
Sensors
gogo:read-sensorsgogo:read-sensor
OutputsandServos
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
Returnsalistoftheprimitivesofthisextension.
gogo:howmany-gogos
gogo:howmany-gogos
ReportsthenumberofUSBHIDdevicesvisibletothecomputerandhavingthecorrect
vendorandproductIDtobeaGoGoboard.Aboardwillonlybedetectedifitisboth
connectedandpoweredon.Usingthisprimitiveisonewaytodeterminequicklywhethera
GoGoboardhastheHIDfirmwareloaded.(AUSB-Serialversionoftheboardwillnotbe
detected.).
gogo:talk-to-output-ports
gogo:talk-to-output-portslist-of-portnames
Establishesalistofoutputportsthatwillbecontrolledwithsubsequentoutput-port
commands.Seebelow…
gogo:set-output-port-power
gogo:set-output-port-powerpower-level
power-levelisanumberbetween0and100,reflectingthepercentageofmaximum
power.Setstheamountofpowerthatwillbefedtotheoutputportsindicatedintalk-to-
output-ports.Thiswillnotaffecttheon-offstateoftheoutputports.So,forexample,ifa
motorisalreadyconnectedtoanoutputportandrunning,changingitspowerwillchange
itsspeed.Ifthemotorisnotrunning,changingthepowerlevelwillnotturniton;instead,it
willaffectthespeedatwhichthemotorstartswhenitisturnedonwithoutput-port-on.
gogo:output-port-on
gogo:output-port-on
Turnsontheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehave
beensetwithtalk-to-output-ports,noportswillbeturnedon.
gogo:output-port-off
gogo:output-port-off
Turnsofftheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehave
beensetwithtalk-to-output-ports,noportswillbeturnedoff.
gogo:output-port-clockwise
gogo:output-port-clockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,so
thatamotorattachedtooneoftheseportswouldturnclockwise.
gogo:output-port-counterclockwise
gogo:output-port-counterclockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,
sothatamotorattachedtooneoftheseportswouldturncounterclockwise.
gogo:set-servo
gogo:set-servonumber
SetsthePulse-WidthModulation(PWM)proportionoftheoutputport(s)thathavebeen
specifiedwithtalk-to-output-ports.Notethattheservoconnectorsarethemalepinsnext
tothestandardmotorconnectors.DifferentservosrespondtodifferentPWMranges,but
allservosreadPWMproportionsandsetthepositionoftheirmaingearaccordingly.
gogo:led
gogo:ledon-or-off
Turnstheuser-LEDonoroff,dependingontheargument.gogo:led1turnstheLEDon;
gogo:led0turnsitoff.
gogo:beep
gogo:beep
CausestheGoGoboardtobeep.
gogo:read-sensors
gogo:read-sensors
ReportsalistcontainingthecurrentreadingsofalleightsensorsportsoftheGoGo.
gogo:read-sensor
gogo:read-sensorwhich-sensor
Reportsthevalueofsensornumberwhich-sensor,wherewhich-sensorisanumber
between0-7.
gogo:read-all
gogo:read-all
Reportsalldataavailablefromtheboard,inaraw-listformusefulfordebugging.
gogo:send-bytes
gogo:send-byteslist
SendsalistofbytestotheGoGoboard.Usefulfordebuggingorfortestinganynewor
futurefunctionalitythatisaddedtotheGoGoboardwithnewfirmwareupdates.
NetLogoLsExtension
LevelSpacefundamentals
LevelSpacemustbeloadedinamodelusingextensions [ls]atthetopofyourmodel.
Oncethisisdone,amodelwillbeabletoloadupothermodelsusingtheLevelSpace
primitives,runcommandsandreportersinthem,andclosethemdownwhentheyareno
longerneeded.
AskingandreportinginLevelSpaceisconceptuallyprettystraightforward:Youpassblocks
ofcodetochildmodels,andthechildmodelsrespondasifyouhadtypedthatcodeinto
theirCommandCenter.LevelSpaceallowsyoutoreportstrings,numbers,andlistsfroma
childtoitsparent.Itisnotpossibletodirectlyreportturtles,patches,links,oranyoftheir
respectivesets.Further,itisnotpossibletopushdatafromachildtoitsparent-parents
mustasktheirchildrentoreport.Thismimicksthewayinwhichturtlescannot“push”data
totheobserver,butrelyontheobservertoaskthemforit.
Ingeneral,theLevelSpacesyntaxhasbeendesignedtoalignwithexistingNetLogo
primitiveswheneverpossible.
HeadlessandInteractiveModels
LevelSpacehastwodifferentchildmodeltypes;headlessmodelsandinteractivemodels.
Theyeachhavetheirstrengthsandweaknesses:
Interactivemodels*arefull-fledgedmodelsthatgivefullaccesstotheirinterfaceand
widgets,*runabitslower,andusemorememory*arevisiblebydefault
HeadlessModels*onlygiveyouaccesstotheirviewandcommandcenter*arefasterand
uselessmemorythaninteractivemodels.*arehiddenbydefault
Typicallyyouwillwanttouseheadlessmodelswhenyouarerunningalargenumberof
models,orifyousimplywanttorunthemfaster.Interactivemodelsaregoodifyouruna
smallamountofmodels,ifyouarewritingaLevelSpacemodelandneedtobeableto
debug,orifyouneedaccesstowidgetsduringruntime.
KeepingTrackofModels
Childmodelsarekepttrackofintheextensionwithanidnumber,startingwith0,andall
communicationfromparenttochildisdonebyreferencingthisnumber,henceforthreferred
toasmodel-id.
Theeasiestwaytoworkwithmultiplemodelsistostoretheirmodel-idinalist,anduse
NetLogo’slistprimitivestosort,filter,etc.themduringruntime.
Keepingtrackofmodelsisimportant:MostLevelSpaceprimitiveswillfailandcausea
runtimeinterruptionifprovidedamodel-idtoanon-existingmodel.Youcanusels:model-
exists? model-idtocheckifmodel-idreferstoanexistingmodel.
Ageneralusecase:AskingandReporting
ThisusecaseisbasedontheModelVisualizerandPlotterExample-modelfromthe
NetLogoModelsLibrary.
Asimplethingwecandoistoopenupsomemodels,runthemconcurrently,andcalculate
theaverageofsomereporter.Let’ssaythatweareinterestedinfindingthemeannumber
ofsheepinabunchofWolfSheepPredationmodels.Firstwewouldopenupsomeof
thesemodels,andsetthemup:
to setup
ls:reset
ca
ls:create-models 30 "Wolf Sheep Predation.nlogo"
ls:ask ls:models [ set grass? true setup ]
reset-ticks
end
Wethenwanttorunallourchildmodels,andthenfindoutwhatthemeannumberof
sheepis:
to go
ls:ask ls:models [ go ]
show mean [ count sheep ] ls:of ls:models
end
Ageneralusecase:Inter-ModelInteractions
ThisusecaseisbasedontheModelInteractionsExample-modelfromtheNetLogoModels
Library.
Let’simaginethatwehavetwomodels:aWolfSheepPredation-modelcalledWSP,anda
ClimateChangemodelcalledCC.Nowlet’simaginethatwewanttheregrowthtimeinthe
wSPmodeltodependonthetemperatureintheCCmodel.UsingLevelSpace’sprimitives,
wecoulddosomethinglikethis:
; 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 ]
AgeneralUsecase:Tidyingup“Dead”ChildModels
Aspreviouslymentioned,itisimportanttokeeptrackof“living”and“dead”modelswhen
youdynamicallycreateanddisposeofmodels.Letusimaginewehavesomelistsof
modelsofdifferentkinds,andwewanttomakesurethatweonlykeepthemodelsthatare
alive.Afterrunningcodethatkillschildmodelswecanusethels:model-exists?primitive
tocleanupourlistofmodelslikethis:
to-report remove-dead-models [list-of-models]
report filter [ [ model-id ] -> ls:model-exists model-id] list-of-models
end
Wethenreassigneachlistofmodelswiththis,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
CitingLevelSpaceinResearch
IfyouuseLevelSpaceinresearch,weaskthatyouciteus,
Hjorth,A.Head,B.&Wilensky,U.(2015).“LevelSpaceNetLogoextension”.
http://ccl.northwestern.edu/rp/levelspace/index.shtmlEvanston,IL:CenterforConnected
LearningandComputerBasedModeling,NorthwesternUniversity.
Primitives
CommandingandReporting
ls:askls:ofls:reportls:withls:letls:assign
LogicandControl
ls:modelsls:showls:show-allls:hidels:hide-allls:path-ofls:name-ofls:model-exists?
OpeningandClosingModels
ls:create-modelsls:create-interactive-modelsls:closels:reset
ls:create-models
ls:create-modelsnumberpath
ls:create-modelsnumberpathanonymouscommand
Createthespecifiednumberofinstancesofthegiven.nlogomodel.Thepathcanbe
absolute,orrelativetothemainmodel.Comparedwithls:create-interactive-models,this
primitivecreateslightweightmodelsthatarehiddenbydefault.Youshouldusethis
primitiveifyouplanonhavingmanyinstancesofthegivenmodel.Themodelsmaybe
shownusingls:show;whenvisible,theywillhaveaviewandcommandcenter,butno
otherwidgets,e.g.plotsormonitors.
Ifgivenacommand,LevelSpacewillcallthecommandafterloadingeachinstanceofthe
modelwiththemodel-idastheargument.Thisallowsyoutoeasilystoremodelidsina
variableorlistwhenloadingmodels,ordootherinitialization.Forexample,tostorea
modelidinavariable,youcando:
let model-id 0
(ls:create-models "My-Model.nlogo" [ [id] -> set model-id id ])
ChildmodelRNGsareseededfromtheparentmodelsRNGwhentheyarecreated.Thus,
ifyouseedtheparent’smodelRNGbeforechildmodelbeforechildmodelsarecreated,
thesimulationasawholewillbereproducible.Usethels:random-seedprimitivetoseedthe
modelsystem’sRNGsafterchildmodelshavebeencreated.
ls:create-interactive-models
ls:create-interactive-modelsnumberpath
ls:create-interactive-modelsnumberpathanonymouscommand
Likels:create-models,createsthespecifiednumberofinstancesofthegiven.nlogo
model.Unlikels:create-models,ls:create-interactive-modelscreatesmodelsthatare
visiblebydefault,andhaveallwidgets.Youshouldusethisprimitiveifyouplanonhaving
onlyahandfulofinstancesofthegivenmodel,andwouldliketobeabletointeractwiththe
instancesthroughtheirinterfacesduringruntime.
ChildmodelRNGsareseededfromtheparentmodelsRNGwhentheyarecreated.Thus,
ifyouseedtheparent’smodelRNGbeforechildmodelbeforechildmodelsarecreated,
thesimulationasawholewillbereproducible.Usethels:random-seedprimitivetoseedthe
modelsystem’sRNGsafterchildmodelshavebeencreated.
ls:close
ls:closemodel-or-list-of-models
Closethemodelormodelswiththegivenmodel-id.
ls:reset
ls:reset
Closedownallchildmodels(and,recursively,theirchildmodels).You’lloftenwanttocall
thisinyoursetupprocedure.
Notethatclear-alldoesnotcloseLevelSpacemodels.
ls:ask
ls:askmodel-or-list-of-modelscommandargument
Askthegivenchildmodelorlistofchildmodelstorunthegivencommand.Thisisthe
primaryofdoingthingswithchildmodels.Forexample:
ls:ask model-id [ create-turtles 5 ]
Youcanalsoaskalistofmodelstoalldothesamething:
ls:ask ls:models [ create-turtles 5 ]
Youmaysupplythecommandwitharguments,justlikeyouwouldwithanonymous
commands:
let turtle-id 0
let speed 5
(ls:ask model-id [ [t s] -> ask turtle t [ fd s ] ] turtle-id speed)
Notethatthecommandscannotaccessvariablesintheparentmodeldirectly.Youmust
eitherpassinformationinthroughargumentsorusingls:let.
ls:of
reporterls:ofmodel-or-list-of-models
Runthegivenreporterinthegivenmodelandreporttheresult.
ls:ofisdesignedtoworklikeNetLogo’sinbuiltof:Ifyousendls:ofamodel-id,itwill
reportthevalueofthereporterfromthatmodel.Ifyousenditalistofmodel-ids,itwill
reportalistofvaluesofthereporterstringfromallmodels.Youcannotpassargumentsto
ls:of,butyoucanusels:let.
[ count turtles ] ls:of model-id
ls:report
ls:reportmodel-or-list-of-modelsreporterargument
Runthegivenreporterinthegivenmodelandreporttheresult.Thisformexiststoallow
youtopassargumentstothereporter.
let turtle-id 0
(ls:report model-id [ [a-turtle] -> [ color ] of turtle a-turtle ] turtle-id)
ls:with
list-of-modelsls:withreporter
Reportsanewlistofmodelscontainingonlythosemodelsthatreporttruewhentheyrun
thereporterblock.
ls:models ls:with [ count turtles > 100 ]
ls:let
ls:letvariable-namevalue
Createsavariablecontainingthegivendatathatcanbeaccessedbythechildmodels.
ask turtles [
ls:let my-color color
ls:ask my-model [
ask turtles [ set color my-color ]
]
]
ls:letworksquitesimilartoletinthatthevariableisonlylocallyaccessible:
ask turtles [
ls:let my-color color
]
;; my-color is innaccessible here
ls:letisverysimilartolet,exceptinafewcases.
ls:letwilloverwritepreviousvaluesinthevariable
Ifyoudo
ls:let my-var 5
ls:let my-var 6
my-varwillbesetequalto6.Thereisnols:set.
ls:letsupportsvariableshadowing
Ifyoudo
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-modelwillshow6andthen5.Thisisknownasvariableshadowing.
Theparentmodelcannotdirectlyreadthevalueofanlsvariable
Forexample,thisdoesnotwork.
ls:let my-var 5
show my-var
Thisisintentional.lsvariablesaremeanttobeusedforsharingdatawithchildmodels.The
parentmodelalreadyhasaccesstothedata.
Furthermore,changingthevalueofanlsletvariableinachildmodelwillnotaffectitinany
othermodel.Forexample:
ls:let my-var 0
ls:ask ls:models [
set my-var my-var + 1
show my-var
]
Allmodelswillprint1.
ls:assign
ls:assignmodel-or-list-of-modelsglobal-variablevalue
Setsthegivenglobalvariableinchildmodeltogivenvalue.Forinstance
ls:assign ls:models glob1 count turtles
setstheglobalvariableglob1inallmodelstotheparent’smodelcount turtles.
ls:models
ls:models
Reportalistofmodel-idsforallexistingmodels.
ls:show
ls:showmodel-or-list-of-models
Makesallofthegivenmodelsvisible.
ls:show-all
ls:show-allmodel-or-list-of-models
Makesallofthegivenmodelsandtheirdescendentsvisible.
ls:hide
ls:hidemodel-or-list-of-models
Hideallofthegivenmodels.Hidingmodelsisagoodwayofmakingyoursimulationrun
faster.
ls:hide-all
ls:hide-allmodel-or-list-of-models
Hideallofthegivenmodelsandtheirdescendents.Hidingmodelsisagoodwayofmaking
yoursimulationrunfaster.
ls:path-of
ls:path-ofmodel-or-list-of-models
Reportthefullpath,includingthe.nlogofilename,ofthemodel.Ifalistofmodelsisgiven,
alistofpathsisreported.
ls:name-of
ls:name-ofmodel-or-list-of-models
Reportsthenameofthe.nlogofileofthemodel.Thisisthenameofthewindowinwhich
themodelappearswhenvisible.Ifalistofmodelsisgiven,alistofnamesisreported.
ls:model-exists?
ls:model-exists?model-or-list-of-models
Reportabooleanvalueforwhetherthereisamodelwiththatmodel-id.Thisisoftenuseful
whenyouaredynamicallygeneratingmodels,andwanttoensurethatyouarenotasking
modelsthatnolongerexisttodostuff.
ls:random-seed
ls:random-seedseed
BehavesexactlylikeNetLogo’sbuilt-inprimitiverandom-seed,exceptthatchildmodelshave
theirRNGsseededbasedonthegivenseedaswell(aswelltheirchildmodels,andtheir
childmodels’childmodels,andsoforth).Thisprimitiveshouldalmostalwaysbeused
insteadofNetLogo’sbuilt-inoneforseedingRNGwhenusingLevelSpace.
NetLogoMatrixExtension
Using
ThematrixextensionaddsanewmatrixdatastructuretoNetLogo.Amatrixisamutable2-dimensionalarraycontaining
onlynumbers.
WhentoUse
Althoughmatricesstorenumbers,muchlikealistoflists,oranarrayofarrays,theprimaryreasontousethematrixdata
typeistotakeadvantageofspecialmathematicaloperationsassociatedwithmatrices.Forinstance,matrixmultiplication
isaconvenientwaytoperformgeometrictransformations,andtherepeatedapplicationofmatrixmultiplicationcanalso
beusedtosimulateotherdynamicprocesses(forinstance,processesongraph/networkstructures).
Ifyou’dliketoknowmoreaboutmatricesandhowtheycanbeused,youmightconsideracourseonlinearalgebra,or
searchthewebfortutorials.Thematrixextensionalsoallowsyoutosolvelinearalgebraicequations(specifiedina
matrixformat),andeventoidentifytrendsinyourdataandperformlinear(ordinaryleastsquares)regressionsondata
setswithmultipleexplanatoryvariables.
HowtoUse
Thematrixextensioncomespreinstalled.
Tousethematrixextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [matrix]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddmatrixtothelist.
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
Matrixcreationandconversionto/fromlists
matrix:make-constantmatrix:make-identitymatrix:from-row-listmatrix:from-column-listmatrix:to-row-list
matrix:to-column-listmatrix:copymatrix:pretty-print-text
Advancedfeatures
matrix:solvematrix:forecast-linear-growthmatrix:forecast-compound-growthmatrix:forecast-continuous-growth
matrix:regress
Matrixdataretrievalandmanipulation
matrix:getmatrix:get-rowmatrix:get-columnmatrix:setmatrix:set-rowmatrix:set-columnmatrix:swap-rows
matrix:swap-columnsmatrix:set-and-reportmatrix:dimensionsmatrix:submatrixmatrix:map
Mathoperations
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
Reportsanewn-rowsbyn-colsmatrixobject,withallentriesinthematrixcontainingthesamevalue(number).
matrix:make-identity
matrix:make-identitysize
Reportsanewsquarematrixobject(withdimensionsn-sizexn-size),consistingoftheidentitymatrix(1salongthemain
diagonal,0selsewhere).
matrix:from-row-list
matrix:from-row-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolist,whereeachiteminthatlistisanotherlist(correspondingto
eachoftherowsofthematrix.)
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-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolistcontainingeachofthecolumnsofthematrix.
matrix:to-row-list
matrix:to-row-listmatrix
Reportsalistoflists,containingeachrowofthematrix.
matrix:to-column-list
matrix:to-column-listmatrix
Reportsalistoflists,containingeachcolumnofthematrix.
matrix:copy
matrix:copymatrix
Reportsanewmatrixthatisanexactcopyofthegivenmatrix.Thisprimitiveisimportantbecausethematrixtypeis
mutable(changeable).Here’sacodeexample:
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-textmatrix
Reportsastringthatisatextualrepresentationofthematrix,inaformatthatisreasonablyhuman-readablewhen
displayed.
matrix:get
matrix:getmatrixrow-icol-j
Reportsthe(numeric)valueatlocationrow-i(secondargument),col-j(thirdargument),inthegivenmatrixgiveninthe
firstargument
matrix:get-row
matrix:get-rowmatrixrow-i
Reportsasimple(notnested)NetLogolistcontainingtheelementsofrow-i(secondargument)ofthematrixsuppliedin
thefirstargument.
matrix:get-column
matrix:get-columnmatrixcol-j
Reportsasimple(notnested)NetLogolistcontainingtheelementsofcol-jofthematrixsuppliedinthefirstargument.
matrix:set
matrix:setmatrixrow-icol-jnew-value
Changesthegivenmatrixbysettingthevalueatlocationrow-i,col-jtonew-value
matrix:set-row
matrix:set-rowmatrixrow-isimple-list
Changesthegivenmatrixmatrixbyreplacingtherowatrow-iwiththecontentsofthesimple(notnested)NetLogolist
simple-list.Thesimple-listmusthavealengthequaltothenumberofcolumnsinthematrix,i.e.,thematrixrowlength.
matrix:set-column
matrix:set-columnmatrixcol-jsimple-list
Changesthegivenmatrixmatrixbyreplacingthecolumnatcol-jwiththecontentsofthesimple(notnested)NetLogolist
simple-list.Thesimple-listmusthavealengthequaltothenumberofrowsinthematrix,i.e.,thematrixcolumnlength
length.
matrix:swap-rows
matrix:swap-rowsmatrixrow1row2
Changesthegivenmatrixmatrixbyswappingtherowsatrow1androw2witheachother.
matrix:swap-columns
matrix:swap-columnsmatrixcol1col2
Changesthegivenmatrixmatrixbyswappingthecolumnsatcol1andcol2witheachother.
matrix:set-and-report
matrix:set-and-reportmatrixrow-icol-jnew-value
Reportsanewmatrix,whichisacopyofthegivenmatrixexceptthatthevalueatrow-i,col-jhasbeenchangedtonew-
value.ANetLogostatementsuchasset mat matrix:set-and-report mat 2 3 10willresultinmatpointingtothisnew
matrix,acopyoftheoldversionofmatwiththeelementatrow2,column3beingsetto10.Theoldversionofmatwillbe
“lost”.
matrix:dimensions
matrix:dimensionsmatrix
Reportsa2-elementlist([num-rows,num-cols]),containingthenumberofrowsandnumberofcolumnsinthegiven
matrix
matrix:submatrix
matrix:submatrixmatrixr1c1r2c2
Reportsanewmatrixobject,consistingofarectangularsubsectionofthegivenmatrix.Therectangularregionisfrom
rowr1upto(butnotincluding)rowr2,andfromcolumnc1upto(butnotincluding)columnc2.
Hereisanexample:
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:mapanonymousreportermatrix
matrix:mapanonymousreportermatrixanything
Reportsanewmatrixwhichresultsfromapplyingreporter(ananonymousreporterorthenameofareporter)toeachof
theelementsofthegivenmatrix.Forexample,
matrix:map sqrt matrix
wouldtakethesquarerootofeachelementofmatrix.Ifmorethanonematrixargumentisprovided,thereporterisgiven
theelementsofeachmatrixasarguments.Thus,
(matrix:map + matrix1 matrix2)
wouldaddmatrix1andmatrix2.
Thisreporterismeanttobethesameasmap,butformatricesinsteadoflists.
matrix:times-scalar
matrix:times-scalarmatrixfactor
AsofNetLogo5.1,matrix:timescanmultiplymatricesbyscalarsmakingthisfunctionobsolete.Usematrix:times
instead.
Reportsanewmatrix,whichistheresultofmultiplyingeveryentryintheoriginalmatrixbythegivenscalingfactor.
matrix:times
matrix:timesm1m2
matrix:timesm1m2...
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesandscalars(usingstandardmatrixmultiplication–
makesureyourmatrixdimensionsmatchup.)Withoutparentheses,ittakestwoarguments.Withparenthesesittakes
twoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:*
m1matrix:*m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesand/orscalars(usingstandardmatrixmultiplication
–makesureyourmatrixdimensionsmatchup.)Thisisexactlythesameasmatrix:times m1 m2
Takesprecedenceovermatrix:+andmatrix:-,sameasnormalmultiplication.
matrix:times-element-wise
matrix:times-element-wisem1m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricestogether,element-wise.Allelementsaremultiplied
byscalarargumentsaswell.Notethatallmatrixargumentsmusthavethesamedimensions.Withoutparentheses,it
takestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butat
leastonemustbeamatrix.
matrix:plus-scalar
matrix:plus-scalarmatrixnumber
AsofNetLogo5.1,matrix:pluscanaddmatricesandscalarsmakingthisfunctionobsolete.Usematrix:plusinstead.
Reportsamatrix,whichistheresultofaddingtheconstantnumbertoeachelementofthegivenmatrix.
matrix:plus
matrix:plusm1m2
matrix:plusm1m2...
Reportsamatrix,whichistheresultofaddingthegivenmatricesandscalars.Scalarsareaddedtoeachelement.
Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbe
numbersormatrices,butatleastonemustbeamatrix.
matrix:+
m1matrix:+m2
Reportsamatrix,whichistheresultofaddingthegivenmatricesand/orscalars.Thisisexactlythesameasmatrix:plus
m1 m2
Takesprecedenceaftermatrix:*,sameasnormaladdition.
matrix:minus
matrix:minusm1m2
matrix:minusm1m2...
Reportsamatrix,whichistheresultofsubtractingallargumentsbesidesm1fromm1.Scalarargumentsaretreatedas
matricesofthesamesizeasthematrixargumentswitheveryelementequaltothatscalar.Withoutparentheses,ittakes
twoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleast
onemustbeamatrix.
matrix:-
m1matrix:-m2
Reportsamatrix,whichistheresultofsubtractingthegivenmatricesand/orscalars.Thisisexactlythesameas
matrix:minus m1 m2
Takesprecedenceaftermatrix:*,sameasnormalsubtraction.
matrix:inverse
matrix:inversematrix
Reportstheinverseofthegivenmatrix,orresultsinanerrorifthematrixisnotinvertible.
matrix:transpose
matrix:transposematrix
Reportsthetransposeofthegivenmatrix.
matrix:real-eigenvalues
matrix:real-eigenvaluesmatrix
Reportsalistcontainingtherealeigenvaluesofthegivenmatrix.
matrix:imaginary-eigenvalues
matrix:imaginary-eigenvaluesmatrix
Reportsalistcontainingtheimaginaryeigenvaluesofthegivenmatrix.
matrix:eigenvectors
matrix:eigenvectorsmatrix
Reportsamatrixthatcontainstheeigenvectorsofthegivenmatrix.(Eacheigenvectorasacolumnoftheresulting
matrix.)
matrix:det
matrix:detmatrix
Reportsathedeterminantofthematrix.
matrix:rank
matrix:rankmatrix
Reportstheeffectivenumericalrankofthematrix,obtainedfromSVD(SingularValueDecomposition).
matrix:trace
matrix:tracematrix
Reportsthetraceofthematrix,whichissimplythesumofthemaindiagonalelements.
matrix:solve
matrix:solveAC
Reportsthesolutiontoalinearsystemofequations,specifiedbytheAandCmatrices.Ingeneral,solvingasetoflinear
equationsisakintomatrixdivision.Thatis,thegoalistofindamatrixBsuchthatA*B=C.(Forsimplelinearsystems,
CandBcanbothbe1-dimensionalmatrices–i.e.vectors).IfAisnotasquarematrix,thena“leastsquares”solutionis
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
Reportsafour-elementlistoftheform:
[ forecast constant slope R2 ]
Theforecastisthepredictednextvaluethatwouldfollowinthesequencegivenbythedata-listinput,basedonalinear
trend-line.Normallydata-listwillcontainobservationsonsomevariable,Y,fromtimet=0totimet=(n-1)wherenisthe
numberofobservations.TheforecastisthepredictedvalueofYatt=n.Theconstantandslopearetheparametersof
thetrend-line
Y = *constant* + *slope* * t.
TheR2valuemeasuresthegoodnessoffitofthetrend-linetothedata,withanR
2=1beingaperfectfitandanR
2of0
indicatingnodiscernibletrend.LineargrowthassumesthatthevariableYgrowsbyaconstantabsoluteamounteach
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-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-proportion R2 ]
Whereasmatrix:forecast-linear-growthassumesgrowthbyaconstantabsoluteamounteachperiod,matrix:forecast-
compound-growthassumesthatYgrowsbyaconstantproportioneachperiod.Theconstantandgrowth-proportionare
theparametersofthetrend-line
Y = constant * growth-proportiont.
Notethatthegrowthproportionistypicallyinterpretedasgrowth-proportion=(1.0+growth-rate).Therefore,if
matrix:forecast-compound-growthreturnsagrowth-proportionof1.10,thatimpliesthatYgrowsby(1.10-1.0)=10%
eachperiod.Notethatifgrowthisnegative,matrix:forecast-compound-growthwillreturnagrowth-proportionoflessthan
one.E.g.,agrowth-proportionof0.90impliesagrowthrateof-10%.
NOTE:ThecompoundgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)Becauseitis
impossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-compound-growthwillresultinanerrorif
itfindsazeroornegativenumberindata-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-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-rate R2 ].Whereasmatrix:forecast-compound-growthassumesdiscretetimewithY
growingbyagivenproportioneachfiniteperiodoftime(e.g.,amonthorayear),matrix:forecast-continuous-growth
assumesthatYiscompoundedcontinuously(e.g.,eachsecondorfractionofasecond).Theconstantandgrowth-rate
aretheparametersofthetrend-line
Y = constant * e(growth-rate * t)
matrix:forecast-continuous-growthisthe“calculus”analogofmatrix:forecast-compound-growth.Thetwowillnormally
yieldsimilar(butnotidentical)results,asshownintheexamplebelow.growth-ratemay,ofcourse,benegative.
NOTE:ThecontinuousgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)
Becauseitisimpossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-continuous-growth
willresultinanerrorifitfindsazeroornegativenumberindata-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
AllthreeoftheforecastprimitivesabovearejustspecialcasesofperforminganOLS(ordinary-least-squares)linear
regression–thematrix:regressprimitiveprovidesaflexible/general-purposeapproach.Theinputisamatrixdata-matrix,
withthefirstcolumnbeingtheobservationsonthedependentvariableandeachsubsequentcolumnbeingthe
observationsonthe(1ormore)independentvariables.Thuseachrowconsistsofanobservationofthedependent
variablefollowedbythecorrespondingobservationsforeachindependentvariable.
TheoutputisaLogonestedlistcomposedoftwoelements.Thefirstelementisalistcontainingtheregressionconstant
followedbythecoefficientsoneachoftheindependentvariables.Thesecondelementisa3-elementlistcontainingthe
R2statistic,thetotalsumofsquares,andtheresidualsumofsquares.Thefollowingcodeexampleshowshowthe
matrix:regressprimitivecanbeusedtoperformthesamefunctionasthecodeexamplesshowninthematrix:forecast-*-
growthprimitivesabove.(However,keepinmindthatthematrix:regressprimitiveismorepowerfulthanthis,andcan
havemanymoreindependentvariablesintheregression,asindicatedinthefourthexamplebelow.)
;; 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.
NetLogoNwExtension
Usage
Thefirstthingthatoneneedstounderstandinordertoworkwiththenetworkextensionishowtotelltheextension
whichnetworktoworkwith.Considerthefollowingexamplesituation:
breed [ bankers banker ]
breed [ clients client ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]
Basically,youhavebankersandclients.Clientscanhaveaccountswithbankers.Bankerscanprobablyhave
accountwithotherbankers,andanyonecanbefriendswithanyone.
Nowwemightwanttoconsiderthiswholethingasonebignetwork.Ifthatisthecase,thereisnothingspecialtodo:
bydefault,theNWextensionprimitivesconsiderallturtlesandalllinkstobepartofthecurrentnetwork.
Wecouldalso,however,beonlyinterestedinasubsetofthenetwork.Maybewewanttoconsideronlyfriendship
relations.Furthermore,maybewewanttoconsideronlythefriendshipsbetweenbankers.Afterall,havingavery
highcentralityinanetworkofbankerfriendshipsisverydifferentfromhavingahighcentralityinanetworkofclient
friendships.
Tospecifysuchnetworks,weneedtotelltheextensionbothwhichturtlesandwhichlinksweareinterestedin.All
theturtlesfromthespecifiedsetofturtleswillbeincludedinthenetwork,andonlythelinksfromthespecifiedsetof
linksthatarebetweenturtlesofthespecifiedsetwillbeincluded.Forexample,ifyouaskforbankersand
friendships,eventhelonelybankerswithnofriendswillbeincluded,butfriendshiplinksbetweenbankersand
clientswillnotbeincluded.Thewaytotelltheextensionaboutthisiswiththenw:set-contextprimitive,whichyou
mustcallpriortodoinganyoperationsonanetwork.
Someexamples:
nw:set-context turtles links willgiveyoueverything:bankersandclients,friendshipsandaccounts,asonebig
network.
nw:set-context turtles friendships willgiveyouallthebankersandclientsandfriendshipsbetweenanyof
them.
nw:set-context bankers friendships willgiveyouallthebankers,andonlyfriendshipsbetweenbankers.
nw:set-context bankers links willgiveyouallthebankers,andanylinksbetweenthem,whethertheselinksare
friendshipsoraccounts.
nw:set-context clients accountswillgiveyoualltheclients,andaccountsbetweeneachother,butsinceinour
fictionalexampleclientscanonlyhaveaccountswithbankers,thiswillbeacompletelydisconnectednetwork.
Specialagentsetsvsnormalagentsets
ItmustbenotedthatNetLogohastwotypesofagentsetsthatbehaveslightlydifferently,andthatthishasanimpact
onthewaynw:set-contextworks.Wewillsayafewwordsabouttheseconceptsherebut,forathorough
understanding,itishighlyrecommendedthatyoureadthesectiononagentsetsintheNetLogoprogrammingguide.
The“special”agentsetsinNetLogoareturtles,linksandthedifferent“breed”agentsets.Whatisspecialabout
themisthattheycangrow:ifyoucreateanewturtle,itwillbeaddedtotheturtlesagentset.Ifyouhaveabankers
breedandyoucreateanewbanker,itwillbeaddedtothebankersagentsetandtotheturtlesagentset.Samegoes
forlinks.Otheragentsets,suchasthosecreatedwiththewithprimitive(e.g.,turtles with [ color = red ] )orthe
turtle-setandlink-setprimitives)areneveraddedto.Thecontentofnormalagentsetswillonlychangeifthe
agentsthattheycontaindie.
Toshowhowdifferenttypesofagentsetsinteractwithnw:set-context,let’screateaverysimplenetwork:
clear-all
create-turtles 3 [ create-links-with other turtles ]
Let’ssetthecontexttoturtlesandlinks(whichisthedefaultanyway)andusenw:get-contexttoseewhatwe
have:
nw:set-context turtles links
show map sort nw:get-context
Wegetallthreeturtlesandallthreelinks:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Nowlet’skilloneturtle:
ask one-of turtles [ die ]
show map sort nw:get-context
Asexpected,thecontextisupdatedtoreflectthedeathoftheturtleandofthetwolinksthatdiedwithit:
[[(turtle 0) (turtle 1)] [(link 0 1)]]
Whatifwenowcreateanewturtle?
create-turtles 1
show map sort nw:get-context
Sinceourcontextisusingthespecialturtlesagentset,thenewturtleisautomaticallyadded:
[[(turtle 0) (turtle 1) (turtle 3)] [(link 0 1)]]
Nowlet’sdemonstratehowitworkswithnormalagentsets.Westartoverwithanewnetworkofredturtles:
clear-all
create-turtles 3 [
create-links-with other turtles
set color red
]
Andwesetthecontexttoturtles with [ color = red ]) andlinks
nw:set-context (turtles with [ color = red ]) links
show map sort nw:get-context
Sinceallturtlesarered,wegeteverythinginourcontext:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Butwhatifweaskoneofthemtoturnblue?
ask one-of turtles [ set color blue ]
show map sort nw:get-context
Nochange.Theagentsetusedinourcontextremainsunaffected:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Ifwekilloneofthem,however…
ask one-of turtles [ die ]
show map sort nw:get-context
Itgetsremovedfromtheset:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
Whatifweaddanewredturtle?
create-turtles 1 [ set color red ]
show map sort nw:get-context
Nope:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
Anoteregardingfloatingpointcalculations
NeitherJGraphTnorJung,thetwonetworklibrariesthatweuseinternally,usestrictfpfloatingpointcalculations.
Thisdoesmeanthatexactreproducibilityofresultsinvolvingfloatingpointcalculationsbetweendifferenthardware
architecturesisnotfullyguaranteed.(NetLogoitselfalwaysusesstrictmathsothisonlyappliestosomeprimitivesof
theNWextension.)
Performance
Inordertobefastinasmanycircumstancesaspossible,theNWextensiontrieshardtonevercalculatethings
twice.Itremembersallpaths,distances,andcentralitiesthatitcalculates.So,whilethefirsttimeyouaskforthe
distancebetweenturtle 0andturtle 3782maytakesometime,afterthat,itshouldbealmostinstantaneous.
Furthermore,itkeepstrackofvaluesitjusthappenedtocalculatealongtheway.Forexample,ifturtle 297iscloser
toturtle 0thanturtle 3782is,itmayjusthappentofigureoutthedistancebetweenturtle 0andturtle 297while
itfiguresoutthedistancebetweenturtle 0andturtle 3782.Itwillrememberthisvalue,sothatifyouaskitforthe
distancebetweenturtle 0andturtle 297,itdoesn’thavetodoallthatworkagain.
ThereareafewcircumstanceswheretheNWextensionhastoforgetthings.Ifthenetworkchangesatall(youadd
turtlesorlinks,orremoveturtlesorlinks),ithastoforgeteverything.Forweightedprimitives,ifthevalueofthe
weightvariablechangesforanyofthelinksinthenetwork,itwillforgetthevaluesassociatedwiththatweight
variable.
Ifyou’reworkingonanetworkthatcanchangeregularly,trytodoallyournetworkcalculationsatonce,thenallyour
networkchangesatonce.Themoreyourinterweavenetworkcalculationsandnetworkchanges,themoretheNW
extensionwillhavetorecalculatethings.Forexample,ifyouhaveatrafficmodel,andcarsneedtofigureoutthe
shortestpathtotheirdestinationbasedonthetrafficeachtick,haveallthecarsfindtheirshortestpaths,then
changethenetworkweightstoaccountforhowtraffichaschanged.
Theremayberareoccasionsinwhichyoudon’twanttheNWextensiontoremembervalues.Forexample,ifyou’re
workingonanextremelylargenetwork,rememberingallthosevaluesmaytakemorememorythanyouhave.Inthat
case,youcanjustcallnw:set-context (first nw:get-context) (last nw:get-context) toforcetheNWextensionto
immediatelyforgeteverything.
Primitives
Generators
nw:generate-preferential-attachmentnw:generate-randomnw:generate-watts-strogatznw:generate-small-world
nw:generate-lattice-2dnw:generate-ringnw:generate-starnw:generate-wheel
PathandDistance
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/CommunityDetection
nw:bicomponent-clustersnw:weak-component-clustersnw:louvain-communitiesnw:maximal-cliquesnw:biggest-
maximal-cliques
ContextManagement
nw:set-contextnw:get-contextnw:with-context
ImportandExport
nw:save-matrixnw:load-matrixnw:save-graphmlnw:load-graphmlnw:loadnw:save
CentralityMeasures
nw:betweenness-centralitynw:eigenvector-centralitynw:page-ranknw:closeness-centralitynw:weighted-closeness-
centrality
ClusteringMeasures
nw:clustering-coefficientnw:modularity
nw:set-context
nw:set-contextturtlesetlinkset
Specifiesthesetofturtlesandthesetoflinksthattheextensionwillconsidertobethecurrentgraph.Alltheturtles
fromturtlesetandallthelinksfromlinksetthatconnecttwoturtlesfromturtlesetwillbeincluded.
Thiscontextisusedbyallotherprimitives(unlessspecifiedotherwise)untilanewcontextisspecified.(Atthe
moment,onlythegeneratorprimitivesandthefileinputprimitivesareexceptionstothisrule.)
Seetheusagesectionforamuchmoredetailedexplanationofnw:set-context.
nw:get-context
nw:get-context
Reportsthecontentofthecurrentgraphcontextasalistcontainingtwoagentsets:theagentsetofturtlesthatare
partofthecontextandtheagentsetoflinksthatarepartofthecontext.
Let’ssaywestartwithablankslateandthedefaultcontextconsistingofturtlesandlinks,nw:get-contextwill
reportalistthespecialturtlesandlinksbreedagentsets:
observer> clear-all
observer> show nw:get-context
observer: [turtles links]
Ifweaddsometurtlesandlinkstoourcontext,we’llstillseethesamething,eventhoughturtlesandlinkshave
internallygrown:
observer> crt 2 [ create-links-with other turtles ]
observer> show nw:get-context
observer: [turtles links]
Ifyouhadsetyourcontexttonormalagentsetsinstead(builtwithturtle-set,link-setorwith)hereiswhatyou
wouldsee:
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)]
Ifyouthencreatenewturtlesandlinks,theyarenotaddedtothecontextbecausenormalagentsetsdon’tgrow(see
Specialagentsetsvsnormalagentsets):
observer> crt 2 [ create-links-with other turtles ]
observer> show nw:get-context
observer: [(agentset, 0 turtles) (agentset, 0 links)]
Butifyouconstructnewagentsetsandsetthecontexttothem,yournewagentswillbethere:
observer> nw:set-context turtle-set turtles link-set links
observer> show nw:get-context
observer: [(agentset, 2 turtles) (agentset, 1 link)]
Ifyouwanttoseetheactualcontentofyourcontext,itiseasytoturnyouragentsetsintoliststhatcanbenicely
displayed.Justuseacombinationofmapandsort:
observer> show map sort nw:get-context
observer: [[(turtle 0) (turtle 1)] [(link 0 1)]]
Finally,youcanusenw:get-contexttostoreacontextthatyoueventuallywanttorestore:
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
Hereistheresult:
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-contextturtlesetlinksetcommand-block
Executesthecommand-blockwiththecontexttemporarilysettoturtlesetandlinkset.Aftercommand-blockfinishes
running,thepreviouscontextwillberestored.
Forexample:
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]
IfyouhaveNWextensioncoderunningintwoforeverbuttonsorloopblocksthateachneedtousedifferent
contexts,youshouldusenw:with-contextineachtomakesuretheyareoperatinginthecorrectcontext.
nw:turtles-in-radius
nw:turtles-in-radiusradius
Returnsthesetofturtleswithinthegivendistance(numberoflinksfollowed)ofthecallingturtleinthecurrent
context,includingthecallingturtle.
nw:turtles-in-radiusformwillfollowbothundirectedlinksanddirectedoutlinks.Youcanthinkofturtles-in-
radiusas“turtleswhoIcangettoinradiussteps”.
Ifyouwanttheprimitivetofollowonlyundirectedlinksoronlydirectedlinks,youcandoitbysettingthecontext
appropriately.Forexample:nw:set-context turtles undir-links (assumingundir-linksisanundirectedlink
breed)ornw:set-context turtles dir-links(assumingdir-linksisadirectedlinkbreed).
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
]
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
Asyoumayhavenoticed,theresultincludesthecallingturtle.ThismimicsthebehavioroftheregularNetLogoin-
radiusprimitive.
nw:turtles-in-reverse-radius
nw:turtles-in-reverse-radiusradius
Likenw:turtles-in-radius,butfollowsin-linksinsteadofout-links.Alsofollowundirectedlinks.Youcanthinkof
turtles-in-reverse-radiusas“turtleswhocangettomeinradiussteps”.
nw:distance-to
nw:distance-totarget-turtle
Findstheshortestpathtothetargetturtleandreportsthetotaldistanceforthispath,orfalseifnopathexistsinthe
currentcontext.Eachlinkcountsforadistanceofone.
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
Willoutput:
(turtle 0): 2
nw:weighted-distance-to
nw:weighted-distance-totarget-turtleweight-variable
Likenw:distance-to,buttakeslinkweightintoaccount.Theweightscannotbenegativenumbers.
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
Willoutput:
(turtle 0): 1.5
nw:path-to
nw:path-totarget-turtle
Findstheshortestpathtothetargetturtleandreportstheactualpathbetweenthesourceandthetargetturtle.The
pathisreportedasthelistoflinksthatconstitutethepath.
Ifnopathexistbetweenthesourceandthetargetturtles,falsewillbereportedinstead.
NotethattheNW-Extensionrememberspathsthatitscalculatedpreviouslyunlessthenetworkchanges.Thus,you
don’tneedtostorepathstoefficientlymoveacrossthenetwork;youcanjustkeepre-callingoneofthepath
primitives.Ifthenetworkchanges,however,thestoredanswersareforgotten.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
Willoutput:
(turtle 0): [(link 0 1) (link 1 2)]
nw:turtles-on-path-to
nw:turtles-on-path-totarget-turtle
Likenw:path-to,buttheturtlesonthepatharereported,insteadofthelinks,includingthesourceturtleandtarget
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
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
nw:weighted-path-to
nw:weighted-path-totarget-turtleweight-variable
Likenw:path-to,buttakeslinkweightintoaccount.
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
Willoutput:
(turtle 0): [(link 0 3) (link 3 4) (link 2 4)]
nw:turtles-on-weighted-path-to
nw:turtles-on-weighted-path-totarget-turtleweight-variable
Likenw:turtles-on-path-to,buttakeslinkweightintoaccount.
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
Willoutput:
(turtle 0): [(turtle 0) (turtle 3) (turtle 4) (turtle 2)]
nw:mean-path-length
nw:mean-path-length
Reportstheaverageshortest-pathlengthbetweenalldistinctpairsofnodesinthecurrentcontext.
Reportsfalseunlesspathsexistbetweenallpairs.
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
Willouput:
observer: 1.3333333333333333
observer: false
nw:mean-weighted-path-length
nw:mean-weighted-path-lengthweight-variable
Likenw:mean-path-length,buttakesintoaccountlinkweights.
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
Willouput:
observer: 2.6666666666666665
observer: false
nw:betweenness-centrality
nw:betweenness-centrality
Tocalculatethebetweennesscentralityofaturtle,youtakeeveryotherpossiblepairsofturtlesand,foreachpair,
youcalculatetheproportionofshortestpathsbetweenmembersofthepairthatpassesthroughthecurrentturtle.
Thebetweennesscentralityofaturtleisthesumofthese.
Asofnow,linkweightsarenottakenintoaccount.
nw:eigenvector-centrality
nw:eigenvector-centrality
TheEigenvectorcentralityofanodecanbethoughtofastheamountofinfluenceanodehasonanetwork.In
practice,turtlesthatareconnectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)geta
higherEigenvectorcentralityscore.
Inthisimplementation,theeigenvectorcentralityisnormalizedsuchthatthehighesteigenvectorcentralityanode
canhaveis1.ThisimplementationisdesignedtoagreewithGephi’simplementationouttoatleast3decimal
places.IfyoudiscoverthatitdisagreeswithGephionaparticularnetwork,pleasereportit.
Theprimitiverespectslinkdirection,eveninmixed-directednetworks.Thisistheoneplacewhereitshoulddisagree
withGephi;Gephirefusestotreatdirectedlinksasdirectedinmixed-networks.
Asofnow,linkweightsarenottakenintoaccount.
nw:page-rank
nw:page-rank
Thepagerankofanodecanbethoughtofastheproportionoftimethatanagentwalkingforeveratrandomonthe
networkwouldspendatthisnode.Theagenthasanequalchanceoftakinganyofanodesedges,andwilljump
aroundthenetworkcompletelyrandomly15%ofthetime.Inpractice,likewitheigenvectorcentrality,turtlesthatare
connectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)getahigherpagerank.
Pagerankisoneoftheseveralalgorithmsthatsearchenginesusetodeterminetheimportanceofawebsite.
Thesumofallpagerankvaluesshouldbeapproximatelyone.Unlikeeigenvectorcentrality,pagerankisdefinedfor
allnetworks,nomattertheconnectivity.Currently,ittreatsalllinksasundirectedlinks.
Asofnow,linkweightsarenottakenintoaccount.
nw:closeness-centrality
nw:closeness-centrality
Theclosenesscentralityofaturtleisdefinedastheinverseoftheaverageofit’sdistancestoallotherturtles.(Some
peopleusethesumofdistancesinsteadoftheaverage,buttheextensionusestheaverage.)
Notethatthisprimitivereportstheintra-componentclosenessofaturtle,thatis,ittakesintoaccountonlythe
distancestotheturtlesthatarepartofthesamecomponentasthecurrentturtle,sincedistancetoturtlesinother
componentsisundefined.Theclosenesscentralityofanisolatedturtleisdefinedtobezero.
nw:weighted-closeness-centrality
nw:weighted-closeness-centralitylink-weight-variable
Thisisidenticaltonw:closeness-centrality,exceptthatweightsprovidedbythegivenvariablearetreatedasthe
distancesoflinks.
nw:clustering-coefficient
nw:clustering-coefficient
Reportsthelocalclusteringcoefficientoftheturtle.Theclusteringcoefficientofanodemeasureshowconnectedits
neighborsare.Itisdefinedasthenumberoflinksbetweenthenode’sneighborsdividedbythetotalnumberof
possiblelinksbetweenitsneighbors.
nw:clustering-coefficienttakesthedirectednessoflinksintoaccount.Adirectedlinkcountsasasinglelink
whereasanundirectedlinkcountsastwolinks(onegoingone-way,onegoingtheother).
Theglobalclusteringcoefficientmeasureshowmuchnodestendtoclustertogetherinthenetworkingeneral.Itis
definedbasedonthetypesoftripletsinthenetwork.Atripletconsistsofacentralnodeandtwoofitsneighbors.Ifits
neighborsarealsoconnected,it’saclosedtriplet.Ifitsneighborsarenotconnected,it’sanopentriplet.Theglobal
clusteringcoefficientissimplythenumberofclosedtripletsinanetworkdividedbythetotalnumberoftriplets.Itcan
becalculatedfromthelocalclusteringcoefficientquiteeasilywiththefollowingcode
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
Notethattheabovewillonlyworkwiththedefaultcontext,andmayneedtotweakedifyou’vesettheturtlesorlinks
inthenetworktosomethingotherthanturtlesandlinks.
Theaveragelocalclusteringcoefficientisanotherpopularmethodformeasuringtheamountofclusteringinthe
networkasawhole.Itmaybecalculatedwith
mean [ nw:clustering-coefficient ] of turtles
nw:modularity
nw:modularity
Modularityisameasurementofcommunitystructureinthenetwork.Itisdefinedbasedonthenumberofin-
communitylinksversusthenumberofbetween-communitylinks.Thisprimitivetakesasinputalistofagentsets,
whereeachoftheagentsetsisonethecommunitiesthatyou’reseparatingthenetworkinto.
Thismeasurementworksonundirected,directed,andmixed-directednessnetworks.Inthecaseofmixed-
directedness,undirectedlinksaretreatedessentiallythesameastwoopposingdirectedlinks.Itdoesnottake
weightintoaccount.
Example:
nw:modularity (list (turtles with [ color = blue ]) (turtles with [ color = red ]))
nw:bicomponent-clusters
nw:bicomponent-clusters
Reportsthelistofbicomponentclustersinthecurrentnetworkcontext.Abicomponent(alsoknownasamaximal
biconnectedsubgraph)isapartofanetworkthatcannotbedisconnectedbyremovingonlyonenode(i.e.youneed
toremoveatleasttwotodisconnectit).Theresultisreportedasalistofagentsets,inrandomorder.Notethatone
turtlecanbeamemberofmorethanonebicomponentatonce.
nw:weak-component-clusters
nw:weak-component-clusters
Reportsthelistof“weakly”connectedcomponentsinthecurrentnetworkcontext.Aweaklyconnectedcomponentis
simplyagroupofnodeswherethereisapathfromeachnodetoeveryothernode.A“strongly”connected
componentwouldbeonewherethereisadirectedpathfromeachnodetoeveryother.Theextensiondoesnot
supporttheidentificationofstronglyconnectedcomponentsatthemoment.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecannotbeamemberofmorethan
oneweaklyconnectedcomponentatonce.
nw:louvain-communities
nw:louvain-communities
Detectscommunitystructurepresentinthenetwork.ItdoesthisbymaximizingmodularityusingtheLouvainmethod.
Thecommunitiesarereportedasalistofturtle-sets.
Oftenyou’llwanttotellturtlesaboutthecommunitythattheyarein.Youcandothislikeso:
turtles-own [ community ]
...
foreach nw:louvain-communities [ [comm] ->
ask comm [ set community comm ]
]
Youcangiveeachcommunityitsowncolorwithsomethinglikethis:
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
Acliqueisasubsetofanetworkinwhicheverynodehasadirectlinktoeveryothernode.Amaximalcliqueisa
cliquethatisnot,itself,containedinabiggerclique.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecanbeamemberofmorethanone
maximalcliqueatonce.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:biggest-maximal-cliques
nw:biggest-maximal-cliques
Thebiggestmaximalcliquesare,asthenameimplies,thebiggestcliquesinthecurrentcontext.Often,morethan
onecliquearetiedforthetitleofbiggestclique,sotheresultisreportedasalistofagentsets,inrandomorder.Ifyou
wantonlyoneclique,useone-of nw:biggest-maximal-cliques.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:generate-preferential-attachment
nw:generate-preferential-attachmentturtle-breedlink-breednum-nodesmin-degreeoptional-command-
block
GeneratesanewnetworkusingaversionoftheBarabási–Albertalgorithm.Thisnetworkwillhavethepropertyof
being“scalefree”:thedistributionofdegrees(i.e.thenumberoflinksforeachturtle)shouldfollowapowerlaw.
Generationworksasfollowsturtlesareadded,onebyone,eachformingmin-degreelinkstoapreviouslyadded
turtles,untilnum-nodesisreached.Themorelinksaturtlealreadyhas,thegreatertheprobabilitythatnewturtles
formlinkswithitwhentheyareadded.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-preferential-attachment turtles links 100 1 [ set color red ]
nw:generate-random
nw:generate-randomturtle-breedlink-breednum-nodesconnection-probabilityoptional-command-block
Generatesanewrandomnetworkofnum-nodesturtlesinwhicheachonehasaconnection-probability(between0
and1)ofbeingconnectedtoeachotherturtles.ThealgorithmusestheG(n,p)variantoftheErdős–Rényimodel.
ThealgorithmisO(n²)fordirectednetworksandO(n²/2)forundirectednetworks,sogeneratingmorethanacouple
thousandnodeswilllikelytakeaverylongtime.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
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
GeneratesanewWatts-Strogatzsmall-worldnetwork.
Thealgorithmbeginsbycreatingaringofnodes,whereeachnodeisconnectedtoneighborhood-sizenodeson
eitherside.Then,eachlinkisrewiredwithprobabilityrewire-prob.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Furthermore,
theturtlesaregeneratedintheordertheyappearasincreate-ordered-turtles.So,inordertolaytheringoutasa
ring,youcandosomethinglike:
nw:generate-watts-strogatz turtles links 50 2 0.1 [ fd 10 ]
nw:generate-small-world
nw:generate-small-worldturtle-breedlink-breedrow-countcolumn-countclustering-exponentis-toroidal
optional-command-block
Generatesanewsmall-worldnetworkusingtheKleinbergModel.Notethatnw:generate-watts-strogatzgeneratesa
moretraditionalsmall-worldnetwork.
Thealgorithmproceedsbygeneratingalatticeofthegivennumberofrowsandcolumns(thelatticewillwraparound
itselfifis-toroidalistrue).The“smallworldeffect”iscreatedbyaddingadditionallinksbetweenthenodesinthe
lattice.Thehighertheclustering-exponent,themorethealgorithmwillfavoralreadyclose-bynodeswhenadding
newlinks.Aclusteringexponentof2.0istypicallyused.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-small-world turtles links 10 10 2.0 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togenerateakleinberglattice
accrosstheentireworld,andlayitoutaccordingly,trythefollowing:
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-2dturtle-breedlink-breedrow-countcolumn-countis-toroidaloptional-command-block
Generatesanew2Dlatticenetwork(basically,agrid)ofrow-countrowsandcolumn-countcolumns.Thegridwill
wraparounditselfifis-toroidalistrue.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-lattice-2d turtles links 10 10 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togeneratealatticeaccross
theentireworld,andlayitoutaccordingly,trythefollowing:
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-ringturtle-breedlink-breednum-nodesoptional-command-block
Generatesaringnetworkofnum-nodesturtles,inwhicheachturtleisconnectedtoexactlytwootherturtles.
Thenumberofnodesmustbeatleastthree.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-ring turtles links 100 [ set color red ]
nw:generate-star
nw:generate-starturtle-breedlink-breednum-nodesoptional-command-block
Generatesastarnetworkinwhichthereisonecentralturtleandeveryotherturtleisconnectedonlytothiscentral
node.Thenumberofturtlescanbeaslowasone,butitwon’tlookmuchlikeastar.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-star turtles links 100 [ set color red ]
nw:generate-wheel
nw:generate-wheelturtle-breedlink-breednum-nodesoptional-command-block
Variants:
nw:generate-wheel-inward
nw:generate-wheel-outward
Generatesawheelnetwork,whichisbasicallyaringnetworkwithanadditional“central”turtlethatisconnectedto
everyotherturtle.
Thenumberofnodesmustbeatleastfour.
Thenw:generate-wheelonlyworkswithundirectedlinkbreeds.Thenw:generate-wheel-inwardandnw:generate-
wheel-outwardversionsonlyworkwithdirectedlink-breed.Theinwardandoutwardpartoftheprimitivenamesrefer
tothedirectionthatthe“spokes”ofthewheelpointtorelativetothecentralturtle.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-wheel turtles links 100 [ set color red ]
nw:save-matrix
nw:save-matrixfile-name
Savesthecurrentnetwork,asdefinedbynw:set-context,tofile-name,asatextfile,intheformofasimple
connectionmatrix.
Hereis,forexample,aundirectedringnetworkwithfournodes:
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
Andhereisthedirectedversion:
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
Atthemoment,nw:save-matrixdoesnotsupportlinkweights.Everylinkisrepresentedasa“1.00”intheconnection
matrix.Thiswillchangeinafutureversionoftheextension.
nw:load-matrix
nw:load-matrixfile-nameoptional-command-block
Generatesanewnetworkaccordingtotheconnectionmatrixsavedinfile-name,usingturtle-breedandlink-breedto
createthenewturtlesandlinks.
Atthemoment,nw:load-matrixdoesnotsupportlinkweights.
Pleasebeawarethatthebreedsthatuseusetoloadthematrixmaybedifferentfromthosethatyouusedwhenyou
savedit.
Forexample:
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
…willgiveyoubackundirectedlinks,evenifyousaveddirectedlinksintothematrix.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-matrix "matrix.txt" turtles links [ set color red ]
nw:save-graphml
nw:save-graphmlfile-name
YoucansavethecurrentgraphtoGraphML.ThefollowingNetLogocode:
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
WillproducethefollowingGraphMLfile:
<?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>
Afewthingstonotice:
Thebreedisstoredasdatafield,bothfornodesandedges.
ThedataincludesbothNetLogo’sinternalvariablesandthevariablesthatweredefinedaseitherbreeds-own,
turtles-own,linkbreeds-ownorlinks-own.
Eachkeygetsanattr.typebasedontheactualtypesofthevaluescontainedintheagentvariables.Thethree
possibletypesare"string","double"and"boolean".Todeterminetheattributetypeofaparticularagentvariable,
theextensionwilllookatthefirstagentinthegraph.Toseewhichagentisfirst,youcanlookattheresultof
nw:get-context.Notethatvariablescontainingothertypesofvalues,suchasturtles,patches,lists,etc.,willbe
storedasstrings.
Thisexampleonlyhasadirectedlink,andyouwillnoticethe<graph edgedefault="directed">element.Ifwehad
onlyundirectedlinks,wewouldhave<graph edgedefault="undirected">.Whatifwetrytomixbothkindsoflink?
Atthemoment,theextensionwillsavesucha“mixed”graphasifitwereanundirectedgraph(seethisissuefor
moredetails).Theorderofthesourceandtargetwillberespected,however,soifyouknowwhichbreeds
representdirectedlinks,youcanfigureitoutaposteriori.
nw:load-graphml
nw:load-graphmlfile-nameoptional-command-block
LoadingaGraphMLfileintoNetLogowiththenetworkextensionshouldbeassimpleascallingnw:load-graphml
"example.graphml",butthereisabitofpreparationinvolved.
Thekeyideaisthatnw:load-graphmlwilltrytoassigntheattributevaluesdefinedintheGraphMLfiletoNetLogo
agentvariablesofthesamenames(thisisnotcasesensitive).Thefirstoneittriestosetisbreedifitisthere,sothe
turtleorlinkwillgettherightbreedand,hence,therightbreedvariables.
Onespecialcaseisthewhonumber,whichisignoredbytheimporterifitispresentasaGraphMLattribute:NetLogo
doesnotallowyoutomodifythisnumberonceaturtleiscreatedand,besides,therecouldalreadybeanexisting
turtlewiththatnumber.
ThesimplestcasetohandleiswhentheoriginalGraphMLfilehasbeensavedfromNetLogobyusingnw:save-
graphml.Inthiscase,allyoushouldhavetodoistomakesurethatyouhavethesamebreedandvariables
definitionaswhenyousavedthefileandyoushouldgetbackyouroriginalgraph.Forexample,ifyouwanttoload
thefilefromthenw:save-graphmlexampleabove,youshouldhavethefollowingdefinitions:
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 ]
LoadingagraphthatwassavedfromadifferentprogramthanNetLogoisquitepossibleaswell,butitmaytakeabit
oftinkeringtogetalltheattribute-variablematchupright.Ifyouencountermajorproblems,pleasedonothesitateto
openanissue.
Theextensionwilltrytoassignthetypedefinedbyattr.typetoeachvariablethatitloads.Ifit’sunabletoconvertit
tothattype,itwillloaditasastring.Ifattr.typeisnotdefined,orissettoanunknownvalue,theextensionwillfirst
trytoloadthevalueasadouble,thentryitasaboolean,andfinallyfallbackonastring.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-graphml "example.graphml" [ set color red ]
Notethatthiscommandblockcanbeusedtobuildalistoranagentsetcontainingthenewlycreatednodes:
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:loadfile-namedefault-turtle-breeddefault-link-breedoptional-command-block
Filetypespecificvariants:
nw:load
nw:load-dl
nw:load-gdf
nw:load-gexf
nw:load-gml
nw:load-vna
ImportthegivenfileintoNetLogo.Likenw:load-graphml,theimporterwilldoitsbesttomatchnodeandedge
attributesinthefilewithturtleandlinkvariablesinNetLogo.Ifbreedisspecifiedfornodesandedgesinthefileand
existsinNetLogo,itwillbeused.Otherwise,thedefaultturtleandlinkbreedsareused.
Limitations:
Multigraphsarenotsupportedinimporting.Evenifthefileformatsupportsit(andmanydon’t),onlythefirstlink
willbeusedonimport.ThisisduetoalimitationintheparsinglibrariesNWuses.nw:load-graphmldoessupport
multigraphswiththenormalNetLogolimitationthattwoturtlescansharemorethanonelinkonlyifallthelinksare
ofdifferentbreeds.
nw:loaddeterminesthefile-typeofgivenfilebasedontheextensionandcallsthecorrespondingload-*primitiveon
it.NotethatGraphMLmustbeimportedwithnw:load-graphml.
nw:save
nw:savefile-name
Filetypespecificvariants:
nw:save-dl
nw:save-gdf
nw:save-gexf
nw:save-gml
nw:save-vna
Exportthenetworkcontextinthegivenformattothegivenfile.Turtleandlinkattributeswillbeexportedtoformats
thatsupportnodeandedgeproperties.
Limitations:
xandy(notxcorandycor)canonlybenumbers.xandyarecommonlyusedinformatspertainingtopositionand
behindthescenesNWusesGephi’slibrariesforexporting.Furthermore,xandywillbeaddedeveniftheydidn’t
existinthemodel.Again,thisisbecauseNWusesGephi’slibrarieswhichassumethatnodeshavepositions
storedinxandy.IfyouwishtoexporttoGephispecifically,werecommendcreatingxandyturtlesvariablesand
settingthemtoxcorandycorbeforeexport.
ColorwillbeexportedinastandardRGBformat.Thisshouldhopefullyincreasecompatibilitywithotherprograms.
Turtleandlinkvariablesthatcontainvaluesofdifferenttypeswillbestoredasstrings.Unfortunately,mostnetwork
formatsrequirethatnodeandattributeshaveasingletype.
Manyprogramsuselabeltostoretheidofnodes.Thus,ifyou’rehavingtroubleimportingdataexportedfrom
NetLogointoanotherprogram,youmighttrysettingturtles’labelstotheirwhonumber.
Multigraphsarenotsupported.Thus,twoturtlescanshareatmostonelink.nw:save-graphmldoessupport
multigraphs,sousethatifturtlescanhavemorethanonetypeoflinkconnectingthem.
nw:savedeterminesthefile-typeofthegivenfilebasedontheextensionandcallsthecorrespondingsave-*primitive
onit.NotethatGraphMLmustbeexportedwithnw:save-graphml.
NetLogoPaletteExtension
UsingthePaletteExtension
TheNetLogopaletteextensionallowstomapvaluestocolors.ThecolorsgobeyondNetLogocolors,including
ColorBrewercolorschemesorarbitraryRGBcolors.Additionally,itprovidesaprimitivetomaptocolorgradientsanda
primitivetolaunchaColorBrewerdialogforeasyschemeselection.
GettingStarted
TogetstartedwithpalettesaddtothetopofyourCodetab:
extensions [palette]
youcanthencallanyoftheprimitivesbyaddingpalette:beforetheprimitive:
palette:scale-gradient
palette:scale-scheme
palette:scheme-color
palette:scheme-dialog
ThepaletteextensionprimitivesreturnalistcontainingRGBcolors[[r g b][r g b]...[r g b]] ,exceptfor
palette:scheme-dialogwhichopensadialog.
WhatcolorsshouldIuse?
ColorBrewerhasmanycolorswheretostart.ColorBrewerhasthreeschemesSequential,DivergentandQualitative.The
useofColorBrewerformapsisdiscussedatlengthinthispaper(Harrower,Brewer2003).Choosingtherightcolorsisa
designproblem,thus,therearemanyacceptablesolution.However,theseguidelinesmightbeusefulforchoosingcolors
inAgentBasedModels:
Sequentialcolorsarebestforcontinuousnaturalphenomenamodelssuchasasheatdiffusioninphysicsorfirein
earthsciences.
Divergentcolorsareusefulforhighlightingamiddlevalueinamodel.Itcanbealsoappliedtotheheatdiffusionmodel
ifthegoalistohighlightthemiddletemperature.
Qualitativecolorsarebestforchoosingcolorsinmodelswherecolordenotescategoryandnotvalue.
Foragentsthatcoverlargeareasavoidstrongcolorsandtrytousepastelcolors.However,foralownumberofsmall
isolatedagentstrytousestrongcolorssuchassuchaaccent.
Themaingoalistoavoidhavingalargeareacoveredwithagentswithabrightcolorandorhavingsmallareashaving
amutedpastelcolor.
Ifyouarecoloringbothturtlesandpatches,makesuretheyhavedifferentrangesofhue,saturationandvalue.E.g.
Usedifferenthuesofpastelforpatchesandaccentforturtles
ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?
Theanswerdependsonthetaskthatyourwillbeaskingfromyouruser.
Forexample,gradientsaremoreaestheticthusaremorememorablethandiscretecolors.Consequently,agradientcan
beabetterchoiceforpresentationswherethemaingoaloftheimageistobeattractiveandmemorable.However,
binningvaluesinadiscretesetofcolorssimplifiestaskssuchasestimationandcountingbyremovingunnecessary
detailtodisplaythebigpicture.Thus,discretecolorscanbeabetterchoiceforapaperwheretheuserwillhavethetime
andinteresttostudythevisualization.
InordertoseethedifferenceyoucanturnonandoffthegradientintheHeatDiffusionmodel.Youcanobservethat
turninggradientonmakesthemodelmoreaesthetic,butitbecomeshardertoestimatethevalueofapatchatagiven
position.
ExampleModels
ThereisanexampleofusingthepaletteprimitivesintheCodeExamplessectionofthemodelslibrary:
PaletteExample
AndoneSampleModelthatusestheextension:
HeatDiffusion-AlternativeGradient
FurtherReading
BesuretochecktheColorBrewerwebpage
TogetadeeperunderstandingofhowtousethecolorschemesreadtheColorBrewerpaper(Harrower,Brewer2003)
Primitives
palette:scale-gradientpalette:scale-schemepalette:scheme-colorspalette:scale-gradient
palette:scale-gradient
palette:scale-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofa
listcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,the
colorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
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-schemescheme-typescheme-colornumber-of-classesrange1range2
ReportsanRGBcolorproportionaltonumberusingthecolorbrewerschemes.Ittakessixargumentsthefirstthree
argumentsdefinetheColorBrewerlegend.Firtheusershouldselectascheme-typewhichcanbe“Sequential”,
“Divergent,Qualitative”.Thenitshouldselectavarietyofscheme-colorswhichdependingonthescheme-colorcanhave
namessuchas“Reds”,“Divergent”,“Set1”.Finallytheusershouldselectthenumberofclasseswithaminimumof3and
amaximumbetween9and11.Formoreinformationgotohttp://www.colorbrewer.orgorconsultthescheme-dialog
primitive.
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtoschemecolors.While,ifrange2islessthanrange1,the
colorschemeselectionisinverted.
Ifnumberislessthanrange1,thenthefirstcoloroftheresultingColorBrewerlegendischosen.
Ifnumberisgraterthanrange2,thenthelastcoloroftheresultingColorBrewerlegendischosen.
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
reportalistofRGBcolorswiththesizespecifiedintheanumberofclasses
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-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofa
listcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,the
colorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
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
ColorBrewerwww.colorbrewer.org
HARROWER,M.andC.BREWER(2003).ColorBrewer:Anonlinetoolforselectingcolorschemesformaps.The
CartographicJournal40(1):27-37.)
HEALEY,CG(2006)PerceptioninVisualization,(comprehensivereviewupdatedregularly).
HEALEY,CG,BOOTHKS,andENNS,JT(1995).VisualizingReal-TimeMultivariateDataUsingPreattentive
ProcessingACMTransactionsonModelingandComputerSimulation5,3,190-221.
TUFTE,E(1983)TheVisualDisplayofQuantitativeInformation,GraphicsPress.
WARE,C(2004)InformationVisualization,2ndEd.,MorganKaufmann.Feedback
NetLogoProfilerExtension
UsingtheProfilerExtension
Ifyou’dlikeyourmodeltorunfaster,theprofilerextensionmaybeusefultoyou.It
includesprimitivesthatmeasurehowmanytimestheproceduresinyourmodelarecalled
duringarunandhowlongeachcalltakes.Youcanusethisinformationtowheretofocus
yourspeedupefforts.
Caution:
Theprofilerextensionisexperimental.Itisnotyetwelltestedoruserfriendly.
Nonetheless,wethinksomeuserswillfindituseful.
Howtouse
Theprofilerextensioncomespreinstalled.Tousetheextensioninyourmodel,addaline
tothetopofyourCodetab:
extensions [profiler]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddprofilertothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
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
ThankstoRogerPeppeforhiscontributionstothecode.
Primitives
profiler:callsprofiler:exclusive-timeprofiler:inclusive-timeprofiler:start
profiler:stopprofiler:resetprofiler:report
profiler:calls
profiler:callsprocedure-name
Reportsthenumberoftimesthatprocedure-namewascalled.Ifprocedure-nameisnot
defined,thenreports0.
profiler:exclusive-time
profiler:exclusive-timeprocedure-name
Reportstheexclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.
Exclusivetimeisthetimefromwhentheprocedurewasentered,untilitfinishes,butdoes
notincludeanytimespentinotheruser-definedprocedureswhichitcalls.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:inclusive-time
profiler:inclusive-timeprocedure-name
Reportstheinclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.Inclusive
timeisthetimefromwhentheprocedurewasentered,untilitfinishes.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:start
profiler:start
Instructstheprofilertobeginrecordinguser-definedprocedurecalls.
profiler:stop
profiler:stop
Instructstheprofilertostoprecordinguser-definedprocedurecalls.
profiler:reset
profiler:reset
Instructstheprofilertoeraseallcollecteddata.
profiler:report
profiler:report
Reportsastringcontainingabreakdownofalluser-definedprocedurecalls.TheCalls
columncontainsthenumberoftimesauser-definedprocedurewascalled.TheIncl
T(ms)columnisthetotaltime,inmilliseconds,ittookforthecalltocomplete,includingthe
timespentinotheruser-definedprocedures.TheExcl T(ms)columnisthetotaltime,in
milliseconds,spentwithinthatuser-definedprocedure,notcountingotheruser-define
proceduresitcalled.TheExcl/callscolumnisanestimateofthetime,inmilliseconds,
spentinthatuser-definedprocedureforeachcall.
Hereisexampleoutput:
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
NetLogoRExtension
TheR-ExtensionofNetLogoprovidesprimitivestousethestatisticalsoftwareR(GnuS)(seetheRProjectwebsite)withina
NetLogomodel.ThereareprimitivestocreateR-VariableswithvaluesfromNetLogovariablesoragentsandothersto
evaluatecommandsinRwithandwithoutreturnvalues.
Using
Tousetheextensioninyourmodel,addalinetothetopofyourprocedurestab:
extensions [ r ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddrtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide.
ForexamplesoftheusageoftheR-Extension,modelscanbedownloadedfromtheprojectrepository.Thesemodelsare
installedwithNetLogointhe“models”directoryoftheRextension.Pleasenotethat(asofNetLogo6.0)thesemodelsare
notincludedintheNetLogomodelslibrary.
SomeTips
Plotting
IfyouwanttousetheplotfunctionofR,youcouldactivatetheJavaGDplotdeviceviar:setPlotDevice,seethe“plot-
example1.nlogo”model.Thisisthepreferedmethod!
ButyoucanalsousethestandardRdevice,butthen,youhavetogiveRsomecputime,e.g.byrunanevalulationof
sys.sleep(0.01)withaforeverbutton.Seethe“plot-example2.nlogo”.(ManythankstoThomasPetzold!).Thecreationof
plotsintofilesisalsopossible.Seethe“plot-into-file-example.nlogo”intheexamplesfolder.
LoadandSavedatafrom/intofile(s)
It’spossibletoloadandsavedatafromfiledirectlyinR.Thiscodesnippetillustrates:
r:eval "dataname <- read.table('<path to file>')" ; read file
r:eval "write.table(dataname, file='<filename>')" ; write file
Data.framewithvectorincells
Normally,adata.framecellcontainsonlyasinglevalue.Eachcolumnisrepresentedasavectorandifyouwouldputa
vectorofvectorstoadata.frame,itwouldbesplittedintoseveralcolumns.WiththeR-Extensionitispossibletoputavector
intoadata.framecell,whenyouassignaNetLogoListtoacolumnwhichcontainsnestedNetLogoListsforeachrow.Ifyou
want,forexample,tousewrite.tableonthisdata.frame,youhavetomarkthiscolumnasclass="AsIs".Youcandothisby
usingtheI(x)-function.
Example:Ifthecolumnofinteresthasthename“col1”ofthedata.frame“df1”youcouldexecuter:eval "df1$col1 <-
I(df1$col1)".Callhelp(I)fromwithinanRterminalforfurtherdetails.
LoadanR-Script
Furthermore,youcandefinefunctionsinanR-Script,loadit,andusethefunctions.LoadR-filesviar:eval "source('<path
to r-file>')".
LoadaPackage
It’salsopossibletoloadRpackagesviar:eval "library(<name of package>)".
Whenyoucompileyourcodecontainingextensions [r]youwillcreateanewRworkspace.Untilyoureloadtheextension,
openanewmodelorsubmittheprimitive[r:clear](#rclear),allRvariablesassignedinthissessionwillbeavailablelike
youwoulduseRfromthecommandlineorintheRConsole.
InteractiveShell
YoucanopenanInteractiveRShellviar:interactiveShell.ThisshellisaporttotheunderlayingRinstance.Thisshell
worksontheglobalenvironment(seeEnvironmentsintheRExtensionbelow)whiletheextensionitselfworkonacustom
localenvironment.Butthereisoneautomaticvariable“nl.env”intheglobalenvironment,whichisareferencetothelocal
environmentoftheextension.Don’tdeletethisvariable!
Youcanaccessavariablecreatedbytheextensionviaget("<variable name>",nl.env),forexamplemyvar <-
get("myvar",nl.env).IfyouwanttoplotfromtheInteractiveShellyoushouldusetheincludedJavaGDplotdevice(see
r:setPlotDevice).YoucansaveandloadthehistoryofenteredRcommandsviaaright-mousebuttoncontextmenu.
Pleasereadthenotesatthetopoftheoutputtextareaafteropeningtheshell!OnLinuxOSitcanhappenthatyouseean
errormessagefromX11.Pleasecheck,ifeverythingworkedcorrecly.Ifso,youcanignorethesemessages.Ifnot,please
writeareporttobugs@ccl.northwestern.eduoropenanissue.
EnvironmentsIntheRExtension
WhenyouloadamodeltheR-ExtensioncreatesanewRenvironment.WhenyoucreateanRvariableusingtheR-
Extension,thisvariableiscreatedinthelocalRenvironment.Furthermore,allcallsfromtheR-Extensionworkonthislocal
environment.ThisnewenvironmentconceptenablesyoutousetheextensioninBehaviorSpaceExperiments.Therefore,
youdon’thavetocareabouttheenvironmentwhileyou’renotusingtheInteractiveShellorothertools,whichworkonthe
globalenvironment.Youcanexplicitlyassignavariabletotheglobalenvironmentbyusingthe<-operatororbyexecuting
assign(<name>,<value>,envir=.GlobalEnv).IfyouworkwiththeInteractiveShell,seethenotesatthetopoftheoutputtext
areaafteropeningtheshell.
Typehelp(environment)inanRshelltolearnmoreaboutenvironments.
Youcan/shouldclear(i.e.removeallvariableandfreememory)thelocalenvironmentviar:clearLocal.Ifyouwanttoclear
alsotheglobalenvironment(thewholeworkspace),callr:clear.
Memory
WiththeR-ExtensionyoucanloadRintotheprocessofNetLogo.BecauseofthearchitectureofR,bothsoftwareshareone
systemprocessandthereforethememorygiventoNetLogo.
InsomecircumstancesitcanhappenthatyoureceiveanoutofmemoryerrorduetoJava’sheapspace.Youcanincrease
theheapspacebeforestartingNetLogobyadaptingthe-XmxJVM-parameter(seealsotheNetLogomanualsectionon
Windowsmemory).Buton32-bitsystems,thisisverylimited.Therefore,itisagoodideatousea64-bitsystemifyou
want/needtousehighamountofRAM.YoucanseethememoryusageofRbystartingtheinteractiveshell
(r:interactiveShell)andtypethere:memory.size(max=F)andmemory.size(max=T).Furthermore,youcancheckthememory
limitbytyping:memory.limit().
Seealso:
Rmanualpageformemory.profile
Rmanualpageforobject.size
Rmanualpageformemory.size
Ifyoucallthegarbagecollectorintheinteractiveshellbytypinggc(),youwillgetsomeinformationaboutthecurrent
memoryusage(seealsohttp://stat.ethz.ch/R-manual/R-patched/library/base/html/gc.html).
Ifyoutypegc(nl.env)youwillseethepercentageofmemoryusedforconscellsandvectors.
Don’tforgettocallther:gcprimitiveafterremovinganRvariableanddon’tforgettoremoveRvariableyoudon’tneed
anymore!Seehowthememoryusagechangesafterremovingvariableandcallingr:gc.
Ifyouusetoomuchmemory,itcanhappen,thatNetLogowillcloseabruptly.Insuchacase,checkifthereisawayto
reducethememoryused.Ifnot,trytoswitchovertotheRserve-extension.WiththeRserve-Extensionbothsoftware,
NetLogoandR,runindependently.Thereis,ofcause,alsoalimitoftransferabledataamountwithonerequest,butitisless
restrictive.
Onelastnotetothistopic:KeepinmindthatRisavector-orientedlanguage.Preventmasscallswithsinglevalues
wheneverpossibleandreplacethembyvectoroperations.Thisismuchfasterandmorestable.
Headless
SinceR-Extensionversion1.1itispossibleusetheextensionwhenNetLogoisrunninginheadlessmode.Thisisfor
examplethecase,whenyourunBehaviorSpaceexperimentsfromthecommandline(seehere).Thedifferenceis,thatthe
interactiveShellisnotinitialized/instanciated.YoucanusetheextensionasyouknowitfromGUImode,butitisnot
possibletoopentheinteractiveShell(r:interactiveShell)andtosettheplotdevice(r:setPlotDevice).Butoneadditional
thingshastobedone:Youhavetocallr:stopfinallywhenrunningNetLogoheadlesstostoptheRengine.Otherwise
NetLogowillnotbeclosedandyouwillnotgetbacktothecommandlineprompt.WhensettingupaBehaviorSpace
experiment,thereistheoptiontosetfinalcommands.Thisisagoodplacetoaddther:stopcommand(seeimage).
Installing
TheRExtensionisbundledwithNetLogo6.Touseit,youwillneedacompatibleRinstallationandyoumayneedto
configuretheextension.
InstallingR
StandardR3installationsshouldwork(sometimeswithoutconfiguration).AsofNetLogo6.0.2,thefollowingoperating
system/Rversionsweretested:
MacOSX,R3.3.3
Windows10,R3.3.2
Ubuntu14.04(64-bit),R3.0.2
OnceRisinstalled,youwillneedtoinstalltherJavapackage.CertainfeaturesoftheRextensionrelyontheJavaGD
package.
Toinstall,starttheRGuifromyourprogramlist,clickontheitem“Packages”inthemenubarandthenon“Install
Package(s)”.Selectyourfavoriteserverandfind“rJava”,aswellas“JavaGD”and/or“CommonJavaJars”(bothoptional)in
thelistofpackages.
Ifyoupreferusingtheconsole,youcaninstallthesamepackagesbyrunningthefollowingcommandsintheconsole(and
followingthepromptstheygenerate,asappropriate).
install.packages("rJava")
install.packages("JavaGD") # Optional
install.packages("CommonJavaJars") # Optional
ConfiguringtheRextension
IfyouareusingLinuxorMacOSandoneoftheaboveRversions,youmaynotneedtoperformanyfurtherconfiguration.
AneasywaytodeterminewhetheryouneedtoconfiguretheextensionittoopenanewNetLogomodel,addextensions [
r ]tothecodetabandpress“Check.”Ifyouseeanerror,youneedtoconfiguretheRextension.TheRextensioncanbe
configuredbyeditingthe“user.properties”fileinatexteditor(“user.properties”islocatedintherextensiondirectoryaspart
oftheNetLogoinstallation).Thefollowingkeysareusedtoconfiguretheextension:
r.home:Controlswhichinstallationofrisused.
jri.home.paths:ControlsthepathtothejrisubdirectoryoftherJavalibrary.
NotethatyouwillhavetoexitNetLogoandrestarttoseeconfigurationchangestakeeffect,astheconfigurationfileisonly
loadedonceperNetLogoinstance.Seebelowonhowtodeterminetheappropriatevaluestoforr.homeand
jri.home.paths.
Determiningr.homeandjri.home.paths
r.homeisthepathtothe“R”installationdirectorywhichcontainsthe“bin”directory.Ifyou’rehavingtroublefindingthis,you
canrunR.home(component = "home")inR,orR RHOMEonthecommandline(ifRisonyourpath).
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.pathsisalistofdirectoriestocheckforjri.It’sinthejridirectoryundertherJavalibraryinstallation.Youcanfind
thejridirectoryintherJavapackagebyrunningthefollowinginR:
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
Takethepathandedittheuser.propertiesfile,uncommentingandeditingonesetofr.homeandjri.home.pathstomatch
thevaluesobtainedinR.Whenyou’redone,theuser.propertiesfileshouldhavethefollowinglines(giventheabove
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
Saveuser.propertiesandloadamodelusingtheRextension.Youshouldseeitstartandrunproperly.
Windows-SpecificInstallationSteps
WindowsrequirestheadditionalconfigurationstepofconfiguringthePATHenvironmentvariable.Additionally,editingthe
user.propertiesfileonWindowsisslightlymoredifficultthanonotherplatforms.
ConfiguringthePATH
Tobegin,determinetheappropriatedirectoryfromyourRinstallationtoaddtoyourPATH.Todothis,determinewhere
yourRinstallationislocated(herewe’llusethelocationC:\ProgramFiles\R\R-),thenfollowthesesteps.
1. OpentheSystemPropertiesdialog.Youcantype“EnvironmentVariable”intoCortanaornavigatetherethrough“Control
Panel”>System>“Advancedsystemsettings”.
2. Clickthe“Environmentvariables…”buttoninthelowerrightofthedialog.
3. Clickthe“Path”variableinthelowerpanel,thenclickthelower“Edit…”button.
4. Windows10allowsyoutochoose“New”andenteraseparatepath.Ifyou’reusingWindows7,appendthevalue,usinga
semicolontoseparateitfromtheentrybefore.
Ifyou’reusing32-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\i386\
Ifyou’reusing64-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\x64\
1. ChooseOK,andOKagain
2. LogoutofyouruserandbackinorrestartWindowstoletthesettingtakeaffect.
NotethatyouwillneedtoupdatethissettingifyouwishtoupgradetheversionofRusedbyNetLogo.
Notesonediting“user.properties”onWindows
“user.properties”isanewline-delimitedfile.Thismeansifitisopenedin“Notepad”itwilllooklikeallthetextisonasingle
line.Forthisreason,itisrecommendedtoopenfirstin“WordPad”andresavebeforeeditinginNotepad.Alternatively,ifyou
haveafull-featuredtexteditor(likeNotepad++,Vim,orEmacs)installed,youcanusethattoeditthefile.
Toreiterateawarninggiveninthe“user.properties”file,thedirectoryseparatorforWindowsmustbeenteredin
user.propertiesasdouble-backslash(“\”)orsingle-forward-slash(“/”).
Primitives
r:clearr:clearLocalr:evalr:__evaldirectr:gcr:getr:interactiveShellr:putr:putagentr:putagentdfr:putdataframe
r:putlistr:putnamedlistr:setPlotDevicer:stop
r:clear
r:clear
ClearstheR-Workspace.AllvariablesinRwillbedeleted.ItevaluatestheRcommandrm(list=ls())and
rm(list=ls(nl.env)).Thisdeletesvariablescreatedinglobalaswellaslocalenvironment(seeREnvironmentsfordetails
aboutenvironments).It’salwaysagoodideatoaddthiscommandtoyoursetupprocedureunderyour“clear-all”call.
;; clear the R workspace
r:clear
r:clearLocal
r:clearLocal
ItclearsthelocalRenvironment,whichisusedbytheextension.Allvariableswhichhavebeencreatedinthelocal
environmentwillbedeleted.ItevaluatestheRcommandrm(list=ls(nl.env)).SeeREnvironmentsfordetailsabout
environments.Seer:clearfordeletingallvariables,i.e.theglobalsaswell.
;; delete the local variables
r:clearLocal
r:eval
r:evalR-command
ItevaluatesthesubmittedRcommand.TheRcommandshouldn’treturnavalue.
;; 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:__evaldirectR-command
EvaluatesthesubmittedRcommandintheglobalenvironment(notinthelocalenvironmentliker:evaldoes)andwithouta
check(notusingtry-functioninternally).ThiscanbenecessaryforsomeRpackages,likegglopt2.Pleasenote,thatyoucan
producenameclasheswhencreatingnewvariablesusingthisprimitive.Thevariablewillbecreatedintotheglobal
environmentandwillnotoverwritevariablewiththesamenamethathavebeencreatedintothelocalenvironment.Ifyou
requestavariablewithr:getitwillsearchinthelocalenvironmentfirst.Therefore,iftherearevariableswiththesamename
inthelocalandtheglobalenvironment,itwillreportthevariablefromthelocalenvironmentandnotthevariablecreatedvia
r:__evaldirect.Ifthereisonlyavariablewiththerequestednameintheglobalenvironment,everythingwillbefine-r:get
willreportthevalueofthisvariable.Ifyouwanttoremoveavariablecreatedviar:__evaldirect,i.e.intheglobal
environment,callr:eval "rm(myvar, envir=.GlobalEnv)",replacemyvarbythenameofyourvariable.TheRcommand
shouldn’treturnavalue.Thisprimitiveisexperimental.
;; 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
CallsthegarbagecollectorofJava(i.e.theR-Extension)andR.CallthisprimitiveafterremovinganRvariabletofreethe
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:getR-command
ReportsthereturnvalueofthesubmittedRcommand.ReturntypecouldbeaString,Number,Boolean,NetLogoListora
NetLogoListofLists.
RlistswillbeconvertedintoaNetLogoList.IftheRlistitselfcontainsfurtherlists,itwillbeconvertedintoaNetLogoList
withnestedNetLogolists.Listscontainingvaluesofdifferentdatatypesarealsosupported(e.g.mixedStrings,Numbers
andBooleans/Logicals).
Data.frameswillbeconvertedintoaNetLogoListwithnestedListforeachcolumn,butthecolumnnameswillbelost(same
fornamedRlists).
Rmatricescanbereceived,buttheyareconvertedintooneNetLogolist.NULLandNAvaluesarenotconvertedandwill
throwanerror,becauseNetLogohasnocorrespondingvalue.
;; returns a list with 10 variables
show r:get "rnorm(10)"
r:interactiveShell
r:interactiveShell
Opensawindowwithtwotextareas.TheupperoneistheRoutputstreamandintheloweroneyoucantypeRcommands.
ThisistheaccesstotheunderlayingRsession.Youcantypemulti-linecommands.TosubmitcommandspressCtrl+Enter.
With“PageUp”and“PageDown”intheinputareayoucanbrowsethroughthehistroyofsubmittedcommands.Withright-
mouseclickcontextmenu,youcansaveandloadanRHistory(interchangeablewithRterminalandotherRGUIs).
Pleasenote,thattheInteractiveShellworksontheglobalenvironment,whilecommandssubmittedfromNetLogolivesinan
localenvironment.Areferencetothislocalenvironmentisautomaticallyaddedtotheglobalenvironment(namednl.env,
pleasedonotdeletethisvariable.Withacallofr:clearyoucanrestoreitbutthiswillemptyyourworkspace).Youcanuse
thistohaveaccesstovariableswhichyouhavecreatedfromNetLogobyget("<variable name>",nl.env).Tocopyfor
exampleanvariablewiththenamevar1fromthelocalenvironmenttotheglobalenvironment,typevar <-
get("var",nl.env).SeesectionREnvironmentsfordetails.Ifyoujustwanttoseethecontentsofavariablewhichlivesin
thelocalenvironment,youcouldsubmityourcommand,forexampleintheNetLogoCommandCenter,andtheresultwillbe
shownintheoutputareaoftheInteractiveShell.Forexample:
r:put "test" (list world-width world-height)
r:interactiveShell
r:eval "print(test)"
r:eval "str(test)"
VariableswhichhavebeencreatedintheInteractiveShellareavailablefromNetLogo,eveniftheyarecreatedintheglobal
environment.Butifthereisavariablewiththesamenameinthelocalenvironment,youwillgetthisvariableinNetLogo
insteadtheonefromtheglobalenvironment.
IfyouwanttoexecuteplotcommandsfromtheInteractiveShellyoushouldactivatetheintegratedJavaGDplotdevicevia
r:setPlotDevicefirst.
;; opens Interactive Shell
r:interactiveShell
r:put
r:putnamevalue
CreatesanewvariableinRwiththenamename.ThevaluecanbeaString,Number,BooleanorList.
NetLogoListsareconvertedtoRvectors,ifallentriesareofthesamedatatype.IfaNetLogolistcontainsdifferentdata
types(mixedStrings,NumbersofBooleans),itwillbeconvertedintoanRlist.IfaNetLogoListcontainsother/nested
NetLogoListsitwillbeconvertedintoanRlistandthenestedListsarehandledbythesamerule(Vectorsifallitemsareof
thesamedatatype,…).
;; 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:putagentnameagentvariables
r:putagentnameagentsetvariables
CreatesanewnamedlistinRwiththenamename.Theargumentvariablesisanynumberofstringswhichlistand
variable(s)oftheagent|agentset.NamesoftheelementsoftheRlistwillbethesameasthenamesoftheagentvariables.
Turtleswillbeassignedinascendingorderoftheirwho-variable.Patcheswillbeassignedinlinesfromupperlefttolower
right.Sincetheargumentsofthisprimitivearerepeatable,don’tforgettheparenthesesaroundthestatement.
;; 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:putagentdfnameagentvariables
r:putagentdfnameagentsetvariables
Sameasr:putagentbutcreatesanRdata.frameinsteadalist.Pleasereadthenotesaboutdata.framesifoneofyour
agentvariablescontainsNetLogoLists.
;; 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:putdataframenamevarnamevaluevarname2value2...
Sameasr:putnamedlistbutcreatesanRdata.frameinsteadofalist.IfyousendmorethanonelisttoNetLogoandthe
listsareofdifferentlength,thesmalleroneswillbefilledwithNAvalues.
IfyousendnestedLogoLists(e.g.oftype:[[][]…])toonecolumnpleasereadthenotesaboutdataframeswithvectorsin
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:putlistnamevalue
CreatesanewlistinRwiththenamename.VariableisrepeatableandcanbeaNumber,BooleanorList.Each“Variable”
willgetthenameofitsposition(1,2,3,…).Sincetheargumentsofthisprimitivearerepeatable,don’tforgetthe
parenthesesaroundthestatement.
;; 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:putnamedlistnamevarnamevaluevarname2value2...
CreatesanewnamedlistinRwiththenamename.Variablenamesandvaluesfollowinalternatingsequenceandmaybe
repeatedasmanytimesasdesired.ValuescanbeaNumber,BooleanorList.Eachvaluewillgetthenamevarname.Since
theargumentsofthisprimitivearerepeatable,don’tforgettoputthestatementintoparentheses.
;; 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
ToopenanRplotinawindowyoucanusetheJavaGDplotdevice.Withthisprimitiveyoucanactivatethisdeviceandall
followingcallsofRplotswillbeprintedwiththisdevice.
Tousethisdevice,youhavetoinstalltheJavaGDpackageinR.OpenanRterminalortheInteractiveShell(see
r:interactiveShell)andtypeinstall.packages("JavaGD").
Withthisplotwindowyoucansavetheplottoanfileofdifferentgraphictypeandyoucancopytheplottotheclipboard.
Pleasenote,thatonLinuxOSitcanbenecessarytoallowtoaddimagestotheclipboard(e.g.inKDEyouhavetoconfigure
KLIPPERtoallowimages).Theresolutionforrasterimagesdependsonthesizeoftheplotwindow.Ifyouneedhigh
resolutionmaximazethewindow(anddon’tusejpeg,becausethedriverisbad)orbetteruseavectorimageformat.
Pleaseseethenotesaboutplottingforotherdetails.
;; activate the JavaGD plot device
r:setPlotDevice
r:stop
r:stop
StopstheRengine.Thisisneeded(only)ifNetLogoisrunninginheadlessmode,forexamplewhenrunning
BehaviorSpaceexperimentsfromthecommandlinewithsomethinglikethis:
java -cp NetLogo.jar org.nlogo.headless.Main --model mymodel.nlogo --experiment exp1 --table outtab1.csv
Shouldbethelastcallinheadlesssimulation.Seeusagenotesabovefordetails.
r:stop
Troubleshooting
Belowaresomecommonproblemsandsomeideasonhowtoremedythem.Pleasekeepinmindthatweplantocontinue
toimprovetheRextensionfollowingthereleaseofNetLogo6.Wewelcomefeedbackonhowtoimprovetheextensionas
wellasbugreportspointingustoanynewproblemsyouencounter.
LoadingRpackagesfails
See,forexample,thispost.
AfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextension
ChangingworkingdirectoryinRdoesn’tworkbecauseitchangesalsoJava’slibrarypaththatNetLogoneedstofindits
extensions.PleaseuseabsolutepathtoanyfilesinRinsteadofchangingtheworkingdirectory.
Specificerrorcodelist
Error#01.InvalidRHome.RhomeisspecifiedviatheR_HOMEenvironmentvariableorapropertiesfile,butcouldn’tbe
foundatthespecifiedpath.SeeaboveforhowtospecifyRhome.
Error#02:CannotfindrJava/JRI.TheRExtensionwasunabletolocateyourinstallationofrJava.Somestepstoresolve:
EnsurethatrJava(0.9-8orlater)isinstalledinR.Ensurethatit’sinstalledeithersystem-wideorforyouasauser
EnsurethatyourconfigurationpointstotheproperrJavalocation.Ifyouhaveauser.propertiesfile,ensurethat
jri.home.pathsincludesthepathgivenbyRwhenyourunsystem.file("jri",package="rJava")
Error#03:CannotloadrJavalibraries.ThismayindicateacorruptedrJavainstallation.TryreinstallingrJava.
Error#04:ErrorinR-Extension.Thisisanunknowninitializationerror.EnsurethatyouarerunningR3.0.0orlaterand
havetherJavaextensioninstalled(version0.9-8orlater).Pleasereportthiserrortobugs@ccl.northwestern.eduoropen
anewissueontheR-Extensionissuetracker.
Error#05:TherewasanerrorsettingR_HOME.Checkyouruser.propertiesfiletoensurethatr.homespecifiesavalidpath
totheRextension.YoumayalsobeabletoworkaroundthiserrorbysettingtheR_HOMEenvironmentvariable.Ifthiserror
persists,pleasereportit!
Error#06:CannotloadRlibraries.ThismayindicateacorruptedorimproperlyconfiguredRinstallation.Ifyou’recertain
thatyourRinstallationisfine,pleasereportthisasanissue.
Citation
Thiele,JC;Grimm,V(2010).NetLogomeetsR:Linkingagent-basedmodelswithatoolboxfortheiranalysis.Environmental
ModellingandSoftware,Volume25,Issue8:972-974[DOI:10.1016/j.envsoft.2010.02.008]
CopyrightandLicense
TheRextensionisCopyright(C)2009-2016JanC.ThieleandCopyright(C)2016UriWilensky/TheCenterforConnected
Learning.
NetLogo-R-Extensionisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNUGeneralPublic
LicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimplied
warrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicensefor
moredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwithNetLogo-R-Extension(locatedinGPL.txt).
NetLogoRndExtension
ThisextensionaddstheabilitytodoroulettewheelselectioninNetLogo.Itprovidesasimpler
waytoaccomplishthesamethingastheLotteryExamplefromtheNetLogoModelsLibrary.
Usage
Whichprimitivetousedependsonwhetheryouwanttoselectanitemfromalistorfroman
agenset.Italsodependsonwhetheryouwantoneormanyitemsand,ifyouwantmany,if
repeatsareallowedornot.Thefollowingtablesummarizesthesituation:
FromanAgentSet FromaList
Oneitem rnd:weighted-one-of rnd:weighted-one-of-list
Manyitems,without
repeats rnd:weighted-n-of rnd:weighted-n-of-list
Manyitems,withrepeats rnd:weighted-n-of-with-
repeats
rnd:weighted-n-of-list-with-
repeats
(Note:theinitialversionoftheextensionhadasinglesetofprimitivesforbothlistsand
agentsets,butitturnedouttobeconfusing,sowechangedit.Ifyouwereusingtheold
versionoftheextension,youwillneedtomodifyyourcodetousethenewprimitives.)
Inallcases,youwillneedtoprovidetwothingstotheprimitive:
The“candidates”:theitemsthattheprimitivewillselectfrom.
The“weight”:howlikelyitisforeachcandidatetobeselected.
Ifyouwanttoselectmorethanoneitems,youwillalsoneedtotellit:
Howmanyitemstoselect.
Anoteaboutperformance
TheextensionusesKeithSchwarz’simplementationofVose’sAliasMethod(seeSchwarz’s
Darts,Dice,andCoinspage).Assumingyouarechoosingncandidatesforacollectionofsize
mwithrepeats,thismethodhasaninitializationcostofO(m)followedbyacostofO(1)for
eachitemyoupick,soO(m+n)overall.
Forexample,inthefollowingcode:
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 ] ]
…thelineusingrnd:weighted-n-of-list-with-repeatswilllikelyrun100timesfasterthanthe
lineusingacombinationofn-valuesandrnd:weighted-one-of-list.Thisisbecause
rnd:weighted-n-of-list-with-repeatsonlyinitializesthealgorithmonceandrnd:weighted-
one-ofdoesiteachtimeitiscalled.
(Notethatcomposingn-valueswithrnd:weighted-one-of-listdoesnotpreservetheorderof
theoriginalcandidatelist,whilernd:weighted-n-of-list-with-repeatsdoes.)
Thingsareabitmorecomplicatedifyouarechoosingwithoutrepeats,however.Inthiscase,
thealgorithmmayhavetodiscardsomepicksbecausethecandidateshavealreadybeen
selected.Whenthisstartshappeningtoooften(maybebecausesomeweightsaremuch
biggerthanothers),theextensionre-initializesthealgorithmwiththealready-picked
candidatesexcluded.Thisshouldnothappentoooften,however,sowhilepickingwithout
repeatshasanupperboundofO(m*n)intheory,itshouldusuallynotbemuchmorethan
O(m+n)inpractice.
Thepreviousremarksapplytoagentsetprimitivesasmuchastheyapplytolistprimitives.
Primitives
AgentSetPrimitives
rnd:weighted-one-ofrnd:weighted-n-ofrnd:weighted-n-of-with-repeats
ListPrimitives
rnd:weighted-one-of-listrnd:weighted-n-of-listrnd:weighted-n-of-list-with-repeats
rnd:weighted-one-of
rnd:weighted-one-ofagentsetreporter
Reportsarandomagentfromagentset.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustnotbenegative.
Iftheagentsetisempty,itreportsnobody.
HereisafullrewriteoftheLotteryExamplemodelusingthernd:weighted-one-ofprimitive:
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-ofsizeagentset[reporter]
Reportsanagentsetofthegivensizerandomlychosenfromtheagentset,withnorepeats.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustbenon-negativenumbers.
Itisanerrorforsizetobegreaterthanthesizeoftheagentset.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
rnd:weighted-n-of-with-repeats
rnd:weighted-n-of-with-repeatssizeagentset[reporter]
Reportsalistofthegivensizerandomlychosenfromtheagentset,withrepeats.(Whyalist
insteadofanagentset?Becauseanagentsetcannotcontainthesameagentmorethan
once.)
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporter
forthatagent.Theweightsmustbenon-negativenumbers.
Itisnotanerrorforsizetobegreaterthanthesizeoftheagentset,buttherehastobeat
leastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
rnd:weighted-one-of-list
rnd:weighted-one-of-listlistanonymous-reporter
Reportsarandomitemfromlist.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisanerrorforthelisttobeempty.
Acommonwaytousetheprimitiveistohavealistoflists,wherethefirstitemofeachsublist
isthethingyouwanttochooseandtheseconditemistheweight.Hereisashortexample:
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 ]
]
ThisshouldprintBroughlyfourtimesmoreoftenthanitprintsA.
Ifyouhappentohaveyouritemsandyourweightsintwoseparatelists,youcancombine
themintopairsbyusingacombinationofmapandlist:
let items [ "A" "B" "C" ]
let weights [ 0.1 0.2 0.7 ]
let pairs (map list items weights)
Sinceweapplymaptoboththeitemslistandtheweightslist,theparenthesesareneededin
(map list items weights).Wealsousetheconciseanonymousproceduresyntax(seethe
programmingguide)topasslistasthereporterformap.Thesamethingcouldhavebeen
written(map [ [a b] -> list a b ] items weights) .
rnd:weighted-n-of-list
rnd:weighted-n-of-listsizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withnorepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisanerrorforsizetobegreaterthanthesizeofthelist of candidates.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistof
candidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
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 ]
Thisshouldprintalistoffournumbers,wherethebiggernumbers(32,64,128,256)havea
muchbetterchancetoshowupthanthesmallerones(2,4,8,16).
rnd:weighted-n-of-list-with-repeats
rnd:weighted-n-of-list-with-repeatssizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withrepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-
reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtothe
anonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionofthe
ProgrammingGuideformoredetails.)
Itisnotanerrorforsizetobegreaterthanthesizeofthelistofcandidates,buttherehasto
beatleastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,they
allhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistof
candidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
Example:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]
print map first rnd:weighted-n-of-list-with-repeats 25 pairs [ [p] -> last p ]
Thisshouldprintalistof25AsandBs,withroughlyfourtimesasmanyBsthanAs.
NetLogoSoundExtension
Using
TheSoundExtensionletsNetLogomodelsmaketwokindsofsounds:MIDIsoundsand
playbackofpre-recordedsoundfiles.
TheJavaAPIsusedarejavax.sound.midiandjava.applet.AudioClip.
HowtoUse
Thesoundextensioncomespreinstalled.Tousetheextensioninyourmodel,addthisat
thetopofyourCodetab:
extensions [sound]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,so
justaddsoundtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
Forexamplesthatusethesoundextension,seetheSoundsectionunderCodeExamples
intheNetLogoModelsLibrary.
MIDIsupport
TheMIDIpartoftheextensionsimulatesa128-keyelectronickeyboardwith47drumsand
128melodicinstruments,asprovidedbyGeneralMIDILevel1specification.
Itsupports15polyphonicinstrumentchannelsandasinglepercussionchannel.Using
morethan15differentmelodicinstrumentssimultaneouslyinamodelwillcausesome
soundstobelostorcutoff.
Thepitchofamelodicinstrumentisspecifiedbyakeynumber.Thekeysonthekeyboard
arenumberedconsecutivelyfrom0to127,where0istheleft-mostkey.MiddleCiskey
number60.
Theloudnessofaninstrumentisspecifiedbyavelocity,whichrepresentstheforcewith
whichthekeyboardkeyisdepressed.Velocityrangesfrom0to127,where64isthe
standardvelocity.Ahighervelocityresultsinaloudersound.
Primitives
sound:drumssound:instrumentssound:play-drumsound:play-notesound:play-note-later
sound:drums
sound:drums
Reportsalistofthenamesofthe47drumsforusewithsound:play-drum.
sound:instruments
sound:instruments
Reportsalistofthenamesofthe128instrumentsforusewithsound:play-note,
sound:play-note-later,sound:start-noteandsound:stop-note.
sound:play-drum
sound:play-drumdrumvelocity
Playsadrum.
Example:
sound:play-drum "ACOUSTIC SNARE" 64
sound:play-note
sound:play-noteinstrumentkeynumbervelocityduration
Playsanoteforaspecifiedduration,inseconds.Theagentdoesnotwaitforthenoteto
finishbeforecontinuingtonextcommand.
;; play a trumpet at middle C for two seconds
sound:play-note "TRUMPET" 60 64 2
sound:play-note-later
sound:play-note-laterdelayinstrumentkeynumbervelocityduration
Waitsforthespecifieddelaybeforeplayingthenoteforaspecifiedduration,inseconds.
Theagentdoesnotwaitforthenotetofinishbeforecontinuingtonextcommand.
Example:
;; in one second, play a trumpet at middle C for two seconds
sound:play-note-later 1 "TRUMPET" 60 64 2
DrumNames
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
InstrumentNames
*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
NetLogoTableExtension
Using
Thetableextensionispre-installedinNetLogo.
Tousethetableextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [table]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddtabletothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithantableinNetLogo,youcouldalsojustusealistfor.Butyoumaywanttoconsiderusingantableinsteadfor
speedreasons.Listsandtableshavedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrunfasterbyselectingthe
appropriatedatastructure.
Tablesareusefulwhenyouneedtodoassociatevalueswithothervalues.Forexample,youmightmakeatableofwordsandtheirdefinitions.
Thenyoucanlookupthedefinitionofanyword.Here,thewordsarethe"keys".Youcaneasilyretrievethevalueforanykeyinthetable,butnot
viceversa.
UnlikeNetLogo’slistsandstrings,tablesare“mutable”.Thatmeansthatyoucanactuallymodifythemdirectly,ratherthanconstructinganaltered
copyaswithlists.Ifthetableisusedinmorethanoneplaceinyourcode,anychangesyoumakewillshowupeverywhere.It’strickytowritecode
involvingmutablestructuresandit’seasytomakesubtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunlessyou’re
certainyouwantandneedmutability.
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"]
ManipulatingTables
Ifthesamekeyisusedwithtable:putmorethanonceforthesametable,thevalueprovidedtolastcalloftable:putwillbethevalueshownwhen
table:getisused.Hereisanexample:
let dict table:make
table:put dict "a" 5
table:put dict "a" 3
print table:get dict "a"
=> 3
Becausetablesaremutable,manipulatingexistingvaluesshouldbedonebycallingtable:getortable:get-or-defaultonakey,transformingthe
returnedvalue,andthencallingtable:puttoupdatethetransformedvalueinthetable.Hereisanexampleprocedurewhichincrementsavaluein
atableatagivenkey.Ifthekeydoesn’texist,itputsa1atthatkeyinstead.
to increment-table-value [ dict key ]
let i table:get-or-default dict key 0
table:put dict key i + 1
end
KeyRestrictions
TablekeysarelimitedtothefollowingNetLogotypes:
Numbers
Strings
Booleans
Listscontainingonlyelementswhicharethemselvesvalidkeys
Ifyouattempttouseanillegalvalue,thetableextensionwillraiseanexception,asshowninthefollowingexample.
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:cleartable
Removesallkey-valuepairsfromtable.
table:counts
table:countslist
Countstheoccurrencesofeachelementofthegivenlistandreportsthecountsinatable.
table:group-agents
table:group-agentsagentsetanonymousreporter
Groupstheagentsintheagentsetbasedonthegivenreporter.Agentsthatreportthesamethingforreporterwillbegroupedtogether.Theresults
ofthereporterwillbeusedasthekeysintheresultingtableandthegroupswillbeagentsets.
Forexample:
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
Groupstheitemsofthelistbasedonthegivenreporter.Thereportershouldtakeasingleargument,whichwillbetheitemsofthelist.Itemsthat
reportthesamethingwhenpassedtothereporterwillbegroupedtogether.Theresultsofthereporterwillbeusedasthekeysintheresulting
tableandthegroupswillbelists.
Forexample:
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-listlist
Reportsanewtablewiththecontentsoflist.listmustbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecond
elementisthevalue.
table:get
table:gettablekey
Reportsthevaluethatkeyismappedtointhetable.Causesanerrorifthereisnoentryforthekey.
table:get-or-default
table:get-or-defaulttablekeydefault-value
Reportsthevaluethatkeyismappedtointhetable.Reportsthedefault-valueifthereisnoentryforthekey.
table:has-key?
table:has-key?tablekey
Reportstrueifkeyhasanentryintable.
table:keys
table:keystable
Reportsalistofallthekeysintable,inthesameorderthekeyswereinserted.
table:length
table:lengthtable
Reportsthenumberofentriesintable.
table:make
table:make
Reportsanew,emptytable.
table:put
table:puttablekeyvalue
Mapskeytovalueintable.Ifanentryalreadyexistsinthetableforthegivenkey,itisreplaced.
table:remove
table:removetablekey
Removesthemappingintableforkey.
table:to-list
table:to-listtable
Reportsalistwiththecontentoftable.Thelistwillbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecond
elementisthevalue.Thekeysappearinthesameordertheywereinserted.
table:values
table:valuestable
Reportsalistwiththeentriesoftable.Theentrieswillappearinthesameordertheywereinserted,withduplicatesincluded.
NetLogoVidExtension
Concepts
VideoSource
Thevidextensionhasabuilt-inconceptofavideosource.Atthemoment,theonlyvideosources
availablearemoviesinthedirectorythemodellivesinandcamerasattachedtothecomputer.The
vidextensionopensanewvideosourcewiththevid:<source>-openandvid:<source>-select.
Theseprimitiveschangethesourcetotheselectedsource.Ifasourceisalreadyopen,itclosesit
beforeopeninganewone.
SourceLifecycle
Moviesourcesare“stopped”afterbeingcreatedbyvid:movie-selectorvid:movie-open.Camera
sourcesstartoffas“playing”afterbeingcreatedbyvid:camera-selectorvid:camera-open.Ifa
sourceisinstatus“stopped”itcanbestartedwithvid:start.Conversely,ifthesourceis“playing”it
canbestoppedwithvid:stop.Whenasourceis“stopped”,eachcalltovid:capture-imagewill
returnthesameimage.
VideoRecorder
Thevidextensionalsohastheconceptofarecording,aseriesofframeswhichcanbesewninto
an“mp4”movie.Therecorderstatuscanbequeriedusingvid:recorder-status.Therecorder
statusis“inactive”untilstartedwithvid:start-recorder,whichsetsitto“recording”.Whilethe
recorderis“recording”thevid:record-view,vid:record-interface,andvid:record-sourcecanbe
usedtosaveframestotherecording.Youcanchoosetosavetherecordingwhilerecordingusing
vid:save-recordingwhichsavesthemovietothespecifiedfileandresettherecordingstatusto
“inactive”.Ifyouwouldprefertothrowawaytherecordedframeswithoutsaving,usevid: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
Providesalistofallavailablecameras.
Example:
vid:camera-names => []
vid:camera-names => ["Mac Camera"]
vid:camera-names => ["Logitech Camera"]
vid:camera-open
vid:camera-open
Opensthenamedcameraasavideosource.Ifnonameisprovided,opensthefirstcamerathat
wouldbelistedbycamera-names.
Example:
vid:camera-open ; opens first camera
(vid:camera-open "Logitech Camera")
Errors:
Message"vid: no cameras found" :nocamerasareavailable.
Message"vid: camera "\<name\>" not found":ifthenamedcameraisnotavailable.
vid:camera-select
vid:camera-select
Promptstheusertoselectacameraasvideosource.Thiscommanddoesnoterroriftheuser
cancels.Usevid:statustoseeifauserselectedacamera.
Example:
vid:camera-select
Errors:
Message“vid:nocamerasfound”:nocamerasareavailable.
vid:movie-select
vid:movie-select
Promptstheusertoselectamovietouseasavideosource.Theformatssupportedarethose
supportedbyJavaFX2.Thiscommanddoesnoterroriftheusercancels.Usevid:statustoseeif
theuserselectedamovie.
Example:
vid:movie-select
Errors:
Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open
vid:movie-openfilename
Opensavideofromthefilesystem.Iftheprovidedpathisnotabsolutetheextensionsearchesfor
thegivenpathrelativetothecurrentmodeldirectory.Iftheprovidedpathisabsolutetheextension
opensthefile.
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":themoviecouldnotbefound.
Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open-remote
vid:movie-open-remoteurl
Opensaremotevideofromawebsiteorftpserver.
Example:
vid:movie-open-remote "http://example.org/foo.mp4"
Errors:
Message"vid: no movie found":ThespecifiedURLcouldnotbeloadedorerroredwhile
loading.
Message"vid: format not supported":Thefiletypeoftheremotemovieisnotsupported.
Message"vid: protocol not supported":ThemoviewasatanunsupportedURLprotocol.
Supportedprotocolsareftpandhttp.
vid:close
vid:close
Closesthecurrentlyselectedvideosource.Hasnoeffectifthereisnoactivevideosource.
Example:
vid:close
vid:start
vid:start
Startstheselectedvideosource.Avideosourcemusthavebeenselectedbeforecallingvid:start.
Example:
vid:start
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:stop
vid:stop
Stopsthecurrentlyrunningvideosource.
Example:
vid:stop
vid:status
vid:status
Reportsthecurrentstatusofanactivevideo.Notethataftercallingvid:movie-openorvid:movie-
selectthestatuswillbesetto“stopped”,whileaftercallingvid:camera-openorvid:camera-select
thestatuswillbe“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
Capturesanimagefromthecurrentlyselectedactivesource.
Ifwidthandheightarenotspecified,theimageiscapturedatthecurrentsourceresolution.
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
Ifyouwanttocaptureimagesatadifferentresolution,simplyreplacevid:capture-imagewith,e.g.,
(vid:capture-image 640 480).
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:set-time
vid:set-timeseconds
Setsthetimeofthecurrentvideosourceto*seconds*.Thishasnoeffectwhenthecurrentvideo
sourceisacamera.
Example:
vid:set-time 100
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
Message"vid: invalid time":Thecurrentlyactivevideodoesnotcontainthespecifiedsecond.
Thesecondmaybenegative,orgreaterthanthelengthofthevideo.
vid:show-player
vid:show-playerwidthheight
Showsaplayerinaseparatewindow.Ifthereisnovideosource,thewindowwillbeanemptyblack
frame.Ifthereisanactivevideosource,itwillbedisplayedinthewindowwiththespecifiedwidth
andheight.Ifthereisaplayingvideosource,itwillbedisplayedinthewindowatitsspecifiedwidth
andheight.Ifwidthandheightareomitted,thevideowillbedisplayedinitsnativeresolution.
Examplewithnativeresolution:
vid:show-player
Examplewithcustomresolution:
(vid:show-player 640 480)
Errors:
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:hide-player
vid:hide-player
Hidestheplayerifopen.Doesnothingifthereisnoplayerwindow.
Example:
vid:hide-player
vid:record-view
vid:record-view
RecordsthecurrentimageshownintheNetLogoviewtotheactiverecording.
Example:
vid:record-view
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
vid:record-interface
vid:record-interface
RecordstheNetLogointerfaceviewtotheactiverecording.
Example:
vid:record-interface
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: export interface not supported":ThecallingNetLogoversiondoesnotsupport
interfaceexports.ThiswilloccurwhenrunningNetLogoheadlessly.
vid:record-source
vid:record-source
Recordsaframetotheactiverecordingfromthecurrentlyactivesource.
Example:
vid:record-source
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selecta
sourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:recorder-status
vid:recorder-status
Reportsthecurrentstatusoftherecorder.Initiallyandaftertherecorderissaved(viavid:save-
recording)orreset(viavid:reset-recorder)therecorderstatusis“inactive”.Aftercalling
vid:start-recorderthestatuswillbe“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
Startstherecorder.Iftherecorderisalreadyrunningthiswillcauseanerrortoberaised.Ifdesired,
arecordingwidthandheightcanbesupplied.Ifwidthandheightarenotsupplied,theywillbe
determinedfromthefirstframerecorded.
Example:
vid:start-recorder
(vid:start-recorder 640 480)
Errors:
Message"vid: recorder already started":Therecorderhasalreadybeenstarted.Theexisting
recordingshouldbesavedorresetbeforestartingtherecording.
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthe
dimensionsiszeroornegative).
vid:save-recording
vid:save-recordingfilename
Savestherecordingtothespecifiedpath.Iftherecorderisnotrunningthiswillcauseanerrortobe
raised.Notethatatpresenttherecordingwillalwaysbesavedinthe“mp4”format.Ifthesupplied
filenamedoesnotendin“.mp4”,the“.mp4”suffixwillbeadded.Notethatvid:save-recordingwill
overwriteexistingfilesofthesamename.vid:save-recordingwillerroriftherecorderhasnotbeen
startedorifthefilecannotbewrittensincethecontainingdirectorydoesnotexist.
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":Therecorderhasnotbeenstarted.Starttherecorder
withvid:start-recorder.
Message"vid: no such directory":Thedirectorycontainingthespecifiedsavefiledoesnot
exist.
Message"vid: no frames recorded":Youtriedtosavearecordingwithnoframesrecorded.
Checkthatyouarerecordingproperlyorusevid:reset-recordingtotochangetherecording
formatwithoutsaving.
NetLogoView2.5dExtension
TheView2.5DextensionoffersvisualizationforPatchandTurtlereporters,inrealtime,ina
simulation’scontext.
HowtoUse
Theview2.5dextensionispre-installedinNetLogo.
Tousetheview2.5dextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [view2.5d]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustadd
view2.5dtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
IncorporatingIntoModels
openawindowusingeithertheview2.5d:patch-vieworview2.5d:turtle-viewcommands(itcanbea
goodideatoputtheseinyour‘SETUP’procedureoraseparatebutton).
updateyourwindow’sviewusingoneoftheupdatecommands(puttheseinyour‘GO’procedure).
SeetheView2.5dCodeExamplesintheNetLogomodelslibrary.
Feedback
Sendcomments,bugs,orotherfeedbacktoCCLFeedbackand/orCoreyBrady.
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-viewTitleReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallfor
subsequentupdatesandmodifications.SpecificationoftheReporterusestheNetLogoanonymous
proceduresyntax,fromtheObserverperspective.
Example:
view2.5d:patch-view "Test" [ [the-turtle] -> [pxcor] of the-turtle]
view2.5d:decorate-patch-view
view2.5d:decorate-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:drawsthe
turtlesofthemodelattheircurrentlocation,ontopofthePatchviewdisplay
NOTE:onlyhasaneffectinthe“structures”patchview(intheothers,thepatchvalueis
inclinedbasedonneighbors&gradient)
NOTE:fornegativepatchvalues,theturtleshapesaredrawnbelow(orbitunderneathto
seethem)
Example:
view2.5d:decorate-patch-view "Test"
view2.5d:undecorate-patch-view
view2.5d:undecorate-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)
TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:STOPSdrawingtheturtlesof
themodelattheircurrentlocation,ontopofthePatchviewdisplay
Example:
view2.5d:undecorate-patch-view "Test"
view2.5d:turtle-view
view2.5d:turtle-viewTitleAgentsReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontext
causesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallfor
subsequentupdates.Theturtle-setisanyselectorforturtles.SpecificationoftheReporterusesthe
NetLogotasksyntax,fromtheObserverperspective.
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
ThiscommandmustbecalledfromtheObservercontext.Updatesallexistingpatch-viewwindows
accordingtothelatestvalues.
view2.5d:update-patch-view
view2.5d:update-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.Updatesonlythepatch-viewwindowwiththe
specifiedtitle(ifany).
view2.5d:update-turtle-view
view2.5d:update-turtle-viewTitleAgents
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Theturtle-setselectormustbesuppliedtorefreshthesetofturtles.
view2.5d:get-z-scale
view2.5d:get-z-scaletitle
ThisreportermustbecalledfromtheObservercontext.Returnsthecurrentz-scaleoftheturtle-viewor
patch-viewwindowwiththespecifiedtitle(ifany).
view2.5d:set-z-scale
view2.5d:set-z-scaleTitlenew-z-scale
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-vieworpatch-view
windowwiththespecifiedtitle(ifany).Theviewisnowdisplayedwiththenewz-scale.
view2.5d:set-turtle-stem-thickness
view2.5d:set-turtle-stem-thicknessTitlethickness
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Turtlesarenowdrawnwith“pins”or“stems”thathavethespecifiedthickness
(insteadofthehairlinedefault)
view2.5d:get-observer-angles
view2.5d:get-observer-anglesTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingtheobserver’sangular
perspective{headingpitch}(theplaceonanimaginarysphereatthezoomdistanceisupdatedto
obeyheading&pitchgiven)
view2.5d:set-observer-angles
view2.5d:set-observer-anglesTitleheadingpitch
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setstheobserver’sangularperspective(theplaceonanimaginarysphereatthe
zoomdistanceisupdatedtoobeyheading&pitchgiven)
view2.5d:get-observer-xy-focus
view2.5d:get-observer-xy-focusTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingthexandycoordinates
theobserveris“lookingat”inthepatchplane.
view2.5d:set-observer-xy-focus
view2.5d:set-observer-xy-focusTitlenumberycor
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setsthexandycoordinatestheobserverthatis“lookingat”inthepatchplane.
view2.5d:get-observer-distance
view2.5d:get-observer-distanceTitle
ThisreportermustbecalledfromtheObservercontext.Returnstheobserver’sdistancefromits“focus
point”
view2.5d:set-observer-distance
view2.5d:set-observer-distanceTitlenew-distance
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththe
specifiedtitle(ifany).Setstheobserver’sdistancefromits“focuspoint”
view2.5d:remove-patch-view
view2.5d:remove-patch-viewTitle
Thiscommandclosesandremovesthespecifiedpatchviewprogrammatically(equivalenttoclosing
thewindowmanually).
view2.5d:remove-turtle-view
view2.5d:remove-turtle-viewTitle
Thiscommandclosesandremovesthespecifiedturtleviewprogrammatically(equivalenttoclosing
thewindowmanually).
view2.5d:remove-all-patch-views
view2.5d:remove-all-patch-views
Thiscommandclosesandremovesallpatchviewsprogrammatically(equivalenttoclosingthe
windowsmanually).
view2.5d:remove-all-turtle-views
view2.5d:remove-all-turtle-views
Thiscommandclosesandremovesallturtleviewsprogrammatically(equivalenttoclosingthe
windowsmanually).
view2.5d:count-windows
view2.5d:count-windows
Thisreporterreturnsthenumberofturtleandpatchviewsthatarecurrentlyactive.
FAQ(FrequentlyAskedQuestions)
NetLogo6.0.4UserManual
FeedbackfromusersisveryvaluabletousindesigningandimprovingNetLogo.We’dliketohearfromyou.(SeeContacting
Us.)
General
WhyisitcalledNetLogo?
The“Logo”partisbecauseNetLogoisadialectoftheLogolanguage.
“Net”ismeanttoevokethedecentralized,interconnectednatureofthephenomenayoucanmodelwithNetLogo,including
networkphenomena.ItalsoreferstoHubNet,themultiuserparticipatorysimulationenvironmentincludedinNetLogo.
HowdoIciteNetLogoorHubNetinapublication?
IfyouuseorrefertoNetLogo,HubNetoramodelfromtheNetLogomodelslibrary,weaskthatyouciteitasfollows:
NetLogoitself:Wilensky,U.1999.NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnectedLearningandComputer-
BasedModeling,NorthwesternUniversity.Evanston,IL.
HubNet:Wilensky,U.&Stroup,W.,1999.HubNet.http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnected
LearningandComputer-BasedModeling,NorthwesternUniversity.Evanston,IL.
HowdoIciteamodelfromtheModelsLibraryinapublication?
Thecorrectcitationisincludedinthe“CreditsandReferences”sectionofeachmodel’sInfotab.
WhereandwhenwasNetLogocreated?
NetLogowasfirstcreatedin1999byUriWilenskyattheCenterforConnectedLearningandComputer-BasedModeling,thenat
TuftsUniversityintheBostonarea.NetLogogrewoutofStarLogoT,whichwasauthoredbyWilenskyin1997.In2000,theCCL
movedtoNorthwesternUniversity,intheChicagoarea.NetLogo1.0cameoutin2002,2.0in2003,3.0in2005,4.0in2007,4.1
in2009,and5.0in2012.
WhatprogramminglanguagewasNetLogowrittenin?
NetLogoiswrittenmostlyinScala,withsomepartsinJava.(ScalacodecompilestoJavabytecodeandisfullyinteroperable
withJavaandotherJVMlanguages.)
What’stherelationshipbetweenStarLogoandNetLogo?
TheoriginalStarLogobeganattheMITMediaLabin1989andranontheConnectionMachine.Laterversionsweredeveloped
forMacintoshcomputers:MacStarLogo(1994,MIT)andStarLogoT(1997,Tufts).
TodaytherearetwoStarLogodescendantsunderactivedevelopment:NetLogo(fromtheCCLatNorthwesternUniversity)and
StarLogoTNG(fromMIT).NetLogoisthemostwidelyusedagent-basedmodelingenvironmentinbotheducationandresearch.
StarLogoTNGisdistinguishedbyitsprogramminginterfacebasedoncoloredblocks.
UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?
NetLogoisfree,opensourcesoftwareundertheGPL(GNUGeneralPublicLicense),version2,or(atyouroption)anylater
version.
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,pleasecontactUriWilenskyat
uri@northwestern.edu.
ThesourcecodeisonGitHub,here.Developmentdiscussionisonthenetlogo-develgroup.
TheUserManualispublishedunderaCreativeCommonsAttribution-ShareAlikelicense(CCBY-SA3.0).
SourcecodeforalloftheextensionsbundledwithNetLogoisonGitHub,here.Mostoftheextensionsareinthepublicdomain
(CC0notice).Otherextensionsarereleasedunderopensourcelicenses.Seeeachextension’sREADMEfordetails.
TheCodeExamplesintheModelsLibraryareinthepublicdomain(CC0notice).
TherestofthemodelsintheModelsLibraryareprovidedunderavarietyoflicenses.Somearepublicdomainandsomeare
opensource,butmostareundertheCreativeCommonsAttribution-ShareAlikelicense(CCBY-NC-SA),whichisnotanopen
sourcelicense,thoughthemodelsarefreefornoncommercialdistributionanduse.
Seeeachmodel’sInfotabtocheckitsparticularlicense.
ThemodelsareinapublicGitrepositoryhere.
DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?
Weofferworkshopsfromtimetotime.Ifaworkshophasbeenscheduled,wewillannounceitontheNetLogoUsersGroup.
ArethereanyNetLogotextbooks?
TheCCLhaspublishedatextbook(writtenbytheauthorofNetLogo)thatgivesanintroductiontoagent-basedmodeling
methodsusingNetLogo.Itgoesstepbystepwithcodingexampleshowtodesign,build,revise,andanalyzemodels.Andit
presentssomeadvancedtechniques.
Seewww.intro-to-abm.comformoreinformationonthattextbook.
SeetheTextbookssectionofourResourcespage.
WeattheCCLhavehopedtowriteseveralmoreNetLogotextbooks.Thesecouldbeaimedatdifferentaudiences,suchas:
middleschool,highschool,undergraduatecourseinmodelingorcomplexity,practicalguideforinterestedadults.
Unfortunately,wehavenotyetbeenabletofindthetimetomakethesehappen.Ifanyonefromtheusercommunitywouldlike
tocollaborateonsuchaventure,pleaseletusknow.Wewouldwelcomeit.
IsNetLogoavailableinotherlanguagesbesidesEnglish?
VolunteershavetranslatedtheusermanualintoChineseandCzech.ThetranslatedversionsareavailablefromtheNetLogo
website.
Sofar,theNetLogouserinterfacehasbeenlocalizedinEnglish,Spanish,Chinese,Russian,andJapanese.Allfivelanguages
areincludedinthestandarddownload.
WeareseekingvolunteerstocompleteandimprovetheselocalizationsandtotranslatetheNetLogosoftwareandmanualinto
asmanyotherlanguagesaspossible.Ifyou’reabletohelpinthisendeavor,pleasecontactus.
IsNetLogocompiledorinterpreted?
Shortanswer:someofboth.
Longanswer:NetLogodoesincludeacompilerthatgeneratesJavabytecode.However,thiscompilerdoesnotyetsupportthe
entirelanguage,sosomepartsofusercoderemaininterpreted.NotethatourcompilergeneratesJavabytecode,andJava
virtualmachineshave“just-in-time”compilersthatinturncompileJavabytecodeallthewaytonativecode,somuchusercode
isultimatelytranslatedtonativecode.
Hasanyonebuiltamodelof<x>?
TrylookingattheNetLogoModelsLibrary,theNetLogoModelingCommons,ourCommunityModelspage,andourlistof
referencestoNetLogoinoutsideworks.
YoumightalsoaskthequestionontheNetLogoUsersGroupand/orsearchpastmessagesonthegroup.
AreNetLogomodelsrunsscientificallyreproducible?
Yes.NetLogo’spseudorandomnumbergeneratorandagentschedulingalgorithmsaredeterministic,andNetLogoalwaysuses
Java’s“strictmath”library,whichgivesbit-for-bitidenticalresultsregardlessofplatform.Butkeepthefollowingcautionsinmind:
Ifyourmodelusesrandomnumbers,theninordertogetreproduciblebehavior,youmustusetherandom-seedcommand
tosettherandomseedinadvance,sothatyourmodelwillreceivetheexactsamesequenceofrandomnumbersevery
time.Rememberthatagentsetsarealwaysinrandomorder,soanythingyoudowithagentsetsusesrandomnumbers.
Ifyourmodelusestheeveryorwaitcommandsinsuchawaythataffectstheoutcomeofthemodel,thenyoumayget
differentresultsondifferentcomputers,orevenonthesamecomputer,sincethemodelmayrunatadifferentspeed.
Inordertoreproducemodelrunsexactly,youmustbeusingtheexactsameversionofNetLogo.Thedetailsoftheagent
schedulingmechanismandtherandomnumbergeneratormaychangebetweenNetLogoversions,andotherchanges
(bugfixesintheengine,languagechanges,andsoforth)mayalsoaffectthebehaviorofyourmodel.(Thenagain,they
maynot.)
WehaveexpendedeveryefforttomakeNetLogomodelrunsfullyreproducible,butofcoursethiscannevertrulybean
iron-cladguarantee,duenotonlytothepossibilityofrandomhardwarefailure,butalsothepossibilityofhumanerrorinthe
designof:yourmodel,NetLogo,yourJavaVM,yourhardware,andsoon.
WillNetLogoandNetLogo3Dremainseparate?
Fornow,yes.NetLogo3DisincludedwithNetLogo,butitisstillaseparateapplication.
Ideallyasingleunifiedapplicationwouldsupportboth2Dand3Dmodeling.Wewoulddesignthe3Dworldsupportsoitdoesn’t
getinthewaywhenyouarebuilding2Dmodels.ModelsbuiltinNetLogo3Dmightrequirechangesinordertoruninthe
hypotheticalunifiedapplication.
CanIrunNetLogoonmyphoneortablet?
No.NeitheriOS,norAndroid,norWindowsRTsupportsrunningJavaapplicationssuchasNetLogo.
WeareworkingonanalternateimplementationofNetLogoonaJavaScriptandHTML5base,insteadofJava.Itwillworkona
varietyoftabletsandphones.Wedon’tknowyetwhenitwillbeready,andweexpectthatforalongtimeitwillonlysupporta
subsetofthefeaturesindesktopNetLogo.Themanyperson-yearsofdevelopmenteffortthathavegoneintotheJavaversion
can’tcheaplyoreasilybereplicatedonanotherplatform.
Fortechnicaldetailsonthisnewproject,gohere.
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?
Yes.WhenyouinstallNetLogo,thefolderthatiscreatedcontainshastheversionnumberinitsname,somultipleversionscan
coexist.
OnWindowssystems,whicheverversionyouinstalledlastwillbetheversionthatopenswhenyoudoubleclickamodelfilein
WindowsExplorer.OnMacs,youcancontrolwhatversionopensvia“GetInfo”intheFinder.
I’monaUNIXsystemandIcan’tuntarthedownload.Why?
Someofthefilesinthetarballhavelongpathnames,toolongforthestandardtarformat.YoumustusetheGNUversionoftar
instead(oranotherprogramwhichunderstandstheGNUtarextensions).Onsomesystems,theGNUversionoftarisavailable
underthename“gnutar”.YoucanfindoutifyouarealreadyusingtheGNUversionbytypingtar --versionandseeingifthe
outputsays“tar(GNUtar)”.
HowdoIinstallNetLogounattended?
Itdependsonwhichplatformyouareusing.
Linux:UntarNetLogointotheappropriateplace.
Mac:CopytheNetLogodirectoryfromthediskimageintotheApplicationsfolder.
Windows:TheinstallerisanMSIwhichcanberunusingoneofthefollowingcommands(thesemayrequireadmin
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
Wealsomaintainanadvancedinstallationwikipagewhichmayhaveadditionaltipsandtricks.Weencourageuserswhohave
problemswithunattendedinstallationorideasonhowitcouldbeimprovedtoemailfeedback@ccl.northwestern.edu.
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?
Yes.NetLogorunsfinefromanyfilesystem,includingread-onlyfilesystems.
WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?
Yourcomputerisswitchingtopowersavingmodewhenunplugged.It’snormalforthistoreducespeedalittle,butunfortunately
thereisabuginJavathatdrasticallyslowsdownSwingapplications,includingNetLogo.
Oneworkaroundistochangethepowersettingsonyourcomputersoitdoesn’tgointopowersavingmodewhenyouunplugit.
(Ifyoudothis,yourbatterywon’tlastaslong.)
AnotherworkaroundistorunNetLogowithanoptionrecommendedbyOracle,byeditingtheNetLogo6.0.4.vmoptionsfile,
foundintheNetLogodirectory(underProgramFilesonyourharddrive,unlessyouinstalledNetLogoinadifferentlocation).Add
onanewline:
-Dsun.java2d.ddoffscreen=false
YoucanseethedetailsoftheJavabugandvoteforOracletofixithere.
WhydoesNetLogobundleJava?
SinceMacOSXLion,ApplehaveencouragedMacapplicationdeveloperstobundleJava.NetLogobundlesJavabecauseit
allowsustodeliveraconsistent,convenientexperiencetoourusers.BundlingJavaallowsustotestforcompatibilityonceand
avoidanybugscausedbyversionmismatchesorJavaconfigurationincompatibilities.
IfusersareinterestedinusingJavaontheirsysteminsteadoftheversionofJavabundledwithNetLogo,theycanconfigure
NetLogotouseadifferentJavaruntime.Pleasenotethatthischangeisdoneatyourownrisk.Weareunabletooffersupport
forproblemscausedbyrunningNetLogowithanalternateJavaRuntime.TochangetheJavaruntimeusedbyNetLogo,open
theNetLogo.cfgfileandmodifytheapp.runtimepropertytothepathofyourpreferredJavaRuntime.
HowcomeNetLogowon’tstartuponmyLinuxmachine?
WebundleOracle’sJavaruntimewhenusingNetLogoonLinux.Ifyouwouldliketochangetheversionoflinuxused,youcan
modifythe.cfgfilestopointtoadifferentversionofjava(seeHowbigcanmymodelbe?formoreinformation).
Intheory,anyJava8orlaterruntimewillrunNetLogo.Inpractice,someJavaimplementationsaren’thighenoughquality.
RecentversionsofOpenJDKshouldwork;olderonesmaynot.GNUlibgcjdoesnotwork.
Ubuntuusersshouldconsulthttps://help.ubuntu.com/community/Java.
WhenItrytoinstallNetLogoonWindows,Isee“WindowsprotectedyourPC”
Windowsattemptstoprotectusersfromdownloadingmalicioussoftwarebymaintainingalistof“good”and“malicious”software.
ThefirstuserstoinstallanyNetLogoreleasewillseethiswarning.Laterusersmayormaynotseethiswarning.Beforegoing
anyfurther,ensureyouareprotected.TheCCLcanonlyvouchforNetLogodownloadshostedontheCCLWebsite.NetLogo
canbefreelydownloadedfromtheofficialNetLogodownloadpage.IfyouobtainNetLogofromanywhereelse,youinstallitat
yourownrisk!
YoucancontinuepasttheWindowspromptbytakingthefollowingsteps:
Inthe“WindowsprotectedyourPC”prompt,click“MoreInfo”,thepromptwillchange
Inthechangedprompt,click“RunAnyway”andcontinuewithinstallationasnormal
Noteinordertoseethe“MoreInfo”or“RunAnyway”options,youwillneedtoruntheinstallerasanadministrator.Ifyoudonot
seethoseoptions,right-clickandchoose“Runasadministrator”and/orchangeyouruseraccounttoanadministratoraccount
beforeinstalling.
WeattheCCLareworkingonsolvingthisproblemandhopetofreeourusersoftheaddedinstallationdifficultysoon!
WhenItrytostartNetLogoonWindowsIgetanerror“TheJVMcouldnotbestarted”.Help!
AnearlycertainfixistouseatexteditortoedittheNetLogo.cfgfile,changing1024mtoasmallernumber,like512m.This
shouldpermitNetLogotostart,althoughthelowerheapsizelimitmayaffectyourabilitytorunmodelswithmanyagents.See
Howbigcanmymodelbe?forinformationonmodelsizeandhowtoeditthecfgfile.
Ifrunningwiththelowerheapsizelimitisunacceptable,readon.
SomeWindowssystemshavetroubleallocatinglargeamountsofcontiguousvirtualmemory.Upgradingtoanewerversionof
Windowsmayhelp.
RunningWindowsin64-bitmodeinsteadof32-bitmodemayalsohelp.DoublecheckthatWindowsisactuallyrunningin64-bit
mode;seeMicrosoft’sFAQpageon64-bitWindows.
NetLogowon’tstartonMacOSSierra(orlater)
SomeusershavereportedproblemsopeningNetLogo6onMacOSSierra.We’vebeenunabletodeterminearootcausefor
thisproblem,butwe’recontinuingtoinvestigate.We’relookingforassistancefromyouifyourunintothisproblem.Itwouldbe
extremelyhelpfulifyoucouldrunthefollowingcommandinthe“Terminal”applicationandsendtheoutputinanemailto
bugs@ccl.northwestern.edu.
xattr -pl com.apple.quarantine /Applications/NetLogo\ 6.0.4/NetLogo\ 6.0.4.app
runningitshouldgiveyouasinglelineofoutput(somethinglikecom.apple.quarantine: 01e1;58ac6af2;Firefox;F2E0B1E2-D203-
4B05-8DF9-ABA58B52EFEA,butyourswillhavedifferentnumbers,letters,andwords).Pleasecopyandpastethisstringintothe
emailyousendus.
Thereisalsoapartialworkaround!RunningthefollowingcommandintheTerminalwillenableuserstorunNetLogowithout
turningGatekeepercompletelyoff.Thecommandis:
sudo xattr -dr com.apple.quarantine /Applications/NetLogo\ 6.0.4/NetLogo\ 6.0.4.app
NotethatifyouplantorunNetLogo3D,HubNetClient,orNetLogoLogging,youmayalsoneedtore-runthatcommandonce
foreachofthoseapplications.Iftheworkaroundwasnoteffectiveforyou,pleasesendusanemailandletusknow.
NetLogowon’tstartonWindowsorcrashessuddenlyonMacOSSierra
SomeusersonMacOSwithdiscretegraphicscardsexperiencesuddencrashesofNetLogowhenswitchingbetweenintegrated
anddiscretegraphics.It’spossibletopreventthesecrashesbydisablingautomaticgraphicsswitchinginSystemPreferences.
SomeWindowsusersmayalsobeunabletoopenNetLogoduetographicscardsettingsordrivers.Ifyouareunabletoopen
NetLogoonWindows,youmightbeabletofixthisbyupdatingorreinstallingyourgraphicsdriverand/ordisablinganygraphics
cardutilities.BecauseNetLogomightbeunabletostartforanumberofreasons,weencourageyoutocontactusifthesesteps
aren’teffectiveinresolvingtheproblem.
CanIrunNetLogofromthecommandline,withouttheGUI?
Yes.TheeasiestwayistosetupyourmodelrunorrunsasaBehaviorSpaceexperiment.Noadditionalprogrammingis
required.SeetheBehaviorSpaceGuidefordetails.
AnotheroptionistouseourControllingAPI.SomelightJavaprogrammingisrequired.SeetheControllingAPIGuidefordetails
andsamplecode.
DoesNetLogotakeadvantageofmultipleprocessors?
OnlywhenusingBehaviorSpace.BehaviorSpacedoesparallelruns,oneperprocessor.
Forasinglemodelrun,onlyoneprocessorisused.
Weareseekingfundingtomakeitpossibletosplitasinglemodelrunacrossmultipleprocessorsormultiplecomputers.
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?
Manyofthesamecommentsinthepreviousanswerapply.Itisnotpossibletosplitasinglemodelrunacrossmultiple
computers,butyoucanhaveeachmachineinaclusterdoingoneormoreseparate,independentmodelruns,usingeither
BehaviorSpaceorourControllingAPI.Wedon’thaveautomatedsupportforsplittingtherunsacrossclusters,soyou’llneedto
arrangethatyourself.
VarioususersarealreadyusingNetLogoonclusters,withavarietyofhardwareandsoftware.Youcanseekthemoutonthe
NetLogoUsersGroup.
IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
Yes.NetLogoauto-savesfilesasyouareworkingonthem.Thepathtotheauto-savefiledependsonwhetherornotthe
NetLogomodelhasbeensaved.
ForNetLogomodelswhichhavebeensaved,ahiddenfilewiththename“.filename.tmp.nlogo”willbecreatedinthesame
directoryastheNetLogomodel.
ForunsavedNetLogomodels,autosavefilescanbefoundinyourOS-specificjavatemporarydirectory.Thefilesarenamed
accordingtothefollowingformat:autosave_yyyy-MM-dd.HH_mm_ss.nlogowherethetimeanddatearethetimeanddatethe
modelwasopened.Theexactpathwilldependonyouroperatingsystem:
OnMacOS,thetemporarydirectoryis/var/folders/68/<30-character-alphanumeric-sequence>/T/.The30-character-
alphanumeric-sequenceisuniquetoeachmachine.
OnWindowsthelogscanbefoundinC:\Users\<user>\AppData\Local\Temp,where<user>istheloggedinuser.
Onmostnon-MacUnix-likesystemsthetempdirectoryis/tmp.
WhyisHubNetDiscoveryNotWorking?
HubNetdiscoveryprovidestheabilityforHubNetclientsrunningonthesamelocalnetworkastheHubNetserverto
automaticallydisplaytheIPaddressandcurrentactivityoftheserver.ThisusesIPv4multicastoveralocalareanetwork-it
won’tidentifyHubNetserversontheinternetorondifferentnetworks.Somenetworksalsodonotsupportmulticasttrafficandit
willsimplynotworkonthosenetworks.ForHubNetDiscoverytowork,theservermustbebroadcastingtothesamenetwork
thattheclientispollingformessages.Often,boththeclientandserverareonlyconnectedtoasinglenetworkandthereisno
needforfurtherconfiguration.
SinceNetLogo6.0.3,wehavetoolsinplacetoallowclientsand/orserversconnectedtomultiplenetworkstoselectthenetwork
onwhichtheywillbroadcast/listen.WhenrunningaHubNetserver,thisisdonebyselectingtheappropriate“broadcastnetwork”
viaselectiondropdownwhenstartingaHubNetserver.ThispreferencewillberemembereduntilNetLogoisrestarted,soifyou
endupneedingtobroadcastonadifferentnetwork,restartNetLogo.HubNetclientsalsoseeasimilardropdownwhenselecting
whichactivitytojoin.UnlikeHubNetserver,clientsmaychangethenetworkonwhichtheylistenatanytime.HubNetdiscovery
willonlyworkwhenbothclientandserverarelistening/broadcastingonthesamenetwork,sosometrialanderrormaybe
requiredtofigureoutaworkingconfiguration.Generallyspeaking,thesharednetworkistheoneonwhichtheclientandthe
serverhavethemostsimilarIPaddressprefixes.Forinstance,iftheserverselectstobroadcastonanetworkwhereithasIP
address192.168.0.101,aclientshouldpreferlisteningonanetworkwhereithasanIPlike192.167.0.203overanetworkwhere
ithasanIPlike10.5.0.101.Evenwhenthesamenetworkisselected,itispossiblethatthatnetworkmaynotsupportIPv4
multicast,inwhichcasediscoverywillnotworkandclientsmustenterIPaddressesmanually.
Notethatthechangemadein6.0.3simplyenableselectionofthenetworkonwhichclientsandserversbroadcast/listenon.The
HubNetserverstilllistensonallnetworkconnections,soalllistedIPaddressesgivenintheserverbroadcastnetworkselection
dropdownarepotentiallyvalidforaHubNetclient(evenaclientonadifferentnetwork)toconnectto.SimilarlyHubNetclients
mayconnecttoanyHubNetserverreachablefromtheircomputer.
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?
TheonlywayNetLogocanmakeyourmodelrunfasterisbyupdatingtheviewlessfrequently.Asyoumovethespeedsliderto
theright,viewupdatesbecomelessandlessfrequent.Sinceviewupdatestaketime,thatmeansmorespeed.
However,fewerupdatesalsomeansthattheupdatescomefartherapart.Whenseveralsecondspassbetweenupdates,itmay
seemlikeyourmodelhasstopped.Ithasn’t.It’srunningatfullspeed.Watchthetickcounter!(Ifyourmodelusesit.Ifitdoesn’t,
watchsomethingelse,likeaplot.)
Togetafeelforwhat’sgoingon,trymovingtheslidertotherightgraduallyratherthansuddenly.Ifyoufindtheupdatestoo
infrequentattherightmostposition,justdon’tpushthesliderthatfar.
CanIusethemouseto“paint”intheview?
NetLogodoesnothaveabuilt-insetofpaintingtoolsforpaintingintheview.Butwithonlyafewlinesofcode,youcanadd
paintingcapabilitytoyourmodel.Toseehowit’sdone,lookatMouseExample,intheCodeExamplessectionoftheModels
Library.Thesametechniquescanbeusedtolettheuserinteractwithyourmodelusingthemouseinotherways,too.
AnotherpossibilityistocreateanimageinanotherprogramandimportitusingtheimportitemsontheFilemenuortheimport-
*primitives.
Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmy
modelcontain?
WehavetestedNetLogowithmodelsthatusehundredsofmegabytesofRAMandtheyworkfine.Wehaven’ttestedmodels
thatusegigabytesofRAM,though.Theoreticallyitshouldwork,butyoumighthitsomelimitsthatareinherentintheunderlying
JavaVMand/oroperatingsystem(eitherdesigned-inlimits,orbugs).
TheNetLogoenginehasnofixedlimitsonsize.Bydefault,though,NetLogoshipswithaone-gigabyteceilingonhowmuchtotal
RAMitcanuse.Ifyourmodelexceedsthatlimit,you’llgetanOutOfMemoryErrordialog.
IfyouareusingBehaviorSpace,notethatdoingrunsinparallelwillmultiplyyourRAMusageaccordingly.
Eachplatformcontains“.cfg”filescontainingJVMsettings.Thereisonecfgfileforeachsub-application(NetLogo,NetLogo3D,
HubNetClient,etc.)Althoughthefilelocationvariesbyplatform,theprocessforchangingitisthesame.Locatethesectionof
thefilethatlookslikethefollowing:
[JVMOptions]
# there may be one or more lines, leave them unchanged
-Xmx1024m
# there may be one or more lines, leave them unchanged
Modifythevalueimmediatelyfollowing-Xmx,changingittotheamountofspaceyouneed,savethefile,andrestartNetLogo.
Platformspecificnotesfollow:
Windows:ThecfgfileswillbeinC:\Program Files (x86)\NetLogo 6.0.4\appifyouarerunning64-bitwindows,and
C:\Program Files\NetLogo 6.0.4\appotherwise.
MacOSX:ThefileforNetLogowillbelocatedat:/Application/NetLogo 6.0.4/NetLogo.app/Contents/Java/NetLogo.cfg
ForNetLogo3Dandtheotherapplications,youwillfindthefileinthecorrespondinglocationforeachapplicationpackage.
Youcanreachthecfgfilebycontrol-clickingtheapplicationintheFinderandchoosing“ShowPackageContents”fromthe
popupmenu.
PleasenotethatdependingonyourversionofMacOSX,changingthecfgfilemaybreakapplicationsigning.Ifthis
happens,followApple’sdirectionsonthispagetotemporarilyallowappsfrom“Anywhere”,runNetLogoonce,thenrestore
thesettingto“MacAppStoreandIdentifiedDevelopers”.
Other:Thecfgfileswillbelocatedinthenetlogo-6.0.4/appfolderafteruntarring.
Bydefault,MacbuildsofNetLogobundlea64-bitJVM,whichshouldbeabletomakeuseofasmuchmemoryasthelesserof
availablesystemmemoryandthevaluefollowing-Xmx.WindowsandLinuxwillbundlea32-bitor64-bitJVM,dependingon
whichversionyouhavedownloaded.Itisrecommendedthatyouinstall64-bitNetLogoonall64-bitoperatingsystemsforbest
performance.
CanIuseGISdatainNetLogo?
Yes,manyusersareusingGISdatawithNetLogo.ThemostcompletewaytodothatiswiththeGISextension.SeetheGIS
ExtensionGuide.
Asimplerwayistouseimport-pcolors,butthatonlyworksforimportingmapsthatareimages,notmapsinotherformats.
ItisalsopossibletowriteNetLogocodethatreadsGISdatausingourfileI/Oprimitivessuchasfile-open.Forexample,seethe
GrandCanyonmodelintheEarthSciencesectionofSampleModels.
Mymodelrunsslowly.HowcanIspeeditup?
Here’ssomewaystomakeitrunfasterwithoutchangingthestructureofthecode:
Usetick-basedviewupdates,notcontinuousupdates.
Decreasethefrequencyofviewupdatesbypushingthespeedslidertotheright,orturnupdatesoffusingthecheckbox.
IfyourmodelisusingallavailableRAMonyourcomputer,theninstallingmoreRAMshouldhelp.Ifyourharddrivemakes
alotofnoisewhileyourmodelisrunning,youprobablyneedmoreRAM.
Useturtlesize1,1.5,or2,asthe2DrenderingsforthesesizesarecachedbyNetLogo.(Thisonlyaffectsgraphicsspeed
inthe2Dview,notcomputationspeed.)
Inmanycases,though,ifyouwantyourmodeltorunfaster,youmayneedtomakesomechangestothecode.Usuallythe
mostobviousopportunityforspeedupisthatyou’redoingtoomanycomputationsthatinvolvealltheturtlesorallthepatches.
Oftenthiscanbereducedbyreworkingthemodelsothatitdoeslesscomputationpertimestep.ThemembersoftheNetLogo
UsersGroupmaybeabletohelpwiththis.
Theprofilerextensionisusefulforidentifyingwhichpartsofyourcodearetakingthemosttime.
Unlessyouarerunningtheexactsamestringsoverandover,usingrunandrunresultaremuchslowerthanrunningcode
directly;youshouldavoidusingtheseprimitivesonfreshstringsinperformance-criticalcode.
CanIhavemorethanonemodelopenatatime?
OneinstanceofNetLogocanonlyhaveonemodelopenatatime.(Unfortunately,itisunlikelythatthiswillchangeinafuture
version,duetotheengineeringdifficultiesinvolved.)
YoucanhavemultiplemodelsopenbyopeningmultipleinstancesofNetLogo,though.OnWindowsandLinux,simplystartthe
applicationagain.OnaMac,you’llneedtoduplicatetheapplication(notthewholefolder,justtheapplicationitself)intheFinder,
thenopenthecopy.(Thecopytakesuponlyaverysmallamountofadditionaldiskspace.)
CanIchangethechoicesinachooseronthefly?
No.
CanIdividethecodeformymodelupintoseveralfiles?
Onanexperimentalbasis,thisisavailableusingthe__includeskeyword.
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?
ThisisansweredindetailattheendoftheProgrammingGuide.
HowcomemymodelfromanearlierNetLogodoesn’tworkright?
SeetheTransitionGuideforhelp.
HowdoItakethenegativeofanumber?
Anyoftheseways:
(- x)
-1 * x
0 - x
Withthefirstway,theparenthesesarerequired.
Myturtlemovedforward1,butit’sstillonthesamepatch.Why?
Ifyouhavedisabledwrappingattheworldedgesinyourmodel,thentheturtlemightbeataworldedgeandunabletomoveany
further.Youcantestforthisusingcan-move?.
Assumingtheturtleisn’thittingaworldedge,movingforward1isonlyguaranteedtotakeaturtletoanewpatchiftheturtle’s
headingisamultipleof90(thatis,exactlynorth,south,east,orwest).
It’sbecausetheturtlemightnotbestandinginthecenterofapatch.Itmightbenearthecornerofapatch.Forexample,
supposeyourturtleisclosetothesouthwestcornerofapatchandisfacingnortheast.Thelengthofthepatchdiagonalis
1.414…(thesquarerootoftwo),sofd 1willleavetheturtlenearthenortheastcornerofthesamepatch.
Ifyoudon’twanttohavetothinkabouttheseissues,onepossibilityistowriteyourmodelinsuchawaythatyourturtlesalways
cometorestonpatchcenters.Seenextquestion.
HowdoIkeepmyturtlesonpatchcenters?
Aturtleisonapatchcenterwhenitsxcorandycorareintegers.
Youcanmoveaturtletothecenterofitscurrentpatchwitheitherofthesetwoequivalentcommands:
move-to patch-here
setxy pxcor pycor
Butyou’llneverneedtodothatifyouneverallowturtlesoffofpatchcentersinthefirstplace.
Thesproutcommandcreatesturtlesonpatchcenters.Forexample:
ask n-of 50 patches [ sprout 1 [ face one-of neighbors4 ] ]
Anotherwayforaturtletostartonapatchcenteriswithacommandsuchasthislineofturtlecode,whichmovesittothecenter
ofarandompatch:
move-to one-of patches
Onceaturtleisonapatchcenter,aslongasitsheadingalwaysstaysanexactmultipleof90(thatistosay,duenorth,east,
south,orwest),andasitlongasitmovesforwardorbackbyintegeramounts,itwillalwayslandonpatchcenters.
SeeRandomGridWalkExample,intheCodeExamplessectionoftheModelsLibrary,toseethesecodesnippetsinuse.
patch-ahead 1isreportingthesamepatchmyturtleisalreadystandingon.Why?
Seetheanswertwoanswersup.It’sthesameissue.
Thismightnotbethemeaningof“ahead”youwereexpecting.Withpatch-ahead,youmustspecifythedistanceaheadthatyou
wanttolook.Ifyouwanttoknowthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously,itispossibletofindthat
out.SeeNextPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowdoIgivemyturtles“vision”?
Youcanusein-radiustoletaturtleseeacircularareaaroundit.
Severalprimitiveslettheturtle“look”atspecificpoints.Thepatch-aheadprimitiveisusefulforlettingaturtleseewhatisdirectly
infrontofit.Ifyouwanttheturtletolookinanotherdirectionbesidesstraightahead,trypatch-left-and-aheadandpatch-right-
and-ahead.
Ifyouwanttheturtletohaveafull“cone”ofvision,usethein-coneprimitive.
Youcanalsofindoutthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously.SeeNextPatchExample,inthe
CodeExamplessectionoftheModelsLibrary.
Canagentssensewhat’sinthedrawinglayer?
No.Ifyouwanttomakemarksthatagentscansense,usepatchcolors.
I’mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?
Seethe“Math”sectionoftheProgrammingGuideforadiscussionofthisissue.
Thedocumentationsaysthat random-float 1mightreturn0butwillneverreturn1.WhatifI
want1tobeincluded?
Itreallydoesn’tmatter.Evenif1wereapossibleresult,itwouldonlycomeupapproximately1in2^64tries,whichmeansyou’d
bewaitinghundredsofyearsbeforeitevercameupexactly1.
Nonetheless,ifyouareconvincedthatitreallymustbepossibletoget1,youcanuseprecisiontoroundyouranswertoa
certainnumberofdecimalplaces.Forexample:
print precision (random-float 1) 10
0.2745173723
(Ifyouusethismethod,notethat0and1areonlyhalfaslikelytocomeupasotheranswers.Toseewhythisisso,considerthe
casewhereyouonlykeeponedigitafterthedecimalpoint.Resultsbetween0and0.5getroundedto0,butresultsbetween0.5
and1.5getroundedto1;thelatterrangeistwiceaslarge.Ifyouwant0,0.1,0.2,…,0.9,and1toallbeequallylikely,an
alternativeistowriterandom 11 / 10 ;thisgivesall11answerswithequalprobability.)
HowcanIkeeptwoturtlesfromoccupyingthesamepatch?
SeeOneTurtlePerPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowcanIfindoutifaturtleisdead?
Whenaturtledies,itturnsintonobody.nobodyisaspecialvalueusedinNetLogousedtoindicatetheabsenceofaturtleor
patch.Soforexample:
if turtle 0 != nobody [ ... ]
Youcouldalsouseis-turtle?:
if is-turtle? turtle 0 [ ... ]
DoesNetLogohavearrays?
Nearlyallmodelsshouldjustuselistsforthis.
Theusualmotivationforusingarraysinotherprogramminglanguagesisthattheyprovidefastrandomaccess(item)and
mutation(replace-item).ButNetLogo’slists,eventhoughtheyareimmutable,nowprovidenearconstanttimeperformanceon
theseoperations.
ListsinearlierversionsofNetLogo(4.1and4.0)weresimplesingly-linkedlistsandthereforetheseoperationstooklineartime.
ThedatastructureunderlyingNetLogo’slistsnowistheimmutableVectorclassfromtheScalacollectionslibrary.Ituses32-
widehasharraymappedtries,asimplementedbyTiarkRompf,basedinpartonworkbyPhilBagwellandRichHickey.
Ifyouarecertainyouwanttouseraw,mutableJVMarraysinyourmodel,theyareprovidedbythearrayextension.Seethe
Arrays&TablessectionoftheUserManual.
DoesNetLogohavehashtablesorassociativearrays?
Yes,usingthetableextension.SeetheArrays&TablessectionoftheUserManual.
HowcanIusedifferentpatch“neighborhoods”(circular,VonNeumann,Moore,etc.)?
Thein-radiusprimitivesletsyouaccesscircularneighborhoodsofanyradius.
TheneighborsprimitivegivesyouaMooreneighborhoodofradius1,andtheneighbors4primitivegivesyouaVonNeumann
neighborhoodofradius1.
ForMooreorVonNeumannneighborhoodsofalargerradius,seeMoore&VonNeumannExampleintheCodeExamples
sectionoftheModelsLibrary.
HowcanIconvertanagentsettoalistofagents,orviceversa?
Ifyouwantthelistinaparticularorder,usethesortorsort-byprimitives.TheListssectionoftheProgrammingGuideexplains
howtodothis.SeealsoAskOrderingExample,intheCodeExamplessectionoftheModelsLibrary.
Ifyouwantthelistinarandomorder,here’show:
[self] of <agentset>
Becausealloperationsonagentsetsareinrandomorder,theresultinglistisinrandomorder.
Toconvertalistofagentstoanagentset,usetheturtle-set,patch-set,orlink-setprimitives.
HowdoIstopforeach?
Tostopaforeachfromexecutingyouneedtodefineaseparateprocedurethatcontainsonlytheforeach,forexample:
to test
foreach [1 2 3] [ i ->
if i = 2 [ stop ]
print i
]
end
Thiscodewillonlyprintthenumber1.Thestopreturnsfromthecurrentproceduresonothingaftertheforeachwillbeexecuted
either.(Iftheprocedureisareporterprocedure,usereportinsteadofstop.)
I’mtryingtomakealist.WhydoIkeepgettingtheerror“Expectedaconstant”?
Ifalistcontainsonlyconstants,youcanwriteitdownjustbyputtingsquarebracketsaroundit,like[1 2 3].
Ifyouwantyourlisttocontainitemsthatmayvaryatruntime,thelistcannotbewrittendowndirectly.Instead,youbuilditusing
thelistprimitive.
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?
Thisisnormalwhendoingmultiplerunsinparallel.Foradiscussionoftheissue,seethesectiononparallelrunsinthe
BehaviorSpaceGuidesectionoftheUserManual.
HowdoImeasurerunseverynticks?
Userepeatinyourexperiment’sgocommands,e.g.:
repeat 10 [ go ]
tomeasuretherunafterevery10ticks.Essentiallyyouaremakingoneexperimentstepequal10ticks.
I’mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn’twork.Why?
It’sprobablybecauseyoursetupcommandsorsetupprocedureareusingclear-all,causingthevaluessetbyBehaviorSpace
tobecleared.
Onepossibleworkaroundistochangeyourexperiment’ssetupcommandstopreservethevalueofthevariable,e.g.:
let old-var1 var1
setup
set var1 old-var1
Thisworksbecauseevenclear-alldoesn’tclearthevaluesoflocalvariablesmadewithlet
Anotherpossibleworkaroundistochangeyourmodel’ssetupproceduretousemorespecificclearingcommandstoclearonly
whatyouwantcleared.
NetLogo3D
DoesNetLogoworkwithmystereoscopicdevice?
NetLogosupportsfullscreenexclusivemode.Ifthatisallyourdeviceneedsthen,possiblyyes.However,itcanbetrickytogetit
working.Wedon’thaveanysuchdevicessoitisdifficultforustomaketheprocesseasier.Ifyourdeviceneedssomethingelse,
forexample,quadbuffersenabled,theanswerisprobablyno.
Extensions
I’mwritinganextension.Whydoesthecompilersayitcan’tfind org.nlogo.api?
YouneedtoaddNetLogo.jartoyourclasspathwhencompiling.NetLogo.jarisincludedwithNetLogo.
NetLogoDictionary
NetLogo6.0.4UserManual
Alphabetical:ABCDEFGHIJLMNOPRSTUVWXY->
Categories:Turtle-Patch-Links-Agentset-Color-AnonymousProcedures-Control/Logic-World
Perspective-Input/Output-File-List-String-Math-Plotting-System-HubNet
Special:Variables-Keywords-Constants
Categories
Thisisanapproximategrouping.Rememberthataturtle-relatedprimitivemightstillbeusedbypatchesortheobserver,andviceversa.To
seewhichagents(turtles,patches,links,observer)canactuallyrunaprimitive,consultitsdictionaryentry.
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
Controlflowandlogic
andaskask-concurrentcarefullyenderrorerror-messageeveryififelseifelse-valueletloopnotorrepeatreportrunrunresult;(semicolon)set
stopstartuptoto-reportwaitwhilewith-local-randomnesswithout-interruptionxor
AnonymousProcedures
->(anonymousprocedure)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
ArithmeticOperators(+,*,-,/,^,<,>,=,!=,<=,>=)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-InVariables
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
MathematicalConstants
e=2.718281828459045
pi=3.141592653589793
BooleanConstants
false
true
ColorConstants
Since1.0
Since1.3
Since4.0
Since1.0
Since2.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
SeetheColorssectionoftheProgrammingGuideformoredetails.
A
abs
absnumber
Reportstheabsolutevalueofnumber.
show abs -7
=> 7
show abs 5
=> 5
acos
acosnumber
Reportsthearccosine(inversecosine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesinthe
range0to180.
all?
all?agentset[reporter]
Reportstrueifalloftheagentsintheagentsetreporttrueforthegivenreporter.Otherwisereportsfalseassoonasacounterexampleis
found.
Iftheagentsetisempty,reportstrue.
Thereportermustreportabooleanvalueforeveryagent(eithertrueorfalse),otherwiseanerroroccurs.
if all? turtles [color = red]
[ show "every turtle is red!" ]
Seealsoany?.
and
condition1andcondition2
Reportstrueifbothcondition1andcondition2aretrue.
Notethatifcondition1isfalse,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) and (pycor > 0)
[ set pcolor blue ] ;; the upper-right quadrant of
;; patches turn blue
any?
any?agentset
Reportstrueifthegivenagentsetisnon-empty,falseotherwise.
Equivalentto"countagentset>0",butmoreefficient(andarguablymorereadable).
if any? turtles with [color = red]
[ show "at least one turtle is red!" ]
Note:nobodyisnotanagentset.Youonlygetnobodybackinsituationswhereyouwereexpectingasingleagent,notawholeagentset.If
Since4.0
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
any?getsnobodyasinput,anerrorresults.
Seealsoall?,nobody.
approximate-hsb
approximate-hsbhuesaturationbrightness
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheHSBspectrum,inNetLogo's
colorspace.
Thefirstvalue(hue)shouldbeintherangeof0to360,thesecondandthird(saturationandbrightness)intherangebetween0and100.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.
show approximate-hsb 0 0 0
=> 0 ;; (black)
show approximate-hsb 180 57.143 76.863
=> 85 ;; (cyan)
Seealsoextract-hsb,approximate-rgb,extract-rgb.
approximate-rgb
approximate-rgbredgreenblue
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheRGBspectrum,inNetLogo's
colorspace.
Allthreeinputsshouldbeintherange0to255.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.(Seeapproximate-hsb
foradescriptionofwhatpartsoftheHSBcolorspaceNetLogocolorscover;thisisdifficulttocharacterizeinRGBterms.)
show approximate-rgb 0 0 0
=> 0 ;; black
show approximate-rgb 0 255 255
=> 85.2 ;; cyan
Seealsoextract-rgb,approximate-hsb,andextract-hsb.
ArithmeticOperators
+
*
-
/
^
<
>
=
!=
<=
>=
Alloftheseoperatorstaketwoinputs,andallactas"infixoperators"(goingbetweenthetwoinputs,asinstandardmathematicaluse).
NetLogocorrectlysupportsorderofoperationsforinfixoperators.
Theoperatorsworkasfollows:+isaddition,*ismultiplication,-issubtraction,/isdivision,^isexponentiation,<islessthan,>isgreater
than,=isequalto,!=isnotequalto,<=islessthanorequal,>=isgreaterthanorequal.
Notethatthesubtractionoperator(-)alwaystakestwoinputsunlessyouputparenthesesaroundit,inwhichcaseitcantakeoneinput.For
example,totakethenegativeofx,write(-x),withtheparentheses.
Allofthecomparisonoperatorsalsoworkonstrings.
Allofthecomparisonoperatorsworkonagents.Turtlesarecomparedbywhonumber.Patchesarecomparedtoptobottomlefttoright,so
patch010islessthanpatch09andpatch90islessthanpatch100.Linksareorderedbyendpointsandincaseofatiebybreed.Solink
09isbeforelink110astheend1issmaller,andlink08islessthanlink09.Iftherearemultiplebreedsoflinksunbreededlinkswillcome
beforebreededlinksofthesameendpointsandbreededlinkswillbesortedintheordertheyaredeclaredintheCodetab.
Agentsetscanbetestedforequalityorinequality.Twoagentsetsareequaliftheyarethesametype(turtleorpatch)andcontainthesame
agents.
IfyouarenotsurehowNetLogowillinterpretyourcode,youshouldaddparentheses.
show 5 * 6 + 6 / 3
=> 32
show 5 * (6 + 6) / 3
=> 20
Manyextensionobjectsmaybetestedforequalityandinequalityusing=and!=.Forinstance,thearray,matrix,andtableobjectsreturnedby
theirrespectiveextensionsmaybecomparedforequality/inequality.Extensionobjectsmaynotbetestedusing<,>,<=,or>=.
Since1.3
Since1.0
Since4.0
Since1.0
Since1.0
asin
asinnumber
Reportsthearcsine(inversesine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesintherange
-90to90.
ask
askagentset[commands]
askagent[commands]
Thespecifiedagentoragentsetrunsthegivencommands.
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:onlytheobservercanaskallturtlesorallpatches.Thispreventsyoufrominadvertentlyhavingallturtlesaskallturtlesorallpatches
askallpatches,whichisacommonmistaketomakeifyou'renotcarefulaboutwhichagentswillrunthecodeyouarewriting.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
ask-concurrent
ask-concurrentagentset[commands]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitnewmodels.
Theagentsinthegivenagentsetrunthegivencommands,usingaturn-takingmechanismtoproducesimulatedconcurrency.SeetheAsk-
ConcurrentsectionoftheProgrammingGuidefordetailsonhowthisworks.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
Seealsowithout-interruption.
at-points
agentsetat-points[[x1y1][x2y2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesatthegivencoordinates(relativetothisagent).The
coordinatesarespecifiedasalistoftwo-itemlists,wherethetwoitemsarethexandyoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inotherwords,thepointsaretakenasabsolutepatch
coordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,andnotfromthecenterofthepatchundertheturtle.
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
atanxy
Convertsxandyoffsetstoaturtleheadingindegrees(from0to360).
NotethatthisversionofatanisdesignedtoconformtothegeometryoftheNetLogoworld,whereaheadingof0isstraightup,90istothe
right,andsoonclockwisearoundthecircle.(Normallyingeometryanangleof0isright,90isup,andsoon,counterclockwisearoundthe
circle,andatanwouldbedefinedaccordingly.)
Whenyis0:ifxispositive,itreports90;ifxisnegative,itreports270;ifxiszero,yougetanerror.
show atan 1 -1
=> 135
show atan -1 1
=> 315
crt 1 [ set heading 30 fd 1 print atan xcor ycor ]
=> 30
Inthefinalexample,notethattheresultofatanequalstheturtle'sheading.
Ifyoueverneedtoconvertaturtleheading(obtainedwithatanorotherwise)toanormalmathematicalangle,thefollowingshouldbehelpful:
to-report heading-to-angle [ h ]
report (90 - h) mod 360
end
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since4.0
Since2.1
Since5.2
Since4.1.1
autoplot?
autoplot?
Reportstrueifauto-plottingisonforthecurrentplot,falseotherwise.
auto-plot-off
auto-plot-on
auto-plot-off
auto-plot-on
ThispairofcommandsisusedtocontroltheNetLogofeatureofauto-plottinginthecurrentplot.Auto-plottingwillautomaticallyupdatethex
andyaxesoftheplotwheneverthecurrentpenexceedstheseboundaries.Itisusefulwhenwantingtoshowallplottedvaluesinthecurrent
plot,regardlessofthecurrentplotranges.
B
back
bk
backnumber
Theturtlemovesbackwardbynumbersteps.(Ifnumberisnegative,theturtlemovesforward.)
Turtlesusingthisprimitivecanmoveamaximumofoneunitpertimeincrement.Sobk 0.5andbk 1bothtakeoneunitoftime,butbk 3
takesthree.
Iftheturtlecannotmovebackwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof
1asitcanandstop.
Seealsoforward,jump,can-move?.
base-colors
base-colors
Reportsalistofthe14basicNetLogohues.
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
Emitsabeep.Notethatthebeepsoundsimmediately,soseveralbeepcommandsinclosesuccessionmayproduceonlyoneaudiblesound.
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
Whenrunningheadless,thiscommandhasnoeffect.
behaviorspace-experiment-name
behaviorspace-experiment-name
Reportsthecurrentexperimentnameinthecurrentexperiment.
IfnoBehaviorSpaceexperimentisrunning,reports"".
behaviorspace-run-number
behaviorspace-run-number
ReportsthecurrentrunnumberinthecurrentBehaviorSpaceexperiment,startingat1.
IfnoBehaviorSpaceexperimentisrunning,reports0.
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
both-ends
both-ends
Reportstheagentsetofthe2nodesconnectedbythislink.
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
Thisisabuilt-inturtleandlinkvariable.Itholdstheagentsetofallturtlesorlinksofthesamebreedasthisturtleorlink.(Forturtlesorlinks
thatdonothaveanyparticularbreed,thisistheturtlesagentsetofallturtlesorthelinksagentsetofalllinksrespectively.)
Youcansetthisvariabletochangeaturtleorlink'sbreed.(Whenaturtlechangesbreeds,itsshapeisresettothedefaultshapeforthat
breed.Seeset-default-shape.)
Seealsobreed,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>]
Thiskeyword,liketheglobals,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningoftheCodetab,beforeany
proceduredefinitions.Itdefinesabreed.Thefirstinputdefinesthenameoftheagentsetassociatedwiththebreed.Thesecondinputdefines
thenameofasinglememberofthebreed.
Anyturtleofthegivenbreed:
ispartoftheagentsetnamedbythebreedname
hasitsbreedbuilt-invariablesettothatagentset
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlytheturtlesofaparticularbreed.
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)
Seealsoglobals,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
Since3.1
Since2.1
Since1.0
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since5.2
Whenusedonalist,but-firstreportsallofthelistitemsoflistexceptthefirst,andbut-lastreportsallofthelistitemsoflistexceptthelast.
Onstrings,but-firstandbut-lastreportashorterstringomittingthefirstorlastcharacteroftheoriginalstring.
;; 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
Reportstrueifthisturtlecanmovedistanceinthedirectionitisfacingwithoutviolatingthetopology;reportsfalseotherwise.
Itisequivalentto:
patch-ahead distance != nobody
carefully
carefully[commands1][commands2]
Runscommands1.Ifaruntimeerroroccursinsidecommands1,NetLogowon'tstopandalerttheuserthatanerroroccurred.Itwillsuppress
theerrorandruncommands2instead.
Theerror-messagereportercanbeusedincommands2tofindoutwhaterrorwassuppressedincommands1.Seeerror-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
ceilingnumber
Reportsthesmallestintegergreaterthanorequaltonumber.
show ceiling 4.5
=> 5
show ceiling -4.5
=> -4
Seealsofloor,round,precision.
clear-all
ca
clear-all
Combinestheeffectsofclear-globals,clear-ticks,clear-turtles,clear-patches,clear-drawing,clear-all-plots,andclear-output.
clear-all-plots
clear-all-plots
Clearseveryplotinthemodel.Seeclear-plotformoreinformation.
clear-drawing
cd
clear-drawing
Clearsalllinesandstampsdrawnbyturtles.
clear-globals
Since4.0
Since1.0
Since1.0
Since1.0
Since5.0
Since1.0
Since1.0
clear-globals
Setsallglobalvariablesto0.
clear-links
clear-links
Killsalllinks.
Seealsodie.
clear-output
clear-output
Clearsalltextfromthemodel'soutputarea,ifithasone.Otherwisedoesnothing.
clear-patches
cp
clear-patches
Clearsthepatchesbyresettingallpatchvariablestotheirdefaultinitialvalues,includingsettingtheircolortoblack.
clear-plot
clear-plot
Inthecurrentplotonly,resetsallplotpens,deletesalltemporaryplotpens,resetstheplottoitsdefaultvalues(forxrange,yrange,etc.),and
resetsallpermanentplotpenstotheirdefaultvalues.ThedefaultvaluesfortheplotandforthepermanentplotpensaresetintheplotEdit
dialog,whichisdisplayedwhenyouedittheplot.Iftherearenoplotpensafterdeletingalltemporarypens,thatistosayifthereareno
permanentplotpens,adefaultplotpenwillbecreatedwiththefollowinginitialsettings:
Pen:down
Color:black
Mode:0(linemode)
Name:"default"
Interval:1
Seealsoclear-all-plots.
clear-ticks
clear-ticks
Clearsthetickcounter.
Doesnotsetthecountertozero.Afterthiscommandruns,thetickcounterhasnovalue.Attemptingtoaccessorupdateitisanerroruntil
reset-ticksiscalled.
Seealsoreset-ticks.
clear-turtles
ct
clear-turtles
Killsallturtles.
Alsoresetsthewhonumbering,sothenextturtlecreatedwillbeturtle0.
Seealsodie.
color
color
Thisisabuilt-inturtleorlinkvariable.Itholdsthecoloroftheturtleorlink.Youcansetthisvariabletomaketheturtleorlinkchangecolor.
ColorcanberepresentedeitherasaNetLogocolor(asinglenumber),oranRGBcolor(alistof3numbers).SeedetailsintheColorssection
oftheProgrammingGuide.
Since1.0
Since1.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Seealsopcolor.
cos
cosnumber
Reportsthecosineofthegivenangle.Assumestheangleisgivenindegrees.
show cos 180
=> -1
count
countagentset
Reportsthenumberofagentsinthegivenagentset.
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-turtlesnumber
create-ordered-turtlesnumber[commands]
create-ordered<breeds>number
create-ordered<breeds>number[commands]
Createsnumbernewturtles.Newturtlesstartatposition(0,0),arecreatedwiththe14primarycolors,andhaveheadingsfrom0to360,
evenlyspaced.
Ifthecreate-ordered-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,or
whatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
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>-toturtle
create-<breed>-toturtle[commands]
create-<breed>-fromturtle
create-<breed>-fromturtle[commands]
create-<breed>-withturtle
create-<breed>-withturtle[commands]
create-<breeds>-toturtleset
create-<breeds>-toturtleset[commands]
create-<breeds>-fromturtleset
create-<breeds>-fromturtleset[commands]
create-<breeds>-withturtleset
create-<breeds>-withturtleset[commands]
create-link-toturtle
create-link-toturtle[commands]
create-link-fromturtle
create-link-fromturtle[commands]
create-link-withturtle
create-link-withturtle[commands]
create-links-toturtleset
create-links-toturtleset[commands]
create-links-fromturtleset
create-links-fromturtleset[commands]
create-links-withturtleset
create-links-withturtleset[commands]
Since1.0
Since1.0
Since1.1
Usedforcreatingbreededandunbreededlinksbetweenturtles.
create-link-withcreatesanundirectedlinkbetweenthecallerandagent.create-link-tocreatesadirectedlinkfromthecallertoagent.
create-link-fromcreatesadirectedlinkfromagenttothecaller.
Whenthepluralformofthebreednameisused,anagentsetisexpectedinsteadofanagentandlinksarecreatedbetweenthecallerandall
agentsintheagentset.
Theoptionalcommandblockisthesetofcommandseachnewlyformedlinkruns.(Thelinksarecreatedallatoncethenrunoneatatime,in
randomorder.)
Anodecannotbelinkedtoitself.Also,youcannothavemorethanoneundirectedlinkofthesamebreedbetweenthesametwonodes,nor
canyouhavemorethanonedirectedlinkofthesamebreedgoinginthesamedirectionbetweentwonodes.
Ifyoutrytocreatealinkwhereone(ofthesamebreed)alreadyexists,nothinghappens.Ifyoutrytocreatealinkfromaturtletoitselfyouget
aruntimeerror.
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-turtlesnumber
create-turtlesnumber[commands]
create-<breeds>number
create-<breeds>number[commands]
Createsnumbernewturtlesattheorigin.Newturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe14primary
colors.
Ifthecreate-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,or
whatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
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
Seealsohatch,sprout.
create-temporary-plot-pen
create-temporary-plot-penstring
Anewtemporaryplotpenwiththegivennameiscreatedinthecurrentplotandsettobethecurrentpen.
Fewmodelswillwanttousethisprimitive,becausealltemporarypensdisappearwhenclear-plotorclear-all-plotsarecalled.Thenormalway
tomakeapenistomakeapermanentpenintheplot'sEditdialog.
Ifapenwiththatnamealreadyexistsinthecurrentplot,nonewpeniscreated,andtheexistingpenissettothecurrentpen.
Thenewtemporaryplotpenhasthefollowinginitialsettings:
Since3.0
Since1.0
Since1.0
Since1.0
Pen:down
Color:black
Mode:0(linemode)
Interval:1
See:clear-plot,clear-all-plots,andset-current-plot-pen.
D
date-and-time
date-and-time
Reportsastringcontainingthecurrentdateandtime.Theformatisshownbelow.Allfieldsarefixedwidth,sotheyarealwaysatthesame
locationsinthestring.Thepotentialresolutionoftheclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfrom
systemtosystem,dependingonthecapabilitiesoftheunderlyingJavaVirtualMachine.)
show date-and-time
=> "01:19:36.685 PM 19-Sep-2002"
die
die
Theturtleorlinkdies.
if xcor > 20 [ die ]
;; all turtles with xcor greater than 20 die
ask links with [color = blue] [ die ]
;; all the blue links will die
Adeadagentceasestoexist.Theeffectsofthisinclude:
Theagentwillnotexecuteanyfurthercode.Soifyouwriteask turtles [ die print "last words?" ] ,nolastwordswillbeprinted,
becausetheturtlesarealreadydeadbeforetheyhaveachancetoprintanything.
Theagentwilldisappearfromanyagentsetsitwasin,reducingthesizeofthoseagentsetsbyone.
Anyvariablethatwasstoringtheagentwillnowinsteadhavenobodyinit.Soforexamplelet x one-of turtles ask x [ die ] print x
printsnobody.
Ifthedeadagentwasaturtle,everylinkconnectedtoitalsodies.
Iftheobserverwaswatchingorfollowingtheagent,theobserver'sperspectiveresets,asifreset-perspectivehadbeenrun.
Seealso:clear-turtlesclear-links
diffuse
diffusepatch-variablenumber
Tellseachpatchtogiveequalsharesof(number*100)percentofthevalueofpatch-variabletoitseightneighboringpatches.number
shouldbebetween0and1.Regardlessoftopologythesumofpatch-variablewillbeconservedacrosstheworld.(Ifapatchhasfewerthan
eightneighbors,eachneighborstillgetsaneighthshare;thepatchkeepsanyleftovershares.)
Notethatthisisanobservercommandonly,eventhoughyoumightexpectittobeapatchcommand.(Thereasonisthatitactsonallthe
patchesatonce--patchcommandsactonindividualpatches.)
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
Likediffuse,butonlydiffusestothefourneighboringpatches(tothenorth,south,east,andwest),nottothediagonalneighbors.
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>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.It
Since1.0
Since1.0
Since1.0
definesadirectedlinkbreed.LinksofaparticularbreedarealwaysalldirectedorallundirectedThefirstinputdefinesthenameofthe
agentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.Directedlinkscanbecreated
usingcreate-link(s)-to,andcreate-link(s)-from,butnotcreate-link(s)-with
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreedname
hasitsbuilt-invariablebreedsettothatagentset
isdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
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)
Seealsobreed,undirected-link-breed
display
display
Causestheviewtobeupdatedimmediately.(Exception:iftheuserisusingthespeedslidertofast-forwardthemodel,thentheupdatemay
beskipped.)
Alsoundoestheeffectoftheno-displaycommand,sothatifviewupdatesweresuspendedbythatcommand,theywillresume.
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
Evenifno-displaywasnotused,"display"canstillbeuseful,becauseordinarilyNetLogoisfreetoskipsomeviewupdates,sothatfewer
totalupdatestakeplace,sothatmodelsrunfaster.Thiscommandletsyouforceaviewupdate,sowhateverchangeshavetakenplaceinthe
worldarevisibletotheuser.
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
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsono-display.
distance
distanceagent
Reportsthedistancefromthisagenttothegiventurtleorpatch.
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedges
oftheworld)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
ask turtles [ show max-one-of turtles [distance myself] ]
;; each turtle prints the turtle farthest from itself
distancexy
distancexyxy
Reportsthedistancefromthisagenttothepoint(x,y).
Thedistancefromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedgesofthe
world)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
if (distancexy 0 0) > 10
[ set color green ]
;; all turtles more than 10 units from
;; the center of the world turn green.
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since4.0
Since4.0
downhill
downhill4
downhillpatch-variable
downhill4patch-variable
Movestheturtletotheneighboringpatchwiththelowestvalueforpatch-variable.Ifnoneighboringpatchhasasmallervaluethanthe
currentpatch,theturtlestaysput.Iftherearemultiplepatcheswiththesamelowestvalue,theturtlepicksonerandomly.Non-numeric
valuesareignored.
downhillconsiderstheeightneighboringpatches;downhill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
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
]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(downhill)or90(downhill4).
Seealsouphill,uphill4.
dx
dy
dx
dy
Reportsthex-incrementory-increment(theamountbywhichtheturtle'sxcororycorwouldchange)iftheturtleweretotakeonestep
forwardinitscurrentheading.
Note:dxissimplythesineoftheturtle'sheading,anddyissimplythecosine.(Ifthisisthereverseofwhatyouexpected,it'sbecausein
NetLogoaheadingof0isnorthand90iseast,whichisthereverseofhowanglesareusuallydefinedingeometry.)
Note:InearlierversionsofNetLogo,theseprimitiveswereusedinmanysituationswherethenewpatch-aheadprimitiveisnowmore
appropriate.
E
empty?
empty?list
empty?string
Reportstrueifthegivenlistorstringisempty,falseotherwise.
Note:theemptylistiswritten[].Theemptystringiswritten"".
end
end
Usedtoconcludeaprocedure.Seetoandto-report.
end1
end1
Thisisabuilt-inlinkvariable.Itindicatesthefirstendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethesourceforundirectedlinks
itwillalwaysbetheturtlewiththelowerwhonumber.Youcannotsetend1.
crt 2
ask turtle 0
[ create-link-to turtle 1 ]
ask links
[ show end1 ] ;; shows turtle 0
end2
end2
Thisisabuilt-inlinkvariable.Itindicatesthesecondendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethedestinationfor
undirectedlinksitwillalwaysbetheturtlewiththehigherwhonumber.Youcannotsetend2.
Since5.0
Since2.1
Since1.0
Since1.0
Since3.0
Since2.0
Since1.0
Since1.0
Since1.2.1
Since1.0
crt 2
ask turtle 1
[ create-link-with turtle 0 ]
ask links
[ show end2 ] ;; shows turtle 1
error
errorvalue
Causesaruntimeerrortooccur.
Thegivenvalueisconvertedtoastring(ifitisn'tonealready)andusedastheerrormessage.
Seealsoerror-message,carefully.
error-message
error-message
Reportsastringdescribingtheerrorthatwassuppressedbycarefully.
Thisreportercanonlybeusedinthesecondblockofacarefullycommand.
Seealsoerror,carefully.
every
everynumber[commands]
Runsthegivencommandsonlyifit'sbeenmorethannumbersecondssincethelasttimethisagentrantheminthiscontext.Otherwise,the
commandsareskipped.
Byitself,everydoesn'tmakecommandsrunoverandoveragain.Youneedtouseeveryinsidealoop,orinsideaforeverbutton,ifyouwant
thecommandsrunoverandoveragain.everyonlylimitshowoftenthecommandsrun.
Above,"inthiscontext"meansduringthesameask(orbuttonpressorcommandtypedintheCommandCenter).Soitdoesn'tmakesense
towriteask turtles [ every 0.5 [ ... ] ],becausewhentheaskfinishestheturtleswillalldiscardtheirtimersforthe"every".Thecorrect
usageisshownbelow.
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
Seealsowait.
exp
expnumber
Reportsthevalueoferaisedtothenumberpower.
Note:Thisisthesamease^number.
export-view
export-interface
export-output
export-plot
export-all-plots
export-world
export-viewfilename
export-interfacefilename
export-outputfilename
export-plotplotnamefilename
export-all-plotsfilename
export-worldfilename
export-viewwritesthecurrentcontentsofthecurrentviewtoanexternalfilegivenbythestringfilename.ThefileissavedinPNG(Portable
NetworkGraphics)format,soitisrecommendedtosupplyafilenameendingin".png".
export-interfaceissimilar,butforthewholeinterfacetab.
Notethatexport-viewstillworkswhenrunningNetLogoinheadlessmode,butexport-interfacedoesn't.
export-outputwritesthecontentsofthemodel'soutputareatoanexternalfilegivenbythestringfilename.(Ifthemodeldoesnothavea
separateoutputarea,theoutputportionoftheCommandCenterisused.)
export-plotwritesthexandyvaluesofallpointsplottedbyalltheplotpensintheplotgivenbythestringplotnametoanexternalfilegivenby
thestringfilename.Ifapenisinbarmode(mode0)andtheyvalueofthepointplottedisgreaterthan0,theupper-leftcornerpointofthebar
Since1.0
Since1.0
Since3.0
willbeexported.Iftheyvalueislessthan0,thenthelower-leftcornerpointofthebarwillbeexported.
export-all-plotswriteseveryplotinthecurrentmodeltoanexternalfilegivenbythestringfilename.Eachplotisidenticalinformattothe
outputofexport-plot.
export-worldwritesthevaluesofallvariables,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,thedrawing,
thecontentsoftheoutputareaifoneexists,thecontentsofanyplotsandthestateoftherandomnumbergenerator,toanexternalfilegiven
bythestringfilename.(TheresultfilecanbereadbackintoNetLogowiththeimport-worldprimitive.)export-worlddoesnotsavethestateof
openfiles.
export-plot,export-all-plotsandexport-worldsavefilesininplain-text,"comma-separatedvalues"(.csv)format.CSVfilescanbereadby
mostpopularspreadsheetanddatabaseprogramsaswellasanytexteditor.
Ifyouwishtoexporttoafileinalocationotherthanthemodel'slocation,youshouldincludethefullpathtothefileyouwishtoexport.(Use
theforward-slash"/"asthefolderseparator.)
NotethatthefunctionalityoftheseprimitivesisalsoavailabledirectlyfromNetLogo'sFilemenu.
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
Ifthefilealreadyexists,itisoverwritten.Toavoidthisyoumaywishtousesomemethodofgeneratingfreshnames.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...]
Allowsthemodeltouseprimitivesfromtheextensionswiththegivennames.SeetheExtensionsguideformoreinformation.
extract-hsb
extract-hsbcolor
Reportsalistofthreevalues,thefirst(hue)intherangeof0to360,thesecondandthird(brightnessandsaturation)intherangeof0to100.
ThegivencolorcaneitherbeaNetLogocolorintherange0to140,notincluding140itself,oranRGBlistofthreevaluesintherange0to
255representingthelevelsofred,green,andblue.
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]
Seealsoapproximate-hsb,approximate-rgb,extract-rgb.
extract-rgb
extract-rgbcolor
Reportsalistofthreevaluesintherange0to255representingthelevelsofred,green,andblue,respectively,ofthegivenNetLogocolorin
therange0to140,notincluding140itself.
show extract-rgb red
=> [215 50 41]
show extract-rgb cyan
=> [84 196 196]
Seealsoapproximate-rgb,approximate-hsb,extract-hsb.
F
face
faceagent
Setthecaller'sheadingtowardsagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,facewillusethewrappedpath.
Since3.0
Since2.0
Since2.0
Since2.0
Since2.0
Since2.0
Since4.0
Ifthecallerandtheagentareattheexactsameposition,thecaller'sheadingwon'tchange.
facexy
facexyxy
Setthecaller'sheadingtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorterandwrappingisallowed,facexy
willusethewrappedpath.
Ifthecallerisonthepoint(x,y),thecaller'sheadingwon'tchange.
file-at-end?
file-at-end?
Reportstruewhentherearenomorecharacterslefttoreadinfromthecurrentfile(thatwasopenedpreviouslywithfile-open).Otherwise,
reportsfalse.
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
Seealsofile-open,file-close-all.
file-close
file-close
Closesafilethathasbeenopenedpreviouslywithfile-open.
Notethatthisandfile-close-allaretheonlywaystorestarttothebeginningofanopenedfileortoswitchbetweenfilemodes.
Ifnofileisopen,doesnothing.
Seealsofile-close-all,file-open.
file-close-all
file-close-all
Closesallfiles(ifany)thathavebeenopenedpreviouslywithfile-open.
Seealsofile-close,file-open.
file-delete
file-deletestring
Deletesthefilespecifiedasstring
stringmustbeanexistingfilewithwritablepermissionbytheuser.Also,thefilecannotbeopen.Usethecommandfile-closetoclosean
openedfilebeforedeletion.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
file-exists?
file-exists?string
Reportstrueifstringisthenameofanexistingfileonthesystem.Otherwiseitreportsfalse.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itdefaultstotothemodel'sdirectory.
file-flush
file-flush
Forcesfileupdatestobewrittentodisk.Whenyouusefile-writeorotheroutputcommands,thevaluesmaynotbeimmediatelywrittento
disk.Thisimprovestheperformanceofthefileoutputcommands.Closingafileensuresthatalloutputiswrittentodisk.
Sometimesyouneedtoensurethatdataiswrittentodiskwithoutclosingthefile.Forexample,youcouldbeusingafiletocommunicatewith
anotherprogramonyourmachineandwanttheotherprogramtobeabletoseetheoutputimmediately.
Since2.0
Since2.0
Since2.0
Since2.0
file-open
file-openstring
Thiscommandwillinterpretstringasapathnametoafileandopenthefile.Youmaythenusethereportersfile-read,file-read-line,andfile-
read-characterstoreadinfromthefile,orfile-write,file-print,file-type,orfile-showtowriteouttothefile.
Notethatyoucanonlyopenafileforreadingorwritingbutnotboth.Thenextfilei/oprimitiveyouuseafterthiscommanddictateswhich
modethefileisopenedin.Toswitchmodes,youneedtoclosethefileusingfile-close.
Also,thefilemustalreadyexistifopeningafileinreadingmode.
Whenopeningafileinwritingmode,allnewdatawillbeappendedtotheendoftheoriginalfile.Ifthereisnooriginalfile,anewblankfilewill
becreatedinitsplace.(Youmusthavewritepermissioninthefile'sdirectory.)(Ifyoudon'twanttoappend,butwanttoreplacethefile's
existingcontents,usefile-deletetodeleteitfirst,perhapsinsideacarefullyifyou'renotsurewhetheritalreadyexists.)
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscan
bechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
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
Openingafiledoesnotclosepreviouslyopenedfiles.Youcanusefile-opentoswitchbackandforthbetweenmultipleopenfiles.
Seealsofile-closeSeealsofile-close-all.
file-print
file-printvalue
Printsvaluetoanopenedfile,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikefile-show.
Notethatthiscommandisthefilei/oequivalentofprint,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-show,file-type,file-write,andOutput(programmingguide).
file-read
file-read
ThisreporterwillreadinthenextconstantfromtheopenedfileandinterpretitasifithadbeentypedintheCommandCenter.Itreportsthe
resultingvalue.Theresultmaybeanumber,list,string,boolean,orthespecialvaluenobody.
Whitespaceseparatestheconstants.Eachcalltofile-readwillskippastbothleadingandtrailingwhitespace.
Notethatstringsneedtohavequotesaroundthem.Usethecommandfile-writetohavequotesincluded.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
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
Seealsofile-openandfile-write.
file-read-characters
file-read-charactersnumber
Reportsthegivennumberofcharactersfromanopenedfileasastring.Iftherearefewerthanthatmanycharactersleft,itwillreportallofthe
remainingcharacters.
Notethatitwillreturneverycharacterincludingnewlinesandspaces.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"
print file-read-characters 5
;; Current line in file is "Hello World"
=> Hello
Seealsofile-open.
Since2.0
Since2.0
Since2.0
Since2.0
Since1.3
Since1.0
file-read-line
file-read-line
Readsthenextlineinthefileandreportsitasastring.Itdeterminestheendofthefilebyacarriagereturn,anendoffilecharacterorbothin
arow.Itdoesnotreturnthelineterminatorcharacters.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethe
reporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"
print file-read-line
=> Hello World
Seealsofile-open.
file-show
file-showvalue
Printsvaluetoanopenedfile,precededbythisagentagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrack
ofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartofile-write.
Notethatthiscommandisthefilei/oequivalentofshow,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-type,file-write,andOutput(programmingguide).
file-type
file-typevalue
Printsvaluetoanopenedfile,notfollowedbyacarriagereturn(unlikefile-printandfile-show).Thelackofacarriagereturnallowsyoutoprint
severalvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikefile-show.
Notethatthiscommandisthefilei/oequivalentoftype,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-show,file-write,andOutput(programmingguide).
file-write
file-writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytoanopenedfile,notfollowedbyacarriagereturn
(unlikefile-printandfile-show).
Thisagentisnotprintedbeforethevalue,unlikefile-show.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.It
willoutputthevalueinsuchamannerthatfile-readwillbeabletointerpretit.
Notethatthiscommandisthefilei/oequivalentofwrite,andfile-openneedstobecalledbeforethiscommandcanbeused.
file-open "locations.txt"
ask turtles
[ file-write xcor file-write ycor ]
Seealsofile-print,file-show,file-type,andOutput(programmingguide).
filter
filterreporterlist
Reportsalistcontainingonlythoseitemsoflistforwhichthereporterreportstrue--inotherwords,theitemssatisfyingthegivencondition.
reportermaybeananonymousreporterorthenameofareporter.
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"]
Seealsomap,reduce,->(anonymousprocedure).
first
firstlist
firststring
Onalist,reportsthefirst(0th)iteminthelist.
Since1.0
Since3.0
Since3.0
Since1.3
Since1.0
Since1.0
Onastring,reportsaone-characterstringcontainingonlythefirstcharacteroftheoriginalstring.
floor
floornumber
Reportsthelargestintegerlessthanorequaltonumber.
show floor 4.5
=> 4
show floor -4.5
=> -5
Seealsoceiling,round,precision.
follow
followturtle
Similartoride,but,inthe3Dview,theobserver'svantagepointisbehindandaboveturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollowwillalterthehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingthefollowedturtleinstead.
Seealsofollow-me,ride,reset-perspective,watch,subject.
follow-me
follow-me
Askstheobservertofollowthisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollow-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-
me,highlightingthisturtleinstead.
Seealsofollow.
foreach
foreachlistcommand
(foreachlist1...command)
Withasinglelist,runsthecommandforeachitemoflist.commandmaybethenameofacommand,orananonymouscommandcreated
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
Withmultiplelists,runscommandforeachgroupofitemsfromeachlist.So,theyarerunonceforthefirstitems,oncefortheseconditems,
andsoon.Allthelistsmustbethesamelength.
Someexamplesmakethisclearer:
(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
Seealsomap,->(anonymousprocedure).
forward
fd
forwardnumber
Theturtlemovesforwardbynumbersteps,onestepatatime.(Ifnumberisnegative,theturtlemovesbackward.)
fd 10isequivalenttorepeat 10 [ jump 1 ] .fd 10.5isequivalenttorepeat 10 [ jump 1 ] jump 0.5.
Iftheturtlecannotmoveforwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof1
Since1.0
Since1.0
asitcan,thenstop.
Seealsojump,can-move?.
fput
fputitemlist
Addsitemtothebeginningofalistandreportsthenewlist.
;; suppose mylist is [5 7 10]
set mylist fput 2 mylist
;; mylist is now [2 5 7 10]
G
globals
globals[var1...]
Thiskeyword,likethebreed,<breeds>-own,patches-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,before
anyfunctiondefinitions.Itdefinesnewglobalvariables.Globalvariablesare"global"becausetheyareaccessiblebyallagentsandcanbe
usedanywhereinamodel.
Mostoften,globalsisusedtodefinevariablesorconstantsthatneedtobeusedinmanypartsoftheprogram.
H
hatch
hatchnumber[commands]
hatch-<breeds>number[commands]
Thisturtlecreatesnumbernewturtles.Eachnewturtleinheritsofallitsvariables,includingitslocation,fromitsparent.(Exceptions:each
newturtlewillhaveanewwhonumber,anditmaybeofadifferentbreedthanitsparentifthehatch-<breeds>formisused.)
Thenewturtlesthenruncommands.Youcanusethecommandstogivethenewturtlesdifferentcolors,headings,locations,orwhatever.
(Thenewturtlesarecreatedallatonce,thenrunoneatatime,inrandomorder.)
Ifthehatch-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.Otherwise,thenewturtlesarethesame
breedastheirparent.
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
Seealsocreate-turtles,sprout.
heading
heading
Thisisabuilt-inturtlevariable.Itindicatesthedirectiontheturtleisfacing.Thisisanumbergreaterthanorequalto0andlessthan360.0is
north,90iseast,andsoon.Youcansetthisvariabletomakeaturtleturn.
Seealsoright,left,dx,dy.
Example:
set heading 45 ;; turtle is now facing northeast
set heading heading + 10 ;; same effect as "rt 10"
hidden?
hidden?
Thisisabuilt-inturtleorlinkvariable.Itholdsaboolean(trueorfalse)valueindicatingwhethertheturtleorlinkiscurrentlyhidden(i.e.,
invisible).Youcansetthisvariabletomakeaturtleorlinkdisappearorreappear.
Seealsohide-turtle,show-turtle,hide-link,show-link
Example:
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.1
Since4.1
set hidden? not hidden?
;; if turtle was showing, it hides, and if it was hiding,
;; it reappears
hide-link
hide-link
Thelinkmakesitselfinvisible.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"totrue.
Seealsoshow-link.
hide-turtle
ht
hide-turtle
Theturtlemakesitselfinvisible.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"totrue.
Seealsoshow-turtle.
histogram
histogramlist
Histogramsthevaluesinthegivenlist
Drawsahistogramshowingthefrequencydistributionofthevaluesinthelist.Theheightsofthebarsinthehistogramrepresentthe
numbersofvaluesineachsubrange.
Beforethehistogramisdrawn,firstanypreviouspointsdrawnbythecurrentplotpenareremoved.
Anynon-numericvaluesinthelistareignored.
Thehistogramisdrawnonthecurrentplotusingthecurrentplotpenandpencolor.Autoscalingdoesnotaffectahistogram'shorizontal
range,soset-plot-x-rangeshouldbeusedtocontroltherange,andthepenintervalcanthenbeset(eitherdirectlywithset-plot-pen-interval,
orindirectlyviaset-histogram-num-bars)tocontrolhowmanybarsthatrangeissplitupinto.
Besurethatifyouwantthehistogramdrawnwithbarsthatthecurrentpenisinbarmode(mode1).
Forhistogrammingpurposestheplot'sXrangeisnotconsideredtoincludethemaximumXvalue.ValuesequaltothemaximumXwillfall
outsideofthehistogram'srange.
histogram [color] of turtles
;; draws a histogram showing how many turtles there are
;; of each color
home
home
Thisturtlemovestotheorigin(0,0).Equivalenttosetxy 0 0.
hsb
hsbhuesaturationbrightness
ReportsaRGBlistwhengiventhreenumbersdescribinganHSBcolor.Hue,saturation,andbrightnessareintegersintherange0-360,0-
100,0-100respectively.TheRGBlistcontainsthreeintegersintherangeof0-255.
Seealsorgb
hubnet-broadcast
hubnet-broadcasttag-namevalue
ThisbroadcastsvaluefromNetLogototheinterfaceelementwiththenametag-nameontheclients.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-broadcast-clear-output
Since4.1
Since4.1
Since4.1
Since5.0
Since1.2.1
Since1.2.1
Since1.1
Since5.0
Since5.0
Since1.1
hubnet-broadcast-clear-output
Thisclearsallmessagesprintedtothetextareaoneveryclient.
Seealso:hubnet-broadcast-message,hubnet-send-clear-output
hubnet-broadcast-message
hubnet-broadcast-messagevalue
Thisprintsthevalueinthetextareaoneachclient.Thisisthesamefunctionalityasthe"BroadcastMessage"buttonintheHubNetControl
Center.
Seealso:hubnet-send-message
hubnet-clear-override
hubnet-clear-overrides
hubnet-clear-overrideclientagent-or-setvariable-name
hubnet-clear-overridesclient
Removeoverridesfromtheoverridelistonclient.hubnet-clear-overrideremovesonlytheoverrideforthespecifiedvariableforthespecified
agentoragentset.hubnet-clear-overridesremovesalloverridesfromthespecifiedclient.
Seealso:hubnet-send-override
hubnet-clients-list
hubnet-clients-list
ReportsalistcontainingthenamesofalltheclientscurrentlyconnectedtotheHubNetserver.
hubnet-enter-message?
hubnet-enter-message?
Reportstrueifanewclientjustenteredthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameofthe
clientthatjustloggedon.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-exit-message?
hubnet-exit-message?
Reportstrueifaclientjustexitedthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameoftheclientthat
justloggedoff.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-fetch-message
hubnet-fetch-message
Ifthereisanynewdatasentbytheclients,thisretrievesthenextpieceofdata,sothatitcanbeaccessedbyhubnet-message,hubnet-
message-source,andhubnet-message-tag.Thiswillcauseanerrorifthereisnonewdatafromtheclients.
SeetheHubNetAuthoringGuidefordetails.
hubnet-kick-client
hubnet-kick-clientclient-name
Kickstheclientwiththegivenclient-name.ThisisequivalenttoclickingtheclientnameintheHubNetControlCenterandpressingtheKick
button.
hubnet-kick-all-clients
hubnet-kick-all-clients
KicksoutallcurrentlyconnectedHubNetclients.ThisisequivalenttoselectingallclientsintheHubNetControlCenterandpressingtheKick
button.
hubnet-message
hubnet-message
Since1.1
Since1.1
Since1.1
Since1.1
Since4.1
Since1.1
Since4.1
Since4.1
Reportsthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-source
hubnet-message-source
Reportsthenameoftheclientthatsentthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-tag
hubnet-message-tag
Reportsthetagthatisassociatedwiththedatathatwasretrievedbyhubnet-fetch-message.ThetagwillbeoneoftheDisplayNamesofthe
interfaceelementsintheclientinterface.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-waiting?
hubnet-message-waiting?
Thislooksforanewmessagesentbytheclients.Itreportstrueifthereisone,andfalseifthereisnot.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset
hubnet-reset
StartsuptheHubNetsystem.HubNetmustbestartedtouseanyoftheotherhubnetprimitives.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset-perspective
hubnet-reset-perspectivetag-name
Clearswatchorfollowsentdirectlytotheclient.Theviewperspectivewillreverttotheserverperspective.
Seealso:hubnet-send-watchhubnet-send-follow
hubnet-send
hubnet-sendstringtag-namevalue
hubnet-sendlist-of-stringstag-namevalue
Forastring,thissendsvaluefromNetLogotothetagtag-nameontheclientthathasstringforitsusername.
Foralist-of-strings,thissendsvaluefromNetLogotothetagtag-nameonalltheclientsthathaveausernamethatisinthelist-of-strings.
Sendingamessagetoanon-existentclient,usinghubnet-send,generatesahubnet-exit-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-send-clear-output
hubnet-send-clear-outputstring
hubnet-send-clear-outputlist-of-strings
Thisclearsallmessagesprintedtothetextareaonthegivenclientorclients(specifiedinthestringorlist-of-strings.
Seealso:hubnet-send-message,hubnet-broadcast-clear-output
hubnet-send-follow
hubnet-send-followclient-nameagentradius
Tellstheclientassociatedwithclient-nametofollowagentshowingaradiussizedMooreneighborhoodaroundtheagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-followwillalterthehighlightcreatedbypriorcallstohubnet-send-
watch,highlightingthefollowedagentinstead.
Seealso:hubnet-send-watch,hubnet-reset-perspective
Since4.1
Since4.1
Since4.1
Since1.0
Since1.0
Since2.0
hubnet-send-message
hubnet-send-messagestringvalue
Thisprintsvalueinthetextareaontheclientspecifiedbystring.
Seealso:hubnet-broadcast-message
hubnet-send-override
hubnet-send-overrideclient-nameagent-or-setvariable-name
[reporter]
Evaluatesreporterfortheagentoragentsetindicatedthensendsthevaluestotheclientto"override"thevalueofvariable-nameonlyon
client-name.Thisisusedtochangetheappearanceofagentsintheclientview,hence,onlybuilt-invariablesthataffecttheappearanceof
theagentmaybeselected.Forexample,youcanoverridethecolorvariableofaturtle:
ask turtles [ hubnet-send-override client-name self "color" [ red ] ]
Inthisexampleassumethatthereisaturtles-ownvariableclient-namewhichisassociatedwithaloggedinclient,andalltheturtlesareblue.
Thiscodemakestheturtleassociatedwitheachclientappearredinhisorherownviewbutnotonanyoneelse'sorontheserver.
Seealso:hubnet-clear-overrides
hubnet-send-watch
hubnet-send-watchclient-nameagent
Tellstheclientassociatedwithclient-nametowatchagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-watchwillundoperspectivechangescausedbypriorcallstohubnet-
send-follow.
Seealso:hubnet-send-follow,hubnet-reset-perspective
I
if
ifcondition[commands]
Reportermustreportaboolean(trueorfalse)value.
Ifconditionreportstrue,runscommands.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommandsandothersdon't.
if xcor > 0[ set color blue ]
;; turtles in the right half of the world
;; turn blue
Seealsoifelse,ifelse-value.
ifelse
ifelsereporter[commands1][commands2]
Reportermustreportaboolean(trueorfalse)value.
Ifreporterreportstrue,runscommands1.
Ifreporterreportsfalse,runscommands2.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommands1whileothersruncommands2.
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
Seealsoif,ifelse-value.
ifelse-value
ifelse-valuereporter[reporter1][reporter2]
Reportermustreportaboolean(trueorfalse)value.
Since3.0
Since3.0
Since4.0
Since1.0
Since3.0
Ifreporterreportstrue,theresultisthevalueofreporter1.
Ifreporterreportsfalse,theresultisthevalueofreporter2.
Thiscanbeusedwhenaconditionalisneededinthecontextofareporter,wherecommands(suchasifelse)arenotallowed.
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
Seealsoif,ifelse.
import-drawing
import-drawingfilename
Readsanimagefileintothedrawing,scalingittothesizeoftheworld,whileretainingtheoriginalaspectratiooftheimage.Theimageis
centeredinthedrawing.Theolddrawingisnotclearedfirst.
Agentscannotsensethedrawing,sotheycannotinteractwithorprocessimagesimportedbyimport-drawing.Ifyouneedagentstosensean
image,useimport-pcolorsorimport-pcolors-rgb.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),that
informationwillbeimportedaswell.
import-pcolors
import-pcolorsfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransfers
theresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Theresultingpatchcolorsmaybedistorted,sincethe
NetLogocolorspacedoesnotincludeallpossiblecolors.(SeetheColorsectionoftheProgrammingGuide.)import-pcolorsmaybeslowfor
someimages,particularlywhenyouhavemanypatchesandalargeimagewithmanydifferentcolors.
Sinceimport-pcolorssetsthepcolorofpatches,agentscansensetheimage.Thisisusefulifagentsneedtoanalyze,process,orotherwise
interactwiththeimage.Ifyouwanttosimplydisplayastaticbackdrop,withoutcolordistortion,seeimport-drawing.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfully
transparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-pcolors-rgb
import-pcolors-rgbfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransfers
theresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Unlikeimport-pcolorstheexactcolorsintheoriginalimage
areretained.ThepcolorvariableofallthepatcheswillbeanRGBlistratherthanan(approximated)NetLogocolor.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfully
transparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-world
import-worldfilename
Readsthevaluesofallvariablesforamodel,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,froman
externalfilenamedbythegivenstring.Thefileshouldbeintheformatusedbytheexport-worldprimitive.
NotethatthefunctionalityofthisprimitiveisalsodirectlyavailablefromNetLogo'sFilemenu.
Whenusingimport-world,toavoiderrors,performthesestepsinthefollowingorder:
1. Openthemodelfromwhichyoucreatedtheexportfile.
2. PresstheSetupbutton,togetthemodelinastatefromwhichitcanberun.
3. Importthefile.
4. Re-openanyfilesthatthemodelhadopenedwiththefile-opencommand.
5. Ifyouwant,pressGobuttontocontinuerunningthemodelfromthepointwhereitleftoff.
Ifyouwishtoimportafilefromalocationotherthanthemodel'slocation,youmayincludethefullpathtothefileyouwishtoimport.See
export-worldforanexample.
in-cone
Since4.0
Since4.0
Since4.0
Since4.0
agentsetin-conedistanceangle
Thisreporterletsyougiveaturtlea"coneofvision"infrontofitself.Theconeisdefinedbythetwoinputs,thevisiondistance(radius)and
theviewingangle.Theviewinganglemayrangefrom0to360andiscenteredaroundtheturtle'scurrentheading.(Iftheangleis360,then
in-coneisequivalenttoin-radius.)
in-conereportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetthatfallinthecone.(Thiscanincludetheagentitself.)
Thedistancetoapatchismeasuredfromthecenterofthepatch.
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
Reportstrueifthereisadirectedlinkgoingfromturtletothecalleroranundirectedlinkconnectingturtletothecaller.Youcanthinkofthisas
"istherealinkIcanusetogetfromturtletothecaller?"
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
Reportstheagentsetofalltheturtlesthathavedirectedlinkscomingfromthemtothecalleraswellasallturtlesthathaveanundirectedlink
connectingthemwiththecaller.Youcanthinkofthisas"alltheturtlesthatcangettothecallerusingalink."
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>-fromturtle
in-link-fromturtle
Reportsadirectedlinkfromturtletothecalleroranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromturtletothecaller."
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
Seealso:out-link-tolink-with
__includes
__includes[filename...]
CausesexternalNetLogosourcefiles(withthe.nlssuffix)tobeincludedinthismodel.Includedfilesmaycontainbreed,variable,and
proceduredefinitions.__includescanonlybeusedonceperfile.
Thefilenamesmustbestrings,forexample:
__includes [ "utils.nls" ]
Or,formultiplefiles:
Since1.0
Since6.0.2
Since1.1
Since1.0
Since1.2.1
Since1.2.1
Since6.0
Since6.0
Since1.2.1
Since4.0
Since4.0
Since4.0
Since1.0
Since1.2.1
Since1.2.1
Since4.0
Since1.0
Since1.2.1
Since4.0
Since4.0
__includes [ "utils1.nls" "utils2.nls" ]
in-radius
agentsetin-radiusnumber
Reportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetwhosedistancefromthecallerislessthanorequalto
number.(Thiscanincludetheagentitself.)
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.
ask turtles
[ ask patches in-radius 3
[ set pcolor red ] ]
;; each turtle makes a red "splotch" around itself
insert-item
insert-itemindexlistvalue
insert-itemindexstring1string2
Onalist,insertsaniteminthatlist.indexistheindexwheretheitemwillbeinserted.Thefirstitemhasanindexof0.(The6thiteminalist
wouldhaveanindexof5.)
Likewiseforastring,butallcharactersinamultiple-characterstring2areinsertedatindex.
show insert-item 2 [2 7 4 5] 15
=> [2 7 15 4 5]
show insert-item 2 "cat" "re"
=> "caret"
inspect
inspectagent
Opensanagentmonitorforthegivenagent(turtleorpatch).
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
Seestop-inspectingandstop-inspecting-dead-agents
int
intnumber
Reportstheintegerpartofnumber--anyfractionalpartisdiscarded.
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
Since1.0
Since1.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
Reportstrueifvalueisofthegiventype,falseotherwise.
item
itemindexlist
itemindexstring
Onlists,reportsthevalueoftheiteminthegivenlistwiththegivenindex.
Onstrings,reportsthecharacterinthegivenstringatthegivenindex.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
;; suppose mylist is [2 4 6 8 10]
show item 2 mylist
=> 6
show item 3 "my-shoe"
=> "s"
J
jump
jumpnumber
Theturtlemovesforwardbynumberunitsallatonce(ratherthanonestepatatimeaswiththeforwardcommand).
Iftheturtlecannotjumpnumberunitsbecauseitisnotpermittedbythecurrenttopologytheturtledoesnotmoveatall.
Seealsoforward,can-move?.
L
label
label
Thisisabuilt-inturtleorlinkvariable.Itmayholdavalueofanytype.Theturtleorlinkappearsintheviewwiththegivenvalue"attached"to
itastext.Youcansetthisvariabletoadd,change,orremoveaturtleorlink'slabel.
Seealsolabel-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
Thisisabuilt-inturtleorlinkvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolorthe
turtleorlink'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofaturtleorlink'slabel.
Seealsolabel,plabel,plabel-color.
Example:
Since1.0
Since4.0
Since4.0
Since4.0
ask turtles [ set label-color red ]
;; all the turtles now have red labels
last
lastlist
laststring
Onalist,reportsthelastiteminthelist.
Onastring,reportsaone-characterstringcontainingonlythelastcharacteroftheoriginalstring.
layout-circle
layout-circleagentsetradius
layout-circlelist-of-turtlesradius
Arrangesthegiventurtlesinacirclecenteredonthepatchatthecenteroftheworldwiththegivenradius.(Iftheworldhasanevensizethe
centerofthecircleisroundeddowntothenearestpatch.)Theturtlespointoutwards.
Ifthefirstinputisanagentset,theturtlesarearrangedinrandomorder.
Ifthefirstinputisalist,theturtlesarearrangedclockwiseinthegivenorder,startingatthetopofthecircle.(Anynon-turtlesinthelistare
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-radialturtle-setlink-setroot-agent
Arrangestheturtlesinturtle-setconnectedbylinksinlink-set,inaradialtreelayout,centeredaroundtheroot-agentwhichismovedtothe
centeroftheworldview.
Onlylinksinthelink-setwillbeusedtodeterminethelayout.Iflinksconnectturtlesthatarenotinturtle-setthoseturtleswillremain
stationary.
Evenifthenetworkdoescontaincycles,andisnotatruetreestructure,thislayoutwillstillwork,althoughtheresultswillnotalwaysbe
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-springturtle-setlink-setspring-constantspring-lengthrepulsion-constant
Arrangestheturtlesinturtle-set,asifthelinksinlink-setarespringsandtheturtlesarerepellingeachother.Turtlesthatareconnectedby
linksinlink-setbutnotincludedinturtle-setaretreatedasanchorsandarenotmoved.
spring-constantisameasureofthe"tautness"ofthespring.Itisthe"resistance"tochangeintheirlength.spring-constantistheforcethe
springwouldexertifit'slengthwerechangedby1unit.
spring-lengthisthe"zero-force"lengthorthenaturallengthofthesprings.Thisisthelengthwhichallspringstrytoachieveeitherbypushing
outtheirnodesorpullingthemin.
repulsion-constantisameasureofrepulsionbetweenthenodes.Itistheforcethat2nodesatadistanceof1unitwillexertoneachother.
Therepulsioneffecttriestogetthenodesasfaraspossiblefromeachother,inordertoavoidcrowdingandthespringeffecttriestokeep
themat"about"acertaindistancefromthenodestheyareconnectedto.Theresultisthelayingoutofthewholenetworkinawaywhich
highlightsrelationshipsamongthenodesandatthesametimeiscrowdedlessandisvisuallypleasing.
ThelayoutalgorithmisbasedontheFruchterman-Reingoldlayoutalgorithm.Moreinformationaboutthisalgorithmcanbeobtainedhere.
to make-a-triangle
set-default-shape turtles "circle"
crt 3
ask turtle 0
[
Since4.0
Since1.0
Since1.0
Since1.0
Since2.1
Since4.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-tutteturtle-setlink-setradius
Theturtlesthatareconnectedbylinksinlink-setbutnotincludedinturtle-setareplacedinacirclelayoutwiththegivenradius.Thereshould
beatleast3agentsinthisagentset.
Theturtlesinturtle-setarethenlaidoutinthefollowingmanner:Eachturtleisplacedatcentroid(orbarycenter)ofthepolygonformedbyits
linkedneighbors.(Thecentroidislikea2-dimensionalaverageofthecoordinatesoftheneighbors.)
(Thepurposeofthecircleof"anchoragents"istopreventalltheturtlesfromcollapsingdowntoonepoint.)
Afterafewiterationsofthis,thelayoutwillstabilize.
ThislayoutisnamedafterthemathematicianWilliamThomasTutte,whoproposeditasamethodforgraphlayout.
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
leftnumber
Theturtleturnsleftbynumberdegrees.(Ifnumberisnegative,itturnsright.)
length
lengthlist
lengthstring
Reportsthenumberofitemsinthegivenlist,orthenumberofcharactersinthegivenstring.
let
letvariablevalue
Createsanewlocalvariableandgivesitthegivenvalue.Alocalvariableisonethatexistsonlywithintheenclosingblockofcommands.
Ifyouwanttochangethevalueafterwards,useset.
Example:
let prey one-of sheep-here
if prey != nobody
[ ask prey [ die ] ]
link
linkend1end2
<breed>end1end2
Giventhewhonumbersoftheendpoints,reportsthelinkconnectingtheturtles.Ifthereisnosuchlinkreportsnobody.Torefertobreeded
linksyoumustusethesingularbreedformwiththeendpoints.
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
Since4.0
Since4.0
Since4.0
Since4.0
Since4.0
Seealsopatch-at.
link-heading
link-heading
Reportstheheadingindegrees(atleast0,lessthan360)fromend1toend2ofthelink.Throwsaruntimeerroriftheendpointsareatthe
samelocation.
ask link 0 1 [ print link-heading ]
;; prints [[towards other-end] of end1] of link 0 1
Seealsolink-length
link-length
link-length
Reportsthedistancebetweentheendpointsofthelink.
ask link 0 1 [ print link-length ]
;; prints [[distance other-end] of end1] of link 0 1
Seealsolink-heading
link-set
link-setvalue
(link-setvalue1value2...)
Reportsanagentsetcontainingallofthelinksanywhereinanyoftheinputs.Theinputsmaybeindividuallinks,linkagentsets,nobody,or
lists(ornestedlists)containinganyoftheabove.
link-set self
link-set [my-links] of nodes with [color = red]
Seealsoturtle-set,patch-set.
link-shapes
link-shapes
Reportsalistofstringscontainingallofthelinkshapesinthemodel.
Newshapescanbecreated,orimportedfromothermodels,intheLinkShapesEditor.
show link-shapes
=> ["default"]
links
links
Reportstheagentsetconsistingofalllinks.Thisisaspecialagentsetthatcangrowasturtlesareaddedtotheworld,seetheprogramming
guideformoreinfo.
show count links
;; prints the number of links
links-own
links-own[var1...]
<link-breeds>-own[var1...]
Thelinks-ownkeyword,liketheglobals,breed,<breeds>-own,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningof
aprogram,beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachlink.
Ifyouspecifyabreedinsteadof"links",onlylinksofthatbreedhavethelistedvariables.(Morethanonelinkbreedmaylistthesame
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]
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.3
list
listvalue1value2
(listvalue1...)
Reportsalistcontainingthegivenitems.Theitemscanbeofanytype,producedbyanykindofreporter.
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
lnnumber
Reportsthenaturallogarithmofnumber,thatis,thelogarithmtothebasee(2.71828...).
Seealsoe,log.
log
lognumberbase
Reportsthelogarithmofnumberinbasebase.
show log 64 2
=> 6
Seealsoln.
loop
loop[commands]
Repeatsthecommandsforever,oruntiltheenclosingprocedureexitsthroughuseofthestoporreportcommands.
to move-to-world-edge ;; turtle procedure
loop [
if not can-move? 1 [ stop ]
fd 1
]
end
Inthisexample,stopexitsnotjusttheloop,buttheentireprocedure.
Note:inmanycircumstances,itismoreappropriatetouseaforeverbuttontorepeatsomethingindefinitely.SeeButtonsintheProgramming
Guide.
lput
lputvaluelist
Addsvaluetotheendofalistandreportsthenewlist.
;; suppose mylist is [2 7 10 "Bob"]
set mylist lput 42 mylist
;; mylist now is [2 7 10 "Bob" 42]
M
map
mapreporterlist
(mapreporterlist1...)
Withasinglelist,thegivenreporterisrunforeachiteminthelist,andalistoftheresultsiscollectedandreported.reportermaybean
anonymousreporterorthenameofareporter.
show map round [1.1 2.2 2.7]
=> [1 2 3]
show map [ i -> i * i ] [1 2 3]
=> [1 4 9]
Withmultiplelists,thegivenreporterisrunforeachgroupofitemsfromeachlist.So,itisrunonceforthefirstitems,onceforthesecond
items,andsoon.Allthelistsmustbethesamelength.
Since1.0
Since4.0
Since1.0
Since3.1
Since3.1
Since1.0
Someexamplesmakethisclearer:
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]
Seealsoforeach,->(anonymousprocedure).
max
maxlist
Reportsthemaximumnumbervalueinthelist.Itignoresothertypesofitems.
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-ofnumberagentset[reporter]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththehighestvaluesofreporter.Theagentsetisbuiltbyfindingallthe
agentswiththehighestvalueofreporter,iftherearenotnumberagentswiththatvaluethenagentswiththesecondhighestvaluearefound,
andsoon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; 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)
Seealsomax-one-of,with-max.
max-one-of
max-one-ofagentset[reporter]
Reportstheagentintheagentsetthathasthehighestvalueforthegivenreporter.Ifthereisatiethiscommandreportsonerandomagent
withthehighestvalue.Ifyouwantallsuchagents,usewith-maxinstead.
show max-one-of patches [count turtles-here]
;; prints the first patch with the most turtles on it
Seealsomax-n-of,with-max.
max-pxcor
max-pycor
max-pxcor
max-pycor
Thesereportersgivethemaximumx-coordinateandmaximumy-coordinate,(respectively)forpatches,whichdeterminesthesizeofthe
world.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,themaximumx-andy-coordinates
mustbegreaterthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
crt 100 [ setxy random-float max-pxcor
random-float max-pycor ]
;; distributes 100 turtles randomly in the
;; first quadrant
Seealsomin-pxcor,min-pycor,world-width,andworld-height
mean
meanlist
Reportsthestatisticalmeanofthenumericitemsinthegivenlist.Errorsonnon-numericitems.Themeanistheaverage,i.e.,thesumofthe
itemsdividedbythetotalnumberofitems.
Since1.0
Since1.0
Since1.0
Since4.0
Since1.0
show mean [xcor] of turtles
;; prints the average of all the turtles' x coordinates
median
medianlist
Reportsthestatisticalmedianofthenumericitemsofthegivenlist.Ignoresnon-numericitems.Themedianistheitemthatwouldbeinthe
middleifalltheitemswerearrangedinorder.(Iftwoitemswouldbeinthemiddle,themedianistheaverageofthetwo.)
show median [xcor] of turtles
;; prints the median of all the turtles' x coordinates
member?
member?valuelist
member?string1string2
member?agentagentset
Foralist,reportstrueifthegivenvalueappearsinthegivenlist,otherwisereportsfalse.
Forastring,reportstrueorfalsedependingonwhetherstring1appearsanywhereinsidestring2asasubstring.
Foranagentset,reportstrueifthegivenagentisappearsinthegivenagentset,otherwisereportsfalse.
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
Seealsoposition.
min
minlist
Reportstheminimumnumbervalueinthelist.Itignoresothertypesofitems.
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]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththelowestvaluesofreporter.Theagentsetisbuiltbyfindingalltheagents
withthelowestvalueofreporter,iftherearenotnumberagentswiththatvaluethentheagentswiththesecondlowestvaluearefound,and
soon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; 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)
Seealsomin-one-of,with-min.
min-one-of
min-one-ofagentset[reporter]
Reportsarandomagentintheagentsetthatreportsthelowestvalueforthegivenreporter.Ifthereisatie,thiscommandreportsone
randomagentthatmeetsthecondition.Ifyouwantallsuchagentsusewith-mininstead.
show min-one-of turtles [xcor + ycor]
;; reports the first turtle with the smallest sum of
;; coordinates
Seealsowith-min,min-n-of.
Since3.1
Since3.1
Since1.0
Since2.0
Since1.0
Since3.0
Since1.0
Since1.0
min-pxcor
min-pycor
min-pxcor
min-pycor
Thesereportersgivetheminimumx-coordinateandminimumy-coordinate,(respectively)forpatches,whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,theminimumx-andy-coordinates
mustbelessthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
crt 100 [ setxy random-float min-pxcor
random-float min-pycor ]
;; distributes 100 turtles randomly in the
;; third quadrant
Seealsomax-pxcor,max-pycor,world-width,andworld-height
mod
number1modnumber2
Reportsnumber1modulonumber2:thatis,theresidueofnumber1(modnumber2).modisisequivalenttothefollowingNetLogocode:
number1 - (floor (number1 / number2)) * number2
Notethatmodis"infix",thatis,itcomesbetweenitstwoinputs.
show 62 mod 5
=> 2
show -8 mod 3
=> 1
Seealsoremainder.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
modes
modeslist
Reportsalistofthemostcommonitemoritemsinlist.
TheinputlistmaycontainanyNetLogovalues.
Iftheinputisanemptylist,reportsanemptylist.
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?
Reportstrueifthemousebuttonisdown,falseotherwise.
Note:Ifthemousepointerisoutsideofthecurrentview,mouse-down?willalwaysreportfalse.
mouse-inside?
mouse-inside?
Reportstrueifthemousepointerisinsidethecurrentview,falseotherwise.
mouse-xcor
mouse-ycor
mouse-xcor
mouse-ycor
Reportsthexorycoordinateofthemouseinthe2Dview.Thevalueisintermsofturtlecoordinates,soitmightnotbeaninteger.Ifyouwant
patchcoordinates,useround mouse-xcorandround mouse-ycor.
Note:Ifthemouseisoutsideofthe2Dview,reportsthevaluefromthelasttimeitwasinside.
Since4.0
Since4.0
Since4.0
Since4.0
;; to make the mouse "draw" in red:
if mouse-down?
[ ask patch mouse-xcor mouse-ycor [ set pcolor red ] ]
move-to
move-toagent
Theturtlesetsitsxandycoordinatestobethesameasthegivenagent's.
(Ifthatagentisapatch,theeffectistomovetheturtletothecenterofthatpatch.)
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
Notethattheturtle'sheadingisunaltered.Youmaywanttousethefacecommandfirsttoorienttheturtleinthedirectionofmotion.
Seealsosetxy.
my-<breeds>
my-links
my-<breeds>
my-links
Reportsanagentsetofalllinksconnectedtothecallerofthecorrespondingbreed,regardlessofdirectedness.Generally,youmightconsider
usingmy-out-linksinsteadofthisprimitive,asitworkswellforeitherdirectedorundirectednetworks(sinceitexcludesdirected,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
Ifyouonlywanttheundirectedlinksconnectedtoanode,youcandomy-links with [ not is-directed-link? self ].
my-in-<breeds>
my-in-links
my-in-<breeds>
my-in-links
Reportsanagentsetofallthedirectedlinkscominginfromothernodestothecalleraswellasallundirectedlinksconnectedtothecaller.
Youcanthinkofthisas"alllinksthatyoucanusetotraveltothisnode".
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
Reportsanagentsetofallthedirectedlinksgoingoutfromthecallertoothernodesaswellasundirectedlinksconnectedtothecaller.You
canthinkofthisas"alllinksyoucanusetotravelfromthisnode".
crt 5
ask turtle 0
[
create-links-to other turtles
show my-out-links ;; shows agentset containing all the links
Since1.0
Since3.1
Since2.0
Since1.1
Since1.1
]
ask turtle 1
[
show my-out-links ;; shows an empty agentset
]
myself
myself
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theturtle,patchorlinkwhoaskedmetodowhatI'm
doingrightnow."
Whenanagenthasbeenaskedtorunsomecode,usingmyselfinthatcodereportstheagent(turtle,patchorlink)thatdidtheasking.
myselfismostoftenusedinconjunctionwithoftoreadorsetvariablesintheaskingagent.
myselfcanbeusedwithinblocksofcodenotjustintheaskcommand,butalsohatch,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
Seethe"MyselfExample"codeexampleformoreexamples.
Seealsoself.
N
n-of
n-ofsizeagentset
n-ofsizelist
Fromanagentset,reportsanagentsetofsizesizerandomlychosenfromtheinputset,withnorepeats.
Fromalist,reportsalistofsizesizerandomlychosenfromtheinputset,withnorepeats.Theitemsintheresultappearinthesameorder
thattheyappearedintheinputlist.(Ifyouwanttheminrandomorder,useshuffleontheresult.)
Itisanerrorforsizetobegreaterthanthesizeoftheinput.
ask n-of 50 patches [ set pcolor green ]
;; 50 randomly chosen patches turn green
Seealsoone-of.
n-values
n-valuessizereporter
Reportsalistoflengthsizecontainingvaluescomputedbyrepeatedlyrunningthereporter.reportermaybeananonymousreporterorthe
nameofareporter.
Ifthereporteracceptsinputs,theinputwillbethenumberoftheitemcurrentlybeingcomputed,startingfromzero.
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]
Seealsoreduce,filter,->(anonymousprocedure),range.
neighbors
neighbors4
neighbors
neighbors4
Reportsanagentsetcontainingthe8surroundingpatches(neighbors)or4surroundingpatches(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 ]
Since4.0
Since4.0
Since3.0
Since5.2
Since3.0
Since1.0
;; turns the four neighboring patches red
<breed>-neighbors
link-neighbors
<breed>-neighbors
link-neighbors
Reportstheagentsetofallturtlesfoundattheotherendofanylinks(undirectedordirected,incomingoroutgoing)connectedtothisturtle.
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
Reportstrueifthereisalink(eitherdirectedorundirected,incomingoroutgoing)betweenturtleandthecaller.
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
ReportsastringcontainingtheversionnumberoftheNetLogoyouarerunning.
show netlogo-version
=> "6.0.4"
netlogo-web?
netlogo-web?
ReportstrueifthemodelisrunninginNetLogoWeb.
new-seed
new-seed
Reportsanumbersuitableforseedingtherandomnumbergenerator.
Thenumbersreportedbynew-seedarebasedonthecurrentdateandtimeinmillisecondsandlieinthegenerator'susablerangeofseeds,-
2147483648to2147483647.
new-seedneverreportsthesamenumbertwiceinsuccession,evenacrossparallelBehaviorSpaceruns.(Thisisaccomplishedbywaitinga
millisecondiftheseedforthecurrentmillisecondwasalreadyused.)
Seealsorandom-seed.
no-display
no-display
Turnsoffallupdatestothecurrentviewuntilthedisplaycommandisissued.Thishastwomajoruses.
One,youcancontrolwhentheuserseesviewupdates.Youmightwanttochangelotsofthingsontheviewbehindtheuser'sback,soto
speak,thenmakethemvisibletotheuserallatonce.
Two,yourmodelwillrunfasterwhenviewupdatingisoff,soifyou'reinahurry,thiscommandwillletyougetresultsfaster.(Notethat
Since4.0
Since4.0
Since1.0
Since4.0
Since4.0
Since1.0
normallyyoudon'tneedtouseno-displayforthis,sinceyoucanalsousetheon/offswitchinviewcontrolstriptofreezetheview.)
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsodisplay.
nobody
nobody
Thisisaspecialvaluewhichsomeprimitivessuchasturtle,one-of,max-one-of,etc.reporttoindicatethatnoagentwasfound.Also,whena
turtledies,itbecomesequaltonobody.
Note:Emptyagentsetsarenotequaltonobody.Ifyouwanttotestforanemptyagentset,useany?.Youonlygetnobodybackinsituations
whereyouwereexpectingasingleagent,notawholeagentset.
set target one-of other turtles-here
if target != nobody
[ ask target [ set color red ] ]
no-links
no-links
Reportsanemptylinkagentset.
no-patches
no-patches
Reportsanemptypatchagentset.
not
notboolean
Reportstrueifbooleanisfalse,otherwisereportsfalse.
if not any? turtles [ crt 10 ]
no-turtles
no-turtles
Reportsanemptyturtleagentset.
O
of
[reporter]ofagent
[reporter]ofagentset
Foranagent,reportsthevalueofthereporterforthatagent(turtleorpatch).
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
Foranagentset,reportsalistthatcontainsthevalueofthereporterforeachagentintheagentset(inrandomorder).
crt 4
show sort [who] of turtles
=> [0 1 2 3]
show sort [who * who] of turtles
=> [0 1 4 9]
one-of
one-ofagentset
one-oflist
Fromanagentset,reportsarandomagent.Iftheagentsetisempty,reportsnobody.
Since1.0
Since4.0
Since4.0
Since4.0
Since4.0
Fromalist,reportsarandomlistitem.Itisanerrorforthelisttobeempty.
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
Seealson-of.
or
boolean1orboolean2
Reportstrueifeitherboolean1orboolean2,orboth,istrue.
Notethatifcondition1istrue,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) or (pycor > 0) [ set pcolor red ]
;; patches turn red except in lower-left quadrant
other
otheragentset
Reportsanagentsetwhichisthesameastheinputagentsetbutomitsthisagent.
show count turtles-here
=> 10
show count other turtles-here
=> 9
other-end
other-end
Ifrunbyaturtle,reportstheturtleattheotherendoftheaskinglink.
Ifrunbyalink,reportstheturtleattheendofthelinkthatisn'ttheaskingturtle.
Thesedefinitionsaredifficulttounderstandintheabstract,butthefollowingexamplesshouldhelp:
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
Astheseexampleshopefullymakeplain,the"other"endistheendthatisneitheraskingnorbeingasked.
out-<breed>-neighbor?
out-link-neighbor?
out-<breed>-neighbor?turtle
out-link-neighbor?turtle
Reportstrueifthereisadirectedlinkgoingfromthecallertoturtleorifthereisanundirectedlinkconnectingthecallerwithturtle.Youcan
thinkofthisas"canIgetfromthecallertoturtleusingalink?"
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
Since4.0
Since2.1
Since2.1
Since2.1
Since2.1
Since1.0
Since2.0
Reportstheagentsetofalltheturtlesthathavedirectedlinksfromthecaller,orundirectedlinkswiththecaller.Youcanthinkofthisas"who
canIgettofromthecallerusingalink?"
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>-toturtle
out-link-toturtle
Reportsadirectedlinkfromthecallertoturtleoranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromthecallertoturtle."
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
]
Seealso:in-link-fromlink-with
output-print
output-show
output-type
output-write
output-printvalue
output-showvalue
output-typevalue
output-writevalue
Thesecommandsarethesameastheprint,show,type,andwritecommandsexceptthatvalueisprintedinthemodel'soutputarea,instead
ofintheCommandCenter.(Ifthemodeldoesnothaveaseparateoutputarea,thentheCommandCenterisused.)SeealsoOutput
(programmingguide).
P
patch
patchxcorycor
Giventhexandycoordinatesofapoint,reportsthepatchcontainingthatpoint.(Thecoordinatesareabsolutecoordinates;theyarenot
computedrelativetothisagent,aswithpatch-at.)
Ifxandyareintegers,thepointisthecenterofapatch.Ifxoryisnotaninteger,roundingtothenearestintegerisusedtodeterminewhich
patchcontainsthepoint.
Ifwrappingisallowedbythetopology,thegivencoordinateswillbewrappedtobewithintheworld.Ifwrappingisnotallowedandthegiven
coordinatesareoutsidetheworld,reportsnobody.
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
Seealsopatch-at.
patch-ahead
patch-aheaddistance
Since1.0
Since2.0
Since1.0
Since2.0
Since2.0
Since4.0
Reportsthesinglepatchthatisthegivendistance"ahead"ofthisturtle,thatis,alongtheturtle'scurrentheading.Reportsnobodyifthepatch
doesnotexistbecauseitisoutsidetheworld.
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
Seealsopatch-at,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at
patch-atdxdy
Reportsthepatchat(dx,dy)fromthecaller,thatis,thepatchcontainingthepointdxeastanddypatchesnorthofthisagent.
Reportsnobodyifthereisnosuchpatchbecausethatpointisbeyondanon-wrappingworldboundary.
ask patch-at 1 -1 [ set pcolor green ]
;; if caller is a turtle or patch, turns the
;; patch just southeast of the caller green
Seealsopatch,patch-ahead,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at-heading-and-distance
patch-at-heading-and-distanceheadingdistance
patch-at-heading-and-distancereportsthesinglepatchthatisthegivendistancefromthisturtleorpatch,alongthegivenabsoluteheading.
(Incontrasttopatch-left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakenintoaccount.)Reportsnobodyifthe
patchdoesnotexistbecauseitisoutsidetheworld.
ask patch-at-heading-and-distance -90 1 [ set pcolor green ]
;; turns the patch 1 to the west of this patch green
Seealsopatch,patch-at,patch-left-and-ahead,patch-right-and-ahead.
patch-here
patch-here
patch-herereportsthepatchundertheturtle.
Notethatthisreporterisn'tavailabletoapatchbecauseapatchcanjustsay"self".
patch-left-and-ahead
patch-right-and-ahead
patch-left-and-aheadangledistance
patch-right-and-aheadangledistance
Reportsthesinglepatchthatisthegivendistancefromthisturtle,inthedirectionturnedleftorrightthegivenangle(indegrees)fromthe
turtle'scurrentheading.Reportsnobodyifthepatchdoesnotexistbecauseitisoutsidetheworld.
(Ifyouwanttofindapatchinagivenabsoluteheading,ratherthanonerelativetothecurrentturtle'sheading,usepatch-at-heading-and-
distanceinstead.)
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
Seealsopatch,patch-at,patch-at-heading-and-distance.
patch-set
patch-setvalue1
(patch-setvalue1value2...)
Reportsanagentsetcontainingallofthepatchesanywhereinanyoftheinputs.Theinputsmaybeindividualpatches,patchagentsets,
nobody,orlists(ornestedlists)containinganyoftheabove.
patch-set self
patch-set patch-here
(patch-set self neighbors)
Since4.1
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since1.0
Since1.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
Seealsoturtle-set,link-set.
patch-size
patch-size
Reportsthesizeofthepatchesintheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsoset-patch-size.
patches
patches
Reportstheagentsetconsistingofallpatches.
patches-own
patches-own[var1...]
Thiskeyword,liketheglobals,breed,<breed>-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeany
functiondefinitions.Itdefinesthevariablesthatallpatchescanuse.
Allpatcheswillthenhavethegivenvariablesandbeabletousethem.
Allpatchvariablescanalsobedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoglobals,turtles-own,breed,<breeds>-own.
pcolor
pcolor
Thisisabuilt-inpatchvariable.Itholdsthecolorofthepatch.Youcansetthisvariabletomakethepatchchangecolor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.ColorcanberepresentedeitherasaNetLogocolor(asingle
number)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
Seealsocolor.
pen-down
pd
pen-erase
pe
pen-up
pu
pen-down
pen-erase
pen-up
Theturtlechangesmodesbetweendrawinglines,removinglinesorneither.Thelineswillalwaysbedisplayedontopofthepatchesand
belowtheturtles.Tochangethecolorofthepensetthecoloroftheturtleusingset color.
Note:Whenaturtle'spenisdown,allmovementcommandscauselinestobedrawn,includingjump,setxy,andmove-to.
Note:Thesecommandsareequivalenttosettingtheturtlevariable"pen-mode"to"down","up",and"erase".
Note:OnWindowsdrawinganderasingalinemightnoteraseeverypixel.
pen-mode
Thisisabuilt-inturtlevariable.Itholdsthestateoftheturtle'spen.Yousetthevariabletodrawlines,eraselinesorstopeitherofthese
actions.Possiblevaluesare"up","down",and"erase".
pen-size
Since1.0
Since1.0
Since4.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Since1.0
Thisisabuilt-inturtlevariable.Itholdsthewidthoftheline,inpixels,thattheturtlewilldraw(orerase)whenthepenisdown(orerasing).
plabel
plabel
Thisisabuilt-inpatchvariable.Itmayholdavalueofanytype.Thepatchappearsintheviewwiththegivenvalue"attached"toitastext.
Youcansetthisvariabletoadd,change,orremoveapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel-color,label,label-color.
plabel-color
plabel-color
Thisisabuilt-inpatchvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolorthe
patch'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel,label,label-color.
plot
plotnumber
Incrementsthex-valueoftheplotpenbyplot-pen-interval,thenplotsapointattheupdatedx-valueanday-valueofnumber.(Thefirsttime
thecommandisusedonaplot,thepointplottedhasanx-valueof0.)
plot-name
plot-name
Reportsthenameofthecurrentplot(astring)
plot-pen-exists?
plot-pen-exists?string
Reportstrueifaplotpenwiththegivennameisdefinedinthecurrentplot.Otherwisereportsfalse.
plot-pen-down
plot-pen-up
plot-pen-down
plot-pen-up
Putsdown(orup)thecurrentplot-pen,sothatitdraws(ordoesn't).(Bydefault,allpensaredowninitially.)
plot-pen-reset
plot-pen-reset
Clearseverythingthecurrentplotpenhasdrawn,movesitto(0,0),andputsitdown.Ifthepenisapermanentpen,thecolor,mode,and
intervalareresettothedefaultvaluesfromtheplotEditdialog.
plotxy
plotxynumber1number2
Movesthecurrentplotpentothepointwithcoordinates(number1,number2).Ifthepenisdown,aline,bar,orpointwillbedrawn(depending
onthepen'smode).
plot-x-min
plot-x-max
plot-y-min
plot-y-max
plot-x-min
plot-x-max
plot-y-min
plot-y-max
Since1.0
Since1.0
Since1.0
Since1.0
Reportstheminimumormaximumvalueonthexoryaxisofthecurrentplot.
Thesevaluescanbesetwiththecommandsset-plot-x-rangeandset-plot-y-range.(TheirdefaultvaluesaresetfromtheplotEditdialog.)
position
positionitemlist
positionstring1string2
Onalist,reportsthefirstpositionofiteminlist,orfalseifitdoesnotappear.
Onstrings,reportsthepositionofthefirstappearancestring1asasubstringofstring2,orfalseifitdoesnotappear.
Note:Thepositionsarenumberedbeginningwith0,notwith1.
;; suppose mylist is [2 7 4 7 "Bob"]
show position 7 mylist
=> 1
show position 10 mylist
=> false
show position "in" "string"
=> 3
Seealsomember?.
precision
precisionnumberplaces
Reportsnumberroundedtoplacesdecimalplaces.
Ifplacesisnegative,theroundingtakesplacetotheleftofthedecimalpoint.
show precision 1.23456789 3
=> 1.235
show precision 3834 -3
=> 4000
Seealsoround,ceiling,floor.
print
printvalue
PrintsvalueintheCommandCenter,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikeshow.
Seealsoshow,type,write,output-print,andOutput(programmingguide).
pxcor
pycor
pxcor
pycor
Thesearebuilt-inpatchvariables.Theyholdthexandycoordinateofthepatch.Theyarealwaysintegers.Youcannotsetthesevariables,
becausepatchesdon'tmove.
pxcorisgreaterthanorequaltomin-pxcorandlessthanorequaltomax-pxcor;similarlyforpycorandmin-pycorandmax-pycor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoxcor,ycor.
R
random
randomnumber
Ifnumberispositive,reportsarandomintegergreaterthanorequalto0,butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomintegerlessthanorequalto0,butstrictlygreaterthannumber.
Ifnumberiszero,theresultisalways0aswell.
Note:InversionsofNetLogopriortoversion2.0,thisprimitivereportedafloatingpointnumberifgivenanon-integerinput.Thisisnolonger
thecase.Ifyouwantafloatingpointanswer,youmustnowuserandom-floatinstead.
show random 3
Since2.0
Since1.2.1
Since2.0
Since1.2.1
Since1.2.1
Since3.1
Since3.1
Since1.0
;; prints 0, 1, or 2
show random -3
;; prints 0, -1, or -2
show random 3.5
;; prints 0, 1, 2, or 3
Seealsorandom-float.
random-float
random-floatnumber
Ifnumberispositive,reportsarandomfloatingpointnumbergreaterthanorequalto0butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomfloatingpointnumberlessthanorequalto0,butstrictlygreaterthannumber.
Ifnumberiszero,theresultisalways0.
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-exponentialmean
random-gammaalphalambda
random-normalmeanstandard-deviation
random-poissonmean
Reportsanaccordinglydistributedrandomnumberwiththemeanand,inthecaseofthenormaldistribution,thestandard-deviation.(The
standarddeviationmaynotbenegative.)
random-exponentialreportsanexponentiallydistributedrandomfloatingpointnumber.Itisequivalentto(- mean) * ln random-float 1.0.
random-gammareportsagamma-distributedrandomfloatingpointnumberascontrolledbythefloatingpointalphaandlambdaparameters.
Bothinputsmustbegreaterthanzero.(Note:forresultswithagivenmeanandvariance,useinputsasfollows:alpha=mean*mean/
variance;lambda=1/(variance/mean).)
random-normalreportsanormallydistributedrandomfloatingpointnumber.
random-poissonreportsaPoisson-distributedrandominteger.
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
Reportsarandomintegerrangingfrommin-pxcor(or-y)tomax-pxcor(or-y)inclusive.
ask turtles [
;; move each turtle to the center of a random patch
setxy random-pxcor random-pycor
]
Seealsorandom-xcor,random-ycor.
random-seed
random-seednumber
Setstheseedofthepseudo-randomnumbergeneratortotheintegerpartofnumber.Theseedmustbeintherange-2147483648to
2147483647;notethatthisissmallerthanthefullrangeofintegerssupportedbyNetLogo(-9007199254740992to9007199254740992).
SeetheRandomNumberssectionoftheProgrammingGuideformoredetails.
random-seed 47822
Since3.1
Since3.1
Since6.0
Since1.1
Since1.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
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinatesalongthegivenaxis,xory.
Turtlecoordinatesrangefrommin-pxcor-0.5(inclusive)tomax-pxcor+0.5(exclusive)horizontally;vertically,substitute-yfor-x.
ask turtles [
;; move each turtle to a random point
setxy random-xcor random-ycor
]
Seealsorandom-pxcor,random-pycor.
range
rangestop
(rangestartstop)
(rangestartstopstep)
Generatesalistofnumbers,startingatstart,endingbeforestop,countingbystep.startdefaultsto0andstepdefaultsto1.
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]
Seealson-values
read-from-string
read-from-stringstring
InterpretsthegivenstringasifithadbeentypedintheCommandCenter,andreportstheresultingvalue.Theresultmaybeanumber,list,
string,orbooleanvalue,orthespecialvalue"nobody".
Usefulinconjunctionwiththeuser-inputprimitiveforconvertingtheuser'sinputintousableform.
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
reducereporterlist
Reducesalistfromlefttorightusingthegivenreporter,resultinginasinglevalue.Thismeans,forexample,thatreduce [ [a b] -> a + b]
[1 2 3 4]isequivalentto(((1+2)+3)+4).Iflisthasasingleitem,thatitemisreported.Itisanerrortoreduceanemptylist.reportermay
beananonymousreporterorthenameofareporter.
Thefirstinputpassedtothereporteristheresultsofar,andthesecondinputisthenextiteminthelist.
Sinceitcanbedifficulttodevelopanintuitionaboutwhatreducedoes,herearesomesimpleexampleswhich,whilenotusefulinthemselves,
maygiveyouabetterunderstandingofthisprimitive:
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])
Since1.2.1
Since1.0
Since1.0
Since2.0
=> [5 4 3 2 1]
Herearesomemoreusefulexamples:
;; 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
Seealsofilter,->(anonymousprocedure.
remainder
remaindernumber1number2
Reportstheremainderwhennumber1isdividedbynumber2.ThisisequivalenttothefollowingNetLogocode:
number1 - (int (number1 / number2)) * number2
show remainder 62 5
=> 2
show remainder -8 3
=> -2
Seealsomod.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
remove
removeitemlist
removestring1string2
Foralist,reportsacopyoflistwithallinstancesofitemremoved.
Forstrings,reportsacopyofstring2withalltheappearancesofstring1asasubstringremoved.
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-duplicateslist
Reportsacopyoflistwithallduplicateitemsremoved.Thefirstofeachitemremainsinplace.
set mylist [2 7 4 7 "Bob" 7]
set mylist remove-duplicates mylist
;; mylist is now [2 7 4 "Bob"]
remove-item
remove-itemindexlist
remove-itemindexstring
Foralist,reportsacopyoflistwiththeitematthegivenindexremoved.
Forstrings,reportsacopyofstringwiththecharacteratthegivenindexremoved.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
set mylist [2 7 4 7 "Bob"]
set mylist remove-item 2 mylist
Since1.0
Since1.0
Since1.0
Since3.0
Since3.0
Since4.0
Since1.0
Since4.1
;; mylist is now [2 7 7 "Bob"]
show remove-item 2 "string"
=> "sting"
repeat
repeatnumber[commands]
Runscommandsnumbertimes.
pd repeat 36 [ fd 1 rt 10 ]
;; the turtle draws a circle
replace-item
replace-itemindexlistvalue
replace-itemindexstring1string2
Onalist,replacesaniteminthatlist.indexistheindexoftheitemtobereplaced,startingwith0.(The6thiteminalistwouldhaveanindex
of5.)Notethat"replace-item"isusedinconjunctionwith"set"tochangealist.
Likewiseforastring,butthegivencharacterofstring1removedandthecontentsofstring2splicedininstead.
show replace-item 2 [2 7 4 5] 15
=> [2 7 15 5]
show replace-item 1 "cat" "are"
=> "caret"
report
reportvalue
Immediatelyexitsfromthecurrentto-reportprocedureandreportsvalueastheresultofthatprocedure.reportandto-reportarealwaysused
inconjunctionwitheachother.Seeto-reportforadiscussionofhowtousethem.
reset-perspective
rp
reset-perspective
Theobserverstopswatching,following,orridinganyturtles(orpatches).(Ifitwasn'twatching,following,orridinganybody,nothing
happens.)Inthe3Dview,theobserveralsoreturnstoitsdefaultposition(abovetheorigin,lookingstraightdown).
Seealsofollow,ride,watch.
reset-ticks
reset-ticks
Resetsthetickcountertozero,setsupallplots,thenupdatesallplots(sothattheinitialstateoftheworldisplotted).
Normallyreset-ticksgoesattheendofasetupprocedure.
Seealsoclear-ticks,tick,ticks,tick-advance,setup-plots,update-plots.
reset-timer
reset-timer
Resetsthetimertozeroseconds.Seealsotimer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsed
modeltimeinticks.
resize-world
resize-worldmin-pxcormax-pxcormin-pycormax-pycor
Changesthesizeofthepatchgrid.
Ifthegivenpatchgridcoordinatesaredifferentthantheonesinuse,allturtlesandlinksdie,andtheexistingpatchgridisdiscardedandnew
patchescreated.Otherwise,existingturtlesandlinkswillliveifthegridcoordinatesareunchanged.
Retainingreferencestooldpatchesorpatchsetsisinadvisableandmaysubsequentlycauseruntimeerrorsorotherunexpectedbehavior.
Since1.0
Since1.0
Since3.0
Since3.0
Since1.0
Since1.0
Since1.0
Seealsoset-patch-size.
reverse
reverselist
reversestring
Reportsareversedcopyofthegivenlistorstring.
show mylist
;; mylist is [2 7 4 "Bob"]
set mylist reverse mylist
;; mylist now is ["Bob" 4 7 2]
show reverse "live"
=> "evil"
rgb
rgbredgreenblue
ReportsaRGBlistwhengiventhreenumbersdescribinganRGBcolor.Thenumbersarerangecheckedtobebetween0and255.
Seealsohsb
ride
rideturtle
Settheperspectivetoturtle.
Everytimeturtlemovestheobserveralsomoves.Thus,inthe2DViewtheturtlewillstayatthecenteroftheview.Inthe3Dviewitisasif
lookingthroughtheeyesoftheturtle.Iftheturtledies,theperspectiveresetstothedefault.
Theobservermayonlywatchorfollowasinglesubject.Callingridewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingtheriddenturtleinstead.
Seealsoreset-perspective,watch,follow,subject.
ride-me
ride-me
Askstheobservertoridethisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingride-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,
highlightingthisturtleinstead.
Seealsoride.
right
rt
rightnumber
Theturtleturnsrightbynumberdegrees.(Ifnumberisnegative,itturnsleft.)
round
roundnumber
Reportstheintegernearesttonumber.
Ifthedecimalportionofnumberisexactly.5,thenumberisroundedinthepositivedirection.
Notethatroundinginthepositivedirectionisnotalwayshowroundingisdoneinothersoftwareprograms.(Inparticular,itdoesnotmatch
thebehaviorofStarLogoT,whichalwaysroundednumbersendingin0.5tothenearesteveninteger.)Therationaleforthisbehavioristhatit
matcheshowturtlecoordinatesrelatetopatchcoordinatesinNetLogo.Forexample,ifaturtle'sxcoris-4.5,thenitisontheboundary
betweenapatchwhosepxcoris-4andapatchwhosepxcoris-5,buttheturtlemustbeconsideredtobeinonepatchortheother,sothe
turtleisconsideredtobeinthepatchwhosepxcoris-4,becauseweroundtowardsthepositivenumbers.
show round 4.2
=> 4
show round 4.5
=> 5
show round -4.5
=> -4
Seealsoprecision,ceiling,floor.
Since1.3
Since1.3
Since1.0
Since1.3
Since1.0
Since1.0
run
runresult
runcommand
(runcommandinput1...)
runstring
runresultreporter
(runresultreporterinput1...)
runresultstring
Therunformexpectsthenameofacommand,ananonymouscommand,orastringcontainingcommands.Thisagentthenrunsthem.
Therunresultformexpectsthenameofareporter,ananonymousreporter,orastringcontainingareporter.Thisagentrunsitandreports
theresult.
Notethatyoucan'tuseruntodefineorredefineprocedures.Ifyoucareaboutperformance,notethatthecodemustbecompiledfirstwhich
takestime.However,compiledbitsofcodearecachedbyNetLogoandthususingrunonthesamestringoverandoverismuchfasterthan
runningdifferentstrings.Thefirstrun,though,willbemanytimesslowerthanrunningthesamecodedirectly,orinananonymouscommand.
Anonymousproceduresarerecommendedoverstringswheneverpossible.(Anexampleofwhenyoumustusestringsisifyouaccept
piecesofcodefromtheuserofyourmodel.)
Anonymousproceduresmayfreelyreadand/orsetlocalvariablesandprocedureinputs.Tryingtodothesamewithstringsmayormaynot
workandshouldnotbereliedon.
Whenusinganonymousprocedures,youcanprovidethemwithinputs,ifyousurroundtheentirecallwithparentheses.Forexample:
(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
Seealsoforeach,->(anonymousprocedure).
S
scale-color
scale-colorcolornumberrange1range2
Reportsashadeofcolorproportionaltothevalueofnumber.
Ifrange1islessthanrange2,thenthelargerthenumber,thelightertheshadeofcolor.Butifrange2islessthanrange1,thecolorscalingis
inverted.
Ifnumberislessthanrange1,thenthedarkestshadeofcolorischosen.
Ifnumberisgreaterthanrange2,thenthelightestshadeofcolorischosen.
Note:forcolorshadeisirrelevant,e.g.greenandgreen+2areequivalent,andthesamespectrumofcolorswillbeused.
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
Reportsthisturtle,patch,orlink.
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theagentwhoaskedmetodowhatI'mdoingright
now."
Notethatitisalwaysredundanttowrite[foo] of self.Thisisalwaysequivalenttosimplywritingfoo.
Seealsomyself.
;(semicolon)
;comments
Afterasemicolon,therestofthelineisignored.Thisisusefulforadding"comments"toyourcode--textthatexplainsthecodetohuman
readers.Extrasemicolonscanbeaddedforvisualeffect.
NetLogo'sEditmenuhasitemsthatletyoucommentoruncommentwholesectionsofcode.
sentence
se
Since1.0
Since2.0
Since1.0
Since1.0
Since1.0
sentencevalue1value2
(sentencevalue1...)
Makesalistoutofthevalues.Ifanyvalueisalist,itsitemsareincludedintheresultdirectly,ratherthanbeingincludedasasublist.
Examplesmakethisclearer:
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
setvariablevalue
Setsvariabletothegivenvalue.
Variablecanbeanyofthefollowing:
Aglobalvariabledeclaredusing"globals"
Theglobalvariableassociatedwithaslider,switch,chooser,orinputbox.
Avariablebelongingtothisagent
Ifthisagentisaturtle,avariablebelongingtothepatchundertheturtle.
Alocalvariablecreatedbytheletcommand.
Aninputtothecurrentprocedure.
set-current-directory
set-current-directorystring
Setsthecurrentdirectorythatisusedbytheprimitivesfile-delete,file-exists?,andfile-open.
Thecurrentdirectoryisnotusediftheabovecommandsaregivenanabsolutefilepath.Thisisdefaultedtotheuser'shomedirectoryfor
newmodels,andischangedtothemodel'sdirectorywhenamodelisopened.
NotethatinWindowsfilepathsthebackslashneedstobeescapedwithinastringbyusinganotherbackslash"C:\\"
Thechangeistemporaryandisnotsavedwiththemodel.
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-plotplotname
Setsthecurrentplottotheplotwiththegivenname(astring).Subsequentplottingcommandswillaffectthecurrentplot.
set-current-plot-pen
set-current-plot-penpenname
Thecurrentplot'scurrentpenissettothepennamedpenname(astring).Ifnosuchpenexistsinthecurrentplot,aruntimeerroroccurs.
set-default-shape
set-default-shapeturtlesstring
set-default-shapelinksstring
set-default-shapebreedstring
Specifiesadefaultinitialshapeforallturtlesorlinks,orforaparticularbreedofturtlesorlinks.Whenaturtleorlinkiscreated,oritchanges
breeds,itshapeissettothegivenshape.
Thiscommanddoesn'taffectexistingagents,onlyagentsyoucreateafterwards.
Thegivenbreedmustbeeitherturtles,links,orthenameofabreed.Thegivenstringmustbethenameofacurrentlydefinedshape.
Innewmodels,thedefaultshapeforallturtlesis"default".
Notethatspecifyingadefaultshapedoesnotpreventyoufromchanginganagent'sshapelater.Agentsdon'thavetobestuckwiththeir
breed'sdefaultshape.
Since1.0
Since4.1
Since6.0.2
Since1.0
Since1.0
Since1.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"
Seealsoshape.
set-histogram-num-bars
set-histogram-num-barsnumber
Setthecurrentplotpen'splotintervalsothat,giventhecurrentxrangefortheplot,therewouldbenumbernumberofbarsdrawnifthe
histogramcommandiscalled.
Seealsohistogram.
__set-line-thickness
__set-line-thicknessnumber
Specifiesthethicknessoflinesandoutlinedelementsintheturtle'sshape.
Thedefaultvalueis0.Thisalwaysproduceslinesonepixelthick.
Non-zerovaluesareinterpretedasthicknessinpatches.Athicknessof1,forexample,produceslineswhichappearonepatchthick.(It's
commontouseasmallervaluesuchas0.5or0.2.)
Linesarealwaysatleastonepixelthick.
Thiscommandisexperimentalandmaychangeinlaterreleases.
set-patch-size
set-patch-sizesize
Setsthesizeofthepatchesoftheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsopatch-size,resize-world.
set-plot-background-color
set-plot-background-colorcolor
Setsthebackgroundcolorofthecurrentplot.Thecolormaybespecifiedasanumberoralist.SeetheColorssectionoftheprogramming
guideformoredetails.Thischangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,thebackgroundcolorwillrevertto
white.
Note:Plotbackgroundsdonotsupporttransparency.Ifalistisusedtosetthecolor,thealphacomponentwillbeignored.
set-plot-pen-color
set-plot-pen-colorcolor
Setsthecolorofthecurrentplotpentocolor.
set-plot-pen-interval
set-plot-pen-intervalnumber
Tellsthecurrentplotpentomoveadistanceofnumberinthexdirectionduringeachuseoftheplotcommand.(Theplotpenintervalalso
affectsthebehaviorofthehistogramcommand.)
set-plot-pen-mode
set-plot-pen-modenumber
Setsthemodethecurrentplotpendrawsintonumber.Theallowedplotpenmodesare:
0(linemode)theplotpendrawsalineconnectingtwopointstogether.
1(barmode):theplotpendrawsabarofwidthplot-pen-intervalwiththepointplottedastheupper(orlower,ifyouareplottinganegative
number)leftcornerofthebar.
Since5.0
Since1.0
Since1.0
Since1.0
Since1.0
Since2.1
2(pointmode):theplotpendrawsapointatthepointplotted.Pointsarenotconnected.
Thedefaultmodefornewpensis0(linemode).
setup-plots
setup-plots
Foreachplot,runsthatplot'ssetupcommands,includingthesetupcodeforanypensintheplot.
reset-tickshasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsoupdate-plots.
set-plot-x-range
set-plot-y-range
set-plot-x-rangeminmax
set-plot-y-rangeminmax
Setstheminimumandmaximumvaluesofthexoryaxisofthecurrentplot.
Thechangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,therangeswillreverttotheirdefaultvaluesassetinthe
plot'sEditdialog.
setxy
setxyxy
Theturtlesetsitsx-coordinatetoxanditsy-coordinatetoy.
Equivalenttoset xcor x set ycor y,exceptithappensinonetimestepinsteadoftwo.
Ifxoryisoutsidetheworld,NetLogowillthrowaruntimeerror,unlesswrappingisturnedonintherelevantdimensions.Forexample,with
wrappingturnedoninbothdimensionsandthedefaultworldsizewheremin-pxcor = -16,max-pxcor = 16,min-pycor = -16andmax-pycor =
16,askingaturtletosetxy 17 17willmoveittothecenterofpatch(-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
Seealsomove-to.
shade-of?
shade-of?color1color2
Reportstrueifbothcolorsareshadesofoneanother,falseotherwise.
show shade-of? blue red
=> false
show shade-of? blue (blue + 1)
=> true
show shade-of? gray white
=> true
shape
shape
Thisisabuilt-inturtleandlinkvariable.Itholdsastringthatisthenameoftheturtleorlink'scurrentshape.Youcansetthisvariableto
changetheshape.Newturtlesandlinkshavetheshape"default"unlesstheadifferentshapehasbeenspecifiedusingset-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
Seealsoset-default-shape,shapes.
shapes
Since1.0
Since1.0
Since1.0
Since4.0
Since2.0
Since1.0
Since1.0
shapes
Reportsalistofstringscontainingalloftheturtleshapesinthemodel.
Newshapescanbecreated,orimportedfromtheshapeslibraryorfromothermodels,intheShapesEditor.
show shapes
=> ["default" "airplane" "arrow" "box" "bug" ...
ask turtles [ set shape one-of shapes ]
show
showvalue
PrintsvalueintheCommandCenter,precededbythisagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrack
ofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartowrite.
Seealsoprint,type,write,output-show,andOutput(programmingguide).
show-turtle
st
show-turtle
Theturtlebecomesvisibleagain.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"tofalse.
Seealsohide-turtle.
show-link
show-link
Thelinkbecomesvisibleagain.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"tofalse.
Seealsohide-link.
shuffle
shufflelist
Reportsanewlistcontainingthesameitemsastheinputlist,butinrandomizedorder.
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
sinnumber
Reportsthesineofthegivenangle.Assumesangleisgivenindegrees.
show sin 270
=> -1
size
size
Thisisabuilt-inturtlevariable.Itholdsanumberthatistheturtle'sapparentsize.Thedefaultsizeis1,whichmeansthattheturtleisthe
samesizeasapatch.Youcansetthisvariabletochangeaturtle'ssize.
sort
sortlist
sortagentset
Reportsasortedlistofnumbers,strings,oragents.
Iftheinputcontainsnonumbers,strings,oragents,theresultistheemptylist.
Since1.3
Since5.0
Since1.0
Iftheinputcontainsatleastonenumber,thenumbersinthelistaresortedinascendingorderandanewlistreported;non-numbersare
ignored.
Or,iftheinputcontainsatleastonestring,thestringsinthelistaresortedinascendingorderandanewlistreported;non-stringsare
ignored.
Or,iftheinputisanagentsetoralistcontainingatleastoneagent,asortedlistofagents(neveranagentset)isreported;non-agentsare
ignored.Agentsaresortedinthesameorderthe<operatoruses.(Patchesaresortedwiththetopleft-mostpatchfirstandthebottomright-
mostpatchlast,turtlesaresortedbywhonumber).
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
=> []
Seealsosort-by,sort-on.
sort-by
sort-byreporterlist
sort-byreporteragentset
Iftheinputisalist,reportsanewlistcontainingthesameitemsastheinputlist,inasortedorderdefinedbythebooleanreporter.reporter
maybeananonymousreporterorthenameofareporter.
Thetwoinputstoreporterarethevaluesbeingcompared.Thereportershouldreporttrueifthefirstargumentcomesstrictlybeforethe
secondinthedesiredsortorder,andfalseotherwise.
Iftheinputisanagentsetoralistofagents,reportsalist(neveranagentset)ofagents.
Iftheinputisalist,thesortisstable,thatis,theorderofitemsconsideredequalbythereporterisnotdisturbed.Iftheinputisanagentset,
tiesarebrokenrandomly.
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"]
Seealsosort,sort-on,->(anonymousprocedure).
sort-on
sort-on[reporter]agentset
Reportsalistofagents,sortedaccordingtoeachagent'svalueforreporter.Tiesarebrokenrandomly.
Thevaluesmustbeallnumbers,allstrings,orallagentsofthesametype.
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
Seealsosort,sort-by.
sprout
sproutnumber[commands]
sprout-<breeds>number[commands]
Createsnumbernewturtlesonthecurrentpatch.Thenewturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe
14primarycolors.Theturtlesimmediatelyruncommands.Thisisusefulforgivingthenewturtlesdifferentcolors,headings,orwhatever.
Since1.0
Since1.0
Since3.1
Since1.0
Since1.0
Since5.2
(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
Ifthesprout-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
sprout 5
sprout-wolves 10
sprout 1 [ set color red ]
sprout-sheep 1 [ set color black ]
Seealsocreate-turtles,hatch.
sqrt
sqrtnumber
Reportsthesquarerootofnumber.
stamp
stamp
Thisturtleorlinkleavesanimageofitsshapeinthedrawingatitscurrentlocation.
Note:Theshapesmadebystampmaynotbepixel-for-pixelidenticalfromcomputertocomputer.
stamp-erase
stamp-erase
Thisturtleorlinkremovesanypixelsbelowitinthedrawinginsidetheboundsofitsshape.
Note:Theshapesmadebystamp-erasemaynotbepixel-for-pixelidenticalfromcomputertocomputer.
standard-deviation
standard-deviationlist
Reportsthesamplestandarddeviationofalistofnumbers.Ignoresothertypesofitems.
(Notethatthisestimatesthestandarddeviationforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
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-definedprocedurewhich,ifitexists,willbecalledwhenamodelisfirstloadedintheNetLogoapplication.
to startup
setup
end
startupdoesnotrunwhenamodelisrunheadlessfromthecommandline,orbyparallelBehaviorSpace.
stop
stop
Thisagentexitsimmediatelyfromtheenclosingprocedure,ask,orask-likeconstruct(e.g.crt,hatch,sprout).Onlytheenclosingprocedureor
constructstops,notallexecutionfortheagent.
if not any? turtles [ stop ]
;; exits if there are no more turtles
Note:stopcanalsobeusedtostopaforeverbutton.SeeButtonsintheProgrammingGuidefordetails.
stopcanalsobeusedtostopaBehaviorSpacemodelrun.Ifthegocommandsdirectlycallaprocedure,thenwhenthatprocedurecallsstop,
therunends.
stop-inspecting
Since5.2
Since3.0
Since2.1
Since1.0
Since2.1
Since1.0
Since1.0
stop-inspectingagent
Closestheagentmonitorforthegivenagent(turtleorpatch).Inthecasethatnoagentmonitorisopen,stop-inspectingdoesnothing.
stop-inspecting patch 2 4
;; the agent monitor for that patch closes
ask sheep [ stop-inspecting self ]
;; close all agent monitors for sheep
Seeinspectandstop-inspecting-dead-agents.
stop-inspecting-dead-agents
stop-inspecting-dead-agents
Closesallagentmonitorsfordeadagents.Seeinspectandstop-inspecting.
subject
subject
Reportstheturtle(orpatch)thattheobserveriscurrentlywatching,following,orriding.Reportsnobodyifthereisnosuchturtle(orpatch).
Seealsowatch,follow,ride.
sublist
substring
sublistlistposition1position2
substringstringposition1position2
Reportsjustasectionofthegivenlistorstring,rangingbetweenthefirstposition(inclusive)andthesecondposition(exclusive).
Note:Thepositionsarenumberedbeginningwith0,notwith1.
show sublist [99 88 77 66] 1 3
=> [88 77]
show substring "apartment" 1 5
=> "part"
subtract-headings
subtract-headingsheading1heading2
Computesthedifferencebetweenthegivenheadings,thatis,thenumberofdegreesinthesmallestanglebywhichheading2couldbe
rotatedtoproduceheading1.Apositiveanswermeansaclockwiserotation,anegativeanswercounterclockwise.Theresultisalwaysinthe
range-180to180,butisneverexactly-180.
Notethatsimplysubtractingthetwoheadingsusingthe-(minus)operatorwouldn'twork.Justsubtractingcorrespondstoalwaysrotating
clockwisefromheading2toheading1;butsometimesthecounterclockwiserotationisshorter.Forexample,thedifferencebetween5
degreesand355degreesis10degrees,not-350degrees.
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
sumlist
Reportsthesumoftheitemsinthelist.
show sum [energy] of turtles
;; prints the total of the variable "energy"
;; from all the turtles
T
tan
tannumber
Since4.0
Since4.0
Since4.0
Since4.0
Reportsthetangentofthegivenangle.Assumestheangleisgivenindegrees.
thickness
thickness
Thisisabuilt-inlinkvariable.Itholdsanumberthatisthelink'sapparentsizeasafractionofthepatchsize.Thedefaultthicknessis0,which
meansthatregardlessofpatch-sizethelinkswillalwaysappear1pixelwide.Youcansetthisvariabletochangealink'sthickness.
tick
tick
Advancesthetickcounterbyoneandupdatesallplots.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Normallytickgoesattheendofagoprocedure.
Seealsoticks,tick-advance,reset-ticks,clear-ticks,update-plots.
tick-advance
tick-advancenumber
Advancesthetickcounterbynumber.Theinputmaybeanintegerorafloatingpointnumber.(Somemodelsdivideticksmorefinelythanby
ones.)Theinputmaynotbenegative.
Whenusingtick-basedviewupdates,theviewisnormallyupdatedevery1.0ticks,sousingtick-advancewithanumberlessthen1.0may
notalwaystriggeranupdate.Ifyouwanttomakesurethattheviewisupdated,youcanusethedisplaycommand.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Doesnotupdateplots.
Seealsotick,ticks,reset-ticks,clear-ticks.
ticks
ticks
Reportsthecurrentvalueofthetickcounter.Theresultisalwaysanumberandnevernegative.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Mostmodelsusethetickcommandtoadvancethetickcounter,inwhichcasetickswillalwaysreportaninteger.Ifthetick-advance
commandisused,thenticksmayreportafloatingpointnumber.
Seealsotick,tick-advance,reset-ticks,clear-ticks.
tie
tie
Tiesend1andend2ofthelinktogether.Ifthelinkisadirectedlinkend1istherootturtleandend2istheleafturtle.Themovementoftheroot
turtleaffectsthelocationandheadingoftheleafturtle.Ifthelinkisundirectedthetieisreciprocalsobothturtlescanbeconsideredroot
turtlesandleafturtles.Movementorchangeinheadingofeitherturtleaffectsthelocationandheadingoftheotherturtle.
Whentherootturtlemoves,theleafturtlesmovesthesamedistance,inthesamedirection.Theheadingoftheleafturtleisnotaffected.
Thisworkswithforward,jump,andsettingthexcororycoroftherootturtle.
Whentherootturtleturnsrightorleft,theleafturtleisrotatedaroundtherootturtlethesameamount.Theheadingoftheleafturtleisalso
changedbythesameamount.
Ifthelinkdies,thetierelationisremoved.
crt 2 [ fd 3 ]
;; creates a link and ties turtle 1 to turtle 0
ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
Seealsountie
tie-mode
tie-mode
Since1.0
Since1.0
Since1.0
Thisisabuilt-inlinkvariable.Itholdsastringthatisthenameofthetiemodethelinkiscurrentlyin.Usingthetieanduntiecommands
changesthemodeofthelink.Youcanalsosettie-modeto"free"tocreateanon-rigidjointbetweentwoturtles(seetheTiesectionofthe
ProgrammingGuidefordetails).Bydefaultlinksarenottied.
Seealso:tie,untie
timer
timer
Reportshowmanysecondshavepassedsincethecommandreset-timerwaslastrun(orsinceNetLogostarted).Thepotentialresolutionof
theclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfromsystemtosystem,dependingonthecapabilitiesof
theunderlyingJavaVirtualMachine.)
Seealsoreset-timer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsed
modeltimeinticks.
to
toprocedure-name
toprocedure-name[input1...]
Usedtobeginacommandprocedure.
to setup
clear-all
crt 500
end
to circle [radius]
crt 100 [ fd radius ]
end
to-report
to-reportprocedure-name
to-reportprocedure-name[input1...]
Usedtobeginareporterprocedure.
Thebodyoftheprocedureshouldusereporttoreportavaluefortheprocedure.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
Reportstheheadingfromthisagenttothegivenagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardswillusethewrapped
path.
Note:askingfortheheadingfromanagenttoitself,oranagentonthesamelocation,willcausearuntimeerror.
set heading towards turtle 1
;; same as "face turtle 1"
Seealsoface.
towardsxy
towardsxyxy
Reportstheheadingfromtheturtleorpatchtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardsxywillusethewrapped
path.
Since1.0
Since4.0
Since1.0
Since1.0
Since1.0
Since2.0
Note:askingfortheheadingtothepointtheagentisalreadystandingonwillcausearuntimeerror.
Seealsofacexy.
turtle
turtlenumber
<breed>number
Reportstheturtlewiththegivenwhonumber,ornobodyifthereisnosuchturtle.Forbreededturtlesyoumayalsousethesinglebreedform
torefertothem.
ask turtle 5 [ set color red ]
;; turtle with who number 5 turns red
turtle-set
turtle-setvalue1
(turtle-setvalue1value2...)
Reportsanagentsetcontainingalloftheturtlesanywhereinanyoftheinputs.Theinputsmaybeindividualturtles,turtleagentsets,nobody,
orlists(ornestedlists)containinganyoftheabove.
turtle-set self
(turtle-set self turtles-on neighbors)
(turtle-set turtle 0 turtle 2 turtle 9)
(turtle-set frogs mice)
Seealsopatch-set,link-set.
turtles
turtles
Reportstheagentsetconsistingofallturtles.Thisisaspecialagentsetthatcangrowasturtlesareaddedtotheworld,seetheprogramming
guideformoreinfo.
show count turtles
;; prints the number of turtles
turtles-at
turtles-atdxdy
<breeds>-atdxdy
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy)fromthecaller.(Theresultmayincludethecalleritselfifthecallerisaturtle.)
create-turtles 5 [ setxy 2 3 ]
show count [turtles-at 1 1] of patch 1 2
=> 5
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
turtles-here
turtles-here
<breeds>-here
Reportsanagentsetcontainingalltheturtlesonthecaller'spatch(includingthecalleritselfifit'saturtle).
crt 10
ask turtle 0 [ show count turtles-here ]
=> 10
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
breed [cats cat]
breed [dogs dog]
create-cats 5
create-dogs 1
ask dogs [ show count cats-here ]
=> 5
turtles-on
turtles-onagent
Since1.0
turtles-onagentset
<breeds>-onagent
<breeds>-onagentset
Reportsanagentsetcontainingalltheturtlesthatareonthegivenpatchorpatches,orstandingonthesamepatchasthegiventurtleor
turtles.
ask turtles [
if not any? turtles-on patch-ahead 1
[ fd 1 ]
]
ask turtles [
if not any? turtles-on neighbors [
die-of-loneliness
]
]
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
turtles-own
turtles-own[var1...]
<breeds>-own[var1...]
Theturtles-ownkeyword,liketheglobals,breed,<breeds>-own,andpatches-ownkeywords,canonlybeusedatthebeginningofaprogram,
beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachturtle.
Ifyouspecifyabreedinsteadof"turtles",onlyturtlesofthatbreedhavethelistedvariables.(Morethanoneturtlebreedmaylistthesame
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]
Seealsoglobals,patches-own,breed,<breeds>-own.
type
typevalue
PrintsvalueintheCommandCenter,notfollowedbyacarriagereturn(unlikeprintandshow).Thelackofacarriagereturnallowsyoutoprint
severalvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikeshow.
type 3 type " " print 4
=> 3 4
Seealsoprint,show,write,output-type,andOutput(programmingguide).
U
undirected-link-breed
undirected-link-breed[<link-breeds><link-breed>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.It
definesanundirectedlinkbreed.Linksofaparticularbreedarealwayseitheralldirectedorallundirected.Thefirstinputdefinesthenameof
theagentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreedname
hasitsbuilt-invariablebreedsettothatagentset
isdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
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)]
Seealsobreed,directed-link-breed
Since4.0
Since5.0
Since1.0
Since1.0
Since3.1
Since3.1
Since3.1
untie
untie
Untiesend2fromend1(setstie-modeto"none")iftheywerepreviouslytiedtogether.Ifthelinkisanundirectedlink,thenitwilluntieend1
fromend2aswell.Itdoesnotremovethelinkbetweenthetwoturtles.
Seealsotie
SeetheTiesectionoftheProgrammingGuideformoredetails.
update-plots
update-plots
Foreachplot,runsthatplot'supdatecommands,includingtheupdatecodeforanypensintheplot.
tickhasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.Modelsthatusefractionalticksmayneed
update-plots,sincetick-advancedoesnotupdatetheplots.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsosetup-plots.
uphill
uphill4
uphillpatch-variable
uphill4patch-variable
Movestheturtletotheneighboringpatchwiththehighestvalueforpatch-variable.Ifnoneighboringpatchhasahighervaluethanthecurrent
patch,theturtlestaysput.Iftherearemultiplepatcheswiththesamehighestvalue,theturtlepicksonerandomly.Non-numericvaluesare
ignored.
uphillconsiderstheeightneighboringpatches;uphill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
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
]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(uphill)or90(uphill4).
Seealsodownhill,downhill4.
user-directory
user-directory
Opensadialogthatallowstheusertochooseanexistingdirectoryonthesystem.
Itreportsastringwiththeabsolutepathorfalseiftheusercancels.
set-current-directory user-directory
;; Assumes the user will choose a directory
user-file
user-file
Opensadialogthatallowstheusertochooseanexistingfileonthesystem.
Itreportsastringwiththeabsolutefilepathorfalseiftheusercancels.
file-open user-file
;; Assumes the user will choose a file
user-new-file
user-new-file
Opensadialogthatallowstheusertochoosealocationandnameofanewfiletobecreated.Itreportsastringwiththeabsolutefilepathor
falseiftheusercancels.
Since1.1
Since1.1
Since3.1
Since2.0
Since1.0
file-open user-new-file
;; Assumes the user will choose a file
Notethatthisreporterdoesn'tactuallycreatethefile;normallyyouwouldcreatethefileusingfile-open,asintheexample.
Iftheuserchoosesanexistingfile,theywillbeaskediftheywishtoreplaceitornot,butthereporteritselfdoesn'tcausethefiletobe
replaced.Todothatyouwouldusefile-delete.
user-input
user-inputvalue
Reportsthestringthatausertypesintoanentryfieldinadialogwithtitlevalue.
valuemaybeofanytype,butistypicallyastring.
show user-input "What is your name?"
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-message
user-messagevalue
Opensadialogwithvaluedisplayedasthemessagetotheuser.
valuemaybeofanytype,butistypicallyastring.
user-message (word "There are " count turtles " turtles.")
Notethatifauserclosestheuser-messagedialogwiththe"X"inthecorner,thebehaviorwillbethesameasiftheyhadclicked"OK".
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-one-of
user-one-ofvaluelist-of-choices
Opensadialogwithvaluedisplayedasthemessageandlist-of-choicesdisplayedasapopupmenufortheusertoselectfrom.
Reportstheiteminlist-of-choicesselectedbytheuser.
valuemaybeofanytype,butistypicallyastring.
if "yes" = user-one-of "Set up the model?" ["yes" "no"]
[ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-yes-or-no?
user-yes-or-no?value
Reportstrueorfalsebasedontheuser'sresponsetovalue.
valuemaybeofanytype,butistypicallyastring.
if user-yes-or-no? "Set up the model?"
[ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
V
variance
variancelist
Reportsthesamplevarianceofalistofnumbers.Ignoresothertypesofitems.
(Notethatthiscomputesanunbiasedestimateofthevarianceforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
Thesamplevarianceisthesumofthesquaresofthedeviationsofthenumbersfromtheirmean,dividedbyonelessthanthenumberof
numbersinthelist.
show variance [2 7 4 3 5]
=> 3.7
Since1.0
Since3.0
Since3.0
Since1.0
W
wait
waitnumber
Waitthegivennumberofseconds.(Thisneedn'tbeaninteger;youcanspecifyfractionsofseconds.)Notethatyoucan'texpectcomplete
precision;theagentwillneverwaitlessthanthegivenamount,butmightwaitslightlymore.
repeat 10 [ fd 1 wait 0.5 ]
Whiletheagentiswaiting,nootheragentscandoanything.Everythingstopsuntiltheagentisdone.
Seealsoevery.
watch
watchagent
Putsaspotlightonagent.Inthe3Dviewtheobserverwillalsoturntofacethesubject.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-
me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch-me.
watch-me
watch-me
Askstheobservertowatchthisagent.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-
me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch.
while
while[reporter][commands]
Ifreporterreportsfalse,exittheloop.Otherwiseruncommandsandrepeat.
Thereportermayhavedifferentvaluesfordifferentagents,sosomeagentsmayruncommandsadifferentnumberoftimesthanother
agents.
while [any? other turtles-here]
[ fd 1 ]
;; turtle moves until it finds a patch that has
;; no other turtles on it
who
who
Thisisabuilt-inturtlevariable.Itholdstheturtle's"whonumber"orIDnumber,anintegergreaterthanorequaltozero.Youcannotsetthis
variable;aturtle'swhonumberneverchanges.
Whonumbersstartat0.Adeadturtle'snumberwillnotbereassignedtoanewturtleuntilyouusetheclear-turtlesorclear-allcommands,at
whichtimewhonumberingstartsoveragainat0.
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
Youcanusetheturtlereportertoretrieveaturtlewithagivenwhonumber.Seealsoturtle.
Notethatwhonumbersaren'tbreed-specific.Notwoturtlescanhavethesamewhonumber,eveniftheyaredifferentbreeds:
clear-turtles
Since1.0
Since4.0
Since2.1
Since2.1
Since4.0
create-frogs 1
create-mice 1
ask turtles [ print who ]
;; prints (in some random order):
;; (frog 0): 0
;; (mouse 1): 1
Eventhoughweonlyhaveonemouse,itismouse 1notmouse 0,becausethewhonumber0wasalreadytakenbythefrog.
with
agentsetwith[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,abooleanreporter.Reportsanewagentsetcontaining
onlythoseagentsthatreportedtrue--inotherwords,theagentssatisfyingthegivencondition.
show count patches with [pcolor = red]
;; prints the number of red patches
<breed>-with
link-with
<breed>-withturtle
link-withturtle
Reportsalinkbetweenturtleandthecaller(directedorundirected,incomingoroutgoing).Ifnolinkexiststhenitreportsnobody.Ifmorethan
onesuchlinkexists,reportsarandomone.
crt 2
ask turtle 0 [
create-link-with turtle 1
show link-with turtle 1 ;; prints link 0 1
]
Seealso:in-link-from,out-link-to
with-max
agentsetwith-max[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingall
agentsreportingthemaximumvalueofthegivenreporter.
show count patches with-max [pxcor]
;; prints the number of patches on the right edge
Seealsomax-one-of,max-n-of.
with-min
agentsetwith-min[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingonly
thoseagentsthathavetheminimumvalueofthegivenreporter.
show count patches with-min [pycor]
;; prints the number of patches on the bottom edge
Seealsomin-one-of,min-n-of.
with-local-randomness
with-local-randomness[commands]
Thecommandsarerunwithoutaffectingsubsequentrandomevents.Thisisusefulforperformingextraoperations(suchasoutput)without
changingtheoutcomeofamodel.
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 ]
Sinceone-ofisusedinsidewith-local-randomness,bothrunswillbeidentical.
Specificallyhowitworksis,thestateoftherandomnumbergeneratorisrememberedbeforethecommandsrun,thenrestoredafterwards.(If
youwanttorunthecommandswithafreshrandomstateinsteadofthesamerandomstatethatwillberestoredlater,youcanbeginthe
Since1.1
Since1.0
Since3.1
Since3.1
Since1.0
Since2.0
commandswithrandom-seed new-seed.)
Thefollowingexampledemonstratesthattherandomnumbergeneratorstateisthesamebothbeforethecommandsrunandafterwards.
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]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitinnewmodels.
Theagentrunsallthecommandsintheblockwithoutallowingotheragentsusingask-concurrentto"interrupt".Thatis,otheragentsareput
"onhold"anddonotrunanycommandsuntilthecommandsintheblockarefinished.
Note:Thiscommandisonlyusefulinconjunctionwithask-concurrent.
Seealsoask-concurrent.
word
wordvalue1value2
(wordvalue1...)
Concatenatestheinputstogetherandreportstheresultasastring.
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
ThesereportersgivethetotalwidthandheightoftheNetLogoworld.
Thewidthequalsmax-pxcor-min-pxcor+1andtheheightequalsmax-pycor-min-pycor+1.
Seealsomax-pxcor,max-pycor,min-pxcor,andmin-pycor
wrap-color
wrap-colornumber
wrap-colorcheckswhethernumberisintheNetLogocolorrangeof0to140(notincluding140itself).Ifitisnot,wrap-color"wraps"the
numericinputtothe0to140range.
Thewrappingisdonebyrepeatedlyaddingorsubtracting140fromthegivennumberuntilitisinthe0to140range.(Thisisthesame
wrappingthatisdoneautomaticallyifyouassignanout-of-rangenumbertothecolorturtlevariableorpcolorpatchvariable.)
show wrap-color 150
=> 10
show wrap-color -10
=> 130
write
writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytotheCommandCenter,notfollowedbyacarriage
return(unlikeprintandshow).
Thisagentisnotprintedbeforethevalue,unlikeshow.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.
write "hello world"
=> "hello world"
Since1.0
Since6.0
Seealsoprint,show,type,output-write,andOutput(programmingguide).
X
xcor
xcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentxcoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pxcor-0.5)andstrictlylessthan(max-pxcor+0.5).
Seealsosetxy,ycor,pxcor,pycor,
xor
boolean1xorboolean2
Reportstrueifeitherboolean1orboolean2istrue,butnotwhenbotharetrue.
if (pxcor > 0) xor (pycor > 0)
[ set pcolor blue ]
;; upper-left and lower-right quadrants turn blue
Y
ycor
ycor
Thisisabuilt-inturtlevariable.Itholdsthecurrentycoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pycor-0.5)andstrictlylessthan(max-pycor+0.5).
Seealsosetxy,xcor,pxcor,pycor,
->
->
[[args]->commands]
[[args]->reporter]
Createsandreportsananonymousprocedure-acommandorreporter-dependingontheinput.Withincommandsorreporterthelistedargs
maybeusedjustasyouwoulduseletorprocedurevariables.Thevariablenamesinargshavethesamerestrictionsasvariablenamesof
commandsandreporters.Inaddition,theymustnotmatchthenameofanyletorprocedurevariableintheirprocedure.
Anonymousproceduresarecommonlyusedwiththeprimitivesforeach,map,reduce,filter,sort-by,andn-values.Seethoseentriesfor
exampleusage.
SeetheAnonymousProceduressectionoftheProgrammingGuidefordetails.