Lab 2: Iterative Vector Modeling - Purdue Physics

Lab 2: Iterative Vector Modeling
Goals
In this lab, you will learn:
• How to model and manipulate vectors in vPython
o vPython’s vector magnitude function mag()
• How to create a loop in vPython
• How to use loops to model motion iteratively in vPython
Remember that a vector is a directional quantity, in that is has both a magnitude and a
direction.
 What is the relationship between a vector and its magnitude and unit vector?
(enter a mathematical relationship)
PART I: Vector Math in vPython
In vPython, we will represent vectors graphically, by treating them as arrows. Remember
that an arrow is a 3D object that vPython natively creates. However, vPython also has a
vector(x,y,z) object. This object is not a 3D object that appears in the visualizer window,
but rather a numerical construct that allows vPython to perform vector manipulations.
vPython works with vectors in terms of their components. While vPython has an object
called vector(), it treats this object as an ordered triplet, meaning that it just stores the x,
y, and z component of the vector. Also, vPython does vector math natively, component
by component. However, if we wish to describe a vector as a direction and a magnitude
rather than by its components, then we have to create a variable for the magnitude, and a
vector for the unit vector.
To demonstrate this, let us create a simple program to explore vector addition and
subtraction in vPython.
Open up VIDLE:
• from the Lab or any ITaP computer go to start->course software->science>physics->PHYS172->VIDLE
In the VIDLE editor window, enter the “first two lines of code”:
from __future__ import division
from visual import *
©Purdue University 2013 1 Since we are going to be treating vectors as arrows, we now need to create our arrows.
Label the section of code “Vector Objects” with a comment. Remember that comment
lines start with a “#”. Next create two arrows with the following attributes:
Name
A
B
Object type
arrow
arrow
color
red
cyan
shaftwidth
0.2
0.2
Note that we are not yet defining the position nor axis attributes of the arrows. We will
define these later. Right now we need to just create the objects, so that we can define
other properties as attributes of the arrows (e.g. vector magnitude and unit vector).
In vPython, you can create non-standard attributes of objects by naming and defining
the attribute:
objectName.attribute = quantity
This is what we will be doing in giving the arrow a magnitude and unit vector.
However, to do this we must first create the object. If you try to define the attributes
before you have created the objects to which they apply, then you will get an error
message.
Next, we are going to create the magnitudes and unit vectors of vectors A and B from the
previous section. In the “Vector Objects” section of code, create the following four
objects by name and value. Remember that to define a scalar quantity, you type the name
of the quantity, an equals sign, followed by its value. For a vector quantity you type the
name of the quantity, an equals sign, followed by vector(x,y,z), where x, y, and z are the
components of the vector.
Quantity
Vector A’s Magnitude
Vector A’s unit vector
Vector B’s Magnitude
Vector B’s unit vector
Quantity Name
A.mag
A.dir
B.mag
B.dir
Object Type
scalar
vector
scalar
vector
Value
3.00
<-0.7071, 0.7071, 0>
4.00
<0.7071, 0.7071, 0>
Now that we have defined the magnitude and direction of vectors A and B, we can now
put the vectors into component form, which vPython more readily recognizes. Since we
are representing the vectors as arrows, there needs to be an attribute of the arrow that
gives it a direction and magnitude. This attribute is the axis of the arrow, which will
represent the components of the vector.
To put the vectors into component form, you need to remember the mathematical
relationship between a vector and its unit vector, and magnitude. Remember, if you
multiply a vector times a scalar, the product is still a vector.
©Purdue University 2013 2 Label a new section of code “Vectors in Component Form” with a comment line.
Directly below this line, write a line of code to create vectors A and B:
#Vectors in Component Form
A.axis = A.mag * A.dir
B.axis = B.mag * B.dir
Since A.dir and B.dir should already be defined in vPython as vector quantities, you do
not need to use vector(x,y,z) as vPython already recognizes that the equation produces a
vector. Moreover, vPython already knows that the axis attribute of an arrow must be a
vector quantity.
Note that we could just created vectors in component form right from the start with the
following lines of code:
A = vector(A_x, A_y, A_z)
B = vector(B_x, B_y, B_z)
where A_x, A_y, A_z, B_x, B_y, and B_z are the vector components of the two vectors.
However, we have already created two arrows with those names, and furthermore, these
two lines of code will not create a visual object.
Before we go any further, save the program as vectors.py.
To verify that vPython has the correct values for the components of the vectors, we can
tell the program to print the vectors to the vPython Shell window. First, we will add a
comment to announce that we are going to print the vectors to the screen. Add the
following to your code:
#Print Vectors
print(“vector A=”, A.axis)
print(“vector B=”, B.axis)
and run the program. Notice that the program prints the entire vector to the screen inside
of square brackets.
If you were only interested in having the computer print the x-components of
the vectors to the screen, then you could type:
print(A.axis.x)
print(B.axis.x)
Running the program, you see that the computer prints the value of the x
coordinates without square brackets. This is because the x-coordinates of the
vectors are themselves treated as a scalar quantity by vPython. (Vectors are
treated as an ordered triplet of three scalar quantities.)
©Purdue University 2013 3 CHECKPOINT 1: Raise your hand and ask your instructor to check
your work. You may proceed while you wait.
Now let us create a third vector C, which is the sum of vectors A and B. First, create a
new object in the “Vector Objects” section of the code with the following attributes:
Name
C
Object type
arrow
color
yellow
shaftwidth
0.2
Since vPython works natively with vectors, we need only to add the following lines of
code to our program:
#Create vector C, which is sum of vectors A and B
C.axis = A.axis + B.axis
print(“vector C=”, C.axis)
where the print statement was added to show the components of vector C. To determine
the magnitude of vector C, we can use the mag() function, which calculates the magnitude
of a vector quantity inside of the parenthesis. Add the following line of code:
C.mag = mag(C.axis)
Now we need only to determine the unit vector of C. Again, since vPython works
natively with vectors, we need only to add the following line of code:
C.dir = C.axis/ C.mag
Add a print statement to you code, which will print the vector components, magnitude,
and unit vector of vector C. You can use the previous print statements in the code as an
example. Run the program and verify that your printed results match the results from
Excel.
Lastly, we want to show vector addition graphically in vPython. This means aligning the
vectors A and B head to tail. To do this, create a new section of code (using a comment
line) called “Aligning Vectors for Geometric Addition”. Next, use that new section to
change the following vector attributes (change them symbolically):
Attribute
A.pos
B.pos
C.pos
New Value
<-2, -1, 0>
Head of vector A
Tail of vector A
Your new section of code should look like the following:
©Purdue University 2013 4 #Aligning
A.pos =
B.pos =
C.pos =
Vectors for Geometric Addition
???
???
???
Run the program to check that the vector arrows line up correctly.
Throughout the rest of the lab, we will be using arrows to represent vectors. Becoming
familiar with the use of vectors in vPython, as well as symbolic vector math/manipulation
will be helpful in constructing our model systems.
PART II: Modeling Motion and Iteration
We now have nearly all of the tools needed to start building computer models of systems.
The first system that we are going to model is the motion of cup moving at a constant
velocity (Which you explored in the first week’s recitation.) To model the motion of the
cup, we are going to use the position update formula:
∆𝑟 = 𝑣∆𝑡
This formula represents how the position vector of an object changes in time in response
to the velocity of that object. Notice that there is a vector multiplied by a scalar on the
right side of the equation (which is itself a vector), and there is a vector on the left side as
well.
This formula makes use of delta notation, which signifies the change in a quantity. ∆𝑟
represents the change in the position vector over a period of time ∆𝑡. Therefore, to
determine the value of ∆𝑡, you subtract the initial time from the final time, which tells
you the amount of time between them. Symbolically:
𝑡!"#$% − 𝑡!"!#!$% = ∆𝑡
This can be rewritten as:
𝑡!"#$% = 𝑡!"!#!$% + ∆𝑡
which can be read as “the time that it will be is equal to the current time plus the elapsed
time.”
Likewise, the change in the position vector can be determined by subtracting the initial
position from the final position, in order to determine the displacement vector ∆𝑟.
Symbolically, we write this as the following mathematical sentence:
©Purdue University 2013 5 𝑟!"#!" − 𝑟!"!#!$% = ∆𝑟 Where you end up… …minus where you were… …is equal to… … how far you move If we rewrite the equation, the mathematical sentence becomes a bit more intuitive: 𝑟!"#$% = 𝑟!"!#!$% + ∆𝑟 Where you end up… …is equal to… …where you were… …plus how far you move If we were to rewrite the position update formula in this same manner (by expanding the
delta notation for ∆𝑟 into 𝑟!"#$% − 𝑟!"!#!$% and moving 𝑟!"!#!$% to the right-hand-side of the
equation):
𝑟!"#$% = 𝑟!"!#!$% + 𝑣∆𝑡
Thus, if you know where something is, and how fast and in what direction it is moving,
then you can predict where it will be a short time ∆𝑡 in the future.
Modeling the cup in vPython
We will now construct a model of the cup in vPython. We are going to need a fresh
VIDLE editor window, as we do not want to erase our existing VIDLE code.
go to File -> New Window
To get started on the model, type in the “first two lines of code” which we will use in
every model.
Next, use a comment line to create a new section of code called “Objects”.
We are now going to create two objects, the floor of the room and the wall of the room,
which we will model as boxes.
Remember that the position of a box is the location of the center of the box, and that the
size of the box specifies its x-, y-, and z- dimensions. Also, remember that the room is
square (5 meters x 5 meters), and assume that the ceiling is 3 meters above the floor
(giving the height of the wall). Lastly, assume that the floor and wall are 0.2 meters thick
Location in Room of Origin
©Purdue University 2013 6 Object Name
floor
wall
Shape
box
box
color
orange
orange
pos
size
In the “Objects” section of code, create these two objects with these attributes. We will
now model the cup as a small cyan cylinder, 0.05 meters in radius, and 0.15 meters long,
pointing straight up, positioned about ¾ meter above the floor and 10 cm from a vertical
wall.
Object Name
cup
Shape
cylinder
color
cyan
radius
axis
pos
Create this object in the “Objects” section of the code.
We now need to acknowledge that the cup is moving by specifying its velocity. Assume
that the cup is moving at a constant speed of approximately 1/3 of a meter per second.
Below the line creating the cup, add a line to your code that creates a new vector quantity
called “cup.v” and set the value of this quantity.
Now we need to define the quantity ∆𝑡. However, we will first create a new section of
code (with a comment line) called “simulation parameters”. In this section of code,
create a new quantity called “deltat”. You will need to set a value for this parameter.
CHECKPOINT 2: Raise your hand and ask your instructor to
check your work. Loops and motion
We will use a programming concept called a loop to model motion. A loop is a set of
instructions that are repeated over and over until some condition is met. There are many
ways of creating loops in vPython, however we will be restricting ourselves right now to
using the while statement to create loops. The condition that we will use right now to
“break” the loop is to have the computer simulate the motion of the cup for a certain
amount of time. Once the code has simulated this amount of time, the loop will break,
and the program will move on to the next set of instructions.
There are three parts of code when creating a while loop:
1. Initializing conditions and otherwise preparing the code for the loop
2. The while statement and condition to be met
3. The code inside the loop (the instructions to be repeated)
We will add these parts to our code one at a time.
©Purdue University 2013 7 To organize our code, create a new section of code called “Initializing Model”. We will
use this section of code to prepare the computer for the loop. In this section of code, we
need to tell the computer to start the simulation at time 𝑡 = 0.
•
•
Create a new quantity called “t” (for time), and set it equal to zero.
Add a comment at the end of this line specifying the units as seconds.
Next, we need to specify how long we want the simulation to run. Let us say that we
want the code to model 10 seconds of motion.
•
•
Create a quantity called “simtime”, and set it equal to 10.
Add a comment at the end of this line specifying the units as seconds.
This section of code should look as follows:
#Initializing Model
t = 0
# units of seconds
simtime = 10 # units of seconds
In the next section of code, we use the while statement to create the loop, and specify the
condition to be met on the same line, followed by a colon.
Add the following line to your code:
while t<simtime:
This line of code tells the computer that while the condition is true (that t<simtime), the
computer should keep looping through the instructions. This hints that we will need to
include a way of increasing the value of t such that it is eventually larger than simtime.
The colon tells the computer to begin the loop.
The instructions inside the loop (the instructions to be repeated) are signified by being
indented relative to the while statement. When you push return to go to the next line,
VIDLE will automatically indent your next line. In fact, VIDLE will continue to indent
the lines until you hit delete after hitting return to create a new line.
There are many things that we want to include inside the loop, as the loop will allow us to
iterate through the position update formula. First, we want to calculate the displacement
of the cup during the first time step.
©Purdue University 2013 8 •
•
Create a new quantity called delta_r
Use the Position Update Formula to assign a value to this quantity (remember that
vPython natively recognizes vectors and vector math)
We are now ready to update the position of the cup. To do this, add the following line of
code to the loop (make sure it is indented):
cup.pos = cup.pos + delta_r
This line of code tells the computer to “change the value of cup.pos to the value of
cup.pos plus delta_r.” You may recognize that this is just a restating of the position
update formula! Note that while this is a mathematically void statement (unless delta_r
is zero), this is a perfectly valid statement in vPython.
Next, we need a way of getting the position information from the computer. To do this,
we are going to use a print statement. Add the following line to your code after the cup
position update:
print(“t=”, t, “ cup.pos=”, cup.pos)
Lastly, we need to include a line of code to update the time.
•
Seeing how the position of the cup was updated, what line of code would you
add in order to update the time?
The part of your code with the loop should loop like the following:
#Initializing Model
t = 0
# units of seconds
simtime = 10 # units of seconds
while t<simtime:
delta_r = ???
cup.pos = cup.pos + delta_r
print “t=”, t, “
cup.pos=”, cup.pos
t = ???
©Purdue University 2013 9 Save the program as cup.py and run the program.
•
What did you see?
•
How far did the cup move during the simulation? (Use the Python Shell
Window)
CHECKPOINT 3: Raise your hand and ask your instructor to
check your work. ©Purdue University 2013 10