Guidelines

Assignments and Due Dates

Find the assignments and due dates on our Canvas course page. For full credit, be sure to honor the due date: assignments must be submitted on time. They are discussed after submission, so late assignments cannot be accepted.

Econ 450 students should skip parts marked as Advanced (unless pursuing an honors supplement). However, such sections may apply to Econ 650 students; attend to the assignment details.

Computationally oriented homework projects implement methods developed in the course. Students must use NetLogo for these projects, even if they are using another language for their term project. Successful project completion will demonstrate an ability to design and construct very simple agent-based models.

You may discuss the assignments online. In the online discussions of assignments, I have two goals that partially conflict. First, I want a full discussion as you attempt the assignments, so that all confusions are quickly addressed. Second, I want everyone to do their own work.

You may find that to ask a question or help another student, you need to post a code snippet. Snippets are OK. But for collected assignments, do not share the bulk of your code before the assignment is collected.

Please do not be too paranoid about posting a little code. I trust you all to have good intent. But avoid posting code when a nice hint or link may serve as well to help your colleague, and never post more than is really needed for the discussion. The day after an assignment is due, you may share as much of your code as you wish. (By implication, assignments will not be accepted after the due date.)

Preparing Your Code for Submission

Here are some practices you should follow for every computational project.

  • Put your name and the date at the very top of your source files.

  • Fully comment all all your code. The purpose of every global variable, including interface globals, should be carefully defined. Make your comment lines reasonably short, using multiple lines for long comments. Put comments on their own line when that reduces clutter.

  • Attribute all borrowed code by adding a comment giving the author's name. If the good comes from an existing model, provide a full citation of the model.

  • Avoid hardcoding numbers when possible. (Instead, set global variables in setupGlobals.)

  • Distinguish between procedures and reporters (to vs. to-report): only reporters can use the report keyword.

  • When you work with turtles, work with them directly. (Do not work with their who numbers.)

  • When you work with patches, work with them directly. (Do not work with their coordinates.)

  • Your setup procedure should generally look like this:

    to setup
      clear-all
      setupGlobals
      setupPatches
      setupAgents
      reset-ticks
      setupGUI
    end
  • Most important: bring the error messages that you encounter to the list for discussion, so that you do not have to struggle on your own.

Short Computational Projects

Population Growth

This is just a summary of the assignment. Find the details as exercises in my lecture notes on Complex Dynamical Systems, which are posted in the System Dynamics and Population Growth module on Canvas. Before attempting this assignment, be sure to complete the prerequisites listed there. Work on these prerequisites is ungraded and not collected, but students who do not master these preliminary skills or skip the required readings should not expect to be able to complete this assignment. If you feel a that information you need is missing from the prerequisites and the required reading, please let me know right away.

Fishing World

For this assignment, create (and turn in) two separate program files and the requested charts. Put your name and date near the top of each program file, in a program comment. Provide answers to any discussion questions as program comments.

Fishing World: Assignment Overview

This assignment is based on the Fishing World lecture. Before your start, quickly read this all the way through. Then slowly work through all the exercises.

Part I

Create a NetLogo program based on the Basic Fishing World. Produce any required charts.

Part II

Create a NetLogo program based on the Buddy World. Produce any required charts.

Before attempting this exercise, complete the prerequisites listed in the Fishing World introduction. Although the course should cover all this material before the exercise is due, students who do not master these preliminary skills should not expect to be able to complete this assignment. If you feel a that information you need is missing, please let me know right away.

Full assignment details and exercises are in the Fishing World lecture. Complete every exercise, except those marked as optional.

Segregation Exercise

Preliminaries

Assignment Details

After learning about the Schelling Segregation Model and its implementation in the NetLogo Models Library, you will design an experiment and then write a report.

