first courses workshop day 4 mark guzdial college of computing georgia institute of technology...

341
First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology [email protected] http://www.cc.gatech.edu/~mark.guzdial http://www.georgiacomputes.org

Upload: brooke-williams

Post on 03-Jan-2016

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

First Courses WorkshopDay 4

Mark Guzdial College of Computing

Georgia Institute of [email protected]

http://www.cc.gatech.edu/~mark.guzdialhttp://www.georgiacomputes.org

Page 2: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Workshop Plan-Day 4 9-10:00 am: Introducing data structures (in Java) in a Media

Computation approach MIDI notes, then linked lists of MIDI.

10:00-10:15: Break 10:15-11:15: Linked lists and trees of pictures

A "scene graph" as a first tree. 11:15-12:15: Simulations.

Using Turtles from the Wednesday lecture Creating the wildebeests and villagers: Making movies from simulations

12:15-1:15: Lunch 1:15-2:30: Tackling a homework assignment in Media Computation

with Java. Creating linked list music or Making a movie with sound or Modifying a Simulation.

2:30-2:45: Break 2:45-3:15: Introducing Computing in an Engineering Context with

MATLAB 3:15-4:30: Tackling a homework assignment in MATLAB

Engineering Computing: Analyzing live Internet data

Page 3: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Multimedia CS2 in Java

Driving question: “How did the wildebeests stampede in The Lion King?”

Spring 2005: 31 students, 75% female, 91% success rate.

Page 4: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Connecting to the WildebeestsIt’s all about data structures

Page 5: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus

Introduction to Java and Media Computation Manipulating turtles, images, MIDI, sampled sounds. Insertion and deletion (with shifting) of sampled

sounds (arrays).

Structuring Music Goal: A structure for flexible music composition Put MIDI phrases into linked list nodes.

Use Weave and Repeat to create repeating motifs as found in Western Music

At very end, create a two-branched list to start on trees.

CanonSwan

Bells Fur Elise

Page 6: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

HW2: Create a collage, but must use turtles

Page 7: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (Continued)

Structuring Images Using linearity in linked list to

represent ordering (e.g., left to right) Using linearity in linked list to

represent layering (as in PowerPoint) Mixing positioned and layered in one

structure, using abstract super classes.

Structuring a scene in terms of branches—introducing a scene graph (first tree)

(We’ll see these slides as an example later.)

Page 8: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (Cont’d)

Structuring Sound Collecting sampled

sounds into linked lists and trees, as with images.

But all traversals are recursive.

Use different traversals of same tree to generate different sounds.

Replace a sound in-place

Original

Scale the children

Scale the next

Page 9: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (cont’d)

Generalizing lists and trees Create an abstract class

“Linked List Node” (LLNode) on top of the sound and image class hierarchies

Make all image and sound examples work the same

abstract LLNode

Knows next

Knows how to do all basic list operations

Page 10: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (Cont’d)

GUIs as trees We introduce

construction of a Swing frame as construction of a tree.

Different layout managers are then different renderers of the same tree.

Traditional (binary) trees as a specialization Can we make trees that

are faster to search?

JFrame

JPanel

JLabel “This is panel1!”

JPanel

JButton “Make a sound”

JButton “Make a picture”

Page 11: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (cont’d)

Lists that Loop Introduce circular linked lists as a way of create

Mario-Brothers’ style cel animations. Introduce trees that loop as a way of introducing

graphs.

gal1-rightface.jpg gal1-

right2.jpg

gal1-right1.jpg

gal1-rightface.jpg

Page 12: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (cont’d)

Introducing Simulations Introduce continuous and discrete event simulations, and

Normal and uniform probability distributions We do wolves and deer,

disease propagation,political influence.

Create a set of classes for simulation, then re-write our simulations for those classes.

Writing results to a file for later analysis

Finally, Making the Wildebeests and Villagers Mapping from positions of our turtles to an animation frame. Creating an animation from a simulation.

Page 13: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

HW7: Simulate European emigration to America Students are

required to try several different scenarios, aiming for historical accuracy.

Counts of Europeans, Americans, and in-transit per year are written to a file for graphing in Excel

Page 14: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus (cont’d)

Introduction to Discrete Event Simulations Create a discrete event simulation of trucks, factories,

salespeople, and markets. Use turtles to create an animated display. Now, the real focus is the simulation, and the

animation is just a mapping from the simulation. Animation becomes yet another medium in which we can

review results, like data in an Excel spreadsheet, music, or sound.

Page 15: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

A selection of data structures

First, structuring music: Notes, Phrases, Parts, and Scores as a nice example

of objects and modeling.

Then linked lists of images Is it about layering (as in Photoshop) or positioning

(as in Lord of the Rings)?

Then trees of images A Scene Graph

Page 16: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Telling DrJava where to find files

Page 17: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Parts of DrJava

Text of your class file (.java)

Where you interact with Java

List of class files that you have open

Page 18: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

An example with Music

> import jm.util.*;

> import jm.music.data.*;

> Note n1;

> n1 = new Note(60,0.5);

> // Create an eighth note at C octave 4

• JMusic pieces need to be imported first to use them.

Page 19: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

An example with Music

> import jm.util.*;

> import jm.music.data.*;

> Note n1;

> n1 = new Note(60,0.5);

> // Create an eighth note at C octave 4

• Declare a Note variable.

Page 20: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

An example with Music

> import jm.util.*;

> import jm.music.data.*;

> Note n1;

> n1 = new Note(60,0.5);

> // Create an eighth note at C octave 4

• Note instances have nothing to do with filenames.

• To create a note, you need to know which note, and a duration

Starting a line with // creates a comment—ignored by Java

Page 21: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

MIDI notes

Page 22: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Making more notes> Note n2=new Note(64,0.5);> View.notate(n1);Error: No 'notate' method in

'jm.util.View' with arguments: (jm.music.data.Note)

> Phrase phr = new Phrase();> phr.addNote(n1);> phr.addNote(n2);> View.notate(phr);-- Constructing MIDI file from'Untitled

Score'... Playing with JavaSound ... Completed MIDI playback --------

Page 23: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What’s going on here?

> Note n2=new Note(64,0.5);> View.notate(n1);Error: No 'notate' method in 'jm.util.View' with arguments: (jm.music.data.Note)

• We’ll make another Note (at E4, another eighth note)

• There is an object named View that knows how to notate parts of music, but not an individual note.

Page 24: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What’s going on here?

> Phrase phr = new Phrase();> phr.addNote(n1);> phr.addNote(n2);> View.notate(phr);-- Constructing MIDI file from'Untitled Score'... Playing with JavaSound ... Completed MIDI playback --------

• We’ll create a new Phrase instance and make a variable phr to refer to it. (phr has to be declared to be a Phrase.)

• Phrase instances know how to addNote notes to them. These are methods that take an argument—a Note instance.

• The View object does know how to notate an input Phrase instance. It generates this cool window where you see the notes and can play them (or save them as MIDI.)

Page 25: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Playing a different Phrase

> Phrase nuphr = new Phrase(0.0,JMC.FLUTE);

> nuphr.addNote(n2);

> nuphr.addNote(n1);

> View.notate(nuphr);

• We can specify when a phrase starts and with what instrument.

• We can add notes (even the same notes!) in different orders

Page 26: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Modeling Music

The JMusic package is really modeling music. Notes have tones and durations. Musical Phrases are collections of notes. We can play (and View) a musical phrase.

A phrase doesn’t have to start when other phrases do, and a phrase can have its own instrument.

Page 27: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Objects know things and can do things

What instances of this class know

What instances of this class can do

Note A musical note and a duration

<Nothing we’ve seen yet>

Phrase The notes in the phrase

addNote(aNote)

Page 28: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

AmazingGrace

