Homework 5: Spatial Games : Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM

Similar documents
Homework 6: Spatial Games Due: 11:59pm on Friday, October 30

Objects, Object-Oriented Design, Methods /

Homework 5: Graphics Due: 11:59pm on Thursday, October 22

Arrays and Strings

Lecture 16: Object-oriented Programming

Programming Lab 1 (JS Hwk 3) Due Thursday, April 28

Repetition CSC 121 Fall 2014 Howard Rosenthal

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

go-tutorial Documentation Release latest

Making use of other Applications

Creating a new form with check boxes, drop-down list boxes, and text box fill-ins. Customizing each of the three form fields.

Last Time: Objects and Abstraction. If it walks like a circle, swims like a circle, and quacks like a circle...!

Tips from the experts: How to waste a lot of time on this assignment

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

If Statements, For Loops, Functions

Assignment #1 Simple C++

CS1 Lecture 12 Feb. 11, 2019

Tips from the experts: How to waste a lot of time on this assignment

More Examples /

The Big Python Guide

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Homework 7: Sudoku. Preliminaries. Overview

CALCULUS LABORATORY ACTIVITY: Numerical Integration, Part 1

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

CS 100 Spring Lecture Notes 3/8/05 Review for Exam 2

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Expressions and Casting

When you first start OneNote, it creates a sample notebook for you. You can use this notebook or quickly create your own.

JS Lab 1: (Due Thurs, April 27)

CMPSCI 187 / Spring 2015 Hanoi

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

1. The Normal Distribution, continued

Issue with Implementing PrimeSieve() in Go

Fireworks 3 Animation and Rollovers

CS 177 Recitation. Week 8 Methods

Macromedia - Fireworks TechNotes: How to create transparent Pop-up Menus

Fundamentals of Python: First Programs. Chapter 4: Strings (Indexing, Slicing, and Methods)

Note on homework for SAS date formats

Intro. Scheme Basics. scm> 5 5. scm>

Part 6b: The effect of scale on raster calculations mean local relief and slope

CS 170 Java Programming 1. Week 10: Loops and Arrays

High-Dimensional Connectivity and Cooperation

Functions & Variables !

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

HO-1: INTRODUCTION TO FIREWORKS

EMP105A-D - How to plan and build a basic form in Front Page.

Our second exam is Thursday, November 10. Note that it will not be possible to get all the homework submissions graded before the exam.

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Using Flash Animation Basics

Fundamentals: Expressions and Assignment

Reviewing all Topics this term

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Lab 12: Sampling and Interpolation

CheckBook Pro 2 Help

1 Getting started with Processing

Our second exam is Monday, April 3. Note that it will not be possible to get all the homework submissions graded before the exam.

CS 2316 Individual Homework 5 Joint Probability Out of 100 points

FOR Loops. Last Modified: 01 June / 1

Clip Art and Graphics. Inserting Clip Art. Inserting Other Graphics. Creating Your Own Shapes. Formatting the Shape

Lecture 10: Lindenmayer Systems

Loop structures and booleans

EXCEL + POWERPOINT. Analyzing, Visualizing, and Presenting Data-Rich Insights to Any Audience KNACK TRAINING

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Writing to and reading from files

Microsoft Office 365: Tips to Save You Time and Improve Productivity

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Pre Lab (Lab-1) Scrutinize Different Computer Components

CS1 Lecture 4 Jan. 23, 2019

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

CS1 Lecture 13 Feb. 13, 2019

Page design and working with frames

Integrated Study Units For Clicker 5

CS107, Lecture 2 Bits and Bytes; Integer Representations

The American University in Cairo. Academic Computing Services. Word prepared by. Soumaia Ahmed Al Ayyat

POWERPOINT BASICS: MICROSOFT OFFICE 2010

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

CS161: Introduction to Computer Science Homework Assignment 10 Due: Monday 11/28 by 11:59pm

CS2110 Assignment 2 Lists, Induction, Recursion and Parsing, Summer

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Assignment 7: Due Wednesday May 6 at 11pm

Lesson 2 page 1. ipad # 17 Font Size for Notepad (and other apps) Task: Program your default text to be smaller or larger for Notepad

EXCLAIMER CLOUD SIGNATURES FOR OFFICE 365. Deliver the most professional, intuitive and simple signature software designed for Office 365

