Introduction to 3D modeling

advertisement
Physics 2211
Spring 2010
Lab #1
Introduction to 3D modeling
With notes for Teaching Assistants
(please send suggestions/typos/etc. to caballero@gatech.edu)
1 Objectives
In this course you will construct computer models to:
• visualize motion in 3D,
• visualize vector quantities like position, momentum, and force in 3D,
• perform calculations based on fundamental principles to predict the motion of interacting
objects, and
• animate the predicted motions in 3D.
To do this you will use a 3D programming environment called VPython.
In this lab you will learn:
• how to use IDLE, the interactive editor for VPython,
• how to structure a simple computer program,
• how to create 3D objects such as spheres and arrows,
• how to use vectors in VPython, and
• how to use lists in VPython.
This handout is organized as follows. In Section 2, you will read about the requirements of the
laboratory including answer questions and lab checkpoints. Section 3 provides a simple overview
of how to organize a typical computer program. In Section 4, you begin your first programming
activity – learning the syntax and structure of the programming language. Section 5 introduces
you to using lists in VPython. In Section 5.2 and 5.3, you will begin to use lists to perform physical
calculations.
1
TA Notes:
The first part of this lab is relatively straight-forward. Students are simply following instructions
and answering questions about what they see. This is the best time to go around the room
and meet the students. introduce yourself and the other TAs.
Ask them about their experience with programming and assess which groups have students
with strong programming skills. Ensure that these students allow other students with less (no)
experience to contribute. Encourage students with little experience in programming to be the
recorder for the group.
Tell students about the weekly programming assignment and that the exams will generally
have one programming question on them. All students are responsible for knowing VPython
and it is an essential part of the course.
2 Organization of the Labs
2.1 Answering Questions
Your group is required to document your activities in the laboratory. There are points in the lab
where questions have been posed. These are usually indicated by question boxes. However, you
should also look for sentences similar to, do this in your lab notebook. When you encounter a
question, you should:
• follow any instructions given,
• answer the question(s) posed, and
• write the answer(s) to the question(s) somewhere.
A question box looks like this:
Questions:
This is a question box. You should stop working when you see this box, follow any instructions
given in this box, and answer any questions posed in this box. Write these answers down.
2.2 Checkpoints
You will be required to complete computer programs in the laboratory. Because you will be using
your computer programs and programming knowledge on weekly assignments, it is important that
your programs operate correctly. A Teaching Assistant (TA) is available in the laboratory to assist
you and to review your work.
There are certain locations in each laboratory handout, usually after completing an activity, where
a checkpoint box has been placed. When you reach these boxes, you should:
• stop working,
2
• review the work you have completed,
• review any questions you answered, and
• call a TA over to check your progress.
Your TA will ask you questions about the lab. To receive full credit for the lab, the TA must check
your group off at each checkpoint. A checkpoint box looks like this:
Checkpoint:
This is a checkpoint box. You should stop working when you see this box, review your work,
and raise your hand to signal a TA. The TA will check your progress.
3 Overview of a Computer Program
A computer program consists of a sequence of instructions. The computer carries out the instructions one by one, in the order in which they appear, and stops when it reaches the end. Each
instruction must be entered exactly correctly (as if it were an instruction to your calculator). If the
computer encounters an error in an instruction (such as a typing error), it will stop running and
print a red error message.
A typical program has four sections:
• Setup statements
• Definitions of constants
• Creation of objects
• Calculations to predict motion or move objects (these may be repeated)
4 Activity #1
Using IDLE to Create a Program
Find an icon called IDLE for VPython on the Desktop. Double click the IDLE icon. This starts
IDLE, which is the editing environment for VPython.
4.1 Starting a program: Setup statements
Enter the following two statements in the IDLE editor window:
from
future
import division
from visual import *
Every VPython program begins with these setup statements.
3
The first statement (from space underscore underscore future underscore underscore space import space division) tells the Python language to treat 1/2 as 0.5. Without the first statement, the
Python programming language does integer division with truncation and 1/2 is zero! The second
statement tells the program to use the 3D module (called “visual”).
Before we write any more, let’s save the program:
In the IDLE editor, from the File menu, select Save. Save the program to the P:\ drive, in your
prism folder, and give it the name vectors.py. You must type the .py file extension – IDLE
will not automatically add it. Without the .py file extension IDLE won’t colorize your program
statements in a helpful way.
4.2 Creating an object
In the next section of your program you will create 3D objects.
Tell VPython to make a sphere. On the next line, type:
sphere()
This statement tells the computer to create a sphere object. Run the program by pressing F5 on
the keyboard. Two new windows appear in addition to the editing window. One of them is the 3-D
graphics window, which now contains a sphere.
4.3 The 3-D graphics scene
By default the sphere is at the center of the scene, and the “camera” (that is, your point of view) is
looking directly at the center.
• Hold down both mouse buttons and move the mouse up and down to make the camera move
closer or farther away from the center of the scene. (This may differ on Macintosh or Linux
machines.)
• Hold down the right mouse button alone and move the mouse to make the camera “revolve”
around the scene, while always looking at the center. (This may differ on Macintosh or Linux
machines.)
When you first run the program, the coordinate system has the positive x direction to the right, the
positive y direction pointing up, and the positive z direction coming out of the screen toward you.
You can then rotate the camera view to make these axes point in other directions.
4.4 The Python Shell window is important – Error messages appear here
IMPORTANT:
Arrange the windows on your screen so the Shell window is always visible as in the figure below.
DO NOT CLOSE THE SHELL WINDOW.
KILL the program by closing only the graphic display window.
4
The second new window that opened when you ran the program is the Python Shell window. If you
include lines in the program that tell the computer to print text, the text will appear in this window.
• Use the mouse to make the Python Shell window smaller, and move it to the lower part of
the screen. Keep it open when you are writing and running programs so you can easily spot
error messages, which appear in this window.
• Make your edit window small enough that you can see both the edit window and the Python
Shell window at all times.
• Do not expand the edit window to fill the whole screen. You will lose important information if
you do!
• To kill the program, close only the graphics window. Do not close the Python Shell window
4.5 Error messages: Making and fixing an error
To see an example of an error message, let’s make a spelling mistake.
• Change the second statement of the program to the following:
from bisual import *
• Run the program.
Notice you get a message in red text in the Python Shell window. The message gives the
filename, the line where the error occurred, and a description of the error (in this case,
ImportError: No module named bisual).
Read error messages top down: The top line contains the information about the location of
the error.
• Whenever your program fails to run properly, look for a red error message in the Python Shell
window.
5
Even if you don’t understand the error message, it is important to be able to see it, in order to
find out that there is an error in your code. This helps you distinguish between a typing or coding
mistake, and a program that runs correctly but does something other than what you intended.
• Correct the spelling mistake. Return the second statement to from visual import *
4.6 Changing “attributes” (position, size, color, shape, etc.) of an object
Now let’s give the sphere a different position in space and a radius.
• Change the last line of the program to the following:
sphere(pos=vector(-5,2,-3), radius=0.40, color=color.red)
• Run the program. Experiment with other changes to pos, radius, and color, running the
program each time you change something.
Questions:
What does changing the pos attribute of a sphere do?
What does changing the radius attribute of a sphere do?
What does changing the color attribute of a sphere do?
TA Notes:
Keep your students honest. Make sure that they are answering these questions on paper. Ask
them to show you their work.
As with any of these labs, test their understanding of the material. Ask for details. Questions
like:
• How do you know that?
• Where in your code are you doing that?
• What if we wanted the code to do this?
are good starts. Try to refine these questions to each section. In future labs, sample questions
will be provided to help you.
Probing the students’ understanding is a very important part of the learning process. It makes
a big difference with students when you are engaging them. They will feel more comfortable
asking for help if they need it, instead taking a short-cut or cheating. And they will often think
more deeply about the work that they are doing instead of simply following instructions.
To experiment with colors, select visual to Help pull-down menu.
6
4.7 Autoscaling and units
VPython automatically “zooms” the camera in or out so that all objects appear in the window. Because of this “autoscaling”, the numbers for the pos and radius could be in any consistent set of
units, like meters, centimeters, inches, etc. For example, your program could represent a sphere
with a radius 0.20 m and a position vector of h2, 4, 0i m.
In this course we will always use SI units in our programs (“Systeme International”, the
system of units based on meters, kilograms, and seconds).
4.8 Creating a second object
We can tell the program to create additional objects.
• On a new line, after the statement that creates the red sphere, create a green sphere whose
center is at h−3, −1, 0i and whose radius is 0.15, then run the program.
You should now see the original red sphere and a new green sphere. In later exercises, the red
sphere will represent a baseball and the green sphere will represent a tennis ball. (The radii are
exaggerated for visibility.)
4.9 Creating an arrow object
We often use arrow objects in VPython to depict vector quantities. Next, we add arrows to our
program. These will represent vector quantities in future programs.
• Type the following on a new line, then run the program:
arrow(pos=vector(2,-3,0), axis=vector(3,4,0), color=color.cyan)
• Experiment with other changes to pos, axis, and color, running the program each time you
change something. Change one thing at a time so you can tell what effect your changes
have. For example, try making a second arrow with the same pos but a different axis (and
different color.)
Questions:
Is the pos of an arrow the location of its tail, its tip, its middle, or somewhere else?
Is the axis of an arrow the position of its tail, the position of its tip, or the position of the tip
relative to the tail (that is, a vector pointing from tip to tail)?
To create a sphere whose center is at the tip of the cyan arrow above, what should the pos of
the sphere be?
4.10 Multiplying by a scalar: Scaling an arrow’s axis
Because the axis of an arrow is a vector, we can perform scalar multiplication on it. Start with this
arrow: arrow(pos=vector(2,-3,0), axis=vector(3,4,0), color=color.cyan)
7
• Modify the axis of the arrow by changing the statement to the following, and note the result
in the lab notebook:
arrow(pos=vector(2,-3,0), axis=-0.5*vector(3,4,0), color=color.cyan)
Questions:
To make an arrow 3 times as long without changing its direction, what scalar factor would you
multiply axis by?
To reverse the direction of an arrow without changing its length, what scalar factor would you
multiply axis by?
4.11 Comment lines (lines ignored by the computer)
Comment lines start with a #(pound sign). A comment line can be a note to yourself, such as:
# objects created in following lines
Or a comment can be used to remove a line of code temporarily, without erasing it.
• Put a # at the beginning of the line creating your arrow, and run the program:
#arrow(pos=vector(2,-3,0), axis=-0.5* vector(3,4,0), color=color.cyan)
Note the pound sign at the beginning of the line. The pound sign lets VPython know that anything
after it is just a comment, not actual instructions. The statement will be skipped when the program
is run.
• Run the program. Explain what you see.
4.12 Representing position vectors with arrows
Clean up your program so it contains only the following objects:
• A red sphere (representing a baseball) at location h−5, 2, −3i , with radius 0.4
• A green sphere (representing a tennis ball) at location h−3, −1, 0i, with radius 0.15
• A cyan arrow with its tail at h2, −3, 0i and its tip at h2, −3, 0i + h3, 4, 0i
We can use arrows to represent position vectors and relative position vectors. Remember that a
~ and ends at a position B
~ can be found by “final
relative position vector that starts at a position A
~ −A
~.
minus initial”, or B
We want to make an arrow represent the relative position vector of the tennis ball with respect to
the baseball. That is, the arrow’s tail should be at the position of the baseball (the red sphere),
and the tip should be at the position of the tennis ball (the green sphere).
8
Questions:
What would be the pos of this arrow, whose tail is on the baseball (the red sphere)?
What would be the axis of this arrow, so that the tip is on the tennis ball (the green sphere)?
Using these values of pos and axis, change the last line of the program to make the cyan arrow
point from the red baseball to the green tennis ball.
• Run the program.
Checkpoint:
Examine the 3D display carefully. Change the location of the baseball to h3, 4, 5i. What
happens to the arrow? Return the arrow to h−5, 2, −3i.
Remember to ask your TA to check your progress.
TA Notes:
Make sure that students are making this change to their program. Ask them why the arrow
remains the way it does. At this point they should not represent the attributes symbolically, so
the numeric quantities are fixed.
You should check off students at each checkpoint. If students do not complete the checkpoints,
their grade will be penalized.
4.13 Naming objects; Using object names and attributes
We want this arrow to always point toward the tennis ball, no matter what position we give the tennis ball. To do this, we will have to refer to the tennis ball’s position symbolically. But first, because
there is more than one sphere and we need to tell them apart, we need to give the objects names.
• Give names to the spheres by changing the “sphere” statements in the program to the following:
baseball = sphere(pos=vector(-5, 2, -3), radius=0.40, color=color.red)
tennisball = sphere(pos=vector(-3,-1,3.5), radius=0.15, color=color.green)
We’ve now given names to the spheres. We can use these names later in the program to refer to each sphere individually. Furthermore, we can specifically refer to the attributes of each
object by writing, for example, tennisball.pos to refer to the tennis ball’s position attribute, or
baseball.color to refer to the baseball’s color attribute. To see how this works, do the following
exercise.
• Start a new line at the end of your program and type:
print tennisball.pos
9
• Run the program.
• Look at the text output window. The printed vector should be the same as the tennis ball’s
position.
What do you expect to see if you add this line to your program?
print tennisball.pos - baseball.pos
• Add this statement and run the program to see if your prediction was correct.
Let’s also give a name to the arrow.
• Edit the last line of the program (the cyan arrow) to the following, to give the arrow a name:
bt = arrow(pos= ....
)
Because we can refer to the attributes of objects symbolically, we want to write symbolic expressions for the axis and pos of the arrow bt. The expressions should use general attribute names in
symbolic form, like tennisball.pos and baseball.pos, not specific numerical vector values such
as vector(-3,-1,0). This way, if the positions of the tennis ball or baseball are changed, the arrow
will still point from baseball to tennis ball.
Questions:
In symbols (letters, not numbers), what should be the pos of the cyan arrow that points from
the baseball to the tennis ball? Make sure that your expression doesn’t contain any
numbers.
In symbols (letters, not numbers), what should be the axis of the cyan arrow that points from
the baseball to the tennis ball? (Remember that a relative position vector that starts at a
~ and ends at a position B
~ can be found by “final minus initial”, or B
~ − A).
~ Make sure
position A
that your expression doesn’t contain any numbers.
• Change the last line of the program so that the arrow statement uses these symbolic expressions for pos and axis.
• Run the program. Rotate the 3D display and examine it closely to make sure that the cyan
arrow still points from the baseball to the tennis ball. If it doesn’t, correct your program, still
using no numbers.
• Change the pos of the baseball to h−4, −2, 5i. Change the pos of the tennis ball to h3, 1, −2i.
Run the program. Examine the 3D display closely to make sure that the cyan arrow still
points from the baseball to the tennis ball. If it doesn’t, correct your program, still using no
numbers in the statement creating the arrow.
10
4.14 Vector Components
We often measure the components with respect to a fixed coordinate system. These components
are the projection of the vector along the coordinate directions. While we can project a vector
along any other vector, we choose to project it along the coordinate directions. In this section you
will create three arrows (all the same color) that represent the projections of the relative position
vector along the coordinate directions.
• Create three arrows to represent the length of the relative position vector in each coordinate
direction.
• You must do this symbolically. You can reference the x component of a vector using vectorname.x.
The same is true for y and z.
• Run your program. What should the pos and axis of each arrow?
Checkpoint:
Does your program behave as it is supposed to?
That is: if you change the positions of both balls, does the arrow automatically adjust so it still
points from the baseball (red) to the tennis ball (green)?
Do your vector components update automatically?
TA Notes:
Ensure students make the above changes. Ask them how the symbolic representation differs
from the numeric one. What are the advantages to the symbolic representation? When would
you want to use the numeric representation?
Ask them how to do vector addition. Have them change the pos of the component arrows so
that the components add tip-to-tail to give the relative position vector.
Save this program as vectors.py. You will need this program to complete one of your weekly
programming assignments.
5 Activity #2
Lists in VPython
In VPython it is possible to create a list of things, and then travel through the list from beginning to
end, picking up the things one at a time. The kind of loop used to do this is called a for loop. You
need to understand lists in order to calculate the average velocity of a particle given its position
vectors as a function of time.
5.1 Create a new program file
Start a new VPython program. Save this program as lists.py to your P:\ drive. Remember to
leave the Python Shell window visible at all times. Do not close this window, because it gives
you error messages; end the program by closing the graphical display window. The first two
11
statements at the very beginning of your program should be:
from future import division
from visual import *
In the first line note the two underscores before and two after the word future.
5.1.1 A list of words
A list is denoted by square brackets. Type the following code into your program:
list of words = [‘cat’,‘hippo’,‘snake’]
print list of words
(It is necessary to put words in quotes to tell VPython that these are just words, not names of
variables.)
• Run the program.
Note that the list is printed just as you typed it in – all the words are printed at once.
[‘cat’, ‘hippo’, ‘snake’]
What if you want to pick up the words one at a time, in order? Add the following statements:
for thisword in list of words:
print ‘I see a’, thisword, ‘over there.’
• Run your program. The output in the shell window should look like this:
[‘cat’,
I see a
I see a
I see a
‘hippo’, ‘snake’]
cat over there.
hippo over there.
snake over there.
Make sure everyone in your group understands what this kind of a for loop is doing. Try changing
the code, predicting what will happen, and running the program to confirm your prediction.
Write a bit of code that uses a list to produce the output:
What
What
What
What
color
color
color
color
is
is
is
is
a
a
a
a
crocodile?
rhino?
zebra?
bison?
Checkpoint:
Which variable controls what is printed each time the loop executes?
Call your TA over to check your progress.
12
TA Notes:
This lab is fairly straight-forward. Students should be writing some code in their lab notebooks.
Encourage them to play around with the lists a bit. This part of the lab will be the focus of the
weekly programming assignment – so they need a solid understanding of lists.
5.1.2 A list of numbers
Besides words, a list can contain other things, such as numbers or graphical objects. Here is a list
of even numbers:
list of evens = [2,4,6,8,10]
• At the end of your program add code to create a list of the odd numbers that are less than 10,
and a loop to print out the square of each number. (VPython uses ** to represent numbers
raised to a power, i.e. 23 = 2**3.)
• Run your program.
The output in the shell window should look like this:
1
9
25
49
81
5.1.3 A list of spheres
You can make a list of graphical objects such as spheres or arrows, and loop through the list,
changing the objects. Enter the following code and run the program.
list of spheres = [sphere(pos=(-9,0,0)), sphere(pos=(9,0,0)), sphere(pos=(0,9,0)),
sphere(pos=(0,-9,0)), sphere(pos=(0,0,9)), sphere(pos=(0,0,-9))]
print list of spheres
Rotate the display. What is the location of the spheres?
Questions:
Explain the change you would need to make to move the spheres from their current locations
to 5 units from the origin.
How about shifting them by h1, −1, 2i units?
Now, enter the following code:
13
for thisball in list of spheres:
rate(1)
thisball.color = color.green
thisball.radius = 0.5
print thisball.pos
Rotate the display. Explain what each line is doing each time the loop executes.
Questions:
Rewrite this code so the spheres become blue with radii of 0.1 units.
How would you shift the position of each ball by h1, −1, 2i units in the loop?
TA Notes:
Ensure that the students can represent these changes/shifts appropriately. Look over the lab
notebook. This may be difficult for some groups who are uncomfortable in translating real math
to Python. Explain to them that they can alter any property of an object in the loop.
5.2 Creating lists dynamically
In the examples above lists were created by typing in all the entries. Lists can also be created by
appending one item at a time.
list_of_boxes = [ ]
n = 0
nmax = 5
while n < nmax:
rate(1)
list_of_boxes.append(box(pos=(2*n,0,0)))
n = n + 1
## create an empty list
## counter for number of boxes
## number of boxes we want
## add a box
## count this box
TA Notes:
Here you want to remind them about the idea of a loop. Have them point out the four major
parts: (1) Initialization, (2) Loop Control/Test, (3) Loop Contents/Calculations and (4) Update.
Ask them about “[ ]”. If needed, explain it’s empty just like the list before inserting things into it.
5.2.1 Creating a list of arrows
At the end of your program, write code that creates a list of arrows, each one with its tail h1, 0, 0i
units from the center of a different sphere and pointing in the +x-direction with a length of 5 units
in your list of spheres. Follow this procedure:
• Create an empty list.
• Loop through list of spheres.
14
• Create an arrow with its tail displaced h1, 0, 0i units from the center of each sphere pointing
in the +x-direction with a length of 5 units.
• Append the arrow to the list.
Rotate the display to ensure your program works.
Questions:
What would you change in your code to get the arrows pointing at 45◦ to the axis with a length
of 6 units?
5.3 Referencing elements in a list
In the examples above, you were interested in the value of a single element (i.e., a single item) in
the list. Usually, it is useful to determine the value of the next element as well.
You will learn to use indices to do this. Indices are numbers that reference an element’s location
in the list. Copy the code below to generate a list of position vectors.
list_of_locs = [ ]
j = 0
jmax = 5
while j < jmax:
rate(1)
location = vector(j,j**2,0)
print ’Location is:’, location
list_of_locs.append(location)
j = j + 1## count this location
## create an empty list
## counter for number of locations
## number of locations we want
## generate a location
## print the location
## add a location to the list
You now have a list of locations of an unknown object. Referencing elements with indices becomes
important when you are interested in the vector displacement of the object. This displacement is
given by the vector equation,
∆~r = ~rf − ~ri
Therefore, you must know both the value of the current location and the value after the displacement. Referencing these elements in a list is simply adding a bracket with the appropriate index.
For example, we can reference elements in a list with three elements called list of things using:
list of things[index]
where index refers to the location of an item in the list. For example, the first item in the list can
be reference using list of things[1]. For the second, list of things[2], etc. However, we
cannot use list of things[4] because there is no fourth item in our list.
15
5.3.1 Using referenced elements
Add this line of code after the previous one to calculate the displacements,
list_of_displacements = [ ]
## create an empty list
k = 0
## counts number of displacements
kmax = 4
## total number of displacements
while k < kmax:
rate(1)
displacement = list_of_locs[k+1] - list_of_locs[k]
## calculate a displacement
print ’Displacement is:’, displacement
## print the displacement
list_of_displacements.append(displacement)## add a displacement to the list
k = k + 1
## count this displacement
• Run your program.
• Add a line of code the the loop that produces an arrow the represents the vector displacement.
• What is the pos of these arrows?
Questions:
Explain the line of code displacement = list of locs[k+1] - list of locs[k]. What
does it do?
What is the purpose of kmax? Change its value to 5, what happens? Why?
What is necessary to modify the above code to calculate average velocities?
Where would the tail of an arrow representing the average velocity between two locations, ~rf
and ~ri , lie? Your answer will only include the given vectors and a number.
Checkpoint:
Have your TA check your work before turning both programs into WebAssign.
TA Notes:
This last bit section may not be familiar to students. You can use pictures of arrays as boxes
linked end-to-end to talk about order and how index referencing works.
Ensure that every member turns in the program to WebAssign. If students have issues with
this last section, encourage them to write the code outside the loop and then make it a loop.
Use the lab notebook for any planning necessary.
Make sure that their code works correctly before they leave the laboratory. They will use this
code on a homework assignment.
16
6 Turn in your program to WebAssign
There is a WebAssign assignment where everyone should turn in your final program. When you
turn in a program to WebAssign , be sure to follow the instructions given there, which may sometimes ask you to change some of the parameters in your program.
Everyone in the group should save a copy of the program on his or her own P:\ drive, for future
reference. (You can email the program to each other, if necessary.)
7 Using VPython outside of class
You should download VPython and install it on your own computer. You will need it for weekly
homework assignments outside of class.
7.1 Reference manual and programming help
There is an on-line reference manual for VPython. In IDLE, from the Help pull-down menu select
Visual. The first link, Reference manual, gives detailed information on spheres, arrows, etc.
In IDLE, from the Help pull-down menu select Python Docs to obtain detailed information on the
Python programming language upon which VPython is based. We will use only a small subset of
Python’s extensive capabilities.
Last edited: Sunday 10th January, 2010 at 10:56am
17
Download