Professional Documents
Culture Documents
Generating
import java.io.*; // For BufferedWriter
try {
// open the file
reader = new BufferedReader(new FileReader(inputFile));
// loop reading from the file
while ((line = reader.readLine()) != null) {
doubleValue = Double.parseDouble(line);
doubleValue = doubleValue * factor;
key = Math.ceil(doubleValue) / (double) factor;
if (valueMap.containsKey(key)) {
currCount = valueMap.get(key);
currCount++;
valueMap.put(key,currCount);
}
else {
valueMap.put(key,1);
}
}
}
Now, write the counts to a file
for graphing
/**
* Method to output the keys and values in the histogram
* to a file
* @param fileName the name of the file to write to
*/
public void writeFile(String fileName) {
}
/**
* Generate the histogram from the uniform data
*/
public static void genUniform() {
Using it HistogramGenerator histGen = new HistogramGenerator();
double[] keyArray = {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0};
histGen.countValuesForKeys("C:/dsBook/uniform.txt",keyArray);
histGen.writeFile("C:/dsBook/uniformHist.txt");
}
/**
* Method to generate the normal histogram
*/
public static void genNormal() {
HistogramGenerator histGen = new HistogramGenerator();
double[] keyArray = {-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3,
-0.2, -0.1,0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0};
histGen.countValuesForKeys("C:/dsBook/normal.txt",keyArray);
histGen.writeFile("C:/dsBook/normalHist.txt");
}
How do we view a distribution?
A Histogram
Load the values into a Spreadsheet,
Then graph the result
A uniform distribution
A Uniform Distribution
Frequency
70
60
50
40
Frequency
30
20
10
0
2
8
0
1
0.
0.
0.
0.
A Normal
Distribution
// Fill it with 500 numbers between -1.0 and 1.0, normally distributed
for (int i=0; i < 500; i++){
try{
output.write("\t"+rng.nextGaussian());
output.newLine();
} catch (Exception ex) {
System.out.println("Couldn't write the data!");
System.out.println(ex.getMessage());
}
}
Again, in a Spreadsheet
Graphing the normal distribution
Frequency
30
25
20
15 Frequency
10
5 The end aren’t
actually high—
0 the tails go
6 2 8 4 further.
-2 . . . . 0
0.
4
0.
8
1.
2
1.
6 2
-1 -1 -0 -0
How do we shift the distribution
where we want it?
// Fill it with 500 numbers with a mean of 5.0 and a
//larger spread, normally distributed
for (int i=0; i < 500; i++){
try{
output.write("\t"+((range * rng.nextGaussian())+mean));
output.newLine();
} catch (Exception ex) {
System.out.println("Couldn't write the data!");
System.out.println(ex.getMessage());
}
}
Multiply the random nextGaussian()
by the range you want, then add the
mean to shift it where you want it.
A new normal distribution
Frequency
18
16
14
12
10
Frequency
8
6
4
2
0
-2
-1
10
-1.5
-0.5
0.5
1.5
2.5
3.5
4.5
5.5
6.5
7.5
8.5
9.5
Key idea:
Ordering Events by Time
Straightening time
• Inserting it into the right place
• Sorting it afterwards
We’ll actually do these in reverse order:
• We’ll add a new event, then sort it.
• Then we’ll insert it into the right place.
public class EventQueueExercisor {
public static void main(String[] args){
// Make an EventQueue
Exercising
EventQueue queue = new EventQueue();
/**
* EventQueue
* It's called an event "queue," but it's not really.
* Instead, it's a list (could be an array, could be a linked list)
* that always keeps its elements in time sorted order.
* When you get the nextEvent, you KNOW that it's the one
* with the lowest time in the EventQueue
**/
public class EventQueue {
private LinkedList elements;
/// Constructor
public EventQueue(){
elements = new LinkedList();
}
Mostly, it’s a queue
public SimEvent peek(){
return (SimEvent) elements.getFirst();}
Add 3 to right
But can’t
have 3
below 10!
Final
And can’t have 5
version!
above 3
Java’s PriorityQueue does this!
The Java class PriorityQueue already
implements a min-heap.
Our third option is just to use the
PriorityQueue for the EventQueue.
• But now you know what the options are and
how they work.
Finally: A Discrete Event
Simulation
Now, we can assemble queues, different
kinds of random, and a sorted
EventQueue to create a discrete event
simulation.
Running a DESimulation
Welcome to DrJava.
> FactorySimulation fs = new
FactorySimulation();
> fs.openFrames("D:/temp/");
> fs.run(25.0)
What we see (not much)
The detail tells the story
Time: 1.7078547183397625 Distributor: 0 Arrived at warehouse
Time: 1.7078547183397625 Distributor: 0 is blocking
>>> Timestep: 1
Time: 1.727166341118611 Distributor: 3 Arrived at warehouse
Time: 1.727166341118611 Distributor: 3 is blocking
>>> Timestep: 1
Notice that
Time: 1.8778754913001443 Distributor: 4 Arrived at warehouse
Time: 1.8778754913001443 Distributor: 4 is blocking time 2 never
>>> Timestep: 1 occurs!
Time: 1.889475045031698 Distributor: 2 Arrived at warehouse
Time: 1.889475045031698 Distributor: 2 is blocking
>>> Timestep: 1
Time: 3.064560375192933 Distributor: 1 Arrived at warehouse
Time: 3.064560375192933 Distributor: 1 is blocking
>>> Timestep: 3
Time: 3.444420374970288 Truck: 2 Arrived at warehouse with load 13
Time: 3.444420374970288 Distributor: 0 unblocked!
Time: 3.444420374970288 Distributor: 0 Gathered product for orders of 11
>>> Timestep: 3
Time: 3.8869697922832698 Truck: 0 Arrived at warehouse with load 18
Time: 3.8869697922832698 Distributor: 3 unblocked!
Time: 3.8869697922832698 Distributor: 3 Gathered product for orders of 12
>>> Timestep: 3
What questions we can answer
How long do distributors wait?
• Subtract the time that they unblock from the time that
they block
How much product sits in the warehouse?
• At each time a distributor leaves, figure out how much
is left in the warehouse.
How long does the line get at the warehouse?
• At each block, count the size of the queue.
Can we move more product by having more
distributors or more trucks?
• Try it!
How DESimulation works
Turtle
LinkedList
-heading * +frames FrameSequence
-XPos
-YPos
+show()
+forward() 1
+replay()
+turn() 1 #agents
+setColor()
Agent -world World
+setPenDown() Simulation
#speed
1 #output
+init() 1 +setPicture()
+getAgents()
+die()
*
#simulation +add() 1
+getClosest()
+remove()
+countInRange() EventQueue
+openFrames()
+act() *
1 +setUp()
*
+openFile() -events +peek()
Queue +run() +add()
+endStep() +pop()
-blocked +lineForFile()
+push() 1 +size()
+closeFile() +empty()
+peek()
+pop() 1 +insertInOrder()
+empty() * +sort()
DEAgent +size()
-blocked Resource
+isBlocked() -amount
+isReady()
+amountAvailable() DESimluation
+validTime()
+consume()
+waitFor() -now
+add()
+unblocked() +getTime() *
+addToList()
+processEvent() +addEvent()
+log()
+run()
FactorySimulation: Extend a few
classes
Turtle
LinkedList
-heading * +frames FrameSequence
-XPos
-YPos
+show()
+forward() 1
+replay()
+turn() 1 #agents
+setColor()
Agent -world World
+setPenDown() Simulation
#speed
1 #output
+init() 1 +setPicture()
+getAgents()
+die()
*
#simulation +add() 1
+getClosest()
+remove()
+countInRange() EventQueue
+openFrames()
+act() *
1 +setUp()
*
Queue +openFile() -events +peek()
+run() +add()
-blocked +endStep() +pop()
+push() +lineForFile()
DEAgent 1 +size()
+peek() * +closeFile() +empty()
-blocked +pop() 1
+insertInOrder()
+isBlocked() +empty()
Resource +sort()
+isReady() +size()
+validTime() -amount
DESimluation
+waitFor() +amountAvailable()
+unblocked() +consume() -now
+processEvent() +add() +getTime() *
+addToList() +addEvent()
+log()
Distributor +run()
Truck -amountOrdered
/** What is the event? We'll use integers to represent the meaning
* of the event -- the "message" of the event.
* Each agent will know the meaning of the integer for themselves.
**/
public int message;
DEAgent: Process events, block
if needed
DEAgents define the constants for messages:
What will be the main events for this agent?
If the agent needs a resource, it asks to see if
it’s available, and if not, it blocks itself.
It will be told to unblock when it’s ready.
Agents are responsible for scheduling their
OWN next event!
An Example: A Truck
/**
* Truck -- delivers product from Factory
* to Warehouse.
**/
public class Truck extends DEAgent {
if (!blocked.empty()){
// Ask the next Agent in the queue if it can be unblocked
DEAgent topOne = (DEAgent) blocked.peek();
// Is it ready to run given this resource?
if (topOne.isReady(this)) {
// Remove it from the queue
topOne = (DEAgent) blocked.pop();
// And tell it it’s unblocked
topOne.unblocked(this);
}
}
}
An example blocking agent:
Distributor
/**
* Distributor -- takes orders from Market to Warehouse,
* fills them, and returns with product.
**/
public class Distributor extends DEAgent {
/**
* Accessor for factory
**/
public FactoryProduct getFactory(){return factory;}
Setting up the Factory
Simulation
public void setUp(){
// Let the world be setup
super.setUp();
// Give the world a reasonable background
FileChooser.setMediaPath("D:/cs1316/MediaSources/");
world.setPicture(new Picture(
FileChooser.getMediaPath("EconomyBackground.jpg")));