CS1102: Macros and Recursion

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

CS 100: Computability, Python Lists

CMSC 201 Spring 2019 Lab 06 Lists

Page Replacement. (and other virtual memory policies) Kevin Webb Swarthmore College March 27, 2018

CPSC 217 Assignment 3

CS 2110 Fall Instructions. 1 Installing the code. Homework 4 Paint Program. 0.1 Grading, Partners, Academic Integrity, Help

Flash Image Enhancer Manual DMXzone.com Flash Image Enhancer Manual

CSE 142, Autumn 2018 Programming Assignment #9: Critters (20 points) Due Tuesday, December 4th, 9:00 PM

Text Input and Conditionals

Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9

CS108, Stanford Handout #3. HW1 CodeCamp

How to create a prototype

Transcription:

Homework 5: Spatial Games 02-201: Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM 1. Reading Read Ch. 8 and Ch. 9 of An Introduction to Programming in Go (on pointers and structs). 2. Set up The set up is the basically the same as for homework 4. 1. Inside of your existing go directory, create a directory called src. 2. Download the template from Piazza, and unzip it into the src directory. (Make sure that you also have the code.google.com directory from HW4.) You should now have a bunch of directories that look like this: It s fine if you also have other homework directories under src as well. 3. Set your GOPATH environment variable to the location of your go directory that you made above. On a Mac: export GOPATH=/Users/pcompeau/Desktop/go where you replace the directory name after the = with the location of the go directory you just made. On Windows use set GOPATH=C:\Users\pcompeau\Desktop\go 1