Your report should include a UML class diagram and a UML activity diagram. It should include the charts and/or tables you produce from your BehaviorSpace output. (Include these in the main body of the report, not in a separate appendix.) Follow the formatting checklist for instructions on how to properly format your submission. (This is the same checklist that you should use for your term paper.)

  1. Carefully describe (in words) the essential features of the Schelling (1978) segregation model (hereafter referred to as the Schelling Model), as set out by Schelling (1978, ch4, pages 147-155). Your goal here is to describe the aspects of the model that must be incorporated in any computational model that might claim to represent a Schelling Segregation Model. For the model details, you may rely entirely on my posted notes rather than reading the Schelling chapter.

    • What social issues did Schelling think his model addressed? (This is not a question about the simulation outcomes but rather of the model structure: in what ways can you map the model to the real world?)

    • Technical question: Does the Schelling Model satisfy the standard definition of a 2D cellular automaton? (Be very specific and detailed.)

  2. Does the implementation of the Schelling Model in the NetLogo Models Library (Sample Models » Social Science » Segregation) capture the general structural features of the Schelling Model? (What is included; what is missing; what if anything is an extension?)

  3. Based on the model, construct a UML class diagram that can guide an implementation in code of the core agent type in the Schelling model.

  4. Based on the readings, construct a UML activity diagram (or flow chart) that can guide an implementation of the Schelling model as computer code. (You can use any drawing program you like, but you may want to use umletto, LucidChart, Dia, draw.io, or Gliffy for this.)

    Your activity diagram does not need to represent the setting of sliders: treat the user-chosen slider values like any other exogenous global value. Your activity diagram does not need to present any detailed code from the procedure body, but it should carefully present the simulation schedule.

    Discuss the how the simulation works, making reference to your UML diagram. For this discussion, you may find it useful to add procedure summaries, resembling those in my lecture notes.

  5. Whenever your research involves changing an existing model, you must archive an unmodified copy of the original model. In this case, you will be modifying the Segregation Model in the NetLogo models library, and that can serve as the archived version. To a personal folder, save a new copy of this model as <LastName>-Segregation.nlogo. (Replace <LastName> with your last name.) Add a comment with your name and date at the very top, followed by a full attribution of the code. In your copy (not to the original), document the name, type, and meaning of all variables. You will add your experiments to this copy (not to the original).

  6. Look at the Interface tab and the Code tab of the Segregation Model. What parameter values must be specified by the user before “experiments” can be run? In your report, document the name, type, and meaning of these variables.

  7. Based on your reading and on preliminary observations of the simulation, propose two different numerical measures of the segregation outcomes of the Schelling model. (Not other outcomes.)

    Each measure should be to shed some light on how segregated the agents are at any point in time. These measures must be computable from information available at the end of each iteration. At least one measure should be an addition you make to the model. You may use one measure that is already in the original model, but you need to write a new reporter procedure for the other. Be creative! There is no ‘best’ answer for this.) But, carefully explain and justify your choices. Aside from that, there is no right answer; be creative!

    Your new measure need not be your own invention: if you wish, you can use ideas you find in your reading. (As always, use appropriate attribution!) You should write a new reporter procedure that computes this measure.

    Note that you are justifying looking at these measures prior to actually running your experiments. The results of your experiments may affect your judgments about these measures, but you do not need to revise your measures in light of your results. Here you are just learning how to explore the model. Not all explorations end up being worthwhile; that is a normal part of the research process.

  8. Create an experimental design, carefully following our discussion of experimental design. (See the readings above, and follow our experimental design outline.) Use at least 5 values for each continuous treatment factor (i.e., model parameter). Use at least 5 replicates for each scenario.

    For example, you might explore how the final values of your two proposed measures of segregation are affected by changes in one or more model parameters.

    Graduate student should include a regression analysis. (If you have never studied regression, please contact me.)

  9. Run your experiments and report your results, carefully following our discussion of results reporting. (See the readings above.)

    Summarize your results. Do they support your hypotheses? (Give your best and most honest assessment. There are no extra points for confirming or disconfirming an hypothesis.) Comment on the compatibility of your proposed segregation measures: do they produce similar or divergent results? Do either or both of your proposed measures have any advantages or drawbacks? (Does either appear more useful than the other?)

  10. In your conclusion, briefly recap your hypotheses and how your evidence from the model bears on them. Then propose some possible extensions to the Schelling model. You may draw on the readings for this, but if you do, be sure to fully attribute the idea. Be clear about what aspects of the real world your extensions are meant to accomodate. (This is a brainstorming exercise; you do not have to implement these extensions!)

Resource Extraction

What to Submit

  • One (1) NetLogo model file named ExtractionWorld04.nlogo. This should be fully commented and should implement all parts of the exercise. (Undergrads need not do Part V.)

  • One (1) .nls file containing testPatchColors and createCluster

  • One (1) run-sequence line chart. (Undergrads may produce this any way they wish, for any model feature they wish. Grad students should complete part V.)

Resource Extraction: Preliminaries

Complete the `Mushroom Hunt`_ exercise before attempting the present exercise. Additionally, be sure you have carefully read the following appendices: NetLogo Introduction and NetLogo Programming. Pay particular attention to the following topics.

  • defining reporter procedures

  • defining command procedures

  • defining procedures with arguments

  • boolean comparisons

  • conditional branching

  • File-Based IO

Class and posted exercises should cover all this material before the exercise is due. If you feel that any information you need is missing, please let me know right away.

Resource Extraction: Assignment Details

Find the details of the Resource Extraction exercise in the notes that I posted to Canvas. First, quickly read over the posted notes. This will give you the needed context for the exercise. Then slowly work through all of the exercises in that chapter, rereading the notes as you go. Each student should do all exercises in this assignment, except for exercises explicitly marked as optional. (Undergrads need not do part V.)

Additional Explorations

Party Model

Related readings:

Party Model: Interface Tab

  • Click the Interface tab for the Party Model. Note three sliders for setting model parameters. The number slider sets the number of individuals, and the num-groups slider sets the number of groups. Set these sliders to match the setup description at http://ccl.northwestern.edu/netlogo/docs/sample.html (How many individuals? How many groups?)

  • Move the speed slider into the slower region, and set view updates chooser to continuous, so that you will be able to see what is going on.

  • After you set your model parameters with the sliders, press the setup button, and then click the go button.

Party Model: Basic Questions

  • What do you see happening as you run the Party Model? How do you explain it?

  • What does the tolerance slider do in the Party Model? What do you expect to happen if you set tolerance to a large value. Does it? What do you expect to happen if you set tolerance to a very small value. Does it?

Party Model: Questions for Discussion

You should find your own answer for each of these questions, and then pick one for discussion that you still find interesting or puzzling. (Try to pick a question that has not already been discussed by someone else.)

  • In chapter 1, how do Railsback and Grimm define "emergence"? Based on this definition, to what extent would you characterize the model outcomes as emergent?

  • What do Railsback and Grimm say is a "common mistake of beginners"? Does the Party Model avoid that mistake? Is the resulting model useful? If so, how?

  • In chapter 1, how do Railsback and Grimm define a "full-fledged" ABM? Based on this definition, to what extent would you characterize the Party model as full-fledged? Would RG argue that this model should be full-fledged?

  • In the Party Model, party-goers attend only to the sex composition of their group. One interpretation is as follows: guys will leave if the discussion is too full of “girl talk”, and girls will leave if the discussion is too full of “guy talk”. But in this course, we all are discussing agent-based simulation together, so clearly topic interest can cut across gender. How severe a limitation of the model is this, in terms of its goals? How might you address this limitation yet still pursue the goals of the model?

  • In the Party Model, party-goers join a fixed number of groups, rather like tables in a school cafeteria. How severe a limitation of the model is this, in terms of its goals? How might you address this limitation yet still pursue the goals of the model?

