Categories of Primitives

This is an approximate grouping. Remember that a turtle-related primitive might still be called by patches or observers, and vice versa. To see which agent (turtles, patches, observer) can actually run each command, consult each individual entry in the dictionary.

Turtle-related

back (bk) BREED-at BREED-here BREED-on clear-turtles (ct) create-BREED create-custom-BREED create-custom-turtles (cct) create-turtles (crt) die distance distance-nowrap distancexy distancexy-nowrap downhill downhill4 dx dy forward (fd) hatch hideturtle (ht) home inspect is-turtle? jump left (lt) myself no-label nobody -of other-turtles-here other-BREED-here patch-ahead patch-here patch-left-and-ahead patch-right-and-ahead pen-down (pd) pen-up (pu) right (rt) self set-default-shape setxy showturtle (st) sprout stamp towards towards-nowrap towardsxy towardsxy-nowrap turtle turtles turtles-at turtles-from turtles-here turtles-on turtles-own uphill value-from

Patch-related primitives

clear-patches (cp) diffuse diffuse4 distance distance-nowrap distancexy distancexy-nowrap inspect is-patch? myself neighbors neighbors4 no-label nobody nsum nsum4 -of patch patch-at patch-ahead patch-at-heading-and-distance patch-here patch-left-and-ahead patch-right-and-ahead patches patches-from patches-own self sprout value-from

Agentset primitives

any? ask at-points BREED-at BREED-here BREED-on count histogram-from in-radius in-radius-nowrap is-agent? is-agentset? is-patch-agentset? is-turtle-agentset? max-one-of min-one-of neighbors neighbors4 one-of other-turtles-here other-BREED-here patches patches-from random-n-of random-one-of turtles with turtles-at turtles-from turtles-here turtles-on values-from

Color primitives

extract-hsb extract-rgb hsb rgb scale-color shade-of? wrap-color

Control flow and logic primitives

and end foreach if ifelse ifelse-value locals loop map not or repeat report run runresult ; (semicolon) stop startup to to-report wait while without-interruption xor

Display primitives

clear-all (ca) clear-graphics (cg) clear-patches (cp) clear-turtles (ct) display no-display no-label screen-edge-x screen-edge-y screen-size-x screen-size-y

HubNet primitives

hubnet-broadcast hubnet-enter-message? hubnet-exit-message? hubnet-fetch-message hubnet-message hubnet-message-source hubnet-message-tag hubnet-message-waiting? hubnet-reset hubnet-send hubnet-set-client-interface

Input/output primitives

clear-output export-graphics export-interface export-output export-plot export-all-plots export-world get-date-and-time import-world mouse-down? mouse-xcor mouse-ycor print read-from-string reset-timer set-current-directory show timer type user-choice user-choose-directory user-choose-file user-choose-new-file user-input user-message user-yes-or-no? write

File primitives

file-at-end? file-close file-close-all file-delete file-exists? file-open file-print file-read file-read-characters file-read-line file-show file-type file-write user-choose-directory user-choose-file user-choose-new-file

List primitives

but-first but-last empty? filter first foreach fput is-list? item last length list lput map member? modes n-values position random-n-of random-one-of reduce remove remove-duplicates remove-item replace-item reverse sentence shuffle sort sort-by values-from

String primitives

Operators (+, <, >, =, !=, <=, >=) but-first but-last empty? first is-string? item last length member? position remove remove-item read-from-string replace-item reverse substring word

Mathematical primitives

Arithmetic Operators (+, *, -, /, ^, <, >, =, !=, <=, >=) abs acos asin atan ceiling cos e exp floor int ln log max mean median min mod modes pi precision random random-exponential random-float random-gamma random-int-or-float random-normal random-poisson random-seed remainder round sin sqrt standard-deviation sum tan variance

Plotting primitives

autoplot? auto-plot-off auto-plot-on clear-all-plots clear-plot create-temporary-plot-pen export-plot export-all-plots histogram-from histogram-list plot plot-name plot-pen-down (ppd) plot-pen-reset plot-pen-up (ppu) plot-x-max plot-x-min plot-y-max plot-y-min plotxy ppd ppu set-current-plot set-current-plot-pen set-histogram-num-bars set-plot-pen-color set-plot-pen-interval set-plot-pen-mode set-plot-x-range set-plot-y-range

Built-In Variables

Turtles

breed color heading hidden? label label-color pen-down? shape size who xcor ycor

Patches

pcolor plabel plabel-color pxcor pycor

Other

?

Keywords

breeds end globals locals patches-own to to-report turtles-own

Constants

Mathematical Constants

e = 2.718281828459045
pi = 3.141592653589793

Boolean Constants

false
true

Color Constants

The allowable range of values for colors is 0 up to but not including 140. Each color ranges from black to white over a scale of ten. Thus the color red goes from black (10) to dark red (11) to red (15) to light red (19) to white (19.9999). The scale is discontinuous; 19.9999 is white, but 20.0 is black.

The available color names are listed below. (See also the rgb and hsb primitives.)

black = 0
gray = 5
white = 9.9999
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

A

abs

abs number

Reports the absolute value of number.

show abs -7
=> 7
show abs 5
=> 5

acos

acos number

Reports the arc cosine (inverse cosine) of the given number. The input must be in the range -1.0 to 1.0. The result is in degrees, and lies in the range 0.0 to 180.0.

and

condition1 and condition2

Reports true if both condition1 and condition2 are true.

Note that if condition1 is false, then condition2 will not be run (since it can't affect the result).

if (pxcor > 0) and (pycor > 0)
  [ set pcolor blue ]  ;; the upper-right quadrant of
                       ;; patches turn blue

any?

any? agentset

Reports true if the given agentset is non-empty, false otherwise.

Equivalent to "count agentset > 0", but arguably more readable.

if any? turtles with [color = red]
  [ show "at least one turtle is red!" ]

Arithmetic Operators (+, *, -, /, ^, <, >, =, !=, <=, >=)

All of these operators take two inputs, and all act as "infix operators" (going between the two inputs, as in standard mathematical use). NetLogo correctly supports order of operations for infix operators.

The operators work as follows: + is addition, * is multiplication, - is subtraction, / is division, ^ is exponentiation, < is less than, > is greater than, = is equal to, != is not equal to, <= is less than or equal, >= is greater than or equal.

Note that the subtraction operator (-) always takes two inputs unless you put parentheses around it, in which case it can take one input. For example, to take the negative of x, then write (- x).

All of the comparison operators also work on strings, and the addition operator (+) also functions as a string concatenation operator (see example below).

If you are not sure how NetLogo will interpret your code, you should insert parentheses.

show 5 * 6 + 6 / 3
=> 32
show 5 * (6 + 6) / 3
=> 20
show "tur" + "tle"
=> "turtle"

asin

asin number

Reports the arc sine (inverse sine) of the given number. The input must be in the range -1.0 to 1.0. The result is in degrees, and lies in the range -90.0 to 90.0.

ask

ask agentset [commands]
ask agent [commands]

Takes a list of commands that will be run by the specified agent or agentset.

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

at-points

agentset at-points [[x1 y1] [x2 y2] ...]

Reports a subset of the given agentset that includes only the agents on the patches the given distances away from the calling agent. The distances are specified as a list of two-item lists, where the two items are the x and y offsets.

If the caller is the observer, then the points are measured relative to the origin, in other words, the points are taken as absolute patch coordinates.

If the caller is a turtle, the points are measured relative to the turtle's exact location, and not from the center of the patch under the turtle.

ask turtles at-points [[2 4] [1 2] [10 15]]
[ fd 1 ]  ;; only the turtles on the patches at the
          ;; distances (2,4), (1,2) and (10,15),
          ;; relative to the caller, move

atan

atan x y

Reports the arc tangent, in degrees (from 0 to 360), of x divided by y.

When y is 0: if x is positive, it reports 90; if x is negative, it reports 270; if x is zero, you get an error.

Note that this version of atan is designed to conform to the geometry of the NetLogo world, where a heading of 0 is straight up, 90 is to the right, and so on clockwise around the circle. (Normally in geometry an angle of 0 is right, 90 is up, and so on, counterclockwise around the circle, and atan would be defined accordingly.)

show atan 1 -1
=> 135.0
show atan -1 1
=> 315.0

autoplot?

autoplot?

Reports true if auto-plotting is on for the current plot, false otherwise.

auto-plot-off
auto-plot-on

auto-plot-off
auto-plot-on

This pair of commands is used to control the NetLogo feature of auto-plotting in the current plot. Auto-plotting will automatically update the x and y axes of the plot whenever the current pen exceeds these boundaries. It is useful when wanting to display all plotted values in the current plot, regardless of the current plot ranges.

B

back
bk

back number
Turtle Command

The turtle moves backward by number steps. (If number is negative, the turtle moves forward.)

Turtles using this primitive can move a maximum of one unit per time increment. So bk 0.5 and bk 1 both take one unit of time, but bk 3 takes three.

See also forward, jump.

breed

breed
Turtle Command

This is a built-in turtle variable. It holds the agentset of all turtles of the same breed as this turtle. (For turtles that do not have any particular breed, this is the turtles agentset of all turtles.) You can set this variable to change a turtle's breed.

See also breeds.

Example:

breeds [cats dogs]
;; turtle code:
if breed = cats [ show "meow!" ]
set breed dogs
show "woof!"

breeds

breeds [breed1 breed2 ...]

This keyword, like the globals, turtles-own, and patches-own keywords, can only be used at the beginning of a program, before any function definitions. It defines breeds and their associated agentsets.

Any turtle of the given breed:

Most often, the agentset is used in conjunction with ask to give commands to only the turtles of a particular breed.

breeds [ mice frogs ]
to setup
  ca
  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

See also globals, patches-own, turtles-own, <BREED>-own, create-<BREED>, create-custom-<BREED>, <BREED>-at, <BREED>-here.

but-first
bf
but-last
bl

but-first list
but-first string
but-last list
but-last string

When used on a list, but-first reports all of the list items of list except the first, and but-last reports all of the list items of list except the last.

On strings, but-first and but-last report a shorter string omitting the first or last character of the original string.

;; mylist is [2 4 6 5 8 12]
set mylist but-first mylist
;; mylist is now [4 6 5 8 12]
set mylist but-last mylist
;; mylist is now [4 6 8]
show but-first "string"
;; prints "tring"
show but-last "string"
;; prints "strin"

C

ceiling

ceiling number

Reports the smallest integer greater than or equal to number.

show ceiling 4.5
=> 5
show ceiling -4.5
=> -4

clear-all
ca

clear-all
Observer Command

Kills all turtles, resets all global variables to zero, and calls clear-patches and clear-all-plots.

clear-all-plots

clear-all-plots
Observer Command

Clears every plot in the model. See clear-plot for more information.

clear-graphics
cg

clear-graphics
Observer Command

Kills all turtles and clears all patches. Combines the effect of clear-turtles and clear-patches.

clear-output
cc

clear-output
Observer Command

Clears all text from the output portion of the Command Center.

clear-patches
cp

clear-patches
Observer Command

Clears the patches by resetting all patch variables to their default initial values, including setting their color to black.

clear-plot

clear-plot

In the current plot only, resets all plot pens, deletes all temporary plot pens, resets the plot to its default values (for x range, y range, etc.), and resets all permanent plot pens to their default values. The default values for the plot and for the permanent plot pens are set in the plot Edit dialog, which is displayed when you edit the plot. If there are no plot pens after deleting all temporary pens, that is to say if there are no permanent plot pens, a default plot pen will be created with the following initial settings:

See also clear-all-plots.

clear-turtles
ct

clear-turtles
Observer Command

Kills all turtles.

See also die.

color

color
Turtle Command

This is a built-in turtle variable. It holds the color of the turtle. You can set this variable to make the turtle change color.

See also pcolor.

cos

cos number

Reports the cosine of the given angle. Assumes the angle is given in degrees.

show cos 180
=> -1.0

count

count agentset

Reports the number of agents in the given agentset.

show count turtles
;; prints the total number of turtles
show count patches with [pcolor = red]
;; prints the total number of red patches

create-turtles
crt
create-<BREED>

create-turtles number
create-<BREED> number
Observer Command

Creates number new turtles . New turtles start at position (0, 0), are created with the 14 primary colors, and have headings from 0 to 360, evenly spaced.

crt 100
ask turtles [ fd 10 ] ;; makes an evenly spaced circle

If the create-<BREED> form is used, the new turtles are created as members of the given breed.

create-custom-turtles
cct
create-custom-<BREED>
cct-<BREED>

create-custom-turtles number [ commands ]
create-custom-<BREED> number [ commands ]
Observer Command

Creates number new turtles (of the given breed, if specified). New turtles start at position (0, 0). New turtles are created with the 14 primary colors and have headings from 0 to 360, evenly spaced.

The new turtles immediately run commands. This is useful for giving the new turtles a different color, heading, or whatever.

breeds [canaries snakes]
to setup
  ca
  create-custom-canaries 50
    [ set color yellow ]
  create-custom-snakes 50
    [ set color green ]
end

Note: While the commands are running, no other agents are allowed to run any code (as with the without-interruption command). This ensures that the new turtles cannot interact with any other agents until they are fully initialized. In addition, no screen updates take place until the commands are done. This ensures that the new turtles are never drawn on-screen until they are fully initialized.

create-temporary-plot-pen

create-temporary-plot-pen string

A new temporary plot pen with the given name is created in the current plot and set to be the current pen.

Few models will want to use this primitive, because all temporary pens disappear when clear-plot or clear-all-plots are called. The normal way to make a pen is to make a permanent pen in the plot's Edit dialog.

If a temporary pen with that name already exists in the current plot, no new pen is created, and the existing pen is set to the the current pen. If a permanent pen with that name already exists in the current plot, you get a runtime error.

The new temporary plot pen has the following initial settings:

See: clear-plot, clear-all-plots, and set-current-plot-pen.

D

die

die
Turtle Command

The turtle dies.

if xcor > 20 [ die ]

;; all turtles with xcor greater than 20 die

See also: ct

diffuse

diffuse patch-variable number
Observer Command

Tells each patch to share (number * 100) percent of the value of patch-variable with its eight neighboring patches. number should be between 0 and 1.

Note that this is an observer command only, even though you might expect it to be a patch command. (The reason is that it acts on all the patches at once -- patch commands act on individual patches.)

diffuse chemical 0.5
;; each patch diffuses 50% of its variable
;; chemical to its neighboring 8 patches. Thus,
;; each patch gets 1/8 of 50% of the chemical
;; from each neighboring patch.)

