Introduction to Simulations CS1316: Representing Structure and Behavior.

85
Introduction to Simulations CS1316: Representing Structure and Behavior

Transcript of Introduction to Simulations CS1316: Representing Structure and Behavior.

Page 1: Introduction to Simulations CS1316: Representing Structure and Behavior.

Introduction to Simulations

CS1316: Representing Structure and Behavior

Page 2: Introduction to Simulations CS1316: Representing Structure and Behavior.

Story What’s a simulation? Why do we simulate?

• Discrete vs. Continuous• Resources

Building software to be modifiable: Software Engineering• Building models out of objects: aggregation, generalizing and

specializing Continuous Simulations

• Predatory-prey: Wolves and Deer• Changing our simulation• Creating hungry wolves• Other options: Hungry deer? Deer sex? Wolf sex?

How do we compare simulations?• Creating text files

Page 3: Introduction to Simulations CS1316: Representing Structure and Behavior.

Simulations “A simulation is a representation of a system of objects in

a real or fantasy world.The purpose of creating a computer simulation is to provide a framework in which to understand the simulated situation, for example, to understand the behavior of a waiting line, the workload of clerks, or the timeliness of service to customers.A computer simulation makes it possible to collect statistics about these situations, and to test out new ideas about their organization.”• Adele Goldberg & David Robson, Smalltalk-80: The

Language and Its Implementation (Addison-Wesley, 1989)

Page 4: Introduction to Simulations CS1316: Representing Structure and Behavior.

Simulations and Objects

Object-oriented programming was invented, in part, to make simulations easier to build!

The characteristics of objects make them more like real world objects, e.g.,• Each thing knows some stuff and knows how to do

some stuff.

• Objects get things done by asking each other to do things.

• Your internals are private, unless you want to make them otherwise.

Page 5: Introduction to Simulations CS1316: Representing Structure and Behavior.

Continuous vs. Discrete Simulations

Two main kinds of simulations in the world.

Continuous: Each moment of time is simulated.• When every moment counts.

Discrete: Skip to the important moments.• Want to simulate 100 years?

Page 6: Introduction to Simulations CS1316: Representing Structure and Behavior.

Resources Resources are points of coordination in a

simulation.• Examples: A cashier, a library book, a parking space

on a ferry, a jelly bean. Some resources are fixed and others are

produced and consumed. Some resources are renewable and shared. Others are coordinated.

• Example: For a surgeon to do a surgery, the patient must meet the surgeon at the operating table (the resource)

Page 7: Introduction to Simulations CS1316: Representing Structure and Behavior.

When an object has to wait…

What happens if you (or your proxy object) need a resource and it’s not available?• You wait in a queue

• A list that is first-in-first-out (FIFO)

Page 8: Introduction to Simulations CS1316: Representing Structure and Behavior.

A simulation is an executed model

Setting up a simulation is a process of modeling the world (real or fantasy) to be simulated.

That model is realized in terms of objects. We want our model to:

• Reflect the world.

• Be easy to extend and change. Some of our modeling techniques:

• Aggregation

• Generalization and specialization

Page 9: Introduction to Simulations CS1316: Representing Structure and Behavior.

Aggregation

Some objects are made up of other objects.• Cars have engines

• People have livers and lungs• These internal things are objects, too!

• Livers don’t directly mess with the innards of lungs!

We call this aggregation• Putting references to some objects inside of

other objects.

Page 10: Introduction to Simulations CS1316: Representing Structure and Behavior.

Generalization and Specialization

There are general and specialized forms of real world objects.• Cells are biological objects that have membranes and

a nucleus and mitochondria and…

• Blood, lung, and liver cells are all cells but have specialized functions.

The superclass-subclass relationship is a way of modeling general forms of objects and specialized forms of objects

Page 11: Introduction to Simulations CS1316: Representing Structure and Behavior.

Making it concrete:Wolves eating deer

Page 12: Introduction to Simulations CS1316: Representing Structure and Behavior.

Running the simulationWelcome to DrJava.> WolfDeerSimulation wds = new WolfDeerSimulation()> wds.run()>>> Timestep: 0Wolves left: 5Deer left: 20>>> Timestep: 1Wolves left: 5Deer left: 20<SIGH!> A deer died...>>> Timestep: 2Wolves left: 5Deer left: 19>>> Timestep: 3Wolves left: 5Deer left: 19<SIGH!> A deer died...>>> Timestep: 4Wolves left: 5Deer left: 18