Party Model: Technical Questions

  • How many ways can we split 5 people into at most 2 groups? How would you determine how many ways can we split 150 people into at most 10 groups? Hint: http://en.wikipedia.org/wiki/Partition_(number_theory)

  • Use the default values of 70 individuals and 10 groups, but set the tolerance to say 12%. Now run the model a few times. (Once will probably be enough to see a very odd outcome.) Why does this happen?

Traffic Basic

Related readings:

Traffic Basic: Basic Questions

  • Recall what Railsback and Grimm say is a "common mistake of beginners". Does this model avoid that mistake? Is the resulting model useful? If so, how?

  • Note three sliders for setting model parameters. Explain the role of each of these.

Traffic Basic: Discussion Questions

You should find your own answer for each of these questions, and then pick one for discussion that you still find interesting or puzzling. (Try to pick a question that has not already been discussed by someone else.)

  • In what sense is behavior "adaptive" in this model?

  • How sensitive are the outcomes to the acceleration settings? How sensitive are the outcomes to the deceleration settings?

  • To what extent would you characterize the model outcomes as emergent?

  • Based on the Railsback and Grimm definition of a "full-fledged" ABM, what would you like to add to make the Traffic Basic model more full-fledged?

  • What happens if you maximize acceleration and minimize deceleration. Is this a realistic outcome or a limitation of the model? Can you explain it?

  • Do you think this model has any “real-world” utility. If so, what?

  • Watch this short video: http://www.youtube.com/watch?feature=player_embedded&v=Suugn-p5C1M Does it affect your view of the usefulness of the model? Why or why not?

  • How might you link the cars to make a train? How would this affect your outcomes? Does autonomous goal seeking produce efficiency?

Traffic Basic: Technical Questions

  • Suppose you would like to characterize the response of model outcomes to the model settings. What outcome measure(s) would you use? How would you like to gather the data? What kind of chart would best display your data?

Wolf-Sheep Predation

Related readings:

Wolf-Sheep Predation: Basic Questions

  • What are the goals of this model?

  • Note seven sliders and two switches for setting model parameters. Explain the role of each of these.

  • Again, what do Railsback and Grimm say is a "common mistake of beginners"? Does this model avoid that mistake? Is the resulting model useful? If so, how?

  • In chapter 1, how do Railsback and Grimm define a "full-fledged" ABM? Based on this definition, to what extent would you characterize the model as full-fledged? Would RG argue that this model should be full-fledged?

Wolf-Sheep Predation: Discussion Questions

  • How does Wilensky define “stability” for this model? Why does adding "grass" to the model matter for the stability of outcomes?

  • How sensitive are the outcomes to the wolf-parameter settings? How sensitive are the outcomes to the sheep-parameter settings?

  • To what extent would you characterize the model outcomes as emergent?

  • Based on the Railsback and Grimm definition of a "full-fledged" ABM, what would you like to add to make the Wolf-Sheep Predation model more full-fledged?

Wolf-Sheep Predation: Technical Questions

  • Agents do not age in this model. In terms of the goals of this model, does that matter? Why or why not?

Coin Flipping

For this exercise, you will create (and turn in) four separate program files and a two separate charts. Put your name and date near the top of each program file, in a program comment. Your answers to any discussion questions below should be in the form of program comments.

Coin Flipping: Part 0 (background; not collected)

Here is what we will do, in basic outline. Simulate draws from a Bernoulli distribution. Simulate draws from a binomial distribution. Characterize this process with run-sequence plots and histograms.

  1. Write a function simulating a draw from a Bernoulli distribution. Name the function bernouilli. The function should take one input: the probability of success (p). It should return a 1 for success and a 0 for failure.

  2. Make a plot that illustrates how of repeated draws from a Bernoulli converges to p.

  3. Write a function simulating one draw from a binomial distribution. Do this by repeatedly calling bernoulli. Name your function binomial. The function should take two input: the number of Bernoulli draws (n), and the probability of success (p).

  4. Make a plot that illustrates how of repeated draws from a binomial converges to n p.

  5. Make a histogram that illustrates the sample variance in a fixed number of repeated draws from a binomial.

Coin Flipping: Part I

In this part of the exercise, we implement the basic program structure for a coin-flipping program. We will use this program to simulate the outcome of a single trial (one coin flip) and of many trials (many coin flips). We also add buttons to the GUI.

  1. Choose or create a folder to hold your project files. Create a new source code file named coinflip01 (plus an appropriate filename extension).

  2. Your program should introduce three global variables: outcome, nHeads, and nTrials.

  3. Add a coinFlip function, which simulates one flip of a fair coin.

    Implement your function as follows. Draw a random floating point value, uniformly between 0 and 1. Then use conditional branching to return a result of either 1 (if the number drawn is less than 0.5) or 0 (otherwise).

  4. We want to use our coinFlip function in a simulation. Simulations very often have two core components: a setup procedure that sets up the initial state of the simulation, and a go (or step) procedure that advances the simulation. We will follow this conventional structure. Start by addign procedures named setup and go, creating an empty stub for each. Then add to these stubs some comments stating what you want them to do when completely implemented. (When implemented, setup will initialize our global variables, and go will flip a coin once and then change the global variables accordingly.)

  5. Implement the setup procedure, which does the preliminary model set up. At this point, setup need only perform the initialization of your global variables. (E.g., reset the values of your global variables to 0.)

  6. Next we implement the go procedure. Your go procedure should

    • call coinFlip and assign the returned value to outcome

    • increment nHeads by the value of outcome,

    • increment nTrials by 1.

    A good way to proceed is to copy these three goals into your procedure body as comments, and then (below each comment) implement each goal.

  7. Q: Implementing setup and go produces a complete a coin-flipping program. Run your setup procedure, then run your go procedure 100 times. (Use a looping construct to do this.) Then print nHeads / nTrials. Did you get half heads and half tails? Should you have?

  8. Q: Rerun your setup procedure, and again run your go procedure 100 times. Do you get an identical outcome? If not, how could you ensure identical outcomes?

  9. Q: Now, again run your go procedure 100 times (this time without first running setup). What is different about the outcome?

  10. Extra exercise (not required): use string concatenation to print an informative summary of the number of trials, the number of heads, and the number of tails.