3. Reading data from files 3.1 Opening and closing files If you want to read the data from a file you must open it so that it is available for use. To do that in Go, you use the os.open function, which returns a variable that represents the file and whether there was an error. For example: var filename = "field.txt" file, err := os.open(filename) if err!= nil { fmt.println("error: something went wrong opening the file.") fmt.println("probably you gave the wrong filename.") To do this, you must import "os". Once you are done with a file, you should close it using the Close() function, which is called using the syntax: file.close() if your file variable was named file. 3.2 Reading data from files Once you have a file open, there are many ways to read data from it. We will see the most common, which is to use something called a Scanner. A scanner reads through the file, line by line. 1. You create a Scanner using the bufio.newscanner function: scanner := bufio.newscanner(file) where file is a file variable that you have opened (not a filename). import "bufio" 2. Now you can loop through the lines of a file using a for loop of the following form: for scanner.scan() { fmt.println("the current line is:", scanner.text()) To do this, you must The scanner.scan() function tries to read the next line and returns false if it could not. Inside the for loop, you can get the current line as a string using scanner.text() as above. 3. Once you re done reading the file, it s good practice to check to see if there was an error during the file reading. You do this by checking whether scanner.err() returns something that isn t nil: if scanner.err()!= nil { fmt.println("error: there was a problem reading the file" os.exit(1) 2

3.3 Another example reading lines This code reads the lines in a file and puts them into a slice of strings. func readfile(filename string) []string { // open the file and make sure all went well in, err := os.open(filename) if err!= nil { fmt.println("error: couldn t open the file") os.exit(1) // create the variable to hold the lines var lines []string = make([]string, 0) // for every line in the file scanner := bufio.newscanner(in) for scanner.scan() { // append it to the lines slice lines = append(lines, scanner.text()) // check that all went ok if scanner.err()!= nil { fmt.println("sorry: there was some kind of error during the file reading") os.exit(1) // close the file and return the lines in.close() return lines 3.4 Parsing a string that contains data The code above to read a file reads a file line by line, and each line is a string. Often you may have several data items encoded on the same line. For example, suppose the first line of your file contains the width, height, and length of a cube: 10.7 30.2 15.8 We would like to extract these 3 floating point data items from the line. Again there are several ways to do this. We ll see two. The First Method: Using Split. The first uses strings.split function, which takes a single string, plus a string that says what substring separates the item. For example, if your string contains 3

var line string = "10.7,30.2,15.8" You could split it into 3 strings using: var items []string = strings.split(line, ",") Now, items will contain the 3 data items: items[0] == "10.7" items[1] == "30.2" items[2] == "15.8" The things in items are still strings. They are now in a format similar to what you have seen with os.args. You must convert them to float64, int, etc. as appropriate. The Second Method: Using Sscanf. The second method works if you have a small number of data items on the line. It uses a function with a strange name: fmt.sscanf. This stands for scan a S tring using a f format. You use it as follows: var line string = "10.7 30.2 15.8" var f1, f2, f3 float64 fmt.sscanf(line, "%f %f %f", &f1, &f2, &f3) This call uses some strange syntax. We can break it down: line is the string that contains the data you want to parse. "%v %v %v" is the format string that says how the data in the first parameter is formatted. Each item %v means there will be a some data item here, so this format string means that there will be 3 pieces of data separated by spaces. Sscanf will figure out what type of data the value is based on the next parameters (described below). the &f1, &f2, &f3 parameters say where to store each of the floating point numbers in the format string. This & syntax is new. Its purpose here is to allow the function Sscanf to change the values of the f1,f2,f3 variables. We will see this more in the future. Since f1,f2,f3 are float64s, Sscanf will read floats for each of them. The format string can be very complex and can parse things besides floats. Some examples: 1. This will read two integers separated by a comma followed by a float separated by spaces: var c, d int var f float64 var line string = "101,31 2.7" fmt.sscanf(line, "%v,%v %v", &c, &d, &f) 2. This will scan two string separated by spaces: line := "Dave Susan" var name1, name2 string fmt.sscanf(line, "%v %v", &name1, &name2) The nice thing about the Sscanf method is that it handles both the parsing and conversion for you. The downside is that the number of data items must be small and known ahead of time. 4

Sscanf is part of a family of functions that read and print data: fmt.scanf, fmt.sprintf, fmt.printf and others that all work the same way. You can read more about them here: http: //golang.org/pkg/fmt/. This is the reason for the name fmt that we ve seen for a long time now: most of the functions in this package do formatted input and output in the style of Sscanf. 5

4. Assignment 4.1 The Prisoner s Dilemma The Prisoner s Dilemma refers to the following situation: Two criminals who committed a crime together are being interrogated by the police in separate rooms. Each prisoner has a choice to either cooperate with their partner in crime and stay silent, or to be a defector and rat on their partner to gain favor with the police. The outcome of the interrogation depends on the choices made by the two prisoners: If both prisoners cooperate with each other and stay silent, then each prisoner only goes to prison for a short time (because there is little evidence against them). If both prisoners defect (i.e., rat on each other), then they both get long sentences. If one prisoner stays silent in an attempt to cooperate, but the other defects, then the one who testifies gets a big reward: immunity from prosecution. On the other hand, the person who stayed silent gets a long sentence. We can model these outcomes in the following way: Each prisoner either adopts a strategy of cooperation ( C ) with their partner or defection ( D ) from their partner. Prisoner 1 Prisoner 2 Outcome C C both get 1 point D D both get 0 points D C prisoner 1 gets b points and prisoner 2 gets 0 points C D prisoner 1 gets 0 points and prisoner 2 gets b points That is: 0 points for a long sentence, 1 point for a short sentence, and b points for immunity. Here b > 1 is a parameter that says how much reward a prisoner gets for being the only defector. 1 z The Prisoner s Dilemma is widely studied as a model for real policy situations. Pollution is a good example: if no one pollutes (everyone adopts a C strategy), everyone does well. If everyone pollutes (everyone adopts a D strategy), we all lose. But if you live in the only country that pollutes (the only D country), then you get the economic benefit without the global cost (a big reward for you). 4.2 Spatial Games This assignment adds a twist: we assume that there are n 2 prisoners arranged in cells in a prison in an n-by-n grid. Every prisoner is either a C-prisoner (cooperator with their fellow prisoners) or a D-prisoner (defector who snitches to the police). The D-prisoners testify against the prisoners in the cells that neighbor theirs, and the C-prisoners always stay silent. The reward to a prisoner is the sum of the points according to the scheme above. For example, consider this C-cell and its neighbors: 1 In practice, the outcomes should be negative (a prison sentence is rarely seen as a reward), but we have positive outcomes here in order to simplify the problem. 6

D D C D C D C D C The center cell plays 8 prisoner dilemma games, and gets a total of 3 points: 0 points for interacting with their D neighbors, and 3 points for interacting with their C neighbors. 2 Another example: D D C C D D C D C The center cell gets 4b points: 0 points for interacting with each of its D neighbors, and b points for interacting with each of its C neighbors. After calculating the score, each prisoner gets to change strategies: it adopts the strategy (C or D) of the prisoner in its neighboring cells that scored the most points. After each round, the points are reset to 0. In summary, the overall procedure is: 1. prisoners are either C or D prisoners. 2. prisoners get points according to their neighbors using the point system in the table above. 3. after all the scores have been calculated, the prisoners adopt new strategies (either C or D) according to the best strategy in their neighborhood in the previous round. 4. this procedure is repeated for a given number of steps. These spatial games were first explored in: Nowak and May, Evolutionary games and spatial chaos, Nature 359:826 829 (1992). 2 The original paper on these spatial games includes interactions with oneself. This doesn t affect the qualitative behavior of the system but is less intuitive. 7

4.3 What to do In this assignment, you will write a program to simulate this group of prisoners arranged in a grid. You will write a program that can be run with the following command line:./spatial FILENAME b STEPS where FILENAME gives the file that contains the initial assignments of C or D strategies (in the format described below), STEPS is an integer that indicates how many steps you should run your program for, and b is the reward that a D cell gets against a C cell as described above. The main tasks are to write functions to (a) read in the initial field, and (b) update the scores and strategies according to the rules above. As a result, you should produce two things: 1. An image in PNG format corresponding to the final version of the board after STEPS steps. 2. An animated GIF displaying all STEPS steps of running the program. 4.4 How to draw an animated GIF We can generate a single image from a canvas object c by calling the field c.img, which is an image.image type. By placing each image generated from a series of Prisoner s Dilemma boards into a []image.image slice, we can then generate an animated GIF. In the code template, you will find a file called gifhelper.go. This file contains the function Process that takes a slice []image.image and a file name (such as "prisoners") as a string, and generates a GIF with this file name from the image slice. (It needs the functions in the gogif folder in order to run.) 4.5 Format of the initial field file The FILENAME command line parameter will be the name of a file that contains the field dimensions and the initial type for each of the cells. The first line of the file will contain the number of rows and columns, e.g.: 10 15 means there are 10 rows, each having 15 columns. Each subsequent line is a string of Cs and Ds of length equal to the number of columns. There will be a line for each row. Together, these rows give the initial strategies for each cell. For example: CCCCCCCCCCCCCCC CCCCCCCCCCCDCCC CCCCCCCCCCCCCCC CCCCDCCCDDCCCCC CCCCCCCCDDCCCCC CCCCCCCCCCCCCCC CCCCCCCCCCDCCCC CCCCDCCCCCCCCCC 8

CCCCCDCCCCDCCCC CCCCCDCCCCCCCCC The assignment contains several example files: f99.txt, f100.txt, rand200-10.txt, rand200-50.txt, and smallfield.txt. 4.6 Tips on how to start First, install the template from Piazza. Before you write any code to make the field evolve, compile and test your program by reading the starting field f100.txt using 0 steps of evolution using the command:./spatial f99.txt 1.65 0 This will ensure that you are reading the field and writing the picture correctly. The field should look like this: before you do any evolution steps. Next, write functions for the field to evolve. Now test your program for more steps. If you run the command./spatial f99.txt 1.65 30 You should get the picture: 9

4.7 Explore your program 1. If you execute the command:./spatial f99.txt 1.65 80 You should get a picture that looks like: Try lots of other numbers of steps and see how the pattern changes. 2. Compare these four runs./spatial f99.txt 1.59 80./spatial f99.txt 1.6 80./spatial f99.txt 1.65 80./spatial f99.txt 1.7 80 What is going on here? 10

3. The initial field f99.txt is a single D cell in the center of a 99-by-99 field of C cells. The initial field f100.txt is the same, except the field dimensions are 100 by 100. If you run You get:./spatial f100.txt 1.65 80 Notice the result is not symmetric, unlike what you get with f99.txt: Why do you think that this is the case? 4. Compare these two runs:./spatial rand200-10.txt 1.55 0./spatial rand200-10.txt 1.55 200 You should get: 11

4.8 Learning outcomes After completing this assignment, you should have: learned how to read data from a file, understood how to use struct types, learned about the Prisoner s dilemma and spatial games, gained additional practice drawing images. 4.9 If you re interested... Implement the color scheme for drawing the field that is described in the Nowak and May paper cited above (where there are four colors depending on the current and previous state of a cell). 12