Page 13: Introduction to Simulations CS1316: Representing Structure and Behavior.

An Example Simulation

The WolfDeerSimulation is a continuous simulation.• Each moment in time is simulated.

It has no resources. It is a predator-prey simulation

• A common real world (ecological) situation.

• There are parameters to change to explore under what conditions predators and prey survive and in what numbers.

Page 14: Introduction to Simulations CS1316: Representing Structure and Behavior.

The Model of this SimulationWolfDeerSimulation

Knows the list of wolves and deer

KnowsHow to run() each moment in time

AgentNode

Knows its turtle (agent)

KnowsHow to get/set agent, to remove an agent

Wolf

KnowsHow to act(), and to find the closest deer.

Deer

KnowsHow to act() and die

TurtleLLNode

Page 15: Introduction to Simulations CS1316: Representing Structure and Behavior.

Complicated Set of Relationships in this Model

Wolf and Deer are kinds of Turtle• Specializations of Turtle

AgentNode is a kind of LLNode AgentNodes each have one Turtle (Wolf or

Deer) inside it. WolfDeerSimulation has two AgentNodes for

the lists of live wolves and deer. Each Wolf and Deer knows what simulation its

in.

Page 16: Introduction to Simulations CS1316: Representing Structure and Behavior.

A UML Class Diagram

+run()

-wolves-deer

WolfDeerSimulation

+setAgent()+getAgent()

-myTurtle

AgentNode

+getNext()+remove()+count()+add()

-next

LLNode

+act()+getClosest()

Wolf

Turtle

+act()+die()

Deer

*-myTurtle1

*

-wolves1

*

-deer

1

-mySim

1

*

-mySim1

*

Page 17: Introduction to Simulations CS1316: Representing Structure and Behavior.

Unified Modeling Language (UML)

This is a UML class diagram.• A graphical notation for describing the

relationships between classes in a model. UML is a standard that describes several

different kinds of diagrams.• Collaboration diagrams: How objects work

together and how they call on one another.

• Sequence diagrams: What the order of events are in an object system.

Page 18: Introduction to Simulations CS1316: Representing Structure and Behavior.

A class in a UML class diagram

Name of the class Instance variables

or fields: What the class instances know

Operations or methods: What the instances know how

+run()

-wolves-deer

WolfDeerSimulation

Page 19: Introduction to Simulations CS1316: Representing Structure and Behavior.

Generalization-specialization relationships

Turtle

+act()+die()

Deer

A Deer is a subclass of Turtle: It’s a specialization of Turtle

Page 20: Introduction to Simulations CS1316: Representing Structure and Behavior.

Associations

WolfDeerSimulation has twoAgentNodes in it: One to represent wolves and one to represent deer.

AgentNodes don’t know their simulation

+run()

-wolves-deer

WolfDeerSimulation

+setAgent()+getAgent()

-myTurtle

AgentNode

*

-wolves1

*

-deer

1

Page 21: Introduction to Simulations CS1316: Representing Structure and Behavior.

A Class Diagram describes the Model, without the Code

+run()

-wolves-deer

WolfDeerSimulation

+setAgent()+getAgent()

-myTurtle

AgentNode

+getNext()+remove()+count()+add()

-next

LLNode

+act()+getClosest()

Wolf

Turtle

+act()+die()

Deer

*-myTurtle1

*

-wolves1

*

-deer

1

-mySim

1

*

-mySim1

*

Page 22: Introduction to Simulations CS1316: Representing Structure and Behavior.

WolfDeerSimulation