GUI Details: Buttons

For user convenience, we often add widgets to a GUI that controls our simulation. For now, add just a single type of GUI widget: three buttons.

  1. Add a button named Setup that runs your setup procedure.

  2. Add a button labeled Go Once that runs your go procedure.

  3. Add a button labeled Go 100 that runs your go procedure 100 times.

  4. Test your buttons!

NetLogo Details

  1. The command to reset your global variables is clear-all.

  2. Your coinFlip function should be a reporter that returns either 0 or 1. Consider using ifelse-value.

  3. NetLogo allows point-and-click addition of any GUI widget in the Interface tab,

  4. We are not using patches or turtles. If you want, you can set the patch width to -1 to make the Graphics Window invisible.

Coin Flipping: Part II

It is important to be able to collect data from our simulations for subsequent analysis. In this part of the Coin Flipping exercise, we write data from a coin-flipping simulation to a file. Subsequently, we create a run-sequence plot based on that data. So that we can gather more interesting data, we will generalize our model to allow for unfair coins.

  1. So far we have been assuming a fair coin. Let us generalize this. Add a new global variable named pHead, with a default value of 0.5. This will be the probability of getting a head from a single coin flip. Change your coinFlip function to use pHead.

  2. First, make sure you have saved your program file from Part I. Next, make a copy of that file in the same folder. Call this new program file coinflip02 (plus an appropriate filename extension).

  3. Create a subfolder named out folder to hold your output. (You will write an output file to this folder.)

  4. Modify your setup and go procedures to do data collection.

    Add the following to your setup procedure: it should now prepare the file temp.csv (in the out folder) for writing. This setup removes any old version of this file and creates an appropriate header.

    Add the following to your go procedure: it should now append one line to temp.csv, which will be the updated value of outcome.

  5. As before, set up your model and again run your go procedure 100 times. Note that because of the changes you have made, this will write your data to out/temp.csv.

  6. Use the data you have written to out/temp.csv to create a run-sequence plot of the cumulative proportion of heads after each of the 100 coin flips. (Effectively, you wish to plot 100 sequential values of nHeads / nTrials, but use the data you wrote to file.) Save your chart as runSequence01.png.

GUI Details: Sliders and Real-Time Plots

We are going to add slider widget to control how unfair our coin flip is. We will also add a real-time run-sequence plot. You have already created a plot based on the data you wrote to temp.csv. Now, separately, add a real-time plot to your GUI.

  1. Move pHead into a slider, with an initial value of 0.5, a range from 0 to 1, and a step of 0.01.

  2. Add a real-time run-sequence plot of the running mean number of heads. Make sure your plot is cleared by setup and updated by go.

NetLogo Details

  1. Creation of a slider introduces and initializes a global variable; you should not declare it separately using the globals keyword.

    Do not set default values in your setup procedure, because this will interfere with the user’s use of interface globals. Instead, use the special startup procedure for this. http://ccl.northwestern.edu/netlogo/docs/dict/startup.html

  2. To add a plot, you can right click on the Interface window, wherever you wish to place the plot. Change the pen update command to plot nHeads / nTrials. Change the y-range to [0,1].

    If you want to use reset-ticks in your setup procedure, you will have to change your plot command just a bit: if (nTrials > 0) [plot nHeads / nTrials]. Be sure you can explain why.

  3. The clear-all command will also clear your plot. The command to run any setup code in your plot is setup-plots, but we do not need that at this time. The command to update your plot is update-plots.

Coin Flipping: Part III

So for, one “trial” has been a single coin flip. Next, we allow more than one coin flip per trial. (So you are now doing binomial instead of Bernoulli trials.) You will again save your data to a file for subsequent analysis, but this time you will make a histogram from the output. Additionally, we will work on making a more useful GUI by adding two new widgets: a slider and a monitor.

  1. First, make sure you have saved your program file from Part II. Next, copy that file to a new program file named coinflip03 (plus an appropriate filename extension).

  2. Retest your existing implementation as follows. Run setup, and then check the value of nHeads. (The result should be 0.) Run go 100 times, and then check the value of nHeads. (The result is random but is probably near 50.)

  3. The big change we are making is allowing more than one coin flip per trial. To support this, introduce a new global variable named nFlipsPerTrial, with a default value of 5.

  4. Create a new oneTrial function, which

    • calls coinFlip a total of nFlipsPerTrial times, and

    • returns the total number of “heads” this produces.

  5. Modify your go procedure: it should now call oneTrial (instead of coinFlip) and then set outcome to the number of heads produced. (It should still write outcome to your output file.)

  6. Q: You are now ready to run your new (binomial) simulation. Run setup, and then run your new go procedure 100 times. What result to you expect? Do you get the expected result?

  7. Perform the following simulation experiment with your model. Set nFlipsPerTrial equal to 5. Produce output data for 100 trials. Using the data produced by your simulation, produce a histogram of the number of heads produced in your 100 trials Save your chart as histogram01.png.

