VPython basics
Claimed by Taylor Dingler Spring 2018
This is a beginning overview to vPython with some basic syntax and functions.
Installation or Online Use
Python can be rather difficult to install. However, you can use an online version in order to do all code online.
Online/ Glowscript
1. Go to [1]
2. Log into a Google account.
3. Click here in "You are signed in as [account name you select] and your programs are here."
4. Click the blue Create New Program.
To install VPython simply follow the instructions in the links given below. After the installation is completed just open the VIDLE for Python (usually there is a shortcut created on your desktop) and start typing your code.
Windows
Install VPython here
OSX
Install VPython here
Linux
Install VPython here
Getting started with Python
Introduction to basic Python use
The first two lines of your program should be:
- from __future__ import division
from visual import *
The first line enables float division, so 3 / 2 = 1.5 (not 1) and the second line enables graphics module to plot your 3D simulation.
Variables
A variable is the name given to a chosen value. Variables can be manipulated, changed, or renamed within vPython.
Assigning Variables
x = 5
This assigns the variable x the number 5. Note: The equal sign does not mean equal. Think of it more as labeling.
Python allows allows you to redefine variables
y = 0 x = y
In this case, we have taken the original x and assigned it the value from the variable y making the value of x equal to 0.
Increasing a Variable
Let's say you want x to increase by one after a certain line of code, to keep variables to a minimum. Python allows you do to so.
x = 2 x = x + 1
In this case, we have taken the original value of x and added one to it. If you call x again, its value will now be 3. This will be helpful in loops.
Creating VPython Objects
In VPython you can create an object with certain attributes (e.g. radius, position). You can store the information about that object in a variable. This way you can access a certain object using a variable it is stored in. Here are examples of some objects you can create and how to define them
variableName = ball( pos=vector(x_coordinate, y_coordinate, z_coordinate), radius = radius_measure, color = color.blue)
Note: There are different colors you can assign some of which are red, blue, magenta, cyan, yellow, and more.
myArrow = arrow(pos=vector(x_coordinate,y_coordinate,z_coordinate), axis=vector(x1_coordinate,y1_coordinate,z1_coordinate), color = color.color_of_the_arrow)
The axis refers to the more so thickness of the arrow. When coding, you can multiply this vector by a scalar value.
myVector = vector(x_coordinate,y_coordinate,z_coordinate)
Outside of objects, you can just create a vector numbers to be used later, such as making the force or velocity vector.
You can leave a path behind a moving object simply by specifying make_trail=True
:
ball.make_trail = True
Each time you change (object).pos, this new position is added to a curve, thereby leaving a trail behind the moving sphere. This works with arrow, box, cone, cylinder, ellipsoid, pyramid, ring, and sphere.
Manipulating VPython values
- Accessing attributes of the variable
To access the attribute of a given variable just use the syntax object.attribute
(e.g. to access the position of the ball variable, you should do ball.pos
)
- Updating variable
To update a variable (such as time, speed, force or the position of the object) you should do variable = variable + updateIncrement
Running VPython code
To run VPython code simply press F5. While running your code you will see the visual module and a shell (a place where all print out information is displayed)
Loops
There are two types of loops that can be use in Python: for loop and while loop. Loops repeat the actions within them until a certain pre-determined point is reached.
- While loops
The body of a while loop is executed, while a certain condition is true. All the statements within the while loop are indented. While loop is equivalent to integration, because it manually breaks down the physical process into small parts and adds them up (see Iterative Prediction as a good example of the physical application of a while loop). While loop has the following structure:
while (condition)
- the body of the while loop
updating the loop
For example:
while (t < 60) distance = distance + velocity * deltat t = t + deltat
Note:To animate, put rate(integerNumber). The higher the rate, the faster the animation. A good number to pick is rate(200). Note: All variables called within the while loop should be created first outside the original loop as it makes it a little easier to troubleshoot at times.
Comments
Comments in the code have no impact on the code execution, because they are just ignored by the computer. Comments in VPython start with a pound sign (#) and end when a line ends. It is a good practice to place some useful information (like an explanation to a certain step) in the comments, so other people will find it easier to understand your code. For example:
x = x + 1 # incrementing x variable
Debugging techniques
Unfortunately, sometimes programs do not work in a way we intended them to work. Here are some tips to fixing your code.
- If you get an error try to understand the error message and fix your code accordingly. The most common errors are syntax errors, like parenthesis mismatch or wrong arguments passed into the function.
- Make sure you updating your condition for a while loop, so you don't have an infinite loop.
- Check if your are dividing by zero anywhere.
- Make sure you have correct indentation everywhere.
- Put plenty of
print()
statements, so you can know what is going on in every single stage of your code. - Check your mathematical expressions for the order of precedence (e.g.
x / (y * z)
is not equivalent tox / y * z
) - Try commenting out some steps to see which parts of your code do not work.
For further information on debugging see VPython Common Errors and Troubleshooting.
Useful built-in functions
Printing out information
print(value, variable)
Prints out the given value in the programming shell. An example is as follows print("x =", x)
The program will print x = and then the value of x from the code you have. Or print("200")
This will just print the number 200.
The print function is useful in checking your math while coding!!
Math
x**y
Raises x to the y-th power.
x+y
Computes normal addition
x-y
Computes normal subtraction
x*y
Computes multiplications Note: You cannot multiply two vectors!! You can, however, multiply a vector by a scalar.
Vectors
cross(vectorA, vectorB)
Calculates the cross product of two vectors
mag(vector)
Calculates the magnitude of the vector
norm(vector)
Calculates the unit vector of the vector
dot(vector_1, vector_2)
Calculates the dot product of two vectors
The structure of VPython program
A typical VPython program has the following structure:
- Declare all the constants that will be used in the physical process you are going to model
- Create all the objects that are taking part in the process
- Start a while loop
- Calculate the forces on the given objects (or any other factors that alter the position of the given objects)
- Alter the positions (or other variables you need to alter) of the given objects to observe their trajectory
For example:
This program uses a simple algorithm that produces an approximate motion of Earth around the Sun.
from __future__ import division from visual import * r=5.0 theta=0.0 dtheta=0.01 sun=sphere(color=color.yellow) earth=sphere(pos=(r,0,0),color=color.blue) t = 0 while (t < 60): rate(20) theta=theta+dtheta x=r*cos(theta) y=r*sin(theta) earth.pos=(x,y,0) t = t + 0.1
Connectedness
How is this topic connected to something that you are interested in?
I enjoy coding and believe coding to be helpful in trying to visualize physics and the mathematics behind it, especially through vPython.
How is it connected to your major?
I am a Computer Engineering major, and I have learned two other programming languages previously and still have two more at least to learn.
Is there an interesting industrial application?
Every simulation starting from interaction of molecules can be modeled in VPython to get the general idea of the process.
See also
General Overview of VPython
External links
The official VPython website with the links to YouTube tutorials
References
This section contains the the references you used while writing this page
3. GlowScript
4. Code source