diffuse4

diffuse4 patch-variable number
Observer Command

Like diffuse, but only diffuses to the four neighboring patches (to the north, south, east, and west), not to the diagonal neighbors.

diffuse4 chemical 0.5
;; each patch diffuses 50% of its variable
;; chemical to its neighboring 4 patches. Thus,
;; each patch gets 1/4 of 50% of the chemical
;; from each neighboring patch.)

display

display

Causes the graphics window to be updated immediately.

Also undoes the effect of the no-display command, so that if display updates were suspended by that command, they will resume.

no-display
ask turtles [ jump 10 set color blue set size 5 ]
display
;; turtles move, change color, and grow, with none of
;; their intermediate states visible to the user, only
;; their final state

Even if no-display was not used, "display" can still be useful, because ordinarily NetLogo is free to skip some screen updates, so that fewer total updates take place, so that models run faster. This command lets you force a display update, so whatever changes have taken place in the world are visible to the user.

ask turtles [ set color red ]
display
ask turtles [ set color blue]
;; turtles turn red, then blue; use of "display" forces
;; red turtles to appear briefly

There is exception to the "immediately" rule: if the command is used by an agent that is running "without interruption" (such as via the without-interruption command, inside a procedure defined using to-report, or inside a command such as hatch, sprout, or cct), then the display update takes place once the agent is done running without interruption.

Note that display and no-display operate independently of the switch in the graphics window control strip that freezes the display.

See also no-display.

distance

distance agent
Turtle Command Patch Command

Reports the distance from this agent to the given turtle or patch.

The distance to or a from a patch is measured from the center of the patch.

Unlike "distance-nowrap", turtles and patches use the wrapped distance (around the edges of the screen) if that distance is shorter than the on-screen distance.

distance-nowrap

distance-nowrap agent
Turtle Command Patch Command

Reports the distance from this agent to the given turtle or patch.

The distance to or a from a patch is measured from the center of the patch.

Unlike "distance", this always reports the on-screen distance, never a distance that would require wrapping around the edges of the screen.

distancexy

distancexy xcor ycor
Turtle Command Patch Command

Reports the distance from this agent to the point (xcor, ycor).

The distance from a patch is measured from the center of the patch.

Unlike "distancexy-nowrap", the wrapped distance (around the edges of the screen) is used if that distance is shorter than the on-screen distance.

if (distancexy 0 0) > 10
  [ set color green ]
;; all turtles more than 10 units from
;; the center of the screen turn green.

distancexy-nowrap

distancexy-nowrap xcor ycor
Turtle Command Patch Command

Reports the distance from this agent to the point (xcor, ycor).

The distance from a patch is measured from the center of the patch.

Unlike "distancexy", this always reports the on-screen distance, never a distance that would require wrapping around the edges of the screen.

downhill

downhill patch-variable
Turtle Command

Reports the turtle heading (between 0 and 359 degrees) in the direction of the minimum value of the variable patch-variable, of the patches in a one-patch radius of the turtle. (This could be as many as eight or as few as five patches, depending on the position of the turtle within its patch.)

If there are multiple patches that have the same smallest value, a random one of those patches will be selected.

If the patch is located directly to the north, south, east, or west of the patch that the turtle is currently on, a multiple of 90 degrees is reported. However, if the patch is located to the northeast, northwest, southeast, or southwest of the patch that the turtle is currently on, the direction the turtle would need to reach the nearest corner of that patch is reported.

See also downhill4, uphill, uphill4.

downhill4

downhill4 patch-variable
Turtle Command

Reports the turtle heading (between 0 and 359 degrees) as a multiple of 90 degrees in the direction of the minimum value of the variable patch-variable, of the four patches to the north, south, east, and west of the turtle. If there are multiple patches that have the same least value, a random patch from those patches will be selected.

See also downhill, uphill, uphill4.

dx
dy

dx
dy
Turtle Command

Reports the x-increment or y-increment (the amount by which the turtle's xcor or ycor would change) if the turtle were to take one step forward in its current heading.

Note: dx is simply the sine of the turtle's heading, and dy is simply the cosine. (If this is the reverse of what you expected, it's because in NetLogo a heading of 0 is north and 90 is east, which is the reverse of how angles are usually defined in geometry.)

Note: In earlier versions of NetLogo, these primitives were used in many situations where the new patch-ahead primitive is now more appropriate.

E

empty?

empty? list
empty? string

Reports true if the given list or string is empty, false otherwise.

Note: the empty list is written []. The empty string is written "".

end

end

Used to conclude a procedure. See to and to-report.

every

every number [ commands ]

Runs the given commands at most every number seconds.

By itself, every doesn't make commands run over and over again. You need to use every inside a loop, or inside a forever button, if you want the commands run over and over again. every only limits how often the commands run.

More technically, its exact behavior is as follows. When an agent reaches an "every", it checks a timer to see if the given amount of time has passed since the last time the same agent ran the commands in the "every" in the same context. If so, it runs the commands; otherwise they are skipped and execution continues.

Here, "in the same context" means during the same ask (or button press or command typed in the Command Center). So it doesn't make sense to write ask turtles [ every 0.5 [ ... ] ], because when the ask finishes the turtles will all discard their timers for the "every". The correct usage is shown below.

every 0.5 [ ask turtles [ fd 1 ] ]
;; twice a second the turtles will move forward 1
every 2 [ set index index + 1 ]
;; every 2 seconds index is incremented

See also wait.

exp

exp number

Reports the value of e raised to the number power.

Note: This is the same as e ^ number.

export-graphics
export-interface
export-output
export-plot
export-all-plots
export-world

export-graphics filename
export-interface filename
export-output filename
export-plot plotname filename
export-all-plots filename
export-world filename

export-graphics writes the current contents of the graphics window to an external file given by the string filename. The file is saved in PNG (Portable Network Graphics) format, so it is recommended to supply a filename ending in ".png".

export-interface is similar, but for the whole interface tab, not just the graphics window.

export-output writes the contents of the output portion of the Command Center to an external file given by the string filename.

export-plot writes the x and y values of all points plotted by all the plot pens in the plot given by the string plotname to an external file given by the string filename. If a pen is in bar mode (mode 0) and the y value of the point plotted is greater than 0, the upper-left corner point of the bar will be exported. If the y value is less than 0, then the lower-left corner point of the bar will be exported.

export-all-plots writes every plot in the current model to an external file given by the string filename. Each plot is identical in format to the output of export-plot.

export-world writes the values of all variables, both built-in and user-defined, including all observer, turtle, and patch variables, to an external file given by the string filename. (The result file can be read back into NetLogo with the import-world primitive.)

export-plot, export-all-plots and export-world save files in in plain-text, "comma-separated values" (.csv) format. CSV files can be read by most popular spreadsheet and database programs as well as any text editor.

If the file already exists, it is overwritten.

If you wish to export to a file in a location other than the model's location, you should include the full path to the file you wish to export. (Use the forward-slash "/" as the folder separator.)

Note that the functionality of these primitives is also available directly from NetLogo's File menu.

export-world "fire.csv"
;; exports the state of the model to the file fire.csv
;; located in the NetLogo folder
export-plot "Temperature" "c:/My Documents/plot.csv"
;; exports the plot named
;; "Temperature" to the file plot.csv located in
;; the C:\My Documents folder
export-all-plots "c:/My Documents/plots.csv"
;; exports all plots to the file plots.csv
;; located in the C:\My Documents folder

extract-hsb

extract-hsb color

Reports a list of three values in the range 0.0 to 1.0 representing the hue, saturation and brightness, respectively, of the given NetLogo color in the range 0 to 140.

show extract-hsb red
=> [0.0 1.0 1.0]
show extract-hsb cyan
=> [0.5 1.0 1.0]

See also hsb, rgb, extract-rgb.

extract-rgb

extract-rgb color

Reports a list of three values in the range 0.0 to 1.0 representing the levels of red, green, and blue, respectively, of the given NetLogo color in the range 0 to 140.

show extract-rgb red
=> [1.0 0.0 0.0]
show extract-rgb cyan
=> [0.0 1.0 1.0]

See also rgb, hsb, extract-hsb.

F

file-at-end?

file-at-end?

Reports true when there are no more characters left to read in from the current file (that was opened previously with file-open). Otherwise, reports false.

file-open "myfile.txt"
print file-at-end?
=> false ;; Can still read in more characters
print file-read-line
=> This is the last line in file
print file-at-end
=> true ;; We reached the end of the file

See also file-open, file-close-all.

file-close

file-close

Closes a file that has been opened previously with file-open.

Note that this and file-close-all are the only ways to restart to the beginning of an opened file or to switch between file modes.

If no file is open, does nothing.

See also file-close-all, file-open.

file-close-all

file-close-all

Closes all files (if any) that have been opened previously with file-open.

See also file-close, file-open.

file-delete

file-delete string

Deletes the file specified as string

string must be an existing file with writable permission by the user. Also, the file cannot be open. Use the command file-close to close an opened file before deletion.