GUI Details

We are going to add widgets to our GUI.

  1. Include the same buttons as in Part I. Test all your buttons.

  2. Move the nFlipsPerTrial global variable into a slider taking values from 1 to 50 (with an increment of 1), with an initial value of 5.

  3. Let us make it easier to monitor the number of heads per trial so far. Add a monitor for nHeads / nTrials.

NetLogo Details:

Coin Flipping: Part IV

In this part of the exercise, we learn to how to use objects to run our previous simulation. Call these object “coin flippers”. We let the coin flippers do the coin flipping, and they also manipulate global variables. In one round of the simulation, each coin flipper run one trial and stores the results of that trial. We also add a dynamic histogram of these stored outcomes to our GUI.

  1. First, make sure you have saved your program file from Part III. Next, copy this to a new program file named coinflip04 (plus an appropriate filename extension). We are going to make some changes in this new file.

  2. Previously, we repeatedly experimented with running 100 trials. Now we will formalize that by adding a new global variable, nTrialsPerRound, with an initial value of 20.

    However, we will not simply run nTrialsPerRound trials. Instead, we will use nTrialsPerRound different objects, each doing one trial.

  3. Each coin flipper will need an attribute to store the result of its trial. Name this attribute outcome. (Remove the outcome global variable.)

  4. Discard the old go procedure; it is time to write a brand new one. It should now run an entire round, not just a single trial. A single round should

    • have each coin flipper run oneTrial once, set its outcome attribute to the result, and increment nTrials

    • then, count the total number of heads flipped (in this round) by all coin flippers, and set nHeads to the result

  5. Optional: Create a global list containing each round’s total for coin-flipper outcomes. We will repurpose nHeads for this: while nHeads will still be a global variable, it will now be a list of numbers instead of a number. (This introduces a little memory.) Your setup procedure should therefore initialize nHeads to an empty list. Each round, use lput to append the round’s total number of heads to the nHeads list (and of course, use set to set nHeads to the new list).

GUI Details (Plots, Sliders)

  1. Move nTrialsPerRound into a slider, with a range from 1 to 50, an initial value of 20, and a step-size of 1.

  2. Each round, plot the number of heads.

  3. Add a dynamic histogram of the outcome attribute of your coin flippers. This should be updated once each round.

  4. Q: Experiment with your program. Explain what your dynamic histogram illustrates.

  5. Optional: If you have created a list of the number of heads produced for each round, plot its mean in the run-sequence plot you have already created. Each iteration, plot the last number appended to nHeads. In the same chart, plot the running mean of nHeads (i.e., the average number of heads per round).

NetLogo Details

  1. Use patches as your coin-flipper objects. In the Code tab, use the patches-own keyword to add an outcome attribute. (Note that patches-own does not define global variables, but rather patch attributes.)

  2. Be sure to review the code in the Histogram Example in the NetLogo Models Library before attempting to make your dynamic histogram.

  3. We now want outcome to be the name of a patch attribute; it cannot also be the name of a global variable.

  4. Since patches will be our coin flippers, we need the correct number of patches. Each patch runs one trial, and each round we run nTrialsPerRound trials. So add the following to your setup procedure:

    resize-world 0 0 0 (nTrialsPerRound - 1)
    set-patch-size (400 / nTrialsPerRound)

    Read about resize-world and set-patch-size in the NetLogo Dictionary, and then explain in detail (in program comments) what this code does. Test this code by running your setup procedure.

  5. Remember that [attr] of patches creates a list of all the values of the patch attribute attr.

  6. To plot two series in the same chart, you need to add a second plot pen. In this case, add a pen that plots the mean of nHeads.

  7. You can use the NetLogo mean primitive http://ccl.northwestern.edu/netlogo/docs/dictionary.html#mean

  8. Use the pcolor attribute to represent the number of heads. Make a patch greener as it flips more heads. Think carefully about what range you want to use; it can be bigger than the possible outcomes, if you wish.


Gambler’s Ruin

Reminder: The Gambler’s Ruin exercise presumes you have successfully completed the other programming assignments (especially Coin Flipping and `Logistic Map`_).

Gambler’s Ruin Part I: Two-Player Gambler’s Ruin

  1. Create a new program file named ruin01 (plus an appropriate filename extension).

  2. Do the 2-Player Gambler’s Ruin exercise, as described in the exercise in the lecture notes. https://subversion.american.edu/aisaac/notes/gamblers_ruin.html

    You may find it useful to use a while loop.

  3. Export your wealth history for player 1 to out/temp.csv. (You may use a different filename, but use an out folder immediately below your program file.) Open this CSV file in your favorite spreadsheet (e.g., Calc or Excel). Produce a run-sequence plot from this data. Save your spreadsheet graph as a PNG file, and submit it with this assignment.

  4. DRY is good programming practice, and we will be able to reuse our playOnce procedure later in this assignment. So move the playOnce procedure into a new module, named ruin.nls, and import it into your ruin01 model file. After doing this, make sure your model still runs as before.

GUI Extensions

  1. Make a dynamic time-series plot of the evolution of one player’s wealth over time. This plots the wealth of one player. Give your plot the name "Player 1 Wealth". Run your simulation to produce the data for this plot.

NetLogo Notes

plot

http://ccl.northwestern.edu/netlogo/docs/dictionary.html#plot

export-plot

http://ccl.northwestern.edu/netlogo/docs/dictionary.html#export-plot (you can use the export-plot command to export your plot data in CSV format)

while

