How To Add Random Number Of Agents In Netlogo
Tutorial #3: Procedures
NetLogo 6.two.ii User Manual
This tutorial leads you through the process of building a complete model, congenital up in stages, with every footstep explained forth the way.
- Agents and procedures
- Making the setup button
- Switching to tick-based view updates
- Making the get button
- Experimenting with commands
- Patches and variables
- Turtle variables
- Monitors
- Switches and labels
- More procedures
- Plotting
- Tick counter
- Some more details
- What's next?
- Appendix: Consummate code
Agents and procedures
In Tutorial #two, you learned how to apply the command center and agent monitors to audit and modify agents and make them practice things. Now y'all're set to learn about the real heart of a NetLogo model: the Code tab.
Y'all've seen that agents in NetLogo are divided into patches, turtles, links, and the observer. Patches are stationary and arranged in a filigree. Turtles move over that grid. Links connect ii turtles. The observer oversees everything that's going on and does whatever the turtles, patches and links tin't practice for themselves.
All four types of agents can run NetLogo commands. All four can likewise run "procedures". A procedure combines a series of NetLogo commands into a single new command that you ascertain.
You volition at present learn to write procedures that make turtles move, eat, reproduce, and dice. Y'all will as well learn how to make monitors, sliders, and plots. The model nosotros'll build is a simple ecosystem model not unlike Wolf Sheep Predation from Tutorial #1.
Making the setup button
To beginning a new model, select "New" from the File menu. Then begin past creating a setup push:
- Click the "Add together" icon in the toolbar at the top of the Interface tab.
- On the bill of fare next to Add, select Push (if it isn't already selected).
- Click wherever yous want the button to appear in the empty white area of the Interface tab.
- A dialog box for editing the button opens. Blazon
setup
in the box labeled "Commands".- Press the OK push when you're done; the dialog box closes.
At present you have a setup button. Pressing the button runs a process called "setup". A procedure is a sequence of NetLogo commands that we assign a new name. Nosotros'll define that procedure presently, but we haven't yet. The push button refers to a process that doesn't be, so the push turns red:
If you want to see the actual error bulletin, click the push.
Now we'll create the "setup" process, so the error message will get away:
- Switch to the Code tab.
- Type the following:
to setup clear-all create-turtles 100 [ setxy random-xcor random-ycor ] reset-ticks end
When you're washed, the Code tab looks like this:
Note that some lines are indented. Most people discover information technology helpful to indent their code. It isn't mandatory, just it makes the code easier to read and modify.
Your process begins with to
and ends with finish
. Every procedure begins and ends with these words.
Let's look at what you typed in and see what each line of your procedure does:
-
to setup
begins defining a procedure named "setup". -
clear-all
resets the world to an initial, empty state. All the patches plough black and any turtles you might accept created disappear. Basically, it wipes the slate clean for a new model run. -
create-turtles 100
creates 100 turtles. They start out standing at the origin, that is, the heart of patch 0,0. - After
create-turtles
nosotros can put commands for the new turtles to run, enclosed by square brackets. -
setxy random-xcor random-ycor
is a command using "reporters". A reporter, equally opposed to a command, reports a result. Outset each turtle runs the reporterrandom-xcor
which volition report a random number from the allowable range of turtle coordinates forth the 10 axis. Then each turtle runs the reporterrandom-ycor
, same for the Y axis. Finally each turtle runs thesetxy
command with those 2 numbers every bit inputs. That makes the turtle move to the betoken with those coordinates. -
reset-ticks
starts the tick counter, now that setup is otherwise complete. -
end
completes the definition of the "setup" procedure.
When you lot're done typing, switch to the Interface tab and press the setup button you made before. You lot will run into the turtles scattered effectually the globe:
Printing setup a couple more than times, and run into how the organisation of turtles is different each time. Notation that some turtles may exist right on top of each other.
Remember a chip about what y'all needed to do to brand this happen. You needed to make a button in the interface and make a procedure that the button uses. The push only worked in one case you lot completed both of these split steps. In the residuum of this tutorial, you volition often have to complete two or more like steps to add together another feature to the model. If something doesn't appear to work subsequently you completed what you idea is the final step for that new feature, continue to read ahead to see if there is still more to do. Subsequently reading ahead for a couple of paragraphs, y'all should then go back over the directions to see if at that place is any step you might have missed.
Switching to tick-based view updates
Now that we're using the tick counter (with reset-ticks
), we should tell NetLogo that it but needs to update the view one time per tick, instead of continuously updating it.
- Discover the view updates menu. It'due south above the view and by default says "continuous".
- Choose "on ticks" instead.
This makes your model run faster and ensures a consistent appearance (since the updates will happen at consequent times). See the Programming Guide for a fuller discussion of view updates.
Making the become button
Now make a button called "get". Follow the same steps you used to make the setup push, except:
- For Commands enter
become
instead ofsetup
.- Cheque the "Forever" checkbox in the edit dialog.
- Check the "Disable until ticks get-go" checkbox too.
The "Forever" checkbox makes the button stay downwards once pressed, so its commands run over and over over again, not simply once.
The "Disable until ticks start" prevents you from pressing go earlier setup.
- Then add together a go procedure to the Code tab:
to go move-turtles tick cease
tick
is a primitive that advances the tick counter past i tick.
Merely what is move-turtles
? Is it a primitive (in other words, built-in to NetLogo)? No, information technology's another process that you're about to add. Then far, you lot accept introduced 2 procedures that you lot added yourself: setup
and go
.
- Add together the
move-turtles
procedure after thego
procedure:to go move-turtles tick finish to move-turtles enquire turtles [ correct random 360 forwards 1 ] end
Notation at that place are no spaces around the hyphen in movement-turtles
. In Tutorial #2 we used scarlet - 2
, with spaces, in order to subtract two numbers, only hither we desire motion-turtles
, without spaces. The "-" combines "move" and "turtles" into a single proper name.
Hither is what each command in the movement-turtles
procedure does:
-
enquire turtles [ ... ]
says that each turtle should run the commands in the brackets. -
right random 360
is another command that uses a reporter. Showtime, each turtle picks a random whole number between 0 and 359. (random
doesn't include the number y'all requite it as a possible effect.) Then the turtle turns right this number of degrees. -
forward i
makes the turtle move forward one step.
Why couldn't we have just written all of these commands in get
instead of in a carve up procedure? We could take, but during the course of building your project, it's likely that you'll add many other parts. We'd like to keep go
every bit elementary as possible, so that information technology is like shooting fish in a barrel to empathize. Eventually, it volition include many other things you want to take happen as the model runs, such as calculating something or plotting the results. Each of these things to exercise will have its own procedure and each procedure volition have its own unique name.
The 'go' button you made in the Interface tab is a forever button, meaning that it will continually run its commands until you shut it off (by clicking on it again). Later y'all have pressed 'setup' once, to create the turtles, press the 'become' button. Lookout man what happens. Turn information technology off, and you'll meet that all the turtles end in their tracks.
Note that if a turtle moves off the edge of the world, it "wraps", that is, it appears on the other side. (This is the default beliefs. Information technology tin can be changed; encounter the Topology department of the Programming Guide for more information.)
Experimenting with commands
We suggest you get-go experimenting with other turtle commands.
Type commands into the Command Centre (like turtles> set color red
), or add commands to setup
, get
, or motion-turtles
.
Annotation that when y'all enter commands in the Control Center, you must choose turtles>
, patches>
, links>
, or observer>
in the popup card on the left, depending on which agents are going to run the commands. It's just similar using inquire turtles
or enquire patches
, only saves typing. You can also use the tab key to switch agent types, which you lot might find more convenient than using the carte du jour.
Yous might endeavour typing turtles>
pen-downward
into the Command Center and then pressing the become button.
Also, inside the motility-turtles
procedure you can try changing correct random 360
to correct random 45
.
Play around. It'south easy and the results are immediate and visible – one of NetLogo'south many strengths.
When yous experience you've done enough experimenting for now, you're prepare to go on improving the model you are building.
Patches and variables
Now we've got 100 turtles aimlessly moving effectually, completely unaware of annihilation else around them. Permit'southward make things a picayune more interesting by giving these turtles a nice background against which to move.
Go back to the
setup
procedure. We tin can rewrite it as follows:to setup clear-all setup-patches setup-turtles reset-ticks end
The new definition of
setup
refers to 2 new procedures. To ascertainsetup-patches
, add this:to setup-patches ask patches [ set pcolor greenish ] stop
The
setup-patches
procedure sets the colour of every patch to green to get-go with. (A turtle's color variable iscolor
; a patch'due south ispcolor
.)The simply part remaining in our new 'setup' that is still undefined is
setup-turtles
.
- Add this procedure too:
to setup-turtles create-turtles 100 ask turtles [ setxy random-xcor random-ycor ] end
Did you notice that the new
setup-turtles
procedure has well-nigh of the aforementioned commands as the oldsetup
procedure?
- Switch back to the Interface tab.
- Press the setup push.
Voila! A lush NetLogo landscape complete with turtles and greenish patches appears:
Afterwards seeing the new setup
procedure work a few times, you may find information technology helpful to read through the procedure definitions again.
Turtle variables
So we have some turtles running around on a landscape, only they aren't doing anything with information technology. Let's add some interaction between the turtles and the patches.
We'll make the turtles consume "grass" (the greenish patches), reproduce, and dice. The grass will gradually grow back later on information technology is eaten.
Nosotros'll need a fashion of controlling when a turtle reproduces and dies. Nosotros'll determine that by keeping rail of how much "energy" each turtle has. To do that nosotros need to add a new turtle variable.
You've already seen built-in turtle variables like color
. To make a new turtle variable, we add a turtles-own
declaration at the top of the Lawmaking tab, before all the procedures. Call it free energy
:
turtles-ain [free energy] to get move-turtles eat-grass tick end
Let's use this newly defined variable (free energy
) to allow the turtles to swallow.
- Switch to the Code tab.
- Rewrite the
become
procedure as follows:to become move-turtles eat-grass tick end
Add together a new
eat-grass
procedure:to consume-grass enquire turtles [ if pcolor = greenish [ set pcolor blackness set free energy energy + x ] ] stop
We are using the if
command for the first time. Look at the code carefully. Each turtle, when it runs these commands, compares the value of the patch colour it is on (pcolor
) to the value for green
. (A turtle has straight admission to the variables of the patch it is continuing on.) If the patch color is green, the comparing reports truthful
, and only then will the turtle run the commands within the brackets (otherwise information technology skips them). The commands make the turtle modify the patch color to black and increase its own energy by 10. The patch turns black to signify that the grass at that spot has been eaten. And the turtle is given more energy, from having just eaten.
Next, let'southward make the move of turtles utilize up some of the turtle's free energy.
- Rewrite
motion-turtles
as follows:to move-turtles ask turtles [ right random 360 forward 1 set energy free energy - i ] end
Equally each turtle wanders, it will lose one unit of measurement of energy at each step.
- Switch to the Interface tab now and press the setup button and the go button.
You'll meet the patches turn black as turtles travel over them.
Monitors
Side by side you volition create 2 monitors in the Interface tab with the toolbar. (You make them simply similar buttons and sliders, using the Add icon on the toolbar.) Let'south make the commencement monitor now.
- Create a monitor past clicking the Add icon on the toolbar, selecting Monitor next to it, and clicking on an open up spot in the Interface.
A dialog box will appear.
- In the dialog type:
count turtles
(run across prototype below).- Press the OK button to close the dialog.
turtles
is an "agentset", the prepare of all turtles. count
tells u.s. how many agents are in that set.
Let's make the 2d monitor at present:
- Create a monitor by clicking the Add together icon on the toolbar, selecting Monitor next to information technology, and clicking on an open up spot in the Interface.
A dialog box volition appear.
- In the Reporter section of the dialog box blazon:
count patches with [pcolor = green]
(encounter image below).- In the Display proper noun section of the dialog box blazon:
green patches
- Press the OK button to shut the dialog box.
Here we're using count
again to see how many agents are in an agentset. patches
is the set of all the patches, just we don't just want to know how many patches there are total, we desire to know how many of them are dark-green. That's what with
does; it makes a smaller agentset of just those agents for whom the condition in the brackets is true. The condition is pcolor = green
, and then that gives u.s. but the green patches.
Now we take two monitors that volition report how many turtles and green patches we take, to help us track what's going on in our model. Every bit the model runs, the numbers in the monitors volition automatically modify.
- Employ the setup and become buttons and watch the numbers in the monitors change.
Switches and labels
The turtles aren't just turning the patches blackness. They're too gaining and losing energy. As the model runs, effort using a turtle monitor to watch one turtle's energy become up and down.
Information technology would exist nicer if we could run across every turtle'due south free energy all the fourth dimension. Nosotros will at present do exactly that, and add a switch so we can turn the extra visual information on and off.
- Click on the Add together icon on the toolbar (in the Interface tab).
- Select Switch from the menu side by side to Add.
- Click on an open spot in the interface.
A dialog volition appear.
- Into the Global variable field, type
show-free energy?
Don't forget to include the question marking in the name. (See image below.)
- At present go back to the 'go' procedure using the Lawmaking tab with the Toolbar.
- Rewrite the
eat-grass
procedure as follows:to eat-grass ask turtles [ if pcolor = greenish [ set pcolor black fix free energy energy + 10 ] ifelse show-free energy? [ set label energy ] [ set label "" ] ] terminate
The eat-grass
procedure introduces the ifelse
command. Await at the code carefully. Each turtle, when information technology runs these new commands, checks the value of show-energy?
(determined by the switch). If the switch is on, comparison is true and the turtle will run the commands within the first set of brackets. In this case, it assigns the value for the energy to the characterization of the turtle. If the comparing is false (the switch is off) and then the turtle runs the commands inside the second set of brackets. In this case, information technology removes the text labels (by setting the label of the turtle to exist nil).
(In NetLogo, a slice of text is called a "string", short for string of characters. A string is a sequence of letters or other characters, written between double quotes. Here we have two double quotes correct next to each other, with nothing in between them. That'south an empty string. If a turtle'due south label is an empty string, no text is attached to the turtle.)
- Exam this in the Interface tab, by running the model (using the setup and go buttons) switching the
show-energy?
switch dorsum and forth.
When the switch is on, you'll run across the energy of each turtle go up each time it eats grass. You'll also come across its energy going down whenever it moves.
More than procedures
Now our turtles are eating. Permit's make them reproduce and die, too. And allow's make the grass grow dorsum. Nosotros'll add all 3 of these of these behaviors at present, by making three separate procedures, one for each behavior.
- Go to the Code tab.
- Rewrite the
go
process as follows:to go move-turtles swallow-grass reproduce bank check-death regrow-grass tick end
Add the procedures for
reproduce
,check-death
, andregrow-grass
every bit shown beneath:to reproduce enquire turtles [ if energy > 50 [ set up energy energy - l hatch i [ set energy fifty ] ] ] finish to check-decease ask turtles [ if energy <= 0 [ die ] ] finish to regrow-grass ask patches [ if random 100 < three [ set up pcolor green ] ] end
Each of these procedures uses the if
command. Each turtle, when it runs check-expiry
it will check to encounter if its energy is less or equal to 0. If this is true, then the turtle is told to die
(die is a NetLogo primitive).
When each turtle runs reproduce
, information technology checks the value of the turtle'due south energy
variable. If it is greater than 50, then the turtle runs the commands within the first set of brackets. In this case, it decreases the turtle's free energy by 50, then 'hatches' a new turtle with an energy of 50. The hatch
control is a NetLogo primitive which looks similar this: hatch
number [ commands ]. This turtle creates number new turtles, each identical to its parent, and asks the new turtle(s) that take been hatched to run commands. You tin can apply the commands to give the new turtles different colors, headings, or whatever. In our case we run one command. We set the energy for the newly hatched turtle to be 50.
When each patch runs regrow-grass
it volition check to see if a random integer from 0 to 99 is less than iii. If and then, the patch color is set to green. This volition happen iii% of the fourth dimension (on average) for each patch, since there are 3 numbers (0, i, and 2) out of 100 possible that are less than 3.
- Switch to the Interface tab now and press the setup and go buttons.
Y'all should see some interesting behavior in your model now. Some turtles die off, some new turtles are created (hatched), and some grass grows back. This is exactly what we set out to do.
If you keep to sentry your monitors in your model, you will see that the count turtles and green patches monitors both fluctuate. Is this pattern of fluctuation predictable? Is there a relationship betwixt the variables?
Information technology'd be dainty if we had a easier mode to rails the changes in the model behavior over time. NetLogo allows us to plot information as we proceed. That will be our next step.
Plotting
To make plotting piece of work, we'll need to create a plot in the Interface tab and put some commands inside it.
The commands we put in the plots volition run automatically when our setup
procedure calls reset-ticks
and when our become
process calls tick
.
- Create a plot by clicking the Add icon on the toolbar, selecting Plot next to information technology, and clicking on an open spot in the Interface.
- Set its Name to "Totals" (see epitome below)
- Set the Ten axis label to "time"
- Set up the Y axis label to "totals"
- Alter the name of the "default" pen to "turtles".
- Enter
plot count turtles
nether Pen Update Commands.- Press the "Add Pen" push button.
- Change the name of the new pen to "grass".
- Enter
plot count patches with [pcolor = light-green]
under Pen Update Commands.
When you're done, the dialog should await like this:
- Press OK in the Plot dialog to finish editing.
Note that when y'all create the plot yous can also set the minimum and maximum values on the X and Y axes. You'll want to get out the "Auto Calibration" checkbox checked, so that if anything you plot exceeds the minimum and maximum values for the axes, the axes will automatically grow so you tin can see all the data.
Note that nosotros used the plot
control to add the side by side point to a plot. This command moves the current plot pen to the point that has an X coordinate equal to ane greater than the previously plotted X coordinate and a Y coordinate equal to the value given in the plot command (in the first case, the number of turtles, and in the 2d case, the number of green patches). As the pens motility they each draw a line.
- Setup and run the model again.
Y'all can at present picket the plot being fatigued equally the model is running. Your plot should have the general shape of the i below, though your plot might not look exactly the aforementioned.
Remember that we left "Auto Scale?" on. This allows the plot to readjust itself when information technology runs out of room.
If you forget which pen is which, you tin edit the plot and bank check the "Bear witness legend?" checkbox.
You might effort running the model several times to run into what aspects of the plot are the same and which are unlike from run to run.
Tick counter
To make comparisons between plots from i model run and another, information technology is often useful to do the comparing for the same length of model run. Learning how to stop or start an action at a specific time can help make this happen by stopping the model at the aforementioned indicate each model run. Keeping track of how many times the go
process is run is a useful way to cue these deportment. That's what the tick counter does.
Yous're already using the tick counter in your model, with the reset-ticks
and tick
commands, which also trigger plotting.
Yous can also use the tick counter for other things, such as to fix a limit on the total length of a run.
Alter the
get
process:to become if ticks >= 500 [ stop ] move-turtles consume-grass check-expiry reproduce regrow-grass tick finish
Now setup and run the model.
The graph and model won't keep running forever. They should stop automatically when the tick counter in the Interface tab'due south toolbar reaches 500.
The tick
control advances the tick counter by i. ticks
is a reporter which reports the current value of the tick counter. reset-ticks
, in your setup
procedure, takes care of restarting the tick counter at 0 when a new run is ready and set up to brainstorm.
Some more than details
Showtime, instead of e'er using 100 turtles, you lot can have a varying number of turtles.
- Create a slider named "number": click the Add icon on the toolbar, select Slider adjacent to it, and click on an open spot in the interface.
- Effort changing the minimum and maximum values in the slider.
- Then inside of
setup-turtles
, instead ofcreate-turtles 100
yous tin type:to setup-turtles create-turtles number [ setxy random-xcor random-ycor ] terminate
Exam this change and compare how having more or fewer turtles initially affect the plots over fourth dimension.
2nd, wouldn't information technology be dainty to adjust the energy the turtles gain and lose every bit they consume grass and reproduce?
- Make a slider chosen
energy-from-grass
.- Make another slider called
birth-energy
.- Then, within of
consume-grass,
make this change:to swallow-grass ask turtles [ if pcolor = green [ fix pcolor black fix energy (energy + energy-from-grass) ] ifelse show-energy? [ set label energy ] [ set label "" ] ] end
And, within of
reproduce
, make this change:to reproduce inquire turtles [ if free energy > nascency-energy [ set energy energy - nascency-energy hatch one [ set energy nativity-energy ] ] ] finish
Finally, what other slider could you add to vary how oft grass grows back? Are at that place rules you can add to the movement of the turtles or to the newly hatched turtles that happen merely at certain times? Attempt writing them.
What's next?
So at present you lot have a unproblematic model of an ecosystem. Patches abound grass. Turtles wander, swallow the grass, reproduce, and dice.
You have created an interface containing buttons, sliders, switches, monitors, and a plot. You've even written a series of procedures to requite the turtles something to exercise.
That's where this tutorial leaves off.
If you'd similar to look at some more documentation about NetLogo, the Interface Guide department of the manual walks you through every chemical element of the NetLogo interface in guild and explains its role. For a detailed clarification and specifics about writing procedures, refer to the Programming Guide. All of the primitives are listed and described in the NetLogo Dictionary.
Besides, you lot can continue experimenting with and expanding this model if you'd like, experimenting with different variables and behaviors for the agents.
Alternatively, you may desire to revisit the kickoff model in the tutorial, Wolf Sheep Predation. This is the model you used in Tutorial #ane
. In the Wolf Sheep Predation model, you saw sheep move around, consume resources that are replenished occasionally (grass), reproduce under certain conditions, and die if they ran out of resources. Just that model had another type of fauna moving effectually – wolves. The add-on of wolves requires some additional procedures and some new primitives. Wolves and sheep are ii different "breeds" of turtle. To run into how to utilize breeds, written report Wolf Sheep Predation.
Alternatively, yous can wait at other models (including the many models in the Code Examples section of the Models Library) or even become ahead and build your own model. You don't even take to model anything. It tin be interesting just to watch patches and turtles forming patterns, to endeavour to create a game to play, or any.
Hopefully you have learned some things, both in terms of the NetLogo language and most how to go nigh building a model. The entire set of procedures that was created in a higher place is shown below.
Appendix: Consummate code
The complete model is also available in NetLogo'due south Models Library, in the Code Examples department. Information technology'due south called "Tutorial 3".
Observe that this listing is full of "comments", which begin with semicolons. Comments let you mix an explanation the code right in with the lawmaking itself. Y'all might use comments to help others empathize your model, or y'all might use them as notes to yourself.
In the Lawmaking tab, comments are grayness, so your eyes can pick them out easily.
turtles-own [energy] ;; for keeping track of when the turtle is prepare ;; to reproduce and when it volition die to setup clear-all setup-patches setup-turtles reset-ticks end to setup-patches ask patches [ set pcolor dark-green ] finish to setup-turtles create-turtles number ;; uses the value of the number slider to create turtles inquire turtles [ setxy random-xcor random-ycor ] end to get if ticks >= 500 [ end ] ;; stop later on 500 ticks move-turtles eat-grass check-death reproduce regrow-grass tick ;; increase the tick counter by one each fourth dimension through end to move-turtles ask turtles [ right random 360 frontwards 1 ready energy energy - 1 ;; when the turtle moves information technology looses 1 unit of energy ] stop to eat-grass enquire turtles [ if pcolor = dark-green [ gear up pcolor black ;; the value of energy-from-grass slider is added to energy set energy energy + energy-from-grass ] ifelse show-free energy? [ set label free energy ] ;; the characterization is prepare to be the value of the free energy [ set label "" ] ;; the characterization is set to an empty text value ] finish to reproduce ask turtles [ if energy > nascency-free energy [ set energy energy - nascency-energy ;; take away birth-free energy to give birth hatch 1 [ set energy birth-energy ] ;; requite this birth-free energy to the offspring ] ] stop to check-decease enquire turtles [ if energy <= 0 [ dice ] ;; removes the turtle if it has no energy left ] end to regrow-grass ask patches [ ;; three out of 100 times, the patch color is fix to green if random 100 < 3 [ set pcolor green ] ] terminate
How To Add Random Number Of Agents In Netlogo,
Source: https://ccl.northwestern.edu/netlogo/docs/tutorial3.html
Posted by: rubioalwass.blogspot.com
0 Response to "How To Add Random Number Of Agents In Netlogo"
Post a Comment