Note that the string can either be a file name or an absolute file path. If it is a file name, it looks in whatever the current directory is. This can be changed using the command set-current-directory. It is defaulted to the model's directory.

file-exists?

file-exists? string

Reports true if string is the name of an existing file on the system. Otherwise it reports false.

Note that the string can either be a file name or an absolute file path. If it is a file name, it looks in whatever the current directory is. This can be changed using the command set-current-directory. It defaults to to the model's directory.

file-open

file-open string

This command will interpret string as a path name to a file and open the file. You may then use the reporters file-read, file-read-line, and file-read-characters to read in from the file, or file-write, file-print, file-type, or file-show to write out to the file.

Note that you can only open a file for reading or writing but not both. The next file i/o primitive you use after this command dictates which mode the file is opened in. To switch modes, you need to close the file using file-close.

Also, the file must exist when opening a file in reading mode. When opening a file in writing mode, all new data will be appended to the end of the original file. If there is no original file, a new blank file will be created in its place (The user needs to have writable permission in the file's directory).

Note that the string can either be a file name or an absolute file path. If it is a file name, it looks in whatever the current directory is. This can be changed using the command set-current-directory. It is defaulted to the model's directory.

file-open "myfile-in.txt"
print file-read-line
=> First line in file ;; File is in reading mode
file-open "C:\\NetLogo\\myfile-out.txt"
;; assuming Windows machine
file-print "Hello World" ;; File is in writing mode

See also file-close.

file-print

file-print value

Prints value to an opened file, followed by a carriage return.

The calling agent is not printed before the value, unlike file-show.

Note that this command is the file i/o equivalent of print, and file-open needs to be called before this command can be used.

See also file-show, file-type, and file-write.

file-read

file-read

This reporter will read in the next constant from the opened file and interpret it as if it had been typed in the Command Center. It reports the resulting value. The result may be a number, list, string, boolean, or the special value nobody.

Whitespace separates the constants. Each call to file-read will skip past both leading and trailing whitespace.

Note that strings need to have quotes around them. Use the command file-write to have quotes included.

Also note that the file-open command must be called before this reporter can be used, and there must be data remaining in the file. Use the reporter file-at-end? to determine if you are at the end of the file.

file-open "myfile.data"
print file-read + 5
;; Next value is the number 1
=> 6
print length file-read
;; Next value is the list [1 2 3 4]
=> 4

See also file-open and file-write.

file-read-characters

file-read-characters number

Reports the given number of characters from an opened file as a string. If there are fewer than that many characters left, it will report all of the remaining characters.

Note that it will return every character including newlines and spaces.

Also note that the file-open command must be called before this reporter can be used, and there must be data remaining in the file. Use the reporter file-at-end? to determine if you are at the end of the file.

file-open "myfile.txt"
print file-read-characters 8
;; Current line in file is "Hello World"
=> Hello Wo

See also file-open.

file-read-line

file-read-line

Reads the next line in the file and reports it as a string. It determines the end of the file by a carriage return, an end of file character or both in a row. It does not return the line terminator characters.

Also note that the file-open command must be called before this reporter can be used, and there must be data remaining in the file. Use the reporter file-at-end? to determine if you are at the end of the file.

file-open "myfile.txt"
print file-read-line
=> Hello World

See also file-open.

file-show

file-show value

Prints value to an opened file, preceded by the calling agent, and followed by a carriage return. (The calling agent is included to help you keep track of what agents are producing which lines of output.) Also, all strings have their quotes included similar to file-write.

Note that this command is the file i/o equivalent of show, and file-open needs to be called before this command can be used.

See also file-print, file-type, and file-write.

file-type

file-type value

Prints value to an opened file, not followed by a carriage return (unlike file-print and file-show). The lack of a carriage return allows you to print several values on the same line.

The calling agent is not printed before the value. unlike file-show.

Note that this command is the file i/o equivalent of type, and file-open needs to be called before this command can be used.

See also file-print, file-show, and file-write.

file-write

file-write value

This command will output value, which can be a number, string, list, boolean, or nobody to an opened file not followed by a carriage return (unlike file-print and file-show).

The calling agent is not printed before the value, unlike file-show. Its output will also includes quotes around strings and is prepended with a space. It will output the value in such a manner that file-read will be able to interpret it.

Note that this command is the file i/o equivalent of write, and file-open needs to be called before this command can be used.

file-open "locations.txt"
ask turtles 
  [ file-write xcor file-write ycor ]

See also file-print, file-show, and file-type.

filter

filter [reporter] list

Reports a list containing only those items of list for which the boolean reporter is true -- in other words, the items satisfying the given condition.

In reporter, use ? to refer to the current item of list.

show filter [? < 3] [1 3 2]
=> [1 2]
show filter [first ? != "t"] ["hi" "there" "everyone"]
=> ["hi" "everyone"]

See also map, reduce, ?.

first

first list
first string

On a list, reports the first (0th) item in the list.

On a string, reports a one-character string containing only the first character of the original string.

floor

floor number

Reports the largest integer less than or equal to number.

show floor 4.5
=> 4
show floor -4.5
=> -5

foreach

foreach list [ commands ]
(foreach list1 ... listn [ commands ])

With a single list, runs commands for each item of list. In commands, use ? to refer to the current item of list.

foreach [1.1 2.2 2.6] [ show ? + " -> " + round ? ]
=> 1.1 -> 1
=> 2.2 -> 2
=> 2.6 -> 3

With multiple lists, runs commands for each group of items from each list. So, they are run once for the first items, once for the second items, and so on. All the lists must be the same length. In commands, use ?1 through ?n to refer to the current item of each list.

Some examples make this clearer:

(foreach [1 2 3] [2 4 6]
   [ show "the sum is: " + (?1 + ?2) ])
=> "the sum is: 3"
=> "the sum is: 6"
=> "the sum is: 9"
(foreach list (turtle 1) (turtle 2) [3 4]
  [ ask ?1 [ fd ?2 ] ])
;; turtle 1 moves forward 3 patches
;; turtle 2 moves forward 4 patches

See also map, ?.

forward
fd

forward number
Turtle Command

The turtle moves forward by number steps. (If number is negative, the turtle moves backward.)

Turtles using this primitive can move a maximum of one unit per time increment. So fd 0.5 and fd 1 both take one unit of time, but fd 3 takes three.

See also jump.

fput

fput item list

Adds item to the beginning of a list and reports the new list.

;; suppose mylist is [5 7 10]
set mylist fput 2 mylist
;; mylist is now [2 5 7 10]

G

get-date-and-time

get-date-and-time

Reports a string containing the current date and time. The format is shown below. All fields are fixed width, so they are always at the same locations in the string. The potential resolution of the clock is milliseconds. (Whether you get resolution that high in practice may vary from system to system, depending on the capabilities of the underlying Java Virtual Machine.)

show get-date-and-time
=> "01:19:36.685 PM 19-Sep-2002"

globals

globals [var1 var2 ...]

This keyword, like the breeds, <BREED>-own, patches-own, and turtles-own keywords, can only be used at the beginning of a program, before any function definitions. It defines new global variables. Global variables are "global" because they are accessible by all agents and can be used anywhere in a model.

Most often, globals is used to define variables or constants that need to be used in many parts of the program.

H

hatch

hatch number [ commands ]
Turtle Command

Each turtle creates number new turtles, each identical to itself, and tells the new turtles to run commands. This is useful for giving the new turtles different colors, headings, breeds, or whatever.

Note: While the commands are running, no other agents are allowed to run any code (as with the without-interruption command). This ensures that the new turtles cannot interact with any other agents until they are fully initialized. In addition, no screen updates take place until the commands are done. This ensures that the new turtles are never drawn on-screen in an only partly initialized state.

hatch 1 [ lt 45 fd 1 ]
;; each turtle creates one new turtle,
;; and the child turns and moves away

heading

heading
Turtle Command

This is a built-in turtle variable. It indicates the direction the turtle is facing. This is a number greater than or equal to 0 and less than 360. 0 is north, 90 is east, and so on. You can set this variable to make a turtle turn.

See also right, left, dx, dy.

Example:

set heading 45      ;; turtle is now facing northeast
set heading heading + 10 ;; same effect as "rt 10"

hidden?

hidden?
Turtle Command

This is a built-in turtle variable. It holds a boolean (true or false) value indicating whether the turtle is currently hidden (i.e., invisible). You can set this variable to make a turtle disappear or reappear.

See also hideturtle, showturtle.

Example:

set hidden? not hidden?
;; if turtle was showing, it hides, and if it was hiding,
;; it reappears

hideturtle
ht

hideturtle
Turtle Command

The turtle makes itself invisible.

Note: This command is equivalent to setting the turtle variable "hidden?" to true.

See also showturtle.

histogram-from

histogram-from agentset [ reporter ]

Removes points drawn by the current plot pen, then draws a histogram of the values reported when all agents in the agentset run the given reporter. (It should report a numeric value. Any non-numeric values reported are ignored.)

The histogram is drawn on the current plot using the current plot pen and pen color. Use set-plot-x-range to control the range of values to be histogrammed, and set the pen interval (either directly with set-plot-pen-interval, or indirectly via set-histogram-num-bars) to control how many bars that range is split up into.

Be sure that if you want the histogram drawn with bars that the current pen is in bar mode (mode 1).

As of NetLogo 2.0.2, for histogramming purposes the plot's X range is not considered to include the maximum X value. Values equal to the maximum X will fall outside of the histogram's range.

histogram-from turtles [color]
;; draws a histogram showing how many turtles there are
;; of each color

Note: using this primitive amounts to the same thing as writing: histogram-list values-from agentset [ reporter ], but is more efficient.

histogram-list

histogram-list list

Removes points drawn by the current plot pen, then draws a histogram of the values in the given list.

See histogram-from, above, for more information.

home

home
Turtle Command

Moves the turtle to the origin. Equivalent to setxy 0 0.

hsb

hsb hue saturation brightness

Reports a number in the range 0 to 140, not including 140 itself, that represents the given color, specified in the HSB spectrum, in NetLogo's color space.

All three values should be in the range 0.0 to 1.0.

The color reported may be only an approximation, since the NetLogo color space does not include all possible colors. (It contains only certain discrete hues, and for each hue, either saturation or brightness may vary, but not both -- at least one of the two is always 1.0.)

show hsb 0 0 0
=> 0.0  ;; (black)
show hsb 0.5 1.0 1.0
=> 85.0 ;; (cyan)

See also extract-hsb, rgb, extract-rgb.

hubnet-broadcast

hubnet-broadcast tag-name value

This broadcasts value from NetLogo to the variable, in the case of Calculator HubNet, or interface element, in the case of Computer HubNet, with the name tag-name to the clients.

See the HubNet Authoring Guide for details and instructions.

hubnet-enter-message?

hubnet-enter-message?

Reports true if a new computer client just entered the simulation. Reports false otherwise. hubnet-message-source will contain the user name of the client that just logged on.

See the HubNet Authoring Guide for details and instructions.

hubnet-exit-message?

hubnet-exit-message?

Reports true if a computer client just exited the simulation. Reports false otherwise. hubnet-message-source will contain the user name of the client that just logged off.

See the HubNet Authoring Guide for details and instructions.

hubnet-fetch-message

hubnet-fetch-message

If there is any new data sent by the clients, this retrieves the next piece of data, so that it can be accessed by hubnet-message, hubnet-message-source, and hubnet-message-tag. This will cause an error if there is no new data from the clients.

See the HubNet Authoring Guide for details.

hubnet-message

hubnet-message

Reports the message retrieved by hubnet-fetch-message.

See the HubNet Authoring Guide for details.

hubnet-message-source

hubnet-message-source

Reports the name of the client that sent the message retrieved by hubnet-fetch-message.

See the HubNet Authoring Guide for details.

hubnet-message-tag

hubnet-message-tag

Reports the tag that is associated with the data that was retrieved by hubnet-fetch-message. For Calculator HubNet, this will report one of the variable names set with the hubnet-set-client-interface primitive. For Computer HubNet, this will report one of the Display Names of the interface elements in the client interface.

See the HubNet Authoring Guide for details.

hubnet-message-waiting?

hubnet-message-waiting?

This looks for a new message sent by the clients. It reports true if there is one, and false if there is not.

See the HubNet Authoring Guide for details.

hubnet-reset

hubnet-reset

Starts up the HubNet system. HubNet must be started to use any of the other hubnet primitives with the exception of hubnet-set-client-interface.

See the HubNet Authoring Guide for details.

hubnet-send

hubnet-send string tag-name value

hubnet-send list-of-strings tag-name value

For Calculator HubNet, this primitive acts in exactly the same manner as hubnet-broadcast. (We plan to change this in a future version of NetLogo.)

For Computer HubNet, it acts as follows:

For a string, this sends value from NetLogo to the tag tag-name on the client that has string for its user name.

For a list-of-strings, this sends value from NetLogo to the tag tag-name on all the clients that have a user name that is in the list-of-strings.

Sending a message to a non-existent client, using hubnet-send, generates a hubnet-exit-message.

See the HubNet Authoring Guide for details.

hubnet-set-client-interface

hubnet-set-client-interface client-type client-info

If client-type is "TI-83+", client-info is a list containing two items. The first item is a string containing the name of the activity to enable on the TI Navigator web site. hubnet-set-client-interface "TI-83+" notifies the user to enable this activity. The second item is a list of the tags for which to check. The tag list sets which variables NetLogo expects from the calculators. NetLogo will only check for these variables and will ignore all others.

If client-type is "COMPUTER", client-info is a list containing a string with the file name and path (relative to the model) to the file which will serve as the client's interface. This interface will be sent to any clients that log in.

hubnet-set-client-interface
  "TI-83+"
  ["AAA - Gridlock 1.3" ["L1" "LOCS"]] 
;; notifies the user to enable the activity
;; AAA - Gridlock 1.3 and looks for the calculator
;; lists L1 and LOCS on the Navigator server

hubnet-set-client-interface
  "COMPUTER"
  ["clients/Disease client.nlogo"]
;; when clients log in, they will will get the
;; interface described in the file
;; clients/Disease client.nlogo, relative to
;; the location of the model

Future versions of HubNet may support other client types, and/or change the meaning of the second input to this command.

See the HubNet Authoring Guide for details.

I

if

if condition [ commands ]

Reporter must report a boolean (true or false) value.

If condition reports true, runs commands.

The reporter may report a different value for different agents, so some agents may run commands and others don't.

if xcor > 0[ set color blue ]
;; turtles on the right half of the screen
;; turn blue

ifelse

ifelse reporter [ commands1 ] [ commands2 ]

Reporter must report a boolean (true or false) value.

If reporter reports true, runs commands1.

If reporter reports false, runs commands2.

The reporter may report a different value for different agents, so some agents may run commands1 while others run commands2.

ask patches
  [ ifelse pxcor > 0
      [ set pcolor blue ]
      [ set pcolor red ] ]
;; the left half of the screen turns red and
;; the right half turns blue

ifelse-value

ifelse-value reporter [ reporter1 ] [ reporter2 ]

Reporter must report a boolean (true or false) value.

If reporter reports true, the result is the value of reporter1.

If reporter reports false, the result is the value of reporter2.

This can be used when a conditional is needed in the context of a reporter, where commands (such as ifelse) are not allowed.

ask patches
  [ set pcolor
    ifelse-value (pxcor > 0)
      [ blue ]
      [ red ] ]
;; the left half of the screen 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 [ifelse-value (?1 > ?2) [?1] [?2]]
  [1 3 2 5 3 8 3 2 1]
=> 8

import-world

import-world filename

Reads the values of all variables for a model, both built-in and user-defined, including all observer, turtle, and patch variables, from an external file named by the given string. The file should be in the format used by the export-world primitive.

Note that the functionality of this primitive is also directly available from NetLogo's File menu.

When using import-world, to avoid errors, perform these steps in the following order:

  1. Open the model from which you created the export file.
  2. Press the Setup button, to get the model in a state from which it can be run.
  3. Import the file.
  4. If you want, press Go button to continue running the model from the point where it left off.

If you wish to import a file from a location other than the model's location, you may include the full path to the file you wish to import. See export-world for an example.

in-radius
in-radius-nowrap

agentset in-radius number
agentset in-radius-nowrap number
Turtle Command Patch Command

Reports an agentset that includes only those agents from the original agentset whose distance from the caller is less than or equal to number.

The distance to or a from a patch is measured from the center of the patch.

in-radius allows its distance measurements to wrap around the edge of the screen; in-radius-nowrap does not.

ask turtles
  [ ask patches in-radius 3
      [ set pcolor red ] ]
;; each turtle makes a red "splotch" around itself

inspect

inspect agent

Opens an agent monitor for the given agent (turtle or patch).

inspect patch 2 4
;; an agent monitor opens for that patch
inspect random-one-of sheep
;; an agent monitor opens for a random turtle from
;; the "sheep" breed

int

int number

Reports the integer part of number -- any fractional part is discarded.

show int 4.7
=> 4
show int -3.5
=> -3

is-agent?
is-agentset?
is-boolean?
is-list?
is-number?
is-patch?
is-patch-agentset?
is-string?
is-turtle?
is-turtle-agentset?

is-agent? value
is-agentset? value
is-boolean? value
is-list? value
is-number? value
is-patch? value
is-patch-agentset? value
is-string? value
is-turtle? value
is-turtle-agentset? value

Reports true if value is of the given type, false otherwise.

item

item index list
item index string

On lists, reports the value of the item in the given list with the given index.

On strings, reports the character in the given string at the given index.

Note that the indices begin from 0, not 1. (The first item is item 0, the second item is item 1, and so on.)

;; suppose mylist is [2 4 6 8 10]
show item 2 mylist
=> 6
show item 3 "my-shoe"
=> "s"

J

jump

jump number
Turtle Command

Turtles move forward by number units all at once, without the amount of time passing depending on the distance.

This command is useful for synchronizing turtle movements. The command forward 15 takes 15 times longer to run than forward 1, but jump 15 runs in the same amount of time as forward 1.

Note: When turtles jump, they do not step on any of the patches along their path.

L

label

label
Turtle Command

This is a built-in turtle variable. It may hold a value of any type. The turtle appears in the graphics window with the given value "attached" to it as text. You can set this variable to add, change, or remove a turtle's label.

See also no-label, label-color, plabel, plabel-color.

Example:

ask turtles [ set label who ]
;; all the turtles now are labeled with their
;; id numbers
ask turtles [ set label no-label ]
;; all turtles now are not labeled

label-color

label-color
Turtle Command

This is a built-in turtle variable. It holds a number greater than or equal to 0 and less than 140. This number determines what color the turtle's label appears in (if it has a label). You can set this variable to change the color of a turtle's label.

See also no-label, label, plabel, plabel-color.

Example:

ask turtles [ set label-color red ]
;; all the turtles now have red labels

last

last list
last string

On a list, reports the last item in the list.

On a string, reports a one-character string containing only the last character of the original string.

left
lt

left number
Turtle Command

The turtle turns left by number degrees. (If number is negative, it turns right.)

length

length list
length string

Reports the number of items in the given list, or the number of characters in the given string.

list

list value1 value2
(list value1 ... valuen)

Reports a list containing the given items. The items can be of any type, produced by any kind of reporter.

show list (random 10) (random 10)
=> [4 9]  ;; or similar list
show (list 5)
=> [5]
show (list (random 10) 1 2 3 (random 10))
=> [4 1 2 3 9]  ;; or similar list 

ln

ln number

Reports the natural logarithm of number, that is, the logarithm to the base e (2.71828...).

See also e, log.

locals

locals [Vax1 var2 ...]

Locals is a keyword used to declare "local" variables in a procedure, that is, variables that are usable only within that procedure. It must appear at the beginning of the procedure, before any commands.

A local variable may not have the same name as an existing observer, turtle, or patch variable.

See to and to-report.

to hunt  ;; turtle procedure
  locals [prey]
  set prey random-one-of other-turtles-here
  if prey != nobody
    [ eat prey ]
end

log

log number base

Reports the logarithm of number in base base.

show log 64 2
=> 6

See also ln.

loop

loop [ commands ]

Runs the list of commands forever, or until the current procedure exits through use of the stop command or the report command.

Note: In most circumstances, you should use a forever button in order to repeat something forever. The advantage of using a forever button is that the user can click the button to stop the loop.

lput

lput value list

Adds value to the end of a list and reports the new list.

;; suppose mylist is [2 7 10 "Bob"]
set mylist lput 42 mylist
;; mylist now is [2 7 10 "Bob" 42]

M

map

map [reporter] list
(map [reporter] list1 ... list2)

With a single list, the given reporter is run for each item in the list, and a list of the results is collected and reported.

In reporter, use ? to refer to the current item of list.

show map [round ?] [1.1 2.2 2.7]
=> [1 2 3]
show map [? * ?] [1 2 3]
=> [1 4 9]

With multiple lists, the given reporter is run for each group of items from each list. So, it is run once for the first items, once for the second items, and so on. All the lists must be the same length.

In reporter, use ?1 through ?n to refer to the current item of each list.

Some examples make this clearer:

show (map [?1 + ?2] [1 2 3] [2 4 6])
=> [3 6 9]
show (map [?1 + ?2 = ?3] [1 2 3] [2 4 6] [3 5 9])
=> [true false true]

See also foreach, ?.

max

max list

Reports the maximum number value in the list. It ignores other types of items.

show max values-from turtles [xcor]
;; prints the x coordinate of the turtle which is
;; farthest right on the screen

max-one-of

max-one-of agentset [reporter]

Reports the agent in the agentset that has the highest value for the given reporter.

show max-one-of patches [count turtles-here]

;; prints the patch with the most turtles on it

mean

mean list

Reports the statistical mean of the numeric items in the given list. Ignores non-numeric items. The mean is the average, i.e., the sum of the items divided by the total number of items.

show mean values-from turtles [xcor]
;; prints the average of all the turtles' x coordinates

median

median list

Reports the statistical median of the numeric items of the given list. Ignores non-numeric items. The median is the item that would be in the middle if all the items were arranged in order. (If two items would be in the middle, the median is the average of the two.)

show median values-from turtles [xcor]
;; prints the median of all the turtles' x coordinates

member?

member? value list
member? string1 string2

For a list, reports true if the given value appears in the given list, otherwise reports false.

For a string, reports true or false depending on whether string1 appears anywhere inside string2 as a substring.

show member? 2 [1 2 3]
=> true
show member? 4 [1 2 3]
=> false
show member? "rin" "string"
=> true

See also position.

min

min list

Reports the minimum number value in the list. It ignores other types of items.

show min values-from turtles [xcor]
;; prints the lowest x-coordinate of all the turtles

min-one-of

min-one-of agentset [reporter]

Reports the agent in the agentset that reports the lowest value for the given reporter.

show min-one-of turtles [xcor + ycor]
;; reports the turtle with the smallest sum of
;; its coordinates

mod

number1 mod number2

Reports number1 modulo number2: that is, the residue of number1 (mod number2). mod is is equivalent to the following NetLogo code:

number1 - (floor (number1 / number2)) * number2

Note that mod is "infix", that is, it comes between its two inputs.

show 62 mod 5
=> 2
show -8 mod 3
=> 1

See also remainder. mod and remainder behave the same for positive numbers, but differently for negative numbers.

modes

modes list

Reports a list of the most common item or items in list.

The input list may contain any NetLogo values.

If the input is an empty list, reports an empty list.

show modes [1 2 2 3 4]
=> [2]
show modes [1 2 2 3 3 4]
=> [2 3]
show modes [ [1 2 [3]] [1 2 [3]] [2 3 4] ]
=> [[1 2 [3]]
show modes values-from turtles [pxcor]
;; shows which columns of patches have the most
;; turtles on them

mouse-down?

mouse-down?

Reports true if the mouse button is down, false otherwise.

Note: If the mouse pointer is outside of the NetLogo graphics window, mouse-down? will always report false.

mouse-xcor
mouse-ycor

mouse-xcor
mouse-ycor

Reports the x or y coordinate of the mouse in the Graphics Window. The value is in terms of turtle coordinates, so it is a floating-point number. If you want patch coordinates, use round mouse-xcor and round mouse-ycor.

Note: If the mouse is outside of the NetLogo graphics window, reports the value from the last time it was inside.

;; to make the mouse "draw" in red:
if mouse-down?
  [ set pcolor-of patch-at mouse-xcor mouse-ycor red ]

myself

myself
Turtle Command Patch Command

When an agent has been asked to run some code, using myself in that code reports the agent (turtle or patch) that did the asking.

myself is most often used in conjunction with -of to read or set variables in the asking agent.

myself can be used within blocks of code not just in the ask command, but also hatch, sprout, values-from, value-from, turtles-from, patches-from, histogram-from, with, min-one-of, and max-one-of.

ask turtles
  [ ask patches in-radius 3
      [ set pcolor color-of myself ] ]
;; each turtle makes a colored "splotch" around itself

See the "Myself Example" code example for more examples.

See also self.

N

n-values

n-values size [reporter]

Reports a list of length size containing values computed by repeatedly running reporter.

In reporter, use ? to refer to the number of the item currently being computed, starting from zero.

show n-values 5 [1]
=> [1 1 1 1 1]
show n-values 5 [?]
=> [0 1 2 3 4]
show n-values 3 [turtle ?]
=> [(turtle 0) (turtle 1) (turtle 2)]
show n-values 5 [? * ?]
=> [0 1 4 9 16]

See also reduce, filter, ?.

neighbors
neighbors4

neighbors
neighbors4
Turtle Command Patch Command

Reports an agentset containing the 8 surrounding patches (neighbors) or 4 surrounding patches (neighbors4).

show sum values-from neighbors [count turtles-here]
  ;; prints the total number of turtles on the eight
  ;; patches around the calling turtle or patch
ask neighbors4 [ set pcolor red ]
  ;; turns the four neighboring patches red

no-display

no-display

Turns off all updating of the graphics window until the display command is issued. This has two major uses.

One, you can control when the user sees screen updates. You might want to change lots of things on the screen behind the user's back, so to speak, then make them visible to the user all at once.

Two, your model will run faster when graphics updating is off, so if you're in a hurry, this command will let you get results faster. (Note that normally you don't need to use no-display for this, since you can also use the on/off switch in graphics window control strip to freeze the display.)

Note that display and no-display operate independently of the switch in the graphics window control strip that freezes the display.

See also display.

no-label

no-label

This is a special value used to remove labels from turtles and patches.

When you set a turtle's label to no-label, or a patch's plabel to no-label, then a label will no longer be drawn on top of the turtle or patch.

See also label, label-color, plabel, plabel-color.

nobody

nobody

This is a special value which some primitives such as turtle, random-one-of, max-one-of, etc. report to indicate that no agent was found. Also, when a turtle dies, it becomes equal to nobody.

Note: Empty agentsets are not equal to nobody. If you want to test for an empty agentset, use any?.

set other random-one-of other-turtles-here
if other != nobody
  [ set color-of other red ]

not

not boolean

Reports true if boolean is false, otherwise reports false.

if not (color = blue) [ fd 10 ]
;; all non-blue turtles move forward 10 steps

nsum
nsum4

nsum patch-variable
nsum4 patch-variable
Turtle Command Patch Command

For each patch, reports the sum of the values of patch-variable in the 8 surrounding patches (nsum) or 4 surrounding patches (nsum4).

Note that nsum/nsum4 are equivalent to the combination of the sum, values-from, and neighbors/neighbors4 primitives:

sum values-from neighbors [var]
  ;; does the same thing as "nsum var"
sum values-from neighbors4 [var]
  ;; does the same thing as "nsum4 var"

Therefore nsum and nsum4 are included as separate primitives mainly for backwards compatibility with older versions of NetLogo, which did not have the neighbors and neighbors4 primitives.

See also neighbors, neighbors4.

O

-of

VARIABLE-of agent

Reports the value of the VARIABLE of the given agent. Can also be used to set the value of the variable.

set color-of random-one-of turtles red
;; a randomly chosen turtle turns red
ask turtles [ set pcolor-of (patch-at -1 0) red ]
;; each turtle turns the patch on its left red

one-of

one-of agentset

If given a turtle agentset, reports the turtle in the set with the lowest numbered ID.

If given a patch agentset, reports the patch in the set with the highest pycor and, if a tie-breaker is needed, with the lowest pxcor.

If the agentset is empty, reports nobody.

See also random-one-of.

or

boolean1 or boolean2

Reports true if either boolean1 or boolean2, or both, is true.

Note that if condition1 is true, then condition2 will not be run (since it can't affect the result).

if (pxcor > 0) or (pycor > 0) [ set pcolor red ]
;; patches turn red except in lower-left quadrant

other-turtles-here
other-BREED-here

other-turtles-here
other-BREED-here
Turtle Command

Reports an agentset consisting of all turtles on the calling turtle's patch (not including the caller itself). If a breed is specified, only turtles with the given breed are included.

;; suppose I am one of 10 turtles on the same patch
show count other-turtles-here
=> 9

Example using breeds:

breeds [cats dogs]
show count other-dogs-here
;; prints the number of dogs (that are not me) on my patch

See also turtles-here.

P

patch

patch pxcor pycor

Given two integers, reports the single patch with the given pxcor and pycor. (The coordinates are the actual coordinates; they are not computed relative to the calling agent, as with patch-at.) pxcor and pycor must be integers.

ask (patch 3 -4) [ set pcolor green ]
;; patch with pxcor of 3 and pycor of -4 turns green

See also patch-at.

patch-ahead

patch-ahead distance
Turtle Command

Reports the single patch that is the given distance "ahead" of the calling turtle, that is, along the turtle's current heading.

set pcolor-of (patch-ahead 1) green
;; turns the patch 1 in front of the calling turtle
;;   green; note that this might be the same patch
;;   the turtle is standing on

See also patch-at, patch-left-and-ahead, patch-right-and-ahead, patch-at-heading-and-distance.

patch-at

patch-at dx dy

Reports the single patch at (dx, dy) from the caller, that is, dx patches east and dy patches north of the caller. (If the caller is the observer, the given offsets are computed from the origin.)

ask patch-at 1 -1 [ set pcolor green ]
;; if caller is the observer, turn the patch
;;   at (1, -1) green
;; if caller is a turtle or patch, turns the
;;   patch just southeast of the caller green

See also patch, patch-ahead, patch-left-and-ahead, patch-right-and-ahead, patch-at-heading-and-distance.

patch-at-heading-and-distance

patch-at-heading-and-distance heading distance
Turtle Command Patch Command

patch-at-heading-and-distance reports the single patch that is the given distance from the calling turtle or patch, along the given absolute heading. (In contrast to patch-left-and-ahead and patch-right-and-ahead, the calling turtle's current heading is not taken into account.)

set pcolor-of (patch-at-heading-and-distance -90 1) green
;; turns the patch 1 to the west of the calling patch
;;   green

See also patch, patch-at, patch-left-and-ahead, patch-right-and-ahead.

patch-here

patch-here
Turtle Command

patch-here reports the patch under the turtle.

Note that this reporter isn't available to a patch because a patch can just say "self".

patch-left-and-ahead
patch-right-and-ahead

patch-left-and-ahead angle distance
patch-right-and-ahead angle distance
Turtle Command

Reports the single patch that is the given distance from the calling turtle, in the direction turned left or right the given angle (in degrees) from the turtle's current heading.

(If you want to find a patch in a given absolute heading, rather than one relative to the current turtle's heading, use patch-at-heading-and-distance instead.)

set pcolor-of (patch-right-and-ahead 30 1) green
;; the calling turtle "looks" 30 degrees right of its
;;   current heading at the patch 1 unit away, and turns
;;   that patch green; note that this might be the same
;;   patch the turtle is standing on

See also patch, patch-at, patch-at-heading-and-distance.

patches

patches

Reports the agentset consisting of all patches.

patches-from

patches-from agentset [ reporter ]

Reports a patch agentset made by gathering together all the patches reported by reporter for each agent in agentset.

For each agent, the reporter must report a patch agentset, a single patch, or nobody.

patches-from turtles [patch-here]
  ;; reports the set of all patches with turtles on them;
  ;; if there are many more patches than turtles, this will
  ;; run much faster than "patches with [any? turtles-here]"

See also turtles-from.

patches-own

patches-own [var1 var2 ...]

This keyword, like the globals, breeds, <BREED>-own, and turtles-own keywords, can only be used at the beginning of a program, before any function definitions. It defines the variables that all patches can use.

All patches will then have the given variables and be able to use them.

All patch variables can also be directly accessed by any turtle standing on the patch.

See also globals, turtles-own, breeds, <BREED>-own.

pcolor

pcolor
Patch Command

This is a built-in patch variable. It holds the color of the patch. You can set this variable to make the patch change color.

All patch variables can be directly accessed by any turtle standing on the patch.

See also color.

pen-down
pd
pen-up
pu

pen-down
pen-up
Turtle Command

The turtle its pen down (or up), so that it draws (leaves a trail) when they move (or doesn't).

Turtles draw by changing the color of the patches underneath them to their own color. To change the color of the turtle's pen (and the color of the turtle itself), use set color.

Note: When a turtle's pen is down, only the commands forward and back cause drawing.

Note: Theses commands are equivalent to setting the turtle variable "pen-down?" to true or false.

See also pen-down?.

pen-down?

pen-down?
Turtle Command

This is a built-in turtle variable. It holds a boolean (true or false) value indicating whether the turtle's pen is currently down. You can set this variable to put a turtle's pen down or pick it back up again.

See also pen-down, pen-up.

plabel

plabel
Patch Command

This is a built-in patch variable. It may hold a value of any type. The patch appears in the graphics window with the given value "attached" to it as text. You can set this variable to add, change, or remove a patch's label.

All patch variables can be directly accessed by any turtle standing on the patch.

See also no-label, plabel-color, label, label-color.

plabel-color

plabel-color
Patch Command

This is a built-in patch variable. It holds a number greater than or equal to 0 and less than 140. This number determines what color the patch's label appears in (if it has a label). You can set this variable to change the color of a patch's label.

All patch variables can be directly accessed by any turtle standing on the patch.

See also no-label, plabel, label, label-color.

plot

plot number

Increments the x-value of the plot pen by plot-pen-interval, then plots a point at the updated x-value and a y-value of number. (The first time the command is used on a plot, the point plotted has an x-value of 0.)

plot-name

plot-name

Reports the name of the current plot (a string).

plot-pen-down
ppd
plot-pen-up
ppu

plot-pen-down
plot-pen-up

Puts down (or up) the current plot-pen, so that it draws (or doesn't). (By default, all pens are down initially.)

plot-pen-reset

plot-pen-reset

Clears everything the current plot pen has drawn, moves it to (0,0), and puts it down. If the pen is a permanent pen, the color and mode are reset to the default values from the plot Edit dialog.

plotxy

plotxy number1 number2

Moves the current plot pen to the point with coordinates (number1, number2). If the pen is down, a line, bar, or point will be drawn (depending on the pen's mode).

plot-x-min
plot-x-max
plot-y-min
plot-y-max

plot-x-min
plot-x-max
plot-y-min
plot-y-max

Reports the minimum or maximum value on the x or y axis of the current plot.

These values can be set with the commands set-plot-x-range and set-plot-y-range. (Their default values are set from the plot Edit dialog.)

position

position item list
position string1 string2

On a list, reports the first position of item in list, or false if it does not appear.

On strings, reports the position of the first appearance string1 as a substring of string2, or false if it does not appear.

Note: The positions are numbered beginning with 0, not with 1.

;; suppose mylist is [2 7 4 7 "Bob"]
show position 7 mylist
=> 1
show position 10 mylist
=> false
show position "rin" "string"
=> 2

See also member?.

precision

precision number places

Reports number rounded to places decimal places.

If places is negative, the rounding takes place to the left of the decimal point.

show precision 1.23456789 3
=> 1.235
show precision 3834 -3
=> 4000

print

print value

Prints value in the Command Center, followed by a carriage return.

The calling agent is not printed before the value, unlike show.

See also show, type, and write.

pxcor
pycor

pxcor
pycor
Patch Command

These are built-in patch variables. They hold the x and y coordinate of the patch. They are always integers. You cannot set these variables, because patches don't move.

pxcor is greater than or equal to (- screen-edge-x) and less than or equal to screen-edge-x; similarly for pycor and screen-edge-y.

All patch variables can be directly accessed by any turtle standing on the patch.

See also xcor, ycor.

R

random

random number

If number is positive, reports a random integer greater than or equal to 0, but strictly less than number.

If number is negative, reports a random integer less than or equal to 0, but strictly greater than number.

If number is zero, the result is always 0 as well.

Note: In versions of NetLogo prior to version 2.0, this primitive reported a floating point number if given a floating point input. This is no longer the case. If you want a floating point answer, you must now use random-float instead.

show random 3
;; prints 0, 1,  or 2
show random -3
;; prints 0, -1, or -2
show random 3.0
;; prints 0, 1,  or 2
show random 3.5
;; prints 0, 1, 2, or 3

See also random-float.

random-float

random-float number

If number is positive, reports a random floating point number greater than or equal to 0.0 but strictly less than number.

If number is negative, reports a random floating point number less than or equal to 0.0, but strictly greater than number.

If number is zero, the result is always 0.0.

show random-float 3
;; prints a number at least 0.0 but less than 3.0,
;; for example 2.589444906014774
show random-float 2.5
;; prints a number at least 0.0 but less than 2.5,
;; for example 1.0897423196760796

random-exponential
random-gamma
random-normal
random-poisson

random-exponential mean
random-gamma alpha lambda
random-normal mean standard-deviation
random-poisson mean

Reports an accordingly distributed random number with the mean and, in the case of the normal distribution, the standard-deviation.

random-exponential reports an exponentially distributed random floating point number.

random-gamma reports a gamma-distributed random floating point number as controlled by the floating point alpha and lambda parameters. Both inputs must be greater than zero. (Note: for results with a given mean and variance, use inputs as follows: alpha = mean * mean / variance; lambda = 1 / (variance / mean).)

random-normal reports a normally distributed random floating point number.

random-poisson reports a Poisson-distributed random integer.

show random-exponential 2
;; prints an exponentially distributed random floating
;; point number with a mean of 2
show random-normal 10.1 5.2
;; prints a normally distributed random floating point
;; number with a mean of 10.1 and a standard deviation
;; of 5.2 
show random-poisson 3.4
;; prints a Poisson-distributed random integer with a
;; mean of 3.4

random-int-or-float

random-int-or-float number

NOTE: This primitive should not be used in new models. It is included only for backwards compatibility with NetLogo 1.x. It will not necessarily continue to be supported in future versions of NetLogo.

When a NetLogo 1.x model is read into NetLogo 2.0 or higher, all uses of the "random" primitive are automatically converted to "random-int-or-float" instead, because the meaning of "random" has changed. It used to sometimes return an integer and sometimes a floating point number; now it always returns an integer. This primitive mimics the old behavior, as follows:

If number is positive, reports a random number greater than or equal to 0 but strictly less than number.

If number is negative, the number reported is less than or equal to 0, but strictly greater than number.

If number is zero, the result is always zero as well.

If number is an integer, reports a random integer.

If number is floating point (has a decimal point), reports a floating point number.

show random-int-or-float 3
;; prints 0, 1,  or 2
show random-int-or-float 5.0
;; prints a number at least 0.0 but less than 5.0,
;; for example 4.686596634174661

random-n-of

random-n-of size agentset

From an agentset, reports an agentset of size size randomly chosen from the input set.

From an list, reports a list of size size randomly chosen from the input set. The items in the result appear in the same order that they appeared in the input list. (If you want them in random order, use shuffle on the result.)

It is an error for size to be greater than the size of the input.

ask random-n-of 50 patches [ set pcolor green ]
;; 50 randomly chosen patches turn green

See also random-one-of.

random-one-of

random-one-of agentset
random-one-of list

From an agentset, reports a random agent. If the agentset is empty, reports nobody.

From a list, reports a random list item. It is an error for the list to be empty.

ask random-one-of patches [ set pcolor green ]
;; a random patch turns green
set pcolor-of random-one-of patches green
;; another way to say the same thing
ask patches with [any? turtles-here]
  [ show random-one-of turtles-here ]
;; for each patch containing turtles, prints one of
;; those turtles

;; suppose mylist is [1 2 3 4 5 6]
show random-one-of mylist
;; prints a value randomly chosen from the list

See also one-of and random-n-of.

random-seed

random-seed number

Sets the seed of the pseudo-random number generator to the integer part of number. The seed may be any integer in the range supported by NetLogo (-2147483648 to 2147483647).

See the Random Numbers section of the Programming Guide for more details.

random-seed 47823
show random 100
=> 57
show random 100
=> 91
random-seed 47823
show random 100
=> 57
show random 100
=> 91

read-from-string

read-from-string string

Interprets the given string as if it had been typed in the Command Center, and reports the resulting value. The result may be a number, list, string, or boolean value, or the special value "nobody".

Useful in conjunction with the user-input primitive for converting the user's input into usable form.

show read-from-string "3" + read-from-string "5"
=> 8
show length read-from-string "[1 2 3]"
=> 3
crt read-from-string user-input "Make how many turtles?"
;; the number of turtles input by the user
;; are created

reduce

reduce [reporter] list

Reduces a list from left to right using reporter, resulting in a single value. This means, for example, that reduce [?1 + ?2] [1 2 3 4] is equivalent to (((1 + 2) + 3) + 4). If list has a single item, that item is reported. It is an error to reduce an empty list.

In reporter, use ?1 and ?2 to refer to the two objects being combined.

Since it can be difficult to develop an intuition about what reduce does, here are some simple examples which, while not useful in themselves, may give you a better understanding of this primitive:

show reduce [?1 + ?2] [1 2 3]
=> 6
show reduce [?1 - ?2] [1 2 3]
=> -4
show reduce [?2 - ?1] [1 2 3]
=> 2
show reduce [?1] [1 2 3]
=> 1
show reduce [?2] [1 2 3]
=> 3
show reduce [sentence ?1 ?2] [[1 2] [3 [4]] 5]
=> [1 2 3 [4] 5]
show reduce [fput ?2 ?1] (fput [] [1 2 3 4 5])
=> [5 4 3 2 1]
Here are some more useful examples:
;; find the longest string in a list
to-report longest-string [strings]
  report reduce
    [ifelse-value (length ?1 >= length ?2) [?1] [?2]]
    strings
end

show longest-string ["hi" "there" "!"]
=> "there"

;; count the number of occurrences of an item in a list
to-report occurrences [x xs]
  report reduce
    [ifelse-value (?2 = x) [?1 + 1] [?1]] (fput 0 xs)
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 eval-polynomial [coeffs x]
  report reduce [(x * ?1) + ?2] coeffs
end

;; evaluate 3x^2 + 2x + 1 at x = 4
show eval-polynomial [3 2 1] 4
=> 57

remainder

remainder number1 number2

Reports the remainder when number1 is divided by number2. This is equivalent to the following NetLogo code:

number1 - (int (number1 / number2)) * number2
show remainder 62 5
=> 2
show remainder -8 3
=> -2

See also mod. mod and remainder behave the same for positive numbers, but differently for negative numbers.

remove

remove item list
remove string1 string2

For a list, reports a copy of list with all instances of item removed.

For strings, reports a copy of string2 with all the appearances of string1 as a substring removed.

set mylist [2 7 4 7 "Bob"]
set mylist remove 7 mylist
;; mylist is now [2 4 "Bob"]
show remove "na" "banana"
=> "ba"

remove-duplicates

remove-duplicates list

Reports a copy of list with all duplicate items removed. The first of each item remains in place.

set mylist [2 7 4 7 "Bob" 7]
set mylist remove-duplicates mylist
;; mylist is now [2 7 4 "Bob"]

remove-item

remove-item index list
remove-item index string

For a list, reports a copy of list with the item at the given index removed.

For strings, reports a copy of string2 with the character at the given index removed.

Note that the indices begin from 0, not 1. (The first item is item 0, the second item is item 1, and so on.)

set mylist [2 7 4 7 "Bob"]
set mylist remove-item 2 mylist
;; mylist is now [2 7 7 "Bob"]
show remove-item 3 "banana"
=> "banna"

repeat

repeat number [ commands ]

Runs commands number times.

pd repeat 36 [ fd 1 rt 10 ]
;; the turtle draws a circle

replace-item

replace-item index list value
replace-item index string1 string2

On a list, replaces an item in that list. index is the index of the item to be replaced, starting with 0. (The 6th item in a list would have an index of 5.) Note that "replace-item" is used in conjunction with "set" to change a list.

Likewise for a string, but the given character of string1 removed and the contents of string2 spliced in instead.

show replace-item 2 [2 7 4 5] 15
=> [2 7 15 5]
show replace-item 1 "sat" "lo"
=> "slot"

report

report value

Immediately exits from the current to-report procedure and reports value as the result of that procedure. report and to-report are always used in conjunction with each other. See to-report for a discussion of how to use them.

reset-timer

reset-timer

Resets the global clock to zero. See also timer.

reverse

reverse list
reverse string

Reports a reversed copy of the given list or string.

show mylist
;; mylist is [2 7 4 "Bob"]
set mylist reverse mylist
;; mylist now is ["Bob" 4 7 2]
show reverse "string"
=> "gnirts"

rgb

rgb red green blue

Reports a number in the range 0 to 140, not including 140 itself, that represents the given color, specified in the RGB spectrum, in NetLogo's color space.

All three inputs should be in the range 0.0 to 1.0.

The color reported may be only an approximation, since the NetLogo color space does not include all possible colors. (See hsb for a description of what parts of the HSB color space NetLogo colors cover; this is difficult to characterize in RGB terms.)

show rgb 0 0 0
=> 0.0  ;; black
show rgb 0 1.0 1.0
=> 85.0 ;; cyan

See also extract-rgb, hsb, and extract-hsb.

right
rt

right number
Turtle Command

The turtle turns right by number degrees. (If number is negative, it turns left.)

round

round number

Reports the integer nearest to number.

If the decimal portion of number is exactly .5, the number is rounded in the positive direction.

Note that rounding in the positive direction is not always how rounding is done in other software programs. (In particular, it does not match the behavior of StarLogoT, which always rounded numbers ending in 0.5 to the nearest even integer.) The rationale for this behavior is that it matches how turtle coordinates relate to patch coordinates in NetLogo. For example, if a turtle's xcor is -4.5, then it is on the boundary between a patch whose pxcor is -4 and a patch whose pxcor is -5, but the turtle must be considered to be in one patch or the other, so the turtle is considered to be in the patch whose pxcor is -4, because we round towards the positive numbers.

show round 4.2
=> 4
show round 4.5
=> 5
show round -4.5
=> -4

run

run string

This agent interprets the given string as a sequence of one or more NetLogo commands and runs them.

The code runs in the agent's current context, which means it has access to the values of local variables, "myself", and so on.

See also runresult.

runresult

runresult string

This agent interprets the given string as a NetLogo reporter and runs it, reporting the result obtained.

The code runs in the agent's current context, which means it has access to the values of local variables, "myself", and so on.

See also run.

S

scale-color

scale-color color number range1 range2

Reports a shade of color proportional to number.

If range1 is less than range2, then the larger the number, the lighter the shade of color. But if range2 is less than range1, the color scaling is inverted.

If number is less than range1, then the darkest shade of color is chosen.

If number is greater than range2, then the lightest shade of color is chosen.

Note: for color shade is irrelevant, e.g. green and green + 2 are equivalent, and the same spectrum of colors will be used.

ask turtles [ set color scale-color red age 0 50 ]
;; colors each turtle a shade of red proportional
;; to its value for the age variable

screen-edge-x
screen-edge-y

screen-edge-x
screen-edge-y

These reporters give the maximum x-coordinate and maximum y-coordinate (respectively) of the Graphics Window.

screen-edge-x and -y are the "half-width" and "half-height" of the NetLogo world -- the distances from the origin to the edges. screen-size is the same as ((2 * screen-edge) + 1).

Note: You can set the size of the Graphics Window only by editing it -- these are reporters which cannot be set.

cct 100 [ setxy (random-float screen-edge-x)
                     (random-float screen-edge-y) ]
;; distributes 100 turtles randomly in the
;; first quadrant

screen-size-x
screen-size-y

screen-size-x
screen-size-y

These reporters give the total width and height of the NetLogo world.

Screen-size is the same as ((2 * screen-edge) + 1).

self

self
Turtle Command Patch Command

Reports this turtle or patch.

ask turtles with [self != myself]
  [ die ]
;; this turtle kills all other turtles

See also myself.

; (semicolon)

; comments

After a semicolon, the rest of the line is ignored. This is useful for adding "comments" to your code -- text that explains the code to human readers. Extra semicolons can be added for visual effect.

sentence
se

sentence value1 value2
(sentence value1 ... valuen)

Makes a list out of the values. If any value is a list, its items are included in the result directly, rather than being included as a sublist. Examples make this clearer:

show sentence 1 2
=> [1 2]
show sentence [1 2] 3
=> [1 2 3]
show sentence 1 [2 3]
=> [1 2 3]
show sentence [1 2] [3 4]
=> [1 2 3 4]
show (sentence [1 2] 3 [4 5] (3 + 3) 7)
=> [1 2 3 4 5 6 7]

set

set variable value

Sets variable to the given value.

Variable can be any of the following:

set-current-directory

set-current-directory string

Sets the current directory that is used by the primitives file-delete, file-exists?, and file-open.

The current directory is not used if the above commands are given an absolute file path. This is defaulted to the user's home directory for new models, and is changed to the model's directory when a model is opened.

Note that in Windows file paths the backslash needs to be escaped within a string by using another backslash "C:\\"

The change is temporary and is not saved with the model.

Note: in applets, this command has no effect, since applets are only allowed to read files from the same directory on the server where the model is stored.

set-current-directory "C:\\NetLogo"
;; Assume it is a Windows Machine
file-open "myfile.txt"
;; Opens file "C:\\NetLogo\\myfile.txt"

set-current-plot

set-current-plot plotname

Sets the current plot to the plot with the given name (a string). Subsequent plotting commands will affect the current plot.

set-current-plot-pen

set-current-plot-pen penname

The current plot's current pen is set to the pen named penname (a string). If no such pen exists in the current plot, a runtime error occurs.

set-default-shape

set-default-shape turtles string
set-default-shape breed string
Observer Command

Specifies a default initial shape for all turtles, or for a particular breed. When a turtle is created, or it changes breeds, it shape is set to the given shape.

The specified breed must be either turtles or a breed defined by the breeds keyword, and the specified string must be the name of a currently defined shape.

In new models, the default shape for all turtles is "default".

Note that specifying a default shape does not prevent you from changing an individual turtle's shape later; turtles don't have to be stuck with their breed's default shape.

create-turtles 1 ;; new turtle's shape is "default"
create-cats 1    ;; new turtle's shape is "default"

set-default-shape turtles "circle"
create-turtles 1 ;; new turtle's shape is "circle"
create-cats 1    ;; new turtle's shape is "circle"

set-default-shape cats "cat"
set-default-shape dogs "dog"
create-cats 1   ;; new turtle's shape is "cat"
ask cats [ set breed dogs ]
  ;; all cats become dogs, and automatically
  ;; change their shape to "dog"

See also shape.

set-histogram-num-bars

set-histogram-num-bars integer

Set the current plot pen's plot interval so that, given the current x range for the plot, there would be integer number of bars drawn if the histogram-from or histogram-list commands were called.

See also histogram-from.

set-plot-pen-color

set-plot-pen-color number

Sets the color of the current plot pen to number.

set-plot-pen-interval

set-plot-pen-interval number

Tells the current plot pen to move a distance of number in the x direction during each use of the plot command. (The plot pen interval also affects the behavior of the histogram-from and histogram-list commands.)

set-plot-pen-mode

set-plot-pen-mode number

Sets the mode the current plot pen draws in to number. The allowed plot pen modes are:

The default mode for new pens is 0 (line mode).

set-plot-x-range
set-plot-y-range

set-plot-x-range min max
set-plot-y-range min max

Sets the minimum and maximum values of the x or y axis of the current plot.

The change is temporary and is not saved with the model. When the plot is cleared, the ranges will revert to their default values as set in the plot's Edit dialog.

setxy

setxy x y
Turtle Command

The turtle sets its x-coordinate to x and its y-coordinate to y.

Equivalent to set xcor x set ycor y, except it happens in one time step instead of two.

setxy 0 0
;; turtle moves to the middle of the center patch

shade-of?

shade-of? color1 color2

Reports true if both colors are shades of one another, false otherwise.

show shade-of? blue red
=> false
show shade-of? blue (blue + 1)
=> true
show shade-of? gray white
=> true

shape

shape
Turtle Command

This is a built-in turtle variable. It holds a string that is the name of the turtle's current shape. You can set this variable to change a turtle's shape. New turtles have the shape "default" unless the a different shape has been specified using set-default-shape.

See also set-default-shape.

show

show value

Prints value in the Command Center, preceded by the calling agent, and followed by a carriage return. (The calling agent is included to help you keep track of what agents are producing which lines of output.) Also, all strings have their quotes included similar to write.

See also print, type, and write.

showturtle
st

showturtle
Turtle Command

The turtle becomes visible again.

Note: This command is equivalent to setting the turtle variable "hidden?" to false.

See also hideturtle.

shuffle

shuffle list

Reports a new list containing the same items as the input list, but in randomized order.

show shuffle [1 2 3 4 5]
=> [5 2 4 1 3]
show shuffle [1 2 3 4 5]
=> [1 3 5 2 4]

sin

sin number

Reports the sine of the given angle. Assumes angle is given in degrees.

show sin 270
=> -1.0

size

size
Turtle Command

This is a built-in turtle variable. It holds a number that is the turtle's apparent size in the graphics window. The default size for a turtle is 1.0, which means that the turtle is the same size as a patch. You can set this variable to change a turtle's size.

All turtles appear the same size in the graphics window unless the "Turtle Sizes" checkbox in the graphics window edit dialog is checked. If that checkbox is not checked, you can still use this variable, but it will not have any visible effect.

Note: the "Turtle Sizes" feature is currently considered experimental. It may cause your model to run much more slowly, and it may cause display anomalies.

sort

sort list

Reports a new list containing the same items as the input list, but in ascending order.

If there is at least one number in the list, the list is sorted in numerically ascending order and any non-numeric items of the input list are discarded.

If there are no numbers, but at least one string in the list, the list is sorted in alphabetically ascending order and any non-string items are discarded.

sort-by

sort-by [reporter] list

Reports a new list containing the same items as the input list, in a sorted order defined by the boolean (true or false) reporter.

In reporter, use ?1 and ?2 to refer to the two objects being compared. reporter should be true if ?1 comes strictly before ?2 in the desired sort order, and false otherwise.

show sort-by [?1 < ?2] [3 1 4 2]
=> [1 2 3 4]
show sort-by [?1 > ?2] [3 1 4 2]
=> [4 3 2 1]
show sort-by [length ?1 < length ?2] ["zzz" "z" "zz"]
=> ["z" "zz" "zzz"]

sprout

sprout number [ commands ]
Patch Command

Creates number new turtles on the current patch. The new turtles have random colors and orientations, and they immediately run commands. This is useful for giving the new turtles different colors, headings, breeds, or whatever.

sprout 1 [ set color red ]

Note: While the commands are running, no other agents are allowed to run any code (as with the without-interruption command). This ensures that the new turtles cannot interact with any other agents until they are fully initialized. In addition, no screen updates take place until the commands are done. This ensures that the new turtles are never drawn on-screen until they are fully initialized.

sqrt

sqrt number

Reports the square root of number.

stamp

stamp color
Turtle Command

Sets the color of the patch under the turtle to the given color.

repeat 30 [ stamp yellow fd 3 rt 6 ]
;; the turtle records its arched path -- contrast to the
;; effect of "pen-down"

standard-deviation

standard-deviation list

Reports the unbiased statistical standard deviation of a list of numbers. Ignores other types of items.

show standard-deviation [1 2 3 4 5 6]
=> 1.8708286933869707
show standard-deviation values-from turtles [energy]
;; prints the standard deviation of the variable "energy"
;; from all the turtles

startup

startup
Observer Command

User-defined procedure which, if it exists, will be called when a model is first loaded.

to startup
  setup
end

stop

stop

The calling agent exits immediately from the enclosing procedure, ask, or ask-like construct (cct, hatch, sprout). Only the current procedure stops, not all execution for the agent.

Note: stop can be used to stop a forever button. If the forever button directly calls a procedure, then when that procedure stops, the button stops. (In a turtle or patch forever button, the button won't stop until every turtle or patch stops -- a single turtle or patch doesn't have the power to stop the whole button.)

substring

substring string position1 position2

Reports just a section of the given string, ranging between the given positions.

Note: The positions are numbered beginning with 0, not with 1.

show substring "turtle" 1 4
=> "urt"

sum

sum list

Reports the sum of the items in the list.

show sum values-from turtles [energy]
;; prints the total of the variable "energy"
;; from all the turtles

T

tan

tan number

Reports the tangent of the given angle. Assumes the angle is given in degrees.

timer

timer

Reports how many seconds have passed since the command reset-timer was last run (or since NetLogo started). The potential resolution of the clock is milliseconds. (Whether you get resolution that high in practice may vary from system to system, depending on the capabilities of the underlying Java Virtual Machine.)

to

to procedure-name
to procedure-name [input1 input2 ...]

Used to begin a command procedure.

to setup
  ca
  crt 500
end

to circle [radius]
  cct 100 [ fd radius ]
end

to-report

to-report procedure-name
to-report procedure-name [input1 input2 ...]

Used to begin a reporter procedure.

The body of the procedure should use report to report a value for the procedure. See report.

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
towards-nowrap

towards agent
towards-nowrap agent
Turtle Command Patch Command

Reports the heading from this agent to the given agent.

If the wrapped distance (around the edges of the screen) is shorter than the on-screen distance, towards will report the heading of the wrapped path. towards-nowrap never uses the wrapped path.

Note: asking for the heading from an agent to itself, or an agent on the same location, will cause a runtime error.

towardsxy
towardsxy-nowrap

towardsxy x y
towardsxy-nowrap x y
Turtle Command Patch Command

Reports the heading from the turtle or patch towards the point (x,y).

If the wrapped distance (around the edges of the screen) is shorter than the on-screen distance, towardsxy will report the heading of the wrapped path. towardsxy-nowrap never uses the wrapped path.

Note: asking for the heading to the point the agent is already standing on will cause a runtime error.

turtle

turtle number

Reports the turtle with the given ID number, or nobody if there is no such turtle. number must be an integer.

set color-of turtle 5 red
;; turtle with id number 5 turns red
ask turtle 5 [ set color red ]
;; another way to do the same thing

turtles

turtles

Reports the agentset consisting of all turtles.

show count turtles
;; prints the number of turtles

turtles-at
BREED-at

turtles-at dx dy
BREED-at dx dy

Reports an agentset containing the turtles on the patch (dx, dy) from the caller (including the caller itself if it's a turtle). If the caller is the observer, dx and dy are calculated from the origin (0,0).

;; suppose I have 40 turtles at the origin
show count turtles-at 0 0
=> 40

If the name of a breed is substituted for "turtles", then only turtles of that breed are included.

breeds [cats dogs]
create-custom-dogs 5 [ setxy 2 3 ]
show count dogs-at 2 3
=> 5

turtles-from

turtles-from agentset [ reporter ]

Reports a turtle agentset made by gathering together all the turtles reported by reporter for each agent in agentset.

For each agent, the reporter must report a turtle agentset, a single turtle, or nobody.

turtles-from patches [random-one-of turtles-here]
  ;; reports a turtleset containing one turtle from
  ;; each patch (that has any turtles on it)
turtles-from neighbors [turtles-here]
  ;; if run by a turtle or patch, reports the set of
  ;; all turtles on the neighboring eight patches; note that
  ;; this could be written more concisely using turtles-on,
  ;; like this:
  ;;   turtles-on neighbors

See also patches-from, turtles-on.

turtles-here
BREED-here

turtles-here
BREED-here

Reports an agentset containing all the turtles on the caller's patch (including the caller itself if it's a turtle).

ca
crt 10
ask turtle 0 [ show count turtles-here ]
=> 10

If the name of a breed is substituted for "turtles", then only turtles of that breed are included.

breeds [cats dogs]
create-cats 5
create-dogs 1
ask dogs [ show count cats-here ]
=> 5

See also other-turtles-here.

turtles-on
BREED-on

turtles-on agent
turtles-on agentset
BREED-on agent
BREED-on agentset

Reports an agentset containing all the turtles that are on the given patch or patches, or standing on the same patch as the given turtle or turtles.

ask turtles [
  if not any? turtles-on patch-ahead 1
    [ fd 1 ]
]
ask turtles [
  if not any? turtles-on neighbors [
    die-of-loneliness
  ]
]

If the name of a breed is substituted for "turtles", then only turtles of that breed are included.

See also turtles-from.

turtles-own
BREED-own

turtles-own [var1 var2 ...]
BREED-own [var1 var2 ...]

The turtles-own keyword, like the globals, breed, <BREED>-own, and patches-own keywords, can only be used at the beginning of a program, before any function definitions. It defines the variables belonging to each turtle.

If you specify a breed instead of "turtles", only turtles of that breed have the listed variables. (More than one breed may list the same variable.)

breeds [cats dogs hamsters]
turtles-own [eyes legs]   ;; applies to all breeds
cats-own [fur kittens]
hamsters-own [fur cage]
dogs-own [hair puppies]

See also globals, patches-own, breeds, <BREED>-own.

type

type value

Prints value in the Command Center, not followed by a carriage return (unlike print and show). The lack of a carriage return allows you to print several values on the same line.

The calling agent is not printed before the value. unlike show.

type 3 type " " print 4
=> 3 4

See also print, show, and write.

U

uphill

uphill patch-variable
Turtle Command

Reports the turtle heading (between 0 and 359 degrees) in the direction of the maximum value of the variable patch-variable, of the patches in a one-patch radius of the turtle. (This could be as many as eight or as few as five patches, depending on the position of the turtle within its patch.)

If there are multiple patches that have the same greatest value, a random one of those patches will be selected.

If the patch is located directly to the north, south, east, or west of the patch that the turtle is currently on, a multiple of 90 degrees is reported. However, if the patch is located to the northeast, northwest, southeast, or southwest of the patch that the turtle is currently on, the direction the turtle would need to reach the nearest corner of that patch is reported.

See also uphill4, downhill, downhill.

uphill4

uphill4 patch-variable
Turtle Command

Reports the turtle heading (between 0 and 359 degrees) as a multiple of 90 degrees in the direction of the maximum value of the variable patch-variable, of the four patches to the north, south, east, and west of the turtle. If there are multiple patches that have the same greatest value, a random patch from those patches will be selected.

See also uphill, downhill, downhill4.

user-choice

user-choice value list-of-choices

Opens a dialog with value displayed as the message and a button corresponding to each item in list-of-choices.

Reports the item in list-of-choices that is associated with the button the user presses.

value may be of any type, but is typically a string.

if "yes" = (user-choice
                   "Set up the model?"
                   ["no" "yes"])
  [ setup ]

user-choose-directory

user-choose-directory

Opens a dialog that allows the user to choose an existing directory on the system.

It reports a string with the absolute path or false if the user cancels.

set-current-directory user-choose-directory
;; Assumes the user will choose a directory

user-choose-file

user-choose-file

Opens a dialog that allows the user to choose an existing file on the system.

It reports a string with the absolute file path or false if the user cancels.

file-open user-choose-file
;; Assumes the user will choose a file

user-choose-new-file

user-choose-new-file

Opens a dialog that allows the user to choose a new file on the system.

It reports a string with the absolute file path or false if the user cancels.

Note that no file is ever created or overwritten with this reporter.

file-open user-choose-new-file
;; Assumes the user will choose a file

user-input

user-input value

Reports the string that a user types into an entry field in a dialog with title value.

value may be of any type, but is typically a string.

show user-input "What is your name?"

user-message

user-message value

Opens a dialog with value displayed as the message.

value may be of any type, but is typically a string.

user-message "There are " + count turtles + " turtles."

user-yes-or-no?

user-yes-or-no? value

Reports true or false based on the user's response to value.

value may be of any type, but is typically a string.

if user-yes-or-no? "Set up the model?"
  [ setup ]

V

value-from

value-from agent [reporter]

Reports the value of the reporter for the given agent (turtle or patch).

show value-from (turtle 5) [who * who]
=> 25
show value-from (patch 0 0) [count turtles in-radius 3]
;; prints the number of turtles located within a
;; three-patch radius of the origin

values-from

values-from agentset [reporter]

Reports a list that contains the value of the reporter for each agent in the agentset.

ca
crt 4
show values-from turtles [who]
=> [0 1 2 3]
show values-from turtles [who * who]
=> [0 1 4 9]

variance

variance list

Reports the sample variance of a list of numbers. Ignores other types of items.

The sample variance is the sum of the squares of the deviations of the numbers from their mean, divided by one less than the number of numbers in the list.

show variance [2 7 4 3 5]
=> 3.7

W

wait

wait number

Wait the given number of seconds. (You can use floating-point numbers to specify fractions of seconds.) Note that you can't expect complete precision; the agent will never wait less than the given amount, but might wait slightly more.

repeat 10 [ fd 1 wait 0.5 ]

See also every.

while

while [reporter] [ commands ]

If reporter reports false, exit the loop. Otherwise run commands and repeat.

The reporter may have different values for different agents, so some agents may run commands a different number of times than other agents.

while [any? other-turtles-here]
  [ fd 1 ]
;; turtle moves until it finds a patch that has
;; no other turtles on it

who

who
Turtle Command

This is a built-in turtle variable. It holds the turtle's id number (an integer greater than or equal to zero). You cannot set this variable; a turtle's id number never changes.

When NetLogo starts, or after you use the clear-all or clear-turtles commands, new turtles are created with ids in order, starting at 0. If a turtle dies, though, a new turtle may eventually be assigned the same id number that was used by the dead turtle.

Example:

show values-from (turtles with [color = red]) [who]
;; prints a list of the id numbers of all red turtles
;; in the Command Center
ca
cct 100
  [ ifelse who < 50
      [ set color red ]
      [ set color blue ] ]
;; turtles 0 through 49 are red, turtles 50
;; through 99 are blue

You can use the turtle reporter to retrieve a turtle with a given id number. See also turtle.

with

agentset with [reporter]

Takes two inputs: on the left, an agentset (usually "turtles" or "patches"). On the right, a boolean reporter. Reports a new agentset containing only those agents that reported true -- in other words, the agents satisfying the given condition.

show count patches with [pcolor = red]
;; prints the number of red patches

without-interruption

without-interruption [ commands ]

The agent runs all the commands in the block without allowing other agents to "interrupt". That is, other agents are put "on hold" and do not execute any commands until the commands in the block are finished.

crt 5
ask turtles
  [ without-interruption
      [ type 1 fd 1 type 2 ] ]
=> 1212121212
;; because each turtle will output 1 and move,
;; then output 2.  however:
ask turtles
  [ type 1 fd 1 type 2 ]
=> 1111122222
;; because each turtle will output 1 and move,
;; then output 2

word

word value1 value2
(word value1 ... valuen)

Concatenates the inputs together and reports the result as a string.

show word "tur" "tle"
=> "turtle"
word "a" 6
=> "a6"
set directory "c:\\foo\\fish\\"
show word directory "bar.txt"
=> "c:\foo\fish\bar.txt"
show word [1 54 8] "fishy"
=> "[1 54 8]fishy"
show (word "a" "b" "c" 1 23)
=> "abc123"

wrap-color

wrap-color number

wrap-color checks whether number is in the NetLogo color range of 0 to 140 (not including 140 itself). If it is not, wrap-color "wraps" the numeric input to the 0 to 140 range.

The wrapping is done by repeatedly adding or subtracting 140 from the given number until it is in the 0 to 140 range. (This is the same wrapping that is done automatically if you assign an out-of-range number to the color turtle variable or pcolor patch variable.)

show wrap-color 150
=> 10
show wrap-color -10
=> 130

write

write value

This command will output value, which can be a number, string, list, boolean, or nobody to the Command Center not followed by a carriage return (unlike print and show).

The calling agent is not printed before the value, unlike show. Its output will also includes quotes around strings and is prepended with a space.

write "hello world"
=>  "hello world"

See also print, show, and type.

X

xcor

xcor
Turtle Command

This is a built-in turtle variable. It holds the current x coordinate of the turtle. This is a floating point number, not an integer. You can set this variable to change the turtle's location.

This variable is always greater than or equal to (- screen-edge-x) and strictly less than screen-edge-x.

See also setxy, ycor, pxcor, pycor,

xor

boolean1 xor boolean2

Reports true if either boolean1 or boolean2 is true, but not when both are true.

if (pxcor > 0) xor (pycor > 0)
  [ set pcolor blue ]
;; upper-left and lower-right quadrants turn blue

Y

ycor

ycor
Turtle Command

This is a built-in turtle variable. It holds the current y coordinate of the turtle. This is a floating point number, not an integer. You can set this variable to change the turtle's location.

This variable is always greater than or equal to (- screen-edge-y) and strictly less than screen-edge-y.

See also setxy, xcor, pxcor, pycor,

?

?

?, ?1, ?2, ...

These are special local variables. They hold the current inputs to a reporter or command block for certain primitives (for example, the current item of a list being visited by foreach or map).

? is always equivalent to ?1.

You may not set these variables, and you may not use them except with certain primitives, currently foreach, map, reduce, filter, sort-by, and n-values. See those entries for example usage.