Lab 5 – Test Review Lab

advertisement
Lab 5 – Test Review Lab
Date: September 20, 2011
Assignment Due Date: September 27, 2011
Goal: In this lab we will reinforce concepts that you have learned so far in the lecture. Many of the
concepts will be on the exam so it is recommended that you are very thorough and careful in going
through these exercises. Specifically, we will use R to explore unit conversions, plot trig functions, plot
and explore exponential functions, plot solutions of discrete time dynamical systems, and understand
the difference between cobweb plots and solution plots.
Unit Conversions
As you have probably realized, it is often necessary to convert between units when modeling. Let’s
write a simple function to see how we can use R to help us convert years to seconds. Take a minute and
think about how you might do this.
1 year = 365 days
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds
Using these it is now simple to write code that does these conversions for us. First we will write a code
to convert from years to days.
YearsToDays = function(y){y*365}
In the function written above the input is a number of years and the output is the equivalent number of
days. Try out a few to make sure it works.
YearsToDays(1) = 365
YearsToDays(2) = 730
Now we will write the more complicated function, YearsToSeconds(y).
YearsToSeconds = function(y){y*365*24*60*60}
Why do we multiply these numbers together to convert?
How many seconds has a ten year old lived on their exact tenth birthday?
How would you write a function to reverse this and calculate SecondsToYears?
Now write a code to change units between oranges/second to bananas/minute given the following.
1 orange = 3 bananas
1 minute = 60 seconds
MAKE SURE YOUR UNDERSTAND UNIT CONVERSIONS!
Trig Functions
In order to plot sine and cosine functions in R we need to define some important parameters:
average(A), amplitude(B), period(T), and shift( ). Below are the general formulas for sine and cosine.
Define an input vector.
t = seq(from=0,to=2*pi,by=.01)
To start, define your parameters as follows.
A=0
B=0
T = 2*pi
Phi = 0
Now write code to plot the general sine and cosine functions given above. Plot sine in red and cosine in
blue on the same figure. Once you have this done, experiment with different parameters and see how
your plots change. Then answer the following questions.
What is average (A)?
What is amplitude (B)?
What is period (T)?
What is shift (Phi)?
Exponential Functions
Now let’s look at plots of exponential solutions.
Suppose a bacterial population grows at a rate r and follows this discrete time dynamical system.
As explained in section 1.7 a general solution can be written in terms of r and the initial population size,
b0, as follows.
Use the following definitions for now.
r=2
b0 = 1
Define an input vector.
t = 0:20
Define your solution function.
B = function(t){b0*exp(log(r, base = exp(1))*t)}
NOTE: log(x, base = exp(1)) is the way you write ln(x) in R.
Now plot the solution.
plot(t,B(t))
This is solution shows exponential growth as each bacteria replicates in each time step and none of the
bacteria die.
What should we get if we plot the natural log of the solution? Why?
plot(t,log(B(t),base=exp(1)))
What is the slope of this line? Algebraically calculate the natural log of the general solution,
.
Suppose that B(t) is the solution to a particular system and that c(t) = ln(B(t)). We know c(t) = .25t + 1.
Plot the solution B(t). What is the growth rate r? What is the initial condition B0?
HINT: Write code to define the function c(t). Write another function B(t) which is exp(c(t)). Plot B(t) and
think about the slope and what B(0) mean.
Plotting Solutions Using Updating Functions
You have now learned to write code to simulate discrete time dynamical systems using loops. We will
extend this idea in order to plot the solutions you get from the simulations. Last week we wrote code
that redefined the solution value at each time step. We used print() to see the values R was computing.
Our codes looked something like this.
D = 250
M=0
T = 20
update = function(M){.5*M + D}
for (i in 1:T){
M = update(M)
print(M)
}
When we run this code we are able to see the value of M at each time step. However, R has only saved
the final value of M since we have redefined it at each step. We will now learn how to save every value
of M which will allow us to plot solutions easily.
Before changing our code to simulate we must learn a bit more about how to use vectors in R. Let’s
define a new vector P.
P = c(0,2,4,6)
We get an error here because we redefined what c meant earlier in the lab. To get rid of this error you
need to type rm(c) into your console. This will clear the variable c so we can use it to combine 0,2,4, and
6 into a new vector.
What is the third value of P? It is easy for us to see that it is 4. R can give us this answer very quickly
which comes in handy for large vectors.
P[3]
R ouputs the number 4.
What if we want to add another element in our vector P? This will be the fifth element in the vector so
we will simply define P[5].
P[5] = 8
Now print the vector P to the console using print(P). As you can see we have now added another
element to our vector. We can redefine any element in P but watch what happens if we now define
P[10].
P[10] = 10
When we look at P in our console, notice that P[6], P[7], P[8], and P[9] are all NA. This means that we
have defined a tenth element but have not yet defined these previous elements. R has saved space for
them but those elements are empty. Be careful of having empty elements in your vectors when doing
computations in R.
We will now use what we just learned about vectors and change our loop above to the following.
M=0
for (i in 1:T){
M[i+1] = update(M[i])
print(M)
}
As you can see, M now is a vector that contains all the values from the previous times. We can now
move print(M) outside the loop because we only need to print all the values once. Do this in your code
now.
Now that we have the values saved as a vector, it is simple to plot the solutions as a function of time.
We need to first define our time vector.
Time = 0:T
plot(Time,M,ann=FALSE)
title(main=”Solution”,xlab=”time”,ylab=”Amount of Amoxicillin (mg)”)
Now let’s define the equilibrium value and plot this as a line on our solution plot.
MEQ = 2*D
EQvec = rep(MEQ,times=T+1) Why do we need T+1 elements here?
lines(Time,EQvec,col=”red”)
Change the dose and rerun your code to plot different solutions for different doses. Also change the
amount of time steps and see how that changes the solution plots.
Now simulate and plot solutions for the following non-linear discrete time system.
Also plot the positive equilibrium value as a line.
Why is this system non-linear? Does the process of simulating the system change because it is nonlinear?
Cobwebs vs. Solutions
For the last part of the lab we will examine the difference between cobweb plots and solution plots.
Before we start looking at specific examples, talk to those around you about what the differences are.
How do you make a cobweb plot? How do you make a solution plot?
We will now look at the same two systems we just plotted solutions for to see how they relate to the
cobweb plots. Copy and paste DiscreteSolve.R from the webpage into a new script. To get this script to
run properly we will first clear all the variables that are currently stored in R. In the console type the
following.
rm(list=ls(all=TRUE)) DON’T FORGET THIS STEP or DiscreteSolve may not work!
Now that you have removed the variables run the DiscreteSolve.R code. This will not give any output or
plots as it is just defining a function for you to use. DO NOT CHANGE THIS SCRIPT! Open a new script of
just use the console for the remaining part of this lab.
Let’s first look at the model for medication use and discuss what DiscreteSolve() does. We will first
define the updating function.
D = 250
update = function(M){.5*M+D}
Now we can use the DiscreteSolve function to see what this system does. DiscreteSolve needs three
inputs from the user. The first argument is the updating function function. The second is the number of
time steps you wish to simulate for. The last is the initial condition. To simulate the antibiotic model for
20 time steps with M=0 as our initial condition we do the following.
DiscreteSolve(update,20,0)
This gives the following.
- Outputs the values for each time step to the console.
- Plots the cobweb plot. The starting value is plotted in green with the ending value in red.
- Plots the solution plot.
With these three tools we should be able to see clearly the differences between cobweb plots and
solution plots. Talk with those around you about the following questions.
- What are the differences in the axes for each plot? Why?
- How do you know if the system has reached equilibrium on the cobweb plot? On the solution
plot?
- How can you tell if the system does not reach equilibrium on the cobweb plot? On the solution
plot?
- What is the process for creating each graph?
Redefine your updating function and run DiscreteSolve again.
update = function(k){2/(1+k)}
DiscreteSolve(update,20,0)
Change your initial condition and your number of time steps and run DiscreteSolve many more times.
Be sure that your answers to the questions above make sense for each time you run the system.
If you understand all the concepts included in this lab, you should be well
prepared for the exam tomorrow. GOOD LUCK!
Download