http://ccl.northwestern.edu/netlogo/docs/dictionary.html#while

ticks

http://ccl.northwestern.edu/netlogo/docs/dictionary.html#ticks Reports the number of times you called tick http://ccl.northwestern.edu/netlogo/docs/dictionary.html#tick

module

Move the playOnce procedure into ruin.nls, and in your Code tab use the __includes keyword to include ruin.nls.

ruin2player

Rather than create a procedure that runs the whole simulation, it is more traditional in NetLogo to create a forever button, which calls the schedule until the schedule calls stop. Feel free to do it this way.

Gambler’s Ruin Part II: N-Player Gambler’s Ruin

Static Pairs

Before attempting this part of the exercise, you may find it helpful to read The Process of Programming (Gambler’s Ruin). This guide emphasizes the value of proceeding step by step, with TODO-list outlines, stubs, and placeholders.

This part goes in a separate file from the previous exercises.

  • Create a new program file for this part of the exercise. Name the file for this part the exercise ruin02 (plus an appropriate filename extension).

  • Do the N-Player Gambler’s Ruin (Static Pairs) exercise, as described in the exercise in the lecture notes.

  • Create a histogram of the final distribution of wealth. Ideally, you will export the final distribution of wealth in CSV format and create this histogram in your favorite spreadsheet.

GUI Considerations

  • Add a dynamic histogram of the evolution of the wealth distribution over time. (See the Histogram Example in the NetLogo Models Library.)

  • Add buttons named setup and Static Pairs to run your setup and staticPairsRuin procedures.

  • Color code the wealth of each agent.

NetLogo Specific Considerations

  • Use the __includes keyword to include ruin.nls in your Code tab. This gives you access to your good friend, the playOnce procedure.

  • Place your discussion in the Info tab. (You can delete the NetLogo Features and the Related Models sections.)

  • Use patches for your wealth-owning objects. During setup (or startup) use the resize-world primitive to make 1000 patches as a 40 x 25 grid.

  • Use scale-color to represent the wealth levels of your players (i.e., the patches).

  • Use plabel to visually display the wealth of "agents" (i.e., patches).

Questions to consider:

  • How many players are there? What is their initial wealth? Should such numbers be stored as global variables? Why?

  • What happens if you never run setup but try to run staticPairsRuin? Why?

  • In a GUI interface to this model, why might we introduce a slider (say, nAgents)?

N-Player Gambler’s Ruin: Random Repairing

This work goes in the same file as your previous work on the N-person model. (That is, just add to your ruin02 file.)

  • Do the N-Player Gambler’s Ruin (Random Re-Pairing) exercise, as described in the lecture notes.

  • Implement two versions of the N-Player Gambler’s Ruin, with random re-pairing, as described in the lecture notes. The first version (randomPairs01) stops when any player’s wealth goes to zero. The second version (randomPairs02) stops after a fixed number of iterations.

  • What does the histogram look like when you stop when the first wealth goes to zero? What does the histogram look like when you stop after maxitr rounds? It is reasonable to interpret the response to these stopping conditions as reflecting “institutional” considerations?

GUI Considerations

  • Add two buttons to run the randomPairs01 and randomPairs02 simulation (after setup, of course).

Gambler’s Ruin Part III: Reimplementation

Advanced

Anticipatory Comment: An array location may seem like a pretty shallow concept of an agent. It is actually a very common one in the literature. This assignment shows you how it can be simple and useful.

This goes in a separate file from the previous exercises. Name the file for this part of the exercise ruin03 (plus an appropriate filename extension).

GUI Extensions

  • Add buttons and plots as in the object-based version.

Extra Things to Try

  • Use export-plot to write data to a file.

  • After reading about how to write data to a file (in the required readings), modify your 2-person Gambler’s Ruin model to write to a file two numbers each tick: the tick and the wealth of the first player. (Do not forget your file-close when you are done!) Discuss any problems you have with this exercise.

Questions to Consider:

  • How much must we actually change our code in order to create the object-based simulation?

  • Does the object-based simulation seem to run faster or slower than the array-based simulation?

  • Why bother with the object version? (After all, it should give the same results.)

The Process of Programming (Gambler’s Ruin)

Do things a little bit at a time. Do not try to do too much at once. After each change, make sure your programs still runs without errors. (Use procedure stubs to achieve this.) Use lots of extra print statements so that you can see what is going on in your program.

Let us see how you might approach the problem of writing an array version of the staticPairsRuin procedure, step by step. We assume that you begin with a copy of your 2-player gambler’s ruin file, and that you will add to this a staticPairsRuin procedure.

First, start with an empty procedure. This is called a stub. Your stub needs to have the correct signature; in this case it will have one input (a list of players) and no outputs. Your empty stub is sure to execute without a problem.