public class WolfDeerSimulation { /* Linked lists for tracking wolves and deer */ private AgentNode wolves; private AgentNode deer; /** Accessors for wolves and deer */ public AgentNode getWolves(){return wolves;} public AgentNode getDeer(){return deer;}

Why private?

Only the simulation should know its wolves and deer.

Page 23: Introduction to Simulations CS1316: Representing Structure and Behavior.

The main run() method public void run() { World w = new World(); w.setAutoRepaint(false); // Start the lists wolves = new AgentNode(); deer = new AgentNode(); // create some deer int numDeer = 20; for (int i = 0; i < numDeer; i++) { deer.add(new AgentNode(new Deer(w,this))); }

We want to control when the world updates itself.

AgentNodes contain the Deer

Page 24: Introduction to Simulations CS1316: Representing Structure and Behavior.

Head and Rest

Wolves and deer are AgentNodes…but the real content starts at getNext().

We call this the head of the list.• It’s a placeholder.

We call the rest the rest or body of the list.• This makes it possible to remove a node, even if it’s the first

one in the list.

Head

getNext:

Rest

getNext:

wolves

Rest

getNext:

Rest

getNext:

Page 25: Introduction to Simulations CS1316: Representing Structure and Behavior.

Make some wolves

// create some wolves

int numWolves = 5;

for (int i = 0; i < numWolves; i++)

{

wolves.add(new AgentNode(new Wolf(w,this)));

}

Page 26: Introduction to Simulations CS1316: Representing Structure and Behavior.

Start our simulation loop // declare a wolf and deer Wolf currentWolf = null; Deer currentDeer = null; AgentNode currentNode = null; // loop for a set number of timesteps (50 here) for (int t = 0; t < 50; t++) { // loop through all the wolves currentNode = (AgentNode) wolves.getNext();

while (currentNode != null) { currentWolf = (Wolf) currentNode.getAgent(); currentWolf.act(); currentNode = (AgentNode) currentNode.getNext(); }

What’s going on here?

It’s our AgentNodes that are in a linked list. Each one of them contains (aggregation!) a Wolf.

Have to pull the Wolf out to get it to act()

Page 27: Introduction to Simulations CS1316: Representing Structure and Behavior.

Give the deer a chance to act

// loop through all the deer currentNode = (AgentNode) deer.getNext();

while (currentNode != null) { currentDeer = (Deer) currentNode.getAgent(); currentDeer.act(); currentNode = (AgentNode) currentNode.getNext(); }

Same unpackaging going on here.

Page 28: Introduction to Simulations CS1316: Representing Structure and Behavior.

Show us what happened // repaint the world to show the movement w.repaint(); // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); System.out.println("Wolves left: "+wolves.getNext().count()); System.out.println("Deer left: "+deer.getNext().count()); // Wait for one second //Thread.sleep(1000); } }

Does the simulation go too fast? Make the thread of execution sleep for 1000 milliseconds

Page 29: Introduction to Simulations CS1316: Representing Structure and Behavior.

Implementing a Wolfimport java.awt.Color;import java.util.Random;import java.util.Iterator;

/** * Class that represents a wolf. The wolf class * tracks all the living wolves with a linked list. * * @author Barb Ericson [email protected] */public class Wolf extends Turtle{ /////////////// fields ////////////////////// /** class constant for the color */ private static final Color grey = new Color(153,153,153);

/** class constant for probability of NOT turning */

protected static final double PROB_OF_STAY = 1/10;

A final is something that won’t change: A constant. It’s used to make code more readable yet easy-to-change.

Private vs. Protected? Use Protected if your subclasses will need to access (new kinds of wolves?)

Constants are typically all-caps

Page 30: Introduction to Simulations CS1316: Representing Structure and Behavior.

More Wolf fields

/** class constant for top speed (max num steps can move in a timestep) */

protected static final int maxSpeed = 60; /** My simulation */ protected WolfDeerSimulation mySim; /** random number generator */ protected static Random randNumGen = new Random();

There is more than one kind of random. Treating it as an object makes it easier to have different kinds later.

maxSpeed should probably be all-caps (or did you want to make it variable? Do wolves get slower as they get hungry?

Page 31: Introduction to Simulations CS1316: Representing Structure and Behavior.

Constructors

////////////////////////////// Constructors //////////////////////// /** * Constructor that takes the model display (the original * position will be randomly assigned) * @param modelDisplayer thing that displays the model * @param mySim my simulation */ public Wolf (ModelDisplay modelDisplayer,WolfDeerSimulation

thisSim) { super(randNumGen.nextInt(modelDisplayer.getWidth()), randNumGen.nextInt(modelDisplayer.getHeight()), modelDisplayer); init(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 mySim my simulation */ public Wolf (int x, int y, ModelDisplay modelDisplayer, WolfDeerSimulation thisSim) { // let the parent constructor handle it super(x,y,modelDisplayer); init(thisSim); }

Remember that a constructor must match its superclass, if you want to use super(). These are like the ones in Turtle.

What’s a ModelDisplay? The abstract superclass of the World.

Page 32: Introduction to Simulations CS1316: Representing Structure and Behavior.

Using a Random:PseudoRandom Number Generator

Page 33: Introduction to Simulations CS1316: Representing Structure and Behavior.

Initialize a Wolf ////////////////// methods ////////////////////////////////////////

/** * Method to initialize the new wolf object */ public void init(WolfDeerSimulation thisSim) { // set the color of this wolf setColor(grey); // turn some random direction this.turn(randNumGen.nextInt(360)); // set my simulation mySim = thisSim; }

Get an integer at most 360

Page 34: Introduction to Simulations CS1316: Representing Structure and Behavior.

Is there a Deer to eat?

public AgentNode getClosest(double distance,AgentNode list) { // get the head of the deer linked list AgentNode head = list; AgentNode curr = head; AgentNode closest = null; Deer thisDeer; double closestDistance = 0; double currDistance = 0; // loop through the linked list looking for the closest deer while (curr != null) { thisDeer = (Deer) curr.getAgent(); currDistance = thisDeer.getDistance(

this.getXPos(),this.getYPos()); if (currDistance < distance) { if (closest == null || currDistance < closestDistance) { closest = curr; closestDistance = currDistance; } } curr = (AgentNode) curr.getNext(); } return closest; }

|| is “OR”

Walk this through in English to see that it’s doing what you think it should.

Page 35: Introduction to Simulations CS1316: Representing Structure and Behavior.

Modeling what a Wolf does /** * 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 some specified distance AgentNode closeDeer = getClosest(30, (AgentNode) mySim.getDeer().getNext()); if (closeDeer != null) { Deer thisDeer = (Deer) closeDeer.getAgent(); this.moveTo(thisDeer.getXPos(), thisDeer.getYPos()); thisDeer.die(); }

getClosest returns an AgentNode, so we have to get the Deer out of it with getAgent()

Why getNext()? Because we need the body of the list, and that’s after the head.

Page 36: Introduction to Simulations CS1316: Representing Structure and Behavior.

If can’t eat, then move else { // 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(maxSpeed)); } }

Get an integer at most 360, or at most maxSpeed

Page 37: Introduction to Simulations CS1316: Representing Structure and Behavior.

Deerimport java.awt.Color;import java.util.Random;

/** * Class that represents a deer. The deer class * tracks all living deer with a linked list. * * @author Barb Ericson [email protected] */public class Deer extends Turtle{ /////////////// fields ////////////////////// /** class constant for the color */ private static final Color brown = new Color(116,64,35); /** class constant for probability of NOT turning */ private static final double PROB_OF_STAY = 1/5;

Page 38: Introduction to Simulations CS1316: Representing Structure and Behavior.

Deer fields (instance variables)

/** class constant for top speed (max num steps can move in a timestep) */

private static final int maxSpeed = 50; /** random number generator */ private static Random randNumGen = new

Random(); /** the simulation I'm in */ private WolfDeerSimulation mySim;

Page 39: Introduction to Simulations CS1316: Representing Structure and Behavior.

DeerConstructors

////////////////////////////// Constructors //////////////////////// /** * Constructor that takes the model display (the original * position will be randomally assigned * @param modelDisplayer thing which will display the model */ public Deer (ModelDisplay modelDisplayer,WolfDeerSimulation

thisSim) { super(randNumGen.nextInt(modelDisplayer.getWidth()), randNumGen.nextInt(modelDisplayer.getHeight()), modelDisplayer); init(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 */ public Deer (int x, int y, ModelDisplay modelDisplayer, WolfDeerSimulation thisSim) { // let the parent constructor handle it super(x,y,modelDisplayer); init(thisSim); }

Nothing new here…

Page 40: Introduction to Simulations CS1316: Representing Structure and Behavior.

Initializing a Deer /** * Method to initialize the new deer object */ public void init(WolfDeerSimulation thisSim) { // set the color of this deer setColor(brown); // turn some random direction this.turn(randNumGen.nextInt(360)); // know my simulation mySim = thisSim; }

Nothing new here…

Page 41: Introduction to Simulations CS1316: Representing Structure and Behavior.

What Deer Do /** * Method to act during a time step * pick a random direction and move some random amount up to top speed */ public void act() { // 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(maxSpeed)); }

Nothing new here…

Page 42: Introduction to Simulations CS1316: Representing Structure and Behavior.

When Deer Die /** * Method that handles when a deer dies */ public void die() { // Leave a mark on the world where I died... this.setBodyColor(Color.red); // Remove me from the "live" list mySim.getDeer().remove(this); // ask the model display to remove this // Think of this as "ask the viewable world to remove this turtle" //getModelDisplay().remove(this); System.out.println("<SIGH!> A deer died..."); }

If you want the body and its trail to disappear…

Why don’t we have to say getNext() before the remove()?

Page 43: Introduction to Simulations CS1316: Representing Structure and Behavior.

AgentNodes

AgentNodes contain Turtles• That’s aggregation

It’s a subclass of LLNode• It’s a specialization of LLNode

Page 44: Introduction to Simulations CS1316: Representing Structure and Behavior.

AgentNode implementation

/** * Class to implement a linked list of Turtle-like characters. * (Maybe "agents"?) **/public class AgentNode extends LLNode { /** * The Turtle being held **/ private Turtle myTurtle;

Page 45: Introduction to Simulations CS1316: Representing Structure and Behavior.

AgentNode constructors /** Two constructors: One for creating the head of the list * , with no agent **/ public AgentNode() {super();} /** * One constructor for creating a node with an agent **/ public AgentNode(Turtle agent){ super(); this.setAgent(agent); }

Page 46: Introduction to Simulations CS1316: Representing Structure and Behavior.

AgentNode getter/setter

/** * Setter for the turtle **/ public void setAgent(Turtle agent){ myTurtle = agent; } /** * Getter for the turtle **/ public Turtle getAgent(){return myTurtle;}

Page 47: Introduction to Simulations CS1316: Representing Structure and Behavior.

AgentNode: Remove node where Turtle is found /** * Remove the node where this turtle is found. **/ public void remove(Turtle myTurtle) { // Assume we're calling on the head AgentNode head = this; AgentNode current = (AgentNode) this.getNext(); while (current != null) { if (current.getAgent() == myTurtle) {// If found the turtle, remove that node head.remove(current); } current = (AgentNode) current.getNext(); } }

It’s just like other linked list removes, but now we’re looking for the node that contains the input turtle.

Page 48: Introduction to Simulations CS1316: Representing Structure and Behavior.

Think about it…

What if AgentNodes contained Objects?• Object is a class that is the superclass of all

classes (even if not explicitly extended).

• AgentNodes that contain Objects could be general linked lists that contain anything

• Just cast things as you need them as you pull them out.

Page 49: Introduction to Simulations CS1316: Representing Structure and Behavior.

Back to the simulation:What might we change?

Wolves that aren’t always hungry? Having wolves that chase deer?

Have deer run from wolves? And how do we look at the results?

We’ll deal with hunger first, then with comparing, then with running towards/away.

Page 50: Introduction to Simulations CS1316: Representing Structure and Behavior.

Creating a Hungry Wolf/** * A class that extends the Wolf to have a Hunger level. * Wolves only eat when they're hungry **/public class HungryWolf extends Wolf { /** * Number of cycles before I'll eat again **/ private int satisfied; /** class constant for number of turns before hungry */ private static final int MAX_SATISFIED = 3;

Page 51: Introduction to Simulations CS1316: Representing Structure and Behavior.

Need tomatch

/** * Constructor that takes the model display (the original * position will be randomly assigned) * @param modelDisplayer thing that displays the model * @param mySim my simulation */ public HungryWolf (ModelDisplay

modelDisplayer,WolfDeerSimulation thisSim) { super(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 mySim my simulation */ public HungryWolf (int x, int y, ModelDisplay

modelDisplayer, WolfDeerSimulation thisSim) { // let the parent constructor handle it super(x,y,modelDisplayer,thisSim); }

Page 52: Introduction to Simulations CS1316: Representing Structure and Behavior.

Initializing a HungryWolf

/** * Method to initialize the hungry wolf object */ public void init(WolfDeerSimulation thisSim) { super.init(thisSim); satisfied = MAX_SATISFIED; }

Page 53: Introduction to Simulations CS1316: Representing Structure and Behavior.

What a HungryWolf does /** * Method to act during a time step * pick a random direction and move some random amount up to top speed */ public void act() { // Decrease satisfied time, until hungry again satisfied--; // get the closest deer within some specified distance AgentNode closeDeer = getClosest(30, (AgentNode) mySim.getDeer().getNext()); if (closeDeer != null) { // Even if deer close, only eat it if you're hungry. if (satisfied <= 0) {Deer thisDeer = (Deer) closeDeer.getAgent(); this.moveTo(thisDeer.getXPos(), thisDeer.getYPos()); thisDeer.die(); satisfied = MAX_SATISFIED;

}}

If there is a Deer near, then check if you’re hungry, and only then—eat and get “full”

Page 54: Introduction to Simulations CS1316: Representing Structure and Behavior.

And if no Deer are near… else { // if the randome number is > prob of turning then turn if (randNumGen.nextFloat() > PROB_OF_TURN) { this.turn(randNumGen.nextInt(360)); } // go forward some random amount forward(randNumGen.nextInt(maxSpeed));

} }

Nothing new here…

Page 55: Introduction to Simulations CS1316: Representing Structure and Behavior.

Changing the Simulation to make HungryWolves (in run())

// create some wolves

int numWolves = 5;

for (int i = 0; i < numWolves; i++)

{

wolves.add(new AgentNode(new HungryWolf(w,this)));

}Everything else just works, because HungryWolf is a kind of Wolf

Page 56: Introduction to Simulations CS1316: Representing Structure and Behavior.

Writing to a Text File

We have to create a stream that allows us access to a file.

We’re going to want to write strings to it. We’re going to have to handle things

going wrong—exceptional events like the filename being wrong or the disk failing.

Here’s how…

Page 57: Introduction to Simulations CS1316: Representing Structure and Behavior.

Input and Output Streams - java.io

Java handles input and output through sequential streams of bits

Programs can read from a stream or write to a stream

Sourceor

Destination

Program100110

ArrayString

File Byte DataCharacter Data

Page 58: Introduction to Simulations CS1316: Representing Structure and Behavior.

Standard Input and Output

We have been using System.out.println to print output to a PrintStream (standard output).

System.out.println(“First Name: “ + firstName);

There is also a System.err PrintStream that can be used to write to the standard error output.

System.err.println(“Error: no file name given”);

You can use System.in to read a byte or bytes from an InputStream (standard input).

int numGrades = System.in.read();

Page 59: Introduction to Simulations CS1316: Representing Structure and Behavior.

Chaining Input and Output Classes

Often input or output classes are chained• Passing one type of

input/output class to the constructor for another

One common thing is to chain a processing class with a data sink class• Like a BufferedReader or

BufferedWriter and a FileReader or FileWriter

new BufferedReader(new FileReader(fileName));

Page 60: Introduction to Simulations CS1316: Representing Structure and Behavior.

Exceptions

Exceptions are disruptions in the normal flow of a program. Exception is short for exceptional event.

The programmer is required to handle checked exceptions in Java • like trying to read from a file that doesn’t exist

Run-time exceptions do not have to be handled by the programmer • like trying to invoke a method on a object reference that is

null

• Children of RuntimeException

Page 61: Introduction to Simulations CS1316: Representing Structure and Behavior.

Try and Catch Use a try & catch clause to catch an exception

try {

code that can cause exceptions

} catch (ExceptionClassName varName) {

code to handle the exception

} catch (ExceptionClassName varName) {

code to handle the exception

} You can catch several exceptions

• Make the most general one last

• All exceptions are children of the class Exception

Page 62: Introduction to Simulations CS1316: Representing Structure and Behavior.

Try and Catch: If the file isn’t there…

What if you want to know if a file isn’t found• That you are trying to read from

• If this occurs you might want to use a JFileChooser to let the user pick the file

You also want to handle any other errortry {

code that can cause the exception

} catch (FileNotFoundException ex) {

code to handle when the file isn’t found

} catch (Exception ex) {

code to handle the exception

}

Page 63: Introduction to Simulations CS1316: Representing Structure and Behavior.

Catching Exceptions

A catch clause will catch the given Exception class and any subclasses of it.

So to catch all exceptions use:try {

code that can throw the exception

} catch (Exception e) {System.err.println(“Exception: “ + e.getMessage());

System.err.println(“Stack Trace is:”);

e.printStackTrace();

}

You can create your own exceptions by subclassing Exception or a child of Exception.

You can print the error message and the stack trace (the list of all currently running methods)

Page 64: Introduction to Simulations CS1316: Representing Structure and Behavior.

The optional finally clause

A try and catch statement can have a finally clause• Which will always be executed

• Will happen if no exceptions

• Will happen even if exceptions occurtry {

code that can cause the exception} catch (FileNotFoundException ex) {

code to handle when the file isn’t found} finally {

code to always be executed}

Page 65: Introduction to Simulations CS1316: Representing Structure and Behavior.

Writing to a File

Use a try-catch clause to catch exceptions• Create a buffered writer from a file writer

writer = new BufferedWriter(new FileWriter(fileName));

• Write the datawriter.write(data);

• Close the buffered writer• writer.close();

Page 66: Introduction to Simulations CS1316: Representing Structure and Behavior.

Reading Lines of Character Data Enclose the code in a try and catch clause

• Catch FileNotFoundException if the file doesn’t exist• And you may want to give the user a chance to specify a new

file

• Catch Exception to handle all other errors Create a buffered reader from a file reader for more

efficient reading• File names are relative to the current directory

Loop reading lines from the buffered reader until the line is null• Do something with the data

Close the buffered reader

Page 67: Introduction to Simulations CS1316: Representing Structure and Behavior.

Reading from File Example BufferedReader reader = null; String line = null; // try to read the file try { // create the buffered reader reader = new BufferedReader(new FileReader(fileName)); // loop reading lines till the line is null (end of file) while ((line = reader.readLine()) != null) {

// do something with the line } // close the buffered reader reader.close(); } catch (Exception ex) { // handle exception }

Page 68: Introduction to Simulations CS1316: Representing Structure and Behavior.

Adding an Output File to WolfDeerSimulation

/* A BufferedWriter for writing to */ public BufferedWriter output; /** * Constructor to set output to null **/ public WolfDeerSimulation() { output = null; }

Page 69: Introduction to Simulations CS1316: Representing Structure and Behavior.

Opening the File /** * Open the input file and set the BufferedWriter to speak to it. **/ public void openFile(String filename){ // Try to open the file try { // create a writer output = new BufferedWriter(new FileWriter(filename)); } catch (Exception ex) { System.out.println("Trouble opening the file " + filename); // If any problem, make it null again output = null; } }

Page 70: Introduction to Simulations CS1316: Representing Structure and Behavior.

Changing the time loop // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); System.out.println("Wolves left: "+wolves.getNext().count()); System.out.println("Deer left: "+deer.getNext().count()); // If we have an open file, write the counts to it if (output != null) { // Try it try{ output.write(wolves.getNext().count()+"\t"+deer.getNext().count()); 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; } }

Page 71: Introduction to Simulations CS1316: Representing Structure and Behavior.

After the timing loop

// If we have an open file, close it and null the variable if (output != null){ try{ output.close();} catch (Exception ex) {System.out.println("Something went wrong closing the file");} finally { // No matter what, mark the file as not-there output = null;} }

Page 72: Introduction to Simulations CS1316: Representing Structure and Behavior.

Running the Simulation with a File

Welcome to DrJava.

> WolfDeerSimulation wds = new WolfDeerSimulation();

> wds.openFile("D:/cs1316/wds-run1.txt")

> wds.run();

Page 73: Introduction to Simulations CS1316: Representing Structure and Behavior.

Finding the file in Excel

Page 74: Introduction to Simulations CS1316: Representing Structure and Behavior.

Adding Labels for the Chart

0

5

10

15

20

25

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

Wolves

Deer

Page 75: Introduction to Simulations CS1316: Representing Structure and Behavior.

Making Wolves and Deer Run

What we do:• In Deer, if there is a Wolf within our smelling range,

run in the opposite direction (turn towards, turn 180, move)

• In Wolf, if there is a Deer within our smelling range, run towards it.

• (Stays the same) If the Wolf gets close enough, gobble up the Deer.

• (Stays the same) For both, otherwise, wander aimlessly.

Page 76: Introduction to Simulations CS1316: Representing Structure and Behavior.

New constants for Deer

/** class constant for probability of NOT turning */ private static final double PROB_OF_STAY = 1/5; /** class constant for how far deer can smell */ private static final double SMELL_RANGE = 50; /** class constant for top speed (max num steps can move

in a timestep) */ private static final int maxSpeed = 30;

Page 77: Introduction to Simulations CS1316: Representing Structure and Behavior.

Deer-finding closest Wolf

/** * Method to get the closest wolf within the passed distance * to this deer. We'll search the input list of the kind * of objects to compare to.*/ public AgentNode getClosest(double distance,AgentNode list) { // get the head of the deer linked list AgentNode head = list; AgentNode curr = head; AgentNode closest = null; Wolf thisWolf; double closestDistance = 0; double currDistance = 0; // loop through the linked list looking for the closest deer while (curr != null) { thisWolf = (Wolf) curr.getAgent(); currDistance = thisWolf.getDistance(this.getXPos(),this.getYPos()); if (currDistance < distance) { if (closest == null || currDistance < closestDistance) { closest = curr; closestDistance = currDistance; } } curr = (AgentNode) curr.getNext(); } return closest; }

Strikingly similar to Wolf’s for find Deer, no?

Page 78: Introduction to Simulations CS1316: Representing Structure and Behavior.

Deer new act()

/** * 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 wolf within the smell range AgentNode closeWolf = getClosest(SMELL_RANGE, (AgentNode)

mySim.getWolves().getNext()); if (closeWolf != null) { Wolf thisWolf = (Wolf) closeWolf.getAgent(); // Turn to face the wolf this.turnToFace(thisWolf); // Now directly in the opposite direction this.turn(180); // How far to run? How about half of max speed?? this.forward((int) (maxSpeed/2)); } else { // 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(maxSpeed)); } }

Think about this in terms of the values that can be changed and their relative values.

Does this match the English description we had a few slides back?

Page 79: Introduction to Simulations CS1316: Representing Structure and Behavior.

Wolf Constants

/** class constant for probability of NOT turning */ protected static final double PROB_OF_STAY = 1/10; /** class constant for top speed (max num steps can move

in a timestep) */ protected static final int maxSpeed = 40; /** 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;

Page 80: Introduction to Simulations CS1316: Representing Structure and Behavior.

How Wolf’s smell 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 AgentNode closeDeer = getClosest(SMELL_RANGE, (AgentNode) mySim.getDeer().getNext()); if (closeDeer != null) { Deer thisDeer = (Deer) closeDeer.getAgent(); // Turn torward deer this.turnToFace(thisDeer); // How much to move? How about minimum of maxSpeed // or distance to deer? this.forward((int) Math.min(maxSpeed, thisDeer.getDistance(this.getXPos(),this.getYPos()))); }

Page 81: Introduction to Simulations CS1316: Representing Structure and Behavior.

The rest of normal Wolf actions

// get the closest deer within the attack distance closeDeer = getClosest(ATTACK_RANGE, (AgentNode) mySim.getDeer().getNext()); if (closeDeer != null) { Deer thisDeer = (Deer) closeDeer.getAgent(); this.moveTo(thisDeer.getXPos(), thisDeer.getYPos()); thisDeer.die(); } else // Otherwise, wander aimlessly { // if the randome 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(maxSpeed)); } // end else } // end act()

Page 82: Introduction to Simulations CS1316: Representing Structure and Behavior.

Changes to WolfDeerSimulation…NOTHING!

We have the same interface as we used to have, so nothing changes in WolfDeerSimulation.

Very powerful idea:• If changes to a class keep the interface the

same, then all users of the class don’t have to change at all.

Page 83: Introduction to Simulations CS1316: Representing Structure and Behavior.

Running the new simulationWelcome to DrJava.> WolfDeerSimulation wds = new

WolfDeerSimulation();> wds.openFile("D:/cs1316/wds-

chase.txt")> wds.run();

0

2

4

6

8

10

12

14

16

18

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

Wolves

Deer

Page 84: Introduction to Simulations CS1316: Representing Structure and Behavior.

Explorations

What does the relative speed of Deer and Wolves matter? • Does it matter if Deer go faster? Wolves?

What if Deer and Wolves can smell farther away?• What if one can smell better than the other?

What’s the effect of having more Deer or more Wolves?

What if HungryWolves could starve (say at -10 satisfaction)? Do more deer live?

Page 85: Introduction to Simulations CS1316: Representing Structure and Behavior.

Doing More Simulations

How much code would be in common in every simulation we’d build?• We already have lots of duplication, e.g.,

getClosest.

Goal: Can we make an Agent/Actor class and Simulation class that we’d subclass with very little additional code to create new simulations?