import jm.music.data.*;import jm.JMC;import jm.util.*;import jm.music.tools.*; public class AmazingGraceSong { private Score myScore = new Score("Amazing Grace"); public void fillMeUp(){ myScore.setTimeSignature(3,4); double[] phrase1data = {JMC.G4, JMC.QN, JMC.C5, JMC.HN, JMC.E5,JMC.EN, JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.HN,JMC.A4,JMC.QN, JMC.G4,JMC.HN,JMC.G4,JMC.EN,JMC.A4,JMC.EN, JMC.C5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.EN,JMC.E5,JMC.EN, JMC.G5,JMC.DHN}; double[] phrase2data = {JMC.G5,JMC.HN,JMC.E5,JMC.EN,JMC.G5,JMC.EN, JMC.G5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.HN,JMC.A4,JMC.QN, JMC.G4,JMC.HN,JMC.G4,JMC.EN,JMC.A4,JMC.EN, JMC.C5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.DHN }; Phrase myPhrase = new Phrase(); myPhrase.addNoteList(phrase1data); myPhrase.addNoteList(phrase2data); // create a new part and add the phrase to it Part aPart = new Part("Parts", JMC.FLUTE, 1); aPart.addPhrase(myPhrase); // add the part to the score myScore.addPart(aPart); }; public void showMe(){ View.notate(myScore); }; }

> AmazingGraceSong song1 = new AmazingGraceSong();> song1.fillMeUp();> song1.showMe();

Page 29: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Imports and some private data

import jm.music.data.*;import jm.JMC;import jm.util.*;import jm.music.tools.*; public class AmazingGraceSong { private Score myScore = new Score("Amazing Grace"); myScore is private instance data

Page 30: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Filling theScore

public void fillMeUp(){ myScore.setTimeSignature(3,4); double[] phrase1data = {JMC.G4, JMC.QN, JMC.C5, JMC.HN, JMC.E5,JMC.EN, JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.HN,JMC.A4,JMC.QN, JMC.G4,JMC.HN,JMC.G4,JMC.EN,JMC.A4,JMC.EN, JMC.C5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.EN,JMC.E5,JMC.EN, JMC.G5,JMC.DHN}; double[] phrase2data = {JMC.G5,JMC.HN,JMC.E5,JMC.EN,JMC.G5,JMC.EN, JMC.G5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.HN,JMC.A4,JMC.QN, JMC.G4,JMC.HN,JMC.G4,JMC.EN,JMC.A4,JMC.EN, JMC.C5,JMC.HN,JMC.E5,JMC.EN,JMC.C5,JMC.EN, JMC.E5,JMC.HN,JMC.D5,JMC.QN, JMC.C5,JMC.DHN }; Phrase myPhrase = new Phrase(); myPhrase.addNoteList(phrase1data); myPhrase.addNoteList(phrase2data); // create a new part and add the phrase to it Part aPart = new Part("Parts", JMC.FLUTE, 1); aPart.addPhrase(myPhrase); // add the part to the score myScore.addPart(aPart); };

Each array is note, duration, note, duration, note, duration, etc.

I broke it roughly into halves.

Page 31: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Showing the Score

public void showMe(){

View.notate(myScore);

};

Page 32: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Part: Instrument &

Phrase: startingTime &

The Organization of JMusic Objects

Phrase: startingTime &

Note (pitch,duration)

Note (pitch,duration)

Note (pitch,duration)

Note (pitch,duration)

Note (pitch,duration)

Part: Instrument &

Score: timeSignature, tempo, &

Page 33: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Thought Experiment

How are they doing that? How can there be any number of Notes in a

Phrase, Phrases in a Part, and Parts in a Score? (Hint: They ain’t usin’ arrays!)

Page 34: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How do we explore composition here? We want to quickly and easily throw together

notes in different groupings and see how they sound.

The current JMusic structure models music. Let’s try to create a structure that models thinking

about music as bunches of riffs/SongElements that we want to combine in different ways.

Then comes notes in arrays,linked lists of segments of AmazingGrace,then real and flexible linked lists…

Page 35: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Version 3: SongNode and SongPhrase SongNode instances will hold pieces (phrases)

from SongPhrase. SongNode instances will be the nodes in the

linked list Each one will know its next.

Ordering will encode the order in the Part. Each one will get appended after the last.

Page 36: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using SongNode and SongPhrase

Welcome to DrJava.> import jm.JMC;> SongNode node1 = new SongNode();> node1.setPhrase(SongPhrase.riff1());> SongNode node2 = new SongNode();> node2.setPhrase(SongPhrase.riff2());> SongNode node3 = new SongNode();> node3.setPhrase(SongPhrase.riff1());> node1.setNext(node2);> node2.setNext(node3);> node1.showFromMeOn(JMC.SAX);

Page 37: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

All three SongNodes in one Part

Page 38: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How to think about it

node1

myPhrase: riff1

next: node2

node2

myPhrase: riff2

next: node3

node3

myPhrase: riff1

next: null

Page 39: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Declarations for SongNode

import jm.music.data.*;import jm.JMC;import jm.util.*;import jm.music.tools.*; public class SongNode { /** * the next SongNode in the list */ private SongNode next; /** * the Phrase containing the notes and durations associated with this node */ private Phrase myPhrase;

SongNode’s know their Phrase and the next node in the list

Page 40: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Constructor for SongNode

/**

* When we make a new element, the next part is empty, and ours is a blank new part

*/

public SongNode(){

this.next = null;

this.myPhrase = new Phrase();

}

Page 41: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Setting the phrase

/**

* setPhrase takes a Phrase and makes it the one for this node

* @param thisPhrase the phrase for this node

*/

public void setPhrase(Phrase thisPhrase){

this.myPhrase = thisPhrase;

}

Page 42: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Linked list methods /** * Creates a link between the current node and the input node * @param nextOne the node to link to */ public void setNext(SongNode nextOne){ this.next = nextOne; } /** * Provides public access to the next node. * @return a SongNode instance (or null) */ public SongNode next(){ return this.next; }

Page 43: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

insertAfter /** * Insert the input SongNode AFTER this node, * and make whatever node comes NEXT become the next of the input node. * @param nextOne SongNode to insert after this one */ public void insertAfter(SongNode nextOne) { SongNode oldNext = this.next(); // Save its next this.setNext(nextOne); // Insert the copy nextOne.setNext(oldNext); // Make the copy point on to the rest

}

Page 44: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using and tracing insertAfter()

> SongNode nodeA = new SongNode();> SongNode nodeB = new SongNode();> nodeA.setNext(nodeB);> SongNode nodeC = new SongNode()> nodeA.insertAfter(nodeC);

public void insertAfter(SongNode nextOne) { SongNode oldNext = this.next(); // Save its next this.setNext(nextOne); // Insert the copy nextOne.setNext(oldNext); // Make the copy point on to the rest

}

Page 45: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Traversing the list

/** * Collect all the notes from this node on * in an part (then a score) and open it up for viewing. * @param instrument MIDI instrument (program) to be used in playing this list */ public void showFromMeOn(int instrument){ // Make the Score that we'll assemble the elements into // We'll set it up with a default time signature and tempo we like // (Should probably make it possible to change these -- maybe with inputs?) Score myScore = new Score("My Song"); myScore.setTimeSignature(3,4); myScore.setTempo(120.0); // Make the Part that we'll assemble things into Part myPart = new Part(instrument); // Make a new Phrase that will contain the notes from all the phrases Phrase collector = new Phrase(); // Start from this element (this) SongNode current = this; // While we're not through... while (current != null) { collector.addNoteList(current.getNotes()); // Now, move on to the next element current = current.next(); }; // Now, construct the part and the score. myPart.addPhrase(collector); myScore.addPart(myPart); // At the end, let's see it! View.notate(myScore);

}

Page 46: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Core of the Traversal// Make a new Phrase that will contain the notes from all the phrases

Phrase collector = new Phrase(); // Start from this element (this) SongNode current = this; // While we're not through... while (current != null) { collector.addNoteList(current.getNotes()); // Now, move on to the next element current = current.next(); };

Page 47: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Then return what you collected

// Now, construct the part and the score.

myPart.addPhrase(collector);

myScore.addPart(myPart);

// At the end, let's see it!

View.notate(myScore);

}

Page 48: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

getNotes() just pulls the notes back out

/** * Accessor for the notes inside the node's phrase * @return array of notes and durations inside the phrase */ private Note [] getNotes(){ return this.myPhrase.getNoteArray(); }

Page 49: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

SongPhrase

SongPhrase is a collection of static methods. We don’t ever need an instance of SongPhrase. Instead, we use it to store methods that return

phrases. It’s not very object-oriented, but it’s useful here.

Page 50: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

SongPhrase.riff1()import jm.music.data.*;import jm.JMC;import jm.util.*;import jm.music.tools.*;

public class SongPhrase { //Little Riff1 static public Phrase riff1() { double[] phrasedata = {JMC.G3,JMC.EN,JMC.B3,JMC.EN,JMC.C4,JMC.EN,JMC.D4,JMC.EN}; Phrase myPhrase = new Phrase(); myPhrase.addNoteList(phrasedata); return myPhrase;

Page 51: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

SongPhrase.riff2()

//Little Riff2 static public Phrase riff2() { double[] phrasedata =

{JMC.D4,JMC.EN,JMC.C4,JMC.EN,JMC.E4,JMC.EN,JMC.G4,JMC.EN};

Phrase myPhrase = new Phrase(); myPhrase.addNoteList(phrasedata); return myPhrase; }

Page 52: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Computing a phrase

//Larger Riff1 static public Phrase pattern1() { double[] riff1data = {JMC.G3,JMC.EN,JMC.B3,JMC.EN,JMC.C4,JMC.EN,JMC.D4,JMC.EN}; double[] riff2data = {JMC.D4,JMC.EN,JMC.C4,JMC.EN,JMC.E4,JMC.EN,JMC.G4,JMC.EN};

Phrase myPhrase = new Phrase(); // 3 of riff1, 1 of riff2, and repeat all of it 3 times for (int counter1 = 1; counter1 <= 3; counter1++) {for (int counter2 = 1; counter2 <= 3; counter2++) myPhrase.addNoteList(riff1data); myPhrase.addNoteList(riff2data); }; return myPhrase; }

Page 53: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

As long as it’s a phrase…

The way that we use SongNote and SongPhrase, any method that returns a phrase is perfectly valid SongPhrase method.

Page 54: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

10 Random Notes(Could be less random…) /* * 10 random notes **/ static public Phrase random() { Phrase ranPhrase = new Phrase(); Note n = null; for (int i=0; i < 10; i++) { n = new Note((int) (128*Math.random()),0.1); ranPhrase.addNote(n); } return ranPhrase; }

Page 55: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

10 Slightly Less Random Notes /* * 10 random notes above middle C **/ static public Phrase randomAboveC() { Phrase ranPhrase = new Phrase(); Note n = null; for (int i=0; i < 10; i++) { n = new Note((int) (60+(5*Math.random())),0.25); ranPhrase.addNote(n); } return ranPhrase; }

Page 56: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Going beyond connecting nodes

So far, we’ve just created nodes and connected them up.

What else can we do? Well, music is about repetition and interleaving

of themes. Let’s create those abilities for SongNodes.

Page 57: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Repeating a Phrase

Welcome to DrJava.

> SongNode node = new SongNode();

> node.setPhrase(SongPhrase.randomAboveC());

> SongNode node1 = new SongNode();

> node1.setPhrase(SongPhrase.riff1());

> node.repeatNext(node1,10);

> import jm.JMC;

> node.showFromMeOn(JMC.PIANO);

Page 58: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What it looks like

node node1 node1 node1 …

Page 59: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Repeating /** * Repeat the input phrase for the number of times

specified. * It always appends to the current node, NOT insert. * @param nextOne node to be copied in to list * @param count number of times to copy it in. */ public void repeatNext(SongNode nextOne,int count) { SongNode current = this; // Start from here SongNode copy; // Where we keep the current copy for (int i=1; i <= count; i++) { copy = nextOne.copyNode(); // Make a copy current.setNext(copy); // Set as next current = copy; // Now append to copy } }

Note! What happens to this’s next? How would you create a looong repeat chain of several types of phrases with this?

Page 60: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Really useful: Do this with people as nodes! We give people pieces of paper with “notes” on

them. Nodes point to their “next”

Page 61: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Here’s making a copy

/** * copyNode returns a copy of this node * @return another song node with the same notes */ public SongNode copyNode(){ SongNode returnMe = new SongNode(); returnMe.setPhrase(this.getPhrase()); return returnMe; }

Page 62: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 1:public void repeatNext(SongNode nextOne,int count) { SongNode current = this; // Start from here SongNode copy; // Where we keep the current copy

node

phrase: 10 random notes

next: null

current

node1

phrase: riff1()

next: null

nextOne

Page 63: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 2:copy = nextOne.copyNode(); // Make a copy

node

phrase: 10 random notes

next: null

current

node1

phrase: riff1()

next: null

phrase: riff1()

next: null

copy nextOne

Page 64: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 3:current.setNext(copy); // Set as next

node

phrase: 10 random notes

next:

current

node1

phrase: riff1()

next: null

phrase: riff1()

next: null

copy nextOne

Page 65: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 4: current = copy; // Now append to copy

node

phrase: 10 random notes

next:

current

node1

phrase: riff1()

next: null

phrase: riff1()

next: null

copy nextOne

Page 66: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 5 & 6: copy = nextOne.copyNode(); // Make a copy current.setNext(copy); // Set as next

node

phrase: 10 random notes

next:

current

node1

phrase: riff1()

next: null

phrase: riff1()

next:

copy

phrase: riff1()

next: null

nextOne

Page 67: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Step 7 (and so on): current = copy; // Now append to copy

node

phrase: 10 random notes

next:

current

node1

phrase: riff1()

next: null

phrase: riff1()

next:

copy

phrase: riff1()

next: null

nextOne

Page 68: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What happens if the node already points to something? Consider repeatNext and how it inserts:

It simply sets the next value. What if the node already had a next? repeatNext will erase whatever used to come

next. How can we fix it?

Page 69: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

repeatNextInserting

/** * Repeat the input phrase for the number of times specified. * But do an insertion, to save the rest of the list. * @param nextOne node to be copied into the list * @param count number of times to copy it in. **/ public void repeatNextInserting(SongNode nextOne, int count){ SongNode current = this; // Start from here SongNode copy; // Where we keep the current copy for (int i=1; i <= count; i++) { copy = nextOne.copyNode(); // Make a copy current.insertAfter(copy); // INSERT after current current = copy; // Now append to copy } }

Page 70: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Weaving /** * Weave the input phrase count times every skipAmount nodes * @param nextOne node to be copied into the list * @param count how many times to copy * @param skipAmount how many nodes to skip per weave */ public void weave(SongNode nextOne, int count, int skipAmount) { SongNode current = this; // Start from here SongNode copy; // Where we keep the one to be weaved in SongNode oldNext; // Need this to insert properly int skipped; // Number skipped currently for (int i=1; i <= count; i++) { copy = nextOne.copyNode(); // Make a copy //Skip skipAmount nodes skipped = 1; while ((current.next() != null) && (skipped < skipAmount)) { current = current.next(); skipped++; }; oldNext = current.next(); // Save its next current.insertAfter(copy); // Insert the copy after this one current = oldNext; // Continue on with the rest if (current.next() == null) // Did we actually get to the end early? break; // Leave the loop

} }

Should we break before the last insert (when we get to the end) or after?

Page 71: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Creating a node to weave

> SongNode node2 = new SongNode();> node2.setPhrase(SongPhrase.riff2());> node2.showFromMeOn(JMC.PIANO);

Page 72: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Doing a weave

> node.weave(node2,4,2);

> node.showFromMeOn(JMC.PIANO);

Page 73: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Weave Results

Before:

After

Page 74: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Walking the Weave

public void weave(SongNode nextOne, int count, int skipAmount)

{ SongNode current = this; // Start from here SongNode copy; // Where we keep the one to be weaved in SongNode oldNext; // Need this to insert properly int skipped; // Number skipped currently

Page 75: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Skip forwardfor (int i=1; i <= count; i++) { copy = nextOne.copyNode(); // Make a copy //Skip skipAmount nodes skipped = 1; while ((current.next() != null) && (skipped < skipAmount)) { current = current.next(); skipped++; };

Page 76: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Then do an insert

if (current.next() == null) // Did we actually get to the end early? break; // Leave the loop oldNext = current.next(); // Save its next current.insertAfter(copy); // Insert the copy after this one current = oldNext; // Continue on with the rest }

Page 77: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Shifting to Images

Now that we’ve introduced linked lists with MIDI, we shift to images. Briefly, two kinds of linked lists. Then scene graphs

Page 78: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Building a Scene

Computer graphics professionals work at two levels: They define individual characters and effects on

characters in terms of pixels. But then most of their work is in terms of the scene:

Combinations of images (characters, effects on characters).

To describe scenes, they often use linked lists and trees in order to assemble the pieces.

Page 79: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

> FileChooser.setMediaPath("D:/cs1316/MediaSources/");> PositionedSceneElement tree1 = new PositionedSceneElement(new

Picture(FileChooser.getMediaPath("tree-blue.jpg")));> PositionedSceneElement tree2 = new PositionedSceneElement(new

Picture(FileChooser.getMediaPath("tree-blue.jpg")));> PositionedSceneElement tree3 = new PositionedSceneElement(new

Picture(FileChooser.getMediaPath("tree-blue.jpg")));> PositionedSceneElement doggy = new PositionedSceneElement(new

Picture(FileChooser.getMediaPath("dog-blue.jpg")));> PositionedSceneElement house = new PositionedSceneElement(new

Picture(FileChooser.getMediaPath("house-blue.jpg")));> Picture bg = new Picture(FileChooser.getMediaPath("jungle.jpg"));> tree1.setNext(tree2); tree2.setNext(tree3); tree3.setNext(doggy);

doggy.setNext(house);> tree1.drawFromMeOn(bg);> bg.show();

Version 1: PositionedSceneElement

In this example, using chromakey to compose..just for the fun of it.

Page 80: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What this looks like:

Page 81: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Slightly different ordering:Put the doggy between tree2 and tree3> tree3.setNext(house); tree2.setNext(doggy);

doggy.setNext(tree3);> bg = new

Picture(FileChooser.getMediaPath("jungle.jpg"));> tree1.drawFromMeOn(bg);> bg.show();

Yes, we can put multiple statements in one line.

Page 82: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Slightly different picture

Page 83: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Removing the doggy

> tree1.setNext(tree2); tree2.setNext(tree3); tree3.setNext(doggy); doggy.setNext(house);

> tree1.remove(doggy);> tree1.drawFromMeOn(bg);

Page 84: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Putting the mutt back

> bg = new Picture(FileChooser.getMediaPath("jungle.jpg"));

> tree1.insertAfter(doggy);> tree1.drawFromMeOn(bg);

Page 85: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Animation = (Changing a structure + rendering) * n We can use what we just did to create

animation. Rather than think about animation as “a series of

frames,” Think about it as:

Repeatedly: Change a data structure Render (draw while traversing) the data structure to create a

frame

Page 86: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

AnimatedPositionedScene

public class AnimatedPositionedScene { /** * A FrameSequence for storing the frames **/ FrameSequence frames; /** * We'll need to keep track * of the elements of the scene **/ PositionedSceneElement tree1, tree2, tree3, house, doggy, doggyflip;

Page 87: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Setting up the animation

public void setUp(){ frames = new FrameSequence("D:/Temp/");

FileChooser.setMediaPath("D:/cs1316/mediasources/");

Picture p = null; // Use this to fill elements p = new Picture(FileChooser.getMediaPath("tree-

blue.jpg")); tree1 = new PositionedSceneElement(p); p = new Picture(FileChooser.getMediaPath("tree-

blue.jpg")); tree2 = new PositionedSceneElement(p);

p = new Picture(FileChooser.getMediaPath("tree-blue.jpg"));

tree3 = new PositionedSceneElement(p); p = new Picture(FileChooser.getMediaPath("house-

blue.jpg")); house = new PositionedSceneElement(p); p = new Picture(FileChooser.getMediaPath("dog-

blue.jpg")); doggy = new PositionedSceneElement(p); doggyflip = new PositionedSceneElement(p.flip()); }

Page 88: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Render the first frame

public void make(){ frames.show(); // First frame Picture bg = new

Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.setNext(doggy); doggy.setNext(tree2);

tree2.setNext(tree3); tree3.setNext(house); tree1.drawFromMeOn(bg); frames.addFrame(bg);

Page 89: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Render the doggy moving right // Dog moving right bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggy); tree2.insertAfter(doggy); tree1.drawFromMeOn(bg); frames.addFrame(bg);

bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggy); tree3.insertAfter(doggy); tree1.drawFromMeOn(bg); frames.addFrame(bg);

bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggy); house.insertAfter(doggy); tree1.drawFromMeOn(bg); frames.addFrame(bg);

Page 90: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Moving left

//Dog moving left bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggy); house.insertAfter(doggyflip); tree1.drawFromMeOn(bg); frames.addFrame(bg); bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggyflip); tree3.insertAfter(doggyflip); tree1.drawFromMeOn(bg); frames.addFrame(bg);

bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggyflip); tree2.insertAfter(doggyflip); tree1.drawFromMeOn(bg); frames.addFrame(bg);

bg = new Picture(FileChooser.getMediaPath("jungle.jpg")); tree1.remove(doggyflip); tree1.insertAfter(doggyflip); tree1.drawFromMeOn(bg); frames.addFrame(bg);

}

Page 91: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Results

Page 92: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Version 2: Layering

> Picture bg = new Picture(400,400);> LayeredSceneElement tree1 = new LayeredSceneElement(new Picture(FileChooser.getMediaPath("tree-blue.jpg")),10,10);> LayeredSceneElement tree2 = new LayeredSceneElement(new Picture(FileChooser.getMediaPath("tree-blue.jpg")),100,10);> LayeredSceneElement tree3 = new LayeredSceneElement(new Picture(FileChooser.getMediaPath("tree-blue.jpg")),200,100);> LayeredSceneElement house = new LayeredSceneElement(new Picture(FileChooser.getMediaPath("house-blue.jpg")),175,175);> LayeredSceneElement doggy = new LayeredSceneElement(new Picture(FileChooser.getMediaPath("dog-blue.jpg")),150,325);> tree1.setNext(tree2); tree2.setNext(tree3); tree3.setNext(doggy);

doggy.setNext(house);> tree1.drawFromMeOn(bg);> bg.show();

Page 93: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

First version of Layered Scene

Page 94: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Reordering the layering

> house.setNext(doggy); doggy.setNext(tree3); tree3.setNext(tree2); tree2.setNext(tree1);

> tree1.setNext(null);> bg = new Picture(400,400);> house.drawFromMeOn(bg);> bg.show();

Basically, we’re reversing the list

Page 95: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Reordered (relayered) scene

Think about what’s involved in creating a method to reverse() a list…

Page 96: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What’s the difference?

If we were in PowerPoint or Visio, you’d say that we changed the layering. “Bring to front” “Send to back” “Bring forward” “Send backward”

These commands are actually changing the ordering of the layers in the list of things to be redrawn.

• Change the ordering in the list.

• Render the scene

• Now it’s a different layering!

Page 97: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Version 3: A List with Both

Problem 1: Why should we have only layered scene elements or positioned scene elements?

Can we have both? SURE! If each element knows how to draw itself! But they took different parameters!

Layered got their (x,y) passed in. It works if we always pass in a turtle that’s set to the right place to draw

if it’s positioned (and let the layered ones do whatever they want!) Problem 2: Why is there so much duplicated code?

Why do only layered elements know last() and add()?

Page 98: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using Superclasses

What we really want is to define a class SceneElement That knows most of being a picture element. It would be an abstract class because we don’t actually mean to

ever create instances of THAT class.

Then create subclasses: SceneElementPositioned and SceneElementLayered We’d actually use these.

Page 99: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Class Structure

Abstract Class SceneElement

It knows its Picture myPic and its next (SceneElement).

It knows how to get/set next, to reverse() and insertAfter(), and to drawFromMeOn().

It defines drawWith(turtle), but leaves it for its subclasses do complete.

An abstract class defines structure and behavior that subclasses will inherit.

Page 100: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Class Structure

Abstract Class SceneElement

It knows its Picture myPic and its next.

It knows how to get/set next, to reverse() and insertAfter(), and to drawFromMeOn() and drawWith(turtle)

Class SceneElementPositioned

It knows how to drawWith(turtle)

Class SceneElementLayered

It knows its position (x,y).

It knows how to drawWith(turtle) by moving to (x,y) then dropping.

We say that the subclasses extend the superclass.

The subclasses inherit data and methods from superclass.

Page 101: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using the new structure

public class MultiElementScene { public static void main(String[] args){ FileChooser.setMediaPath("D:/cs1316/mediasources/");

// We'll use this for filling the nodes Picture p = null; p = new Picture(FileChooser.getMediaPath("swan.jpg")); SceneElement node1 = new SceneElementPositioned(p.scale(0.25));

p = new Picture(FileChooser.getMediaPath("horse.jpg")); SceneElement node2 = new SceneElementPositioned(p.scale(0.25)); p = new Picture(FileChooser.getMediaPath("dog.jpg")); SceneElement node3 = new SceneElementLayered(p.scale(0.5),10,50); p = new Picture(FileChooser.getMediaPath("flower1.jpg")); SceneElement node4 = new SceneElementLayered(p.scale(0.5),10,30); p = new Picture(FileChooser.getMediaPath("graves.jpg")); SceneElement node5 = new SceneElementPositioned(p.scale(0.25));

Page 102: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Rendering the scene

node1.setNext(node2); node2.setNext(node3); node3.setNext(node4); node4.setNext(node5); // Now, let's see it! Picture bg = new Picture(600,600); node1.drawFromMeOn(bg); bg.show(); }}

Page 103: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Rendered scene

Page 104: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

New Version: Trees for defining scenes Not everything in a scene is a single list.

Think about a pack of fierce doggies, er, wolves attacking the quiet village in the forest.

Real scenes cluster. Is it the responsibility of the elements to know about

layering and position? Is that the right place to put that know how?

How do we structure operations to perform to sets of nodes? For example, moving a set of them at once?

Page 105: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Attack of the Nasty Wolvies

Page 106: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Closer…

Page 107: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Then the Hero Appears!

Page 108: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

And the Wolvies retreat

Page 109: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What’s underlying this

This scene is described by a tree Each picture is a BlueScreenNode in this tree. Groups of pictures are organized in HBranch or

VBranch (Horizontal or Vertical branches) The root of the tree is just a Branch. The branches are positioned using a MoveBranch.

Page 110: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Labeling the Pieces

VBranch with BlueScreenNode wolves

MoveBranch to (10,50)

Branch (root)

HBranch with BSN trees

HBranch with 3 BSN houses and a

VBranch with 3 BSN houses

MoveBranch to (10,400)

MoveBranch to (300,450)

Page 111: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

It’s a Tree

VBranch with BlueScreenNode wolves

MoveBranch to (10,50)

Branch (root)

HBranch with BSN trees

HBranch with 3 BSN houses and a

VBranch with 3 BSN houses

MoveBranch to (10,400)

MoveBranch to (300,450)

Page 112: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Class Structure

DrawableNode knows only next, but knows how to do everything that our picture linked lists do (insertAfter, remove, last, drawOn(picture)). Everything else is a subclass of that.

PictNode knows it’s Picture myPict and knows how to drawWith(turtle) (by dropping a picture)

BlueScreenNode doesn’t know new from PictNode but knows how to drawWith(turtle) by using bluescreen.

Page 113: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Branch Class Structure

Branch knows its children—a linked list of other nodes to draw. It knows how to drawWith by: (1) telling all its children to draw. (2) then telling all its children to draw.

A HBranch draws its children by spacing them out horizontally.

A VBranch draws its children by spacing them out vertically.

Page 114: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Class Structure Diagram

DrawableNode

Knows: next

Branch

Knows: children

HBranch

Knows how to drawWith horizontally

VBranch

Knows how to drawWith vertically

PictNode

Knows: myPict

Knows how to drawWith

BlueScreenNode

Knows how to drawWith as bluescreen

Note: This is not the same as the scene (object) structure!

Page 115: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using these Classes:When doggies go bad!public class WolfAttackMovie { /** * The root of the scene data structure **/ Branch sceneRoot; /** * FrameSequence where the animation * is created **/ FrameSequence frames; /** * The nodes we need to track between methods **/ MoveBranch wolfentry, wolfretreat, hero;

These are the nodes that change during the animation, so must be available outside the local method context

Page 116: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Setting up the pieces

/** * Set up all the pieces of the tree. **/ public void setUp(){ Picture wolf = new Picture(FileChooser.getMediaPath("dog-

blue.jpg")); Picture house = new Picture(FileChooser.getMediaPath("house-

blue.jpg")); Picture tree = new Picture(FileChooser.getMediaPath("tree-

blue.jpg")); Picture monster = new Picture(FileChooser.getMediaPath("monster-

face3.jpg"));

Page 117: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Making a Forest

//Make the forest MoveBranch forest = new MoveBranch(10,400); // forest

on the bottom HBranch trees = new HBranch(50); // Spaced out 50

pixels between BlueScreenNode treenode; for (int i=0; i < 8; i++) // insert 8 trees {treenode = new BlueScreenNode(tree.scale(0.5)); trees.addChild(treenode);} forest.addChild(trees);

Page 118: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Make attacking wolves

// Make the cluster of attacking "wolves" wolfentry = new MoveBranch(10,50); // starting position VBranch wolves = new VBranch(20); // space out by 20 pixels

between BlueScreenNode wolf1 = new BlueScreenNode(wolf.scale(0.5)); BlueScreenNode wolf2 = new BlueScreenNode(wolf.scale(0.5)); BlueScreenNode wolf3 = new BlueScreenNode(wolf.scale(0.5)); wolves.addChild(wolf1);wolves.addChild(wolf2);

wolves.addChild(wolf3); wolfentry.addChild(wolves);

Page 119: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Make retreating wolves

// Make the cluster of retreating "wolves" wolfretreat = new MoveBranch(400,50); // starting position wolves = new VBranch(20); // space them out by 20 pixels between wolf1 = new BlueScreenNode(wolf.scale(0.5).flip()); wolf2 = new BlueScreenNode(wolf.scale(0.5).flip()); wolf3 = new BlueScreenNode(wolf.scale(0.5).flip()); wolves.addChild(wolf1);wolves.addChild(wolf2);

wolves.addChild(wolf3); wolfretreat.addChild(wolves);

Page 120: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

It takes a Village…

// Make the village MoveBranch village = new MoveBranch(300,450); // Village on bottom HBranch hhouses = new HBranch(40); // Houses are 40 pixels apart

across BlueScreenNode house1 = new BlueScreenNode(house.scale(0.25)); BlueScreenNode house2 = new BlueScreenNode(house.scale(0.25)); BlueScreenNode house3 = new BlueScreenNode(house.scale(0.25)); VBranch vhouses = new VBranch(-50); // Houses move UP, 50 pixels

apart BlueScreenNode house4 = new BlueScreenNode(house.scale(0.25)); BlueScreenNode house5 = new BlueScreenNode(house.scale(0.25)); BlueScreenNode house6 = new BlueScreenNode(house.scale(0.25)); vhouses.addChild(house4); vhouses.addChild(house5);

vhouses.addChild(house6); hhouses.addChild(house1); hhouses.addChild(house2);

hhouses.addChild(house3); hhouses.addChild(vhouses); // Yes, a VBranch can be a child of an

HBranch! village.addChild(hhouses);

Page 121: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Making the village’s hero

// Make the monster

hero = new MoveBranch(400,300);

BlueScreenNode heronode = new BlueScreenNode(monster.scale(0.75).flip());

hero.addChild(heronode);

Page 122: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Assembling the Scene

//Assemble the base scene

sceneRoot = new Branch();

sceneRoot.addChild(forest);

sceneRoot.addChild(village);

sceneRoot.addChild(wolfentry);

}

Want the forest on top of the village? Put the village in BEFORE the forest! Then it will get rendered first

Where’s the wolfretreat and monster? They’ll get inserted into the scene in the middle of the movie

Page 123: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Trying out one scene:Very important for testing! /**

* Render just the first scene

**/

public void renderScene() {

Picture bg = new Picture(500,500);

sceneRoot.drawOn(bg);

bg.show();

}

Page 124: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Okay that works

Page 125: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Rendering the whole movie

/**

* Render the whole animation

**/

public void renderAnimation() {

frames = new FrameSequence("D:/Temp/");

frames.show();

Picture bg;

Page 126: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Wolvies attack! (for 25 frames) // First, the nasty wolvies come closer to the poor village // Cue the scary music for (int i=0; i<25; i++) { // Render the frame bg = new Picture(500,500); sceneRoot.drawOn(bg); frames.addFrame(bg); // Tweak the data structure wolfentry.moveTo(wolfentry.getXPos()+5,wolfentry.getYPos()+10); }

Inch-by-inch, er, 5-pixels by 10 pixels, they creep closer.

Page 127: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Our hero arrives! (In frame 26)

// Now, our hero arrives!

this.root().addChild(hero);

// Render the frame

bg = new Picture(500,500);

sceneRoot.drawOn(bg);

frames.addFrame(bg);

Page 128: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exit the threatening wolves,enter the retreating wolves // Remove the wolves entering, and insert the wolves

retreating this.root().children.remove(wolfentry); this.root().addChild(wolfretreat); // Make sure that they retreat from the same place that

they were at wolfretreat.moveTo(wolfentry.getXPos(),

wolfentry.getYPos()); // Render the frame bg = new Picture(500,500); sceneRoot.drawOn(bg); frames.addFrame(bg);

Page 129: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The wolves retreat (more quickly) // Now, the cowardly wolves hightail it out of there! // Cue the triumphant music for (int i=0; i<10; i++) { // Render the frame bg = new Picture(500,500); sceneRoot.drawOn(bg); frames.addFrame(bg); // Tweak the data structure wolfretreat.moveTo(wolfretreat.getXPos()-10,

wolfretreat.getYPos()-20); } }

Page 130: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Making the Movie

Welcome to DrJava.> WolfAttackMovie wam = new WolfAttackMovie();

wam.setUp(); wam.renderScene();

> wam.renderAnimation();

There are no frames to show yet. When you add a frame it will be shown

> wam.replay();

Page 131: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Completed Movie

Page 132: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Homework Assignment! Option 1: Create linked list music

Create music with at least five calls to repeatInserting or weave It must be at least 20 nodes long. Make one new riff yourself and use it. Draw the resultant sound structure

Option 2: Make a movie—with sound! Use a scene graph for the visuals, and a linked list for the sound.

Maybe play one node per frame?

Can use play() for background sounds, blockingPlay() for foreground sounds

Only rule: During rendering, cannot create any new sounds. Must be in the linked list of sounds already.

Example: HW4 and HW6 at http://coweb.cc.gatech.edu/cs1316/458

Page 133: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Simulations

We build a simulation “from scratch”: Wolves and deer Based on Anne Fleury’s work about students avoiding

abstraction and preferring duplicating/explicit code. We’re trying to make it easier to understand, and then

introduce abstraction.

Then we build a simulation package that makes it all easier.

Page 134: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Real programmers don’t make data structures…often Programmers almost never make arrays. Most programmers don’t make linked lists or trees or

graphs, either! Or hashtables/dictionaries, or heaps, or stacks and queues.

These core, general, abstract data structures are typically provided in some form through libraries for the language. That’s true for both Python/Jython and Java.

Page 135: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Real programmers make models…often The basic processes of modeling is something

that every object-oriented programmer does all the time. Aggregation: connecting objects together through

references Generalization and Specialization

Learning how data structures work is learning about modeling.

Page 136: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Real programmers make data structures…sometimes Sometimes you do make data structures.

If you need a specialized structure. If you want just the methods you want in the way that

you want them. For example, Java’s LinkedList has no insertAfter()!

If you need it to work faster.

Page 137: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Real programmers make data structures choices!

You choose between different data structures all the time.

Often the choice is based on running time. Arrays are faster than linked lists for some things (like

accessing element i),while linked lists are faster for other things (like insertion and deletion).

Sometimes the choice is for particular properties. Use trees for clustering, Use graphs for cycles, Use hashtables for lookup by String, not index number

Page 138: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Building a Simulation Package

Let’s make it much easier to build simulations. We’ll use Java’s data structures, rather than build our own. We’ll create Simulation and Agent as a general simulation, so

that we only subclass them to create our specific simulations.

A classic “real programmer” challenge: Making code designed to be reused (by us, but could be anyone) later.

Page 139: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

WDSimulation with new package

Page 140: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DiseaseSimulation

Page 141: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalSimulation

Page 142: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Design of the Package

Page 143: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How we use the package

Subclass Simulation to define your general simulation. Override the methods that you want to change. Feel free to call super.method() to reuse the general

functionality. Subclass Agent to define your simulation agents/actors.

Override the methods that you want to change. Feel free to call super.method() to reuse the general

functionality.

Page 144: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What Simulation provides

getAgents(), add(), remove(): Manipulate the list of all agents

setUp(): Open a world openFile(): Write data to a file openFrames(): Write frames to a FrameSequence run(): Run the simulation—for a number of timesteps, tell

each agent to act() endStep(): Print the timestep and write to the file. lineForFile(): Define what to print to the file. closeFile(): End the file writing

Page 145: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What Agent provides

setSpeed(), getSpeed(): Change/get speed init(): Add to simulation agents list die(): Make body red and remove from

simulation agents list getClosest(): Get the closest agent from a list

within a range. countInRange(): Count the agents within a range

that are on a list. act(): By default, wander aimlessly

Page 146: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Redefining WDSimulation

Page 147: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

WDSimulation

/** * WDSimulation -- using the Simulation class **/public class WDSimulation extends Simulation { /** * Fill the world with wolves and deer **/ public void setUp(){ // Let the world be set up super.setUp(); // Just for storing the new deer and wolves DeerAgent deer; WolfAgent wolf; // create some deer int numDeer = 20; for (int i = 0; i < numDeer; i++) { deer = new DeerAgent(world,this); } // create some wolves int numWolves = 5; for (int i = 0; i < numWolves; i++) { wolf = new WolfAgent(world,this); }

}

We need setUp() to define the world (let super.setUp() do that), then fill it with our agents.

Page 148: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Writing out our counts in WDSimulation /** * lineForFile -- write out number of wolves and deer **/ public String lineForFile(){ // Get the size (an int), make it an Integer, // in order to turn it into a string. (Whew!) return (new Integer(DeerAgent.allDeer.size())).toString()+"/t"+ (new Integer(WolfAgent.allWolves.size())).toString(); }

It’s not easy to convert an integer (size() of the list) to a string.

Page 149: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Defining our Deerimport java.awt.Color; // Color for colorizingimport java.util.LinkedList;

/** * DeerAgent -- Deer as a subclass of Agent **/public class DeerAgent extends Agent { /** class constant for the color */ private static final Color brown = new Color(116,64,35); /** class constant for how far deer can smell */ private static final double SMELL_RANGE = 50; /** Collection of all Deer */ public static LinkedList allDeer = new LinkedList();

Notice allDeer!

It’s a LinkedList—for free!

It’s static—there’s one list shared by all instances of the class. It’s the list of all DeerAgents, and there’s only one of these lists.

Page 150: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DeerAgent initialization

/** * Initialize, by adding to Deer list **/ public void init(Simulation thisSim){ // Do the normal initializations super.init(thisSim); // Make it brown setColor(brown); // Add to list of Deer allDeer.add(this); }

Page 151: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DeerAgent’s way of dying

/** * To die, do normal stuff, but * also remove from deer list **/ public void die(){ super.die(); allDeer.remove(this); System.out.println("Deer left: "+allDeer.size()); }

Page 152: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DeerAgent’s actions

/** * How a DeerAgent acts **/ public void act() { // get the closest wolf within the smell range WolfAgent closeWolf = (WolfAgent)

getClosest(SMELL_RANGE, WolfAgent.allWolves); if (closeWolf != null) { // Turn to face the wolf this.turnToFace(closeWolf); // Now directly in the opposite direction this.turn(180); // How far to run? How about half of current speed?? this.forward((int) (speed/2)); } else { // Run the normal act() -- wander aimlessly super.act(); } }

This is it folks!It’s all that we have to write to make DeerAgents work!

Page 153: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Constructors

////////////////////////////// Constructors //////////////////////// // Copy this section AS-IS into subclasses, but rename Agent to // Your class. /** * Constructor that takes the model display (the original * position will be randomly assigned) * @param modelDisplayer thing that displays the model * @param thisSim my simulation */ public DeerAgent (ModelDisplay modelDisplayer,Simulation thisSim) { super(randNumGen.nextInt(modelDisplayer.getWidth()), randNumGen.nextInt(modelDisplayer.getHeight()), modelDisplayer, thisSim); } /** Constructor that takes the x and y and a model * display to draw it on * @param x the starting x position * @param y the starting y position * @param modelDisplayer the thing that displays the model * @param thisSim my simulation */ public DeerAgent (int x, int y, ModelDisplay modelDisplayer, Simulation thisSim) { // let the parent constructor handle it super(x,y,modelDisplayer,thisSim); }

DON’T care about this!

Copy it in as-is, and make the names match your class.

That’s it. Period.

Page 154: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

WolfAgentimport java.awt.Color;import java.util.LinkedList;

/** * WolfAgent -- Wolf as a subclass of Agent **/public class WolfAgent extends Agent { /** class constant for how far wolf can smell */ private static final double SMELL_RANGE = 50;

/** class constant for how close before wolf can attack */ private static final double ATTACK_RANGE = 30; /** Collection of all Wolves */ public static LinkedList allWolves = new LinkedList();

Page 155: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

WolfAgent initializations /** * Initialize, by adding to Wolf list **/ public void init(Simulation thisSim){ // Do the normal initializations super.init(thisSim); // Make it brown setColor(Color.gray); // Add to list of Wolves allWolves.add(this); }

Page 156: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

WolfAgentact()

/** * Chase and eat the deer **/ /** * Method to act during a time step * pick a random direction and move some random amount up to top speed */ public void act() { // get the closest deer within smelling range DeerAgent closeDeer = (DeerAgent) getClosest(SMELL_RANGE, DeerAgent.allDeer); if (closeDeer != null) { // Turn torward deer this.turnToFace(closeDeer); // How much to move? How about minimum of maxSpeed // or distance to deer? this.forward((int) Math.min(speed, closeDeer.getDistance(this.getXPos(),this.getYPos()))); }

// get the closest deer within the attack distance closeDeer = (DeerAgent) getClosest(ATTACK_RANGE, DeerAgent.allDeer); if (closeDeer != null) { this.moveTo(closeDeer.getXPos(), closeDeer.getYPos()); closeDeer.die(); } else // Otherwise, wander aimlessly { super.act(); } // end else } // end act()

The same constructors are there, but let’s ignore those.

Page 157: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Running the WDSimulation

Welcome to DrJava.

> WDSimulation wd = new WDSimulation();

> wd.openFrames("D:/temp/"); // If you want an animation

> wd.openFile(“D:/cs1316/wds-data1.txt”); // If you want an output file.

> wd.run();

If you just want to run it:> WDSimulation wd = new WDSimulation();> wd.run();

Page 158: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DiseaseSimulation

Page 159: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What happens in a DiseaseSimulation We create a bunch of PersonAgents. One of them is sick. While running:

They wander aimlessly. If a Person gets close (within 10? 20?) of an infected

person, that Person gets infected, too.

Page 160: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

DiseaseSimulation

/** * DiseaseSimulation -- using the Simulation class **/public class DiseaseSimulation extends Simulation {/** * Fill the world with 60 persons, one sick **/ public void setUp(){ // Let the world be set up //super.setUp(); // Or set it up with a smaller world world = new World(300,300); world.setAutoRepaint(false);

PersonAgent moi; // 60 people for (int num = 0; num < 60; num++) { moi = new PersonAgent(world,this); } // Infect the first one moi = (PersonAgent) getAgents().get(0); moi.infect(); }

setUp() just creates 60 people, and the first one becomes infected.

Page 161: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Deciding what to store in a file

/**

* lineForFile -- write out number of infected

**/

public String lineForFile(){

PersonAgent first;

first = (PersonAgent) agents.get(0);

return (new Integer(first.infected())).toString();

}

infected() is an instance method that returns the number of infected persons. It doesn’t matter which person we ask it of, so we just grab the first one.

Page 162: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Defining a PersonAgent

import java.awt.Color; // Color for colorizingimport java.util.LinkedList;

/** * PersonAgent -- Person as a subclass of Agent **/public class PersonAgent extends Agent {

public boolean infection;

Page 163: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PersonAgent initialization

/** * Initialize, by setting color and making move fast **/ public void init(Simulation thisSim){ // Do the normal initializations super.init(thisSim); // Make it lightGray setColor(Color.lightGray); // Don't need to see the trail setPenDown(false); // Start out uninfected infection = false; // Make the speed large speed = 100; }

Page 164: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PersonAgent act() /** * How a Person acts **/ public void act() { // Is there a person within infection range of me? PersonAgent closePerson = (PersonAgent) getClosest(10, simulation.getAgents()); if (closePerson != null) { // If this person is infected, and I'm not infected if (closePerson.infection && !this.infection) { // I become infected this.infect(); } }

// Run the normal act() -- wander aimlessly super.act(); }

Page 165: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Getting sick

/** * Become infected **/ public void infect(){ this.infection = true; this.setColor(Color.red); // Print out count of number infected System.out.println("Number infected: "+infected()); }

Page 166: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Counting the infected /** * Count infected **/ public int infected() { int count = 0; LinkedList agents = simulation.getAgents(); PersonAgent check; for (int i = 0; i<agents.size(); i++){ check = (PersonAgent) agents.get(i); if (check.infection) {count++;} } return count; }

We could have added them to an infected list and just checked the size(), too.

There are constructors here, too, but we’re ignoring them now.

Page 167: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Running a DiseaseSimulation

DiseaseSimulation ds2 = new DiseaseSimulation();ds2.openFile(“D:/cs1316/disease-fullsize.txt”);ds2.run();

Page 168: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Comparing Small and Large Worlds for Disease Propagation

0

10

20

30

40

50

60

70

1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49

public void setUp(){ // Let the world be set up super.setUp(); // Or set it up with a smaller world //world = new World(300,300); //world.setAutoRepaint(false);

A common activity in this class: Generate data for Excel and analyze it there.

Page 169: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Small world DiseaseSimulation

0

10

20

30

40

50

60

70

1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49

public void setUp(){ // Let the world be set up //super.setUp(); // Or set it up with a smaller world world = new World(300,300); world.setAutoRepaint(false);

Page 170: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalSimulation

Page 171: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How it works

There are two sets of PoliticalAgents: Red and Blue Both wander aimlessly, but within constraints.

Blue is only to the right, red only to the left. Overlap for 200 pixels in the middle.

If a Blue gets surrounded (argued down?) by more Red supporters than Blue supporters, the Blue turns Red. And vice-versa.

But there is a problem with getting converted mid-timestep!

Page 172: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalSimulation

import java.awt.Color;/** * PoliticalSimulation -- using the Simulation class **/public class PoliticalSimulation extends Simulation {

/** * Fill the world with 60 persons **/ public void setUp(){ // Let the world be set up super.setUp();

PoliticalAgent moi; // 60 people for (int num = 0; num < 60; num++) { moi = new PoliticalAgent(world,this); // First 30 are red if (num < 30) { moi.politics = Color.red; moi.moveTo(100,100); PoliticalAgent.redParty.add(moi); } else { moi.politics = Color.blue; moi.moveTo(500,100); PoliticalAgent.blueParty.add(moi); } moi.setColor(moi.politics);

} // for loop } // setUp()

Page 173: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Tracking the PoliticalSimulation

/** * lineForFile -- write out number of each party **/ public String lineForFile(){

return (new Integer(PoliticalAgent.redParty.size())).toString()+"\t"+ (new Integer(PoliticalAgent.blueParty.size())).toString(); } /** * EndStep, count the number of each **/ public void endStep(int t){ super.endStep(t); System.out.println("Red: "+PoliticalAgent.redParty.size()+" Blue: "+ PoliticalAgent.blueParty.size()); }

We’re accessing here the static variables that track the redParty and blueParty.

Page 174: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalAgentimport java.awt.Color; // Color for colorizingimport java.util.LinkedList;

/** * PoliticalAgent -- Red or Blue Stater as a subclass of Agent **/public class PoliticalAgent extends Agent {

// Red or Blue public Color politics; public static LinkedList redParty = new LinkedList(); public static LinkedList blueParty = new LinkedList();

Page 175: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Initializing our PoliticalAgents /** * Initialize **/ public void init(Simulation thisSim){ // Do the normal initializations super.init(thisSim); // Don't need to see the trail setPenDown(false);

// Speed is 100 speed = 100;

}

Page 176: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Converting political preference

/** * Set politics **/ public void setPolitics(Color pref){ System.out.println("I am "+politics+" converting to "+pref); if (pref == Color.red) { blueParty.remove(this); redParty.add(this); this.politics = pref;} else { blueParty.add(this); redParty.remove(this); this.politics = pref; } this.setColor(pref); }

Page 177: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalAgent act() /** * How a PoliticalAgent acts **/ public void act() { // What are the number of blues and red near me? int numBlue = countInRange(30,blueParty); int numRed = countInRange(30,redParty);

if (politics==Color.red){ // If I'm red, and there are more blue than red near me, convert if (numBlue > numRed){ setPolitics(Color.blue);} } if (politics==Color.blue){ // If I'm blue, and there are more red than blue near me, convert if (numRed > numBlue) { setPolitics(Color.red);} }

Page 178: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PoliticalAgent act(), cont’d// Run the normal act() -- wander aimlessly super.act(); // But don't let them wander too far! // Let them mix only in the middle if (politics==Color.red) { if (this.getXPos() > 400) { // Did I go too far right? this.moveTo(200,this.getYPos());} } if (politics==Color.blue) { if (this.getXPos() < 200) { // Did I go too far left? this.moveTo(400,this.getYPos());} } }

Page 179: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How the Simulation Package works

There are lots of calls to this this.setUp(), for example.

This will call the instance’s method. Typically, the subclass!

If the subclass doesn’t have the method, it will inherit the method from the superclass.

The subclass can still call the superclass version using super.

Page 180: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Let’s trace the DiseaseSimulation

DiseaseSimulation ds2 = new DiseaseSimulation();ds2.run();

public Simulation() { // By default, don't write to a file. output = null; // And there is no FrameSequence frames = null; }

Here’s how a Simulation class instance gets constructed.

Page 181: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

ds2.run();

/**

* Run for a default of 50 steps

**/

public void run(){

this.run(50);

this.closeFile();

}

Both methods are in Simulation

/** * Ask all agents to run for the number of input * steps **/ public void run(int timeRange) { // A frame, if we're making an animation Picture frame; // For storing the current agent Agent current = null; // Set up the simulation this.setUp();

Does ds2 have a setUp() method?

Page 182: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

this.setUp() in DiseaseSimulation

/** * Fill the world with 60 persons, one sick **/ public void setUp(){ // Let the world be set up super.setUp();

PersonAgent moi; // 60 people for (int num = 0; num < 60; num++) { moi = new PersonAgent(world,this); } // Infect the first one moi = (PersonAgent) getAgents().get(0); moi.infect(); }

public void setUp(){ // Set up the World world = new World(); world.setAutoRepaint(false); }

Back to Simulation just for a moment, to set up the world, then back again.

Page 183: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Back to public void run(int timeRange) in Simulation // Set up the simulation this.setUp(); // loop for a set number of timesteps for (int t = 0; t < timeRange; t++) { // loop through all the agents, and have them // act() for (int index=0; index < agents.size(); index++) { current = (Agent) agents.get(index); current.act(); }

Do PersonAgents have act()’s?

You bet!

Page 184: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

PersonAgent act() to Agent act()

public void act() { // Is there a person within infection range of me? PersonAgent closePerson = (PersonAgent)

getClosest(20, simulation.getAgents()); if (closePerson != null) { // If this person is infected, and I'm not infected if (closePerson.infection && !this.infection) { // I become infected this.infect(); } }

// Run the normal act() -- wander aimlessly super.act(); }

public void act() { // Default action: wander aimlessly // if the random number is > prob of NOT turning then turn if (randNumGen.nextFloat() > PROB_OF_STAY) { this.turn(randNumGen.nextInt(360)); } // go forward some random amount forward(randNumGen.nextInt(speed)); } // end act()

Page 185: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Finishing Simulation run() // repaint the world to show the movement world.repaint(); if (frames != null){ // Make a frame from the world, then // add the frame to the sequence frame = new Picture(world.getWidth(),world.getHeight()); world.drawOn(frame); frames.addFrame(frame); } // Do the end of step processing this.endStep(t); // Wait for one second //Thread.sleep(1000); }

Hang on! Not done yet!

Page 186: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

endStep() calls lineForFile() (in DiseaseSimulation) public void endStep(int t){ // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); // If we have an open file, write the counts to it if (output != null) { // Try it try{

output.write(lineForFile()); output.newLine(); } catch (Exception ex) { System.out.println("Couldn't write the data!"); System.out.println(ex.getMessage()); // Make output null so that we don't keep trying output = null; } } } // endStep()

public String lineForFile(){ PersonAgent first; first = (PersonAgent) agents.get(0); return (new Integer(first.infected())).toString(); }

Page 187: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How much do you have to know?

Do you have to know what Simulation run() does? Or Agent act()? Not in any detail! You need to know what it roughly does, so you can

decide if you need it via super You need to know when your code will be called,

so that you can do what you need to, at the right point in the simulation.

Page 188: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Finally! Making Wildebeests

We simply copy characters to frames wherever the turtles are.

Page 189: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Story: The Curious Birds

The turtle-like curious bird things wander, slowly, toward the mysterious egg.

As they get up close to it—it opens its eyes and shows its fangs!

They scamper away while the monster shifts around and looks to the left and right.

Page 190: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Movie

Page 191: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

“What’s the big deal?”

“Isn’t this darn similar to the wolves attacking the village movie?”

Yes. But we didn’t have to build a scene graph and define

every frame here. We simply built a simulation and said “Go.”

Each time that we run this simulation, it’ll be slightly different. We can have as many “takes” as we want, and tweak the rules

of behavior as we want.

Page 192: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

A Mapping

We move Agents (turtles) in a simulation

And once a timestep, we map these to images and draw them.

Page 193: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

BirdSimulation

/** * BirdSimulation * A flock of 10 birds investigate a mysterious egg, * which suddenly shows itself to be a monster! **/public class BirdSimulation extends Simulation { public EggAgent egg; // We'll need to get this later in BirdAgent FrameSequence myFrames; // Need a separate one from Simulations

Page 194: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Setting up the Simulation

/** * Set up the world with 10 birds and the mysterious egg **/ public void setUp(){ // Set up the world super.setUp(); // We'll need frames for the animation myFrames = new FrameSequence("D:/Temp/"); myFrames.show(); BirdAgent tweetie; // 10 of 'em for (int num = 0; num < 10; num++) { tweetie = new BirdAgent(world,this);} // And the egg egg = new EggAgent(world,this); }

Page 195: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Creating the Animation

public void endStep(int t) { // Do the normal file processing (if any) super.endStep(t); // But now, make a 640x480 frame, and copy // in pictures from all the agents Picture frame = new Picture(640,480); Agent drawMe = null; for (int index=0; index<this.getAgents().size(); index++) { drawMe = (Agent) this.getAgents().get(index); drawMe.myPict.bluescreen(frame,drawMe.getXPos(), drawMe.getYPos()); } myFrames.addFrame(frame); }

Page 196: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Explaining the key lines

We get our Agent (BirdAgent or EggAgent).

Get the picture myPict then bluescreen it onto the frame at the current position of the agent’s turtle.

drawMe = (Agent) this.getAgents().get(index); drawMe.myPict.bluescreen(frame, drawMe.getXPos(), drawMe.getYPos());

Page 197: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Getting the timestep

Since we want something to happen at certain timesteps, we need act() to have the timestep. We need Simulation to pass us the timestep. We need Agent’s act() to catch the timestep and

pass it on as no timestep, so that all the old simulations continue to work.

Page 198: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Simulation change

// loop through all the agents, and have them

// act()

for (int index=0; index < agents.size(); index++) {

current = (Agent) agents.get(index);

current.act(t); // NEW -- pass in timestep

}

Page 199: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Addition to Agent

/**

* act() with a timestep

**/

public void act(int t){

// By default, don't act on it

this.act();

}Think through why we need this.

Simulation is now calling act(timestep). Our other simulations don’t have act(int t)…

Page 200: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

BirdAgent

/**

* BirdAgents use the bird character JPEGs

**/

public class BirdAgent extends Agent{

public static Picture bird1, bird2, bird3, bird4, bird5, bird6;

Why static? Would it work without static? Yes, but more resource intensive.

Page 201: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Setting up birds /** * Set up the birds **/ public void init(Simulation thisSim){ if (bird1 == null) { // Do we have the bird characters defined yet? // CHANGE ME! FileChooser.setMediaPath("D:/cs1316/MediaSources/"); bird1 = new Picture(FileChooser.getMediaPath("bird1.jpg")); bird2 = new Picture(FileChooser.getMediaPath("bird2.jpg")); bird3 = new Picture(FileChooser.getMediaPath("bird3.jpg")); bird4 = new Picture(FileChooser.getMediaPath("bird4.jpg")); bird5 = new Picture(FileChooser.getMediaPath("bird5.jpg")); bird6 = new Picture(FileChooser.getMediaPath("bird6.jpg")); }

Setting up a bunch of static variables to hold the bird pictures

Page 202: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Finishing BirdAgent init() // Start out with myPict as bird1 myPict = bird1; // Do the normal initializations super.init(thisSim); // Move all the birds to the far right corner this.setPenDown(false); this.moveTo(600,400); // Set speed to relatively slow this.setSpeed(40);

}

Page 203: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

What Birds do

/** * act(t) For first 20 steps, walk toward the egg, * +/- 30 degrees. * Then walk AWAY from the egg, and with MORE wandering (panic). **/

public void act(int t){ // First, handle motion if (t <= 20) { // Tell it that this really is a BirdSimulation BirdSimulation mySim = (BirdSimulation) simulation; // which has an egg this.turnToFace(mySim.egg); this.turn(randNumGen.nextInt(60)-30); forward(randNumGen.nextInt(speed)); } else { // Run away!! this.turnToFace(640,480); // Far right corner this.turn(randNumGen.nextInt(80)-40); forward(randNumGen.nextInt(speed)); }

What’s going on with this math is getting +/-. 0 to 60, minus 30, gives you -30 to 30

Page 204: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Birds also change character look (cell animation) // Next, set a new character int cell = randNumGen.nextInt(6)+1; // 0 to 5, + 1 => 1 to 6 switch (cell) { case 1: myPict = bird1; // this.drop(bird1); break; case 2: myPict = bird2; //this.drop(bird2); break; case 3: myPict = bird3; //this.drop(bird3); break; case 4: myPict = bird4; //this.drop(bird4); break; case 5: myPict = bird5; //this.drop(bird5); break; case 6: myPict = bird6; //this.drop(bird6); break; } // end switch } // end act

What’s this?

It’s called a switch or case statement.

Instead of 6 if’s, we have one big case.

Consider drop vs. chromakey? Think about resources and mapping to other media

Page 205: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Zooming in on the switch

We compute a random integer between 1 and 6.

We announce that we’re going to choose between options (switch) depending on the value of cell.

We identify each value we’re checking with a case statement.

Java executes the one that matches the switch.

Execution ends and jumps to the end of the switch on break.

int cell = randNumGen.nextInt(6)+1; // 0 to 5, + 1 => 1 to 6 switch (cell) { case 1: myPict = bird1; break; case 2: myPict = bird2; break;

Page 206: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

EggAgent

/** * EggAgent -- big scary egg that sits there until t=15, * then emerges as a monster! **/public class EggAgent extends Agent { public static Picture egg1, egg2, egg3, egg4;

Page 207: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Init() for an EggAgent /** * To initialize, set it up as the Egg in the upper lefthand corner **/ public void init(Simulation thisSim){ if (egg1 == null) { //Initialize //CHANGE ME! FileChooser.setMediaPath("D:/cs1316/MediaSources/"); egg1 = new Picture(FileChooser.getMediaPath("egg1.jpg")); egg2 = new Picture(FileChooser.getMediaPath("egg2.jpg")); egg3 = new Picture(FileChooser.getMediaPath("egg3.jpg")); egg4 = new Picture(FileChooser.getMediaPath("egg4.jpg")); } // Start out as egg1 myPict = egg1;

Page 208: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Meet the Eggs

Page 209: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The rest of EggAgent init()

// Normal initialization super.init(thisSim); // Make the turtle disappear //this.hide(); // Not really necessary this.setPenDown(false); // Move the egg up to the left hand corner this.moveTo(10,10); }

Page 210: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Eggs don’t move in act(int t) /** * To act, just drop the Egg for 15 steps, * then be the eyes opened for five steps, * then be the eyes switching back-and-forth **/ public void act(int t) { if (t < 19) { myPict = egg1;} //this.drop(egg1);} if (t>19 && t<24) { myPict = egg2;} //this.drop(egg2);}

Page 211: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Even when they’re looking scary

if (t>23) { int choose=randNumGen.nextInt(2); if (choose == 1) { myPict = egg3;} //this.drop(egg3);} else { myPict = egg4;} //this.drop(egg4);} } } // end act()

Page 212: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

To Explore Start the birds out all over the screen

So that we can see them wave, etc. better. Have the birds react to a state of the egg

For example: “egg.scary()==true”, so that we’re not tied to a particular timestep (frame #)

Have the birds react to one another. “I’m crowded, I’m going to move that way.”

Big idea! An animation is only one kind of representation to make from a simulation. How about playing certain sounds or MIDI phrases from

different characters at different times?

Page 213: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

CS1 for Engineering in MATLAB

Syllabus Sample lessons on getting started

Page 214: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Syllabus Getting started with MATLAB

Introduction to Vectors, the main MATLAB data type Conditionals, iteration, and functions Cell arrays (mini-databases) Structures Problem solving General arrays Graphing (MATLAB does professional quality graphics) Bodies of Rotation and Matrices File I/O Multimedia: Image and sound manipulation Serious CS: Numerical methods, Big O, Sorting,

Queues, and Graphs

Page 215: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Objectives – the MATLAB User Interface■ How to use the Command window to explore single

commands interactively and how to recall earlier commands to be repeated or changed

■ Where to examine the variables and files created in MATLAB

■ How to view and edit data tables created in MATLAB■ How MATLAB presents graphical data in separate

windows■ How to create scripts to solve simple arithmetic problems

Page 216: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Default WindowFile menu

Close icon

Current directoryCurrent

directory

Command window

Workspace window

Command history

Page 217: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Array Editor

New variable icon

Page 218: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

If you don’t have MATLAB, Octave!

Page 219: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

2.4 Scripts

Create a script derived from the Pythagorean theorem to compute the hypotenuse of a right triangle:

H2 = A2 + B2

where A and B are the sides adjacent to the right angle, and H is the hypotenuse opposite.

clearclc

A = 3; % the first side of a triangleB = 4; % the second side of a trianglehypSq = A^2 + B^2; % the square of the% hypotenuseH = sqrt(hypSq) % the answer

Page 220: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Store these in your working directory to access cd W:/home/guzdial/Documents/

Page 221: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

2.5 Engineering Example—Spacecraft Launchclearclc

cmPerInch = 2.54; % general knowledgeinchesPerFt = 12; % general knowledgemetersPerCm = 1/100; % general knowledgeMetersPerFt = metersPerCm * cmPerInch * inchesPerFt;startFt = 25000; % ft - givenstartM = startFt * MetersPerFt;g = 9.81; % m/sec^2top = 100; % km - givens = (top*1000) - startM; % minitial_v = (2*g*s)^0.5 % the final answer

Page 222: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Passing in parameters, return values

function retval = avg (v)

if (isvector (v))

retval = sum (v) / length (v);

endif

endfunction Saved as avg.m

Page 223: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

3.1 Concept: Using Built-in Functions In this chapter we will see the use of some of the functions built into

MATLAB. At the end of each chapter that uses built-in functions, you will find a

summary table listing the function specifications. For help on a specific function, you can type the following:

>> help <function name> For example:

>> help sqrt SQRT Square root.

SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive.

Page 224: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

3.2 Concept: Data Collections

This section considers two very common ways to group data: in arrays and in vectors.Data Abstraction allows us to refer to groups of data collectively:

“all the temperature readings for May” or “all the purchases from Wal-Mart.”

We can not only move these items around as a group, but also perform mathematical or logical operations on these groups, e.g.:

compute the average, maximum, or minimum temperatures for a month

A Homogeneous Collection is constrained to accept only items of the same data type – in this case, they will all be numbers

Page 225: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

3.3 MATLAB Vectors

Individual items in a vector are usually referred to as its elements. Vector elements have two separate and distinct attributes that make them unique in a specific vector:

their numerical value and their position in that vector.

For example, the individual number 66 is the third element in this vector. Its value is 66 and its index is 3. There may be other items in the vector with the value of 66, but no other item will be located in this vector at position 3.

Page 226: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Vector Manipulation

We consider the following basic operations on vectors:

Creating a Vector Determining the size of a Vector Extracting data from a vector by indexing Shortening a Vector Mathematical and logical operations on Vectors

Page 227: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Creating a Vector – Constant Values Entering the values directly, e.g.

A = [2, 5, 7, 1, 3] Entering the values as a range of numbers e.g.,

B = 1:3:20

Using the linspace(...) function e.g. C = linspace (0, 20, 11)

Using the functions zeros(1,n), ones(1,n), rand(1,n) and randn(1,n) to create vectors filled with 0, 1, or random values between 0 and 1

Page 228: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Size of Vectors and Arrays

MATLAB provides two functions to determine the size of arrays in general (a vector is an array with one row):

the function size(A) when applied to the array A returns vector containing two quantities: the number of rows and the number of columns

The function length(A) returns the maximum value in the size of an array; for a vector, this is its length.

Page 229: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Indexing a Vector

The process of extracting values from a vector, or inserting values into a vector

Syntax: v(index) returns the element(s) at the location(s)

specified by the vector index. v(index) = value replaces the elements at the

location(s) specified by the vector index. The indexing vector may contain either

numerical or logical values

Page 230: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Indexing examples

octave:10> a = [1,12,43,25,34]

a = 1 12 43 25 34octave:14> a a = 1 12 43 25 34

octave:15> a<12ans = 1 0 0 0 0

octave:16> a(1)ans = 1octave:17> a(a < 12)ans = 1octave:18> a < 20ans = 1 1 0 0 0

octave:19> a(a < 20)ans = 1 12

Page 231: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Numerical Indexing

The indexing vector may be of any length It should contain integer (non-fractional)

numbers The values in the indexing vector are

constrained by the following rules:For reading elements, all index values must be

1 <= element <= length(vector)For replacing elements, all index values must be

1 <= element

Page 232: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Replacement Rules

1. Either:• All dimensions of the blocks on either side of the replacement

instruction must be equal, or• There must be a single element on the RHS of the

replacement

2. If you replace beyond the end of the existing vector, the vector length is automatically increased.

• Any element not specifically replaced remains unchanged.• Elements beyond the existing length not replaced are set to 0.

Page 233: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Replacement examples

octave:20> a(3)=567a = 1 12 567 25 34

octave:21> aa = 1 12 567 25 34

octave:22> a(a < 20) = [12,34]a = 12 34 567 25 34

Page 234: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Logical Indexing The indexing vector length must be less than or equal to

the original vector length It must contain logical values (true or false) Access to the vector elements is by their relative position

in the logical vector When reading elements, only the elements corresponding to

true index values are returned When replacing elements, the elements corresponding to true

index values are replaced Beware – logical vectors in Matlab echo in the Command

window as 1 or 0, but they are not the same thing.

Page 235: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Shortening an Array

Never actually necessary. It is advisable to extract what you want by indexing rather than removing what you don’t want.

Can lead to logic problems when changing the length of a vector

Accomplished by assigning the empty vector ([]) to elements of a vector, or to complete rows or columns of an array.

Page 236: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Operating on Vectors

Three techniques extend directly from operations on scalar values:

■ Arithmetic operations■ Logical operations■ Applying library functions

Two techniques are unique to arrays in general, and to vectors in particular:

■ Concatenation■ Slicing (generalized indexing)

Page 237: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Arithmetic operations

In the Command window, enter the following:>> A = [2 5 7 1 3];>> A + 5ans =7 10 12 6 8>> A .* 2ans =4 10 14 2 6>> B = -1:1:3B =-1 0 1 2 3

Page 238: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Arithmetic operations (continued)

>> A .* B % element-by-element multiplicationans =-2 0 7 2 9>> A * B % matrix multiplication!!??? Error using ==> mtimesInner matrix dimensions must agree.>> C = [1 2 3]C =1 2 3>> A .* C % A and C must have the same length??? Error using ==> timesMatrix dimensions must agree.

Page 239: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Logical operations

>> A = [2 5 7 1 3];>> B = [0 6 5 3 2];>> A >= 5ans =0 1 1 0 0>> A >= Bans =1 0 1 0 1>> C = [1 2 3]>> A > C??? Error using ==> gt

Matrix dimensions must agree.

Page 240: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Logical operations (continued)

>> A = [true true false false];>> B = [true false true false];>> A & Bans =1 0 0 0>> A | Bans =1 1 1 0>> C = [1 0 0]; % NOT a logical vector>> A(C) % yes, you can index logical vectors, but ...??? Subscript indices must either be real positive

integers or logicals.

Page 241: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

A Footnote: the find function Continuing the code above:

>> C = find(B)ans = [1 3]

The find(...) function consumes a logical vector and returns the numerical indices of the elements of that vector that are true.

Example:octave:23> a > 20ans = 0 1 1 1 1octave:24> c = find(a > 20)c = 2 3 4 5

Page 242: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Applying library functions

All MATLAB functions accept vectors of numbers rather than single values and return a vector of the same length. Special Functions:■ sum(v) and mean(v) consume a vector and return a number■ min(v) and max(v) return two quantities: the minimum ormaximum value in a vector, plus the position in that vectorwhere that value occurred. ■ round(v), ceil(v), floor(v), and fix(v) remove the fractional part of the numbers in a vector by conventional rounding, rounding up, rounding down, and rounding toward zero, respectively.

Exercise: Make up a vector and try all of these on it!

Page 243: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Concatenation

MATLAB lets you construct a new vector by concatenating other vectors: A = [B C D ... X Y Z]where the individual items in the brackets may be any vector defined as a constant or variable, and the length of A will be the sum of the lengths of the individual vectors. A = [1 2 3 42]is a special case where all the component elements are scalar quantities.

Page 244: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Concatenation Example

octave:27> aa = 12 34 567 25 34

octave:28> bb = 78.600 45.600 12.200

octave:29> c=[a b]c = 12.000 34.000 567.000 25.000 34.000 78.600

45.600 12.200

Page 245: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Slicing (generalized indexing)

A(4) actually creates an anonymous 1 × 1 index vector, 4, and then using it to extract the specified element from the array A.

In general, B(<rangeB>) = A(<rangeA>)

where <rangeA> and <rangeB> are both index vectors, A is an existing array, and B can be an existing array, a new array, or absent altogether (giving B the name ans). The values in B at the indices in <rangeB> are assigned the values of A from <rangeA> .

Page 246: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Rules for Slicing

■ Either the dimensions of <rangeB> must be equal to the dimensions of <rangeA> or <rangeA> must be of size 1

■ If B did not exist before this statement was implemented, it is zero filled where assignments were not explicitly made

■ If B did exist before this statement, the values not directly assigned in <rangeB> remain unchanged

Page 247: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Representing Mathematical Vectors

An unfortunate clash of names Vectors in mathematics can be represented by Matlab

vectors The first, second and third values being the x, y and z

components Matlab vector addition and subtraction work as expected. Matlab magnitude and scaling works as expected. Dot product is just the sum of A .* B Cross product has a Matlab function

Page 248: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Engineering Example—Forces and Moments So given a pair of forces A

and B acting at a point P, find: The resultant force, and The moment of that resultant

about the origin

Page 249: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Vector SolutionclearclcPA = [0 1 1]PB = [1 1 0]P = [2 1 1]M = [4 0 1]% find the resultant of PA and PBPC = PA + PB% find the unit vector in the direction of PCmag = sqrt(sum(PC.^2))unit_vector = PC/mag% find the moment of the force PC about M% this is the cross product of MP and PCMP = P - Mmoment = cross( MP, PC )

Page 250: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

MATLAB Arrays

Page 251: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

A Transposed Array

Page 252: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Array Manipulation

We consider the following basic operations on vectors:

Creating an array Extracting data from an array by indexing Shortening an array Mathematical and logical operations on arrays

Page 253: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Creating an Array – Constant Values Entering the values directly, e.g.

A = [2, 5, 7; 1, 3, 42] the semicolon identifies the next row, as would a new line in the command

Using the functions zeros( rows, cols), ones(rows, cols), rand(rows, cols) and randn(rows, cols) to create vectors filled with 0, 1, or random values between 0 and 1

octave:32> m = [1, 2, 3; 4, 5, 6]m = 1 2 3 4 5 6

Page 254: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Indexing an Array

The process of extracting values from an array, or inserting values into an array

Syntax: A(row, col) returns the element(s) at the location(s)

specified by the array row and column indices. A(row, col) = value replaces the elements at the

location(s) specified by the array row and column indices.

The indexing row and column vectors may contain either numerical or logical values

Page 255: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Numerical Indexing

The indexing vectors may be of any length It should contain integer (non-fractional)

numbers The values in the indexing vectors are

constrained by the following rules:For reading elements, all index values must be

1 <= element <= length(array dimension)For replacing elements, all index values must be

1 <= element

Page 256: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Replacement Rules

1. Either:• All dimensions of the blocks on either side of the replacement

instruction must be equal, or• There must be a single element on the RHS of the

replacement

2. If you replace beyond the end of any dimension of the existing array, the size in that dimension is automatically increased.

• Any element not specifically replaced remains unchanged.• Elements beyond the existing dimension length not replaced

are set to 0.

Page 257: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Logical Indexing

The indexing vector length must be less than or equal to the original array dimension

It must contain logical values (true or false) Access to the array elements is by their relative

position in the logical vectors When reading elements, only the elements

corresponding to true index values are returned When replacing elements, the elements

corresponding to true index values are replaced

Page 258: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Logical indexing in matrices example

octave:32> m = [1, 2, 3; 4, 5, 6]

m =

1 2 3

4 5 6

octave:34> m ( m<=4 ) = -1

m =

-1 -1 -1

-1 5 6

Page 259: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Operating on Arrays

Four techniques extend directly from operations on vectors:

■ Arithmetic operations■ Logical operations■ Applying library functions■ Slicing (generalized indexing)

The following deserves an additional word because of the nature of arrays:

■ Concatenation

Page 260: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Array Concatenation

Array concatenation can be accomplished horizontally or vertically: R = [A B C] succeeds as long as A, B and C have the

same number of rows; the columns in R will be the sum of the columns in A, B and C.

R = [A; B; C] succeeds as long as A, B and C have the same number of columns; the rows in R will be the sum of the rows in A, B and C.

Page 261: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Reshaping Arrays

Arrays are actually stored in column order in Matlab. So internally, a 2 × 3 array is stored as a column vector: A(1,1) A(2,1) A(1,2) A(2,2) A(1,3) A(2,3)

Any n × m array can be reshaped into any p × q array as long as n*m = p*q using the reshape function.

Page 262: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

3.6 Engineering Example—Computing Soil Volume Consider the example where you are given the

depth of soil from a survey in the form of a rectangular array of soil depth.

You are also given the footprint of the foundations of a building to be built on that site and the depth of the foundation.

Compute the volume of soil to be removed.

Page 263: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Survey Data

Page 264: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Building Footprint

Page 265: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Solutionclearclc% soil depth data for each square produced % by the surveydpth = [8 8 9 8 8 8 8 8 7 8 7 7 7 7 8 8 8 78 8 8 8 8 8 8 7 7 7 7 7 8 7 8 8 8 7 . . .9 8 8 7 7 8 7 7 7 7 8 8 9 9 9 8 7 8];% estimated proportion of each square that should % be excavatedarea = [1 1 1 1 1 1 1 1 1 1 .3 0 0 0 0 0 0 0 . . .0 0 0 0 0 0 .4 .8 .9 1 1 1 1 1 1 1 1 .6];square_volume = dpth .* area;total_soil = sum(sum(square_volume))

Page 266: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.1 Concept: Code Blocks A code block is a collection of zero or more MATLAB instructions

identified for one of two reasons:1. you wish to execute them only under certain circumstances, or2. You wish to repeat them a certain number of times

Some languages identify code blocks by enclosing them in braces ({. . .}); others identify them by the level of indentation of the text.

MATLAB uses the occurrence of key command words in the text to define the extent of code blocks: if, switch, while, for, case, otherwise, else,

elseif, end Code blocks are identified with blue coloring by the MATLAB text

editor. They are not part of the code block, but they serve both as instructions on what to do with the code block, and as delimiters that define the extent of the code block.

Page 267: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.2 Conditional Execution in General Basic conditional execution

requires two things: A logical expression, and A code block

If the expression is true, the code block is executed.

Otherwise, execution is resumed at the instruction following the code block

Page 268: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Compound conditionals

By introducing elseif and else, we allow for the possibility of either conditional or unconditional execution when a test returns false as illustrated.

Page 269: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.3 if Statements

The general template for if statements is:if <logical expression 1> <code block 1>elseif <logical expression 2> <code block 2>...elseif <logical expression n> <code block n>else <default code block>end

Page 270: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

General Observations

A logical expression is any statement that returns a logical result.

If that result is a logical vector, v, the if statement behaves as: if all(v)

While indentation has no effect on the logical flow, it helps to clarify the logical flow. The MATLAB editor automatically creates suitable indentation as you type.

Page 271: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.4 switch Statements

The template for a switch statement is:switch <parameter> case <case specification 1> <code block 1> case <case specification 2> <code block 2> . . case <case specification n> <code block n> otherwise <default code block> end

Page 272: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

General Observations

The switch statement is looking for the parameter to have an exact match to one of the cases.

One case specification may have multiple values enclosed in braces( {…}).

The default case catches any values of the parameter other than the specified cases.

The default case should trap bad parameter values.

Page 273: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.5 Iteration in General

Iteration allows controlled repetition of a code block. Control statements at the beginning of the code block specify the manner and extent of the repetition:

The for loop is designed to repeat its code block a fixed number of times and largely automates the process of managing the iteration.

The while loop is more flexible in character. Its code block can be repeated a variable number of times. It is much more of a “do-it-yourself” iteration kit.

Page 274: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.6 for Loops

The template for a for loop is:for <variable> = <vector> <code block>end

The for loop automatically sets the value of the variable to each element of the vector in turn and executes the code block with that value.

Page 275: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.7 while Loops

The code block will be repeated as long as the logical expression returns true.

The while loop template is:<initialization>while <logical expression> <code block> % must make some changes % to enable the loop to terminateend

Page 276: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

4.8 Engineering Example—Computing Liquid LevelsGive a tank as shown, how do you calculate the volume of liquid? The answer of course is “it depends on h.”If h <= r, do one calculation;otherwise if h < (H-r) do a second;Otherwise if h <= H, do a third;Otherwise there is an error!

Page 277: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Solutionif h < r v = (1/3)*pi*h.^2.*(3*r-h);elseif h < H-r v = (2/3)*pi*r^3 + pi*r^2*(h-r);elseif h <= H v = (4/3)*pi*r^3 + pi*r^2*(H-2*r) ... - (1/3)*pi*(H-h)^2*(3*r-H+h);else disp(‘liquid level too high’) continueendfprintf( ... 'rad %0.2f ht %0.2f level %0.2f vol %0.2f\n', ... r, H, h, v);

Page 278: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

5.1 Concept: Abstraction

Procedural abstraction permits a code block that solves a particular sub-problem to be packaged and applied to different data inputs.

analogous to the concept of data abstraction where individual data items are gathered to form a collection.

We have already used a number of built-in procedural abstractions in the form of functions.

They allow us to apply a code block about which we know nothing to data that we provide.

Page 279: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

5.1 Concept: Encapsulation

Encapsulation is the concept of putting a wrapper around a collection that you wish to protect from outside influence. Functions encapsulate the code they contain in two ways:

the variables declared within the function are not visible from elsewhere, and

the function’s ability to change the values of variables (otherwise known as causing side effects) is restricted to its own code body.

Page 280: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

5.2 Black Box View of a Function

<param 1...n> are the formal parameters – the names given to the incoming data inside the function.

<item 1...n> are the actual parameters provided to the function by its caller. They may have names different from the formal parameter names They are correlated to the formal parameter names by their position

Page 281: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

5.3 MATLAB Implementation

The template for defining a function is:function <return info> <function name> (<parameters>) <documentation> <code body> % must return the results

The function code must be stored in a file whose name is the name of the function.

Functions return data to the caller by assigning values to the return variable(s)

MATLAB throws an error if a function does not make assignments to all the return variables.

Page 282: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

5.4 Engineering Example—Measuring a Solid Object

We need to compute the volume and wetted area of this object.

This requires one function that computes the volume and wetted area of a cylinder

We have a range of disk heights for which we require this information.

Page 283: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Solution

The function stored in cylinder.mfunction [area, volume] = cylinder(height, radius)% function to compute the area and volume of a cylinder% usage: [area, volume] = cylinder(height, radius)base = pi .* radius.^2;volume = base .* height;area = 2 * pi * radius .* height + 2 * base;

The test script

clearclch = 1:5; % set a range of disk thicknessesR = 25;r = 3;[Area Vol] = cylinder(h, R) % dimensions of large disk[area vol] = cylinder(h, r) % dimensions of the hole% compute remaining volumeVol = Vol - 8*volArea = Area + 8*(area - 2*2*pi*r.^2)

Page 284: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Background

Two relationships between characters and numbers1. Individual characters have an internal numerical

representation: The shapes we see in windows are created by a character generator.

2. Strings of characters represent numerical values: Numerical values are stored in MATLAB in a special, internal

representation for efficient numerical computation. Whenever we need to see the value of a number, the internal

representation is converted into a character string representing its value in a form we can read.

Similarly, to enter numerical values, we create a character string and have it converted to the internal representation

Page 285: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Concept: Mapping

Mapping defines a relationship between two entities. e.g. the idea that the function f(x) = x2 defines the mapping between the value of x and the value

of f(x).

We will apply that concept to the process of translating a character (like ‘A’) from its graphical form to a numerical internal code. Character mapping allows each individual graphic character to be uniquely represented by a numerical value.

Page 286: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Concept: Casting

Casting is the process of changing the way a language views a piece of data without actually changing the data value. Under normal circumstances, a language like MATLAB automatically presents a set of data in the “right” form. However, there are times when we wish to force the language to treat a data item in a specific way; we might want to view the underlying numerical representation as a number rather that as a character, in which case we have to cast the variable containing the character to a numerical data type.MATLAB implements casting as a function with the name of the data type expected. In essence, these functions implement the mapping from one character representation to another.

Page 287: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

MATLAB Implementation of Casting

>> uint8('A') % uint8 is an integer data type % with values 0 - 255ans = 65>> char(100) % char is the character classans = d>> char([97 98 99 100 101])ans = abcde>> double('fred')ans = 102 114 101 100>> fred = 'Fred'fred = Fred>> next = fred + 1next = 71 115 102 101>> a = uint8(fred)a = 70 114 101 100>> name = char(a + 1)name = Gsfe

Page 288: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

String Operations

Since strings are internally represented as vectors of numbers, all the normal vector operations apply: Arithmetic and logical operations Concatenation Shortening Indexing Slicing

Page 289: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Conversion from Numbers to Strings

Use the following built-in MATLAB functions for a simple conversion of a single number, x, to its string representation:

int2str(x) if you want it displayed as an integer value num2str(x, n) to see the decimal parts; the parameter n

represents the number of decimal places required—if not specified, its default value is 3

sprintf(…) provides finer-grained format control Its first parameter is a format control string that defines how

the resulting string should be formatted. A variable number of value parameters follow the format string,

providing data items as necessary to satisfy the formatting.

Page 290: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Format Control in sprintf(…) Characters in the format string are copied to the result string. Special behavior is introduced by two special characters:

'%' introduces a conversion specification: %d (integer), %f (real), %g (general), %c (character) and %s(string).

Each conversion requires a value parameter in the sprintf(…) call.A number may be placed immediately after the % character to specify the minimum number of characters in the conversion. The %f and %g conversions can include '.n' to indicate the number of decimal places required.

'\' introduces escape characters for format control. The most common: \n (new line) and \t (tab).

Page 291: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Conversion from Strings to Numbers:input(…)

When possible, allow input(...) to do the conversion. The function input(str) presents the string parameter to the user in the

Command window and waits for the user to type some characters and the Enter key, all of which are echoed in the Command window. Then it converts the input string according to the following rules. If the string begins with:

a numerical character, MATLAB converts the string to a number An alpabetic character, MATLAB constructs a variable name and looks

for its definition an open bracket, '[', an array is constructed the single quote character, MATLAB creates a string If a format error occurs, MATLAB repeats the prompt.

This behavior can be modified if 's' is provided as the second parameter to input(…), in which case the complete input character sequence is saved as a string regardless of content.

Page 292: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Conversion from Strings to Numbers: sscanf

In its simplest form, CV = sscanf(str, fmt) scans the string str and converts each data item according to the conversion specifications in the format string fmt.

Each item discovered in str produces a new row on the result array, CV, a column vector.

If you convert strings this way, each character in the string becomes a separate numerical result in the output vector.

MATLAB allows you to substitute thecharacter '*' for the conversion size parameter to suppress any strings in the input string. For example:str = 'are 4.700 1.321 4.800000'B = sscanf( str, '%*s %f %f %f')B =4.70001.32104.8000

Page 293: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Miscellaneous Character String Operations disp(…) shows the contents of a variable in the

Command Window fprintf(…) formats data for the Command Window exactly

as sprintf does to produce a string.

Page 294: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

String Comparison Strings may be compared as vectors; however, they must then obey vector

comparison rules strcmp(…) and strcmpi(…) compare strings of any length.

>> 'abcd' == 'abcd'ans = 1 1 1 1>> 'abcd' == 'abcde'??? Error using ==> eqArray dimensions must match for binary array op.>> strcmp('abcd', 'abcde')ans = 0>> strcmp('abcd', 'abcd')ans = 1>> 'abc' == 'a'ans = 1 0 0>> strcmpi('ABcd', 'abcd')ans = 1

Page 295: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

6.5 Arrays of Strings

Character string arrays can be constructed by either of the following: As a vertical vector of strings, all of which must be the

same length By using a special version of the char(…) cast

function that accepts a variable number of strings with different lengths, pads them with blanks to make all rows the same length, and stores them in an array of characters

Page 296: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Engineering Example—Encryption

Encryption is the process of somehow changing a message in the form of a string of characters so that it can be understood at its destination, but is unintelligible to a third party who does not have access to the

original encryption scheme.

Early encryption schemes involved shifting characters in the alphabet either by a constant amount or according to a one-time message pad.

However, these schemes are relatively easily cracked by examining letter frequencies.

Page 297: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Our Approach

We will use a scheme that makes use of the MATLAB random number generator to create a random character shift unique to each occurrence of characters in a message, so that letter frequency cannot be used to determine the encryption technique.

At the destination, as long as the random number generator is seeded with an agreed value, the message can be reconstructed by shifting back the message characters.

A few minor modifications wrap the characters on the alphabet to remain within the set of printable letters.

Page 298: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Solution - encryption%%% encryption section% seed the random generator to a known staterand('state', 123456)loch = 33;hich = 126;range = hich+1-loch;rn = floor( range * rand(1, length(txt) ) );change = (txt>=loch) & (txt<=hich);enc = txt;enc(change) = enc(change) + rn(change);enc(enc > hich) = enc(enc > hich) - range;disp('encrypted text')encrypt = char(enc);

Page 299: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

The Solution - decryption

%% good decryption% seed the random generator to the same staterand('state', 123456);rn = floor( range * rand(1, length(txt) ) );change = (encrypt>=loch) & (encrypt <= hich)dec = encrypt;dec(change) = dec(change) - rn(change) + range;dec(dec > hich) = dec(dec > hich) - range;disp('good decrypt');decrypt = char(dec)

Page 300: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

String Functions

num2str(a,n) Converts a number to its numerical representation with n decimal places

disp(...) Displays matrix or textfprintf(...) Prints formatted informationinput(...) Prompts the user to enter a valuesscanf(...) Formats input conversionsprintf(...) Formats a string resultstrcmp(s1, s2) Compares two strings; returns true if equalstrcmpi(s1, s2) Compares two strings without regard to

case; returns true if equal

Page 301: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-301

11.1 Plotting in General The fundamental container for plotting is a

MATLAB figure Simple plot of x versus y: plot(x, y) Plot enhancements

axis, colormap, grid on, hold on, legend, shading, text, title, view, xlabel, ylabel, zlabel

Use subplot(r, c, n) for multiple plots on one figure

Page 302: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exercise: Try this simple graph

octave:38> x=0:0.05:10*pi;

octave:39> y=exp(-1.*x).*sin(x);

octave:40> plot(x,y)

Don’t forget the semi-colons!

Page 303: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-303

Plot Enhancements1. clf

2. x = -2*pi:.05:2*pi;

3. subplot(2,3,1)

4. plot(x, sin(x))

5. title('1 - sin(x)');

6. subplot(2,3,2)

7. plot(x, cos(x))

8. title('2 - cos(x)');

9. subplot(2,3,3)

10. plot(x, tan(x))

11. title('3 - tan(x)');

12. subplot(2,3,4)

13. plot(x, x.^2)

14. title('4 - x^2');

15. subplot(2,3,5)

16. plot(x, sqrt(x))

17. title('5 - sqrt(x)');

18. subplot(2,3,6)

19. plot(x, exp(x))

20. title('4 - e^x');

Page 304: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-304

11.2 2-D Plotting Basic function for 2-D plots: plot(x, y, str)

x and y are vectors of the same length str specifies optional line color & style control

Plot options subplot, axis, hold on, title

Parametric plotting Allows the variables on each axis to be dependent on

a separate, independent variable

Page 305: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-305

Multiple 2-D Plots

Page 306: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-306

Special 2-D Effects% Code for the first three plots

1. clear

2. clc

3. close all

4. x = linspace(0, 2*pi);

5. subplot(2, 3, 1)

6. plot(x, sin(x))

7. axis([0 2*pi -0.5 0.5])

8. title('Changing Data Range on an Axis')

9. subplot(2, 3, 2)

10. plot(x, sin(x))

11. hold on

12. plot(x, cos(x))

13. axis tight

14. title('Multiple Plots with hold on')

15. subplot(2, 3, 3)

16. plot(x, sin(x), 'ó')

17. hold on

18. plot(x, cos(x), 'r:')

19. axis tight

20. title('Multiple Plots with hold on')

Page 307: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-307

Transforming a Circle to an Airfoil

Page 308: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-308

11.3 3-D Plotting 2-D plots in MATLAB are actually 3-D plots (select

the Rotate 3D icon on the tool bar) Linear 3-D Plots

Extend 2-D plots by adding a set of z values Use plot3(x, y, z, str)

Linear Parametric 3-D Plots Allow variables on each axis to be dependent on a

separate, independent variable Other plot capabilities

bar3(x, y), barh3(x, y), pie3(y)

Page 309: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exercise: Try this simple 3-D plot

octave:38> x=0:0.05:10*pi;octave:39> y=exp(-1.*x).*sin(x);octave:41> z=cos(x);octave:46> plot3(x,y,z)

Page 310: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-310

3-D View of a 2-D Plot

Page 311: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-311

3-D Line plots

Page 312: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-312

Parametric Line Plots

Page 313: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-313

11.4 Surface Plots Production of images based on mapping a 2-D

surface create a plaid Basic capabilities

meshgrid(x, y): compute mappings for the 3-D coordinates

mesh(xx, yy, zz): plots the surface as white facets outlined by colored lines

surf(xx, yy, zz): plots the surface as colored facets outlined by black lines

Page 314: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exercise: Try this Surface Example

facets = 120; len = 2; radius = 1;thr = linspace(0,2*pi,facets);xr = [0 len];[x th] = meshgrid(xr, thr );y = radius * cos(th);z = radius * sin(th);surf(x,y,z);

Page 315: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-315

Designing a Cube Surface plot

Page 316: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-316

Cube Surfaces

Page 317: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-317

Simple Surface Plot

Page 318: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-318

Compound Surface Plot

Page 319: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-319

Using External Illumination

Page 320: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-320

Designing a Cylinder Plot

Page 321: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-321

Cylinder Plot

Page 322: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-322

Sphere Plot

Page 323: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Bodies of Rotation Created by rotating a linear curve about a

specified axis i.e. rotate z = f(x) about the x or z axes (not y)

Rotate z = f(x) about the x-axis y = r cos(θ), z = r sin(θ)

Rotate z = f(x) about the z-axis x = r cos(θ), y = r sin(θ)

1-323

Page 324: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-324

Rotating About the X Axis

Page 325: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-325

Rotating About the Z Axis

Page 326: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-326

Bodies of Rotation

Page 327: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-327

Rotating Arbitrary Shapes

Page 328: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

General Rotation TechniquesRotating about an Arbitrary Axis

1-328

• Calculate the matrix that will place your axis of rotation along the x-axis

• Transform x and z with that rotation

• Rotate the results about the x-axis

• Invert the transformation on the resulting surface

Page 329: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-329

A Solid Disk

Page 330: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

1-330

A Klein Bottle

Page 331: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Reading Excel Data

octave:51> help csv2cellcsv2cell is the dynamically-linked function from the file/usr/lib/octave/site/oct/api-v13/i686-pc-cygwin/octave-forge/csv2cell.oct

-- Function File: C = csv2cell (FILE) -- Function File: C = csv2cell (FILE, SEP) -- Function File: C = csv2cell (FILE, SEP, PROT) Read a CSV (Comma Separated Values) file and convert it into a cell. SEP changes the character used to separate two fields. By default, two fields are expected to be separated by a coma (`,'). PROT changes the character used to protect a string. By default it's a double quote (`"').

MATLAB actually has very nice csvread and csvwrite. Octave…doesn’t

Page 332: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Reading into Cellsoctave:61> cells=csv2cell("Names.csv")cells =

{ [1,1] = Name [2,1] = Mark [3,1] = Barb [4,1] = Matthew [5,1] = Katherine [6,1] = Jennifer [1,2] = Gender [2,2] = 1 [3,2] = 2 [4,2] = 1 [5,2] = 2 [6,2] = 2 [1,3] = Age [2,3] = 44 [3,3] = 45 [4,3] = 15 [5,3] = 12 [6,3] = 9}

Page 333: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Another way to read Excel Data

octave:60> help dlmreaddlmread is the dynamically-linked function from the file/usr/lib/octave/site/oct/api-v13/i686-pc-cygwin/octave-forge/dlmread.oct

-- Loadable Function: DATA = dlmread (FILE) -- Loadable Function: DATA = dlmread (FILE,SEP) -- Loadable Function: DATA = dlmread (FILE,SEP,R0,C0) -- Loadable Function: DATA = dlmread (FILE,SEP,RANGE) Read the matrix DATA from a text file The RANGE parameter must

be a 4 element vector containing the upper left and lower right corner [R0,C0,R1,C1] The lowest index value is zero.

Page 334: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Using dlmread

octave:62> data = dlmread("Names.csv",",")

data =

NA 0.00000 0.00000 0.00000

0.00000 1.00000 44.00000 0.00000

0.00000 2.00000 45.00000 0.00000

0.00000 1.00000 15.00000 0.00000

0.00000 2.00000 12.00000 0.00000

0.00000 2.00000 9.00000 0.00000

Page 335: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

How do we get just the data we want?

octave:79> [rows cols] = size(data)rows = 6cols = 4octave:80> col3 = [zeros(rows,1) zeros(rows,1) ones(rows,1)

zeros(rows,1)]col3 =

0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0

Page 336: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Can’t use 0’s and 1’s – must be true/false

octave:88> col3==1ans = 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0

octave:89> index = col3==1index = 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0

octave:90> data(index)ans = 0 44 45 15 12 9

Page 337: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

But that first row is just from the header!octave:93> ages(2:1:rows)

ans =

44

45

15

12

9

Page 338: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exercise

Study the world! Country Country code Year (2004) Population in

thousands Exchange rate

with US$ Per capita

GDP

Page 339: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Getting you started

octave:95> pops=dlmread("pops2004.csv",",");

octave:96> [rows,cols]=size(pops)

rows = 189

cols = 11

octave:97> col4=[zeros(rows,1) zeros(rows,1) zeros(rows,1), ones(rows,1) zeros(rows,1) zeros(rows,1) zeros(rows,1) zeros(rows,1) zeros(rows,1) zeros(rows,1) zeros(rows,1)];

popdata = pops(col4==1);

octave:99> x=1:1:rows;

octave:100> plot(x,popdata)

Alternatively:

col4 = popdata(:,4)

Page 340: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Country populations in 2004

Page 341: First Courses Workshop Day 4 Mark Guzdial College of Computing Georgia Institute of Technology guzdial@cc.gatech.edu mark.guzdial

Exercise Questions

If you sort the data (hint: “help sort”), what does the curve of world populations look like? Are all populations equally likely?

How about the curve of exchange rates or per capita GDP?

What’s the highest CGDP? What’s the lowest? What’s the highest exchange rate? What’s the

lowest?