to staticPairsRuin [#playerlist]
end

Next, make a list of the things you want to do, and take them up one at a time. Put your todo list in the body of your procedure. For example:

to staticPairsRuin [#playerlist]
  ;TODO: pairup the items in #playerlist
  ;TODO: for each pair, call `ruin2player`
end

What we really want to do is the last bit, but we need some pairs in order to do that. So as a temporary placeholder, let us just make up some pairs. This will serve as a “placeholder” until we get around to the first TODO item.

to staticPairsRuin [#playerlist]
  ;TODO: pairup the items in #playerlist
  let _pair01 (list patch 0 0 patch 0 1)
  let _pairs (list _pair01)  ;;to be replaced!
  show _pairs ;;scaffolding
  ;TODO: call `ruin2player` once for each pair
end

Check the syntax of your code. (In NetLogo, press the "Check" button in the Code tab. Do this every time you add code to your Code tab.) It seems to be OK, so switch to the Interface tab and "run" your procedure. I.e., just enter its name in the command center. Voila, it works!

After (seriously, after) you have that working ok, you are ready to try running ruin2player on each pair. But to do that, you need to take care of some preliminaries.

  • you need to make ruin2player available

  • ruin2player has some global dependencies, so you need to provide those: maxitr, playOn, and playOnce

If you began with a copy of your 2-player file, all of this is already in place. But now we hit a barrier. The problem is, we want to run ruin2player for each pair, but we do not yet know how to do that. Since we have a list of pairs, you suspect you should use the foreach command. But you may not yet fully understand this command. So first you need to make sure you understand this command. So you go to http://ccl.northwestern.edu/netlogo/docs/dictionary.html#foreach and to https://subversion.american.edu/aisaac/notes/netlogo-intro.html#agentsets-vs-lists and read about how to use foreach. You learn that ? is a special name that is sequentially assigned to each item in the foreach sequence. So you test that out:

to staticPairsRuin [#playerlist]
  ;TODO: pairup the items in #playerlist
  let _pair01 (list patch 0 0 patch 0 1)
  let _pairs (list _pair01)  ;;to be replaced!
  show _pairs ;;scaffolding
  ;TODO: call `ruin2player` once for each pair
  ; first, test understanding of :code:`foreach`
  foreach _pairs [print ?]
end

You use the Check button and find this is OK, so you again run your procedure from the command center and look at the output. Does it look like you expect? Make sure you can explain why you are seeing this output!

Now for your last step, you want to replace [print ?] (which just prints the pair) with the code block that does what you want to do (which is to run ruin2player with the pair). To do that, you should move to the command center and try a few things.

For example, at the Command Center you try

ruin2player (list patch 0 0 patch 0 1)

What happens next depends on how you wrote ruin2player. If you wrote it to accept a list containing two players, it works. However, if you wrote it to take two separate players (rather than a list), you get

ERROR: RUIN2player expected 2 inputs.

Oh, of course: in this case ruin2player needs two players. So in this case you would instead try

ruin2player patch 0 0 patch 0 1

Hey, that works! Now you are ready to go back and use what you have learned to improve your procedure. Assuming you wrote ruin2player to accept a list:

to staticPairsRuin [#playerlist]
  ;TODO: pairup the items in #playerlist
  let _pair01 (list patch 0 0 patch 0 1)
  let _pairs (list _pair01)  ;;to be replaced!
  show _pairs ;;scaffolding
  ;TODO: for each pair, call `ruin2player`
  foreach %pairs [ruin2player ?]
end

Syntax check your code, and try to run it. If it runs, you have completed the hard part. Finally, complete the other TODO item: create the pairs of all the items in playerlist, and replace your place-holder list with your new list of pairs.

The Template Models

First Approach to the Template Models

This exercise teaches you to model production, harvesting, and growth. It is closely related to the Sugarscape model.

Plan ahead! Begin your programming by entering explicit comments, which layout your program structure! Keep most comments as you fill in actual code; they will document your code. Your code should be heavily commented. (This is graded.) Be sure to document the type and meaning of every variable or parameter. Be sure to attribute any borrowed code, including tests.

Second Approach to the Template Models

Simple Network Model

setup procedure
  • Create a set of turtles with random positions

  • Create a random set of links between the turtles

    • Each turtle has same chance of having links

go procedure
  • Pick a random turtle and a random one of its links, and replace it within one attached preferentially

    • Higher chance of linking to a turtle with the most links

  • Go to Model Library, open Network » Preferential Attachment, and save under a new name

    • Agentset – a set of agents

      • Defaults to a random order but can be sorted (into a list)

      • Can also pick a random agent from the agentset

      • If we want agentset to persist, must set it to a name we have previously declared in globals or locally

    • In the context of a turtle, other turtles produces an agentset of all of the other turtles.

Modify Life

  • File > Model Library > Computer Science > Cellular Automata > Life

  • Save on desktop under a new name

Bowen’s suggested modifications of Life * add a slider for global variable init-number

  • default = 2

  • possible values from 1 to 5

  • find the go procedure

    • change 2 to init-number

    • change 3 to init-number + 1

Modify Small Worlds

  • File > Models Library > Networks > Small Worlds

  • Save on desktop under a new name

  • On interface, put in a slider:

    • Global variable init-links

    • Minimum 1

    • Increment 1

    • Maximum 3

    • Value 2

  • Procedures

    • scroll through to find setup, make-turtles, and wire-them

    • determine: what does wire-them do?

  • modifications (suggested by Bowen):

    • Always link to n+1

    • If init-links = 2 or 3 then also link to n + 2

    • If init-links = 3 then also link to n + 3

  • handle divide-by-zero error when running with init-links = 1

    • Divide by clustering-coefficient-of-lattice, divide by dum, protect dum from being zero

      • We might eventually want a better fix

Prisoner’s Dilemma Exercise

Let agents interact by playing a simple two-player game. We will combine this two-player game with learning: agents change what strategy as the gain experience with the game.

Save your model as <FirstLast>-pd.nlogo, where you replace <FirstLast> with your own name (so my program would be called AlanIsaac-pd.nlogo).

Implement this game

Write a NetLogo simulation in which agents play a simple two-player game like the Prisoner’s Dilemma. Each agent plays the game using some strategy. As a first pass, let each agent randomly select which strategy to use (during setup). (But see below.) After setup, the game proceeds in rounds. On each round every agent is paired up with exactly one other agent, and the agents play the game. All agent pairs play the same game, and each agent receives a resulting payoff. Agents total up their scores over time. Agents can observe the payoffs of other agents. After a few rounds, agents decide whether to change strategy.

You can do everything with patches, but it is also fine to use turtles.

Some details:

  1. Players must have a choice of at least three strategies. One strategy must be Tit-for-tat. The others may be any strategies you wish.

  2. The model must include some adaptation. A player’s choice of strategy should be based on observed payoffs (of some other agents).

  3. A single iteration of the simulation schedule should update all players.

  4. The GUI for your model should include a dynamic time-series chart diplaying the number of agents with each strategy.

  5. The GUI should allow the user to select the proportion of agents that start playing each strategy.

  6. If all the agents end up playing the same strategy, the simulation should stop.

  7. Add a game chooser to the GUI, with at least two games. One game must be the standard Prisoner’s Dilemma you have already been working with. The other may be any two-player game you wish.

Document

All you are going to hand in is a NetLogo program so make sure you:

  1. Include many comments in your code file. If I don’t understand what your code does, you won’t get full credit.

  2. Use the Information tab to describe your code. (Include an overview of the problem, describe the game strategies, and specify how agents decide which strategy to use.)

Experiment

Once your simulation model is coded, it is time to experiment. Try different initial proportions of strategies and different games. Do the agents all converge on the same strategy? If so, how many ticks does it takes? Since there is randomness in the simulation, you will need multiple replicates of each scenario (say 10) to get a sense of how they perform on average.

Describe the results of your experiments, including the statistics you collect, in the Info tab of your project.

ZIT Exercise

Based on an exercise by Mark McBride (https://github.com/memcbride/ZITrading).

  1. develop flow diagrams for the ZIT Gode-Sunder computational model

  2. Consider a ZIT implementation, such as the McBride (2008) online demo ZI Trading NetLogo Model (https://github.com/memcbride/ZITrading). McBride implements the zero-intelligence constrained (ZI-C) traders from Gode and Sunder: the ZI-C traders are constrained not to make any trade that will yield a negative profit. McBride sets the following defaults:

    • Number of Buyers: 50

    • Number of Sellers: 50

    • Maximum Buyer Value: 200

    • Maximum Seller Cost: 200

  3. does the McBride ZI Trading demo for ZI-C trading correctly implement the Gode-Sunder experiments? (With ZI-C traders.)

  4. Complete 5 runs of the ZI-C simulation with McBride’s default parameter values, setting T=2000.

    For each run:

    • predict the equilibrium price and quantity (based on the supply and demand curves) (If you use McBrides implementation, you can hover the cursor over the intersection of the demand and supply curves.)

    • record the following data: volume, average price, standard deviation of price, and market efficiency

  5. Experiment: increase the number of sellers to 100

  6. Record your initial initial simulation results in a table like the following. Make a similar table after changing the number of sellers.

    Obs Price Qty Vol Avg-Price Std-Dev Efficiency
    1
    2
    3
    4
    5
  7. Your write up should consider the following questions:

    1. Do the observed transaction prices and volumes approach the predicted values? How quickly?

    2. What level of market efficiency arises?

    3. How much dispersion is there in the transaction prices?

    4. How can a transaction price be above the demand curve or below the supply curve?

    5. How does changing the number of sellers affect efficiency? What about the number of buyers? Why?

Sugarscape Exercise: Introduction

Sugarscape Part I

  1. In the NetLogo Models Library, experiment with the Sugarscape 1 model. What part of the Epstein and Axtell book does this model correspond to? How accurately does it reproduce the EA setup? (Make a table of values from the code and from the book, with page numbers from the book.)

  2. How accurately does it reproduce the EA results? Why does average vision initially rise? Why does average metabolism initially fall? Why do the agents stop moving?

  3. Why do some agents die off no matter how low you set the population? Does this conflict with the notion that this environment has a "carrying capacity"?

  4. Examine the code. How exactly does the random-in-range "reporter" (i.e., function) work?

  5. Suggest at least one code improvement (in readability, speed, or elegance) that does not change the way the model functions. Note: if you change the code, be sure to work with a copy of the file, not with the original!

  6. Use BehaviorSpace to allow the initial population to vary from 200 to 1000 by increments of 100. As your output, measure the population after 100 ticks. (For this experiment, you may use a single replicate for each scenario.) Describe the relationship between initial population and final population. Criticize EA’s concept of “carrying capacity”.

Sugarscape Part II

  1. In the NetLogo Models Library, experiment with the Sugarscape 2 model. What part of the Epstein and Axtell book does this model correspond to? How accurately does it reproduce the EA setup and results? (Make a table of values from the code and from the book, with page numbers.)

  2. How exactly does it differ from the Sugarscape 1 model? What do we learn from this change? (I.e., how do the outcomes change, and why?)

  3. How does the "visualization" chooser work? (Be very detailed.)

Sugarscape Part III (NOT required)

  1. Copy the Model Library's Sugarscape 3 model into your homework directory as sugarscapeIII.nlogo.

  2. Add spice to the model by "rotating" the sugar distribution by 90 degrees. (You should end up with something like Figure IV-1.)

  3. Turn off replacement of turtles that die.

  4. Following EA chapter 4, implement the multi-commodity movement rule.

  5. Use BehaviorSpace to vary maximum vision and maximum metabolism. End each run after 100 iterations, and record the final population (carrying capacity).

  6. Fit a model of the carrying capacity to your variables. (E.g., use WL's LinearModelFit command.) Hint: you will find using Import to be easiest if you have only data in the file.

  7. Implement the agent trade rule T, and add a switch to turn trade on or off.

  8. Use BehaviorSpace to vary maximum vision, maximum metabolism, and your trade switch. End each run after 1000 iterations, and record the final population (carrying capacity).